问:
Why do my react-native components overlap
I want to position 2 components underneath each other. My component looks like this :

```<code>import React from 'react';
import {connect} from 'react-redux';
import {Text, StyleSheet, View, ListView, Switch, TextInput} from 'react-native';
import {List, ListItem} from 'native-base';
import SearchBar from '../shared/search-bar';

const mapStateToProps = (state) => {
    return {
        movies: state.movies.movies
    };
};

const mapDispatchToProps = (dispatch) => {
    return {};
};

const Component = ({movies}) => {
    return (
        <View style={styles.container}>
            <SearchBar style={styles.searchBarContainer}/>
            <List
                style={styles.list}
                dataArray={movies}
                renderRow={movie => <ListItem><Text>{movie.title}</Text></ListItem>}
            />
        </View>
    );
};

let styles = StyleSheet.create({
    container: {
        flexDirection: 'column',
        flex: 1,
    },
    searchBarContainer: {
        flex: 0
    },
    list: {
        flex: 1
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(Component);
</code>```

For some reason, when they are rendered, the list is just rendered over the searchbar. Why does the flexDirection:'column' not position them underneath each other?

I feel like I'm missing something about the flexbox layout.

答: in your style.container, remove the flex entry but keep the flexDirection.</p>

Body:
I want to position 2 components underneath each other. My component looks like this :

import React from 'react';
import {connect} from 'react-redux';
import {Text, StyleSheet, View, ListView, Switch, TextInput} from 'react-native';
import {List, ListItem} from 'native-base';
import SearchBar from '../shared/search-bar';

const mapStateToProps = (state) => {
    return {
        movies: state.movies.movies
    };
};

const mapDispatchToProps = (dispatch) => {
    return {};
};

const Component = ({movies}) => {
    return (
        <View style={styles.container}>
            <SearchBar style={styles.searchBarContainer}/>
            <List
                style={styles.list}
                dataArray={movies}
                renderRow={movie => <ListItem><Text>{movie.title}</Text></ListItem>}
            />
        </View>
    );
};

