问:
Nested Routes with React Router v4 - Solutions
I am trying to get nested routes working on React Router v4. I am referring to this page https://reacttraining.com/react-router/web/guides/quick-start

So how they do nested route is this

```<code>import React from 'react'
import {
    BrowserRouter as Router,
    Route,
    Link
} from 'react-router-dom'

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/topics">Topics</Link></li>
          </ul>

      <hr/>

      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/topics" component={Topics}/>
    </div>
  </Router>
)

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
)

const About = () => (
  <div>
    <h2>About</h2>
  </div>
)

const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
    <ul>
      <li>
        <Link to={`${match.url}/rendering`}>
          Rendering with React
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/components`}>
          Components
        </Link>
      </li>
      <li>
        <Link to={`${match.url}/props-v-state`}>
          Props v. State
        </Link>
      </li>
    </ul>

    <Route path={`${match.url}/:topicId`} component={Topic}/>
    <Route exact path={match.url} render={() => (
      <h3>Please select a topic.</h3>
    )}/>
  </div>
)

const Topic = ({ match }) => (
  <div>
    <h3>{match.params.topicId}</h3>
  </div>
)

export default BasicExample
</code>```

This works obviously but I want to change it into a class format.

So I have tried below

index.js

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

App.js

```<code>class App extends Component {
    render() {
        return (
            <div className="container">
                <header>
                    <span className="icn-logo"><i className="material-icons">code</i></span>
                    <ul className="main-nav">
                        <li><Link to="/">Home</Link></li>
                        <li><Link to="/about">About</Link></li>
                        <li><Link to="/teachers">Teachers</Link></li>
                        <li><Link to="/courses">Courses</Link></li>
                    </ul>
                </header>
                <Route exact path="/" component={Home}/>
                <Route path="/about" component={About}/>
                <Route path="/teachers" component={Teachers}/>
                <Route path="/courses" component={Course}/>
            </div>
        );
    }
}

export default App;
</code>```

The problem is that when I click on the links, it routes to the correct url and it works but when I type in the url myself, it gives cannot GET /about and so on even though they are all rendering to same url - whether I click on the links or whether i type them myself. I am thinking App route is not being rendered except at root which I don't understand why. Does anyone know why that might be?

Also, how do I convert my code so that I can take in the match parameter like the first example code? So in topics it is taking match object as a parameter and I am guessing that is some kind of reference to its previous url

SOLUTIONS

Okay I'm going to provide solutions here as a lot of video based React Router tutorials do not cover React Router v4. I hope the noobs who are struggling with the new React Router can get help from this answer.

So basically you have to be able to differentiate client side route with the asset request and webpack-dev-server provides a perfect option for this.

All you have to do is add

```<code>devServer: {
    port: 3000,
    historyApiFallback: {
        index:'index.html'
    }
}
</code>```

to the webpack.config.js which will always point to index.html when there is no response from the server

This is my reference. Might be useful to read it https://jaketrent.com/post/pushstate-webpack-dev-server/

答:
This is generally a server problem rather than anything in your client-side code.  If you are using express with static serving:

```<code>app.use(express.static('build'));
</code>```

Then if there isn't a file in the directory build, or another express route that matches e.g. /about then express won't respond with anything.

You need to add a catch all route to express in addition to the static middleware above - it must be after it in your route definitions though.

```<code>app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../build', 'index.html'));
};
</code>```

This is a wildcard route, so anything that hasn't been matched by the static middleware will be sent index.html.  Once that lands in your browser then react-router will take over and load the correct components.

Body:
I am trying to get nested routes working on React Router v4. I am referring to this page https://reacttraining.com/react-router/web/guides/quick-start

So how they do nested route is this

import React from 'react'
import {
    BrowserRouter as Router,
    Route,
    Link
} from 'react-router-dom'

const BasicExample = () => (
  <Router>

<Link to="/">Home</Link>

<Link to="/about">About</Link>

<Link to="/topics">Topics</Link>

      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/topics" component={Topics}/>

  </Router>
)

const Home = () => (

Home

)

const About = () => (

About

)

const Topics = ({ match }) => (

Topics

        <Link to={`${match.url}/rendering`}>
          Rendering with React
        </Link>

        <Link to={`${match.url}/components`}>
          Components
        </Link>

        <Link to={`${match.url}/props-v-state`}>
          Props v. State
        </Link>

    <Route path={`${match.url}/:topicId`} component={Topic}/>
    <Route exact path={match.url} render={() => (

Please select a topic.

    )}/>

)

const Topic = ({ match }) => (

{match.params.topicId}

)

export default BasicExample

This works obviously but I want to change it into a class format.

So I have tried below

index.js

render((
        <Router>

                <Route path="/" component={App}/>

        </Router>
    ), document.getElementById('root')
);

App.js

class App extends Component {
    render() {
        return (

                    code

<Link to="/">Home</Link>

<Link to="/about">About</Link>

<Link to="/teachers">Teachers</Link>

<Link to="/courses">Courses</Link>

                <Route exact path="/" component={Home}/>
                <Route path="/about" component={About}/>
                <Route path="/teachers" component={Teachers}/>
                <Route path="/courses" component={Course}/>

        );
    }
}

export default App;

The problem is that when I click on the links, it routes to the correct url and it works but when I type in the url myself, it gives cannot GET /about and so on even though they are all rendering to same url - whether I click on the links or whether i type them myself. I am thinking App route is not being rendered except at root which I don't understand why. Does anyone know why that might be?

Also, how do I convert my code so that I can take in the match parameter like the first example code? So in topics it is taking match object as a parameter and I am guessing that is some kind of reference to its previous url

SOLUTIONS

Okay I'm going to provide solutions here as a lot of video based React Router tutorials do not cover React Router v4. I hope the noobs who are struggling with the new React Router can get help from this answer.

So basically you have to be able to differentiate client side route with the asset request and webpack-dev-server provides a perfect option for this.

All you have to do is add

devServer: {
    port: 3000,
    historyApiFallback: {
        index:'index.html'
    }
}

to the webpack.config.js which will always point to index.html when there is no response from the server

This is my reference. Might be useful to read it https://jaketrent.com/post/pushstate-webpack-dev-server/

Body:
This is generally a server problem rather than anything in your client-side code.  If you are using express with static serving:

app.use(express.static('build'));

Then if there isn't a file in the directory build, or another express route that matches e.g. /about then express won't respond with anything.

You need to add a catch all route to express in addition to the static middleware above - it must be after it in your route definitions though.

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../build', 'index.html'));
};

This is a wildcard route, so anything that hasn't been matched by the static middleware will be sent index.html.  Once that lands in your browser then react-router will take over and load the correct components.


来源: stackexchange

问:
Writing to .dat file results in random Chinese characters being written
I have this program:

```<code>using namespace std;

class Motherboards
{
    char Board_Manufacturer_Name[50];
    char Socket_Type[50];
    char Chipset_Type[50];
    char Board_Name[50];
    char Feature1[500];
    char Feature2[500];
    char Feature3[500];
    float Price;

    public:
    void getdata();
    void displaydata();
};
void Motherboards::getdata()
{
    cout << " Enter Manufacturer Name :\n";
    cin.getline(Board_Manufacturer_Name, 50);
    cout << "\n Enter the Socket type :\n";
    cin.getline(Socket_Type, 50);
    cout << "\n Enter the Chipset Type :\n";
    cin.getline(Chipset_Type, 50);
    cout << "\n Enter the Board Name :\n";
    cin.getline(Board_Name, 50);
    cout << "\n Enter 3 main features for this Board :\n";
    cout << "\n1.) ";
    cin.getline(Feature1, 500);
    cout << "\n2.) ";
    cin.getline(Feature2, 500);
    cout << "\n3.) ";
    cin.getline(Feature3, 500);
    cout << "Price :\n";
    cin >> Price;
    cout << "\n";
}
void Motherboards::displaydata()
{
    cout << " Manufacturer : " << Board_Manufacturer_Name << endl;
    cout << " Socket : " << Socket_Type << endl;
    cout << " Chipset : " << Chipset_Type << endl;
    cout << " Board Name : " << Board_Name << endl;
    cout << " Features :\n" << "1.) " << Feature1 << endl
        << "2.) " << Feature2 << endl
        << "3.) " << Feature3 << endl;
    cout << " Price :\n" << Price;
    cout << "\n";
}

