问:
Spring Data Neo4j @GraphId and @Index
Can anyone exmplain the difference betwen @GraphId and @Index annotation from org.neo4j.ogm.annotation ?
For now, after reading the docs it seems that @GraphId is used to create identifier for Neo4j internal logic and users should not rely on that, because it can be reused over time. But what about @Index?

As I understand, the main advantage of graph based databases is that once we know the node/relation from which to start things become easy, since all we need to do is just traverse the graph from that starting node. And indexing helps  to do so, right? So, we can write something like START n = node:index_name(property_name = value) and immitiately start exloring the graph from the indexed node by 'property_name' property, right?

So, consider this entity :

```<code>@ToString
@NodeEntity(label = "Event")
@NoArgsConstructor
public class Event{

    public Event(String eventName, LocalDate dateTime){
        this.name = eventName;
        this.date = dateTime;
    }

    public Event(Long id, String eventName, LocalDate dateTime){
        this(eventName, dateTime);
        this.id = id;
    }

    @Getter
    @GraphId
    private Long id;

    @Getter
    @Index(unique = true, primary = true)
    @Property(name = "name")
    private String name;

    @Getter
    @Property(name = "date")
    @Convert(DateConverter.class)
    private LocalDate date;
}
</code>```

As you can see the String name property is annotated with @Index. How can I write Cypher query to actually start from the node with name = 'something'? What is the index name? Or does Spring Data Neo4j 4.2.0.RELEASE figure it itself when write just MATCH (event:Event {name = 'somehting'} ... ?

```<code>@Repository
public interface EventRepository extends Neo4jRepository<Event, String>{

    Event findOne(String eventName);

}
</code>```

Here the repositry class and as you might see I am using String as the type of the id of the entity the repository manages, so I assume Spring uses name property of Event class to generate a query for Event findOne(String eventName);

答:
@Index is similar to @Indexed if your are familiar with spring-data-mongodb or @Index in spring-data-jpa. Basically it indexes the field(among other things) which makes it searching for this field quite fast.<br>
  Regarding your repository method, it should be named like this   </p>

```<code>Event findByName(String eventName);
</code>```

Title: Spring Data Neo4j @GraphId and @Index

Body:
Can anyone exmplain the difference betwen @GraphId and @Index annotation from org.neo4j.ogm.annotation ?
For now, after reading the docs it seems that @GraphId is used to create identifier for Neo4j internal logic and users should not rely on that, because it can be reused over time. But what about @Index?

As I understand, the main advantage of graph based databases is that once we know the node/relation from which to start things become easy, since all we need to do is just traverse the graph from that starting node. And indexing helps  to do so, right? So, we can write something like START n = node:index_name(property_name = value) and immitiately start exloring the graph from the indexed node by 'property_name' property, right?

So, consider this entity :

@ToString
@NodeEntity(label = "Event")
@NoArgsConstructor
public class Event{

    public Event(String eventName, LocalDate dateTime){
        this.name = eventName;
        this.date = dateTime;
    }

    public Event(Long id, String eventName, LocalDate dateTime){
        this(eventName, dateTime);
        this.id = id;
    }

    @Getter
    @GraphId
    private Long id;

    @Getter
    @Index(unique = true, primary = true)
    @Property(name = "name")
    private String name;

    @Getter
    @Property(name = "date")
    @Convert(DateConverter.class)
    private LocalDate date;
}

As you can see the String name property is annotated with @Index. How can I write Cypher query to actually start from the node with name = 'something'? What is the index name? Or does Spring Data Neo4j 4.2.0.RELEASE figure it itself when write just MATCH (event:Event {name = 'somehting'} ... ?

@Repository
public interface EventRepository extends Neo4jRepository<Event, String>{

    Event findOne(String eventName);

}

Here the repositry class and as you might see I am using String as the type of the id of the entity the repository manages, so I assume Spring uses name property of Event class to generate a query for Event findOne(String eventName);

Body:
@Index is similar to @Indexed if your are familiar with spring-data-mongodb or @Index in spring-data-jpa. Basically it indexes the field(among other things) which makes it searching for this field quite fast.

  Regarding your repository method, it should be named like this

Event findByName(String eventName);


来源: stackexchange

问:
Best way to restrict access by IP address?
For an ASP.NET C# application, we will need to restrict access based on IP address. What is the best way to accomplish this?</p>

答:
One way is using a HttpModule.

From the link (in case it ever goes away):

```<code>/// <summary>
/// HTTP module to restrict access by IP address
/// </summary>

public class SecurityHttpModule : IHttpModule
{
 public SecurityHttpModule() { }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(Application_BeginRequest);
    }

    private void Application_BeginRequest(object source, EventArgs e)
    {
        HttpContext context = ((HttpApplication)source).Context;
        string ipAddress = context.Request.UserHostAddress;
        if (!IsValidIpAddress(ipAddress))
        {
            context.Response.StatusCode = 403;  // (Forbidden)

        }
    }

    private bool IsValidIpAddress(string ipAddress)
    {
        return (ipAddress == "127.0.0.1");
    }

    public void Dispose() { /* clean up */ }
}
</code>```

Once the HTTP Module class is built you need to register it in the httpModules section of your web.config file, like this:

```<code><configuration>
    <system.web>
        <httpModules>
            <add name="SecurityHttpModule" type="SecurityHttpModule"/>
        </httpModules>
    </system.web>
</configuration>
</code>```

This adds the module to the ASP.NET request pipeline for your web application.

OwnerDisplayName: Keb

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: Keb

Body:
One way is using a HttpModule.

From the link (in case it ever goes away):

/// <summary>
/// HTTP module to restrict access by IP address
/// </summary>

public class SecurityHttpModule : IHttpModule
{
 public SecurityHttpModule() { }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(Application_BeginRequest);
    }

    private void Application_BeginRequest(object source, EventArgs e)
    {
        HttpContext context = ((HttpApplication)source).Context;
        string ipAddress = context.Request.UserHostAddress;
        if (!IsValidIpAddress(ipAddress))
        {
            context.Response.StatusCode = 403;  // (Forbidden)

        }
    }

    private bool IsValidIpAddress(string ipAddress)
    {
        return (ipAddress == "127.0.0.1");
    }

    public void Dispose() { /* clean up */ }
}

Once the HTTP Module class is built you need to register it in the httpModules section of your web.config file, like this:

<configuration>
    <system.web>
        <httpModules>
            <add name="SecurityHttpModule" type="SecurityHttpModule"/>
        </httpModules>
    </system.web>
</configuration>

This adds the module to the ASP.NET request pipeline for your web application.

OwnerDisplayName: Mitch Wheat


问:
Why is this Objective-C code leaking memory?
Why does this leak?

The arrayOfPerformances is a NSMutableArray, (nonatomic, retain) property that is synthesized.

The currentPerformanceObject is a Performance *, (nonatomic, retain) property that is synthesized.

Performance is a custom class

```<code>if(self.arrayOfPerformances == nil)
    {
        self.arrayOfPerformances = [[NSMutableArray alloc]init];
    }

    [self.arrayOfPerformances addObject:currentPerformanceObject];
    [currentPerformanceObject release];
    currentPerformanceObject = nil;
</code>```

答:
You are creating a new array and retaining it at the same time in this line, because you are invoking a (retain) property setter with the dot notation:

```<code>// Your property
@property (nonatomic, retain) NSMutableArray *arrayOfPerformances;

// The offending code
self.arrayOfPerformances = [[NSMutableArray alloc]init];
</code>```

Because of that, the locally-created array is leaking because you don't release it. You should autorelease that array, or create a temporary local var, assign, then release the local var, like so:

```<code>// Either this
self.arrayOfPerformances = [[[NSMutableArray alloc] init] autorelease];

// Or this (props Nick Forge, does the same as above)
self.arrayOfPerformances = [NSMutableArray array];

// Or this
NSMutableArray *newArray = [[NSMutableArray alloc] init];
self.arrayOfPerformances = newArray;
[newArray release];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Why does this leak?

The arrayOfPerformances is a NSMutableArray, (nonatomic, retain) property that is synthesized.

The currentPerformanceObject is a Performance *, (nonatomic, retain) property that is synthesized.

Performance is a custom class

if(self.arrayOfPerformances == nil)
    {
        self.arrayOfPerformances = [[NSMutableArray alloc]init];
    }

    [self.arrayOfPerformances addObject:currentPerformanceObject];
    [currentPerformanceObject release];
    currentPerformanceObject = nil;

Body:
You are creating a new array and retaining it at the same time in this line, because you are invoking a (retain) property setter with the dot notation:

// Your property
@property (nonatomic, retain) NSMutableArray *arrayOfPerformances;

// The offending code
self.arrayOfPerformances = [[NSMutableArray alloc]init];

Because of that, the locally-created array is leaking because you don't release it. You should autorelease that array, or create a temporary local var, assign, then release the local var, like so:

// Either this
self.arrayOfPerformances = [[[NSMutableArray alloc] init] autorelease];

// Or this (props Nick Forge, does the same as above)
self.arrayOfPerformances = [NSMutableArray array];

// Or this
NSMutableArray *newArray = [[NSMutableArray alloc] init];
self.arrayOfPerformances = newArray;
[newArray release];


问:
How to create a SQL query with optional parameters in Python Flask?
How to create a SQL query with optional parameters in Python Flask?

I use a HTML form to filter the data from a SQL table. The form has multiple optional fields. How can I create a SQL query based on the filled fields in the form?

For example, if the users fill in 3 fields "name", "amount" and "itemtype", the query is like:

```<code>rows = cursor.execute("""SELECT * FROM items WHERE name = ? AND amount=? AND itemtype = ? """, name, amount, itemtype).fetchall()
</code>```

If they skip "amount", the query is like:

```<code>rows = cursor.execute("""SELECT * FROM items WHERE name = ? AND itemtype = ? """, name, itemtype).fetchall()
</code>```

答:
<s>I prefer to use Python's format string function for this. It's splitting hairs, but format allows to set name in the string, so it's technically more explicit. However, I would suggest using **kwargs instead of *args, so you don't have to rely on magic.</s>

UPADATE 2019

This was a terrible answer. You never, ever, EVER want to take user generated data and interpolate it directly into a SQL query. It is imperative that you always sanitize user input in order to protect against SQL injection. Python has defined a database API specification that any database package that is not an ORM like SQLAlchemy should implement. Long story short, you should be NEVER, EVER, EVER use str.format(), %, or "fstrings" to interpolate data into your SQL queries.

The database API specification provides a way to safely interpolate data into queries. Every python database interface should have a Cursor class that is returned from a Connection object. The Cursor class will implement a method named execute. This obviously will execute a query, but it will also have a second argument–usually called args. According to the specification:

Parameters may be provided as sequence or mapping and will be bound to variables in the operation. Variables are specified in a database-specific notation (see the module's paramstyle attribute for details).

By "sequence", it means that args can be a list or tuple, and by "mapping", it means that args can also be a dict. Depending on the package, the way to specify where your data should be interpolated may differ. There are six options for this. Which formatting the package you're using can be found in the paramstyle constant of the package. For instance, PyMySQL(and most implementations of the spec that I've used) uses format and pyformat. A simple example would be:

format

```<code>cursor.execute('SELECT * FROM t WHERE a = %s, b = %s;', (1, 'baz'))
</code>```

pyformat

```<code>cursor.execute('SELECT * FROM t WHERE a = %(foo)s, b = %(bar)s;', {'foo': 1, 'bar': 'baz'})
</code>```

Both of these would execute as:

```<code>SELECT * FROM t WHERE a = 1, b = 'baz';
</code>```

You should make sure to explore the documentation of the database API package you're using. One extremely helpful thing I came across using psycopg2, a PostgresSQL package, was its extras module. For instance, a common problem when trying to insert data securely is encountered when inserting multiple rows at once. psycopg2 has a clever solution to this problem in its execute_values function. Using execute_values, this code:

```<code>execute_values(cursor, "INSERT INTO t (a, b) VALUES %s;", ((1, 'foo'), (2, 'baz')))
</code>```

... is executed as:

```<code>"INSERT INTO t (a, b) VALUES (1, 'foo'), (2, 'baz');"
</code>```

Body:
How to create a SQL query with optional parameters in Python Flask?

I use a HTML form to filter the data from a SQL table. The form has multiple optional fields. How can I create a SQL query based on the filled fields in the form?

For example, if the users fill in 3 fields "name", "amount" and "itemtype", the query is like:

rows = cursor.execute("""SELECT * FROM items WHERE name = ? AND amount=? AND itemtype = ? """, name, amount, itemtype).fetchall()

If they skip "amount", the query is like:

rows = cursor.execute("""SELECT * FROM items WHERE name = ? AND itemtype = ? """, name, itemtype).fetchall()

Body:
<s>I prefer to use Python's format string function for this. It's splitting hairs, but format allows to set name in the string, so it's technically more explicit. However, I would suggest using **kwargs instead of *args, so you don't have to rely on magic.</s>

UPADATE 2019

This was a terrible answer. You never, ever, EVER want to take user generated data and interpolate it directly into a SQL query. It is imperative that you always sanitize user input in order to protect against SQL injection. Python has defined a database API specification that any database package that is not an ORM like SQLAlchemy should implement. Long story short, you should be NEVER, EVER, EVER use str.format(), %, or "fstrings" to interpolate data into your SQL queries.

The database API specification provides a way to safely interpolate data into queries. Every python database interface should have a Cursor class that is returned from a Connection object. The Cursor class will implement a method named execute. This obviously will execute a query, but it will also have a second argument–usually called args. According to the specification:

Parameters may be provided as sequence or mapping and will be bound to variables in the operation. Variables are specified in a database-specific notation (see the module's paramstyle attribute for details).

By "sequence", it means that args can be a list or tuple, and by "mapping", it means that args can also be a dict. Depending on the package, the way to specify where your data should be interpolated may differ. There are six options for this. Which formatting the package you're using can be found in the paramstyle constant of the package. For instance, PyMySQL(and most implementations of the spec that I've used) uses format and pyformat. A simple example would be:

format

cursor.execute('SELECT * FROM t WHERE a = %s, b = %s;', (1, 'baz'))

pyformat

cursor.execute('SELECT * FROM t WHERE a = %(foo)s, b = %(bar)s;', {'foo': 1, 'bar': 'baz'})

Both of these would execute as:

SELECT * FROM t WHERE a = 1, b = 'baz';

You should make sure to explore the documentation of the database API package you're using. One extremely helpful thing I came across using psycopg2, a PostgresSQL package, was its extras module. For instance, a common problem when trying to insert data securely is encountered when inserting multiple rows at once. psycopg2 has a clever solution to this problem in its execute_values function. Using execute_values, this code:

execute_values(cursor, "INSERT INTO t (a, b) VALUES %s;", ((1, 'foo'), (2, 'baz')))

... is executed as:

"INSERT INTO t (a, b) VALUES (1, 'foo'), (2, 'baz');"

ContentLicense: CC BY-SA 4.0


问:
How does Git compute SHA hashes so quickly?
I know git is fast but I have only recently found how fast it really can be.

In one of my projects, I am trying to compute SHA-256 hashes of a huge file (82 MB with 850k rows) and it took over a minute to compute it (includes hashing and a couple of other small operations).

Even with SHA-1, it took me 30+ seconds while git seems to be doing it in just a second or two.

I am computing the hash in Scala using java's Security API by combining all the lines of the file.

```<code>val lines = Source.fromFile(filePath, "UTF-8").getLines().toList
MessageDigest.getInstance("SHA-256")
.digest(lines.mkString("\n").getBytes).map("%02x".format(_)).mkString
</code>```

So, how does Git do it so quickly, or rather the more important question, why is my method so slow?

Edit: For those not familiar with scala syntax, lines will have all the lines of the file in a List and mkString method returns a string of all the elements in the list combined with the given separator.

答:
The hash computation is redirected at compile time to a specific implementation in cache.h.  The underlying platform may provide an optimized (e.g., assembler or machine-dependent C coded) hash routine.  Of course, your Java implementation may or may not also provide such a routine.

If the platform does not have its own implementation, Git provides one written in C that works on large memory blocks, and still has some hand-tweaks and inline asms with architecture and compiler ifdefs.

Body:
I know git is fast but I have only recently found how fast it really can be.

In one of my projects, I am trying to compute SHA-256 hashes of a huge file (82 MB with 850k rows) and it took over a minute to compute it (includes hashing and a couple of other small operations).

Even with SHA-1, it took me 30+ seconds while git seems to be doing it in just a second or two.

I am computing the hash in Scala using java's Security API by combining all the lines of the file.

val lines = Source.fromFile(filePath, "UTF-8").getLines().toList
MessageDigest.getInstance("SHA-256")
.digest(lines.mkString("\n").getBytes).map("%02x".format(_)).mkString

So, how does Git do it so quickly, or rather the more important question, why is my method so slow?

Edit: For those not familiar with scala syntax, lines will have all the lines of the file in a List and mkString method returns a string of all the elements in the list combined with the given separator.


问:
New to C#, can anyone explain to me how enums and setting variables for enums works?
I'm sure this is a very simple question, but I'm learning how to program in C# and the "flow" of this text adventure program makes perfect sense to me, but I'm confused how  the third line "private States myState;" works.

As you can see, the program starts by setting the variable myState to States.cell, which calls a void method (not shown below) that waits for a key that changes the variable "myState" thus updating the update function.

My question is, how does the "enum" class work? It seems as though it's possible to make a variable from the "enum States" line, but I don't understand why that is. Sorry if this is a really stupid question.

Here's the code:

```<code>        public Text text;
private enum States {cell, sheets_0, mirror, lock_0, sheets_1, cell_mirror, lock_1, freedom};
private States myState;

// Use this for initialization
void Start () {
    myState = States.cell;
}

// Update is called once per frame
void Update () {
    print (myState);
        if      (myState == States.cell){           state_cell();}
        else if (myState == States.sheets_0){       state_sheets_0();}
        else if (myState == States.mirror){         state_mirror();}
        else if (myState == States.lock_0){         state_lock_0();}
        else if (myState == States.sheets_1){       state_sheets_1();}
        else if (myState == States.cell_mirror){    state_cell_mirror();}
        else if (myState == States.lock_1){         state_lock_1();}
        else if (myState == States.freedom){        state_freedom();}
}
</code>```

答:
An enum is basically a special type that lets you define named values. You're creating a named type just as you would if you were defining a class. What your code is actually doing is first defining your enumerated type called States with all the possible named values, then declaring a variable "myState" using the enum type "States" that you defined in the line before. What you can't see in your code is that by default in c# the underlying type for your enum is an integer, and each of your possible values also has an integer value assigned to it which could be overridden if needed, so all you're really doing in your update code is an integer comparison. Is there any reason you're not using a switch instead of that big if/else block? Also you could eliminate the start function and just instantiate your myState variable like this:

```<code>private States myState = States.cell;
</code>```

MSDN has pretty good documentation for it here:

https://msdn.microsoft.com/en-us/library/sbbt4032.aspx

Body:
I'm sure this is a very simple question, but I'm learning how to program in C# and the "flow" of this text adventure program makes perfect sense to me, but I'm confused how  the third line "private States myState;" works.

As you can see, the program starts by setting the variable myState to States.cell, which calls a void method (not shown below) that waits for a key that changes the variable "myState" thus updating the update function.

My question is, how does the "enum" class work? It seems as though it's possible to make a variable from the "enum States" line, but I don't understand why that is. Sorry if this is a really stupid question.

Here's the code:

        public Text text;
private enum States {cell, sheets_0, mirror, lock_0, sheets_1, cell_mirror, lock_1, freedom};
private States myState;

// Use this for initialization
void Start () {
    myState = States.cell;
}

// Update is called once per frame
void Update () {
    print (myState);
        if      (myState == States.cell){           state_cell();}
        else if (myState == States.sheets_0){       state_sheets_0();}
        else if (myState == States.mirror){         state_mirror();}
        else if (myState == States.lock_0){         state_lock_0();}
        else if (myState == States.sheets_1){       state_sheets_1();}
        else if (myState == States.cell_mirror){    state_cell_mirror();}
        else if (myState == States.lock_1){         state_lock_1();}
        else if (myState == States.freedom){        state_freedom();}
}

Body:
An enum is basically a special type that lets you define named values. You're creating a named type just as you would if you were defining a class. What your code is actually doing is first defining your enumerated type called States with all the possible named values, then declaring a variable "myState" using the enum type "States" that you defined in the line before. What you can't see in your code is that by default in c# the underlying type for your enum is an integer, and each of your possible values also has an integer value assigned to it which could be overridden if needed, so all you're really doing in your update code is an integer comparison. Is there any reason you're not using a switch instead of that big if/else block? Also you could eliminate the start function and just instantiate your myState variable like this:

private States myState = States.cell;

MSDN has pretty good documentation for it here:

https://msdn.microsoft.com/en-us/library/sbbt4032.aspx


问:
how to handle deprecation warning in momentjs
I want to use momentjs to check for invalid date/time strings:

```<code>var invalid = '2017-03-18 23;00;00';
if (moment(invalid).isValid()) {
  return 'valid date'
}
</code>```

This (correctly) throws a stacktrace with the familiar 'Deprecation warning: value provided is not in a recognized RFC2822 or ISO format......'

But even if I add a try/catch:

```<code>try {
  var invalid = '2017-03-18 23;00;00';
  if (moment(invalid).isValid()) {
    return 'valid date'
  }
catch (err) {
  throw Error ('invalid date format');
}
</code>```

the stacktrace is still printed.
What do I need to do to avoid the stacktrace from being printed?

I've searched all similar questions on StackOverflow but they all try to solve a different problem (fixing the input or finding the correct syntax to parse the input).

I using v2.18.1.

答:
You have to use moment(String, String); to parse your input. If you don't want to specify a format (or an array of formats), you can use moment.ISO_8601. As the docs says:

Moment already supports parsing iso-8601 strings, but this can be specified explicitly in the format/list of formats when constructing a moment

This way you will not have deprecation warning. Here a working example:

var invalid = '2017-03-18 23;00;00';
if (moment(invalid, moment.ISO_8601).isValid()) {
  console.log('valid date');
} else {
  console.log('invalid date');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

PS. Anyway, if you have a list of accepted format, I suggest to use moment(String, String[]); (and strict parsing, if needed).

Body:
I want to use momentjs to check for invalid date/time strings:

var invalid = '2017-03-18 23;00;00';
if (moment(invalid).isValid()) {
  return 'valid date'
}

This (correctly) throws a stacktrace with the familiar 'Deprecation warning: value provided is not in a recognized RFC2822 or ISO format......'

But even if I add a try/catch:

try {
  var invalid = '2017-03-18 23;00;00';
  if (moment(invalid).isValid()) {
    return 'valid date'
  }
catch (err) {
  throw Error ('invalid date format');
}

the stacktrace is still printed.
What do I need to do to avoid the stacktrace from being printed?

I've searched all similar questions on StackOverflow but they all try to solve a different problem (fixing the input or finding the correct syntax to parse the input).

I using v2.18.1.

Body:
You have to use moment(String, String); to parse your input. If you don't want to specify a format (or an array of formats), you can use moment.ISO_8601. As the docs says:

Moment already supports parsing iso-8601 strings, but this can be specified explicitly in the format/list of formats when constructing a moment

This way you will not have deprecation warning. Here a working example:

var invalid = '2017-03-18 23;00;00';
if (moment(invalid, moment.ISO_8601).isValid()) {
  console.log('valid date');
} else {
  console.log('invalid date');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

PS. Anyway, if you have a list of accepted format, I suggest to use moment(String, String[]); (and strict parsing, if needed).


问:
how can i move around the board for knights tour [java]
I'm trying to make a knights tour program. Right now I have it so the knight starts at around the middle of the board and moves in a circle. But now if I want the knight to start at 0,0 I just get errors saying array out of bounds. I'm guessing that I need a method to check to see if its safe to move the next point but I'm not too sure.

Here is the code I have right now.

```<code>public class Knight1 {

    public static void main(String[] args) {
        int board[][] = new int[8][8];
        int horizontal[] = new int[8];
        int vertical[] = new int[8];

        horizontal[0] = 2;
        horizontal[1] = 1;
        horizontal[2] = -1;
        horizontal[3] = -2;
        horizontal[4] = -2;
        horizontal[5] = -1;
        horizontal[6] = 1;
        horizontal[7] = 2;

        vertical[0] = -1;
        vertical[1] = -2;
        vertical[2] = -2;
        vertical[3] = -1;
        vertical[4] = 1;
        vertical[5] = 2;
        vertical[6] = 2;
        vertical[7] = 1;

        int moveNumber = 0;
        int currentRow = 0;
        int currentCol = 0;
        int counter = 1;
        int x = 0;
        int y = 7;
        int xOffset[] = {x + 1, x + 1, x + 2, x + 2, x - 1, x - 1, x - 2, x - 2};
        int yOffset[] = {y - 2, y + 2, y - 1, y + 1, y - 2, y + 2, y - 1, y + 1};
        for (int i = 0; i < 8; i++) {
            if (xOffset[i] >= 0 && yOffset[i] >= 0 && xOffset[i] < 8 && yOffset[i] < 8) {
                currentRow = xOffset[i];
                currentCol =  yOffset[i];
                Board[currentRow][currentCol] = counter;
                counter++;
            }
        }
        printBoard(board);
    }

    public static void printBoard(int[][] board) {
        for (int x = 0; x < 8; x++) {
            for (int y = 0; y < 8; y++) {
                System.out.print("  " + board[x][y]);
            }
            System.out.println();
        }
    }
}
</code>```

答:
Problem is in while condition, a hint for solution is that you must exclude -2 and -1 when currentRow/Column is 0(only exclude -2 if it is 1), also exclude +1 and +2 when currentRow/Column is 7(only +2 when it is 6) otherwise your index in board[currentRow][currentCol] = counter; will be out of bounds.

Here is how rules for knight movement could look:

```<code>    int x = 0;
    int y = 7;
    int xOffset[] = {x + 1, x + 1, x + 2, x + 2, x - 1, x - 1, x - 2, x - 2};
    int yOffset[] = {y - 2, y + 2, y - 1, y + 1, y - 2, y + 2, y - 1, y + 1};
    for (int i = 0; i < 8; i++) {
        if (xOffset[i] >= 0 && yOffset[i] >= 0 && xOffset[i] < 8 && yOffset[i] < 8) {
            // X and Y are currentRow and currentColumn in your example
            // Code is copied from my java chess game and I was lazy to change variable everywhere
            x = xOffset[i];
            y = yOffset[i];
        }
    }
</code>```

Body:
I'm trying to make a knights tour program. Right now I have it so the knight starts at around the middle of the board and moves in a circle. But now if I want the knight to start at 0,0 I just get errors saying array out of bounds. I'm guessing that I need a method to check to see if its safe to move the next point but I'm not too sure.

Here is the code I have right now.

public class Knight1 {

    public static void main(String[] args) {
        int board[][] = new int[8][8];
        int horizontal[] = new int[8];
        int vertical[] = new int[8];

        horizontal[0] = 2;
        horizontal[1] = 1;
        horizontal[2] = -1;
        horizontal[3] = -2;
        horizontal[4] = -2;
        horizontal[5] = -1;
        horizontal[6] = 1;
        horizontal[7] = 2;

        vertical[0] = -1;
        vertical[1] = -2;
        vertical[2] = -2;
        vertical[3] = -1;
        vertical[4] = 1;
        vertical[5] = 2;
        vertical[6] = 2;
        vertical[7] = 1;

        int moveNumber = 0;
        int currentRow = 0;
        int currentCol = 0;
        int counter = 1;
        int x = 0;
        int y = 7;
        int xOffset[] = {x + 1, x + 1, x + 2, x + 2, x - 1, x - 1, x - 2, x - 2};
        int yOffset[] = {y - 2, y + 2, y - 1, y + 1, y - 2, y + 2, y - 1, y + 1};
        for (int i = 0; i < 8; i++) {
            if (xOffset[i] >= 0 && yOffset[i] >= 0 && xOffset[i] < 8 && yOffset[i] < 8) {
                currentRow = xOffset[i];
                currentCol =  yOffset[i];
                Board[currentRow][currentCol] = counter;
                counter++;
            }
        }
        printBoard(board);
    }

    public static void printBoard(int[][] board) {
        for (int x = 0; x < 8; x++) {
            for (int y = 0; y < 8; y++) {
                System.out.print("  " + board[x][y]);
            }
            System.out.println();
        }
    }
}

Body:
Problem is in while condition, a hint for solution is that you must exclude -2 and -1 when currentRow/Column is 0(only exclude -2 if it is 1), also exclude +1 and +2 when currentRow/Column is 7(only +2 when it is 6) otherwise your index in board[currentRow][currentCol] = counter; will be out of bounds.

Here is how rules for knight movement could look:

    int x = 0;
    int y = 7;
    int xOffset[] = {x + 1, x + 1, x + 2, x + 2, x - 1, x - 1, x - 2, x - 2};
    int yOffset[] = {y - 2, y + 2, y - 1, y + 1, y - 2, y + 2, y - 1, y + 1};
    for (int i = 0; i < 8; i++) {
        if (xOffset[i] >= 0 && yOffset[i] >= 0 && xOffset[i] < 8 && yOffset[i] < 8) {
            // X and Y are currentRow and currentColumn in your example
            // Code is copied from my java chess game and I was lazy to change variable everywhere
            x = xOffset[i];
            y = yOffset[i];
        }
    }


答:
Its pretty simple:

the porpose of this line:

```<code>private enum States {cell, sheets_0, mirror, lock_0, sheets_1, cell_mirror, lock_1, freedom};
</code>```

Is to define an enum named "States"

The porpose of the line after it:

```<code>private States myState;
</code>```

Is to create an instance of the type "State" named "my state"

Title: New to C#, can anyone explain to me how enums and setting variables for enums works?

Body:
Its pretty simple:

the porpose of this line:

private enum States {cell, sheets_0, mirror, lock_0, sheets_1, cell_mirror, lock_1, freedom};

Is to define an enum named "States"

The porpose of the line after it:

private States myState;

Is to create an instance of the type "State" named "my state"


答:
If your .arrayOfPerformances property is never released (it would usually be released in -dealloc), than the array itself, plus any object in the array will be leaked when this object is dealloced.

You need to release both properties in your -dealloc:

```<code>- (void)dealloc
{
    ... other deallocs
    self.arrayOfPerformances = nil;
    self.currentPerformanceObject = nil;
    [super dealloc];
}
</code>```

Also, as @BoltClock has pointed out, you need to release or auto-release your NSMutableArray. The best way to do this is to initialize it using the autoreleased method:

```<code>self.arrayOfPerformances = [NSMutableArray array];
</code>```

Also, you don't need to release your currentPerformanceObject, you should just set the property to nil, since setting the retained property to nil will release it for you. Your code should probably look something like this:

```<code>if (self.arrayOfPerformances == nil) {
    self.arrayOfPerformances = [NSMutableArray array];
}
[self.arrayOfPerformances addObject:self.currentPerformanceObject];
self.currentPerformanceObject = nil;
</code>```

Title: Why is this Objective-C code leaking memory?

Body:
If your .arrayOfPerformances property is never released (it would usually be released in -dealloc), than the array itself, plus any object in the array will be leaked when this object is dealloced.

You need to release both properties in your -dealloc:

- (void)dealloc
{
    ... other deallocs
    self.arrayOfPerformances = nil;
    self.currentPerformanceObject = nil;
    [super dealloc];
}

Also, as @BoltClock has pointed out, you need to release or auto-release your NSMutableArray. The best way to do this is to initialize it using the autoreleased method:

self.arrayOfPerformances = [NSMutableArray array];

Also, you don't need to release your currentPerformanceObject, you should just set the property to nil, since setting the retained property to nil will release it for you. Your code should probably look something like this:

if (self.arrayOfPerformances == nil) {
    self.arrayOfPerformances = [NSMutableArray array];
}
[self.arrayOfPerformances addObject:self.currentPerformanceObject];
self.currentPerformanceObject = nil;


问:
How to avoid zombie processes in python?
In Python3, I have essentially the following code:

server.py:

```<code>import os
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 10000))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.listen(5)

