问:
Friendly Windows Minimum Version in InnoSetup
I can set the minimum version required (for example XP SP3) in Inno-Setup by going

```<code>MinVersion=0,5.01.2600
</code>```

However, that leads to the rather unfriendly Message Box:

This program requires Windows NT version 5.1.2600 or later.

Is there any way to have this say instead:

This program requires WindowsXP Service Pack 3 or later.

答:
This string is named WinVersionTooLowError and is defined as

```<code>This program requires %1 version %2 or later.
</code>```

You can redefine it in the [Messages] section.

OwnerDisplayName: Kris Erickson

Body:
I can set the minimum version required (for example XP SP3) in Inno-Setup by going

MinVersion=0,5.01.2600

However, that leads to the rather unfriendly Message Box:

This program requires Windows NT version 5.1.2600 or later.

Is there any way to have this say instead:

This program requires WindowsXP Service Pack 3 or later.

LastEditorDisplayName: Kris Erickson

Body:
This string is named WinVersionTooLowError and is defined as

This program requires %1 version %2 or later.

You can redefine it in the [Messages] section.

OwnerDisplayName: jdigital


来源: stackexchange

问:
Ruby on Rails Routes with Locales
I am using this guide: http://edgeguides.rubyonrails.org/i18n.html

What I would like:

/about goes to pages#about with the defaulted locale of en.

/en/about goes to pages#about with the locale of en.

/es/about goes to pages#about with the locale of es.

What I get:

/about goes to root_path with the locale of about.

/en/about goes to pages#about with the locale of en.

/es/about goes to pages#about with the locale of es.

Here is some code:

```<code># config/routes.rb
match '/:locale' => 'pages#news'

scope "(:locale)", :locale => /en|es/ do
  match '/abcd' => 'pages#abcd'
  match '/plan' => 'pages#plan'
  match '/about' => 'pages#about'
  match '/history' => 'pages#history'
  match '/projects' => 'pages#projects'
  match '/donate' => 'pages#donate'
  match '/opportunities' => 'pages#opportunities'
  match '/board' => 'pages#board'
end

root :to => "pages#news"

# app/controller/application_controller.rb
before_filter :set_locale

def set_locale
  # if params[:locale] is nil then I18n.default_locale will be used
  I18n.locale = params[:locale]
end

def default_url_options(options={})
  { :locale => I18n.locale }
end
</code>```

If I am reading the guide correctly, section 2.5 says that I should be able to access /about and have it load the default locale.

From 2.5:

```<code># config/routes.rb
scope "(:locale)", :locale => /en|nl/ do
  resources :books
end
</code>```

With this approach you will not get a
  Routing Error when accessing your
  resources such as
  http://localhost:3001/books without a
  locale. This is useful for when you
  want to use the default locale when
  one is not specified.

答:
The first line in your routes.rb is a catch-all route

```<code>match '/:locale' => 'pages#news'
</code>```

It should be the last line in the file, right after the root route.

ContentLicense: CC BY-SA 2.5

Title: Ruby on Rails Routes with Locales

Body:
I am using this guide: http://edgeguides.rubyonrails.org/i18n.html

What I would like:

/about goes to pages#about with the defaulted locale of en.

/en/about goes to pages#about with the locale of en.

/es/about goes to pages#about with the locale of es.

What I get:

/about goes to root_path with the locale of about.

/en/about goes to pages#about with the locale of en.

/es/about goes to pages#about with the locale of es.

Here is some code:

# config/routes.rb
match '/:locale' => 'pages#news'

scope "(:locale)", :locale => /en|es/ do
  match '/abcd' => 'pages#abcd'
  match '/plan' => 'pages#plan'
  match '/about' => 'pages#about'
  match '/history' => 'pages#history'
  match '/projects' => 'pages#projects'
  match '/donate' => 'pages#donate'
  match '/opportunities' => 'pages#opportunities'
  match '/board' => 'pages#board'
end

root :to => "pages#news"

# app/controller/application_controller.rb
before_filter :set_locale

def set_locale
  # if params[:locale] is nil then I18n.default_locale will be used
  I18n.locale = params[:locale]
end

def default_url_options(options={})
  { :locale => I18n.locale }
end

If I am reading the guide correctly, section 2.5 says that I should be able to access /about and have it load the default locale.

From 2.5:

# config/routes.rb
scope "(:locale)", :locale => /en|nl/ do
  resources :books
end

With this approach you will not get a
  Routing Error when accessing your
  resources such as
  http://localhost:3001/books without a
  locale. This is useful for when you
  want to use the default locale when
  one is not specified.

Body:
The first line in your routes.rb is a catch-all route

match '/:locale' => 'pages#news'

It should be the last line in the file, right after the root route.


问:
Convert GENCODE IDs to Ensembl - Ranged SummarizedExperiment
I have an expression set matrix with the rownames being what I think is a GENCODE ID in the format for example
"ENSG00000000003.14"
"ENSG00000000457.13"
"ENSG00000000005.5" and so on.
I would like to convert these to gene_symbol but I am not sure of the best way to do so, especially because of the ".14" or ".13" which I believe is the version. Should I first trim all IDs for what is after the dot and then use biomaRt to convert? if so, what is the most efficient way of doing it? Is there a better way to get to the gene_symbol?

Many thanks for you help

答:
As already mentioned, these are ENSEMBL IDs. First thing, you would need to do is to check your expression set object and identify which database it uses for annotations. Sometimes, the IDs may map to different gene symbols in newer (updated) annotation databases.

Anyway, expecting that the IDs belong to Humans, you can use this code to get the gene symbols very easily.

```<code>library(org.Hs.eg.db)       ## Annotation DB
library(AnnotationDbi)

ids <- c("ENSG00000000003", "ENSG00000000457","ENSG00000000005")
gene_symbol <- select(org.Hs.eg.db,keys = ids,columns = "SYMBOL",keytype = "ENSEMBL")
</code>```

You can try with org.Hs.eg.db or the exact db your expression set uses (if that information is available).

ContentLicense: CC BY-SA 3.0

Body:
As already mentioned, these are ENSEMBL IDs. First thing, you would need to do is to check your expression set object and identify which database it uses for annotations. Sometimes, the IDs may map to different gene symbols in newer (updated) annotation databases.

Anyway, expecting that the IDs belong to Humans, you can use this code to get the gene symbols very easily.

library(org.Hs.eg.db)       ## Annotation DB
library(AnnotationDbi)

ids <- c("ENSG00000000003", "ENSG00000000457","ENSG00000000005")
gene_symbol <- select(org.Hs.eg.db,keys = ids,columns = "SYMBOL",keytype = "ENSEMBL")

You can try with org.Hs.eg.db or the exact db your expression set uses (if that information is available).


问:
Mongodb query does not use prefix on compound index with text field
I've created the following index on my collection:

```<code>db.myCollection.createIndex({
  user_id: 1,
  name: 'text'
})
</code>```

If I try to see the execution plan of a query containing both fields, like this:

```<code>db.getCollection('campaigns').find({
    user_id: ObjectId('xxx')
   ,$text: { $search: 'bla' }
}).explain('executionStats')
</code>```

I get the following results:

```<code>...
"winningPlan" : {
    "stage" : "TEXT",
    "indexPrefix" : {
        "user_id" : ObjectId("xxx")
    },
    "indexName" : "user_id_1_name_text",
    "parsedTextQuery" : {
        "terms" : [
            "e"
        ],
        "negatedTerms" : [],
        "phrases" : [],
        "negatedPhrases" : []
    },
    "inputStage" : {
        "stage" : "TEXT_MATCH",
        "inputStage" : {
            "stage" : "TEXT_OR",
            "inputStage" : {
                "stage" : "IXSCAN",
                "keyPattern" : {
                    "user_id" : 1.0,
                    "_fts" : "text",
                    "_ftsx" : 1
                },
                "indexName" : "user_id_1_name_text",
                "isMultiKey" : true,
                "isUnique" : false,
                "isSparse" : false,
                "isPartial" : false,
                "indexVersion" : 1,
                "direction" : "backward",
                "indexBounds" : {}
            }
        }
    }
}
...
</code>```

As stated in the documentation, MongoDB can use index prefixes to perform indexed queries.

Since user_id is a prefix for the index above, I'd expect that a query only by user_id would use the index, but if I try the following:

```<code>db.myCollection.find({
    user_id: ObjectId('xxx')
}).explain('executionStats')
</code>```

I get:

```<code>...
"winningPlan" : {
    "stage" : "COLLSCAN",
    "filter" : {
        "user_id" : {
            "$eq" : ObjectId("xxx")
        }
    },
    "direction" : "forward"
},
...
</code>```

So, it is not using the index at all and performing a full collection scan.

答:
In general MongoDB can use index prefixes to support queries, however compound indexes including geospatial or text fields are a special case of sparse compound indexes. If a document does not include a value for any of the text index field(s) in a compound index, it will not be included in the index.

In order to ensure correct results for a prefix search, an alternative query plan will be chosen over the sparse compound index:

If a sparse index would result in an incomplete result set for queries and sort operations, MongoDB will not use that index unless a hint() explicitly specifies the index.

Setting up some test data in MongoDB 3.4.5 to demonstrate the potential problem:

```<code>db.myCollection.createIndex({ user_id:1, name: 'text' }, { name: 'myIndex'})

// `name` is a string; this document will be included in a text index
db.myCollection.insert({ user_id:123, name:'Banana' })

// `name` is a number; this document will NOT be included in a text index
db.myCollection.insert({ user_id:123, name: 456 })

// `name` is missing; this document will NOT be included in a text index
db.myCollection.insert({ user_id:123 })
</code>```

Then, forcing the compound text index to be used:

```<code>db.myCollection.find({user_id:123}).hint('myIndex')
</code>```

The result only includes the single document with the indexed text field name, rather than the three documents that would be expected:

```<code>{
  "_id": ObjectId("595ab19e799060aee88cb035"),
  "user_id": 123,
  "name": "Banana"
}
</code>```

