问:
log messages appearing twice with Python Logging
I'm using Python logging, and for some reason, all of my messages are appearing twice.

I have a module to configure logging:

```<code># BUG: It's outputting logging messages twice - not sure why - it's not the propagate setting.
def configure_logging(self, logging_file):
    self.logger = logging.getLogger("my_logger")
    self.logger.setLevel(logging.DEBUG)
    self.logger.propagate = 0
    # Format for our loglines
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    # Setup console logging
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    self.logger.addHandler(ch)
    # Setup file logging as well
    fh = logging.FileHandler(LOG_FILENAME)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    self.logger.addHandler(fh)
</code>```

Later on, I call this method to configure logging:

```<code>if __name__ == '__main__':
    tom = Boy()
    tom.configure_logging(LOG_FILENAME)
    tom.buy_ham()
</code>```

And then within say, the buy_ham module, I'd call:

```<code>self.logger.info('Successfully able to write to %s' % path)
</code>```

And for some reason, all the messages are appearing twice. I commented out one of the stream handlers, still the same thing. Bit of a weird one, not sure why this is happening. I'm assuming I've missed something obvious.

答:
If you are seeing this problem and you're not adding the handler twice then see abarnert's answer here

From the docs:

Note: If you attach a handler to a logger and one or more of its
ancestors, it may emit the same record multiple times. In general, you
should not need to attach a handler to more than one logger - if you
just attach it to the appropriate logger which is highest in the
logger hierarchy, then it will see all events logged by all descendant
loggers, provided that their propagate setting is left set to True. A
common scenario is to attach handlers only to the root logger, and to
let propagation take care of the rest.

So, if you want a custom handler on "test", and you don't want its messages also going to the root handler, the answer is simple: turn off its propagate flag:

logger.propagate = False
```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Python logging, and for some reason, all of my messages are appearing twice.

I have a module to configure logging:

# BUG: It's outputting logging messages twice - not sure why - it's not the propagate setting.
def configure_logging(self, logging_file):
    self.logger = logging.getLogger("my_logger")
    self.logger.setLevel(logging.DEBUG)
    self.logger.propagate = 0
    # Format for our loglines
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    # Setup console logging
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    self.logger.addHandler(ch)
    # Setup file logging as well
    fh = logging.FileHandler(LOG_FILENAME)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    self.logger.addHandler(fh)

Later on, I call this method to configure logging:

if __name__ == '__main__':
    tom = Boy()
    tom.configure_logging(LOG_FILENAME)
    tom.buy_ham()

And then within say, the buy_ham module, I'd call:

self.logger.info('Successfully able to write to %s' % path)

And for some reason, all the messages are appearing twice. I commented out one of the stream handlers, still the same thing. Bit of a weird one, not sure why this is happening. I'm assuming I've missed something obvious.


来源: stackexchange

问:
Android: Scenario where onPause is called but not onStop?
I'm trying to understand the difference between onPause and onStop.

I've read all the different forums but I still am not clear about the difference. I've created a simple app to try and test when which method gets called. For that I've simply placed loggers in each method.

From my trials -

Popups do not call either method

Switching to another activity calls both methods

Pulling down the notification bar calls neither method

I've only seen either both methods being called in quick succession or neither getting called at all.
I'm trying to find scenarios where onPause gets called but onStop doesn't.

The purpose is to understand whether defining onPause is even required. If the scenarios in which only onPause gets called are so rare, it doesn't even make sense to write separate code for onPause. Shouldn't writing onStop be sufficient?

```<code>public class LifecycleActivity extends ActionBarActivity {

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Rachit", "In Destroy Method");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lifecycle);
        Log.d("Rachit", "In Create Method");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Rachit", "In Start Method");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Rachit", "In Resume Method");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Rachit", "In Pause Method");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Rachit", "In Restart Method");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Rachit", "In Stop Method");
    }
}
</code>```

答:
Activity A --> Activity B
If B is transparent, A' onPause will be called but no onStop.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to understand the difference between onPause and onStop.

I've read all the different forums but I still am not clear about the difference. I've created a simple app to try and test when which method gets called. For that I've simply placed loggers in each method.

From my trials -

Popups do not call either method

Switching to another activity calls both methods

Pulling down the notification bar calls neither method

I've only seen either both methods being called in quick succession or neither getting called at all.
I'm trying to find scenarios where onPause gets called but onStop doesn't.

The purpose is to understand whether defining onPause is even required. If the scenarios in which only onPause gets called are so rare, it doesn't even make sense to write separate code for onPause. Shouldn't writing onStop be sufficient?

public class LifecycleActivity extends ActionBarActivity {

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Rachit", "In Destroy Method");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lifecycle);
        Log.d("Rachit", "In Create Method");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Rachit", "In Start Method");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Rachit", "In Resume Method");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Rachit", "In Pause Method");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Rachit", "In Restart Method");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Rachit", "In Stop Method");
    }
}


问:
Getting "Client was not authenticated to send anonymous mail during MAIL FROM" error from Exchange SMTP using Rust lettre library
I am writing a Rust application that will send email through an Exchange server with SMTP functionality enabled. According to Microsoft's webpage, the settings that are required are:

Server address smtp.office365.com

Port 587

StartTLS Enabled

Credentials for mail account login

These are corroborated by the POP/IMAP settings of the webmail service.

Here is my code (with some censoring):

```<code>extern crate lettre;

use self::lettre::email::EmailBuilder;
use self::lettre::transport::smtp::{SecurityLevel, SmtpTransportBuilder, SUBMISSION_PORT};
use self::lettre::transport::smtp::authentication::Mechanism;
use self::lettre::transport::EmailTransport;

