问:
Elasticsearch 5.x Repository Java Spring Boot
I want to use the elasticsearchrepository with Java Spring Boot:

https://github.com/spring-projects/spring-data-elasticsearch

It is not a RELEASE version, but should work for elasticsearch 5.4.0. I'm using ELK stack 5.x.

I have the following pom.xml dependencies:

```<code><repositories>
<repository>
    <id>elasticsearch-releases</id>
    <url>https://artifacts.elastic.co/maven</url>
    <releases>
        <enabled>true</enabled>
    </releases>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
</repository>
</code>```

```<code><dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.4.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.4.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>x-pack-transport</artifactId>
    <version>5.4.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-elasticsearch</artifactId>
    <version>3.0.0.BUILD-SNAPSHOT</version>
</dependency>
</code>```

The following post repository:

```<code>@Repository
public interface IElasticPostRepository extends ElasticsearchRepository<Post, String> {
}
</code>```

Receiving the following error:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'postComponent' defined in file [C:\... PostComponent.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IElasticPostRepository': Cannot resolve reference to bean 'elasticsearchTemplate' while setting bean property 'elasticsearchOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticsearchTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.class]: Unsatisfied dependency expressed through method 'elasticsearchTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elasticsearchClient' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'elasticsearchClient' threw exception; nested exception is java.lang.NoSuchMethodError: org.elasticsearch.common.settings.Settings.settingsBuilder()Lorg/elasticsearch/common/settings/Settings$Builder;
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
</code>```

Update Spring Boot 2.0.0 - SNAPSHOT

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'postComponent' defined in file [C:...\PostComponent.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IElasticPostRepository': Cannot resolve reference to bean 'elasticsearchTemplate' while setting bean property 'elasticsearchOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticsearchTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.class]: Unsatisfied dependency expressed through method 'elasticsearchTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elasticsearchClient' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.transport.TransportClient]: Factory method 'elasticsearchClient' threw exception; nested exception is java.lang.AbstractMethodError: org.elasticsearch.transport.TcpTransport.connectToChannels(Lorg/elasticsearch/cluster/node/DiscoveryNode;Lorg/elasticsearch/transport/ConnectionProfile;)Lorg/elasticsearch/transport/TcpTransport$NodeChannels;
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:726) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:191) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1281) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1137) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:499) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122) ~[spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1245) [spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1233) [spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
</code>```

I cannot find why this error shows up. Who has experience with this?

答:
As I can see in the logs you are trying to use Spring Boot 1.X with the 3.X spring-data-elasticsearch (SDE).

I think that it won't work that way. SDE 3.X has dependency to spring-data-commons 2.X which as I know will be released with the Spring 5.X.

So in this case you have to use Spring Boot 2.X (2.0.0 M2 or last snapshot) which has dependency to Spring 5.X and uses the SDE 3.X (but to be honest I am not 100% sure is it working right now with latest snapshot of Spring Boot because SDE 3.X is still under development- I've tried SDE 3.X but with pure Spring own auto-configuration - not with boot).

You have to be also aware that Elasticsearch 5.X doesn't support embedded node out-of-the-box and within autoconfiguration for Spring Boot there is no embedded node now - only transport client.

Body:
I want to use the elasticsearchrepository with Java Spring Boot:

https://github.com/spring-projects/spring-data-elasticsearch

It is not a RELEASE version, but should work for elasticsearch 5.4.0. I'm using ELK stack 5.x.

I have the following pom.xml dependencies:

<repositories>
<repository>
    <id>elasticsearch-releases</id>
    <url>https://artifacts.elastic.co/maven</url>
    <releases>
        <enabled>true</enabled>
    </releases>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
</repository>

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.4.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.4.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>x-pack-transport</artifactId>
    <version>5.4.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-elasticsearch</artifactId>
    <version>3.0.0.BUILD-SNAPSHOT</version>
</dependency>

The following post repository:

@Repository
public interface IElasticPostRepository extends ElasticsearchRepository<Post, String> {
}

Receiving the following error:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'postComponent' defined in file [C:\... PostComponent.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IElasticPostRepository': Cannot resolve reference to bean 'elasticsearchTemplate' while setting bean property 'elasticsearchOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticsearchTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.class]: Unsatisfied dependency expressed through method 'elasticsearchTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elasticsearchClient' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.Client]: Factory method 'elasticsearchClient' threw exception; nested exception is java.lang.NoSuchMethodError: org.elasticsearch.common.settings.Settings.settingsBuilder()Lorg/elasticsearch/common/settings/Settings$Builder;
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1193) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1095) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) ~[spring-context-4.3.9.RELEASE.jar:4.3.9.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.4.RELEASE.jar:1.5.4.RELEASE]

Update Spring Boot 2.0.0 - SNAPSHOT

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'postComponent' defined in file [C:...\PostComponent.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IElasticPostRepository': Cannot resolve reference to bean 'elasticsearchTemplate' while setting bean property 'elasticsearchOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticsearchTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchDataAutoConfiguration.class]: Unsatisfied dependency expressed through method 'elasticsearchTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'elasticsearchClient' defined in class path resource [org/springframework/boot/autoconfigure/data/elasticsearch/ElasticsearchAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.elasticsearch.client.transport.TransportClient]: Factory method 'elasticsearchClient' threw exception; nested exception is java.lang.AbstractMethodError: org.elasticsearch.transport.TcpTransport.connectToChannels(Lorg/elasticsearch/cluster/node/DiscoveryNode;Lorg/elasticsearch/transport/ConnectionProfile;)Lorg/elasticsearch/transport/TcpTransport$NodeChannels;
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:726) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:191) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1281) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1137) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:499) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) ~[spring-beans-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.0.BUILD-20170707.185126-370.jar:5.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122) ~[spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386) [spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1245) [spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1233) [spring-boot-2.0.0.BUILD-20170708.142037-770.jar:2.0.0.BUILD-SNAPSHOT]

I cannot find why this error shows up. Who has experience with this?


来源: stackexchange

问:
is Flying Saucer project closed?
Someone know what happened with Flying Saucer project?

http://code.google.com/p/flying-saucer/ site down and I can't get access to manuals :(

答: My understanding is that the project is essentially dead. I believe that the last release was in April of 2009 some time.</p>

ContentLicense: CC BY-SA 4.0

Title: is Flying Saucer project closed?

ContentLicense: CC BY-SA 2.5


问:
Parent
 not wrapping child element with float attribute
Please look at this example and explain to me why the green
 does not wrap itself around the orange
.

```<code><div id='green'>
  <div id="orange"></div>
</div>

#green{
    border: 20px solid #3D3;
}

#orange{
    width :100px;
    height: 100px;
    border: 10px solid orange;
    float: left;
}
</code>```

答: you could just add display:inline-block to the orange box.</p>

ContentLicense: CC BY-SA 3.0

Title: Parent <div> not wrapping child element with float attribute

Body:
Please look at this example and explain to me why the green
 does not wrap itself around the orange