This exception should be more clearly highlighted in the MongoDB documentation; watch/upvote DOCS-10322 in the MongoDB issue tracker for updates.

Body:
I've created the following index on my collection:

db.myCollection.createIndex({
  user_id: 1,
  name: 'text'
})

If I try to see the execution plan of a query containing both fields, like this:

db.getCollection('campaigns').find({
    user_id: ObjectId('xxx')
   ,$text: { $search: 'bla' }
}).explain('executionStats')

I get the following results:

...
"winningPlan" : {
    "stage" : "TEXT",
    "indexPrefix" : {
        "user_id" : ObjectId("xxx")
    },
    "indexName" : "user_id_1_name_text",
    "parsedTextQuery" : {
        "terms" : [
            "e"
        ],
        "negatedTerms" : [],
        "phrases" : [],
        "negatedPhrases" : []
    },
    "inputStage" : {
        "stage" : "TEXT_MATCH",
        "inputStage" : {
            "stage" : "TEXT_OR",
            "inputStage" : {
                "stage" : "IXSCAN",
                "keyPattern" : {
                    "user_id" : 1.0,
                    "_fts" : "text",
                    "_ftsx" : 1
                },
                "indexName" : "user_id_1_name_text",
                "isMultiKey" : true,
                "isUnique" : false,
                "isSparse" : false,
                "isPartial" : false,
                "indexVersion" : 1,
                "direction" : "backward",
                "indexBounds" : {}
            }
        }
    }
}
...

As stated in the documentation, MongoDB can use index prefixes to perform indexed queries.

Since user_id is a prefix for the index above, I'd expect that a query only by user_id would use the index, but if I try the following:

db.myCollection.find({
    user_id: ObjectId('xxx')
}).explain('executionStats')

I get:

...
"winningPlan" : {
    "stage" : "COLLSCAN",
    "filter" : {
        "user_id" : {
            "$eq" : ObjectId("xxx")
        }
    },
    "direction" : "forward"
},
...

So, it is not using the index at all and performing a full collection scan.

Body:
In general MongoDB can use index prefixes to support queries, however compound indexes including geospatial or text fields are a special case of sparse compound indexes. If a document does not include a value for any of the text index field(s) in a compound index, it will not be included in the index.

In order to ensure correct results for a prefix search, an alternative query plan will be chosen over the sparse compound index:

If a sparse index would result in an incomplete result set for queries and sort operations, MongoDB will not use that index unless a hint() explicitly specifies the index.

Setting up some test data in MongoDB 3.4.5 to demonstrate the potential problem:

db.myCollection.createIndex({ user_id:1, name: 'text' }, { name: 'myIndex'})

// `name` is a string; this document will be included in a text index
db.myCollection.insert({ user_id:123, name:'Banana' })

// `name` is a number; this document will NOT be included in a text index
db.myCollection.insert({ user_id:123, name: 456 })

// `name` is missing; this document will NOT be included in a text index
db.myCollection.insert({ user_id:123 })

Then, forcing the compound text index to be used:

db.myCollection.find({user_id:123}).hint('myIndex')

The result only includes the single document with the indexed text field name, rather than the three documents that would be expected:

{
  "_id": ObjectId("595ab19e799060aee88cb035"),
  "user_id": 123,
  "name": "Banana"
}

This exception should be more clearly highlighted in the MongoDB documentation; watch/upvote DOCS-10322 in the MongoDB issue tracker for updates.


问:
Check for duplicate characters in string using for-in loops in Swift
I did this using while loops but I'm wondering if there's a way to do this with for loops. I'm trying to write this clean so I can write it on a whiteboard for people to understand.</p>
```<code>var str = "Have a nice day"

func unique(_ str: String) -> String {
    var firstIndex = str.startIndex

    while (firstIndex != str.endIndex) {
        var secondIndex = str.index(after: firstIndex)

        while (secondIndex != str.endIndex) {
            if (str[firstIndex] == str[secondIndex]) {
                return "Not all characters are unique"
            }
            secondIndex = str.index(after: secondIndex)
        }
        firstIndex = str.index(after: firstIndex)
    }
    return "All the characters are unique"
}

print("\(unique(str))")
</code>```

答:
Here is the for-loop version of your question.

```<code>let string = "Have a nice day"

func unique(_ string: String) -> String {
    for i in 0..<string.characters.count {
        for j in (i+1)..<string.characters.count {
            let firstIndex = string.index(string.startIndex, offsetBy: i)
            let secondIndex = string.index(string.startIndex, offsetBy: j)
            if (string[firstIndex] == string[secondIndex]) {
                return "Not all characters are unique"
            }
        }
    }
    return "All the characters are unique"
}
</code>```

There are a lot of ways this can be achieved and this is just one way of doing it.

ContentLicense: CC BY-SA 4.0

Body:
I did this using while loops but I'm wondering if there's a way to do this with for loops. I'm trying to write this clean so I can write it on a whiteboard for people to understand.

var str = "Have a nice day"

func unique(_ str: String) -> String {
    var firstIndex = str.startIndex

    while (firstIndex != str.endIndex) {
        var secondIndex = str.index(after: firstIndex)

        while (secondIndex != str.endIndex) {
            if (str[firstIndex] == str[secondIndex]) {
                return "Not all characters are unique"
            }
            secondIndex = str.index(after: secondIndex)
        }
        firstIndex = str.index(after: firstIndex)
    }
    return "All the characters are unique"
}

print("\(unique(str))")

Body:
Here is the for-loop version of your question.

let string = "Have a nice day"

func unique(_ string: String) -> String {
    for i in 0..<string.characters.count {
        for j in (i+1)..<string.characters.count {
            let firstIndex = string.index(string.startIndex, offsetBy: i)
            let secondIndex = string.index(string.startIndex, offsetBy: j)
            if (string[firstIndex] == string[secondIndex]) {
                return "Not all characters are unique"
            }
        }
    }
    return "All the characters are unique"
}

There are a lot of ways this can be achieved and this is just one way of doing it.


问:
Swift JSON parsing and printing a specified value from an array
Hi I'm trying to get data from a certain JSON API. I can gat a snapshot of all values from the API, which is shown below. But I can't manage to put a specifiek row in a variable. This is the JSON form which I get. I want to print the "Description" value.Can someone help me with this?

And Hier is my code:

```<code>func apiRequest() {
    let config = URLSessionConfiguration.default
    let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
    let password = "G23@rE9t1#"
    let loginString = String(format: "%@:%@", username, password)
    let userPasswordData = loginString.data(using: String.Encoding.utf8)
    let base64EncodedCredential = userPasswordData?.base64EncodedString()
    let authString = "Basic " + (base64EncodedCredential)!

    print(authString)
    config.httpAdditionalHeaders = ["Authorization" : authString]
    let session = URLSession(configuration: config)

    var running = false
    let url = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")

    let task = session.dataTask(with: url! as URL) {
        ( data, response, error) in
        if let taskHeader = response as? HTTPURLResponse {
            print(taskHeader.statusCode)
        }
        if error != nil {
            print("There is an error!!!")
            print(error)
        } else {
            if let content = data {
                do {
                    let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(array)

                    if let items = array["items"] {
                         if let description = items["Description"] as? [[String:Any]]{
                            print(description as Any)
                         }
                    }
                }
                catch {
                    print("Error: Could not get any data")
                }
            }
        }
        running = false
    }

    running = true
    task.resume()

    while running {
        print("waiting...")
        sleep(1)
    }
}
</code>```

答: use the SwiftyJSON and it would be as easy as json["items"][i].arrayValue as return and array with items Values or json["items"][i]["description"].stringValue to get a string from a row

Body:
Hi I'm trying to get data from a certain JSON API. I can gat a snapshot of all values from the API, which is shown below. But I can't manage to put a specifiek row in a variable. This is the JSON form which I get. I want to print the "Description" value.Can someone help me with this?

And Hier is my code:

func apiRequest() {
    let config = URLSessionConfiguration.default
    let username = "F44C3FC2-91AF-5FB2-8B3F-70397C0D447D"
    let password = "G23@rE9t1#"
    let loginString = String(format: "%@:%@", username, password)
    let userPasswordData = loginString.data(using: String.Encoding.utf8)
    let base64EncodedCredential = userPasswordData?.base64EncodedString()
    let authString = "Basic " + (base64EncodedCredential)!

    print(authString)
    config.httpAdditionalHeaders = ["Authorization" : authString]
    let session = URLSession(configuration: config)

    var running = false
    let url = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")

    let task = session.dataTask(with: url! as URL) {
        ( data, response, error) in
        if let taskHeader = response as? HTTPURLResponse {
            print(taskHeader.statusCode)
        }
        if error != nil {
            print("There is an error!!!")
            print(error)
        } else {
            if let content = data {
                do {
                    let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                    print(array)

                    if let items = array["items"] {
                         if let description = items["Description"] as? [[String:Any]]{
                            print(description as Any)
                         }
                    }
                }
                catch {
                    print("Error: Could not get any data")
                }
            }
        }
        running = false
    }

    running = true
    task.resume()

    while running {
        print("waiting...")
        sleep(1)
    }
}


问:
asp.Net newbie help me
I'm trying to get into the world of asp.NET and I'm trying out some stuff.

Am I way off??

```<code>     <br />
    <asp:TextBox ID="txtoriginal" runat="server"></asp:TextBox>

<asp:Button ID="btnCount" runat="server" Text="reverse"
        onclick="btnCount_Click" />

    <asp:Label ID="lblAnswer" runat="server"></asp:Label>

</form>
</code>```

so this is that part im havin trouble with

```<code>    protected void btnCount_Click(object sender, EventArgs e)
    {

        lblAnswer.Text = txtoriginal.Text;

        stroriginalText = txtoriginal.Text;
        strReverse = stroriginalText.ToCharArray();
        Array.Reverse(strReverse);
        lblAnswer.Text = strReverse;
    }
}
}
</code>```

