问:
WPF Dependency Property On Change Update Control
I am currently trying to get a view to update when a dependency value changes.

I have copied the code from the view into it's parent and didn't use the dependency and it worked fine.  I believe my issue is with how I am creating the DependencyProperty.

```<code>public partial class CULabelConfigControl : UserControl {

    private CreditUnion CU { get; set; }

    public static readonly DependencyProperty CUProperty = DependencyProperty.Register(
        "CU",
        typeof(CreditUnion),
        typeof(CULabelConfigControl),
        new FrameworkPropertyMetadata(null)
    );
</code>```

I currently receive an Error at run time:

```<code>"A 'Binding' cannot be set on the 'CU' property of type 'CULabelConfigControl'.
 A 'Binding' can only be set on a DependencyProperty of a DependencyObject."
</code>```

Any point in the right direction would be helpful.  And let me know if I need to share any other details.

答:
It should look like this:

```<code>public partial class CULabelConfigControl : UserControl
{
    public static readonly DependencyProperty CUProperty =
        DependencyProperty.Register(
            nameof(CU),
            typeof(CreditUnion),
            typeof(CULabelConfigControl));

    public CreditUnion CU
    {
        get { return (CreditUnion)GetValue(CUProperty); }
        set { SetValue(CUProperty, value); }
    }
}
</code>```

In the XAML of your UserControl, you would bind to this property by specifying the UserControl as RelativeSource, e.g.

```<code><Label Content="{Binding CU, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</code>```

If you need to get notified in the UserControl class whenever the property value changes, you should register a PropertyChangedCallback:

```<code>public static readonly DependencyProperty CUProperty =
    DependencyProperty.Register(
        nameof(CU),
        typeof(CreditUnion),
        typeof(CULabelConfigControl),
        new PropertyMetadata(CUPropertyChanged));

private static void CUPropertyChanged(
    DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    var control = (CULabelConfigControl)obj;

    // react on value change here
}
</code>```

Body:
I am currently trying to get a view to update when a dependency value changes.

I have copied the code from the view into it's parent and didn't use the dependency and it worked fine.  I believe my issue is with how I am creating the DependencyProperty.

public partial class CULabelConfigControl : UserControl {

    private CreditUnion CU { get; set; }

    public static readonly DependencyProperty CUProperty = DependencyProperty.Register(
        "CU",
        typeof(CreditUnion),
        typeof(CULabelConfigControl),
        new FrameworkPropertyMetadata(null)
    );

I currently receive an Error at run time:

"A 'Binding' cannot be set on the 'CU' property of type 'CULabelConfigControl'.
 A 'Binding' can only be set on a DependencyProperty of a DependencyObject."

Any point in the right direction would be helpful.  And let me know if I need to share any other details.

Body:
It should look like this:

public partial class CULabelConfigControl : UserControl
{
    public static readonly DependencyProperty CUProperty =
        DependencyProperty.Register(
            nameof(CU),
            typeof(CreditUnion),
            typeof(CULabelConfigControl));

    public CreditUnion CU
    {
        get { return (CreditUnion)GetValue(CUProperty); }
        set { SetValue(CUProperty, value); }
    }
}

In the XAML of your UserControl, you would bind to this property by specifying the UserControl as RelativeSource, e.g.

<Label Content="{Binding CU, RelativeSource={RelativeSource AncestorType=UserControl}}"/>

If you need to get notified in the UserControl class whenever the property value changes, you should register a PropertyChangedCallback:

public static readonly DependencyProperty CUProperty =
    DependencyProperty.Register(
        nameof(CU),
        typeof(CreditUnion),
        typeof(CULabelConfigControl),
        new PropertyMetadata(CUPropertyChanged));

private static void CUPropertyChanged(
    DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
    var control = (CULabelConfigControl)obj;

    // react on value change here
}


来源: stackexchange

问:
Python 3.6 validating an integer input
I am using Python 3.6 currently and my code currently is asking a user to input 2 integers and convert them into binary form, this is not a problem, the issue that I have is when it asks the user to input a number, if they put anything other than an integer, it will break the code and come up with an error, is there a specific few lines of code that will ensure that errors will not display if letters or floats are inputted?

```<code>def add():

    Num1 = int(input("Input the first number between 0 and 255, the calculated answer must not be above 255: "))
    Num2 = int(input("Input the second number between 0 and 255, the calculated answer must not be above 255: "))
</code>```

I have tried one method which was:

```<code>if type(Num1) != int:
    print("Please input a number")
    add()
</code>```

However I still get errors when testing the code.

I would like the code to detect that a string or float has been inputted, then reload the "def" function without giving a syntax error.

This is the print result:

答:
This is the gist of how to get an integer from the command line. It works using a while loop and try/except statements. You can add the checks for the integer range. You can use this code to create a function, which can be called twice for your particular problem. </p>

```<code>n = None
while True:
    n = input('enter an integer')
    try:
        n = int(n)
        break
    except:
        continue
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python 3.6 validating an integer input

Body:
I am using Python 3.6 currently and my code currently is asking a user to input 2 integers and convert them into binary form, this is not a problem, the issue that I have is when it asks the user to input a number, if they put anything other than an integer, it will break the code and come up with an error, is there a specific few lines of code that will ensure that errors will not display if letters or floats are inputted?

def add():

    Num1 = int(input("Input the first number between 0 and 255, the calculated answer must not be above 255: "))
    Num2 = int(input("Input the second number between 0 and 255, the calculated answer must not be above 255: "))

I have tried one method which was:

if type(Num1) != int:
    print("Please input a number")
    add()

However I still get errors when testing the code.

I would like the code to detect that a string or float has been inputted, then reload the "def" function without giving a syntax error.

This is the print result:

Body:
This is the gist of how to get an integer from the command line. It works using a while loop and try/except statements. You can add the checks for the integer range. You can use this code to create a function, which can be called twice for your particular problem.

n = None
while True:
    n = input('enter an integer')
    try:
        n = int(n)
        break
    except:
        continue


问:
Resolving java.lang.AbstractMethodError, Error creating bean with name 'entityManagerFactory' in Spring
I am trying to get my project to use MySQL with JPA. Each time I add the JPA dependency to mu pom.xml I get the following error.

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at co.onefi.services.payroll.Application.main(Application.java:19) [classes/:na]
Caused by: java.lang.AbstractMethodError: null
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:280) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:382) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
</code>```

Here's what my pom.xml looks like

```<code><?xml version="1.0" encoding="UTF-8"?>
   <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>sample-service</artifactId>
<version>0.1.0</version>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>
<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>com.jayway.jsonpath</groupId>
  <artifactId>json-path</artifactId>
  <scope>test</scope>
</dependency>
<!--Deps -->
<dependency>
  <groupId>joda-time</groupId>
  <artifactId>joda-time</artifactId>
</dependency>
<dependency>
  <groupId>org.jadira.usertype</groupId>
  <artifactId>usertype.core</artifactId>
  <version>3.1.0.CR1</version>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.16.8</version>
  <scope>provided</scope>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<properties>
  <java.version>1.8</java.version>
</properties>
<build>
  <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
</build>
<repositories>
   <repository>
     <id>spring-releases</id>
   <url>https://repo.spring.io/libs-release</url>
  </repository>
</repositories>
<pluginRepositories>
   <pluginRepository>
    <id>spring-releases</id>
    <url>https://repo.spring.io/libs-release</url>
   </pluginRepository>
</pluginRepositories>
</project>
</code>```

I have tried solutions to similar questions
Error creating bean with name 'entityManagerFactory

Error creating bean with name 'entityManagerFactory' defined in class path resource
Didn't work for me.

答:
Your getting the error because, you've classpath problem.
Open you pom.xml with eclipe and go to dependency hierarchy and search for the version of hibernate.

There should be one version.

Body:
I am trying to get my project to use MySQL with JPA. Each time I add the JPA dependency to mu pom.xml I get the following error.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1080) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at co.onefi.services.payroll.Application.main(Application.java:19) [classes/:na]
Caused by: java.lang.AbstractMethodError: null
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:280) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:382) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]

Here's what my pom.xml looks like

<?xml version="1.0" encoding="UTF-8"?>
   <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>sample-service</artifactId>
<version>0.1.0</version>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>
<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>com.jayway.jsonpath</groupId>
  <artifactId>json-path</artifactId>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>joda-time</groupId>
  <artifactId>joda-time</artifactId>
</dependency>
<dependency>
  <groupId>org.jadira.usertype</groupId>
  <artifactId>usertype.core</artifactId>
  <version>3.1.0.CR1</version>
</dependency>
<dependency>
  <groupId>org.projectlombok</groupId>
  <artifactId>lombok</artifactId>
  <version>1.16.8</version>
  <scope>provided</scope>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<properties>
  <java.version>1.8</java.version>
</properties>
<build>
  <plugins>
    <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
</build>
<repositories>
   <repository>
     <id>spring-releases</id>
   <url>https://repo.spring.io/libs-release</url>
  </repository>
</repositories>
<pluginRepositories>
   <pluginRepository>
    <id>spring-releases</id>
    <url>https://repo.spring.io/libs-release</url>
   </pluginRepository>
</pluginRepositories>
</project>

I have tried solutions to similar questions
Error creating bean with name 'entityManagerFactory