.

#green{
    border: 20px solid #3D3;
}

#orange{
    width :100px;
    height: 100px;
    border: 10px solid orange;
    float: left;
}


问:
Get Values from child nodes from XML | Python
I have the following XML.

I am using ElementTree library to scrape the values.

```<code><?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <url>
  <loc> Test1</loc>
  </url>
 <url>
  <loc>Test 2</loc>
 </url>
 <url>
  <loc>Test 3</loc>
 </url>
</urlset>
</code>```

I need to get the values out of 'loc tag'.

Desired Output:

```<code>Test 1
Test 2
Test 3
</code>```

Tried Code:

```<code>tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('url'):
 rank = atype.find('loc').text
print (rank)
</code>```

Any suggestions on where am I wrong ?

答:
```<code>from lxml import etree

tree = etree.parse('sitemap.xml')
    for element in tree.iter('*'):
        if element.text.find('Test') != -1:
            print element.text
</code>```

Probably isn't the most beautiful solution, but it works :)

Body:
I have the following XML.

I am using ElementTree library to scrape the values.

<?xml version="1.0" encoding="UTF-8"?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <url>
  <loc> Test1</loc>
  </url>
 <url>
  <loc>Test 2</loc>
 </url>
 <url>
  <loc>Test 3</loc>
 </url>
</urlset>

I need to get the values out of 'loc tag'.

Desired Output:

Test 1
Test 2
Test 3

Tried Code:

tree = ET.parse('sitemap.xml')
root = tree.getroot()
for atype in root.findall('url'):
 rank = atype.find('loc').text
print (rank)

Any suggestions on where am I wrong ?

Body:
from lxml import etree

tree = etree.parse('sitemap.xml')
    for element in tree.iter('*'):
        if element.text.find('Test') != -1:
            print element.text

Probably isn't the most beautiful solution, but it works :)


问:
How can I blur the background of my layout?
I have tried most of the solutions from stack overflow, but I don't seem to get a correct implementation of the blurred effect.

Help me out please

答:
You can use this

Blur.java

```<code>import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build.VERSION;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;

public class Blur {

    @SuppressLint("NewApi")
    public static Bitmap fastblur(Context context, Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {

        if (VERSION.SDK_INT > 16) {
            Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

            final RenderScript rs = RenderScript.create(context);
            final Allocation input = Allocation.createFromBitmap(
                    rs,
                    sentBitmap,
                    Allocation.MipmapControl.MIPMAP_NONE,
                    Allocation.USAGE_SCRIPT);

            final Allocation output = Allocation.createTyped(rs, input.getType());
            final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
            script.setRadius(radius /* e.g. 3.f */);
            script.setInput(input);
            script.forEach(output);
            output.copyTo(bitmap);
            return bitmap;
        }

        // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>

        Bitmap bitmap;

        if (canReuseInBitmap) {
            bitmap = sentBitmap;
        } else {
            bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
        }

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        bitmap.setPixels(pix, 0, w, 0, 0, w, h);
        return (bitmap);
    }

}

*BlurImage.java*

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;

public class BlurImage {
    private Context context;

    private  Bitmap getScreenshot(View v) {
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Config.ARGB_4444);
        v.draw(new Canvas(b));
        return b;
    }

    public void applyBlur(Context context, View mainView, View blurView) {
        this.context = context;
        blur(getScreenshot(blurView), mainView);
    }

    @SuppressLint({"NewApi"})
    private void blur(Bitmap bitmap, View view) {
        Bitmap overlay = Bitmap.createBitmap((int) (((float) view.getMeasuredWidth()) / 3.0f), (int) (((float) view.getMeasuredHeight()) / 3.0f), Config.ARGB_4444);
        Canvas canvas = new Canvas(overlay);
        canvas.translate(((float) (-view.getLeft())) / 3.0f, ((float) (-view.getTop())) / 3.0f);
        canvas.scale(1.0f/ 3.0f, 1.0f / 3.0f);
        Paint paint = new Paint();
        paint.setFlags(2);
        canvas.drawBitmap(bitmap, 0.0f, 0.0f, paint);
        view.setBackground(new BitmapDrawable(this.context.getResources(), Blur.fastblur(context,overlay, (int) 20.0f, true)));
    }
}
</code>```

Body:
You can use this

Blur.java

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build.VERSION;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;

public class Blur {

    @SuppressLint("NewApi")
    public static Bitmap fastblur(Context context, Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {

        if (VERSION.SDK_INT > 16) {
            Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

            final RenderScript rs = RenderScript.create(context);
            final Allocation input = Allocation.createFromBitmap(
                    rs,
                    sentBitmap,
                    Allocation.MipmapControl.MIPMAP_NONE,
                    Allocation.USAGE_SCRIPT);

            final Allocation output = Allocation.createTyped(rs, input.getType());
            final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
            script.setRadius(radius /* e.g. 3.f */);
            script.setInput(input);
            script.forEach(output);
            output.copyTo(bitmap);
            return bitmap;
        }

        // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com>

        Bitmap bitmap;

        if (canReuseInBitmap) {
            bitmap = sentBitmap;
        } else {
            bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
        }

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        bitmap.setPixels(pix, 0, w, 0, 0, w, h);
        return (bitmap);
    }

}

*BlurImage.java*

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;

public class BlurImage {
    private Context context;

    private  Bitmap getScreenshot(View v) {
        Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Config.ARGB_4444);
        v.draw(new Canvas(b));
        return b;
    }

    public void applyBlur(Context context, View mainView, View blurView) {
        this.context = context;
        blur(getScreenshot(blurView), mainView);
    }

    @SuppressLint({"NewApi"})
    private void blur(Bitmap bitmap, View view) {
        Bitmap overlay = Bitmap.createBitmap((int) (((float) view.getMeasuredWidth()) / 3.0f), (int) (((float) view.getMeasuredHeight()) / 3.0f), Config.ARGB_4444);
        Canvas canvas = new Canvas(overlay);
        canvas.translate(((float) (-view.getLeft())) / 3.0f, ((float) (-view.getTop())) / 3.0f);
        canvas.scale(1.0f/ 3.0f, 1.0f / 3.0f);
        Paint paint = new Paint();
        paint.setFlags(2);
        canvas.drawBitmap(bitmap, 0.0f, 0.0f, paint);
        view.setBackground(new BitmapDrawable(this.context.getResources(), Blur.fastblur(context,overlay, (int) 20.0f, true)));
    }
}


问:
Android Internet connectivity check better method
According to the Android developer site, Determining and Monitoring the Connectivity Status, we can check there is an active Internet connection. But this is not working if even only Wi-Fi is connected and not Internet available (it notifies there is an Internet connection).

Now I ping a website and check whether Internet connections are available or not. And this method needs some more processing time. Is there a better method for checking Internet connectivity than this to avoid the time delay in ping the address?

答:
On checking this issue it found that We cannot determine whether an active internet connection is there, by using the method specified in the  developer site:
https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