答:
I believe that you can solve this when you create a new string from char[]. Something like this:

```<code>char[] strChars = txtOriginal.Text.ToCharArray();
Array.Reverse(strChars);
blAnswer.Text = new string(strChars);
</code>```

Regards.

Title: asp.Net newbie help me

Body:
I'm trying to get into the world of asp.NET and I'm trying out some stuff.

Am I way off??

    <asp:TextBox ID="txtoriginal" runat="server"></asp:TextBox>

<asp:Button ID="btnCount" runat="server" Text="reverse"
        onclick="btnCount_Click" />

    <asp:Label ID="lblAnswer" runat="server"></asp:Label>

</form>

so this is that part im havin trouble with

    protected void btnCount_Click(object sender, EventArgs e)
    {

        lblAnswer.Text = txtoriginal.Text;

        stroriginalText = txtoriginal.Text;
        strReverse = stroriginalText.ToCharArray();
        Array.Reverse(strReverse);
        lblAnswer.Text = strReverse;
    }
}
}

Body:
I believe that you can solve this when you create a new string from char[]. Something like this:

char[] strChars = txtOriginal.Text.ToCharArray();
Array.Reverse(strChars);
blAnswer.Text = new string(strChars);

Regards.


问:
How can I simulate MS Access 2013 in order to make sure my DB is compatible?
I built a db for MS Access 2016 (both front end and back end) and it has grown to be very extensive (130+ queries, 50+ reports, etc...), but I have just stumbled upon a user whose copy of the DB isn't working because of compatibility issues.

I was wondering if there was a setting in the menu that might make the DB think it is running version 2013. This would help me with the present problem of adjusting the current DB to accommodate this user.

答:
The generally accepted solution is to ALWAYS develop with the lowest common version. Access handles and works VERY well when moving forward, but not backwards. After all, a very old computer might not even have windows or a mouse – you can’t expect it to run modern software.

So the general approach is to develop in 2013, or even 2010. The resulting compiled accDE you distribute to each workstation will in near all cases run without issue. So there is no “switch” or some such. If the lowest common version of Access is 2013, then that is the development edition you should work with. Thus users with 2013, or 2016 should not have any issues.

Of course the other tip is to split your database (you clearly done that). And ensure that each workstation receives a copy of the front end (application part). So keep in mind that you don’t want to open + use a single deployed front end with “different” versions of Access. Following the above simple approach should result in a trouble free deployment approach and allow the two versions of Access to work without issues.

edit:
Also, if you have any references to a particular version of outlook, Excel, word etc., then you need to remove those references and adopt late binding.


问:
Tunneling httplib Through a Proxy
I am trying to figure out how to send data to a server through a proxy. I was hoping this would be possible through tor but being as tor uses SOCKS it apparently isn't possible with httplib (correct me if I am wrong)

This is what I have right now

```<code>import httplib
con = httplib.HTTPConnection("google.com")
con.set_tunnel(proxy, port)
con.send("Sent Stuff")
</code>```

The problem is, it seems to freeze when the tunnel is set. Thanks for your help.

答:
As a follow-up to Khue Vu's answer, here's a complete example, the details of getting this working with a SOCKS proxy were more complex than expected.

First install PySocks with:

```<code>pip install PySocks
</code>```

Then you need to manually set up your SOCKS proxy after instantiating your HTTPConnection and informing it that it's going to be using a proxy:

```<code>from http.client import HTTPConnection
from urllib.parse import urlparse, urlencode

import socks

url = urlparse("http://final.destination.example.com:8888/")

conn = HTTPConnection('127.0.0.1', 9000) # use socks proxy address
conn.set_tunnel(url.netloc, url.port) # remote host and port that you actually want to talk to
conn.sock = socks.socksocket() # manually set socket
conn.sock.set_proxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9000) # use socks proxy address
conn.sock.connect((url.netloc, url.port)) # remote host and port that you actually want to talk to

request_path = "%s?%s" % (url.path, url.query)
conn.request("POST", request_path, post_data)
</code>```

Note that the imports above are python3.x

Title: Tunneling httplib Through a Proxy

Body:
I am trying to figure out how to send data to a server through a proxy. I was hoping this would be possible through tor but being as tor uses SOCKS it apparently isn't possible with httplib (correct me if I am wrong)

This is what I have right now

import httplib
con = httplib.HTTPConnection("google.com")
con.set_tunnel(proxy, port)
con.send("Sent Stuff")

The problem is, it seems to freeze when the tunnel is set. Thanks for your help.

Body:
As a follow-up to Khue Vu's answer, here's a complete example, the details of getting this working with a SOCKS proxy were more complex than expected.

First install PySocks with:

pip install PySocks

Then you need to manually set up your SOCKS proxy after instantiating your HTTPConnection and informing it that it's going to be using a proxy:

from http.client import HTTPConnection
from urllib.parse import urlparse, urlencode

import socks

url = urlparse("http://final.destination.example.com:8888/")

conn = HTTPConnection('127.0.0.1', 9000) # use socks proxy address
conn.set_tunnel(url.netloc, url.port) # remote host and port that you actually want to talk to
conn.sock = socks.socksocket() # manually set socket
conn.sock.set_proxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9000) # use socks proxy address
conn.sock.connect((url.netloc, url.port)) # remote host and port that you actually want to talk to

request_path = "%s?%s" % (url.path, url.query)
conn.request("POST", request_path, post_data)

Note that the imports above are python3.x


问:
Determining offsetX of a mouseEvent from a particular element with overflow-x: auto
I have an element with overflow-x: auto, and I want to be able to click inside this element and determine the left offset (in px) from the left edge of the element. The issue is that this element contains some other elements within it, so I can't just use the raw offsetX property on MouseEvent, as if I ever accidentally click inside one of the nested divs, it will give me the offset from the left padding edge of that inner div, not the element I want to be targeted.

Additionally, I can't just use MouseEvent.clientX - element.offsetLeft, as if I am scrolled into the element at all, it won't return the value that accounts for the now-hidden scrolled-past part of my element.

How can I either:
1 - Determine the distance between the X pos of the mouse event and the left padding edge of my element?

OR

2 - create a workaround to somehow specify the target of the mouseEvent (this is a read-only property, so I'm unsure if this is even possible)?

I am using Typescript and Angular4, and I dob't want to use jQuery, so please don't suggest a jQuery based solution.  Thanks!

Thanks.

答:
EDIT
This can also be done by using the HTML DOM property scrollLeft on the container element

Figured out a solution.

We can make sure to only perform mouse movement logic when the offsetX property is with regard to our container element by adding a conditional like so:

```<code>if (mouseMoveEvent.clientX - myElement.offsetLeft) <= mouseMoveEvent.offsetX) {
    // Handle mousemove
}
else {
    // Do nothing
}
</code>```

In the case of this overflow-x:auto element, mouseMoveEvent.offsetX should only ever be greater than or equal to (mouseMoveEvent.clientX - this.element.offsetLeft).

Therefore, if it isn't, that means our mouseMoveEvent.offsetX property is targeting an inner element, and we can just skip the logic in that case.

Body:
EDIT
This can also be done by using the HTML DOM property scrollLeft on the container element

Figured out a solution.

We can make sure to only perform mouse movement logic when the offsetX property is with regard to our container element by adding a conditional like so:

if (mouseMoveEvent.clientX - myElement.offsetLeft) <= mouseMoveEvent.offsetX) {
    // Handle mousemove
}
else {
    // Do nothing
}

In the case of this overflow-x:auto element, mouseMoveEvent.offsetX should only ever be greater than or equal to (mouseMoveEvent.clientX - this.element.offsetLeft).

Therefore, if it isn't, that means our mouseMoveEvent.offsetX property is targeting an inner element, and we can just skip the logic in that case.


问:
DbDataReader inner working
We have high load system which consist from SQL Server and .NET apps.
We are using DbDataReader to retrieve data from SQL and persist it into JSON to send it across the wire. Our system uses time stamp for all the records that were inserted or modified in order to only send updated data over the wire (each table has extract date time column which gets updated when record is inserted or modified).

In some instances we are seeing that some records would be updated in the database at the same time as we were persisting our JSON. For those records we would not see them in JSON, but showing correct in DB when we check manually. What is even stranger is that other records that have same date time stamp (up to milliseconds the same) are present in JSON. So issue is that next time we retrieve data from DB we only get records above certain date time, which leads to missing couple records that were modified at the same time as JSON was written.

My initial thought is that it could be timing issue that record was not modified when JSON was being written. But how do you deal with this situations?

So my question is what would DbDataReader return only records that were present when DbCommand.ExecuteReader() was executed or it will return records that were modified in database after as well?

答:
issue is that next time we retrieve data from DB we only get records above certain date time, which leads to missing couple records

It appears you are attempting to extract disjoint subsets of rows from a SQL Server table.  It's not necessary to get into the gory details of transaction isolation levels in this case.

The bottom line is that unless you take a table lock that lasts for at least several milliseconds, you can't use a datetime column to extract disjoint delta's from a SQL Server table.  You see rows as they are committed, not as they are written.  So even if the clock resolution was infinite, transactions can commit in a different order than they read the clock and write the rows.

You can use a rowversion column for this, as SQL Server increments the value for every transaction.

Or you can build your extract logic to expect overlapping rows.

Or use Transactional Replication, Change Data Capture, or Change Tracking.

Title: DbDataReader inner working


问:
Angular 2/4 img src
I'm simply trying to render an image in a component.  I can't seem to find a decent answer that works.

Can someone point me in the right direction?

Enviroment:

angular/cli 1.1.2

node 8.1.0

OS win x64

angular -v 4.2.5

What I have tired (HTML):

```<code><img [src]={{imgUrl}} />
<img [src]="imgUrl" />

<img src={{imgUrl}} />
<img src="imgUrl" />

<img ng-src="imgUrl" />

<img src="assets/images/img.jpg" />
<!-- and a few more -->
</code>```

