问:
Php how to correctly use return function?
Hello I have a problem with this function I want to show the result of the function to put in a variable and send it to the database but it does not show me anything you can see in the example in the Second Block when I added echo its show me but I don't know how to get that result out I did use return but it gave a different result

```<code>$fullname = "Ayoub Chafik" ;

function orderID($data){
    $AKK = "AK". date('YmdHis');
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str)
    $str[0];

}
// I want to see resulte here of this function
   echo orderID($fullname) ;

?>
</code>```

This is the second Block

```<code><?php

$fullname = "Ayoub Chafik" ;

function orderID($data){
    echo $AKK = "AK". date('YmdHis');
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str)
    echo $str[0];

}

echo orderID($fullname) ;

?>
</code>```

答:
Some examples varying output based on your code sample.

```<code>$fullname = "Ayoub Chafik";
function orderID($data){
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str) {
    return $str;
    }
}
echo orderID($fullname) ;
// output "AYOUB"
function _orderID($data){
    $return = false;
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str) {
    $return = $str;
    }
    return $return;
}
echo _orderID($fullname) ;
// output "CHAFIK"
function _orderID_($data){
    $return = [];
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str) {
    array_push($return,$str);
    }
    return json_encode($return);
}
echo _orderID_($fullname) ;
// output ["AYOUB","CHAFIK"]
</code>```

check the above examples on PHP SandBox

Body:
Hello I have a problem with this function I want to show the result of the function to put in a variable and send it to the database but it does not show me anything you can see in the example in the Second Block when I added echo its show me but I don't know how to get that result out I did use return but it gave a different result

$fullname = "Ayoub Chafik" ;

function orderID($data){
    $AKK = "AK". date('YmdHis');
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str)
    $str[0];

}
// I want to see resulte here of this function
   echo orderID($fullname) ;

?>

This is the second Block

<?php

$fullname = "Ayoub Chafik" ;

function orderID($data){
    echo $AKK = "AK". date('YmdHis');
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str)
    echo $str[0];

}

echo orderID($fullname) ;

?>

Body:
Some examples varying output based on your code sample.

$fullname = "Ayoub Chafik";
function orderID($data){
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str) {
    return $str;
    }
}
echo orderID($fullname) ;
// output "AYOUB"
function _orderID($data){
    $return = false;
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str) {
    $return = $str;
    }
    return $return;
}
echo _orderID($fullname) ;
// output "CHAFIK"
function _orderID_($data){
    $return = [];
    $string = strtoupper($data);
    $strs=explode(" ",$string);
    foreach($strs as $str) {
    array_push($return,$str);
    }
    return json_encode($return);
}
echo _orderID_($fullname) ;
// output ["AYOUB","CHAFIK"]

check the above examples on PHP SandBox


来源: stackexchange

问:
React-router URLs don't work when refreshing or writing manually
I'm using React-router and it works fine while I'm clicking on link buttons, but when I refresh my webpage it does not load what I want.

For instance, I am in localhost/joblist and everything is fine because I arrived here pressing a link. But if I refresh the webpage I get:

Cannot GET /joblist
```
<p>By default, it didn't work like this. Initially I had my URL as <code>localhost/#/</code> and <code>localhost/#/joblist</code> and they worked perfectly fine. But I don't like this kind of URL, so trying to erase that <code>#</code>, I wrote:</p>
```Router.run(routes, Router.HistoryLocation, function (Handler) {
 React.render(<Handler/>, document.body);
});
```
<p>This problem does not happen with <code>localhost/</code>, this one always returns what I want.</p>
<p>This app is single-page, so <code>/joblist</code> doesn't need to ask anything to any server.</p>
<p>My entire router.</p>
```var routes = (
    <Route name="app" path="/" handler={App}>
        <Route name="joblist" path="/joblist" handler={JobList}/>
        <DefaultRoute handler={Dashboard}/>
        <NotFoundRoute handler={NotFound}/>
    </Route>
);

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});
```

答:
A solution in React for a JavaScript SPA with Laravel

The accepted answer is the best explanation of why such problems happen. As already explained, you have to configure both the client side and server side.

In your blade template, include the JavaScript bundled file, make sure to use URL facade like this:

```
<p>In your routes, make sure to add this to the main endpoint where the blade template is. For example,</p>
```Route::get('/setting-alerts', function () {
   return view('user.set-alerts');
});
```
<p>The above is the main endpoint for the blade template. Now add an optional route too,</p>
```Route::get('/setting-alerts/{spa?}', function () {
  return view('user.set-alerts');
});
```

The problem that happens is that first the blade template is loaded, then the React router. So, when you're loading '/setting-alerts', it loads the HTML content and the JavaScript code.

But when you load '/setting-alerts/about', it first loads on the server side. Since it is on the server side, there isn't anything on this location, and it returns not found. When you have that optional router, it loads that same page and React Router is also loaded, then the React loader decides which component to show.

ContentLicense: CC BY-SA 4.0

Body:
I'm using React-router and it works fine while I'm clicking on link buttons, but when I refresh my webpage it does not load what I want.

For instance, I am in localhost/joblist and everything is fine because I arrived here pressing a link. But if I refresh the webpage I get:

Cannot GET /joblist

By default, it didn't work like this. Initially I had my URL as localhost/#/ and localhost/#/joblist and they worked perfectly fine. But I don't like this kind of URL, so trying to erase that #, I wrote:

Router.run(routes, Router.HistoryLocation, function (Handler) {
 React.render(<Handler/>, document.body);
});

This problem does not happen with localhost/, this one always returns what I want.

This app is single-page, so /joblist doesn't need to ask anything to any server.

My entire router.

var routes = (
    <Route name="app" path="/" handler={App}>
        <Route name="joblist" path="/joblist" handler={JobList}/>
        <DefaultRoute handler={Dashboard}/>
        <NotFoundRoute handler={NotFound}/>
    </Route>
);

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});

Body:
A solution in React for a JavaScript SPA with Laravel

The accepted answer is the best explanation of why such problems happen. As already explained, you have to configure both the client side and server side.

In your blade template, include the JavaScript bundled file, make sure to use URL facade like this:

<script src="{{ URL::to('js/user/spa.js') }}"></script>

In your routes, make sure to add this to the main endpoint where the blade template is. For example,

Route::get('/setting-alerts', function () {
   return view('user.set-alerts');
});

The above is the main endpoint for the blade template. Now add an optional route too,

Route::get('/setting-alerts/{spa?}', function () {
  return view('user.set-alerts');
});

The problem that happens is that first the blade template is loaded, then the React router. So, when you're loading '/setting-alerts', it loads the HTML content and the JavaScript code.

But when you load '/setting-alerts/about', it first loads on the server side. Since it is on the server side, there isn't anything on this location, and it returns not found. When you have that optional router, it loads that same page and React Router is also loaded, then the React loader decides which component to show.


问:
Python 3+ How to edit a line in a text file
This has been asked, and it has been answered. Though, the answers do not favor my situation or what I'm trying to achieve.

I have 100's of text files I need to update. I need to update the same one line in each file. I want to open up a text file and only modify a single line. I do not want to re-write the text file using write() or writelines(). I also do not want to use fileinput.input() because that too is re-writing the text file using print statements.

The files contain thousands of lines of critical data and I cannot trust that Python will recreate everything correctly in the files (I understand this will probably never happen). There are several lines that pertain to footer data which is non-critical and that's what I am updating.

How can one update a single line in a text file, without recreating the file. Appending one line in a text must be possible.

Thanks in advance