This will only check whther ther active connection of wifi.

So I found 2 methods which will check whether there is an active internet connection

1.Ping a website using below method

```<code>URL url = new URL(myUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        // 30 second time out.
        httpURLConnection.setConnectTimeout(30000);
        httpURLConnection.connect();
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            isAvailable = true;
        }
</code>```

2.Check the availability of Google DNS using socket

```<code>  try {
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

        sock.connect(sockaddr, 1000); // this will block no more than timeoutMs
        sock.close();

        return true;
}
</code>```

The second method is little faster than 2nd method (Which suits for my requirement)

Thanks all for the answers and support.

Body:
On checking this issue it found that We cannot determine whether an active internet connection is there, by using the method specified in the  developer site:
https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

This will only check whther ther active connection of wifi.

So I found 2 methods which will check whether there is an active internet connection

1.Ping a website using below method

URL url = new URL(myUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        // 30 second time out.
        httpURLConnection.setConnectTimeout(30000);
        httpURLConnection.connect();
        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            isAvailable = true;
        }

2.Check the availability of Google DNS using socket

  try {
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

        sock.connect(sockaddr, 1000); // this will block no more than timeoutMs
        sock.close();

        return true;
}

The second method is little faster than 2nd method (Which suits for my requirement)

Thanks all for the answers and support.


问:
Inherit same Method for 2 Different Class
How to simplify this, 2 method in class are identical.

First class.

```<code>Public Class Gui
Inherits System.Web.UI.Page

Public Sub CreateStyleLink(ByVal StyleArray() As String)
    Dim StrStyleLink As String

    For Each StyleName In StyleArray
        StrStyleLink = [Global].ArrStyles(StyleName)

        Dim ObjScript As New HtmlGenericControl("link")
        ObjScript.Attributes.Add("rel", "Stylesheet")
        ObjScript.Attributes.Add("type", "text/css")
        ObjScript.Attributes.Add("href", StrStyleLink)
        Me.Page.Header.Controls.Add(ObjScript)
    Next
End Sub

Public Sub CreateScriptLink(ByVal ScriptArray() As String)
    Dim ScriptLink As String

    For Each ScriptName In ScriptArray
        ScriptLink = [Global].ArrScripts(ScriptName)

        Dim ObjScript As New HtmlGenericControl("script")
        ObjScript.Attributes.Add("type", "text/javascript")
        ObjScript.Attributes.Add("src", ScriptLink)
        Me.Page.Header.Controls.Add(ObjScript)
    Next
End Sub

Public Sub SetSelectedMenu(ByVal MenuName As String, Optional ByRef ObjPage As Page = Nothing)
    Dim ObjMenu As New HtmlGenericControl

    If ObjPage Is Nothing Then
        ObjMenu = MyBase.Page.FindControl(MenuName)
    Else
        ObjMenu = ObjPage.FindControl(MenuName)
    End If
    ObjMenu.Attributes.Add("class", "selected")
End Sub

Public Sub ExecuteScript(ByVal ScriptName As String, Optional ByVal ScriptParam As String = "")
    Dim requestSM As ScriptManager = ScriptManager.GetCurrent(Me.Page)
    If Not requestSM Is Nothing And requestSM.IsInAsyncPostBack Then
        ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, ScriptName, ScriptName + "('" + ScriptParam + "');", True)
    Else
        Me.Page.ClientScript.RegisterStartupScript(Me.GetType, ScriptName, ScriptName + "('" + ScriptParam + "');", True)
    End If
End Sub

End Class
</code>```

Second class.

```<code>Public Class GuiControl
Inherits System.Web.UI.UserControl

Public Sub CreateStyleLink(ByVal StyleArray() As String)
    Dim StrStyleLink As String

    For Each StyleName In StyleArray
        StrStyleLink = [Global].ArrStyles(StyleName)

        Dim ObjScript As New HtmlGenericControl("link")
        ObjScript.Attributes.Add("rel", "Stylesheet")
        ObjScript.Attributes.Add("type", "text/css")
        ObjScript.Attributes.Add("href", StrStyleLink)
        Me.Page.Header.Controls.Add(ObjScript)
    Next
End Sub

Public Sub CreateScriptLink(ByVal ScriptArray() As String)
    Dim ScriptLink As String

    For Each ScriptName In ScriptArray
        ScriptLink = [Global].ArrScripts(ScriptName)

        Dim ObjScript As New HtmlGenericControl("script")
        ObjScript.Attributes.Add("type", "text/javascript")
        ObjScript.Attributes.Add("src", ScriptLink)
        Me.Page.Header.Controls.Add(ObjScript)
    Next
End Sub

Public Sub ExecuteScript(ByVal ScriptName As String, Optional ByVal ScriptParam As String = "")
    Dim requestSM As ScriptManager = ScriptManager.GetCurrent(Me.Page)
    If Not requestSM Is Nothing And requestSM.IsInAsyncPostBack Then
        ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, ScriptName, ScriptName + "('" + ScriptParam + "');", True)
    Else
        Me.Page.ClientScript.RegisterStartupScript(Me.GetType, ScriptName, ScriptName + "('" + ScriptParam + "');", True)
    End If
End Sub
End Class
</code>```

答:
Creating a base class just to inherit a common method often is not the way to go.  Inheritance is meant to create a more specific type of object, not just for sharing.  In this case one is a Page, the other is a UserControl, which probably don't define a hierarchical relationship.

As such, a utility or helper class would probably be the route to go, basically as Chris described.  One addition i'd make would be to make the two methods Shared, so as to not need an instance just to use.

By using a normal instance method, you'd have to go something along this route:

```<code>Dim help As New UserControlHelper
help.CreateScriptLink(Me)
</code>```

as opposed to a Shared method, could could be done just as:

```<code>UserControlHelper.CreateScriptLink(Me)
</code>```

I don't recall if Page inherits from UserControl (or vice-versa), so you may need to find a higher class to pass into the method, but the idea is basically the same.

Body:
How to simplify this, 2 method in class are identical.

First class.

Public Class Gui
Inherits System.Web.UI.Page

Public Sub CreateStyleLink(ByVal StyleArray() As String)
    Dim StrStyleLink As String

    For Each StyleName In StyleArray
        StrStyleLink = [Global].ArrStyles(StyleName)

        Dim ObjScript As New HtmlGenericControl("link")
        ObjScript.Attributes.Add("rel", "Stylesheet")
        ObjScript.Attributes.Add("type", "text/css")
        ObjScript.Attributes.Add("href", StrStyleLink)
        Me.Page.Header.Controls.Add(ObjScript)
    Next
End Sub

Public Sub CreateScriptLink(ByVal ScriptArray() As String)
    Dim ScriptLink As String

    For Each ScriptName In ScriptArray
        ScriptLink = [Global].ArrScripts(ScriptName)

        Dim ObjScript As New HtmlGenericControl("script")
        ObjScript.Attributes.Add("type", "text/javascript")
        ObjScript.Attributes.Add("src", ScriptLink)
        Me.Page.Header.Controls.Add(ObjScript)
    Next
