问:
how to solve Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException migrating to Java 11(Openjdk-11.0.1 )
I have installed OpenJDK 11.0.1 and when i try to run my application using mvn install, i get the following error, i have added the necessary dependency as fix by adding javax.xml.bind to my pom.xml but it doesn't seem to work, anybody faced this problem? do i need to do anything else?
my mvn --version returns this

```<code>Maven home: /usr/local/Cellar/maven/3.5.2/libexec
Java version: 11.0.1, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
Default locale: en_GB, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.2", arch: "x86_64", family: "mac"
</code>```

i add this but didn't fix the problem

```<code><dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>
</code>```

and here is what i get

```<code>[INFO] --- maven-failsafe-plugin:2.20:integration-test (failsafe-integration-tests) @ name-sample-test ---
[WARNING] Error injecting: org.apache.maven.plugin.failsafe.IntegrationTestMojo
java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
    at java.base/java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredConstructors(Class.java:3138)
    at java.base/java.lang.Class.getDeclaredConstructors(Class.java:2358)
    at com.google.inject.spi.InjectionPoint.forConstructorOf(InjectionPoint.java:245)
    at com.google.inject.internal.ConstructorBindingImpl.create(ConstructorBindingImpl.java:99)
    at com.google.inject.internal.InjectorImpl.createUninitializedBinding(InjectorImpl.java:658)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBinding(InjectorImpl.java:882)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBindingRecursive(InjectorImpl.java:805)
    at com.google.inject.internal.InjectorImpl.getJustInTimeBinding(InjectorImpl.java:282)
    at com.google.inject.internal.InjectorImpl.getBindingOrThrow(InjectorImpl.java:214)
    at com.google.inject.internal.InjectorImpl.getProviderOrThrow(InjectorImpl.java:1006)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1038)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1001)
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051)
    at org.eclipse.sisu.space.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:53)
    at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:65)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
    at org.eclipse.sisu.bean.BeanScheduler$Activator.onProvision(BeanScheduler.java:176)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:126)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:63)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:45)
    at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1016)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
    at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1012)
    at org.eclipse.sisu.inject.Guice4$1.get(Guice4.java:162)
    at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
    at org.eclipse.sisu.plexus.LazyPlexusBean.getValue(LazyPlexusBean.java:51)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:263)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:255)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:517)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:121)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:47)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
    ... 56 more
</code>```

答:
You need add this dependency as well,</p>

```<code><dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.0</version>
</dependency>
</code>```

Body:
I have installed OpenJDK 11.0.1 and when i try to run my application using mvn install, i get the following error, i have added the necessary dependency as fix by adding javax.xml.bind to my pom.xml but it doesn't seem to work, anybody faced this problem? do i need to do anything else?
my mvn --version returns this

Maven home: /usr/local/Cellar/maven/3.5.2/libexec
Java version: 11.0.1, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
Default locale: en_GB, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.2", arch: "x86_64", family: "mac"

i add this but didn't fix the problem

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

and here is what i get

[INFO] --- maven-failsafe-plugin:2.20:integration-test (failsafe-integration-tests) @ name-sample-test ---
[WARNING] Error injecting: org.apache.maven.plugin.failsafe.IntegrationTestMojo
java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
    at java.base/java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredConstructors(Class.java:3138)
    at java.base/java.lang.Class.getDeclaredConstructors(Class.java:2358)
    at com.google.inject.spi.InjectionPoint.forConstructorOf(InjectionPoint.java:245)
    at com.google.inject.internal.ConstructorBindingImpl.create(ConstructorBindingImpl.java:99)
    at com.google.inject.internal.InjectorImpl.createUninitializedBinding(InjectorImpl.java:658)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBinding(InjectorImpl.java:882)
    at com.google.inject.internal.InjectorImpl.createJustInTimeBindingRecursive(InjectorImpl.java:805)
    at com.google.inject.internal.InjectorImpl.getJustInTimeBinding(InjectorImpl.java:282)
    at com.google.inject.internal.InjectorImpl.getBindingOrThrow(InjectorImpl.java:214)
    at com.google.inject.internal.InjectorImpl.getProviderOrThrow(InjectorImpl.java:1006)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1038)
    at com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1001)
    at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051)
    at org.eclipse.sisu.space.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:53)
    at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:65)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
    at org.eclipse.sisu.bean.BeanScheduler$Activator.onProvision(BeanScheduler.java:176)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:126)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:63)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:45)
    at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1016)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
    at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1012)
    at org.eclipse.sisu.inject.Guice4$1.get(Guice4.java:162)
    at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
    at org.eclipse.sisu.plexus.LazyPlexusBean.getValue(LazyPlexusBean.java:51)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:263)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:255)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:517)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:121)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:47)
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
    ... 56 more

Body:
You need add this dependency as well,

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.3.0</version>
</dependency>


来源: stackexchange

问:
map function returns item even if condition is not true
Here's my code:

```<code>//input = aaaaaaa,                ddd,            ,
 asdsad,

newUser =
users
  .split(',')
  .map(item => {
    item = item.trim();
    if(item.length > 0) {
      return item;
    }
}).join();

//output = aaaaaaa,ddd,,asdsad,
</code>```

So my question is why if item has 0 length is returned from map function? Am I missing something obvious?

//EDIT:

Yeah, now its removoing empty strings but what about white spaces? My result still looks like this:

asdasdasd      ,       aa

I want to have:

asdasdasd,aa

答:
The length of the array returned by map() will always be equal to the length of orignal array. When you want to remove elements of array accoring to condition use filter() .

In the particular case you can remove white spaces first from the string and then remove two or more adjacent commas with single comma.

let input = 'aaaaaaa,                ddd,            ,     asdsad,'
let res = input.replace(/\s+/g,'').replace(/,{2,}/,',');
console.log(res)```

ContentLicense: CC BY-SA 4.0

Body:
Here's my code:

//input = aaaaaaa,                ddd,            ,
 asdsad,

newUser =
users
  .split(',')
  .map(item => {
    item = item.trim();
    if(item.length > 0) {
      return item;
    }
}).join();

//output = aaaaaaa,ddd,,asdsad,

So my question is why if item has 0 length is returned from map function? Am I missing something obvious?

//EDIT:

Yeah, now its removoing empty strings but what about white spaces? My result still looks like this:

asdasdasd      ,       aa

I want to have:

asdasdasd,aa


问:
How does one effectively handle temporary objects in Core Data since the objectID changes between temporary objects and permanent objects?
What is the best way to handle temporary objects in Core Data?  I've seen solutions where temporary contexts are created, where they are inserted into nil contexts, etc.

However, here's the issue I'm seeing in both of these solutions.  I'm using Core Data for my object model and and in some of my views store a NSSet of Core Data objects.  The problem I have is when the object is stored, the objectID changes which effectively invalidates anything stored in any NSSet since the isEqual and hash are now different.  While I could invalidate the object stored in the NSSet, it often is not practical and certainly not always easy.

Here's the things I've considered:

1)  override isEqual method and hash on NSManagedObject (obviously bad)

2)  do not place any NSManagedObject in a NSSet (use a NSDictionary where the key is always fixed)

3)  use an entirely different type to store in NSSet where I could correctly implement the isEqual and hash code methods

Does anyone have a better solution for this?

答: ManagedObjects in an NSSet -- that sounds like a Core Data relationship. Why not simply store your temporary managedObjects in a relationship, and have Core Data take care of the problems you're now running into. Then you can concentrate on when and how to delete the temporary objects, or break the relationship or whatever is needed.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Find missing item in a list grouped
I have a list of objects dailySchedule with the properties Order, District, and other properties.

```<code>public class dailySchedule
{
        public int Order { get; set; }
        public string Title { get;  }
        public string District { get;  }
        ....
}
</code>```

the list is loaded with these values

Each district must have 6 orders,

var ordersValue = new List<int> {1, 2, 3, 4, 5, 6};

I want to find for each district, which order is missing.

The result must be
District 0  order {2,3,5,6}
District 12 order {5,6}

How can do that with linq c#?

答:
Try the below code which will give you result with each district and its missing orders</p>

```<code>        var allOrders = new List<int>() { 1, 2, 3, 4, 5, 6 };
        var result = orders.GroupBy(gp => gp.District).Select(sl =>
            new { District = sl.Key, Order = allOrders.Where(wh => sl.All(all => all.Order != wh)) });
