问:
How do I properly convert XML to JS Objects while properly containing CDATA
I am trying to build an RSS reader web-based app. The issue I'm having is that when I read the XML from the RSS and convert it to a javascript object; anything wrapped in [![CDATA]] gives me an undefined object. Here's what I'm using:

```<code>function XML2jsobj(node) {

var data = {};

// append a value
function Add(name, value) {
    if (data[name]) {
        if (data[name].constructor != Array) {
            data[name] = [data[name]];
        }
        data[name][data[name].length] = value;
    }
    else {
        data[name] = value;
    }
};

// element attributes
var c, cn;
for (c = 0; cn = node.attributes[c]; c++) {
    Add(cn.name, cn.value);
}

// child elements
for (c = 0; cn = node.childNodes[c]; c++) {
    if (cn.nodeType == 1) {
        if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {
            // text value
            Add(cn.nodeName, cn.firstChild.nodeValue);
        }
        else {
            // sub-object
            Add(cn.nodeName, XML2jsobj(cn));
        }
    }
}

return data;
</code>```

}

```<code>var url = "http://rss.cnn.com/rss/cnn_world.rss";
var url1 = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20'"+url+"'";
function getWithJQ2(){
    $.get(url1, function (data) {
        console.log("data:",data);
        var items = XML2jsobj(data.getElementsByTagName('channel')[0]);
        responseFeed = items;
            console.log("First article:",responseFeed.item[0]);

        console.log("items:",items);

    });
}
</code>```

The RSS feed I'm using is http://rss.cnn.com/rss/cnn_world.rss.
As previously stated, all objects are properly created, however if you notice; the  tags are wrapped around CDATA and a quick look in console shows them to be empty objects. I'm not too sure if I gave enough information about this problem but I've been stuck on this for a while.

答:
The nodeType of a CDATA section is 4, so you can get your current code to work by checking for that in the same place you check for text nodes.

Before:

```<code>if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {
</code>```

After:

```<code>if (cn.childNodes.length == 1 &&
    (cn.firstChild.nodeType == 3 || cn.firstChild.nodeType === 4)) {
</code>```

Body:
I am trying to build an RSS reader web-based app. The issue I'm having is that when I read the XML from the RSS and convert it to a javascript object; anything wrapped in [![CDATA]] gives me an undefined object. Here's what I'm using:

function XML2jsobj(node) {

var data = {};

// append a value
function Add(name, value) {
    if (data[name]) {
        if (data[name].constructor != Array) {
            data[name] = [data[name]];
        }
        data[name][data[name].length] = value;
    }
    else {
        data[name] = value;
    }
};

// element attributes
var c, cn;
for (c = 0; cn = node.attributes[c]; c++) {
    Add(cn.name, cn.value);
}

// child elements
for (c = 0; cn = node.childNodes[c]; c++) {
    if (cn.nodeType == 1) {
        if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {
            // text value
            Add(cn.nodeName, cn.firstChild.nodeValue);
        }
        else {
            // sub-object
            Add(cn.nodeName, XML2jsobj(cn));
        }
    }
}

return data;

}

var url = "http://rss.cnn.com/rss/cnn_world.rss";
var url1 = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20'"+url+"'";
function getWithJQ2(){
    $.get(url1, function (data) {
        console.log("data:",data);
        var items = XML2jsobj(data.getElementsByTagName('channel')[0]);
        responseFeed = items;
            console.log("First article:",responseFeed.item[0]);

        console.log("items:",items);

    });
}

The RSS feed I'm using is http://rss.cnn.com/rss/cnn_world.rss.
As previously stated, all objects are properly created, however if you notice; the  tags are wrapped around CDATA and a quick look in console shows them to be empty objects. I'm not too sure if I gave enough information about this problem but I've been stuck on this for a while.

Body:
The nodeType of a CDATA section is 4, so you can get your current code to work by checking for that in the same place you check for text nodes.

Before:

