问:
How can I search a json file to return values satisfying a particular criteria?
Here is my json file:

```<code>{"items":[{"reputation":6623,"user_id":836,"location":"Durham, United Kingdom","link":"https://datascience.stackexchange.com/users/836/neil-slater","display_name":"Neil Slater"},{"reputation":6267,"user_id":381,"location":"Silicon Valley","link":"https://datascience.stackexchange.com/users/381/emre","display_name":"Emre"},{"reputation":5033,"user_id":2452,"location":"Atlanta, GA","link":"https://datascience.stackexchange.com/users/2452/aleksandr-blekh","display_name":"Aleksandr Blekh"},{"reputation":3537,"user_id":11097,"location":"Gurgaon, India","link":"https://datascience.stackexchange.com/users/11097/dawny33","display_name":"Dawny33"},{"reputation":3257,"user_id":21,"location":"London, United Kingdom","link":"https://datascience.stackexchange.com/users/21/sean-owen","display_name":"Sean Owen"}]
</code>```

How can I extract display names of users who are from a particular location, say Israel? I am trying to write nested query for the same but getting syntax errors.

答:
I think you are using this approach: </p>

```<code>   data = {"items":[{"reputation":6623,"user_id":836,"location":"Durham, United Kingdom","link":"https://datascience.stackexchange.com/users/836/neil-slater","display_name":"Neil Slater"},{"reputation":6267,"user_id":381,"location":"Silicon Valley","link":"https://datascience.stackexchange.com/users/381/emre","display_name":"Emre"},{"reputation":5033,"user_id":2452,"location":"Atlanta, GA","link":"https://datascience.stackexchange.com/users/2452/aleksandr-blekh","display_name":"Aleksandr Blekh"},{"reputation":3537,"user_id":11097,"location":"Gurgaon, India","link":"https://datascience.stackexchange.com/users/11097/dawny33","display_name":"Dawny33"},{"reputation":3257,"user_id":21,"location":"London, United Kingdom","link":"https://datascience.stackexchange.com/users/21/sean-owen","display_name":"Sean Owen"}]}

    for key,value in data.items():
             for i in range(len(value)):
                     if 'United Kingdom' in value[i]['location']:
                             print value[i]['display_name']
</code>```

<p>Output: </p>

```<code>Neil Slater
Sean Owen
</code>```

Body:
Here is my json file:

{"items":[{"reputation":6623,"user_id":836,"location":"Durham, United Kingdom","link":"https://datascience.stackexchange.com/users/836/neil-slater","display_name":"Neil Slater"},{"reputation":6267,"user_id":381,"location":"Silicon Valley","link":"https://datascience.stackexchange.com/users/381/emre","display_name":"Emre"},{"reputation":5033,"user_id":2452,"location":"Atlanta, GA","link":"https://datascience.stackexchange.com/users/2452/aleksandr-blekh","display_name":"Aleksandr Blekh"},{"reputation":3537,"user_id":11097,"location":"Gurgaon, India","link":"https://datascience.stackexchange.com/users/11097/dawny33","display_name":"Dawny33"},{"reputation":3257,"user_id":21,"location":"London, United Kingdom","link":"https://datascience.stackexchange.com/users/21/sean-owen","display_name":"Sean Owen"}]

How can I extract display names of users who are from a particular location, say Israel? I am trying to write nested query for the same but getting syntax errors.

Body:
I think you are using this approach:

   data = {"items":[{"reputation":6623,"user_id":836,"location":"Durham, United Kingdom","link":"https://datascience.stackexchange.com/users/836/neil-slater","display_name":"Neil Slater"},{"reputation":6267,"user_id":381,"location":"Silicon Valley","link":"https://datascience.stackexchange.com/users/381/emre","display_name":"Emre"},{"reputation":5033,"user_id":2452,"location":"Atlanta, GA","link":"https://datascience.stackexchange.com/users/2452/aleksandr-blekh","display_name":"Aleksandr Blekh"},{"reputation":3537,"user_id":11097,"location":"Gurgaon, India","link":"https://datascience.stackexchange.com/users/11097/dawny33","display_name":"Dawny33"},{"reputation":3257,"user_id":21,"location":"London, United Kingdom","link":"https://datascience.stackexchange.com/users/21/sean-owen","display_name":"Sean Owen"}]}

    for key,value in data.items():
             for i in range(len(value)):
                     if 'United Kingdom' in value[i]['location']:
                             print value[i]['display_name']

Output:

Neil Slater
Sean Owen


来源: stackexchange

问:
What cause memory reservation
I have an application written in c++ that reserved 1.2GB memory but only 600MB are committed.
The application use COM/DCOM, ADO.

I would ask you if you have any idea why so many memory are reserved and never committed?

Thanks

答: The application might intentionally reserve a large region for some allocator and only commit smaller regions as they are actually needed. If that's the case - they won't be committed until you make the application actually ask the allocator for memory allocation and it does commit memory.</p>

ContentLicense: CC BY-SA 2.5

Title: What cause memory reservation


问:
Express Session not Working for Ajax Call
When I call the /test route directly from the browser, I find that the session has been properly set. But when I do the same from an ajax call, I find that the session does not have the information I had previously added through the other route /temp.

express-session config

```<code>{
    "key": "nsid",
    "secret": "some secret password",
    "cookie": {
        "path": "/",
        "httpOnly": false,
        "maxAge": null,
        "secure": false
    },
    "resave": true,
    "saveUninitialized": true,
    "proxy": null
}
</code>```

routes.js

```<code>router.get('/temp', (req, res) => {
    const useCase = 'card';
    req.session = req.session || {};
    req.session.trackingInformation = {};
    req.session.trackingInformation.useCase = useCase;
    req.session.save();
    console.log(req.session);
    res.render('/temp');
});

router.get('/test', (req, res) => {
    console.log(Util.inspect(req.session));
    res.send({});
});
</code>```

ajax call

```<code>fetch('/test').then((response) => {
    if (response.status >= 400) {
        console.log(response.status);
    }
    return response.json();
}).then((json) => {
    console.log(json);
    //do something
});
</code>```

When I call the localhost:8000/temp and then call the /test as a fetch ajax call:

```<code>{
    "cookie": {
        "path": "/",
        "_expires": null,
        "originalMaxAge": null,
        "httpOnly": false,
        "secure": false
    },
    "_csrfSecret": "secret",
    "_shared": {
        "deviceInfo": {
        ...
        }
    }
}
</code>```

The trackingInformation property clearly is not set. But if I call the same directly from my browser localhost:8000/test after first calling locahost:8000/temp, I have the trackingInformation set in the session.

```<code>{
    "cookie": {
        ...
    },
    "_csrfSecret": "secret",
    "_shared": {
        "deviceInfo": {
        ...
        }
    },
    "trackingInformation": {
        "useCase": "card"
    }
}
</code>```

答:
The answer was in the ajax call. Fetch by default doesn't send the cookies. You need to enable the sending of cookies by passing credential: 'same-origin' as an option. So the fetch call should have been -

```<code>fetch('/test', {
    credentials: 'same-origin'
}).then((response) => {
    if (response.status >= 400) {
        console.log(response.status);
    }
    return response.json();
}).then((json) => {
    console.log(json);
    //do something
});
</code>```

Look at this for more information.

ContentLicense: CC BY-SA 3.0

Body:
When I call the /test route directly from the browser, I find that the session has been properly set. But when I do the same from an ajax call, I find that the session does not have the information I had previously added through the other route /temp.

express-session config

{
    "key": "nsid",
    "secret": "some secret password",
    "cookie": {
        "path": "/",
        "httpOnly": false,
        "maxAge": null,
        "secure": false
    },
    "resave": true,
    "saveUninitialized": true,
    "proxy": null
}

routes.js

router.get('/temp', (req, res) => {
    const useCase = 'card';
    req.session = req.session || {};
    req.session.trackingInformation = {};
    req.session.trackingInformation.useCase = useCase;
    req.session.save();
    console.log(req.session);
    res.render('/temp');
});

router.get('/test', (req, res) => {
    console.log(Util.inspect(req.session));
    res.send({});
});

ajax call

fetch('/test').then((response) => {
    if (response.status >= 400) {
        console.log(response.status);
    }
    return response.json();
}).then((json) => {
    console.log(json);
    //do something
});

When I call the localhost:8000/temp and then call the /test as a fetch ajax call:

{
    "cookie": {
        "path": "/",
        "_expires": null,
        "originalMaxAge": null,
        "httpOnly": false,
        "secure": false
    },
    "_csrfSecret": "secret",
    "_shared": {
        "deviceInfo": {
        ...
        }
    }
}

The trackingInformation property clearly is not set. But if I call the same directly from my browser localhost:8000/test after first calling locahost:8000/temp, I have the trackingInformation set in the session.

{
    "cookie": {
        ...
    },
    "_csrfSecret": "secret",
    "_shared": {
        "deviceInfo": {
        ...
        }
    },
    "trackingInformation": {
        "useCase": "card"
    }
}

Body:
The answer was in the ajax call. Fetch by default doesn't send the cookies. You need to enable the sending of cookies by passing credential: 'same-origin' as an option. So the fetch call should have been -

fetch('/test', {
    credentials: 'same-origin'
}).then((response) => {
    if (response.status >= 400) {
        console.log(response.status);
    }
    return response.json();
}).then((json) => {
    console.log(json);
    //do something
});

Look at this for more information.


答:
Sample Code :

```<code>import json

location = 'United Kingdom'
jso = '''{"items":[{"reputation":6623,"user_id":836,"location":"Durham, United Kingdom","link":"https://datascience.stackexchange.com/users/836/neil-slater","display_name":"Neil Slater"},{"reputation":6267,"user_id":381,"location":"Silicon Valley","link":"https://datascience.stackexchange.com/users/381/emre","display_name":"Emre"},{"reputation":5033,"user_id":2452,"location":"Atlanta, GA","link":"https://datascience.stackexchange.com/users/2452/aleksandr-blekh","display_name":"Aleksandr Blekh"},{"reputation":3537,"user_id":11097,"location":"Gurgaon, India","link":"https://datascience.stackexchange.com/users/11097/dawny33","display_name":"Dawny33"},{"reputation":3257,"user_id":21,"location":"London, United Kingdom","link":"https://datascience.stackexchange.com/users/21/sean-owen","display_name":"Sean Owen"}]}'''

dic = json.loads(jso)

for entry in dic['items']:
    if location.lower() in entry['location'].lower():
        print (entry['display_name'])
</code>```

Output:

```<code>Neil Slater
Sean Owen
</code>```

Title: How can I search a json file to return values satisfying a particular criteria?

Body:
Sample Code :

import json

location = 'United Kingdom'
jso = '''{"items":[{"reputation":6623,"user_id":836,"location":"Durham, United Kingdom","link":"https://datascience.stackexchange.com/users/836/neil-slater","display_name":"Neil Slater"},{"reputation":6267,"user_id":381,"location":"Silicon Valley","link":"https://datascience.stackexchange.com/users/381/emre","display_name":"Emre"},{"reputation":5033,"user_id":2452,"location":"Atlanta, GA","link":"https://datascience.stackexchange.com/users/2452/aleksandr-blekh","display_name":"Aleksandr Blekh"},{"reputation":3537,"user_id":11097,"location":"Gurgaon, India","link":"https://datascience.stackexchange.com/users/11097/dawny33","display_name":"Dawny33"},{"reputation":3257,"user_id":21,"location":"London, United Kingdom","link":"https://datascience.stackexchange.com/users/21/sean-owen","display_name":"Sean Owen"}]}'''

dic = json.loads(jso)

for entry in dic['items']:
    if location.lower() in entry['location'].lower():
        print (entry['display_name'])

Output:

Neil Slater
Sean Owen


问:
Email sent in PHP with no body and no attachment
I want to send a Word file as attachment using PHP and the email is being sent, but with no body and a noname attachment is sent.

Here is the code:

```<code>$website=getwebsite($id);
  //define the receiver of the email
$to = $email;
//define the subject of the email
$subject = "order- ".getorderid($id);
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: order@$website\r\nReply-To: order@$website";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents($file)));
//define the body of the message.
//echo $file;
ob_start(); //Turn on output buffering
?>

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<p>Dear Customer,</p>

<p>Please find attached your requested paper.</p>
<p>

Thanks & Regards</p>

<?php echo $website?>  Papers Team

 </p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/vnd.ms-word; name="plagerism.doc";
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
</code>```

Can anyone explain what I am doing wrong?

答: Instead of trying to compose the mime yourself, you could try using this class, saves you alot of headakes: http://sourceforge.net/projects/phpmailer/files/phpmailer%20for%20php5_6/</p>

Body:
I want to send a Word file as attachment using PHP and the email is being sent, but with no body and a noname attachment is sent.

Here is the code:

$website=getwebsite($id);
  //define the receiver of the email
$to = $email;
//define the subject of the email
$subject = "order- ".getorderid($id);
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: order@$website\r\nReply-To: order@$website";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents($file)));
//define the body of the message.
//echo $file;
ob_start(); //Turn on output buffering
?>

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Dear Customer,

Please find attached your requested paper.

Thanks & Regards

<?php echo $website?>  Papers Team

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/vnd.ms-word; name="plagerism.doc";
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";

Can anyone explain what I am doing wrong?


问:
Use Django's ORM in Celery
I have a few django micro-services.
Their main workload is constant background processes, not request handling.

The background processes constantly use Django's ORM, and since I needed to hack a few things for it to work properly (it did for quite a while), now I have problems with the DB connection, since Django is not really built for using DB connections a lot in the background I guess...

Celery is always suggested in these cases, but before switching the entire design, I want to know if it really is a good solution.

Can celery tasks (a lot of tasks, time-consuming tasks) use Django's ORM in the background without problems?

答:
Can celery tasks (a lot of tasks, time-consuming tasks) use Django's ORM in the background without problems?

Yes, depending on your definition of “problems” :-)