</code>```

Title: Find missing item in a list grouped

Body:
I have a list of objects dailySchedule with the properties Order, District, and other properties.

public class dailySchedule
{
        public int Order { get; set; }
        public string Title { get;  }
        public string District { get;  }
        ....
}

the list is loaded with these values

Each district must have 6 orders,

var ordersValue = new List<int> {1, 2, 3, 4, 5, 6};

I want to find for each district, which order is missing.

The result must be
District 0  order {2,3,5,6}
District 12 order {5,6}

How can do that with linq c#?

Body:
Try the below code which will give you result with each district and its missing orders

        var allOrders = new List<int>() { 1, 2, 3, 4, 5, 6 };
        var result = orders.GroupBy(gp => gp.District).Select(sl =>
            new { District = sl.Key, Order = allOrders.Where(wh => sl.All(all => all.Order != wh)) });


问:
Spring Boot, MySQL, Tomcat can't create intital connections of pool in Eclipse
I have created a webapp using Spring Boot and REST APIs in Eclipse. When I try to run it using Tomcat 8, it gives the error
"o.a.tomcat.jdbc.pool.ConnectionPool: Unable to create initial connections of pool."

I tried using the solutions provided but nothing seemed to work, it always gives the same error.

This is my application.properties file -

```<code>spring.datasource.url = jdbc:mysql://localhost:3306/dbase?autoReconnect=true&useSSL=false
spring.datasource.username = 1234
spring.datasource.password = 1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

spring.jpa.hibernate.ddl-auto = update
</code>```

and this is the pom.xml file -

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.springboot</groupId>
  <artifactId>springbootrestapi</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springbootrestapiexample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  </dependencies>
  <build>
    <finalName>springbootrestapiexample</finalName>
  </build>
</project>
</code>```

This is the stack trace -

```<code>16:33:43.182 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
16:33:43.206 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
16:33:43.207 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Users/Amber%20Bhanarkar/eclipse-workspace/springbootrestapi/target/classes/]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2019-05-29 16:33:43.767  INFO 13396 --- [  restartedMain] c.s.s.StudentApplication                 : Starting StudentApplication on LAPTOP-BV6107FE with PID 13396 (started by Amber Bhanarkar in C:\Users\Amber Bhanarkar\eclipse-workspace\springbootrestapi)
2019-05-29 16:33:43.768  INFO 13396 --- [  restartedMain] c.s.s.StudentApplication                 : No active profile set, falling back to default profiles: default
2019-05-29 16:33:43.892  INFO 13396 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@754391d8: startup date [Wed May 29 16:33:43 IST 2019]; root of context hierarchy
2019-05-29 16:33:49.463  INFO 13396 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-05-29 16:33:49.552  INFO 13396 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-29 16:33:49.554  INFO 13396 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
2019-05-29 16:33:50.076  INFO 13396 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-29 16:33:50.076  INFO 13396 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 6188 ms
2019-05-29 16:33:50.354  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2019-05-29 16:33:50.359  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-05-29 16:33:55.529 ERROR 13396 --- [  restartedMain] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
</code>```

Here is StudentApplication.java -

```<code>package com.springboot.springbootrestapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@SpringBootApplication
@EnableJpaAuditing
public class StudentApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudentApplication.class, args);
    }

}
</code>```

答:
You have to change quite few things

1.Goto your mysql installed directory in C drive and find my.ini file.

Change default_authentication_plugin to this

```<code>default_authentication_plugin=mysql_native_password
</code>```

and then goto your MySQL command line client,
After logging in, run this query:

ALTER USER 'yourusername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'yourpassword';

then restart the mysql service and run your program.

replace "yourusername" and "yourpassword" with your actual username and password of MySQL.

Goto POM and replace:

```<code>    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</code>```

with latest MySQL8 connector

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

i hope it helps :)

Body:
I have created a webapp using Spring Boot and REST APIs in Eclipse. When I try to run it using Tomcat 8, it gives the error
"o.a.tomcat.jdbc.pool.ConnectionPool: Unable to create initial connections of pool."

I tried using the solutions provided but nothing seemed to work, it always gives the same error.

This is my application.properties file -

spring.datasource.url = jdbc:mysql://localhost:3306/dbase?autoReconnect=true&useSSL=false
spring.datasource.username = 1234
spring.datasource.password = 1234
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

spring.jpa.hibernate.ddl-auto = update

and this is the pom.xml file -

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.springboot</groupId>
  <artifactId>springbootrestapi</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springbootrestapiexample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  </dependencies>
  <build>
    <finalName>springbootrestapiexample</finalName>
  </build>
</project>

This is the stack trace -

16:33:43.182 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
16:33:43.206 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
16:33:43.207 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Users/Amber%20Bhanarkar/eclipse-workspace/springbootrestapi/target/classes/]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2019-05-29 16:33:43.767  INFO 13396 --- [  restartedMain] c.s.s.StudentApplication                 : Starting StudentApplication on LAPTOP-BV6107FE with PID 13396 (started by Amber Bhanarkar in C:\Users\Amber Bhanarkar\eclipse-workspace\springbootrestapi)
2019-05-29 16:33:43.768  INFO 13396 --- [  restartedMain] c.s.s.StudentApplication                 : No active profile set, falling back to default profiles: default
2019-05-29 16:33:43.892  INFO 13396 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@754391d8: startup date [Wed May 29 16:33:43 IST 2019]; root of context hierarchy
2019-05-29 16:33:49.463  INFO 13396 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-05-29 16:33:49.552  INFO 13396 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-05-29 16:33:49.554  INFO 13396 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
2019-05-29 16:33:50.076  INFO 13396 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-05-29 16:33:50.076  INFO 13396 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 6188 ms
2019-05-29 16:33:50.354  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2019-05-29 16:33:50.359  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-05-29 16:33:50.360  INFO 13396 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-05-29 16:33:55.529 ERROR 13396 --- [  restartedMain] o.a.tomcat.jdbc.pool.ConnectionPool      : Unable to create initial connections of pool.

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.

Here is StudentApplication.java -

package com.springboot.springbootrestapi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@SpringBootApplication
@EnableJpaAuditing
public class StudentApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudentApplication.class, args);
    }

}

Body:
You have to change quite few things

1.Goto your mysql installed directory in C drive and find my.ini file.

Change default_authentication_plugin to this

default_authentication_plugin=mysql_native_password

and then goto your MySQL command line client,
After logging in, run this query:

ALTER USER 'yourusername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'yourpassword';

then restart the mysql service and run your program.

replace "yourusername" and "yourpassword" with your actual username and password of MySQL.

Goto POM and replace:

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>

with latest MySQL8 connector

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

i hope it helps :)


问:
Why isn't the code working (here) when I try to change values of a list using 'for' loop?
Let's say there's this random list:

```<code>st=['smthg','xyz','random','000','666']
</code>```

I want to change the values of the indices 1 to 3 using this for loop:

```<code>for anythg in st:
      st[1:3]='whtevr'
</code>```

The shell(IDLE) doesn't give any response to this and the commandline freezes (the cmdln, however, after interrupting the execution and typing in 'st', it starts displaying:

```<code>'t','e','v','r','t','e','v','r','t','e','v','r','t','e','v','r','t','e','v',
</code>```

endlessly,until one again presses ctrl+C ).

I know the correct way to execute that properly would be:

```<code>for i in range(1,4):
    st[i]='whtevr'
</code>```

Still, I'm expecting an answer for why didn't the previous one work?
(a beginner question, still.)

*

答:
You can use list comprehension using enumerate and check for the indices using if/else

```<code>st = ['smthg','xyz','random','000','666']

new_st = ['wtevr' if 0 < i < 4 else ele for i, ele in enumerate(st)]
# ['smthg', 'wtevr', 'wtevr', 'wtevr', '666']
</code>```

If you want to stick to your version, you should create a copy of the original list first and then change the elements in the copy

```<code>st=['smthg','xyz','random','000','666']
new_st = st[:]

for i in range(len(new_st)):
    if 0<i<4:
        new_st[i]='whtevr'
</code>```

Body:
Let's say there's this random list:

st=['smthg','xyz','random','000','666']

I want to change the values of the indices 1 to 3 using this for loop:

for anythg in st:
      st[1:3]='whtevr'

The shell(IDLE) doesn't give any response to this and the commandline freezes (the cmdln, however, after interrupting the execution and typing in 'st', it starts displaying:

't','e','v','r','t','e','v','r','t','e','v','r','t','e','v','r','t','e','v',

endlessly,until one again presses ctrl+C ).

I know the correct way to execute that properly would be:

for i in range(1,4):
    st[i]='whtevr'

Still, I'm expecting an answer for why didn't the previous one work?
(a beginner question, still.)

*

Body:
You can use list comprehension using enumerate and check for the indices using if/else

st = ['smthg','xyz','random','000','666']

new_st = ['wtevr' if 0 < i < 4 else ele for i, ele in enumerate(st)]
# ['smthg', 'wtevr', 'wtevr', 'wtevr', '666']

If you want to stick to your version, you should create a copy of the original list first and then change the elements in the copy

st=['smthg','xyz','random','000','666']
new_st = st[:]

for i in range(len(new_st)):
    if 0<i<4:
        new_st[i]='whtevr'


问:
Winsock2: select() function giving "invalid arguement error" (Error 10022)?
Running the select() function (Line 13 of provided code) returns error 10022 (WSAEINVAL) meaning either my timeout variable in negative or all 3 other variables are NULL. But I only get this error after the first iteration through the outside loop.