With .ts file like:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  imgUrl = "";

  constructor() {}

  ngOnInit() {
     this.imgUrl = 'assets/images/img.jpg';
     // i have also tried
     // ~/assets/...
     // ./assets/...
     // etc
  }

}
</code>```

Project structure:

```<code>src
--app
----home
------ts-files
--assets
----images
------img.jpg
</code>```

I have also tried moving the file from assets to the same ts folder, and some other places.

But I only get the same 404 error.

GET http://localhost:4200/assets/images/img.jpg 404 (Not Found)

UPDATE

.angular-cli.json content (autogenerated):

```<code>{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "Test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}
</code>```

答:
have you tried

https://docs.angularjs.org/api/ng/directive/ngSrc

Title: Angular 2/4 img src

Body:
I'm simply trying to render an image in a component.  I can't seem to find a decent answer that works.

Can someone point me in the right direction?

Enviroment:

angular/cli 1.1.2

node 8.1.0

OS win x64

angular -v 4.2.5

What I have tired (HTML):

With .ts file like:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  imgUrl = "";

  constructor() {}

  ngOnInit() {
     this.imgUrl = 'assets/images/img.jpg';
     // i have also tried
     // ~/assets/...
     // ./assets/...
     // etc
  }

}

Project structure:

src
--app
----home
------ts-files
--assets
----images
------img.jpg

I have also tried moving the file from assets to the same ts folder, and some other places.

But I only get the same 404 error.

GET http://localhost:4200/assets/images/img.jpg 404 (Not Found)

UPDATE

.angular-cli.json content (autogenerated):

{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "Test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

Body:
have you tried

<img ng-src="{{imgUrl}}" />

https://docs.angularjs.org/api/ng/directive/ngSrc


问:
Moving the player freely all over the screen
I'm making a game where the ball(the player) is suppose to avoid other balls passing by the screen. Basically I want the ball always to follow the location of the touch. So wherever I'm moving my finger on the screen, the ball follows.

This is the player Class:

```<code>import SpriteKit

struct ColliderType {

static let Player: UInt32 = 1
static let Blue: UInt32 = 2
static let Green: UInt32 = 3
static let Yellow: UInt32 = 4
static let Red: UInt32 = 5

}

class Player: SKSpriteNode {

func initialize() {
    self.name = "Player"
    self.zPosition = 1
    self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.height /
 2)
    self.physicsBody?.affectedByGravity = false
    self.physicsBody?.categoryBitMask = ColliderType.Player
    self.physicsBody?.collisionBitMask = ColliderType.Blue |
 ColliderType.Green | ColliderType.Red | ColliderType.Yellow
    self.physicsBody?.contactTestBitMask = ColliderType.Blue |
 ColliderType.Green | ColliderType.Red | ColliderType.Yellow
 }

 }
</code>```

This is the GameplayScene:

```<code>import SpriteKit

class GameplayScene: SKScene, SKPhysicsContactDelegate {

var player = Player()

var ball = SKSpriteNode()

var scoreLabel = SKLabelNode()
var score = 0

var counter = Timer()

override func didMove(to view: SKView) {
    initialize()
}

override func update(_ currentTime: TimeInterval) {

}

override func touchesBegan(_ touches: Set<UITouch>, with event:
UIEvent?) {

    for touch in touches {

        let location = touch.location(in: self)

        if atPoint(location).name == "Retry" {
            self.removeAllActions()
            self.removeAllChildren()
            initialize()
        }

        if atPoint(location).name == "Quit" {
            let mainmenu = MainMenuScene(fileNamed: "MainMenuScene")
            mainmenu!.scaleMode = .aspectFill
            self.view?.presentScene(mainmenu!, transition:
 SKTransition.fade(withDuration: TimeInterval(1)))
        }

    }

}

override func touchesEnded(_ touches: Set<UITouch>, with event:
UIEvent?) {

}

override func touchesMoved(_ touches: Set<UITouch>, with event:
UIEvent?) {

}

func didBegin(_ contact: SKPhysicsContact) {

    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()

    if contact.bodyA.node?.name == "Player" {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name ==
"Red" {
        playerDied()
        firstBody.node?.removeFromParent()
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name ==
"Blue" {
        playerDied()
        firstBody.node?.removeFromParent()
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name ==
"Green" {
        playerDied()
        firstBody.node?.removeFromParent()
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name ==
"Yellow" {
        playerDied()
        firstBody.node?.removeFromParent()
    }

}

func initialize() {

    score = 0

    physicsWorld.contactDelegate = self

    createPlayer()
    createBackground()
    spawnRedBall()
    spawnBlueBall()
    spawnGreenBall()
    spawnYellowBall()
    createLabel()

    counter = Timer.scheduledTimer(timeInterval: TimeInterval(0.7),
target: self, selector: "incrementScore", userInfo: nil, repeats: true)
}

func createPlayer() {
    player = Player(imageNamed: "Player")
    player.initialize()
    player.position = CGPoint(x: 0, y: 0)
    self.addChild(player)
}

func createBackground() {
    let bg = SKSpriteNode(imageNamed: "BG")
    bg.name = "BG"
    bg.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    bg.position = CGPoint(x: 0, y: 0)
    self.addChild(bg)
}

func createRedBall() {
    let ball = SKSpriteNode(imageNamed: "Red")
    ball.name = "Red"
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    ball.zPosition = 1
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height /
2)
    ball.physicsBody?.categoryBitMask = ColliderType.Red
    ball.physicsBody?.affectedByGravity = false
    ball.physicsBody?.isDynamic = false

    ball.position.y = self.size.height + 100
    ball.position.x = CGFloat.randomBetweenNumbers(firstNum: -345,
secondNum: 345)

    self.addChild(ball)

    let destination = self.frame.height * 2
    let move = SKAction.moveTo(y: -destination, duration:
TimeInterval(10))
    let remove = SKAction.removeFromParent()

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveRed")
}

func spawnRedBall() {

    let spawn = SKAction.run({ () -> Void in
        self.createRedBall()
    })

    let delay = SKAction.wait(forDuration: TimeInterval(0.5))
    let sequence = SKAction.sequence([spawn, delay])

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnRed")
}

func createBlueBall() {
    let ball = SKSpriteNode(imageNamed: "Blue")
    ball.name = "Blue"
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    ball.zPosition = 1
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height /
2)
    ball.physicsBody?.categoryBitMask = ColliderType.Blue
    ball.physicsBody?.affectedByGravity = false
    ball.physicsBody?.isDynamic = false

    ball.position.y = -self.size.height + 100
    ball.position.x = CGFloat.randomBetweenNumbers(firstNum: -345,
secondNum: 345)

    self.addChild(ball)

    let destination = self.frame.height * 2
    let move = SKAction.moveTo(y: destination, duration:
TimeInterval(10))
    let remove = SKAction.removeFromParent()

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveBlue")
}

func spawnBlueBall() {

    let spawn = SKAction.run({ () -> Void in
        self.createBlueBall()
    })

    let delay = SKAction.wait(forDuration: TimeInterval(0.5))
    let sequence = SKAction.sequence([spawn, delay])

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnBlue")
}

func createGreenBall() {
    let ball = SKSpriteNode(imageNamed: "Green")
    ball.name = "Green"
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    ball.zPosition = 1
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height /
2)
    ball.physicsBody?.categoryBitMask = ColliderType.Green
    ball.physicsBody?.affectedByGravity = false
    ball.physicsBody?.isDynamic = false

    ball.position.x = -self.size.width + 200
    ball.position.y = CGFloat.randomBetweenNumbers(firstNum: -637,
secondNum: 637)

    self.addChild(ball)

    let destination = self.frame.height * 2
    let move = SKAction.moveTo(x: destination, duration:
TimeInterval(10))
    let remove = SKAction.removeFromParent()

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveGreen")
}

func spawnGreenBall() {

    let spawn = SKAction.run({ () -> Void in
        self.createGreenBall()
    })

    let delay = SKAction.wait(forDuration: TimeInterval(0.5))
    let sequence = SKAction.sequence([spawn, delay])

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnGreen")
}

func createYellowBall() {
    let ball = SKSpriteNode(imageNamed: "Yellow")
    ball.name = "Yellow"
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    ball.zPosition = 1
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height /
2)
    ball.physicsBody?.categoryBitMask = ColliderType.Green
    ball.physicsBody?.affectedByGravity = false
    ball.physicsBody?.isDynamic = false

    ball.position.x = self.size.width + 200
    ball.position.y = CGFloat.randomBetweenNumbers(firstNum: -637,
secondNum: 637)

    self.addChild(ball)

    let destination = self.frame.height * 2
    let move = SKAction.moveTo(x: -destination, duration:
TimeInterval(10))
    let remove = SKAction.removeFromParent()

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveYellow")
}

func spawnYellowBall() {

    let spawn = SKAction.run({ () -> Void in
        self.createYellowBall()
    })

    let delay = SKAction.wait(forDuration: TimeInterval(0.5))
    let sequence = SKAction.sequence([spawn, delay])

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnYellow")
}

func createLabel() {
    scoreLabel.zPosition = 3
    scoreLabel.position = CGPoint(x: -320, y: 600)
    scoreLabel.fontName = "Verdana"
    scoreLabel.fontSize = 70
    scoreLabel.text = "0"
    self.addChild(scoreLabel)
}

func incrementScore() {
    score += 1
    scoreLabel.text = String(score)
}

func playerDied() {

    counter.invalidate()

    let highscore = GameManager.instance.getHighscore()

    if highscore < score {
        GameManager.instance.setHighscore(highscore: score)
    }

    let retry = SKSpriteNode(imageNamed: "Retry")
    let quit = SKSpriteNode(imageNamed: "Quit")

    retry.name = "Retry"
    retry.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    retry.position = CGPoint(x: -150, y: -50)
    retry.zPosition = 2
    retry.setScale(0)

    quit.name = "Quit"
    quit.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    quit.position = CGPoint(x: 150, y: -50)
    quit.zPosition = 2
    quit.setScale(0)

    let scaleUp = SKAction.scale(to: 1, duration: TimeInterval(0.5))

    retry.run(scaleUp)
    quit.run(scaleUp)

    self.addChild(retry)
    self.addChild(quit)

}

}
</code>```

答:
I think it is more natural when implementing a dragging, to drag a sprite from the touch location rather than from the center of the sprite. To do this, you should calculate the offset and add it the new sprite's position, like this:</p>

```<code>override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        for touch in touches {

            let current =  touch.location(in: self)
            let previous = touch.previousLocation(in: self)

            if ball.contains(current) {

                let offset = CGPoint(x: current.x - previous.x , y: current.y - previous.y)
                ball.position = CGPoint(x: ball.position.x + offset.x , y: ball.position.y + offset.y)
            }
        }
    }