More seriously: The Django ORM performance will be mostly limited by the performance characteristics of the underlying database engine.

If your chosen database engine is PostgreSQL, for example, you will be able to handle a high volume of concurrent connections.

Title: Use Django's ORM in Celery


问:
Props value not showing on top of render to a function ReactJS
However the this.props.NotesAll retrieving object from another component and it's showing object's to under render() method but when I'm trying to use that this.props.NotesAll on top of render on a function to working with those object, and i'm trying to check the value with console on functions it's just always say's undefined shit. So please help me ReactNinja's what actually is the wrong is going on here.

Here codes you can have a look on them

```<code>export default class EditNotes extends Component {
    constructor(props) {
        super(props);
        this.state ={};
    }

    handleEdit() {
        console.log(this + ' Clicked on That ');
    }

//Here it's throwing error when I'm trying to click and console. the problem is here. i want this.props.NotesAll value here also to finding elements from objects
    handleDelete(id) {
        let Notes = this.props.NotesAll;
        console.log(Notes)
    }

    render() {
        let noteItems;
</code>```

//this.props.NotesAll working fine here.

```<code>        if (this.props.NotesAll) {
            noteItems = this.props.NotesAll.map( Note => {
                return(
                    <li key={Note.id}>{Note.body}
                    <button onClick={this.handleEdit.bind(Note.id)} className="btn btn-primary btn-sm">Edit</button>
                    <button onClick={this.handleDelete.bind(Note.id)} className="btn btn-danger btn-sm">Delete</button></li>
                    );
            });
        }
        return(
            <div className="col-md-4">
                <h3 className="header-ttile">Current Notes:</h3>
                <ul className="note-item-wrapper">
                {noteItems}
                </ul>
            </div>
            );
    }
}
</code>```

答:
You define the binding in a wrong way, first parameter will be the context to which you want to bind.

Use this:

```<code><button onClick={this.handleDelete.bind(this, Note.id)}
</code>```

Syntax:

```<code>fun.bind(thisArg[, arg1[, arg2[, ...]]])
</code>```

thisArg:

The value to be passed as the this parameter to the target function
  when the bound function is called.

Body:
However the this.props.NotesAll retrieving object from another component and it's showing object's to under render() method but when I'm trying to use that this.props.NotesAll on top of render on a function to working with those object, and i'm trying to check the value with console on functions it's just always say's undefined shit. So please help me ReactNinja's what actually is the wrong is going on here.

Here codes you can have a look on them

export default class EditNotes extends Component {
    constructor(props) {
        super(props);
        this.state ={};
    }

    handleEdit() {
        console.log(this + ' Clicked on That ');
    }

//Here it's throwing error when I'm trying to click and console. the problem is here. i want this.props.NotesAll value here also to finding elements from objects
    handleDelete(id) {
        let Notes = this.props.NotesAll;
        console.log(Notes)
    }

    render() {
        let noteItems;

//this.props.NotesAll working fine here.

        if (this.props.NotesAll) {
            noteItems = this.props.NotesAll.map( Note => {
                return(

{Note.body}
                    <button onClick={this.handleEdit.bind(Note.id)} className="btn btn-primary btn-sm">Edit</button>
                    <button onClick={this.handleDelete.bind(Note.id)} className="btn btn-danger btn-sm">Delete</button>

                    );
            });
        }
        return(

Current Notes:

                {noteItems}

            );
    }
}

Body:
You define the binding in a wrong way, first parameter will be the context to which you want to bind.

Use this:

<button onClick={this.handleDelete.bind(this, Note.id)}

Syntax:

fun.bind(thisArg[, arg1[, arg2[, ...]]])

thisArg:

The value to be passed as the this parameter to the target function
  when the bound function is called.


问:
Printing with sed or awk a line following a matching pattern
Question: I'd like to print a single line directly following a line that contains a matching pattern.

My version of sed will not take the following syntax (it bombs out on +1p) which would seem like a simple solution:

```<code>sed -n '/ABC/,+1p' infile
</code>```

I assume awk would be better to do multiline processing, but I am not sure how to do it.

答:
Actually sed -n '/pattern/{n;p}' filename will fail if the pattern match continuous lines:

```<code>$ seq 15 |sed -n '/1/{n;p}'
2
11
13
15
</code>```

The expected answers should be:

```<code>2
11
12
13
14
15
</code>```

My solution is:

```<code>$ sed -n -r 'x;/_/{x;p;x};x;/pattern/!s/.*//;/pattern/s/.*/_/;h' filename
</code>```

For example:

```<code>$ seq 15 |sed -n -r 'x;/_/{x;p;x};x;/1/!s/.*//;/1/s/.*/_/;h'
2
11
12
13
14
15
</code>```

Explains:

x;: at the beginning of each line from input, use x command to exchange the contents in pattern space & hold space.