Basically my set up is send a window of packets of size N at base, then check to see if any confirmations have been sent back to me by checking if my socket is ready to be read from. For the first window of packets, the select() call works just fine, returning 1. But all calls to select() after the first iteration of the full loop result in the error code. I'm completely out of ideas.

I saw a thread saying to just wrap the function with another function call and it didn't seem to change the problem. I have no idea why it would work the first loop but not at all after that.

```<code>int Exit = 0;
int endRecv = 0;
int ready = 0;
//Sending Algorithm
int base = 0;
uint32_t confirmedPosition;

while (Exit == 0) {
    //Send data in an N sized Window.
    for (int i = 0; i < N; i++) {
        if (successfulPackets[i + base] != 1) {
            memcpy(&buffer_tx, &packets[i + base], BUFFERS_LEN);
            sendto(socketS, buffer_tx, BUFFERS_LEN, 0, (sockaddr*)& addrDest, sizeof(addrDest));
        }
    }
    endRecv = 0;
    //Receive Confirmations
    while (endRecv == 0) {
        //Poll to see if something is waiting
        ready = select(NULL, &readfds, NULL, NULL, &pollTime);
        if (ready == -1) {
            printf("Error with Code: %d", WSAGetLastError());
        } else if (ready == 1) {//If yes, log confirmation
            recvfrom(socketS, buffer_rx, BUFFERS_LEN, 0, (sockaddr *)&from, &fromlen);
            memcpy(&confirmedPosition, &buffer_rx, 4);
            successfulPackets[confirmedPosition] = 1;
            fileSize -= BUFFERS_LEN - 8;
        } else {//If no, end receiving and send
            endRecv = 1;
        }
    }
    //Apply Changes to Base
    for (int i = 0; i < N; i++) {
        if (successfulPackets[base] == 1) {
            base++;
        }
    }
    if (fileSize <= 0) {
        Exit = 1;
    }
}
</code>```

答:
When select returns 0 then the content of the structure readfds is also set to zero (select modifies it to indicate which socket is ready).

When the outer loop executes again then the readfds structure does not contain any socket to check, which causes the error. You should set again the socket in readfds.

Body:
Running the select() function (Line 13 of provided code) returns error 10022 (WSAEINVAL) meaning either my timeout variable in negative or all 3 other variables are NULL. But I only get this error after the first iteration through the outside loop.

Basically my set up is send a window of packets of size N at base, then check to see if any confirmations have been sent back to me by checking if my socket is ready to be read from. For the first window of packets, the select() call works just fine, returning 1. But all calls to select() after the first iteration of the full loop result in the error code. I'm completely out of ideas.

I saw a thread saying to just wrap the function with another function call and it didn't seem to change the problem. I have no idea why it would work the first loop but not at all after that.

int Exit = 0;
int endRecv = 0;
int ready = 0;
//Sending Algorithm
int base = 0;
uint32_t confirmedPosition;

while (Exit == 0) {
    //Send data in an N sized Window.
    for (int i = 0; i < N; i++) {
        if (successfulPackets[i + base] != 1) {
            memcpy(&buffer_tx, &packets[i + base], BUFFERS_LEN);
            sendto(socketS, buffer_tx, BUFFERS_LEN, 0, (sockaddr*)& addrDest, sizeof(addrDest));
        }
    }
    endRecv = 0;
    //Receive Confirmations
    while (endRecv == 0) {
        //Poll to see if something is waiting
        ready = select(NULL, &readfds, NULL, NULL, &pollTime);
        if (ready == -1) {
            printf("Error with Code: %d", WSAGetLastError());
        } else if (ready == 1) {//If yes, log confirmation
            recvfrom(socketS, buffer_rx, BUFFERS_LEN, 0, (sockaddr *)&from, &fromlen);
            memcpy(&confirmedPosition, &buffer_rx, 4);
            successfulPackets[confirmedPosition] = 1;
            fileSize -= BUFFERS_LEN - 8;
        } else {//If no, end receiving and send
            endRecv = 1;
        }
    }
    //Apply Changes to Base
    for (int i = 0; i < N; i++) {
        if (successfulPackets[base] == 1) {
            base++;
        }
    }
    if (fileSize <= 0) {
        Exit = 1;
    }
}


问:
Remove padding/margin from JavaFX Label
Is there a way to remove the default space (padding/margin) that JavaFX label adds? I want to get rid of the space displayed between the black lines on the image below:

Source code:

```<code>public class LabelTest extends Application
{

    @Override
    public void start(final Stage primaryStage)
    {
        final Group root = new Group();
        final Scene scene = new Scene(root, 300, 130, Color.WHITE);

        final GridPane gridpane = new GridPane();
        gridpane.setPadding(new Insets(5));
        gridpane.setHgap(10);
        gridpane.setVgap(10);

        final Label label = new Label("Label");
        label.setStyle("-fx-font-size:44px;-fx-font-weight: bold;-fx-text-fill:#5E34B1;-fx-background-color:#ffc300;");
        GridPane.setHalignment(label, HPos.CENTER);
        gridpane.add(label, 0, 0);

        root.getChildren().add(gridpane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
</code>```

答:
For me it was easiest to just use setPadding.

```<code>label.setPadding(new Insets(-2,0,0,0)); //top, right, bottom, left
</code>```

This way I did not have to deal with the css-style sheet.

Title: Remove padding/margin from JavaFX Label

Body:
Is there a way to remove the default space (padding/margin) that JavaFX label adds? I want to get rid of the space displayed between the black lines on the image below:

Source code:

public class LabelTest extends Application
{