pub fn send_mail() {
    let email = EmailBuilder::new()
        .from("my email")
        .to("destination email")
        .body("testing")
        .subject("testing")
        .build()
        .unwrap();

    // Connect to SMTP server
    let mut transport = SmtpTransportBuilder::new(("smtp.office365.com", SUBMISSION_PORT))
        .expect("Failed to create email transport")
        .encrypt()
        .smtp_utf8(true)
        .credentials("my email", "my password")
        .authentication_mechanism(Mechanism::Login)
        .build();
    println!("Mail transport built");

    println!("{:?}", transport.send(email.clone()));
}
</code>```

When I compile and run the code,it gives me this error:

Err(Permanent(Response { code: Code { severity:
  PermanentNegativeCompletion, category: Unspecified3, detail: 0 },
  message: ["5.7.57 SMTP; Client was not authenticated to send anonymous
  mail during MAIL FROM [SYXPR01CA0106.ausprd01.prod.outlook.com]"] }))

Why is this happening?

The closest I've come in my research is an issue on GitHub in relation to the lettre library not supporting the Login authentication mechanism (which Office 365 uses); however, the codebase was updated to support Login and I am using the master branch directly from GitHub so theoretically my application should support the Login mechanism.

Edit: Forgot to mention that I attempted an EHLO to the server, but it returned a (Client:(Connection closed)) error.

答:
I used telnet and openssl to try connecting directly to my SMTP server, where I found that AUTH LOGIN requires 3 commands; one to send the AUTH LOGIN code, one to send the username and another to send the password. I found that the lettre library implements all its AUTH commands as single commands, so this wasn't working with the server. I downloaded the source code for the library, changed the send function to do the three separate commands, recompiled my code and everything worked fine :)

My addition to the lettre code:

```<code>if (accepted_mechanisms[0] == Mechanism::Login) &&
            (accepted_mechanisms.capacity() == 1) {
            try_smtp!(self.client.command("AUTH LOGIN"), self);
            try_smtp!(self.client.command(base64::encode_config(
                                            &username.as_bytes(),
                                            base64::STANDARD).as_str()), self);
            try_smtp!(self.client.command(base64::encode_config(
                                                        &password.as_bytes(),
                                                        base64::STANDARD).as_str()), self);
</code>```

Body:
I am writing a Rust application that will send email through an Exchange server with SMTP functionality enabled. According to Microsoft's webpage, the settings that are required are:

Server address smtp.office365.com

Port 587

StartTLS Enabled

Credentials for mail account login

These are corroborated by the POP/IMAP settings of the webmail service.

Here is my code (with some censoring):

extern crate lettre;

use self::lettre::email::EmailBuilder;
use self::lettre::transport::smtp::{SecurityLevel, SmtpTransportBuilder, SUBMISSION_PORT};
use self::lettre::transport::smtp::authentication::Mechanism;
use self::lettre::transport::EmailTransport;

pub fn send_mail() {
    let email = EmailBuilder::new()
        .from("my email")
        .to("destination email")
        .body("testing")
        .subject("testing")
        .build()
        .unwrap();

    // Connect to SMTP server
    let mut transport = SmtpTransportBuilder::new(("smtp.office365.com", SUBMISSION_PORT))
        .expect("Failed to create email transport")
        .encrypt()
        .smtp_utf8(true)
        .credentials("my email", "my password")
        .authentication_mechanism(Mechanism::Login)
        .build();
    println!("Mail transport built");

    println!("{:?}", transport.send(email.clone()));
}

When I compile and run the code,it gives me this error:

Err(Permanent(Response { code: Code { severity:
  PermanentNegativeCompletion, category: Unspecified3, detail: 0 },
  message: ["5.7.57 SMTP; Client was not authenticated to send anonymous
  mail during MAIL FROM [SYXPR01CA0106.ausprd01.prod.outlook.com]"] }))

Why is this happening?

The closest I've come in my research is an issue on GitHub in relation to the lettre library not supporting the Login authentication mechanism (which Office 365 uses); however, the codebase was updated to support Login and I am using the master branch directly from GitHub so theoretically my application should support the Login mechanism.

Edit: Forgot to mention that I attempted an EHLO to the server, but it returned a (Client:(Connection closed)) error.

Body:
I used telnet and openssl to try connecting directly to my SMTP server, where I found that AUTH LOGIN requires 3 commands; one to send the AUTH LOGIN code, one to send the username and another to send the password. I found that the lettre library implements all its AUTH commands as single commands, so this wasn't working with the server. I downloaded the source code for the library, changed the send function to do the three separate commands, recompiled my code and everything worked fine :)

My addition to the lettre code:

if (accepted_mechanisms[0] == Mechanism::Login) &&
            (accepted_mechanisms.capacity() == 1) {
            try_smtp!(self.client.command("AUTH LOGIN"), self);
            try_smtp!(self.client.command(base64::encode_config(
                                            &username.as_bytes(),
                                            base64::STANDARD).as_str()), self);
            try_smtp!(self.client.command(base64::encode_config(
                                                        &password.as_bytes(),
                                                        base64::STANDARD).as_str()), self);


问:
Oauth2 Golang - Own database and users
I'm building a web application in Golang, and at the moment I'm struggling with the authentication/authorization mechanisms.

I want to deploy this app to different platforms (browsers, androids, etc). To achieve this I chosed to use oauth 2.0, namely this lib: https://github.com/golang/oauth2 .

The problem I'm facing is how to achieve this with my own database and users. The lib has a jwt package (https://github.com/golang/oauth2/tree/master/jwt) and also has a package clientcredentials (https://github.com/golang/oauth2/blob/master/clientcredentials/clientcredentials.go) that can be used for 2-legged Oauth 2.0, but I have no idea how to achieve this, and can't find any example showing it. Which package should I use? The token should be set when user sends a POST with its credentials at http://example.domain/login.

Can someone provide me some hints / show me a simple example?

答:
Have you explored solutions such as ory/hydra, which will handle everything OAuth2/OpenID related and let you handle user authentication?

Implementing your own OAuth2 provider is dangerous territory. It only takes one misread RFC and BOOM! Security vulnerability. It's typically better to entrust that responsibility to established security experts or lasting projects as opposed to home-grown remedies.

Of course, this isn't to say that everybody needs to jump onto the hype train and use this cool new software. In fact, I would urge the opposite: if you are a competent security analyst and feel comfortable writing an OAuth2/OpenID Connect implementation, go right ahead! But us normal people who don't want our hair to gray before we are thirty will use existing technologies to our advantage.

Title: Oauth2 Golang - Own database and users


问:
How do I access css/scss with react?
I have a react component where I am trying to change the background color of the css when clicking the div.

I know you can set the color in the component, but I am using this component many times, and don't to make multiple component files with just a different color, and even if I did, I am curious besides the fact.

How can I access (or even console.log to figure it out on my own) the css file and its properties through the component?  Thanks ahead of time.

答:
You can pass in the desired background color as a prop, and use internal state with an onClick handler.

Container.js

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

const Container = () => (
  <ClickableDiv backgroundColor="#FF0000">
    <p>This is my text.</p>
  </ClickableDiv>
);

export default Container;
</code>```

ClickableDiv.js

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

class ClickableDiv extends Component {
  constructor() {
    super();
    this.state = {};
    this.handleDivClick = this.handleDivClick.bind(this);
  }

  handleDivClick() {
    const { backgroundColor } = this.props;
    if (backgroundColor) this.setState({ backgroundColor });
  }

  render() {
    const { backgroundColor } = this.state;
    return (
      <div style={{ backgroundColor }} onClick={this.handleDivClick}>
        {this.props.children}
      </div>
    );
  }
}

export default ClickableDiv;
</code>```

Title: How do I access css/scss with react?

Body:
You can pass in the desired background color as a prop, and use internal state with an onClick handler.

Container.js

import React from 'react';
import ClickableDiv from './ClickableDiv';

const Container = () => (
  <ClickableDiv backgroundColor="#FF0000">
    <p>This is my text.</p>
  </ClickableDiv>
);

export default Container;

ClickableDiv.js

import React, { Component } from 'react';

class ClickableDiv extends Component {
  constructor() {
    super();
    this.state = {};
    this.handleDivClick = this.handleDivClick.bind(this);
  }

  handleDivClick() {
    const { backgroundColor } = this.props;
    if (backgroundColor) this.setState({ backgroundColor });
  }

  render() {
    const { backgroundColor } = this.state;
    return (
      <div style={{ backgroundColor }} onClick={this.handleDivClick}>
        {this.props.children}
      </div>
    );
  }
}

export default ClickableDiv;


问:
flash embed code closed
ok so i got a embed code which is hosted on another site
i enter the script to my page but now it makes my html validation fail

with errors like this one

```<code>sh_id=cfe4b9038d67c69a9016a223b1040583&watermark=0&clickTag=null" width="1000"…
</code>```

they all mainly apply to this part of it &watermark=0&clickTag=null"

and the validator says i need a /> but when i change it from > to /> dreamweaver says it invaid

```<code><param name="allowFullScreen" value="true"><param name="wmode" value="transparent"><param name="allowScriptAccess" value="always">
</code>```

i dont know this code is there away to change it and still work? i deleted it from the end but then the watermark appears again.

any help would be appreciated

答: I fixed it by changing my doctype and add &; instead of just &.

ContentLicense: CC BY-SA 2.5

Title: flash embed code closed

Body:
ok so i got a embed code which is hosted on another site
i enter the script to my page but now it makes my html validation fail

with errors like this one

sh_id=cfe4b9038d67c69a9016a223b1040583&watermark=0&clickTag=null" width="1000"…

they all mainly apply to this part of it &watermark=0&clickTag=null"

and the validator says i need a /> but when i change it from > to /> dreamweaver says it invaid

<param name="allowFullScreen" value="true"><param name="wmode" value="transparent"><param name="allowScriptAccess" value="always">

i dont know this code is there away to change it and still work? i deleted it from the end but then the watermark appears again.

any help would be appreciated


问:
Block cross-domain iframe console logging
I'm making a page that has multiple iFrames that show reports. The reports generate a ton of console output which contributes to the page taking up more memory.

I tried to do the workaround with

```<code>console.log = function() {}
</code>```

As well as a couple others I found, but none of them work. Majority of the errors are "Failed to load resource" and failed GET requests. I'm wondering if there's a way to maybe filter just those out.

Again the issue is that all the iFrames are cross domain and I have 0 access to the source.

答:
Try it like this </p>

```<code>    iframeWindow.console.log = function() { /* nop */ };
</code>```

<p>This works on Mozilla,Chrome </p>

Body:
I'm making a page that has multiple iFrames that show reports. The reports generate a ton of console output which contributes to the page taking up more memory.

I tried to do the workaround with

console.log = function() {}

As well as a couple others I found, but none of them work. Majority of the errors are "Failed to load resource" and failed GET requests. I'm wondering if there's a way to maybe filter just those out.

Again the issue is that all the iFrames are cross domain and I have 0 access to the source.

Body:
Try it like this

    iframeWindow.console.log = function() { /* nop */ };

This works on Mozilla,Chrome


问:
H2OServerError: HTTP 500 Server Error: Server error water.util.DistributedException:
I am having trouble loading in a data set to h2o. I keep getting the same H2o server error when I was able to run this same code without issue yesterday.

```<code>import h2o
h2o.init()

h2o.import_file('train_csv')
</code>```

The train_csv is in the same directory and the is saved in the lines above from a spark dataframe. I continue to get the same error:

```<code>H2OServerError                            Traceback (most recent call last)
<ipython-input-3-d9a5a8533622> in <module>()
----> 1 h2o.import_file('train_csv')

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in import_file(path,
destination_frame, parse, header, sep, col_names, col_types, na_strings,
pattern)
    405         return lazy_import(path, pattern)
    406     else:
--> 407         return H2OFrame()._import_parse(path, pattern,
destination_frame, header, sep, col_names, col_types, na_strings)
    408
    409

/home/.local/lib/python3.5/site-packages/h2o/frame.py in _import_parse(self,
path, pattern, destination_frame, header, separator, column_names,
column_types, na_strings)
    306             path = os.path.abspath(path)
    307         rawkey = h2o.lazy_import(path, pattern)
--> 308         self._parse(rawkey, destination_frame, header, separator,
column_names, column_types, na_strings)
    309         return self
    310

/home/.local/lib/python3.5/site-packages/h2o/frame.py in _parse(self,
rawkey, destination_frame, header, separator, column_names, column_types,
na_strings)
    319     def _parse(self, rawkey, destination_frame="", header=None,
separator=None, column_names=None, column_types=None,
    320                na_strings=None):
--> 321         setup = h2o.parse_setup(rawkey, destination_frame, header,
separator, column_names, column_types, na_strings)
    322         return self._parse_raw(setup)
    323

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in
parse_setup(raw_frames, destination_frame, header, separator, column_names,
column_types, na_strings)
    550         kwargs["separator"] = ord(separator)
    551
--> 552     j = api("POST /3/ParseSetup", data=kwargs)
    553     if "warnings" in j and j["warnings"]:
    554         for w in j["warnings"]:

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in api(endpoint, data,
json, filename, save_to)
     97     # type checks are performed in H2OConnection class
     98     _check_connection()
---> 99     return h2oconn.request(endpoint, data=data, json=json,
filename=filename, save_to=save_to)
    100
    101

/home/.local/lib/python3.5/site-packages/h2o/backend/connection.py in
request(self, endpoint, data, json, filename, save_to)
   400                                     auth=self._auth,
verify=self._verify_ssl_cert, proxies=self._proxies)
    401             self._log_end_transaction(start_time, resp)
--> 402             return self._process_response(resp, save_to)
    403
    404         except (requests.exceptions.ConnectionError,
requests.exceptions.HTTPError) as e:

/home/.local/lib/python3.5/site-packages/h2o/backend/connection.py in
_process_response(response, save_to)
    728         # Note that it is possible to receive valid H2OErrorV3
object in this case, however it merely means the server
    729         # did not provide the correct status code.
--> 730         raise H2OServerError("HTTP %d %s:\n%r" % (status_code,
response.reason, data))
    731
    732

H2OServerError: HTTP 500 Server Error:
Server error water.util.DistributedException:
  Error: DistributedException from /127.0.0.1:54321
  Request: None