Error creating bean with name 'entityManagerFactory' defined in class path resource
Didn't work for me.


问:
Play application configurations not loading?
Configurations for my Play module are not loading.

The project structure for my build and config files looks like:

```<code>/project/modules/my_module/build.sbt
/project/modules/conf/my_conf.conf
</code>```

I run the project with:

```<code>cd /project/modules/my_module
sbt "run -Dconfig.resource=conf/my_conf.conf"
</code>```

When I read the setting, it is null:

```<code>String mySetting = Play.application().configuration().getString("my_setting")
</code>```

From debugging the application, it appears none of my settings are loaded into Play.application.configuration().

I used System.getProperty("user.dir") to verify that the working driectory is /project/modules/my_module/ so conf/my_conf.conf should be the right path. Any suggestions how to troubleshoot this?

答:
You dont have default config file application.conf in your classpath, try to rename my_conf.conf to application.conf and run your app with sbt run or if you are using custom config file, follow below procedure to load the file

Using -Dconfig.resource

This will search for an alternative configuration file in the application classpath (you usually provide these alternative configuration files into your application conf/ directory before packaging). Play will look into conf/ so you don’t have to add conf/.

```<code>$ /path/to/bin/<project-name> -Dconfig.resource=prod.conf
</code>```

so try to run app with sbt run -Dconfig.resource=my_conf.conf

These two play documentation will hep you to get better idea
 https://www.playframework.com/documentation/2.6.x/ConfigFile
https://www.playframework.com/documentation/2.6.x/ProductionConfiguration

Body:
Configurations for my Play module are not loading.

The project structure for my build and config files looks like:

/project/modules/my_module/build.sbt
/project/modules/conf/my_conf.conf

I run the project with:

cd /project/modules/my_module
sbt "run -Dconfig.resource=conf/my_conf.conf"

When I read the setting, it is null:

String mySetting = Play.application().configuration().getString("my_setting")

From debugging the application, it appears none of my settings are loaded into Play.application.configuration().

I used System.getProperty("user.dir") to verify that the working driectory is /project/modules/my_module/ so conf/my_conf.conf should be the right path. Any suggestions how to troubleshoot this?

Body:
You dont have default config file application.conf in your classpath, try to rename my_conf.conf to application.conf and run your app with sbt run or if you are using custom config file, follow below procedure to load the file

Using -Dconfig.resource

This will search for an alternative configuration file in the application classpath (you usually provide these alternative configuration files into your application conf/ directory before packaging). Play will look into conf/ so you don’t have to add conf/.

$ /path/to/bin/<project-name> -Dconfig.resource=prod.conf

so try to run app with sbt run -Dconfig.resource=my_conf.conf

These two play documentation will hep you to get better idea
 https://www.playframework.com/documentation/2.6.x/ConfigFile
https://www.playframework.com/documentation/2.6.x/ProductionConfiguration


问:
Need a regular expression in python to separate the signal definitions
The string which contains the signal definitons is of the form,

signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip);signal_b=super:mario|repp:ver;signal_c=semi:six_sig;signal_d=(1=last:end|start:twist;0=demo:test)

I want to separate signal definition and put them in a list. Something like below,

```<code>signalDefList = [
    'signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)',
    'signal_b=super:mario|repp:ver',
    'signal_c=semi:six_sig',
    'signal_d=(1=last:end|start:twist;0=demo:test)'
]
</code>```

Can anybody help me with this?

答:
As it was already answered you should use ;(?=signal).

To get desired output put it inside re.split() method:

```<code>import re
signalDefList = re.split(';(?=signal)', data)
signalDefList
#['signal_a=3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)',
# 'signal_b=super:mario|repp:ver',
# 'signal_c=semi:six_sig',
# 'signal_d=(1=last:end|start:twist;0=demo:test)']
</code>```

Body:
The string which contains the signal definitons is of the form,

signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip);signal_b=super:mario|repp:ver;signal_c=semi:six_sig;signal_d=(1=last:end|start:twist;0=demo:test)

I want to separate signal definition and put them in a list. Something like below,

signalDefList = [
    'signal_a=(3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)',
    'signal_b=super:mario|repp:ver',
    'signal_c=semi:six_sig',
    'signal_d=(1=last:end|start:twist;0=demo:test)'
]

Can anybody help me with this?

Body:
As it was already answered you should use ;(?=signal).

To get desired output put it inside re.split() method:

import re
signalDefList = re.split(';(?=signal)', data)
signalDefList
#['signal_a=3=box1:soc1.sig_a1|box1:soc1.sig_a0;2=box2:band_x1;1=xbox:abis|xbox1:bbs.seg_b;0=trip:skip)',
# 'signal_b=super:mario|repp:ver',
# 'signal_c=semi:six_sig',
# 'signal_d=(1=last:end|start:twist;0=demo:test)']


问:
How to get line break within string interpolation in Angularjs
So I'm trying to do something very simple and I'm stuck. I have a String variable and within that variable I Wanna set line break so certain part of the text goes to new line.

What I have tried:

```<code>title: string = "My \n Title";
title: string = "My\ Title";
title: string = "My\
Title";
title: string = "My" + "\n" + "Title";
</code>```

I have tried many variations but its just not working. Am I being stupid and missing something very obvious?

Not a duplicate as I have tried the
 and it has not worked.

Update:

The variable is being printed in the browser HTML like so {{title}}

答:
Here are two demonstrably working versions...

White Space

Solution One... if you want newlines to be respected in HTML... (works with the back-tick strings, or with 'My \ntitle'...

document.getElementById('example').innerHTML = `My
title`;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h1 {
  white-space: pre;
}</code>```

```
</div>
</div>
</p>

<p>Angular Version:</p>

```
{{title}}

```

<h1>HTML Break</h1>

<p>Solution two... you want to use HTML...</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById('example').innerHTML = 'My<br />title';</code>```

```

Use ng-bind-html if you want to allow HTML during binding.

Body:
So I'm trying to do something very simple and I'm stuck. I have a String variable and within that variable I Wanna set line break so certain part of the text goes to new line.

What I have tried:

title: string = "My \n Title";
title: string = "My\ Title";
title: string = "My\
Title";
title: string = "My" + "\n" + "Title";

I have tried many variations but its just not working. Am I being stupid and missing something very obvious?

Not a duplicate as I have tried the
 and it has not worked.

Update:

The variable is being printed in the browser HTML like so {{title}}

Body:
Here are two demonstrably working versions...

White Space

Solution One... if you want newlines to be respected in HTML... (works with the back-tick strings, or with 'My \ntitle'...

document.getElementById('example').innerHTML = `My
title`;

h1 {
  white-space: pre;
}

<h1 id="example">

</h1>

Angular Version:

<h1 style="white-space: pre;">{{title}}</h1>

HTML Break

Solution two... you want to use HTML...

document.getElementById('example').innerHTML = 'My<br />title';

<h1 id="example">

</h1>

Use ng-bind-html if you want to allow HTML during binding.


问:
SMS BroadcastReceiver on Oreo
I have a SMS listener that works well in versions prior to Oreo (API 26) but seems to be ignored in API 26. According to documentation, SMS_RECEIVED_ACTION is exempted from the implicit broadcast limitations (link), so no changes should be needed.

Here is my listener:

```<code>public class SmsListener extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        (...)
    }
}
</code>```

I have this on the manifest:

```<code><receiver android:name=".communication.SmsListener"
    android:permission="android.permission.BROADCAST_SMS">
    <intent-filter android:priority="1000">
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
</receiver>
</code>```

And also set the permissions

```<code><uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
</code>```

Have tried with different sample projects like this as well and the outcome is the same, no SMS is captured in API 26.

Can someone provide me a working sample or help me figure out whether I have to change something or if there is a bug in API 26?

答:
Providing permissions in the manifest.xml alone wasn't enough and I had to add code for runtime permission request.

Add this code to your MainActiviy:

```<code>ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.RECEIVE_SMS},
            MY_PERMISSIONS_REQUEST_SMS_RECEIVE);
</code>```

Define this at the top of MainActivity Class:

```<code>private int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10;
</code>```

And also add this override:

```<code>@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == MY_PERMISSIONS_REQUEST_SMS_RECEIVE) {
        // YES!!
        Log.i("TAG", "MY_PERMISSIONS_REQUEST_SMS_RECEIVE --> YES");
    }
}
</code>```

See Android documentation for runtime permissions

See BroadcastReceiver SMS_Received not working on new devices , Broadcast Receivers not working in Android 6.0 Marshmallow

Title: SMS BroadcastReceiver on Oreo

Body:
I have a SMS listener that works well in versions prior to Oreo (API 26) but seems to be ignored in API 26. According to documentation, SMS_RECEIVED_ACTION is exempted from the implicit broadcast limitations (link), so no changes should be needed.

Here is my listener:

public class SmsListener extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        (...)
    }
}

I have this on the manifest:

<receiver android:name=".communication.SmsListener"
    android:permission="android.permission.BROADCAST_SMS">
    <intent-filter android:priority="1000">
        <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
</receiver>

And also set the permissions

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>

Have tried with different sample projects like this as well and the outcome is the same, no SMS is captured in API 26.

Can someone provide me a working sample or help me figure out whether I have to change something or if there is a bug in API 26?