    @Override
    public void start(final Stage primaryStage)
    {
        final Group root = new Group();
        final Scene scene = new Scene(root, 300, 130, Color.WHITE);

        final GridPane gridpane = new GridPane();
        gridpane.setPadding(new Insets(5));
        gridpane.setHgap(10);
        gridpane.setVgap(10);

        final Label label = new Label("Label");
        label.setStyle("-fx-font-size:44px;-fx-font-weight: bold;-fx-text-fill:#5E34B1;-fx-background-color:#ffc300;");
        GridPane.setHalignment(label, HPos.CENTER);
        gridpane.add(label, 0, 0);

        root.getChildren().add(gridpane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Body:
For me it was easiest to just use setPadding.

label.setPadding(new Insets(-2,0,0,0)); //top, right, bottom, left

This way I did not have to deal with the css-style sheet.


问:
Cannot resolve scoped service from root provider .Net Core 2
When I try to run my app I get the error

```<code>InvalidOperationException: Cannot resolve 'API.Domain.Data.Repositories.IEmailRepository' from root provider because it requires scoped service 'API.Domain.Data.EmailRouterContext'.
</code>```

What's odd is that this EmailRepository and interface is set up exactly the same as far as I can tell as all of my other repositories yet no error is thrown for them.  The error only occurs if I try to use the app.UseEmailingExceptionHandling(); line. Here's some of my Startup.cs file.

```<code>public class Startup
{
    public IConfiguration Configuration { get; protected set; }
    private APIEnvironment _environment { get; set; }

    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        Configuration = configuration;

        _environment = APIEnvironment.Development;
        if (env.IsProduction()) _environment = APIEnvironment.Production;
        if (env.IsStaging()) _environment = APIEnvironment.Staging;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var dataConnect = new DataConnect(_environment);

        services.AddDbContext<GeneralInfoContext>(opt => opt.UseSqlServer(dataConnect.GetConnectString(Database.GeneralInfo)));
        services.AddDbContext<EmailRouterContext>(opt => opt.UseSqlServer(dataConnect.GetConnectString(Database.EmailRouter)));

        services.AddWebEncoders();
        services.AddMvc();

        services.AddScoped<IGenInfoNoteRepository, GenInfoNoteRepository>();
        services.AddScoped<IEventLogRepository, EventLogRepository>();
        services.AddScoped<IStateRepository, StateRepository>();
        services.AddScoped<IEmailRepository, EmailRepository>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        app.UseAuthentication();

        app.UseStatusCodePages();
        app.UseEmailingExceptionHandling();

        app.UseMvcWithDefaultRoute();
    }
}
</code>```

Here is the EmailRepository

```<code>public interface IEmailRepository
{
    void SendEmail(Email email);
}

public class EmailRepository : IEmailRepository, IDisposable
{
    private bool disposed;
    private readonly EmailRouterContext edc;

    public EmailRepository(EmailRouterContext emailRouterContext)
    {
        edc = emailRouterContext;
    }

    public void SendEmail(Email email)
    {
        edc.EmailMessages.Add(new EmailMessages
        {
            DateAdded = DateTime.Now,
            FromAddress = email.FromAddress,
            MailFormat = email.Format,
            MessageBody = email.Body,
            SubjectLine = email.Subject,
            ToAddress = email.ToAddress
        });
        edc.SaveChanges();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
                edc.Dispose();
            disposed = true;
        }
    }
}
</code>```

And finally the exception handling middleware

```<code>public class ExceptionHandlingMiddleware
{
    private const string ErrorEmailAddress = "errors@ourdomain.com";
    private readonly IEmailRepository _emailRepository;

    private readonly RequestDelegate _next;

    public ExceptionHandlingMiddleware(RequestDelegate next, IEmailRepository emailRepository)
    {
        _next = next;
        _emailRepository = emailRepository;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next.Invoke(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex, _emailRepository);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception,
        IEmailRepository emailRepository)
    {
        var code = HttpStatusCode.InternalServerError; // 500 if unexpected

        var email = new Email
        {
            Body = exception.Message,
            FromAddress = ErrorEmailAddress,
            Subject = "API Error",
            ToAddress = ErrorEmailAddress
        };

        emailRepository.SendEmail(email);

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int) code;
        return context.Response.WriteAsync("An error occured.");
    }
}

public static class AppErrorHandlingExtensions
{
    public static IApplicationBuilder UseEmailingExceptionHandling(this IApplicationBuilder app)
    {
        if (app == null)
            throw new ArgumentNullException(nameof(app));
        return app.UseMiddleware<ExceptionHandlingMiddleware>();
    }
}
</code>```

Update:
I found this link https://github.com/aspnet/DependencyInjection/issues/578 which led me to change my Program.cs file's BuildWebHost method from this

```<code>public static IWebHost BuildWebHost(string[] args)
{
    return WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();
}
</code>```

to this

```<code>public static IWebHost BuildWebHost(string[] args)
{
    return WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseDefaultServiceProvider(options =>
            options.ValidateScopes = false)
        .Build();
}
</code>```

I don't know what exactly is going on but it seems to work now.

答:
Your middleware and the service has to be compatible with each other in order to inject the service via the constructor of your middleware. Here, your middleware has been created as a convention-based middleware which means it acts as a singleton service and you have created your service as scoped-service. So, you cannot inject a scoped-service into the constructor of a singleton-service because it forces the scoped-service to act as a singleton one. However, here are your options.

Inject your service as a parameter to the InvokeAsync method.

Make your service a singleton one, if possible.

Transform your middleware to a factory-based one.

A Factory-based middleware is able to act as a scoped-service. So, you can inject another scoped-service via the constructor of that middleware. Below, I have shown you how to create a factory-based middleware.

This is only for demonstration. So, I have removed all the other code.

```<code>public class Startup
{
    public Startup()
    {
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<TestMiddleware>();
        services.AddScoped<TestService>();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMiddleware<TestMiddleware>();
    }
}
</code>```

The TestMiddleware:

```<code>public class TestMiddleware : IMiddleware
{
    public TestMiddleware(TestService testService)
    {
    }

    public Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        return next.Invoke(context);
    }
}
</code>```

The TestService:

```<code>public class TestService
{
}
</code>```

Body:
When I try to run my app I get the error

InvalidOperationException: Cannot resolve 'API.Domain.Data.Repositories.IEmailRepository' from root provider because it requires scoped service 'API.Domain.Data.EmailRouterContext'.

What's odd is that this EmailRepository and interface is set up exactly the same as far as I can tell as all of my other repositories yet no error is thrown for them.  The error only occurs if I try to use the app.UseEmailingExceptionHandling(); line. Here's some of my Startup.cs file.

public class Startup
{
    public IConfiguration Configuration { get; protected set; }
    private APIEnvironment _environment { get; set; }

    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        Configuration = configuration;

        _environment = APIEnvironment.Development;
        if (env.IsProduction()) _environment = APIEnvironment.Production;
        if (env.IsStaging()) _environment = APIEnvironment.Staging;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var dataConnect = new DataConnect(_environment);

        services.AddDbContext<GeneralInfoContext>(opt => opt.UseSqlServer(dataConnect.GetConnectString(Database.GeneralInfo)));
        services.AddDbContext<EmailRouterContext>(opt => opt.UseSqlServer(dataConnect.GetConnectString(Database.EmailRouter)));

        services.AddWebEncoders();
        services.AddMvc();

        services.AddScoped<IGenInfoNoteRepository, GenInfoNoteRepository>();
        services.AddScoped<IEventLogRepository, EventLogRepository>();
        services.AddScoped<IStateRepository, StateRepository>();
        services.AddScoped<IEmailRepository, EmailRepository>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        app.UseAuthentication();

        app.UseStatusCodePages();
        app.UseEmailingExceptionHandling();

        app.UseMvcWithDefaultRoute();
    }
}

Here is the EmailRepository

public interface IEmailRepository
{
    void SendEmail(Email email);
}

public class EmailRepository : IEmailRepository, IDisposable
{
    private bool disposed;
    private readonly EmailRouterContext edc;

    public EmailRepository(EmailRouterContext emailRouterContext)
    {
        edc = emailRouterContext;
    }

    public void SendEmail(Email email)
    {
        edc.EmailMessages.Add(new EmailMessages
        {
            DateAdded = DateTime.Now,
            FromAddress = email.FromAddress,
            MailFormat = email.Format,
            MessageBody = email.Body,
            SubjectLine = email.Subject,
            ToAddress = email.ToAddress
        });
        edc.SaveChanges();
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
                edc.Dispose();
            disposed = true;
        }
    }
}

And finally the exception handling middleware

public class ExceptionHandlingMiddleware
{
    private const string ErrorEmailAddress = "errors@ourdomain.com";
    private readonly IEmailRepository _emailRepository;

    private readonly RequestDelegate _next;

    public ExceptionHandlingMiddleware(RequestDelegate next, IEmailRepository emailRepository)
    {
        _next = next;
        _emailRepository = emailRepository;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next.Invoke(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex, _emailRepository);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception,
        IEmailRepository emailRepository)
    {
        var code = HttpStatusCode.InternalServerError; // 500 if unexpected

        var email = new Email
        {
            Body = exception.Message,
            FromAddress = ErrorEmailAddress,
            Subject = "API Error",
            ToAddress = ErrorEmailAddress
        };

        emailRepository.SendEmail(email);

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int) code;
        return context.Response.WriteAsync("An error occured.");
    }
}

public static class AppErrorHandlingExtensions
{
    public static IApplicationBuilder UseEmailingExceptionHandling(this IApplicationBuilder app)
    {
        if (app == null)
            throw new ArgumentNullException(nameof(app));
        return app.UseMiddleware<ExceptionHandlingMiddleware>();
    }
}

Update:
I found this link https://github.com/aspnet/DependencyInjection/issues/578 which led me to change my Program.cs file's BuildWebHost method from this

public static IWebHost BuildWebHost(string[] args)
{
    return WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .Build();
}

to this

public static IWebHost BuildWebHost(string[] args)
{
    return WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseDefaultServiceProvider(options =>
            options.ValidateScopes = false)
        .Build();
}

I don't know what exactly is going on but it seems to work now.

Body:
Your middleware and the service has to be compatible with each other in order to inject the service via the constructor of your middleware. Here, your middleware has been created as a convention-based middleware which means it acts as a singleton service and you have created your service as scoped-service. So, you cannot inject a scoped-service into the constructor of a singleton-service because it forces the scoped-service to act as a singleton one. However, here are your options.

Inject your service as a parameter to the InvokeAsync method.

Make your service a singleton one, if possible.

Transform your middleware to a factory-based one.

A Factory-based middleware is able to act as a scoped-service. So, you can inject another scoped-service via the constructor of that middleware. Below, I have shown you how to create a factory-based middleware.

This is only for demonstration. So, I have removed all the other code.

public class Startup
{
    public Startup()
    {
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<TestMiddleware>();
        services.AddScoped<TestService>();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMiddleware<TestMiddleware>();
    }
}

The TestMiddleware:

public class TestMiddleware : IMiddleware
{
    public TestMiddleware(TestService testService)
    {
    }

    public Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        return next.Invoke(context);
    }
}

The TestService:

public class TestService
{
}


问:
Pass an array of enums in C#
I need to allow multiple roles to have access to a method, in a controller in C# Web api.

I have a custom AuthorizeAttribute which takes an enum of role type, how can I make it so it accepts multiple enums ie. a variable length array of enums.

This is the code I have written for the Attribute:

```<code>private readonly RoleEnum roleInApplication;

public ScopeAuthorizeAttribute(RoleEnum roleInApplication)
{
    this.roleInApplication = roleInApplication;
}

public override void OnAuthorization(HttpActionContext actionContext)
{
    base.OnAuthorization(actionContext);
    .......
    var relatedPermisssionRole = (db call to get the rolename..etc)
    RoleEnum role;
    if (Enum.TryParse(relatedPermisssionRole, out role) && role == roleInApplication)
    {
            // Succeed if the scope array contains the required scope
            return;
     }
  }

    HandleUnauthorizedRequest(actionContext);
}
</code>```

And in the controller, I use it like this:

