问:
Obtaining motion vectors from raw video
I'd like to know if there is any good (and freely available) text, on how to obtain motion vectors of macro blocks in raw video stream. This is often used in video compression, although my application of it is not video encoding.

Code that does this is available in OSS codecs, but understanding the method by reading the code is kinda hard.

My actual goal is to determine camera motion in 2D projection space, assuming the camera is only changing it's orientation (NOT the position). What I'd like to do is divide the frames into macro blocks, obtain their motion vectors, and get the camera motion by averaging those vectors.

I guess OpenCV could help with this problem, but it's not available on my target platform.

答: If you assume only camera motion, I suspect there is something possible with analysis of the FFT of successive images. For frequencies whose amplitudes have not changed much, the phase information will indicate the camera motion. Not sure if this will help with camera rotation, but lateral and vertical motion can probably be computed. There will be difficulties due to new information appearing on one edge and disappearing on the other and I'm not sure how much that will hurt. This is speculative thinking in response to your question, so I have no proof or references :-)</p>

Title: Obtaining motion vectors from raw video


来源: stackexchange

问:
VBA Why is my loop stuck on the first item, after I ensure it doesn't meet criteria
I am currently using a for loop that goes through two ranges of data - if it sees that a cell in the first row has the word "Rejected" and that the second row is empty it is meant to fill that cell with pending, then spawn an email before exiting the sub.

Once you start the loop again it is is meant to find the next row that meets these arguments. However it only goes to the first one again.

I tried to negate this by making sure it fills that cell with 'pending' - meaning it is no longer empty, and yet it still only goes to there.

Here's the code:

```<code>Dim i As Long 'Defining i, which will be used to loop through the ranges.

For i = 6 To 50000 'Setting the ranges -
    If Range("M" & i) = "Rejected" And Range("N" & i) = "" Then 'Searches through the ranges first job that the partner has rejected - and then checks as to whether the partner has issued their assessment.
        Range("O" & i) = "'Pending" 'Changes the first one that has been  to 'Pending' so it won't be picked up the next time the code is run.
        GoTo Email
    End If
Next
</code>```

I'm not really sure how else to go about it. I need the sub to stop once it's done an email else it could loop and create hundreds at a time which not only would overload the system, by would inundate my inbox.

Ps, not sure why my code is formatting weirdly - sorry

答:
The thing is that you are using a GoTo and does what is supposed to do, Go to... your Mail label. Once there it will continue the code down, never will go up, is like skipping the loop. Instead you can put your email code into another procedure and call it when necessary, that way the loop will continue:

```<code>Option Explicit
Sub Test()

    Dim C As Range 'this will loop through the range
    Dim LastRow As Long 'this will find the last row

    With ThisWorkbook.Sheets("MySheetName") 'change MySheetName
        LastRow = .Cells(.Rows.Count, "M").End(xlUp).Row 'last row with data on column M
        For Each C In .Range("M6:M" & LastRow) 'loop through M6 to M & last row
            If C = "Rejected" And .Cells(C.Row, "N") = vbNullString And Not .Cells(C.Row, "O") = "'Pending" Then 'vbnullstring has better performance than ""
                .Cells(C.Row, "O") = "'Pending"
                Mail C.Row
            End If
        Next C
    End With

End Sub
Sub Mail(MailRow As Long)

    'Code doing your mail

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am currently using a for loop that goes through two ranges of data - if it sees that a cell in the first row has the word "Rejected" and that the second row is empty it is meant to fill that cell with pending, then spawn an email before exiting the sub.

Once you start the loop again it is is meant to find the next row that meets these arguments. However it only goes to the first one again.

I tried to negate this by making sure it fills that cell with 'pending' - meaning it is no longer empty, and yet it still only goes to there.

Here's the code:

Dim i As Long 'Defining i, which will be used to loop through the ranges.

For i = 6 To 50000 'Setting the ranges -
    If Range("M" & i) = "Rejected" And Range("N" & i) = "" Then 'Searches through the ranges first job that the partner has rejected - and then checks as to whether the partner has issued their assessment.
        Range("O" & i) = "'Pending" 'Changes the first one that has been  to 'Pending' so it won't be picked up the next time the code is run.
        GoTo Email
    End If
Next

I'm not really sure how else to go about it. I need the sub to stop once it's done an email else it could loop and create hundreds at a time which not only would overload the system, by would inundate my inbox.

Ps, not sure why my code is formatting weirdly - sorry

Body:
The thing is that you are using a GoTo and does what is supposed to do, Go to... your Mail label. Once there it will continue the code down, never will go up, is like skipping the loop. Instead you can put your email code into another procedure and call it when necessary, that way the loop will continue:

Option Explicit
Sub Test()

    Dim C As Range 'this will loop through the range
    Dim LastRow As Long 'this will find the last row

    With ThisWorkbook.Sheets("MySheetName") 'change MySheetName
        LastRow = .Cells(.Rows.Count, "M").End(xlUp).Row 'last row with data on column M
        For Each C In .Range("M6:M" & LastRow) 'loop through M6 to M & last row
            If C = "Rejected" And .Cells(C.Row, "N") = vbNullString And Not .Cells(C.Row, "O") = "'Pending" Then 'vbnullstring has better performance than ""
                .Cells(C.Row, "O") = "'Pending"
                Mail C.Row
            End If
        Next C
    End With

End Sub
Sub Mail(MailRow As Long)

    'Code doing your mail

End Sub


问:
PHP Laravel sending mail returns validation error and empty fields
I'm building a laravel-app and when I try to send a mail I get a validation error which I cannot localize.

My form looks like this:

```<code><form method="POST" action="{{ route('help') }}">
   <input type="hidden" name="job" value="{{ $job->id }}">
    @csrf
   <input type="text" placeholder="Name" name="name" required>
   <input type="email" placeholder="Email" name="email" required>
   <input type="tel" pattern="^[0-9-+s()]*$" placeholder="Phonenr." name="phone" required>
   <button type="submit">Send</button>
</form>
</code>```

and my controller I have this:

```<code>use Validator;
use App\Mail\HelpMail;

class HelpController extends Controller {

   public function __invoke(Request $request) {
      $validator = Validator::make($request->all(), [
        'name' => ['required', 'string'],
        'email' => ['required', 'email'],
        'phone' => ['required'],
        'job' => ['required', 'integer', 'exists:jobs,id'],
      ]);

      ...
   }
}
</code>```

Then in my HelpMail

```<code>class HelpMail {
   use Queueable, SerializesModels;

   public $job;
   public $name;
   public $email;
   public $phone;

   public function __construct($data) {
     $this->job = $data['job'];
     $this->name = $data['name'];
     $this->email = $data['email'];
     $this->phone = $data['phone'];
   }

}
</code>```

This returns an error like: name must be filled out, email must be filled out and phone must be filled out.
When I comment out the validation, the mail goes through, but then the fields/payload is empty, and I have absolutely no clue why this happens, since I use the same method on my contact form.

What am I missing?

答:
So in your case using the facade you will have to manually handle if any errors:

```<code>$validator = Validator::make($request->all(), [
        'name' => ['required', 'string'],
        'email' => ['required', 'email'],
        'phone' => ['required'],
        'job' => ['required', 'integer', 'exists:jobs,id'],
      ]);