答:
I don't think this is possible in any programming language at the file level. Files simply don't work that way -- especially text-based files which you are likely replacing with different-length data in the middle. You would need raw disk level access (making this a stupidly difficult problem).

If you really want to pursue it, check the raw disk question here:

Is it possible to get writing access to raw devices using python with windows?

EVEN THEN: I'm pretty sure at some level AT LEAST an entire block of data will be read from the drive and re-written (this is physically how drives work if I recall).

ContentLicense: CC BY-SA 3.0


问:
spring-boot application: ApplicationContextException: Unable to start EmbeddedWebApplicationContext
When I try to run this spring boot application I am getting an exception.

Code:

```<code> package com.example.extract.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages= "com.example.extract")
@EnableAutoConfiguration
//@SpringBootApplication
public class Demo1Application extends SpringBootServletInitializer {

    private static Class<Demo1Application> applicationClass = Demo1Application.class;

    public static void main(String[] args) {
        System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH","true");
        SpringApplication.run(applicationClass, args);
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(applicationClass);

    }
}
</code>```

pom.xml

```<code> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>Start</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo-1</name>
    <description>extraction of file</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>

<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>

<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>

<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.2</version>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>

<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0-m08</version>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>

<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-cypher-compiler-2.2</artifactId>
<version>2.2.5</version>
</dependency>

<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>6.0.0</version>
</dependency>

<!-- Dependecy Added for PostGreSql -->

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1100-jdbc41</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
</dependency>

<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.0</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-commons</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

<exclusions>

<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>

<exclusion>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<groupId>org.apache.cxf</groupId>
</exclusion>

</exclusions>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.12.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.12.RELEASE</version>
</dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>

</project>
</code>```

Trace

```<code>>
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.8.RELEASE)

2017-11-13 22:12:44.037  INFO 4920 --- [           main] c.example.extract.boot.Demo1Application  : Starting Demo1Application on DESKTOP-O061U2P with PID 4920 (E:\WorkSpace\demo-1\target\classes started by adity in E:\WorkSpace\demo-1)
2017-11-13 22:12:44.041  INFO 4920 --- [           main] c.example.extract.boot.Demo1Application  : No active profile set, falling back to default profiles: default
2017-11-13 22:12:44.110  INFO 4920 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@55ca8de8: startup date [Mon Nov 13 22:12:44 IST 2017]; root of context hierarchy
2017-11-13 22:12:45.186  INFO 4920 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'httpRequestHandlerAdapter' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]]
2017-11-13 22:12:45.552  INFO 4920 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-11-13 22:12:45.743  INFO 4920 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$6edf9e5] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-11-13 22:12:45.800  WARN 4920 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
2017-11-13 22:12:45.809  INFO 4920 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-13 22:12:45.822 ERROR 4920 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at com.example.extract.boot.Demo1Application.main(Demo1Application.java:21) [classes/:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:189) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:162) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    ... 8 common frames omitted
</code>```

I have tried everything that is mentioned in available in stackoverflow but still getting the same exception.

答:
Please mention packaging as "jar" instead of "war", rebuild and restart the application. Try this and let me know how it goes.

```<code><packaging>jar</packaging>
</code>```

Also, I see there is an exclusion for "spring-boot-starter-tomcat" dependency, please remove it as this seems to be the cause for not detecting embedded tomcat container.

Body:
When I try to run this spring boot application I am getting an exception.

Code:

 package com.example.extract.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages= "com.example.extract")
@EnableAutoConfiguration
//@SpringBootApplication
public class Demo1Application extends SpringBootServletInitializer {

    private static Class<Demo1Application> applicationClass = Demo1Application.class;

    public static void main(String[] args) {
        System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH","true");
        SpringApplication.run(applicationClass, args);
    }
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(applicationClass);

    }
}

pom.xml

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>Start</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo-1</name>
    <description>extraction of file</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>

<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>

<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>

<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.2</version>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>

<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0-m08</version>
</dependency>

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>

<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-cypher-compiler-2.2</artifactId>
<version>2.2.5</version>
</dependency>

<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>6.0.0</version>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1100-jdbc41</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
</dependency>

<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>2.11.0</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-commons</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

<exclusions>

<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>

<exclusion>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<groupId>org.apache.cxf</groupId>
</exclusion>

</exclusions>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.12.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.12.RELEASE</version>
</dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>

</project>

Trace

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

2017-11-13 22:12:44.037  INFO 4920 --- [           main] c.example.extract.boot.Demo1Application  : Starting Demo1Application on DESKTOP-O061U2P with PID 4920 (E:\WorkSpace\demo-1\target\classes started by adity in E:\WorkSpace\demo-1)
2017-11-13 22:12:44.041  INFO 4920 --- [           main] c.example.extract.boot.Demo1Application  : No active profile set, falling back to default profiles: default
2017-11-13 22:12:44.110  INFO 4920 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@55ca8de8: startup date [Mon Nov 13 22:12:44 IST 2017]; root of context hierarchy
2017-11-13 22:12:45.186  INFO 4920 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'httpRequestHandlerAdapter' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]]
2017-11-13 22:12:45.552  INFO 4920 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-11-13 22:12:45.743  INFO 4920 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$6edf9e5] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-11-13 22:12:45.800  WARN 4920 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
2017-11-13 22:12:45.809  INFO 4920 --- [           main] utoConfigurationReportLoggingInitializer :

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-11-13 22:12:45.822 ERROR 4920 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) ~[spring-context-4.3.12.RELEASE.jar:4.3.12.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at com.example.extract.boot.Demo1Application.main(Demo1Application.java:21) [classes/:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:189) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:162) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:134) ~[spring-boot-1.5.8.RELEASE.jar:1.5.8.RELEASE]
    ... 8 common frames omitted

I have tried everything that is mentioned in available in stackoverflow but still getting the same exception.

Body:
Please mention packaging as "jar" instead of "war", rebuild and restart the application. Try this and let me know how it goes.

<packaging>jar</packaging>

Also, I see there is an exclusion for "spring-boot-starter-tomcat" dependency, please remove it as this seems to be the cause for not detecting embedded tomcat container.


问:
Need help for javascript closure code example
I am trying to grasp the concept of closure in javascript and come across the following codes on http://javascriptissexy.com:

```<code>// This example is explained in detail below (just after this code box).
function celebrityIDCreator (theCelebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
  theCelebrities[i]["id"] = function ()  {
    return uniqueID + i;
  }
 }

 return theCelebrities;
}

var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

var stalloneID = createIdForActionCelebs[0];console.log(stalloneID.id());//103
</code>```

In the preceding example, by the time the anonymous functions are called, the value of i is 3 (the length of the array and then it increments). The number 3 was added to the uniqueID to create 103 for ALL the celebritiesID. So every position in the returned array get id = 103, instead of the intended 100, 101, 102.

Question: Can anyone explain to me why the value of stallonID is 103 instead of 100? I am lost at "The number 3 was added to the uniqueID to create 103 for ALL the celebritiesID.".

Thanks!

答:
As you see here actionCelebs array every object element id refers to the closure function, which has not been run yet, untill you access the actionCelebs[1]['id'] like this,

when that closure get run, you know closer has access to outer function variable by reference that means if inside a closure a referenced outer function variable changes,it changes in the outer function too.

In your codecelebrityIDCreator() runs the for loop, i from 0 - 3, and your closure function not getting executed,

so after the celebrityIDCreator() finishes, inside the celebrityIDCreator() scope the value i = 3,

so when you finally acces createIdForActionCelebs[0]['id'] the closure function gets run and in this line return uniqueID + i finds i's value 3 everytime from outer function scope, that's why your id is always 103