let styles = StyleSheet.create({
    container: {
        flexDirection: 'column',
        flex: 1,
    },
    searchBarContainer: {
        flex: 0
    },
    list: {
        flex: 1
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(Component);

For some reason, when they are rendered, the list is just rendered over the searchbar. Why does the flexDirection:'column' not position them underneath each other?

I feel like I'm missing something about the flexbox layout.


来源: stackexchange

问:
Django setting TIME_ZONE in DATABASES has no effect with 'date' lookup
UPDATE April 8th, 2019

This is a known bug for django<=2.2, fixed as of this PR

=================================

(We assume the mysql backends)

I can set TIME_ZONE several times in settings.py, one for the global django app, and one for each database (see https://docs.djangoproject.com/en/1.11/ref/settings/#time-zone (ref1))

Typical usage would be for a legacy database where datetimes are not stored in UTC.

No date lookup

Querying my database takes this setting into account, e.g. :

In settings.py

```<code>USE_TZ = True
TIME_ZONE = 'Europe/Paris' # tz1
DATABASES = {
    'legacy': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '....cnf',
        },
        'TIME_ZONE': 'Europe/Paris', # tz2
    },
    'default' : {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '....cnf',
        },
    }
}
</code>```

In the manage.py shell

```<code>>>> dt = timezone.make_aware(datetime.datetime(2017, 7, 6, 20, 50))
>>> dt
datetime.datetime(2017, 7, 6, 20, 50, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
>>> MyModel.objects.filter(my_datetime_field=dt).exists()
True
</code>```

This works because my database reads '2017-07-06 20:50:00'

With date lookup

Related doc https://docs.djangoproject.com/en/1.11/ref/models/querysets/#date (ref2)

But this does not work, while it logically should

```<code>>>> MyModel.objects.filter(my_datetime_field__date=dt.date()).exists()
False*
</code>```

The related SQL query from DEBUG is :

```<code>SELECT (1) AS `a` FROM `my_model` WHERE DATE(CONVERT_TZ(`my_model`.`my_datetime_field`, 'UTC', 'Europe/Paris')) = '2017-07-06' LIMIT 1;
</code>```

(*) Note that I haven't filled the timezone table in MySQL, so the result should be True in this case, but could be False close to midnight.
Related doc is https://dev.mysql.com/doc/refman/5.7/en/mysql-tzinfo-to-sql.html

Two things are wrong. First, conversion should be from Paris to Paris, instead of UTC to Paris. The conversion should go from the database timezone tz2 to the django app one tz1.

Indeed from ref1 :

When USE_TZ is True and the database doesn’t support time zones (e.g. SQLite, MySQL, Oracle), Django reads and writes datetimes in local time according to this option if it is set and in UTC if it isn’t.

and ref2 :

When USE_TZ is True, fields are converted to the current time zone before filtering

Secondly, when tz1 == tz2, there should be no need to use CONVERT_TZ and the query will work without timezone tables in MySQL.

The explicit queries are :

```<code>mysql> SELECT (1) AS `a` FROM `my_model` WHERE `my_model`.`my_datetime_field` = '2017-07-06 20:50:00' LIMIT 1;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

mysql> SELECT (1) AS `a` FROM `my_model` WHERE DATE(`my_model`.`my_datetime_field`) = '2017-07-06' LIMIT 1;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.00 sec)
</code>```

Why is 'UTC' appearing in the query? Should it not be 'Europe/Paris'?

Am I misunderstanding something from the doc, or is it a bug?

Thank you.

EDIT : My system tz is not UTC, if this is any help

```<code>mysql> SELECT @@global.time_zone, @@session.time_zone, @@system_time_zone;
+--------------------+---------------------+--------------------+
| @@global.time_zone | @@session.time_zone | @@system_time_zone |
+--------------------+---------------------+--------------------+
| SYSTEM             | SYSTEM              | CEST               |
+--------------------+---------------------+--------------------+
</code>```

答:
From the documentation -

When USE_TZ is True and the database doesn’t support time zones (e.g. SQLite, MySQL, Oracle), Django reads and writes datetimes in local time according to this option if it is set and in UTC if it isn’t.

So, it seems (from your "I see" code) like your server timezone (= db tz = local time, since legacy) is UTC. Hence, due to your settings (USE_TZ=True & TZ=Paris) the conversion from UTC to Paris TZ is happening.

Thus, you have misunderstood the docs and it is not a bug.

ContentLicense: CC BY-SA 4.0

Body:
UPDATE April 8th, 2019

This is a known bug for django<=2.2, fixed as of this PR

=================================

(We assume the mysql backends)

I can set TIME_ZONE several times in settings.py, one for the global django app, and one for each database (see https://docs.djangoproject.com/en/1.11/ref/settings/#time-zone (ref1))

Typical usage would be for a legacy database where datetimes are not stored in UTC.

No date lookup

Querying my database takes this setting into account, e.g. :

In settings.py

USE_TZ = True
TIME_ZONE = 'Europe/Paris' # tz1
DATABASES = {
    'legacy': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '....cnf',
        },
        'TIME_ZONE': 'Europe/Paris', # tz2
    },
    'default' : {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '....cnf',
        },
    }
}

In the manage.py shell

>>> dt = timezone.make_aware(datetime.datetime(2017, 7, 6, 20, 50))
>>> dt
datetime.datetime(2017, 7, 6, 20, 50, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
>>> MyModel.objects.filter(my_datetime_field=dt).exists()
True

This works because my database reads '2017-07-06 20:50:00'

With date lookup

Related doc https://docs.djangoproject.com/en/1.11/ref/models/querysets/#date (ref2)

But this does not work, while it logically should

>>> MyModel.objects.filter(my_datetime_field__date=dt.date()).exists()
False*

The related SQL query from DEBUG is :

SELECT (1) AS `a` FROM `my_model` WHERE DATE(CONVERT_TZ(`my_model`.`my_datetime_field`, 'UTC', 'Europe/Paris')) = '2017-07-06' LIMIT 1;

(*) Note that I haven't filled the timezone table in MySQL, so the result should be True in this case, but could be False close to midnight.
Related doc is https://dev.mysql.com/doc/refman/5.7/en/mysql-tzinfo-to-sql.html

Two things are wrong. First, conversion should be from Paris to Paris, instead of UTC to Paris. The conversion should go from the database timezone tz2 to the django app one tz1.

Indeed from ref1 :

When USE_TZ is True and the database doesn’t support time zones (e.g. SQLite, MySQL, Oracle), Django reads and writes datetimes in local time according to this option if it is set and in UTC if it isn’t.

and ref2 :

When USE_TZ is True, fields are converted to the current time zone before filtering

Secondly, when tz1 == tz2, there should be no need to use CONVERT_TZ and the query will work without timezone tables in MySQL.

The explicit queries are :

mysql> SELECT (1) AS `a` FROM `my_model` WHERE `my_model`.`my_datetime_field` = '2017-07-06 20:50:00' LIMIT 1;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

mysql> SELECT (1) AS `a` FROM `my_model` WHERE DATE(`my_model`.`my_datetime_field`) = '2017-07-06' LIMIT 1;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.00 sec)

Why is 'UTC' appearing in the query? Should it not be 'Europe/Paris'?

Am I misunderstanding something from the doc, or is it a bug?

Thank you.

EDIT : My system tz is not UTC, if this is any help

mysql> SELECT @@global.time_zone, @@session.time_zone, @@system_time_zone;
+--------------------+---------------------+--------------------+
| @@global.time_zone | @@session.time_zone | @@system_time_zone |
+--------------------+---------------------+--------------------+
| SYSTEM             | SYSTEM              | CEST               |
+--------------------+---------------------+--------------------+

ContentLicense: CC BY-SA 3.0


问:
Sort array of SKShapeNode elements
Any idea on how to sort an array of SKShapeNode elements by their names? Let just assume each SKShapeNode.name property is a number 100,23,31,... All of them are group into shapeNodesCollection. What should be done to sort it out into another array - shapeNodesCollectionSorted? Below you can find some abstract code.

```<code>class Example: GameScene {

    ...

    var shapeNodesCollection = [SKShapeNode]()
    var shapeNodesCollectionSorted = [SKShapeNode]()

    ...

    shapeNodesCollectionSorted = ... //sorted shapeNodesCollection

}
</code>```

Many thanks to anyone for any contribution.

答:
If the name property is a simple numeric type (e.g., Int, Float, etc) then this should be enough:

```<code>var shapeNodesCollectionSorted = shapeNodesCollection.sorted { $0.name < $1.name }
</code>```

The shapeNodesCollectionSorted will then contain the shapes sorted in ascending order according to the name property.

Title: Sort array of SKShapeNode elements

Body:
Any idea on how to sort an array of SKShapeNode elements by their names? Let just assume each SKShapeNode.name property is a number 100,23,31,... All of them are group into shapeNodesCollection. What should be done to sort it out into another array - shapeNodesCollectionSorted? Below you can find some abstract code.

class Example: GameScene {

    ...

    var shapeNodesCollection = [SKShapeNode]()
    var shapeNodesCollectionSorted = [SKShapeNode]()

    ...

    shapeNodesCollectionSorted = ... //sorted shapeNodesCollection

}

Many thanks to anyone for any contribution.

Body:
If the name property is a simple numeric type (e.g., Int, Float, etc) then this should be enough:

var shapeNodesCollectionSorted = shapeNodesCollection.sorted { $0.name < $1.name }

The shapeNodesCollectionSorted will then contain the shapes sorted in ascending order according to the name property.


问:
What essential design artifacts do you produce?
In the course of your software development lifecycle, what essential design artifacts do you produce? What makes them essential to your practice?

The project I'm currently on has been in production for more than 8 years. This web application has been actively enhanced and maintained over that time. While we have CMMI-based policies and processes in place, with portions of our practice being well defined, the design phase has been largely overlooked. What are the best practices?

答:
Designs change so much during development and afterwards that most of my carefully crafted documents rot away in source control and become almost more of a hindrance than a help, once code is in production.  I see design documents as necessary to good communication and to clarify your thinking while you develop something, but after that it takes a herculean effort to keep them properly maintained.

I do take pictures of whiteboards and save the JPEGs to source control.  Those are some of my best design docs!

OwnerDisplayName: Eric Z Beard

ContentLicense: CC BY-SA 2.5


问:
How can I change the color of my prompt in zsh (different from normal text)?
To recognize better the start and the end of output on a commandline, I want to change the color of my prompt, so that it is visibly different from the programs output. As I use zsh, can anyone give me a hint?</p>

答:
Zsh comes with colored prompts builtin. Try

```<code>autoload -U promptinit && promptinit
</code>```

and then prompt -l lists available prompts, -p fire previews the "fire" prompt, -s fire sets it.

When you are ready to add a prompt add something like this below the autoload line above:

```<code>prompt fade red
</code>```

OwnerDisplayName: Mnementh

Body:
Zsh comes with colored prompts builtin. Try

autoload -U promptinit && promptinit

and then prompt -l lists available prompts, -p fire previews the "fire" prompt, -s fire sets it.

When you are ready to add a prompt add something like this below the autoload line above:

prompt fade red


问:
What server to use?
I want to create an Android Application. This application needs to use a server. But the problem with me and like many others is that without an industrial training or experience I have really basic knowledge of what a server does.
My app needs to do the following:

Their will be two kinds of clients. Both shall have some kind of interaction between them like seeing each others info based on some search query and then if needed connect to each other via chat.

The server should store this information in some kind of database maybe a MySQL record or recommend something better that's used in real world.

For chat, I am thinking of using Ejabberd with xmpp server.

I have searched through net and I have to say, the more I search, the more I get confused. There are Amazon Web Services, Google Cloud Services etc.. But I don't know what specific should I begin with. How should I set-up my server for this specific use.

I know some of us will be skeptical that this question is off-topic or doesn't belong here, but I still want to take a chance to ask this question. Because I know there are millions like me searching where to begin with and if someone helps us get past this barrier, millions of developers could stand a chance.
I would suggest if someone could explain on How to deal with servers, it would be really appreciated by newbies like me.

答:
I was also struck at the same point in starting and now I have enough wisdom to guide you.

First it is useless to get struck with Amazon & Google.

You need a domain (You can get one from GoDaddy.com or just get a free subdomain from 000webhost.com)

Learn Web Development(Any Language through which you will be able to give response in JSON, I use PHP)

Your app does not need any cloud backend, or servers like google cloud. Its all communicating with your own code.

Feel free to comment

Your domain server will be quite similar to XAMPP

Title: What server to use?


问:
Unable to inject javascript with Swashbuckle/Swagger
I'm using the Swashbuckle NuGet package to create Swagger documentation for my API. https://www.nuget.org/packages/Swashbuckle

I'm trying to make some minor changes to the UI - essentially just to add some corporate branding to the header.

I have added two files as embedded resources to my project, in a directory called resources.

These are injected into the UI via:

```<code>.EnableSwaggerUi(c =>
{
    c.InjectStylesheet(thisAssembly, typeof(SwaggerConfig).Namespace + ".Resources.Swagger.css");

    c.InjectJavaScript(thisAssembly, typeof(SwaggerConfig).Namespace + ".Resources.Swagger.js");
}
</code>```

Which results in the following link being added to rendered page.

```<code><link href="ext/ang_nav_api-Resources-Swagger-css" rel="stylesheet" type="text/css" media="screen">
</code>```

This is all correct and the stylesheet works as expected.

However the .js script doesn't appear on the client.

Changing the c.InjectJavaScript to c.InjectStylesheet does inject the file as a <link> .. so I'm happy that the file itself is correctly embedded etc.

What could be wrong here?

答:
The .js script will not appear on the client. (not on the way you would expect)
Look closely to the code of index.html:
https://github.com/domaindrivendev/Swashbuckle/blob/8223bedae706fec612c98ebbcee6b2d7033ae349/Swashbuckle.Core/SwaggerUi/CustomAssets/index.html#L98

Your customScripts will be loaded dynamically on the onComplete event

```<code>$.getScript(script);
</code>```

Body:
I'm using the Swashbuckle NuGet package to create Swagger documentation for my API. https://www.nuget.org/packages/Swashbuckle

I'm trying to make some minor changes to the UI - essentially just to add some corporate branding to the header.

I have added two files as embedded resources to my project, in a directory called resources.

These are injected into the UI via:

.EnableSwaggerUi(c =>
{
    c.InjectStylesheet(thisAssembly, typeof(SwaggerConfig).Namespace + ".Resources.Swagger.css");

    c.InjectJavaScript(thisAssembly, typeof(SwaggerConfig).Namespace + ".Resources.Swagger.js");
}

Which results in the following link being added to rendered page.

<link href="ext/ang_nav_api-Resources-Swagger-css" rel="stylesheet" type="text/css" media="screen">

This is all correct and the stylesheet works as expected.

However the .js script doesn't appear on the client.

Changing the c.InjectJavaScript to c.InjectStylesheet does inject the file as a <link> .. so I'm happy that the file itself is correctly embedded etc.

What could be wrong here?

Body:
The .js script will not appear on the client. (not on the way you would expect)
Look closely to the code of index.html:
https://github.com/domaindrivendev/Swashbuckle/blob/8223bedae706fec612c98ebbcee6b2d7033ae349/Swashbuckle.Core/SwaggerUi/CustomAssets/index.html#L98

Your customScripts will be loaded dynamically on the onComplete event

$.getScript(script);


问:
Finding the last different position in an array
I have a vector A of dimension 1xn composed of zeros and ones. I want a very efficient way to find the position j of the last element of A such that A(j)~=A(n). If the elements of A are all equal then the code should return n.

Example:

If A=[1 0 1 1 1], I should get 2.

If A=[0 0 0 0 0], I should get 5.

If A=[1 0 0 0 0], I should get 1.

答:
In one line, just for the fun of it:</p>

```<code>result = min([find(A~=A(end),1,'last') numel(A)]);
</code>```

Body:
In one line, just for the fun of it:

result = min([find(A~=A(end),1,'last') numel(A)]);


问:
SecureString in MVC
My model is like:

```<code>public string Password { get; set; }
</code>```

And i use it in my repository.cs like:

```<code>   string somePass= user.pass
                        if (somePass== pass)
                        {
                            return user;
                        }
</code>```

On security scan, this appears to be a heap inspection issue. And it reccomends to use "Secure String"
But when i define the Password parameter as SecureString in my model class and change my repository.cs i get the error.

How can i prevent this to be a security issue?

答:
It seems like it's referring to the secure string class: https://msdn.microsoft.com/es-es/library/system.security.securestring(v=vs.110).aspx

Long story short. A secure string removes its value from memory once it's no longer needed. I've never used fortify, but since your variable name is referring to a password, I'm guessing that fortify sees it as a vulnerability because a password is confidential information that has no reason to be kept in memory once you're done using it.

Title: SecureString in MVC

Body:
My model is like:

public string Password { get; set; }

And i use it in my repository.cs like:

   string somePass= user.pass
                        if (somePass== pass)
                        {
                            return user;
                        }

On security scan, this appears to be a heap inspection issue. And it reccomends to use "Secure String"
But when i define the Password parameter as SecureString in my model class and change my repository.cs i get the error.

How can i prevent this to be a security issue?


问:
How to limit a Twitter search to specific accounts in R
here's my code:

```<code>    library(RCurl)
    library(twitteR)
    library(ROAuth)
    #run the libraries ctrl+r
    api_key<-"3snovyV8bNn8jVWu93UNP61rd"
    api_secret<-"1U3crdPY2kS4Nx12OaxjlE2geyDFSzJXJnVSJaEvIUV3LqHdCa"
    access_token<-"2457340967-8wOYs9X7m66RzywCtT6KHlow6hP8zTNpSMTid7Y"
    access_token_secret<-"gTqLbHGPayMgF3FG0o0tb42yBWd3TiCZ67vhXOfnLICZT"
    setup_twitter_oauth(api_key,api_secret,access_token,access_token_secret)
    #ctrl+r
    searchTwitter("Cristiano Ronaldo", n=25, lang="en", since=NULL,
    until=NULL,
          locale=NULL, geocode=NULL, sinceID=NULL, maxID=NULL,
          resultType=NULL, retryOnRateLimit=120)
    #ctrl+r
    Rtweets(n=25, lang="en", since=NULL)
</code>```

I'm looking for a command in order to specify the tweets I want to extract by account (i.e. Cristiano Ronaldo's official Twitter account).

Thanks!!!

答:
I've used the smappR package's function getTimeline to get tweets from a single user account.

You'll need to install smappR from GitHub, if you haven't done so previously.

library(devtools)
install_github("SMAPPNYU/smappR")

You could then use the getTimeline function to get Ronaldo's tweets:

```<code>getTimeline(screen_name = "Cristiano",
filename = "ronaldo_tweets.json", # where tweets will be stored
n=500, ## number of tweets to download (max is 3,200)
oauth_folder = "~/Dropbox/credentials")
</code>```

The screen_name argument refers to the user's twitter handle. Note also that smappR assumes that you have one or more OAuth objects in a folder. You can read about their setup here: https://github.com/SMAPPNYU/smappR

I hope that this helps.

Body:
here's my code:

    library(RCurl)
    library(twitteR)
    library(ROAuth)
    #run the libraries ctrl+r
    api_key<-"3snovyV8bNn8jVWu93UNP61rd"
    api_secret<-"1U3crdPY2kS4Nx12OaxjlE2geyDFSzJXJnVSJaEvIUV3LqHdCa"
    access_token<-"2457340967-8wOYs9X7m66RzywCtT6KHlow6hP8zTNpSMTid7Y"
    access_token_secret<-"gTqLbHGPayMgF3FG0o0tb42yBWd3TiCZ67vhXOfnLICZT"
    setup_twitter_oauth(api_key,api_secret,access_token,access_token_secret)
    #ctrl+r
    searchTwitter("Cristiano Ronaldo", n=25, lang="en", since=NULL,
    until=NULL,
          locale=NULL, geocode=NULL, sinceID=NULL, maxID=NULL,
          resultType=NULL, retryOnRateLimit=120)
    #ctrl+r
    Rtweets(n=25, lang="en", since=NULL)

I'm looking for a command in order to specify the tweets I want to extract by account (i.e. Cristiano Ronaldo's official Twitter account).

Thanks!!!

Body:
I've used the smappR package's function getTimeline to get tweets from a single user account.

You'll need to install smappR from GitHub, if you haven't done so previously.

library(devtools)
install_github("SMAPPNYU/smappR")

You could then use the getTimeline function to get Ronaldo's tweets:

getTimeline(screen_name = "Cristiano",
filename = "ronaldo_tweets.json", # where tweets will be stored
n=500, ## number of tweets to download (max is 3,200)
oauth_folder = "~/Dropbox/credentials")

The screen_name argument refers to the user's twitter handle. Note also that smappR assumes that you have one or more OAuth objects in a folder. You can read about their setup here: https://github.com/SMAPPNYU/smappR

I hope that this helps.


问:
Ruby to_yaml stringifies my json
I am trying to convert a ruby hash to yaml. I'd like part of the hash be valid json; however, when I try to serialize the json string, it is converted to yaml in quotes.

For example, when I just have a simple string, the ouput is as follows (note foo is not in quotations):

```<code>request = {}
request['body'] = 'foo'
request.to_yaml # outputs: body: foo
</code>```

However, when I add something to the beginning of the string, like { foo the output for body gets quoted:

```<code>request['body'] = '{ foo'
request.to_yaml # outputs: body: '{ foo'
</code>```

How can I get around this? I've tried JSON.parse and, though that make work, I can't be guaranteed that this input will actually be json (could be xml, etc...) -- I just want to give back whatever was given to me but not "stringified".

Basically, I want to give an object that looks like:

```<code>{ 'request' => {
    'url' => '/posts',
    'method' => 'GET',
    'headers' => [
      'Content-Type' => 'application/json'
    ]
  },
  'response' => {
    'code' => 200,
    'body' => '[{"id":"ef4b3a","title":"this is the title"},{"id":"a98c4f","title":"title of the second post"}]'
  }
}
</code>```

Which returns:

```<code>request:
    url: /posts
    method: GET
    headers:
        - Content-Type: application/json

response:
    code: 200
    body:
        [{"id":"ef4b3a","title":"this is the title"},{"id":"a98c4f","title":"title of the second post"}]
</code>```

The reason being: right now, I can go from yaml to the correct ruby hash but I can't go the other way.

答:
The method my_hash.to_yaml() just takes a hash and converts it to YAML without doing anything special to the values. The method does not care whether your string is JSON or XML, it just treats it as a string.

So why is my JSON being put into quotes when other strings aren't?

Good question! The reason is simple: curly braces are a valid part of YAML syntax.

This:

```<code>my_key: { sub: 1, keys: 2}
</code>```

Is called flow mapping syntax in YAML, and it allows you make nested mappings in one line. To escape strings which have curly braces in them, YAML uses quotes:

```<code>my_key: "{ sub: 1, keys: 2}" # this is just a string
</code>```

Of course, the quotes are optional for all strings:

```<code>my_key: "foo" #same as my_key: foo
</code>```

Okay, but I want to_yaml() to find my JSON string and convert it to YAML mappings like the rest of the hash.

Well then, you need to convert your JSON string to a hash like the rest of your hash. to_yaml() converts a hash to YAML. It doesn't convert strings to YAML. The proper method for doing this is to use JSON.parse, as you mentioned:

```<code>request['body'] = JSON.parse( '{"id":"ef4b3a"}' )
</code>```

But the string might not be JSON! It might be XML or some other smelly string.

This is exactly why to_yaml() doesn't convert strings. A wise programmer once told me: "Strings are strings. Strings are not data structures. Strings are strings."

If you want to convert a string into a data structure, you need to validate it and parse it. Because there's no guarantee that a string will be valid, it's your responsibility as a programmer to determine whether your data is JSON or XML or just bad, and to decide how you want to respond to each bit of data.

Since it looks like you're parsing web pages, you might want to consider using the same bit of data other web clients use to parse these things:

```<code>{ 'request' => {
    'url' => '/posts',
    'method' => 'GET',
    'headers' => [
      'Content-Type' => 'application/json' #<== this guy, right here!
    ]
  },
  'response' => {
    'code' => 200,
    'body' => '[{"id":"ef4b3a","title":"this is the title"},{"id":"a98c4f","title":"title of the second post"}]'
  }
}
</code>```

If the content-type doesn't agree with the body then you should throw an error because your input data is bad.

Title: Ruby to_yaml stringifies my json

Body:
I am trying to convert a ruby hash to yaml. I'd like part of the hash be valid json; however, when I try to serialize the json string, it is converted to yaml in quotes.

For example, when I just have a simple string, the ouput is as follows (note foo is not in quotations):

request = {}
request['body'] = 'foo'
request.to_yaml # outputs: body: foo

However, when I add something to the beginning of the string, like { foo the output for body gets quoted:

request['body'] = '{ foo'
request.to_yaml # outputs: body: '{ foo'

How can I get around this? I've tried JSON.parse and, though that make work, I can't be guaranteed that this input will actually be json (could be xml, etc...) -- I just want to give back whatever was given to me but not "stringified".

Basically, I want to give an object that looks like:

{ 'request' => {
    'url' => '/posts',
    'method' => 'GET',
    'headers' => [
      'Content-Type' => 'application/json'
    ]
  },
  'response' => {
    'code' => 200,
    'body' => '[{"id":"ef4b3a","title":"this is the title"},{"id":"a98c4f","title":"title of the second post"}]'
  }
}

Which returns:

request:
    url: /posts
    method: GET
    headers:
        - Content-Type: application/json

response:
    code: 200
    body:
        [{"id":"ef4b3a","title":"this is the title"},{"id":"a98c4f","title":"title of the second post"}]

The reason being: right now, I can go from yaml to the correct ruby hash but I can't go the other way.

Body:
The method my_hash.to_yaml() just takes a hash and converts it to YAML without doing anything special to the values. The method does not care whether your string is JSON or XML, it just treats it as a string.

So why is my JSON being put into quotes when other strings aren't?

Good question! The reason is simple: curly braces are a valid part of YAML syntax.

This:

my_key: { sub: 1, keys: 2}

Is called flow mapping syntax in YAML, and it allows you make nested mappings in one line. To escape strings which have curly braces in them, YAML uses quotes:

my_key: "{ sub: 1, keys: 2}" # this is just a string

Of course, the quotes are optional for all strings:

my_key: "foo" #same as my_key: foo

Okay, but I want to_yaml() to find my JSON string and convert it to YAML mappings like the rest of the hash.

Well then, you need to convert your JSON string to a hash like the rest of your hash. to_yaml() converts a hash to YAML. It doesn't convert strings to YAML. The proper method for doing this is to use JSON.parse, as you mentioned:

request['body'] = JSON.parse( '{"id":"ef4b3a"}' )

But the string might not be JSON! It might be XML or some other smelly string.

This is exactly why to_yaml() doesn't convert strings. A wise programmer once told me: "Strings are strings. Strings are not data structures. Strings are strings."

If you want to convert a string into a data structure, you need to validate it and parse it. Because there's no guarantee that a string will be valid, it's your responsibility as a programmer to determine whether your data is JSON or XML or just bad, and to decide how you want to respond to each bit of data.

Since it looks like you're parsing web pages, you might want to consider using the same bit of data other web clients use to parse these things:

{ 'request' => {
    'url' => '/posts',
    'method' => 'GET',
    'headers' => [
      'Content-Type' => 'application/json' #<== this guy, right here!
    ]
  },
  'response' => {
    'code' => 200,
    'body' => '[{"id":"ef4b3a","title":"this is the title"},{"id":"a98c4f","title":"title of the second post"}]'
  }
}

If the content-type doesn't agree with the body then you should throw an error because your input data is bad.


问:
How do I retrieve the data in the name list attribute (html) using jQuery?
I am trying to retrieve the list of names from the inputs through jQuery.
Could anyone advise how I can do it?

The following inputs for example:

```<code>Henry | 25 | Financial Advisor
Eric  | 28 | Chemistry Professor
Lance | 30 | Database Administrator
</code>```

How can I retrieve the names Henry, Eric, Lance using jQuery and the name[ ] attribute?

HTML

```<code><div id="wrapper">
<div id="form_div">
 <form method="post" action="store_employee.php">
  <table id="employee_table" align=center>
   <tr id="row1">
    <td><input type="text" name="name[]" placeholder="Enter Name"></td>
    <td><input type="text" name="age[]" placeholder="Enter Age"></td>
    <td><input type="text" name="job[]" placeholder="Enter Job"></td>
   </tr>
  </table>
  <input type="button" onclick="add_row();" value="ADD ROW">
  <input type="submit" name="submit_row" value="SUBMIT">
 </form>
</div>
</code>```

Javascript

```<code>    function add_row()
{
    $rowno=jQuery("#employee_table tr").length;
    $rowno=$rowno+1;
    jQuery("#employee_table tr:last").after(
        "<tr id='row"+$rowno+"'>"+
            "<td><input type='text' name='name[]' placeholder='Enter Name'></td>"+
            "<td><input type='text' name='age[]' placeholder='Enter Age'></td>"+
            "<td><input type='text' name='job[]' placeholder='Enter Job'></td>"+
            "<td><input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')></td>"+
        "</tr>");
    }

function delete_row(rowno)
{
    jQuery('#'+rowno).remove();
}
</code>```

Body:
I am trying to retrieve the list of names from the inputs through jQuery.
Could anyone advise how I can do it?

The following inputs for example:

Henry | 25 | Financial Advisor
Eric  | 28 | Chemistry Professor
Lance | 30 | Database Administrator

How can I retrieve the names Henry, Eric, Lance using jQuery and the name[ ] attribute?

HTML

 <form method="post" action="store_employee.php">

    <input type="text" name="name[]" placeholder="Enter Name">
    <input type="text" name="age[]" placeholder="Enter Age">
    <input type="text" name="job[]" placeholder="Enter Job">

  <input type="button" onclick="add_row();" value="ADD ROW">
  <input type="submit" name="submit_row" value="SUBMIT">
 </form>

Javascript

    function add_row()
{
    $rowno=jQuery("#employee_table tr").length;
    $rowno=$rowno+1;
    jQuery("#employee_table tr:last").after(
        "
"+
            "<input type='text' name='name[]' placeholder='Enter Name'>	"+
            "<input type='text' name='age[]' placeholder='Enter Age'>	"+
            "<input type='text' name='job[]' placeholder='Enter Job'>	"+
            "<input type='button' value='DELETE' onclick=delete_row('row"+$rowno+"')>	"+
        "
");
    }

function delete_row(rowno)
{
    jQuery('#'+rowno).remove();
}

Body: var names = $("[name='name[]']");


问:
Java Enums: Two enum types, each containing references to each other?
Is there a way to get around the class-loading issues caused by having two enums that reference each other?

I have two sets of enumerations, Foo and Bar, defined like so:

```<code>public class EnumTest {

  public enum Foo {
    A(Bar.Alpha),
    B(Bar.Delta),
    C(Bar.Alpha);

    private Foo(Bar b) {
      this.b = b;
    }

    public final Bar b;
  }

  public enum Bar {
    Alpha(Foo.A),
    Beta(Foo.C),
    Delta(Foo.C);

    private Bar(Foo f) {
      this.f = f;
    }

    public final Foo f;
  }

  public static void main (String[] args) {
    for (Foo f: Foo.values()) {
      System.out.println(f + " bar " + f.b);
    }
    for (Bar b: Bar.values()) {
      System.out.println(b + " foo " + b.f);
    }
  }
}
</code>```

The above code produces as output:

```<code>A bar Alpha
B bar Delta
C bar Alpha
Alpha foo null
Beta foo null
Delta foo null
</code>```

I understand why it happens - the JVM starts classloading Foo; it sees the Bar.Alpha in Foo.A's constructor, so it starts classloading Bar.  It sees the Foo.A reference in the call to Bar.Alpha's constructor, but (since we're still in Foo.A's constructor) Foo.A is null at this point, so Bar.Alpha's constructor gets passed a null.  If I reverse the two for loops (or otherwise reference Bar before Foo), the output changes so that Bar's values are all correct, but Foo's values are not.

Is there any way to get around this?  I know I can create a static Map and a static Map in a 3rd class, but that feels fairly hackish to me.  I could also make Foo.getBar() and Bar.getFoo() methods that refer to the external map, so it wouldn't even change my interface (the actual classes I have use inspectors instead of public fields), but it still feels kind of unclean to me.

(The reason I'm doing this in my actual system: Foo and Bar represent types of messages that 2 apps send to each other; the Foo.b and Bar.f fields represent the expected response type for a given message - so in my sample code, when app_1 receives a Foo.A, it needs to reply with a Bar.Alpha and vice-versa.)

Thanks in advance!

答:
You can use EnumMap, and fill it within one of the enums.

```<code>private static EnumMap<Foo, LinkedList<Bar>> enumAMap;

public static void main(String[] args) throws Exception {
    enumAMap = new EnumMap<Foo, LinkedList<Bar>>(Foo.class);
    System.out.println(Bar.values().length); // initialize enums, prevents NPE
    for (Foo a : Foo.values()) {
        for (Bar b : enumAMap.get(a)) {
            System.out.println(a + " -> " + b);
        }
    }
}

public enum Foo {
    Foo1(1),
    Foo2(2);

    private int num;

    private Foo(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }
}

public enum Bar {
    Bar1(1, Foo.Foo1),
    Bar2(2, Foo.Foo1),
    Bar3(3, Foo.Foo2),
    Bar4(4, Foo.Foo2);

    private int num;
    private Foo foo;

    private Bar(int num, Foo foo) {
        this.num = num;
        this.foo = foo;
        if (!enumAMap.containsKey(foo)) {
            enumAMap.put(foo, new LinkedList<Bar>());
        }
        enumAMap.get(foo).addLast(this);
    }

    public int getNum() {
        return num;
    }

    public Foo getFoo() {
        return foo;
    }
}
</code>```

Output:

```<code>4
Foo1 -> Bar1
Foo1 -> Bar2
Foo2 -> Bar3
Foo2 -> Bar4
</code>```

Body:
Is there a way to get around the class-loading issues caused by having two enums that reference each other?

I have two sets of enumerations, Foo and Bar, defined like so:

public class EnumTest {

  public enum Foo {
    A(Bar.Alpha),
    B(Bar.Delta),
    C(Bar.Alpha);

    private Foo(Bar b) {
      this.b = b;
    }

    public final Bar b;
  }

  public enum Bar {
    Alpha(Foo.A),
    Beta(Foo.C),
    Delta(Foo.C);

    private Bar(Foo f) {
      this.f = f;
    }

    public final Foo f;
  }

  public static void main (String[] args) {
    for (Foo f: Foo.values()) {
      System.out.println(f + " bar " + f.b);
    }
    for (Bar b: Bar.values()) {
      System.out.println(b + " foo " + b.f);
    }
  }
}

The above code produces as output:

A bar Alpha
B bar Delta
C bar Alpha
Alpha foo null
Beta foo null
Delta foo null

I understand why it happens - the JVM starts classloading Foo; it sees the Bar.Alpha in Foo.A's constructor, so it starts classloading Bar.  It sees the Foo.A reference in the call to Bar.Alpha's constructor, but (since we're still in Foo.A's constructor) Foo.A is null at this point, so Bar.Alpha's constructor gets passed a null.  If I reverse the two for loops (or otherwise reference Bar before Foo), the output changes so that Bar's values are all correct, but Foo's values are not.

Is there any way to get around this?  I know I can create a static Map and a static Map in a 3rd class, but that feels fairly hackish to me.  I could also make Foo.getBar() and Bar.getFoo() methods that refer to the external map, so it wouldn't even change my interface (the actual classes I have use inspectors instead of public fields), but it still feels kind of unclean to me.

(The reason I'm doing this in my actual system: Foo and Bar represent types of messages that 2 apps send to each other; the Foo.b and Bar.f fields represent the expected response type for a given message - so in my sample code, when app_1 receives a Foo.A, it needs to reply with a Bar.Alpha and vice-versa.)

Thanks in advance!

Body:
You can use EnumMap, and fill it within one of the enums.

private static EnumMap<Foo, LinkedList<Bar>> enumAMap;

public static void main(String[] args) throws Exception {
    enumAMap = new EnumMap<Foo, LinkedList<Bar>>(Foo.class);
    System.out.println(Bar.values().length); // initialize enums, prevents NPE
    for (Foo a : Foo.values()) {
        for (Bar b : enumAMap.get(a)) {
            System.out.println(a + " -> " + b);
        }
    }
}

public enum Foo {
    Foo1(1),
    Foo2(2);

    private int num;

    private Foo(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }
}

public enum Bar {
    Bar1(1, Foo.Foo1),
    Bar2(2, Foo.Foo1),
    Bar3(3, Foo.Foo2),
    Bar4(4, Foo.Foo2);

    private int num;
    private Foo foo;

    private Bar(int num, Foo foo) {
        this.num = num;
        this.foo = foo;
        if (!enumAMap.containsKey(foo)) {
            enumAMap.put(foo, new LinkedList<Bar>());
        }
        enumAMap.get(foo).addLast(this);
    }

    public int getNum() {
        return num;
    }

    public Foo getFoo() {
        return foo;
    }
}

Output:

4
Foo1 -> Bar1
Foo1 -> Bar2
Foo2 -> Bar3
Foo2 -> Bar4


问:
Given a file, find the ten most frequently occurring words as efficiently as possible
This is apparently an interview question (found it in a collection of interview questions), but even if it's not it's pretty cool.

We are told to do this efficiently on all complexity measures. I thought of creating a HashMap that maps the words to their frequency. That would be O(n) in time and space complexity, but since there may be lots of words we cannot assume that we can store everything in memory.

I must add that nothing in the question says that the words cannot be stored in memory, but what if that were the case? If that's not the case, then the question does not seem as challenging.

答: You could make a time/space tradeoff and go O(n^2) for time and O(1) for (memory) space by counting how many times a word occurs each time you encounter it in a linear pass of the data. If the count is above the top 10 found so far, then keep the word and the count, otherwise ignore it.


问:
How to color dendrogram labels using R based on label name not grouping
I am trying to color the labels of a dendrogram based on a portion of the label name. The label name is derived from file names in a folder. The files are .txt files and are named in this manner: 167_001.txt with the first three numbers indicating a particular author of a text and the final three numbers differentiating the separate pieces of writing by that author. I want to label the branches by the full name of the file, but color the label only based on the first 3 numbers so I can see which works by a specific author might have more in common with a different author to see who influenced who. These are medieval authors so you won't be helping me find any modern authors who might have plagiarized something. So if a file begins with 080 I want all the 080 files to be one color no matter what the final part of the file name is and no matter where it is grouped, but I still want the end part of the file to be in the label name. Here is what I have so far:

```<code># Load data
data(USArrests)
dd <- dist(scale(USArrests), method = "euclidean")

#Perform a cluster analysis on the distance object
hc <- hclust(dd)
#Get the text file names to use as labels

dend <- as.dendrogram(hc)

dend2 = color_unique_labels(dend)
d5gr=color_branches(dend2,5,groupLabels=TRUE)
#plot(d5gr)
plot(d5gr, horiz=TRUE)
</code>```

As you can see I am using the dendextend package. If anyone has a better package or one that will accomplish what I need just as well, that would be great. What I currently have will put the files in the same color family since they are similar enough the "color_unique_labels" function offered by dendextend at least sort of colors them in shades of the same color, but it does not make them the exact same color as I would like so the same author is always the same color and then it is easier to see which works share similarities with different authors. See below. There are a few hundred different authors so I would prefer to not assign each one an individual color manually (A ="red", B ="blue", C ="orchid", etc...), but would prefer something that works like "color_unique_labels" and automatically chooses and assigns a color based on the first 3 numbers in the filename. My example is using the USArrests package and I would perhaps like to see how to color the state names by the first letter, so all the "A" states and "C" states and so on are the same color. So Alabama, Alaska, Arizona, and Arkansas should all be the same color and California, Colorado, and Connecticut should also be the same color. Again, I would prefer to find a way to make it more automated as my real dataset has a few hundred possibilities and not just 50, however, I am not opposed if that is the only option. Thanks in advance!

dendextend dendrogram using "color_unique_labels" function

答:
Hope your question was answered by now. In case this is still useful to you, here's my stab at solving it:

First you create a new variable that groups the authors in their categories (you said something about the beginning of a categorical variable you already had). Depending on the nr of categories want to create you'll need different code, check the Quick R Recoding variables section and this tutorial on recode() for what might work for your particular case.

If this proves difficult in R, maybe try generating the group variable in Excel - it has a good filtering function that can help you quickly fill in the reference code. For future dataset/dataframe management, I can recommend chopping it up in as many variables as you actually have: If I understand your problem correctly it seems like part of the issue comes from having two categorical variables in one (group + author = filename).

Once you've got your group variable ("GROUP") you'll need to assign a color set to it:

```<code>library(dendextend)
library(colorspace)

#make GROUP color palette:

GROUP <-dataframe$GROUP #factorize group variable
n_GROUP <- length(unique(GROUP)) #count nr of unique groups
cols <- rainbow_hcl(n_GROUP) #select a number of colors based on GROUP size
col_GROUP <- cols[GROUP] #make color palette assigning the selected colors to the groups
</code>```

So here is where the 'color labels by category' trick actually takes place: after you've made the dendrogram but before plotting the dendrogram you sort your colors according to the dendrogram (dend):

```<code>dend <- as.dendrogram(hc) #hc into dendrogram

#sort GROUP color palette according to dend:
col_GROUP <- col_GROUP[order.dendrogram(dend)]

#plot dendrogram as you would normally do, I did this:
dend <- dend %>%
set("labels_colors", col_GROUP) %>% #change label colors to GROUP
plot(main = "Dendrogram with labels colored according to GROUP")
legend("topleft", legend = levels(GROUP), fill = cols, cex = 0.5)
</code>```

This should color your labels according to their group category. A similar thing can be done in case you want to change the label names too (i.e. change the unique names needed for analysis to bigger category names). You just sort the GROUP factor according to dend and set labels while plotting to GROUP (see dendextended::set in R help for plotting options).

Hope this helps,
Cheers!

Body:
I am trying to color the labels of a dendrogram based on a portion of the label name. The label name is derived from file names in a folder. The files are .txt files and are named in this manner: 167_001.txt with the first three numbers indicating a particular author of a text and the final three numbers differentiating the separate pieces of writing by that author. I want to label the branches by the full name of the file, but color the label only based on the first 3 numbers so I can see which works by a specific author might have more in common with a different author to see who influenced who. These are medieval authors so you won't be helping me find any modern authors who might have plagiarized something. So if a file begins with 080 I want all the 080 files to be one color no matter what the final part of the file name is and no matter where it is grouped, but I still want the end part of the file to be in the label name. Here is what I have so far:

# Load data
data(USArrests)
dd <- dist(scale(USArrests), method = "euclidean")

#Perform a cluster analysis on the distance object
hc <- hclust(dd)
#Get the text file names to use as labels

dend <- as.dendrogram(hc)

dend2 = color_unique_labels(dend)
d5gr=color_branches(dend2,5,groupLabels=TRUE)
#plot(d5gr)
plot(d5gr, horiz=TRUE)

As you can see I am using the dendextend package. If anyone has a better package or one that will accomplish what I need just as well, that would be great. What I currently have will put the files in the same color family since they are similar enough the "color_unique_labels" function offered by dendextend at least sort of colors them in shades of the same color, but it does not make them the exact same color as I would like so the same author is always the same color and then it is easier to see which works share similarities with different authors. See below. There are a few hundred different authors so I would prefer to not assign each one an individual color manually (A ="red", B ="blue", C ="orchid", etc...), but would prefer something that works like "color_unique_labels" and automatically chooses and assigns a color based on the first 3 numbers in the filename. My example is using the USArrests package and I would perhaps like to see how to color the state names by the first letter, so all the "A" states and "C" states and so on are the same color. So Alabama, Alaska, Arizona, and Arkansas should all be the same color and California, Colorado, and Connecticut should also be the same color. Again, I would prefer to find a way to make it more automated as my real dataset has a few hundred possibilities and not just 50, however, I am not opposed if that is the only option. Thanks in advance!

dendextend dendrogram using "color_unique_labels" function

Body:
Hope your question was answered by now. In case this is still useful to you, here's my stab at solving it:

First you create a new variable that groups the authors in their categories (you said something about the beginning of a categorical variable you already had). Depending on the nr of categories want to create you'll need different code, check the Quick R Recoding variables section and this tutorial on recode() for what might work for your particular case.

If this proves difficult in R, maybe try generating the group variable in Excel - it has a good filtering function that can help you quickly fill in the reference code. For future dataset/dataframe management, I can recommend chopping it up in as many variables as you actually have: If I understand your problem correctly it seems like part of the issue comes from having two categorical variables in one (group + author = filename).

Once you've got your group variable ("GROUP") you'll need to assign a color set to it:

library(dendextend)
library(colorspace)

#make GROUP color palette:

GROUP <-dataframe$GROUP #factorize group variable
n_GROUP <- length(unique(GROUP)) #count nr of unique groups
cols <- rainbow_hcl(n_GROUP) #select a number of colors based on GROUP size
col_GROUP <- cols[GROUP] #make color palette assigning the selected colors to the groups

So here is where the 'color labels by category' trick actually takes place: after you've made the dendrogram but before plotting the dendrogram you sort your colors according to the dendrogram (dend):

dend <- as.dendrogram(hc) #hc into dendrogram

#sort GROUP color palette according to dend:
col_GROUP <- col_GROUP[order.dendrogram(dend)]

#plot dendrogram as you would normally do, I did this:
dend <- dend %>%
set("labels_colors", col_GROUP) %>% #change label colors to GROUP
plot(main = "Dendrogram with labels colored according to GROUP")
legend("topleft", legend = levels(GROUP), fill = cols, cex = 0.5)

This should color your labels according to their group category. A similar thing can be done in case you want to change the label names too (i.e. change the unique names needed for analysis to bigger category names). You just sort the GROUP factor according to dend and set labels while plotting to GROUP (see dendextended::set in R help for plotting options).

Hope this helps,
Cheers!


问:
"yarn resourcemanager" yields "The system cannot find the batch label specified - resourcemanager"
I am running hadoop 2.7.1 on windows 64 in pseudo-distributed mode, and can't manage to run yarn. Whenever I try to start it via yarn resourcemanager I get the following output:

```<code>The system cannot find the batch label specified - resourcemanager
Usage: java [-options] class [args...]
       (to execute a class)
or  java [-options] -jar jarfile [args...]
       (to execute a jar file)
where options include:
-d32          use a 32-bit data model if available
-d64          use a 64-bit data model if available
-server       to select the "server" VM
              The default VM is server.

-cp <class search path of directories and zip/jar files>
-classpath <class search path of directories and zip/jar files>
              A ; separated list of directories, JAR archives,
              and ZIP archives to search for class files.
-D<name>=<value>
              set a system property
-verbose:[class|gc|jni]
              enable verbose output
-version      print product version and exit
-version:<value>
              Warning: this feature is deprecated and will be removed
              in a future release.
              require the specified version to run
-showversion  print product version and continue
-jre-restrict-search | -no-jre-restrict-search
              Warning: this feature is deprecated and will be removed
              in a future release.
              include/exclude user private JREs in the version search
-? -help      print this help message
-X            print help on non-standard options
-ea[:<packagename>...|:<classname>]
-enableassertions[:<packagename>...|:<classname>]
              enable assertions with specified granularity
-da[:<packagename>...|:<classname>]
-disableassertions[:<packagename>...|:<classname>]
              disable assertions with specified granularity
-esa | -enablesystemassertions
              enable system assertions
-dsa | -disablesystemassertions
              disable system assertions
-agentlib:<libname>[=<options>]
              load native agent library <libname>, e.g. -agentlib:hprof
              see also, -agentlib:jdwp=help and -agentlib:hprof=help
-agentpath:<pathname>[=<options>]
              load native agent library by full pathname
-javaagent:<jarpath>[=<options>]
              load Java programming language agent, see java.lang.instrument
-splash:<imagepath>
              show splash screen with specified image
See http://www.oracle.com/technetwork/java/javase/documentation/index.html for more details.
</code>```

I suppose it's likely to be an issue with my current yarn-site.xml, but can't find what it is:

```<code><configuration>
<property>
    <name>yarn.resourcemanager.hostname</name>
    <value>localhost</value>
</property>
<property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
</property>
<property>
    <name>yarn.nodemanager.aux-services.mapreduce.shuffle.class</name>
    <value>org.apache.hadoop.mapred.ShuffleHandler</value>
</property>
<property>
    <name>yarn.application.classpath</name>
    <value>
        %HADOOP_HOME%\etc\hadoop,
        %HADOOP_HOME%\share\hadoop\common\*,
        %HADOOP_HOME%\share\hadoop\common\lib\*,
        %HADOOP_HOME%\share\hadoop\mapreduce\*,
        %HADOOP_HOME%\share\hadoop\mapreduce\lib\*,
        %HADOOP_HOME%\share\hadoop\hdfs\*,
        %HADOOP_HOME%\share\hadoop\hdfs\lib\*,
        %HADOOP_HOME%\share\hadoop\yarn\*,
        %HADOOP_HOME%\share\hadoop\yarn\lib\*
    </value>
</property>
</configuration>
</code>```

Following the only thing I managed to find on the internet about this issue I Tried editing yarn-site.xml changing LF to CRLF in Notepad++, but that didn't help at all.

答:
see Hadoop 2.3.0 over windows 2008 r2 x64 about nodemanager
</p>

Body:
I am running hadoop 2.7.1 on windows 64 in pseudo-distributed mode, and can't manage to run yarn. Whenever I try to start it via yarn resourcemanager I get the following output:

The system cannot find the batch label specified - resourcemanager
Usage: java [-options] class [args...]
       (to execute a class)
or  java [-options] -jar jarfile [args...]
       (to execute a jar file)
where options include:
-d32          use a 32-bit data model if available
-d64          use a 64-bit data model if available
-server       to select the "server" VM
              The default VM is server.

-cp <class search path of directories and zip/jar files>
-classpath <class search path of directories and zip/jar files>
              A ; separated list of directories, JAR archives,
              and ZIP archives to search for class files.
-D<name>=<value>
              set a system property
-verbose:[class|gc|jni]
              enable verbose output
-version      print product version and exit
-version:<value>
              Warning: this feature is deprecated and will be removed
              in a future release.
              require the specified version to run
-showversion  print product version and continue
-jre-restrict-search | -no-jre-restrict-search
              Warning: this feature is deprecated and will be removed
              in a future release.
              include/exclude user private JREs in the version search
-? -help      print this help message
-X            print help on non-standard options
-ea[:<packagename>...|:<classname>]
-enableassertions[:<packagename>...|:<classname>]
              enable assertions with specified granularity
-da[:<packagename>...|:<classname>]
-disableassertions[:<packagename>...|:<classname>]
              disable assertions with specified granularity
-esa | -enablesystemassertions
              enable system assertions
-dsa | -disablesystemassertions
              disable system assertions
-agentlib:<libname>[=<options>]
              load native agent library <libname>, e.g. -agentlib:hprof
              see also, -agentlib:jdwp=help and -agentlib:hprof=help
-agentpath:<pathname>[=<options>]
              load native agent library by full pathname
-javaagent:<jarpath>[=<options>]
              load Java programming language agent, see java.lang.instrument
-splash:<imagepath>
              show splash screen with specified image
See http://www.oracle.com/technetwork/java/javase/documentation/index.html for more details.

I suppose it's likely to be an issue with my current yarn-site.xml, but can't find what it is:

<configuration>
<property>
    <name>yarn.resourcemanager.hostname</name>
    <value>localhost</value>
</property>
<property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
</property>
<property>
    <name>yarn.nodemanager.aux-services.mapreduce.shuffle.class</name>
    <value>org.apache.hadoop.mapred.ShuffleHandler</value>
</property>
<property>
    <name>yarn.application.classpath</name>
    <value>
        %HADOOP_HOME%\etc\hadoop,
        %HADOOP_HOME%\share\hadoop\common\*,
        %HADOOP_HOME%\share\hadoop\common\lib\*,
        %HADOOP_HOME%\share\hadoop\mapreduce\*,
        %HADOOP_HOME%\share\hadoop\mapreduce\lib\*,
        %HADOOP_HOME%\share\hadoop\hdfs\*,
        %HADOOP_HOME%\share\hadoop\hdfs\lib\*,
        %HADOOP_HOME%\share\hadoop\yarn\*,
        %HADOOP_HOME%\share\hadoop\yarn\lib\*
    </value>
</property>
</configuration>

Following the only thing I managed to find on the internet about this issue I Tried editing yarn-site.xml changing LF to CRLF in Notepad++, but that didn't help at all.


问:
Is it possible to use Realm Mobile Platform sync server on port 80?
I would like to use the Realm Mobile Platform sync server over public wifi with only port 80 open in the firewall.

Is it possible to configure Realm Mobile Platform (Realm Object Server) and client API to work across port 80 rather than the default 9080?

答:
The docs say:

You must also choose a port number above 1024, as the Realm Object
  Server does not run as root. It is recommended to use the default port
  (9443).

If you would like to be able to connect to Realm Object Server on a
  port lower than 1024, such as the default HTTPS port 443, you can
  forward traffic to the port that Realm Object Server is listening on:

sudo iptables -A PREROUTING -t nat -p tcp --dport 443 -j REDIRECT
  --to-port 9443

So to successfully connect using port 80, you can leave the default http. listen_port at 9080 and run this command:

sudo iptables -A PREROUTING -t nat -p tcp --dport 80 -j REDIRECT --to-port 9080


问:
NameError: name 'csv' is not defined
I am new to Python, and I want to write a csv file, that lists the roots of my equation.
I am working on Sage.
My code is  :

```<code>with open('out.csv', 'w') as f:
    c = csv.writer(f)
    c.writerows(root)
</code>```

The error I am getting is " NameError: name 'csv' is not defined "

Can anybody help please?

答:
csv is not a builtin, although it's part of the standard library. You need to import it:

```<code>import csv

# your code
</code>```

Title: NameError: name 'csv' is not defined

Body:
I am new to Python, and I want to write a csv file, that lists the roots of my equation.
I am working on Sage.
My code is  :

with open('out.csv', 'w') as f:
    c = csv.writer(f)
    c.writerows(root)

The error I am getting is " NameError: name 'csv' is not defined "

Can anybody help please?

Body:
csv is not a builtin, although it's part of the standard library. You need to import it:

import csv

# your code


问:
Solidity Remix simple questions
Am new to Solidity here, this is the code I am testing and remix spits out

browser/Untitled.sol:1:1: : Source file does not specify required compiler version!Consider adding "pragma solidity ^0.4.12
contract C {
^
Spanning multiple lines.

Hopefully someone can give some guidance.

```<code>contract C {
    function bytes32ToString(bytes32 x) constant returns (string) {
        bytes memory bytesString = new bytes(32);
        uint charCount = 0;
        for (uint j = 0; j < 32; j++) {
            byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
            if (char != 0) {
                bytesString[charCount] = char;
                charCount++;
            }
        }
        bytes memory bytesStringTrimmed = new bytes(charCount);
        for (j = 0; j < charCount; j++) {
            bytesStringTrimmed[j] = bytesString[j];
        }
        return string(bytesStringTrimmed);
    }

    function bytes32ArrayToString(bytes32[] data) returns (string) {
        bytes memory bytesString = new bytes(data.length * 32);
        uint urlLength;
        for (uint i=0; i<data.length; i++) {
            for (uint j=0; j<32; j++) {
                byte char = byte(bytes32(uint(data[i]) * 2 ** (8 * j)));
                if (char != 0) {
                    bytesString[urlLength] = char;
                    urlLength += 1;
                }
            }
        }
        bytes memory bytesStringTrimmed = new bytes(urlLength);
        for (i=0; i<urlLength; i++) {
            bytesStringTrimmed[i] = bytesString[i];
        }
        return string(bytesStringTrimmed);
    }     }
</code>```

答:
This code is actually compiled, and the warning is just that: a warning.

It's suggested in the solidity docs to specify a compiler version, to reject compilation by compiler versions that may introduce breaking changes.

Try adding pragma solidity ^0.4.11; (or some other version) to the top of your file, and you'll see the warning disappear.

Your full file would now be:

```<code>pragma solidity ^0.4.11;

contract C {
    function bytes32ToString(bytes32 x) constant returns (string) {
        bytes memory bytesString = new bytes(32);
        uint charCount = 0;
        for (uint j = 0; j < 32; j++) {
            byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
            if (char != 0) {
                bytesString[charCount] = char;
                charCount++;
            }
        }
        bytes memory bytesStringTrimmed = new bytes(charCount);
        for (j = 0; j < charCount; j++) {
            bytesStringTrimmed[j] = bytesString[j];
        }
        return string(bytesStringTrimmed);
    }

    function bytes32ArrayToString(bytes32[] data) returns (string) {
        bytes memory bytesString = new bytes(data.length * 32);
        uint urlLength;
        for (uint i=0; i<data.length; i++) {
            for (uint j=0; j<32; j++) {
                byte char = byte(bytes32(uint(data[i]) * 2 ** (8 * j)));
                if (char != 0) {
                    bytesString[urlLength] = char;
                    urlLength += 1;
                }
            }
        }
        bytes memory bytesStringTrimmed = new bytes(urlLength);
        for (i=0; i<urlLength; i++) {
            bytesStringTrimmed[i] = bytesString[i];
        }
        return string(bytesStringTrimmed);
    }
}
</code>```

Title: Solidity Remix simple questions

Body:
Am new to Solidity here, this is the code I am testing and remix spits out

browser/Untitled.sol:1:1: : Source file does not specify required compiler version!Consider adding "pragma solidity ^0.4.12
contract C {
^
Spanning multiple lines.

Hopefully someone can give some guidance.

contract C {
    function bytes32ToString(bytes32 x) constant returns (string) {
        bytes memory bytesString = new bytes(32);
        uint charCount = 0;
        for (uint j = 0; j < 32; j++) {
            byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
            if (char != 0) {
                bytesString[charCount] = char;
                charCount++;
            }
        }
        bytes memory bytesStringTrimmed = new bytes(charCount);
        for (j = 0; j < charCount; j++) {
            bytesStringTrimmed[j] = bytesString[j];
        }
        return string(bytesStringTrimmed);
    }

    function bytes32ArrayToString(bytes32[] data) returns (string) {
        bytes memory bytesString = new bytes(data.length * 32);
        uint urlLength;
        for (uint i=0; i<data.length; i++) {
            for (uint j=0; j<32; j++) {
                byte char = byte(bytes32(uint(data[i]) * 2 ** (8 * j)));
                if (char != 0) {
                    bytesString[urlLength] = char;
                    urlLength += 1;
                }
            }
        }
        bytes memory bytesStringTrimmed = new bytes(urlLength);
        for (i=0; i<urlLength; i++) {
            bytesStringTrimmed[i] = bytesString[i];
        }
        return string(bytesStringTrimmed);
    }     }

Body:
This code is actually compiled, and the warning is just that: a warning.

It's suggested in the solidity docs to specify a compiler version, to reject compilation by compiler versions that may introduce breaking changes.

Try adding pragma solidity ^0.4.11; (or some other version) to the top of your file, and you'll see the warning disappear.

Your full file would now be:

pragma solidity ^0.4.11;

contract C {
    function bytes32ToString(bytes32 x) constant returns (string) {
        bytes memory bytesString = new bytes(32);
        uint charCount = 0;
        for (uint j = 0; j < 32; j++) {
            byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
            if (char != 0) {
                bytesString[charCount] = char;
                charCount++;
            }
        }
        bytes memory bytesStringTrimmed = new bytes(charCount);
        for (j = 0; j < charCount; j++) {
            bytesStringTrimmed[j] = bytesString[j];
        }
        return string(bytesStringTrimmed);
    }

    function bytes32ArrayToString(bytes32[] data) returns (string) {
        bytes memory bytesString = new bytes(data.length * 32);
        uint urlLength;
        for (uint i=0; i<data.length; i++) {
            for (uint j=0; j<32; j++) {
                byte char = byte(bytes32(uint(data[i]) * 2 ** (8 * j)));
                if (char != 0) {
                    bytesString[urlLength] = char;
                    urlLength += 1;
                }
            }
        }
        bytes memory bytesStringTrimmed = new bytes(urlLength);
        for (i=0; i<urlLength; i++) {
            bytesStringTrimmed[i] = bytesString[i];
        }
        return string(bytesStringTrimmed);
    }
}


问:
How do you store a list of directories into an array in Bash (and then print them out)?
I want to write a shell script to show a list of directories entered by a user and then for a user to select one of the directories with an index number based on how many directories there are

I'm thinking this is some kind of array operation, but im not sure how to do this in shell script

example:

```<code>> whichdir
There are 3 dirs in the current path
1 dir1
2 dir2
3 dir3
which dir do you want?
> 3
you selected dir3!
</code>```

答:
```<code>$ ls -a
./ ../ .foo/ bar/ baz qux*
$ shopt -s dotglob
$ shopt -s nullglob
$ array=(*/)
$ for dir in "${array[@]}"; do echo "$dir"; done
.foo/
bar/
$ for dir in */; do echo "$dir"; done
.foo/
bar/
$ PS3="which dir do you want? "
$ echo "There are ${#array[@]} dirs in the current path"; \
select dir in "${array[@]}"; do echo "you selected ${dir}"'!'; break; done
There are 2 dirs in the current path
1) .foo/
2) bar/
which dir do you want? 2
you selected bar/!
</code>```

Body:
I want to write a shell script to show a list of directories entered by a user and then for a user to select one of the directories with an index number based on how many directories there are

I'm thinking this is some kind of array operation, but im not sure how to do this in shell script

example:

> whichdir
There are 3 dirs in the current path
1 dir1
2 dir2
3 dir3
which dir do you want?
> 3
you selected dir3!


问:
Meteor Up deployment error
I am deploying meteor app using Meteor Up.
The development app is at the location /apps/proto/meteor/GatewayUI
and i have the .deploy folder which is inside the GatewayUI folder.
On giving the command "mup deploy", I get the following error

```<code>{ Error: spawn meteor ENOENT
at exports._errnoException (util.js:1018:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
at onErrorNT (internal/child_process.js:367:16)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn meteor',
path: 'meteor',  spawnargs:
[ 'build',
'--directory',
'/tmp/mup-meteor-981e8b09-055e-4ffe-a50a-d73d07c1ac5f',
'--architecture',
'os.linux.x86_64',
'--debug',
'--mobile-settings',
'/apps/proto/meteor/GatewayUI/settings.json' ] }
This error usually happens when meteor is not installed.
</code>```

My mup.js is as follows:

```<code>module.exports = {
servers: {
one: {
  // TODO: set host address, username, and authentication method
  host: 'myhost',
  username: 'myusername',
  // pem: './path/to/pem'
  password: 'mypassword'
  // or neither for authenticate from ssh-agent
}
},

meteor: {
// TODO: change app name and path
name: 'GatewayUI',
path: '../../GatewayUI/',

servers: {
  one: {},
},

buildOptions: {
debug: true,
executable: 'meteor',

},

env: {
  // TODO: Change to your app's url
  // If you are using ssl, it needs to start with https://
  ROOT_URL: 'http://gatewayui.com',
  MONGO_URL: 'mongodb://localhost/meteor',
},

// ssl: { // (optional)
//   // Enables let's encrypt (optional)
//   autogenerate: {
//     email: 'email.address@domain.com',
//     // comma seperated list of domains
//     domains: 'website.com,www.website.com'
//   }
// },

docker: {
  // change to 'kadirahq/meteord' if your app is not using Meteor 1.4
  image: 'abernix/meteord:base',
  // imagePort: 80, // (default: 80, some images EXPOSE different ports)
},

// This is the maximum time in seconds it will wait
// for your app to start
// Add 30 seconds if the server has 512mb of ram
// And 30 more if you have binary npm dependencies.
deployCheckWaitTime: 60,

// Show progress bar while uploading bundle to server
// You might need to disable it on CI servers
enableUploadProgressBar: true
},
 mongo: {
  port: 27199,
  version: '3.4.1',
  servers: {
    one: {}
  }
 }
};
</code>```

答:
A couple of things for this to not happen
1) make sure Meteor is installed. In my case, it was installed, however, the path was not set. It happened, because I forgot to add the path permanently
2) Docker, Mongo, Meteor should be installed in effect.
3) Every time, mup setup must precede mup deploy.

Title: Meteor Up deployment error

Body:
I am deploying meteor app using Meteor Up.
The development app is at the location /apps/proto/meteor/GatewayUI
and i have the .deploy folder which is inside the GatewayUI folder.
On giving the command "mup deploy", I get the following error

{ Error: spawn meteor ENOENT
at exports._errnoException (util.js:1018:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
at onErrorNT (internal/child_process.js:367:16)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn meteor',
path: 'meteor',  spawnargs:
[ 'build',
'--directory',
'/tmp/mup-meteor-981e8b09-055e-4ffe-a50a-d73d07c1ac5f',
'--architecture',
'os.linux.x86_64',
'--debug',
'--mobile-settings',
'/apps/proto/meteor/GatewayUI/settings.json' ] }
This error usually happens when meteor is not installed.

My mup.js is as follows:

module.exports = {
servers: {
one: {
  // TODO: set host address, username, and authentication method
  host: 'myhost',
  username: 'myusername',
  // pem: './path/to/pem'
  password: 'mypassword'
  // or neither for authenticate from ssh-agent
}
},

meteor: {
// TODO: change app name and path
name: 'GatewayUI',
path: '../../GatewayUI/',

servers: {
  one: {},
},

buildOptions: {
debug: true,
executable: 'meteor',

},

env: {
  // TODO: Change to your app's url
  // If you are using ssl, it needs to start with https://
  ROOT_URL: 'http://gatewayui.com',
  MONGO_URL: 'mongodb://localhost/meteor',
},

// ssl: { // (optional)
//   // Enables let's encrypt (optional)
//   autogenerate: {
//     email: 'email.address@domain.com',
//     // comma seperated list of domains
//     domains: 'website.com,www.website.com'
//   }
// },

docker: {
  // change to 'kadirahq/meteord' if your app is not using Meteor 1.4
  image: 'abernix/meteord:base',
  // imagePort: 80, // (default: 80, some images EXPOSE different ports)
},

// This is the maximum time in seconds it will wait
// for your app to start
// Add 30 seconds if the server has 512mb of ram
// And 30 more if you have binary npm dependencies.
deployCheckWaitTime: 60,

// Show progress bar while uploading bundle to server
// You might need to disable it on CI servers
enableUploadProgressBar: true
},
 mongo: {
  port: 27199,
  version: '3.4.1',
  servers: {
    one: {}
  }
 }
};


问:
Reading message from chronicle queue does not move the current index to the next cycle automatically
Reading message from chronicle queue does not move the current index to the next cycle automatically. I get the following logs messages:
697917 [SCHEDULER#4] INFO net.openhft.chronicle.queue.impl.single.SingleChronicleQueueExcerpts - Rolled 2 times to find the next cycle file. This can occur if you appenders have not written anything for a while, leaving the cycle files with a gap.

What does this means?

My queue files are : 20160824.cq4 20160826.cq4 20160829.cq4 20160830.cq4. The 20160825.cq4 file does not exist, because there was no data added to the queue.

答:
This is just FYI since I can't comment as I just signed up.  I was seeing a similar issue however not with the empty journals between days, just multiple days.  I was getting a false return from ExcerptTailer.readDocument and noticed that the index hopped by a number greater than 2^32 between my last index and my first indicating a cycle shift.  I only switched versions from

compile 'net.openhft:chronicle-queue:4.5.5'

compile 'net.openhft:chronicle-queue:4.5.27'

And the issue was resolved.  As I am just in a prototyping phase I have not had a need to keep up so was quite far behind.  I hope this helps and it does indeed look to be resolved for my case anyway.


答:
The reason '{ foo' requires quote is because this is part of the YAML specification 7.3.3 Plain Style.

Excerpt

Plain  scalars  must  never  contain  the  “: ”  and  “#”  character  combinations.  Such  combinations  would  cause  ambiguity  with mapping key: value pairs and comments. In addition, inside flow collections, or when used as implicit keys, plain scalars must
  not contain the “[”, “]”, “{”, “}” and “,” characters. These characters would cause ambiguity with flow collection structures.

Based on the above even your stated "return" value is incorrect and the body is probably enclosed in single quotes e.g.

```<code>response:
  code: 200
  body: '[{"id":"ef4b3a","title":"this is the title"},{"id":"a98c4f","title":"title of the second post"}]'
</code>```

Otherwise it would create ambiguity with "Flow Sequences" ([,]) and "Flow Mappings" ({,}).

If you would like result of the JSON, XML or other notation language to be represented appropriately (read objectively) then you will need to determine the correct parser (may be from the "Content-Type") and parse it before converting it YAML

Title: Ruby to_yaml stringifies my json

Body:
The reason '{ foo' requires quote is because this is part of the YAML specification 7.3.3 Plain Style.

Excerpt

Plain  scalars  must  never  contain  the  “: ”  and  “#”  character  combinations.  Such  combinations  would  cause  ambiguity  with mapping key: value pairs and comments. In addition, inside flow collections, or when used as implicit keys, plain scalars must
  not contain the “[”, “]”, “{”, “}” and “,” characters. These characters would cause ambiguity with flow collection structures.

Based on the above even your stated "return" value is incorrect and the body is probably enclosed in single quotes e.g.

response:
  code: 200
  body: '[{"id":"ef4b3a","title":"this is the title"},{"id":"a98c4f","title":"title of the second post"}]'

Otherwise it would create ambiguity with "Flow Sequences" ([,]) and "Flow Mappings" ({,}).

If you would like result of the JSON, XML or other notation language to be represented appropriately (read objectively) then you will need to determine the correct parser (may be from the "Content-Type") and parse it before converting it YAML


问:
C# - How to iterate through a list of lists
I have a class --

```<code>public class AccountNumber
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string AccountNumber_RecordID { get; set; }
    public string AccountNumber_SegmentLength { get; set; }
    public string AccountNumber_Number { get; set; }

}
</code>```

I'm using LINQ to XML to get the list --

```<code>List<AccountNumber> accNum =
 (from p in xmlDocument.Descendants("AccountNumber")
  select new AccountNumber
  {
      AccountNumber_RecordID = (string)p.Element("RecordID").Value,
      AccountNumber_SegmentLength = (string)p.Element("SegmentLength").Value,
      AccountNumber_Number = (string)p.Element("Number").Value
  }).ToList();
</code>```

I have a SQLite db created from the class AccountNumber. I want to use the entire list in an update statement. But how do i iterate through the list?

I want something like this, but not sure how to achieve it.

```<code>foreach accNum
        {
               db.Insert(accNum);
        }
</code>```

答:
Close with the foreach, it would be as follows:

```<code>    foreach (var acc in accNum)
    {
        db.Add(acc);
    }
    db.SaveChanges();
</code>```

Not forgetting to save changes.

Body:
I have a class --

public class AccountNumber
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string AccountNumber_RecordID { get; set; }
    public string AccountNumber_SegmentLength { get; set; }
    public string AccountNumber_Number { get; set; }

}

I'm using LINQ to XML to get the list --

List<AccountNumber> accNum =
 (from p in xmlDocument.Descendants("AccountNumber")
  select new AccountNumber
  {
      AccountNumber_RecordID = (string)p.Element("RecordID").Value,
      AccountNumber_SegmentLength = (string)p.Element("SegmentLength").Value,
      AccountNumber_Number = (string)p.Element("Number").Value
  }).ToList();

I have a SQLite db created from the class AccountNumber. I want to use the entire list in an update statement. But how do i iterate through the list?

I want something like this, but not sure how to achieve it.

foreach accNum
        {
               db.Insert(accNum);
        }

Body:
Close with the foreach, it would be as follows:

    foreach (var acc in accNum)
    {
        db.Add(acc);
    }
    db.SaveChanges();

Not forgetting to save changes.


问:
what regular expression can extract data I need?
I have a string

```<code>url = '//item.taobao.com/item.htm?id\u003d528341191030\u0026ns\u003d1\u0026abbucket\u003d0#detail'
</code>```

I like to extract the number 528341191030 between the first two \u. I tried this,

```<code>m = re.search('\?id\u\d+d(\d+?)\u', url)
if m:
  print m.group(1)
</code>```

But it doesn't work. What is wrong with my solution?

答:
Well, you could always try this (not super elegant but works):</p>

```<code>first = url.find('\u') + 2
prev = 'u'
m = ""
for i in range(first, len(url)):
    if prev == '\' and url[i] == 'u':
         break
    else:
        m += url[i]
    if url[i] == 'd':
        m = ""
</code>```

Body:
I have a string

url = '//item.taobao.com/item.htm?id\u003d528341191030\u0026ns\u003d1\u0026abbucket\u003d0#detail'

I like to extract the number 528341191030 between the first two \u. I tried this,

m = re.search('\?id\u\d+d(\d+?)\u', url)
if m:
  print m.group(1)

But it doesn't work. What is wrong with my solution?

Body:
Well, you could always try this (not super elegant but works):

first = url.find('\u') + 2
prev = 'u'
m = ""
for i in range(first, len(url)):
    if prev == '\' and url[i] == 'u':
         break
    else:
        m += url[i]
    if url[i] == 'd':
        m = ""


问:
How to check if a mouse is over a control
How does one check if the mouse is over a certain HWND? I have tried using the WM_MOUSELEAVE and WM_MOUSEMOVE messages to keep track, but if you click a button and drag the mouse out of the button, it doesn't receive the WM_MOUSELEAVE until the mouse is released, which is too late, because:

When you click a button, the WM_COMMAND message is only sent if:

1. The mouse was originally depressed over the button

2. The mouse is over the button

3. The mouse is released over the button

I need to replicate this functionality.

答:
To duplicate this functionality, just call SetCapture() so that mouse messages are sent to your window even if the mouse leaves it. You can read the current mouse position as it moves and determine if it is still over your window/button (I'm still not 100% sure what you are doing). And, when the mouse button is released, you can call ReleaseCapture() to restore where mouse messages are sent.

EDIT: Oh, and you can use the Windows API function WindowFromPoint() to determine which window the mouse is over.


问:
Picturebox location for X and Y is different then what is being entered in properties
I have 2 picture box's, a hero and an enemy. The hero seems to load fine at the location I specify in the properties of the PictureBox (0,0). However, the enemy picture box I want it to be set to location (90,90), which I do set it to that, but when I run the windows form - for some reason - it is showing the picture form is at location (60,58).

The hero PictureBox is the Green and the Enemy is Orange.

I am wanting to make a simple game and want to move the hero the exact size as the tile he is so that if you move the hero to where the enemy is they should stack up flat on top of each other. I have my form set to a full size of (300,300) and both picture boxes are a size of (30,30). So, they should be able to "move" 10 moves to the left and right - if they are set at a starting position of (0,0). I am not sure if it is my movement method that is messing me up but I also have zero ideas as to why the location of x and y are different when I tried to post it to console to debug this situation- instead of being 90,90 where I placed it on the form and in properties. Ideally I should be able to move 3 to the left and 3 down and be on top of the enemy but it's not at all correct.

Is there any reason why these are not the same? I will attach photos and my source code.

Starting Position

Hero Moving - They are not directly on top of each other but should be

Enemy Properties - to show size and location

Hero Properties - to show size and location

CODE

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mirage
{
public partial class Form1 : Form
{
Random rand = new Random();

public Form1()
{
    InitializeComponent();
    Console.WriteLine("HERO STARTING LOCATION --- X = : {0} ---- Y = : {1}", pctrBxHero.Location.X, pctrBxHero.Location.Y);
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Font myFont = new Font("Lucida", 10))
    {
        e.Graphics.DrawString("@", myFont, Brushes.Green, new Point(0, 0));
    }
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    int x = pctrBxHero.Location.X;
    int y = pctrBxHero.Location.Y;

    if (e.KeyCode == Keys.Right) x += 30;
    else if (e.KeyCode == Keys.Left) x -= 30;
    else if (e.KeyCode == Keys.Up) y -= 30;
    else if (e.KeyCode == Keys.Down) y += 30;

    pctrBxHero.Location = new Point(x, y);
    Console.WriteLine("HERO --- X = : {0} ---- Y = : {1}", x, y);
    Console.WriteLine("ENEMY --- X = : {0} ---- Y = : {1}", pctrBxEnemy.Location.X, pctrBxEnemy.Location.Y);
}

private void pictureBox2_Paint_1(object sender, PaintEventArgs e)
{

    using (Font myFont = new Font("Lucida", 10))
    {
        e.Graphics.DrawString("X", myFont, Brushes.Orange, new Point(0, 0));
    }
}
}
}
</code>```

答:
After a few hours of massive confusion I have fixed my problem. It turns out it was a scaling issue.

I had my form AutoScaleMode property set to "Font"- which is the default setting.

That was scaling my picture boxes down and scaling my form down. I believe the issue was so major is because I am using a laptop and a 24" monitor. I was running the program on my secondary monitor (the 24") and it was producing a warped result.

It seems as that building stuff by pixels, now-a-days, is less effective/attractive because of high Dpi screens.

Once I switched the form AutoScaleMode to Dpi the results did in fact yield a true 300x300 and my picture box's are exactly where they should be.

This is a tad annoying and took me awhile to realize but hopefully this will help someone else.

I am still not exactly sure as to why the pixels/frame would not show up as the 300x300 like I specified in the properties but it is now resolved. I would love to know why if anyone knows.

Body:
I have 2 picture box's, a hero and an enemy. The hero seems to load fine at the location I specify in the properties of the PictureBox (0,0). However, the enemy picture box I want it to be set to location (90,90), which I do set it to that, but when I run the windows form - for some reason - it is showing the picture form is at location (60,58).

The hero PictureBox is the Green and the Enemy is Orange.

I am wanting to make a simple game and want to move the hero the exact size as the tile he is so that if you move the hero to where the enemy is they should stack up flat on top of each other. I have my form set to a full size of (300,300) and both picture boxes are a size of (30,30). So, they should be able to "move" 10 moves to the left and right - if they are set at a starting position of (0,0). I am not sure if it is my movement method that is messing me up but I also have zero ideas as to why the location of x and y are different when I tried to post it to console to debug this situation- instead of being 90,90 where I placed it on the form and in properties. Ideally I should be able to move 3 to the left and 3 down and be on top of the enemy but it's not at all correct.

Is there any reason why these are not the same? I will attach photos and my source code.

Starting Position

Hero Moving - They are not directly on top of each other but should be

Enemy Properties - to show size and location

Hero Properties - to show size and location

CODE

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mirage
{
public partial class Form1 : Form
{
Random rand = new Random();

public Form1()
{
    InitializeComponent();
    Console.WriteLine("HERO STARTING LOCATION --- X = : {0} ---- Y = : {1}", pctrBxHero.Location.X, pctrBxHero.Location.Y);
}

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    using (Font myFont = new Font("Lucida", 10))
    {
        e.Graphics.DrawString("@", myFont, Brushes.Green, new Point(0, 0));
    }
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    int x = pctrBxHero.Location.X;
    int y = pctrBxHero.Location.Y;

    if (e.KeyCode == Keys.Right) x += 30;
    else if (e.KeyCode == Keys.Left) x -= 30;
    else if (e.KeyCode == Keys.Up) y -= 30;
    else if (e.KeyCode == Keys.Down) y += 30;

    pctrBxHero.Location = new Point(x, y);
    Console.WriteLine("HERO --- X = : {0} ---- Y = : {1}", x, y);
    Console.WriteLine("ENEMY --- X = : {0} ---- Y = : {1}", pctrBxEnemy.Location.X, pctrBxEnemy.Location.Y);
}

private void pictureBox2_Paint_1(object sender, PaintEventArgs e)
{

    using (Font myFont = new Font("Lucida", 10))
    {
        e.Graphics.DrawString("X", myFont, Brushes.Orange, new Point(0, 0));
    }
}
}
}


问:
Dynamic tabs and tables in Rmarkdown with kable
I am using the following code to create dynamic tabs with tables in Rmarkdown.

```<code># TEST
``` {r echo=FALSE, results = 'asis', message = FALSE, warnings = FALSE}
print_month <- function(month) {
  cat("   \n##", format(month, "%B"), " results    \n")
  print(knitr::kable(data.frame(A = c(1,2,3), B = c(1,2,3))))
  cat("   \n")
}

seq.Date(from = ymd(20170101), to = ymd(20170601), by = 'month') %>%
  purrr::walk(print_month)
```
</code>```

I have seen it working before, but I can't really narrow down why it fails sometimes. When it fails it looks like this

The tables are paragraphs when I look into the HTML code, but when working normally it should be rendered as a table...

答:
Maybe the print() and cat() functions might be interacting with each other?

I prefer functions to return a single assembled string, and let the caller decide how to output it.

```<code>library(magrittr)
library(lubridate)
assemble_month <- function(month) {
  d <- mtcars[1:5, 1:6] #data.frame(A = c(1,2,3), B = c(1,2,3))
  html_table <- knitr::kable(d, format = "html")
  paste0(
    "\n##", format(month, "%B"), " results\n",
    html_table,
    "\n"
  )
}

seq.Date(from = ymd(20170101), to = ymd(20170601), by = 'month') %>%
  purrr::map_chr(assemble_month) %>%
  cat()
</code>```

A disadvantage with my approach though is it outputs the html table in a way fails to leverage knitr's nice markdown-to-html css formatting.  I typically add styling back with kableExtra, so html_table becomes

```<code>  html_table <- mtcars[1:5, 1:6] %>%
    knitr::kable(format = "html") %>%
    kableExtra::kable_styling(
      bootstrap_options = c("striped", "hover", "condensed", "responsive"),
      full_width = F
    )
</code>```

(I used a bigger example table to make it look more realistic.)

Body:
I am using the following code to create dynamic tabs with tables in Rmarkdown.

# TEST
``` {r echo=FALSE, results = 'asis', message = FALSE, warnings = FALSE}
print_month <- function(month) {
  cat("   \n##", format(month, "%B"), " results    \n")
  print(knitr::kable(data.frame(A = c(1,2,3), B = c(1,2,3))))
  cat("   \n")
}

seq.Date(from = ymd(20170101), to = ymd(20170601), by = 'month') %>%
  purrr::walk(print_month)
```

I have seen it working before, but I can't really narrow down why it fails sometimes. When it fails it looks like this

The tables are paragraphs when I look into the HTML code, but when working normally it should be rendered as a table...

Body:
Maybe the print() and cat() functions might be interacting with each other?

I prefer functions to return a single assembled string, and let the caller decide how to output it.

library(magrittr)
library(lubridate)
assemble_month <- function(month) {
  d <- mtcars[1:5, 1:6] #data.frame(A = c(1,2,3), B = c(1,2,3))
  html_table <- knitr::kable(d, format = "html")
  paste0(
    "\n##", format(month, "%B"), " results\n",
    html_table,
    "\n"
  )
}

seq.Date(from = ymd(20170101), to = ymd(20170601), by = 'month') %>%
  purrr::map_chr(assemble_month) %>%
  cat()

A disadvantage with my approach though is it outputs the html table in a way fails to leverage knitr's nice markdown-to-html css formatting.  I typically add styling back with kableExtra, so html_table becomes

  html_table <- mtcars[1:5, 1:6] %>%
    knitr::kable(format = "html") %>%
    kableExtra::kable_styling(
      bootstrap_options = c("striped", "hover", "condensed", "responsive"),
      full_width = F
    )

(I used a bigger example table to make it look more realistic.)


问:
Insufficient Privilege during update
I'm getting an insufficient privilege while updating the table in B schema. The table owner is A schema but I have given the update grant to B schema, even then it is throwing an error. If i give the Select grant along with update it is working. Why I need to give select grant along with update if i just want to update the table. I'm using Exadata as my back end version</p>

答:
Update works, without need granting select provilage, as shown below. I used Oracle for this test case.

SQL> create user test1 identified by test1 profile default ;

User created.

SQL> grant connect , resource to test1 ;

Grant succeeded.

SQL> create user test2 identified by test2 profile default ;

User created.

SQL> grant connect , resource to test2 ;

Grant succeeded.

SQL> connect test1/test1
Connected.
SQL> create table abc (name varchar2(20) ) ;

Table created.

SQL> insert into test1.abc values ('xyz') ;

1 row created.

SQL> commit
  2  ;

Commit complete.

SQL> select * from test1.abc
  2  ;

NAME

xyz

SQL> grant update on test1.abc to test2 ;

Grant succeeded.

SQL> connect test2/test2
Connected.

SQL> update test1.abc set  name='XXYYZZ' ;

1 row updated.

SQL> commit
  2  ;

Commit complete.

SQL> connect test1/test1
Connected.
SQL> select * from abc ;

NAME

XXYYZZ

Title: Insufficient Privilege during update


答: Cycle through the string of words and store each in a dictionary(using python) and number of times they occur as the value.</p>

Title: Given a file, find the ten most frequently occurring words as efficiently as possible

Body:
This is apparently an interview question (found it in a collection of interview questions), but even if it's not it's pretty cool.

We are told to do this efficiently on all complexity measures. I thought of creating a HashMap that maps the words to their frequency. That would be O(n) in time and space complexity, but since there may be lots of words we cannot assume that we can store everything in memory.

I must add that nothing in the question says that the words cannot be stored in memory, but what if that were the case? If that's not the case, then the question does not seem as challenging.