问:
Only rendering the Google login button on one page
I'm having an issue where the google login button is rendering on every page because its "hardcoded" into the html file (or so I think is the root cause)

index.html

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="google-signin-client_id" content="....apps.googleusercontent.com">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
        <title>React App</title>
  </head>
  <body>
    <div id="root"></div>

  </body>
</html>
</code>```

I generate the button with LoginPage.js

```<code>/* global gapi */

import React from 'react';

import { withRouter } from 'react-router';

class SignIn extends React.Component{

    constructor(props){
        super(props);
        this.onSignIn = this.onSignIn.bind(this)
    }

    componentDidMount() {
        console.log('this mounted')
        gapi.signin2.render('my-signin2', {
            'scope': 'profile email',
            'width': 300,
            'height': 50,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': this.onSignIn,
        });
    }

    onSignIn(googleUser) {
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
        // want to add in a redirect to `/options`
    }

    render() {
        return(
            <div>
                <div id="my-signin2" data-onsuccess={this.onSignIn}></div>
            </div>
        )
    }

}

export default withRouter(SignIn)
</code>```

Finally I have another component page called Form (that I'm not going to show all of the JS for simplicity sake).

Then my index.js

```<code>const App = () => (
    <MuiThemeProvider>
        <Router>
            <div>
                <Route path="/" component={SignIn} />
                <Route path="/options" component={Form} />
            </div>
        </Router>
    </MuiThemeProvider>
);
ReactDOM.render(<App />, document.getElementById('root'));
</code>```

I'm having an issue that the Google SignIn button is being rendered on every page.

Is there something I need to change in my HTML file? Is it because it's being fired when componentDidMount() is being run?

Or is it because I am using react-router incorrectly?

答:
I think the problem is with your router. If you only want the sign In component to show up on '/' then you need to specify an exact match:

<Route exact path="/" component={SignIn} />

Body:
I'm having an issue where the google login button is rendering on every page because its "hardcoded" into the html file (or so I think is the root cause)

index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="google-signin-client_id" content="....apps.googleusercontent.com">

        <title>React App</title>

I generate the button with LoginPage.js

/* global gapi */

import React from 'react';

import { withRouter } from 'react-router';

class SignIn extends React.Component{

    constructor(props){
        super(props);
        this.onSignIn = this.onSignIn.bind(this)
    }

    componentDidMount() {
        console.log('this mounted')
        gapi.signin2.render('my-signin2', {
            'scope': 'profile email',
            'width': 300,
            'height': 50,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': this.onSignIn,
        });
    }

    onSignIn(googleUser) {
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
        // want to add in a redirect to `/options`
    }

    render() {
        return(

        )
    }

}

export default withRouter(SignIn)

Finally I have another component page called Form (that I'm not going to show all of the JS for simplicity sake).

Then my index.js

const App = () => (
    <MuiThemeProvider>
        <Router>

                <Route path="/" component={SignIn} />
                <Route path="/options" component={Form} />

        </Router>
    </MuiThemeProvider>
);
ReactDOM.render(<App />, document.getElementById('root'));

I'm having an issue that the Google SignIn button is being rendered on every page.

Is there something I need to change in my HTML file? Is it because it's being fired when componentDidMount() is being run?

Or is it because I am using react-router incorrectly?


来源: stackexchange

问:
Passing input value from parent window to popup window
I had made a parent window that includes a text box and hyperlink to open a PopUp Child JSP Page.

I wish to access the value entered in textbox on the Child JSP through request.getParameter method. How can I achieve this?

答:
Just pass the value along as querystring in the URL of the popup window.

Assuming that you've a

```<code><input type="text" id="foo">
</code>```

you can pass it to the popup window as follows

```<code>var foo = document.getElementById('foo').value;
window.open('child.jsp?foo=' + encodeURIComponent(foo));
</code>```

then you can access it in popup window as follows

```<code><p>The value is ${param.foo}</p>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Just pass the value along as querystring in the URL of the popup window.

Assuming that you've a

<input type="text" id="foo">

you can pass it to the popup window as follows

var foo = document.getElementById('foo').value;
window.open('child.jsp?foo=' + encodeURIComponent(foo));

then you can access it in popup window as follows

<p>The value is ${param.foo}</p>


问:
How to split content from markdown file in jekyll
I'm trying to split some content from my markdown file.

For example my HTML Code looks like

```<code><body>
<div class="1">{{ x }}</div>
<div class="2">{{ y }}</div>
<div class="2">{{ y }}</div>
</body>
</code>```

and my markdown file looks like

```<code>---
layout: subpage
title: ABC
---

<!-- this content should be in div class = 1 -->
# Hello
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.

<!-- this content should be in div class = 2 -->
## Bye
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</code>```

How can I solve this problem? Could you guys please help me? Thanks!

答:
Put your content in front matter:

```<code>---
layout: subpage
title: ABC
p1: this is my first paragraph
p2: this is another one
---
</code>```

Then you can access with page.p1:

```<code><div>{{page.p1}}</div>
<div>{{page.p2}}</div>
</code>```

Or put them in a list and iterate , you get the idea.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to split some content from my markdown file.

For example my HTML Code looks like

{{ x }}

{{ y }}

{{ y }}

and my markdown file looks like

---
layout: subpage
title: ABC
---

# Hello
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.

## Bye
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.

How can I solve this problem? Could you guys please help me? Thanks!

Body:
Put your content in front matter:

---
layout: subpage
title: ABC
p1: this is my first paragraph
p2: this is another one
---

Then you can access with page.p1:

<div>{{page.p1}}</div>
<div>{{page.p2}}</div>

Or put them in a list and iterate , you get the idea.


问:
How do I tag the current git changeset from inside the Jenkinsfile?
I want to tag the current git changeset and push the tag from inside the Jenkinsfile. If the tag already exists it must be replaced.

I want to use this logic in order to tag the build that passed with the snapshot tag, which would be a mobile tag.

How can I do this?

答:
For people that couldn't get the above working I used the sshagent plugin directly, which did the trick:

```<code>stage('tag build'){
checkout([
    $class: 'GitSCM', branches: [[name: '*/master']],
    userRemoteConfigs: [[credentialsId: 'git',
    url: 'ssh://<ssh URL>']],
    extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'targeted-dir']]
])

sshagent(credentials: ['<credentials ID.']){
  dir('targeted-dir'){
    sh("git config user.email '<email>")
    sh("git config user.name '<user>.com'")

    // deletes current snapshot tag
    sh ("git tag -d ${PARAM_VERSION_NUMBER} || true")
    // tags current changeset
    sh ("git tag -a ${PARAM_VERSION_NUMBER} -m \"versioning ${PARAM_VERSION_NUMBER}\"")
    // deletes tag on remote in order not to fail pushing the new one
    sh ("git push origin :refs/tags/snapshot")
    // pushes the tags
    sh ("git push --tags")
    }
}
</code>```

}

Body:
For people that couldn't get the above working I used the sshagent plugin directly, which did the trick:

stage('tag build'){
checkout([
    $class: 'GitSCM', branches: [[name: '*/master']],
    userRemoteConfigs: [[credentialsId: 'git',
    url: 'ssh://<ssh URL>']],
    extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: 'targeted-dir']]
])

sshagent(credentials: ['<credentials ID.']){
  dir('targeted-dir'){
    sh("git config user.email '<email>")
    sh("git config user.name '<user>.com'")

    // deletes current snapshot tag
    sh ("git tag -d ${PARAM_VERSION_NUMBER} || true")
    // tags current changeset
    sh ("git tag -a ${PARAM_VERSION_NUMBER} -m \"versioning ${PARAM_VERSION_NUMBER}\"")
    // deletes tag on remote in order not to fail pushing the new one
    sh ("git push origin :refs/tags/snapshot")
    // pushes the tags
    sh ("git push --tags")
    }
}

}


问:
hbase importTsv FileNotFoundException
My configuration is hadoop 2.0.0 with hbase 0.96. The all thing is running in pseudo distributed mode.

When I run importTsv with the following command.

```<code>./hbase  org.apache.hadoop.hbase.mapreduce.ImportTsv -Dimporttsv.columns=HBASE_ROW_KEY,surname,name,age persons 'hdfs://localhost:9000/user/joe/persons.tsv'
</code>```

it tries to read the file hdfs://localhost:9000/home/joe/Programs/hbase-0.96.0-hadoop2/lib/hbase-client-0.96.0-hadoop2.jar that does not exist...

Below the stack trace.

Thank you a lot for any help.

```
2013-10-22 19:33:52,079 INFO  [main] mapreduce.TableOutputFormat: Created table instance for persons
2013-10-22 19:33:53,253 INFO  [main] mapreduce.JobSubmitter: Cleaning up the staging area file:/tmp/hadoop-joe/mapred/staging/joe1659915806/.staging/job_local1659915806_0001
2013-10-22 19:33:53,256 ERROR [main] security.UserGroupInformation: PriviledgedActionException as:joe (auth:SIMPLE) cause:java.io.FileNotFoundException: File does not exist: hdfs://localhost:9000/home/joe/Programs/hbase-0.96.0-hadoop2/lib/hbase-client-0.96.0-hadoop2.jar
Exception in thread "main" java.io.FileNotFoundException: File does not exist: hdfs://localhost:9000/home/joe/Programs/hbase-0.96.0-hadoop2/lib/hbase-client-0.96.0-hadoop2.jar
    at org.apache.hadoop.hdfs.DistributedFileSystem$17.doCall(DistributedFileSystem.java:1110)
    at org.apache.hadoop.hdfs.DistributedFileSystem$17.doCall(DistributedFileSystem.java:1102)
    at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1102)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:288)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:224)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestamps(ClientDistributedCacheManager.java:93)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestampsAndCacheVisibilities(ClientDistributedCacheManager.java:57)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:264)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:300)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:387)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1268)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1265)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1491)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1265)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1286)
    at org.apache.hadoop.hbase.mapreduce.ImportTsv.run(ImportTsv.java:480)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
    at org.apache.hadoop.hbase.mapreduce.ImportTsv.main(ImportTsv.java:484)

```