End Sub

Public Sub SetSelectedMenu(ByVal MenuName As String, Optional ByRef ObjPage As Page = Nothing)
    Dim ObjMenu As New HtmlGenericControl

    If ObjPage Is Nothing Then
        ObjMenu = MyBase.Page.FindControl(MenuName)
    Else
        ObjMenu = ObjPage.FindControl(MenuName)
    End If
    ObjMenu.Attributes.Add("class", "selected")
End Sub

Public Sub ExecuteScript(ByVal ScriptName As String, Optional ByVal ScriptParam As String = "")
    Dim requestSM As ScriptManager = ScriptManager.GetCurrent(Me.Page)
    If Not requestSM Is Nothing And requestSM.IsInAsyncPostBack Then
        ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, ScriptName, ScriptName + "('" + ScriptParam + "');", True)
    Else
        Me.Page.ClientScript.RegisterStartupScript(Me.GetType, ScriptName, ScriptName + "('" + ScriptParam + "');", True)
    End If
End Sub

End Class

Second class.

Public Class GuiControl
Inherits System.Web.UI.UserControl

Public Sub CreateStyleLink(ByVal StyleArray() As String)
    Dim StrStyleLink As String

    For Each StyleName In StyleArray
        StrStyleLink = [Global].ArrStyles(StyleName)

        Dim ObjScript As New HtmlGenericControl("link")
        ObjScript.Attributes.Add("rel", "Stylesheet")
        ObjScript.Attributes.Add("type", "text/css")
        ObjScript.Attributes.Add("href", StrStyleLink)
        Me.Page.Header.Controls.Add(ObjScript)
    Next
End Sub

Public Sub CreateScriptLink(ByVal ScriptArray() As String)
    Dim ScriptLink As String

    For Each ScriptName In ScriptArray
        ScriptLink = [Global].ArrScripts(ScriptName)

        Dim ObjScript As New HtmlGenericControl("script")
        ObjScript.Attributes.Add("type", "text/javascript")
        ObjScript.Attributes.Add("src", ScriptLink)
        Me.Page.Header.Controls.Add(ObjScript)
    Next
End Sub

Public Sub ExecuteScript(ByVal ScriptName As String, Optional ByVal ScriptParam As String = "")
    Dim requestSM As ScriptManager = ScriptManager.GetCurrent(Me.Page)
    If Not requestSM Is Nothing And requestSM.IsInAsyncPostBack Then
        ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, ScriptName, ScriptName + "('" + ScriptParam + "');", True)
    Else
        Me.Page.ClientScript.RegisterStartupScript(Me.GetType, ScriptName, ScriptName + "('" + ScriptParam + "');", True)
    End If
End Sub
End Class

Body:
Creating a base class just to inherit a common method often is not the way to go.  Inheritance is meant to create a more specific type of object, not just for sharing.  In this case one is a Page, the other is a UserControl, which probably don't define a hierarchical relationship.

As such, a utility or helper class would probably be the route to go, basically as Chris described.  One addition i'd make would be to make the two methods Shared, so as to not need an instance just to use.

By using a normal instance method, you'd have to go something along this route:

Dim help As New UserControlHelper
help.CreateScriptLink(Me)

as opposed to a Shared method, could could be done just as:

UserControlHelper.CreateScriptLink(Me)

I don't recall if Page inherits from UserControl (or vice-versa), so you may need to find a higher class to pass into the method, but the idea is basically the same.


问:
Python Requests: requests.exceptions.TooManyRedirects: Exceeded 30 redirects
I was trying to crawl this page using python-requests library

```<code>import requests
from lxml import etree,html

url = 'http://www.amazon.in/b/ref=sa_menu_mobile_elec_all?ie=UTF8&node=976419031'
r = requests.get(url)
tree = etree.HTML(r.text)
print tree
</code>```

but I got above error. (TooManyRedirects)
I tried to use allow_redirects parameter but same error

r = requests.get(url, allow_redirects=True)

I even tried to send headers and data alongwith url but I'm not sure if this is correct way to do it.

```<code>headers = {'content-type': 'text/html'}
payload = {'ie':'UTF8','node':'976419031'}
r = requests.post(url,data=payload,headers=headers,allow_redirects=True)
</code>```

how to resolve this error. I've even tried beautiful-soup4 out of curiosity and I got different but same kind of error

page = BeautifulSoup(urllib2.urlopen(url))

```<code>urllib2.HTTPError: HTTP Error 301: The HTTP server returned a redirect error that would lead to an infinite loop.
The last 30x error message was:
Moved Permanently
</code>```

答:
Increase of max_redirect is possible by explicitly specifying the count as in example below:

```<code>session = requests.Session()
session.max_redirects = 60
session.get('http://www.amazon.com')
</code>```

Body:
I was trying to crawl this page using python-requests library

import requests
from lxml import etree,html

url = 'http://www.amazon.in/b/ref=sa_menu_mobile_elec_all?ie=UTF8&node=976419031'
r = requests.get(url)
tree = etree.HTML(r.text)
print tree

but I got above error. (TooManyRedirects)
I tried to use allow_redirects parameter but same error

r = requests.get(url, allow_redirects=True)

I even tried to send headers and data alongwith url but I'm not sure if this is correct way to do it.

headers = {'content-type': 'text/html'}
payload = {'ie':'UTF8','node':'976419031'}
r = requests.post(url,data=payload,headers=headers,allow_redirects=True)

how to resolve this error. I've even tried beautiful-soup4 out of curiosity and I got different but same kind of error

page = BeautifulSoup(urllib2.urlopen(url))

urllib2.HTTPError: HTTP Error 301: The HTTP server returned a redirect error that would lead to an infinite loop.
The last 30x error message was:
Moved Permanently

Body:
Increase of max_redirect is possible by explicitly specifying the count as in example below:

session = requests.Session()
session.max_redirects = 60
session.get('http://www.amazon.com')


问:
AJAX script with json format data not working
My complete script is as follows

```<code>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(window).on('load',function(){
            $('#myModal').modal('show');
        });
    </script>
    <script>
        $( document ).ready(function () {
            $("#vote").click(function (e) {
                var poll_id = $('input[name=pollID]', '#myForm').val();
                var poll_option_id = $('input[name=voteOpt]:checked', '#myForm').val() ;
                //alert(poll_id + "AND" + poll_option_id);
                $.ajax({
                    type: "POST",
                    url: "http://localhost/poll/index.php/form/poll",
                    data: {poll_id: poll_id, poll_option_id: poll_option_id},
                    dataType: "json",
                    success: function(data) {
                        alert(data);
                    }, error: function() {
                        alert("ERROR");
                    }
                });
            });
        });
    </script>
</code>```

And I have the following inside poll function in form controller