while True:
    print("waiting")
    connection, client_address = sock.accept()
    print("received")
    child_pid = os.fork()
    if child_pid == 0:
        print("connection received")
        received = connection.recv(1024)
        connection.sendall("OK".encode('utf-8'))
        os._exit(0)
</code>```

client.py:

```<code>import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 10000))
sock.close()
</code>```

When I start the server and then the client, each time the client finishes a zombie process remains.

How to change the code so that no zombie process remains?

答:
When a process exits, it remains in the process table until something reads its return code. Assuming this is linux, you could make it a daemon and have the init process deal with it. But you could also just call os.waitpid yourself. Here is an example of a class that waits for pids in the background. Its nice becaue it keeps your program from exiting until its fully tidied itself up. You could expand it to do things like sending kill signals to child processes, logging results, and etc.

```<code>import threading
import queue
import os
import time

class ZombieKiller(threading.Thread):
    """Okay, really its just a zombie waiter, but where's the fun in that?
    """
    def __init__(self):
        super().__init__()
        self.pid_q = queue.Queue()
        self.start()

    def run(self):
        while True:
            pid = self.pid_q.get()
            if pid is None:
                return
            print(pid, 'wait')
            os.waitpid(pid, 0)
            print(pid, 'wait done')

    def cull_zombie(self, pid):
        self.pid_q.put(pid)

    def close(self):
        self.pid_q.put(None)
        self.join()