</code>```

Body:
I'm making a game where the ball(the player) is suppose to avoid other balls passing by the screen. Basically I want the ball always to follow the location of the touch. So wherever I'm moving my finger on the screen, the ball follows.

This is the player Class:

import SpriteKit

struct ColliderType {

static let Player: UInt32 = 1
static let Blue: UInt32 = 2
static let Green: UInt32 = 3
static let Yellow: UInt32 = 4
static let Red: UInt32 = 5

}

class Player: SKSpriteNode {

func initialize() {
    self.name = "Player"
    self.zPosition = 1
    self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.height /
 2)
    self.physicsBody?.affectedByGravity = false
    self.physicsBody?.categoryBitMask = ColliderType.Player
    self.physicsBody?.collisionBitMask = ColliderType.Blue |
 ColliderType.Green | ColliderType.Red | ColliderType.Yellow
    self.physicsBody?.contactTestBitMask = ColliderType.Blue |
 ColliderType.Green | ColliderType.Red | ColliderType.Yellow
 }

 }

This is the GameplayScene:

import SpriteKit

class GameplayScene: SKScene, SKPhysicsContactDelegate {

var player = Player()

var ball = SKSpriteNode()

var scoreLabel = SKLabelNode()
var score = 0

var counter = Timer()

override func didMove(to view: SKView) {
    initialize()
}

override func update(_ currentTime: TimeInterval) {

}

override func touchesBegan(_ touches: Set<UITouch>, with event:
UIEvent?) {

    for touch in touches {

        let location = touch.location(in: self)

        if atPoint(location).name == "Retry" {
            self.removeAllActions()
            self.removeAllChildren()
            initialize()
        }

        if atPoint(location).name == "Quit" {
            let mainmenu = MainMenuScene(fileNamed: "MainMenuScene")
            mainmenu!.scaleMode = .aspectFill
            self.view?.presentScene(mainmenu!, transition:
 SKTransition.fade(withDuration: TimeInterval(1)))
        }

    }

}

override func touchesEnded(_ touches: Set<UITouch>, with event:
UIEvent?) {

}

override func touchesMoved(_ touches: Set<UITouch>, with event:
UIEvent?) {

}

func didBegin(_ contact: SKPhysicsContact) {

    var firstBody = SKPhysicsBody()
    var secondBody = SKPhysicsBody()

    if contact.bodyA.node?.name == "Player" {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name ==
"Red" {
        playerDied()
        firstBody.node?.removeFromParent()
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name ==
"Blue" {
        playerDied()
        firstBody.node?.removeFromParent()
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name ==
"Green" {
        playerDied()
        firstBody.node?.removeFromParent()
    }

    if firstBody.node?.name == "Player" && secondBody.node?.name ==
"Yellow" {
        playerDied()
        firstBody.node?.removeFromParent()
    }

}

func initialize() {

    score = 0

    physicsWorld.contactDelegate = self

    createPlayer()
    createBackground()
    spawnRedBall()
    spawnBlueBall()
    spawnGreenBall()
    spawnYellowBall()
    createLabel()

    counter = Timer.scheduledTimer(timeInterval: TimeInterval(0.7),
target: self, selector: "incrementScore", userInfo: nil, repeats: true)
}

func createPlayer() {
    player = Player(imageNamed: "Player")
    player.initialize()
    player.position = CGPoint(x: 0, y: 0)
    self.addChild(player)
}

func createBackground() {
    let bg = SKSpriteNode(imageNamed: "BG")
    bg.name = "BG"
    bg.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    bg.position = CGPoint(x: 0, y: 0)
    self.addChild(bg)
}

func createRedBall() {
    let ball = SKSpriteNode(imageNamed: "Red")
    ball.name = "Red"
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    ball.zPosition = 1
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height /
2)
    ball.physicsBody?.categoryBitMask = ColliderType.Red
    ball.physicsBody?.affectedByGravity = false
    ball.physicsBody?.isDynamic = false

    ball.position.y = self.size.height + 100
    ball.position.x = CGFloat.randomBetweenNumbers(firstNum: -345,
secondNum: 345)

    self.addChild(ball)

    let destination = self.frame.height * 2
    let move = SKAction.moveTo(y: -destination, duration:
TimeInterval(10))
    let remove = SKAction.removeFromParent()

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveRed")
}

func spawnRedBall() {

    let spawn = SKAction.run({ () -> Void in
        self.createRedBall()
    })

    let delay = SKAction.wait(forDuration: TimeInterval(0.5))
    let sequence = SKAction.sequence([spawn, delay])

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnRed")
}

func createBlueBall() {
    let ball = SKSpriteNode(imageNamed: "Blue")
    ball.name = "Blue"
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    ball.zPosition = 1
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height /
2)
    ball.physicsBody?.categoryBitMask = ColliderType.Blue
    ball.physicsBody?.affectedByGravity = false
    ball.physicsBody?.isDynamic = false

    ball.position.y = -self.size.height + 100
    ball.position.x = CGFloat.randomBetweenNumbers(firstNum: -345,
secondNum: 345)

    self.addChild(ball)

    let destination = self.frame.height * 2
    let move = SKAction.moveTo(y: destination, duration:
TimeInterval(10))
    let remove = SKAction.removeFromParent()

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveBlue")
}

func spawnBlueBall() {

    let spawn = SKAction.run({ () -> Void in
        self.createBlueBall()
    })

    let delay = SKAction.wait(forDuration: TimeInterval(0.5))
    let sequence = SKAction.sequence([spawn, delay])

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnBlue")
}

func createGreenBall() {
    let ball = SKSpriteNode(imageNamed: "Green")
    ball.name = "Green"
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    ball.zPosition = 1
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height /
2)
    ball.physicsBody?.categoryBitMask = ColliderType.Green
    ball.physicsBody?.affectedByGravity = false
    ball.physicsBody?.isDynamic = false

    ball.position.x = -self.size.width + 200
    ball.position.y = CGFloat.randomBetweenNumbers(firstNum: -637,
secondNum: 637)

    self.addChild(ball)

    let destination = self.frame.height * 2
    let move = SKAction.moveTo(x: destination, duration:
TimeInterval(10))
    let remove = SKAction.removeFromParent()

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveGreen")
}

func spawnGreenBall() {

    let spawn = SKAction.run({ () -> Void in
        self.createGreenBall()
    })

    let delay = SKAction.wait(forDuration: TimeInterval(0.5))
    let sequence = SKAction.sequence([spawn, delay])

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnGreen")
}

func createYellowBall() {
    let ball = SKSpriteNode(imageNamed: "Yellow")
    ball.name = "Yellow"
    ball.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    ball.zPosition = 1
    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.height /
2)
    ball.physicsBody?.categoryBitMask = ColliderType.Green
    ball.physicsBody?.affectedByGravity = false
    ball.physicsBody?.isDynamic = false

    ball.position.x = self.size.width + 200
    ball.position.y = CGFloat.randomBetweenNumbers(firstNum: -637,
secondNum: 637)

    self.addChild(ball)

    let destination = self.frame.height * 2
    let move = SKAction.moveTo(x: -destination, duration:
TimeInterval(10))
    let remove = SKAction.removeFromParent()

    ball.run(SKAction.sequence([move, remove]), withKey: "MoveYellow")
}

func spawnYellowBall() {

    let spawn = SKAction.run({ () -> Void in
        self.createYellowBall()
    })

    let delay = SKAction.wait(forDuration: TimeInterval(0.5))
    let sequence = SKAction.sequence([spawn, delay])

    self.run(SKAction.repeatForever(sequence), withKey: "SpawnYellow")
}

func createLabel() {
    scoreLabel.zPosition = 3
    scoreLabel.position = CGPoint(x: -320, y: 600)
    scoreLabel.fontName = "Verdana"
    scoreLabel.fontSize = 70
    scoreLabel.text = "0"
    self.addChild(scoreLabel)
}

func incrementScore() {
    score += 1
    scoreLabel.text = String(score)
}

func playerDied() {

    counter.invalidate()

    let highscore = GameManager.instance.getHighscore()

    if highscore < score {
        GameManager.instance.setHighscore(highscore: score)
    }

    let retry = SKSpriteNode(imageNamed: "Retry")
    let quit = SKSpriteNode(imageNamed: "Quit")

    retry.name = "Retry"
    retry.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    retry.position = CGPoint(x: -150, y: -50)
    retry.zPosition = 2
    retry.setScale(0)

    quit.name = "Quit"
    quit.anchorPoint = CGPoint(x: 0.5, y: 0.5)
    quit.position = CGPoint(x: 150, y: -50)
    quit.zPosition = 2
    quit.setScale(0)

    let scaleUp = SKAction.scale(to: 1, duration: TimeInterval(0.5))

    retry.run(scaleUp)
    quit.run(scaleUp)

    self.addChild(retry)
    self.addChild(quit)

}

}

Body:
I think it is more natural when implementing a dragging, to drag a sprite from the touch location rather than from the center of the sprite. To do this, you should calculate the offset and add it the new sprite's position, like this:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        for touch in touches {

            let current =  touch.location(in: self)
            let previous = touch.previousLocation(in: self)

            if ball.contains(current) {

                let offset = CGPoint(x: current.x - previous.x , y: current.y - previous.y)
                ball.position = CGPoint(x: ball.position.x + offset.x , y: ball.position.y + offset.y)
            }
        }
    }


问:
Why is 'new' an operator, not a function?
Are there any issues, like compile time operator, with sizeof associated with new?</p>

答:
I think the short answer to your question is that the new operator isn't a function, because it is the new that appears in a new-expression, and new-expression doesn't follow the function call syntax. How can it be a function, when one of the possible components/operand of a new-expression is a type-id? Could you define the syntax of a new-expression such that new would be a function, presumably overloaded on the type being allocated? And if you could, would Bjarne Stroustrup have preferred that syntax to the syntax he actually invented, and that ISO standardized?

To be honest, I think that in everyday English the standard is pushing its luck classifying the new-expression as a "unary expression" at all. If it is, then its "single" operand consists of up to three separate parts (new-placement, new-type-id, new-initializer). Not that it really matters - it is what it is, and AFAIK the standard doesn't define any properties which apply to all operators, so it doesn't matter that much whether you call it an operator, or just a keyword used to introduce a new-expression.


问:
Makefile execute script for every file in folder
i want to execute for every .sh file a shell script that convert a .sh script into .md file.
At the moment i got this output from makefile

```<code>'./myscript' < testB.sh testA.sh >> testB.md testA.md
</code>```

but i want an output like this

```<code>'./myscript' < testA.sh >> testA.md; './shelltomd' < testB.sh >> testB.md
</code>```

i want to do this without any form of loop but i dont know how to solve this with makefile only :/

my Makefile

```<code>SH_FILES=$(wildcard *.sh)
SHTOMD=$(SH_FILES:.sh=.md)
md:
'./myscript' <$< $(SH_FILES) >>$< $(SHTOMD)
</code>```

thank you for your help stackoverflow community and sry for my bad english :D

答:
You need to write a single rule that knows how to turn one .sh file into one .md file.  You can use a pattern rule for that:

```<code>%.md : %.sh
        './myscript' < $< > $@