if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {

After:

if (cn.childNodes.length == 1 &&
    (cn.firstChild.nodeType == 3 || cn.firstChild.nodeType === 4)) {


来源: stackexchange

问:
Is there a way to modify this YouTube download script to access the 4K version of the video?
I've been using the script below to download technical videos for later analysis. The script has worked well for me and retrieves the highest resolution version available for the videos that I have needed.

Now I've come across a 4K YouTube video, and my script only saves an mp4 with 1280x720.

I'd like to know if there is a way to adjust my current script to download higher resolution versions of this video. I understand there are python packages that might address this, but right now I would like stick to this step-by-step method if possible.

above: info from Quicktime and OSX

```<code>"""
length:   175 seconds
quality:  hd720
type:     video/mp4; codecs="avc1.64001F, mp4a.40.2"
Last-Modified: Sun, 21 Aug 2016 10:41:48 GMT
Content-Type: video/mp4
Date: Sat, 01 Apr 2017 16:50:16 GMT
Expires: Sat, 01 Apr 2017 16:50:16 GMT
Cache-Control: private, max-age=21294
Accept-Ranges: bytes
Content-Length: 35933033
Connection: close
Alt-Svc: quic=":443"; ma=2592000
X-Content-Type-Options: nosniff
Server: gvs 1.
"""

import urlparse, urllib2

vid        = "vzS1Vkpsi5k"
save_title = "YouTube SpaceX - Booster Number 4 - Thaicom 8 06-06-2016"
url_init   = "https://www.youtube.com/get_video_info?video_id=" + vid

resp = urllib2.urlopen(url_init, timeout=10)
data = resp.read()
info =  urlparse.parse_qs(data)
title = info['title']

print "length:  ", info['length_seconds'][0] + " seconds"

stream_map   = info['url_encoded_fmt_stream_map'][0]
vid_info     = stream_map.split(",")

mp4_filename = save_title + ".mp4"

for video in vid_info:
    item = urlparse.parse_qs(video)

    print 'quality: ', item['quality'][0]
    print 'type:    ', item['type'][0]

    url_download  = item['url'][0]
    resp          = urllib2.urlopen(url_download)

    print resp.headers

    length  = int(resp.headers['Content-Length'])
    my_file = open(mp4_filename, "w+")

    done, i = 0, 0
    buff    = resp.read(1024)
    while buff:

        my_file.write(buff)
        done += 1024
        percent = done * 100.0 / length
        buff = resp.read(1024)

        if not i%1000:
            percent = done * 100.0 / length
            print str(percent) + "%"

        i += 1
    break
</code>```

答:
indeed
info ['adaptive_fmts'] [0]
returns the information of the whole video, but the url is not usable directly , but the bar of advancement</p>

ContentLicense: CC BY-SA 3.0

Body:
I've been using the script below to download technical videos for later analysis. The script has worked well for me and retrieves the highest resolution version available for the videos that I have needed.

Now I've come across a 4K YouTube video, and my script only saves an mp4 with 1280x720.

I'd like to know if there is a way to adjust my current script to download higher resolution versions of this video. I understand there are python packages that might address this, but right now I would like stick to this step-by-step method if possible.

above: info from Quicktime and OSX

"""
length:   175 seconds
quality:  hd720
type:     video/mp4; codecs="avc1.64001F, mp4a.40.2"
Last-Modified: Sun, 21 Aug 2016 10:41:48 GMT
Content-Type: video/mp4
Date: Sat, 01 Apr 2017 16:50:16 GMT
Expires: Sat, 01 Apr 2017 16:50:16 GMT
Cache-Control: private, max-age=21294
Accept-Ranges: bytes
Content-Length: 35933033
Connection: close
Alt-Svc: quic=":443"; ma=2592000
X-Content-Type-Options: nosniff
Server: gvs 1.
"""

import urlparse, urllib2

vid        = "vzS1Vkpsi5k"
save_title = "YouTube SpaceX - Booster Number 4 - Thaicom 8 06-06-2016"
url_init   = "https://www.youtube.com/get_video_info?video_id=" + vid

resp = urllib2.urlopen(url_init, timeout=10)
data = resp.read()
info =  urlparse.parse_qs(data)
title = info['title']

print "length:  ", info['length_seconds'][0] + " seconds"

stream_map   = info['url_encoded_fmt_stream_map'][0]
vid_info     = stream_map.split(",")

mp4_filename = save_title + ".mp4"

for video in vid_info:
    item = urlparse.parse_qs(video)

    print 'quality: ', item['quality'][0]
    print 'type:    ', item['type'][0]

    url_download  = item['url'][0]
    resp          = urllib2.urlopen(url_download)

    print resp.headers

    length  = int(resp.headers['Content-Length'])
    my_file = open(mp4_filename, "w+")

    done, i = 0, 0
    buff    = resp.read(1024)
    while buff:

        my_file.write(buff)
        done += 1024
        percent = done * 100.0 / length
        buff = resp.read(1024)

        if not i%1000:
            percent = done * 100.0 / length
            print str(percent) + "%"

        i += 1
    break


问:
sprintf string manupulation not working correctly in loadrunner
I am building a queryString like this:

```<code>#include <stdio.h>

int main()
{
    char filters[300];
    char logicalAnd[5] = " and ";
    char orderNumberFilter[55];
    char punchOrderFilter[50];
    char jobsiteFilter[50];
    char frenteFilter[50];
    char statusFilter[23];

    char orderNumber[] = "pedidos";
    char punchOrder[] = "123456789";
    char jobsite[] = "65119415";
    char frente[] = "65119415";
    char status[] = "B";

    sprintf(orderNumberFilter, "OrderNum eq '%s'", orderNumber);
    sprintf(punchOrderFilter, "PurchOrder eq '%s'", punchOrder);
    sprintf(jobsiteFilter, "Jobsite eq '%s'", jobsite);
    sprintf(frenteFilter, "Frente eq '%s'", frente);
    sprintf(statusFilter, "Status eq '%s'", status);

    sprintf(filters, "%s%s%s%s%s%s", "&$filter=", orderNumberFilter, logicalAnd, punchOrderFilter, logicalAnd, jobsiteFilter);
    printf(filters);

    return 0;
}
</code>```

And I am getting this output using an online compiller:

```<code>&$filter=OrderNum eq 'pedidos' and PurchOrder eq '123456789' and Jobsite eq '65119415'
</code>```

But when i try the same code in loadrunner using lr_output_message("filters: %s", filters); to show the results, this is what I am getting:

```<code>&$filter=OrderNum eq 'pedidos' and &$filter=OrderNum eq 'pedidos'PurchOrder eq '123456789' and &$filter=OrderNum eq 'pedidos' and &$filter=OrderNum eq 'pedidos'PurchOrder eq '123456789'Lº¯L•¯L‹Jobsite eq '65119415'
</code>```

I also tried a basic example I saw using strcpy:

```<code>sprintf(orderNumberFilter, "OrderNum eq '%s'", orderNumber);
sprintf(punchOrderFilter, "PurchOrder eq '%s'", punchOrder);
sprintf(jobsiteFilter, "Jobsite eq '%s'", jobsite);
sprintf(frenteFilter, "Frente eq '%s'", frente);
sprintf(statusFilter, "Status eq '%s'", status);

strcpy(filters, "&$filter=");
strcpy(filters, orderNumberFilter);
strcpy(filters, logicalAnd);
strcpy(filters, punchOrderFilter);
strcpy(filters, logicalAnd);
strcpy(filters, jobsiteFilter);

lr_output_message("filters: %s", filters);
</code>```

And this is the output:

```<code>Jobsite eq '65119415'
</code>```

So... whats going on with load runnner?

*Replaced subsequents strcpy for strcat as  @Some programmer dude sugested

```<code>char filters[300];
char logicalAnd[5] = " and ";
char orderNumberFilter[55];
char punchOrderFilter[50];
char jobsiteFilter[50];
char frenteFilter[50];
char statusFilter[23];

char orderNumber[] = "pedidos";
char punchOrder[] = "123456789";
char jobsite[] = "65119415";
char frente[] = "65119415";
char status[] = "B";

sprintf(orderNumberFilter, "OrderNum eq '%s'", orderNumber);
sprintf(punchOrderFilter, "PurchOrder eq '%s'", punchOrder);
sprintf(jobsiteFilter, "Jobsite eq '%s'", jobsite);
sprintf(frenteFilter, "Frente eq '%s'", frente);
sprintf(statusFilter, "Status eq '%s'", status);

strcpy(filters, "&$filter=");
strcat(filters, orderNumberFilter);
strcat(filters, logicalAnd);
strcat(filters, punchOrderFilter);
strcat(filters, logicalAnd);
strcat(filters, jobsiteFilter);
</code>```

Here is the output:

```<code>&$filter=OrderNum eq 'pedidos' and OrderNum eq 'pedidos'PurchOrder eq '123456789' and OrderNum eq 'pedidos'Jobsite eq '65119415'
</code>```

It's closer but scrambled.

答:
You have an unterminated string in

```<code>char logicalAnd[5] = " and ";
</code>```

If you write

```<code>char logicalAnd[] = " and ";
</code>```

as you did with other string literals, the compiler will include the '\0' terminator. But you restricted the array length, and in this circumstance the compiler does not include the terminator, or issue warnings.

As it is, the behaviour is undefined when you pass what you think is a "string", but isn't, to string handling functions like strcpy and strcat.

Body:
I am building a queryString like this:

#include <stdio.h>

int main()
{
    char filters[300];
    char logicalAnd[5] = " and ";
    char orderNumberFilter[55];
    char punchOrderFilter[50];
    char jobsiteFilter[50];
    char frenteFilter[50];
    char statusFilter[23];

    char orderNumber[] = "pedidos";
    char punchOrder[] = "123456789";
    char jobsite[] = "65119415";
    char frente[] = "65119415";
    char status[] = "B";

    sprintf(orderNumberFilter, "OrderNum eq '%s'", orderNumber);
    sprintf(punchOrderFilter, "PurchOrder eq '%s'", punchOrder);
    sprintf(jobsiteFilter, "Jobsite eq '%s'", jobsite);
    sprintf(frenteFilter, "Frente eq '%s'", frente);
    sprintf(statusFilter, "Status eq '%s'", status);

    sprintf(filters, "%s%s%s%s%s%s", "&$filter=", orderNumberFilter, logicalAnd, punchOrderFilter, logicalAnd, jobsiteFilter);
    printf(filters);

    return 0;
}

And I am getting this output using an online compiller:

&$filter=OrderNum eq 'pedidos' and PurchOrder eq '123456789' and Jobsite eq '65119415'

But when i try the same code in loadrunner using lr_output_message("filters: %s", filters); to show the results, this is what I am getting:

&$filter=OrderNum eq 'pedidos' and &$filter=OrderNum eq 'pedidos'PurchOrder eq '123456789' and &$filter=OrderNum eq 'pedidos' and &$filter=OrderNum eq 'pedidos'PurchOrder eq '123456789'Lº¯L•¯L‹Jobsite eq '65119415'

I also tried a basic example I saw using strcpy:

sprintf(orderNumberFilter, "OrderNum eq '%s'", orderNumber);
sprintf(punchOrderFilter, "PurchOrder eq '%s'", punchOrder);
sprintf(jobsiteFilter, "Jobsite eq '%s'", jobsite);
sprintf(frenteFilter, "Frente eq '%s'", frente);
sprintf(statusFilter, "Status eq '%s'", status);

strcpy(filters, "&$filter=");
strcpy(filters, orderNumberFilter);
strcpy(filters, logicalAnd);
strcpy(filters, punchOrderFilter);
strcpy(filters, logicalAnd);
strcpy(filters, jobsiteFilter);

lr_output_message("filters: %s", filters);

And this is the output:

Jobsite eq '65119415'

So... whats going on with load runnner?

*Replaced subsequents strcpy for strcat as  @Some programmer dude sugested

char filters[300];
char logicalAnd[5] = " and ";
char orderNumberFilter[55];
char punchOrderFilter[50];
char jobsiteFilter[50];
char frenteFilter[50];
char statusFilter[23];

char orderNumber[] = "pedidos";
char punchOrder[] = "123456789";
char jobsite[] = "65119415";
char frente[] = "65119415";
char status[] = "B";

sprintf(orderNumberFilter, "OrderNum eq '%s'", orderNumber);
sprintf(punchOrderFilter, "PurchOrder eq '%s'", punchOrder);
sprintf(jobsiteFilter, "Jobsite eq '%s'", jobsite);
sprintf(frenteFilter, "Frente eq '%s'", frente);
sprintf(statusFilter, "Status eq '%s'", status);

strcpy(filters, "&$filter=");
strcat(filters, orderNumberFilter);
strcat(filters, logicalAnd);
strcat(filters, punchOrderFilter);
strcat(filters, logicalAnd);
strcat(filters, jobsiteFilter);

Here is the output:

&$filter=OrderNum eq 'pedidos' and OrderNum eq 'pedidos'PurchOrder eq '123456789' and OrderNum eq 'pedidos'Jobsite eq '65119415'

It's closer but scrambled.

Body:
You have an unterminated string in

char logicalAnd[5] = " and ";

If you write

char logicalAnd[] = " and ";

as you did with other string literals, the compiler will include the '\0' terminator. But you restricted the array length, and in this circumstance the compiler does not include the terminator, or issue warnings.

As it is, the behaviour is undefined when you pass what you think is a "string", but isn't, to string handling functions like strcpy and strcat.


问:
React Native - Reveal modal with option to show more upon tapping it
I have a form that once completed, a Result component will slide up on the screen showing a score. There will be a TouchableHighlight on this component so that once pressed, the Result component will slide up more to reveal more details about the result. So something like below where completing the form will make my Result component appear with a button to reveal more information.

```<code>Show result
|--------------------------|
|   Result Score: 100   ^  |
|                          |
|--------------------------|
______________________________
Click on arrow to reveal more information
|--------------------------|
|   Result Score: 100      |
|                          |
|   Some more info         |
|--------------------------|
</code>```

At the moment, my result component appears by manipulating styles and changing the flex value, but this results in shrinking my form to fit the results. I was thinking if a better solution was to render a modal as it doesn't matter if form is covered by the results. I'm looking for recommendations to implement this.

答:
I have solved similar things with this layout

```<code>render {
  return (
    <View>
      <ScrollView/>
      <FooterComponent/>
    </View>
  )
}
</code>```

The footer component will receive an absolute position on the bottom of the View and the ScrollView will display the regular content.
When required, I can show the FooterComponent or even use the Animation API to slide it in.
Then you can either render a Modal to "show more" or increase the size of the FooterComponent to span the entire height.

Body:
I have a form that once completed, a Result component will slide up on the screen showing a score. There will be a TouchableHighlight on this component so that once pressed, the Result component will slide up more to reveal more details about the result. So something like below where completing the form will make my Result component appear with a button to reveal more information.

Show result
|--------------------------|
|   Result Score: 100   ^  |
|                          |
|--------------------------|
______________________________
Click on arrow to reveal more information
|--------------------------|
|   Result Score: 100      |
|                          |
|   Some more info         |
|--------------------------|

At the moment, my result component appears by manipulating styles and changing the flex value, but this results in shrinking my form to fit the results. I was thinking if a better solution was to render a modal as it doesn't matter if form is covered by the results. I'm looking for recommendations to implement this.

Body:
I have solved similar things with this layout

render {
  return (
    <View>
      <ScrollView/>
      <FooterComponent/>
    </View>
  )
}

The footer component will receive an absolute position on the bottom of the View and the ScrollView will display the regular content.
When required, I can show the FooterComponent or even use the Animation API to slide it in.
Then you can either render a Modal to "show more" or increase the size of the FooterComponent to span the entire height.


问:
REST API from mobile app - Does securing the first call with a CAPTCHA make sense?
Let's say I have an iOS/Android app which rely on a custom REST API for things such as account management (register, login, password reset, get/set user-related data).

There is no good way to guarantee my API is only called from my mobile application. Oauth2 and the like with 'secret' in the client code - can be easily reverse-engineered.

Let's say I have an API call like this:

https://www.myapi.com/register_user?username=UUU&password=PPP&email=EEE

(of course, not exactly like that but you get the idea)

This create a new user and from then all API calls will either include a session-token or something that ties the API call to a specific app user with an account.

This first registration call is the only one that is not protected by anything and what I'm worried about is that a malicious person calls it 1,000,000 times from a PC script to create lots of fake users, especially with real email addresses. People with these addresses won't be able to use the app.

So How to protect that very first API call to prevent mass misuse? I'm thinking of including a server-validated mobile-friendly CAPTCHA in the user registration form.

Again, all subsequent API calls are protected with session-token and API-call-count monitored per user (suspicious ones are blocked).

Does that make sense? Am I over-complicating things? Many Thanks

PS: It seems other interesting alternatives include using email-validation or a solid third-party identity provider like Google and the like - None of these 3 options is perfect. Anyway, interested in the discussion around this issue.

答:
I suggest CAPTCHA to be a second level of protection to be turned on when you're seeing registration abuse. There are a couple of different angles here:

1. Does your app need this protection at all?

Unless you're assigning expensive resources right away when the account is requested, all that's happening is that a bunch of database records are being created. If you are allocating resources immediately, then you need to change the onboarding flow so that users are given those only after they legitimately verify their emails and login to the app. You can separately institute a clean-up job, so that all requests that have not been activated within a reasonable period (maybe two weeks?) are deleted from the DB.

2. Do you have any real-time monitoring of registrations?

If you can stay on top of the registration API calls, you can prevent most of the abuse attempts. Most of the time, you're trying to improve on the number of new users that are signing up. With monitoring/alerting, you can take defensive actions when the signup behavior starts looking suspicious. For example:

Sudden major spike in API calls without any trigger from your end (like new marketing campaigns or a blog post)

Too many registration attempts from a single IP or IP range

Observing the same values in the HTTP request header (assuming here the API call your app makes passes along some client-specific values and does not use a static request header)

3. Abuse prevention options

As I said in the beginning, CAPTCHA can be a second level where the first level is to have a throttling feature for the registration requests. With each new registration attempt from the same IP, you can exponentially take a longer time to respond. After too many attempts are observed and the response time is already long enough, you can start asking for the CAPTCHA.

Hopefully at this stage, you have abuse under control. But also be prepared to start blocking/temporarily banning API calls if CAPTCHA does not give the result you expect.

BTW, this and most other anti-abuse features will benefit from being able to configure your service on-the-fly, to play with different values/options while observing and analyzing the effects.


问:
Importing a SparkSession DataFrame on DSX
I'm currently working on Data Science Experience and would like to import a CSV file as a SparkSession DataFrame. I am able to successfully import the DataFrame, however, all of the column attributes are converted to string type. How do you make this DSX feature recognize the types present in the CSV file?  </p>

答:
Currently, the generated code for the actual creation of the pyspark.sql.DataFrame looks like this:

```<code>df_data_1 = spark.read\
  .format('org.apache.spark.sql.execution.datasources.csv.CSVFileFormat')\
  .option('header', 'true')\
  .load('swift://container_name.' + name + '/test.csv')
df_data_1.take(5)
</code>```

You have to add the the following options, then the schema will be inferred:

```<code>.option(inferschema='true')\
</code>```

Body:
Currently, the generated code for the actual creation of the pyspark.sql.DataFrame looks like this:

df_data_1 = spark.read\
  .format('org.apache.spark.sql.execution.datasources.csv.CSVFileFormat')\
  .option('header', 'true')\
  .load('swift://container_name.' + name + '/test.csv')
df_data_1.take(5)

You have to add the the following options, then the schema will be inferred:

.option(inferschema='true')\


问:
Function object called via class attribute fails
I currently have a system of classes that register callbacks and then call them when certain conditions are met. However I am running into some problems storing the function object.

A:

```<code>class Foo(object):
  _callback = None

  @classmethod
  def Register(cls, fn):
    cls._callback = fn

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback()
</code>```

```<code>input clear Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux

Traceback (most recent call last):   File "python", line 12, in <module>
TypeError: unbound method Bar() must be called with Foo instance as first argument (got nothing instead)
</code>```

I am not sure why it requires a Foo instance when the function is not a member of Foo.

B:

```<code>class Foo(object):
  _callback = []

  @classmethod
  def Register(cls, fn):
    cls._callback.append(fn)

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback[0]()
</code>```

Why does the first version not work while the second version does? What functionality differs when adding it to a list instead.

答:
.Assigning it is just adding it to the classes __dict__ which stores the references of the bound and unbound methods (ie functions). So, by doing this your just adding another reference to an unbound function which is expecting an instance as its first argument.

Here's an easier example:

```<code>class Foo:
    test = lambda x: x

Foo.test("Hello world!")
</code>```

Error:

```<code>unbound method <lambda>(): must be called....
</code>```

Body:
I currently have a system of classes that register callbacks and then call them when certain conditions are met. However I am running into some problems storing the function object.

A:

class Foo(object):
  _callback = None

  @classmethod
  def Register(cls, fn):
    cls._callback = fn

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback()

input clear Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux

Traceback (most recent call last):   File "python", line 12, in <module>
TypeError: unbound method Bar() must be called with Foo instance as first argument (got nothing instead)

I am not sure why it requires a Foo instance when the function is not a member of Foo.

B:

class Foo(object):
  _callback = []

  @classmethod
  def Register(cls, fn):
    cls._callback.append(fn)

def Bar():
  print "Called"

Foo.Register(Bar)
Foo._callback[0]()

Why does the first version not work while the second version does? What functionality differs when adding it to a list instead.

Body:
.Assigning it is just adding it to the classes __dict__ which stores the references of the bound and unbound methods (ie functions). So, by doing this your just adding another reference to an unbound function which is expecting an instance as its first argument.

Here's an easier example:

class Foo:
    test = lambda x: x

Foo.test("Hello world!")

Error:

unbound method <lambda>(): must be called....


问:
How to set the flag BUILD_ONLY for multiple modules?
I am trying to build only certain modules, e.g. s2, dynamodb, and cognito from the source code.  I use various settings to pass to cmake but none works.

-DBUILD_ONLY=s3 -DBUILD_ONLY=dynamodb -DBUILD_ONLY=cognito. (Only the last one gets built.)

-DBUILD_ONLY=s3,dynamodb,cognito. (Unrecognized module because the whole string is treaded as module name)

-DBUILD_ONLY="s3 dynamodb cognito" (Same error.)

Body: -DBUILD_ONLY="service1;service2;service3"


问:
Linux -> C++ code : Object Serialization
What library should I use for an object serialization that is the input for an .net webservice (meaning that this webservice needs an xml at its input)?

As a further question:

If using Non Intrusive Version (Boot Serialization), when writing in the xml file what is the exactly code? (oa<< ?). I've tried some solutions but it seems I have error. I can't actually say oa<< g. .

Here is the code:

```<code>#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <dlfcn.h>
#include <iostream>
#include <fstream>

class gps_position
{
public:
    int degrees;
    int minutes;
    float seconds;
    gps_position(){};
};

namespace boost { namespace serialization {

    template<class Archive>
    void serialize(Archive & ar, gps_position & g, const unsigned int version)
    {
        ar & g.degrees;
        ar & g.minutes;
        ar & g.seconds;
    }

} } // namespace boost::serialization

// gps_position g;

int main() {

    gps_position obj;
    std::ofstream ofs("filename2.xml");

    if(ofs.good()) {
        //const gps_position g;

        try {
            boost::archive::xml_oarchive oa(ofs);

            // what to write in the xml?
            oa << ??????????????????;

        } catch(boost::archive::archive_exception& ex) {

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

答:
Boost Serialization will serialize C++ objects into an XML stream. I don't know if it will automatically be compatible with your webservice or not though.

Answer to comment:
Here is an example:

```<code>#include <boost/serialization/vector.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <fstream>

class myclass
{
    //...
private:
    int var1;
    double var2;
    std::vector<int> var3;

    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(var1);
        ar & BOOST_SERIALIZATION_NVP(var2);
        ar & BOOST_SERIALIZATION_NVP(var3);
    }
};

//...

myclass myobject;

//...

ofstream ofs("filename.xml");
if(ofs.good()) {
    try {
        boost::archive::xml_oarchive oa(ofs);
        oa << BOOST_SERIALIZATION_NVP(myobject);
    }catch(boost::archive::archive_exception& ex){
        //...
    }
}
</code>```

Basically inside your class you need to make boost::serialization::access a friend and provide the member function serialize.  Some tricks are played here with overloading the & operator to act as a stream operator in different directions depending on whether you are saving or loading.  For most classes, just follow this pattern though for all the member variables and don't worry about what is actually happening (read the docs if you want to know).

To actually serialize the object, you just stream it to an xml_oarchive object that can be instantiated to write to any ostream object.

ContentLicense: CC BY-SA 2.5

Body:
What library should I use for an object serialization that is the input for an .net webservice (meaning that this webservice needs an xml at its input)?

As a further question:

If using Non Intrusive Version (Boot Serialization), when writing in the xml file what is the exactly code? (oa<< ?). I've tried some solutions but it seems I have error. I can't actually say oa<< g. .

Here is the code:

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <dlfcn.h>
#include <iostream>
#include <fstream>

class gps_position
{
public:
    int degrees;
    int minutes;
    float seconds;
    gps_position(){};
};

namespace boost { namespace serialization {

    template<class Archive>
    void serialize(Archive & ar, gps_position & g, const unsigned int version)
    {
        ar & g.degrees;
        ar & g.minutes;
        ar & g.seconds;
    }

} } // namespace boost::serialization

// gps_position g;

int main() {

    gps_position obj;
    std::ofstream ofs("filename2.xml");

    if(ofs.good()) {
        //const gps_position g;

        try {
            boost::archive::xml_oarchive oa(ofs);

            // what to write in the xml?
            oa << ??????????????????;

        } catch(boost::archive::archive_exception& ex) {

        }
    }
    return 0;
}

Body:
Boost Serialization will serialize C++ objects into an XML stream. I don't know if it will automatically be compatible with your webservice or not though.

Answer to comment:
Here is an example:

#include <boost/serialization/vector.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <fstream>

class myclass
{
    //...
private:
    int var1;
    double var2;
    std::vector<int> var3;

    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(var1);
        ar & BOOST_SERIALIZATION_NVP(var2);
        ar & BOOST_SERIALIZATION_NVP(var3);
    }
};

//...

myclass myobject;

//...

ofstream ofs("filename.xml");
if(ofs.good()) {
    try {
        boost::archive::xml_oarchive oa(ofs);
        oa << BOOST_SERIALIZATION_NVP(myobject);
    }catch(boost::archive::archive_exception& ex){
        //...
    }
}

Basically inside your class you need to make boost::serialization::access a friend and provide the member function serialize.  Some tricks are played here with overloading the & operator to act as a stream operator in different directions depending on whether you are saving or loading.  For most classes, just follow this pattern though for all the member variables and don't worry about what is actually happening (read the docs if you want to know).

To actually serialize the object, you just stream it to an xml_oarchive object that can be instantiated to write to any ostream object.


问:
Send values through a PHP-script with Arduino
I am trying to get my Arduino With Ethernet Shield to call a PHP script. The domain is like this: sub.domain.com and the script I want to call is like this script.php?value1=value&somevalue2=somevalue&value3=somevalue.

I tried making it work with the example that comes with the Arduino library, but I was not successful.

```<code>EthernetClient ethClient;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEF };
char server[] = "sub.domain.com";