</code>```

答: The h2o.import_file() function requires using the full path of the file.  Change your code to use the full path and hopefully that will solve the issue.

Body:
I am having trouble loading in a data set to h2o. I keep getting the same H2o server error when I was able to run this same code without issue yesterday.

import h2o
h2o.init()

h2o.import_file('train_csv')

The train_csv is in the same directory and the is saved in the lines above from a spark dataframe. I continue to get the same error:

H2OServerError                            Traceback (most recent call last)
<ipython-input-3-d9a5a8533622> in <module>()
----> 1 h2o.import_file('train_csv')

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in import_file(path,
destination_frame, parse, header, sep, col_names, col_types, na_strings,
pattern)
    405         return lazy_import(path, pattern)
    406     else:
--> 407         return H2OFrame()._import_parse(path, pattern,
destination_frame, header, sep, col_names, col_types, na_strings)
    408
    409

/home/.local/lib/python3.5/site-packages/h2o/frame.py in _import_parse(self,
path, pattern, destination_frame, header, separator, column_names,
column_types, na_strings)
    306             path = os.path.abspath(path)
    307         rawkey = h2o.lazy_import(path, pattern)
--> 308         self._parse(rawkey, destination_frame, header, separator,
column_names, column_types, na_strings)
    309         return self
    310

/home/.local/lib/python3.5/site-packages/h2o/frame.py in _parse(self,
rawkey, destination_frame, header, separator, column_names, column_types,
na_strings)
    319     def _parse(self, rawkey, destination_frame="", header=None,
separator=None, column_names=None, column_types=None,
    320                na_strings=None):
--> 321         setup = h2o.parse_setup(rawkey, destination_frame, header,
separator, column_names, column_types, na_strings)
    322         return self._parse_raw(setup)
    323

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in
parse_setup(raw_frames, destination_frame, header, separator, column_names,
column_types, na_strings)
    550         kwargs["separator"] = ord(separator)
    551
--> 552     j = api("POST /3/ParseSetup", data=kwargs)
    553     if "warnings" in j and j["warnings"]:
    554         for w in j["warnings"]:

/home/.local/lib/python3.5/site-packages/h2o/h2o.py in api(endpoint, data,
json, filename, save_to)
     97     # type checks are performed in H2OConnection class
     98     _check_connection()
---> 99     return h2oconn.request(endpoint, data=data, json=json,
filename=filename, save_to=save_to)
    100
    101

/home/.local/lib/python3.5/site-packages/h2o/backend/connection.py in
request(self, endpoint, data, json, filename, save_to)
   400                                     auth=self._auth,
verify=self._verify_ssl_cert, proxies=self._proxies)
    401             self._log_end_transaction(start_time, resp)
--> 402             return self._process_response(resp, save_to)
    403
    404         except (requests.exceptions.ConnectionError,
requests.exceptions.HTTPError) as e:

/home/.local/lib/python3.5/site-packages/h2o/backend/connection.py in
_process_response(response, save_to)
    728         # Note that it is possible to receive valid H2OErrorV3
object in this case, however it merely means the server
    729         # did not provide the correct status code.
--> 730         raise H2OServerError("HTTP %d %s:\n%r" % (status_code,
response.reason, data))
    731
    732

H2OServerError: HTTP 500 Server Error:
Server error water.util.DistributedException:
  Error: DistributedException from /127.0.0.1:54321
  Request: None


问:
How to debug aws lambda functions written in node js
We have been developing AWS Lambda functions in Node JS for a few months. Can we debug, i.e. step through the Node JS code as we can with .Net C# code in Visual Studio?</p>

答:
I would like to share what I have found as I had had some hard time trying to find it out. The solution is based on what I found on article "Debugging AWS Lambda Functions Locally using VS Code and lambda-local"(https://www.codeproject.com/Articles/1163890/Debugging-AWS-Lambda-functions-locally-using-VS-Co) with some modification in order to work in our Windows based environment.

Here is the summary:

1) To use Visual Studio Code to lunch a debug session. Am example of launch.json for debugging 'llDebugDetail.js' is as below:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/test/llDebugDetail.js",
            "cwd": "${workspaceRoot}"
        }
    ]
}
</code>```

2) To use the lambda-local framework to call (execute) the lambda function. The lambda-local framework has to be installed locally, otherwise the VSC debugger won't find it. Our lambda function is invoked by calling the following URL:
https://xxx.execute-api.ap-southeast-2.amazonaws.com/resourceName/{id}/detail.
The {id} is a GUID parameter for selecting a product item and returning its details.

Here is the 'llDebugDetail.js' code for calling the 'getDetail' function for returning product details with the GUID as its id in the URL. The function is within the 'getDetail.js' file.

```<code>const lambdaLocal = require('lambda-local');
var path = require("path");
const myPath = path.join(__dirname, '../getDetail.js');
const testEvent = {
    "resource": "resourceName/12da3f7d-7ce2-433f-8659-5d7cd0d74d9a/detail",
    "pathParameters": {"id": "12da3f7d-7ce2-433f-8659-5d7cd0d74d9a"}
}

var lambdaFunc = require(myPath);

lambdaLocal.execute({
    event: testEvent,
    lambdaFunc: lambdaFunc,
    lambdaHandler: "getDetail"
}).then(function(done) {
    console.log(done);
}).catch(function(err) {
    console.log(err);
});
</code>```

With the above done, you can now set break points anywhere within your code, e.g. inside getDetail.js, launch the program and the step through the code from the break points within getDetail.js.

Body:
I would like to share what I have found as I had had some hard time trying to find it out. The solution is based on what I found on article "Debugging AWS Lambda Functions Locally using VS Code and lambda-local"(https://www.codeproject.com/Articles/1163890/Debugging-AWS-Lambda-functions-locally-using-VS-Co) with some modification in order to work in our Windows based environment.

Here is the summary:

1) To use Visual Studio Code to lunch a debug session. Am example of launch.json for debugging 'llDebugDetail.js' is as below:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/test/llDebugDetail.js",
            "cwd": "${workspaceRoot}"
        }
    ]
}

2) To use the lambda-local framework to call (execute) the lambda function. The lambda-local framework has to be installed locally, otherwise the VSC debugger won't find it. Our lambda function is invoked by calling the following URL:
https://xxx.execute-api.ap-southeast-2.amazonaws.com/resourceName/{id}/detail.
The {id} is a GUID parameter for selecting a product item and returning its details.

Here is the 'llDebugDetail.js' code for calling the 'getDetail' function for returning product details with the GUID as its id in the URL. The function is within the 'getDetail.js' file.

const lambdaLocal = require('lambda-local');
var path = require("path");
const myPath = path.join(__dirname, '../getDetail.js');
const testEvent = {
    "resource": "resourceName/12da3f7d-7ce2-433f-8659-5d7cd0d74d9a/detail",
    "pathParameters": {"id": "12da3f7d-7ce2-433f-8659-5d7cd0d74d9a"}
}

var lambdaFunc = require(myPath);

lambdaLocal.execute({
    event: testEvent,
    lambdaFunc: lambdaFunc,
    lambdaHandler: "getDetail"
}).then(function(done) {
    console.log(done);
}).catch(function(err) {
    console.log(err);
});

With the above done, you can now set break points anywhere within your code, e.g. inside getDetail.js, launch the program and the step through the code from the break points within getDetail.js.


问:
How can I perform a reverse string search in Excel without using VBA?
I have an Excel spreadsheet containing a list of strings. Each string is made up of several words, but the number of words in each string is different.

Using built in Excel functions (no VBA), is there a way to isolate the last word in each string?

Examples:

```
  Are you classified as human? -> human?
Negative, I am a meat popsicle -> popsicle
                  Aziz! Light! -> Light!```

答:
Copy into a column, select that column and HOME > Editing > Find & Select, Replace:

Replace All.

There is a space after the asterisk.

OwnerDisplayName: eJames

Body:
I have an Excel spreadsheet containing a list of strings. Each string is made up of several words, but the number of words in each string is different.

Using built in Excel functions (no VBA), is there a way to isolate the last word in each string?

Examples:

  Are you classified as human? -> human?
Negative, I am a meat popsicle -> popsicle
                  Aziz! Light! -> Light!


问:
Cordova FileEntry.file() returning size 0
I'm running into an issue where when I save a jpg as an octet-stream on windows, the subsequent read returns a file with size of 0.  I can see the file on my hard drive, and the file looks fine, but reading the file fails.

The code below is what I'm using to interact with the file system, with some hacks thrown in to try to solve this issue.

```<code>function downloadFileFromUrl(url, localPath, contentType, successCallback, failureCallback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';

    xhr.onload = function () {
        if (this.status == 200) {
            localPath = encodeURI(localPath);
            writePersistantFile(localPath, this.response, true, contentType,
                function (fileEntry) {
                    if (successCallback != undefined) {
                        successCallback(fileEntry);
                    }
                },
                function (error) {
                    if (failureCallback != undefined) {
                        failureCallback(error);
                    }
                });
        }
    };
    xhr.send();
}

function createDirectoryRecursively(path, parentDir, callback, errorCallback) {
    if (path == null || path.length == 0) {
        callback(parentDir);
        return;
    }
    var index = path.indexOf('/');
    var dirName = null;
    var remainder = null;
    if (index <= 0) {
        dirName = path;
    } else {
        dirName = path.substring(0, index);
        remainder = path.substring(index + 1);
    }

    parentDir.getDirectory(dirName, { create: true, exclusive: true }, function (dirEntry) {
        self.createDirectoryRecursively(remainder, dirEntry, callback, errorCallback);
    }, function (error) {
        if (error.code == 12) {
            parentDir.getDirectory(dirName, { create: false }, function (dirEntry) {
                self.createDirectoryRecursively(remainder, dirEntry, callback, errorCallback);
            }, function (error2) {
                errorCallback(error);
            });
            return;
        }
        errorCallback(error);
    });
}

function getFile(fileName, parentDir, callback, errorCallback) {
    if (parentDir == null) {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
            function (fs) {
                getFile(fileName, fs.root, callback, errorCallback);
            },
            function (error) {

            });
        return;
    }
    if (fileName.indexOf('/') >= 0) {
        var dirName = fileName.substring(0, fileName.lastIndexOf('/'));
        createDirectoryRecursively(dirName, parentDir,
            function (directory) {
                var name = fileName.substring(fileName.lastIndexOf('/') + 1);
                getFile(name, directory, callback, errorCallback);
            }, errorCallback);
        return;
    }
    parentDir.getFile(fileName, { create: true },
        function (fileEntry) {
            console.log('obtained file');
            callback(fileEntry);
        },
        function (error) {
            if (error.code == 1) {
                parentDir.getFile(fileName, { create: false },
                    function (fileEntry) {
                        console.log('obtained file');
                        callback(fileEntry);
                    },
                    function (error) {
                        if (error.code == 12) {
                            return;
                        }
                        errorCallback(error);
                    });
                return;
            }
            errorCallback(error);
        });
}

function readPersistantFile(filePath, successCallback, errorCallback) {
    getFile(filePath, null,
        function (fileEntry) {
            console.log('obtained file');
            fileEntry.file(function (file) {
                console.log('file size: ' + file.size);
                var reader = new FileReader();

                reader.onloadend = function () {
                    console.log("Successful file read");
                    if (successCallback != undefined) {
                        successCallback(this.result);
                    }
                };

                var extension = filePath.substring(filePath.lastIndexOf('.') + 1);
                if (extension == 'json') {
                    reader.readAsText(file);
                } else {
                    reader.readAsDataURL(file);
                }
            });

        },
        function (error) {
            console.log('An error occured while getting the file');
            console.error(error);
            if (errorCallback != undefined) {
                errorCallback(error);
            }
        });
}

function writePersistantFile(filePath, data, isBinary, contentType, successCallback, errorCallback) {
    var dataSize = (data.length != undefined) ? data.length : (data.size != undefined)? data.size : 5 * 1024 * 1024;
    window.requestFileSystem(LocalFileSystem.PERSISTENT, dataSize, function (fs) {
        console.log('file system opened: ' + fs.name);

        var lastIndex = filePath.lastIndexOf('/');
        var directory = filePath.substring(0, lastIndex);
        createDirectoryRecursively(directory, fs.root, function (parentDir) {
            console.log('Directory created');
            var fileName = filePath.substring(lastIndex + 1);
            getFile(fileName, parentDir,
                function (fileEntry) {
                    console.log('obtained file');
                    fileEntry.createWriter(function (fileWriter) {
                        console.log('created writer');
                        if (typeof (data) == 'string') {
                            fileWriter.write(new Blob([data], { type: contentType }));
                        } else {
                            fileWriter.write(data);
                        }

                        if (successCallback != undefined) {
                            successCallback(fileEntry);
                        }
                    });
                },
                function (error) {
                    console.log('An error occured while getting the file');
                    console.error(error);
                    if (errorCallback != undefined) {
                        errorCallback(error);
                    }
                });

        }, function (error) {
            console.log('An error occured while saving the file');
            console.error(error);
            if (errorCallback != undefined) {
                errorCallback(error);
            }
        });
    });
}
</code>```