```<code>[ScopeAuthorize(RoleEnum.ADMIN)]
public async Task<IHttpActionResult> Create(MyModel model)
</code>```

How do I allow multiple roles? eg.

```<code>[ScopeAuthorize(RoleEnum.ADMIN, RoleEnum.USER)]
public async Task<IHttpActionResult> Create(MyModel model)
</code>```

答:
You could use params as in public ScopeAuthorizeAttribute(params RoleEnum[] roleInApplication) but in reality you are trying to solve the issue in the wrong way, consider using Flags instead:

```<code>[FlagsAttribute]
enum Role
{
  None = 0,
  Admin = 1,
  User = 2,
  SomeOtherRole = 4
}
</code>```

Then you can pass your roles as one parameter using bitwise OR:

```<code>[ScopeAuthorize(Role.Admin | Role.User)]
public async Task<IHttpActionResult> Create(MyModel model)
</code>```

But don't just copy my code snippet, it is definitely worth having a good read of the documentation for Flags  esp. Guidelines for FlagsAttribute and Enum to ensure you use this pattern correctly. There are a few caveats you must be aware of, which are not immediately obvious. It will be a 5 minutes well spent.

Also, I suggest you refrain from suffixing your enum with the word Enum and using UPPERCASE for your enum names.

Title: Pass an array of enums in C#

Body:
I need to allow multiple roles to have access to a method, in a controller in C# Web api.

I have a custom AuthorizeAttribute which takes an enum of role type, how can I make it so it accepts multiple enums ie. a variable length array of enums.

This is the code I have written for the Attribute:

private readonly RoleEnum roleInApplication;

public ScopeAuthorizeAttribute(RoleEnum roleInApplication)
{
    this.roleInApplication = roleInApplication;
}

public override void OnAuthorization(HttpActionContext actionContext)
{
    base.OnAuthorization(actionContext);
    .......
    var relatedPermisssionRole = (db call to get the rolename..etc)
    RoleEnum role;
    if (Enum.TryParse(relatedPermisssionRole, out role) && role == roleInApplication)
    {
            // Succeed if the scope array contains the required scope
            return;
     }
  }

    HandleUnauthorizedRequest(actionContext);
}

And in the controller, I use it like this:

[ScopeAuthorize(RoleEnum.ADMIN)]
public async Task<IHttpActionResult> Create(MyModel model)

How do I allow multiple roles? eg.

[ScopeAuthorize(RoleEnum.ADMIN, RoleEnum.USER)]
public async Task<IHttpActionResult> Create(MyModel model)

Body:
You could use params as in public ScopeAuthorizeAttribute(params RoleEnum[] roleInApplication) but in reality you are trying to solve the issue in the wrong way, consider using Flags instead:

[FlagsAttribute]
enum Role
{
  None = 0,
  Admin = 1,
  User = 2,
  SomeOtherRole = 4
}

Then you can pass your roles as one parameter using bitwise OR:

[ScopeAuthorize(Role.Admin | Role.User)]
public async Task<IHttpActionResult> Create(MyModel model)

But don't just copy my code snippet, it is definitely worth having a good read of the documentation for Flags  esp. Guidelines for FlagsAttribute and Enum to ensure you use this pattern correctly. There are a few caveats you must be aware of, which are not immediately obvious. It will be a 5 minutes well spent.

Also, I suggest you refrain from suffixing your enum with the word Enum and using UPPERCASE for your enum names.


问:
How to set Retrofit URL string from Resources
I've refactored some parts of my code which is written in Kotlin and tend to put url's in strings.xml, but when I want to point to the string in strings.xml file in annotation part of the Retrofit, I get the following error.

An annotation argument must be a compile-time constant

Here is my code:

```<code>interface SampleApiService {
    @GET(Resources.getSystem().getString(R.string.sample_url))
    fun getSamples(){
    }
}
</code>```

Could anyone please tell me what is wrong?

Found the answer in the following post.

答:
Problem solved,
Tnx to Retrofit 2 - Dynamic URL

I had to use another annotation mark of retrofit.

New: @Url parameter annotation allows passing a complete URL for an endpoint.

Here is the result:

```<code>interface SampleApiService {
    @GET
    fun getSamples(
        @Url url: String =
            Resources.getSystem().getString(R.string.sample_url)
    )
            : Deferred<ArrayList<Sample>>

}
</code>```

Body:
I've refactored some parts of my code which is written in Kotlin and tend to put url's in strings.xml, but when I want to point to the string in strings.xml file in annotation part of the Retrofit, I get the following error.

An annotation argument must be a compile-time constant

Here is my code:

interface SampleApiService {
    @GET(Resources.getSystem().getString(R.string.sample_url))
    fun getSamples(){
    }
}

Could anyone please tell me what is wrong?

Found the answer in the following post.

Body:
Problem solved,
Tnx to Retrofit 2 - Dynamic URL

I had to use another annotation mark of retrofit.

New: @Url parameter annotation allows passing a complete URL for an endpoint.

Here is the result:

interface SampleApiService {
    @GET
    fun getSamples(
        @Url url: String =
            Resources.getSystem().getString(R.string.sample_url)
    )
            : Deferred<ArrayList<Sample>>

}


问:
Build an executable using a pattern in Makefile
Here is a simple Makefile content:

```<code>CXXCOMP=g++
CXXFLAGS=-std=c++11 -g

%.o: %.cpp
    $(CXXCOMP) $(CXXFLAGS) -c $<

main: %.o
    $(CXXCOMP) $(CXXFLAGS) -o $@ $^
</code>```

I expect that the first rule will generate a .o file for each .cpp one, while the second rule will generate a main file from all the .o ones.

Actually, the following statement is printed to terminal when I try to make main:

```<code>target `main' doesn't match the target pattern
</code>```

Can you please explain a bit more in depth what's going on and how to solve this little issue?

答:
The %.o is not a shell wildcard, it works only in the context of pattern rules. To do what you want you have to use the wildcard function, e.g.

```<code> main: $(wildcard *.o)
           $(CXXCOMP) $(CXXFLAGS) -o $@ $^
</code>```

but as Matt correctly points out, has a set of different problems. A better way is to use a make variable for the source files, and then construct the list of object files.

```<code>SRC = $(wildcard *.cpp)
OBJ = $(SRC:.cpp=.o)

main: $(OBJ)
      ...
</code>```

Body:
Here is a simple Makefile content:

CXXCOMP=g++
CXXFLAGS=-std=c++11 -g

%.o: %.cpp
    $(CXXCOMP) $(CXXFLAGS) -c $<

main: %.o
    $(CXXCOMP) $(CXXFLAGS) -o $@ $^

I expect that the first rule will generate a .o file for each .cpp one, while the second rule will generate a main file from all the .o ones.

Actually, the following statement is printed to terminal when I try to make main:

target `main' doesn't match the target pattern

Can you please explain a bit more in depth what's going on and how to solve this little issue?

Body:
The %.o is not a shell wildcard, it works only in the context of pattern rules. To do what you want you have to use the wildcard function, e.g.

 main: $(wildcard *.o)
           $(CXXCOMP) $(CXXFLAGS) -o $@ $^

but as Matt correctly points out, has a set of different problems. A better way is to use a make variable for the source files, and then construct the list of object files.

SRC = $(wildcard *.cpp)
OBJ = $(SRC:.cpp=.o)

main: $(OBJ)
      ...


问:
How to set a persistent global variable by scripted pipeline?
I need to pass a variable from a pipeline to another one without triggering the build of the second one.
Basically, the first pipeline should set the value of this variable and terminate. When I run the second pipeline, it should be able to get this value.
So far, I used a properties' file but I'd like to know if there is a way to avoid it. Is it possible?</p>

答:
I think the EnvInject plugin is what you need. </p>

<p>As alternative solution:
You could also write to a file from the first job and source that file from your second job if it is started. The location must be persistent, do not use the workspace dir. </p>

Body:
I think the EnvInject plugin is what you need.

As alternative solution:
You could also write to a file from the first job and source that file from your second job if it is started. The location must be persistent, do not use the workspace dir.


问:
Precompilation and startup times on ASP.Net
I am developping a (relatively small) website in ASP.Net 2.0. I am also using nAnt to perform some easy tweaking on my project before delivering executables. In its current state, the website is "precompiled" using

aspnet_compiler.exe -nologo -v ${Appname} -u ${target}

I have noticed that after the IIS pool is restarted (after a idle shutdown or a recycle), the application takes up to 20 seconds before it is back online (and Application_start is reached).

I don't have the same issue when I am debugging directly within Visual Studio (it takes 2 seconds to start) so I am wondering if the aspnet_compiler is really such a good idea.

I couldn't find much on MSDN. How do you compile your websites for production?

答:
Make sure that:

You are using a Web Application project rather than a Web Site project, this will result in a precompiled binary for your code behind

You have turned off debug code generation in the web.config file - I guess if this is different to when you used aspnet_compiler the code may be recompiled