void setup() {
    [...]
    if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
    }

    [...]
}

void loop() {
    [...]
  if (ethClient.connect(server, 80)) {
    Serial.println("Conected to: " + String(server));
    String getUrl = "/script.php?location=" + String(LOCATIONID) + "&sc=2&feedP=" + String(feedBar) + "&returnP=" + String(returnBar) ;
    Serial.println(getUrl);
    // Make a HTTP request:
    ethClient.println("GET " + getUrl + " HTTP/1.1");
    ethClient.println("Host: sub.domain.com");
    ethClient.println("Connection: close");
    ethClient.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("Could not connect to: " + String(server));
  }

if (ethClient.available()) {
  char c = ethClient.read();
  Serial.println("Respons: ");
  Serial.print(c);
}
    [...]
}
</code>```

答: It works when not using a subdomain.</p>

Body:
I am trying to get my Arduino With Ethernet Shield to call a PHP script. The domain is like this: sub.domain.com and the script I want to call is like this script.php?value1=value&somevalue2=somevalue&value3=somevalue.

I tried making it work with the example that comes with the Arduino library, but I was not successful.

EthernetClient ethClient;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEF };
char server[] = "sub.domain.com";

void setup() {
    [...]
    if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
    }

    [...]
}

void loop() {
    [...]
  if (ethClient.connect(server, 80)) {
    Serial.println("Conected to: " + String(server));
    String getUrl = "/script.php?location=" + String(LOCATIONID) + "&sc=2&feedP=" + String(feedBar) + "&returnP=" + String(returnBar) ;
    Serial.println(getUrl);
    // Make a HTTP request:
    ethClient.println("GET " + getUrl + " HTTP/1.1");
    ethClient.println("Host: sub.domain.com");
    ethClient.println("Connection: close");
    ethClient.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("Could not connect to: " + String(server));
  }

if (ethClient.available()) {
  char c = ethClient.read();
  Serial.println("Respons: ");
  Serial.print(c);
}
    [...]
}

Body: It works when not using a subdomain.


问:
Vim select the ends of multiple lines (block mode, but where the ending column varies)
Is there any way in vim that I can select the end of all these lines? (I'm only showing the end of the lines in these screenshots).

In block mode I can get them all if the bottom line is longer than the rest, but if the bottom line is shorter, the longer lines are truncated.

EDIT | I guess I can just pad out the bottom line with spaces before I select, then delete the spaces later.

答:
Click somewhere (anywhere) in the first line you wish to append text to.

Press Control + V.

Press Down to create an arbitrary vertical block selection that spans the desired lines.

Press $ to expand the visual block selection to the ends of every line selected.

Press Shift + A to append text to every selected line.

Type the text you want to append.

Press Escape and the text will be appended across the selected lines.


问:
How do i pass the values from html.editorfor() to my controller
This is the code generated by the Visual Studio when i added a view for my Edit function

I want to pass the values inside the <input> generated by the @Html.EditorFor() from the view to my controller.

How can i access those values? Can i do it without manually declaring textboxes via <input class="form-control text-box single-line" id="Surname" name="Surname" type="text"> ?

```<code>@using (Html.BeginForm("Save","my",FormMethod.Post)){
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>User</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @Value=Model.Name, @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
    }