def test():
    zombie_killer = ZombieKiller()
    for i in range(3):
        pid = os.fork()
        if pid == 0:
            # child
            time.sleep(5)
            print(os.getpid(), 'work done')
            exit()
        else:
            # parent
            zombie_killer.cull_zombie(pid)
    zombie_killer.close()
    print('test complete')

test()
</code>```

Body:
In Python3, I have essentially the following code:

server.py:

import os
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 10000))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.listen(5)

while True:
    print("waiting")
    connection, client_address = sock.accept()
    print("received")
    child_pid = os.fork()
    if child_pid == 0:
        print("connection received")
        received = connection.recv(1024)
        connection.sendall("OK".encode('utf-8'))
        os._exit(0)

client.py:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 10000))
sock.close()

When I start the server and then the client, each time the client finishes a zombie process remains.

How to change the code so that no zombie process remains?

Body:
When a process exits, it remains in the process table until something reads its return code. Assuming this is linux, you could make it a daemon and have the init process deal with it. But you could also just call os.waitpid yourself. Here is an example of a class that waits for pids in the background. Its nice becaue it keeps your program from exiting until its fully tidied itself up. You could expand it to do things like sending kill signals to child processes, logging results, and etc.

import threading
import queue
import os
import time

class ZombieKiller(threading.Thread):
    """Okay, really its just a zombie waiter, but where's the fun in that?
    """
    def __init__(self):
        super().__init__()
        self.pid_q = queue.Queue()
        self.start()

    def run(self):
        while True:
            pid = self.pid_q.get()
            if pid is None:
                return
            print(pid, 'wait')
            os.waitpid(pid, 0)
            print(pid, 'wait done')

    def cull_zombie(self, pid):
        self.pid_q.put(pid)

    def close(self):
        self.pid_q.put(None)
        self.join()

def test():
    zombie_killer = ZombieKiller()
    for i in range(3):
        pid = os.fork()
        if pid == 0:
            # child
            time.sleep(5)
            print(os.getpid(), 'work done')
            exit()
        else:
            # parent
            zombie_killer.cull_zombie(pid)
    zombie_killer.close()
    print('test complete')

test()


问:
Batch script to remove parentheses and spaces from all file names
I have to manipulate dozens if not hundreds of images fairly often. When I get the images, it's often 1018u182012480d1j80.jpg type filenames, so I can select all of the images, and then hit 'F2' to rename them all to image (1).jpg | image (2).jpg | ... etc. Can someone write me a batch script to remove the parentheses and the spaces in the file names?

If possible, it'd be great if I didn't even have to open it up and edit the batch file to update the current dir, I.E, if it can just use %CD% or something to get the current folder, that would be awesome.

I don't understand batch files at all but here's one I found that will remove the parentheses, but I have to add the sourcedir.

```<code>@ECHO OFF
SETLOCAL
SET "sourcedir=C:\.." #Can we make this just find the location?
FOR /f "delims=" %%a IN (
  'dir /b /s /a-d "%sourcedir%\*" '
 ) DO (
 SET "name=%%~na"
 SETLOCAL ENABLEDELAYEDEXPANSION
 SET "newname=!name:)=!"
 SET "newname=!newname:(=!"
 IF "!name!" neq "!newname!" (
  IF EXIST "%%~dpa!newname!%%~xa" (ECHO cannot RENAME %%a
   ) ELSE (REN "%%a" "!newname!%%~xa")

 )
 endlocal
)
</code>```

答:
The script should work if file names/paths does not contain any ! exclamation mark.

Supply a folder path as an argument (see sample calls below). This can be done even by file explorer's drag&drop feature (drag a folder, drop on batch). Read call /? or Command Line arguments (Parameters) for %~1 explanation.

Narrow to only .jpg files using "%sourcedir%\*.jpg" in FOR /f line.

```<code>@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion

SET "sourcedir=%~1"                               supplied string
if NOT defined sourcedir SET "sourcedir=%CD%"     current directory if nothing supplied

rem basic validity check
if NOT exist "%sourcedir%\*" (
  echo wrong directory "%sourcedir%"
  goto :next
)
FOR /f "delims=" %%a IN ('dir /b /s /a-d "%sourcedir%\*" ') DO (
  SET "name=%%~na"
  SETLOCAL ENABLEDELAYEDEXPANSION
      rem     remove ) right parenthesis
  SET "newname=!name:)=!"
      rem        remove ( left parenthesis
  SET "newname=!newname:(=!"
      rem        remove ↓ space(s)
  SET "newname=!newname: =!"
  IF "!name!" neq "!newname!" (
      IF EXIST "%%~dpa!newname!%%~xa" (
        ECHO cannot RENAME %%a
      ) ELSE (
        rem operational RENAME command is merely ECHO-ed for debugging purposes
        ECHO RENAME "%%a" "!newname!%%~xa"
      )
  )
  ENDLOCAL
)
:next
rem pause to see output
pause
</code>```

Sample call without argument - applies to the current directory:

```<code>d:\bat\SU> D:\bat\SO\43097467.bat
RENAME "d:\bat\SU\New Text Document.txt" "NewTextDocument.txt"
RENAME "d:\bat\SU\Files\ruzna pisma.png" "ruznapisma.png"
RENAME "d:\bat\SU\Files\volume control options.png" "volumecontroloptions.png"
RENAME "d:\bat\SU\Files\volume mixer.png" "volumemixer.png"
RENAME "d:\bat\SU\Files\1126981\ERKS 100004_thumb.jpg" "ERKS100004_thumb.jpg"
Press any key to continue . . .
</code>```

Sample call with argument - applies to the supplied directory:

```<code>d:\bat\SU> D:\bat\SO\43097467.bat D:\test\43097467
RENAME "D:\test\43097467\image do - Copy (2).bmp" "imagedo-Copy2.bmp"
cannot RENAME D:\test\43097467\image do - Copy (3).bmp
RENAME "D:\test\43097467\image do - Copy (4).bmp" "imagedo-Copy4.bmp"
Press any key to continue . . .
</code>```

Sample call, argument with spaces must be enclosed in a pair of double quotes:

```<code>d:\bat\SU> D:\bat\SO\43097467.bat "D:\bat\odds and ends\a b"
RENAME "D:\bat\odds and ends\a b\c d\my list_Utf8.txt" "mylist_Utf8.txt"
RENAME "D:\bat\odds and ends\a b\c d\e f\h i batch.bat" "hibatch.bat"
RENAME "D:\bat\odds and ends\a b\c d\e f\System locale.png" "Systemlocale.png"
Press any key to continue . . .