if ($validator->fails()) {
    // either with view, or use response()->json($validator->errors);
    return view('view_name')->withErrors($validator->errors);
} else {
    return view('view_name');
}
</code>```

You can instead use the validation on the request object, which will return back to the view with the errors message bag in it:

```<code>public function __invoke(Request $request) {
      $request->validate([
        'name' => ['required', 'string'],
        'email' => ['required', 'email'],
        'phone' => ['required'],
        'job' => ['required', 'integer', 'exists:jobs,id'],
      ]);

      ...
}
</code>```

Body:
I'm building a laravel-app and when I try to send a mail I get a validation error which I cannot localize.

My form looks like this:

<form method="POST" action="{{ route('help') }}">
   <input type="hidden" name="job" value="{{ $job->id }}">
    @csrf
   <input type="text" placeholder="Name" name="name" required>
   <input type="email" placeholder="Email" name="email" required>
   <input type="tel" pattern="^[0-9-+s()]*$" placeholder="Phonenr." name="phone" required>
   <button type="submit">Send</button>
</form>

and my controller I have this:

use Validator;
use App\Mail\HelpMail;

class HelpController extends Controller {

   public function __invoke(Request $request) {
      $validator = Validator::make($request->all(), [
        'name' => ['required', 'string'],
        'email' => ['required', 'email'],
        'phone' => ['required'],
        'job' => ['required', 'integer', 'exists:jobs,id'],
      ]);

      ...
   }
}

Then in my HelpMail

class HelpMail {
   use Queueable, SerializesModels;

   public $job;
   public $name;
   public $email;
   public $phone;

   public function __construct($data) {
     $this->job = $data['job'];
     $this->name = $data['name'];
     $this->email = $data['email'];
     $this->phone = $data['phone'];
   }

}

This returns an error like: name must be filled out, email must be filled out and phone must be filled out.
When I comment out the validation, the mail goes through, but then the fields/payload is empty, and I have absolutely no clue why this happens, since I use the same method on my contact form.

What am I missing?

Body:
So in your case using the facade you will have to manually handle if any errors:

$validator = Validator::make($request->all(), [
        'name' => ['required', 'string'],
        'email' => ['required', 'email'],
        'phone' => ['required'],
        'job' => ['required', 'integer', 'exists:jobs,id'],
      ]);

if ($validator->fails()) {
    // either with view, or use response()->json($validator->errors);
    return view('view_name')->withErrors($validator->errors);
} else {
    return view('view_name');
}

You can instead use the validation on the request object, which will return back to the view with the errors message bag in it:

public function __invoke(Request $request) {
      $request->validate([
        'name' => ['required', 'string'],
        'email' => ['required', 'email'],
        'phone' => ['required'],
        'job' => ['required', 'integer', 'exists:jobs,id'],
      ]);

      ...
}


问:
Log4j2 could not find a logging implementation with Spring Boot
I'm getting this error trying to use log4j2 with spring boot.

```<code>ERROR StatusLogger Log4j2 could not find a logging implementation.
Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
</code>```

I'm have followed this guide: http://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html#howto-configure-log4j-for-logging - and also added the two log4j2-dependencies from https://logging.apache.org/log4j/2.x/maven-artifacts.html

My dependency:tree looks like this:

```<code>[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @  musikkjulekalender ---
[INFO] no.saiboten:musikkjulekalender:war:1.0-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.hibernate:hibernate-validator:jar:5.2.4.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.3.1:compile
[INFO] |  +- org.springframework:spring-web:jar:4.3.2.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:4.3.2.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-jetty:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.eclipse.jetty:jetty-servlets:jar:9.3.11.v20160721:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-continuation:jar:9.3.11.v20160721:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-http:jar:9.3.11.v20160721:compile
[INFO] |  |  \- org.eclipse.jetty:jetty-io:jar:9.3.11.v20160721:compile
[INFO] |  +- org.eclipse.jetty:jetty-webapp:jar:9.3.11.v20160721:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-xml:jar:9.3.11.v20160721:compile
[INFO] |  |  \- org.eclipse.jetty:jetty-servlet:jar:9.3.11.v20160721:compile
[INFO] |  |     \- org.eclipse.jetty:jetty-security:jar:9.3.11.v20160721:compile
[INFO] |  +- org.eclipse.jetty.websocket:websocket-server:jar:9.3.11.v20160721:compile
[INFO] |  |  +- org.eclipse.jetty.websocket:websocket-common:jar:9.3.11.v20160721:compile
[INFO] |  |  |  \- org.eclipse.jetty.websocket:websocket-api:jar:9.3.11.v20160721:compile
[INFO] |  |  +- org.eclipse.jetty.websocket:websocket-client:jar:9.3.11.v20160721:compile
[INFO] |  |  \- org.eclipse.jetty.websocket:websocket-servlet:jar:9.3.11.v20160721:compile
[INFO] |  \- org.eclipse.jetty.websocket:javax-websocket-server-impl:jar:9.3.11.v20160721:compile
[INFO] |     +- org.eclipse.jetty:jetty-annotations:jar:9.3.11.v20160721:compile
[INFO] |     |  +- org.eclipse.jetty:jetty-plus:jar:9.3.11.v20160721:compile
[INFO] |     |  +- javax.annotation:javax.annotation-api:jar:1.2:compile
[INFO] |     |  +- org.ow2.asm:asm:jar:5.0.1:compile
[INFO] |     |  \- org.ow2.asm:asm-commons:jar:5.0.1:compile
[INFO] |     |     \- org.ow2.asm:asm-tree:jar:5.0.1:compile
[INFO] |     +- org.eclipse.jetty.websocket:javax-websocket-client-impl:jar:9.3.11.v20160721:compile
[INFO] |     \- javax.websocket:javax.websocket-api:jar:1.0:compile
[INFO] +- org.springframework.boot:spring-boot-starter-data-jpa:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-aop:jar:1.4.0.RELEASE:compile
[INFO] |  |  \- org.aspectj:aspectjweaver:jar:1.8.9:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-jdbc:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat:tomcat-jdbc:jar:8.5.4:compile
[INFO] |  |  |  \- org.apache.tomcat:tomcat-juli:jar:8.5.4:compile
[INFO] |  |  \- org.springframework:spring-jdbc:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.hibernate:hibernate-core:jar:5.0.9.Final:compile
[INFO] |  |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  |  +- org.javassist:javassist:jar:3.20.0-GA:compile
[INFO] |  |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  |  +- org.jboss:jandex:jar:2.0.0.Final:compile
[INFO] |  |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  |  \- xml-apis:xml-apis:jar:1.4.01:compile
[INFO] |  |  \- org.hibernate.common:hibernate-commons-annotations:jar:5.0.1.Final:compile
[INFO] |  +- org.hibernate:hibernate-entitymanager:jar:5.0.9.Final:compile
[INFO] |  +- javax.transaction:javax.transaction-api:jar:1.2:compile
[INFO] |  \- org.springframework:spring-aspects:jar:4.3.2.RELEASE:compile
[INFO] +- com.h2database:h2:jar:1.4.192:compile
[INFO] +- org.springframework.boot:spring-boot-starter-test:jar:1.4.0.RELEASE:test
[INFO] |  +- org.springframework.boot:spring-boot-test:jar:1.4.0.RELEASE:test
[INFO] |  +- org.springframework.boot:spring-boot-test-autoconfigure:jar:1.4.0.RELEASE:test
[INFO] |  +- com.jayway.jsonpath:json-path:jar:2.2.0:test
[INFO] |  |  \- net.minidev:json-smart:jar:2.2.1:test
[INFO] |  |     \- net.minidev:accessors-smart:jar:1.1:test
[INFO] |  +- org.assertj:assertj-core:jar:2.5.0:test
[INFO] |  +- org.mockito:mockito-core:jar:1.10.19:test
[INFO] |  |  \- org.objenesis:objenesis:jar:2.1:test
[INFO] |  +- org.hamcrest:hamcrest-core:jar:1.3:compile
[INFO] |  +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO] |  +- org.skyscreamer:jsonassert:jar:1.3.0:test
[INFO] |  |  \- org.json:json:jar:20140107:test
[INFO] |  +- org.springframework:spring-core:jar:4.3.2.RELEASE:compile
[INFO] |  \- org.springframework:spring-test:jar:4.3.2.RELEASE:test
[INFO] +- org.springframework.boot:spring-boot-starter:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.4.0.RELEASE:compile
[INFO] |  \- org.yaml:snakeyaml:jar:1.17:runtime
[INFO] +- org.springframework.boot:spring-boot-starter-log4j2:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.apache.logging.log4j:log4j-slf4j-impl:jar:2.6.2:compile
[INFO] |  +- org.slf4j:jcl-over-slf4j:jar:1.7.21:compile
[INFO] |  \- org.slf4j:jul-to-slf4j:jar:1.7.21:compile
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.6.2:compile
[INFO] +- org.apache.logging.log4j:log4j-core:jar:2.6.2:compile
[INFO] +- org.apache.commons:commons-lang3:jar:3.3.2:compile
[INFO] +- org.mongodb:mongo-java-driver:jar:2.12.4:compile
[INFO] +- org.springframework.data:spring-data-mongodb:jar:1.9.2.RELEASE:compile
[INFO] |  +- org.springframework:spring-tx:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.springframework:spring-context:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.springframework:spring-beans:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.springframework:spring-expression:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.springframework.data:spring-data-commons:jar:1.12.2.RELEASE:compile
[INFO] |  \- org.slf4j:slf4j-api:jar:1.7.21:compile
[INFO] +- com.google.api-client:google-api-client:jar:1.18.0-rc:compile
[INFO] +- com.google.http-client:google-http-client-jackson2:jar:1.18.0-rc:compile
[INFO] |  \- com.google.http-client:google-http-client:jar:1.18.0-rc:compile
[INFO] +- com.google.oauth-client:google-oauth-client:jar:1.18.0-rc:compile
[INFO] |  \- com.google.code.findbugs:jsr305:jar:1.3.9:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.2:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.1:compile
[INFO] +- com.google.apis:google-api-services-oauth2:jar:v2-rev81-1.19.0:compile
[INFO] +- com.fasterxml.jackson.core:jackson-core:jar:2.8.2:compile
[INFO] +- org.mongodb.morphia:morphia:jar:0.107:compile
[INFO] +- org.springframework.security:spring-security-web:jar:4.1.1.RELEASE:compile
[INFO] |  +- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  \- org.springframework.security:spring-security-core:jar:4.1.1.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-config:jar:4.1.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-aop:jar:4.3.2.RELEASE:compile
[INFO] +- org.springframework.social:spring-social-config:jar:1.1.4.RELEASE:compile
[INFO] |  \- org.springframework.social:spring-social-web:jar:1.1.4.RELEASE:compile
[INFO] |     \- javax.inject:javax.inject:jar:1:compile
[INFO] +- org.springframework.social:spring-social-core:jar:1.1.4.RELEASE:compile
[INFO] +- org.springframework.social:spring-social-facebook:jar:2.0.3.RELEASE:compile
[INFO] +- org.apache.httpcomponents:httpclient:jar:4.3.6:compile
[INFO] |  +- org.apache.httpcomponents:httpcore:jar:4.4.5:compile
[INFO] |  \- commons-codec:commons-codec:jar:1.10:compile
[INFO] +- org.mockito:mockito-all:jar:1.10.8:compile
[INFO] +- junit:junit:jar:4.11:compile
[INFO] +- org.eclipse.jetty:apache-jsp:jar:9.3.11.v20160721:provided
[INFO] |  +- org.eclipse.jetty:jetty-util:jar:9.3.11.v20160721:compile
[INFO] |  +- org.eclipse.jetty:jetty-server:jar:9.3.11.v20160721:compile
[INFO] |  +- org.eclipse.jetty.toolchain:jetty-schemas:jar:3.1:provided
[INFO] |  +- javax.servlet:javax.servlet-api:jar:3.1.0:compile
[INFO] |  +- org.mortbay.jasper:apache-jsp:jar:8.0.33:provided
[INFO] |  |  \- org.mortbay.jasper:apache-el:jar:8.0.33:provided
[INFO] |  \- org.eclipse.jdt.core.compiler:ecj:jar:4.4.2:provided
[INFO] +- javax.servlet:jstl:jar:1.2:compile
[INFO] +- org.springframework.data:spring-data-jpa:jar:1.10.2.RELEASE:compile
[INFO] |  +- org.springframework:spring-orm:jar:4.3.2.RELEASE:compile
[INFO] |  \- org.aspectj:aspectjrt:jar:1.8.9:compile
[INFO] +- postgresql:postgresql:jar:9.1-901-1.jdbc4:compile
[INFO] \- joda-time:joda-time:jar:2.9.4:compile
</code>```

I have added the standard log4j2.xml-file to src/main/resources/config with the default config:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Logger name="org.apache.log4j.xml" level="info"/>
    <Root level="debug">
      <AppenderRef ref="STDOUT"/>
    </Root>
  </Loggers>
</Configuration>
</code>```