</code>```

答:
UPDATE

found the answer, i simply needed to pass this code as an argument in my function inside the controller that would create an object User with properties inside Include

public string Submit ([Bind(Include = "Name")] User user){
}

Body:
This is the code generated by the Visual Studio when i added a view for my Edit function

I want to pass the values inside the <input> generated by the @Html.EditorFor() from the view to my controller.

How can i access those values? Can i do it without manually declaring textboxes via <input class="form-control text-box single-line" id="Surname" name="Surname" type="text"> ?

@using (Html.BeginForm("Save","my",FormMethod.Post)){
    @Html.AntiForgeryToken()

User

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Id)

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @Value=Model.Name, @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                <input type="submit" value="Save" class="btn btn-default" />

    }


问:
C# DAL returing generic List<T>
Could I return List  from my DAL ?, In internet I read somewhere that it's not good.
What is the problem if return List ?</p>

答:
In principle, there's no problem with returning List<T>, however a common problem is when classes return a member List<T> variable which violates encapsulation e.g.

```<code>public class SomeClass<T>
{
    public List<T> Items { get; private set; }
    public void DoSomething()
    {
        T first = Items[0];
        ...
    }
}
</code>```

In this case, any clients of this class can modify its state which could lead to bugs since the class can no longer protect its invariants. Note that returning IList<T> in this case will not help.

For a data access object however, it will (hopefully) not retain the results of any queries, so a new copy of the list will be returned each time and it will not be affected by the modifications of any clients.

Title: C# DAL returing generic List<T>

Body:
In principle, there's no problem with returning List<T>, however a common problem is when classes return a member List<T> variable which violates encapsulation e.g.

public class SomeClass<T>
{
    public List<T> Items { get; private set; }
    public void DoSomething()
    {
        T first = Items[0];
        ...
    }
}

In this case, any clients of this class can modify its state which could lead to bugs since the class can no longer protect its invariants. Note that returning IList<T> in this case will not help.

For a data access object however, it will (hopefully) not retain the results of any queries, so a new copy of the list will be returned each time and it will not be affected by the modifications of any clients.


答:
Whenever you assign a function to a class object, it becomes a method:

```<code>In [6]: Foo.baz = lambda self: 'baz'