d:\bat\SU>
</code>```

Body:
I have to manipulate dozens if not hundreds of images fairly often. When I get the images, it's often 1018u182012480d1j80.jpg type filenames, so I can select all of the images, and then hit 'F2' to rename them all to image (1).jpg | image (2).jpg | ... etc. Can someone write me a batch script to remove the parentheses and the spaces in the file names?

If possible, it'd be great if I didn't even have to open it up and edit the batch file to update the current dir, I.E, if it can just use %CD% or something to get the current folder, that would be awesome.

I don't understand batch files at all but here's one I found that will remove the parentheses, but I have to add the sourcedir.

@ECHO OFF
SETLOCAL
SET "sourcedir=C:\.." #Can we make this just find the location?
FOR /f "delims=" %%a IN (
  'dir /b /s /a-d "%sourcedir%\*" '
 ) DO (
 SET "name=%%~na"
 SETLOCAL ENABLEDELAYEDEXPANSION
 SET "newname=!name:)=!"
 SET "newname=!newname:(=!"
 IF "!name!" neq "!newname!" (
  IF EXIST "%%~dpa!newname!%%~xa" (ECHO cannot RENAME %%a
   ) ELSE (REN "%%a" "!newname!%%~xa")

 )
 endlocal
)

Body:
The script should work if file names/paths does not contain any ! exclamation mark.

Supply a folder path as an argument (see sample calls below). This can be done even by file explorer's drag&drop feature (drag a folder, drop on batch). Read call /? or Command Line arguments (Parameters) for %~1 explanation.

Narrow to only .jpg files using "%sourcedir%\*.jpg" in FOR /f line.

@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion

SET "sourcedir=%~1"                               supplied string
if NOT defined sourcedir SET "sourcedir=%CD%"     current directory if nothing supplied

rem basic validity check
if NOT exist "%sourcedir%\*" (
  echo wrong directory "%sourcedir%"
  goto :next
)
FOR /f "delims=" %%a IN ('dir /b /s /a-d "%sourcedir%\*" ') DO (
  SET "name=%%~na"
  SETLOCAL ENABLEDELAYEDEXPANSION
      rem     remove ) right parenthesis
  SET "newname=!name:)=!"
      rem        remove ( left parenthesis
  SET "newname=!newname:(=!"
      rem        remove ↓ space(s)
  SET "newname=!newname: =!"
  IF "!name!" neq "!newname!" (
      IF EXIST "%%~dpa!newname!%%~xa" (
        ECHO cannot RENAME %%a
      ) ELSE (
        rem operational RENAME command is merely ECHO-ed for debugging purposes
        ECHO RENAME "%%a" "!newname!%%~xa"
      )
  )
  ENDLOCAL
)
:next
rem pause to see output
pause

Sample call without argument - applies to the current directory:

d:\bat\SU> D:\bat\SO\43097467.bat
RENAME "d:\bat\SU\New Text Document.txt" "NewTextDocument.txt"
RENAME "d:\bat\SU\Files\ruzna pisma.png" "ruznapisma.png"
RENAME "d:\bat\SU\Files\volume control options.png" "volumecontroloptions.png"
RENAME "d:\bat\SU\Files\volume mixer.png" "volumemixer.png"
RENAME "d:\bat\SU\Files\1126981\ERKS 100004_thumb.jpg" "ERKS100004_thumb.jpg"
Press any key to continue . . .

Sample call with argument - applies to the supplied directory:

d:\bat\SU> D:\bat\SO\43097467.bat D:\test\43097467
RENAME "D:\test\43097467\image do - Copy (2).bmp" "imagedo-Copy2.bmp"
cannot RENAME D:\test\43097467\image do - Copy (3).bmp
RENAME "D:\test\43097467\image do - Copy (4).bmp" "imagedo-Copy4.bmp"
Press any key to continue . . .

Sample call, argument with spaces must be enclosed in a pair of double quotes:

d:\bat\SU> D:\bat\SO\43097467.bat "D:\bat\odds and ends\a b"
RENAME "D:\bat\odds and ends\a b\c d\my list_Utf8.txt" "mylist_Utf8.txt"
RENAME "D:\bat\odds and ends\a b\c d\e f\h i batch.bat" "hibatch.bat"
RENAME "D:\bat\odds and ends\a b\c d\e f\System locale.png" "Systemlocale.png"
Press any key to continue . . .

d:\bat\SU>


问:
I want to use my raw input use my functions
I have a program that i've been working on to see if I can use a raw input with my functions

```<code>class object:
# this shows that x is on top of y
    def on(self,x,y):
        self.x = x
        self.y = y
        x = 1
        y = 0

        if x > y:
            print True
        else:
            print False
# this clears x making nothing be on top of x
    def clear(self,x):
        self.x = x
        x = None
        print(x)
#  this shows that x is bigger than y
    def heavy(self,x,y):
        self.x = x
        self.y = y
        x = 1
        y = 0

        if x > y:
            print True
        else:
            print False

    input = raw_input("Enter an object: (Type stop to stop the loop): ") # raw input allows me to write string without the quotes
    obj = ""
    while input != ("stop"):
        obj = obj + " " + input
        input = raw_input("Enter an object: ")
    print ("These are the objects: " + obj)
# this is a loop that allows the user to enter as many objects until they type stop
</code>```

What i would like to happen is when the user enters a word of two, I can use the functions that i created. for example If i use on() (first function) it will display (on(word1,word2) and if i use clear it will display (clear(word1) clearing the second word. I just wanted to know if i am on the right track. Hope that is well explained thanks
hope to be apart of this great community :)

答:
If I understand what you are asking take a look at what I have below.

Below I have 4 defined variables. 3 of them will perform a different task. The 4th one is used to figure out what variable to use. I hope this points you in the right direction.

```<code>def random_words(word,word2):
    print (word +"\n"+"First"+"\n"+ word2)

# you can decide how to print each string given.
# This will allow you to place one on top of the other.
# the "\n" will print the following string on the next line.

def other_words(word,word2):
    print (word +" Second "+ word2)

def more_words(word,word2):
    print (word +" Third "+ word2)

def select_def(sdef,word,word2): # This variable will decide the others
    if sdef == "1":
        random_words(word,word2)
    elif sdef == "2":
        other_words(word,word2)
    else:
        more_words(word,word2)

var1= str(input("Enter a number -->"))
var2= str(input("Enter a Word -->"))
var3= str(input("Enter another -->"))

select_def(var1,var2,var3)
</code>```

Example to call the function.

```<code>select_def("2","Makin","Bacon") #You can use something like this in an input function.
</code>```

result:

```<code>>>>
Makin Second Bacon
</code>```

2nd example:

```<code>select_def("1","Makin","Bacon")
</code>```

result:

```<code>>>>
Makin
First
Bacon
</code>```

Body:
I have a program that i've been working on to see if I can use a raw input with my functions

class object:
# this shows that x is on top of y
    def on(self,x,y):
        self.x = x
        self.y = y
        x = 1
        y = 0

        if x > y:
            print True
        else:
            print False
# this clears x making nothing be on top of x
    def clear(self,x):
        self.x = x
        x = None
        print(x)
#  this shows that x is bigger than y
    def heavy(self,x,y):
        self.x = x
        self.y = y
        x = 1
        y = 0

        if x > y:
            print True
        else:
            print False

    input = raw_input("Enter an object: (Type stop to stop the loop): ") # raw input allows me to write string without the quotes
    obj = ""
    while input != ("stop"):
        obj = obj + " " + input
        input = raw_input("Enter an object: ")
    print ("These are the objects: " + obj)
# this is a loop that allows the user to enter as many objects until they type stop

What i would like to happen is when the user enters a word of two, I can use the functions that i created. for example If i use on() (first function) it will display (on(word1,word2) and if i use clear it will display (clear(word1) clearing the second word. I just wanted to know if i am on the right track. Hope that is well explained thanks
hope to be apart of this great community :)

Body:
If I understand what you are asking take a look at what I have below.

Below I have 4 defined variables. 3 of them will perform a different task. The 4th one is used to figure out what variable to use. I hope this points you in the right direction.

def random_words(word,word2):
    print (word +"\n"+"First"+"\n"+ word2)

# you can decide how to print each string given.
# This will allow you to place one on top of the other.
# the "\n" will print the following string on the next line.

def other_words(word,word2):
    print (word +" Second "+ word2)

def more_words(word,word2):
    print (word +" Third "+ word2)

def select_def(sdef,word,word2): # This variable will decide the others
    if sdef == "1":
        random_words(word,word2)
    elif sdef == "2":
        other_words(word,word2)
    else:
        more_words(word,word2)

var1= str(input("Enter a number -->"))
var2= str(input("Enter a Word -->"))
var3= str(input("Enter another -->"))

select_def(var1,var2,var3)

Example to call the function.

select_def("2","Makin","Bacon") #You can use something like this in an input function.

result:

>>>
Makin Second Bacon

2nd example:

select_def("1","Makin","Bacon")

result:

>>>
Makin
First
Bacon


问:
remove duplicates from an array - vba
I have a code, that grabs data from a column of a file, and puts it into an array.

now, I want to go through this array and delete duplicates but I can't make it go through... any ideas?

this is the code, and the array is at the end:

```<code>Dim i As Long
Dim searchItem As Variant
strSearch = ""
searchItem = ""
strFile = "...\Desktop\xl files min\src.xlsm"
Set s_wbk = Workbooks.Open(strFile)
With s_wbk.Worksheets("Sheet1")
    For i = 1 To Rows.Count
        If Not IsEmpty(Cells(i, 1).Value) Then
           strSearch = strSearch & "," & Cells(i, 1).Value
        End If
    Next i
End With
s_wbk.Close
searchItem = Split(strSearch, ",") '*NEED TO REMOVE DUPLICATES
</code>```

答:
This worked for me:

```<code>Function removeDuplicates(ByVal myArray As Variant) As Variant

Dim d As Object
Dim v As Variant 'Value for function
Dim outputArray() As Variant
Dim i As Integer

Set d = CreateObject("Scripting.Dictionary")

For i = LBound(myArray) To UBound(myArray)

    d(myArray(i)) = 1

Next i

i = 0
For Each v In d.Keys()

    ReDim Preserve outputArray(0 To i)
    outputArray(i) = v
    i = i + 1

Next v

removeDuplicates = outputArray