Body:
I am trying to grasp the concept of closure in javascript and come across the following codes on http://javascriptissexy.com:

// This example is explained in detail below (just after this code box).
function celebrityIDCreator (theCelebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
  theCelebrities[i]["id"] = function ()  {
    return uniqueID + i;
  }
 }

 return theCelebrities;
}

var actionCelebs = [{name:"Stallone", id:0}, {name:"Cruise", id:0}, {name:"Willis", id:0}];

var createIdForActionCelebs = celebrityIDCreator (actionCelebs);

var stalloneID = createIdForActionCelebs[0];console.log(stalloneID.id());//103

In the preceding example, by the time the anonymous functions are called, the value of i is 3 (the length of the array and then it increments). The number 3 was added to the uniqueID to create 103 for ALL the celebritiesID. So every position in the returned array get id = 103, instead of the intended 100, 101, 102.

Question: Can anyone explain to me why the value of stallonID is 103 instead of 100? I am lost at "The number 3 was added to the uniqueID to create 103 for ALL the celebritiesID.".

Thanks!


问:
Calling ExifInterface in a loop causing java.lang.StackOverflowError
I'm working on something that needs to call ExifInterface for all camera images to get images location and time, It's working fine for most of the devices but it causing java.lang.StackOverflowError in some devices like Redmi 3S.

What I'm doing is something like this.

```<code>for (String imagePath : paths) {
      ExifInterface exif = new ExifInterface(imagePath);
      float[] latlng = new float[2];
      if(exif.getLatLong(latlng)){
        //====rest of the process happened here.
      }
 }
</code>```

this is stacktrace

```<code>Fatal Exception: java.lang.StackOverflowError: stack size 1038KB
       at java.lang.Integer.valueOf(Integer.java:742)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:1940)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readExifSegment(ExifInterface.java:1863)
       at android.media.ExifInterface.getJpegAttributes(ExifInterface.java:1662)
       at android.media.ExifInterface.loadAttributes(ExifInterface.java:1339)
       at android.media.ExifInterface.(ExifInterface.java)
       at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:148)
       at android.os.HandlerThread.run(HandlerThread.java:61)
</code>```

Any idea how can I stop this?

答:
Our app have also faced this problem, by following code:

```<code>ExifInterface exif = new ExifInterface(f.getAbsolutePath());
int exifRotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
</code>```

facebook project "fresco" also face the same issue, https://github.com/facebook/fresco/issues/1661

I think this error is device specific and image specific, image need be large to reproduce this, and happening in Android's ExifInterface itself, we cannot do much here, maybe android sdk will fix this issue someday.

I suggest only use workaround solution to overcome this issue,

```<code>public static ExifInterface get(String path) throws IOException {
    try {
        return new ExifInterface(path);
    } catch (RuntimeException | StackOverflowError ex) {
        // Internal error in Android's EXIF API.
        Log.w(FX.LOG_TAG, "Android failed to perform EXIF analysis on image: " + path + ";\n" +  ex);
        throw new IOException(ex);
   }
}
</code>```

Body:
I'm working on something that needs to call ExifInterface for all camera images to get images location and time, It's working fine for most of the devices but it causing java.lang.StackOverflowError in some devices like Redmi 3S.

What I'm doing is something like this.

for (String imagePath : paths) {
      ExifInterface exif = new ExifInterface(imagePath);
      float[] latlng = new float[2];
      if(exif.getLatLong(latlng)){
        //====rest of the process happened here.
      }
 }

this is stacktrace

Fatal Exception: java.lang.StackOverflowError: stack size 1038KB
       at java.lang.Integer.valueOf(Integer.java:742)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:1940)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2041)
       at android.media.ExifInterface.readImageFileDirectory(ExifInterface.java:2014)
       at android.media.ExifInterface.readExifSegment(ExifInterface.java:1863)
       at android.media.ExifInterface.getJpegAttributes(ExifInterface.java:1662)
       at android.media.ExifInterface.loadAttributes(ExifInterface.java:1339)
       at android.media.ExifInterface.(ExifInterface.java)
       at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:148)
       at android.os.HandlerThread.run(HandlerThread.java:61)

Any idea how can I stop this?

Body:
Our app have also faced this problem, by following code:

ExifInterface exif = new ExifInterface(f.getAbsolutePath());
int exifRotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

facebook project "fresco" also face the same issue, https://github.com/facebook/fresco/issues/1661

I think this error is device specific and image specific, image need be large to reproduce this, and happening in Android's ExifInterface itself, we cannot do much here, maybe android sdk will fix this issue someday.

I suggest only use workaround solution to overcome this issue,

public static ExifInterface get(String path) throws IOException {
    try {
        return new ExifInterface(path);
    } catch (RuntimeException | StackOverflowError ex) {
        // Internal error in Android's EXIF API.
        Log.w(FX.LOG_TAG, "Android failed to perform EXIF analysis on image: " + path + ";\n" +  ex);
        throw new IOException(ex);
   }
}


问:
Exporting hundreds of thousands of records with ColdFusion
Using ColdFusion 9.0.1, I need to export hundreds of thousands of database records to Excel XLSX or CSV (XLSX is preferred). This must be done on demand. So far I've tried using cfspreadsheet but it chokes when exporting more than a couple thousand rows in the XLSX format. However, exporting to XLS works fine (of course there is a ~65,000 row limit).

What are my options to export so many records? Theoretically the users could need to export as many as one million records. I'm also using SQL Server 2008 R2 -- is there a way to somehow export the records to a file there and then send the file through CF to the user? What options do I have? Thanks.

答: Since you are using SQL Server 2008, you could take advantage of SQL Server Reporting Services (SSRS) and create a report that can be called via web service (or HTTP GET/POST) by ColdFusion.  SSRS has the capability to export reports as Excel as well. You'll need to read up on SSRS to make this work, but it's fairly easy to do.</p>

ContentLicense: CC BY-SA 2.5


问:
python click app is failing with indication of "missing argument" but cannot locate the issue
I am creating an app with Click in python 3.6. I seem to have an error that I cannot find. I have posted my code below.

The problem is that when I type:

```<code>python clickapp.py --help
</code>```

all is good. But when I type

```<code>python clickapp.py simplerequest --help
</code>```

I get an error indicating that I am missing the argument "directory", but there is no traceback to indicate the source of the error. The exact output is:

```<code>Usage: clickapp.py [OPTIONS] STARTDATE ENDDATE DIRECTORY COMMAND [ARGS]...

Error: Missing argument "directory".
</code>```

Here is the code that I used. This is a minimal example with filename clickapp.py.

```<code>import click

@click.group()
@click.argument('startdate')
@click.argument('enddate')
@click.argument('directory', type=click.Path())
@click.pass_context
def cli(ctx,
        startdate,
        enddate,
        directory):

    ctx.obj['directory'] = directory
    ctx.obj['startdate'] = startdate
    ctx.obj['enddate'] = enddate

@click.command()
@click.argument('arg1', type=str)
@click.argument('arg2', type=click.Path(exists=True))
@click.argument('arg3', type=int)
@click.pass_context
def SimpleRequest(ctx,
                  arg1,
                  arg2,
                  arg3):

    """Simple request processor"""

    ctx.obj['arg1'] = arg1
    ctx.obj['arg2'] = arg2
    ctx.obj['arg3'] = arg3

cli.add_command(SimpleRequest)

if __name__ == '__main__':
    cli(obj={})
</code>```

Can anyone see the source of the error?

I tried a few things:

I removed the type=click.Path(exists=True) in arg2 to see if that might be causing the problem. But that did not change anything.

I also tried to remove some validation logic around inserting the variables into the ctx dictionary, but that did not help either.