答:
It appears not to be the code above, which can be easily optimized, but rather the length / number of folders being passed in.

The same file being written had a length of 36 characters and 4 subfolders.  Changing this to just a single file name such as 'page-1.jpg' worked without issue.

Body:
I'm running into an issue where when I save a jpg as an octet-stream on windows, the subsequent read returns a file with size of 0.  I can see the file on my hard drive, and the file looks fine, but reading the file fails.

The code below is what I'm using to interact with the file system, with some hacks thrown in to try to solve this issue.

function downloadFileFromUrl(url, localPath, contentType, successCallback, failureCallback) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';

    xhr.onload = function () {
        if (this.status == 200) {
            localPath = encodeURI(localPath);
            writePersistantFile(localPath, this.response, true, contentType,
                function (fileEntry) {
                    if (successCallback != undefined) {
                        successCallback(fileEntry);
                    }
                },
                function (error) {
                    if (failureCallback != undefined) {
                        failureCallback(error);
                    }
                });
        }
    };
    xhr.send();
}

function createDirectoryRecursively(path, parentDir, callback, errorCallback) {
    if (path == null || path.length == 0) {
        callback(parentDir);
        return;
    }
    var index = path.indexOf('/');
    var dirName = null;
    var remainder = null;
    if (index <= 0) {
        dirName = path;
    } else {
        dirName = path.substring(0, index);
        remainder = path.substring(index + 1);
    }

    parentDir.getDirectory(dirName, { create: true, exclusive: true }, function (dirEntry) {
        self.createDirectoryRecursively(remainder, dirEntry, callback, errorCallback);
    }, function (error) {
        if (error.code == 12) {
            parentDir.getDirectory(dirName, { create: false }, function (dirEntry) {
                self.createDirectoryRecursively(remainder, dirEntry, callback, errorCallback);
            }, function (error2) {
                errorCallback(error);
            });
            return;
        }
        errorCallback(error);
    });
}

function getFile(fileName, parentDir, callback, errorCallback) {
    if (parentDir == null) {
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
            function (fs) {
                getFile(fileName, fs.root, callback, errorCallback);
            },
            function (error) {

            });
        return;
    }
    if (fileName.indexOf('/') >= 0) {
        var dirName = fileName.substring(0, fileName.lastIndexOf('/'));
        createDirectoryRecursively(dirName, parentDir,
            function (directory) {
                var name = fileName.substring(fileName.lastIndexOf('/') + 1);
                getFile(name, directory, callback, errorCallback);
            }, errorCallback);
        return;
    }
    parentDir.getFile(fileName, { create: true },
        function (fileEntry) {
            console.log('obtained file');
            callback(fileEntry);
        },
        function (error) {
            if (error.code == 1) {
                parentDir.getFile(fileName, { create: false },
                    function (fileEntry) {
                        console.log('obtained file');
                        callback(fileEntry);
                    },
                    function (error) {
                        if (error.code == 12) {
                            return;
                        }
                        errorCallback(error);
                    });
                return;
            }
            errorCallback(error);
        });
}

function readPersistantFile(filePath, successCallback, errorCallback) {
    getFile(filePath, null,
        function (fileEntry) {
            console.log('obtained file');
            fileEntry.file(function (file) {
                console.log('file size: ' + file.size);
                var reader = new FileReader();

                reader.onloadend = function () {
                    console.log("Successful file read");
                    if (successCallback != undefined) {
                        successCallback(this.result);
                    }
                };

                var extension = filePath.substring(filePath.lastIndexOf('.') + 1);
                if (extension == 'json') {
                    reader.readAsText(file);
                } else {
                    reader.readAsDataURL(file);
                }
            });

        },
        function (error) {
            console.log('An error occured while getting the file');
            console.error(error);
            if (errorCallback != undefined) {
                errorCallback(error);
            }
        });
}

function writePersistantFile(filePath, data, isBinary, contentType, successCallback, errorCallback) {
    var dataSize = (data.length != undefined) ? data.length : (data.size != undefined)? data.size : 5 * 1024 * 1024;
    window.requestFileSystem(LocalFileSystem.PERSISTENT, dataSize, function (fs) {
        console.log('file system opened: ' + fs.name);

        var lastIndex = filePath.lastIndexOf('/');
        var directory = filePath.substring(0, lastIndex);
        createDirectoryRecursively(directory, fs.root, function (parentDir) {
            console.log('Directory created');
            var fileName = filePath.substring(lastIndex + 1);
            getFile(fileName, parentDir,
                function (fileEntry) {
                    console.log('obtained file');
                    fileEntry.createWriter(function (fileWriter) {
                        console.log('created writer');
                        if (typeof (data) == 'string') {
                            fileWriter.write(new Blob([data], { type: contentType }));
                        } else {
                            fileWriter.write(data);
                        }

                        if (successCallback != undefined) {
                            successCallback(fileEntry);
                        }
                    });
                },
                function (error) {
                    console.log('An error occured while getting the file');
                    console.error(error);
                    if (errorCallback != undefined) {
                        errorCallback(error);
                    }
                });

        }, function (error) {
            console.log('An error occured while saving the file');
            console.error(error);
            if (errorCallback != undefined) {
                errorCallback(error);
            }
        });
    });
}


问:
How to Create an HTML Popup Window Next to Image when Hovering Over It?
I'm attempting to make a webpage where there are several images as links for visiting separate pages, and I want to make a popup show next to the image with a summary, title, and other details of the page in HTML (maybe a button "Read More" or something). I'm trying to create a popup similar to
this one:

I've got my images already, and I can't find a template where there's a separate popup next to the image, because all the image css transition links have the title and text inside the image rather than next to it as a popup. Is this to complicated to do in CSS, or is it possible?

Thanks in advance!  If there is any need for clarification in my question, please ask!

```<code><a href="SecretPlants.html">
<img class="imgLinks" src="file:///E:/Grace/Art/Animation-Computing/Website/ContentTABS/ResourceFiles/Literature/TheSecretsHeldInPlants/SecretLifeofPlantsCover.jpg" alt="Link to Plants Research Paper" height="300">

<a href="EmbraceDifferences.html">
<img class="imgLinks" src="Embrace Differences Cover Image.jpg" alt="Link to Plants Research Paper" height="300">

<a href="Teams of Teams, Hierarchy of Teams, and Hierarchy Essay.html">
<img class="imgLinks" src="Cover.jpg" alt="Link to Hierarchy and Team Critical Essay" height="300">
</code>```

答:
I create an example for you, hopefully it can usefull for you :

HTML :

```<code><div class="button">
    <img class="parentPic" src="http://lorempixel.com/400/200/sports/1" alt"test" />
    <section class="speech">
    <div class="row">
    <div class="col-md-2"></div>
    <div class="col-md-8">
       <div class="list-group">
           <a href="#" class="list-group-item active">
           <h4 class="list-group-item-heading">List group item heading</h4>
           <p class="list-group-item-text">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley</p>
           </a>
      </div>
  <div class="well well-sm">Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown</div>

  <ul class="list-group">
  <li class="list-group-item">
  <span class="badge">14</span>
Cras justo odio
 </li>
</ul>

 </div>
  <div class="col-md-2"></div>
  </div>

 </section>
 </div>
</code>```

CSS :

```<code>.button {
  position: relative;
 }

 .button > img {
</code>```

display: inline-block;

```<code>    color: #fff;
    padding: 0.4em 0.6em;
    font-size: 1.3em;

   }

  .button section {
    display: none;
    position: absolute;
    top: 2em;
    left: 32em;
    padding: 20px;
    margin: 0;
    border: 5px solid #fd0;
    background: white;
    border-radius: 1em;
  }

 .button section > p {
    display:block;
    text-align:center;
  }
 }

 .button .parentPic {
   display: block;
   border-radius: 0.8em;
   max-width: 100%;
   height: auto;
  }

 .button:focus section,
 .button:hover section {
    display: inline-flex;
    top:0px;
  }

 .speech {
     position: relative;
     width: 300px;
     height: 400px;
     text-align: center;
     line-height: 20px;
     background-color:  white;
     border: 8px solid  #fd0;
     -webkit-border-radius: 30px;
     -moz-border-radius: 30px;
     border-radius: 30px;
     -webkit-box-shadow: 2px 2px 4px #888;
     -moz-box-shadow: 2px 2px 4px #888;
     box-shadow: 2px 2px 4px #888;
   }
  .title{
       text -align:center;
     }
     .speech > p{
       padding:15px;
     }

     .speech:before {
       content: ' ';
       position: absolute;
       width: 0;
       height: 0;
       left: 0px;

       border: 0px solid;
       border-color:  #fd0 transparent transparent  #fd0;
     }

     .speech:after {
       content: '';
       position: absolute;
         width: 0;
         height: 0;
         left: -29px;
         top: 50px;
         border-top: 13px solid;
         border-left: 25px solid;
         border-right: 3px solid;
         border-top-left-radius: 39px;
         border-bottom-left-radius: 41px;
         border-color: #fd0 transparent transparent #fd0;
     }
</code>```

https://jsfiddle.net/emilvr/9x7j430L/3/

Body:
I create an example for you, hopefully it can usefull for you :

HTML :

<div class="button">
    <img class="parentPic" src="http://lorempixel.com/400/200/sports/1" alt"test" />
    <section class="speech">
    <div class="row">
    <div class="col-md-2"></div>
    <div class="col-md-8">
       <div class="list-group">
           <a href="#" class="list-group-item active">
           <h4 class="list-group-item-heading">List group item heading</h4>
           <p class="list-group-item-text">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley</p>
           </a>
      </div>
  <div class="well well-sm">Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown</div>

  <ul class="list-group">
  <li class="list-group-item">
  <span class="badge">14</span>