Any guesses? I've tried running from within Spring Tool Suite and with the maven spring-boot plugin.

By popular request, here is the complete pom.xml:

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

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

    <modelVersion>4.0.0</modelVersion>
    <groupId>no.saiboten</groupId>
    <artifactId>musikkjulekalender</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Musikkjulekalender</name>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</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</artifactId>
             <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
     <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.6.2</version>
      </dependency>
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.6.2</version>
      </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.12.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client</artifactId>
            <version>1.18.0-rc</version>
        </dependency>
        <dependency>
            <groupId>com.google.http-client</groupId>
            <artifactId>google-http-client-jackson2</artifactId>
            <version>1.18.0-rc</version>
        </dependency>
        <dependency>
            <groupId>com.google.oauth-client</groupId>
            <artifactId>google-oauth-client</artifactId>
            <version>1.18.0-rc</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-oauth2</artifactId>
            <version>v2-rev81-1.19.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb.morphia</groupId>
            <artifactId>morphia</artifactId>
            <version>0.107</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-facebook</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>apache-jsp</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.4</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>
</code>```

答:
There might be multiple reasons but common reason is you might have wrong JAR (corrupted).
Delete JARs from repository and try to download again. It will solve the problem.

In my case I have deleted org folder from maven repository
{home}.m2\repository\org.

I have posted similar question here.
Spring boot: ERROR StatusLogger Log4j2 could not find a logging implementation

Body:
I'm getting this error trying to use log4j2 with spring boot.

ERROR StatusLogger Log4j2 could not find a logging implementation.
Please add log4j-core to the classpath. Using SimpleLogger to log to the console...

I'm have followed this guide: http://docs.spring.io/spring-boot/docs/current/reference/html/howto-logging.html#howto-configure-log4j-for-logging - and also added the two log4j2-dependencies from https://logging.apache.org/log4j/2.x/maven-artifacts.html

My dependency:tree looks like this:

[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @  musikkjulekalender ---
[INFO] no.saiboten:musikkjulekalender:war:1.0-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.hibernate:hibernate-validator:jar:5.2.4.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.3.0.Final:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.3.1:compile
[INFO] |  +- org.springframework:spring-web:jar:4.3.2.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:4.3.2.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-jetty:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.eclipse.jetty:jetty-servlets:jar:9.3.11.v20160721:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-continuation:jar:9.3.11.v20160721:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-http:jar:9.3.11.v20160721:compile
[INFO] |  |  \- org.eclipse.jetty:jetty-io:jar:9.3.11.v20160721:compile
[INFO] |  +- org.eclipse.jetty:jetty-webapp:jar:9.3.11.v20160721:compile
[INFO] |  |  +- org.eclipse.jetty:jetty-xml:jar:9.3.11.v20160721:compile
[INFO] |  |  \- org.eclipse.jetty:jetty-servlet:jar:9.3.11.v20160721:compile
[INFO] |  |     \- org.eclipse.jetty:jetty-security:jar:9.3.11.v20160721:compile
[INFO] |  +- org.eclipse.jetty.websocket:websocket-server:jar:9.3.11.v20160721:compile
[INFO] |  |  +- org.eclipse.jetty.websocket:websocket-common:jar:9.3.11.v20160721:compile
[INFO] |  |  |  \- org.eclipse.jetty.websocket:websocket-api:jar:9.3.11.v20160721:compile
[INFO] |  |  +- org.eclipse.jetty.websocket:websocket-client:jar:9.3.11.v20160721:compile
[INFO] |  |  \- org.eclipse.jetty.websocket:websocket-servlet:jar:9.3.11.v20160721:compile
[INFO] |  \- org.eclipse.jetty.websocket:javax-websocket-server-impl:jar:9.3.11.v20160721:compile
[INFO] |     +- org.eclipse.jetty:jetty-annotations:jar:9.3.11.v20160721:compile
[INFO] |     |  +- org.eclipse.jetty:jetty-plus:jar:9.3.11.v20160721:compile
[INFO] |     |  +- javax.annotation:javax.annotation-api:jar:1.2:compile
[INFO] |     |  +- org.ow2.asm:asm:jar:5.0.1:compile
[INFO] |     |  \- org.ow2.asm:asm-commons:jar:5.0.1:compile
[INFO] |     |     \- org.ow2.asm:asm-tree:jar:5.0.1:compile
[INFO] |     +- org.eclipse.jetty.websocket:javax-websocket-client-impl:jar:9.3.11.v20160721:compile
[INFO] |     \- javax.websocket:javax.websocket-api:jar:1.0:compile
[INFO] +- org.springframework.boot:spring-boot-starter-data-jpa:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-aop:jar:1.4.0.RELEASE:compile
[INFO] |  |  \- org.aspectj:aspectjweaver:jar:1.8.9:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-jdbc:jar:1.4.0.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat:tomcat-jdbc:jar:8.5.4:compile
[INFO] |  |  |  \- org.apache.tomcat:tomcat-juli:jar:8.5.4:compile
[INFO] |  |  \- org.springframework:spring-jdbc:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.hibernate:hibernate-core:jar:5.0.9.Final:compile
[INFO] |  |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  |  +- org.javassist:javassist:jar:3.20.0-GA:compile
[INFO] |  |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  |  +- org.jboss:jandex:jar:2.0.0.Final:compile
[INFO] |  |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  |  \- xml-apis:xml-apis:jar:1.4.01:compile
[INFO] |  |  \- org.hibernate.common:hibernate-commons-annotations:jar:5.0.1.Final:compile
[INFO] |  +- org.hibernate:hibernate-entitymanager:jar:5.0.9.Final:compile
[INFO] |  +- javax.transaction:javax.transaction-api:jar:1.2:compile
[INFO] |  \- org.springframework:spring-aspects:jar:4.3.2.RELEASE:compile
[INFO] +- com.h2database:h2:jar:1.4.192:compile
[INFO] +- org.springframework.boot:spring-boot-starter-test:jar:1.4.0.RELEASE:test
[INFO] |  +- org.springframework.boot:spring-boot-test:jar:1.4.0.RELEASE:test
[INFO] |  +- org.springframework.boot:spring-boot-test-autoconfigure:jar:1.4.0.RELEASE:test
[INFO] |  +- com.jayway.jsonpath:json-path:jar:2.2.0:test
[INFO] |  |  \- net.minidev:json-smart:jar:2.2.1:test
[INFO] |  |     \- net.minidev:accessors-smart:jar:1.1:test
[INFO] |  +- org.assertj:assertj-core:jar:2.5.0:test
[INFO] |  +- org.mockito:mockito-core:jar:1.10.19:test
[INFO] |  |  \- org.objenesis:objenesis:jar:2.1:test
[INFO] |  +- org.hamcrest:hamcrest-core:jar:1.3:compile
[INFO] |  +- org.hamcrest:hamcrest-library:jar:1.3:test
[INFO] |  +- org.skyscreamer:jsonassert:jar:1.3.0:test
[INFO] |  |  \- org.json:json:jar:20140107:test
[INFO] |  +- org.springframework:spring-core:jar:4.3.2.RELEASE:compile
[INFO] |  \- org.springframework:spring-test:jar:4.3.2.RELEASE:test
[INFO] +- org.springframework.boot:spring-boot-starter:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.4.0.RELEASE:compile
[INFO] |  \- org.yaml:snakeyaml:jar:1.17:runtime
[INFO] +- org.springframework.boot:spring-boot-starter-log4j2:jar:1.4.0.RELEASE:compile
[INFO] |  +- org.apache.logging.log4j:log4j-slf4j-impl:jar:2.6.2:compile
[INFO] |  +- org.slf4j:jcl-over-slf4j:jar:1.7.21:compile
[INFO] |  \- org.slf4j:jul-to-slf4j:jar:1.7.21:compile
[INFO] +- org.apache.logging.log4j:log4j-api:jar:2.6.2:compile
[INFO] +- org.apache.logging.log4j:log4j-core:jar:2.6.2:compile
[INFO] +- org.apache.commons:commons-lang3:jar:3.3.2:compile
[INFO] +- org.mongodb:mongo-java-driver:jar:2.12.4:compile
[INFO] +- org.springframework.data:spring-data-mongodb:jar:1.9.2.RELEASE:compile
[INFO] |  +- org.springframework:spring-tx:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.springframework:spring-context:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.springframework:spring-beans:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.springframework:spring-expression:jar:4.3.2.RELEASE:compile
[INFO] |  +- org.springframework.data:spring-data-commons:jar:1.12.2.RELEASE:compile
[INFO] |  \- org.slf4j:slf4j-api:jar:1.7.21:compile
[INFO] +- com.google.api-client:google-api-client:jar:1.18.0-rc:compile
[INFO] +- com.google.http-client:google-http-client-jackson2:jar:1.18.0-rc:compile
[INFO] |  \- com.google.http-client:google-http-client:jar:1.18.0-rc:compile
[INFO] +- com.google.oauth-client:google-oauth-client:jar:1.18.0-rc:compile
[INFO] |  \- com.google.code.findbugs:jsr305:jar:1.3.9:compile
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.2:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.1:compile
[INFO] +- com.google.apis:google-api-services-oauth2:jar:v2-rev81-1.19.0:compile
[INFO] +- com.fasterxml.jackson.core:jackson-core:jar:2.8.2:compile
[INFO] +- org.mongodb.morphia:morphia:jar:0.107:compile
[INFO] +- org.springframework.security:spring-security-web:jar:4.1.1.RELEASE:compile
[INFO] |  +- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  \- org.springframework.security:spring-security-core:jar:4.1.1.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-config:jar:4.1.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-aop:jar:4.3.2.RELEASE:compile
[INFO] +- org.springframework.social:spring-social-config:jar:1.1.4.RELEASE:compile
[INFO] |  \- org.springframework.social:spring-social-web:jar:1.1.4.RELEASE:compile
[INFO] |     \- javax.inject:javax.inject:jar:1:compile
[INFO] +- org.springframework.social:spring-social-core:jar:1.1.4.RELEASE:compile
[INFO] +- org.springframework.social:spring-social-facebook:jar:2.0.3.RELEASE:compile
[INFO] +- org.apache.httpcomponents:httpclient:jar:4.3.6:compile
[INFO] |  +- org.apache.httpcomponents:httpcore:jar:4.4.5:compile
[INFO] |  \- commons-codec:commons-codec:jar:1.10:compile
[INFO] +- org.mockito:mockito-all:jar:1.10.8:compile
[INFO] +- junit:junit:jar:4.11:compile
[INFO] +- org.eclipse.jetty:apache-jsp:jar:9.3.11.v20160721:provided
[INFO] |  +- org.eclipse.jetty:jetty-util:jar:9.3.11.v20160721:compile
[INFO] |  +- org.eclipse.jetty:jetty-server:jar:9.3.11.v20160721:compile
[INFO] |  +- org.eclipse.jetty.toolchain:jetty-schemas:jar:3.1:provided
[INFO] |  +- javax.servlet:javax.servlet-api:jar:3.1.0:compile
[INFO] |  +- org.mortbay.jasper:apache-jsp:jar:8.0.33:provided
[INFO] |  |  \- org.mortbay.jasper:apache-el:jar:8.0.33:provided
[INFO] |  \- org.eclipse.jdt.core.compiler:ecj:jar:4.4.2:provided
[INFO] +- javax.servlet:jstl:jar:1.2:compile
[INFO] +- org.springframework.data:spring-data-jpa:jar:1.10.2.RELEASE:compile
[INFO] |  +- org.springframework:spring-orm:jar:4.3.2.RELEASE:compile
[INFO] |  \- org.aspectj:aspectjrt:jar:1.8.9:compile
[INFO] +- postgresql:postgresql:jar:9.1-901-1.jdbc4:compile
[INFO] \- joda-time:joda-time:jar:2.9.4:compile

I have added the standard log4j2.xml-file to src/main/resources/config with the default config:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
    </Console>
  </Appenders>
  <Loggers>
    <Logger name="org.apache.log4j.xml" level="info"/>
    <Root level="debug">
      <AppenderRef ref="STDOUT"/>
    </Root>
  </Loggers>
</Configuration>

Any guesses? I've tried running from within Spring Tool Suite and with the maven spring-boot plugin.

By popular request, here is the complete pom.xml:

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

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

    <modelVersion>4.0.0</modelVersion>
    <groupId>no.saiboten</groupId>
    <artifactId>musikkjulekalender</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>Musikkjulekalender</name>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</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</artifactId>
             <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
     <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.6.2</version>
      </dependency>
      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.6.2</version>
      </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.12.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client</artifactId>
            <version>1.18.0-rc</version>
        </dependency>
        <dependency>
            <groupId>com.google.http-client</groupId>
            <artifactId>google-http-client-jackson2</artifactId>
            <version>1.18.0-rc</version>
        </dependency>
        <dependency>
            <groupId>com.google.oauth-client</groupId>
            <artifactId>google-oauth-client</artifactId>
            <version>1.18.0-rc</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.apis</groupId>
            <artifactId>google-api-services-oauth2</artifactId>
            <version>v2-rev81-1.19.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb.morphia</groupId>
            <artifactId>morphia</artifactId>
            <version>0.107</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.social</groupId>
            <artifactId>spring-social-facebook</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.8</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>apache-jsp</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.4</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <useSystemClassLoader>false</useSystemClassLoader>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
        <repository>
            <id>org.jboss.repository.releases</id>
            <name>JBoss Maven Release Repository</name>
            <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>


问:
Search for a criteria and get a sub-text
I have this text inside a cell from Excel:

```<code>1.Technical occurrence - Reason 1; (100%);04.02.2019
2.Systemic occurrence - Reason 2; (100%);06.02.2019
3.Technical escape - Reason 3; (100%);06.02.2019
4.Systemic escape - Reason 4; (100%);06.02.2019
</code>```

I would like help me with a formula that is searching for Systemic occurrence criteria and get the corresponding text from that line (in this case Reason 2)

The structure of an item is always the same (2.Systemic occurrence - Reason 2; (100%);06.02.2019), but the order of items can differ.

Is it possible to do this with Excel with a formula?

Body:
I have this text inside a cell from Excel:

1.Technical occurrence - Reason 1; (100%);04.02.2019
2.Systemic occurrence - Reason 2; (100%);06.02.2019
3.Technical escape - Reason 3; (100%);06.02.2019
4.Systemic escape - Reason 4; (100%);06.02.2019

I would like help me with a formula that is searching for Systemic occurrence criteria and get the corresponding text from that line (in this case Reason 2)

The structure of an item is always the same (2.Systemic occurrence - Reason 2; (100%);06.02.2019), but the order of items can differ.

Is it possible to do this with Excel with a formula?

Body:
Try:

=IFERROR(IF(FIND("Systemic occurrence",A1),MID(A1,(FIND("-",A1,1)+2),((FIND(";",A1,1))-(FIND("-",A1,1)+2))),""),"")

Results:


问:
IF statement in loop throwing syntax error
I'm creating a small batch script that loops over lines in documents then selects the correct condition and print out related message.

This is what I have tried.

```<code>...
set /p action=enter action(send,receive)