In [7]: f = Foo()

In [8]: f.baz()
Out[8]: 'baz'
</code>```

Note, this means you can dynamically add methods to classes, which will be visible on instantiated objects!

```<code>In [9]: Foo.anothermethod = lambda self, x: x*2

In [10]: f.anothermethod(4)
Out[10]: 8
</code>```

From the docs:

If you still don’t understand how methods work, a look at the
  implementation can perhaps clarify matters. When an instance attribute
  is referenced that isn’t a data attribute, its class is searched. If
  the name denotes a valid class attribute that is a function object, a
  method object is created by packing (pointers to) the instance object
  and the function object just found together in an abstract object:
  this is the method object. When the method object is called with an
  argument list, a new argument list is constructed from the instance
  object and the argument list, and the function object is called with
  this new argument list.

Title: Function object called via class attribute fails

Body:
Whenever you assign a function to a class object, it becomes a method:

In [6]: Foo.baz = lambda self: 'baz'

In [7]: f = Foo()

In [8]: f.baz()
Out[8]: 'baz'

Note, this means you can dynamically add methods to classes, which will be visible on instantiated objects!

In [9]: Foo.anothermethod = lambda self, x: x*2

In [10]: f.anothermethod(4)
Out[10]: 8

From the docs:

If you still don’t understand how methods work, a look at the
  implementation can perhaps clarify matters. When an instance attribute
  is referenced that isn’t a data attribute, its class is searched. If
  the name denotes a valid class attribute that is a function object, a
  method object is created by packing (pointers to) the instance object
  and the function object just found together in an abstract object:
  this is the method object. When the method object is called with an
  argument list, a new argument list is constructed from the instance
  object and the argument list, and the function object is called with
  this new argument list.


问:
Xamarin iOS Launch Screen Image In Storyboard Not Pulling From Asset Catalog
I'm using Visual Studio 2017 and the latest Xamarin iOS 10.10.0.30. I've tried following the documentation for creating a launch screen storyboard. I created all the launch screen images add added them in the Media tool under Asset Catalogs (both AppIcons and LaunchImages).

I'd prefer to just use these static images instead of creating a storyboard, but that doesn't seem to be an option. So, when creating the view for Resources\LaunchScreen.storyboard, I add an Image View and go to properties and to the Image drop down. The images in the asset catalog are not listed in the drop down, but the Xamarin images in the Resources folder are listed.  Something does not make sense.

Can we not use the LaunchImages from the asset catalog in Visual Studio? If we have to use a storyboard, how do we get it to select the right image for the device it is starting on?

答: It seems I am able to use the asset catalog launch images if I edit the info.plist in an XML editor and remove the UILaunchStoryboardName key.  When I open it in the Manifest Editor it still says LaunchScreen....not sure what is with these settings.</p>


问:
Scalable architecture design for social networking apps
I want to design and architect a scalable app that will be a combination of a social blog with all admin and blogging features plus the app will also have course broadcasting like coursera and udemy.

What technologies should I look into:
I have studied some LAMP and MEAN stack based apps but got more confused in choosing the tech stack.
should I use a standard solution like BuddyPress or some other WordPress based stuff or should I design it from scratch?
How do I divide it component wise so that's it scalable and highly modular?

Are there any references or some pre-made solutions or documentations or design patterns because whatever I am planning to work has already been done.

答:
It depends on what do you wanna achieve.

For example, you have these ways for architecture:

A whole APP in one server.

Microservices, distributed parts of your app.

Serverless (Backend as service).

About apps, you already said it:

If you choose to create something from scratch, you can control the architecture and services that your app need in order to work at 100%.

If you choose APPs like Wordpress, Vanilla Forums and similar (APPs that you will have to install that you didn't create and perhaps you will end creating modules that solve problems that you have).

What else?

Do you have time to create something from scratch?

Do you have the money to create something from scratch?

Does premade software like Wordpress fulfill all your requirements?

To be honest, if you have the money and time you can choose whatever you want.

But if time is important, well, choose something premade like Wordpress and similar solutions.

Once you answer those questions we will be able to help you with more details.


问:
Is it possible to drag and drop events into a row with an existing event in fullcalendar?
I'm currently working a hotel booking using fullcalendar and it seems that full calendar can't drop events into a row that has existing events( that's what I've learn so far ).But if there are ways to do it, then please tell me.</p>

答:
eventOverlap: true //
Allow you to drop more than one event in the period.

selectOverlap: true
//Allow you to select over other event.


问:
How to analyze a Python code's performance?
Regards. To analyze Python code's performance, may the code below does it?

```<code>import time