int main()
{
    int x;
    system("cls");
    Motherboards M;
    fstream Infile;
    Infile.open("MotherboardList.dat", ios::in | ios::out | ios::app);
    if (!Infile)
    {
        cerr << "Error :";
    }
    cout << "Enter the details of the motherboard that you want to add :\n";
    M.getdata();
    Infile.write((char*)&M, sizeof(M));
    cout << "Do you wanna confirm ?";
    M.displaydata();
    cin >> x;
    cout << "Written :\n";
    Infile.read((char*)&M, sizeof(M));
    M.displaydata();
    Infile.close();

    return 0;
}
</code>```

I get this output:

Why is my data written in some random language (maybe Chinese?), and what do I have to change to actually write the data properly?

I wanted the text file to be in English. Also, shouldn't there be a line break after each data I entered?

答:
The file you create is not a valid text file, but a binary file.
you are writing internals of a c++ struct to the file in its binary representation.

if you want the file to be human readable, serialize your struct to string before writing to file, use JSON or XML.

And de-serialize after reading back if you want the c program to understand it.

ContentLicense: CC BY-SA 3.0

Body:
I have this program:

using namespace std;

class Motherboards
{
    char Board_Manufacturer_Name[50];
    char Socket_Type[50];
    char Chipset_Type[50];
    char Board_Name[50];
    char Feature1[500];
    char Feature2[500];
    char Feature3[500];
    float Price;

    public:
    void getdata();
    void displaydata();
};
void Motherboards::getdata()
{
    cout << " Enter Manufacturer Name :\n";
    cin.getline(Board_Manufacturer_Name, 50);
    cout << "\n Enter the Socket type :\n";
    cin.getline(Socket_Type, 50);
    cout << "\n Enter the Chipset Type :\n";
    cin.getline(Chipset_Type, 50);
    cout << "\n Enter the Board Name :\n";
    cin.getline(Board_Name, 50);
    cout << "\n Enter 3 main features for this Board :\n";
    cout << "\n1.) ";
    cin.getline(Feature1, 500);
    cout << "\n2.) ";
    cin.getline(Feature2, 500);
    cout << "\n3.) ";
    cin.getline(Feature3, 500);
    cout << "Price :\n";
    cin >> Price;
    cout << "\n";
}
void Motherboards::displaydata()
{
    cout << " Manufacturer : " << Board_Manufacturer_Name << endl;
    cout << " Socket : " << Socket_Type << endl;
    cout << " Chipset : " << Chipset_Type << endl;
    cout << " Board Name : " << Board_Name << endl;
    cout << " Features :\n" << "1.) " << Feature1 << endl
        << "2.) " << Feature2 << endl
        << "3.) " << Feature3 << endl;
    cout << " Price :\n" << Price;
    cout << "\n";
}

int main()
{
    int x;
    system("cls");
    Motherboards M;
    fstream Infile;
    Infile.open("MotherboardList.dat", ios::in | ios::out | ios::app);
    if (!Infile)
    {
        cerr << "Error :";
    }
    cout << "Enter the details of the motherboard that you want to add :\n";
    M.getdata();
    Infile.write((char*)&M, sizeof(M));
    cout << "Do you wanna confirm ?";
    M.displaydata();
    cin >> x;
    cout << "Written :\n";
    Infile.read((char*)&M, sizeof(M));
    M.displaydata();
    Infile.close();

    return 0;
}

I get this output:

Why is my data written in some random language (maybe Chinese?), and what do I have to change to actually write the data properly?

I wanted the text file to be in English. Also, shouldn't there be a line break after each data I entered?


问:
Check variable exists in current url in classic asp
Is there a way to check if a variable exists on the current page in asp? i.e.
For the url:  https://stackoverflow.com/?question=something
I'd like to check if the ?question variable exists.

<%Request.ServerVariables("Query_String")%> would give question=something but I just want to know if the current url contains ?question. I don't care what the actual value is as long as it exists.

答:
Ask the Request collection:

```<code>HasParam = Request("question").Count > 0
</code>```

Body:
Ask the Request collection:

HasParam = Request("question").Count > 0


问:
ServiceProvider not found laravel 5.2
I'm creating a composer installable project inside vendor.
This is my service provider file,

```<code><?php
namespace vimuths123\gitpack;

use Illuminate\Support\ServiceProvider;

class GitpackServiceProvider extends ServiceProvider {
    public function register() {
        $this->app->bind('gitpack', function ($app) {
            return new Gitpack;
        });
    }

    public function boot() {
        // loading the routes file
        require __DIR__ . '/Http/routes.php';

        // define the path for the view files
        $this->loadViewsFrom(__DIR__ . '/../views', 'gitpack');
    }
}
</code>```

This is the structure,

```<code>vendor
      |
     vimuths123
        |-gitpack
           |-src
           |  |-GitpackServiceProvider.php
           |
           |-composer.json
</code>```

I already added my service provider in app/config.php

```<code> vimuths123\gitpack\GitpackServiceProvider::class,
</code>```

and my root composer.json I have following code.

```<code>"psr-4": {
            "App\\": "app/",
            "vimuths123\\gitpack\\" : "vendor/vimuths123/gitpack/src"
        }
</code>```

This is my package composer file,

```<code>{
    "name": "vimuths123/gitpack",
    "autoload": {
        "psr-4" : {
            "vimuths123\\gitpack\\" : "src"
         }
    },
    "require": {
        "composer/installers": "~1.2"
    }
}
</code>```

but all I'm getting is this error,

Class 'vimuths123\gitpack\GitpackServiceProvider' not found

It would be great help someone can help me on this.

答:
Run the following artisan command:

```<code>php artisan optimize
</code>```

Then see if the class can be found by Laravel.

Title: ServiceProvider not found laravel 5.2

Body:
I'm creating a composer installable project inside vendor.
This is my service provider file,

<?php
namespace vimuths123\gitpack;

use Illuminate\Support\ServiceProvider;

class GitpackServiceProvider extends ServiceProvider {
    public function register() {
        $this->app->bind('gitpack', function ($app) {
            return new Gitpack;
        });
    }

    public function boot() {
        // loading the routes file
        require __DIR__ . '/Http/routes.php';

        // define the path for the view files
        $this->loadViewsFrom(__DIR__ . '/../views', 'gitpack');
    }
}

This is the structure,

vendor
      |
     vimuths123
        |-gitpack
           |-src
           |  |-GitpackServiceProvider.php
           |
           |-composer.json

I already added my service provider in app/config.php

 vimuths123\gitpack\GitpackServiceProvider::class,

and my root composer.json I have following code.

"psr-4": {
            "App\\": "app/",
            "vimuths123\\gitpack\\" : "vendor/vimuths123/gitpack/src"
        }

This is my package composer file,

{
    "name": "vimuths123/gitpack",
    "autoload": {
        "psr-4" : {
            "vimuths123\\gitpack\\" : "src"
         }
    },
    "require": {
        "composer/installers": "~1.2"
    }
}

but all I'm getting is this error,

Class 'vimuths123\gitpack\GitpackServiceProvider' not found

It would be great help someone can help me on this.

Body:
Run the following artisan command:

php artisan optimize

Then see if the class can be found by Laravel.


问:
Do PHP threads run sequentially?
I did all the work to custom build php with pthread support. I slightly edited this code from: http://php.net/manual/en/class.thread.php

```<code>class workerThread extends Thread {
public function __construct($i){
  $this->i=$i;
  $this->c=0;
}

public function run(){
while($this->c < 10){
   echo $this->i , '<br/>';
   sleep(1);
   $this->c++;
}
}
}

for($i=0;$i<50;$i++){
$workers[$i]=new workerThread($i);
$workers[$i]->start();
}
</code>```

The output is not as i would have expected where all results are in sequential order: 0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
2
2
3
3
3 etc.

Do I misunderstand how threads should work? Isn't the sleep(1) supposed to allow another thread to take control of the processor and perform it's calculation?

答:
No, the threads created by PHP's pthreads extension do not run sequentially. They are actual kernel threads, and so they will run however the task scheduler of the kernel decides to run them.

Isn't the sleep(1) supposed to allow another thread to take control of the processor and perform it's calculation?

Given the sleep() function in PHP utilises the sleep system call, the following description from wikipedia is applicable:

Sleep causes the thread or process to give up the remainder of its time slice and stay in the Not Runnable state for the specified duration. While there is generally a guarantee for the minimum time period, there is no strict guarantee that the thread will run immediately or soon, or even at all, once the specified time has passed. It is up to the scheduler's discretion, and dependent on thread priorities and implementation details such as timer resolutions when the sleeping thread will run again.

Title: Do PHP threads run sequentially?

Body:
I did all the work to custom build php with pthread support. I slightly edited this code from: http://php.net/manual/en/class.thread.php

class workerThread extends Thread {
public function __construct($i){
  $this->i=$i;
  $this->c=0;
}

public function run(){
while($this->c < 10){
   echo $this->i , '
';
   sleep(1);
   $this->c++;
}
}
}

for($i=0;$i<50;$i++){
$workers[$i]=new workerThread($i);
$workers[$i]->start();
}

The output is not as i would have expected where all results are in sequential order: 0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
2
2
3
3
3 etc.

Do I misunderstand how threads should work? Isn't the sleep(1) supposed to allow another thread to take control of the processor and perform it's calculation?


问:
Try to call a component inside a component - React
So I started with React and I have these two Components.

In the first component I want to iterate an array of objects with the map() function (which works) and call the other component that for now just returns a simple h1 tag.

Well, nothing is been called and there is no error in the console.
I believe the problem is in the return sentence in the renderAvatarData()
(if I do console.log after the return sentence it seems to not get there but if the console.log is before the return it invokes)

HomePageBoxesData.js

```<code>import React, { Component } from 'react';

import AvatarDetails from './AvatarDetails';

class HomePageBoxesData extends Component{

  constructor(props) {
    super(props);
  };

  renderAvatarData(){
    this.props.data.map(data => {
        return <AvatarDetails data={data}/>
    });
  }

  render(){
    return(
        <div>
            {this.renderAvatarData()}
        </div>
     );
   }
};

export default HomePageBoxesData;
</code>```

AvatarDetails.js

```<code>import React, { Component } from 'react';

class AvatarDetails extends Component{

    constructor(props) {
      super(props);
    };

    render(){
       return(
         <h1>Hello World</h1>
       );
    }
};