答:
Your help parsing problem is that click is attempting to fill in the startdate endate directory arguments first.

So your simplerequest --help fills in the first two and then it complains that the third (directory) is missing.

Usually the command (simplerequest) would be the first argument. You could then add optional args before, since click can easily distinguish those from the command.

Or you could coerce click to see the first arg as a valid command and do the help anyways, but this is non-standard and would require some code. Also it would preclude the command name being the start date, although they are likely easily differentiated.

Body:
I am creating an app with Click in python 3.6. I seem to have an error that I cannot find. I have posted my code below.

The problem is that when I type:

python clickapp.py --help

all is good. But when I type

python clickapp.py simplerequest --help

I get an error indicating that I am missing the argument "directory", but there is no traceback to indicate the source of the error. The exact output is:

Usage: clickapp.py [OPTIONS] STARTDATE ENDDATE DIRECTORY COMMAND [ARGS]...

Error: Missing argument "directory".

Here is the code that I used. This is a minimal example with filename clickapp.py.

import click

@click.group()
@click.argument('startdate')
@click.argument('enddate')
@click.argument('directory', type=click.Path())
@click.pass_context
def cli(ctx,
        startdate,
        enddate,
        directory):

    ctx.obj['directory'] = directory
    ctx.obj['startdate'] = startdate
    ctx.obj['enddate'] = enddate

@click.command()
@click.argument('arg1', type=str)
@click.argument('arg2', type=click.Path(exists=True))
@click.argument('arg3', type=int)
@click.pass_context
def SimpleRequest(ctx,
                  arg1,
                  arg2,
                  arg3):

    """Simple request processor"""

    ctx.obj['arg1'] = arg1
    ctx.obj['arg2'] = arg2
    ctx.obj['arg3'] = arg3

cli.add_command(SimpleRequest)

if __name__ == '__main__':
    cli(obj={})

Can anyone see the source of the error?

I tried a few things:

I removed the type=click.Path(exists=True) in arg2 to see if that might be causing the problem. But that did not change anything.

I also tried to remove some validation logic around inserting the variables into the ctx dictionary, but that did not help either.


问:
Implicit resolution failure on import of implicit value with same name as method in class
The following implicit value resolution issue sneaked up on me today as demonstrated in this REPL snippet:

```<code>scala> case class X(s:String,implicit val a:Int)
defined class X

scala> class C(i:X) {
  def a:Int = 1
  def b:Int = {
    import i.a
    implicitly[Int]
  }
}
<console>:17: error: could not find implicit value for parameter e: Int
           implicitly[Int]
                                                                     ^

scala> class C(i:X) {
  def a:Int = 1
  def b:Int = {
    import i.{a=>c}
    implicitly[Int]
  }
}
defined class C
</code>```

Although the imported implicit value a shadows the method of the same name, there should be no reason why the implicit resolution fails.
Can anybody shed some light on why the import i.{a=>c} rename is necessary?

答: I'm pretty sure it's a bug, although I couldn't quickly identify an existing bug report.  It works without the rename in dotty.</p>

Body:
The following implicit value resolution issue sneaked up on me today as demonstrated in this REPL snippet:

scala> case class X(s:String,implicit val a:Int)
defined class X

scala> class C(i:X) {
  def a:Int = 1
  def b:Int = {
    import i.a
    implicitly[Int]
  }
}
<console>:17: error: could not find implicit value for parameter e: Int
           implicitly[Int]
                                                                     ^

scala> class C(i:X) {
  def a:Int = 1
  def b:Int = {
    import i.{a=>c}
    implicitly[Int]
  }
}
defined class C

Although the imported implicit value a shadows the method of the same name, there should be no reason why the implicit resolution fails.
Can anybody shed some light on why the import i.{a=>c} rename is necessary?


问:
PHP-Ews | ErrorInvalidIdMalformed: Id is malformed
I am currently working on a script fetching subjects and attachements from an email received with Exchange.

For this purpose, I have found php-ews and used one of the provided examples to retrieve the attachments.
The script throws ErrorInvalidIdMalformed: Id is malformed when I try running it.

I would have guessed I made a mistake getting the MessageID from Outlook, but it seems that there is only one field labeled "MessageID". It looks like this:
3cbab9c9ad50410592b55f7ade96a57a@[domain].fr

Is there anything I have missed ?

Thanks for helping.

答:
It looks like your confusing the EWSId with the MessageId, the EWSid is the identifier that can be used to access an Item directly see https://msdn.microsoft.com/en-us/library/office/dn605828%28v=exchg.150%29.aspx for a full discussion.

The messageId 3cbab9c9ad50410592b55f7ade96a57a@[domain].fr in your instance is the Internet MessageID which is assigned generally by the first MTA to  process the Message. You can search for a Message with this ID using EWS and the FindItem operation eg Exchange Web Service find EmailMessage by "Message-ID" header but you can't use that ID to bind to the item directly. (if you do just want an ewsId you can bind to directly use the EWSEditor https://ewseditor.codeplex.com/ to get a bindable example)


问:
Where does Xcode store .m files of a framework?
In Xcode there are many frameworks (like mkmapkit.framework).

This framework contains only .h (header) files. Where can I find the corresponding .m (implementation) files.

答: The framework classes are available as binary library files (.dylib, .a etc. for example). So .m which are implementation source files are not available. Header .h must be available as without header files compiling is not possible. </p>


问:
What does this error "Caused by: java.lang.RuntimeException: Found more than one sub-view matching holder with view: has descendant: with id:" mean?
I'm using espresso to test an Android application with a recyclerview, and I keep getting this exception.The issue happens when the method,

onView(withId(R.id.playing_recycler)).perform(scrollTo(hasDescendant(withId(R.id.header))));

is called.

The whole Error is here:

```<code>android.support.test.espresso.PerformException: Error performing 'scroll RecyclerView to: holder with view: has descendant: with id: com.refactor:id/header' on view 'with id: com.refactor:id/playing_recycler'.
at android.support.test.espresso.PerformException$Builder.build(PerformException.java:83)
at android.support.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:80)
at android.support.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:56)
at android.support.test.espresso.ViewInteraction.runSynchronouslyOnUiThread(ViewInteraction.java:184)
at android.support.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:115)
at android.support.test.espresso.ViewInteraction.perform(ViewInteraction.java:87)
at com.ui.home.nowplaying.BaseNowPlayingFragmentEspressoTest.checkNowPlayingMoreLikeThisDoesExist(BaseNowPlayingFragmentEspressoTest.java:197)
at com.ui.home.playing.LikeThisTest.testThisIsDisplayed(LikeThisTest.java:37)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at android.support.test.internal.statement.UiThreadStatement.evaluate(UiThreadStatement.java:55)
at com.test.base.DelayedFinishActivityTestRule$DelayedFinishActivityTestStatement.evaluate(DelayedFinishActivityTestRule.java:226)
at android.support.test.rule.ServiceTestRule$ServiceStatement.evaluate(ServiceTestRule.java:329)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1996)
Caused by: java.lang.RuntimeException: Found more than one sub-view matching holder with view: has descendant: with id: com.refactor:id/header

*** Matched ViewHolder item at position: 2 ***

View Hierarchy:
+>PercentRelativeLayout{id=-1, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, root-is-layout-requested=true, has-input-connection=false, x=0.0, y=0.0, child-count=1}
|
+->TypeFaceTextView{id=2131690060, res-name=more_like_this_header, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, root-is-layout-requested=true, has-input-connection=false, x=0.0, y=0.0, text=More like this, input-type=0, ime-target=false, has-links=false}
|

*** Matched ViewHolder item at position: 7 ***

View Hierarchy:
+>PercentRelativeLayout{id=-1, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, root-is-layout-requested=true, has-input-connection=false, x=0.0, y=0.0, child-count=1}
|
+->TypeFaceTextView{id=2131690060, res-name=more_like_this_header, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, root-is-layout-requested=true, has-input-connection=false, x=0.0, y=0.0, text=More like this, input-type=0, ime-target=false, has-links=false}
|

at android.support.test.espresso.contrib.RecyclerViewActions$ScrollToViewAction.perform(RecyclerViewActions.java:361)
at android.support.test.espresso.ViewInteraction$1.run(ViewInteraction.java:144)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
</code>```