FOR /F %%j IN (countryList.txt) DO (
 For /F %%k IN (ports.txt) DO (
     IF "%action%" == "send"( ECHO Script will run as send for %%j country on %%k port)
     ELSE IF "%action%" == "receive"( ECHO Script will run as receive for %%j country on %%k port)
)
)
echo END
</code>```

I am using ELSE IF, because in real case there are more conditions than just send and receive.
I am expecting simple message out of ECHO.

答:
Your issue is with basic syntax; enter if /? at the Command Prompt for its usage information.

        If /I "%action%" == "send" (
            Echo Script will run as send for %%j country on %%k port
        ) Else (
            Echo Script will run as receive for %%j country on %%k port
        )
```

Body:
I'm creating a small batch script that loops over lines in documents then selects the correct condition and print out related message.

This is what I have tried.

...
set /p action=enter action(send,receive)

FOR /F %%j IN (countryList.txt) DO (
 For /F %%k IN (ports.txt) DO (
     IF "%action%" == "send"( ECHO Script will run as send for %%j country on %%k port)
     ELSE IF "%action%" == "receive"( ECHO Script will run as receive for %%j country on %%k port)
)
)
echo END

I am using ELSE IF, because in real case there are more conditions than just send and receive.
I am expecting simple message out of ECHO.


问:
How to update a RoR model's associations without updating the corresponding model's attributes
I have the following models (with corresponding database tables) in my Rails 3 application:

```<code>class User < ActiveRecord::Base
  has_many :service_users
  has_many :services, :through => :service_users

  attr_accessor :password

  attr_accessible :password, :password_confirmation, :service_ids

  validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :within => 6..40 }
  ...
end

class Service < ActiveRecord::Base
  has_many :service_users
  has_many :users, :through => :service_users
  ...
end

class ServiceUser < ActiveRecord::Base
  belongs_to :service
  belongs_to :user
end

#User Controller:

class UsersController < ApplicationController
  ...
  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated."
      redirect_to @user
    else
      @title = "Edit user"
      render 'edit'
    end
  end
  ...
end
</code>```

I want to be able to update a User model's associated services without having to specify the password and password confirmation attributes. How can I do this?

答: you will want to look into conditional validation to specify whether or not the password attribute in your model should be validated when you are updating/saving the model.  here is a Railscast episode that, while a little dated, is still fairly straightforward and should get you off on the right path</p>

ContentLicense: CC BY-SA 3.0

Body:
I have the following models (with corresponding database tables) in my Rails 3 application:

class User < ActiveRecord::Base
  has_many :service_users
  has_many :services, :through => :service_users

  attr_accessor :password

  attr_accessible :password, :password_confirmation, :service_ids

  validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :within => 6..40 }
  ...
end

class Service < ActiveRecord::Base
  has_many :service_users
  has_many :users, :through => :service_users
  ...
end

class ServiceUser < ActiveRecord::Base
  belongs_to :service
  belongs_to :user
end

#User Controller:

class UsersController < ApplicationController
  ...
  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated."
      redirect_to @user
    else
      @title = "Edit user"
      render 'edit'
    end
  end
  ...
end

I want to be able to update a User model's associated services without having to specify the password and password confirmation attributes. How can I do this?


问:
How to handle NULL values when sorting?
I am looking for a way to return NULL values last when sorting either DESC or ASC in SQL (the envelopping code is in Python) and maybe be able to retun the NULL values first depending on some config

I tried replacing the NULL values with numeric values but in the long run I found that it is not a suitable solution since in some cases I need to traceback the origin of the NULL, why I have it and putting a numeric value could influence the work of someone else and give inaccurate results.

```<code>if request.sort:
    sql += " order by " + ', '.join([sort.split(':')[0] + " " + sort.split(':')[1] for sort in request.sort])

return sql
</code>```

答:
You can still use the numeric replacement of nulls and keep the original values if you only do the replacement in the order by syntax. The resulting SQL would look like this:

```<code>SELECT col1, col2, col3
FROM Table
ORDER BY COALESCE(col1, -99)
</code>```

Also found a nice reference for sorting with nulls.

Title: How to handle NULL values when sorting?

Body:
I am looking for a way to return NULL values last when sorting either DESC or ASC in SQL (the envelopping code is in Python) and maybe be able to retun the NULL values first depending on some config

I tried replacing the NULL values with numeric values but in the long run I found that it is not a suitable solution since in some cases I need to traceback the origin of the NULL, why I have it and putting a numeric value could influence the work of someone else and give inaccurate results.

if request.sort:
    sql += " order by " + ', '.join([sort.split(':')[0] + " " + sort.split(':')[1] for sort in request.sort])

return sql

Body:
You can still use the numeric replacement of nulls and keep the original values if you only do the replacement in the order by syntax. The resulting SQL would look like this:

SELECT col1, col2, col3
FROM Table
ORDER BY COALESCE(col1, -99)