End Function
</code>```

Hope it helps

Title: remove duplicates from an array - vba

Body:
I have a code, that grabs data from a column of a file, and puts it into an array.

now, I want to go through this array and delete duplicates but I can't make it go through... any ideas?

this is the code, and the array is at the end:

Dim i As Long
Dim searchItem As Variant
strSearch = ""
searchItem = ""
strFile = "...\Desktop\xl files min\src.xlsm"
Set s_wbk = Workbooks.Open(strFile)
With s_wbk.Worksheets("Sheet1")
    For i = 1 To Rows.Count
        If Not IsEmpty(Cells(i, 1).Value) Then
           strSearch = strSearch & "," & Cells(i, 1).Value
        End If
    Next i
End With
s_wbk.Close
searchItem = Split(strSearch, ",") '*NEED TO REMOVE DUPLICATES

Body:
This worked for me:

Function removeDuplicates(ByVal myArray As Variant) As Variant

Dim d As Object
Dim v As Variant 'Value for function
Dim outputArray() As Variant
Dim i As Integer

Set d = CreateObject("Scripting.Dictionary")

For i = LBound(myArray) To UBound(myArray)

    d(myArray(i)) = 1

Next i

i = 0
For Each v In d.Keys()

    ReDim Preserve outputArray(0 To i)
    outputArray(i) = v
    i = i + 1

Next v

removeDuplicates = outputArray

End Function

Hope it helps


问:
pure opengl zoom camera to mouse pos
Im trying to edit my mouse zoom function to zoom towards the mouse pos in 3d world, I can get the 3d cords of the mouse if i need that just not sure how to do it.

At the moment my zoom just zooms towards the screen center.

```<code>void CCamera::OnMouseWheel(float zDelta)
{
    Position -= Reference;

    if(zDelta < 0 && length(Position) < 500.0f)
    {
        Position += Position * 0.1f;
    }

    if(zDelta > 0 && length(Position) > 0.05f)
    {
        Position -= Position * 0.1f;
    }

    Position += Reference;

    CalculateViewMatrix();
}

void CCamera::CalculateViewMatrix()
{
    ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
    ViewMatrixInverse = inverse(ViewMatrix);
    ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
    ViewProjectionMatrixInverse = ViewMatrixInverse * ProjectionMatrixInverse;
}
</code>```

答:
You may need to do some editing on your code to make sure everything is compatible such as editing the viewgraph. But here is a code snippet from my project that does exactly what you are saying. I think that the code is pretty self-explanatory,

```<code>void modelDefinition::onMouseWheel(wxMouseEvent &event)
{
    if(event.GetWheelRotation() != 0)
    {
        /* This section of the code was adapted from Agro2D */

        _cameraX += (((2.0 / this->GetSize().GetWidth()) * (event.GetX() - this->GetSize().GetWidth() / 2.0)) / _zoomFactor) * (this->GetSize().GetWidth() / this->GetSize().GetHeight());
        _cameraY += (-(2.0 / this->GetSize().GetHeight()) * (event.GetY() - this->GetSize().GetHeight() / 2.0)) / _zoomFactor;

        if(!_preferences.getMouseZoomReverseState())
        {
            if(event.GetWheelRotation() > 0)
                _zoomFactor *= pow(1.2, -(event.GetWheelDelta()) / 150.0);
            else
                _zoomFactor *= pow(1.2, (event.GetWheelDelta()) / 150.0);
        }
        else
        {
            if(event.GetWheelRotation() < 0)
                _zoomFactor *= pow(1.2, -(event.GetWheelDelta()) / 150.0);
            else
                _zoomFactor *= pow(1.2, (event.GetWheelDelta()) / 150.0);
        }

        /* This will recalculate the new position of the mouse. Assuming that the mouse does not move at all during the process
         * This also enables the feature where the zoom will zoom in/out at the position of the mouse */

        _cameraX -= (((2.0 / this->GetSize().GetWidth()) * (event.GetX() - this->GetSize().GetWidth() / 2.0)) / _zoomFactor) * (this->GetSize().GetWidth() / this->GetSize().GetHeight());
        _cameraY -= (-(2.0 / this->GetSize().GetHeight()) * (event.GetY() - this->GetSize().GetHeight() / 2.0)) / _zoomFactor;
    }

    this->Refresh();// This will force the canvas to experience a redraw event
}
</code>```

I should mention that the function this->Refresh will just cause my screen to update. Yours might be different.

Also, _cameraX and _cameraY stores the offset of the openGL canvas.

Here is the constructor for my canvas:

```<code>modelDefinition::modelDefinition(wxWindow *par, const wxPoint &point, const wxSize &size, problemDefinition &definition) : wxGLCanvas(par, wxID_ANY, NULL, point, size, wxBORDER_DOUBLE | wxBORDER_RAISED)
{
    _geometryContext = new wxGLContext(this);
    wxGLCanvas::SetCurrent(*_geometryContext);

    _localDefinition = &definition;

    _editor.setZoomFactorAddress(_zoomFactor);

    glViewport(0, 0, (double)this->GetSize().GetWidth(), (double)this->GetSize().GetHeight());

    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);// The matrix mode specifies which matrix stack is the target for matrix operations
    glLoadIdentity();// Initial value
    glTranslated((float)this->GetSize().GetWidth() / 2.0f, (float)this->GetSize().GetHeight() / 2.0f, 0.0f);// This will move the camera to the center of the screen

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
    GLenum error = glGetError();
    if(error != GL_NO_ERROR)
    {
    //  wxMessageBox("Error - " + gluErrorString(error));
        return;
    }

    glMatrixMode(GL_MODELVIEW);
}
</code>```

And here is the code that handles updating the position of my view:

```<code>void modelDefinition::updateProjection()
{
    // First, load the projection matrix and reset the view to a default view
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    //Reset to modelview matrix
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    /* This section will handle the translation (panning) and scaled (zooming).
     * Needs to be called each time a draw occurs in order to update the placement of all the components */
    if(_zoomFactor < 1e-9)
        _zoomFactor = 1e-9;

    if(_zoomFactor > 1e6)
        _zoomFactor = 1e6;

    glScaled(_zoomFactor / (this->GetSize().GetWidth() / this->GetSize().GetHeight()), _zoomFactor, 1.0);

    glTranslated(-_cameraX, -_cameraY, 0.0);
}
</code>```

Title: pure opengl zoom camera to mouse pos

Body:
Im trying to edit my mouse zoom function to zoom towards the mouse pos in 3d world, I can get the 3d cords of the mouse if i need that just not sure how to do it.

At the moment my zoom just zooms towards the screen center.

void CCamera::OnMouseWheel(float zDelta)
{
    Position -= Reference;

    if(zDelta < 0 && length(Position) < 500.0f)
    {
        Position += Position * 0.1f;
    }

    if(zDelta > 0 && length(Position) > 0.05f)
    {
        Position -= Position * 0.1f;
    }

    Position += Reference;

    CalculateViewMatrix();
}

void CCamera::CalculateViewMatrix()
{
    ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f);
    ViewMatrixInverse = inverse(ViewMatrix);
    ViewProjectionMatrix = ProjectionMatrix * ViewMatrix;
    ViewProjectionMatrixInverse = ViewMatrixInverse * ProjectionMatrixInverse;
}

Body:
You may need to do some editing on your code to make sure everything is compatible such as editing the viewgraph. But here is a code snippet from my project that does exactly what you are saying. I think that the code is pretty self-explanatory,

void modelDefinition::onMouseWheel(wxMouseEvent &event)
{
    if(event.GetWheelRotation() != 0)
    {
        /* This section of the code was adapted from Agro2D */

        _cameraX += (((2.0 / this->GetSize().GetWidth()) * (event.GetX() - this->GetSize().GetWidth() / 2.0)) / _zoomFactor) * (this->GetSize().GetWidth() / this->GetSize().GetHeight());
        _cameraY += (-(2.0 / this->GetSize().GetHeight()) * (event.GetY() - this->GetSize().GetHeight() / 2.0)) / _zoomFactor;

        if(!_preferences.getMouseZoomReverseState())
        {
            if(event.GetWheelRotation() > 0)
                _zoomFactor *= pow(1.2, -(event.GetWheelDelta()) / 150.0);
            else
                _zoomFactor *= pow(1.2, (event.GetWheelDelta()) / 150.0);
        }
        else
        {
            if(event.GetWheelRotation() < 0)
                _zoomFactor *= pow(1.2, -(event.GetWheelDelta()) / 150.0);
            else
                _zoomFactor *= pow(1.2, (event.GetWheelDelta()) / 150.0);
        }

        /* This will recalculate the new position of the mouse. Assuming that the mouse does not move at all during the process
         * This also enables the feature where the zoom will zoom in/out at the position of the mouse */

        _cameraX -= (((2.0 / this->GetSize().GetWidth()) * (event.GetX() - this->GetSize().GetWidth() / 2.0)) / _zoomFactor) * (this->GetSize().GetWidth() / this->GetSize().GetHeight());
        _cameraY -= (-(2.0 / this->GetSize().GetHeight()) * (event.GetY() - this->GetSize().GetHeight() / 2.0)) / _zoomFactor;
    }

    this->Refresh();// This will force the canvas to experience a redraw event
}

I should mention that the function this->Refresh will just cause my screen to update. Yours might be different.

Also, _cameraX and _cameraY stores the offset of the openGL canvas.

Here is the constructor for my canvas:

modelDefinition::modelDefinition(wxWindow *par, const wxPoint &point, const wxSize &size, problemDefinition &definition) : wxGLCanvas(par, wxID_ANY, NULL, point, size, wxBORDER_DOUBLE | wxBORDER_RAISED)
{
    _geometryContext = new wxGLContext(this);
    wxGLCanvas::SetCurrent(*_geometryContext);

    _localDefinition = &definition;

    _editor.setZoomFactorAddress(_zoomFactor);

    glViewport(0, 0, (double)this->GetSize().GetWidth(), (double)this->GetSize().GetHeight());

    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);// The matrix mode specifies which matrix stack is the target for matrix operations
    glLoadIdentity();// Initial value
    glTranslated((float)this->GetSize().GetWidth() / 2.0f, (float)this->GetSize().GetHeight() / 2.0f, 0.0f);// This will move the camera to the center of the screen

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
    GLenum error = glGetError();
    if(error != GL_NO_ERROR)
    {
    //  wxMessageBox("Error - " + gluErrorString(error));
        return;
    }

    glMatrixMode(GL_MODELVIEW);
}

And here is the code that handles updating the position of my view:

void modelDefinition::updateProjection()
{
    // First, load the projection matrix and reset the view to a default view
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    //Reset to modelview matrix
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    /* This section will handle the translation (panning) and scaled (zooming).
     * Needs to be called each time a draw occurs in order to update the placement of all the components */
    if(_zoomFactor < 1e-9)
        _zoomFactor = 1e-9;

    if(_zoomFactor > 1e6)
        _zoomFactor = 1e6;

    glScaled(_zoomFactor / (this->GetSize().GetWidth() / this->GetSize().GetHeight()), _zoomFactor, 1.0);

    glTranslated(-_cameraX, -_cameraY, 0.0);
}


问:
background color of parent matching height of child with negative top and bottom margins
Attached is an image of the desired affect I am going for. I am trying to do this with negative margins. I need the child element to expand past the parent element on the top and bottom. The issue is the background color of the parent element is matching the height of the child element. This is a responsive site and I will not be able to use absolute positioning of the child element as the height of the child (and therefore parent element) will be variable. Any help would be greatly appreciated

Following is my code...

body {
  background-color:#DBD9DB;
}

#headerImage {
  margin: 0;
}

#headerImage img {
  display: block;
  margin: 0 auto;
}

#parent {
 background-color: #fff4d7;
}

#child {
 background:none #FFF;
 margin:-46px auto -38px;
 position:relative;
 text-align:center;
 width:80%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="headerImage">
    <img src="http://fpoimg.com/300x250?text=Preview" width="300" height="250" />
  </div>
  <div id="parent">
    <div id="child">
      <h1>Title</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum dapibus sapien a nulla finibus mattis id quis est. Proin malesuada magna vitae orci maximus, ac viverra felis iaculis. Curabitur lacinia commodo est et auctor. Suspendisse potenti. Nulla scelerisque metus et leo cursus, non auctor turpis fermentum.</p>
    </div>
  </div>
</body></code>```