export default AvatarDetails;
</code>```

答:
Issue is in renderAvatarData() method, you forgot to use return with map, Use this:

```<code>renderAvatarData(){
    return this.props.data.map((data)=>{
        return <AvatarDetails data={data}/>

    });
}
</code>```

Since you just want to return the Component, you can directly write it like this:

```<code>renderAvatarData(){
    return this.props.data.map(data => <AvatarDetails data={data} /> );
}
</code>```

Body:
So I started with React and I have these two Components.

In the first component I want to iterate an array of objects with the map() function (which works) and call the other component that for now just returns a simple h1 tag.

Well, nothing is been called and there is no error in the console.
I believe the problem is in the return sentence in the renderAvatarData()
(if I do console.log after the return sentence it seems to not get there but if the console.log is before the return it invokes)

HomePageBoxesData.js

import React, { Component } from 'react';

import AvatarDetails from './AvatarDetails';

class HomePageBoxesData extends Component{

  constructor(props) {
    super(props);
  };

  renderAvatarData(){
    this.props.data.map(data => {
        return <AvatarDetails data={data}/>
    });
  }

  render(){
    return(

            {this.renderAvatarData()}

     );
   }
};

export default HomePageBoxesData;

AvatarDetails.js

import React, { Component } from 'react';

class AvatarDetails extends Component{

    constructor(props) {
      super(props);
    };

    render(){
       return(

Hello World

       );
    }
};

export default AvatarDetails;

Body:
Issue is in renderAvatarData() method, you forgot to use return with map, Use this:

renderAvatarData(){
    return this.props.data.map((data)=>{
        return <AvatarDetails data={data}/>

    });
}

Since you just want to return the Component, you can directly write it like this:

renderAvatarData(){
    return this.props.data.map(data => <AvatarDetails data={data} /> );
}


问:
Testing Promises with multiple thens using testdoublejs
I am using testdouble for stubbing calls within my node.js project. This particular function is wrapping a promise and has multiple then calls within the function itself.

```<code>function getUser (rethink, username) {
  return new Promise((resolve, reject) => {
  let r = database.connect();
  r.then(conn => database.table(tablename).filter({username}))
   .then(data => resolve(data))
   .error(err => reject(err));
 });
}
</code>```

So I am wanting to determine if the resolve and reject are handled correctly based on error conditions. Assume there is some custom logic in there that I need to validate.

For my test

```<code>import getUser from './user';
import td from 'testdouble';
test(t => {
  const db = td.object();
  const connect = td.function();
  td.when(connect('options')).thenResolve();
  const result = getUser(db, 'testuser');
  t.verify(result);
}
</code>```

The issue is that the result of connect needs to be a promise, so I use then resolve with a value which needs to be another promise that resolves or rejects.

The line it is relating to is the result of database.connect() is not a promise.

```<code>TypeError: Cannot read property 'then' of undefined
</code>```

Anyone have success with stubbing this type of call with Test Double?

答:
Test double provides stubs for unit testing. And in your case 'db' is the object we need to mock. Creating the mocking db through

td.object(Database) // Database is the class or constructor of your db

will be the right choice, but to simply mock those methods you need in this case, I wouldn't pick that way.

Here's the tested module, 'some.js':

```<code>function getUser (database, username) {
  return new Promise((resolve, reject) => {
    let r = database.connect();
    r.then(conn => database.table('table').filter({username:username}))
      .then(data => resolve(data))
      .catch(err => reject(err));
  });
}

module.exports = getUser;
</code>```

And the test file, using mocha and chai.expect, which is could also be any other unit test module here:

```<code>let td = require('testdouble');
let expect = require('chai').expect;

const getUser = require('./some');

describe('some.js',()=>{
  it('getUser',()=>{
    const db = {};
    const name = 'name';
    db.connect = td.function();
    db.table = td.function('table');
    db.filter = td.function('filter');
    td.when(db.connect()).thenResolve(db);
    td.when(db.table('table')).thenReturn(db);
    td.when(db.filter({username: name})).thenResolve('some user data');
    return getUser(db, name)
      .then(user=>{
        expect(user).to.equal('some user data')
      })
      .catch(e=>assert(e))
  })
})
</code>```

So please let me know if any of these confuse you.

Body:
I am using testdouble for stubbing calls within my node.js project. This particular function is wrapping a promise and has multiple then calls within the function itself.

function getUser (rethink, username) {
  return new Promise((resolve, reject) => {
  let r = database.connect();
  r.then(conn => database.table(tablename).filter({username}))
   .then(data => resolve(data))
   .error(err => reject(err));
 });
}

So I am wanting to determine if the resolve and reject are handled correctly based on error conditions. Assume there is some custom logic in there that I need to validate.

For my test

import getUser from './user';
import td from 'testdouble';
test(t => {
  const db = td.object();
  const connect = td.function();
  td.when(connect('options')).thenResolve();
  const result = getUser(db, 'testuser');
  t.verify(result);
}

The issue is that the result of connect needs to be a promise, so I use then resolve with a value which needs to be another promise that resolves or rejects.

The line it is relating to is the result of database.connect() is not a promise.

TypeError: Cannot read property 'then' of undefined

Anyone have success with stubbing this type of call with Test Double?

Body:
Test double provides stubs for unit testing. And in your case 'db' is the object we need to mock. Creating the mocking db through

td.object(Database) // Database is the class or constructor of your db

will be the right choice, but to simply mock those methods you need in this case, I wouldn't pick that way.

Here's the tested module, 'some.js':

function getUser (database, username) {
  return new Promise((resolve, reject) => {
    let r = database.connect();
    r.then(conn => database.table('table').filter({username:username}))
      .then(data => resolve(data))
      .catch(err => reject(err));
  });
}

module.exports = getUser;

And the test file, using mocha and chai.expect, which is could also be any other unit test module here:

let td = require('testdouble');
let expect = require('chai').expect;

const getUser = require('./some');

describe('some.js',()=>{
  it('getUser',()=>{
    const db = {};
    const name = 'name';
    db.connect = td.function();
    db.table = td.function('table');
    db.filter = td.function('filter');
    td.when(db.connect()).thenResolve(db);
    td.when(db.table('table')).thenReturn(db);
    td.when(db.filter({username: name})).thenResolve('some user data');
    return getUser(db, name)
      .then(user=>{
        expect(user).to.equal('some user data')
      })
      .catch(e=>assert(e))
  })
})

So please let me know if any of these confuse you.


问:
Does camel use an implicit read lock for files?
I'm consuming a file using Camel File component as follows:

```<code><from uri="file:myDir?noop=true&filter=myFilter&scheduler=quartz2&scheduler.cron={{schedule}}/>
</code>```

The source location is read only. Camel File documentation says, it won't be using a read lock by default.

But, I'm getting a permission denied exception while running this code.

Endpoint[file://myFile?filter=myFilter&idempotent=true&noop=true&scheduler=quartz2&scheduler.cron={{mySchedule}}
  cannot begin processing file: GenericFile[myDir\myFile] due to: Access
  is denied. Caused by: [java.io.IOException - Access is denied]

Stack Trace java.io.IOException: Permission denied   at
  java.io.UnixFileSystem.createFileExclusively(Native Method)[:1.8.0_66]
  at java.io.File.createNewFile(File.java:1012)[:1.8.0_66]   at
  org.apache.camel.util.FileUtil.createNewFile(FileUtil.java:587)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.MarkerFileExclusiveReadLockStrategy.acquireExclusiveReadLock(MarkerFileExclusiveReadLockStrategy.java:71)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.GenericFileProcessStrategySupport.begin(GenericFileProcessStrategySupport.java:49)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.GenericFileRenameProcessStrategy.begin(GenericFileRenameProcessStrategy.java:35)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:352)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:211)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:175)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.pollconsumer.quartz2.QuartzScheduledPollConsumerJob.execute(QuartzScheduledPollConsumerJob.java:59)[org.apache.camel:camel-quartz2:2.15.1.redhat-621090]
  at
  org.quartz.core.JobRunShell.run(JobRunShell.java:202)[org.quartz-scheduler:quartz:2.2.1]
  at
  org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)[org.quartz-scheduler:quartz:2.2.1]

From the stack trace, it appears that, camel is trying to create a readLock and it is causing exception due to lack of of permission.

So, my questions are

Why camel is using a lock, even if default value of read lock is none

If this is expected behavior, how can I consume file from a read only location where I don't have write permission?

UPDATE

I tried setting readLockMarkingFile to false as suggested in one of the answer, but that did n't solve the problem. So, I explicitly set readLock to none. Now, it is working. Don't know, why readLock is not none by default as mentioned in documentation.

答: While this doesn't directly answer your question, I've used a trigger file (0 bytes) which the file watcher looks for. Your route would then work on the actual file to which the trigger is a companion. The trigger file is moved to a subdirectory /parent/.camel so it doesn't process again. Although we have noticed routes try to 'pick up' the actual file in a distributed environment where there is more than one server running the route.</p>

Body:
I'm consuming a file using Camel File component as follows:

<from uri="file:myDir?noop=true&filter=myFilter&scheduler=quartz2&scheduler.cron={{schedule}}/>

The source location is read only. Camel File documentation says, it won't be using a read lock by default.

But, I'm getting a permission denied exception while running this code.

Endpoint[file://myFile?filter=myFilter&idempotent=true&noop=true&scheduler=quartz2&scheduler.cron={{mySchedule}}
  cannot begin processing file: GenericFile[myDir\myFile] due to: Access
  is denied. Caused by: [java.io.IOException - Access is denied]

Stack Trace java.io.IOException: Permission denied   at
  java.io.UnixFileSystem.createFileExclusively(Native Method)[:1.8.0_66]
  at java.io.File.createNewFile(File.java:1012)[:1.8.0_66]   at
  org.apache.camel.util.FileUtil.createNewFile(FileUtil.java:587)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.MarkerFileExclusiveReadLockStrategy.acquireExclusiveReadLock(MarkerFileExclusiveReadLockStrategy.java:71)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.GenericFileProcessStrategySupport.begin(GenericFileProcessStrategySupport.java:49)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.strategy.GenericFileRenameProcessStrategy.begin(GenericFileRenameProcessStrategy.java:35)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.processExchange(GenericFileConsumer.java:352)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.processBatch(GenericFileConsumer.java:211)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.component.file.GenericFileConsumer.poll(GenericFileConsumer.java:175)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101)[org.apache.camel:camel-core:2.15.1.redhat-621090
  com.googlecode.concurrentlinkedhashmap:concurrentlinkedhashmap-lru:1.4.2]
  at
  org.apache.camel.pollconsumer.quartz2.QuartzScheduledPollConsumerJob.execute(QuartzScheduledPollConsumerJob.java:59)[org.apache.camel:camel-quartz2:2.15.1.redhat-621090]
  at
  org.quartz.core.JobRunShell.run(JobRunShell.java:202)[org.quartz-scheduler:quartz:2.2.1]
  at
  org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)[org.quartz-scheduler:quartz:2.2.1]

From the stack trace, it appears that, camel is trying to create a readLock and it is causing exception due to lack of of permission.

So, my questions are

Why camel is using a lock, even if default value of read lock is none

If this is expected behavior, how can I consume file from a read only location where I don't have write permission?

UPDATE

I tried setting readLockMarkingFile to false as suggested in one of the answer, but that did n't solve the problem. So, I explicitly set readLock to none. Now, it is working. Don't know, why readLock is not none by default as mentioned in documentation.


问:
Countdown to a date. Swift 3 and Firebase
I'm wanting to use my Firebase database that has the values of a product i.e. lifespan (an integer not a date) and use it to compare the date in which the user has added the item i.e. 25/03/17, I'm not sure how to achieve this. Can somebody give me some advice. I believe it is to do with approximation, so if the liespan is equal 7 then the user should see 7 days and it would decrease each day, so basically a countdown. I've looked at NSDate documentation and the SwiftDate framework and do have a bit of knowledge on the methods I might need to use.

I have this example where it gets the engagement date and compares it with the wedding date, I'm thinking this is somewhat similar to what I want to try and achieve. However as this uses two dates and I want to use a date and an integer:

```<code>    formatter.dateFormat = "dd/MM/yyyy"

    let dateArray = message["message"] as! NSMutableArray

    if let startTimeString = dateArray[0] as? String {
        let weddingDate = formatter.dateFromString(startTimeString)
        var engagementDate:NSDate? = nil

        if let endTimeString = dateArray[1] as? String {
            engagementDate = formatter.dateFromString(endTimeString)
        }
        let now = NSDate()
        let totalEngagementTime = userCalender.components(.Day, fromDate: engagementDate!, toDate: weddingDate!, options: []).day
        let daysFromEngagementUntilNow = userCalender.components(.Day, fromDate: engagementDate!, toDate: now, options: []).day
        let percentage = (Double(daysFromEngagementUntilNow) / Double(totalEngagementTime)) * 100.00
        let timeUntilWedding = userCalender.components(requestedComponent, fromDate: now, toDate: weddingDate!, options: [])
</code>```

Hope I made sense, thank you in advance! :)

答:
In response to a comment from the OP, this answers the question how to calculate

time between two dates

as well as perform a query on Firebase to retrieve events between now and a future date.

Given a Firebase structure to track events:

```<code>events
  event_0
    datestamp: "20170405"
    event_name: "A concert"
  event_1
    datestamp: "20170501"
    event_name: "Wine tasting"
  event_2
    datestamp: "20170410"
    event_name: "50th birthday"
</code>```

Assuming today is 20170402 (April 2nd, 2017) and we want all of the events for the next 30 days along with how many days until the event, when we run the following code and query:

```<code>    let minuteInterval:TimeInterval = 60.0 //how to work with TimeIntervals
    let hourInterval:TimeInterval = 60.0 * minuteInterval
    let dayInterval:TimeInterval = 24 * hourInterval
    let sevenDaysInterval = dayInterval * 30 //30 days from now

    let today = Date() //today

    var futureDate = Date()
    futureDate.addTimeInterval(sevenDaysInterval) //future date is seven days from now

    let formatter = DateFormatter()
    formatter.dateFormat = "yyyyMMdd" //format the date to match how it's stored in Firebase
    let startString = formatter.string(from: today)
    let endString = formatter.string(from: futureDate)

    let eventsRef = self.ref.child("events")
    let myQuery = eventsRef.queryOrdered(byChild: "datestamp")
                                 .queryStarting(atValue: startString)
                                 .queryEnding(atValue: endString)
    myQuery.observeSingleEvent(of: .value, with: { snapshot in
        for child in snapshot.children {
            let snap = child as! FIRDataSnapshot
            let dict = snap.value as! [String: Any]
            let eventName = dict["event_name"] as! String
            let eventDateStampString = dict["datestamp"] as! String
            let endDate = formatter.date(from: eventDateStampString)
            let daysUntilEvent = self.daysDiff(startDate: today, endDate: endDate!)

            print("event: \(eventName)  days from now: \(daysUntilEvent)")
        }
    })
</code>```

and a little function do to the difference in dates calculation

```<code>func daysDiff(startDate: Date, endDate: Date) -> Int {
    let calendar = Calendar.current

    let date1 = calendar.startOfDay(for: startDate)
    let date2 = calendar.startOfDay(for: endDate)

    let a = calendar.dateComponents([.day], from: date1, to: date2)
    return a.value(for: .day)!
}
</code>```

and the result is

```<code>event: A concert  days from now: 3
event: 50th birthday  days from now: 8
event: Wine tasting  days from now: 29
</code>```

Body:
I'm wanting to use my Firebase database that has the values of a product i.e. lifespan (an integer not a date) and use it to compare the date in which the user has added the item i.e. 25/03/17, I'm not sure how to achieve this. Can somebody give me some advice. I believe it is to do with approximation, so if the liespan is equal 7 then the user should see 7 days and it would decrease each day, so basically a countdown. I've looked at NSDate documentation and the SwiftDate framework and do have a bit of knowledge on the methods I might need to use.

I have this example where it gets the engagement date and compares it with the wedding date, I'm thinking this is somewhat similar to what I want to try and achieve. However as this uses two dates and I want to use a date and an integer:

    formatter.dateFormat = "dd/MM/yyyy"

    let dateArray = message["message"] as! NSMutableArray

    if let startTimeString = dateArray[0] as? String {
        let weddingDate = formatter.dateFromString(startTimeString)
        var engagementDate:NSDate? = nil

        if let endTimeString = dateArray[1] as? String {
            engagementDate = formatter.dateFromString(endTimeString)
        }
        let now = NSDate()
        let totalEngagementTime = userCalender.components(.Day, fromDate: engagementDate!, toDate: weddingDate!, options: []).day
        let daysFromEngagementUntilNow = userCalender.components(.Day, fromDate: engagementDate!, toDate: now, options: []).day
        let percentage = (Double(daysFromEngagementUntilNow) / Double(totalEngagementTime)) * 100.00
        let timeUntilWedding = userCalender.components(requestedComponent, fromDate: now, toDate: weddingDate!, options: [])

Hope I made sense, thank you in advance! :)

Body:
In response to a comment from the OP, this answers the question how to calculate

time between two dates

as well as perform a query on Firebase to retrieve events between now and a future date.

Given a Firebase structure to track events:

events
  event_0
    datestamp: "20170405"
    event_name: "A concert"
  event_1
    datestamp: "20170501"
    event_name: "Wine tasting"
  event_2
    datestamp: "20170410"
    event_name: "50th birthday"

Assuming today is 20170402 (April 2nd, 2017) and we want all of the events for the next 30 days along with how many days until the event, when we run the following code and query:

    let minuteInterval:TimeInterval = 60.0 //how to work with TimeIntervals
    let hourInterval:TimeInterval = 60.0 * minuteInterval
    let dayInterval:TimeInterval = 24 * hourInterval
    let sevenDaysInterval = dayInterval * 30 //30 days from now

    let today = Date() //today

    var futureDate = Date()
    futureDate.addTimeInterval(sevenDaysInterval) //future date is seven days from now

    let formatter = DateFormatter()
    formatter.dateFormat = "yyyyMMdd" //format the date to match how it's stored in Firebase
    let startString = formatter.string(from: today)
    let endString = formatter.string(from: futureDate)

    let eventsRef = self.ref.child("events")
    let myQuery = eventsRef.queryOrdered(byChild: "datestamp")
                                 .queryStarting(atValue: startString)
                                 .queryEnding(atValue: endString)
    myQuery.observeSingleEvent(of: .value, with: { snapshot in
        for child in snapshot.children {
            let snap = child as! FIRDataSnapshot
            let dict = snap.value as! [String: Any]
            let eventName = dict["event_name"] as! String
            let eventDateStampString = dict["datestamp"] as! String
            let endDate = formatter.date(from: eventDateStampString)
            let daysUntilEvent = self.daysDiff(startDate: today, endDate: endDate!)

            print("event: \(eventName)  days from now: \(daysUntilEvent)")
        }
    })

and a little function do to the difference in dates calculation

func daysDiff(startDate: Date, endDate: Date) -> Int {
    let calendar = Calendar.current

    let date1 = calendar.startOfDay(for: startDate)
    let date2 = calendar.startOfDay(for: endDate)

    let a = calendar.dateComponents([.day], from: date1, to: date2)
    return a.value(for: .day)!
}

and the result is

event: A concert  days from now: 3
event: 50th birthday  days from now: 8
event: Wine tasting  days from now: 29


问:
Pass -express-flash-messages- in an EJS file
I've a user controller which has a basic authentication logic. I'm using an ejs view engine . I'm finding trouble accessing these flash messages in my view, i.e. .ejs file. What should be the right approach. I dug through some information and found out that we can pass parameters during a res.redirect. However, I don't want to do that, since it will appear in the URL. Is there a solution to this, something like what pug engine has.

```<code> if (!user || !user.authenticate(req.body.password)) {
  req.flash('error', 'Invalid email or password!')
  res.redirect('/login')

  return
 }
</code>```

答:
You could pass your flash messages to your views using res.locals object:

```<code>app.get('/login', function(req, res) {
  res.render('login', { errorMessage: req.flash('error')[0] });
});
</code>```

Then in your view:

```<code><% if (errorMessage) { %>
  <div class="error">
    <p><%= errorMessage %></p> <!-- Invalid email or password! -->
  </div>
<% } %>
</code>```

Body:
I've a user controller which has a basic authentication logic. I'm using an ejs view engine . I'm finding trouble accessing these flash messages in my view, i.e. .ejs file. What should be the right approach. I dug through some information and found out that we can pass parameters during a res.redirect. However, I don't want to do that, since it will appear in the URL. Is there a solution to this, something like what pug engine has.

 if (!user || !user.authenticate(req.body.password)) {
  req.flash('error', 'Invalid email or password!')
  res.redirect('/login')

  return
 }

Body:
You could pass your flash messages to your views using res.locals object:

app.get('/login', function(req, res) {
  res.render('login', { errorMessage: req.flash('error')[0] });
});

Then in your view:

<% if (errorMessage) { %>
  <div class="error">
    <p><%= errorMessage %></p> <!-- Invalid email or password! -->
  </div>
<% } %>


问:
ActionS in Swing ContainerS (JFrameS etc)
It seems that while you can add ActionS to ComponentS, you can't add them to ContainerS such as JFrame, JApplet or JDialog. Since I could find nothing helpful on Google, I felt I should share my findings so people in the future don't have to waste too much time. Please feel free to add information if you think I missed something or let something out.

The solution lies in .getRootPane(), which will then allow you to add actions like so:

jframe.getRootPane().getInputMap(JComponent.WHEN_FOCUSED).(KeyStroke.getKeyStroke("INSERT"), insertAction);

Hope this will be helpful to future generations.

答:
Sure you can add Key Bindings to a JPanel. Its a Swing component.

I'm not sure that the "WHEN_FOCUSED" InputMap will work. Normally focus is on a component, not the root pane.

Check out Key Bindings for a list of the default bindings and my simple example of using Key Bindings.

ContentLicense: CC BY-SA 2.5


问:
Not being able to set a value to a combobox
This is an old Vb6 application I'm working on - and I'm having somewhat of a hard time of setting a value to a combobox.

I first load the data to combobox - mind you - I'm only setting the text values in the combobox, no ID's. Here's what the code looks like...

```<code>Dim z As Integer
Dim a As Integer

oCombobox.Clear
oCombobox.AddItem "", 0

Call GetValuesForCbo

Do While Rs.EOF = False
    z = z + 1
    oCombobox.AddItem "", z

    For a = 0 To oCombobox.ColumnCount - 1
        oCombobox.List(z, a) = Rs.Fields(a).Value
    Next

    Rs.MoveNext
Loop
</code>```

So what happens is I have this function where I pass a ComboxName aka oCombobox. In CallValuesForCBO I query the database to get the values.

```<code>The values are definitely there because I don't get an error when i do this...

m_stringValue = 'Hello' <--this is one of the values I load into combobox
cboName.Value = m_stringValue <-- while this does not throw an error, it does not display any value in the cbo
</code>```

答: VB.ComboBox doesn't have ColumnCount property.

Body:
This is an old Vb6 application I'm working on - and I'm having somewhat of a hard time of setting a value to a combobox.

I first load the data to combobox - mind you - I'm only setting the text values in the combobox, no ID's. Here's what the code looks like...

Dim z As Integer
Dim a As Integer

oCombobox.Clear
oCombobox.AddItem "", 0

Call GetValuesForCbo

Do While Rs.EOF = False
    z = z + 1
    oCombobox.AddItem "", z

    For a = 0 To oCombobox.ColumnCount - 1
        oCombobox.List(z, a) = Rs.Fields(a).Value
    Next

    Rs.MoveNext
Loop

So what happens is I have this function where I pass a ComboxName aka oCombobox. In CallValuesForCBO I query the database to get the values.

The values are definitely there because I don't get an error when i do this...

m_stringValue = 'Hello' <--this is one of the values I load into combobox
cboName.Value = m_stringValue <-- while this does not throw an error, it does not display any value in the cbo


问:
Blink the time like a real digital clock
I am displaying the current time like this way :

```<code>$('#mydiv').html(
   new Date().toLocaleTimeString('en-US',
     { hour12: false, hour: 'numeric', minute: 'numeric' }));
</code>```

and it is displayed for example like this :

16:13

How is it possible to make the two dots blink every one second like a real digital clock?

答:
I fully agree with mplungjan, that there are better questions to ask, however, it also seemed fun todo :)

The blinking part, you could actually do with CSS, no need for javascript tricks (see the second example)

var clockEl = document.querySelector('#clock');

function getTime() {
  return new Date().toLocaleTimeString('en-US',
     { hour12: false, hour: 'numeric', minute: 'numeric' }).toString();
}

function setTime() {
  var time = getTime();
  // check if the colon is there
  if (clockEl.innerText.split(':').length === 1) {
    // if it's not, set the actual time
    clockEl.innerText = time;
  } else {
    // if it is, remove the colon
    clockEl.innerText = time.split(':').join(' ');
  }
}

setInterval( setTime , 1000);
setTime();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#clock { font-family: 'Courier new' }</code>```

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

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var oldTime;

function setTime() {
  var time = new Date().toLocaleTimeString('en-US',
     { hour12: false, hour: 'numeric', minute: 'numeric' });
  if (oldTime === time) {
    return;
  }
  oldTime = time;
  time = time.split(':');
  document.querySelector('#hours').innerText = time[0];
  document.querySelector('#minutes').innerText = time[1];
}

setInterval( setTime, 1000);
setTime();</code>```

.separator {
  animation: blinker 2s linear infinite;
}

@keyframes blinker {
  50% { opacity: 0; }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="clock">
  <span id="hours"></span>
  <span class="separator">:</span>
  <span id="minutes"></span>
</div></code>```

Body:
I am displaying the current time like this way :

$('#mydiv').html(
   new Date().toLocaleTimeString('en-US',
     { hour12: false, hour: 'numeric', minute: 'numeric' }));

and it is displayed for example like this :

16:13

How is it possible to make the two dots blink every one second like a real digital clock?

Body:
I fully agree with mplungjan, that there are better questions to ask, however, it also seemed fun todo :)

The blinking part, you could actually do with CSS, no need for javascript tricks (see the second example)

var clockEl = document.querySelector('#clock');

function getTime() {
  return new Date().toLocaleTimeString('en-US',
     { hour12: false, hour: 'numeric', minute: 'numeric' }).toString();
}

function setTime() {
  var time = getTime();
  // check if the colon is there
  if (clockEl.innerText.split(':').length === 1) {
    // if it's not, set the actual time
    clockEl.innerText = time;
  } else {
    // if it is, remove the colon
    clockEl.innerText = time.split(':').join(' ');
  }
}

setInterval( setTime , 1000);
setTime();

#clock { font-family: 'Courier new' }

<div id="clock"></div>

var oldTime;

function setTime() {
  var time = new Date().toLocaleTimeString('en-US',
     { hour12: false, hour: 'numeric', minute: 'numeric' });
  if (oldTime === time) {
    return;
  }
  oldTime = time;
  time = time.split(':');
  document.querySelector('#hours').innerText = time[0];
  document.querySelector('#minutes').innerText = time[1];
}

setInterval( setTime, 1000);
setTime();

.separator {
  animation: blinker 2s linear infinite;
}

@keyframes blinker {
  50% { opacity: 0; }
}

<div class="clock">
  <span id="hours"></span>
  <span class="separator">:</span>
  <span id="minutes"></span>
</div>


问:
Racket servlet serve static files
I want to try and code some blog or personal website or local web service in Racket. I've done the tutorial here and then I found this mailing list entry. In addition to that, I used the information from the documenation. URL based dispatch seems way easier than the tutorial, so I went for that and got the following code:

```<code>#lang racket

(provide/contract
  (start (-> request? response?)))

(require
  web-server/templates
  web-server/servlet-env
  web-server/servlet
  web-server/dispatch)

;; =====
;; STATE
;; =====
(define (get-vocabulary-for-topic topic)
  ;; for now always returns the same
  (list
    (list "sich fuer eine Person entscheiden" "xuǎnzé" "32" "选择")
    (list "teilnehmen" "cānyù" "14" "参与")
    (list "die Wahl" "dàxuǎn" "43" "大选")))

;; ======================
;; APPS HANDLING REQUESTS
;; ======================

(define (vocabulary-app request topic)
  (response/full
    200 #"OK"
    (current-seconds) TEXT/HTML-MIME-TYPE
    empty
    (list (string->bytes/utf-8 (render-vocabulary-page topic)))))

(define (vocabulary-overview-app request)
  (response/xexpr
    `(html
       (head (title "Vocabulary Overview")
             (link ((rel "stylesheet") (href "css/general.css") (type "text/css"))))
       (body (p "This is an overview of vocabulary pages.")))))