答:
i had this issue and the only way i solved it was to have a custom matcher that could select only one of the views found. your errors shows that multiple views were found with the matcher so espresso cannot make a decision. try this:

```<code>public static Matcher<View> withIndex(final Matcher<View> matcher, final int index) {
        return new TypeSafeMatcher<View>() {
            int currentIndex = 0;

            @Override
            public void describeTo(Description description) {
                description.appendText("with index: ");
                description.appendValue(index);
                matcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                return matcher.matches(view) && currentIndex++ == index;
            }
        };
    }
</code>```

and then you can call it like this:

```<code> Matcher<View> matcher = allOf(withIndex(withId(R.id.myview),1));
        onView(matcher).perform(click());
</code>```

special thanks to the author of the matcher. More info here

Body:
I'm using espresso to test an Android application with a recyclerview, and I keep getting this exception.The issue happens when the method,

onView(withId(R.id.playing_recycler)).perform(scrollTo(hasDescendant(withId(R.id.header))));

is called.

The whole Error is here:

android.support.test.espresso.PerformException: Error performing 'scroll RecyclerView to: holder with view: has descendant: with id: com.refactor:id/header' on view 'with id: com.refactor:id/playing_recycler'.
at android.support.test.espresso.PerformException$Builder.build(PerformException.java:83)
at android.support.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:80)
at android.support.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:56)
at android.support.test.espresso.ViewInteraction.runSynchronouslyOnUiThread(ViewInteraction.java:184)
at android.support.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:115)
at android.support.test.espresso.ViewInteraction.perform(ViewInteraction.java:87)
at com.ui.home.nowplaying.BaseNowPlayingFragmentEspressoTest.checkNowPlayingMoreLikeThisDoesExist(BaseNowPlayingFragmentEspressoTest.java:197)
at com.ui.home.playing.LikeThisTest.testThisIsDisplayed(LikeThisTest.java:37)
at java.lang.reflect.Method.invoke(Native Method)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at android.support.test.internal.statement.UiThreadStatement.evaluate(UiThreadStatement.java:55)
at com.test.base.DelayedFinishActivityTestRule$DelayedFinishActivityTestStatement.evaluate(DelayedFinishActivityTestRule.java:226)
at android.support.test.rule.ServiceTestRule$ServiceStatement.evaluate(ServiceTestRule.java:329)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at android.support.test.internal.runner.TestExecutor.execute(TestExecutor.java:59)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:262)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1996)
Caused by: java.lang.RuntimeException: Found more than one sub-view matching holder with view: has descendant: with id: com.refactor:id/header

*** Matched ViewHolder item at position: 2 ***

View Hierarchy:
+>PercentRelativeLayout{id=-1, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, root-is-layout-requested=true, has-input-connection=false, x=0.0, y=0.0, child-count=1}
|
+->TypeFaceTextView{id=2131690060, res-name=more_like_this_header, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, root-is-layout-requested=true, has-input-connection=false, x=0.0, y=0.0, text=More like this, input-type=0, ime-target=false, has-links=false}
|

*** Matched ViewHolder item at position: 7 ***

View Hierarchy:
+>PercentRelativeLayout{id=-1, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=true, is-selected=false, root-is-layout-requested=true, has-input-connection=false, x=0.0, y=0.0, child-count=1}
|
+->TypeFaceTextView{id=2131690060, res-name=more_like_this_header, visibility=VISIBLE, width=0, height=0, has-focus=false, has-focusable=true, has-window-focus=false, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=true, is-selected=false, root-is-layout-requested=true, has-input-connection=false, x=0.0, y=0.0, text=More like this, input-type=0, ime-target=false, has-links=false}
|

at android.support.test.espresso.contrib.RecyclerViewActions$ScrollToViewAction.perform(RecyclerViewActions.java:361)
at android.support.test.espresso.ViewInteraction$1.run(ViewInteraction.java:144)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:423)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)

Body:
i had this issue and the only way i solved it was to have a custom matcher that could select only one of the views found. your errors shows that multiple views were found with the matcher so espresso cannot make a decision. try this:

public static Matcher<View> withIndex(final Matcher<View> matcher, final int index) {
        return new TypeSafeMatcher<View>() {
            int currentIndex = 0;

            @Override
            public void describeTo(Description description) {
                description.appendText("with index: ");
                description.appendValue(index);
                matcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                return matcher.matches(view) && currentIndex++ == index;
            }
        };
    }

and then you can call it like this:

 Matcher<View> matcher = allOf(withIndex(withId(R.id.myview),1));
        onView(matcher).perform(click());

special thanks to the author of the matcher. More info here


问:
Angular creating component with CLI gives encapsulation: ViewEncapsulation.None
Learning angular5. When I use CLI of Angular to create new components I get the following code:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class ExampleComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}
</code>```

However encapsulation: ViewEncapsulation.None makes the code break and put out the following error message:

I know how to fix the bug just by removing encapsulation: ViewEncapsulation.None. Is there however a way to not have this line of code in the first place?

答:
There's currently an outstanding issue that the CLI is generating ViewEncapsulation.None. This is being tracked here: https://github.com/angular/angular-cli/issues/8398

There is a PR to fix this bug as well, tracked here: https://github.com/angular/devkit/pull/270

For now, you have two options.

You can delete the line encapsulation: ViewEncapsulation.None to get rid of the error. Angular will default ViewEncapsulation.Emulated.

You can keep that line and do as Fateh mentions and add the import. This would keep the ViewEncapsulation set to None which could lead to other issues, such as styles being applied on components you don't want them to be applied to.

Body:
Learning angular5. When I use CLI of Angular to create new components I get the following code:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class ExampleComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }
}

However encapsulation: ViewEncapsulation.None makes the code break and put out the following error message:

I know how to fix the bug just by removing encapsulation: ViewEncapsulation.None. Is there however a way to not have this line of code in the first place?


问:
Update Component State (And UI) With Random Word From Array At Set Interval
I'd like to update a word in a React component every second with a random value from an array. The state seems to update at the interval just fine in DevTools, but there is a weird bug in the browser that I can't seem to pinpoint:
 the text flashes, almost as if it's "scrolling" through the old strings to the new one. Any advice on how to smooth this out would be much appreciated!

import React, { Component } from 'react';

class App extends Component {
  state = {
    name: ""
  }
  getWord = () => {
    let randomWords = ["Friend", "Enemy", "Santa"];
    const randomWord = randomWords[Math.floor(Math.random() * randomWords.length)];

    this.setState({
      name: randomWord
    });
  }

  render() {
    setInterval(this.getWord, 1000);
    return (

{this.state.name}

    );
  }
}

export default App;```

答:
You should make the getWord to do what the name implies: To get a word, return a string.. Not to set the state. To set a state in a function called getWord is misleading and would be considered a side-effect. You'll understand what I mean when you get more experienced :)

Then you should use componentDidMount to set up the timer. Something like this:

```<code>componentDidMount() {
    var _this = this;
    setInterval(function() {
        var newName = _this.getWord();
        _this .setState({name: newName });
    }, 1000);
}
</code>```

This is what react is about... You set new props or the state (either using state, or Redux or whatever) and let React to re-render.

Body:
You should make the getWord to do what the name implies: To get a word, return a string.. Not to set the state. To set a state in a function called getWord is misleading and would be considered a side-effect. You'll understand what I mean when you get more experienced :)

Then you should use componentDidMount to set up the timer. Something like this:

componentDidMount() {
    var _this = this;
    setInterval(function() {
        var newName = _this.getWord();
        _this .setState({name: newName });
    }, 1000);
}

This is what react is about... You set new props or the state (either using state, or Redux or whatever) and let React to re-render.


问:
How to remove top margin BODY
I got this set up

```<code>.image-head {
    background-image:url(http://placehold.it/1920x1080);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: top center;
    height: 1000px;
    width: 100%;
    margin: 0;
    padding: 0;
    color: black;
    #text-align: center;
}

body {
    margin: 0;
    padding: 0;
}
</code>```

Here is my code in full.

How do I remove the top margin?

答:
```<code>.media_bar {
    margin-top: 0;
}
</code>```

Fiddle: https://jsfiddle.net/rjyhrn8b/1/

Title: How to remove top margin BODY

Body:
I got this set up

.image-head {
    background-image:url(http://placehold.it/1920x1080);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: top center;
    height: 1000px;
    width: 100%;
    margin: 0;
    padding: 0;
    color: black;
    #text-align: center;
}

body {
    margin: 0;
    padding: 0;
}

Here is my code in full.

How do I remove the top margin?

Body:
.media_bar {
    margin-top: 0;
}

Fiddle: https://jsfiddle.net/rjyhrn8b/1/


问:
ActiveRecord: Counting associations
I have two tables with a has_one <--> belongs_to relationship: 'user' and 'account'. (An account must have a user, but a user need not have any accounts).

What I'd like to do is return all users who have no accounts...and I'm having a little trouble doing it gracefully. Is there a simple way to do this?

Many thanks...

答:
You have to join the accounts table into the users table then check for an empty account. In Rails 3, you can do it like this:

```<code>User.includes(:account).where('accounts.id' => nil).all
</code>```

In Rails 2, you can do it like this:

```<code>User.find(:all, :include => [ :account ], :conditions => { 'accounts.id' => nil })
</code>```

Title: ActiveRecord: Counting associations

Body:
You have to join the accounts table into the users table then check for an empty account. In Rails 3, you can do it like this:

User.includes(:account).where('accounts.id' => nil).all

In Rails 2, you can do it like this:

User.find(:all, :include => [ :account ], :conditions => { 'accounts.id' => nil })


问:
Python - recursive function call with changing variable value
I'm trying to create a function that uses the Monte Carlo approximation method to calculate the value of pi to the given precision (number of decimal places). I was trying to do this by comparing the approximated value to the literal value of pi and if they don't match, recursively calling the function on itself to try again with a greater number of trials.
This is what I have so far:

```<code>def estimate_pi(precision):

     x = 1

     N_tot = 0
     N_hits = 0

     for i in range(0,trials*10**x):
         if(inside_circle(random.random(),random.random())==True):
             N_hits = N_hits+1
             N_tot = N_tot+1
         else:
             N_tot = N_tot+1

     result = 4.0*N_hits/N_tot

     if compare_to_pi(result,precision)==True:
         print(result)
     else:
         x++
         estimate_pi(precision)

         if trials>999999:
             raise Error('approximation not converging to given precision')
             print(result)
</code>```

I'm having trouble because the variable x, which is supposed to control the number of trials for approximation, gets initialised to 1 every time the function is called. I have no idea what to do, please help!

答:
You need a helper method for this recursive sequence. This is your current method

```<code>def estimate_pi(precision):

     x = 1

     N_tot = 0
     N_hits = 0

     for i in range(0,trials*10**x):
         if(inside_circle(random.random(),random.random())==True):
             N_hits = N_hits+1
             N_tot = N_tot+1
         else:
             N_tot = N_tot+1

     result = 4.0*N_hits/N_tot

     if compare_to_pi(result,precision)==True:
         print(result)
     else:
         x++
         estimate_pi(precision)

         if trials>999999:
             raise Error('approximation not converging to given precision')
             print(result)
</code>```

I'll replace this with

```<code>def estimate_pi(precision):
 x = 1

 N_tot = 0
 N_hits = 0

 for i in range(0,trials*10**x):
     if(inside_circle(random.random(),random.random())==True):
         N_hits = N_hits+1
         N_tot = N_tot+1
     else:
         N_tot = N_tot+1

 result = 4.0*N_hits/N_tot

 if compare_to_pi(result,precision)==True:
     print(result)
 else:
     x++
     estimate_pi_helper(precision, 2) #we are on our second trial

def estimate_pi_helper(precision,trials, N_tot, N_hits):
    if trials>999999: #if we reach our 1000000'th trial we throw an error
         raise Error('approximation not converging to given precision')
         print(result)

 for i in range(0,trials*10**x):
     if(inside_circle(random.random(),random.random())==True):
         N_hits = N_hits+1
         N_tot = N_tot+1
     else:
         N_tot = N_tot+1

 result = 4.0*N_hits/N_tot

 if compare_to_pi(result,precision)==True:
     print(result)
 else:
     x++
     estimate_pi_helper(precision,trials+1, N_tot, N_hits)
</code>```

I fixed your x to be your trials. I also added a helper method that takes trials as a parameter to keep a running count. Finally, your hits and totals are passed in to keep a running count, I Was under the impression that this is how a Monte Carlo simulation is done although I'm probably wrong. If you need a new set of hits and total on each run then please change it accordingly.

Sorry for the indentation issues. IDE should fix it easily

Body:
I'm trying to create a function that uses the Monte Carlo approximation method to calculate the value of pi to the given precision (number of decimal places). I was trying to do this by comparing the approximated value to the literal value of pi and if they don't match, recursively calling the function on itself to try again with a greater number of trials.
This is what I have so far:

def estimate_pi(precision):

     x = 1

     N_tot = 0
     N_hits = 0

     for i in range(0,trials*10**x):
         if(inside_circle(random.random(),random.random())==True):
             N_hits = N_hits+1
             N_tot = N_tot+1
         else:
             N_tot = N_tot+1

     result = 4.0*N_hits/N_tot

     if compare_to_pi(result,precision)==True:
         print(result)
     else:
         x++
         estimate_pi(precision)

         if trials>999999:
             raise Error('approximation not converging to given precision')
             print(result)

I'm having trouble because the variable x, which is supposed to control the number of trials for approximation, gets initialised to 1 every time the function is called. I have no idea what to do, please help!

Body:
You need a helper method for this recursive sequence. This is your current method

def estimate_pi(precision):

     x = 1

     N_tot = 0
     N_hits = 0

     for i in range(0,trials*10**x):
         if(inside_circle(random.random(),random.random())==True):
             N_hits = N_hits+1
             N_tot = N_tot+1
         else:
             N_tot = N_tot+1

     result = 4.0*N_hits/N_tot

     if compare_to_pi(result,precision)==True:
         print(result)
     else:
         x++
         estimate_pi(precision)

         if trials>999999:
             raise Error('approximation not converging to given precision')
             print(result)

I'll replace this with

def estimate_pi(precision):
 x = 1

 N_tot = 0
 N_hits = 0

 for i in range(0,trials*10**x):
     if(inside_circle(random.random(),random.random())==True):
         N_hits = N_hits+1
         N_tot = N_tot+1
     else:
         N_tot = N_tot+1

 result = 4.0*N_hits/N_tot

 if compare_to_pi(result,precision)==True:
     print(result)
 else:
     x++
     estimate_pi_helper(precision, 2) #we are on our second trial

def estimate_pi_helper(precision,trials, N_tot, N_hits):
    if trials>999999: #if we reach our 1000000'th trial we throw an error
         raise Error('approximation not converging to given precision')
         print(result)

 for i in range(0,trials*10**x):
     if(inside_circle(random.random(),random.random())==True):
         N_hits = N_hits+1
         N_tot = N_tot+1
     else:
         N_tot = N_tot+1

 result = 4.0*N_hits/N_tot

 if compare_to_pi(result,precision)==True:
     print(result)
 else:
     x++
     estimate_pi_helper(precision,trials+1, N_tot, N_hits)

I fixed your x to be your trials. I also added a helper method that takes trials as a parameter to keep a running count. Finally, your hits and totals are passed in to keep a running count, I Was under the impression that this is how a Monte Carlo simulation is done although I'm probably wrong. If you need a new set of hits and total on each run then please change it accordingly.

Sorry for the indentation issues. IDE should fix it easily


问:
Backward Scheduling to Exclude Holidays
I have the backward scheduling in my system. i used function shown below to  exclude weekend or push the date back to Friday if backward scheduling laid on the weekend but how can exclude holidays?. for example i want to push any date on 23th and 24th of Nov 2017 after the holiday or 28th .

here is the code i used to skip the weekends

```<code>Create function [dbo].[PreviousWorkDay]( @date date ) returns date as
begin
  set @date = dateadd( day, -1, @date )
  return
  (
    select case datepart( weekday, @date )
      when 7 then dateadd( day, -1, @date )
      when 1 then dateadd( day, -2, @date )
      else @date
    end
  )
end
</code>```

答:
In order to achieve this, you would have to do a couple things.

1) Create infrastructure to list out what dates are considered holidays. This is necessary for two reasons, A) some holidays move days every year (e.g. Thanksgiving), B) what holidays are not work days depends on the organization.