</code>```

(I doubt you want to use >> here)

Once you have taught make how to create an .md file, just tell it which md files you want to create:

```<code>SH_FILES := $(wildcard *.sh)
MD_FILES := $(SH_FILES:.sh=.md)

md: $(MD_FILES)
</code>```

and you're done.

Body:
i want to execute for every .sh file a shell script that convert a .sh script into .md file.
At the moment i got this output from makefile

'./myscript' < testB.sh testA.sh >> testB.md testA.md

but i want an output like this

'./myscript' < testA.sh >> testA.md; './shelltomd' < testB.sh >> testB.md

i want to do this without any form of loop but i dont know how to solve this with makefile only :/

my Makefile

SH_FILES=$(wildcard *.sh)
SHTOMD=$(SH_FILES:.sh=.md)
md:
'./myscript' <$< $(SH_FILES) >>$< $(SHTOMD)

thank you for your help stackoverflow community and sry for my bad english :D

Body:
You need to write a single rule that knows how to turn one .sh file into one .md file.  You can use a pattern rule for that:

%.md : %.sh
        './myscript' < $< > $@

(I doubt you want to use >> here)

Once you have taught make how to create an .md file, just tell it which md files you want to create:

SH_FILES := $(wildcard *.sh)
MD_FILES := $(SH_FILES:.sh=.md)

md: $(MD_FILES)

and you're done.


问:
How can I delete unwanted elements from this JSON array?
I have the following response from an API containing a JSON array and I am trying to remove all elements except for title, column, and searchSourceJSON:

```<code>"hits": [
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Integration-Enabled",
        "_score": 1,
        "_source": {
            "title": "demo Media Integration - Enabled",
            "description": "",
            "hits": 0,
            "columns": [
                "_source"
            ],
            "sort": [
                "timestamp",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"value\":\"Media Integration\",\"disabled\":false},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Integration\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Action\",\"value\":\"Enable\",\"disabled\":false},\"query\":{\"match\":{\"Action\":{\"query\":\"Enable\",\"type\":\"phrase\"}}}}],\"query\":{\"query_string\":{\"query\":\"*\",\"analyze_wildcard\":true}}}"
            }
        }
    },
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Import-True",
        "_score": 1,
        "_source": {
            "title": "demo Media Import - True",
            "description": "",
            "hits": 0,
            "columns": [
                "FormFactor",
                "_type",
                "Identity"
            ],
            "sort": [
                "_type",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"*\"}},\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"disabled\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"negate\":false,\"value\":\"Media Import\"},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Import\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Successful\",\"value\":\"True\",\"disabled\":false},\"query\":{\"match\":{\"Successful\":{\"query\":\"True\",\"type\":\"phrase\"}}}}]}"
            }
        }
    }
]
</code>```

Could someone help me figure out how to delete the unwanted elements from this JSON document using JavaScript?

EDIT: Answered, thank you everyone for the great information!

答:
One low effort way is to use Array#Map and then select only the elements you want.

var hits = [
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Integration-Enabled",
        "_score": 1,
        "_source": {
            "title": "demo Media Integration - Enabled",
            "description": "",
            "hits": 0,
            "columns": [
                "_source"
            ],
            "sort": [
                "timestamp",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"value\":\"Media Integration\",\"disabled\":false},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Integration\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Action\",\"value\":\"Enable\",\"disabled\":false},\"query\":{\"match\":{\"Action\":{\"query\":\"Enable\",\"type\":\"phrase\"}}}}],\"query\":{\"query_string\":{\"query\":\"*\",\"analyze_wildcard\":true}}}"
            }
        }
    },
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Import-True",
        "_score": 1,
        "_source": {
            "title": "demo Media Import - True",
            "description": "",
            "hits": 0,
            "columns": [
                "FormFactor",
                "_type",
                "Identity"
            ],
            "sort": [
                "_type",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"*\"}},\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"disabled\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"negate\":false,\"value\":\"Media Import\"},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Import\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Successful\",\"value\":\"True\",\"disabled\":false},\"query\":{\"match\":{\"Successful\":{\"query\":\"True\",\"type\":\"phrase\"}}}}]}"
            }
        }
    }
]

var filtered = hits.map(function(hit){
  return { title : hit._source.title, searchSourceJSON : hit._source.exampleSavedObjectMeta.searchSourceJSON, columns : hit._source.columns}
})

console.log(filtered)```

Body:
I have the following response from an API containing a JSON array and I am trying to remove all elements except for title, column, and searchSourceJSON:

"hits": [
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Integration-Enabled",
        "_score": 1,
        "_source": {
            "title": "demo Media Integration - Enabled",
            "description": "",
            "hits": 0,
            "columns": [
                "_source"
            ],
            "sort": [
                "timestamp",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"value\":\"Media Integration\",\"disabled\":false},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Integration\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Action\",\"value\":\"Enable\",\"disabled\":false},\"query\":{\"match\":{\"Action\":{\"query\":\"Enable\",\"type\":\"phrase\"}}}}],\"query\":{\"query_string\":{\"query\":\"*\",\"analyze_wildcard\":true}}}"
            }
        }
    },
    {
        "_index": ".example_demo",
        "_type": "search",
        "_id": "demo-Media-Import-True",
        "_score": 1,
        "_source": {
            "title": "demo Media Import - True",
            "description": "",
            "hits": 0,
            "columns": [
                "FormFactor",
                "_type",
                "Identity"
            ],
            "sort": [
                "_type",
                "asc"
            ],
            "version": 1,
            "exampleSavedObjectMeta": {
                "searchSourceJSON": "{\"index\":\"[demo-]YYYY.MM\",\"query\":{\"query_string\":{\"analyze_wildcard\":true,\"query\":\"*\"}},\"highlight\":{\"pre_tags\":[\"@example-highlighted-field@\"],\"post_tags\":[\"@/example-highlighted-field@\"],\"fields\":{\"*\":{}},\"fragment_size\":2147483647},\"filter\":[{\"meta\":{\"disabled\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"_type\",\"negate\":false,\"value\":\"Media Import\"},\"query\":{\"match\":{\"_type\":{\"query\":\"Media Import\",\"type\":\"phrase\"}}}},{\"meta\":{\"negate\":false,\"index\":\"[demo-]YYYY.MM\",\"key\":\"Successful\",\"value\":\"True\",\"disabled\":false},\"query\":{\"match\":{\"Successful\":{\"query\":\"True\",\"type\":\"phrase\"}}}}]}"
            }
        }
    }
]

Could someone help me figure out how to delete the unwanted elements from this JSON document using JavaScript?

EDIT: Answered, thank you everyone for the great information!


问:
Python 3.2 won't import cookielib
I have looked everywhere for this and just cannot find the answer. I have checked my python version and it is version 3.2 . When I try to import cookielib I receive:

ImportError: No module named cookielib

I have seen that in Python 3.0 it was renamed to
http.cookiejar and that it would auto import cookielib.

I thought that maybe there was some wild error in my python configuration so I thought I should try and import http.cookiejar like this import http.cookiejar. That did not work all and I get and error:

 EOFError: EOF read where not expected.

This is not the error I had expected becuase import http.cookies imports just fine.

Does anybody have a solution to this problem? What am I overlooking?

Full Error:

```<code>Traceback (most recent call last):
  File "C:\Users\Spencer\Downloads\selenium-2.20.0.tar\selenium-2.20.0\selenium-2.20.0\test", line 1, in <module>
    import urllib.request, urllib.parse, http.cookiejar
EOFError: EOF read where not expected
</code>```

答: The cookielib module has been renamed to http.cookiejar in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.

Title: Python 3.2 won't import cookielib

Body:
I have looked everywhere for this and just cannot find the answer. I have checked my python version and it is version 3.2 . When I try to import cookielib I receive:

ImportError: No module named cookielib

I have seen that in Python 3.0 it was renamed to
http.cookiejar and that it would auto import cookielib.

I thought that maybe there was some wild error in my python configuration so I thought I should try and import http.cookiejar like this import http.cookiejar. That did not work all and I get and error:

 EOFError: EOF read where not expected.

This is not the error I had expected becuase import http.cookies imports just fine.

Does anybody have a solution to this problem? What am I overlooking?

Full Error:

Traceback (most recent call last):
  File "C:\Users\Spencer\Downloads\selenium-2.20.0.tar\selenium-2.20.0\selenium-2.20.0\test", line 1, in <module>
    import urllib.request, urllib.parse, http.cookiejar
EOFError: EOF read where not expected


问:
Tensorflow read images with labels
I am building a standard image classification model with Tensorflow. For this I have input images, each assigned with a label (number in {0,1}). The Data can hence be stored in a list using the following format:

```<code>/path/to/image_0 label_0
/path/to/image_1 label_1
/path/to/image_2 label_2
...
</code>```

I want to use TensorFlow's queuing system to read my data and feed it to my model. Ignoring the labels, one can easily achieve this by using string_input_producer and wholeFileReader. Here the code:

```<code>def read_my_file_format(filename_queue):
  reader = tf.WholeFileReader()
  key, value = reader.read(filename_queue)
  example = tf.image.decode_png(value)
  return example

#removing label, obtaining list containing /path/to/image_x
image_list = [line[:-2] for line in image_label_list]

input_queue = tf.train.string_input_producer(image_list)
input_images = read_my_file_format(input_queue)
</code>```

However, the labels are lost in that process as the image data is purposely shuffled as part of the input pipeline. What is the easiest way of pushing the labels together with the image data through the input queues?

答:
In addition to the answers provided there are few other things you can do:

Encode your label into the filename. If you have N different categories you can rename your files to something like: 0_file001, 5_file002, N_file003. Afterwards when you read the data from a reader key, value = reader.read(filename_queue) your key/value are:

The output of Read will be a filename (key) and the contents of that file (value)

Then parse your filename, extract the label and convert it to int. This will require a little bit of preprocessing of the data.

Use TFRecords which will allow you to store the data and labels at the same file.

Title: Tensorflow read images with labels

Body:
I am building a standard image classification model with Tensorflow. For this I have input images, each assigned with a label (number in {0,1}). The Data can hence be stored in a list using the following format:

/path/to/image_0 label_0
/path/to/image_1 label_1
/path/to/image_2 label_2
...

I want to use TensorFlow's queuing system to read my data and feed it to my model. Ignoring the labels, one can easily achieve this by using string_input_producer and wholeFileReader. Here the code:

def read_my_file_format(filename_queue):
  reader = tf.WholeFileReader()
  key, value = reader.read(filename_queue)
  example = tf.image.decode_png(value)
  return example

#removing label, obtaining list containing /path/to/image_x
image_list = [line[:-2] for line in image_label_list]

input_queue = tf.train.string_input_producer(image_list)
input_images = read_my_file_format(input_queue)

However, the labels are lost in that process as the image data is purposely shuffled as part of the input pipeline. What is the easiest way of pushing the labels together with the image data through the input queues?


答:
This behavior is due to text indexes being sparse by default:

For a compound index that includes a text index key along with keys of
  other types, only the text index field determines whether the index
  references a document. The other keys do not determine whether the
  index references the documents or not.

The query filter is not referencing the text index field, so the query planner won't consider this index as it can't be certain that the full result set of documents will be returned by the index.

Title: Mongodb query does not use prefix on compound index with text field

Body:
I've created the following index on my collection:

db.myCollection.createIndex({
  user_id: 1,
  name: 'text'
})

If I try to see the execution plan of a query containing both fields, like this:

db.getCollection('campaigns').find({
    user_id: ObjectId('xxx')
   ,$text: { $search: 'bla' }
}).explain('executionStats')

I get the following results:

...
"winningPlan" : {
    "stage" : "TEXT",
    "indexPrefix" : {
        "user_id" : ObjectId("xxx")
    },
    "indexName" : "user_id_1_name_text",
    "parsedTextQuery" : {
        "terms" : [
            "e"
        ],
        "negatedTerms" : [],
        "phrases" : [],
        "negatedPhrases" : []
    },
    "inputStage" : {
        "stage" : "TEXT_MATCH",
        "inputStage" : {
            "stage" : "TEXT_OR",
            "inputStage" : {
                "stage" : "IXSCAN",
                "keyPattern" : {
                    "user_id" : 1.0,
                    "_fts" : "text",
                    "_ftsx" : 1
                },
                "indexName" : "user_id_1_name_text",
                "isMultiKey" : true,
                "isUnique" : false,
                "isSparse" : false,
                "isPartial" : false,
                "indexVersion" : 1,
                "direction" : "backward",
                "indexBounds" : {}
            }
        }
    }
}
...

As stated in the documentation, MongoDB can use index prefixes to perform indexed queries.

Since user_id is a prefix for the index above, I'd expect that a query only by user_id would use the index, but if I try the following:

db.myCollection.find({
    user_id: ObjectId('xxx')
}).explain('executionStats')

I get:

...
"winningPlan" : {
    "stage" : "COLLSCAN",
    "filter" : {
        "user_id" : {
            "$eq" : ObjectId("xxx")
        }
    },
    "direction" : "forward"
},
...

So, it is not using the index at all and performing a full collection scan.


问:
In Ruby, what is the cleanest way of obtaining the index of the largest value in an array?
If a is the array, I want a.index(a.max), but something more Ruby-like.  It should be obvious, but I'm having trouble finding the answer at so and elsewhere.  Obviously, I am new to Ruby.

答:
Here is a way to get all the index values of the max values if more than one.

Given:

```<code>> a
=> [1, 2, 3, 4, 5, 6, 7, 9, 9, 2, 3]
</code>```

You can find the index of all the max values (or any given value) by:

```<code>> a.each_with_index.select {|e, i| e==a.max}.map &:last
=> [7, 8]
</code>```

Body:
Here is a way to get all the index values of the max values if more than one.

Given:

> a
=> [1, 2, 3, 4, 5, 6, 7, 9, 9, 2, 3]

You can find the index of all the max values (or any given value) by:

> a.each_with_index.select {|e, i| e==a.max}.map &:last
=> [7, 8]


问:
How to separate nodejs sessions
I have a very simple nodejs chatbot that learns things about a client that is connected to it. For example, if a client says "My name is Bob" and then asks the chatbot "What is my name?" the chatbot will say "Bob" the problem is that if another client connects to the server and then asks the chatbot the same question, the chatbot will also reply with "Bob". I understand I need to implement some way of dealing with sessions but everything I found online about sessions was explaining things about cookies and how to store user authentication.

All I want to do is let each client have his own instance of the server that knows nothing about the other clients.

答:
You can use an in-memory database such as Redis to store information about connected users by identifying them by their id.
Let's suppose you are using messenger platform for your bot. Each message you receive from Facebook to your webhook comes along with some information, such as the id of user who sent the message, the id of the page to which the message was sent, etc. You can then use Redis to store any information about any user (userID, userName, etc). Once you receive a message, you just query information about the user using their id as the key.</p>

Title: How to separate nodejs sessions


问:
Trying to make a footer with buttons floated to the left and right
I would like this code to resemble the bottom of Google's homepage. It is still listing vertically, even with "inline". I want each three "lists" to be next to each other horizontally on the left and right side of the screen.</p>

```<code>#HTML
<footer>
<div class="footer">
<ul style="width:10%; float:left;list-style-type:none;">
      <li>Advertising</li>
      <li>Business</li>
      <li>About</li>
   </ul>

   <ul style="width:10%; float:right;list-style-type:none;">
      <li>Privacy</li>
      <li>Terms</li>
      <li>Settings</li>
   </ul>
</div>
</footer>

#CSS

.footer li{
  display:inline;
}
</code>```

答:
You could use display: flex; on the .footer DIV, with settings as below