答:
In Hadoop, Configure parameters as follows:etc/hadoop/mapred-site.xml:

```<code><configuration>
    <property>
        <name>mapreduce.framework.name</name>
        <value>yarn</value>
    </property>
</configuration>
</code>```

etc/hadoop/yarn-site.xml:

```<code><configuration>
    <property>
        <name>yarn.nodemanager.aux-services</name>
        <value>mapreduce_shuffle</value>
    </property>
</configuration>
</code>```

Title: hbase importTsv FileNotFoundException

Body:
My configuration is hadoop 2.0.0 with hbase 0.96. The all thing is running in pseudo distributed mode.

When I run importTsv with the following command.

./hbase  org.apache.hadoop.hbase.mapreduce.ImportTsv -Dimporttsv.columns=HBASE_ROW_KEY,surname,name,age persons 'hdfs://localhost:9000/user/joe/persons.tsv'

it tries to read the file hdfs://localhost:9000/home/joe/Programs/hbase-0.96.0-hadoop2/lib/hbase-client-0.96.0-hadoop2.jar that does not exist...

Below the stack trace.

Thank you a lot for any help.

2013-10-22 19:33:52,079 INFO  [main] mapreduce.TableOutputFormat: Created table instance for persons
2013-10-22 19:33:53,253 INFO  [main] mapreduce.JobSubmitter: Cleaning up the staging area file:/tmp/hadoop-joe/mapred/staging/joe1659915806/.staging/job_local1659915806_0001
2013-10-22 19:33:53,256 ERROR [main] security.UserGroupInformation: PriviledgedActionException as:joe (auth:SIMPLE) cause:java.io.FileNotFoundException: File does not exist: hdfs://localhost:9000/home/joe/Programs/hbase-0.96.0-hadoop2/lib/hbase-client-0.96.0-hadoop2.jar
Exception in thread "main" java.io.FileNotFoundException: File does not exist: hdfs://localhost:9000/home/joe/Programs/hbase-0.96.0-hadoop2/lib/hbase-client-0.96.0-hadoop2.jar
    at org.apache.hadoop.hdfs.DistributedFileSystem$17.doCall(DistributedFileSystem.java:1110)
    at org.apache.hadoop.hdfs.DistributedFileSystem$17.doCall(DistributedFileSystem.java:1102)
    at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1102)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:288)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.getFileStatus(ClientDistributedCacheManager.java:224)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestamps(ClientDistributedCacheManager.java:93)
    at org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager.determineTimestampsAndCacheVisibilities(ClientDistributedCacheManager.java:57)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:264)
    at org.apache.hadoop.mapreduce.JobSubmitter.copyAndConfigureFiles(JobSubmitter.java:300)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:387)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1268)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1265)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1491)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1265)
    at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1286)
    at org.apache.hadoop.hbase.mapreduce.ImportTsv.run(ImportTsv.java:480)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
    at org.apache.hadoop.hbase.mapreduce.ImportTsv.main(ImportTsv.java:484)

Body:
In Hadoop, Configure parameters as follows:etc/hadoop/mapred-site.xml:

<configuration>
    <property>
        <name>mapreduce.framework.name</name>
        <value>yarn</value>
    </property>
</configuration>

etc/hadoop/yarn-site.xml:

<configuration>
    <property>
        <name>yarn.nodemanager.aux-services</name>
        <value>mapreduce_shuffle</value>
    </property>
</configuration>


问:
The most efficient way to compare object's property in two arrays
I need to check in Angular2 if one object's property in one array is the same in another array and return value. Is there any more efficient way to do it or maybe something similar to .contains in Swift?

```<code>doSomething(){
    for (let element1 of array1) {
        for (let element2 of array2) {
            if (element1.id == element2.id) {
                return Observable.fromPromise(element2);
            }
        }
    }
}
</code>```

EDIT:

I have to subscribe to this value because I am loading value from the database (in fromPromise):

```<code>this.doSomething().subscribe(id => {
...
}
</code>```

答:
=== for comparing values of id

```<code>   for (const element1 of array1) {
      for (const element2 of array2) {
        if (element1.id === element2.id) {
          return Observable.fromPromise(element2);
        }
      }
    }
</code>```

if you whant to know if the property call id exist in both

```<code>for (const element1 of array1) {
 Object.keys(element1).forEach(key => {
      if(key === 'id') {
          for (const element2 of array2) {
            if (element2.hasOwnProperty(key)) {
              return Observable.fromPromise(element2);
            }
          }
        }
      }
   }
</code>```

Body:
I need to check in Angular2 if one object's property in one array is the same in another array and return value. Is there any more efficient way to do it or maybe something similar to .contains in Swift?

doSomething(){
    for (let element1 of array1) {
        for (let element2 of array2) {
            if (element1.id == element2.id) {
                return Observable.fromPromise(element2);
            }
        }
    }
}

EDIT:

I have to subscribe to this value because I am loading value from the database (in fromPromise):