Also found a nice reference for sorting with nulls.


问:
Toolbar icon tinting on Android
I've noticed that using AppCompat themes, default toolbar icons get tinted by the attribute colorControlNormal in my style.

```<code><style name="MyTheme" parent="Theme.AppCompat">
    <item name="colorControlNormal">@color/yellow</item>
</style>
</code>```

As you can see above, however, it does not happen with all icons. I provided the "plus" sign, which I got from the official icons, and it does not get tinted (I used the "white" version of the png). From what I have understood from this question, system tints only icons with just an alpha channel. Is this true?

If so: Is there a place where I can find alpha-defined, official material icons? If not - and if Toolbar icons need to be alpha-only to be tinted - how is Google expecting us to use provided icons in a Toolbar?

Somewhere in the SDK I found some icons ending in _alpha.png, and they actually get tinted well. However I need the full set of material icons, and from the official sources I could only find white, grey600 and black ones.

Applying a ColorFilter at runtime would be slightly painful, and my actual Toolbar - with some icons tinted, some others not - looks quite bad.

答:
With androidX you can define your Toolbar like this

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:theme="@style/Toolbar" />
```

<p>Then, extend an AppCompat theme and set colorControlNormal property as you like:</p>

<pre class="lang-xml prettyprint-override"><code><style name="Toolbar" parent="Theme.AppCompat.Light">
    <item name="colorControlNormal">@color/colorBaseWhite</item>
    <item name="android:background">@color/colorPrimary</item>
</style>
</code>```

Title: Toolbar icon tinting on Android

Body:
I've noticed that using AppCompat themes, default toolbar icons get tinted by the attribute colorControlNormal in my style.

As you can see above, however, it does not happen with all icons. I provided the "plus" sign, which I got from the official icons, and it does not get tinted (I used the "white" version of the png). From what I have understood from this question, system tints only icons with just an alpha channel. Is this true?

If so: Is there a place where I can find alpha-defined, official material icons? If not - and if Toolbar icons need to be alpha-only to be tinted - how is Google expecting us to use provided icons in a Toolbar?

Somewhere in the SDK I found some icons ending in _alpha.png, and they actually get tinted well. However I need the full set of material icons, and from the official sources I could only find white, grey600 and black ones.

Applying a ColorFilter at runtime would be slightly painful, and my actual Toolbar - with some icons tinted, some others not - looks quite bad.

Body:
With androidX you can define your Toolbar like this

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:theme="@style/Toolbar" />

Then, extend an AppCompat theme and set colorControlNormal property as you like:

<style name="Toolbar" parent="Theme.AppCompat.Light">
    <item name="colorControlNormal">@color/colorBaseWhite</item>
    <item name="android:background">@color/colorPrimary</item>
</style>


问:
R: solving for a variable
I wonder if there's any function that can solve for a variable in an equation in terms of other values.

For example, I have:

```<code>(a-1/3)/(a+b-2/3)==0.3
</code>```

The output of this function should be:

```<code>(0.3*b+0.1333333)/(0.7)
</code>```

Or something along these lines.

Thank you

答:
You can use Yacas through the Ryacas package:

```<code>library(Ryacas)
a <- Sym("a")
b <- Sym("b")
Solve((a-1/3)/(a+b-2/3)==0.3, a)
# Yacas vector:
# [1] a == -((-0.3 * b - 0.1333333333)/0.7)
</code>```

To get the solution as an expression, do:

```<code>solution <- Solve((a-1/3)/(a+b-2/3)==0.3, a)
yacas(paste0("a Where ", solution))
# expression(-((-0.3 * b - 0.1333333333)/0.7))
</code>```

You can define a function returning the solution in function of b as follows:

```<code>f <- function(b) {}
body(f) <- yacas(paste0("a Where ", solution))$text
f
# function (x)
# -((-0.3 * b - 0.1333333333)/0.7)
</code>```

Also note that you do rational calculus to get exact values:

```<code>q1 <- Sym(1)/Sym(3)
q2 <- Sym(2)/Sym(3)
solution <- Solve((a-q1)/(a+b-q2)==0.3, a)
solution
# [1] a == -(3 * (-0.3 * b - 1.2/9)/2.1)
Simplify(solution)
# [1] a + (-0.9 * b/2.1 - 3.6/18.9) == 0
</code>```

Title: R: solving for a variable

Body:
I wonder if there's any function that can solve for a variable in an equation in terms of other values.

For example, I have:

(a-1/3)/(a+b-2/3)==0.3

The output of this function should be:

(0.3*b+0.1333333)/(0.7)

Or something along these lines.

Thank you

Body:
You can use Yacas through the Ryacas package:

library(Ryacas)
a <- Sym("a")
b <- Sym("b")
Solve((a-1/3)/(a+b-2/3)==0.3, a)
# Yacas vector:
# [1] a == -((-0.3 * b - 0.1333333333)/0.7)

To get the solution as an expression, do:

solution <- Solve((a-1/3)/(a+b-2/3)==0.3, a)
yacas(paste0("a Where ", solution))
# expression(-((-0.3 * b - 0.1333333333)/0.7))

You can define a function returning the solution in function of b as follows:

f <- function(b) {}
body(f) <- yacas(paste0("a Where ", solution))$text
f
# function (x)
# -((-0.3 * b - 0.1333333333)/0.7)

Also note that you do rational calculus to get exact values:

q1 <- Sym(1)/Sym(3)
q2 <- Sym(2)/Sym(3)
solution <- Solve((a-q1)/(a+b-q2)==0.3, a)
solution
# [1] a == -(3 * (-0.3 * b - 1.2/9)/2.1)
Simplify(solution)
# [1] a + (-0.9 * b/2.1 - 3.6/18.9) == 0