2) Just like HABO said, remove your dependence on the datepart/weekday as someone could change this setting on your instance and your existing logic would go haywire.

Holiday Infrastructure

```<code>create table dbo.holidays
    (
        holiday_dt date not null
    )

insert into dbo.holidays
values ('2017-11-23') --Thanksgiving (moves every year)
    , ('2017-12-25') --Christmas (same day every year)
</code>```

Answer

```<code>create function [dbo].[PreviousWorkDay]( @date date ) returns date as
begin

    declare @date_rng int = 7 --dont think there would ever be 7 holiday/weekend days in a row
        , @ans date;

    with date_list as
        (
            --use a Recursive CTE to generate a list of recent dates (assuming there is no table w/ each calendar day listed)
            select dateadd(d, -1*@date_rng, @date) as dt
            union all
            select dateadd(d,1,dt) as dt
            from date_list
            where 1=1
            and dt < @date
        )
    select @ans = max(sub.dt)
    from (
        select dl.dt
        , case when datename(dw, dl.dt) in ('Saturday', 'Sunday') then 0
               when h.holiday_dt is not null then 0
               else 1
          end as is_work_day
        from date_list as dl
        left join dbo.holidays as h on dl.dt = h.holiday_dt
        ) as sub
    where 1=1
    and sub.is_work_day = 1

    return @ans;

end

go
</code>```

Example

This function call

```<code>  select dbo.PreviousWorkDay('2017-12-25')
</code>```

would return 2017-12-22.

Title: Backward Scheduling to Exclude Holidays

Body:
I have the backward scheduling in my system. i used function shown below to  exclude weekend or push the date back to Friday if backward scheduling laid on the weekend but how can exclude holidays?. for example i want to push any date on 23th and 24th of Nov 2017 after the holiday or 28th .

here is the code i used to skip the weekends

Create function [dbo].[PreviousWorkDay]( @date date ) returns date as
begin
  set @date = dateadd( day, -1, @date )
  return
  (
    select case datepart( weekday, @date )
      when 7 then dateadd( day, -1, @date )
      when 1 then dateadd( day, -2, @date )
      else @date
    end
  )
end

Body:
In order to achieve this, you would have to do a couple things.

1) Create infrastructure to list out what dates are considered holidays. This is necessary for two reasons, A) some holidays move days every year (e.g. Thanksgiving), B) what holidays are not work days depends on the organization.

2) Just like HABO said, remove your dependence on the datepart/weekday as someone could change this setting on your instance and your existing logic would go haywire.

Holiday Infrastructure

create table dbo.holidays
    (
        holiday_dt date not null
    )

insert into dbo.holidays
values ('2017-11-23') --Thanksgiving (moves every year)
    , ('2017-12-25') --Christmas (same day every year)

Answer

create function [dbo].[PreviousWorkDay]( @date date ) returns date as
begin

    declare @date_rng int = 7 --dont think there would ever be 7 holiday/weekend days in a row
        , @ans date;

    with date_list as
        (
            --use a Recursive CTE to generate a list of recent dates (assuming there is no table w/ each calendar day listed)
            select dateadd(d, -1*@date_rng, @date) as dt
            union all
            select dateadd(d,1,dt) as dt
            from date_list
            where 1=1
            and dt < @date
        )
    select @ans = max(sub.dt)
    from (
        select dl.dt
        , case when datename(dw, dl.dt) in ('Saturday', 'Sunday') then 0
               when h.holiday_dt is not null then 0
               else 1
          end as is_work_day
        from date_list as dl
        left join dbo.holidays as h on dl.dt = h.holiday_dt
        ) as sub
    where 1=1
    and sub.is_work_day = 1

    return @ans;

end

go

Example

This function call

  select dbo.PreviousWorkDay('2017-12-25')

would return 2017-12-22.


问:
Why am I getting “IndentationError: expected an indented block”?
```<code>#!/usr/bin/python

# Import der Python libraries

import RPi.GPIO as GPIO

import time

import datetime

import subprocess

# Verwendung des Board Mode, Angabe der PIN Nummern anstelle der GPIO BCM Nummer

GPIO.setmode(GPIO.BOARD)

# GPIO definieren, bei mir ist es PIN 8

GPIO_PIR = 8

#  GPIO als "Input" festlegen

GPIO.setup(GPIO_PIR,GPIO.IN)

Current_State  = 0

Previous_State = 0

try:

# erst mal schlafen bis der bootvorgang abgeschlossen ist

time.sleep(60)

# Warten bis Sensor sich meldet

while GPIO.input(GPIO_PIR)==1:

  Current_State  = 0

subprocess.Popen('echo initilized PIR | wall', shell=True)

# Schleife bis CTRL+C

while True :

  #Status von Sensor auslesen

  Current_State = GPIO.input(GPIO_PIR)

  if Current_State==1 and Previous_State==0:

    # Kommando zum anschalten, Frambuffer erneuern

    subprocess.Popen('echo Monitor on | wall', shell=True)

    subprocess.Popen('/opt/vc/bin/tvservice -p', shell=True)

    subprocess.Popen('fbset -depth 8', shell=True)

    subprocess.Popen('fbset -depth 16', shell=True)

    subprocess.Popen('sudo /bin/chvt 6 && sudo /bin/chvt 7', shell=True)

    Previous_State=1

  elif Current_State==0 and Previous_State==1:

    # Ausschalten des Monitors

    subprocess.Popen('echo Monitor off | wall', shell=True)

    subprocess.Popen('/opt/vc/bin/tvservice -o', shell=True)

    Previous_State=0

  # 5 Sek Warten

  time.sleep(5)

except KeyboardInterrupt:

print " Exit"

GPIO.cleanup()
</code>```