答:
body {
  background-color: #DBD9DB;
}

#parent {
  background-color: #fff4d7;
}

#parent:before,
#parent:after {
  content: " ";
  display: block;
  height: 50px;
  background-color: blue;
}

#child {
  background: none #FFF;
  position: relative;
  text-align: center;
  width: 80%;
  margin: -50px auto;
}

.parent {
  width: 100%;
  height: auto;
  margin: 0 auto 0 auto;
  background-color: #b5b5b5;
  overflow: hidden;
  position: relative;
}

img {
    width: 100%;
    height: auto;
}

.clearfix {
  overflow: auto;
  zoom: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="parent clearfix">
    <div class="css-slideshow">
          <div id="parent">
                        <img class="clearfix" src="http://unilaboralgirona.com/wp-content/uploads/2015/03/ZContact.jpg" />
      <div id="child">
        <h1>Title</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum dapibus sapien a nulla finibus mattis id quis est. Proin malesuada magna vitae orci maximus, ac viverra felis iaculis. Curabitur lacinia commodo est et auctor. Suspendisse potenti.
          Nulla scelerisque metus et leo cursus, non auctor turpis fermentum.</p>
      </div>
    </div>
    </div>
  </div>
</body></code>```

Body:
Attached is an image of the desired affect I am going for. I am trying to do this with negative margins. I need the child element to expand past the parent element on the top and bottom. The issue is the background color of the parent element is matching the height of the child element. This is a responsive site and I will not be able to use absolute positioning of the child element as the height of the child (and therefore parent element) will be variable. Any help would be greatly appreciated

Following is my code...

body {
  background-color:#DBD9DB;
}

#headerImage {
  margin: 0;
}

#headerImage img {
  display: block;
  margin: 0 auto;
}

#parent {
 background-color: #fff4d7;
}

#child {
 background:none #FFF;
 margin:-46px auto -38px;
 position:relative;
 text-align:center;
 width:80%;
}

Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum dapibus sapien a nulla finibus mattis id quis est. Proin malesuada magna vitae orci maximus, ac viverra felis iaculis. Curabitur lacinia commodo est et auctor. Suspendisse potenti. Nulla scelerisque metus et leo cursus, non auctor turpis fermentum.

Body:
body {
  background-color: #DBD9DB;
}

#parent {
  background-color: #fff4d7;
}

#parent:before,
#parent:after {
  content: " ";
  display: block;
  height: 50px;
  background-color: blue;
}

#child {
  background: none #FFF;
  position: relative;
  text-align: center;
  width: 80%;
  margin: -50px auto;
}

.parent {
  width: 100%;
  height: auto;
  margin: 0 auto 0 auto;
  background-color: #b5b5b5;
  overflow: hidden;
  position: relative;
}

img {
    width: 100%;
    height: auto;
}

.clearfix {
  overflow: auto;
  zoom: 1;
}

<body>
  <div class="parent clearfix">
    <div class="css-slideshow">
          <div id="parent">
                        <img class="clearfix" src="http://unilaboralgirona.com/wp-content/uploads/2015/03/ZContact.jpg" />
      <div id="child">
        <h1>Title</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum dapibus sapien a nulla finibus mattis id quis est. Proin malesuada magna vitae orci maximus, ac viverra felis iaculis. Curabitur lacinia commodo est et auctor. Suspendisse potenti.
          Nulla scelerisque metus et leo cursus, non auctor turpis fermentum.</p>
      </div>
    </div>
    </div>
  </div>
</body>


问:
Can import certificate in london but not in N. Virginia
I am trying to upload my "lets encrypt" certificate, in order to use TLS/SSL on API Gateway. The import process fails on us-east-1 and does not fail (same files, all the same...) in london (eu-west-2).

The error in N. Virginia is:

Sorry! You have reached the maximum number of certificates. Delete
  certificates that are not in use, or contact AWS Support to request an
  increase. Choose Previous button below and fix it.

There is no sense because i don't have any certificate yet.

Followed steps:

Import cert in London, OK!

I see in aws doc i need to put my cert in N. Virginia in order to use it on API Gateway

I remove it from ACM at london.

I switch to N.Virginia Region

Try to upload... FAIL!

What can i do?

Thanks in advance!

答:
After a phone conversation (with aws support) we arrive at the solution.

Finally AWS increase the limit to 10 (if i remember) at N. Virginia.
But i do not understand why my limit is '0' by default at N. Virginia and 10 in London.

Best Regards!


问:
How to split a sequence in F# based on another sequence in an idiomatic way
I have, in F#, 2 sequences, each containing distinct integers, strictly in ascending order: listMaxes and numbers.

If not Seq.isEmpty numbers, then it is guaranteed that not Seq.isEmpty listMaxes and Seq.last listMaxes >= Seq.last numbers.

I would like to implement in F# a function that returns a list of list of integers, whose List.length equals Seq.length listMaxes, containing the elements of numbers divided in lists, where the elements of listMaxes limit each group.

For example: called with the arguments

```<code>listMaxes = seq [ 25; 56; 65; 75; 88 ]
numbers = seq [ 10; 11; 13; 16; 20; 25; 31; 38; 46; 55; 65; 76; 88 ]
</code>```

this function should return

```<code>[ [10; 11; 13; 16; 20; 25]; [31; 38; 46; 55]; [65]; List.empty; [76; 88] ]
</code>```

I can implement this function, iterating over numbers only once:

```<code>let groupByListMaxes listMaxes numbers =
    if Seq.isEmpty numbers then
        List.replicate (Seq.length listMaxes) List.empty
    else
        List.ofSeq (seq {
            use nbe = numbers.GetEnumerator ()
            ignore (nbe.MoveNext ())
            for lmax in listMaxes do
                yield List.ofSeq (seq {
                    if nbe.Current <= lmax then
                        yield nbe.Current
                    while nbe.MoveNext () && nbe.Current <= lmax do
                        yield nbe.Current
                })
        })
</code>```

But this code feels unclean, ugly, imperative, and very un-F#-y.

Is there any functional / F#-idiomatic way to achieve this?

答:
It can be done like this with pattern matching and tail recursion:

```<code>let groupByListMaxes listMaxes numbers =
    let rec inner acc numbers =
        function
        | [] -> acc |> List.rev
        | max::tail ->
            let taken = numbers |> Seq.takeWhile ((>=) max) |> List.ofSeq
            let n = taken |> List.length
            inner (taken::acc) (numbers |> Seq.skip n) tail

    inner [] numbers (listMaxes |> List.ofSeq)
</code>```

Update: I also got inspired by fold and came up with the following solution that strictly refrains from converting the input sequences.

```<code>let groupByListMaxes maxes numbers =
    let rec inner (acc, (cur, numbers)) max =
        match numbers |> Seq.tryHead with
        // Add n to the current list of n's less
        // than the local max
        | Some n when n <= max ->
            let remaining = numbers |> Seq.tail
            inner (acc, (n::cur, remaining)) max
        // Complete the current list by adding it
        // to the accumulated result and prepare
        // the next list for fold.
        | _ ->
            (List.rev cur)::acc, ([], numbers)

    maxes |> Seq.fold inner ([], ([], numbers)) |> fst |> List.rev
</code>```

Body:
I have, in F#, 2 sequences, each containing distinct integers, strictly in ascending order: listMaxes and numbers.

If not Seq.isEmpty numbers, then it is guaranteed that not Seq.isEmpty listMaxes and Seq.last listMaxes >= Seq.last numbers.

I would like to implement in F# a function that returns a list of list of integers, whose List.length equals Seq.length listMaxes, containing the elements of numbers divided in lists, where the elements of listMaxes limit each group.

For example: called with the arguments

listMaxes = seq [ 25; 56; 65; 75; 88 ]
numbers = seq [ 10; 11; 13; 16; 20; 25; 31; 38; 46; 55; 65; 76; 88 ]

this function should return

[ [10; 11; 13; 16; 20; 25]; [31; 38; 46; 55]; [65]; List.empty; [76; 88] ]

I can implement this function, iterating over numbers only once:

let groupByListMaxes listMaxes numbers =
    if Seq.isEmpty numbers then
        List.replicate (Seq.length listMaxes) List.empty
    else
        List.ofSeq (seq {
            use nbe = numbers.GetEnumerator ()
            ignore (nbe.MoveNext ())
            for lmax in listMaxes do
                yield List.ofSeq (seq {
                    if nbe.Current <= lmax then
                        yield nbe.Current
                    while nbe.MoveNext () && nbe.Current <= lmax do
                        yield nbe.Current
                })
        })

But this code feels unclean, ugly, imperative, and very un-F#-y.

Is there any functional / F#-idiomatic way to achieve this?

Body:
It can be done like this with pattern matching and tail recursion:

let groupByListMaxes listMaxes numbers =
    let rec inner acc numbers =
        function
        | [] -> acc |> List.rev
        | max::tail ->
            let taken = numbers |> Seq.takeWhile ((>=) max) |> List.ofSeq
            let n = taken |> List.length
            inner (taken::acc) (numbers |> Seq.skip n) tail

    inner [] numbers (listMaxes |> List.ofSeq)

Update: I also got inspired by fold and came up with the following solution that strictly refrains from converting the input sequences.

let groupByListMaxes maxes numbers =
    let rec inner (acc, (cur, numbers)) max =
        match numbers |> Seq.tryHead with
        // Add n to the current list of n's less
        // than the local max
        | Some n when n <= max ->
            let remaining = numbers |> Seq.tail
            inner (acc, (n::cur, remaining)) max
        // Complete the current list by adding it
        // to the accumulated result and prepare
        // the next list for fold.
        | _ ->
            (List.rev cur)::acc, ([], numbers)

    maxes |> Seq.fold inner ([], ([], numbers)) |> fst |> List.rev


问:
Sorting list throws KeyNotFoundException
I've been working on an project where the application gets data from database to a list and sorts it. The problem is that for one situation the sorting needs to be done by a key that might not exist in all items.

```<code>// The variable list is sorted into another list called sortedList
sortedList = list.OrderBy(x => x.SomeIntegerData["key-that-is-not-in-every-item"]).ToList();
</code>```

Some items don't have that "key-that-is-not-in-every-item" and it causes the application to throw KeyNotFoundException. I can't seem to compare it to null or something that could make the application to do something else when the key is doesn't exist.
Is there a way to use something else like a timestamp (that is quaranteed to exist in every item) to do the sorting when the key doesn't exist?

Thanks

答:
Try:</p>

```<code>// The variable list is sorted into another list called sortedList
sortedList = list.OrderBy(x => x.SomeIntegerData.ContainsKey("key-that-is-not-in-every-item")?x.SomeIntegerData["key-that-is-not-in-every-item"]:null).ToList();
</code>```

Body:
I've been working on an project where the application gets data from database to a list and sorts it. The problem is that for one situation the sorting needs to be done by a key that might not exist in all items.

// The variable list is sorted into another list called sortedList
sortedList = list.OrderBy(x => x.SomeIntegerData["key-that-is-not-in-every-item"]).ToList();

Some items don't have that "key-that-is-not-in-every-item" and it causes the application to throw KeyNotFoundException. I can't seem to compare it to null or something that could make the application to do something else when the key is doesn't exist.
Is there a way to use something else like a timestamp (that is quaranteed to exist in every item) to do the sorting when the key doesn't exist?

Thanks

Body:
Try:

// The variable list is sorted into another list called sortedList
sortedList = list.OrderBy(x => x.SomeIntegerData.ContainsKey("key-that-is-not-in-every-item")?x.SomeIntegerData["key-that-is-not-in-every-item"]:null).ToList();


问:
White spaces in ansible task module
I need some assistance accounting for the white space between valid users and create mask without having to join them with an underscore. These are standard samba configuration options with spaces between them. I tried doing including a \t but that didn't work.

Below is the ansible task i currently have setup which is throwing errors because of the space.

```<code>name: smb.conf
ini_file:
  dest: /etc/samba/smb.conf
  mode: 0644
  section: {{ item.section }}
  path: {{ item.path }}
  public: {{ item.public }}
  valid users: {{ item.valid users}}
  create mask: {{ item.create mask }}
with_items:
- { section: 'samba', path: '/home/user', public: 'no' , valid users: @admin create mask: '0775' }
</code>```

答:
Try that</p>

```<code>{{ item["valid users"] }}
</code>```

Title: White spaces in ansible task module

Body:
I need some assistance accounting for the white space between valid users and create mask without having to join them with an underscore. These are standard samba configuration options with spaces between them. I tried doing including a \t but that didn't work.

Below is the ansible task i currently have setup which is throwing errors because of the space.

name: smb.conf
ini_file:
  dest: /etc/samba/smb.conf
  mode: 0644
  section: {{ item.section }}
  path: {{ item.path }}
  public: {{ item.public }}
  valid users: {{ item.valid users}}
  create mask: {{ item.create mask }}
with_items:
- { section: 'samba', path: '/home/user', public: 'no' , valid users: @admin create mask: '0775' }

Body:
Try that

{{ item["valid users"] }}


问:
How to map an object inside a string to set using ObjectMapper
I am converting a String to Pojo using Jackson ObjectMapper.

My incoming message:

```<code>{
    "countryCode": "US",
    "skuNumber": "TEST",
    "itemTaxCd": "89999",
    "lastModifiedBy": "xyz"
}
</code>```

Method :

```<code>public void processImsProductTaxEvents(String event) {
    try {
        SkuMasterDTO message = objectMapper.readValue(event, SkuMasterDTO.class);
        log.debug("Received message from IMS", message);
    } catch (Exception e) {
        log.error("Error in Object Mapper converting String to TaxCodeDTO", e);
    }
}
</code>```

Now countryCode is inside CountryDTO inside SkuMasterDTO defined as a Set

```<code>private Set<CountryDTO> countries = new HashSet<>();
</code>```

CountryDTO class

```<code>public class CountryDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotNull
    @Size(max = 2)
    private String countryCode;
</code>```

I am trying to set the countryCode to the set without changing the input Json. Any suggestions?

答: Consider using DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAYS in your ObjectMapper instance. Then you must change the json field countryCode to countries or mark Set countries as json property countryCode using @JsonProperty and provide a constructor/factory method within String parameter. This will make your object mapper behave as per your requirements.

Body:
I am converting a String to Pojo using Jackson ObjectMapper.

My incoming message:

{
    "countryCode": "US",
    "skuNumber": "TEST",
    "itemTaxCd": "89999",
    "lastModifiedBy": "xyz"
}

Method :

public void processImsProductTaxEvents(String event) {
    try {
        SkuMasterDTO message = objectMapper.readValue(event, SkuMasterDTO.class);
        log.debug("Received message from IMS", message);
    } catch (Exception e) {
        log.error("Error in Object Mapper converting String to TaxCodeDTO", e);
    }
}

Now countryCode is inside CountryDTO inside SkuMasterDTO defined as a Set

private Set<CountryDTO> countries = new HashSet<>();

CountryDTO class

public class CountryDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotNull
    @Size(max = 2)
    private String countryCode;

I am trying to set the countryCode to the set without changing the input Json. Any suggestions?


问:
python list comprehension not working as expected
I am new to list comprehension in python . I am tying to convert a for-if statement to list comprehension but it is not working as expected:

```<code>a = ['Done', 'add dns addRec test 11.11.11.11']
record = "addRec"
</code>```

Normal python code:

```<code>list_new = []
for member in a:
  if record and "addRec" in member:
    list_new.append(member)
    print(list_new)
</code>```

My list comprehension:

```<code>list_new = [list_new.append(member) for member in a if record and "addRec" in member]
</code>```

list_new is returning as a empty list.

It should return :

```<code>['add dns addRec test 11.11.11.11']
</code>```

答:
Try this:

```<code>list_new = [member for member in a if record and "addRec" in member]
</code>```

Note that the .append() function doesn't return anything.

Body:
I am new to list comprehension in python . I am tying to convert a for-if statement to list comprehension but it is not working as expected:

a = ['Done', 'add dns addRec test 11.11.11.11']
record = "addRec"

Normal python code:

list_new = []
for member in a:
  if record and "addRec" in member:
    list_new.append(member)
    print(list_new)

My list comprehension:

list_new = [list_new.append(member) for member in a if record and "addRec" in member]

list_new is returning as a empty list.

It should return :

['add dns addRec test 11.11.11.11']

Body:
Try this:

list_new = [member for member in a if record and "addRec" in member]

Note that the .append() function doesn't return anything.


问:
Using onClick attribute in layout xml causes a NoSuchMethodException in Android dialogs
I have created a custom dialog and a layout xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tap Me"
        android:onClick="dialogClicked" />
</LinearLayout>
</code>```

In the dialog class I've implemented the method "dialogClicked(View v)":

```<code>public class TestDialog extends Dialog {

 public TestDialog(final Context context)
 {
  super(context);
 }

 @Override
 protected void onCreate(final Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog);
 }

 public void dialogClicked(final View view)
 {
  System.out.println("clicked");
 }

}
</code>```

When I tap the button I get a NoSuchMethodException 'dialogClicked'. Setting the onClick handler in layout xml works fine for activities, but not in dialogs. Any ideas? What I'm doing wrong?

答:
android:onClick="method" is pretty cool, but it doesn't work on Android 1.5 so I am avoiding for some time.

An easy workaround:

Make your Dialog an Activity and use android:theme="@android:style/Theme.Dialog" in you AndroidManifest.

Body:
I have created a custom dialog and a layout xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tap Me"
        android:onClick="dialogClicked" />
</LinearLayout>

In the dialog class I've implemented the method "dialogClicked(View v)":

public class TestDialog extends Dialog {

 public TestDialog(final Context context)
 {
  super(context);
 }

 @Override
 protected void onCreate(final Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.dialog);
 }

 public void dialogClicked(final View view)
 {
  System.out.println("clicked");
 }

}

When I tap the button I get a NoSuchMethodException 'dialogClicked'. Setting the onClick handler in layout xml works fine for activities, but not in dialogs. Any ideas? What I'm doing wrong?