If you've tried those, you could maybe try running ngen over your assembly thus saving the JIT time?

OwnerDisplayName: lucasbfr

LastEditorDisplayName: ScottCher

OwnerDisplayName: Simon


问:
C++ how to sort vector<class *> with operator <
i have

```<code> class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())
</code>```

why it dosent sort ?

but if we had

```<code> bool operator < (c1 w)
    {
        return number < w.number;
    }
</code>```

and

```<code>vector<c1> vec = { ... }
</code>```

it would have been sorted !

答:
Add a external operator< and keep de original one:

```<code>bool operator<(c1* a, c1* b) { return *a < *b; }
</code>```

Now sort will work on the vector.

Body:
i have

 class c1{

public:
    int number;

    c1()
    {
        number=rand()%10;
    }

    bool operator < (c1 *w)
    {
        return number < w->number;
    }

};

vector<c1*> vec = { ... }
sort(vec.begin(),vec.end())

why it dosent sort ?

but if we had

 bool operator < (c1 w)
    {
        return number < w.number;
    }

and

vector<c1> vec = { ... }

it would have been sorted !

Body:
Add a external operator< and keep de original one:

bool operator<(c1* a, c1* b) { return *a < *b; }

Now sort will work on the vector.


问:
How to remove the base Lablel use javascript in html?
My website is reverse proxy google (I am in china ,cannot access google  ),
like  this url :

"https://accounts.google.com/SignUp?hl=zh_CN&continue=https://myaccount.google.com/intro"

I want to  remove the base Lablel  use javascript?,But my method doesn't work,Maybe I did something wrong, I don't know why.Thank you very much for any help.

my js method :

document.body.innerHTML = document.body.innerHTML.replace('<base href.*?>','')

Original code like this :

```<code><!doctype html>
<html lang="zh-CN" dir="ltr">
  <head>
    <base href="https://accounts.google.com/">
</code>```

I expect output :

```<code><!doctype html>
  <html lang="zh-CN" dir="ltr">
    <head>
</code>```

答:
Just take the element with querySelector and remove it.

var elem = document.querySelector('base');
elem.parentNode.removeChild(elem);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="zh-CN" dir="ltr">
  <head>
    <base href="https://accounts.google.com/"/>
  </head>
</html></code>```

Body:
My website is reverse proxy google (I am in china ,cannot access google  ),
like  this url :

"https://accounts.google.com/SignUp?hl=zh_CN&continue=https://myaccount.google.com/intro"

I want to  remove the base Lablel  use javascript?,But my method doesn't work,Maybe I did something wrong, I don't know why.Thank you very much for any help.

my js method :

document.body.innerHTML = document.body.innerHTML.replace('<base href.*?>','')

Original code like this :

<!doctype html>

    <base href="https://accounts.google.com/">

I expect output :

<!doctype html>

Body:
Just take the element with querySelector and remove it.

var elem = document.querySelector('base');
elem.parentNode.removeChild(elem);

<!doctype html>
<html lang="zh-CN" dir="ltr">
  <head>
    <base href="https://accounts.google.com/"/>
  </head>
</html>


问:
Convert the tuples in a list to a dictionary and calculate the frequency
Three friends – Mike, John, and Tom – measured their jumps lengths in centimeters. We've stored their jump results in the template code. Create a dictionary named avg_results which will store the names as keys and their average jump lengths as values.

```<code>jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]
</code>```

I only know how to calculate the sum of measure for each of them, but I don't know how to iterate and get the count of each of them.

```<code>for jump in jumps:
  name,length=jump
  dict_results[name]=dict_results.get(name,0)+length
</code>```

答:
Have you tried grouping with a collections.defaultdict(list), then taking the average from dividing sum() by len():

```<code>from collections import defaultdict

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

d = defaultdict(list)
for name, length in jumps:
    d[name].append(length)

avg = {k: sum(v) / len(v) for k, v in d.items()}

print(avg)
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}
</code>```

You can also use statistics.mean() to get the average:

```<code>from statistics import mean

avg = {k: mean(v) for k, v in d.items()}

print(avg)
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}
</code>```

Body:
Three friends – Mike, John, and Tom – measured their jumps lengths in centimeters. We've stored their jump results in the template code. Create a dictionary named avg_results which will store the names as keys and their average jump lengths as values.

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

I only know how to calculate the sum of measure for each of them, but I don't know how to iterate and get the count of each of them.

for jump in jumps:
  name,length=jump
  dict_results[name]=dict_results.get(name,0)+length

Body:
Have you tried grouping with a collections.defaultdict(list), then taking the average from dividing sum() by len():

from collections import defaultdict

jumps = [('Mike', 283), ('Mike', 317), ('Mike', 302), ('John', 305), ('John', 311), ('John', 297), ('John', 308), ('Tom', 341), ('Tom', 256)]

d = defaultdict(list)
for name, length in jumps:
    d[name].append(length)

avg = {k: sum(v) / len(v) for k, v in d.items()}

print(avg)
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}

You can also use statistics.mean() to get the average:

from statistics import mean

avg = {k: mean(v) for k, v in d.items()}

print(avg)
# {'Mike': 300.6666666666667, 'John': 305.25, 'Tom': 298.5}


问:
Action leaves the mic open

Your Action either leaves the mic open for a user command without a prompt such as a greeting, or an implicit or explicit question.

how can you solve this problem?

答:
Typically, this response from the review team is a design problem, not a coding problem.

It means that you have said something, but not prompted the user to reply to you. So the user does not know what to do next.

For example, if we had this conversation:

```<code>Action: What is your favorite color?
User:   Blue
Action: Great, I'll remember that it is blue.
</code>```

and then nothing happening, the review team would flag it for keeping the microphone open without making it clear what the user should do next.

We can change this to something like:

```<code>Action: What is your favorite color?
User:   Blue
Action: Great, I'll remember that it is blue. What would you like to do next?
</code>```

and it will pass review.

If you actually want to end your conversation instead of asking the user something else, make sure you close the conversation. If your conversation isn't closing when it should be, then update your question to include the code that doesn't seem to be working.

Title: Action leaves the mic open

Body:
Typically, this response from the review team is a design problem, not a coding problem.

It means that you have said something, but not prompted the user to reply to you. So the user does not know what to do next.

For example, if we had this conversation:

Action: What is your favorite color?
User:   Blue
Action: Great, I'll remember that it is blue.

and then nothing happening, the review team would flag it for keeping the microphone open without making it clear what the user should do next.

We can change this to something like:

Action: What is your favorite color?
User:   Blue
Action: Great, I'll remember that it is blue. What would you like to do next?

and it will pass review.

If you actually want to end your conversation instead of asking the user something else, make sure you close the conversation. If your conversation isn't closing when it should be, then update your question to include the code that doesn't seem to be working.


问:
How to solve a starting position problem?
I wrote this code in Unity3D that should rotate an object in a circle, that's the case except that the starting position is not taken into account.
I do not understand why the function written in start is not taken into account for the position</p>

```<code>public class RotationCircuit : MonoBehaviour
{
    float timeCounter = 0;

    float speed;
    float width;
    float height;

    private float startPosY;
    private float startPosX;
    private float startPosZ;

    void Start()
    {
        speed = 1;
        width = 4; //largueur
        //height = 1; //hauteur

        startPosX = transform.position.x;
        startPosY = transform.position.y;
        startPosZ = transform.position.z;

        float y = GetComponent<Transform>().position.y;
        float x = GetComponent<Transform>().position.x;
        float z2 = GetComponent<Transform>().position.z;

        transform.position = new Vector3(x, y, z2);
    }

    void Update()
    {
        timeCounter += Time.deltaTime * speed;

        float x2 = Mathf.Cos(timeCounter) * width;
        //float y2 = Mathf.Sin(timeCounter) * height; //utile pour faire des haut et bas
        float y2 = GetComponent<Transform>().position.y;
        float z2 = GetComponent<Transform>().position.z;

        transform.position = new Vector3(x2, y2, z2);
    }
}
</code>```

答:
in general you should use transform.position instead of GetComponent<Transform>().position

Then your code block

```<code>float y = transform.position.y;
float x = transform.position.x;
float z2 = transform.position.z;

transform.position = new Vector3(x, y, z2);
</code>```

does change absolutely nothing ... you get the current position, store it in local variables and write back exactly the same position ...

Btw they also have the same values you already stored in

```<code>startPosX = transform.position.x;
startPosY = transform.position.y;
startPosZ = transform.position.z;
</code>```

later you never use those values at any point.

The same thing in Update

```<code>float x2 = Mathf.Cos(timeCounter) * width;

float y2 = transform.position.y;
float z2 = transform.position.z;