(define (overview-app request)
  (response/full
    200 #"OK"
    (current-seconds) TEXT/HTML-MIME-TYPE
    empty
    (list (string->bytes/utf-8 (render-overview-page)))))

;; ===============
;; RENDERING STUFF
;; ===============

(define (render-vocabulary-page topic)
  (let
    ([vocabulary (get-vocabulary-for-topic topic)])
    (let
      ([content (render-vocabulary-table vocabulary)]
        [page-title "Vocabulary"]
        [special-css-imports
          (render-css-include "css/vocabulary-table.css")]
        [special-js-imports ""]
        [header ""]
        [footer ""]
        [navigation ""])
      (include-template
        "templates/base.html"))))

(define (render-vocabulary-table vocabulary)
  (let
    ([table-headers (list "German" "Pinyin" "Tones" "Chinese")]
      [word-list vocabulary])
    (include-template "templates/vocabulary-table.html")))

(define (render-overview-page)
  (let
    ([content
       (let
         ([subpage-titles (list "vocabulary")])
         (include-template "templates/overview.html"))]
      [page-title "Overview"]
      [special-css-imports ""]
      [special-js-imports ""]
      [header ""]
      [footer ""]
      [navigation ""])
    (include-template
      "templates/base.html")))

(define (render-css-include path)
  (let
    ([path path])
    (include-template "templates/css-link.html")))