/_/{x;p;x};: if pattern space, which is the hold space actually, contains _ (this is just a indicator indicating if last line matched the pattern or not), then use x to exchange the actual content of current line to pattern space, use p to print current line, and x to recover this operation.

x: recover the contents in pattern space and hold space.

/pattern/!s/.*//: if current line does NOT match pattern, which means we should NOT print the NEXT following line, then use s/.*// command to delete all contents in pattern space.

/pattern/s/.*/_/: if current line matches pattern, which means we should print the NEXT following line, then we need to set a indicator to tell sed to print NEXT line, so use s/.*/_/ to substitute all contents in pattern space to a _(the second command will use it to judge if last line matched the pattern or not).

h: overwrite the hold space with the contents in pattern space; then, the content in hold space is ^_$  which means current line matches the pattern, or ^$, which means current line does NOT match the pattern.

the fifth step and sixth step can NOT exchange, because after s/.*/_/, the pattern space can NOT match /pattern/, so the s/.*// MUST be executed!

ContentLicense: CC BY-SA 4.0

Body:
Question: I'd like to print a single line directly following a line that contains a matching pattern.

My version of sed will not take the following syntax (it bombs out on +1p) which would seem like a simple solution:

sed -n '/ABC/,+1p' infile

I assume awk would be better to do multiline processing, but I am not sure how to do it.

Body:
Actually sed -n '/pattern/{n;p}' filename will fail if the pattern match continuous lines:

$ seq 15 |sed -n '/1/{n;p}'
2
11
13
15

The expected answers should be:

2
11
12
13
14
15

My solution is:

$ sed -n -r 'x;/_/{x;p;x};x;/pattern/!s/.*//;/pattern/s/.*/_/;h' filename

For example:

$ seq 15 |sed -n -r 'x;/_/{x;p;x};x;/1/!s/.*//;/1/s/.*/_/;h'
2
11
12
13
14
15

Explains:

x;: at the beginning of each line from input, use x command to exchange the contents in pattern space & hold space.

/_/{x;p;x};: if pattern space, which is the hold space actually, contains _ (this is just a indicator indicating if last line matched the pattern or not), then use x to exchange the actual content of current line to pattern space, use p to print current line, and x to recover this operation.

x: recover the contents in pattern space and hold space.

/pattern/!s/.*//: if current line does NOT match pattern, which means we should NOT print the NEXT following line, then use s/.*// command to delete all contents in pattern space.

/pattern/s/.*/_/: if current line matches pattern, which means we should print the NEXT following line, then we need to set a indicator to tell sed to print NEXT line, so use s/.*/_/ to substitute all contents in pattern space to a _(the second command will use it to judge if last line matched the pattern or not).

h: overwrite the hold space with the contents in pattern space; then, the content in hold space is ^_$  which means current line matches the pattern, or ^$, which means current line does NOT match the pattern.

the fifth step and sixth step can NOT exchange, because after s/.*/_/, the pattern space can NOT match /pattern/, so the s/.*// MUST be executed!


问:
Using two projects with different configuration settings in a single solution visual studio
I am using a a single solution to reside two projects in visual studio 2012.

Project 1:

wpf

uses "any cpu" configurations (which is a must)

Project 1:

winforms

uses "x86" configurations (which is a must again)

the solution runs like this.

the window from wpf application opens up as startup window. from here a button is pressed to open a form in winform project.

Problem: if i keep the configuration as any cpu, the winform window wont open up and give an error. If i keep the configuration as x86 the wpf would give an error becasue the mlapp (matlab application) i am using wont be recognised.

please help.

答: The solution is to set individual projects to respective configurations as per requirement and then setting the overall solution configuration to "mixed platforms". it worked</p>


问:
Redux-observable returning some sample data
I am using redux-observable and I need to return some sample data as an Observable.  I have the following code in one of my epics

```<code>const sampleFilteredStores = Observable.of([{ type: 'FILTERED_STORES', store: 'a' }, { type: 'FILTERED_STORES', store: 'b' }]);
const filteredStores$ = action$.ofType('SEARCH_STORES').mapTo(Observable.of(sampleFilteredStores).mergeAll());
return filteredStores$;
</code>```

However when I run this I get an error

instrument.js:56 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.(…)

What am I doing wrong here and how do I fix this?

答:
Investigation

In the case of the example code you gave, the first thing we need to do is indent and format the code so that it's easier to understand what is happening.

```<code>const somethingEpic = action => {
  const sampleFilteredStores = Observable.of([
    { type: 'FILTERED_STORES', store: 'a' },
    { type: 'FILTERED_STORES', store: 'b' }
  ]);
  const filteredStores$ = action$.ofType('SEARCH_STORES')
    .mapTo(
      Observable.of(sampleFilteredStores)
        .mergeAll()
    );

  return filteredStores$;
};
</code>```

Exactly how you format your code is your choice, but I personally find something like this much more readable. It will help you debug but also significantly help any future maintainers of your code understand your intent.

mapTo

Now I can see right away one problem, which is that you're passing an Observable to mapTo, which is highly unusual in Rx. It's certainly not wrong 100% of the time, but 99.99% and even in the 0.01% there would be much clearer ways to show the desired intent.

Observable.of

Digging in further, I see two usages of Observable.of.

The first one that stuck out is you pass an Observable to Observable.of: Observable.of(sampleFilteredStores) The same advice as mapTo applies here, this is very uncommon and not recommended because it creates higher order Observables unnecessarily. I do see you use mergeAll() to flatten it, but that gives you an Observable that is basically identical to what sampleFilteredStores is without the indirection.

When I dig even deeper I notice another subtle, but critical thing, you pass an array of actions to Observable.of. This is also highly suspicious because that means you create an Observable that just emits an array of two actions, not emits those two actions sequentially directly. If the later is what you intended, instead you needed to pass the objects directly as arguments themselves. Observable.of(action1, action2, action3, ...etc). You may have gotten confused from seeing someone use Observable.from passing in an array, but that's different than Observable.of

Root Cause

Combining those discoveries I can now see that this epic actually emits an Observable, rather than actions, which is why you're receiving the error from redux. That Observable itself actually would emit an array of actions, so even if you had flatten that Observable out you still would receive the same error.

Solution

It appears the provided code is likely contrived either to simplify your question or as you were learning Rx or redux-observable. But in this specific case I believe you wanted to listen for SEARCH_STORES and when received sequentially dispatch two actions both of type FILTERED_STORES with differing store values.

Using idiomatic Rx, that could look something like this:

```<code>const somethingEpic = action => {
  return action$.ofType('SEARCH_STORES')
    .mergeMap(() => Observable.of(
      { type: 'FILTERED_STORES', store: 'a' },
      { type: 'FILTERED_STORES', store: 'b' }
    ))
};
</code>```

Here we're using mergeMap, but since the Observable.of we flatten in emits synchronously we could have used switchMap or concatMap too, they would have had the same net effect--but that's not the case for Observables that emit async! So definitely study up on the various flattening strategy operators.

This chain can be described as: Whenever we receive object with the property type equals SEARCH_STORES, map it to an Observable of two objects (the FILTERED_STORES actions) that emit sequentially and synchronously.

Closing

Hopefully this helps! One thing to keep in mind when learning and using redux-observable is that it is almost entirely "just RxJS" that happens to be dealing with object which are "actions". So normal, idiomatic Rx is normal idiomatic redux-observable. Same with the problems you might encounter. The only real difference is that redux-observable provides the single ofType operator as shorthand to a filter (as the docs describe). If you have Rx issues in the future, you might find it helpful to refactor your examples to use filter and phrase them agnostic of redux-observable since the Rx community is obviously much larger!

Body:
I am using redux-observable and I need to return some sample data as an Observable.  I have the following code in one of my epics

const sampleFilteredStores = Observable.of([{ type: 'FILTERED_STORES', store: 'a' }, { type: 'FILTERED_STORES', store: 'b' }]);
const filteredStores$ = action$.ofType('SEARCH_STORES').mapTo(Observable.of(sampleFilteredStores).mergeAll());
return filteredStores$;

However when I run this I get an error

instrument.js:56 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.(…)

What am I doing wrong here and how do I fix this?

Body:
Investigation

In the case of the example code you gave, the first thing we need to do is indent and format the code so that it's easier to understand what is happening.

const somethingEpic = action => {
  const sampleFilteredStores = Observable.of([
    { type: 'FILTERED_STORES', store: 'a' },
    { type: 'FILTERED_STORES', store: 'b' }
  ]);
  const filteredStores$ = action$.ofType('SEARCH_STORES')
    .mapTo(
      Observable.of(sampleFilteredStores)
        .mergeAll()
    );

  return filteredStores$;
};

Exactly how you format your code is your choice, but I personally find something like this much more readable. It will help you debug but also significantly help any future maintainers of your code understand your intent.

mapTo

Now I can see right away one problem, which is that you're passing an Observable to mapTo, which is highly unusual in Rx. It's certainly not wrong 100% of the time, but 99.99% and even in the 0.01% there would be much clearer ways to show the desired intent.

Observable.of

Digging in further, I see two usages of Observable.of.

The first one that stuck out is you pass an Observable to Observable.of: Observable.of(sampleFilteredStores) The same advice as mapTo applies here, this is very uncommon and not recommended because it creates higher order Observables unnecessarily. I do see you use mergeAll() to flatten it, but that gives you an Observable that is basically identical to what sampleFilteredStores is without the indirection.