```<code>public function poll() {
        $pollid = $this->input->post('pollID');
        $voteData = array(
            'poll_id' => $pollid,
            'poll_option_id' => $this->input->post('voteOpt')
        );
        $voteSubmit = $this->modal->vote($voteData);
        if($voteSubmit){
            echo 'Your Vote Has Been Submitted successfully.';
        }else{
            echo 'You Had Already Voted.';
        }

}
</code>```

Now the thing is that, modal is executing perfectly on page load. But ajax is not working neither success part is executing nor error. Also on uncommenting the alert before ajax, correct values are alerted. I cannot figure the error.
Please help

答:
For Example.

See you can check is you script is actually sending post values or not these way.

In you console > Network Tab. You can view which post values are sent as POST.

Now I had code in PHP Codeigniter and for me following code worked fine.

```<code>$("#username").keyup(check_if_username_exists);

    function check_if_username_exists() {

    var username = $("#username").val();

    var sRet = false;

    $.ajax(
     {
        type:"post",
        async: false,
        url: "<?php echo site_url('distributor/tenant/check_username_exists'); ?>",
        data:{ username:username},

        success:function(response)
        {

            var parent_fieldset = $("#username").parents('fieldset');
            $("#username").parent().addClass('has-error');

            if (response == "true")
            {
                $('#span').html('<span style="color: #0fa7b5;">'+"Login Username"+"</span>");

                $("#username").removeClass('input-error');

                $("#username").parent().removeClass('has-error');

                console.log('Success! This Username is available');

                hideToastr();

                sRet = true;

            }
            else
            {
                show_error("Error","Oops! This Username is already taken");

                $("#username").addClass('input-error');

                $('#span').html('<span style="color:red;">Username already Exists!</span>');

                console.log('Oops! This Username is already taken');

                sRet = false;
            }

        }
      });

    console.log("End Of Username Exists " + sRet);
    return sRet;
}
</code>```

Also there is third party application POSTMAN which will help your debug your application. It allows you to sent post data with form values.

Update

Also I think you might have multiple JS files include issue or problem with the order they are placed. FYI I used only bootstrap.js and jquery.min.js and everything worked fine. So try removing

```<code><script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
</code>```

UPDATE 2 :

Now for your controller I don't see where you encode or decode your json data.
If Your are sending the values as JSON POST to your controller then you must decode it.

First Check is you are getting JSON data in your controller.
If its working fine, then try for second step.
Step 1:

```<code>public function poll() {
        $polldata = json_decode($_POST);

        echo $polldata;

}
</code>```

Step 2:

```<code>public function poll() {

        $polldata = json_decode($_POST);

        echo $polldata;
        $pollid = $polldata->pollID;
        $voteData = array(
            'poll_id' => $pollid,
            'poll_option_id' => $polldata->pollID->voteOpt
        );
        $voteSubmit = $this->modal->vote($voteData);
        if($voteSubmit){
            echo 'Your Vote Has Been Submitted successfully.';
        }else{
            echo 'You Had Already Voted.';
        }

}
</code>```

Let me know if you face any issues.

Body:
My complete script is as follows

And I have the following inside poll function in form controller

public function poll() {
        $pollid = $this->input->post('pollID');
        $voteData = array(
            'poll_id' => $pollid,
            'poll_option_id' => $this->input->post('voteOpt')
        );
        $voteSubmit = $this->modal->vote($voteData);
        if($voteSubmit){
            echo 'Your Vote Has Been Submitted successfully.';
        }else{
            echo 'You Had Already Voted.';
        }

}

Now the thing is that, modal is executing perfectly on page load. But ajax is not working neither success part is executing nor error. Also on uncommenting the alert before ajax, correct values are alerted. I cannot figure the error.
Please help

Body:
For Example.

See you can check is you script is actually sending post values or not these way.

In you console > Network Tab. You can view which post values are sent as POST.

Now I had code in PHP Codeigniter and for me following code worked fine.

$("#username").keyup(check_if_username_exists);

    function check_if_username_exists() {

    var username = $("#username").val();

    var sRet = false;

    $.ajax(
     {
        type:"post",
        async: false,
        url: "<?php echo site_url('distributor/tenant/check_username_exists'); ?>",
        data:{ username:username},

        success:function(response)
        {

            var parent_fieldset = $("#username").parents('fieldset');
            $("#username").parent().addClass('has-error');

            if (response == "true")
            {
                $('#span').html('<span style="color: #0fa7b5;">'+"Login Username"+"</span>");

                $("#username").removeClass('input-error');

                $("#username").parent().removeClass('has-error');

                console.log('Success! This Username is available');

                hideToastr();

                sRet = true;

            }
            else
            {
                show_error("Error","Oops! This Username is already taken");

                $("#username").addClass('input-error');

                $('#span').html('<span style="color:red;">Username already Exists!</span>');

                console.log('Oops! This Username is already taken');

                sRet = false;
            }

        }
      });

    console.log("End Of Username Exists " + sRet);
    return sRet;
}

Also there is third party application POSTMAN which will help your debug your application. It allows you to sent post data with form values.

Update

Also I think you might have multiple JS files include issue or problem with the order they are placed. FYI I used only bootstrap.js and jquery.min.js and everything worked fine. So try removing

<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>

UPDATE 2 :

Now for your controller I don't see where you encode or decode your json data.
If Your are sending the values as JSON POST to your controller then you must decode it.

First Check is you are getting JSON data in your controller.
If its working fine, then try for second step.
Step 1:

public function poll() {
        $polldata = json_decode($_POST);

        echo $polldata;

}

Step 2:

public function poll() {

        $polldata = json_decode($_POST);

        echo $polldata;
        $pollid = $polldata->pollID;
        $voteData = array(
            'poll_id' => $pollid,
            'poll_option_id' => $polldata->pollID->voteOpt
        );
        $voteSubmit = $this->modal->vote($voteData);
        if($voteSubmit){
            echo 'Your Vote Has Been Submitted successfully.';
        }else{
            echo 'You Had Already Voted.';
        }

}

Let me know if you face any issues.


问:
unobtrusive client validation rules must be unique
Environment: Visual Studio 2013  and Mvc 5

I am upgrading my site from VS 2010 & MVC 3 to VS 2013 & MVC 5. This works just fine in VS 2010 & MVC 3,  where as in the upgrade project (VS 2013 & MVC 5) it is erroring out with the following message.

Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: date

Class

```<code>public partial class FileTransferFilterCriteria
    {
        public string Fice { get; set; }
        public string SourceEmail { get; set; }
        public string TargetEmail { get; set; }

        public DateTime? FromDate { get; set; }
        public DateTime? ToDate { get; set; }

        public string Status { get; set; }
        public string Category { get; set; }
    }
</code>```

Meta Data