Body:
Providing permissions in the manifest.xml alone wasn't enough and I had to add code for runtime permission request.

Add this code to your MainActiviy:

ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.RECEIVE_SMS},
            MY_PERMISSIONS_REQUEST_SMS_RECEIVE);

Define this at the top of MainActivity Class:

private int MY_PERMISSIONS_REQUEST_SMS_RECEIVE = 10;

And also add this override:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == MY_PERMISSIONS_REQUEST_SMS_RECEIVE) {
        // YES!!
        Log.i("TAG", "MY_PERMISSIONS_REQUEST_SMS_RECEIVE --> YES");
    }
}

See Android documentation for runtime permissions

See BroadcastReceiver SMS_Received not working on new devices , Broadcast Receivers not working in Android 6.0 Marshmallow


问:
What is the right way to handle http Error?
Current situation:

i have a service.ts which save data in the backend:

```<code>public update(route: string, values: Array<any>): Observable<boolean> {
  let body = { values: values };

  return this.httpClient.put(route, body, {
    observe: 'response'
  })
  .map((res) => {
    let status = res.status;
    switch (status) {
        case 202:
            return true;
    }
  }, error => {
    switch (error.status) {
        case 406:
            return false;
    }
  });
}
</code>```

i have a http interceptor so i can append token to every request:

```<code>public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next
    .handle(request)
    .do(event => {

    })
    .catch((error: any) => {

    });
}
</code>```

and i have a component with a save method, where i normaly need the result:

```<code>public save(form: FormGroup) {
  let path = '...';
  this.service.update(path, form.value)
    .subscribe(result => {
        // success
    }, error => {
        // fail
    });
}
</code>```

I dont know how to put things together.
I trigger the save method in my component and also need the result (success, error) in the component.

Right now i can only grab the result in my interceptor.
But this is the wrong place for it.

答:
```<code>public update(route: string, values: Array<any>): Observable<boolean> {
  let body = { values: values };

  return this.httpClient.put(route, body, {
    observe: 'response'
  });
}
// You don't need map for httpClient
</code>```

Then the correct way to implement HttpInterceptor is:

```<code>public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(request).do(
      (response: HttpEvent<any>) => {
        // Do stuff with success 'response instanceof HttpResponse'
      },
      (error: any) => {
        // Do stuff with error 'error instance of HttpErrorResponse'
      });
}
</code>```

Body:
Current situation:

i have a service.ts which save data in the backend:

public update(route: string, values: Array<any>): Observable<boolean> {
  let body = { values: values };

  return this.httpClient.put(route, body, {
    observe: 'response'
  })
  .map((res) => {
    let status = res.status;
    switch (status) {
        case 202:
            return true;
    }
  }, error => {
    switch (error.status) {
        case 406:
            return false;
    }
  });
}

i have a http interceptor so i can append token to every request:

public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next
    .handle(request)
    .do(event => {

    })
    .catch((error: any) => {

    });
}

and i have a component with a save method, where i normaly need the result:

public save(form: FormGroup) {
  let path = '...';
  this.service.update(path, form.value)
    .subscribe(result => {
        // success
    }, error => {
        // fail
    });
}

I dont know how to put things together.
I trigger the save method in my component and also need the result (success, error) in the component.

Right now i can only grab the result in my interceptor.
But this is the wrong place for it.

Body:
public update(route: string, values: Array<any>): Observable<boolean> {
  let body = { values: values };

  return this.httpClient.put(route, body, {
    observe: 'response'
  });
}
// You don't need map for httpClient

Then the correct way to implement HttpInterceptor is:

public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(request).do(
      (response: HttpEvent<any>) => {
        // Do stuff with success 'response instanceof HttpResponse'
      },
      (error: any) => {
        // Do stuff with error 'error instance of HttpErrorResponse'
      });
}


问:
Efficient/optimized way of evaluating several conditions?
Which of the following code snippets (A and B below) is more efficient (performance wise) and why?

Furthermore:

Does the compiler rearrange the validate() method calls so that they are called "when needed" i.e. when evaluating each separate condition in the if-statement? In other words, will the compiler treat snippet A just as if it were written as snippet B?

Are there other alternatives (besides snippet A and B) for better perfomance?

(validate(...) checks if a field (provided as an argument)  contains valid values)

Snippet A:

```<code>    boolean okTitle = validate(inputTitle);
    boolean okLocation = validate(inputLocation);
    boolean okDuration = validate(inputDuration);
    boolean okReminder = validate(inputReminder);
    boolean okRepetition = validate(inputRepetition);
    boolean okDate = validate(inputDate);

    if(okTitle && (okLocation || okDuration || okReminder || okRepetition || okDate)){
        setEnabled(true);
    }else{
        setEnabled(false);
    }
</code>```

Snippet B:

```<code>setEnabled(
     validate(inputTitle) &&
     ( validate(inputLocation) || validate(inputDuration) || validate(inputReminder) || validate(inputRepetition) || validate(inputDate) )
   );
</code>```

答:
In those situations, very often, the input is valid 95% of the time and/or the validate method is fast: if that's the case, either method will work fine.

If the input is often invalid and/or if the validate method is slow and you call that piece of code often, then you probably want to use the second method and make sure you test the likeliest reason for invalidity first, for a quick exit of the condition code.

Body:
Which of the following code snippets (A and B below) is more efficient (performance wise) and why?

Furthermore:

Does the compiler rearrange the validate() method calls so that they are called "when needed" i.e. when evaluating each separate condition in the if-statement? In other words, will the compiler treat snippet A just as if it were written as snippet B?

Are there other alternatives (besides snippet A and B) for better perfomance?

(validate(...) checks if a field (provided as an argument)  contains valid values)

Snippet A:

    boolean okTitle = validate(inputTitle);
    boolean okLocation = validate(inputLocation);
    boolean okDuration = validate(inputDuration);
    boolean okReminder = validate(inputReminder);
    boolean okRepetition = validate(inputRepetition);
    boolean okDate = validate(inputDate);

    if(okTitle && (okLocation || okDuration || okReminder || okRepetition || okDate)){
        setEnabled(true);
    }else{
        setEnabled(false);
    }

Snippet B:

setEnabled(
     validate(inputTitle) &&
     ( validate(inputLocation) || validate(inputDuration) || validate(inputReminder) || validate(inputRepetition) || validate(inputDate) )
   );


问:
Why is my form being flattened without calling the flattenFields method?
I am testing my method with this form https://help.adobe.com/en_US/Acrobat/9.0/Samples/interactiveform_enabled.pdf

It is being called like so:

```<code>Pdf.editForm("./src/main/resources/pdfs/interactiveform_enabled.pdf", "./src/main/resources/pdfs/FILLEDOUT.pdf"));
</code>```

where Pdf is just a worker class and editForm is a static method.

The editForm method looks like this:

```<code>public static int editForm(String inputPath, String outputPath) {
    try {
        PdfDocument pdf = new PdfDocument(new PdfReader(inputPath), new PdfWriter(outputPath));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
        Map<String, PdfFormField> m = form.getFormFields();
        for (String s : m.keySet()) {
            if (s.equals("Name_First")) {
                m.get(s).setValue("Tristan");
            }
            if (s.equals("BACHELORS DEGREE")) {
                m.get(s).setValue("Off"); // On or Off
            }
            if (s.equals("Sex")) {
                m.get(s).setValue("FEMALE");
            }
            System.out.println(s);
        }
        pdf.close();
        logger.info("Completed");
    } catch (IOException e) {
        logger.error("Unable to fill form " + outputPath + "\n\t" + e);
        return 1;
    }

    return 0;
}
</code>```

Unfortunately the FILLEDOUT.pdf file is no longer a form after calling this method. Am I doing something wrong?

I was using this resource for guidance. Notice how I am not calling the form.flattenFields(). If I do call that method however, I get an error of java.lang.IllegalArgumentException.

Thank you for your time.

答:
Your form is Reader-enabled, i.e. it contains a usage rights digital signature by a key and certificate issued by Adobe to indicate to a regular Adobe Reader that it shall activate a number of additional features when operating on that very PDF.

If you stamp the file as in your original code, the existing PDF objects will get re-arranged and slightly changed. This breaks the usage rights signature, and Adobe Reader, recognizing that, disclaims "The document has been changed since it was created and use of extended features is no longer available."

If you stamp the file in append mode, though, the changes are appended to the PDF as an incremental update. Thus, the signature still correctly signs its original byte range and Adobe Reader does not complain.

To activate append mode, use StampingProperties when you create your PdfDocument:

```<code>PdfDocument pdf = new PdfDocument(new PdfReader(inputPath), new PdfWriter(outputPath), new StampingProperties().useAppendMode());
</code>```

(Tested with iText 7.1.1-SNAPSHOT and Adobe Acrobat Reader DC version 2018.009.20050)

By the way, Adobe Reader does not merely check the signature, it also tries to determine whether the changes in the incremental update don't go beyond the scope of the additional features activated by the usage rights signature.

Otherwise you could simply take a small Reader-enabled PDF and in append mode replace all existing pages by your own content of choice. This of course is not in Adobe's interest...

Body:
I am testing my method with this form https://help.adobe.com/en_US/Acrobat/9.0/Samples/interactiveform_enabled.pdf

It is being called like so:

Pdf.editForm("./src/main/resources/pdfs/interactiveform_enabled.pdf", "./src/main/resources/pdfs/FILLEDOUT.pdf"));

where Pdf is just a worker class and editForm is a static method.

The editForm method looks like this:

public static int editForm(String inputPath, String outputPath) {
    try {
        PdfDocument pdf = new PdfDocument(new PdfReader(inputPath), new PdfWriter(outputPath));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
        Map<String, PdfFormField> m = form.getFormFields();
        for (String s : m.keySet()) {
            if (s.equals("Name_First")) {
                m.get(s).setValue("Tristan");
            }
            if (s.equals("BACHELORS DEGREE")) {
                m.get(s).setValue("Off"); // On or Off
            }
            if (s.equals("Sex")) {
                m.get(s).setValue("FEMALE");
            }
            System.out.println(s);
        }
        pdf.close();
        logger.info("Completed");
    } catch (IOException e) {
        logger.error("Unable to fill form " + outputPath + "\n\t" + e);
        return 1;
    }

    return 0;
}

Unfortunately the FILLEDOUT.pdf file is no longer a form after calling this method. Am I doing something wrong?

I was using this resource for guidance. Notice how I am not calling the form.flattenFields(). If I do call that method however, I get an error of java.lang.IllegalArgumentException.

Thank you for your time.

Body:
Your form is Reader-enabled, i.e. it contains a usage rights digital signature by a key and certificate issued by Adobe to indicate to a regular Adobe Reader that it shall activate a number of additional features when operating on that very PDF.

If you stamp the file as in your original code, the existing PDF objects will get re-arranged and slightly changed. This breaks the usage rights signature, and Adobe Reader, recognizing that, disclaims "The document has been changed since it was created and use of extended features is no longer available."

If you stamp the file in append mode, though, the changes are appended to the PDF as an incremental update. Thus, the signature still correctly signs its original byte range and Adobe Reader does not complain.

To activate append mode, use StampingProperties when you create your PdfDocument:

PdfDocument pdf = new PdfDocument(new PdfReader(inputPath), new PdfWriter(outputPath), new StampingProperties().useAppendMode());

(Tested with iText 7.1.1-SNAPSHOT and Adobe Acrobat Reader DC version 2018.009.20050)

By the way, Adobe Reader does not merely check the signature, it also tries to determine whether the changes in the incremental update don't go beyond the scope of the additional features activated by the usage rights signature.

Otherwise you could simply take a small Reader-enabled PDF and in append mode replace all existing pages by your own content of choice. This of course is not in Adobe's interest...


问:
Flow: Enforce types on know fields only
I there a Flow notation that would allow to define object type / interface that validates types of knows properties and unknown properties are not type-checked (are assumed of type any)?

const a: {x: number} = { x: 0 }
a.x = 'foo' // desirable error - x is define as number
a.y = 'bar' // undesirable error
```

Example in Try Flow

答:
Yes, you can define indexer property alongside with known properties:

```<code>const a: {x: number, [key:string]: any } = { x: 0 }
</code>```

Or even shorter:

```<code>const a: {x: number, [string]: any } = { x: 0 }
</code>```

More info here

Title: Flow: Enforce types on know fields only

Body:
I there a Flow notation that would allow to define object type / interface that validates types of knows properties and unknown properties are not type-checked (are assumed of type any)?

const a: {x: number} = { x: 0 }
a.x = 'foo' // desirable error - x is define as number
a.y = 'bar' // undesirable error

Example in Try Flow

Body:
Yes, you can define indexer property alongside with known properties:

const a: {x: number, [key:string]: any } = { x: 0 }

Or even shorter:

const a: {x: number, [string]: any } = { x: 0 }

More info here


问:
Mask from max values in numpy array, specific axis
Input example:

I have a numpy array, e.g.

a=np.array([[0,1], [2, 1], [4, 8]])

Desired output:

I would like to produce a mask array with the max value along a given axis, in my case axis 1, being True and all others being False. e.g. in this case

mask = np.array([[False, True], [True, False], [False, True]])

Attempt:

I have tried approaches using np.amax but this returns the max values in a flattened list:

```<code>>>> np.amax(a, axis=1)
array([1, 2, 8])
</code>```

and np.argmax similarly returns the indices of the max values along that axis.

```<code>>>> np.argmax(a, axis=1)
array([1, 0, 1])
</code>```

I could iterate over this in some way but once these arrays become bigger I want the solution to remain something native in numpy.

答:
Method #1

Using broadcasting, we can use comparison against the max values, while keeping dims to facilitate broadcasting -

```<code>a.max(axis=1,keepdims=1) == a
</code>```

Sample run -

```<code>In [83]: a
Out[83]:
array([[0, 1],
       [2, 1],
       [4, 8]])

In [84]: a.max(axis=1,keepdims=1) == a
Out[84]:
array([[False,  True],
       [ True, False],
       [False,  True]], dtype=bool)
</code>```

Method #2

Alternatively with argmax indices for one more case of broadcasted-comparison against the range of indices along the columns -

```<code>In [92]: a.argmax(axis=1)[:,None] == range(a.shape[1])
Out[92]:
array([[False,  True],
       [ True, False],
       [False,  True]], dtype=bool)
</code>```

Method #3

To finish off the set, and if we are looking for performance, use intialization and then advanced-indexing -

```<code>out = np.zeros(a.shape, dtype=bool)
out[np.arange(len(a)), a.argmax(axis=1)] = 1
</code>```

Body:
Input example:

I have a numpy array, e.g.

a=np.array([[0,1], [2, 1], [4, 8]])

Desired output:

I would like to produce a mask array with the max value along a given axis, in my case axis 1, being True and all others being False. e.g. in this case

mask = np.array([[False, True], [True, False], [False, True]])

Attempt:

I have tried approaches using np.amax but this returns the max values in a flattened list:

>>> np.amax(a, axis=1)
array([1, 2, 8])

and np.argmax similarly returns the indices of the max values along that axis.

>>> np.argmax(a, axis=1)
array([1, 0, 1])

I could iterate over this in some way but once these arrays become bigger I want the solution to remain something native in numpy.

Body:
Method #1

Using broadcasting, we can use comparison against the max values, while keeping dims to facilitate broadcasting -

a.max(axis=1,keepdims=1) == a

Sample run -

In [83]: a
Out[83]:
array([[0, 1],
       [2, 1],
       [4, 8]])

In [84]: a.max(axis=1,keepdims=1) == a
Out[84]:
array([[False,  True],
       [ True, False],
       [False,  True]], dtype=bool)

Method #2

Alternatively with argmax indices for one more case of broadcasted-comparison against the range of indices along the columns -

In [92]: a.argmax(axis=1)[:,None] == range(a.shape[1])
Out[92]:
array([[False,  True],
       [ True, False],
       [False,  True]], dtype=bool)

Method #3

To finish off the set, and if we are looking for performance, use intialization and then advanced-indexing -

out = np.zeros(a.shape, dtype=bool)
out[np.arange(len(a)), a.argmax(axis=1)] = 1


问:
Populate Multiple PDFs
I am using itextsharp to populate my PDFs. I have no issues with this. Basically what I am doing is getting the PDF and populating the fields in memory then passing back the MemoryStream to be displayed on a webpage. All this is working with a single document PDF.

What I am trying to figure out now, is merging multiple PDFs into one MemoryStream. The part I cant figure out is, the documents I am populating are identical. So for example, I have a List<Person> that contains 5 persons. I want to fill out a PDF for each person and merge them all into one, in memory. Bare in mind I am going to fill out the same type of document for each person.

The problem I am getting is that when I try to add a second copy of the same PDF to be filled out for the second iteration, it just overwrites the first populated PDF, since it's the same document, therefore not adding a second copy for the second Person at all.

So basically if I had the 5 people, I would end up with a single page with the data of the 5th person, instead of a PDF with 5 like pages that contain the data of each person respectively.

Here's some code...

```<code>MemoryStream ms = ms = new MemoryStream();
PdfReader docReader = null;
PdfStamper Stamper = null;
List<Person> persons = new List<Person>() {
   new Person("Larry", "David"),
   new Person("Dustin", "Byfuglien"),
   new Person("Patrick", "Kane"),
   new Person("Johnathan", "Toews"),
   new Person("Marian", "Hossa")
};