When I dig even deeper I notice another subtle, but critical thing, you pass an array of actions to Observable.of. This is also highly suspicious because that means you create an Observable that just emits an array of two actions, not emits those two actions sequentially directly. If the later is what you intended, instead you needed to pass the objects directly as arguments themselves. Observable.of(action1, action2, action3, ...etc). You may have gotten confused from seeing someone use Observable.from passing in an array, but that's different than Observable.of

Root Cause

Combining those discoveries I can now see that this epic actually emits an Observable, rather than actions, which is why you're receiving the error from redux. That Observable itself actually would emit an array of actions, so even if you had flatten that Observable out you still would receive the same error.

Solution

It appears the provided code is likely contrived either to simplify your question or as you were learning Rx or redux-observable. But in this specific case I believe you wanted to listen for SEARCH_STORES and when received sequentially dispatch two actions both of type FILTERED_STORES with differing store values.

Using idiomatic Rx, that could look something like this:

const somethingEpic = action => {
  return action$.ofType('SEARCH_STORES')
    .mergeMap(() => Observable.of(
      { type: 'FILTERED_STORES', store: 'a' },
      { type: 'FILTERED_STORES', store: 'b' }
    ))
};

Here we're using mergeMap, but since the Observable.of we flatten in emits synchronously we could have used switchMap or concatMap too, they would have had the same net effect--but that's not the case for Observables that emit async! So definitely study up on the various flattening strategy operators.

This chain can be described as: Whenever we receive object with the property type equals SEARCH_STORES, map it to an Observable of two objects (the FILTERED_STORES actions) that emit sequentially and synchronously.

Closing

Hopefully this helps! One thing to keep in mind when learning and using redux-observable is that it is almost entirely "just RxJS" that happens to be dealing with object which are "actions". So normal, idiomatic Rx is normal idiomatic redux-observable. Same with the problems you might encounter. The only real difference is that redux-observable provides the single ofType operator as shorthand to a filter (as the docs describe). If you have Rx issues in the future, you might find it helpful to refactor your examples to use filter and phrase them agnostic of redux-observable since the Rx community is obviously much larger!


问:
Wicket: how do I set dynamic fileName (with timestamp) for ResourceStream download
I am trying to implement support for dynamically setting the fileName for my IResource each time I download the csv file.

I have attached my work so far below. Is this the right way to override and set custom file names for each download? There is a method setFileName that is also listed as an option.
Can someone tell me which is recommended (setResponseHeaders or setFileName) and how best to implement? I am relatively new to wicket and am still finding my way around.

```<code>protected <T extends Object> IResource exportResource(String fileName,  final IDataExporter exporter, final DataTable<T, String> table)
{
final String file = fileName;
final ResourceStreamResource resource = new ResourceStreamResource()
    {
@Override
protected IResourceStream getResourceStream()
{
return new DataExportResourceStreamWriter(dataExporter,table);
}

@Override
protected void setResponseHeaders(ResourceResponse data, Attributes   attributes) {
String pattern = "yyyy-MM-dd_HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String timestamp = simpleDateFormat.format(new Date());
String fileName = file.substring(0,   file.indexOf(".csv"))+"_"+timeStamp+".csv";
data.setFileName(fileName);
super.setResponseHeaders(data, attributes);
}
</code>```

}

Thanks in advance.

答: Your implementation will work fine! To set the file name you can override any method that gives you access to ResourceResponse.

Body:
I am trying to implement support for dynamically setting the fileName for my IResource each time I download the csv file.

I have attached my work so far below. Is this the right way to override and set custom file names for each download? There is a method setFileName that is also listed as an option.
Can someone tell me which is recommended (setResponseHeaders or setFileName) and how best to implement? I am relatively new to wicket and am still finding my way around.

protected <T extends Object> IResource exportResource(String fileName,  final IDataExporter exporter, final DataTable<T, String> table)
{
final String file = fileName;
final ResourceStreamResource resource = new ResourceStreamResource()
    {
@Override
protected IResourceStream getResourceStream()
{
return new DataExportResourceStreamWriter(dataExporter,table);
}

@Override
protected void setResponseHeaders(ResourceResponse data, Attributes   attributes) {
String pattern = "yyyy-MM-dd_HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String timestamp = simpleDateFormat.format(new Date());
String fileName = file.substring(0,   file.indexOf(".csv"))+"_"+timeStamp+".csv";
data.setFileName(fileName);
super.setResponseHeaders(data, attributes);
}

}

Thanks in advance.


问:
I can't migrate the database of my Rails app on Heroku with sqlite
I'm following this tutorial on creating Ruby on Rail apps, and I've hit a roadblock. I am trying to migrate its database to Heroku, only to be told this:

```<code>c:\Sites\railsbridge\test_app>heroku run rails db:migrate
Running rails db:migrate on floating-ocean-40882... up, run.5709 (Free)
rails aborted!
Gem::LoadError: Specified 'sqlite3' for database adapter, but the gem is not
loaded. Add `gem 'sqlite3'` to your Gemfile (and ensure its version is at the
minimum required by ActiveRecord).
</code>```

I already have sqlite3 listed in my Gemfile, what am I doing wrong?

答:
Heroku does not support sqlite and it is suggested to use postgresql for production

Please look into the following posts

Heroku deployment failed because of sqlite3 gem error

Deploying RoR app to Heroku with Sqlite3 fails

You can use Postgresql for production and the change should be simple. Just a change of gem in Gemfile and change in database.yml will do.

Body:
I'm following this tutorial on creating Ruby on Rail apps, and I've hit a roadblock. I am trying to migrate its database to Heroku, only to be told this:

c:\Sites\railsbridge\test_app>heroku run rails db:migrate
Running rails db:migrate on floating-ocean-40882... up, run.5709 (Free)
rails aborted!
Gem::LoadError: Specified 'sqlite3' for database adapter, but the gem is not
loaded. Add `gem 'sqlite3'` to your Gemfile (and ensure its version is at the
minimum required by ActiveRecord).

I already have sqlite3 listed in my Gemfile, what am I doing wrong?


问:
How to rename the log files which will create in rotatingFileHandler after exceeding maxBytes to current datetime.log?
Is it possible to override rollOver() of rotatingFileHandler so that log files name will be current date time.log?

I am new to Python programming.

Code:

```<code>def logger(self , inputStr):

    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')

    fileName = 'log-'+dateTime+'.log'
    Path = path+'/'+fileName

    logger = logging.getLogger("Rotating Log")
    logger.setLevel(logging.DEBUG)
    #logger = logging.Formatter('%(asctime)-15s %(clientip)s %(user)-8s %(message)s')
    handler = RotatingFileHandler(Path, maxBytes=1000000, backupCount=5)
    logger.addHandler(handler)
    for i in range(1000000):
        logger.debug("This is test log line %s" % i)
</code>```

答:
This is how the doRollover() is override to have backup file names as current datetime.log
myRotatingFileHandler.py

```<code>import datetime
import os
import sys
import logging
from logging.handlers import BaseRotatingHandler
import time

class myRotatingFileHandler(BaseRotatingHandler):
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):
    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')

    filename = filename +'/log-'+dateTime+'.log'
    if maxBytes > 0:
        mode = 'a'
    BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
    self.maxBytes = maxBytes
    self.backupCount = backupCount

def doRollover(self):
    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')
    #fileName = 'log-'+dateTime+'.log'
    df = ''
    if self.stream:
        self.stream.close()
        self.stream = None
    if self.backupCount > 0:
        for i in range(self.backupCount - 1, 0, -1):
            sf = self.baseFilename+'/'+'log-'+ datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S') + '.log'
            df = self.baseFilename+'/'+'log-'+ datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S') + '.log'
            if os.path.exists(sf):
                if os.path.exists(df):
                    os.remove(df)
                os.rename(sf, df)
        wkspFldr = os.path.dirname(self.baseFilename)
        df = wkspFldr+'/'+'log-'+ datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S') + '.log'
        print 'LOG FILE ---> ',df
        if os.path.exists(df):
            os.remove(df)
        if os.path.exists(self.baseFilename):
            os.rename(self.baseFilename, df)
    if not self.delay:
        self.stream = self._open()

def shouldRollover(self, record):
    if self.stream is None:
        self.stream = self._open()
    if self.maxBytes > 0:
        msg = "%s\n" % self.format(record)
        self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature
        if self.stream.tell() + len(msg) >= self.maxBytes:
            return 1
    return 0
</code>```

This is the .py code where we have logger function
config.py

```<code>import logging
import os
import datetime
from logging.handlers import RotatingFileHandler
import time
from subprocess import call
from time import gmtime, strftime
import re
import logging.handlers

import myRotatingFileHandler

path = ''
Interval = ''
Value = 0

class config:
def __init__(self, givenPath, interval, value):
    global path
    global Interval
    global Value
    path = givenPath
    Interval = interval
    Value = value

def remove_file_by_days(self):
    now = time.time()
    cutoff = now - (value * 86400)
    files = os.listdir(path)
    file_path = os.path.join(path)

    for xfile in files:
        filePath = file_path + xfile
        if os.path.isfile(filePath):
            t = os.stat(filePath)
            c = t.st_ctime
            if c < cutoff:
                print 'removing file...'
                print filePath
                os.remove(filePath)

def remove_file_by_hours(self):
    dir_to_search = os.listdir(path)
    for file in filenames:
        curpath = os.path.join(path, file)
        file_modified = datetime.fromtimestamp(os.path.getmtime(curpath))
        if datetime.datetime.now() - file_modified > datetime.timedelta(hours = Value):
            print 'removing file...'
            print curpath
            os.remove(curpath)

def remove_file_by_minutes(self):
    dir_to_search = os.listdir(path)
    for file in dir_to_search:
        curpath = os.path.join(path, file)
        file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
        if datetime.datetime.now() - file_modified > datetime.timedelta(hours = Value/60 ):
            print 'removing file...'
            print curpath
            os.remove(curpath)

def logger(self , inputStr):
    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')
    fileName = 'log-'+dateTime+'.log'
    Path = path
    logger = logging.getLogger("Rotating Log")
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler = myRotatingFileHandler.myRotatingFileHandler(Path, maxBytes=1024000*10, backupCount=5)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    for i in range(1000000):
        logger.debug("This is test log line %s" % i)

def debug(self, inputStr):
    if Interval == 'days':
        self.remove_file_by_days()
    if Interval == 'hours':
        self.remove_file_by_hours()
    if Interval == 'minutes':
        self.remove_file_by_minutes()
    self.logger(inputStr)
</code>```

The calling main
logMain.py

```<code>import logging
import os
import sys
import config
from config import config

if __name__ == '__main__':
obj = config('/var/www/cgi-bin/pythonPractice/test/','minutes', 2)
obj.debug('abc')
</code>```

Overall this program does removing of log files form the given path according to number of days, number of hours and number of minutes. And creates the log files with name current datetime.log, if the log file exceeds 10 mb it will create other log file with name current datetime.log.

Body:
Is it possible to override rollOver() of rotatingFileHandler so that log files name will be current date time.log?

I am new to Python programming.

Code:

def logger(self , inputStr):

    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')

    fileName = 'log-'+dateTime+'.log'
    Path = path+'/'+fileName

    logger = logging.getLogger("Rotating Log")
    logger.setLevel(logging.DEBUG)
    #logger = logging.Formatter('%(asctime)-15s %(clientip)s %(user)-8s %(message)s')
    handler = RotatingFileHandler(Path, maxBytes=1000000, backupCount=5)
    logger.addHandler(handler)
    for i in range(1000000):
        logger.debug("This is test log line %s" % i)

Body:
This is how the doRollover() is override to have backup file names as current datetime.log
myRotatingFileHandler.py

import datetime
import os
import sys
import logging
from logging.handlers import BaseRotatingHandler
import time

class myRotatingFileHandler(BaseRotatingHandler):
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0):
    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')

    filename = filename +'/log-'+dateTime+'.log'
    if maxBytes > 0:
        mode = 'a'
    BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
    self.maxBytes = maxBytes
    self.backupCount = backupCount