this.doSomething().subscribe(id => {
...
}

Body:
=== for comparing values of id

   for (const element1 of array1) {
      for (const element2 of array2) {
        if (element1.id === element2.id) {
          return Observable.fromPromise(element2);
        }
      }
    }

if you whant to know if the property call id exist in both

for (const element1 of array1) {
 Object.keys(element1).forEach(key => {
      if(key === 'id') {
          for (const element2 of array2) {
            if (element2.hasOwnProperty(key)) {
              return Observable.fromPromise(element2);
            }
          }
        }
      }
   }


问:
Deserialization of Untrusted Data from XML or JSON
I know deserialization can be vulnerable when an object is serialized with the standard "Serializable" interface (refer to this). But is this vulnerability applied when an object is serialized to XML or JSON? And if it is, how does that happen?
I can't really see how that could happen, so I would appreciate some examples.
Thanks in advance.</p>

答:
That quite specifically depends on the serialization library that you use to deserialize objects and often the parameters used, so it's hard to provide a single answer.

As to "is it possible", yes, it's possible. Here's a sample exploit for XStream, for example:

http://blog.diniscruz.com/2013/12/xstream-remote-code-execution-exploit.html


问:
How do I set editable property of p-column dynamically in ngprime p-datatable
I am using p-datatable from ngprime.

```<code> <p-dataTable [value]="config" [(selection)]="selectedEnviornment" [editable]="true">
  <p-column field="userName" header="User Name" [editable]="false"></p-column>
    <p-column field="password" header="Email" [editable]="false"></p-column>
</p-dataTable>
</code>```

In my component.ts

```<code>for (var index = 0; index < this.config.length; index++) {
this.config[index].editable=true;
      }},
</code>```

Here I have set editable property of my config which is set of rows in p-datatable.

How do I access "editable" property of row from component and set it to editable property of p-column.

Thanks for help.

答:
Use data binding for setting the parameter

[hidden]="yourHiddenParam"

and then in the component declaration:
yourHiddenParam: string = 'false';

Then change the variable.

Body:
I am using p-datatable from ngprime.

In my component.ts

for (var index = 0; index < this.config.length; index++) {
this.config[index].editable=true;
      }},

Here I have set editable property of my config which is set of rows in p-datatable.

How do I access "editable" property of row from component and set it to editable property of p-column.

Thanks for help.


问:
knex raw query schema builder
I would like use the knex raw for schema building. Mainly I want to use to create this session table because seems like knex doesn't have collate functionality

```<code>CREATE TABLE session (
    sid varchar NOT NULL COLLATE "default",
    sess json NOT NULL,
    expire timestamp(6) NOT NULL
)

WITH (OIDS=FALSE);

ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;
</code>```

I tried putting the entire thing in the quotes in knex.raw(), but it's giving me errors.
What is the best strategy in this case?

答:
The short answer is to use knex.schema.raw rather than knex.raw.

The raw below worked for me. I created an abbreviated version of the SQLs since I was getting SQLite Syntax errors while testing with SQLite. Also, note the use of .on('query-error',... which is helpful in returning SQL engine errors.

```<code>let rawCreate = 'CREATE TABLE session ( '+
    'sid varchar NOT NULL, sess json NOT NULL, '+
    'expire timestamp(6) NOT NULL );';
let rawCreateOriginal = 'CREATE TABLE session ( '+
    'sid varchar NOT NULL COLLATE "default", sess json NOT NULL, '+
    'expire timestamp(6) NOT NULL ) WITH (OIDS=FALSE);';

let rawAlter = 'ALTER TABLE "session" ADD KEY "sid" NOT DEFERRABLE INITIALLY IMMEDIATE;';
let rawAlterOriginal = 'ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;';

return knex.schema.hasTable('session')
    .then(function(exists) {
        if (!exists) {
            return knex.schema.raw(rawCreate)
            .on('query-error', function(ex, obj) {
                console.log("DA.INIT81 query-error ex:", ex, "obj:", obj);
            }).then(function() {
                console.log("DA.INIT01 Created table session.");
            }).then(function() {
                return knex.schema.raw(rawAlter)
            }).then(function() {
                console.log("DA.INIT02 Altered table session.");
            });
        }
    })
    .catch((ex) => {
        console.error("DA.INIT88 Create or Alter table session is broken. ex:",ex);
    });
</code>```

Hope this helps!
Gary.

Title: knex raw query schema builder

Body:
I would like use the knex raw for schema building. Mainly I want to use to create this session table because seems like knex doesn't have collate functionality

CREATE TABLE session (
    sid varchar NOT NULL COLLATE "default",
    sess json NOT NULL,
    expire timestamp(6) NOT NULL
)

WITH (OIDS=FALSE);

ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;

I tried putting the entire thing in the quotes in knex.raw(), but it's giving me errors.
What is the best strategy in this case?

Body:
The short answer is to use knex.schema.raw rather than knex.raw.

The raw below worked for me. I created an abbreviated version of the SQLs since I was getting SQLite Syntax errors while testing with SQLite. Also, note the use of .on('query-error',... which is helpful in returning SQL engine errors.

let rawCreate = 'CREATE TABLE session ( '+
    'sid varchar NOT NULL, sess json NOT NULL, '+
    'expire timestamp(6) NOT NULL );';
let rawCreateOriginal = 'CREATE TABLE session ( '+
    'sid varchar NOT NULL COLLATE "default", sess json NOT NULL, '+
    'expire timestamp(6) NOT NULL ) WITH (OIDS=FALSE);';

let rawAlter = 'ALTER TABLE "session" ADD KEY "sid" NOT DEFERRABLE INITIALLY IMMEDIATE;';
let rawAlterOriginal = 'ALTER TABLE "session" ADD CONSTRAINT "session_pkey" PRIMARY KEY ("sid") NOT DEFERRABLE INITIALLY IMMEDIATE;';

return knex.schema.hasTable('session')
    .then(function(exists) {
        if (!exists) {
            return knex.schema.raw(rawCreate)
            .on('query-error', function(ex, obj) {
                console.log("DA.INIT81 query-error ex:", ex, "obj:", obj);
            }).then(function() {
                console.log("DA.INIT01 Created table session.");
            }).then(function() {
                return knex.schema.raw(rawAlter)
            }).then(function() {
                console.log("DA.INIT02 Altered table session.");
            });
        }
    })
    .catch((ex) => {
        console.error("DA.INIT88 Create or Alter table session is broken. ex:",ex);
    });

Hope this helps!
Gary.


问:
push and pull not ordering the elements correctly in Bootstrap4
In the following code, I want to swap positions of Small and Large HTML element when resolution is sm or xs. When I add pull- and push-, the layout goes berserk! What is the correct way to use push- and pull-?

```<code><body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
                <div class="alert alert-success">
                    Hello World
                </div>
            </div>
        </div>
        <div class="row">
<!-- div class="col-xs-6  pull-xs-12 col-md-3 -- This doesn't work>
            <div class="col-xs-6 col-md-3">
                <div class="row">
                    <div class="col-md-12"><h5>Small</h5></div>
                </div>
                <div class="row">
                    <div class="col-md-4">sm1</div>
                    <div class="col-md-4">sm2</div>
                    <div class="col-md-4">sm3</div>
                </div>
            </div>
            <div class="col-xs-6 col-md-3">
                <div class="row">
                    <div class="col-md-12"><h5>Medium</h5></div>
                </div>
                <div class="row">
                    <div class="col-md-4">md1</div>
                    <div class="col-md-4">md2</div>
                    <div class="col-md-4">md3</div>
                </div>
            </div>

            <div class="col-xs-6 col-md-3">
                <div class="row">
                    <div class="col-md-12"><h5>Large</h5></div>
                </div>
                <div class="row">
                    <div class="col-md-4">lg1</div>
                    <div class="col-md-4">lg2</div>
                    <div class="col-md-4">lg3</div>
                </div>
            </div>
<!-- div class="col-xs-6  push-xs-12 col-md-3 -- This doesn't work>
            <div class="col-xs-6 col-md-3">
                <div class="row">
                    <div class="col-md-12"><h5>X-Large</h5></div>
                </div>
                <div class="row">
                    <div class="col-md-4">xl1</div>
                    <div class="col-md-4">xl2</div>
                    <div class="col-md-4">xl3</div>
                </div>
            </div>
        </div>
    </div>
    <div>I am free</div>
    <script src="bower_components/jquery/dist/jquery.min.js"></script>
    <script src="bower_components/tether/dist/js/tether.min.js"></script>
    <script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
</body>
</code>```

答:
If you are using the newest version, Bootstrap 4 beta 2, you should use the order classes.

They support breakpoints, so you could use something like order-1 order-sm-2 as a class on your column(s).

You can read more about them here.

For Bootstrap 4 alpha:

If you have a layout like col-8 and col-4 and want to reorder these, you'll use these classes: col-8 push-4 and col-4 pull-8.

Body:
In the following code, I want to swap positions of Small and Large HTML element when resolution is sm or xs. When I add pull- and push-, the layout goes berserk! What is the correct way to use push- and pull-?

                    Hello World


问:
Betrieve access to data without DDF
I would need help to access data from Betrieve files.

Persasive ODBC driver need a DDF file that define the "schema" for each table, my problem is that DDF file not exist.

The QBasic code that I should migrate to C#, make a substring functions and "cast" for every data type. If I can undestand the syntax, I could create the needed files.

I had used the DDF Builder of PSQLv11, but the aplication send an error "Invalid collating sequence"

Someone can upload an example with BTR and DDF files to know if it works with ODBC?

Here is the code and DB: http://www.mediafire.com/?mnvfa1tg1d6y64w

答: I realize this post is nearly five years old, but I thought I'd contribute in case someone else comes across this in a search.  Any application written in QBasic would not likely be using Pervasive SQL but rather an older version of Windows Btrieve, or even more likely DOS Btrieve.  Pervasive stopped selling and supporting the version that is probably required for the application in question a long time ago, specifically 6.15 for Windows.  I believe the last version for DOS was 5.10a. Both used (optionally) DDF files, specifically FILE.DDF, FIELD.DDF, and INDEX.DDF.  Anything created with Pervasive's SQL version of their DDF manager would not likely be backwards compatible and might not even be able to read the Btrieve Data.  This question might have received better attention had it been tagged for Btrieve.</p>

Title: Betrieve access to data without DDF


问:
Dynamically Filter an Array of Objects in Vue.js
I have a Vue.js app. In this app, I'm trying to dynamically apply filter value to an Array of objects. Each object in the Array has fields. I'm trying to filter these objects by field values. Each field can be filtered by multiple values.

At this time, I have been unsuccessful in figuring out how to do this filtering. I've tried using JavaScript's baked-in filter function. However, that always returned an empty result set for me. I've put together this Fiddle, which includes this code:

```<code>new Vue({
  el: '#app',
  data: {
    currentFilterProperty: '',
    currentFilterValue: '',

    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    dataFilters: [],
    data: [
      { name:'Patricia Miller', age:69, birthday:'04-15-1948' },
      { name:'Bill Baggett', age:62, birthday:'05-07-1955' },
      { name:'Maxine Thies', age:21, birthday:'11-28-1995' },
      { name:'Alison Battle', age:65, birthday:'08-07-1952' },
      { name:'Dick Triplett', age:25, birthday:'08-27-1982' }
    ]
  },

  methods: {
    addFilter: function() {
      var f = this.dataFilters[this.currentFilterProperty];
      if (!f) {
        this.dataFilters = {};
        this.dataFilters[this.currentFilterProperty] = [ this.currentFilterValue ];
      } else {
        this.dataFilters[this.currentFilterProperty].push(this.currentFilterValue);
      }

      // How to apply filter?
    }
  }
})
</code>```

I'm not sure how to apply the filters to the data object.

答:
Take a look the below code.  Change your method to a computed property and then the filter can happen automatically without pressing a button. The fiddle always filters by Name so you'll need to make a few adjustments to work for all filter criteria, but it should get you moving in the correct direction.

new Vue({
  el: '#app',
  data: {
    currentFilterProperty: '',
    currentFilterValue: '',
    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' }
    ],
    data: [
      { name:'Patricia Miller', age:69, birthday:'04-15-1948' },
      { name:'Bill Baggett', age:62, birthday:'05-07-1955' },
      { name:'Maxine Thies', age:21, birthday:'11-28-1995' },
      { name:'Alison Battle', age:65, birthday:'08-07-1952' },
      { name:'Dick Triplett', age:25, birthday:'08-27-1982' }
    ]
  },
  computed:{
   filteredData(){
     var self = this;
        // Add condition for currentFilterProperty == 'Name'
     if(this.currentFilterValue != undefined && this.currentFilterValue != ''){
       return this.data.filter(function(d){
         //alert(d.name + " " + this.currentFilterValue);
        return d.name.indexOf(self.currentFilterValue) != -1;
       });
      }
      // else if(currentFilterProperty == 'Date'){
      // return this.data.filter(function(d){

        //return d.birthday.indexOf(self.currentFilterValue) != -1;
      // });
      else{
       return this.data;
      }
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.4/vue.min.js"></script>

<div id="app">
  <div>
    <select v-model="currentFilterProperty">
      <option v-for="c in cols" :value="c.prop">{{c.title}}</option>
    </select>

    <input placeholder="filter value" v-model="currentFilterValue" />
  </div>
  <hr />

  <table>
    <tbody>
      <tr v-for="(record, index) in filteredData">
        <td style="padding-right:18px;">{{ record.name }}</td>
        <td style="padding-right:18px;">{{ record.age }}</td>
        <td>{{ record.birthday }}</td>
      </tr>
    </tbody>
  </table>
</div></code>```

Body:
I have a Vue.js app. In this app, I'm trying to dynamically apply filter value to an Array of objects. Each object in the Array has fields. I'm trying to filter these objects by field values. Each field can be filtered by multiple values.

At this time, I have been unsuccessful in figuring out how to do this filtering. I've tried using JavaScript's baked-in filter function. However, that always returned an empty result set for me. I've put together this Fiddle, which includes this code:

new Vue({
  el: '#app',
  data: {
    currentFilterProperty: '',
    currentFilterValue: '',

    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' },
    ],

    dataFilters: [],
    data: [
      { name:'Patricia Miller', age:69, birthday:'04-15-1948' },
      { name:'Bill Baggett', age:62, birthday:'05-07-1955' },
      { name:'Maxine Thies', age:21, birthday:'11-28-1995' },
      { name:'Alison Battle', age:65, birthday:'08-07-1952' },
      { name:'Dick Triplett', age:25, birthday:'08-27-1982' }
    ]
  },

  methods: {
    addFilter: function() {
      var f = this.dataFilters[this.currentFilterProperty];
      if (!f) {
        this.dataFilters = {};
        this.dataFilters[this.currentFilterProperty] = [ this.currentFilterValue ];
      } else {
        this.dataFilters[this.currentFilterProperty].push(this.currentFilterValue);
      }

      // How to apply filter?
    }
  }
})

I'm not sure how to apply the filters to the data object.

Body:
Take a look the below code.  Change your method to a computed property and then the filter can happen automatically without pressing a button. The fiddle always filters by Name so you'll need to make a few adjustments to work for all filter criteria, but it should get you moving in the correct direction.

new Vue({
  el: '#app',
  data: {
    currentFilterProperty: '',
    currentFilterValue: '',
    cols: [
      { title: 'Name', prop:'name' },
      { title: 'Age', prop:'age' },
      { title: 'Birthday', prop:'birthday' }
    ],
    data: [
      { name:'Patricia Miller', age:69, birthday:'04-15-1948' },
      { name:'Bill Baggett', age:62, birthday:'05-07-1955' },
      { name:'Maxine Thies', age:21, birthday:'11-28-1995' },
      { name:'Alison Battle', age:65, birthday:'08-07-1952' },
      { name:'Dick Triplett', age:25, birthday:'08-27-1982' }
    ]
  },
  computed:{
   filteredData(){
     var self = this;
        // Add condition for currentFilterProperty == 'Name'
     if(this.currentFilterValue != undefined && this.currentFilterValue != ''){
       return this.data.filter(function(d){
         //alert(d.name + " " + this.currentFilterValue);
        return d.name.indexOf(self.currentFilterValue) != -1;
       });
      }
      // else if(currentFilterProperty == 'Date'){
      // return this.data.filter(function(d){

        //return d.birthday.indexOf(self.currentFilterValue) != -1;
      // });
      else{
       return this.data;
      }
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.4/vue.min.js"></script>

<div id="app">
  <div>
    <select v-model="currentFilterProperty">
      <option v-for="c in cols" :value="c.prop">{{c.title}}</option>
    </select>

    <input placeholder="filter value" v-model="currentFilterValue" />
  </div>
  <hr />

  <table>
    <tbody>
      <tr v-for="(record, index) in filteredData">
        <td style="padding-right:18px;">{{ record.name }}</td>
        <td style="padding-right:18px;">{{ record.age }}</td>
        <td>{{ record.birthday }}</td>
      </tr>
    </tbody>
  </table>
</div>


问:
Declare a static property in an Objective-C class interface
I'm defining an Objective-C class:

```<code>@interface MyRequest : NSObject

@property (strong, nonatomic, readonly) NSDecimalNumber *myNumber;

@property (strong, nonatomic, readonly) CommConfig *commConfig;

@property (nonatomic, assign, readonly) BOOL debug;
</code>```

How do I make commConfig a static variable? When I use the 'class' keyword, the compiler gives me the following warning:

Class property 'commConfig' requires method 'commConfig' to be defined - use @dynamic or provide a method implementation in this class implementation

And the constructor doesn't recognize this line anymore:

```<code>_commConfig = commConfig
</code>```

答:
If not implemented by the programmer instance properties are automatically implemented by the compiler - an instance variable allocated and getter and/or setter methods written. Class properties are never automatically implemented, you therefore need to declare the static backing variable and define the getter. In your @implementation add:

```<code>static CommConfig *_commConfig;

+ (CommConfig *) commConfig { return _commConfig; }
</code>```

You can call the backing anything you wish, e.g. to follow a naming convention for global/static variables.

HTH

Body:
I'm defining an Objective-C class:

@interface MyRequest : NSObject

@property (strong, nonatomic, readonly) NSDecimalNumber *myNumber;

@property (strong, nonatomic, readonly) CommConfig *commConfig;

@property (nonatomic, assign, readonly) BOOL debug;

How do I make commConfig a static variable? When I use the 'class' keyword, the compiler gives me the following warning:

Class property 'commConfig' requires method 'commConfig' to be defined - use @dynamic or provide a method implementation in this class implementation

And the constructor doesn't recognize this line anymore:

_commConfig = commConfig

Body:
If not implemented by the programmer instance properties are automatically implemented by the compiler - an instance variable allocated and getter and/or setter methods written. Class properties are never automatically implemented, you therefore need to declare the static backing variable and define the getter. In your @implementation add:

static CommConfig *_commConfig;

+ (CommConfig *) commConfig { return _commConfig; }

You can call the backing anything you wish, e.g. to follow a naming convention for global/static variables.

HTH


问:
How to reset mysql modes to default after doing SET sql_mode = ''
I accidentally did SET sql_mode = '' while trying to disable ONLY_FULL_GROUP_BY which resets all modes currently enabled. How can I revert to the default settings? I'm running MySQL 5.7.20 on a Homestead Vagrant box.

Thanks

答:
for default  inn 5.7 you should set

```<code>sql_mode = "ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, NO_ZERO_IN_DATE,
      NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER,
      NO_ENGINE_SUBSTITUTION"
</code>```

https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html

check for your real mysql version and subversion for other param

Body:
for default  inn 5.7 you should set

sql_mode = "ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, NO_ZERO_IN_DATE,
      NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, NO_AUTO_CREATE_USER,
      NO_ENGINE_SUBSTITUTION"

https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html

check for your real mysql version and subversion for other param


问:
Singleton pattern for data context
I am using singleton pattern in an ASP.net application. I use LINQ to SQL DataContext.

I face this problem: when a new record is inserted using the DataContext, it is inserted into the database when the changes are submitted. But when the same data is queried using the DataContext, the data is not retrieved, but it's read when closing and opening the application again.

Please let me know how to solve this issue.

I user C# 4.0, LINQ, SQL Server 2008.

Regards,
Jebli

答:
An instance of DataContext is not meant to be used as a Singleton.  An instance of DataContext is meant to be used in a UnitOfWork (a completely different pattern).

If you use the appropriate lifecycle pattern for instances of DataContext, you will rarely have to deal with stale data and never have to deal with a single database connection shared between multiple threads.

Title: Singleton pattern for data context


问:
Parse errors when using partial functions in where statments (Haskell)
I'm pretty new to Haskell and I've run into this problem a few times and have had no luck finding answers online.

```<code>playDomsHandler (dp1,h1,s1) (dp2,h2,s2) b _
    -- players 1 and 2 both knocking, game ends
    | knockingP b h1 && knockingP b h2 = (b, (s1, s2))
    -- just player 1 knocking, player 2 makes a move
    | knockingP b h1 = playDomsHandler (dp1,h1,s1) (dp2,h2,nScore2) nBoard2 2
    -- just player 2 knocking, player 1 makes a move
    | knockingP b h2 = playDomsHandler (dp1,h1,nScore1) (dp2,h2,s2) nBoard1 1
    where
      (nBoard1, nScore1) = nextPlay (dp1,h1,s1) b
      (nBoard2, nScore2) = nextPlay (dp2,h2,s2) b
</code>```

Gives a parse error. (The first bracket in the (nBoard2, nScore2) line)

I've used where statements plenty before but I always seem to run into this problem when using partial functions

Any help much appreciated.

答:
I bet you are using tabs instead of white space for indentation.

The statements in the where construction must be aligned. Haskell interprets every tabs like 8 white space, so if you are messing with white space and tabs maybe your functions are not aligned.

If your editor is configured with tabs showing to 4 white space, you are not seeing this problem, but Haskell does.

I will use - for white space and \t por tabs (equal to 4 white space).

For example:

```<code>where
----(nBoard1, nScore1) = nextPlay (dp1,h1,s1) b
\t  (nBoard2, nScore2) = nextPlay (dp2,h2,s2) b
</code>```

These are not aligned, so Haskell will give parse error on (nBoard2, nScore2)

I recomend to use always white space instead of tabs. Most editors can be configured to replace tabs with 4 or 8 white space characters, so you will not get this problem.

Body:
I'm pretty new to Haskell and I've run into this problem a few times and have had no luck finding answers online.

playDomsHandler (dp1,h1,s1) (dp2,h2,s2) b _
    -- players 1 and 2 both knocking, game ends
    | knockingP b h1 && knockingP b h2 = (b, (s1, s2))
    -- just player 1 knocking, player 2 makes a move
    | knockingP b h1 = playDomsHandler (dp1,h1,s1) (dp2,h2,nScore2) nBoard2 2
    -- just player 2 knocking, player 1 makes a move
    | knockingP b h2 = playDomsHandler (dp1,h1,nScore1) (dp2,h2,s2) nBoard1 1
    where
      (nBoard1, nScore1) = nextPlay (dp1,h1,s1) b
      (nBoard2, nScore2) = nextPlay (dp2,h2,s2) b

Gives a parse error. (The first bracket in the (nBoard2, nScore2) line)

I've used where statements plenty before but I always seem to run into this problem when using partial functions

Any help much appreciated.

Body:
I bet you are using tabs instead of white space for indentation.

The statements in the where construction must be aligned. Haskell interprets every tabs like 8 white space, so if you are messing with white space and tabs maybe your functions are not aligned.

If your editor is configured with tabs showing to 4 white space, you are not seeing this problem, but Haskell does.

I will use - for white space and \t por tabs (equal to 4 white space).

For example:

where
----(nBoard1, nScore1) = nextPlay (dp1,h1,s1) b
\t  (nBoard2, nScore2) = nextPlay (dp2,h2,s2) b

These are not aligned, so Haskell will give parse error on (nBoard2, nScore2)

I recomend to use always white space instead of tabs. Most editors can be configured to replace tabs with 4 or 8 white space characters, so you will not get this problem.


问:
How can I implement scheduled push notifications for Android and IOS App on my parse server?
Parse-push-notifications have certain cons including -

No job queue system.

Scheduled push is not supported.

And so I am thinking to use a different pushadapter.

I have two questions -

Does my approach seems correct?

If yes, which npm package/ push adapter can I use?

What will be the configuration of using this third-party push adapter?

答:
Using third-party push adapters is a valid approach. They are provided by companies like

OneSignal (Website | Adapter Github link)

Pushwoosh (Website | Adapter Github link)

The caveat is that it might cost money, or that they are selling the push data to advertisers. Which, in the case of OneSignal, is explicitly stated in their help section under "FREE".

In that case you need to replace the standard adapter (which has paths to the APNS p12 certificates and credentials to FCM) with another configuration that includes your API keys to the third party provider. This is described in the readme of the adapter repositories.
Then you need to configure their service with the APNS certificates and FCM credentials.

Alternatively, you can use your own scheduler, but that seems a bit more involved. I've read a good article about it here: https://www.linkedin.com/pulse/how-get-parse-background-job-functionality-server-andrey-gordeev/
and the Parse Team recommends using kue for the job (https://github.com/Automattic/kue).

There are some efforts in the Parse Open Source community to build an adapter that supports push notification scheduling. Check out this issue for the latest news (November 2017):
https://github.com/parse-community/parse-server/issues/4105


问:
"URLize" string in ruby
I'm getting some strings on human readable format, and those are gonna be titles of my wordpress posts. So, for generate the url for that post, I would like to know if there's some method for "urlize" a string in ruby. For example, if I have the string "Doing some test on my áccented string ", I would like to get "doing-some-test-on-my-accented-string" or do I have to write my own? Thanks in advance!</p>

答:
After some suggestions, implemented my own method:

```<code>require 'i18n'

I18n.config.available_locales = :en

def urlize(string)
   I18n.transliterate(string).squeeze.gsub(" ", "-").downcase
end
</code>```

Hope this helps someone, thanks for the help!

Title: "URLize" string in ruby

Body:
After some suggestions, implemented my own method:

require 'i18n'

I18n.config.available_locales = :en

def urlize(string)
   I18n.transliterate(string).squeeze.gsub(" ", "-").downcase
end

Hope this helps someone, thanks for the help!


问:
Docker php:5.6-apache 403 (because search permissions are missing on a component of the path)
Files tree:

```<code>├── docker-compose.yml
├── Dockerfile
└── www
    └── index.html
</code>```

Dockerfile :

```<code>FROM php:5.6-apache
ADD ./www /var/www/html/
WORKDIR /var/www/html/
</code>```

docker-compose.yml

```<code>version: '2'
services:
  php5_6:
    build: .
    ports :
     - "80:80"
    volumes:
     - ./www:/var/www/html/
</code>```

Try to start docker

```<code>$ docker-compose up
[core:error] [pid 17] (13)Permission denied: [client 172.19.0.1:53514] AH00035: access to /index.html denied (filesystem path '/var/www/html/index.html') because search permissions are missing on a component of the path
</code>```

In browser http://localhost 403 page

What's wrong?

答: The problem is enabled SELinux. Disable in /etc/selinux/conf will solve it.</p>

Body:
Files tree:

├── docker-compose.yml
├── Dockerfile
└── www
    └── index.html

Dockerfile :

FROM php:5.6-apache
ADD ./www /var/www/html/
WORKDIR /var/www/html/

docker-compose.yml

version: '2'
services:
  php5_6:
    build: .
    ports :
     - "80:80"
    volumes:
     - ./www:/var/www/html/

Try to start docker

$ docker-compose up
[core:error] [pid 17] (13)Permission denied: [client 172.19.0.1:53514] AH00035: access to /index.html denied (filesystem path '/var/www/html/index.html') because search permissions are missing on a component of the path

In browser http://localhost 403 page

What's wrong?


问:
What is the most simple way to remove a row in a CSV using Python CSV?
I'm having trouble finding clear and concise methods of removing a select row from a CSV using the CSV module (not the Panda since it's required to be installed). I would also like to remove a range of rows separately. Every article and every question I've seen either or abroad are not clear at all and tend to include specific logic people are asking about. I just want a clear cut answer that is very simple. </p>

<p>I would like to use argv to provide a filename, beginning row number, and end row numbers. So something like python Script.py /CSVfile.csv 1 5, meaning the file name and remove rows 1 through 5 (beginning and ending). I'm new to Python scripting and I get halfway there, but there is always some logic people include that isn't relevant to what I need to do. I just keep getting blocked (as I typically do when trying to code), any help is appreciated. </p>

```<code>import csv
import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

with open (var1, 'w') as file1:
   reader = csv.reader(file1)
   for line in reader:
      file1.writer()
</code>```

答:
Just enumerate the lines and do not copy them if their index is in the range you want to exclude:

```<code>import csv
import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

with open (var1, 'r') as file1:
   reader = csv.reader(file1)
   for i, line in enumerate(reader):
      if (i < var2) or (i > var3):
          # process line...
</code>```

If you want to filter the file in place, you would write the selected rows to a temporary file and finally rename to new file to the old name, but here there are no valid reason for parsing the rows

```<code>import sys
import tempfile

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

(file2, name2) = tmpfile.msktemp()     # get a temporary file
try:
    with open (var1, 'r') as file1:
       for i, line in enumerate(file1):
          if (i < var2) or (i > var3):   # copy selected lines to temp file
              dummy = file2.write(line)
    file2.close()
except:
    remove(name2) # error: remove tempfile
    file2 = None
if file2 is not None:      # successful copy: rename to initial name
    remove(var1)
    rename(name2, var1)
</code>```

Body:
I'm having trouble finding clear and concise methods of removing a select row from a CSV using the CSV module (not the Panda since it's required to be installed). I would also like to remove a range of rows separately. Every article and every question I've seen either or abroad are not clear at all and tend to include specific logic people are asking about. I just want a clear cut answer that is very simple.

I would like to use argv to provide a filename, beginning row number, and end row numbers. So something like python Script.py /CSVfile.csv 1 5, meaning the file name and remove rows 1 through 5 (beginning and ending). I'm new to Python scripting and I get halfway there, but there is always some logic people include that isn't relevant to what I need to do. I just keep getting blocked (as I typically do when trying to code), any help is appreciated.

import csv
import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

with open (var1, 'w') as file1:
   reader = csv.reader(file1)
   for line in reader:
      file1.writer()

Body:
Just enumerate the lines and do not copy them if their index is in the range you want to exclude:

import csv
import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

with open (var1, 'r') as file1:
   reader = csv.reader(file1)
   for i, line in enumerate(reader):
      if (i < var2) or (i > var3):
          # process line...

If you want to filter the file in place, you would write the selected rows to a temporary file and finally rename to new file to the old name, but here there are no valid reason for parsing the rows

import sys
import tempfile

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

(file2, name2) = tmpfile.msktemp()     # get a temporary file
try:
    with open (var1, 'r') as file1:
       for i, line in enumerate(file1):
          if (i < var2) or (i > var3):   # copy selected lines to temp file
              dummy = file2.write(line)
    file2.close()
except:
    remove(name2) # error: remove tempfile
    file2 = None
if file2 is not None:      # successful copy: rename to initial name
    remove(var1)
    rename(name2, var1)


问:
How to Speed up Android Studio 3.0
I just want to ask "How can I speed up my Android Studio?". Though I do own:

```<code>Dell Inspiron 15R
12GB of RAM Core i7 (N5537),
</code>```

these specs may look cool but still I am unable to working on Android Studio in Peace. As my Android Studio takes a lot of time when I reboot my machine and start the Android studio, its indexing process is way too long, the gradle build process is also way too laggy!

Even whenever I try to run my app on any device say on Virtual Device or any other real device it takes a lot of time, to switch between .java to .xml files is also way too long! For the most of times the Android Studio also stuck and hangs on different events especially on Gradle Build or refreshing the project and indexing the project files!

答: What SO are you using? I'm using the same version of Android Studio on an Acer with Windows 10, 8gb of RAM and i5-7200U, and I'm not facing these problems. Try to defrag your disk, or use a SSD, it helps a lot.</p>

Title: How to Speed up Android Studio 3.0

Body:
I just want to ask "How can I speed up my Android Studio?". Though I do own:

Dell Inspiron 15R
12GB of RAM Core i7 (N5537),

these specs may look cool but still I am unable to working on Android Studio in Peace. As my Android Studio takes a lot of time when I reboot my machine and start the Android studio, its indexing process is way too long, the gradle build process is also way too laggy!

Even whenever I try to run my app on any device say on Virtual Device or any other real device it takes a lot of time, to switch between .java to .xml files is also way too long! For the most of times the Android Studio also stuck and hangs on different events especially on Gradle Build or refreshing the project and indexing the project files!


问:
When I attempt to change the root password by following the documentation, I get a SQL Syntax Error or the password doesn't update
I'm running MariaDB MySQL on a Linux machine. When I attempt to change the password following the documentation, MySQL gives me the following error upon starting:

```<code>2017-11-17  9:25:47 139640910462912 [Note] Server socket created on IP: '::'.
ERROR: 1064 You have an error in your SQL syntax; check the manual that corresponds
   to your MariaDB server version for the right syntax to use near
   'USER 'root'@'localhost' IDENTIFIED BY 'pA$sWord^';' at line 1
2017-11-17  9:25:47 139640910462912 [Note] mysqld: ready for connections.
Version: '10.1.28-MariaDB'  socket: '/run/mysqld/mysqld.sock'  port: 3306  MariaDB Server
</code>```

The specific documentation I'm following:

The instructions assume that you will start the MySQL server from the
  Unix login account that you normally use for running it. For example,
  if you run the server using the mysql login account, you should log in
  as mysql before using the instructions. Alternatively, you can log in
  as root, but in this case you must start mysqld with the --user=mysql
  option. If you start the server as root without using --user=mysql,
  the server may create root-owned files in the data directory, such as
  log files, and these may cause permission-related problems for future
  server startups. If that happens, you will need to either change the
  ownership of the files to mysql or remove them.

Log on to your system as the Unix user that the MySQL server runs as
  (for example, mysql).

Stop the MySQL server if it is running. Locate the .pid file that
  contains the server's process ID. The exact location and name of this
  file depend on your distribution, host name, and configuration. Common
  locations are /var/lib/mysql/, /var/run/mysqld/, and
  /usr/local/mysql/data/. Generally, the file name has an extension of
  .pid and begins with either mysqld or your system's host name.

Stop the MySQL server by sending a normal kill (not kill -9) to the
  mysqld process. Use the actual path name of the .pid file in the
  following command:

```<code>shell> kill `cat /mysql-data-directory/host_name.pid`
</code>```

Use backticks (not forward quotation marks) with the cat command. These cause the
  output of cat to be substituted into the kill command.

NOTE: I used top to end the process. I'm certain it is not running.

```<code>$ ps aux | grep mysql
user 30201  0.0  0.0  10884  2296 pts/6    S+   09:43   0:00 grep mysql
</code>```

Create a text file containing the password-assignment statement on a
  single line. Replace the password with the password that you want to
  use.

MySQL 5.7.6 and later:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

MySQL 5.7.5 and earlier:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');

Save the
  file. This example assumes that you name the file /home/me/mysql-init.
  The file contains the password, so do not save it where it can be read
  by other users. If you are not logged in as mysql (the user the server
  runs as), make sure that the file has permissions that permit mysql to
  read it.

Start the MySQL server with the special --init-file option:

```<code>shell> mysqld --init-file=/home/me/mysql-init &
</code>```

The server executes
  the contents of the file named by the --init-file option at startup,
  changing the 'root'@'localhost' account password.

Other options may be necessary as well, depending on how you normally
  start your server. For example, --defaults-file may be needed before
  --init-file.

After the server has started successfully, delete /home/me/mysql-init.

MariaDB Version:

```<code>$ sudo pacman -Q | grep mariadb
libmariadbclient 10.1.28-1
mariadb 10.1.28-1
mariadb-clients 10.1.28-1
</code>```

File /change_root_password.txt:

```<code>$ ls -lha /change_root_pwd.txt
-rwxrwxrwx 1 mysql mysql 56 Nov 17 09:24 /change_root_pwd.txt
$ cat /change_root_pwd.txt
ALTER USER 'root'@'localhost' IDENTIFIED BY 'pA$sWord^';
</code>```

Command used to start mysqld that results in the above mentioned error:

```<code>sudo mysqld --user=mysql --init-file=/change_root_pwd.txt
</code>```

I found this documentation with an alternate SQL query:

If the ALTER USER statement fails to reset the password, try repeating
  the procedure using the following statements to modify the user table
  directly:

```<code>UPDATE mysql.user
    SET authentication_string = PASSWORD('MyNewPass'), password_expired = 'N'
    WHERE User = 'root' AND Host = 'localhost';
FLUSH PRIVILEGES;
</code>```

When I try that instead of the ALTER USER query, I get no error, but the password does not get updated.

答:
Perhaps I should have understood the difference between MariaDB and MySQL before asking this question.

I do not know why using that method to reset the root Password does not work, but MariaDB has a simpler way to change the root Password which is documented here:

https://www.linode.com/docs/databases/mariadb/how-to-install-mariadb-on-centos-7

Reset the MariaDB Root Password

If you forget your root MariaDB password, it can be reset.

Stop the current MariaDB server instance, then restart it with an option to not ask for a password:

```<code>sudo systemctl stop mariadb
sudo mysqld_safe --skip-grant-tables &
</code>```

Reconnect to the MariaDB server with the MariaDB root account:

```<code>mysql -u root
</code>```

Use the following commands to reset root’s password. Replace password with a strong password:

```<code>use mysql;
update user SET PASSWORD=PASSWORD("password") WHERE USER='root';
flush privileges;
exit
</code>```

Then restart MariaDB:

```<code>sudo systemctl start mariadb
</code>```

Body:
I'm running MariaDB MySQL on a Linux machine. When I attempt to change the password following the documentation, MySQL gives me the following error upon starting:

2017-11-17  9:25:47 139640910462912 [Note] Server socket created on IP: '::'.
ERROR: 1064 You have an error in your SQL syntax; check the manual that corresponds
   to your MariaDB server version for the right syntax to use near
   'USER 'root'@'localhost' IDENTIFIED BY 'pA$sWord^';' at line 1
2017-11-17  9:25:47 139640910462912 [Note] mysqld: ready for connections.
Version: '10.1.28-MariaDB'  socket: '/run/mysqld/mysqld.sock'  port: 3306  MariaDB Server

The specific documentation I'm following:

The instructions assume that you will start the MySQL server from the
  Unix login account that you normally use for running it. For example,
  if you run the server using the mysql login account, you should log in
  as mysql before using the instructions. Alternatively, you can log in
  as root, but in this case you must start mysqld with the --user=mysql
  option. If you start the server as root without using --user=mysql,
  the server may create root-owned files in the data directory, such as
  log files, and these may cause permission-related problems for future
  server startups. If that happens, you will need to either change the
  ownership of the files to mysql or remove them.

Log on to your system as the Unix user that the MySQL server runs as
  (for example, mysql).

Stop the MySQL server if it is running. Locate the .pid file that
  contains the server's process ID. The exact location and name of this
  file depend on your distribution, host name, and configuration. Common
  locations are /var/lib/mysql/, /var/run/mysqld/, and
  /usr/local/mysql/data/. Generally, the file name has an extension of
  .pid and begins with either mysqld or your system's host name.

Stop the MySQL server by sending a normal kill (not kill -9) to the
  mysqld process. Use the actual path name of the .pid file in the
  following command:

shell> kill `cat /mysql-data-directory/host_name.pid`

Use backticks (not forward quotation marks) with the cat command. These cause the
  output of cat to be substituted into the kill command.

NOTE: I used top to end the process. I'm certain it is not running.

$ ps aux | grep mysql
user 30201  0.0  0.0  10884  2296 pts/6    S+   09:43   0:00 grep mysql

Create a text file containing the password-assignment statement on a
  single line. Replace the password with the password that you want to
  use.

MySQL 5.7.6 and later:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

MySQL 5.7.5 and earlier:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');

Save the
  file. This example assumes that you name the file /home/me/mysql-init.
  The file contains the password, so do not save it where it can be read
  by other users. If you are not logged in as mysql (the user the server
  runs as), make sure that the file has permissions that permit mysql to
  read it.

Start the MySQL server with the special --init-file option:

shell> mysqld --init-file=/home/me/mysql-init &

The server executes
  the contents of the file named by the --init-file option at startup,
  changing the 'root'@'localhost' account password.

Other options may be necessary as well, depending on how you normally
  start your server. For example, --defaults-file may be needed before
  --init-file.

After the server has started successfully, delete /home/me/mysql-init.

MariaDB Version:

$ sudo pacman -Q | grep mariadb
libmariadbclient 10.1.28-1
mariadb 10.1.28-1
mariadb-clients 10.1.28-1

File /change_root_password.txt:

$ ls -lha /change_root_pwd.txt
-rwxrwxrwx 1 mysql mysql 56 Nov 17 09:24 /change_root_pwd.txt
$ cat /change_root_pwd.txt
ALTER USER 'root'@'localhost' IDENTIFIED BY 'pA$sWord^';

Command used to start mysqld that results in the above mentioned error:

sudo mysqld --user=mysql --init-file=/change_root_pwd.txt

I found this documentation with an alternate SQL query:

If the ALTER USER statement fails to reset the password, try repeating
  the procedure using the following statements to modify the user table
  directly:

UPDATE mysql.user
    SET authentication_string = PASSWORD('MyNewPass'), password_expired = 'N'
    WHERE User = 'root' AND Host = 'localhost';
FLUSH PRIVILEGES;

When I try that instead of the ALTER USER query, I get no error, but the password does not get updated.

Body:
Perhaps I should have understood the difference between MariaDB and MySQL before asking this question.

I do not know why using that method to reset the root Password does not work, but MariaDB has a simpler way to change the root Password which is documented here:

https://www.linode.com/docs/databases/mariadb/how-to-install-mariadb-on-centos-7

Reset the MariaDB Root Password

If you forget your root MariaDB password, it can be reset.

Stop the current MariaDB server instance, then restart it with an option to not ask for a password:

sudo systemctl stop mariadb
sudo mysqld_safe --skip-grant-tables &

Reconnect to the MariaDB server with the MariaDB root account:

mysql -u root

Use the following commands to reset root’s password. Replace password with a strong password:

use mysql;
update user SET PASSWORD=PASSWORD("password") WHERE USER='root';
flush privileges;
exit

Then restart MariaDB:

sudo systemctl start mariadb


问:
Filter array of dates
I know that there is .filter () in it that filters an array to return it just the way I want, and using a lot to search, when we pass what we want to search in that array.

However I'm having trouble filtering an array of dates like this:

```<code>["08:00" "09:00" "10:10" "10:30" "10:50" "11:30" "11:50" "12:00"];
</code>```

I need to filter it by past date I have start date and end date, for example step to it " 09:00 " and " 11:30 " it should return to me:

```<code>["10:10" "10:30" "10:50"]
</code>```

Trying to do this I did so in my typescript:

```<code>1. this.schedules = this.navigation.lineSelected.schedules;
2. this.schedules.filter (item => {
3. item> this.hourNow && item <this.hourFinish
4.});
</code>```

On line 1 I get all the times I have, so on line 2.4 I filter this array, but it returns everything to me.

How can I do this?

Translating what I need:

I'm going to have two strings of hours like "12:00" and "15:00" I need to make comparisons in my array, because I need the hours that are between interval as in the above example.

When I say time I'm talking about a string, so I need to compare string if it's bigger or not than the other type string that are below "12:00" will not appear in my final array, and strings larger than "15:00" will also do not.

This is the best way I can explain what I need, I do not see any other option to explain. Simply filter an array

答:
I would suggest using Moment as below and parse it to date.

```<code>var str = '15:16:33';
var d = new moment(str, 'HH:mm:ss');
</code>```

Here is more details on moment formats http://momentjs.com/docs/#/parsing/string-format/

Title: Filter array of dates

Body:
I know that there is .filter () in it that filters an array to return it just the way I want, and using a lot to search, when we pass what we want to search in that array.

However I'm having trouble filtering an array of dates like this:

["08:00" "09:00" "10:10" "10:30" "10:50" "11:30" "11:50" "12:00"];

I need to filter it by past date I have start date and end date, for example step to it " 09:00 " and " 11:30 " it should return to me:

["10:10" "10:30" "10:50"]

Trying to do this I did so in my typescript:

1. this.schedules = this.navigation.lineSelected.schedules;
2. this.schedules.filter (item => {
3. item> this.hourNow && item <this.hourFinish
4.});

On line 1 I get all the times I have, so on line 2.4 I filter this array, but it returns everything to me.

How can I do this?

Translating what I need:

I'm going to have two strings of hours like "12:00" and "15:00" I need to make comparisons in my array, because I need the hours that are between interval as in the above example.

When I say time I'm talking about a string, so I need to compare string if it's bigger or not than the other type string that are below "12:00" will not appear in my final array, and strings larger than "15:00" will also do not.

This is the best way I can explain what I need, I do not see any other option to explain. Simply filter an array

Body:
I would suggest using Moment as below and parse it to date.

var str = '15:16:33';
var d = new moment(str, 'HH:mm:ss');

Here is more details on moment formats http://momentjs.com/docs/#/parsing/string-format/


问:
win32com DLL load failed
I'm trying to add win32com to Python 2.7. After looking at this, I added the directory with the _init file (Python27\Lib\site-packages\win32com) but I still get it. I went so far as to try to add a bunch of different folders to the path that seem to have to deal with win32com but I still get the error. If it knows where the file is and I added that folder to PYTHONPATH, why is this happening? I'm using PyDev with Eclipse Juno. My code:

```<code>import win32com.client

print("hello world")
</code>```

when I try to run this, i get this error

```<code>Traceback (most recent call last):
  File "C:\Users\Daniel\EclipseWorkspace\PhotoScript\src\scriptLaunch.py", line 1, in     <module>
    import win32com.client
  File "C:\Python27\Lib\site-packages\win32com\__init__.py", line 5, in <module>
   import win32api, sys, os
ImportError: DLL load failed: The specified module could not be found.
</code>```

答:
in my case typing in cmd:
python C:\Python27\Scripts\pywin32_postinstall.py -install
cmd Windows

I hope this helps

Title: win32com DLL load failed

Body:
I'm trying to add win32com to Python 2.7. After looking at this, I added the directory with the _init file (Python27\Lib\site-packages\win32com) but I still get it. I went so far as to try to add a bunch of different folders to the path that seem to have to deal with win32com but I still get the error. If it knows where the file is and I added that folder to PYTHONPATH, why is this happening? I'm using PyDev with Eclipse Juno. My code:

import win32com.client

print("hello world")

when I try to run this, i get this error

Traceback (most recent call last):
  File "C:\Users\Daniel\EclipseWorkspace\PhotoScript\src\scriptLaunch.py", line 1, in     <module>
    import win32com.client
  File "C:\Python27\Lib\site-packages\win32com\__init__.py", line 5, in <module>
   import win32api, sys, os
ImportError: DLL load failed: The specified module could not be found.


问:
Stop Thread Runnable impossible
I have this thread:

```<code>myThread = new Thread(new Runnable() {
                    public void run() {

                        ServerSocket ss = null;

                        while (!end) {

                            final String incomingMsg;
                            try {
                                ss = new ServerSocket(2201);
                                ss.setSoTimeout(15000);
.. some code ...
    }
                });
                myThread.start();
</code>```

Now i need to stop this with button but nothing work, and i have tried with some code like:

```<code>Handler handler= new Handler();
handler.removeCallbacks(myThread);
myThread.interrupt();
</code>```

But Thread not stopping =(

答:
You can't. Android will automatically stops thread when needed.

What you can do is just stop executing the code inside run() method, Using boolean or something

Title: Stop Thread Runnable impossible

Body:
I have this thread:

myThread = new Thread(new Runnable() {
                    public void run() {

                        ServerSocket ss = null;

                        while (!end) {

                            final String incomingMsg;
                            try {
                                ss = new ServerSocket(2201);
                                ss.setSoTimeout(15000);
.. some code ...
    }
                });
                myThread.start();

Now i need to stop this with button but nothing work, and i have tried with some code like:

Handler handler= new Handler();
handler.removeCallbacks(myThread);
myThread.interrupt();

But Thread not stopping =(


问:
NoClassDefFoundError: javax/xml/bind/UnmarshalException - Spring Security oauth2
Currently I'm working on securing a REST SpringBoot service. I've decided to use oauth2 with JWT. But I'm facing that strange error on application startup. I believe there must be some mistake on spring-security-core and spring-security-jwt versions. Here is stack:

```<code>    Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
    2017-11-17 11:47:34.428 ERROR 9604 --- [           main] o.s.boot.SpringApplication               : Application startup failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at
org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527) [spring-boot-maven-plugin-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at java.base/java.lang.Thread.run(Thread.java:844) [na:na]
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 26 common frames omitted
    Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer.geDefaultMessageConverters(DefaultOAuth2ExceptionRenderer.java:117) ~[spring-security-oauth2-2.2.0.RELEASE.jar:na]
...
        at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 27 common frames omitted
    Caused by: java.lang.ClassNotFoundException: javax.xml.bind.UnmarshalException
        at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:466) ~[na:na]
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:563) ~[na:na]
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496) ~[na:na]
        ... 51 common frames omitted
</code>```

Here is my pom.xml:

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

...

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
    </dependency>
    <!-- Dependency for embed mongo testing -->
    <dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
        <version>2.0.0</version>
        <scope>test</scope>
    </dependency>
    **<!-- Dependency for web security -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>3.2.10.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>**
</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>
</code>```

Is there anything that I've missed on that Configuration?

答: I've realize that changing my jdk from jdk-9.0.1 to jdk1.8.0_151, it works! But I did not understand why jdk-9 does not include jaxb support?! </p>

Body:
Currently I'm working on securing a REST SpringBoot service. I've decided to use oauth2 with JWT. But I'm facing that strange error on application startup. I believe there must be some mistake on spring-security-core and spring-security-jwt versions. Here is stack:

    Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
    2017-11-17 11:47:34.428 ERROR 9604 --- [           main] o.s.boot.SpringApplication               : Application startup failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at
org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527) [spring-boot-maven-plugin-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at java.base/java.lang.Thread.run(Thread.java:844) [na:na]
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 26 common frames omitted
    Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer.geDefaultMessageConverters(DefaultOAuth2ExceptionRenderer.java:117) ~[spring-security-oauth2-2.2.0.RELEASE.jar:na]
...
        at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 27 common frames omitted
    Caused by: java.lang.ClassNotFoundException: javax.xml.bind.UnmarshalException
        at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:466) ~[na:na]
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:563) ~[na:na]
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496) ~[na:na]
        ... 51 common frames omitted

Here is my pom.xml:

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

...

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
    </dependency>

    <dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
        <version>2.0.0</version>
        <scope>test</scope>
    </dependency>
    **
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>3.2.10.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>**
</dependencies>

<properties>
    <java.version>1.8</java.version>
</properties>

Is there anything that I've missed on that Configuration?


问:
Does SQLAlchemy support H2DB?
Does SQLAlchemy support H2 db? I'm using pyramid and would like to connect to H2 db database. If using postgres dialect, I'm getting error like the following:</p>

```<code>File "/Users/homecamera/gotocamera/hcadmin/env/lib/python2.7/site-packages/SQLAlchemy-0.7.3-py2.7-macosx-10.4-x86_64.egg/sqlalchemy/dialects/postgresql/base.py", line 871, in initialize
super(PGDialect, self).initialize(connection)
File "/Users/homecamera/gotocamera/hcadmin/env/lib/python2.7/site-packages/SQLAlchemy-0.7.3-py2.7-macosx-10.4-x86_64.egg/sqlalchemy/engine/default.py", line 181, in initialize
self.get_isolation_level(connection.connection)
File "/Users/homecamera/gotocamera/hcadmin/env/lib/python2.7/site-packages/SQLAlchemy-0.7.3-py2.7-macosx-10.4-x86_64.egg/sqlalchemy/dialects/postgresql/base.py", line 910, in get_isolation_level
cursor.execute('show transaction isolation level')
ProgrammingError: Syntax error in SQL statement "SELECT "; expected "TOP, LIMIT, DISTINCT, ALL, *, NOT, EXISTS"; SQL statement:
show transaction isolation level [42001-140]
DETAIL:  org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SELECT "; expected "TOP, LIMIT, DISTINCT, ALL, *, NOT, EXISTS"; SQL statement:
show transaction isolation level [42001-140]
</code>```

答:
Just in case anyone stumbles over this again, I tried to get this running (as an alternative to sqlite) and it only partially works, and the only driver that works is pg8000.

With the server running using:

```<code>nohup java -cp /opt/h2/bin/h2*.jar org.h2.tools.Server -pg -pgAllowOthers -pgPort 5435 -baseDir /opt/h2-data &
</code>```

This code works in sqlalchemy:

```<code>from sqlalchemy import create_engine
engine = create_engine('postgresql+pg8000://sa:sa@localhost:5435/main')
engine.execute("SELECT 1")
</code>```

However this code throws an exception:
    from sqlalchemy_utils import create_database
    create_database('postgresql+pg8000://sa:sa@localhost:5435/main')

Exception:

```<code>sqlalchemy.exc.ProgrammingError: (pg8000.core.ProgrammingError) ('ERROR',
'HY000', 'General error: "java.lang.IllegalStateException: output binary
format is undefined" [50000-196]', 'org.h2.jdbc.JdbcSQLException: General
error: "java.lang.IllegalStateException: output binary format is undefined"
[50000-196]') [SQL: 'select version()']
</code>```

Title: Does SQLAlchemy support H2DB?

Body:
Does SQLAlchemy support H2 db? I'm using pyramid and would like to connect to H2 db database. If using postgres dialect, I'm getting error like the following:

File "/Users/homecamera/gotocamera/hcadmin/env/lib/python2.7/site-packages/SQLAlchemy-0.7.3-py2.7-macosx-10.4-x86_64.egg/sqlalchemy/dialects/postgresql/base.py", line 871, in initialize
super(PGDialect, self).initialize(connection)
File "/Users/homecamera/gotocamera/hcadmin/env/lib/python2.7/site-packages/SQLAlchemy-0.7.3-py2.7-macosx-10.4-x86_64.egg/sqlalchemy/engine/default.py", line 181, in initialize
self.get_isolation_level(connection.connection)
File "/Users/homecamera/gotocamera/hcadmin/env/lib/python2.7/site-packages/SQLAlchemy-0.7.3-py2.7-macosx-10.4-x86_64.egg/sqlalchemy/dialects/postgresql/base.py", line 910, in get_isolation_level
cursor.execute('show transaction isolation level')
ProgrammingError: Syntax error in SQL statement "SELECT "; expected "TOP, LIMIT, DISTINCT, ALL, *, NOT, EXISTS"; SQL statement:
show transaction isolation level [42001-140]
DETAIL:  org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SELECT "; expected "TOP, LIMIT, DISTINCT, ALL, *, NOT, EXISTS"; SQL statement:
show transaction isolation level [42001-140]

Body:
Just in case anyone stumbles over this again, I tried to get this running (as an alternative to sqlite) and it only partially works, and the only driver that works is pg8000.

With the server running using:

nohup java -cp /opt/h2/bin/h2*.jar org.h2.tools.Server -pg -pgAllowOthers -pgPort 5435 -baseDir /opt/h2-data &

This code works in sqlalchemy:

from sqlalchemy import create_engine
engine = create_engine('postgresql+pg8000://sa:sa@localhost:5435/main')
engine.execute("SELECT 1")

However this code throws an exception:
    from sqlalchemy_utils import create_database
    create_database('postgresql+pg8000://sa:sa@localhost:5435/main')

Exception:

sqlalchemy.exc.ProgrammingError: (pg8000.core.ProgrammingError) ('ERROR',
'HY000', 'General error: "java.lang.IllegalStateException: output binary
format is undefined" [50000-196]', 'org.h2.jdbc.JdbcSQLException: General
error: "java.lang.IllegalStateException: output binary format is undefined"
[50000-196]') [SQL: 'select version()']


问:
getting schema for a table
look at this code :

```<code>public void GetScheme4Table(string tableName)
{
    OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\" + DdListDatabases4GettingTables.SelectedValue + ".mdb;Persist Security Info=True");
    conn.Open();
    DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
                                                     new object[] { null, null, null, tableName });
    GridViewTablesScheme.DataSource = schemaTable;
    GridViewTablesScheme.DataBind();
    conn.Close();
}
</code>```

There is no rows in the schema data table how I can solve this ?

I want to get schema for my table and show in the gridview.

答:
Try the following:</p>

```<code>public DataTable GetScheme4Table(string tableName)
{
    DataTable ret = null;
    IDbCommand command = null;

    using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\" + DdListDatabases4GettingTables.SelectedValue + ".mdb;Persist Security Info=True"))
    {
        command = connection.CreateCommand();
        command.CommandText = string.Format("SELECT TOP 1 * FROM [{0}]", tableName);
        using (IDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo))
        {
            ret = reader.GetSchemaTable();
        }
    }

    return ret;
}
</code>```

Title: getting schema for a table

Body:
look at this code :

public void GetScheme4Table(string tableName)
{
    OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\" + DdListDatabases4GettingTables.SelectedValue + ".mdb;Persist Security Info=True");
    conn.Open();
    DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
                                                     new object[] { null, null, null, tableName });
    GridViewTablesScheme.DataSource = schemaTable;
    GridViewTablesScheme.DataBind();
    conn.Close();
}

There is no rows in the schema data table how I can solve this ?

I want to get schema for my table and show in the gridview.

Body:
Try the following:

public DataTable GetScheme4Table(string tableName)
{
    DataTable ret = null;
    IDbCommand command = null;

    using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\" + DdListDatabases4GettingTables.SelectedValue + ".mdb;Persist Security Info=True"))
    {
        command = connection.CreateCommand();
        command.CommandText = string.Format("SELECT TOP 1 * FROM [{0}]", tableName);
        using (IDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo))
        {
            ret = reader.GetSchemaTable();
        }
    }

    return ret;
}


答:
Please find working solution below. Enjoy :)