```<code>[MetadataType(typeof(FileTransferFilterCriteria.FileTransferFilterCriteriaMetaData))]
    public partial class FileTransferFilterCriteria
    {
        public class FileTransferFilterCriteriaMetaData
        {
            [DataType(DataType.DateTime)]
            [Date(ErrorMessage = ValidationMessageConstants.InvalidDate)]
            [UIHint(UiHintEditorTemplateConstants.DateCalendar)]
            [UIHint(UiHintDisplayTemplateConstants.Date)]
            public DateTime? FromDate { get; set; }

            [DataType(DataType.DateTime)]
            [Date(ErrorMessage = ValidationMessageConstants.InvalidDate)]
            [UIHint(UiHintEditorTemplateConstants.DateCalendar)]
            [UIHint(UiHintDisplayTemplateConstants.Date)]
            public DateTime? ToDate { get; set; }
        }

    }
</code>```

Html

```<code><tr>
                    <th>Upload From Date</th>
                    <td>
                        @Html.EditorFor(x => x.Criteria.FromDate, UiHintEditorTemplateConstants.DateCalendar)
                        @Html.ValidationMessageFor(x => x.Criteria.FromDate)
                    </td>
                </tr>
                <tr>
                    <th>Upload To Date</th>
                    <td>
                        @Html.EditorFor(x => x.Criteria.ToDate, UiHintEditorTemplateConstants.DateCalendar)
                        @Html.ValidationMessageFor(x => x.Criteria.ToDate)
                    </td>
                </tr>
</code>```

Editor Template

```<code>@using System.Globalization

@model DateTime?

@Html.TextBox("",
(Model != null &&
Model.HasValue &&
!Model.Value.ToString(CultureInfo.InvariantCulture).Contains("1900") &&
!Model.Value.ToString(CultureInfo.InvariantCulture).Contains("0001")
?
Model.Value.ToString("MM/dd/yyyy")
:
string.Empty),
new { @class = "datePicker", maxlength = "12", size = "12" })
</code>```

What is wrong here?

Resulting HTML from VS 2010 & MVC 3 project:

```<code><tr>
                    <th>Upload From Date</th>
                    <td>

<input class="datePicker" data-val="true" data-val-date="Invalid date specified. Date should be like MM/DD/YYYY." id="Criteria_FromDate" maxlength="12" name="Criteria.FromDate" size="12" type="text" value="" />

                        <span class="field-validation-valid" data-valmsg-for="Criteria.FromDate" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <th>Upload To Date</th>
                    <td>

<input class="datePicker" data-val="true" data-val-date="Invalid date specified. Date should be like MM/DD/YYYY." id="Criteria_ToDate" maxlength="12" name="Criteria.ToDate" size="12" type="text" value="" />

                        <span class="field-validation-valid" data-valmsg-for="Criteria.ToDate" data-valmsg-replace="true"></span>
                    </td>
                </tr>
</code>```

Resulting HTML - VS 2013 and MVC 5, when i take out the date attribute:

```<code><tr>
                    <th>Upload From Date</th>
                    <td>

<input class="datePicker" data-val="true" data-val-date="The field Upload From Date must be a date." id="Criteria_FromDate" maxlength="12" name="Criteria.FromDate" size="12" type="text" value="" />

                        <br/><span class="field-validation-valid" data-valmsg-for="Criteria.FromDate" data-valmsg-replace="true"></span>
                    </td>
                </tr>
                <tr>
                    <th>Upload To Date</th>
                    <td>

<input class="datePicker" data-val="true" data-val-date="The field Upload To Date must be a date." id="Criteria_ToDate" maxlength="12" name="Criteria.ToDate" size="12" type="text" value="" />

                        <br/><span class="field-validation-valid" data-valmsg-for="Criteria.ToDate" data-valmsg-replace="true"></span>
                    </td>
                </tr>
</code>```

答:
Recently I have upgraded MVC3 application to MVC4 application and changed target framework to 4.0. I have no build errors.

But, I got the same error on below line

  @Html.EditorFor(model => model.CmpnySearchReportCriteria.ReportReturnDueDateFrom)```
</div>
</div>
</p>

<p>Data annotation attribute was decorated in model as below.</p>

```[Display(Name = "Due Date From")]
[DataType(DataType.Date, ErrorMessage = "Please enter a valid date (format: MM/DD/YYYY) for From Report / Return Due Date.")]
public DateTime? ReportReturnDueDateFrom { get; set; }
```

<p>I have written custom client side validation rule for date input field like below. Because automatic type checking validation for date was not available in MVC3.</p>

```public class ModelClientValidationDateRule : ModelClientValidationRule
{
     public ModelClientValidationDateRule(string errorMessage)
     {
           ErrorMessage = errorMessage;
           ValidationType = "date";
      }
}
```

<p>observed that, MVC4 added automatic type checking validation to any DateTime fields. In MVC4, default client validation message is rendered like below.</p>

<p>data-val-date="The field <strong>{PropertyName}</strong> must be a date."</p>

<blockquote>
  <p>Because of our custom client side validation rule data-val-date
  attribute was rendered twice. This is the cause of this error i.e.
  "Validation type names in unobtrusive client validation rules must be
  unique."</p>
</blockquote>

```<input class="datefield hasDatepicker" **data-val="true" data-val-date="The field UpdateDate must be a date." data-val-date="Please enter a valid date (format: MM/DD/YYYY) for From Date."** id="UpdateDate" name="UpdateDate" type="text" value="">
```

<p><strong>To Fix this -</strong></p>

<ol>
<li><p>Comment data annotation attribute</p>

<p><code>public class PreInvoiceSearchCriteria
{
    //[DataType(DataType.Date, ErrorMessage = "Please enter a valid date
      //(format: MM/DD/YYYY) for From Date.")]
    public DateTime? RenewDate { get; set; }
}</code></p></li>
<li><p>If you don’t want default validation message you can update it using JQuery like below.</p></li>
</ol>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {

        $('#DateOfInc').attr("data-val-date", "Please enter a valid date   (format: MM/DD/YYYY) for Date of Inc")
    });</code>```

Body:
Environment: Visual Studio 2013  and Mvc 5

I am upgrading my site from VS 2010 & MVC 3 to VS 2013 & MVC 5. This works just fine in VS 2010 & MVC 3,  where as in the upgrade project (VS 2013 & MVC 5) it is erroring out with the following message.

Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: date

Class

public partial class FileTransferFilterCriteria
    {
        public string Fice { get; set; }
        public string SourceEmail { get; set; }
        public string TargetEmail { get; set; }

        public DateTime? FromDate { get; set; }
        public DateTime? ToDate { get; set; }

        public string Status { get; set; }
        public string Category { get; set; }
    }

Meta Data

[MetadataType(typeof(FileTransferFilterCriteria.FileTransferFilterCriteriaMetaData))]
    public partial class FileTransferFilterCriteria
    {
        public class FileTransferFilterCriteriaMetaData
        {
            [DataType(DataType.DateTime)]
            [Date(ErrorMessage = ValidationMessageConstants.InvalidDate)]
            [UIHint(UiHintEditorTemplateConstants.DateCalendar)]
            [UIHint(UiHintDisplayTemplateConstants.Date)]
            public DateTime? FromDate { get; set; }

            [DataType(DataType.DateTime)]
            [Date(ErrorMessage = ValidationMessageConstants.InvalidDate)]
            [UIHint(UiHintEditorTemplateConstants.DateCalendar)]
            [UIHint(UiHintDisplayTemplateConstants.Date)]
            public DateTime? ToDate { get; set; }
        }

    }