try
{
   // Iterate thru all persons and populate a PDF for each
   foreach(var person in persons){
      PdfCopyFields Copier = new PdfCopyFields(ms);
      Copier.AddDocument(GetReader("Person.pdf"));
      Copier.Close();

      docReader = new PdfReader(ms.ToArray());
      Stamper = new PdfStamper(docReader, ms);
      AcroFields Fields = Stamper.AcroFields;
      Fields.SetField("FirstName", person.FirstName);
   }
}catch(Exception e){
  // handle error
}finally{
   if (Stamper != null)
   {
      Stamper.Close();
   }
   if (docReader != null)
   {
      docReader.Close();
   }
}
</code>```

答: here might be another answer to your solution: Batch Pdf generation</p>

ContentLicense: CC BY-SA 2.5

Title: Populate Multiple PDFs

Body:
I am using itextsharp to populate my PDFs. I have no issues with this. Basically what I am doing is getting the PDF and populating the fields in memory then passing back the MemoryStream to be displayed on a webpage. All this is working with a single document PDF.

What I am trying to figure out now, is merging multiple PDFs into one MemoryStream. The part I cant figure out is, the documents I am populating are identical. So for example, I have a List<Person> that contains 5 persons. I want to fill out a PDF for each person and merge them all into one, in memory. Bare in mind I am going to fill out the same type of document for each person.

The problem I am getting is that when I try to add a second copy of the same PDF to be filled out for the second iteration, it just overwrites the first populated PDF, since it's the same document, therefore not adding a second copy for the second Person at all.

So basically if I had the 5 people, I would end up with a single page with the data of the 5th person, instead of a PDF with 5 like pages that contain the data of each person respectively.

Here's some code...

MemoryStream ms = ms = new MemoryStream();
PdfReader docReader = null;
PdfStamper Stamper = null;
List<Person> persons = new List<Person>() {
   new Person("Larry", "David"),
   new Person("Dustin", "Byfuglien"),
   new Person("Patrick", "Kane"),
   new Person("Johnathan", "Toews"),
   new Person("Marian", "Hossa")
};

try
{
   // Iterate thru all persons and populate a PDF for each
   foreach(var person in persons){
      PdfCopyFields Copier = new PdfCopyFields(ms);
      Copier.AddDocument(GetReader("Person.pdf"));
      Copier.Close();

      docReader = new PdfReader(ms.ToArray());
      Stamper = new PdfStamper(docReader, ms);
      AcroFields Fields = Stamper.AcroFields;
      Fields.SetField("FirstName", person.FirstName);
   }
}catch(Exception e){
  // handle error
}finally{
   if (Stamper != null)
   {
      Stamper.Close();
   }
   if (docReader != null)
   {
      docReader.Close();
   }
}


问:
Disable browser back button for one page application
I need to disable the back button of browser in my single page application.
I tried using methods like onhashchange or window.history.forward but they don't work (reason may be that url doesn't get changed here)

答:
I had a different scenario where we wanted to blacklist a few pages. Allowing most of the SPA to use the back button and a few pages to not allow it. I created a service to override the functionality of the popstate. However I ran into a weird issue with going forward.

```<code>import { RouteAddress } from 'app/common/constants/routes.constants';
import { Injectable } from '@angular/core';
import { StringUtilsService } from 'app/common/services/utilities/string-utils.service';

@Injectable()
export class LocationStrategyService {
    private static shouldSkip = false;
    // Array of route urls that we can't go back to.
    private static blackListed = [
        RouteAddress.ScreeningStepTwoCreditAvailability,
        RouteAddress.ScreeningStepTwo];

    constructor() {
        window.onpopstate = this.overridingPopState;
    }

    overridingPopState(event: any) {
        // This was having issue scoping
        const isBlackListed = (navigatingTo: string): boolean => {
            navigatingTo = navigatingTo.split('?')[0];
            const pathFound = LocationStrategyService.blackListed.find((route) => navigatingTo.endsWith('/' + route));
            return pathFound !== undefined && pathFound.length > 0;
        }

        // have black listed route and determing if able to go back
        if (!LocationStrategyService.shouldSkip && isBlackListed(event.currentTarget.location.pathname)) {
            window.history.forward();
            // Protecting against a going forward that will redirect
            LocationStrategyService.shouldSkip = isBlackListed(window.location.pathname);
        } else {
            LocationStrategyService.shouldSkip = false;
        }
    }
}
</code>```

Then in your AppComponent constructor add the LocationStrategyService and it will call it on start.

```<code>import { LocationStrategyService } from 'app/common/services/utilities/location-strategy.service';
export class AppComponent {

  constructor(
  private locationStrategyService: LocationStrategyService) {}
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I had a different scenario where we wanted to blacklist a few pages. Allowing most of the SPA to use the back button and a few pages to not allow it. I created a service to override the functionality of the popstate. However I ran into a weird issue with going forward.

import { RouteAddress } from 'app/common/constants/routes.constants';
import { Injectable } from '@angular/core';
import { StringUtilsService } from 'app/common/services/utilities/string-utils.service';

@Injectable()
export class LocationStrategyService {
    private static shouldSkip = false;
    // Array of route urls that we can't go back to.
    private static blackListed = [
        RouteAddress.ScreeningStepTwoCreditAvailability,
        RouteAddress.ScreeningStepTwo];

    constructor() {
        window.onpopstate = this.overridingPopState;
    }

    overridingPopState(event: any) {
        // This was having issue scoping
        const isBlackListed = (navigatingTo: string): boolean => {
            navigatingTo = navigatingTo.split('?')[0];
            const pathFound = LocationStrategyService.blackListed.find((route) => navigatingTo.endsWith('/' + route));
            return pathFound !== undefined && pathFound.length > 0;
        }

        // have black listed route and determing if able to go back
        if (!LocationStrategyService.shouldSkip && isBlackListed(event.currentTarget.location.pathname)) {
            window.history.forward();
            // Protecting against a going forward that will redirect
            LocationStrategyService.shouldSkip = isBlackListed(window.location.pathname);
        } else {
            LocationStrategyService.shouldSkip = false;
        }
    }
}

Then in your AppComponent constructor add the LocationStrategyService and it will call it on start.

import { LocationStrategyService } from 'app/common/services/utilities/location-strategy.service';
export class AppComponent {