transform.position = new Vector3(x2, y2, z2);
</code>```

only changes the x component of the position which is calculated by

```<code>Mathf.Cos(timeCounter) * width;
</code>```

which doesn't take the initial transform.position.x or startPosX into account at any point.

I don't exactly know how you want to take the start position into account but it looks like it would be something like this:

```<code>// Little hint: By making those fields serialized
// you can adjust those values directly in the Inspector
// especially while running the Game without having to recompile everytime
[SerializedField] private float speed = 1;
[SerializedField] private float width = 4;
[SerializedField] private float height = 1;

private float timeCounter = 0;
private Vector3 startPosition;

private void Start()
{
    // you can simply store the Vector3 position
    // no need to store each component individually
    startPosition = transform.position;
}

private void Update()
{
    timeCounter += Time.deltaTime * speed;

    var x = Mathf.Cos(timeCounter) * width;
    var y = Mathf.Sin(timeCounter) * height;

    //           from the startPosition    move x right          and y up
    transform.position = startPosition + Vector3.right * x + Vector3.up * y;
}
</code>```

That the object in the beginning jumps once namely width to the right is obviously related to the Mathf.Cos which is 1 for the start time 0.

Body:
I wrote this code in Unity3D that should rotate an object in a circle, that's the case except that the starting position is not taken into account.
I do not understand why the function written in start is not taken into account for the position

public class RotationCircuit : MonoBehaviour
{
    float timeCounter = 0;

    float speed;
    float width;
    float height;

    private float startPosY;
    private float startPosX;
    private float startPosZ;

    void Start()
    {
        speed = 1;
        width = 4; //largueur
        //height = 1; //hauteur

        startPosX = transform.position.x;
        startPosY = transform.position.y;
        startPosZ = transform.position.z;

        float y = GetComponent<Transform>().position.y;
        float x = GetComponent<Transform>().position.x;
        float z2 = GetComponent<Transform>().position.z;

        transform.position = new Vector3(x, y, z2);
    }

    void Update()
    {
        timeCounter += Time.deltaTime * speed;

        float x2 = Mathf.Cos(timeCounter) * width;
        //float y2 = Mathf.Sin(timeCounter) * height; //utile pour faire des haut et bas
        float y2 = GetComponent<Transform>().position.y;
        float z2 = GetComponent<Transform>().position.z;

        transform.position = new Vector3(x2, y2, z2);
    }
}

Body:
in general you should use transform.position instead of GetComponent<Transform>().position

Then your code block

float y = transform.position.y;
float x = transform.position.x;
float z2 = transform.position.z;

transform.position = new Vector3(x, y, z2);

does change absolutely nothing ... you get the current position, store it in local variables and write back exactly the same position ...

Btw they also have the same values you already stored in

startPosX = transform.position.x;
startPosY = transform.position.y;
startPosZ = transform.position.z;

later you never use those values at any point.

The same thing in Update

float x2 = Mathf.Cos(timeCounter) * width;

float y2 = transform.position.y;
float z2 = transform.position.z;

transform.position = new Vector3(x2, y2, z2);

only changes the x component of the position which is calculated by

Mathf.Cos(timeCounter) * width;

which doesn't take the initial transform.position.x or startPosX into account at any point.

I don't exactly know how you want to take the start position into account but it looks like it would be something like this:

// Little hint: By making those fields serialized
// you can adjust those values directly in the Inspector
// especially while running the Game without having to recompile everytime
[SerializedField] private float speed = 1;
[SerializedField] private float width = 4;
[SerializedField] private float height = 1;

private float timeCounter = 0;
private Vector3 startPosition;

private void Start()
{
    // you can simply store the Vector3 position
    // no need to store each component individually
    startPosition = transform.position;
}

private void Update()
{
    timeCounter += Time.deltaTime * speed;

    var x = Mathf.Cos(timeCounter) * width;
    var y = Mathf.Sin(timeCounter) * height;

    //           from the startPosition    move x right          and y up
    transform.position = startPosition + Vector3.right * x + Vector3.up * y;
}

That the object in the beginning jumps once namely width to the right is obviously related to the Mathf.Cos which is 1 for the start time 0.


问:
TensorFlow Linear Regression - returning NaN for weights,bias and Inf for loss
I'm trying to do the below linear regression in TensorFlow, but my output is all Inf and NaNs.

My input dataset has to be Y=0.5*X + 2 + Noise; where X is a normal distribution of size(1000) and Noise is Gaussian with (mu=0.0 and sigma=50)

Output:

loss= 82662.945 W= 15974.369 b 24.379812

loss= 81293050000000.0 W= -508895600.0 b -775064.06

loss= 8.250697e+22 W= 16212403000000.0 b 24692003000.0

loss= 8.373905e+31 W= -5.1649487e+17 b -786638100000000.0

loss= inf W= 1.6454498e+22 b 2.5060722e+19

loss= inf W= -5.2420755e+26 b -7.9838474e+23

loss= inf W= 1.6700204e+31 b 2.543495e+28

loss= inf W= -5.320352e+35 b -8.1030665e+32

loss= inf W= inf b inf

loss= inf W= nan b nan

loss= nan W= nan b nan

loss= nan W= nan b nan

loss= nan W= nan b nan

```<code>import tensorflow as tf
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

noise=np.random.normal(0.0,50,1000)#.astype(np.float32)
x_data=np.random.uniform(0,1000,1000)#.astype(np.float32)
y_data=0.5*x_data+2+noise#.astype(np.float32)

plt.scatter(x_data,y_data,s=0.1)
plt.show()

X=tf.placeholder(shape=(1000,),dtype=tf.float32)
Y=tf.placeholder(shape=(1000,),dtype=tf.float32)

#Learning W and b over the epochs
W=tf.get_variable(name='Weight',dtype=tf.float32,shape(),initializer=tf.zeros_initializer())
b=tf.get_variable(name='Bias',dtype=tf.float32,shape=(),initializer=tf.zeros_initializer())

Y_pred= tf.add(tf.multiply(X, W),b)
loss = tf.reduce_mean(tf.square(Y_pred - Y))

optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.05).minimize(loss)

epochs=100
with tf.Session() as sess:
init=tf.global_variables_initializer()
sess.run(init)
for e in range(epochs):
    _,c=sess.run([optimizer,loss],feed_dict={X: x_data,Y: y_data})
    print('loss=',c,'W=',sess.run(W),'b',sess.run(b))

#plt.scatter(x_data, y_data, 'ro', label='Original data')
plt.plot(x_data, sess.run(W) * x_data + sess.run(b), label='Fitted line')
plt.legend()
plt.show()
</code>```

答:
You have neatly recreated a straightforward example of the exploding gradient problem.

You can read up on potential solutions but the simplest for a toy example might be to reduce your learning rate.

Intuitively, gradient descent is like trying to find your way to the valley floor by pointing in the downhill direction and taking a step, then repeat. At each stage you re-evaluate the direction based on what is downhill now. If the valley is smooth with no local low-spots and your step size is small enough you will eventually find the bottom.

The learning rate is analogous with the size of the step.

So, with too high a learning rate, you can now imagine you are taking such a large step that you step right across the whole valley to a point higher up the hill on the opposite side. Then you turn in order to point downhill again (so roughly a 180 turn) and face the centre of the valley but step right across to even higher up the other side. And so on getting higher and higher up the opposite sides of the valley

So, dramatically reducing your learning rate to something like this seems to allow it to converge:

optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.000001).minimize(loss)
```

Body:
I'm trying to do the below linear regression in TensorFlow, but my output is all Inf and NaNs.

My input dataset has to be Y=0.5*X + 2 + Noise; where X is a normal distribution of size(1000) and Noise is Gaussian with (mu=0.0 and sigma=50)

Output:

loss= 82662.945 W= 15974.369 b 24.379812

loss= 81293050000000.0 W= -508895600.0 b -775064.06

loss= 8.250697e+22 W= 16212403000000.0 b 24692003000.0

loss= 8.373905e+31 W= -5.1649487e+17 b -786638100000000.0

loss= inf W= 1.6454498e+22 b 2.5060722e+19

loss= inf W= -5.2420755e+26 b -7.9838474e+23

loss= inf W= 1.6700204e+31 b 2.543495e+28

loss= inf W= -5.320352e+35 b -8.1030665e+32

loss= inf W= inf b inf

loss= inf W= nan b nan

loss= nan W= nan b nan

loss= nan W= nan b nan

loss= nan W= nan b nan

import tensorflow as tf
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

noise=np.random.normal(0.0,50,1000)#.astype(np.float32)
x_data=np.random.uniform(0,1000,1000)#.astype(np.float32)
y_data=0.5*x_data+2+noise#.astype(np.float32)

plt.scatter(x_data,y_data,s=0.1)
plt.show()

X=tf.placeholder(shape=(1000,),dtype=tf.float32)
Y=tf.placeholder(shape=(1000,),dtype=tf.float32)

#Learning W and b over the epochs
W=tf.get_variable(name='Weight',dtype=tf.float32,shape(),initializer=tf.zeros_initializer())
b=tf.get_variable(name='Bias',dtype=tf.float32,shape=(),initializer=tf.zeros_initializer())