Html

                    Upload From Date

                        @Html.EditorFor(x => x.Criteria.FromDate, UiHintEditorTemplateConstants.DateCalendar)
                        @Html.ValidationMessageFor(x => x.Criteria.FromDate)

                    Upload To Date

                        @Html.EditorFor(x => x.Criteria.ToDate, UiHintEditorTemplateConstants.DateCalendar)
                        @Html.ValidationMessageFor(x => x.Criteria.ToDate)

Editor Template

@using System.Globalization

@model DateTime?

@Html.TextBox("",
(Model != null &&
Model.HasValue &&
!Model.Value.ToString(CultureInfo.InvariantCulture).Contains("1900") &&
!Model.Value.ToString(CultureInfo.InvariantCulture).Contains("0001")
?
Model.Value.ToString("MM/dd/yyyy")
:
string.Empty),
new { @class = "datePicker", maxlength = "12", size = "12" })

What is wrong here?

Resulting HTML from VS 2010 & MVC 3 project:

                    Upload From Date

<input class="datePicker" data-val="true" data-val-date="Invalid date specified. Date should be like MM/DD/YYYY." id="Criteria_FromDate" maxlength="12" name="Criteria.FromDate" size="12" type="text" value="" />

                    Upload To Date

<input class="datePicker" data-val="true" data-val-date="Invalid date specified. Date should be like MM/DD/YYYY." id="Criteria_ToDate" maxlength="12" name="Criteria.ToDate" size="12" type="text" value="" />

Resulting HTML - VS 2013 and MVC 5, when i take out the date attribute:

                    Upload From Date

<input class="datePicker" data-val="true" data-val-date="The field Upload From Date must be a date." id="Criteria_FromDate" maxlength="12" name="Criteria.FromDate" size="12" type="text" value="" />

                    Upload To Date

<input class="datePicker" data-val="true" data-val-date="The field Upload To Date must be a date." id="Criteria_ToDate" maxlength="12" name="Criteria.ToDate" size="12" type="text" value="" />

Body:
Recently I have upgraded MVC3 application to MVC4 application and changed target framework to 4.0. I have no build errors.

But, I got the same error on below line

  @Html.EditorFor(model => model.CmpnySearchReportCriteria.ReportReturnDueDateFrom)

Data annotation attribute was decorated in model as below.

[Display(Name = "Due Date From")]
[DataType(DataType.Date, ErrorMessage = "Please enter a valid date (format: MM/DD/YYYY) for From Report / Return Due Date.")]
public DateTime? ReportReturnDueDateFrom { get; set; }

I have written custom client side validation rule for date input field like below. Because automatic type checking validation for date was not available in MVC3.

public class ModelClientValidationDateRule : ModelClientValidationRule
{
     public ModelClientValidationDateRule(string errorMessage)
     {
           ErrorMessage = errorMessage;
           ValidationType = "date";
      }
}

observed that, MVC4 added automatic type checking validation to any DateTime fields. In MVC4, default client validation message is rendered like below.

data-val-date="The field {PropertyName} must be a date."

Because of our custom client side validation rule data-val-date
  attribute was rendered twice. This is the cause of this error i.e.
  "Validation type names in unobtrusive client validation rules must be
  unique."

<input class="datefield hasDatepicker" **data-val="true" data-val-date="The field UpdateDate must be a date." data-val-date="Please enter a valid date (format: MM/DD/YYYY) for From Date."** id="UpdateDate" name="UpdateDate" type="text" value="">

To Fix this -

Comment data annotation attribute

public class PreInvoiceSearchCriteria
{
    //[DataType(DataType.Date, ErrorMessage = "Please enter a valid date
      //(format: MM/DD/YYYY) for From Date.")]
    public DateTime? RenewDate { get; set; }
}

If you don’t want default validation message you can update it using JQuery like below.

$(document).ready(function () {

        $('#DateOfInc').attr("data-val-date", "Please enter a valid date   (format: MM/DD/YYYY) for Date of Inc")
    });


问:
Batch: Show last user input
(This is my first post here, so bear with me)

Can you show the last user-input in a batch file? I'm gonna try to keep it simple here.

```<code>@echo off

:menu
echo Type 1 to proceed.
set /p example=
if "%example%" == "1" GOTO :proceed
GOTO :error

:proceed
pause

:error
cls
echo You wrote (last user input), that's not correct.
timeout 30
GOTO :menu
</code>```

I know that I could replace the (last user input) with %example%, but then I'd have to make custom error messages for every category, and there are about 50 of them. It'd be easier with a last input command.

By the way, I've taught myself everything that I know about batch, so my example probably has major issues right now, but it works somehow.

答:
You could centralize all user input into a function (user_input)</p>

```<code>:menu1
echo Type 1 to proceed.
call :userInput example
if "%example%" == "1" GOTO :proceed
GOTO :error

:menu2
echo Type 42 to proceed.
call :userInput answer
if "%answer%" == "42" GOTO :proceed
GOTO :error

:userInput
set /p LAST_INPUT=
set "%1=%LAST_INPUT%"
exit /b

:proceed
pause

:error
cls
echo You wrote "%LAST_INPUT%", that's not correct.
timeout 30
GOTO :menu
</code>```

Title: Batch: Show last user input

Body:
(This is my first post here, so bear with me)

Can you show the last user-input in a batch file? I'm gonna try to keep it simple here.

@echo off

:menu
echo Type 1 to proceed.
set /p example=
if "%example%" == "1" GOTO :proceed
GOTO :error

:proceed
pause

:error
cls
echo You wrote (last user input), that's not correct.
timeout 30
GOTO :menu

I know that I could replace the (last user input) with %example%, but then I'd have to make custom error messages for every category, and there are about 50 of them. It'd be easier with a last input command.

By the way, I've taught myself everything that I know about batch, so my example probably has major issues right now, but it works somehow.

Body:
You could centralize all user input into a function (user_input)

:menu1
echo Type 1 to proceed.
call :userInput example
if "%example%" == "1" GOTO :proceed
GOTO :error

:menu2
echo Type 42 to proceed.
call :userInput answer
if "%answer%" == "42" GOTO :proceed
GOTO :error

:userInput
set /p LAST_INPUT=
set "%1=%LAST_INPUT%"
exit /b

:proceed
pause

:error
cls
echo You wrote "%LAST_INPUT%", that's not correct.
timeout 30
GOTO :menu


问:
How to replace everything with blank after question mark in a string?
I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

```<code>var str = "/root/Users?SkillId=201;"
</code>```

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

```<code>var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable
</code>```

I don't want to use for loop for this. Isn't there is any better way to do this?

答:
This should help

var str = "/root/Users?SkillId=201;"