;; ====================
;; ROUTES MANAGING CODE
;; ====================
(define (start request)
  ;; for now only calling the dispatch
  ;; we could put some action here, which shall happen before dispatch
  (blog-dispatch request))

(define-values (blog-dispatch blug-url)
  (dispatch-rules
    [("index") overview-app]
    [("vocabulary") vocabulary-overview-app]
    [("vocabulary" (string-arg)) vocabulary-app]))

(define (respond-unknown-file req)
  (let
    ([content (include-template "templates/unknown-file.html")]
      [page-title "unknown file"]
      [special-css-imports ""]
      [special-js-imports ""]
      [header ""]
      [footer ""]
      [navigation ""])
    (response/full
      404 #"ERROR"
      (current-seconds) TEXT/HTML-MIME-TYPE
      empty
      (list
        (string->bytes/utf-8
          (include-template "templates/base.html"))))))

;; ===========================
;; ADDED FOR RUNNING A SERVLET
;; ===========================
(serve/servlet
  start
  #:servlet-path "/index"  ; default URL
  #:extra-files-paths (list (build-path (current-directory) "static"))  ; directory for static files
  #:port 8000 ; the port on which the servlet is running
  #:servlet-regexp #rx""
  #:launch-browser? true  ; should racket show the servlet running in a browser upon startup?
  ;; #:quit? false  ; ???
  #:listen-ip false  ; the server will listen on ALL available IP addresses, not only on one specified
  #:server-root-path (current-directory)
  #:file-not-found-responder respond-unknown-file)
</code>```

This works fine so far, except that any file in my static directory, actually in subdirectories of the static directory, namely css cannot be found, when I navigate to any "subpages".

What I mean by that is, that a "main page" would be something like localhost:8000/index or localhost:8000/vocabulary and a subpage would be a page like localhost:8000/vocabulary/something.

It seems that the template rendering gets it wrong, does not always access the static directory from the root of the application directory, but instead only looks at localhost:8000/vocabulary/css/general.css, while it should look at localhost:8000/css/general.css, which it does, when I go to any "main page".

Here is a screenshot of this on a main page:

And here it is on a subpage:

So the static directory seems to change depending on what URL is visited. At first I thought I had finally understood how to serve static files, but it seems I have not and I don't know how to fix the problem in the best way.

Here is my directory structure:

```<code>/home/xiaolong/development/Racket/blog2
  - static/
    - css/
      general.css
      vocabulary-table.css
    + img/
    + js/
  - templates/
    base.html
    css-link.html
    js-link.html
    overview.html
    unknown-file.html
    vocabulary-table.html
  blog-demo.rkt
  blog.rkt
</code>```

How can I fix the paths for static files?

I want to be able to simply type css/something.css in the code and no matter which app or route, it should serve the files and I don't want to change the include path depending on what route I am treating in the code.

The command I use for running the server is simply:

```<code>racket blog.rkt
</code>```

from the root directory of the project.

答:
The problem here is not understanding the concept of absolute paths versus relative paths, the concept of the base URL, and how they work together to form the full qualified URL for a given resource.

RFC 3986 is the reference for how URLs are constructed and processed. A note, it actually uses the term Uniform Resource Identifier, URI instead of URL. It supersedes previous documents which used the older and deprecated URL terminology.

But I'll continue to use URL term for sake of consistency with the original question.

It's important to understand the concept of a relative reference in RFC 3986 Section 4.1 and that it can be written as a relative path or absolute path.

Here, the agent that is interpreting the URLs is your browser, it's just processing the URLs your server has sent back to it using RFC 3986 as its basis of how URLs are supposed to work.

A fully qualified URL includes the protocol and host domain as well port number, if required, and the path giving the location of the document or resource relative to the protocol and host domain.

So in your case, the correct fully qualified URL of your CSS file would be http://localhost:8000/css/general.css

From RFC 3986 Section 3
The pieces http and localhost:8000 are called the protocol scheme and authority components respectively, and forms the main identifier for your website, http://localhost:8000 Anything coming after that identifier is called the path component and it precedes the query or URL fragment components which starts with "?" or "#" respectively.

The path component is designed to emulate UNIX file path conventions and constructs a tree hierarchy allowing you to express the location of some given resource relative to your website's identifier. There are some rules you need to take into account.

Relative references resolution is given in Section 5 of RFC 3986. The key concept is the base URL which is used with relative references to construct the fully qualified URL.

When your browser accesses the page located at http://localhost:8000/vocabulary/something and it sees css/general.css which is a relative reference written as a relative path. Following the resolution algorithm, the base URL is taken to be the URL originally used to access the page which is http://localhost:8000/vocabulary/something

Since there is no trailing slash at the end, the path subcomponent to the right of the right-most slash is dropped, giving you http://localhost:8000/vocabulary/. The URL relative reference css/general.css is then appended at the end of the rewritten base URL path, giving you http://localhost:8000/vocabulary/css/general.css, resulting in a 404 error when the browser attempts to retrieve the non-existent resource.

If instead, the browser sees /css/general.css which is a relative reference written as an absolute path. The base URL again is http://localhost:8000/vocabulary/something. Since the relative reference is an absolute path, the entire path to the right of your website identifier is dropped
giving you http://localhost:8000. The relative reference is then appended to the rewritten base URL, giving you http://localhost:8000/css/general.css which is the correct fully qualified URL.

A note, if you happened to access a page with the following URL http://localhost:8000/vocabulary/something/ which has a trailing slash. Then any relative-path references such as css/general.css will be merged to construct
the full URL http://localhost:8000/vocabulary/something/css/general.css because following the algorithm, the browser sees there is a trailing slash at the end of the original base URL and does not drop the last path subcomponent (or rather drops the empty subcomponent to the right of the trailing slash)

Title: Racket servlet serve static files

Body:
I want to try and code some blog or personal website or local web service in Racket. I've done the tutorial here and then I found this mailing list entry. In addition to that, I used the information from the documenation. URL based dispatch seems way easier than the tutorial, so I went for that and got the following code:

#lang racket

(provide/contract
  (start (-> request? response?)))

(require
  web-server/templates
  web-server/servlet-env
  web-server/servlet
  web-server/dispatch)

;; =====
;; STATE
;; =====
(define (get-vocabulary-for-topic topic)
  ;; for now always returns the same
  (list
    (list "sich fuer eine Person entscheiden" "xuǎnzé" "32" "选择")
    (list "teilnehmen" "cānyù" "14" "参与")
    (list "die Wahl" "dàxuǎn" "43" "大选")))

;; ======================
;; APPS HANDLING REQUESTS
;; ======================

(define (vocabulary-app request topic)
  (response/full
    200 #"OK"
    (current-seconds) TEXT/HTML-MIME-TYPE
    empty
    (list (string->bytes/utf-8 (render-vocabulary-page topic)))))

(define (vocabulary-overview-app request)
  (response/xexpr
    `(html
       (head (title "Vocabulary Overview")
             (link ((rel "stylesheet") (href "css/general.css") (type "text/css"))))
       (body (p "This is an overview of vocabulary pages.")))))