to = time.clock(); x = [];
for i in range(0,4):
    x.append(i*0.1);
tend = time.clock(); print(tend-to);

to = time.clock();
y = list(map(lambda x: x*0.1, list(range(0,4))));
tend = time.clock(); print(tend-to);
</code>```

The timers show inconsistency. But sometimes, the result of the two timers also shows inconsistency (sometimes the first timer is faster, sometimes the second one is, although the first one tends to be faster). Some outputs :

```<code>4.631622925399206e-05
4.4898385501326854e-05

4.9624531343562917e-05
6.852911471254275e-05

5.0569760512011734e-05
4.867930217511418e-05

3.78091667379527e-05
2.5993802132341648e-05
</code>```

My question pertain to the code above :

I thought timer to calculate a code performance should be consistent? How to know that a syntax or a tactic performs better than the other? (run more efficiently than the other) Any thoughts on this?

Thanks before. Regards, Arief

答:
From the official documentation:

```<code>>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.3018611848820001
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.2727368790656328
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.23702679807320237
</code>```

In other words: if we strive to talk about a precision in execution time measurements - we restricted to iterate a simple function several thousands times to elicit all side effects.

Body:
Regards. To analyze Python code's performance, may the code below does it?

import time

to = time.clock(); x = [];
for i in range(0,4):
    x.append(i*0.1);
tend = time.clock(); print(tend-to);

to = time.clock();
y = list(map(lambda x: x*0.1, list(range(0,4))));
tend = time.clock(); print(tend-to);

The timers show inconsistency. But sometimes, the result of the two timers also shows inconsistency (sometimes the first timer is faster, sometimes the second one is, although the first one tends to be faster). Some outputs :

4.631622925399206e-05
4.4898385501326854e-05

4.9624531343562917e-05
6.852911471254275e-05

5.0569760512011734e-05
4.867930217511418e-05

3.78091667379527e-05
2.5993802132341648e-05

My question pertain to the code above :

I thought timer to calculate a code performance should be consistent? How to know that a syntax or a tactic performs better than the other? (run more efficiently than the other) Any thoughts on this?

Thanks before. Regards, Arief

Body:
From the official documentation:

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.3018611848820001
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.2727368790656328
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.23702679807320237

In other words: if we strive to talk about a precision in execution time measurements - we restricted to iterate a simple function several thousands times to elicit all side effects.


答:
When you assign Bar to cls._callback, _callback becomes automatically an unbound method of Foo (since it is a function).

Therefore, when called, it is expected to get the instance as its first argument, resulting in failure in cases where it is passed nothing (expects instance) or passed an instance (Bar supports 0 arguments).

However, if you append Bar to a list instead, and then access the list element, you have the normal-old-good Bar ready for use without any bounding conventions hurting it - because it is merely conserved as an object, not a bound method.


问:
Can Symfony be deployed with a hot but read-only cache?
Symfony2 requires that its cache is writable by the process under which it runs, even in production.  However, malicious alteration of that cache could lead to arbitrary code execution and/or arbitrary changes to one's application (and accidental corruption thereof could lead to software failure).

Surely it's good practice to enforce restrictions in the OS that prevent any compromise of public-facing systems from escalating to such arbitrary degrees?

One thought is to deploy a hot but read-only cache of executable code (which is usually static anyway), so that the production system cannot modify it thereafter; dynamic data, e.g. from Doctrine, could still be cached somewhere writable—but it would never be evaluated for code execution.

Is this a supported configuration?  If so, how?  Or am I being overly paranoid?

答:
I've been working on this as well. This becomes a lot more feasible in Symfony 3.3 because the filecache finally supports relative filepaths and dynamic environment variables (in the container).

Try the following and see if it works for you:

```<code># locally
$ app/console cache:clear --no-debug --env=dev
$ app/console cache:warmup --no-debug --env=dev