.footer ul {
  list-style-type: none;
  padding: 0;
}
.footer li {
  display: inline-block;
}
.footer {
  display: flex;
  justify-content: space-between;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div class="footer">
    <ul>
      <li>Advertising</li>
      <li>Business</li>
      <li>About</li>
    </ul>

    <ul>
      <li>Privacy</li>
      <li>Terms</li>
      <li>Settings</li>
    </ul>
  </div>
</footer></code>```

Body:
I would like this code to resemble the bottom of Google's homepage. It is still listing vertically, even with "inline". I want each three "lists" to be next to each other horizontally on the left and right side of the screen.

#HTML

Advertising

Business

About

Privacy

Terms

Settings

#CSS

.footer li{
  display:inline;
}

Body:
You could use display: flex; on the .footer DIV, with settings as below

.footer ul {
  list-style-type: none;
  padding: 0;
}
.footer li {
  display: inline-block;
}
.footer {
  display: flex;
  justify-content: space-between;
}

<footer>
  <div class="footer">
    <ul>
      <li>Advertising</li>
      <li>Business</li>
      <li>About</li>
    </ul>

    <ul>
      <li>Privacy</li>
      <li>Terms</li>
      <li>Settings</li>
    </ul>
  </div>
</footer>


问:
Out of the box Light Switch HTML app has a null error in IE9?
I am trying LightSwitch for the first time, and after making a new HTML C# App - I tried to run it just to see what it looks like.  IE9 freezes immediately and I get this error from Visual Studio 2013:

Unhandled exception at line 5, column 19701 in http://localhost:49609/HTMLClient/Scripts/msls-2.5.1.min.js

0x800a138f - Microsoft JScript runtime error: Unable to get value of the property 'cultures': object is null or undefined

Does anyone know whats going on?  Thank you!

答:
This impacted me on VS 2015 all browsers. I think this is because of a closed environment for the server.

Lin M is basically correct:
Download the two files into the Scripts folder:
http://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js http://ajax.aspnetcdn.com/ajax/globalize/0.1.1/globalize.min.js

Next:
In default.htm  change:

```<code><script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/globalize/0.1.1/globalize.min.js"></script>
</code>```

to:

```<code><script type="text/javascript" src="Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="Scripts/globalize.min.js"></script>
</code>```

Body:
This impacted me on VS 2015 all browsers. I think this is because of a closed environment for the server.

Lin M is basically correct:
Download the two files into the Scripts folder:
http://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js http://ajax.aspnetcdn.com/ajax/globalize/0.1.1/globalize.min.js

Next:
In default.htm  change:

<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>
<script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/globalize/0.1.1/globalize.min.js"></script>

to:

<script type="text/javascript" src="Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="Scripts/globalize.min.js"></script>


答:
You can parse the JSON, and then map to create a new array containing objects with just the properties you need :</p>

```<code>const data = JSON.parse(yourJSON);
const hits = data.hits.map(hit => ({
    title: hit._source.title,
    searchSourceJSON: hit._source.exampleSavedObjectMeta.searchSourceJSON
});
</code>```

Title: How can I delete unwanted elements from this JSON array?

Body:
You can parse the JSON, and then map to create a new array containing objects with just the properties you need :

const data = JSON.parse(yourJSON);
const hits = data.hits.map(hit => ({
    title: hit._source.title,
    searchSourceJSON: hit._source.exampleSavedObjectMeta.searchSourceJSON
});


问:
Tabs don't fit to screen with tabmode=scrollable, Even with a Custom Tab Layout
I have made a custom TabLayout with a ViewPager and am using the TabLayout in scrollable mode:

I need it to be scrollable as the number of dates can vary to as many as 15-20:

```<code><com.example.project.recommendedapp.CustomScrollableTabLayout
    android:id="@+id/tab_layout_movie"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    app:tabGravity="fill"
    app:tabMode="scrollable"
    app:tabTextAppearance="?android:textAppearanceMedium"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
</code>```

The custom class i used as per another similar question:
TabLayout not filling width when tabMode set to 'scrollable'

The custom tablayout class is:

```<code>package com.example.project.recommendedapp;

import android.content.Context;
import android.graphics.Point;
import android.support.design.widget.TabLayout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import java.lang.reflect.Field;

public class CustomScrollableTabLayout extends TabLayout {
    private Context mContext;

    Point size;

    public CustomScrollableTabLayout(Context context) {
        super(context);
        mContext=context;
        size = new Point();
    }

    public CustomScrollableTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext=context;
        size = new Point();
    }

    public CustomScrollableTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext=context;
        size = new Point();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        try {
            if (getTabCount() == 0) {
                return;
            }else {
                Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
                display.getSize(size);
                int width = size.x;

                Field field = TabLayout.class.getDeclaredField("mScrollableTabMinWidth");
                field.setAccessible(true);
                field.set(this, (width / getTabCount()));

                Log.d("FragmentCreate",String.valueOf(width / getTabCount()));
            }
        } catch (Exception e) {
            Log.e("FragmentCreate","Error while setting width",e);
        }
    }
}
</code>```

答:
My solution is slightly different, since I tried the one above and it didn't work on some devices. I've noticed that if all tabs are visible on the screen and if we set tabMode to fixed, TabLayout fills its given width. When we use scrollable, TabLayout acts like its tabGravity is set to center.

So, I calculate the sum of widths of all tabs in TabLayout and if it is lower than measured width I set its tabMode to MODE_FIXED, otherwise to MODE_SCROLLABLE:

```<code>public class CustomTabLayout extends TabLayout {

    private static final String TAG = CustomTabLayout.class.getSimpleName();

    public CustomTabLayout(Context context) {
        super(context);
    }

    public CustomTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getTabCount() == 0)
            return;
        try {
            ViewGroup tabLayout = (ViewGroup)getChildAt(0);
            int widthOfAllTabs = 0;
            for (int i = 0; i < tabLayout.getChildCount(); i++) {
                widthOfAllTabs += tabLayout.getChildAt(i).getMeasuredWidth();
            }
            setTabMode(widthOfAllTabs <= getMeasuredWidth() ? MODE_FIXED : MODE_SCROLLABLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Body:
I have made a custom TabLayout with a ViewPager and am using the TabLayout in scrollable mode:

I need it to be scrollable as the number of dates can vary to as many as 15-20:

<com.example.project.recommendedapp.CustomScrollableTabLayout
    android:id="@+id/tab_layout_movie"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    android:minHeight="?attr/actionBarSize"
    app:tabGravity="fill"
    app:tabMode="scrollable"
    app:tabTextAppearance="?android:textAppearanceMedium"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

The custom class i used as per another similar question:
TabLayout not filling width when tabMode set to 'scrollable'

The custom tablayout class is:

package com.example.project.recommendedapp;

import android.content.Context;
import android.graphics.Point;
import android.support.design.widget.TabLayout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import java.lang.reflect.Field;

public class CustomScrollableTabLayout extends TabLayout {
    private Context mContext;

    Point size;

    public CustomScrollableTabLayout(Context context) {
        super(context);
        mContext=context;
        size = new Point();
    }

    public CustomScrollableTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext=context;
        size = new Point();
    }

    public CustomScrollableTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext=context;
        size = new Point();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        try {
            if (getTabCount() == 0) {
                return;
            }else {
                Display display = ((WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
                display.getSize(size);
                int width = size.x;

                Field field = TabLayout.class.getDeclaredField("mScrollableTabMinWidth");
                field.setAccessible(true);
                field.set(this, (width / getTabCount()));

                Log.d("FragmentCreate",String.valueOf(width / getTabCount()));
            }
        } catch (Exception e) {
            Log.e("FragmentCreate","Error while setting width",e);
        }
    }
}

Body:
My solution is slightly different, since I tried the one above and it didn't work on some devices. I've noticed that if all tabs are visible on the screen and if we set tabMode to fixed, TabLayout fills its given width. When we use scrollable, TabLayout acts like its tabGravity is set to center.

So, I calculate the sum of widths of all tabs in TabLayout and if it is lower than measured width I set its tabMode to MODE_FIXED, otherwise to MODE_SCROLLABLE:

public class CustomTabLayout extends TabLayout {

    private static final String TAG = CustomTabLayout.class.getSimpleName();

    public CustomTabLayout(Context context) {
        super(context);
    }

    public CustomTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (getTabCount() == 0)
            return;
        try {
            ViewGroup tabLayout = (ViewGroup)getChildAt(0);
            int widthOfAllTabs = 0;
            for (int i = 0; i < tabLayout.getChildCount(); i++) {
                widthOfAllTabs += tabLayout.getChildAt(i).getMeasuredWidth();
            }
            setTabMode(widthOfAllTabs <= getMeasuredWidth() ? MODE_FIXED : MODE_SCROLLABLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


问:
Replacing multiple columns with NA Factor Levels with "None"
I'm using the dataset House Prices: Advanced Regression Techniques, which includes multiple factor variables that have NA's among their levels. Consider the columns PoolQL, Alley and MiscFeatures. I want to replace for all these NA's with None in one function, but I fail to do so. Tried this so far:

```<code>MissingLevels <- function(x){
  for(i in names(x)){
  levels <- levels(x[i])
  levels[length(levels) + 1] <- 'None'
  x[i] <- factor(x[i], levels = levels)
  x[i][is.na(x[i])] <- 'None'
  return(x)
  }
}

MissingLevels(df[,c('Alley', 'Fence')])

apply(df[,c('Alley', 'Fence')], 2, MissingLevels)
</code>```

https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data

答:
There are several ways e.g.:

```<code>x <- data.frame(another = 1:3, Alley = c("A", "B", NA), Fence = c("C", NA, NA))
</code>```

Option 1: using forcats package

```<code>x[,c("Alley", "Fence")] <- lapply(x[,c("Alley", "Fence")], fct_explicit_na, na_level = "None")

  another Alley Fence
1       1     A     C
2       2     B  None
3       3  None  None
</code>```

Option 2:

```<code>x[,c("Alley", "Fence")] <- lapply(x[,c("Alley", "Fence")], function(x){`levels<-`(addNA(x), c(levels(x), "None"))})
</code>```

PS: The second answer is inspired in @G. Grothendieck post replace <NA> in a factor column in R

Body:
I'm using the dataset House Prices: Advanced Regression Techniques, which includes multiple factor variables that have NA's among their levels. Consider the columns PoolQL, Alley and MiscFeatures. I want to replace for all these NA's with None in one function, but I fail to do so. Tried this so far:

MissingLevels <- function(x){
  for(i in names(x)){
  levels <- levels(x[i])
  levels[length(levels) + 1] <- 'None'
  x[i] <- factor(x[i], levels = levels)
  x[i][is.na(x[i])] <- 'None'
  return(x)
  }
}

MissingLevels(df[,c('Alley', 'Fence')])

apply(df[,c('Alley', 'Fence')], 2, MissingLevels)

https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data

Body:
There are several ways e.g.:

x <- data.frame(another = 1:3, Alley = c("A", "B", NA), Fence = c("C", NA, NA))

Option 1: using forcats package

x[,c("Alley", "Fence")] <- lapply(x[,c("Alley", "Fence")], fct_explicit_na, na_level = "None")

  another Alley Fence
1       1     A     C
2       2     B  None
3       3  None  None

Option 2:

x[,c("Alley", "Fence")] <- lapply(x[,c("Alley", "Fence")], function(x){`levels<-`(addNA(x), c(levels(x), "None"))})

PS: The second answer is inspired in @G. Grothendieck post replace <NA> in a factor column in R


答:
You can either:

Transverse all the result (which tend to be costly) using a map approach.

Or as it seems to be a request to Elastic Search to filter out the response send by ES. Therefore, less network traffic and you could avoid the need to clean up the data.

You can add a filter path on your query string this way:

_search?filter_path=hits.hits._source