(define (overview-app request)
  (response/full
    200 #"OK"
    (current-seconds) TEXT/HTML-MIME-TYPE
    empty
    (list (string->bytes/utf-8 (render-overview-page)))))

;; ===============
;; RENDERING STUFF
;; ===============

(define (render-vocabulary-page topic)
  (let
    ([vocabulary (get-vocabulary-for-topic topic)])
    (let
      ([content (render-vocabulary-table vocabulary)]
        [page-title "Vocabulary"]
        [special-css-imports
          (render-css-include "css/vocabulary-table.css")]
        [special-js-imports ""]
        [header ""]
        [footer ""]
        [navigation ""])
      (include-template
        "templates/base.html"))))

(define (render-vocabulary-table vocabulary)
  (let
    ([table-headers (list "German" "Pinyin" "Tones" "Chinese")]
      [word-list vocabulary])
    (include-template "templates/vocabulary-table.html")))

(define (render-overview-page)
  (let
    ([content
       (let
         ([subpage-titles (list "vocabulary")])
         (include-template "templates/overview.html"))]
      [page-title "Overview"]
      [special-css-imports ""]
      [special-js-imports ""]
      [header ""]
      [footer ""]
      [navigation ""])
    (include-template
      "templates/base.html")))

(define (render-css-include path)
  (let
    ([path path])
    (include-template "templates/css-link.html")))

;; ====================
;; ROUTES MANAGING CODE
;; ====================
(define (start request)
  ;; for now only calling the dispatch
  ;; we could put some action here, which shall happen before dispatch
  (blog-dispatch request))

(define-values (blog-dispatch blug-url)
  (dispatch-rules
    [("index") overview-app]
    [("vocabulary") vocabulary-overview-app]
    [("vocabulary" (string-arg)) vocabulary-app]))

(define (respond-unknown-file req)
  (let
    ([content (include-template "templates/unknown-file.html")]
      [page-title "unknown file"]
      [special-css-imports ""]
      [special-js-imports ""]
      [header ""]
      [footer ""]
      [navigation ""])
    (response/full
      404 #"ERROR"
      (current-seconds) TEXT/HTML-MIME-TYPE
      empty
      (list
        (string->bytes/utf-8
          (include-template "templates/base.html"))))))