# for production
$ app/console cache:clear --no-debug --env=prod
$ app/console cache:warmup --no-debug --env=prod
</code>```

Body:
I've been working on this as well. This becomes a lot more feasible in Symfony 3.3 because the filecache finally supports relative filepaths and dynamic environment variables (in the container).

Try the following and see if it works for you:

# locally
$ app/console cache:clear --no-debug --env=dev
$ app/console cache:warmup --no-debug --env=dev

# for production
$ app/console cache:clear --no-debug --env=prod
$ app/console cache:warmup --no-debug --env=prod


问:
Use hidden SFSafariViewController to get Safari cookies
I was reading the following post on authenticating users from mobile web pages to native iOS 9 apps and was wondering how to best implement a hidden safari view controller similar to the hidden controller talked about below?

https://library.launchkit.io/how-ios-9-s-safari-view-controller-could-completely-change-your-app-s-onboarding-experience-2bcf2305137f#.r810oldla

答:
This has changed in iOS 11. Going forward, every app (including Safari itself) will have a completely sandboxed data store. Official announcement here (at the 17:28 mark).

Long live the invisible SFSafariViewController. iOS 9 to iOS 10.

If you need a way to pass a guaranteed user match through from Safari to your app, you'll need to use an existing network of device matches, such as Branch.io (full disclosure: I'm on the Branch team). You can read about the techniques Branch uses instead of cookie passthrough here.


问:
Regex split fails at cyrillic string
I need a simple and easy way to isolate words from strings of different languages. I know this is not a trivial task, but I just want to split on common punctuation like .,;:?!@#. Currently I'm using:

```<code>x = "this is sparta, or not."
print re.split([^-\w]', x)
['this', 'is', 'sparta', '', 'Or', 'not', '']
</code>```

But, when I use a Cyrillic string:

```<code>x =  u'правил произношение суффиксов можно иногда'
w = re.split(r'[^-\w]', x)
</code>```

I get:

```<code>[u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'']
</code>```

How can I make a single generic splitter, which solves this problem? Thank you!

EDIT: The issue above is on Python 2.7.10.

答:
Try this:

```<code>re.split(r'\W', x, flags=re.UNICODE)
</code>```

It worked for me on 2.7.13.

Title: Regex split fails at cyrillic string

Body:
I need a simple and easy way to isolate words from strings of different languages. I know this is not a trivial task, but I just want to split on common punctuation like .,;:?!@#. Currently I'm using:

x = "this is sparta, or not."
print re.split([^-\w]', x)
['this', 'is', 'sparta', '', 'Or', 'not', '']

But, when I use a Cyrillic string:

x =  u'правил произношение суффиксов можно иногда'
w = re.split(r'[^-\w]', x)

I get:

[u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'', u'']

How can I make a single generic splitter, which solves this problem? Thank you!

EDIT: The issue above is on Python 2.7.10.

Body:
Try this:

re.split(r'\W', x, flags=re.UNICODE)

It worked for me on 2.7.13.


问:
nix-build: bash permission denied
I'm trying to learn to write Nix expressions, and I thought about doing my own very simple "Hello World!" (as is tradition).

So I have my dir with only this default.nix file :

```<code>{pkgs ? import <nixpkgs> {}}:
derivation {
    system = "x86_64-linux";
    name = "simple-bash-derivation-helloworld";
    builder = pkgs.bash;
    args = [ "-c" "echo 'Hello World' > $out" ];
}
</code>```

Here is what I get when I try to build it:

```<code>nix-build
these derivations will be built:
  /nix/store/3grmahx3ih4c50asj84p7xnpqpj32n5s-simple-bash-derivation-helloworld.drv
building path(s) ‘/nix/store/6psl3rc92311w37c1n6nj0a6jac16hv1-simple-bash-derivation-helloworld’
while setting up the build environment: executing ‘/nix/store/wb34dgkpmnssjkq7yj4qbjqxpnapq0lw-bash-4.4-p12’: Permission denied
builder for ‘/nix/store/3grmahx3ih4c50asj84p7xnpqpj32n5s-simple-bash-derivation-helloworld.drv’ failed with exit code 1
error: build of ‘/nix/store/3grmahx3ih4c50asj84p7xnpqpj32n5s-simple-bash-derivation-helloworld.drv’ failed
</code>```

Removing the args line yields the same issue.

Why do I get a permission issue?
What would be the correct way to make a simple derivation just doing a bash echo?

Please note that this is a learning exercise: I do not want to use stdenv.mkDerivation here for example.

I am running nix-env (Nix) 1.11.9 on an Ubuntu 16.04 system.

Thanks in advance.

答:
Try running ls command on /nix/store/wb34dgkpmnssjkq7yj4qbjqxpnapq0lw-bash-4.4-p12 and you will see it's a directory rather than an executable file (pointing to $out of the pkgs.bash derivation). If you wanted to refer to bash binary you would use:

```<code>builder = "${pkgs.bash}/bin/bash";
</code>```

Title: nix-build: bash permission denied

Body:
I'm trying to learn to write Nix expressions, and I thought about doing my own very simple "Hello World!" (as is tradition).

So I have my dir with only this default.nix file :

{pkgs ? import <nixpkgs> {}}:
derivation {
    system = "x86_64-linux";
    name = "simple-bash-derivation-helloworld";
    builder = pkgs.bash;
    args = [ "-c" "echo 'Hello World' > $out" ];
}

Here is what I get when I try to build it:

nix-build
these derivations will be built:
  /nix/store/3grmahx3ih4c50asj84p7xnpqpj32n5s-simple-bash-derivation-helloworld.drv
building path(s) ‘/nix/store/6psl3rc92311w37c1n6nj0a6jac16hv1-simple-bash-derivation-helloworld’
while setting up the build environment: executing ‘/nix/store/wb34dgkpmnssjkq7yj4qbjqxpnapq0lw-bash-4.4-p12’: Permission denied
builder for ‘/nix/store/3grmahx3ih4c50asj84p7xnpqpj32n5s-simple-bash-derivation-helloworld.drv’ failed with exit code 1
error: build of ‘/nix/store/3grmahx3ih4c50asj84p7xnpqpj32n5s-simple-bash-derivation-helloworld.drv’ failed

Removing the args line yields the same issue.

Why do I get a permission issue?
What would be the correct way to make a simple derivation just doing a bash echo?

Please note that this is a learning exercise: I do not want to use stdenv.mkDerivation here for example.

I am running nix-env (Nix) 1.11.9 on an Ubuntu 16.04 system.

Thanks in advance.

Body:
Try running ls command on /nix/store/wb34dgkpmnssjkq7yj4qbjqxpnapq0lw-bash-4.4-p12 and you will see it's a directory rather than an executable file (pointing to $out of the pkgs.bash derivation). If you wanted to refer to bash binary you would use:

builder = "${pkgs.bash}/bin/bash";


问:
Selenium cannot find element by text via xpath
I am trying to click on some text that is inside of a menu item (I can't use the menu item's id since it's an asp.net webforms menu that has no client ids, thus the ids are unreliable).  Inside the table cell there is

```<code><nobr>Revenue Object Maintenance</nobr>
</code>```

However, if I do:

```<code>selenium.Click("xpath=//nobr[text()='Revenue Object Maintenance'");
</code>```

Selenium errors out:

```<code>ERROR: Invalid xpath [3]: XPath parse error //nobr[text()='Revenue Object Maintenance'
</code>```

How can I click on this nobr instance?

答:
if I do:

```<code>selenium.Click("xpath=//nobr[text()='Revenue Object Maintenance'");
</code>```

Selenium errors out:

The error is obvious: you haven't closed the predicate.

This is a syntactically correct XPath expression:

```<code>//nobr[text()='Revenue Object Maintenance']
</code>```

Body:
I am trying to click on some text that is inside of a menu item (I can't use the menu item's id since it's an asp.net webforms menu that has no client ids, thus the ids are unreliable).  Inside the table cell there is

<nobr>Revenue Object Maintenance</nobr>

However, if I do:

selenium.Click("xpath=//nobr[text()='Revenue Object Maintenance'");

Selenium errors out:

ERROR: Invalid xpath [3]: XPath parse error //nobr[text()='Revenue Object Maintenance'

How can I click on this nobr instance?

Body:
if I do:

selenium.Click("xpath=//nobr[text()='Revenue Object Maintenance'");

Selenium errors out:

The error is obvious: you haven't closed the predicate.

This is a syntactically correct XPath expression:

//nobr[text()='Revenue Object Maintenance']