def doRollover(self):
    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')
    #fileName = 'log-'+dateTime+'.log'
    df = ''
    if self.stream:
        self.stream.close()
        self.stream = None
    if self.backupCount > 0:
        for i in range(self.backupCount - 1, 0, -1):
            sf = self.baseFilename+'/'+'log-'+ datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S') + '.log'
            df = self.baseFilename+'/'+'log-'+ datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S') + '.log'
            if os.path.exists(sf):
                if os.path.exists(df):
                    os.remove(df)
                os.rename(sf, df)
        wkspFldr = os.path.dirname(self.baseFilename)
        df = wkspFldr+'/'+'log-'+ datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S') + '.log'
        print 'LOG FILE ---> ',df
        if os.path.exists(df):
            os.remove(df)
        if os.path.exists(self.baseFilename):
            os.rename(self.baseFilename, df)
    if not self.delay:
        self.stream = self._open()

def shouldRollover(self, record):
    if self.stream is None:
        self.stream = self._open()
    if self.maxBytes > 0:
        msg = "%s\n" % self.format(record)
        self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature
        if self.stream.tell() + len(msg) >= self.maxBytes:
            return 1
    return 0

This is the .py code where we have logger function
config.py

import logging
import os
import datetime
from logging.handlers import RotatingFileHandler
import time
from subprocess import call
from time import gmtime, strftime
import re
import logging.handlers

import myRotatingFileHandler

path = ''
Interval = ''
Value = 0

class config:
def __init__(self, givenPath, interval, value):
    global path
    global Interval
    global Value
    path = givenPath
    Interval = interval
    Value = value

def remove_file_by_days(self):
    now = time.time()
    cutoff = now - (value * 86400)
    files = os.listdir(path)
    file_path = os.path.join(path)

    for xfile in files:
        filePath = file_path + xfile
        if os.path.isfile(filePath):
            t = os.stat(filePath)
            c = t.st_ctime
            if c < cutoff:
                print 'removing file...'
                print filePath
                os.remove(filePath)

def remove_file_by_hours(self):
    dir_to_search = os.listdir(path)
    for file in filenames:
        curpath = os.path.join(path, file)
        file_modified = datetime.fromtimestamp(os.path.getmtime(curpath))
        if datetime.datetime.now() - file_modified > datetime.timedelta(hours = Value):
            print 'removing file...'
            print curpath
            os.remove(curpath)

def remove_file_by_minutes(self):
    dir_to_search = os.listdir(path)
    for file in dir_to_search:
        curpath = os.path.join(path, file)
        file_modified = datetime.datetime.fromtimestamp(os.path.getmtime(curpath))
        if datetime.datetime.now() - file_modified > datetime.timedelta(hours = Value/60 ):
            print 'removing file...'
            print curpath
            os.remove(curpath)

def logger(self , inputStr):
    dateTime = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')
    fileName = 'log-'+dateTime+'.log'
    Path = path
    logger = logging.getLogger("Rotating Log")
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler = myRotatingFileHandler.myRotatingFileHandler(Path, maxBytes=1024000*10, backupCount=5)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    for i in range(1000000):
        logger.debug("This is test log line %s" % i)

def debug(self, inputStr):
    if Interval == 'days':
        self.remove_file_by_days()
    if Interval == 'hours':
        self.remove_file_by_hours()
    if Interval == 'minutes':
        self.remove_file_by_minutes()
    self.logger(inputStr)

The calling main
logMain.py

import logging
import os
import sys
import config
from config import config

if __name__ == '__main__':
obj = config('/var/www/cgi-bin/pythonPractice/test/','minutes', 2)
obj.debug('abc')

Overall this program does removing of log files form the given path according to number of days, number of hours and number of minutes. And creates the log files with name current datetime.log, if the log file exceeds 10 mb it will create other log file with name current datetime.log.


问:
Why bash alias doesn't work in scripts?
I'm using a Mac and I have this alias defined in .bashrc:

```<code>$cat .bashrc | grep la
alias la='ls -la'
</code>```

then I try to use it in a script:

```<code>$cat ./mytest.sh
#!/bin/bash
la
</code>```

It runs and says it cannot find la:

```<code>./mytest.sh: line 2: la: command not found
</code>```

Why is this? I tried on both Mac and Linux, same error!

答:
Your .bashrc is only used by interactive shells. https://www.gnu.org/software/bash/manual/bashref.html#Bash-Startup-Files says:

Invoked non-interactively

When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed:

```<code>if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
</code>```

but the value of the PATH variable is not used to search for the filename.

As noted above, if a non-interactive shell is invoked with the --login option, Bash attempts to read and execute commands from the login shell startup files.

As you can see, there's nothing about .bashrc there. Your alias simply doesn't exist in the script.

But even if .bashrc were read, there's another problem:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt.

So if you wanted aliases to work in a script, you'd have to do shopt -s expand_aliases first. Or just use a shell function instead of an alias:

```<code>la() {
    ls -la
}
</code>```

Title: Why bash alias doesn't work in scripts?

Body:
I'm using a Mac and I have this alias defined in .bashrc:

$cat .bashrc | grep la
alias la='ls -la'

then I try to use it in a script:

$cat ./mytest.sh
#!/bin/bash
la

It runs and says it cannot find la:

./mytest.sh: line 2: la: command not found

Why is this? I tried on both Mac and Linux, same error!

Body:
Your .bashrc is only used by interactive shells. https://www.gnu.org/software/bash/manual/bashref.html#Bash-Startup-Files says:

Invoked non-interactively

When Bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed:

if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi

but the value of the PATH variable is not used to search for the filename.

As noted above, if a non-interactive shell is invoked with the --login option, Bash attempts to read and execute commands from the login shell startup files.

As you can see, there's nothing about .bashrc there. Your alias simply doesn't exist in the script.

But even if .bashrc were read, there's another problem:

Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt.

So if you wanted aliases to work in a script, you'd have to do shopt -s expand_aliases first. Or just use a shell function instead of an alias:

la() {
    ls -la
}


问:
Non Reproducible results even after setting the seed value (Python API of Microsoft CNTK)
Previously, I mentioned that there aren't any options available to define a seed value in Branscripts for CNTK sequential machine learning models[1]. Hence I migrated my code to Python API (CNTK), which gives more fine-grained options when defining the seed values of sequential machine learning models. Below are the instances that I have used random initialization in my implementation (and set the corresponding seed value as well)

// CNTK imports

```<code>import numpy as np
import pandas as pd
import random
import math as m

from cntk.device import *
from cntk import Trainer
from cntk.layers import *

import cntk
import cntk.ops as o
import cntk.layers as l
</code>```