Cras justo odio
 </li>
</ul>

 </div>
  <div class="col-md-2"></div>
  </div>

 </section>
 </div>

CSS :

.button {
  position: relative;
 }

 .button > img {

display: inline-block;

    color: #fff;
    padding: 0.4em 0.6em;
    font-size: 1.3em;

   }

  .button section {
    display: none;
    position: absolute;
    top: 2em;
    left: 32em;
    padding: 20px;
    margin: 0;
    border: 5px solid #fd0;
    background: white;
    border-radius: 1em;
  }

 .button section > p {
    display:block;
    text-align:center;
  }
 }

 .button .parentPic {
   display: block;
   border-radius: 0.8em;
   max-width: 100%;
   height: auto;
  }

 .button:focus section,
 .button:hover section {
    display: inline-flex;
    top:0px;
  }

 .speech {
     position: relative;
     width: 300px;
     height: 400px;
     text-align: center;
     line-height: 20px;
     background-color:  white;
     border: 8px solid  #fd0;
     -webkit-border-radius: 30px;
     -moz-border-radius: 30px;
     border-radius: 30px;
     -webkit-box-shadow: 2px 2px 4px #888;
     -moz-box-shadow: 2px 2px 4px #888;
     box-shadow: 2px 2px 4px #888;
   }
  .title{
       text -align:center;
     }
     .speech > p{
       padding:15px;
     }

     .speech:before {
       content: ' ';
       position: absolute;
       width: 0;
       height: 0;
       left: 0px;

       border: 0px solid;
       border-color:  #fd0 transparent transparent  #fd0;
     }

     .speech:after {
       content: '';
       position: absolute;
         width: 0;
         height: 0;
         left: -29px;
         top: 50px;
         border-top: 13px solid;
         border-left: 25px solid;
         border-right: 3px solid;
         border-top-left-radius: 39px;
         border-bottom-left-radius: 41px;
         border-color: #fd0 transparent transparent #fd0;
     }

https://jsfiddle.net/emilvr/9x7j430L/3/


问:
Macro error while trying to implement a trait inside a macro expansion
fn a() {} seems to satisfy a parsing rule that expected a fn, then some other stuff. items should be able to be function definitions, right? So they should work, right?

```<code>macro_rules! multi_impl {
    (for $base:ty :
        $($t:ty {
            $($i:item);*
        }),+) =>
    {
        $(
            impl $t for $base
            {
                $( $i )*
            }
        )+
    }
}

trait A {
    fn a();
}

trait B {
    fn b();
}

struct S;

multi_impl! {
    for S:
    A {
        fn a() {}
    }, B {
        fn b() {}
    }
}

fn main() {
    S::a();
    S::b();
}
</code>```

playground

The error in question:

error: expected one of `const`, `default`, `extern`, `fn`, `pub`, `type`, `unsafe`, or `}`, found `fn a() { }`
  --> <anon>:11:20
   |
11 |                 $( $i )*
   |                    ^^
```

Making it $( fn $i)* only changes the error to complain about expecting an identifier after the fn, which makes sense, but the initial error does not (at least to me).

Is there a difference to the parser about code that is in the source vs code that's placed into the source by a macro?

答:
The problem isn't that a fn isn't an item, it's that the body of an impl does not contain items.  It contains "impl items".  What it's complaining about is you trying to put a square-shaped block into a round hole, not that the block is the wrong colour.

Yes, those are two different things.  No, you can't capture "impl items" in a macro.  No, you can't turn an item into an impl item.  Because macros capture AST nodes, not the tokens.  Well, methods can have a self argument and regular function's don't.  I don't know, presumably it seemed like a good idea at the time.

Putting the hypothetical back-and-forth aside, the solution in this case is to not bother trying to match anything in particular and just match anything.

```<code>macro_rules! multi_impl
{
    (for $base:ty :
        $($t:ty {
            $($body:tt)*
        }),+) =>
    {
        $(
            impl $t for $base
            {
                $($body)*
            }
        )+
    }
}
</code>```

Body:
fn a() {} seems to satisfy a parsing rule that expected a fn, then some other stuff. items should be able to be function definitions, right? So they should work, right?

macro_rules! multi_impl {
    (for $base:ty :
        $($t:ty {
            $($i:item);*
        }),+) =>
    {
        $(
            impl $t for $base
            {
                $( $i )*
            }
        )+
    }
}

trait A {
    fn a();
}

trait B {
    fn b();
}

struct S;

multi_impl! {
    for S:
    A {
        fn a() {}
    }, B {
        fn b() {}
    }
}

fn main() {
    S::a();
    S::b();
}

playground

The error in question:

error: expected one of `const`, `default`, `extern`, `fn`, `pub`, `type`, `unsafe`, or `}`, found `fn a() { }`
  --> <anon>:11:20
   |
11 |                 $( $i )*
   |                    ^^

Making it $( fn $i)* only changes the error to complain about expecting an identifier after the fn, which makes sense, but the initial error does not (at least to me).

Is there a difference to the parser about code that is in the source vs code that's placed into the source by a macro?

Body:
The problem isn't that a fn isn't an item, it's that the body of an impl does not contain items.  It contains "impl items".  What it's complaining about is you trying to put a square-shaped block into a round hole, not that the block is the wrong colour.

Yes, those are two different things.  No, you can't capture "impl items" in a macro.  No, you can't turn an item into an impl item.  Because macros capture AST nodes, not the tokens.  Well, methods can have a self argument and regular function's don't.  I don't know, presumably it seemed like a good idea at the time.

Putting the hypothetical back-and-forth aside, the solution in this case is to not bother trying to match anything in particular and just match anything.

macro_rules! multi_impl
{
    (for $base:ty :
        $($t:ty {
            $($body:tt)*
        }),+) =>
    {
        $(
            impl $t for $base
            {
                $($body)*
            }
        )+
    }
}


问:
How can I configure ipython to display integers in hex format?
Here's the default behavior:

```<code>In [21]: 255
Out[21]: 255
</code>```

And here's what I would like:

```<code>In [21]: 255
Out[21]: FF
</code>```

Can I setup ipython to do that?

答:
Based on minrk's answer and rjb's answer on another question, I put this in my Python startup file:

```<code>def hexon_ipython():
  '''To print ints as hex, run hexon_ipython().
  To revert, run hexoff_ipython().
  '''
  formatter = get_ipython().display_formatter.formatters['text/plain']
  formatter.for_type(int, lambda n, p, cycle: p.text("0x%x" % n))

def hexoff_ipython():
  '''See documentation for hexon_ipython().'''
  formatter = get_ipython().display_formatter.formatters['text/plain']
  formatter.for_type(int, lambda n, p, cycle: p.text("%d" % n))

hexon = hexon_ipython
hexoff = hexoff_ipython
</code>```

So I can use it like this:

```<code>In [1]: 15
Out[1]: 15

In [2]: hexon()

In [3]: 15
Out[3]: 0xf

In [4]: hexoff()

In [5]: 15
Out[5]: 15
</code>```

Body:
Here's the default behavior:

In [21]: 255
Out[21]: 255

And here's what I would like:

In [21]: 255
Out[21]: FF

Can I setup ipython to do that?

Body:
Based on minrk's answer and rjb's answer on another question, I put this in my Python startup file:

def hexon_ipython():
  '''To print ints as hex, run hexon_ipython().
  To revert, run hexoff_ipython().
  '''
  formatter = get_ipython().display_formatter.formatters['text/plain']
  formatter.for_type(int, lambda n, p, cycle: p.text("0x%x" % n))

def hexoff_ipython():
  '''See documentation for hexon_ipython().'''
  formatter = get_ipython().display_formatter.formatters['text/plain']
  formatter.for_type(int, lambda n, p, cycle: p.text("%d" % n))

hexon = hexon_ipython
hexoff = hexoff_ipython

So I can use it like this:

In [1]: 15
Out[1]: 15

In [2]: hexon()

In [3]: 15
Out[3]: 0xf

In [4]: hexoff()

In [5]: 15
Out[5]: 15


问:
parse password reset key from emailed weblink
Since I switched to using hashed passwords in my demo website, I needed to provide a way reset forgotten passwords.

I've got the pages and php setup to send an email with a url+key that the user will need in order to setup new password.  The email contains the url to click on and the link brings the user to the reset password page.

The part I'm having a bit of trouble with is pulling the key information from the url so I can use it to compare to the key generated from the reset password submission.  The database correctly inserts the key when the forgot password form is submitted.

I'm assuming I need to use parse_url to extract this information from the link but I'm not quite sure how to pull only the key information from the link.

I think PHP_URL_QUERY gets me to the correct part of the URL.  From here I'm not quite sure what to do next since PHP_URL_QUERY gives me all of this:

key='.$2y$10$q53hrjswTfXnkxg8QeJysezbBi91t4yJcbV9bH3addOSiotr6kE1

when what I really want is this to do the comparison:

'.$2y$10$q53hrjswTfXnkxg8QeJysezbBi91t4yJcbV9bH3addOSiotr6kE1

Here's the code I've got right now....

```<code><?php
require_once '../php/connect.php';

function URL() {
  $purl = 'http';
    if ($_SERVER["SERVER_PORT"] == "80") {
      $purl .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
  return $purl;
}

$key = parse_url($purl, PHP_URL_QUERY)

$qry = mysqli_query($link, "SELECT id FROM planner WHERE rkey = '$key'");
$array = mysqli_fetch_array($qry);

    }
}
</code>```

I think I just need a way to strip the key= part from the rest, but I'm not sure that is quite right.

Any assistance is greatly appreciated.

答:
Got this working with the following....this is just a start.  Thanks again everyone.</p>

```<code><?php
require_once '../php/connect.php';

$sub = htmlspecialchars($_GET["key"]);
$ser = "'.";
$rkey = str_replace($ser,'',$sub);

$qry = mysqli_query($link, "SELECT id FROM planner WHERE rkey = '$rkey'");
$row = mysqli_num_rows($qry);

echo $row;