Y_pred= tf.add(tf.multiply(X, W),b)
loss = tf.reduce_mean(tf.square(Y_pred - Y))

optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.05).minimize(loss)

epochs=100
with tf.Session() as sess:
init=tf.global_variables_initializer()
sess.run(init)
for e in range(epochs):
    _,c=sess.run([optimizer,loss],feed_dict={X: x_data,Y: y_data})
    print('loss=',c,'W=',sess.run(W),'b',sess.run(b))

#plt.scatter(x_data, y_data, 'ro', label='Original data')
plt.plot(x_data, sess.run(W) * x_data + sess.run(b), label='Fitted line')
plt.legend()
plt.show()


问:
Key existence checking utility in Map
I'm using the following code for checking if a key exists in a Map instance:

```<code>if (!map_instance.containsKey(key))
    throw new RuntimeException("Specified key doesn't exist in map");
else
   return map_instance.get(key);
</code>```

My question is:

Is there a utility or Map implementation to simplify the above code, such as:

```<code>custom_map.get(key,"Specified key doesn't exist in map");
</code>```

My goal is: if key does not exist in map, the map implementation throws an exception with the passed string.

I don't know whether or not my desire is reasonable?

(Sorry if I am using the wrong terminology or grammar, I am still learning the English language.)

答:
I use Optional Java util class, e.g. </p>

```<code>Optional.ofNullable(elementMap.get("not valid key"))
            .orElseThrow(() -> new ElementNotFoundException("Element not found"));
</code>```

Title: Key existence checking utility in Map

Body:
I'm using the following code for checking if a key exists in a Map instance:

if (!map_instance.containsKey(key))
    throw new RuntimeException("Specified key doesn't exist in map");
else
   return map_instance.get(key);

My question is:

Is there a utility or Map implementation to simplify the above code, such as:

custom_map.get(key,"Specified key doesn't exist in map");

My goal is: if key does not exist in map, the map implementation throws an exception with the passed string.

I don't know whether or not my desire is reasonable?

(Sorry if I am using the wrong terminology or grammar, I am still learning the English language.)

Body:
I use Optional Java util class, e.g.

Optional.ofNullable(elementMap.get("not valid key"))
            .orElseThrow(() -> new ElementNotFoundException("Element not found"));


问:
How to only show update dialog if build is mandatory
There's a way to only show the update dialog confirmation if the build is a mandatory one?</p>

答:
Witalo Benicio Hi. Yes, it can be done in several ways.
But first of all, you have to fetch the build metadata to know if it's mandatory or not. It can be done using getUpdateMetadata(UpdateState.LATEST) - it returns LocalPackage instance with isMandatory flag.

After that you can use:

sync() method with { updateDialog: true } setting. It's the most flexible solution but requires more code to be implemented. And it requires one very important limitation (form CodePush docs):

To further remain in compliance with Apple's guidelines we suggest that App Store-distributed apps don't enable the updateDialog option when calling sync

You can implement your own update dialog and handle user actions by yourself. Maybe, this approach is even better, because in this case you don't violate any Apple's policy and can provide an even more flexible solution.

In any case, you have to fetch metadata first and then make a decision.
Hope it helps.


问:
Can I get ScriptNames for a file through the FileMaker data API?
I need to get a list of scripts for a database file through the FileMaker 17 data API.

I've tried looking in the documentation.

I'm looking for something similar to this, available in the PHP API.

ScriptNames(fileName)

I want to get a list of all scripts on a file.

答:
Unfortunately, not in FileMaker 17. In FileMaker 18 there is an endpoint:</p>

```<code>/fmi/data/version/databases/database-name/scripts
</code>```

Body:
Unfortunately, not in FileMaker 17. In FileMaker 18 there is an endpoint:

/fmi/data/version/databases/database-name/scripts


问:
App script check if a column contains a certain word write date to specific column
im getting the current date-time in a column. But I need the column only to change if COLUMNTOCHECK(3) cells have text "assign".

The moment a cell in COLUMN 3 changes all the cells in column 11 change to the current time. only the cell in column 11 that is in the same row as last changed " assign " should be changed.

So what I need; if 1 cell in column 3 get the value "assign" the current date-time should appear in the same row and column 11. the moment the same call changes back to something else the date-time shouldn't be touched!

I need to get the current time when an error appeared to be set in a specific cell. The moment the error appeared is the moment a cell in column 3 get the value "assign"

```<code>var COLUMNTOCHECK = 3;
var DATETIMELOCATION = [0,11];
var SHEETNAME = 'Blad1'

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
if( sheet.getSheetName() == SHEETNAME ) {
  var selectedCell = ss.getActiveCell();
if( selectedCell.getColumn() == COLUMNTOCHECK && ) {
  var dateTimeCell =
   selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[1]);
  dateTimeCell.setValue(new Date());
  }
 }
}

// i tried other code but this one gives no result back;

function test(test1){
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getActiveSheet()

  var data = sheet.getDataRange().getValue();
  var data_length = data.length;
for(var i=0; i<data_length; i++) {
   if(data[i][0] == "assign") {
  ss.getRange(i+1,11).setValue((new Date()));

  }
 }

}
</code>```

I need and a date-time result in a specific cell, like 29-5-2019 11:33:26:

答:
This should do exactly what you're expecting.

Note: you won't be able to run this manually, it'll run automatically when the sheet is edited.

```<code>function onEdit(e) {
  var sh = e.source.getActiveSheet();
  var col = e.range.getColumn();
  var val = e.range.getValue();

  //check if sheet is 'Blad1', column edited is 'C' & value is 'assign'
  if (sh.getSheetName() === 'Blad1' && col === 3 && val === 'assign') {
    var row = e.range.getRow();
    var tz = e.source.getSpreadsheetTimeZone();
    var date = Utilities.formatDate(new Date(), tz, 'dd-MM-yyyy hh:mm:ss a');

    //set date in column 11 for same row
    sh.getRange(row, 11).setValue(date);
  }
}
</code>```

The time for this script is based on your spreadsheet's current time zone settings, as you can see in var tz. These can be changed really easily depending on your needs, here are some examples if you need to change it to suit your requirement.

```<code>//use spreadsheet timezone setting
var tz = e.source.getSpreadsheetTimeZone();

//use script timezone setting
var tz = Session.getScriptTimeZone();

//enter your own time zone
var tz = 'GMT+0';
</code>```

Body:
im getting the current date-time in a column. But I need the column only to change if COLUMNTOCHECK(3) cells have text "assign".

The moment a cell in COLUMN 3 changes all the cells in column 11 change to the current time. only the cell in column 11 that is in the same row as last changed " assign " should be changed.

So what I need; if 1 cell in column 3 get the value "assign" the current date-time should appear in the same row and column 11. the moment the same call changes back to something else the date-time shouldn't be touched!

I need to get the current time when an error appeared to be set in a specific cell. The moment the error appeared is the moment a cell in column 3 get the value "assign"

var COLUMNTOCHECK = 3;
var DATETIMELOCATION = [0,11];
var SHEETNAME = 'Blad1'

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
if( sheet.getSheetName() == SHEETNAME ) {
  var selectedCell = ss.getActiveCell();
if( selectedCell.getColumn() == COLUMNTOCHECK && ) {
  var dateTimeCell =
   selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[1]);
  dateTimeCell.setValue(new Date());
  }
 }
}

// i tried other code but this one gives no result back;

function test(test1){
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getActiveSheet()

  var data = sheet.getDataRange().getValue();
  var data_length = data.length;
for(var i=0; i<data_length; i++) {
   if(data[i][0] == "assign") {
  ss.getRange(i+1,11).setValue((new Date()));

  }
 }

}

I need and a date-time result in a specific cell, like 29-5-2019 11:33:26:

Body:
This should do exactly what you're expecting.

Note: you won't be able to run this manually, it'll run automatically when the sheet is edited.

function onEdit(e) {
  var sh = e.source.getActiveSheet();
  var col = e.range.getColumn();
  var val = e.range.getValue();

  //check if sheet is 'Blad1', column edited is 'C' & value is 'assign'
  if (sh.getSheetName() === 'Blad1' && col === 3 && val === 'assign') {
    var row = e.range.getRow();
    var tz = e.source.getSpreadsheetTimeZone();
    var date = Utilities.formatDate(new Date(), tz, 'dd-MM-yyyy hh:mm:ss a');

    //set date in column 11 for same row
    sh.getRange(row, 11).setValue(date);
  }
}

The time for this script is based on your spreadsheet's current time zone settings, as you can see in var tz. These can be changed really easily depending on your needs, here are some examples if you need to change it to suit your requirement.

//use spreadsheet timezone setting
var tz = e.source.getSpreadsheetTimeZone();

//use script timezone setting
var tz = Session.getScriptTimeZone();

//enter your own time zone
var tz = 'GMT+0';