//defining the random seed

```<code>np.random.seed(8888)
random.seed(8888)
</code>```

// Defining input and output training vectors

```<code>input_array_df = np.asarray(input_split_df[1:len(input_split_df)], dtype=np.float32)
output_array_df = np.asarray(output_df_df[1:len(output_df_df)], dtype=np.float32)
tup=(input_array_df, output_array_df)
listOfTuplesOfInputsLabels.append(tup)
</code>```

//shuffling the input vector

```<code> random.shuffle(listOfTuplesOfInputsLabels)
</code>```

//Defining sequential model

```<code>num_minibatches = len(features) // minibatch_size
    epoch_size = len(features)*1

    feature = o.input_variable((input_dim),np.float32)
    label = o.input_variable((output_dim),np.float32)

    netout=Sequential([For(range(1), lambda i: Recurrence(LSTM(lstm_cell_dimension,use_peepholes=LSTM_USE_PEEPHOLES,init=glorot_uniform(seed=8888)))),Dense(output_dim,bias=BIAS,init=glorot_uniform(seed=8888))])(feature)

    learner = momentum_sgd(netout.parameters, lr = learning_rate_schedule([(4,0.003),(16,0.002)], unit=UnitType.sample,epoch_size=epoch_size),
                               momentum=momentum_as_time_constant_schedule(minibatch_size / -m.log(0.9)), gaussian_noise_injection_std_dev = gaussian_noise,l2_regularization_weight =l2_regularization_weight)
</code>```

//Splitting into mini batches

```<code>tf = np.array_split(features,num_minibatches)
tl = np.array_split(labels,num_minibatches)
</code>```

//Train

```<code>features = np.ascontiguousarray(tf[i%num_minibatches])
labels = np.ascontiguousarray(tl[i%num_minibatches])
trainer.train_minibatch({feature : features, label : labels})
</code>```

Unfortunately, even though I was able to successfully define the seed value in my code, I could still observe some smaller variations in my final result. Is this because of the floating point calculations? or could you find anything in my code that I should have set the seed value, which I haven't done it already?

Thanks !

[1] Defining a seed value in Branscripts for CNTK sequential machine learning models

答:
Can you try the below:</p>

```<code>from _cntk_py import set_fixed_random_seed, force_deterministic_algorithms
set_fixed_random_seed(1)
force_deterministic_algorithms()
</code>```

Body:
Previously, I mentioned that there aren't any options available to define a seed value in Branscripts for CNTK sequential machine learning models[1]. Hence I migrated my code to Python API (CNTK), which gives more fine-grained options when defining the seed values of sequential machine learning models. Below are the instances that I have used random initialization in my implementation (and set the corresponding seed value as well)

// CNTK imports

import numpy as np
import pandas as pd
import random
import math as m

from cntk.device import *
from cntk import Trainer
from cntk.layers import *

import cntk
import cntk.ops as o
import cntk.layers as l

//defining the random seed

np.random.seed(8888)
random.seed(8888)

// Defining input and output training vectors

input_array_df = np.asarray(input_split_df[1:len(input_split_df)], dtype=np.float32)
output_array_df = np.asarray(output_df_df[1:len(output_df_df)], dtype=np.float32)
tup=(input_array_df, output_array_df)
listOfTuplesOfInputsLabels.append(tup)

//shuffling the input vector

 random.shuffle(listOfTuplesOfInputsLabels)

//Defining sequential model

num_minibatches = len(features) // minibatch_size
    epoch_size = len(features)*1

    feature = o.input_variable((input_dim),np.float32)
    label = o.input_variable((output_dim),np.float32)

    netout=Sequential([For(range(1), lambda i: Recurrence(LSTM(lstm_cell_dimension,use_peepholes=LSTM_USE_PEEPHOLES,init=glorot_uniform(seed=8888)))),Dense(output_dim,bias=BIAS,init=glorot_uniform(seed=8888))])(feature)

    learner = momentum_sgd(netout.parameters, lr = learning_rate_schedule([(4,0.003),(16,0.002)], unit=UnitType.sample,epoch_size=epoch_size),
                               momentum=momentum_as_time_constant_schedule(minibatch_size / -m.log(0.9)), gaussian_noise_injection_std_dev = gaussian_noise,l2_regularization_weight =l2_regularization_weight)

//Splitting into mini batches

tf = np.array_split(features,num_minibatches)
tl = np.array_split(labels,num_minibatches)

//Train

features = np.ascontiguousarray(tf[i%num_minibatches])
labels = np.ascontiguousarray(tl[i%num_minibatches])
trainer.train_minibatch({feature : features, label : labels})

Unfortunately, even though I was able to successfully define the seed value in my code, I could still observe some smaller variations in my final result. Is this because of the floating point calculations? or could you find anything in my code that I should have set the seed value, which I haven't done it already?

Thanks !

[1] Defining a seed value in Branscripts for CNTK sequential machine learning models

Body:
Can you try the below:

from _cntk_py import set_fixed_random_seed, force_deterministic_algorithms
set_fixed_random_seed(1)
force_deterministic_algorithms()


问:
Show all tweets that are on a user's Twitter account page
I have used user timeline to display all the tweets made by a specific user, but what I am trying to achieve is to display all the tweets on my website that the user has made or received.

Is there any way to accomplish it.

答:
So you want to get all tweets made by a user and all tweets that mention a user (aka are sent to a user)?

For the first see,

http://dev.twitter.com/doc/get/statuses/public_timeline

For the second see,

http://dev.twitter.com/doc/get/statuses/mentions

You will need to use OAuth authentication to access the latter API call.


问:
VueJs render template issue
I've an issue to fill data from model into code when I'v more then one template with separate data. What I need is first template renders as many times as many objects in firstFormDetails array and same the second one. There example of my code below:

```<code> <div id="app">
  <first v-for="item in secondFormDetails" track-by="id"></first>
  <second v-for="item in firstFormDetails" track-by="id"></second>
 </div>

 <template id="template-first">
  <div> {{ item.docNumber }}</div>
 </template>

 <template id="template-second">
  <div> {{ item.docNumber }}</div>
 </template>
</code>```

And VueJs module as follows:

```<code>  Vue.component('first', {
     template: '#template-first',
     data: function() {
       return {
         firstFormDetails: [
           {docNumber: 7},
           {docNumber: 7777},
           {docNumber: 10000}
         ]
       }
     }
   });

   Vue.component('second', {
      template: '#template-second',
      data: function() {
        return {
          secondFormDetails: [
            {docNumber: 1908},
            {docNumber: 7777},
            {docNumber: 10000}
          ]
        }
      }
    });

   new Vue({
     el: '#app'
   });
</code>```

答:
When Vue app is loaded, it looks for component field, if component field is not defined then not component is loaded, if component field is defined, Vue looks for the definition of the component and parse it for syntax checking, once the syntax is correct the component is binded. This happens recursively for nested components.

Registering a component is mandatory

Title: VueJs render template issue

Body:
I've an issue to fill data from model into code when I'v more then one template with separate data. What I need is first template renders as many times as many objects in firstFormDetails array and same the second one. There example of my code below:

  <first v-for="item in secondFormDetails" track-by="id"></first>
  <second v-for="item in firstFormDetails" track-by="id"></second>

 <template id="template-first">

 {{ item.docNumber }}

 </template>

 <template id="template-second">

 {{ item.docNumber }}

 </template>

And VueJs module as follows:

  Vue.component('first', {
     template: '#template-first',
     data: function() {
       return {
         firstFormDetails: [
           {docNumber: 7},
           {docNumber: 7777},
           {docNumber: 10000}
         ]
       }
     }
   });

   Vue.component('second', {
      template: '#template-second',
      data: function() {
        return {
          secondFormDetails: [
            {docNumber: 1908},
            {docNumber: 7777},
            {docNumber: 10000}
          ]
        }
      }
    });

   new Vue({
     el: '#app'
   });


问:
Remove particular node in border pane in javafx when stage load
I have a border pane and there are components in its top, left and right side. I want to remove the components of its right side by using the id of the borderPane when the Stage is a load. how do I do that?</p>

答:
you should write your code in the initialize method, it will be implemented as soon as the Stage is loaded

first:

```<code>public class your_class implements Initializable{
//your code
}
</code>```

then you will need to  generate the implemented method

Right-click -> Generate -> implemented methods

it would be like

```<code> @Override
    public void initialize(URL location, ResourceBundle resources) {

    }
</code>```

Body:
you should write your code in the initialize method, it will be implemented as soon as the Stage is loaded

first:

public class your_class implements Initializable{
//your code
}

then you will need to  generate the implemented method

Right-click -> Generate -> implemented methods

it would be like

 @Override
    public void initialize(URL location, ResourceBundle resources) {

    }


问:
transfer 10 GB data files from cloud server to Sharepoint using putty connection
I have to transfer 10 GB data to the sharepoint. but before moving to sharepoint I have to connect to the cloud server where I have saved those 10 gb data files...

So my transfer will be using PUTTY , from cloud server to sharepoint.

Is it possible to connect to the cloud server and sharepoint at the same point using PUTTY