?>
</code>```

Body:
Since I switched to using hashed passwords in my demo website, I needed to provide a way reset forgotten passwords.

I've got the pages and php setup to send an email with a url+key that the user will need in order to setup new password.  The email contains the url to click on and the link brings the user to the reset password page.

The part I'm having a bit of trouble with is pulling the key information from the url so I can use it to compare to the key generated from the reset password submission.  The database correctly inserts the key when the forgot password form is submitted.

I'm assuming I need to use parse_url to extract this information from the link but I'm not quite sure how to pull only the key information from the link.

I think PHP_URL_QUERY gets me to the correct part of the URL.  From here I'm not quite sure what to do next since PHP_URL_QUERY gives me all of this:

key='.$2y$10$q53hrjswTfXnkxg8QeJysezbBi91t4yJcbV9bH3addOSiotr6kE1

when what I really want is this to do the comparison:

'.$2y$10$q53hrjswTfXnkxg8QeJysezbBi91t4yJcbV9bH3addOSiotr6kE1

Here's the code I've got right now....

<?php
require_once '../php/connect.php';

function URL() {
  $purl = 'http';
    if ($_SERVER["SERVER_PORT"] == "80") {
      $purl .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
  return $purl;
}

$key = parse_url($purl, PHP_URL_QUERY)

$qry = mysqli_query($link, "SELECT id FROM planner WHERE rkey = '$key'");
$array = mysqli_fetch_array($qry);

    }
}

I think I just need a way to strip the key= part from the rest, but I'm not sure that is quite right.

Any assistance is greatly appreciated.

Body:
Got this working with the following....this is just a start.  Thanks again everyone.

<?php
require_once '../php/connect.php';

$sub = htmlspecialchars($_GET["key"]);
$ser = "'.";
$rkey = str_replace($ser,'',$sub);

$qry = mysqli_query($link, "SELECT id FROM planner WHERE rkey = '$rkey'");
$row = mysqli_num_rows($qry);

echo $row;

?>


问:
Optimize path distance from circle calculation in D3
In this D3.js graph I'm using the magic numbers 20 when the line is straight and 30 when the line is at an angle as the margin to withdraw from the path in order to add a margin between the circles (graph nodes) and the paths (graph edges).

I'm also using the fairly random number 1.5 as a multiplier to further the distance from the circle of the path's end, since it has a marker-end attached to it.

Given the circle radius of 19 and the arrow path coordinates M0,0 V4 L2,2 Z, I assume it should be possible to calculate the exact distance ("margin") the paths should have from the circles, but my math skills just aren't up for it. I also assume it's possible to figure out the direction of the paths so the margin inversion is no longer required.

If you have ideas on how the distance and margin calculation within the withMargins() function can be optimized, please provide an answer. All optimizations and code reductions are welcome. Here's the relevant code:

```<code>this.withMargins = function() {
    var diff = {
        x: edge.end.x - edge.start.x,
        y: edge.end.y - edge.start.y
    };

    var margins = {
        start: {
            x: 0,
            y: 0
        },
        end: {
            x: 0,
            y: 0
        }
    };

    if (diff.x > 0 && diff.y === 0) {
        margins.start.x = 30;
    } else if (diff.x < 0 && diff.y === 0) {
        margins.start.x = -30;
    } else if (diff.x > 0) {
        margins.start.x = 20;
    } else if (diff.x < 0) {
        margins.start.x = -20;
    }

    if (diff.y > 0 && diff.x === 0) {
        margins.start.y = 30;
    } else if (diff.y < 0 && diff.x === 0) {
        margins.start.y = -30;
    } else if (diff.y > 0) {
        margins.start.y = 20;
    } else if (diff.y < 0) {
        margins.start.y = -20;
    }

    if (margins.start.x != 0) {
        margins.end.x = margins.start.x < 0 ?
            Math.abs(margins.start.x * 1.5) :
            margins.start.x * -1.5;
    }

    if (margins.start.y != 0) {
        margins.end.y = margins.start.y < 0 ?
            Math.abs(margins.start.y * 1.5) :
            margins.start.y * -1.5;
    }

    // The top branch edges are inverted, so their margins
    // needs to be inverted too.
    if (edge.branch === 'top') {
        var startX = margins.start.x;
        var startY = margins.start.y;
        margins.start.x = margins.end.x * -1;
        margins.start.y = margins.end.y * -1;
        margins.end.x = startX * -1;
        margins.end.y = startY * -1;
    }

    edge.start.x += margins.start.x;
    edge.start.y += margins.start.y;
    edge.end.x += margins.end.x;
    edge.end.y += margins.end.y;

    return edge;
};
</code>```

The code might look a bit wonky, but that can largely be explained by it being torn out of a Reveal.js presentation I'm working on. I'm all up for ideas on how to improve other parts of the code as well, but it's particularly the body of the withMargins() function I'm unhappy with.

答:
As far I understand - you have center of the first circle (x0,y0), center of the second circle (x1,y1), circle radius R, desired margin from circle circumference M, and want to find starting and ending coordinates of arrow.

(Seems you are using full distance from circle center, in this case set Marg)

```<code>dx = x1 - x0
dy = y1 - y0
Len = math.sqrt(dx * dx + dy * dy)  //use math.hypot if available
Marg = R + M  //full distance from circle center to arrow end. 30 in your case
Coeff = Marg / Len
ax0 = x0 + Coeff * dx   //arrow start coords
ay0 = y0 + Coeff * dy
ax1 = x1 - Coeff * dx   //arrow end
ay1 = y1 - Coeff * dy
</code>```

That's all.

Body:
In this D3.js graph I'm using the magic numbers 20 when the line is straight and 30 when the line is at an angle as the margin to withdraw from the path in order to add a margin between the circles (graph nodes) and the paths (graph edges).

I'm also using the fairly random number 1.5 as a multiplier to further the distance from the circle of the path's end, since it has a marker-end attached to it.

Given the circle radius of 19 and the arrow path coordinates M0,0 V4 L2,2 Z, I assume it should be possible to calculate the exact distance ("margin") the paths should have from the circles, but my math skills just aren't up for it. I also assume it's possible to figure out the direction of the paths so the margin inversion is no longer required.

If you have ideas on how the distance and margin calculation within the withMargins() function can be optimized, please provide an answer. All optimizations and code reductions are welcome. Here's the relevant code:

this.withMargins = function() {
    var diff = {
        x: edge.end.x - edge.start.x,
        y: edge.end.y - edge.start.y
    };

    var margins = {
        start: {
            x: 0,
            y: 0
        },
        end: {
            x: 0,
            y: 0
        }
    };

    if (diff.x > 0 && diff.y === 0) {
        margins.start.x = 30;
    } else if (diff.x < 0 && diff.y === 0) {
        margins.start.x = -30;
    } else if (diff.x > 0) {
        margins.start.x = 20;
    } else if (diff.x < 0) {
        margins.start.x = -20;
    }

    if (diff.y > 0 && diff.x === 0) {
        margins.start.y = 30;
    } else if (diff.y < 0 && diff.x === 0) {
        margins.start.y = -30;
    } else if (diff.y > 0) {
        margins.start.y = 20;
    } else if (diff.y < 0) {
        margins.start.y = -20;
    }

    if (margins.start.x != 0) {
        margins.end.x = margins.start.x < 0 ?
            Math.abs(margins.start.x * 1.5) :
            margins.start.x * -1.5;
    }

    if (margins.start.y != 0) {
        margins.end.y = margins.start.y < 0 ?
            Math.abs(margins.start.y * 1.5) :
            margins.start.y * -1.5;
    }

    // The top branch edges are inverted, so their margins
    // needs to be inverted too.
    if (edge.branch === 'top') {
        var startX = margins.start.x;
        var startY = margins.start.y;
        margins.start.x = margins.end.x * -1;
        margins.start.y = margins.end.y * -1;
        margins.end.x = startX * -1;
        margins.end.y = startY * -1;
    }

    edge.start.x += margins.start.x;
    edge.start.y += margins.start.y;
    edge.end.x += margins.end.x;
    edge.end.y += margins.end.y;

    return edge;
};

The code might look a bit wonky, but that can largely be explained by it being torn out of a Reveal.js presentation I'm working on. I'm all up for ideas on how to improve other parts of the code as well, but it's particularly the body of the withMargins() function I'm unhappy with.

Body:
As far I understand - you have center of the first circle (x0,y0), center of the second circle (x1,y1), circle radius R, desired margin from circle circumference M, and want to find starting and ending coordinates of arrow.

(Seems you are using full distance from circle center, in this case set Marg)

dx = x1 - x0
dy = y1 - y0
Len = math.sqrt(dx * dx + dy * dy)  //use math.hypot if available
Marg = R + M  //full distance from circle center to arrow end. 30 in your case
Coeff = Marg / Len
ax0 = x0 + Coeff * dx   //arrow start coords
ay0 = y0 + Coeff * dy
ax1 = x1 - Coeff * dx   //arrow end
ay1 = y1 - Coeff * dy

That's all.


问:
celery + rabbitmq on Docker
I'm trying to follow this tutorial How to build docker cluster with celery and RabbitMQ in 10 minutes.

Followed the tutorial, although I did changed the following files.
My docker-compose.yml file looks as follows:

```<code>version: '2'

services:
    rabbit:
    hostname: rabbit
    image: rabbitmq
    environment:
        - RABBITMQ_DEFAULT_USER=user
        - RABBITMQ_DEFAULT_PASS=pass
        - HOSTNAME=rabbitmq
        - RABBITMQ_NODENAME=rabbitmq
    ports:
        - "5672:5672"  # we forward this port because it's useful for debugging
        - "15672:15672"  # here, we can access rabbitmq management plugin

worker:
    build:
    context: .
    dockerfile: Dockerfile
    volumes:
        - .:/app
    links:
        - rabbit
    depends_on:
        - rabbit
</code>```

test_celery/celery.py:

```<code>from __future__ import absolute_import, unicode_literals
from celery import Celery