  constructor(
  private locationStrategyService: LocationStrategyService) {}
}


问:
AWS amazon-s3 rewrite url to query param and go to index.html
I have an S3 bucket hosting a static website with a single .html file (index.html) and some .js and .css.

I want to be able to hit mybucket.s3-website-eu-west-1.amazonaws.com/12345678 and have the url rewritten to mybucket.s3-website-eu-west-1.amazonaws.com/index.html?ID=12345678.

After reading the docs I am not sure I can do this with S3 alone, but maybe I am wrong? What solutions do I have for this?

Note: URL's for the assets (e.g. /css/main.css) need to still work although I could look to inlining everything in the HTML if this is the only option.

答:
This is not directly possible with S3. You can use AWS CloudFront and Edge Lambda to do the URL rewrites as required.

Create a CloudFront distribution and connect your S3 bucket as an origin.

Create an Edge Lambda inside the distribution and write your URL rewrite rules.

```<code>exports.handler = (event, context, callback) => {
  // this is the request we want to re-map
  var request = event.Records[0].cf.request;

  // the request has a 'uri' property which is the value we want to overwrite
  // rewrite the url applying your custom logic
  request.uri = 'some custom logic here to rewrite the url';

  // quit the lambda and let the request chain continue
  callback( null, request );
};
</code>```

Body:
This is not directly possible with S3. You can use AWS CloudFront and Edge Lambda to do the URL rewrites as required.

Create a CloudFront distribution and connect your S3 bucket as an origin.

Create an Edge Lambda inside the distribution and write your URL rewrite rules.

exports.handler = (event, context, callback) => {
  // this is the request we want to re-map
  var request = event.Records[0].cf.request;

  // the request has a 'uri' property which is the value we want to overwrite
  // rewrite the url applying your custom logic
  request.uri = 'some custom logic here to rewrite the url';

  // quit the lambda and let the request chain continue
  callback( null, request );
};


问:
Extracting JSON-data from CSV file
I'm trying to extract a JSON data which is a column in a CSV file. So far I've come to the point where I've extracted the column in the right format, but the formatting is only correct when the variable type is factor. But I can't convert a factor to a json-file using the jsonlite package.

```<code>[1] {"id":509746197991998767,"visibility":{"percentage":100,"time":149797,"visible1":true,"visible2":false,"visible3":false,"activetab":true},"interaction":{"mouseovercount":1,"mouseovertime":1426,"videoplaytime":0,"engagementtime":0,"expandtime":0,"exposuretime":35192}}
</code>```

Another approach is to use stringsAsFactors = F when importing, but I'm struggling in getting the formatting right, where each entry looks like this:

```<code>[1] "{\"id\":509746197991998767,\"visibility\":{\"percentage\":100,\"time\":149797,\"visible1\":true,\"visible2\":false,\"visible3\":false,\"activetab\":true},\"interaction\":{\"mouseovercount\":1,\"mouseovertime\":1426,\"videoplaytime\":0,\"engagementtime\":0,\"expandtime\":0,\"exposuretime\":35192}}"
</code>```

Am I missing something obvious here? I simply just want to exract the JSON files that sits inside a CSV file.

Heres a small example of the CSV file:

```<code>"","CookieID","UnloadVars"
"1",-8857188784608690176,"{""id"":509746197991998767,""visibility"":{""percentage"":100,""time"":149797,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":1,""mouseovertime"":1426,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":35192}}"
"2",-1695626857458244096,"{""id"":2917654329769114342,""visibility"":{""percentage"":46,""time"":0,""visible1"":false,""visible2"":false,""visible3"":false,""activetab"":true}}"
"3",437299165071669184,"{""id"":2252707957388071809,""visibility"":{""percentage"":99,""time"":10168,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":542},""clicks"":[{""x"":105,""y"":449}]}"
"4",292660729552227520,""
"5",7036383942916227072,"{""id"":2299674593327687292,""visibility"":{""percentage"":76,""time"":1145,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":74},""clicks"":[{""x"":197,""y"":135},{""x"":197,""y"":135}]}"
</code>```

Regards,

Frederik.

答:
```<code>df <- readr::read_csv('"","CookieID","UnloadVars"
"1",-8857188784608690176,"{""id"":509746197991998767,""visibility"":{""percentage"":100,""time"":149797,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":1,""mouseovertime"":1426,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":35192}}"
"2",-1695626857458244096,"{""id"":2917654329769114342,""visibility"":{""percentage"":46,""time"":0,""visible1"":false,""visible2"":false,""visible3"":false,""activetab"":true}}"
"3",437299165071669184,"{""id"":2252707957388071809,""visibility"":{""percentage"":99,""time"":10168,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":542},""clicks"":[{""x"":105,""y"":449}]}"
"4",292660729552227520,""
"5",7036383942916227072,"{""id"":2299674593327687292,""visibility"":{""percentage"":76,""time"":1145,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":74},""clicks"":[{""x"":197,""y"":135},{""x"":197,""y"":135}]}"',
col_types = "-cc")
</code>```

Using jsonlite::fromJSON on each separate value, then tidyr::unnest

```<code>library(dplyr)

f <- function(.x)
  if (is.na(.x) || .x == "") data.frame()[1, ] else
    as.data.frame(jsonlite::fromJSON(.x))

df %>%
  tidyr::unnest(UnloadVars = lapply(UnloadVars, f)) %>%
  mutate_at(vars(ends_with("id")), as.character)

# A tibble: 6 x 16
#               CookieID                  id visibility.percentage visibility.time visibility.visible1 visibility.visible2 visibility.visible3 visibility.activetab interaction.mouseovercount interaction.mouseovertime interaction.videoplaytime interaction.engagementtime interaction.expandtime interaction.exposuretime clicks.x clicks.y
#                  <chr>               <chr>                 <int>           <int>               <lgl>               <lgl>               <lgl>                <lgl>                      <int>                     <int>                     <int>                      <int>                  <int>                    <int>    <int>    <int>
# 1 -8857188784608690176  509746197991998784                   100          149797                TRUE               FALSE               FALSE                 TRUE                          1                      1426                         0                          0                      0                    35192       NA       NA
# 2 -1695626857458244096 2917654329769114112                    46               0               FALSE               FALSE               FALSE                 TRUE                         NA                        NA                        NA                         NA                     NA                       NA       NA       NA
# 3   437299165071669184 2252707957388071936                    99           10168                TRUE               FALSE               FALSE                 TRUE                          0                         0                         0                          0                      0                      542      105      449
# 4   292660729552227520                <NA>                    NA              NA                  NA                  NA                  NA                   NA                         NA                        NA                        NA                         NA                     NA                       NA       NA       NA
# 5  7036383942916227072 2299674593327687168                    76            1145                TRUE               FALSE               FALSE                 TRUE                          0                         0                         0                          0                      0                       74      197      135
# 6  7036383942916227072 2299674593327687168                    76            1145                TRUE               FALSE               FALSE                 TRUE                          0                         0                         0                          0                      0                       74      197      135
</code>```

Title: Extracting JSON-data from CSV file

Body:
I'm trying to extract a JSON data which is a column in a CSV file. So far I've come to the point where I've extracted the column in the right format, but the formatting is only correct when the variable type is factor. But I can't convert a factor to a json-file using the jsonlite package.

[1] {"id":509746197991998767,"visibility":{"percentage":100,"time":149797,"visible1":true,"visible2":false,"visible3":false,"activetab":true},"interaction":{"mouseovercount":1,"mouseovertime":1426,"videoplaytime":0,"engagementtime":0,"expandtime":0,"exposuretime":35192}}

Another approach is to use stringsAsFactors = F when importing, but I'm struggling in getting the formatting right, where each entry looks like this:

[1] "{\"id\":509746197991998767,\"visibility\":{\"percentage\":100,\"time\":149797,\"visible1\":true,\"visible2\":false,\"visible3\":false,\"activetab\":true},\"interaction\":{\"mouseovercount\":1,\"mouseovertime\":1426,\"videoplaytime\":0,\"engagementtime\":0,\"expandtime\":0,\"exposuretime\":35192}}"

Am I missing something obvious here? I simply just want to exract the JSON files that sits inside a CSV file.

Heres a small example of the CSV file:

"","CookieID","UnloadVars"
"1",-8857188784608690176,"{""id"":509746197991998767,""visibility"":{""percentage"":100,""time"":149797,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":1,""mouseovertime"":1426,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":35192}}"
"2",-1695626857458244096,"{""id"":2917654329769114342,""visibility"":{""percentage"":46,""time"":0,""visible1"":false,""visible2"":false,""visible3"":false,""activetab"":true}}"
"3",437299165071669184,"{""id"":2252707957388071809,""visibility"":{""percentage"":99,""time"":10168,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":542},""clicks"":[{""x"":105,""y"":449}]}"
"4",292660729552227520,""
"5",7036383942916227072,"{""id"":2299674593327687292,""visibility"":{""percentage"":76,""time"":1145,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":74},""clicks"":[{""x"":197,""y"":135},{""x"":197,""y"":135}]}"

Regards,

Frederik.

Body:
df <- readr::read_csv('"","CookieID","UnloadVars"
"1",-8857188784608690176,"{""id"":509746197991998767,""visibility"":{""percentage"":100,""time"":149797,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":1,""mouseovertime"":1426,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":35192}}"
"2",-1695626857458244096,"{""id"":2917654329769114342,""visibility"":{""percentage"":46,""time"":0,""visible1"":false,""visible2"":false,""visible3"":false,""activetab"":true}}"
"3",437299165071669184,"{""id"":2252707957388071809,""visibility"":{""percentage"":99,""time"":10168,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":542},""clicks"":[{""x"":105,""y"":449}]}"
"4",292660729552227520,""
"5",7036383942916227072,"{""id"":2299674593327687292,""visibility"":{""percentage"":76,""time"":1145,""visible1"":true,""visible2"":false,""visible3"":false,""activetab"":true},""interaction"":{""mouseovercount"":0,""mouseovertime"":0,""videoplaytime"":0,""engagementtime"":0,""expandtime"":0,""exposuretime"":74},""clicks"":[{""x"":197,""y"":135},{""x"":197,""y"":135}]}"',
col_types = "-cc")

Using jsonlite::fromJSON on each separate value, then tidyr::unnest

library(dplyr)

f <- function(.x)
  if (is.na(.x) || .x == "") data.frame()[1, ] else
    as.data.frame(jsonlite::fromJSON(.x))

df %>%
  tidyr::unnest(UnloadVars = lapply(UnloadVars, f)) %>%
  mutate_at(vars(ends_with("id")), as.character)

# A tibble: 6 x 16
#               CookieID                  id visibility.percentage visibility.time visibility.visible1 visibility.visible2 visibility.visible3 visibility.activetab interaction.mouseovercount interaction.mouseovertime interaction.videoplaytime interaction.engagementtime interaction.expandtime interaction.exposuretime clicks.x clicks.y
#                  <chr>               <chr>                 <int>           <int>               <lgl>               <lgl>               <lgl>                <lgl>                      <int>                     <int>                     <int>                      <int>                  <int>                    <int>    <int>    <int>
# 1 -8857188784608690176  509746197991998784                   100          149797                TRUE               FALSE               FALSE                 TRUE                          1                      1426                         0                          0                      0                    35192       NA       NA
# 2 -1695626857458244096 2917654329769114112                    46               0               FALSE               FALSE               FALSE                 TRUE                         NA                        NA                        NA                         NA                     NA                       NA       NA       NA
# 3   437299165071669184 2252707957388071936                    99           10168                TRUE               FALSE               FALSE                 TRUE                          0                         0                         0                          0                      0                      542      105      449
# 4   292660729552227520                <NA>                    NA              NA                  NA                  NA                  NA                   NA                         NA                        NA                        NA                         NA                     NA                       NA       NA       NA
# 5  7036383942916227072 2299674593327687168                    76            1145                TRUE               FALSE               FALSE                 TRUE                          0                         0                         0                          0                      0                       74      197      135
# 6  7036383942916227072 2299674593327687168                    76            1145                TRUE               FALSE               FALSE                 TRUE                          0                         0                         0                          0                      0                       74      197      135


问:
Chrome saying "No Access-Control-Allow-Origin header found" But curl is showing 'Access-Control-Allow-Origin header' while using cloudfront for fonts
Earlier I was using heroku to server static assets. Then I decided to use cloud front to serve static assets for my rails(5.0.2) app on heroku. After configuring it all seemed good but for fonts chrome was throwing this error .

```<code>Access to Font at 'https://eeeeeee.cloudfront.net/assets/fontawesome-webfont-18e6b5ff511b90edf098e62ac45ed9d6673a3eee10165d0de4164d4d02a3a77f.woff?v=3.2.1' from origin 'https://staging-example.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://staging-example.herokuapp.com' is therefore not allowed access.
</code>```

I googled the issue and found some info here 'Cloudfront CORS issue serving fonts on Rails application'. As per the first answer I followed all the steps. My rock-cors configuration is

```<code>config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins %w[
            https://staging-example.herokuapp.com
            http://staging-example.herokuapp.com
          ]
    resource '/assets/*'
  end
end
</code>```

which is there in application.rb
Still I am getting this issue