;; ===========================
;; ADDED FOR RUNNING A SERVLET
;; ===========================
(serve/servlet
  start
  #:servlet-path "/index"  ; default URL
  #:extra-files-paths (list (build-path (current-directory) "static"))  ; directory for static files
  #:port 8000 ; the port on which the servlet is running
  #:servlet-regexp #rx""
  #:launch-browser? true  ; should racket show the servlet running in a browser upon startup?
  ;; #:quit? false  ; ???
  #:listen-ip false  ; the server will listen on ALL available IP addresses, not only on one specified
  #:server-root-path (current-directory)
  #:file-not-found-responder respond-unknown-file)

This works fine so far, except that any file in my static directory, actually in subdirectories of the static directory, namely css cannot be found, when I navigate to any "subpages".

What I mean by that is, that a "main page" would be something like localhost:8000/index or localhost:8000/vocabulary and a subpage would be a page like localhost:8000/vocabulary/something.

It seems that the template rendering gets it wrong, does not always access the static directory from the root of the application directory, but instead only looks at localhost:8000/vocabulary/css/general.css, while it should look at localhost:8000/css/general.css, which it does, when I go to any "main page".

Here is a screenshot of this on a main page:

And here it is on a subpage:

So the static directory seems to change depending on what URL is visited. At first I thought I had finally understood how to serve static files, but it seems I have not and I don't know how to fix the problem in the best way.

Here is my directory structure:

/home/xiaolong/development/Racket/blog2
  - static/
    - css/
      general.css
      vocabulary-table.css
    + img/
    + js/
  - templates/
    base.html
    css-link.html
    js-link.html
    overview.html
    unknown-file.html
    vocabulary-table.html
  blog-demo.rkt
  blog.rkt

How can I fix the paths for static files?

I want to be able to simply type css/something.css in the code and no matter which app or route, it should serve the files and I don't want to change the include path depending on what route I am treating in the code.

The command I use for running the server is simply:

racket blog.rkt

from the root directory of the project.


问:
Most elegant isEmpty() Method for Binary Tree
I'm trying to write the most elegant isEmpty() method for my LinkedBinaryTree class.

When the compiler interacts with the if statement, it should return a boolean value or either true of false. However, since it is necessary to return a value outside the if statement, I've returned a value of false. My logic is that if (count == 0), isEmpty() returns true and doesn't bother with the second line (return false). Is this correct?

```<code>public class LinkedBinaryTree<T> implements BinaryTreeADT<T>
{
   protected int count;
   protected BinaryTreeNode<T> root;

   /**
    * Creates an empty binary tree.
    */
   public LinkedBinaryTree()
   {
      count = 0;
      root = null;
   }

   /**
    * Creates a binary tree with the specified element as its root.
    *
    * @param element  the element that will become the root of the new binary tree
    */
   public LinkedBinaryTree (T element)
   {
      count = 1;
      root = new BinaryTreeNode<T> (element);
   }

   /**
    * Returns true if this binary tree is empty and false otherwise.
    *
    * @return  true if this binary tree is empty
    */
   public boolean isEmpty()
   {
       if (count == 0);
       return false;
   }
</code>```

答:
"Is this correct?" -- you could find out by testing it. I recommend you do so, ideally in a jUnit test:

```<code> @Test
 public void isEmpty_returns_true_for_empty_list() {
     LinkedBinaryTree tree = new LinkedBinaryTree();
     assertTrue(tree.isEmpty());
 }
</code>```

... and a similar test for a non-empty tree.

"Most elegant"?

I would go for one of:

```<code>public boolean isEmpty() {
   return count == 0;
}
</code>```

... or perhaps ...

```<code>public boolean isEmpty() {
   return root == null;
}
</code>```

(Are you sure your implementation needs a count variable?)

Java, like C, allows you to omit the braces from an if statement. A common recommendation is to never omit the braces, because it's a cause of confusion.

What you have written is equivalent to:

```<code> if(count == 0) {
 }
 return false;
</code>```

So it always returns false.

You could write:

```<code> if(count == 0) {
    return true;
 }
 return false;
</code>```

Or without braces (not recommended):

```<code> if(count == 0)
     return true;
 return false;
</code>```

But since this is equivalent to return count == 0, it's inelegant to use an if statement.

Body:
I'm trying to write the most elegant isEmpty() method for my LinkedBinaryTree class.

When the compiler interacts with the if statement, it should return a boolean value or either true of false. However, since it is necessary to return a value outside the if statement, I've returned a value of false. My logic is that if (count == 0), isEmpty() returns true and doesn't bother with the second line (return false). Is this correct?

public class LinkedBinaryTree<T> implements BinaryTreeADT<T>
{
   protected int count;
   protected BinaryTreeNode<T> root;

   /**
    * Creates an empty binary tree.
    */
   public LinkedBinaryTree()
   {
      count = 0;
      root = null;
   }

   /**
    * Creates a binary tree with the specified element as its root.
    *
    * @param element  the element that will become the root of the new binary tree
    */
   public LinkedBinaryTree (T element)
   {
      count = 1;
      root = new BinaryTreeNode<T> (element);
   }

   /**
    * Returns true if this binary tree is empty and false otherwise.
    *
    * @return  true if this binary tree is empty
    */
   public boolean isEmpty()
   {
       if (count == 0);
       return false;
   }

Body:
"Is this correct?" -- you could find out by testing it. I recommend you do so, ideally in a jUnit test:

 @Test
 public void isEmpty_returns_true_for_empty_list() {
     LinkedBinaryTree tree = new LinkedBinaryTree();
     assertTrue(tree.isEmpty());
 }

... and a similar test for a non-empty tree.

"Most elegant"?

I would go for one of:

public boolean isEmpty() {
   return count == 0;
}

... or perhaps ...

public boolean isEmpty() {
   return root == null;
}

(Are you sure your implementation needs a count variable?)

Java, like C, allows you to omit the braces from an if statement. A common recommendation is to never omit the braces, because it's a cause of confusion.

What you have written is equivalent to:

 if(count == 0) {
 }
 return false;

So it always returns false.

You could write:

 if(count == 0) {
    return true;
 }
 return false;

Or without braces (not recommended):

 if(count == 0)
     return true;
 return false;

But since this is equivalent to return count == 0, it's inelegant to use an if statement.


问:
KSoap-Android\JCIFS sends empty HTTP post
I created an NTLM authenticating SOAP client based on KSOAP-Android and JCIFS. The implementation looks something like this:

```<code>public class NtlmServiceConnection implements ServiceConnection
{
    public NtlmServiceConnection(final SoapConnectionInfo connectionInfo, String path)
    {
        httpclient = new DefaultHttpClient();
        httpclient.getAuthSchemes().register(AuthPolicy.NTLM, new NTLMSchemeFactory());

    //...

    @Override
    public InputStream openInputStream() throws IOException {
        ByteArrayEntity re = new ByteArrayEntity(bufferStream.toByteArray());
        post.removeHeaders("CONTENT-LENGTH");
        post.setEntity(re);
        HttpResponse rep = httpclient.execute(post);
        InputStream stream = rep.getEntity().getContent();
        return stream;
    }

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

From the looks of it KSOAP is generating the correct message because bufferStream is populated with the SOAP envelope as expected. JCIFS seems to be doing its job as well as I can see the NTLM challenge response taking place via Wireshark. The issue is that the message body is missing. It is simply null. Due to this the web service encounters a 501 and the InputStream returned is null.

Anyone have a clue why this would happen?

Note: I'm removing the CONTENT-LENGTH header below because setEntity apparently tries to set this but KSOAP has already set it. I simply remove it and allow setEntity to reset it.

答: I finally figured it out and blogged about it here: http://csharpening.net/blog/?p=271</p>

Body:
I created an NTLM authenticating SOAP client based on KSOAP-Android and JCIFS. The implementation looks something like this:

public class NtlmServiceConnection implements ServiceConnection
{
    public NtlmServiceConnection(final SoapConnectionInfo connectionInfo, String path)
    {
        httpclient = new DefaultHttpClient();
        httpclient.getAuthSchemes().register(AuthPolicy.NTLM, new NTLMSchemeFactory());

    //...

    @Override
    public InputStream openInputStream() throws IOException {
        ByteArrayEntity re = new ByteArrayEntity(bufferStream.toByteArray());
        post.removeHeaders("CONTENT-LENGTH");
        post.setEntity(re);
        HttpResponse rep = httpclient.execute(post);
        InputStream stream = rep.getEntity().getContent();
        return stream;
    }

    //....
}

From the looks of it KSOAP is generating the correct message because bufferStream is populated with the SOAP envelope as expected. JCIFS seems to be doing its job as well as I can see the NTLM challenge response taking place via Wireshark. The issue is that the message body is missing. It is simply null. Due to this the web service encounters a 501 and the InputStream returned is null.

Anyone have a clue why this would happen?

Note: I'm removing the CONTENT-LENGTH header below because setEntity apparently tries to set this but KSOAP has already set it. I simply remove it and allow setEntity to reset it.


问:
Injective Matching in Neo4j
I'm looking for an efficient way to do injective matching in Neo4j. If you're not sure what I mean by that; I simply want matches to be returned where every returned node in a match is unique (e.g. has a unique ID), and the same holds for paths.

Using the diagram from Wikipedia (above), the domain, X, of matching is the nodes and paths in the pattern, and the co-domain, Y, is the Database's internal Graph. The above diagram is injective as no 2 arrows from X point to the same element in Y (so no 2 nodes from the pattern are matched to the same node in the Graph, and the same holds for edges), whereas default Neo4J matching is non-injective and allows 2 nodes from the pattern to be matched to the same node in the Graph (you can visualise an example of non-injective matching as the arrows from 1 and 2 in X both pointing to D in Y in the above diagram). Conventional Graph Theory would call matching  multiple items from the domain X to the same item in the co-domain Y "merging", but I can appreciate that that terminology may be confusing in this context.

I can simulate this for specific queries by specifying that matched nodes are distinct:

```<code>match (a), (b) where not id(a) = id(b) return a, b
</code>```

But I want to do it in a general sense without having to be this explicit in every query. So for this example I would like to return matches where (a) and (b) are unique nodes but I would like to do this with some general behaviour rather than specifying the uniqueness based on ID.

It does seem that paths are already guaranteed to be unique when I query, but if someone could confirm that that would be great.

答:
I am not really sure what exactly do you want, but I can upgrade your query to be more efficient.

```<code>Match (a),(b) where id(a) < id(b)
Return a,b
</code>```

If you want to return distinct nodes or relationships cypher has a distinct function. Example:

```<code>Match (a)-->(b)
Return distinct(a)
</code>```

P.s. always use labels for nodes as it speeds up query execution

Title: Injective Matching in Neo4j

Body:
I'm looking for an efficient way to do injective matching in Neo4j. If you're not sure what I mean by that; I simply want matches to be returned where every returned node in a match is unique (e.g. has a unique ID), and the same holds for paths.

Using the diagram from Wikipedia (above), the domain, X, of matching is the nodes and paths in the pattern, and the co-domain, Y, is the Database's internal Graph. The above diagram is injective as no 2 arrows from X point to the same element in Y (so no 2 nodes from the pattern are matched to the same node in the Graph, and the same holds for edges), whereas default Neo4J matching is non-injective and allows 2 nodes from the pattern to be matched to the same node in the Graph (you can visualise an example of non-injective matching as the arrows from 1 and 2 in X both pointing to D in Y in the above diagram). Conventional Graph Theory would call matching  multiple items from the domain X to the same item in the co-domain Y "merging", but I can appreciate that that terminology may be confusing in this context.

I can simulate this for specific queries by specifying that matched nodes are distinct:

match (a), (b) where not id(a) = id(b) return a, b

But I want to do it in a general sense without having to be this explicit in every query. So for this example I would like to return matches where (a) and (b) are unique nodes but I would like to do this with some general behaviour rather than specifying the uniqueness based on ID.

It does seem that paths are already guaranteed to be unique when I query, but if someone could confirm that that would be great.

Body:
I am not really sure what exactly do you want, but I can upgrade your query to be more efficient.

Match (a),(b) where id(a) < id(b)
Return a,b

If you want to return distinct nodes or relationships cypher has a distinct function. Example:

Match (a)-->(b)
Return distinct(a)

P.s. always use labels for nodes as it speeds up query execution


问:
Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'
I am new to EF core and I'm trying to get it to work with my ASP.NET Core project.

I get the above error in my startup.cs when trying configure the DbContext to use a connection string from config. I am following this tutorial.

The problematic code is in startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using tracV2.models;
using tracV2.data;

namespace tracV2
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddSingleton<IConfiguration>(Configuration);

            string conn = Configuration.GetConnectionString("optimumDB");

            services.AddDbContext<tracContext>(options => options.usesqlserver(conn));
        }
```
<p>The <code>UseSqlServer</code> method is recognized if I put it directly into the context:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace tracV2.data
{
    public class tracContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("myrealconnectionstring");
        }
</code>```

All my research online points to missing references, but I can't seem to find out which one I am missing (see image).

答:
First we install the Microsoft.EntityFrameworkCore.SqlServer NuGet Package:

```<code>PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer
</code>```

Then, after importing the namespace with

using Microsoft.EntityFrameworkCore;
```
<p>we add the database context:</p>
<pre class="lang-cs prettyprint-override"><code>services.AddDbContext<AspDbContext>(options =>
    options.UseSqlServer(config.GetConnectionString("optimumDB")));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to EF core and I'm trying to get it to work with my ASP.NET Core project.

I get the above error in my startup.cs when trying configure the DbContext to use a connection string from config. I am following this tutorial.

The problematic code is in startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using tracV2.models;
using tracV2.data;

namespace tracV2
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddSingleton<IConfiguration>(Configuration);

            string conn = Configuration.GetConnectionString("optimumDB");

            services.AddDbContext<tracContext>(options => options.usesqlserver(conn));
        }

The UseSqlServer method is recognized if I put it directly into the context:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace tracV2.data
{
    public class tracContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("myrealconnectionstring");
        }

All my research online points to missing references, but I can't seem to find out which one I am missing (see image).

Body:
First we install the Microsoft.EntityFrameworkCore.SqlServer NuGet Package:

PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer

Then, after importing the namespace with

using Microsoft.EntityFrameworkCore;

we add the database context:

services.AddDbContext<AspDbContext>(options =>
    options.UseSqlServer(config.GetConnectionString("optimumDB")));


问:
SQL how to remove new lines on string end?
Encountered issue when I needed to remove (or replace) new lines at the string end:

Somthing like this

```<code>-----
test

----
</code>```

to

```<code>----
test
----
</code>```

I encountered some examples such as

```<code>isnull(LEFT(fielddata, LEN(fielddata) - PATINDEX('%[^'+CHAR(9)+CHAR(10)+CHAR(12)+CHAR(13)+']%', REVERSE(fielddata))+1),'') as ResultValue
</code>```

But it doesn't seems to work well (in some cases there are still new lines left). It might be more appropriate to use something like regex ^\s+$, but I'm not sure how it supposed to look (just putting regex into example doesn't seems to work)

Can you help me with this please?

UPDATE

---- Is not a part of string! I simply don't know how else I suppose to show here string before (with new lines) and string after without them.

UPDATE 2

Found a reason why previous example didn't work in any situation. It does nothing in case if string contains ONLY new lines (yep, I have those kind of situations)

答:
The TRANSLATE() function should do the trick (REGEXP_REPLACE() would also work, but is more inefficient):

```<code>SELECT TRANSLATE(your_col, chr(10)||chr(11)||chr(13), '') FROM YOUR_TAB;
</code>```

This should remove all newlines, CRs and tabstops. If that's not enough (because the blank line in your example consists of many single spaces or something), you might have to adjust.

Body:
Encountered issue when I needed to remove (or replace) new lines at the string end:

Somthing like this

-----
test

----

to

----
test
----

I encountered some examples such as

isnull(LEFT(fielddata, LEN(fielddata) - PATINDEX('%[^'+CHAR(9)+CHAR(10)+CHAR(12)+CHAR(13)+']%', REVERSE(fielddata))+1),'') as ResultValue

But it doesn't seems to work well (in some cases there are still new lines left). It might be more appropriate to use something like regex ^\s+$, but I'm not sure how it supposed to look (just putting regex into example doesn't seems to work)

Can you help me with this please?

UPDATE

---- Is not a part of string! I simply don't know how else I suppose to show here string before (with new lines) and string after without them.

UPDATE 2

Found a reason why previous example didn't work in any situation. It does nothing in case if string contains ONLY new lines (yep, I have those kind of situations)

Body:
The TRANSLATE() function should do the trick (REGEXP_REPLACE() would also work, but is more inefficient):

SELECT TRANSLATE(your_col, chr(10)||chr(11)||chr(13), '') FROM YOUR_TAB;

This should remove all newlines, CRs and tabstops. If that's not enough (because the blank line in your example consists of many single spaces or something), you might have to adjust.


问:
Function declaration in R and its evaluation?
Sorry for not being more specific in my question title but I was not sure how to phrase it.

I am just trying to understand how function declarations work in R.

```<code>library(magrittr)
library(compiler)

fn1 <- function(x) {x + 1} %>% cmpfun()
fn2 <- (function(x) {x + 1}) %>% cmpfun()

fn1(1) # gives an error
fn2(1) # works as expected
</code>```

Why do I need parentheses around the function declaration so that fn2 works and fn1 does not?

If function is just like any other function, then why are not function calls (as in function declarations) obeying the normal syntax... From the help page on function, its syntax is:

```<code>function( arglist ) expr
return(value)
</code>```

答:
It’s a question of precedence: the first declaration is equivalent to

```<code>fn1 = function(x) ({x + 1} %>% cmpfun())
</code>```

That is, cmpfun is called on the result of {x + 1}, not on the function declaration itself.

Unfortunately I can’t find a documentation of these precedence rules, and the lack of a formal syntax for R means that the only source for this is the R source code itself (or, in this simple case, its observable runtime behaviour).

Apart from this, you ask

why are not function calls (as in function declarations) obeying the normal syntax

— This isn’t really relevant here (for the purpose of your question, it does obey normal syntax) but the reason is: because function, like some other things in R (if, for, …), is a special form that obeys a special syntax, defined by the language.

Body:
Sorry for not being more specific in my question title but I was not sure how to phrase it.

I am just trying to understand how function declarations work in R.

library(magrittr)
library(compiler)

fn1 <- function(x) {x + 1} %>% cmpfun()
fn2 <- (function(x) {x + 1}) %>% cmpfun()

fn1(1) # gives an error
fn2(1) # works as expected

Why do I need parentheses around the function declaration so that fn2 works and fn1 does not?

If function is just like any other function, then why are not function calls (as in function declarations) obeying the normal syntax... From the help page on function, its syntax is:

function( arglist ) expr
return(value)

Body:
It’s a question of precedence: the first declaration is equivalent to

fn1 = function(x) ({x + 1} %>% cmpfun())

That is, cmpfun is called on the result of {x + 1}, not on the function declaration itself.

Unfortunately I can’t find a documentation of these precedence rules, and the lack of a formal syntax for R means that the only source for this is the R source code itself (or, in this simple case, its observable runtime behaviour).

Apart from this, you ask

why are not function calls (as in function declarations) obeying the normal syntax

— This isn’t really relevant here (for the purpose of your question, it does obey normal syntax) but the reason is: because function, like some other things in R (if, for, …), is a special form that obeys a special syntax, defined by the language.


问:
Spring JSR-303 with form:errors tag
I'm trying to use JSR-303 validation and display it's results in jsp page. Here is jsp page code piece which shows error:

```<code><c:set var="Error">
    <form:errors path="name"/>
</c:set>
...
<spring:transform value="${Error}"/>
</code>```

In the controller I have the following:

```<code>@PostMapping(params = "next")
public String next(@Valid @ModelAttribute(COMMAND_NAME) final ProjectNewDetailsCommand cmd,
                   final Errors errors,
                   final Model model,
                   final HttpServletRequest request) {
</code>```

First, the solution which worked for me is writing a custom Validator class:

```<code>@Override
public void validate(Object o, Errors errors) {
    errors.pushNestedPath("project");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.project.creation.name.required");
    errors.popNestedPath();
}
</code>```

In this case the appropriate message from messages.properties was applied and show on UI:

```<code>error.project.creation.name.required=The name must not be blank.
</code>```

Here is another case when I use JSR-303 annotation:

```<code>public class Project {

    ...
    @Size(max = 100, message = "error.project.creation.size")
    private String name;
</code>```

In messages.properties there is the message under key error.project.creation.size, I've also tried to add the message with key Size.command.project.name as it's stated in some of the sources. Error object in controller is also not empty and contains validation errors. But when I use this approach with JSR-303 I got the following error:

```<code>Caused by: javax.servlet.jsp.JspTagException: No message found under code 'Size' for locale 'en_US'.
    at org.springframework.web.servlet.tags.MessageTag.doEndTag(MessageTag.java:200)
</code>```

Which means that for some reason Spring tries to apply Size error code instead of error.project.creation.size or Size.command.project.name. Any ideas why this is happening and how to fix this?

答:
Finally I was able to find the source of the problem. In the code for rendering alerts, there was a spring:message tag:

```<code><spring:message code="${error.code}" arguments="${error.arguments}"/>
</code>```

If works in the following way: it looks for last code from the codes array in Errors class (see DefaultMessageSourceResolvable.getCode method) and that's why it couldn't find Size message and didn't picked up defaultMessage created by hibernate validator or the custom one.

The simple fix in this case was to add text attribute:

```<code><spring:message code="${error.code}" arguments="${error.arguments}" text="${error.defaultMessage}"/>
</code>```

Title: Spring JSR-303 with form:errors tag

Body:
I'm trying to use JSR-303 validation and display it's results in jsp page. Here is jsp page code piece which shows error:

<c:set var="Error">
    <form:errors path="name"/>
</c:set>
...
<spring:transform value="${Error}"/>

In the controller I have the following:

@PostMapping(params = "next")
public String next(@Valid @ModelAttribute(COMMAND_NAME) final ProjectNewDetailsCommand cmd,
                   final Errors errors,
                   final Model model,
                   final HttpServletRequest request) {

First, the solution which worked for me is writing a custom Validator class:

@Override
public void validate(Object o, Errors errors) {
    errors.pushNestedPath("project");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "error.project.creation.name.required");
    errors.popNestedPath();
}

In this case the appropriate message from messages.properties was applied and show on UI:

error.project.creation.name.required=The name must not be blank.

Here is another case when I use JSR-303 annotation:

public class Project {

    ...
    @Size(max = 100, message = "error.project.creation.size")
    private String name;

In messages.properties there is the message under key error.project.creation.size, I've also tried to add the message with key Size.command.project.name as it's stated in some of the sources. Error object in controller is also not empty and contains validation errors. But when I use this approach with JSR-303 I got the following error:

Caused by: javax.servlet.jsp.JspTagException: No message found under code 'Size' for locale 'en_US'.
    at org.springframework.web.servlet.tags.MessageTag.doEndTag(MessageTag.java:200)

Which means that for some reason Spring tries to apply Size error code instead of error.project.creation.size or Size.command.project.name. Any ideas why this is happening and how to fix this?

Body:
Finally I was able to find the source of the problem. In the code for rendering alerts, there was a spring:message tag:

<spring:message code="${error.code}" arguments="${error.arguments}"/>

If works in the following way: it looks for last code from the codes array in Errors class (see DefaultMessageSourceResolvable.getCode method) and that's why it couldn't find Size message and didn't picked up defaultMessage created by hibernate validator or the custom one.

The simple fix in this case was to add text attribute:

<spring:message code="${error.code}" arguments="${error.arguments}" text="${error.defaultMessage}"/>