答:
As Peter indicated you cannot directly transfer the data from the cloud server into SharePoint. You will have to "download" the data using putty and then upload the content using http(s), WebDAV or an API.
10 GB is not a lot of data. You may encounter problems with:
 - long URLs (exceeding 260 characters)
 - illegal characters (e.g. #)
 - blocked files (e.g. dll files are blocked on on-premise)
 - maximum file sizes

NB: The uploaded documents will end up with a new modification date.
The easiest way to transfer the files from your local machine into SharePoint is to use explorer view (and break the 10 GB set into smaller chunks). Alternatively use a 3rd party tool (see e.g. https://collab365.directory/office365-sharepoint/best-sharepoint-migration-tools/ or use a SharePoint Add-in) to upload the content. Please note that some tools offer trial versions but they do not upload 100 % of the content.

Paul | SLIM Applications


问:
Need suggestion for framework
I just went through https://stackoverflow.com/questions/2648/what-php-framework-would-you-choose-for-a-new-application-and-why discussion and read about frameworks.

Till now I've been coding from scratch everytime I developer a new application, Now I want to start with a framework for new project. Things I am looking for in the framework

User Signup Process OAuth module for

List item Twitter (fetching tweets) (important)

OAuth module for Facebook (fetching wall-posts) (important)

MVC Architecture

Paypal module for payments

I dont know if such framework exists, and I am new to frameworks, so I am looking for suggestion for which framework to start with and what all modules/plugins to pick

Language: PHP

Backend: MySQL

Frontend: HTML5/CSS

Platform: OSX

答:
You can just a framework for a solid base and the create those things as models.
I think most frameworks offer something for authentication don't know about the rest, but as I said, use a framework for base and then build what you want.</p>

Title: Need suggestion for framework


问:
Extract the names of the files in folders
I'm working on a project and I'm also wondering how to extract the names of files in folders

e.g. I'm in "CatA" catalog with 2 subfolders:

"CatAA" with catalog "ExpAA" - aaa.zip inside

"CatBB" with catalog "ExpBB" - bbb.zip inside

My goal is to list (get the file names) aaa.zip and bbb.zip file while being in a main "CatA" file.

```<code>string[] dirs = Directory.GetDirectories(@"C:\CatA");

        //checkedListBox1.Items.Insert(0, dirs.Length);

        for (int i = 0; i < dirs.Length - 1; i++)
        {
          //c# go a folder up
          dirs.
          var zipFiles = Directory.GetFiles(@"C:\Users\DLXP3B3\Desktop\tes", "*.zip");
          checkedListBox1.Items.Insert(i, zipFiles[i]);
        }
</code>```

I have some work done, but I don't know how to proceed. Any ideas would be appreciated. Thank you.

答:
If you need the complete path of all files in the parent folder use :-

```<code>var allFilesWithPath = Directory.GetFiles(@"C:\CatA", "*.*", SearchOption.AllDirectories);
</code>```

If you only need the filename and not the complete path, use the below code :-

```<code>    var allFiles = Directory.GetFiles(@"C:\CatA", "*.*", SearchOption.AllDirectories)
        .Select(f => Path.GetFileName(f)).ToArray();
</code>```

Body:
I'm working on a project and I'm also wondering how to extract the names of files in folders

e.g. I'm in "CatA" catalog with 2 subfolders:

"CatAA" with catalog "ExpAA" - aaa.zip inside

"CatBB" with catalog "ExpBB" - bbb.zip inside

My goal is to list (get the file names) aaa.zip and bbb.zip file while being in a main "CatA" file.

string[] dirs = Directory.GetDirectories(@"C:\CatA");

        //checkedListBox1.Items.Insert(0, dirs.Length);

        for (int i = 0; i < dirs.Length - 1; i++)
        {
          //c# go a folder up
          dirs.
          var zipFiles = Directory.GetFiles(@"C:\Users\DLXP3B3\Desktop\tes", "*.zip");
          checkedListBox1.Items.Insert(i, zipFiles[i]);
        }

I have some work done, but I don't know how to proceed. Any ideas would be appreciated. Thank you.

Body:
If you need the complete path of all files in the parent folder use :-

var allFilesWithPath = Directory.GetFiles(@"C:\CatA", "*.*", SearchOption.AllDirectories);

If you only need the filename and not the complete path, use the below code :-

    var allFiles = Directory.GetFiles(@"C:\CatA", "*.*", SearchOption.AllDirectories)
        .Select(f => Path.GetFileName(f)).ToArray();


问:
Getting the 3 consecutive year in Query
I have problem getting the year

I have here in my database year of 11/11/2016 - 11/13/2015 - 11/13/2014
the problem is I want to get that year just deducting current year
so if the current year is 2017 I want to get 2016,2015,2014 , and the next year
2018 the year will get is 2017,2016,2015

```<code>$selectmemberpaid = mysql_query("SELECT

memberid,StartDate,EndDate,tblpayments.activityname,amount_paid FROM

tblattend_activity LEFT JOIN tblpayments ON tblattend_activity.memberid =

.profile_id WHERE memberid='201400001'");
</code>```

That is my query..

and this is my while loop

```<code>while ($rows = mysql_fetch_assoc($selectmemberpaid)) {

    # code...
    $dateTimestamp = strtotime($rows['StartDate']);

    $year = date("Y", $dateTimestamp);

  }
</code>```

答:
You can get the year from a date string by doing something like this:

```<code>$dateTimestamp = strtotime('2015-12-12');
$year = date("Y", $dateTimestamp);
echo $year;
</code>```

Once you get it you can add or subtract to get the previous/next year (after converting the value into an integer).

Title: Getting the 3 consecutive year in Query

Body:
I have problem getting the year

I have here in my database year of 11/11/2016 - 11/13/2015 - 11/13/2014
the problem is I want to get that year just deducting current year
so if the current year is 2017 I want to get 2016,2015,2014 , and the next year
2018 the year will get is 2017,2016,2015

$selectmemberpaid = mysql_query("SELECT

memberid,StartDate,EndDate,tblpayments.activityname,amount_paid FROM

tblattend_activity LEFT JOIN tblpayments ON tblattend_activity.memberid =

.profile_id WHERE memberid='201400001'");

That is my query..

and this is my while loop

while ($rows = mysql_fetch_assoc($selectmemberpaid)) {

    # code...
    $dateTimestamp = strtotime($rows['StartDate']);

    $year = date("Y", $dateTimestamp);

  }

Body:
You can get the year from a date string by doing something like this:

$dateTimestamp = strtotime('2015-12-12');
$year = date("Y", $dateTimestamp);
echo $year;

Once you get it you can add or subtract to get the previous/next year (after converting the value into an integer).


问:
rect move dosen't work
```<code>import pygame, random
pygame.init()
screen = pygame.display.set_mode((700,500))
ball = pygame.image.load('C://python32/ball.jpg')
brick = pygame.image.load('C://python32/brick.jpg')
rect1 = ball.get_rect()
rect2 = brick.get_rect()
screen.fill((255,255,198))
screen.blit(ball,rect1)
screen.blit(brick,rect2)
pygame.display.flip()
if rect1.colliderect(rect2):
    x=random.randrange(0,550)
    y=random.randrange(0,350)
    rect2.move(x,y)            #<-------This part
    pygame.display.flip()
</code>```

I have 2 images ball and brick. When I load them on pygame the 2 images collide. So the if rect1.colliderect(rect2) should work. I tested that by putting is a print function. But the rect2.move dosen't work it doesn't show the change on the pygame. What is wrong?

答:
pygame.Rect.move creates a new rect object with the new position which you have to assign to a variable if you want to use it later.

If you just want to modify the existing rect, you can call the move_ip method (ip stands for in-place), so that the rect is still the same object with a new position.

Title: rect move dosen't work

Body:
import pygame, random
pygame.init()
screen = pygame.display.set_mode((700,500))
ball = pygame.image.load('C://python32/ball.jpg')
brick = pygame.image.load('C://python32/brick.jpg')
rect1 = ball.get_rect()
rect2 = brick.get_rect()
screen.fill((255,255,198))
screen.blit(ball,rect1)
screen.blit(brick,rect2)
pygame.display.flip()
if rect1.colliderect(rect2):
    x=random.randrange(0,550)
    y=random.randrange(0,350)
    rect2.move(x,y)            #<-------This part
    pygame.display.flip()

I have 2 images ball and brick. When I load them on pygame the 2 images collide. So the if rect1.colliderect(rect2) should work. I tested that by putting is a print function. But the rect2.move dosen't work it doesn't show the change on the pygame. What is wrong?


问:
build file name for image used as resource C#
trying to build the file name for image i have in resource folder and it show it ass error.
i create the file name into string parameter,
already create btn as button' look for "fileName" parameter.
the error is: Error 1   'warCards.Properties.Resources' does not contain a definition for 'fileName'.
the game is: War (card game)
thanks for helpers

```<code>  btn.Click += delegate(object sender, EventArgs e)
            {
                Random rnd = new Random();
                int num = rnd.Next(1, 14);
                int letter = 0;// represent random cards symbol 1-dimond 2-heart  3-spades 4-clubs
                string fileName = "_";
                if (num < 10 && num > 1)
                {
                    fileName = fileName + "0" + num.ToString() + "_of_";
                    if (isBlack)
                    {
                        letter = rnd.Next(1, 3);
                        if (letter == 1)
                        {
                            fileName += "spades";
                        }
                        else
                        {
                            fileName += "clubs";
                        }
                        //for example: try to create: _5_of_spades
                        btn.BackgroundImage = warCards.Properties.Resources.fileName;
                        btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
                        btn.Enabled = false;
                        isBlack = !isBlack;

                    }
                }
               };
                this.Controls.Add(btn);
                nextPos.X += 112;

            };
</code>```

答: I did it using the GetObject(string) method.

Body:
trying to build the file name for image i have in resource folder and it show it ass error.
i create the file name into string parameter,
already create btn as button' look for "fileName" parameter.
the error is: Error 1   'warCards.Properties.Resources' does not contain a definition for 'fileName'.
the game is: War (card game)
thanks for helpers

  btn.Click += delegate(object sender, EventArgs e)
            {
                Random rnd = new Random();
                int num = rnd.Next(1, 14);
                int letter = 0;// represent random cards symbol 1-dimond 2-heart  3-spades 4-clubs
                string fileName = "_";
                if (num < 10 && num > 1)
                {
                    fileName = fileName + "0" + num.ToString() + "_of_";
                    if (isBlack)
                    {
                        letter = rnd.Next(1, 3);
                        if (letter == 1)
                        {
                            fileName += "spades";
                        }
                        else
                        {
                            fileName += "clubs";
                        }
                        //for example: try to create: _5_of_spades
                        btn.BackgroundImage = warCards.Properties.Resources.fileName;
                        btn.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
                        btn.Enabled = false;
                        isBlack = !isBlack;

                    }
                }
               };
                this.Controls.Add(btn);
                nextPos.X += 112;

            };


问:
Disable all AJAX / Websocket data requests on a site?
I have the following webpage that loads a bunch of ajax or websocket requests when the page is done loading. This is due to the constant updating of the on page chatroom and constant updating of the prices in the charts.

https://poloniex.com/exchange#btc_ardr

Is there a way to disable the browser from fetching the chatbox data and price updates of the chart? Every time I load the page, it either freezes or lags. I just want to be able to keep the forms intact on the page as I would like to submit them without all the noise.

What is something I can run in the console that can just stop all the activity on the page without messing up the form submissions?

答:
All AJAX requests use XMLHttpRequest internally, except in IE.
You can override the native XMLHttpRequest like this:

```<code>XMLHttpRequest = function(){}
XMLHttpRequest.prototype = {
    open: function(){},
    send: function(){}
}
</code>```

For IE, you can disable XMLHTTP under Security settings.
For disabling WebSocket I used the --disable-web-sockets flag while starting Chrome.

Body:
All AJAX requests use XMLHttpRequest internally, except in IE.
You can override the native XMLHttpRequest like this:

XMLHttpRequest = function(){}
XMLHttpRequest.prototype = {
    open: function(){},
    send: function(){}
}

For IE, you can disable XMLHTTP under Security settings.
For disabling WebSocket I used the --disable-web-sockets flag while starting Chrome.


问:
Get two table values using JOIN query where In Condition
I am trying following query .

```<code>select a.name b.id ,b.proname , b.date
from tablea as a tableb as b
where b.id IN(1,2,3,5)
group by b.id ;
</code>```

a.name repeat one value all rows

```<code>a.name b.id b.proname b.date
user   1   user1    12-05-2017
user   2   user2    15-05-2017
user   3   user3    16-05-2017
user   5   user5    17-05-2017
</code>```

primary key is id

答:
You need to describe relation between tablea and tableb, something like this:

```<code>where b.id IN(1,2,3,5) AND a.id = b.id
</code>```

Here a.id and b.id must be in some relation, for example foreign key.

And you using 'GROUP BY' wrong, I think it's not necessary here at all.

Body:
I am trying following query .

select a.name b.id ,b.proname , b.date
from tablea as a tableb as b
where b.id IN(1,2,3,5)
group by b.id ;

a.name repeat one value all rows

a.name b.id b.proname b.date
user   1   user1    12-05-2017
user   2   user2    15-05-2017
user   3   user3    16-05-2017
user   5   user5    17-05-2017

primary key is id

Body:
You need to describe relation between tablea and tableb, something like this:

where b.id IN(1,2,3,5) AND a.id = b.id

Here a.id and b.id must be in some relation, for example foreign key.

And you using 'GROUP BY' wrong, I think it's not necessary here at all.


问:
what interval does this cron run?
What interval does this CRON run?</p>

```<code>*/5 0 * * * /command
</code>```

答:
The following will run the script /home/user/test.pl every 5 minutes starting at 0 minutes past the hour then 5 minutes past and so on.

```<code>*/5 * * * *  /home/user/test.pl

#  .---------------- minute (0 - 59)
#  |   .------------- hour (0 - 23)
#  |   |   .---------- day of month (1 - 31)
#  |   |   |   .------- month (1 - 12) OR jan,feb,mar,apr ...
#  |   |   |   |  .----- day of week (0 - 6) (Sunday=0 or 7)
#  |   |   |   |  |
#  *   *   *   *  *  command to be executed
</code>```

From: http://en.wikipedia.org/wiki/Cron

Title: what interval does this cron run?

Body:
What interval does this CRON run?

*/5 0 * * * /command

Body:
The following will run the script /home/user/test.pl every 5 minutes starting at 0 minutes past the hour then 5 minutes past and so on.

*/5 * * * *  /home/user/test.pl

#  .---------------- minute (0 - 59)
#  |   .------------- hour (0 - 23)
#  |   |   .---------- day of month (1 - 31)
#  |   |   |   .------- month (1 - 12) OR jan,feb,mar,apr ...
#  |   |   |   |  .----- day of week (0 - 6) (Sunday=0 or 7)
#  |   |   |   |  |
#  *   *   *   *  *  command to be executed

From: http://en.wikipedia.org/wiki/Cron


问:
Uncaught (in promise) TypeError: Cannot read property 'handleClick' of undefined in forEach loop
I have the following code

articles_list.jsx

```<code>import React from 'react';
import './articles_list.css';

export default class ArticlesList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      articles: null
    }
  }

  componentWillMount() {
    fetch('/articles_all')
    .then(res => res.json())
    .then(json => {
      this.setState({
        articles: json.articles
      });
    });
  }

  handleClick(e) {
    e.preventDefault();
    // Do something else
  }

  render() {

    var teste = []

    if (this.state.articles === null) {
      teste.push(<div key="1">No articles</div>)
    } else {
      {this.state.articles.forEach( function(element, index) {
        console.log(element);
        teste.push(<div onClick={this.handleClick} className="articles-menu-item" key={index.toString()}>{element.title}</div>);
      })}
    }

    return(
      <div className="articles-list">
        <div className="articles-list-title">
          ARTICLES
        </div>
        <div className="menu-body">{teste}</div>
      </div>
    );
  }
}
</code>```

and it is working fine when I remove the onClick={this.handleClick}, but with the event handler there I receive the following error:

Uncaught (in promise) TypeError: Cannot read property 'handleClick' of undefined

And nothing is rendered.

For all the examples I've seen, there is nothing wrong with the definition of the event handler. I also tried to define the handler as a arrow function, like:

```<code>handleClick = (e) => {
  e.preventDefault();
  // Do something else
}
</code>```

to see if this could change something, but it was all the same.

Where and how should I define the event handler?

答:
You forgot to bind the forEach function and hence the error since, this inside forEach function will refer to its own context where handleClick is not defined rather than the React Component, Either use .bind(this) like

```<code> {this.state.articles.forEach( function(element, index) {
    console.log(element);
    teste.push(<div onClick={this.handleClick} className="articles-menu-item" key={index.toString()}>{element.title}</div>);
  }.bind(this))}
</code>```

or Arrow function

```<code> {this.state.articles.forEach( (element, index) => {
    console.log(element);
    teste.push(<div onClick={this.handleClick} className="articles-menu-item" key={index.toString()}>{element.title}</div>);
  })}
</code>```

Body:
I have the following code

articles_list.jsx

import React from 'react';
import './articles_list.css';

export default class ArticlesList extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      articles: null
    }
  }

  componentWillMount() {
    fetch('/articles_all')
    .then(res => res.json())
    .then(json => {
      this.setState({
        articles: json.articles
      });
    });
  }

  handleClick(e) {
    e.preventDefault();
    // Do something else
  }

  render() {

    var teste = []

    if (this.state.articles === null) {
      teste.push(
No articles
)
    } else {
      {this.state.articles.forEach( function(element, index) {
        console.log(element);
        teste.push(
{element.title}
);
      })}
    }

    return(

          ARTICLES

{teste}

    );
  }
}

and it is working fine when I remove the onClick={this.handleClick}, but with the event handler there I receive the following error:

Uncaught (in promise) TypeError: Cannot read property 'handleClick' of undefined

And nothing is rendered.

For all the examples I've seen, there is nothing wrong with the definition of the event handler. I also tried to define the handler as a arrow function, like:

handleClick = (e) => {
  e.preventDefault();
  // Do something else
}

to see if this could change something, but it was all the same.

Where and how should I define the event handler?

Body:
You forgot to bind the forEach function and hence the error since, this inside forEach function will refer to its own context where handleClick is not defined rather than the React Component, Either use .bind(this) like

 {this.state.articles.forEach( function(element, index) {
    console.log(element);
    teste.push(<div onClick={this.handleClick} className="articles-menu-item" key={index.toString()}>{element.title}</div>);
  }.bind(this))}

or Arrow function

 {this.state.articles.forEach( (element, index) => {
    console.log(element);
    teste.push(<div onClick={this.handleClick} className="articles-menu-item" key={index.toString()}>{element.title}</div>);
  })}