app = Celery('test_celery',broker='amqp://user:pass@rabbit:5672//',backend='rpc://', include=['test_celery.tasks'])
</code>```

and Dockerfile:

```<code>FROM python:3.6
ADD requirements.txt /app/requirements.txt
ADD ./test_celery /app/
WORKDIR /app/
RUN pip install -r requirements.txt
ENTRYPOINT celery -A test_celery worker --loglevel=info
</code>```

I run the code with the following commands(My OS is Ubuntu 16.04):

```<code>sudo docker-compose build
sudo docker-compose scale worker=5
sudo docker-compose up
</code>```

The output on screen looks something like this:

```<code>rabbit_1  | closing AMQP connection <0.501.0> (172.19.0.6:60470 -> 172.19.0.7:5672, vhost: '/', user: 'admin'):
rabbit_1  | client unexpectedly closed TCP connection
rabbit_1  |
rabbit_1  | =WARNING REPORT==== 8-Jun-2017::03:34:15 ===
rabbit_1  | closing AMQP connection <0.479.0> (172.19.0.6:60468 -> 172.19.0.7:5672, vhost: '/', user: 'admin'):
rabbit_1  | client unexpectedly closed TCP connection
rabbit_1  |
rabbit_1  | =WARNING REPORT==== 8-Jun-2017::03:34:15 ===
rabbit_1  | closing AMQP connection <0.366.0> (172.19.0.4:44754 -> 172.19.0.7:5672, vhost: '/', user: 'admin'):
rabbit_1  | client unexpectedly closed TCP connection
rabbit_1  |
rabbit_1  | =WARNING REPORT==== 8-Jun-2017::03:34:15 ===
rabbit_1  | closing AMQP connection <0.359.0> (172.19.0.4:44752 -> 172.19.0.7:5672, vhost: '/', user: 'admin'):
rabbit_1  | client unexpectedly closed TCP connection
worker_1  | [2017-06-08 03:34:19,138: INFO/MainProcess] missed heartbeat from celery@f77048a9d801
worker_1  | [2017-06-08 03:34:24,140: INFO/MainProcess] missed
heartbeat from celery@79aa2323a472
worker_1  | [2017-06-08 03:34:24,141: INFO/MainProcess] missed heartbeat from celery@93af751ed1b5
</code>```

Then in the same directory I run

```<code>python -m test_celery.run_tasks
</code>```

and the output from this gives me:

a kombu.exceptions.OperationalError: timed out error which I am not sure how to fix and get the same output as in the tutorial.

答: As the output and error report, "client unexpectedly closed TCP connection" , "kombu.exceptions.OperationalError: timed out", it seems that RabbitMQ didn't start as expected. Could you run the command "docker ps -a" to check what's the status of Rabbit container? If exited , "docker logs container-id" will print out logs of Rabbit container.</p>

Title: celery + rabbitmq on Docker

Body:
I'm trying to follow this tutorial How to build docker cluster with celery and RabbitMQ in 10 minutes.

Followed the tutorial, although I did changed the following files.
My docker-compose.yml file looks as follows:

version: '2'

services:
    rabbit:
    hostname: rabbit
    image: rabbitmq
    environment:
        - RABBITMQ_DEFAULT_USER=user
        - RABBITMQ_DEFAULT_PASS=pass
        - HOSTNAME=rabbitmq
        - RABBITMQ_NODENAME=rabbitmq
    ports:
        - "5672:5672"  # we forward this port because it's useful for debugging
        - "15672:15672"  # here, we can access rabbitmq management plugin

worker:
    build:
    context: .
    dockerfile: Dockerfile
    volumes:
        - .:/app
    links:
        - rabbit
    depends_on:
        - rabbit

test_celery/celery.py:

from __future__ import absolute_import, unicode_literals
from celery import Celery

app = Celery('test_celery',broker='amqp://user:pass@rabbit:5672//',backend='rpc://', include=['test_celery.tasks'])

and Dockerfile:

FROM python:3.6
ADD requirements.txt /app/requirements.txt
ADD ./test_celery /app/
WORKDIR /app/
RUN pip install -r requirements.txt
ENTRYPOINT celery -A test_celery worker --loglevel=info

I run the code with the following commands(My OS is Ubuntu 16.04):

sudo docker-compose build
sudo docker-compose scale worker=5
sudo docker-compose up

The output on screen looks something like this:

rabbit_1  | closing AMQP connection <0.501.0> (172.19.0.6:60470 -> 172.19.0.7:5672, vhost: '/', user: 'admin'):
rabbit_1  | client unexpectedly closed TCP connection
rabbit_1  |
rabbit_1  | =WARNING REPORT==== 8-Jun-2017::03:34:15 ===
rabbit_1  | closing AMQP connection <0.479.0> (172.19.0.6:60468 -> 172.19.0.7:5672, vhost: '/', user: 'admin'):
rabbit_1  | client unexpectedly closed TCP connection
rabbit_1  |
rabbit_1  | =WARNING REPORT==== 8-Jun-2017::03:34:15 ===
rabbit_1  | closing AMQP connection <0.366.0> (172.19.0.4:44754 -> 172.19.0.7:5672, vhost: '/', user: 'admin'):
rabbit_1  | client unexpectedly closed TCP connection
rabbit_1  |
rabbit_1  | =WARNING REPORT==== 8-Jun-2017::03:34:15 ===
rabbit_1  | closing AMQP connection <0.359.0> (172.19.0.4:44752 -> 172.19.0.7:5672, vhost: '/', user: 'admin'):
rabbit_1  | client unexpectedly closed TCP connection
worker_1  | [2017-06-08 03:34:19,138: INFO/MainProcess] missed heartbeat from celery@f77048a9d801
worker_1  | [2017-06-08 03:34:24,140: INFO/MainProcess] missed
heartbeat from celery@79aa2323a472
worker_1  | [2017-06-08 03:34:24,141: INFO/MainProcess] missed heartbeat from celery@93af751ed1b5

Then in the same directory I run

python -m test_celery.run_tasks

and the output from this gives me:

a kombu.exceptions.OperationalError: timed out error which I am not sure how to fix and get the same output as in the tutorial.


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答: To expand on what Larsenal has said.  An Interface is a contract that all implementing classes must follow.  Because of this, you can use a technique called programming to the contract.  This allows your software to become implementation independent. </p>

LastEditorDisplayName: ALassek

OwnerDisplayName: Matthew Brubaker


问:
Is it possible to more nicely format the help for a function?
When I use describe-function, I get the documentation text displayed in a Help buffer.

If the doc is long enough, it will wrap in the buffer, but it doesn't wrap nicely.  like this:

I can make the docstring use 72-character lines, but that supposes that the window will be 80 characters, which is not always the case.

Is it possible to get describe-function to emit documentation in a more nicely formatted way?

答: Try enabling global-visual-line-mode to get nice text wrapping in all your buffers.  It works in code and help buffers, but doesn't mess up your line numbering!  Of all the line wrapping modes for emacs, I find it to be the best.  If you don't want to use it globally, simply try M-x visual-line-mode.


问:
Iteratively Subset DataFrame based on Unique Times
Given the following example DataFrame:

```<code>>>> df
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3
3  05/11/2017 08:25:20       4
4  05/11/2017 08:30:14       5
5  05/11/2017 08:30:35       6
</code>```

I want to subset this DataFrame by the 'Time' column, by matching a partial string up to the hour.  For example, I want to subset using partial strings which contain "05/10/2017 01:" and "05/11/2017 08:" which breaks up the subsets into two new data frames:

```<code>>>> df1
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3
</code>```

and

```<code>>>> df2
0  05/11/2017 08:25:20       4
1  05/11/2017 08:30:14       5
2  05/11/2017 08:30:35       6
</code>```

Is it possible to make this subset iterative in Pandas, for multiple dates/times that similarly have the date/hour as the common identifier?

答:
First make sure that the Times column is of type DateTime.
Second, set times column as index.
Third, use between_time method.

```<code>df['Times'] = pd.to_datetime(df['Times'])
df.set_index('Times', inplace=True)

df1 = df.between_time('1:00:00', '1:59:59')
df2 = df.between_time('8:00:00', '8:59:59')
</code>```

Body:
Given the following example DataFrame:

>>> df
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3
3  05/11/2017 08:25:20       4
4  05/11/2017 08:30:14       5
5  05/11/2017 08:30:35       6

I want to subset this DataFrame by the 'Time' column, by matching a partial string up to the hour.  For example, I want to subset using partial strings which contain "05/10/2017 01:" and "05/11/2017 08:" which breaks up the subsets into two new data frames:

>>> df1
                 Times  Values
0  05/10/2017 01:01:03       1
1  05/10/2017 01:05:00       2
2  05/10/2017 01:06:10       3

and

>>> df2
0  05/11/2017 08:25:20       4
1  05/11/2017 08:30:14       5
2  05/11/2017 08:30:35       6

Is it possible to make this subset iterative in Pandas, for multiple dates/times that similarly have the date/hour as the common identifier?

Body:
First make sure that the Times column is of type DateTime.
Second, set times column as index.
Third, use between_time method.

df['Times'] = pd.to_datetime(df['Times'])
df.set_index('Times', inplace=True)

df1 = df.between_time('1:00:00', '1:59:59')
df2 = df.between_time('8:00:00', '8:59:59')


问:
Angular js 1.5 - $injector:modulerr
I'm trying to duplicate an angular Material example as described on https://material.angularjs.org/latest/demo/autocomplete and it's driving me nuts.

I get the following error every time, everywhere (on my machine and JSfiddle)

```<code>> Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.5/$injector/modulerr?p0=autocompleteCustomT…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.5%2Fangular.min.js%3A21%3A332)
    at angular.min.js:6
    at angular.min.js:40
    at q (angular.min.js:7)
    at g (angular.min.js:39)
    at bb (angular.min.js:43)
    at c (angular.min.js:21)
    at yc (angular.min.js:21)
    at ee (angular.min.js:20)
    at angular.min.js:313
    at HTMLDocument.b (angular.min.js:188)
</code>```

The JS fiddle is on this link: https://jsfiddle.net/nicothed/rqv8fLn7

I based it on the blank application on that page: https://material.angularjs.org/latest/getting-started#documentation-version.

Would anyone have an idea of what is happening and how to fix it?

答: Click on the Javascript settings wheel in the top right corner of the javascript panel and choose framework as AngularJS and Load Type as 'No wrap - in '

Title: Angular js 1.5 - $injector:modulerr

Body:
I'm trying to duplicate an angular Material example as described on https://material.angularjs.org/latest/demo/autocomplete and it's driving me nuts.

I get the following error every time, everywhere (on my machine and JSfiddle)

> Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.5/$injector/modulerr?p0=autocompleteCustomT…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.5.5%2Fangular.min.js%3A21%3A332)
    at angular.min.js:6
    at angular.min.js:40
    at q (angular.min.js:7)
    at g (angular.min.js:39)
    at bb (angular.min.js:43)
    at c (angular.min.js:21)
    at yc (angular.min.js:21)
    at ee (angular.min.js:20)
    at angular.min.js:313
    at HTMLDocument.b (angular.min.js:188)

The JS fiddle is on this link: https://jsfiddle.net/nicothed/rqv8fLn7

I based it on the blank application on that page: https://material.angularjs.org/latest/getting-started#documentation-version.

Would anyone have an idea of what is happening and how to fix it?


问:
Node.js syntax error
I want to use socket.io and https://socket.io/get-started/chat/ user this link to understand when I try to run node index.js

I got an error

```<code>const WebSocket = require('./lib/WebSocket');
^^^^^ SyntaxError: Use of const in strict mode.
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Server.init (C:\WEBLER\Socket.io\node_modules\socket.io\node_modules\engi ne.io\lib\server.js:119:16)
    at new Server (C:\WEBLER\Socket.io\node_modules\socket.io\node_modules\engin e.io\lib\server.js:65:8)
    at Function.attach (C:\WEBLER\Socket.io\node_modules\socket.io\node_modules\ engine.io\lib\engine.io.js:123:16)