Hello,
i am getting:

```<code>File "PIR.py", line 30
  time.sleep(60)
     ^
IndentationError: expected an indented block
</code>```

Can you help me?
when i set a tab before "time.sleep" it Comes a Syntax error in the line "while GPIO.input(GPIO_PIR)==1:".
I use this script to manage a PIR sensor for the Magic mirror but it wont work. So i wrote in the terminal "python PIR.py". After that i recognize the error, it is logic that the PIR sensor wont work. But I am a noob in python, so I would like to have your help.

答:
A block is a group of statements in a program or script. Usually it consists of at least one statement and of declarations for the block, depending on the programming or scripting language. A language, which allows grouping with blocks, is called a block structured language. Python is such a language. There are a lot of documentation and tutorials that will tell you why. Here is a start: https://www.python-course.eu/python3_blocks.php

Your code miss some of these block structures when you are required to use them, for example with try: and else:. Other examples you see this is while True: and if - else statements.

```<code>#!/usr/bin/python
# Import der Python libraries
import RPi.GPIO as GPIO
import time
import datetime
import subprocess

# Verwendung des Board Mode, Angabe der PIN Nummern anstelle der GPIO BCM Nummer
GPIO.setmode(GPIO.BOARD)
# GPIO definieren, bei mir ist es PIN 8
GPIO_PIR = 8
#  GPIO als "Input" festlegen
GPIO.setup(GPIO_PIR,GPIO.IN)
Current_State  = 0
Previous_State = 0
try:
  # erst mal schlafen bis der bootvorgang abgeschlossen ist
  time.sleep(60)
  # Warten bis Sensor sich meldet
  while GPIO.input(GPIO_PIR)==1:
    Current_State  = 0
  subprocess.Popen('echo initilized PIR | wall', shell=True)
  # Schleife bis CTRL+C
  while True :
    #Status von Sensor auslesen
    Current_State = GPIO.input(GPIO_PIR)
    if Current_State==1 and Previous_State==0:
      # Kommando zum anschalten, Frambuffer erneuern
      subprocess.Popen('echo Monitor on | wall', shell=True)
      subprocess.Popen('/opt/vc/bin/tvservice -p', shell=True)
      subprocess.Popen('fbset -depth 8', shell=True)
      subprocess.Popen('fbset -depth 16', shell=True)
      subprocess.Popen('sudo /bin/chvt 6 && sudo /bin/chvt 7', shell=True)
      Previous_State=1
    elif Current_State==0 and Previous_State==1:
      # Ausschalten des Monitors
      subprocess.Popen('echo Monitor off | wall', shell=True)
      subprocess.Popen('/opt/vc/bin/tvservice -o', shell=True)
      Previous_State=0
    # 5 Sek Warten
    time.sleep(5)
except KeyboardInterrupt:
  print " Exit"
  GPIO.cleanup()
</code>```

Body:
#!/usr/bin/python

# Import der Python libraries

import RPi.GPIO as GPIO

import time

import datetime

import subprocess

# Verwendung des Board Mode, Angabe der PIN Nummern anstelle der GPIO BCM Nummer

GPIO.setmode(GPIO.BOARD)

# GPIO definieren, bei mir ist es PIN 8

GPIO_PIR = 8

#  GPIO als "Input" festlegen

GPIO.setup(GPIO_PIR,GPIO.IN)

Current_State  = 0

Previous_State = 0

try:

# erst mal schlafen bis der bootvorgang abgeschlossen ist

time.sleep(60)

# Warten bis Sensor sich meldet

while GPIO.input(GPIO_PIR)==1:

  Current_State  = 0

subprocess.Popen('echo initilized PIR | wall', shell=True)

# Schleife bis CTRL+C

while True :

  #Status von Sensor auslesen

  Current_State = GPIO.input(GPIO_PIR)

  if Current_State==1 and Previous_State==0:

    # Kommando zum anschalten, Frambuffer erneuern

    subprocess.Popen('echo Monitor on | wall', shell=True)

    subprocess.Popen('/opt/vc/bin/tvservice -p', shell=True)

    subprocess.Popen('fbset -depth 8', shell=True)

    subprocess.Popen('fbset -depth 16', shell=True)

    subprocess.Popen('sudo /bin/chvt 6 && sudo /bin/chvt 7', shell=True)

    Previous_State=1

  elif Current_State==0 and Previous_State==1:

    # Ausschalten des Monitors

    subprocess.Popen('echo Monitor off | wall', shell=True)

    subprocess.Popen('/opt/vc/bin/tvservice -o', shell=True)

    Previous_State=0

  # 5 Sek Warten

  time.sleep(5)

except KeyboardInterrupt:

print " Exit"

GPIO.cleanup()

Hello,
i am getting:

File "PIR.py", line 30
  time.sleep(60)
     ^
IndentationError: expected an indented block

Can you help me?
when i set a tab before "time.sleep" it Comes a Syntax error in the line "while GPIO.input(GPIO_PIR)==1:".
I use this script to manage a PIR sensor for the Magic mirror but it wont work. So i wrote in the terminal "python PIR.py". After that i recognize the error, it is logic that the PIR sensor wont work. But I am a noob in python, so I would like to have your help.

Body:
A block is a group of statements in a program or script. Usually it consists of at least one statement and of declarations for the block, depending on the programming or scripting language. A language, which allows grouping with blocks, is called a block structured language. Python is such a language. There are a lot of documentation and tutorials that will tell you why. Here is a start: https://www.python-course.eu/python3_blocks.php

Your code miss some of these block structures when you are required to use them, for example with try: and else:. Other examples you see this is while True: and if - else statements.

#!/usr/bin/python
# Import der Python libraries
import RPi.GPIO as GPIO
import time
import datetime
import subprocess

# Verwendung des Board Mode, Angabe der PIN Nummern anstelle der GPIO BCM Nummer
GPIO.setmode(GPIO.BOARD)
# GPIO definieren, bei mir ist es PIN 8
GPIO_PIR = 8
#  GPIO als "Input" festlegen
GPIO.setup(GPIO_PIR,GPIO.IN)
Current_State  = 0
Previous_State = 0
try:
  # erst mal schlafen bis der bootvorgang abgeschlossen ist
  time.sleep(60)
  # Warten bis Sensor sich meldet
  while GPIO.input(GPIO_PIR)==1:
    Current_State  = 0
  subprocess.Popen('echo initilized PIR | wall', shell=True)
  # Schleife bis CTRL+C
  while True :
    #Status von Sensor auslesen
    Current_State = GPIO.input(GPIO_PIR)
    if Current_State==1 and Previous_State==0:
      # Kommando zum anschalten, Frambuffer erneuern
      subprocess.Popen('echo Monitor on | wall', shell=True)
      subprocess.Popen('/opt/vc/bin/tvservice -p', shell=True)
      subprocess.Popen('fbset -depth 8', shell=True)
      subprocess.Popen('fbset -depth 16', shell=True)
      subprocess.Popen('sudo /bin/chvt 6 && sudo /bin/chvt 7', shell=True)
      Previous_State=1
    elif Current_State==0 and Previous_State==1:
      # Ausschalten des Monitors
      subprocess.Popen('echo Monitor off | wall', shell=True)
      subprocess.Popen('/opt/vc/bin/tvservice -o', shell=True)
      Previous_State=0
    # 5 Sek Warten
    time.sleep(5)
except KeyboardInterrupt:
  print " Exit"
  GPIO.cleanup()