```<code>Access to Font at 'https://eeeeeee.cloudfront.net/assets/fontawesome-webfont-18e6b5ff511b90edf098e62ac45ed9d6673a3eee10165d0de4164d4d02a3a77f.woff?v=3.2.1' from origin 'https://staging-example.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://staging-example.herokuapp.com' is therefore not allowed access.
</code>```

Using curl to look for headers I got this out puts
when hitting my url

```<code>curl -H "Origin: https://staging-example.herokuapp.com" -I https://staging-example.herokuapp.com/assets/fontawesome-webfont-18e6b5ff511b90edf098e62ac45ed9d6673a3eee10165d0de4164d4d02a3a77f.woff?v=3.2.1
HTTP/1.1 200 OK
Server: Cowboy
Date: Sat, 17 Jun 2017 13:49:11 GMT
Connection: keep-alive
Access-Control-Allow-Origin: https://staging-example.herokuapp.com
Access-Control-Allow-Methods: GET
Access-Control-Max-Age: 1728000
Access-Control-Allow-Credentials: true
Last-Modified: Tue, 02 May 2017 11:13:21 GMT
Content-Type: application/font-woff
Vary: Origin
Content-Length: 43572
Via: 1.1 vegur
</code>```

When hitting direclty to cdn url

```<code>curl -H "Origin: https://staging-example.herokuapp.com" -I https://eeeeeee.cloudfront.net/assets/fontawesome-webfont-18e6b5ff511b90edf098e62ac45ed9d6673a3eee10165d0de4164d4d02a3a77f.woff?v=3.2.1
HTTP/1.1 200 OK
Content-Type: application/font-woff
Content-Length: 43572
Connection: keep-alive
Server: Cowboy
Date: Sat, 17 Jun 2017 13:19:04 GMT
Access-Control-Allow-Origin: https://staging-example.herokuapp.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Max-Age: 1728000
Access-Control-Allow-Credentials: true
Last-Modified: Tue, 02 May 2017 11:13:21 GMT
Via: 1.1 vegur, 1.1 21e1fe3458bce196f8eb1701ebbbce53.cloudfront.net (CloudFront)
Vary: Origin
Age: 2023
X-Cache: Hit from cloudfront
X-Amz-Cf-Id: zFXm3g53TJ4Nm6a9oH0yjVq-KUvvPoQI1chz_XN8nnaEd-p-TtQPNg==
</code>```

Clearly the headers are present then why chrome is throwing that error. Kindly help.

答:
You need to add preflight headers to your application_controller.rb
:</p>

```<code>  before_action :cors_set_access_control_headers

  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, PATCH, OPTIONS'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  end
</code>```

Body:
Earlier I was using heroku to server static assets. Then I decided to use cloud front to serve static assets for my rails(5.0.2) app on heroku. After configuring it all seemed good but for fonts chrome was throwing this error .

Access to Font at 'https://eeeeeee.cloudfront.net/assets/fontawesome-webfont-18e6b5ff511b90edf098e62ac45ed9d6673a3eee10165d0de4164d4d02a3a77f.woff?v=3.2.1' from origin 'https://staging-example.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://staging-example.herokuapp.com' is therefore not allowed access.

I googled the issue and found some info here 'Cloudfront CORS issue serving fonts on Rails application'. As per the first answer I followed all the steps. My rock-cors configuration is

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins %w[
            https://staging-example.herokuapp.com
            http://staging-example.herokuapp.com
          ]
    resource '/assets/*'
  end
end

which is there in application.rb
Still I am getting this issue

Access to Font at 'https://eeeeeee.cloudfront.net/assets/fontawesome-webfont-18e6b5ff511b90edf098e62ac45ed9d6673a3eee10165d0de4164d4d02a3a77f.woff?v=3.2.1' from origin 'https://staging-example.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://staging-example.herokuapp.com' is therefore not allowed access.

Using curl to look for headers I got this out puts
when hitting my url

curl -H "Origin: https://staging-example.herokuapp.com" -I https://staging-example.herokuapp.com/assets/fontawesome-webfont-18e6b5ff511b90edf098e62ac45ed9d6673a3eee10165d0de4164d4d02a3a77f.woff?v=3.2.1
HTTP/1.1 200 OK
Server: Cowboy
Date: Sat, 17 Jun 2017 13:49:11 GMT
Connection: keep-alive
Access-Control-Allow-Origin: https://staging-example.herokuapp.com
Access-Control-Allow-Methods: GET
Access-Control-Max-Age: 1728000
Access-Control-Allow-Credentials: true
Last-Modified: Tue, 02 May 2017 11:13:21 GMT
Content-Type: application/font-woff
Vary: Origin
Content-Length: 43572
Via: 1.1 vegur

When hitting direclty to cdn url

curl -H "Origin: https://staging-example.herokuapp.com" -I https://eeeeeee.cloudfront.net/assets/fontawesome-webfont-18e6b5ff511b90edf098e62ac45ed9d6673a3eee10165d0de4164d4d02a3a77f.woff?v=3.2.1
HTTP/1.1 200 OK
Content-Type: application/font-woff
Content-Length: 43572
Connection: keep-alive
Server: Cowboy
Date: Sat, 17 Jun 2017 13:19:04 GMT
Access-Control-Allow-Origin: https://staging-example.herokuapp.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Max-Age: 1728000
Access-Control-Allow-Credentials: true
Last-Modified: Tue, 02 May 2017 11:13:21 GMT
Via: 1.1 vegur, 1.1 21e1fe3458bce196f8eb1701ebbbce53.cloudfront.net (CloudFront)
Vary: Origin
Age: 2023
X-Cache: Hit from cloudfront
X-Amz-Cf-Id: zFXm3g53TJ4Nm6a9oH0yjVq-KUvvPoQI1chz_XN8nnaEd-p-TtQPNg==

Clearly the headers are present then why chrome is throwing that error. Kindly help.

Body:
You need to add preflight headers to your application_controller.rb
:

  before_action :cors_set_access_control_headers

  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, PATCH, OPTIONS'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  end


问:
hyperHTML seemingly fails to call (attach?) onload events
I'm attempting to dynamically conditionally load additional JavaScript while using hyperHTML. I've narrowed the failure to the onload event.

Here's an attempt at a minimal, complete, and verifiable example:

class ScriptLoader extends hyperHTML.Component {
  onload(event) {
    notie.alert({ text: "notie loaded" });
  }
  render() {
    return this.html`
      ```

As you can see notie.alert is never called, even though the script is inserted correctly.

This some process works correctly using vanilla JS with addEventListener('load', and appendChild(.

答:
Update this was an issue with Firefox and Web (Safari) considering death nodes scripts injected via innerHTML, even if through a template and after imported.

That means the issue was not with the onload per-se, rather the fact no network request was ever triggered so that onload would never happen indeed.

As you can verify now in the Code Pen eaxmple, which uses your exact same snippet I rewrite in part to make SO happy about me linking Code Pen, both Firefox and Safari, as well as Chrome and Edge should work just fine.

```<code>hyperHTML.bind(document.body)`
  <h2>onload test (notie)</h2>
  ${new ScriptLoader}
`;
</code>```

I am keeping part of the old edit just to make you, or any other reader, aware of a little caveat that JSX affectionate might overuse.

There is one thing you should be careful with: hyperHTML does not parse HTML and

Body:
I'm attempting to dynamically conditionally load additional JavaScript while using hyperHTML. I've narrowed the failure to the onload event.

Here's an attempt at a minimal, complete, and verifiable example:

class ScriptLoader extends hyperHTML.Component {
  onload(event) {
    notie.alert({ text: "notie loaded" });
  }
  render() {
    return this.html`

As you can see notie.alert is never called, even though the script is inserted correctly.

This some process works correctly using vanilla JS with addEventListener('load', and appendChild(.

Body:
Update this was an issue with Firefox and Web (Safari) considering death nodes scripts injected via innerHTML, even if through a template and after imported.

That means the issue was not with the onload per-se, rather the fact no network request was ever triggered so that onload would never happen indeed.

As you can verify now in the Code Pen eaxmple, which uses your exact same snippet I rewrite in part to make SO happy about me linking Code Pen, both Firefox and Safari, as well as Chrome and Edge should work just fine.

hyperHTML.bind(document.body)`
  <h2>onload test (notie)</h2>
  ${new ScriptLoader}
`;

I am keeping part of the old edit just to make you, or any other reader, aware of a little caveat that JSX affectionate might overuse.

There is one thing you should be careful with: hyperHTML does not parse HTML and <script/> is not valid HTML.

You are risking to find nodes where you shouldn't if you don't close non-void tags regularly, and this is beyond hyperHTML capabilities, unfortunately how HTML works in general.

<p/><b>unexpected</b>

I understand for this demo case you had to do that or the parse would complain with a closing script in the page but remember, you can always do this instead, when necessary:

`<script><\x2fscript>`


问:
Why can't I capture this by-reference ('&this') in lambda?
I understand the correct way to capture this (to modify object properties) in a lambda is as follows:

```<code>auto f = [this] () { /* ... */ };
</code>```

But I'm curious as to the following peculiarity I've seen:

```<code>class C {
    public:
        void foo() {
            // auto f = [] () { // this not captured
            auto f = [&] () { // why does this work?
            // auto f = [&this] () { // Expected ',' before 'this'
            // auto f = [this] () { // works as expected
                x = 5;
            };
            f();
        }

    private:
        int x;
};
</code>```

The oddity that I am confused by (and would like answered) is why the following works:

```<code>auto f = [&] () { /* ... */ }; // capture everything by reference
</code>```

And why I cannot explicitly capture this by reference:

```<code>auto f = [&this] () { /* ... */ }; // a compiler error as seen above.
</code>```

答:
Because standard doesn't have &this in Captures lists:

N4713 8.4.5.2 Captures:

```<code>lambda-capture:
    capture-default
    capture-list
    capture-default, capture-list

capture-default:
    &
    =
capture-list:
    capture...opt
    capture-list, capture...opt
capture:
    simple-capture
    init-capture
simple-capture:
    identifier
    &identifier
    this
    * this
init-capture:
    identifier initializer
    &identifier initializer
</code>```

For the purposes of lambda capture, an expression potentially references local entities as follows:

7.3    A this expression potentially references *this.

So, standard guarantees this and *this is valid, and &this is invalid. Also, capturing this means capturing *this(which is a lvalue, the object itself) by reference, rather than capturing this pointer by value!

Body:
I understand the correct way to capture this (to modify object properties) in a lambda is as follows:

auto f = [this] () { /* ... */ };

But I'm curious as to the following peculiarity I've seen:

class C {
    public:
        void foo() {
            // auto f = [] () { // this not captured
            auto f = [&] () { // why does this work?
            // auto f = [&this] () { // Expected ',' before 'this'
            // auto f = [this] () { // works as expected
                x = 5;
            };
            f();
        }

    private:
        int x;
};

The oddity that I am confused by (and would like answered) is why the following works:

auto f = [&] () { /* ... */ }; // capture everything by reference

And why I cannot explicitly capture this by reference:

auto f = [&this] () { /* ... */ }; // a compiler error as seen above.

Body:
Because standard doesn't have &this in Captures lists:

N4713 8.4.5.2 Captures:

lambda-capture:
    capture-default
    capture-list
    capture-default, capture-list

capture-default:
    &
    =
capture-list:
    capture...opt
    capture-list, capture...opt
capture:
    simple-capture
    init-capture
simple-capture:
    identifier
    &identifier
    this
    * this
init-capture:
    identifier initializer
    &identifier initializer

For the purposes of lambda capture, an expression potentially references local entities as follows:

7.3    A this expression potentially references *this.

So, standard guarantees this and *this is valid, and &this is invalid. Also, capturing this means capturing *this(which is a lvalue, the object itself) by reference, rather than capturing this pointer by value!


问:
How to handle calls to multiple functions in the same web service?
This is a super newbie question on Flex.  While I am a seasoned programmer, this is my first ever Flex application; please bear with me for my Flex codes.

I have a web service written in ColdFusion.  In this web service, there are two functions; one is to return all the questions in a quiz and the other one is to return all the answer selections to the questions in a quiz.

```<code>            [Bindable]
        private var questionArray:ArrayCollection;
        private var cfquiz:RemoteObject;

        private function loadQuestions():void {
            currentQuestionCounter = 0;
            btnPrev.enabled = false;
            btnNext.enabled = false;
            cfquiz = new RemoteObject("ColdFusion");
            cfquiz.source = "CFCertExam.cfquiz";
            cfquiz.addEventListener(ResultEvent.RESULT, resultHandler);
        }

        private function resultHandler(event:ResultEvent):void {
            questionArray = event.result as ArrayCollection;

            txt1Questions.htmlText = questionArray.getItemAt(currentQuestionCounter).Question_Text;
            btnNext.enabled = true;
        }
</code>```

I have the codes above.  loadQuestions is called at creationComplete to retrieve the questions.  Things are working fine.  What I want to do is to call another function within the same web service, returnAnswers, to return the answer options for a question.  Since I have cfquiz associated to the web service already, I was using cfquiz to call returnAnswers.  However, there is an event listener associated to cfquiz already, resultHandler is being called when returnAnswers comes back with the results.

My questions are, first, is it possible to check which function returns the results within resultHandler?  If so, how?  And second, what is the best way to handle calls to multiple functions within the same web service?

Thanks in advance,
Monte

答:
I'm a little confused as I can't see where you are calling the actual web service function, for example from these examples, I am expecting to see:

```<code>cfquiz = new RemoteObject("ColdFusion");
cfquiz.source = "CFCertExam.cfquiz";
cfquiz.addEventListener(ResultEvent.RESULT, resultHandler);
cfquiz.myCFCFunctionCall(); /* where is this? */
</code>```

Anyway, AFAIK you can create a new instance of the remote object and set that up to have it's own event listener.

Hope that helps.

Body:
This is a super newbie question on Flex.  While I am a seasoned programmer, this is my first ever Flex application; please bear with me for my Flex codes.

I have a web service written in ColdFusion.  In this web service, there are two functions; one is to return all the questions in a quiz and the other one is to return all the answer selections to the questions in a quiz.

            [Bindable]
        private var questionArray:ArrayCollection;
        private var cfquiz:RemoteObject;

        private function loadQuestions():void {
            currentQuestionCounter = 0;
            btnPrev.enabled = false;
            btnNext.enabled = false;
            cfquiz = new RemoteObject("ColdFusion");
            cfquiz.source = "CFCertExam.cfquiz";
            cfquiz.addEventListener(ResultEvent.RESULT, resultHandler);
        }

        private function resultHandler(event:ResultEvent):void {
            questionArray = event.result as ArrayCollection;

            txt1Questions.htmlText = questionArray.getItemAt(currentQuestionCounter).Question_Text;
            btnNext.enabled = true;
        }

I have the codes above.  loadQuestions is called at creationComplete to retrieve the questions.  Things are working fine.  What I want to do is to call another function within the same web service, returnAnswers, to return the answer options for a question.  Since I have cfquiz associated to the web service already, I was using cfquiz to call returnAnswers.  However, there is an event listener associated to cfquiz already, resultHandler is being called when returnAnswers comes back with the results.

My questions are, first, is it possible to check which function returns the results within resultHandler?  If so, how?  And second, what is the best way to handle calls to multiple functions within the same web service?

Thanks in advance,
Monte

Body:
I'm a little confused as I can't see where you are calling the actual web service function, for example from these examples, I am expecting to see:

cfquiz = new RemoteObject("ColdFusion");
cfquiz.source = "CFCertExam.cfquiz";
cfquiz.addEventListener(ResultEvent.RESULT, resultHandler);
cfquiz.myCFCFunctionCall(); /* where is this? */

Anyway, AFAIK you can create a new instance of the remote object and set that up to have it's own event listener.

Hope that helps.


问:
jQplot Bar Colours Are Wrong With Negative Values
See the attached image, the bar colours are wrong when there are values 0 or below. I have the code set like this:

```<code>seriesColors:['#09c700','#ff0000','#3854ff']

negativeSeriesColors:['#09c700','#ff0000','#3854ff']
</code>```

It seems when a value is 0 or lower it skips the colour. My colour settings are set so the first bar should be green, the second red and the third blue, but you can see it's made the second bar (middle) blue and the last one red and this only happens because the middle bar is a negative value.

答:
This is because it's using "negative" colors, which are separate from your defined "positive" colors.  You can disable the negative colors with useNegativeColors: false on the series render options.

$(document).ready(function(){
    var line1 = [['Nissan', 4],['Porche', -6],['Acura', 2]];

    $('#chart').jqplot([line1], {
        title:'Bar Chart with Custom Colors',
        seriesColors:['#09c700','#ff0000','#3854ff'],
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer,
            rendererOptions: {
                varyBarColor: true,
                fillToZero: true,
                useNegativeColors: false
            }
        },
        axes:{
            xaxis:{
                renderer: $.jqplot.CategoryAxisRenderer
            }
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/jquery.jqplot.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/jquery.jqplot.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/plugins/jqplot.barRenderer.min.js"></script>
<div id="chart"></div></code>```

Body:
See the attached image, the bar colours are wrong when there are values 0 or below. I have the code set like this:

seriesColors:['#09c700','#ff0000','#3854ff']

negativeSeriesColors:['#09c700','#ff0000','#3854ff']

It seems when a value is 0 or lower it skips the colour. My colour settings are set so the first bar should be green, the second red and the third blue, but you can see it's made the second bar (middle) blue and the last one red and this only happens because the middle bar is a negative value.

Body:
This is because it's using "negative" colors, which are separate from your defined "positive" colors.  You can disable the negative colors with useNegativeColors: false on the series render options.

$(document).ready(function(){
    var line1 = [['Nissan', 4],['Porche', -6],['Acura', 2]];

    $('#chart').jqplot([line1], {
        title:'Bar Chart with Custom Colors',
        seriesColors:['#09c700','#ff0000','#3854ff'],
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer,
            rendererOptions: {
                varyBarColor: true,
                fillToZero: true,
                useNegativeColors: false
            }
        },
        axes:{
            xaxis:{
                renderer: $.jqplot.CategoryAxisRenderer
            }
        }
    });
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/jquery.jqplot.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/jquery.jqplot.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqPlot/1.0.9/plugins/jqplot.barRenderer.min.js"></script>
<div id="chart"></div>