var dates = ["08:00", "09:00", "10:10", "10:30", "10:50", "11:30", "11:50", "12:00"]

function parseDate(dStr) {
  var now = new Date();
  now.setHours(dStr.split(':')[0]);
  now.setMinutes(dStr.split(':')[1]);
  now.setSeconds(0);
  return now;
}

function filterDates(start, end) {
  var startDate = parseDate(start);
  var endDate = parseDate(end);
  var parsedDates = dates.map(parseDate);
  return parsedDates.filter(function(dt) {
    return (dt > startDate && dt < endDate)
  }).map(function(dt) {
    return dt.getHours() + ":" + dt.getMinutes()
  })
}

var result = filterDates("09:00", "11:30");
console.log(result);```

Title: Filter array of dates


问:
Is the validation set used for anything besides monitoring progress on the Tensorflow for poets google code lab's project?
I would like to know if the validation set influences in any way the training of the network, or if it's sole purpose is to monitor the training progress (with the tensorflow for poets project in question).

If doesn't, is it okay/good-practice to reduce the validation and training sets to zero once I know the accuracy for my dataset? So in that way I can get a model trained with the most amount of data I can provide.

答:
Very briefly, you have three sets of data: training, testing, and validation.  These inputs should be distinct; any duplication between data sets will reduce some desirable aspect of your final model.

Training data is used just the way you think: these are the inputs that are matched with the expected outputs (after filtering through your model).  The model weights are adjusted until you've converged at the greatest accuracy you can manage.

Testing data is used during training to determine when training is done.  If the testing accuracy is still dropping, then your model is still learning things; when it starts to rise, you're over-fitting.

Validation data is the final check on whether your training phase got to a useful point.  This data set is entirely independent of the previous two, as is representative of not-previously-seen, real-world input.

The short answer is no.  If you fold your testing and validation data into your training set (which is what I think you're trying to ask) and re-train the model, you've changed the training conditions, and you have no evidence that the resulting training is still valid.  How do you know ho many epochs you need to train with this larger data set?  When you're ready to deploy the trained model, how do you know your new accuracy?