str = str.replace(/\?.*$/g,"");
console.log(str);```

Body:
I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

var str = "/root/Users?SkillId=201;"

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable

I don't want to use for loop for this. Isn't there is any better way to do this?


问:
PostgreSQL: get input parameters as row values
I have created a simple function:

```<code>create function my fucnction(uuid, uuid, date) returns boolean as
$$
    select ... from t where t.f1 = $1 and t.f2 = $2 and t.f3 = $3;
$$
language sql stable;
</code>```

It would be great syntax-wise if I could access the input parameters as a single row (which would be equal to ($1, $2, $3) in my function), so I could write:

```<code>create function my fucnction(uuid, uuid, date) returns boolean as
$$
    select ... from t where (t.f1, t.f2, t.f3) = <the input parameters row>;
$$
language sql stable;
</code>```

which would be equal to:

```<code>create function my fucnction(uuid, uuid, date) returns boolean as
$$
    select ... from t where (t.f1, t.f2, t.f3) = ($1, $2, $3);
$$
language sql stable;
</code>```

Is this possible?

答:
This works for me. I am a big fan of the row() function, especially in count(distinct row()) queries.

```<code>create OR REPLACE function my_function(text,text,text) returns bigint as
$$
    select count(*) from t where row(t1,t2,t3) = row($1,$2,$3);
$$
language sql stable;

select * from my_function('a','b','c');
</code>```

NOTE: this seems to work with your syntax of (t1,t2,t3), as well.

EDIT: I may have misunderstood your question.  If you particularly want a named reference like in triggers, you can always pass in a record type (here I am using the type defined by table t).  It might be worth looking into the record datatype as well as PLPGSQL if you need a more complex function:

```<code>create OR REPLACE function my_function(blast t) returns bigint as
$$

    select count(*) from t where (t1,t2,t3) = blast;
$$
language sql stable;

select * from my_function(row('a','b','c'));
</code>```

One last alternative - does not give the niceness of the syntax above, presumably because the type is not defined, but if you need separate parameters on input:

```<code>create OR REPLACE function my_function(_1 text, _2 text, _3 text) returns bigint as
$$

    select count(*) from t where (t1,t2,t3) = (my_function._1, my_function._2, my_function._3);
$$
language sql stable;

select * from my_function('a','b','c')
</code>```

Body:
I have created a simple function:

create function my fucnction(uuid, uuid, date) returns boolean as
$$
    select ... from t where t.f1 = $1 and t.f2 = $2 and t.f3 = $3;
$$
language sql stable;

It would be great syntax-wise if I could access the input parameters as a single row (which would be equal to ($1, $2, $3) in my function), so I could write:

create function my fucnction(uuid, uuid, date) returns boolean as
$$
    select ... from t where (t.f1, t.f2, t.f3) = <the input parameters row>;
$$
language sql stable;

which would be equal to:

create function my fucnction(uuid, uuid, date) returns boolean as
$$
    select ... from t where (t.f1, t.f2, t.f3) = ($1, $2, $3);
$$
language sql stable;

Is this possible?

Body:
This works for me. I am a big fan of the row() function, especially in count(distinct row()) queries.

create OR REPLACE function my_function(text,text,text) returns bigint as
$$
    select count(*) from t where row(t1,t2,t3) = row($1,$2,$3);
$$
language sql stable;

select * from my_function('a','b','c');

NOTE: this seems to work with your syntax of (t1,t2,t3), as well.

EDIT: I may have misunderstood your question.  If you particularly want a named reference like in triggers, you can always pass in a record type (here I am using the type defined by table t).  It might be worth looking into the record datatype as well as PLPGSQL if you need a more complex function:

create OR REPLACE function my_function(blast t) returns bigint as
$$

    select count(*) from t where (t1,t2,t3) = blast;
$$
language sql stable;

select * from my_function(row('a','b','c'));

One last alternative - does not give the niceness of the syntax above, presumably because the type is not defined, but if you need separate parameters on input:

create OR REPLACE function my_function(_1 text, _2 text, _3 text) returns bigint as
$$

    select count(*) from t where (t1,t2,t3) = (my_function._1, my_function._2, my_function._3);
$$
language sql stable;

select * from my_function('a','b','c')


问:
Setting Label Text in XAML to string constant
I have a single string constant that I have to re-use in several different XAML layouts, so instead of duplicating it, I'd like to just bind it to a constant.

I have a class which defines the string in C#:

```<code>public static class StringConstants
{
     public static string MyString { get { return "SomeConstant"; } }
}
</code>```

I'd like to be able to set the value through XAML via something like the following:

```<code><Label Content="{Binding local:StringConstants.MyString}"/>
</code>```

Is this achievable? I've searched for examples, but I've only found samples that involve some tinkering in the code-behind and I'm wondering if there's a simpler, XAML-only solution if I know that I just need to set the value once based on a string value that will never change.

答:
In the case that you have a constant inside of a non-static class, this doesn't work.

My solution for binding to a constant inside of a view model (MVVM).
It uses a getter property with less code for wrapping.

```<code>// view model
public const string MyString = "abc";
public string MyStringConst => MyString;
</code>```

.

```<code><!-- WPF -->
<Label Content="{Binding MyStringConst, FallbackValue='abc'}" />
</code>```

The FallbackValue is used for the Designer preview.

Body:
I have a single string constant that I have to re-use in several different XAML layouts, so instead of duplicating it, I'd like to just bind it to a constant.

I have a class which defines the string in C#:

public static class StringConstants
{
     public static string MyString { get { return "SomeConstant"; } }
}

I'd like to be able to set the value through XAML via something like the following:

Is this achievable? I've searched for examples, but I've only found samples that involve some tinkering in the code-behind and I'm wondering if there's a simpler, XAML-only solution if I know that I just need to set the value once based on a string value that will never change.

Body:
In the case that you have a constant inside of a non-static class, this doesn't work.

My solution for binding to a constant inside of a view model (MVVM).
It uses a getter property with less code for wrapping.

// view model
public const string MyString = "abc";
public string MyStringConst => MyString;

.

<!-- WPF -->
<Label Content="{Binding MyStringConst, FallbackValue='abc'}" />

The FallbackValue is used for the Designer preview.


问:
could we create Virtual host for modules in Zend framework1.11
currently I have a zend 1.xx project with three modules module1, module2, module3.

My requirement is to create separate virtual host for each module.

Like if we type http://module1 is should load module1, and we type http://module2 then it should load module2 of the project.

What should be the DocumentRoot value in virtual host for modules other then default.

For default module .../project/public works fine, but not for other modules.

答:
You can definitely not use virtual hosts to do that, unless you actually split your codebase per module (meaning having a copy of the code with only module1, module2 or module3).

What you can do very easily is disable the default routes (which will remove access to your app altogether I believe, I suppose you haven't defined your own routes), then create a Route chain that chains a route hostname and a route that looks like the default one.

So:

disable the default route

create a route just like the default one without module

create 3 routes hostname (one per domain)

create 3 chains that have a route hostname (3.) and the default route (2.)