问:
Allow a foreign key to be null with Entity Type Builder
I need a foreign key to be null, how can I do this with entity configure?

 public void Configure(EntityTypeBuilder<CostCenter> entity)
        {
            entity.ToTable("CostCenter", ApplicationDataContext.DEFAULT_SCHEMA);

            entity.Property(e => e.Id).ValueGeneratedNever();

            entity.Property(e => e.Name)
                .IsRequired()
                .HasMaxLength(150)
                .IsUnicode(false);

            entity.Property(e => e.Uid).HasColumnName("UID");

            entity.Property(e => e.UpdatedBy)
                .IsRequired()
                .HasMaxLength(250)
                .IsUnicode(false);

            entity.Property(e => e.UpdatedOn).HasColumnType("datetime");

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

<p>Now I need to make this attribute that makes it null</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>entity.HasOne(e => e.Owner)
                .WithMany()
                .HasForeignKey(d => d.OwnerId)
                .HasConstraintName("FK_CostCenter_Account_OwnerId");</code>```

答:
I think that you want to configure that if a CostCenter has a null OwnerId, then the CostCenter does not have an Owner.

Apparently some CostCenters have Owners, and some don't: the Owner is optional. This is a zero-or-one-to-many relationship.

```<code>public void Configure(EntityTypeBuilder<CostCenter> costCenterEntity)
{
    ...

    costCenterEntity.HasOptional(costCenter => costCenter.OwnerId)                    // The owner is optional
        .WithMany(owner => owner.CostCenters)  // the owner has zero or more CostCenters
        .HasForeignKey(costCenter => costCenter.OwnerId)
}
</code>```

It might be that you need to define OwnerId as a nullable property

Body:
I need a foreign key to be null, how can I do this with entity configure?

 public void Configure(EntityTypeBuilder<CostCenter> entity)
        {
            entity.ToTable("CostCenter", ApplicationDataContext.DEFAULT_SCHEMA);

            entity.Property(e => e.Id).ValueGeneratedNever();

            entity.Property(e => e.Name)
                .IsRequired()
                .HasMaxLength(150)
                .IsUnicode(false);

            entity.Property(e => e.Uid).HasColumnName("UID");

            entity.Property(e => e.UpdatedBy)
                .IsRequired()
                .HasMaxLength(250)
                .IsUnicode(false);

            entity.Property(e => e.UpdatedOn).HasColumnType("datetime");

        }

Now I need to make this attribute that makes it null

entity.HasOne(e => e.Owner)
                .WithMany()
                .HasForeignKey(d => d.OwnerId)
                .HasConstraintName("FK_CostCenter_Account_OwnerId");

Body:
I think that you want to configure that if a CostCenter has a null OwnerId, then the CostCenter does not have an Owner.

Apparently some CostCenters have Owners, and some don't: the Owner is optional. This is a zero-or-one-to-many relationship.

public void Configure(EntityTypeBuilder<CostCenter> costCenterEntity)
{
    ...

    costCenterEntity.HasOptional(costCenter => costCenter.OwnerId)                    // The owner is optional
        .WithMany(owner => owner.CostCenters)  // the owner has zero or more CostCenters
        .HasForeignKey(costCenter => costCenter.OwnerId)
}

It might be that you need to define OwnerId as a nullable property


问:
Generating a new ASP.NET session in the current HTTPContext
As a result of a penetration test against some of our products in the pipeline, what looked to be at the time an 'easy' problem to fix is turning out to be a toughy.

Not that it should of course, I mean why would just generating a brand new session for the current HTTPContext be so difficult? Bizarre! Anyway- I've written a cheeky little utility class to "just do it":

(apologies for code formatting/highlighting/Visual Basic I must be doing something wrong)

```<code>
Imports System.Web
Imports System.Web.SessionState

Public Class SwitchSession

    Public Shared Sub SetNewSession(ByVal context As HttpContext)
        ' This value will hold the ID managers action to creating a response cookie
        Dim cookieAdded As Boolean
        ' We use the current session state as a template
        Dim state As HttpSessionState = context.Session
        ' We use the default ID manager to generate a new session id
        Dim idManager As New SessionIDManager()
        ' We also start with a new, fresh blank state item collection
        Dim items As New SessionStateItemCollection()
        ' Static objects are extracted from the current session context
        Dim staticObjects As HttpStaticObjectsCollection = _
            SessionStateUtility.GetSessionStaticObjects(context)
        ' We construct the replacement session for the current, some parameters are new, others are taken from previous session
        Dim replacement As New HttpSessionStateContainer( _
                 idManager.CreateSessionID(context), _
                 items, _
                 staticObjects, _
                 state.Timeout, _
                 True, _
                 state.CookieMode, _
                 state.Mode, _
                 state.IsReadOnly)
        ' Finally we strip the current session state from the current context
        SessionStateUtility.RemoveHttpSessionStateFromContext(context)
        ' Then we replace the assign the active session state using the replacement we just constructed
        SessionStateUtility.AddHttpSessionStateToContext(context, replacement)
        ' Make sure we clean out the responses of any other inteferring cookies
        idManager.RemoveSessionID(context)
        ' Save our new cookie session identifier to the response
        idManager.SaveSessionID(context, replacement.SessionID, False, cookieAdded)
    End Sub

End Class
</code>```

It works fine for the remainder of the request, and correctly identifies itself as the new session (e.g. HTTPContext.Current.Session.SessionID returns the newly generated session identifier).

Surprise surprise then, that when the next request hits the server, the HTTPContext.Session (an HTTPSessionState object) identifies itself with the correct SessionID, but has IsNewSession set to True, and is empty, losing all the session values set in the previous request.

So there must be something special about the previous HTTPSessionState object being removed from the initial request, an event handler here, a callback there, something which handles persisting the session data across requests, or just something I'm missing?

Anybody got any magic to share?

答:
If you're security concious and would like the C# version of this answer removing the old field, please use the following.</p>

```<code>private static void RegenerateSessionId()
{

    // Initialise variables for regenerating the session id
    HttpContext Context = HttpContext.Current;
    SessionIDManager manager = new SessionIDManager();
    string oldId = manager.GetSessionID(Context);
    string newId = manager.CreateSessionID(Context);
    bool isAdd = false, isRedir = false;

    // Save a new session ID
    manager.SaveSessionID(Context, newId, out isRedir, out isAdd);

    // Get the fields using the below and create variables for storage
    HttpApplication ctx = HttpContext.Current.ApplicationInstance;
    HttpModuleCollection mods = ctx.Modules;
    SessionStateModule ssm = (SessionStateModule)mods.Get("Session");
    FieldInfo[] fields = ssm.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
    SessionStateStoreProviderBase store = null;
    FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null;
    SessionStateStoreData rqItem = null;

    // Assign to each variable the appropriate field values
    foreach (FieldInfo field in fields)
    {
        if (field.Name.Equals("_store")) store = (SessionStateStoreProviderBase)field.GetValue(ssm);
        if (field.Name.Equals("_rqId")) rqIdField = field;
        if (field.Name.Equals("_rqLockId")) rqLockIdField = field;
        if (field.Name.Equals("_rqSessionStateNotFound")) rqStateNotFoundField = field;
        if (field.Name.Equals("_rqItem")) rqItem = (SessionStateStoreData)field.GetValue(ssm);
    }

    // Remove the previous session value
    object lockId = rqLockIdField.GetValue(ssm);
    if ((lockId != null) && (oldId != null))
        store.RemoveItem(Context, oldId, lockId, rqItem);

    rqStateNotFoundField.SetValue(ssm, true);
    rqIdField.SetValue(ssm, newId);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
As a result of a penetration test against some of our products in the pipeline, what looked to be at the time an 'easy' problem to fix is turning out to be a toughy.

Not that it should of course, I mean why would just generating a brand new session for the current HTTPContext be so difficult? Bizarre! Anyway- I've written a cheeky little utility class to "just do it":

(apologies for code formatting/highlighting/Visual Basic I must be doing something wrong)

Imports System.Web
Imports System.Web.SessionState

Public Class SwitchSession

    Public Shared Sub SetNewSession(ByVal context As HttpContext)
        ' This value will hold the ID managers action to creating a response cookie
        Dim cookieAdded As Boolean
        ' We use the current session state as a template
        Dim state As HttpSessionState = context.Session
        ' We use the default ID manager to generate a new session id
        Dim idManager As New SessionIDManager()
        ' We also start with a new, fresh blank state item collection
        Dim items As New SessionStateItemCollection()
        ' Static objects are extracted from the current session context
        Dim staticObjects As HttpStaticObjectsCollection = _
            SessionStateUtility.GetSessionStaticObjects(context)
        ' We construct the replacement session for the current, some parameters are new, others are taken from previous session
        Dim replacement As New HttpSessionStateContainer( _
                 idManager.CreateSessionID(context), _
                 items, _
                 staticObjects, _
                 state.Timeout, _
                 True, _
                 state.CookieMode, _
                 state.Mode, _
                 state.IsReadOnly)
        ' Finally we strip the current session state from the current context
        SessionStateUtility.RemoveHttpSessionStateFromContext(context)
        ' Then we replace the assign the active session state using the replacement we just constructed
        SessionStateUtility.AddHttpSessionStateToContext(context, replacement)
        ' Make sure we clean out the responses of any other inteferring cookies
        idManager.RemoveSessionID(context)
        ' Save our new cookie session identifier to the response
        idManager.SaveSessionID(context, replacement.SessionID, False, cookieAdded)
    End Sub

End Class

It works fine for the remainder of the request, and correctly identifies itself as the new session (e.g. HTTPContext.Current.Session.SessionID returns the newly generated session identifier).

Surprise surprise then, that when the next request hits the server, the HTTPContext.Session (an HTTPSessionState object) identifies itself with the correct SessionID, but has IsNewSession set to True, and is empty, losing all the session values set in the previous request.

So there must be something special about the previous HTTPSessionState object being removed from the initial request, an event handler here, a callback there, something which handles persisting the session data across requests, or just something I'm missing?

Anybody got any magic to share?

Body:
If you're security concious and would like the C# version of this answer removing the old field, please use the following.

private static void RegenerateSessionId()
{

    // Initialise variables for regenerating the session id
    HttpContext Context = HttpContext.Current;
    SessionIDManager manager = new SessionIDManager();
    string oldId = manager.GetSessionID(Context);
    string newId = manager.CreateSessionID(Context);
    bool isAdd = false, isRedir = false;

    // Save a new session ID
    manager.SaveSessionID(Context, newId, out isRedir, out isAdd);

    // Get the fields using the below and create variables for storage
    HttpApplication ctx = HttpContext.Current.ApplicationInstance;
    HttpModuleCollection mods = ctx.Modules;
    SessionStateModule ssm = (SessionStateModule)mods.Get("Session");
    FieldInfo[] fields = ssm.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
    SessionStateStoreProviderBase store = null;
    FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null;
    SessionStateStoreData rqItem = null;

    // Assign to each variable the appropriate field values
    foreach (FieldInfo field in fields)
    {
        if (field.Name.Equals("_store")) store = (SessionStateStoreProviderBase)field.GetValue(ssm);
        if (field.Name.Equals("_rqId")) rqIdField = field;
        if (field.Name.Equals("_rqLockId")) rqLockIdField = field;
        if (field.Name.Equals("_rqSessionStateNotFound")) rqStateNotFoundField = field;
        if (field.Name.Equals("_rqItem")) rqItem = (SessionStateStoreData)field.GetValue(ssm);
    }

    // Remove the previous session value
    object lockId = rqLockIdField.GetValue(ssm);
    if ((lockId != null) && (oldId != null))
        store.RemoveItem(Context, oldId, lockId, rqItem);

    rqStateNotFoundField.SetValue(ssm, true);
    rqIdField.SetValue(ssm, newId);
}


问:
C# if directive
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

```<code>void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif
</code>```

答:
These directives provide the ability to conditionally skip sections of source files, to report error and warning conditions, and to delineate distinct regions of source code
You cannot change them at runtime.</p>

Title: C# if directive

Body:
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif


问:
Database structure for common coupled words
I need to create a database to store "most common coupled words".
I will feed my software a huge set of texts (books and articles mainly), separate them into paragraphs and store them in some way.
After that, the user should be able to search for a word and check what other words appear the most inside a paragraph with the searched word.

Example: the user search for "flower" and the system should return something like the following.

```<code>Search word: "flower"

Most common matches with "flower":
1. "red" appeared 4918 times in a paragraph with "flower"
2. "white" appeared 3502 times in a paragraph with "flower"
3. "fresh" appeared 2501 times in a paragraph with "flower"
4. "scented" appeared 2499 times in a paragraph with "flower"
...and so on
</code>```

What's the best database structure to achieve such a functionality with decent speed queries and small storage needs?

Could it be one single tables with sorted words couples and appearence count? Is it better a 2 tables approach for storing words, words_id and a second table to store word1_id, word2_id, count?
Is there another common approach to such a problem?

答:
I would advise against storing pairs. This would lead to quadratic space complexity. If your paragraphs are 100 words long, then there are roughly 5,000 word pairs, so you would store 5,000 records instead of just 100 -- a 50-fold increase. Rather, you could have a word table and a text_index table whose purpose is to map words to paragraphs. Something like this:

create table word (
  id int not null auto_increment,
  form varchar(100) not null default '',

  primary key (id),
  unique key (form)
);

create table text_index (
  id int not null auto_increment,
  word_id int not null default 0,
  paragraph_id int not null default 0,

  primary key (id),
  key (paragraph_id),
  key (word_id)
);
```

<p>In this minimalist example, parahraph IDs would be generated sequentially as you scan the texts. You can certainly refine this, for example by adding a <code>document</code> table with document IDs and mapping paragraphs to documents if you need the ability to trace paragraphs back to books.</p>

<p>The query basically says "give me all the words and word counts that share a paragraph ID with 'flower'":</p>

<pre class="lang-sql prettyprint-override"><code>select w.form, count(*) as c
from text_index a
join text_index b on a.paragraph_id = b.paragraph_id
join word w on b.word_id = w.id
where a.word_id = 1
  and b.word_id != 1
group by b.word_id;
</code>```

Here is some sample data to play with. I haven't tested the query on large data sets, but with proper indexes it should be fast.

insert into word (form)
values
  ('flower'),
  ('toy'),
  ('candle'),
  ('red'),
  ('white'),
  ('fresh'),
  ('scented');

insert into text_index (word_id, paragraph_id)
values
  (1, 1),
  (1, 2),
  (1, 3),
  (1, 4),
  (2, 5),
  (2, 6),
  (3, 7),
  (4, 1),
  (4, 2),
  (4, 2),
  (4, 2),
  (4, 3),
  (5, 1),
  (5, 4),
  (5, 8),
  (6, 1),
  (6, 2),
  (7, 4),
  (7, 7);
```

Body:
I need to create a database to store "most common coupled words".
I will feed my software a huge set of texts (books and articles mainly), separate them into paragraphs and store them in some way.
After that, the user should be able to search for a word and check what other words appear the most inside a paragraph with the searched word.

Example: the user search for "flower" and the system should return something like the following.

Search word: "flower"

Most common matches with "flower":
1. "red" appeared 4918 times in a paragraph with "flower"
2. "white" appeared 3502 times in a paragraph with "flower"
3. "fresh" appeared 2501 times in a paragraph with "flower"
4. "scented" appeared 2499 times in a paragraph with "flower"
...and so on

What's the best database structure to achieve such a functionality with decent speed queries and small storage needs?

Could it be one single tables with sorted words couples and appearence count? Is it better a 2 tables approach for storing words, words_id and a second table to store word1_id, word2_id, count?
Is there another common approach to such a problem?

Body:
I would advise against storing pairs. This would lead to quadratic space complexity. If your paragraphs are 100 words long, then there are roughly 5,000 word pairs, so you would store 5,000 records instead of just 100 -- a 50-fold increase. Rather, you could have a word table and a text_index table whose purpose is to map words to paragraphs. Something like this:

create table word (
  id int not null auto_increment,
  form varchar(100) not null default '',

  primary key (id),
  unique key (form)
);

create table text_index (
  id int not null auto_increment,
  word_id int not null default 0,
  paragraph_id int not null default 0,

  primary key (id),
  key (paragraph_id),
  key (word_id)
);

In this minimalist example, parahraph IDs would be generated sequentially as you scan the texts. You can certainly refine this, for example by adding a document table with document IDs and mapping paragraphs to documents if you need the ability to trace paragraphs back to books.

The query basically says "give me all the words and word counts that share a paragraph ID with 'flower'":

select w.form, count(*) as c
from text_index a
join text_index b on a.paragraph_id = b.paragraph_id
join word w on b.word_id = w.id
where a.word_id = 1
  and b.word_id != 1
group by b.word_id;

Here is some sample data to play with. I haven't tested the query on large data sets, but with proper indexes it should be fast.

insert into word (form)
values
  ('flower'),
  ('toy'),
  ('candle'),
  ('red'),
  ('white'),
  ('fresh'),
  ('scented');

insert into text_index (word_id, paragraph_id)
values
  (1, 1),
  (1, 2),
  (1, 3),
  (1, 4),
  (2, 5),
  (2, 6),
  (3, 7),
  (4, 1),
  (4, 2),
  (4, 2),
  (4, 2),
  (4, 3),
  (5, 1),
  (5, 4),
  (5, 8),
  (6, 1),
  (6, 2),
  (7, 4),
  (7, 7);


问:
mysql | Duplicate Entry for PK - Non PK value change fixed issue - Why?

Issue

When I try to import an CSV file, I recieve the Duplicate entry 'x-x-xx-x-x-x' for key 'PRIMARY'-errors for the PK.

The PK itself are two concated varchars. And as much I can tell, are concated never a duplicate.

My first idea was, that maybe the length of the varchar wouldn't be enough for both keys and a composite-key could just use the length of one key. So I altered both two a value which should fit even such a character length (10 to 16) and… no successed. Same error.

But then it became strange:

I've edited (just for fun) all value-values into 1.0.
And suddenly, the whole import worked without any warning.

But… how? And more important why?

How can the value causing an Duplicate entry '1-b-21-1-b-20' for key 'PRIMARY' error, when they're even not a part of the (composite) PK?

Files

Original files have over 5000.

I reduced the two example CSV files to the only issuing ones:

Gist | CSV - 2 Files | 1 working | 1 issued

Table:

CREATE TABLE `route_neighbours` (
  `start` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
  `end` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
  `distance` decimal(10,1) NOT NULL,
  PRIMARY KEY (`start`,`end`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
```

<h2>Errors:</h2>

<pre class="lang-sql prettyprint-override"><code>2002:2: Duplicate entry '1-j-23-1-i-23' for key 'PRIMARY'
2003:2: Duplicate entry '1-b-17-1-b-18' for key 'PRIMARY'
2004:2: Duplicate entry '1-b-18-1-b-19' for key 'PRIMARY'
2005:2: Duplicate entry '1-b-19-1-b-20' for key 'PRIMARY'
2006:2: Duplicate entry '1-b-20-1-b-21' for key 'PRIMARY'
2007:2: Duplicate entry '1-b-21-1-b-22' for key 'PRIMARY'
2008:2: Duplicate entry '1-b-22-1-b-23' for key 'PRIMARY'
2009:2: Duplicate entry '1-b-23-1-b-24' for key 'PRIMARY'
2010:2: Duplicate entry '1-b-24-1-b-23' for key 'PRIMARY'
2011:2: Duplicate entry '1-b-23-1-b-22' for key 'PRIMARY'
2012:2: Duplicate entry '1-b-22-1-b-21' for key 'PRIMARY'
2013:2: Duplicate entry '1-b-21-1-b-20' for key 'PRIMARY'
2014:2: Duplicate entry '1-b-20-1-b-19' for key 'PRIMARY'
2015:2: Duplicate entry '1-b-19-1-b-18' for key 'PRIMARY'
2016:2: Duplicate entry '1-b-18-1-b-17' for key 'PRIMARY'
2017:2: Duplicate entry '1-b-17-1-b-16' for key 'PRIMARY'
2018:2: Duplicate entry '1-b-16-1-b-15' for key 'PRIMARY'
2019:2: Duplicate entry '1-b-15-1-b-14' for key 'PRIMARY'
2020:2: Duplicate entry '1-b-14-1-b-13' for key 'PRIMARY'
2021:2: Duplicate entry '1-b-13-1-b-12' for key 'PRIMARY'
2022:2: Duplicate entry '1-b-12-1-b-11' for key 'PRIMARY'
2023:2: Duplicate entry '1-b-11-1-b-10' for key 'PRIMARY'
... and much  more lines of these error ...
</code>```

答:
First of all, the primary key defined in the CREATE TABLE query can't exist, for the defined fields don't exist.

Also, the CSV indeed has duplicate records, for example: 1-bl-1;1-x-1;10.0.

Using bash, you can count the unique lines versus all the lines:

```<code># All lines: 1568
cat Issued.csv | wc -l

# Unique lines: 1531
cat Issued.csv | sort | uniq | wc -l
</code>```

So it's not the value causing any errors, it's the duplicate keys.

Body:
Issue

When I try to import an CSV file, I recieve the Duplicate entry 'x-x-xx-x-x-x' for key 'PRIMARY'-errors for the PK.

The PK itself are two concated varchars. And as much I can tell, are concated never a duplicate.

My first idea was, that maybe the length of the varchar wouldn't be enough for both keys and a composite-key could just use the length of one key. So I altered both two a value which should fit even such a character length (10 to 16) and… no successed. Same error.

But then it became strange:

I've edited (just for fun) all value-values into 1.0.
And suddenly, the whole import worked without any warning.

But… how? And more important why?

How can the value causing an Duplicate entry '1-b-21-1-b-20' for key 'PRIMARY' error, when they're even not a part of the (composite) PK?

Files

Original files have over 5000.

I reduced the two example CSV files to the only issuing ones:

Gist | CSV - 2 Files | 1 working | 1 issued

Table:

CREATE TABLE `route_neighbours` (
  `start` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
  `end` varchar(16) COLLATE utf8mb4_unicode_ci NOT NULL,
  `distance` decimal(10,1) NOT NULL,
  PRIMARY KEY (`start`,`end`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Errors:

2002:2: Duplicate entry '1-j-23-1-i-23' for key 'PRIMARY'
2003:2: Duplicate entry '1-b-17-1-b-18' for key 'PRIMARY'
2004:2: Duplicate entry '1-b-18-1-b-19' for key 'PRIMARY'
2005:2: Duplicate entry '1-b-19-1-b-20' for key 'PRIMARY'
2006:2: Duplicate entry '1-b-20-1-b-21' for key 'PRIMARY'
2007:2: Duplicate entry '1-b-21-1-b-22' for key 'PRIMARY'
2008:2: Duplicate entry '1-b-22-1-b-23' for key 'PRIMARY'
2009:2: Duplicate entry '1-b-23-1-b-24' for key 'PRIMARY'
2010:2: Duplicate entry '1-b-24-1-b-23' for key 'PRIMARY'
2011:2: Duplicate entry '1-b-23-1-b-22' for key 'PRIMARY'
2012:2: Duplicate entry '1-b-22-1-b-21' for key 'PRIMARY'
2013:2: Duplicate entry '1-b-21-1-b-20' for key 'PRIMARY'
2014:2: Duplicate entry '1-b-20-1-b-19' for key 'PRIMARY'
2015:2: Duplicate entry '1-b-19-1-b-18' for key 'PRIMARY'
2016:2: Duplicate entry '1-b-18-1-b-17' for key 'PRIMARY'
2017:2: Duplicate entry '1-b-17-1-b-16' for key 'PRIMARY'
2018:2: Duplicate entry '1-b-16-1-b-15' for key 'PRIMARY'
2019:2: Duplicate entry '1-b-15-1-b-14' for key 'PRIMARY'
2020:2: Duplicate entry '1-b-14-1-b-13' for key 'PRIMARY'
2021:2: Duplicate entry '1-b-13-1-b-12' for key 'PRIMARY'
2022:2: Duplicate entry '1-b-12-1-b-11' for key 'PRIMARY'
2023:2: Duplicate entry '1-b-11-1-b-10' for key 'PRIMARY'
... and much  more lines of these error ...

Body:
First of all, the primary key defined in the CREATE TABLE query can't exist, for the defined fields don't exist.

Also, the CSV indeed has duplicate records, for example: 1-bl-1;1-x-1;10.0.

Using bash, you can count the unique lines versus all the lines:

# All lines: 1568
cat Issued.csv | wc -l

# Unique lines: 1531
cat Issued.csv | sort | uniq | wc -l

So it's not the value causing any errors, it's the duplicate keys.


问:
Replacing printf("%g", value) with a stream manipulation
I wanted to replace an implementation of:

```<code>float value = 3.14;
printf("%g", value);
</code>```

(See How %g works in printf for the explanation of %g if required).

But I haven't found an equivalent in the stream manipulators, only for either fixed or scientific, but not the shortest of both (https://en.cppreference.com/w/cpp/io/manip/fixed). Does this exist or is there a "simple" way to implement this?

Some examples from the linked SO question:

544666.678 is written as 544667 if %.6g is used,

The same number is written as 5.4467E+5 when %.5g is used.

答:
%g is the default behavior. For example:

```<code>#include <iomanip>
#include <iostream>

int main()
{
    std::cout << std::setprecision(6) << 544666.678 << "\n"
              << std::setprecision(5) << 544666.678 << "\n";
}
</code>```

Output:

```<code>544667
5.4467e+05
</code>```

The default behavior can be retained with the manipulator std::defaultfloat after std::fixed or std::scientific is set.

Live demo

Body:
I wanted to replace an implementation of:

float value = 3.14;
printf("%g", value);

(See How %g works in printf for the explanation of %g if required).

But I haven't found an equivalent in the stream manipulators, only for either fixed or scientific, but not the shortest of both (https://en.cppreference.com/w/cpp/io/manip/fixed). Does this exist or is there a "simple" way to implement this?

Some examples from the linked SO question:

544666.678 is written as 544667 if %.6g is used,

The same number is written as 5.4467E+5 when %.5g is used.

Body:
%g is the default behavior. For example:

#include <iomanip>
#include <iostream>

int main()
{
    std::cout << std::setprecision(6) << 544666.678 << "\n"
              << std::setprecision(5) << 544666.678 << "\n";
}

Output:

544667
5.4467e+05

The default behavior can be retained with the manipulator std::defaultfloat after std::fixed or std::scientific is set.

Live demo


问:
SQL Select all columns from two or more Unrelated tables
```<code>Table A
    A1 A2
1   1   2
2   2   2
3   1   3

Table B
  A1  A2
1  3   3
2  1   4
3  4   1
4  5   0

Expected Result
Table C
   A1   A2
1  1    2
2  2    2
3  1    3
4  3    3
5  1    4
6  4    1
7  5    0
</code>```

答:
If you want possible duplicates to be in the output, use UNION ALL:

```<code>SELECT A1, A2 FROM TableA
UNION ALL
SELECT A1. A2 FROM TableB
</code>```

If you want duplicates to be grouped together, use UNION:

```<code>SELECT A1, A2 FROM TableA
UNION
SELECT A1. A2 FROM TableB
</code>```

Body:
If you want possible duplicates to be in the output, use UNION ALL:

SELECT A1, A2 FROM TableA
UNION ALL
SELECT A1. A2 FROM TableB

If you want duplicates to be grouped together, use UNION:

SELECT A1, A2 FROM TableA
UNION
SELECT A1. A2 FROM TableB


问:
Does Windows.CopyFile create a temporary local file while source and destination are network shares?
I have a D2007 application that uses Windows.CopyFile to copy MS Word and PowerPoint files from one network folder to another network folder. Our organization is migrating to Windows 7 from Vista. One of my migrated users got an error message that displayed a partial local folder (C:\Users\(username)\...\A100203.doc) during the copy. Does the CopyFile function cache a local copy of the document when it is copying from one network folder to another network folder or is it a direct write? I have never seen this error before and the application has been running for years on Win95, Win 98, Win2000, WinXP and Vista.</p>

答:
Windows.CopyFile does NOT cache the file on your hard drive... instead, it instructs Windows to handle the copying of the file itself (rather than you managing the streams in your own program). The output file buffer (destination) is opened, and the input buffer simply read and written. Essentially this means that the source file is spooled into system memory, then offloaded onto the destination... at no point is an additional cache file created (this would slow file copying down).

You need to provide more specific information about your error... such as either the text or an actual screenshot of the offending error message. This will allow people to provide more useful answers.


问:
Netbeans 11 Javadoc Not Appearing?
I have a question very similar to Javadocs are not appearing on Apache netbeans for java 10 in the sense that I can't seem to add javadoc support to my Apache Netbeans 11 release, or the maven project that I'm working on.

Here is the overview that I have:

As you can see, the javadoc is added in the URL section, but it does not appear in the code editor, even after a restart.

The URL I added: https://docs.oracle.com/en/java/javase/11/docs/api/index.html

But this doesn't work.

How can I resolve this?

答:
I've yet to see somebody who managed to add Javadoc 11 to Netbeans 11.

But there's a work-around which seems to work for many JDK classes, but not for all. If anybody knows how to solve the problem for all JDK classes, please say so, thanks.

Here's the workaround, doing well under Ubuntu 18 Linux with Openjdk11 from the Ubuntu repository, and probably also under other platforms:

Firstly it's strange how we have to add the Javadoc at all. In NB's menu Tools → Java Platforms there's a tab Sources and Javadoc.

1) I tried to use the tab Javadoc first, and had to add all the folders beginning with "java." from the main folder "javadoc/api/" from an unzipped Javadoc11 bundle. This way some JDK functions show the correct Javadoc pop-up help, however many functions just show an empty space, like for example when in Netbeans I enter:

```<code>BigInteger big;
big. _
</code>```

Then the pop-up comes and lists all BigInteger functions but their Javadoc is empty each.

So I tried another approach:

2) From the same NB menu Tools → Java Platforms in the tab Javadoc I removed all entries, and used the other tab Sources where I added all the folders beginning with "java." from an unzipped Java11 source bundle (file src.zip).

This way for many more JDK classes and functions their pop-up window works fine, like the mentioned BigInterger one.

However for certain classes from the java.sql package and probably from others, too, I can't make it to work.
For example I enter in NB:

```<code>java.sql.Statement stat;
stat. _
</code>```

Then I get a pop-up listing all functions, but for many there's a message Javadoc not found in the pop-up window. Like these functions:

```<code>stat.addBatch(…)
stat.execute(…)
stat.executeUpdate(…)
etc.
</code>```

For the following functions however the pop-up window shows the correct Javadoc:

```<code>stat.cancel(…)
stat.close(…)
stat.executeBatch(…)
etc.
</code>```

Title: Netbeans 11 Javadoc Not Appearing?

Body:
I've yet to see somebody who managed to add Javadoc 11 to Netbeans 11.

But there's a work-around which seems to work for many JDK classes, but not for all. If anybody knows how to solve the problem for all JDK classes, please say so, thanks.

Here's the workaround, doing well under Ubuntu 18 Linux with Openjdk11 from the Ubuntu repository, and probably also under other platforms:

Firstly it's strange how we have to add the Javadoc at all. In NB's menu Tools → Java Platforms there's a tab Sources and Javadoc.

1) I tried to use the tab Javadoc first, and had to add all the folders beginning with "java." from the main folder "javadoc/api/" from an unzipped Javadoc11 bundle. This way some JDK functions show the correct Javadoc pop-up help, however many functions just show an empty space, like for example when in Netbeans I enter:

BigInteger big;
big. _

Then the pop-up comes and lists all BigInteger functions but their Javadoc is empty each.

So I tried another approach:

2) From the same NB menu Tools → Java Platforms in the tab Javadoc I removed all entries, and used the other tab Sources where I added all the folders beginning with "java." from an unzipped Java11 source bundle (file src.zip).

This way for many more JDK classes and functions their pop-up window works fine, like the mentioned BigInterger one.

However for certain classes from the java.sql package and probably from others, too, I can't make it to work.
For example I enter in NB:

java.sql.Statement stat;
stat. _

Then I get a pop-up listing all functions, but for many there's a message Javadoc not found in the pop-up window. Like these functions:

stat.addBatch(…)
stat.execute(…)
stat.executeUpdate(…)
etc.

For the following functions however the pop-up window shows the correct Javadoc:

stat.cancel(…)
stat.close(…)
stat.executeBatch(…)
etc.


问:
How can I add a ViewController into my Header?
I want to add my ViewController into the header  of my OverViewController. I wrote an extension to add a Child View as a subview but I do not know how to add it into the header of my ViewController.

```<code>extension UIViewController {

    func add(_ child: UIViewController) {

        //add Child View controller
        addChildViewController(child)

        //add Child View as subview
        view.addSubview(child.view)

        //notify Child View Controller
        child.didMove(toParentViewController: self)
    }
}
</code>```

ViewController should be displayed in the header.

答:
You need to set the frame of your child view controller.</p>

```<code>extension UIViewController {
    func add(_ child: UIViewController) {
        //add Child View controller
        addChildViewController(child)
        //add Child View as subview
        view.addSubview(child.view)
        //set the frame of the child view
        child.view.frame = view.bounds
        //notify Child View Controller
        child.didMove(toParentViewController: self)
    }
}
</code>```

Body:
I want to add my ViewController into the header  of my OverViewController. I wrote an extension to add a Child View as a subview but I do not know how to add it into the header of my ViewController.

extension UIViewController {

    func add(_ child: UIViewController) {

        //add Child View controller
        addChildViewController(child)

        //add Child View as subview
        view.addSubview(child.view)

        //notify Child View Controller
        child.didMove(toParentViewController: self)
    }
}

ViewController should be displayed in the header.

Body:
You need to set the frame of your child view controller.

extension UIViewController {
    func add(_ child: UIViewController) {
        //add Child View controller
        addChildViewController(child)
        //add Child View as subview
        view.addSubview(child.view)
        //set the frame of the child view
        child.view.frame = view.bounds
        //notify Child View Controller
        child.didMove(toParentViewController: self)
    }
}