</code>```

I looked at problems . generally people say upgrade version of node.js
when I run node --version

answer is 2.7.4
 I tried

```<code>npm cache clean -f
npm install stable

node --version
</code>```

but it wasn't solved. How can I solve problem?

答:
const is only available in node v4.0 onwards I believe. You can do as Edilson suggested and use var, or upgrade node from 2.7.4 to a version that supports const. Also, take jsNovice advice and use nvm. Here is a link to the same issue someone else had:
https://github.com/felixrieseberg/npm-windows-upgrade/issues/108</p>

Title: Node.js syntax error

Body:
I want to use socket.io and https://socket.io/get-started/chat/ user this link to understand when I try to run node index.js

I got an error

const WebSocket = require('./lib/WebSocket');
^^^^^ SyntaxError: Use of const in strict mode.
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Server.init (C:\WEBLER\Socket.io\node_modules\socket.io\node_modules\engi ne.io\lib\server.js:119:16)
    at new Server (C:\WEBLER\Socket.io\node_modules\socket.io\node_modules\engin e.io\lib\server.js:65:8)
    at Function.attach (C:\WEBLER\Socket.io\node_modules\socket.io\node_modules\ engine.io\lib\engine.io.js:123:16)

I looked at problems . generally people say upgrade version of node.js
when I run node --version

answer is 2.7.4
 I tried

npm cache clean -f
npm install stable

node --version

but it wasn't solved. How can I solve problem?


问:
Difference between public and private variables
```<code>namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}
</code>```

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

答:
public and private are access modifiers for members. This refers to who can access the members directly through code. public means that access is not limited so that anyone can access the member directly through code. private means that access is limited only to the containing class. So everyone can access numberOne directly through code, but only the containing class can access numberTwo directly through code.

There are a total of five access modifiers:

public: access is not limited

protected: access is limited to the containing class or classes derived from the containing class

internal: access is limited to the containing assembly

protected internal: this is an OR of protected and internal so that access is limited to the containing class or classes derived from the containing class OR the containing assembly

private: access is limited to the containing class

Note that the clause "directly through code" is critical here; it is possible to access these members using reflection.

The relevant section of the C# specification is §3.5, especially §3.5.2.

Body:
namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?


问:
What are emoticons?
What are emoticons in Android and IOS, are they just unused characters codes in UTF-8 that developers decided to map cute pictures to?

If so, are they standardized? (e.g. a smiley face on android is a smiley face on IOS?)

答:
Emojis are standardized UTF-8 character sequences that are the same across multiple devices.

Here's their documentation:
http://unicode.org/emoji/charts/full-emoji-list.html

Title: What are emoticons?


问:
Heroku Python failed to detect app matching buildpack
I can't deploy my Flask app to Heroku...
I've searched in every thread I can and nothing worked for me : add a runtime.txt, set a buildpack. I don't know what can be wrong now.

Here is my root directory for the app :

```<code>Project
 - .git
 - Procfile
 - Readme.md
 - app
 - config.py
 - requirements.txt
 - runtime.txt
 - web.py
</code>```

Here's the content of requirements.txt:

```<code>appdirs==1.4.3
click==6.7
Flask==0.12.1
Flask-WTF==0.14.2
itsdangerous==0.24
Jinja2==2.9.5
MarkupSafe==1.0
packaging==16.8
pyparsing==2.2.0
six==1.10.0
Werkzeug==0.12.1
WTForms==2.1
</code>```

The Procfile :

```<code>web: python web.py
</code>```

And the runtime.txt:

```<code>python-2.7.13
</code>```

When I do git push heroku master, it prints:

```<code>remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:             HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:             See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !   Push rejected to appname.
remote:
</code>```

I tried to add a buildpack with heroku buildpacks:add heroku/Python but then it says that it can't detect app for python buildpack.

What could I possibly did wrong ?

答:
edit the content of your Procfile to

```<code>web: gunicorn web:app --log-file=-
</code>```

I assume your web.py file is contained in your project's root folder i.e you see it once you enter your project's "Project" folder.

Otherwise, if it is contained in the app folder then use

```<code>web: gunicorn app.web:app --log-file=-
</code>```

Body:
I can't deploy my Flask app to Heroku...
I've searched in every thread I can and nothing worked for me : add a runtime.txt, set a buildpack. I don't know what can be wrong now.

Here is my root directory for the app :

Project
 - .git
 - Procfile
 - Readme.md
 - app
 - config.py
 - requirements.txt
 - runtime.txt
 - web.py

Here's the content of requirements.txt:

appdirs==1.4.3
click==6.7
Flask==0.12.1
Flask-WTF==0.14.2
itsdangerous==0.24
Jinja2==2.9.5
MarkupSafe==1.0
packaging==16.8
pyparsing==2.2.0
six==1.10.0
Werkzeug==0.12.1
WTForms==2.1

The Procfile :

web: python web.py

And the runtime.txt:

python-2.7.13

When I do git push heroku master, it prints:

remote: Compressing source files... done.
remote: Building source:
remote:
remote:  !     No default language could be detected for this app.
remote:             HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:             See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !   Push rejected to appname.
remote:

I tried to add a buildpack with heroku buildpacks:add heroku/Python but then it says that it can't detect app for python buildpack.

What could I possibly did wrong ?

Body:
edit the content of your Procfile to

web: gunicorn web:app --log-file=-

I assume your web.py file is contained in your project's root folder i.e you see it once you enter your project's "Project" folder.

Otherwise, if it is contained in the app folder then use

web: gunicorn app.web:app --log-file=-


问:
Access a ListView located in a UserControl from the MainForm in Winforms
I have an app that uses a side menu, and for each button (there are 3) on the left side menu, it changes the pages shown.

I tried doing it with multiple panels, but it's a nightmare to maintain in designer, and it's probably not a very good programming habit, I expect.

So I search and found what seemed to be a great idea: UserControl.
But as usual, it's not that simple (for a badly self-taught guy like me)

The general flow of the program is as follows:

a Btn_uc1_Check button that gathers informations and displays them in a uc1_ListView,

a Btn_uc2_Seek button that gathers informations on the net based on the uc1_ListView , and displays them on uc2_ListView,

a Btn_uc3_compile that compiles the info from uc2_ListView into a file,

a Clear button that clears the ListView depending on the UserControl on screen.

Now to the problem:

How on earth do I gain access to a ListView located in a UserControl to be able to read, clear, and add items from the MainFrom or from another UserControl?

I searched and honestly found nothing corresponding to what I needed?

答:
Quite many questions.

You can gain access to any controls in UC. Just change the property "Modifiers" of the ListView in your UC to "Public".

Set that method to public. Do not use keyword "static". Each control
in your form is an instance of a class, not a static class actually. In the main form, create a button and double click on it in VS designer. A method will automatically generated, something like private void button1_Click. When the button is clicked, all of the code lines in button1_Click will run.

Create a public event handler of your user control, then pass the method in main to the handler.

So the UC class will be similar to this:

```<code>public event EventHandler button_UC_Click_handler;

    public UserControl1()
    {
        InitializeComponent();
    }

    private void button_UC_Click(object sender, EventArgs e)
    {
        button_UC_Click_handler.Invoke(sender, e);
    }
</code>```

In main form:

```<code>public MainForm()
    {
        InitializeComponent();
        userControl11.button_UC_Click_handler += UserControl11_button_UC_Click_handler;
    }

    private void UserControl11_button_UC_Click_handler(object sender, EventArgs e)
    {
        MessageBox.Show("You have clicked it!");
    }
</code>```

Good luck!

Body:
Quite many questions.

You can gain access to any controls in UC. Just change the property "Modifiers" of the ListView in your UC to "Public".

Set that method to public. Do not use keyword "static". Each control
in your form is an instance of a class, not a static class actually. In the main form, create a button and double click on it in VS designer. A method will automatically generated, something like private void button1_Click. When the button is clicked, all of the code lines in button1_Click will run.

Create a public event handler of your user control, then pass the method in main to the handler.

So the UC class will be similar to this:

public event EventHandler button_UC_Click_handler;

    public UserControl1()
    {
        InitializeComponent();
    }

    private void button_UC_Click(object sender, EventArgs e)
    {
        button_UC_Click_handler.Invoke(sender, e);
    }

In main form:

public MainForm()
    {
        InitializeComponent();
        userControl11.button_UC_Click_handler += UserControl11_button_UC_Click_handler;
    }

    private void UserControl11_button_UC_Click_handler(object sender, EventArgs e)
    {
        MessageBox.Show("You have clicked it!");
    }

Good luck!


答:
First, cast your Times column into a datetime format, and set it as the index:

```<code>df['Times'] = pd.to_datetime(df['Times'])
df.set_index('Times', inplace = True)
</code>```

Then use the groupby method, with a TimeGrouper:

```<code>g = df.groupby(pd.TimeGrouper('h'))
</code>```

g is an iterator that yields tuple pairs of times and sub-dataframes of those times. If you just want the sub-dfs, you can do zip(*g)[1].

A caveat: the sub-dfs are indexed by the timestamp, and pd.TimeGrouper only works when the times are the index. If you want to have the timestamp as a column, you could instead do:

```<code>df['Times'] = pd.to_datetime(df['Times'])
df['time_hour'] = df['Times'].dt.floor('1h')
g = df.groupby('time_hour')
</code>```

Alternatively, you could just call .reset_index() on each of the dfs from the former method, but this will probably be much slower.

Title: Iteratively Subset DataFrame based on Unique Times

Body:
First, cast your Times column into a datetime format, and set it as the index:

df['Times'] = pd.to_datetime(df['Times'])
df.set_index('Times', inplace = True)

Then use the groupby method, with a TimeGrouper:

g = df.groupby(pd.TimeGrouper('h'))

g is an iterator that yields tuple pairs of times and sub-dataframes of those times. If you just want the sub-dfs, you can do zip(*g)[1].

A caveat: the sub-dfs are indexed by the timestamp, and pd.TimeGrouper only works when the times are the index. If you want to have the timestamp as a column, you could instead do:

df['Times'] = pd.to_datetime(df['Times'])
df['time_hour'] = df['Times'].dt.floor('1h')
g = df.groupby('time_hour')

Alternatively, you could just call .reset_index() on each of the dfs from the former method, but this will probably be much slower.