问:
Remove specific XML nodes using Clojure
I have the following XML structure:

```<code>(def xmlstr
"<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>B</Type><Note>BB</Note></Item>
    <Item><Type>C</Type><Note>CC</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>")
</code>```

where I want to remove any Item, if it has a Type B or C. The result should be something like:

```<code><ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>
</code>```

I've found it pretty trivial to query such structures using data.xml and data.xml.zip, e.g:

;; lein try org.clojure/data.xml org.clojure/data.zip
(def xmldoc (clojure.data.xml/parse-str xmlstr))
(def zipxml (clojure.zip/xml-zip xmldoc))

(clojure.data.zip.xml/xml-> zipxml :Items :Item [:Type "A"] :Note clojure.data.zip.xml/text)
;; => ("AA" "AA")
```

but didn't find similar declarative features for removing/editing children.

答:
The Tupelo library can easily solve this problem using tupelo.forest. You can find the API docs on GitHub Pages. Below is a test case using your example.

Here we load your xml data and convert it first into enlive and then the native tree structure used by tupelo.forest:

```<code>(ns tst.tupelo.forest-examples
  (:use tupelo.forest tupelo.test )
  (:require
    [clojure.data.xml :as dx]
    [clojure.java.io :as io]
    [clojure.set :as cs]
    [net.cgrand.enlive-html :as en-html]
    [schema.core :as s]
    [tupelo.core :as t]
    [tupelo.string :as ts]))
(t/refer-tupelo)

; Discard any xml nodes of Type="A" or Type="B" (plus blank string nodes)
(dotest
  (with-forest (new-forest)
    (let [xml-str         "<ROOT>
                            <Items>
                              <Item><Type>A</Type><Note>AA1</Note></Item>
                              <Item><Type>B</Type><Note>BB1</Note></Item>
                              <Item><Type>C</Type><Note>CC1</Note></Item>
                              <Item><Type>A</Type><Note>AA2</Note></Item>
                            </Items>
                          </ROOT>"
          enlive-tree     (->> xml-str
                            java.io.StringReader.
                            en-html/html-resource
                            first)
          root-hid        (add-tree-enlive enlive-tree)
          tree-1          (hid->tree root-hid)
</code>```

The hid suffix stands for "Hex ID" which is unique hex value that acts like a pointer to a node/leaf in the tree. At this stage we have just loaded the data in the forest data structure, creating tree-1 which looks like:

```<code> (is= tree-1
   {:attrs {:tag :ROOT},
    :kids  [{:attrs {:tag :tupelo.forest/raw},
             :value "\n                            "}
            {:attrs {:tag :Items},
             :kids  [{:attrs {:tag :tupelo.forest/raw},
                      :value "\n                              "}
                     {:attrs {:tag :Item},
                      :kids  [{:attrs {:tag :Type}, :value "A"}
                              {:attrs {:tag :Note}, :value "AA1"}]}
                     {:attrs {:tag :tupelo.forest/raw},
                      :value "\n                              "}
                     {:attrs {:tag :Item},
                      :kids  [{:attrs {:tag :Type}, :value "B"}
                              {:attrs {:tag :Note}, :value "BB1"}]}
                     {:attrs {:tag :tupelo.forest/raw},
                      :value "\n                              "}
                     {:attrs {:tag :Item},
                      :kids  [{:attrs {:tag :Type}, :value "C"}
                              {:attrs {:tag :Note}, :value "CC1"}]}
                     {:attrs {:tag :tupelo.forest/raw},
                      :value "\n                              "}
                     {:attrs {:tag :Item},
                      :kids  [{:attrs {:tag :Type}, :value "A"}
                              {:attrs {:tag :Note}, :value "AA2"}]}
                     {:attrs {:tag :tupelo.forest/raw},
                      :value "\n                            "}]}
            {:attrs {:tag :tupelo.forest/raw},
             :value "\n                          "}]})
</code>```

We next remove any blank strings with this code:

```<code>blank-leaf-hid? (fn [hid] (and (leaf-hid? hid) ; ensure it is a leaf node
                            (let [value (hid->value hid)]
                              (and (string? value)
                                (or (zero? (count value)) ; empty string
                                  (ts/whitespace? value)))))) ; all whitespace string

blank-leaf-hids (keep-if blank-leaf-hid? (all-hids))
>>              (apply remove-hid blank-leaf-hids)
tree-2          (hid->tree root-hid)
</code>```

yielding tree-2 which looks much neater:

```<code>(is= tree-2
  {:attrs {:tag :ROOT},
   :kids  [{:attrs {:tag :Items},
            :kids  [{:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "A"}
                             {:attrs {:tag :Note}, :value "AA1"}]}
                    {:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "B"}
                             {:attrs {:tag :Note}, :value "BB1"}]}
                    {:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "C"}
                             {:attrs {:tag :Note}, :value "CC1"}]}
                    {:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "A"}
                             {:attrs {:tag :Note}, :value "AA2"}]}]}]})
</code>```

The final code fragment removes Type="B" or Type="C" nodes:

```<code>type-bc-hid?    (fn [hid] (pos? (count (glue
                            (find-leaf-hids hid [:** :Type] "B")
                            (find-leaf-hids hid [:** :Type] "C")))))

type-bc-hids    (find-hids-with root-hid [:** :Item] type-bc-hid?)
>>              (apply remove-hid type-bc-hids)
tree-3          (hid->tree root-hid)
tree-3-hiccup   (hid->hiccup root-hid) ]
</code>```

yielding the final result tree shown in both tree format and hiccup format:

```<code>(is= tree-3
  {:attrs {:tag :ROOT},
   :kids
          [{:attrs {:tag :Items},
            :kids  [{:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "A"}
                             {:attrs {:tag :Note}, :value "AA1"}]}
                    {:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "A"}
                             {:attrs {:tag :Note}, :value "AA2"}]}]}]})
(is= tree-3-hiccup
  [:ROOT
   [:Items
    [:Item [:Type "A"] [:Note "AA1"]]
    [:Item [:Type "A"] [:Note "AA2"]]]]))))
</code>```

The full example can be found in the forest-examples unit test.

Update

Here is the most compact version with extra features removed:

```<code>(dotest
  (with-forest (new-forest)
    (let [xml-str         "<ROOT>
                            <Items>
                              <Item><Type>A</Type><Note>AA1</Note></Item>
                              <Item><Type>B</Type><Note>BB1</Note></Item>
                              <Item><Type>C</Type><Note>CC1</Note></Item>
                              <Item><Type>A</Type><Note>AA2</Note></Item>
                            </Items>
                          </ROOT>"
          enlive-tree     (->> xml-str
                            java.io.StringReader.
                            en-html/xml-resource
                            first)
          root-hid        (add-tree-enlive enlive-tree)
          blank-leaf-hid? (fn [hid] (ts/whitespace? (hid->value hid)))
          has-bc-leaf?    (fn [hid] (or (has-child-leaf? hid [:** :Type] "B")
                                        (has-child-leaf? hid [:** :Type] "C")))
          blank-leaf-hids (keep-if blank-leaf-hid? (all-leaf-hids))
          >>              (apply remove-hid blank-leaf-hids)
          bc-item-hids    (find-hids-with root-hid [:** :Item] has-bc-leaf?)]
      (apply remove-hid bc-item-hids)
      (is= (hid->hiccup root-hid)
        [:ROOT
         [:Items
          [:Item [:Type "A"] [:Note "AA1"]]
          [:Item [:Type "A"] [:Note "AA2"]]]]))))
</code>```

Title: Remove specific XML nodes using Clojure

Body:
I have the following XML structure:

(def xmlstr
"<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>B</Type><Note>BB</Note></Item>
    <Item><Type>C</Type><Note>CC</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>")

where I want to remove any Item, if it has a Type B or C. The result should be something like:

<ROOT>
  <Items>
    <Item><Type>A</Type><Note>AA</Note></Item>
    <Item><Type>A</Type><Note>AA</Note></Item>
  </Items>
</ROOT>

I've found it pretty trivial to query such structures using data.xml and data.xml.zip, e.g:

;; lein try org.clojure/data.xml org.clojure/data.zip
(def xmldoc (clojure.data.xml/parse-str xmlstr))
(def zipxml (clojure.zip/xml-zip xmldoc))

(clojure.data.zip.xml/xml-> zipxml :Items :Item [:Type "A"] :Note clojure.data.zip.xml/text)
;; => ("AA" "AA")

but didn't find similar declarative features for removing/editing children.

Body:
The Tupelo library can easily solve this problem using tupelo.forest. You can find the API docs on GitHub Pages. Below is a test case using your example.

Here we load your xml data and convert it first into enlive and then the native tree structure used by tupelo.forest:

(ns tst.tupelo.forest-examples
  (:use tupelo.forest tupelo.test )
  (:require
    [clojure.data.xml :as dx]
    [clojure.java.io :as io]
    [clojure.set :as cs]
    [net.cgrand.enlive-html :as en-html]
    [schema.core :as s]
    [tupelo.core :as t]
    [tupelo.string :as ts]))
(t/refer-tupelo)

; Discard any xml nodes of Type="A" or Type="B" (plus blank string nodes)
(dotest
  (with-forest (new-forest)
    (let [xml-str         "<ROOT>
                            <Items>
                              <Item><Type>A</Type><Note>AA1</Note></Item>
                              <Item><Type>B</Type><Note>BB1</Note></Item>
                              <Item><Type>C</Type><Note>CC1</Note></Item>
                              <Item><Type>A</Type><Note>AA2</Note></Item>
                            </Items>
                          </ROOT>"
          enlive-tree     (->> xml-str
                            java.io.StringReader.
                            en-html/html-resource
                            first)
          root-hid        (add-tree-enlive enlive-tree)
          tree-1          (hid->tree root-hid)

The hid suffix stands for "Hex ID" which is unique hex value that acts like a pointer to a node/leaf in the tree. At this stage we have just loaded the data in the forest data structure, creating tree-1 which looks like:

 (is= tree-1
   {:attrs {:tag :ROOT},
    :kids  [{:attrs {:tag :tupelo.forest/raw},
             :value "\n                            "}
            {:attrs {:tag :Items},
             :kids  [{:attrs {:tag :tupelo.forest/raw},
                      :value "\n                              "}
                     {:attrs {:tag :Item},
                      :kids  [{:attrs {:tag :Type}, :value "A"}
                              {:attrs {:tag :Note}, :value "AA1"}]}
                     {:attrs {:tag :tupelo.forest/raw},
                      :value "\n                              "}
                     {:attrs {:tag :Item},
                      :kids  [{:attrs {:tag :Type}, :value "B"}
                              {:attrs {:tag :Note}, :value "BB1"}]}
                     {:attrs {:tag :tupelo.forest/raw},
                      :value "\n                              "}
                     {:attrs {:tag :Item},
                      :kids  [{:attrs {:tag :Type}, :value "C"}
                              {:attrs {:tag :Note}, :value "CC1"}]}
                     {:attrs {:tag :tupelo.forest/raw},
                      :value "\n                              "}
                     {:attrs {:tag :Item},
                      :kids  [{:attrs {:tag :Type}, :value "A"}
                              {:attrs {:tag :Note}, :value "AA2"}]}
                     {:attrs {:tag :tupelo.forest/raw},
                      :value "\n                            "}]}
            {:attrs {:tag :tupelo.forest/raw},
             :value "\n                          "}]})

We next remove any blank strings with this code:

blank-leaf-hid? (fn [hid] (and (leaf-hid? hid) ; ensure it is a leaf node
                            (let [value (hid->value hid)]
                              (and (string? value)
                                (or (zero? (count value)) ; empty string
                                  (ts/whitespace? value)))))) ; all whitespace string

blank-leaf-hids (keep-if blank-leaf-hid? (all-hids))
>>              (apply remove-hid blank-leaf-hids)
tree-2          (hid->tree root-hid)

yielding tree-2 which looks much neater:

(is= tree-2
  {:attrs {:tag :ROOT},
   :kids  [{:attrs {:tag :Items},
            :kids  [{:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "A"}
                             {:attrs {:tag :Note}, :value "AA1"}]}
                    {:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "B"}
                             {:attrs {:tag :Note}, :value "BB1"}]}
                    {:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "C"}
                             {:attrs {:tag :Note}, :value "CC1"}]}
                    {:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "A"}
                             {:attrs {:tag :Note}, :value "AA2"}]}]}]})

The final code fragment removes Type="B" or Type="C" nodes:

type-bc-hid?    (fn [hid] (pos? (count (glue
                            (find-leaf-hids hid [:** :Type] "B")
                            (find-leaf-hids hid [:** :Type] "C")))))

type-bc-hids    (find-hids-with root-hid [:** :Item] type-bc-hid?)
>>              (apply remove-hid type-bc-hids)
tree-3          (hid->tree root-hid)
tree-3-hiccup   (hid->hiccup root-hid) ]

yielding the final result tree shown in both tree format and hiccup format:

(is= tree-3
  {:attrs {:tag :ROOT},
   :kids
          [{:attrs {:tag :Items},
            :kids  [{:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "A"}
                             {:attrs {:tag :Note}, :value "AA1"}]}
                    {:attrs {:tag :Item},
                     :kids  [{:attrs {:tag :Type}, :value "A"}
                             {:attrs {:tag :Note}, :value "AA2"}]}]}]})
(is= tree-3-hiccup
  [:ROOT
   [:Items
    [:Item [:Type "A"] [:Note "AA1"]]
    [:Item [:Type "A"] [:Note "AA2"]]]]))))

The full example can be found in the forest-examples unit test.

Update

Here is the most compact version with extra features removed:

(dotest
  (with-forest (new-forest)
    (let [xml-str         "<ROOT>
                            <Items>
                              <Item><Type>A</Type><Note>AA1</Note></Item>
                              <Item><Type>B</Type><Note>BB1</Note></Item>
                              <Item><Type>C</Type><Note>CC1</Note></Item>
                              <Item><Type>A</Type><Note>AA2</Note></Item>
                            </Items>
                          </ROOT>"
          enlive-tree     (->> xml-str
                            java.io.StringReader.
                            en-html/xml-resource
                            first)
          root-hid        (add-tree-enlive enlive-tree)
          blank-leaf-hid? (fn [hid] (ts/whitespace? (hid->value hid)))
          has-bc-leaf?    (fn [hid] (or (has-child-leaf? hid [:** :Type] "B")
                                        (has-child-leaf? hid [:** :Type] "C")))
          blank-leaf-hids (keep-if blank-leaf-hid? (all-leaf-hids))
          >>              (apply remove-hid blank-leaf-hids)
          bc-item-hids    (find-hids-with root-hid [:** :Item] has-bc-leaf?)]
      (apply remove-hid bc-item-hids)
      (is= (hid->hiccup root-hid)
        [:ROOT
         [:Items
          [:Item [:Type "A"] [:Note "AA1"]]
          [:Item [:Type "A"] [:Note "AA2"]]]]))))


来源: stackexchange

问:
iis7 web config file not working error hosting
I have been trying hard to fix the issue in the web.config which doesn't allow me to host my site in the iis 8.5 - windows 2012 r2, throws this error which i have attached a screen shot.

I have no clue of what is going wrong here.

If some one could just shed some light, much appreciated.

答:
Error message is pretty clear. Handler section is locked at parent or grand parent level. When section is locked at parent level you can not override it in child configuration.
Please check following web.config files at following locations.

Check if you have web.config file at location C:\intetpub\wwwroot. If its present check if you have following tag in web.config

```<code><section name="handlers" overrideModeDefault="Deny" />
</code>```

If its there then change it to

```<code><section name="handlers" overrideModeDefault="Allow" />
</code>```

If you don't find web.config in #1 above then open applicationHost.config located at path C:\Windows\System32\inetsrv\config
Check if you have handler section with overrideModeDefault="Deny" and if it is then change it to overrideModeDefault="Allow" as shown in #1.
Once you change it overrideModeDefault="Allow" then you can override it in child web.config

ContentLicense: CC BY-SA 3.0

Body:
Error message is pretty clear. Handler section is locked at parent or grand parent level. When section is locked at parent level you can not override it in child configuration.
Please check following web.config files at following locations.

Check if you have web.config file at location C:\intetpub\wwwroot. If its present check if you have following tag in web.config

<section name="handlers" overrideModeDefault="Deny" />

If its there then change it to

<section name="handlers" overrideModeDefault="Allow" />

If you don't find web.config in #1 above then open applicationHost.config located at path C:\Windows\System32\inetsrv\config
Check if you have handler section with overrideModeDefault="Deny" and if it is then change it to overrideModeDefault="Allow" as shown in #1.
Once you change it overrideModeDefault="Allow" then you can override it in child web.config


问:
syntax error in python while checking for greater than symbol
I am getting syntax error in the below piece of code in python. Can someone please help me to know where I did the mistake. I am new to python.

```<code>X = lambda cus['id'],cus['maxamt']: \
       df1_test.TXNID[(df1_test['CUSTOMERID'] == cus['id'])\
      &(df1_test['CREDITAMT'] > cus['maxamt'])]
</code>```

Thanks for your responses. Here I have a small array with all distinct values of of CUSTOMERID (1st column) and crresponding maximum CREDITAMT (2nd column). df1_test is a bigger dataframe with many columns in it.

I am trying to find the all the records of the df1_test dataset where the CREDITAMT of the customer is greater that the maximum value of the particular customer (The maximum credit amount and distinct customer id I can get from the smaller array)

Here is what I have tried. But it gives me error that " too many indices for array".

I did not want to use a for loop for the problem as the data is huge.

Can someone please help me.

My actual piece of code is:

```<code>X = sorted(cus_np,key=lambda x: \
         df1_test.TXNID[(df1_test['CUSTOMERID']==x[:,0])\
       &(df1_test['CREDITAMT'] > x[:,1])])
</code>```

Thanks for the respose. Please see the example of my data:

```<code>import pandas as pd

small_distinct_array=pd.DataFrame({'id':[1,2,3,4],'max':[200,500,800,400]})

bigger_all_array=pd.DataFrame({'custid':[1,3,4,3,1,1,2,2,3,4],'amt':[300,400,800,300,900,700,500,700,400,500]})
</code>```

I am trying to get the 'custid' values of the bigger_all_array where the corresponding 'amt' value is greater than the max field of small_distinct_array of the same customerid.

答: You cannot have column accesses in parameter names. cus['id'] and cus['maxamt'] are illegal. Just pass cus alone. Most likely you have more problems with this cumbersome piece of code, but at lest you'll get rid of the syntax error.

Body:
I am getting syntax error in the below piece of code in python. Can someone please help me to know where I did the mistake. I am new to python.

X = lambda cus['id'],cus['maxamt']: \
       df1_test.TXNID[(df1_test['CUSTOMERID'] == cus['id'])\
      &(df1_test['CREDITAMT'] > cus['maxamt'])]

Thanks for your responses. Here I have a small array with all distinct values of of CUSTOMERID (1st column) and crresponding maximum CREDITAMT (2nd column). df1_test is a bigger dataframe with many columns in it.

I am trying to find the all the records of the df1_test dataset where the CREDITAMT of the customer is greater that the maximum value of the particular customer (The maximum credit amount and distinct customer id I can get from the smaller array)

Here is what I have tried. But it gives me error that " too many indices for array".

I did not want to use a for loop for the problem as the data is huge.

Can someone please help me.

My actual piece of code is:

X = sorted(cus_np,key=lambda x: \
         df1_test.TXNID[(df1_test['CUSTOMERID']==x[:,0])\
       &(df1_test['CREDITAMT'] > x[:,1])])

Thanks for the respose. Please see the example of my data:

import pandas as pd

small_distinct_array=pd.DataFrame({'id':[1,2,3,4],'max':[200,500,800,400]})

bigger_all_array=pd.DataFrame({'custid':[1,3,4,3,1,1,2,2,3,4],'amt':[300,400,800,300,900,700,500,700,400,500]})

I am trying to get the 'custid' values of the bigger_all_array where the corresponding 'amt' value is greater than the max field of small_distinct_array of the same customerid.


问:
Differences between pattern matching and unification?
I thought I understand how pattern matching like found in Scala and Haskell is different from unification found in Prolog but my misunderstands of Prolog is great.  What is some simple problems solvable by one that cannot be solved by the other?
Thank you</p>

答:
The following in Scala would fail to compile, as it's first case branch attempts to declare the variable x twice.

```<code>(1, 1) match{
   case (x, x) => println("equals")
   case _      => println("not equals")
}
</code>```

If Scala used unification instead of pattern matching this would succeed and print "equals" while

```<code>(1, 2) match{
   case (x, x) => println("equals")
   case _      => println("not equals")
}
</code>```

would print "not equals".  This is because the unification would fail when attempting to bind the variable x to both 1 and 2.

ContentLicense: CC BY-SA 2.5

Body:
The following in Scala would fail to compile, as it's first case branch attempts to declare the variable x twice.

(1, 1) match{
   case (x, x) => println("equals")
   case _      => println("not equals")
}

If Scala used unification instead of pattern matching this would succeed and print "equals" while

(1, 2) match{
   case (x, x) => println("equals")
   case _      => println("not equals")
}

would print "not equals".  This is because the unification would fail when attempting to bind the variable x to both 1 and 2.


问:
$.inArray deep search
I have a json file like this:

```<code>{
    items:
        [{  id: 1,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        },
        {   id: 2,
            catalog: {
                supplier: {
                    priority: 3
                },
            }
        },
        {   id: 3,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        }]
</code>```

Now I want to use the $.inArray function to make a deep search of the items array.
For example all items whose catalog/supplier/priority is 1.

Something like this:

```<code>$.inArray(1, data.items(.catalog.supplier.priority)) > -1
</code>```

How do I accomplish this kind of deep search?

答:
You might use $.grep as well:

var data = {
    items:
        [{  id: 1,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        },
        {   id: 2,
            catalog: {
                supplier: {
                    priority: 3
                },
            }
        },
        {   id: 3,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        }]
 };

 var arr = jQuery.grep(data.items, function( a ) {
  return a.catalog.supplier.priority >1;
});

console.log(arr);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: $.inArray deep search

Body:
I have a json file like this:

{
    items:
        [{  id: 1,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        },
        {   id: 2,
            catalog: {
                supplier: {
                    priority: 3
                },
            }
        },
        {   id: 3,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        }]

Now I want to use the $.inArray function to make a deep search of the items array.
For example all items whose catalog/supplier/priority is 1.

Something like this:

$.inArray(1, data.items(.catalog.supplier.priority)) > -1

How do I accomplish this kind of deep search?

Body:
You might use $.grep as well:

var data = {
    items:
        [{  id: 1,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        },
        {   id: 2,
            catalog: {
                supplier: {
                    priority: 3
                },
            }
        },
        {   id: 3,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        }]
 };

 var arr = jQuery.grep(data.items, function( a ) {
  return a.catalog.supplier.priority >1;
});

console.log(arr);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
PFQuery in TableCell Cause Images to Jump
So I have researched and haven't found anything similar to my situation. All relevant code will be posted below. I am using parse for my backend and am trying to create a feed with people posted images. The images and username load fine, but since the display name and profile picture are in a separate file i had to query them separately. The query for those is located in the table cell itself. This causes images to jump while scrolling. I am aware that is because of the way cells dequeue. Is there a better way to either query or relate the data from both parse queries?

```<code>var usernameArray = [String]()
var detailArray = [String]()
var uuidArray = [String]()
var postArray = [PFFile]()
var followArray = [String]()
var page: Int = 10
var image: UIImage!
var follow = PFObject(className: "Follow")

func loadFollowers(){
    let followerQuery = PFQuery(className: "Follow")
    followerQuery.whereKey("follower", equalTo: (PFUser.current()?.username!)! as String)
    followerQuery.whereKey("blocker", notEqualTo: (PFUser.current()?.username!)! as String)
    followerQuery.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
        if error == nil{
            self.followArray.removeAll(keepingCapacity: false)
            for object in objects!{
                self.followArray.append(object.object(forKey: "following") as! String)
                self.followArray.insert((PFUser.current()?.username!)! as String, at: 0)
            }
            let dataQuery = PFQuery(className: "Posts")
            dataQuery.whereKey("user", containedIn: self.followArray)
            dataQuery.limit = self.page
            dataQuery.addDescendingOrder("_created_at")
            dataQuery.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
                if error == nil{
                    self.usernameArray.removeAll(keepingCapacity: false)
                    self.detailArray.removeAll(keepingCapacity: false)
                    self.postArray.removeAll(keepingCapacity: false)
                    self.uuidArray.removeAll(keepingCapacity: false)
                    for object in objects!{
                        self.usernameArray.append(object.object(forKey: "user") as! String)
                        self.detailArray.append(object.object(forKey: "title") as! String)
                        self.postArray.append(object.object(forKey: "picture") as! PFFile)
                        self.uuidArray.append(object.object(forKey: "uuid") as! String)
                        self.tableView.reloadData()
                    }
                }
            })
        }
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postView") as! FeedTableViewCell

cell.userName.text = usernameArray[indexPath.row]
cell.details.text = detailArray[indexPath.row]
cell.uuid.text = uuidArray[indexPath.row]

let query = PFUser.query()
query?.whereKey("username", equalTo:cell.userName.text!)
query?.findObjectsInBackground(){(objects: [PFObject]?, error: Error?) -> Void in
    if !(error != nil){
        for object in (objects as [PFObject]?)!{
            cell.displayName.text = object.object(forKey: "display") as? String
            if let userPicture = object.object(forKey: "avi") as? PFFile {
                userPicture.getDataInBackground(block: { (imageData: Data?, error: Error?) in
                    if (error == nil) {
                        let image = UIImage(data:imageData!)
                        cell.avi.image = image
                    }
                })
            }
        }
    }
}

aviArray[indexPath.row].getDataInBackground { (data: Data?, error: Error?) in
    if error == nil{
        cell.avi.image = UIImage(data: data!)
    }
}

postArray[indexPath.row].getDataInBackground { (data: Data?, error: Error?) in
    if error == nil{
        cell.post.image = UIImage(data: data!)
    }
}
return cell
}
</code>```

Thank you in advance for the help. I am open to all suggestions because I am at a loss for this. Im not an expert so there is probably a much better way to do this.

答:
Get the actual URL of the image, and set the images with SDWebImage.
No need to reinvent the wheel anymore. It will solve this problem and reduce the complexity of your code.</p>

Body:
So I have researched and haven't found anything similar to my situation. All relevant code will be posted below. I am using parse for my backend and am trying to create a feed with people posted images. The images and username load fine, but since the display name and profile picture are in a separate file i had to query them separately. The query for those is located in the table cell itself. This causes images to jump while scrolling. I am aware that is because of the way cells dequeue. Is there a better way to either query or relate the data from both parse queries?

var usernameArray = [String]()
var detailArray = [String]()
var uuidArray = [String]()
var postArray = [PFFile]()
var followArray = [String]()
var page: Int = 10
var image: UIImage!
var follow = PFObject(className: "Follow")

func loadFollowers(){
    let followerQuery = PFQuery(className: "Follow")
    followerQuery.whereKey("follower", equalTo: (PFUser.current()?.username!)! as String)
    followerQuery.whereKey("blocker", notEqualTo: (PFUser.current()?.username!)! as String)
    followerQuery.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
        if error == nil{
            self.followArray.removeAll(keepingCapacity: false)
            for object in objects!{
                self.followArray.append(object.object(forKey: "following") as! String)
                self.followArray.insert((PFUser.current()?.username!)! as String, at: 0)
            }
            let dataQuery = PFQuery(className: "Posts")
            dataQuery.whereKey("user", containedIn: self.followArray)
            dataQuery.limit = self.page
            dataQuery.addDescendingOrder("_created_at")
            dataQuery.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
                if error == nil{
                    self.usernameArray.removeAll(keepingCapacity: false)
                    self.detailArray.removeAll(keepingCapacity: false)
                    self.postArray.removeAll(keepingCapacity: false)
                    self.uuidArray.removeAll(keepingCapacity: false)
                    for object in objects!{
                        self.usernameArray.append(object.object(forKey: "user") as! String)
                        self.detailArray.append(object.object(forKey: "title") as! String)
                        self.postArray.append(object.object(forKey: "picture") as! PFFile)
                        self.uuidArray.append(object.object(forKey: "uuid") as! String)
                        self.tableView.reloadData()
                    }
                }
            })
        }
    }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postView") as! FeedTableViewCell

cell.userName.text = usernameArray[indexPath.row]
cell.details.text = detailArray[indexPath.row]
cell.uuid.text = uuidArray[indexPath.row]

let query = PFUser.query()
query?.whereKey("username", equalTo:cell.userName.text!)
query?.findObjectsInBackground(){(objects: [PFObject]?, error: Error?) -> Void in
    if !(error != nil){
        for object in (objects as [PFObject]?)!{
            cell.displayName.text = object.object(forKey: "display") as? String
            if let userPicture = object.object(forKey: "avi") as? PFFile {
                userPicture.getDataInBackground(block: { (imageData: Data?, error: Error?) in
                    if (error == nil) {
                        let image = UIImage(data:imageData!)
                        cell.avi.image = image
                    }
                })
            }
        }
    }
}

aviArray[indexPath.row].getDataInBackground { (data: Data?, error: Error?) in
    if error == nil{
        cell.avi.image = UIImage(data: data!)
    }
}

postArray[indexPath.row].getDataInBackground { (data: Data?, error: Error?) in
    if error == nil{
        cell.post.image = UIImage(data: data!)
    }
}
return cell
}

Thank you in advance for the help. I am open to all suggestions because I am at a loss for this. Im not an expert so there is probably a much better way to do this.


问:
Can't get sockets to work in ASP.NET Core
I'm trying to use sockets to send/receive data in ASP.NET Core. I followed a few tutorial I found but I can't seem to get any working. No matter what I try in my website, the socket connector stays in the "Connecting/Opening" state.

These are the tutorials I tried:

http://zbrad.github.io/tools/wscore/ -> this is the one I currently used in my code below

https://radu-matei.github.io/blog/aspnet-core-websockets-middleware/

http://dotnetthoughts.net/using-websockets-in-aspnet-core/

My startup.cs file looks like this:

```<code>using System;
using System.Text;
using arnvanhoutte.Data;
using arnvanhoutte.Models;
using arnvanhoutte.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace arnvanhoutte
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            Console.WriteLine(env.EnvironmentName);
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true);

            Console.WriteLine(Configuration.GetConnectionString("DefaultConnection"));
            if (env.IsDevelopment())
            {
                builder.AddUserSecrets("aspnet-arnvanhoutte-8942961e-3f9b-48f6-a54d-907858e0ad3a");
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        private IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_ => Configuration);

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            services.Configure<IdentityOptions>(opt =>
            {
                opt.Cookies.ApplicationCookie.LoginPath = new PathString("/Admin/User/Login");
            });

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
            services.AddTransient<Seed>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, Seed seeder)
        {

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();

            seeder.SeedRoles().ConfigureAwait(false);
            seeder.SeedAdminUser().ConfigureAwait(false);
            seeder.SeedTestUser().ConfigureAwait(false);

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.Map("/ws", SocketHandler.Map);

          if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            if (env.IsDevelopment())
            {
                app.Use(async (context, next) =>
                {
                    var request = context.Request;
                    if (request.IsHttps)
                    {
                        await next();
                    }
                    else
                    {
                        var devPort = Configuration.GetValue<int>("iisSettings:iisExpress:sslPort");

                        var host = new HostString(request.Host.Host, devPort);

                        string newUrl = $"https://{host}{request.PathBase}{request.Path}{request.QueryString}";
                        context.Response.Redirect(newUrl, true);
                    }
                });
            }

            app.UseIdentity();

            // secretKey contains a secret passphrase only your server knows
            var secretKey = Configuration.GetSection("AppSettings")["SecretKey"];
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

            var options = new TokenProviderOptions
            {
                Path = "/token",
                Audience = "User",
                Issuer = "arnvanhoutte",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                IdentityResolver = (username, password) =>
                {
                    using (
                        var serviceScope =
                            app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
                    {
                        var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();

                        var user = userManager.FindByNameAsync(username).Result;

                        if (user != null && userManager.CheckPasswordAsync(user, password).Result)
                        {
                            return user;
                        }

                        // Credentials are invalid, or account doesn't exist
                        return null;
                    }
                }
            };

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = "arnvanhoutte",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = "User",

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = tokenValidationParameters
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                AuthenticationScheme = "Cookie",
                LoginPath = new PathString("/login"),
                AccessDeniedPath = new PathString("/login"),
                ReturnUrlParameter = "redirect",
                CookieName = "access_token",
                TicketDataFormat = new CustomJwtDataFormat(
                    SecurityAlgorithms.HmacSha256,
                    tokenValidationParameters)
            });

            app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options));

            app.UseMvc(routes =>
            {
                routes.MapRoute("myProjects",
                    "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    "default",
                    "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
</code>```

This is the sockethandler.cs file:

```<code>using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace arnvanhoutte.Services
{
    public class SocketHandler
    {
        public const int BufferSize = 4096;

        private readonly WebSocket _socket;

        private SocketHandler(WebSocket socket)
        {
            _socket = socket;
        }

        private async Task EchoLoop()
        {
            var buffer = new byte[BufferSize];
            var seg = new ArraySegment<byte>(buffer);

            while (_socket.State == WebSocketState.Open)
            {
                var incoming = await _socket.ReceiveAsync(seg, CancellationToken.None);
                var outgoing = new ArraySegment<byte>(buffer, 0, incoming.Count);
                await _socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }

        private static async Task Acceptor(HttpContext hc, Func<Task> n)
        {
            if (!hc.WebSockets.IsWebSocketRequest)
                return;

            var socket = await hc.WebSockets.AcceptWebSocketAsync();
            var h = new SocketHandler(socket);
            await h.EchoLoop();
        }
        public static void Map(IApplicationBuilder app)
        {
            app.UseWebSockets();
            app.Use(Acceptor);
        }
    }
}
</code>```

And this is the html file I serve:

```<code>@{
    Layout = null;
}
<div id="output"></div>

<script language="javascript" type="text/javascript">

    var socket;
    var uri = "ws://" + window.location.host + "/ws";
    var output;
    var text = "test echo";

    function write(s) {
        var p = document.createElement("p");
        p.innerHTML = s;
        output.appendChild(p);
    }

    function doConnect() {
        socket = new WebSocket(uri);
        socket.onopen = function (e) { write("opened " + uri); doSend(); };
        socket.onclose = function (e) { write("closed"); };
        socket.onmessage = function (e) { write("Received: " + e.data); socket.close(); };
        socket.onerror = function (e) { write("Error: " + e.data); };
    }

    function doSend() {
        write("Sending: " + text);
        socket.send(text);
    }

    function onInit() {
        output = document.getElementById("output");
        doConnect();
    }

    window.onload = onInit;

</script>
</code>```

When I run this and navigate to the file, nothing initially appears. After a while do I get this error in the console: sockettest:17 WebSocket connection to 'ws://localhost:44399/ws' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

答:
You aren't calling the Map function of the SocketHandler class in your Configure function of the Startup class.

Add this in the Configurefunction:

```<code>SocketHandler.Map(app);
</code>```

Body:
I'm trying to use sockets to send/receive data in ASP.NET Core. I followed a few tutorial I found but I can't seem to get any working. No matter what I try in my website, the socket connector stays in the "Connecting/Opening" state.

These are the tutorials I tried:

http://zbrad.github.io/tools/wscore/ -> this is the one I currently used in my code below

https://radu-matei.github.io/blog/aspnet-core-websockets-middleware/

http://dotnetthoughts.net/using-websockets-in-aspnet-core/

My startup.cs file looks like this:

using System;
using System.Text;
using arnvanhoutte.Data;
using arnvanhoutte.Models;
using arnvanhoutte.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace arnvanhoutte
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            Console.WriteLine(env.EnvironmentName);
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", true, true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true);

            Console.WriteLine(Configuration.GetConnectionString("DefaultConnection"));
            if (env.IsDevelopment())
            {
                builder.AddUserSecrets("aspnet-arnvanhoutte-8942961e-3f9b-48f6-a54d-907858e0ad3a");
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        private IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_ => Configuration);

            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();

            services.Configure<IdentityOptions>(opt =>
            {
                opt.Cookies.ApplicationCookie.LoginPath = new PathString("/Admin/User/Login");
            });

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
            services.AddTransient<Seed>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, Seed seeder)
        {

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            loggerFactory.AddAzureWebAppDiagnostics();

            seeder.SeedRoles().ConfigureAwait(false);
            seeder.SeedAdminUser().ConfigureAwait(false);
            seeder.SeedTestUser().ConfigureAwait(false);

            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.Map("/ws", SocketHandler.Map);

          if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            if (env.IsDevelopment())
            {
                app.Use(async (context, next) =>
                {
                    var request = context.Request;
                    if (request.IsHttps)
                    {
                        await next();
                    }
                    else
                    {
                        var devPort = Configuration.GetValue<int>("iisSettings:iisExpress:sslPort");

                        var host = new HostString(request.Host.Host, devPort);

                        string newUrl = $"https://{host}{request.PathBase}{request.Path}{request.QueryString}";
                        context.Response.Redirect(newUrl, true);
                    }
                });
            }

            app.UseIdentity();

            // secretKey contains a secret passphrase only your server knows
            var secretKey = Configuration.GetSection("AppSettings")["SecretKey"];
            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));

            var options = new TokenProviderOptions
            {
                Path = "/token",
                Audience = "User",
                Issuer = "arnvanhoutte",
                SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
                IdentityResolver = (username, password) =>
                {
                    using (
                        var serviceScope =
                            app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
                    {
                        var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();

                        var user = userManager.FindByNameAsync(username).Result;

                        if (user != null && userManager.CheckPasswordAsync(user, password).Result)
                        {
                            return user;
                        }

                        // Credentials are invalid, or account doesn't exist
                        return null;
                    }
                }
            };

            var tokenValidationParameters = new TokenValidationParameters
            {
                // The signing key must match!
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                // Validate the JWT Issuer (iss) claim
                ValidateIssuer = true,
                ValidIssuer = "arnvanhoutte",

                // Validate the JWT Audience (aud) claim
                ValidateAudience = true,
                ValidAudience = "User",

                // Validate the token expiry
                ValidateLifetime = true,

                // If you want to allow a certain amount of clock drift, set that here:
                ClockSkew = TimeSpan.Zero
            };

            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                TokenValidationParameters = tokenValidationParameters
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                AuthenticationScheme = "Cookie",
                LoginPath = new PathString("/login"),
                AccessDeniedPath = new PathString("/login"),
                ReturnUrlParameter = "redirect",
                CookieName = "access_token",
                TicketDataFormat = new CustomJwtDataFormat(
                    SecurityAlgorithms.HmacSha256,
                    tokenValidationParameters)
            });

            app.UseMiddleware<TokenProviderMiddleware>(Options.Create(options));

            app.UseMvc(routes =>
            {
                routes.MapRoute("myProjects",
                    "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    "default",
                    "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

This is the sockethandler.cs file:

using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace arnvanhoutte.Services
{
    public class SocketHandler
    {
        public const int BufferSize = 4096;

        private readonly WebSocket _socket;

        private SocketHandler(WebSocket socket)
        {
            _socket = socket;
        }

        private async Task EchoLoop()
        {
            var buffer = new byte[BufferSize];
            var seg = new ArraySegment<byte>(buffer);

            while (_socket.State == WebSocketState.Open)
            {
                var incoming = await _socket.ReceiveAsync(seg, CancellationToken.None);
                var outgoing = new ArraySegment<byte>(buffer, 0, incoming.Count);
                await _socket.SendAsync(outgoing, WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }

        private static async Task Acceptor(HttpContext hc, Func<Task> n)
        {
            if (!hc.WebSockets.IsWebSocketRequest)
                return;

            var socket = await hc.WebSockets.AcceptWebSocketAsync();
            var h = new SocketHandler(socket);
            await h.EchoLoop();
        }
        public static void Map(IApplicationBuilder app)
        {
            app.UseWebSockets();
            app.Use(Acceptor);
        }
    }
}

And this is the html file I serve:

@{
    Layout = null;
}

When I run this and navigate to the file, nothing initially appears. After a while do I get this error in the console: sockettest:17 WebSocket connection to 'ws://localhost:44399/ws' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET

Body:
You aren't calling the Map function of the SocketHandler class in your Configure function of the Startup class.

Add this in the Configurefunction:

SocketHandler.Map(app);


问:
ASP.NET WebForms - Issues disabling list item
I am running (ASP.NET Web Forms) VB.Net code and in the aspx page, i have something like this:

```<code><ul id="tabsdefault" class="tab-menu">
        <li id="accessingIndividuals" runat="server"><a>Accessing Individuals</a></li>
</ul>
</code>```

and in the code behind file, i have this code:

```<code>accessingIndividuals.Disabled = true
</code>```

However, before upgrading to .NET 4.6, this code worked and now after the upgrade, it does not disable the list item.

I have also manually changed the aspx page item with this:

```<code><ul id="tabsdefault" class="tab-menu">
        <li id="accessingIndividuals" runat="server" disabled="disabled"><a>Accessing Individuals</a></li>
</ul>
</code>```

but that did not work and nor did the following:

```<code><ul id="tabsdefault" class="tab-menu">
        <li id="accessingIndividuals" runat="server" disabled="true"><a>Accessing Individuals</a></li>
</ul>
</code>```

Any idea what has changed in .NET Framework or how can disable this item?

Looking at the page source using Developer Tools, the output is like this:

```<code>    <ul id="tabsdefault" class="tab-menu">
        <li id="accessingIndividuals" enabled="false" disabled="disabled" class="selected"><a>Accessing Individuals</a></li>
</ul>
</code>```

答:
Looks like all new Browsers ignore the disable attribute on a list item. One possible solution is:</p>

```<code>    li[disabled]
    {
      pointer-events: none;
      opacity: 0.6;
    }
</code>```

Body:
I am running (ASP.NET Web Forms) VB.Net code and in the aspx page, i have something like this:

Accessing Individuals

and in the code behind file, i have this code:

accessingIndividuals.Disabled = true

However, before upgrading to .NET 4.6, this code worked and now after the upgrade, it does not disable the list item.

I have also manually changed the aspx page item with this:

Accessing Individuals

but that did not work and nor did the following:

Accessing Individuals

Any idea what has changed in .NET Framework or how can disable this item?

Looking at the page source using Developer Tools, the output is like this:

Accessing Individuals

Body:
Looks like all new Browsers ignore the disable attribute on a list item. One possible solution is:

    li[disabled]
    {
      pointer-events: none;
      opacity: 0.6;
    }


问:
why no whole width of screen is covered?
I use css and JavaScript to lock screen, but I am not sure why the lock panel is not the same width as screen, do you have any idea?
Here is HTML source and you find javascript code as below, does anyone help me?

JavaScript:

```<code>function FreezeScreen(msg) {
    scroll(0,0);
    var outerPane = document.getElementById('FreezePane');
    var innerPane = document.getElementById('InnerFreezePane');
    if (outerPane) outerPane.className = 'FreezePaneOn';
    if (innerPane) innerPane.innerHTML = msg;
}
</code>```

HTML:

```<code><body>
<div align="center" id="FreezePane" class="FreezePaneOff">
   <div id="InnerFreezePane" class="InnerFreezePane"> </div>
</div>
</code>```

CSS:

```<code>.FreezePaneOff {
  visibility: hidden;
  display: none;
  position: absolute;
  top: -100px;
  left: -100px;
}

.FreezePaneOn {
  position: absolute;
  top: 0px;
  left: 0px;
  visibility: visible;
  display: block;
  width: 100%;
  height: 100%;
  background-color: #666;
  z-index: 999;
  filter:alpha(opacity=85);
  -moz-opacity:0.85;
  padding-top: 20%;
}

.InnerFreezePane {
  text-align: center;
  width: 66%;
  background-color: #171;
  color: White;
  font-size: large;
  border: dashed 2px #111;
  padding: 9px;
}
</code>```

答:
I solved my quetion by two ways, Method2 is not good because fixed width, but I am not sure why Method1 is ok, does anyone explain to me?

Method1:

```<code>.FreezePaneOn {
  ...
  width: 103%;
  height: 100%;
  ...
}
</code>```

Method2:

```<code>.FreezePaneOn {
  ...
  width: 990px;
  height: 100%;
  ...
}
</code>```

Body:
I use css and JavaScript to lock screen, but I am not sure why the lock panel is not the same width as screen, do you have any idea?
Here is HTML source and you find javascript code as below, does anyone help me?

JavaScript:

function FreezeScreen(msg) {
    scroll(0,0);
    var outerPane = document.getElementById('FreezePane');
    var innerPane = document.getElementById('InnerFreezePane');
    if (outerPane) outerPane.className = 'FreezePaneOn';
    if (innerPane) innerPane.innerHTML = msg;
}

HTML:

CSS:

.FreezePaneOff {
  visibility: hidden;
  display: none;
  position: absolute;
  top: -100px;
  left: -100px;
}

.FreezePaneOn {
  position: absolute;
  top: 0px;
  left: 0px;
  visibility: visible;
  display: block;
  width: 100%;
  height: 100%;
  background-color: #666;
  z-index: 999;
  filter:alpha(opacity=85);
  -moz-opacity:0.85;
  padding-top: 20%;
}

.InnerFreezePane {
  text-align: center;
  width: 66%;
  background-color: #171;
  color: White;
  font-size: large;
  border: dashed 2px #111;
  padding: 9px;
}

Body:
I solved my quetion by two ways, Method2 is not good because fixed width, but I am not sure why Method1 is ok, does anyone explain to me?

Method1:

.FreezePaneOn {
  ...
  width: 103%;
  height: 100%;
  ...
}

Method2:

.FreezePaneOn {
  ...
  width: 990px;
  height: 100%;
  ...
}


问:
Python subprocess.call not waiting for process to finish blender
I have a python script in blender where it has

subprocess.call(os.path.abspath('D:/Test/run-my-script.sh'),shell=True)

followed by many other code which depends on this shell script to finish. What happens is that it doesn't wait for it to finish, I don't know why? I even tried using Popen   instead of call as shown:

```<code>p1 = subprocess.Popen(os.path.abspath('D:/Test/run-my-script.sh'),shell=True)
p1.wait()
</code>```

and I tried using commuincate but it still didn't work:

```<code>p1 = subprocess.Popen(os.path.abspath('D:/Test/run-my-script.sh'),shell=True).communicate()
</code>```

this shell script works great on MacOS (after changing paths) and waits when using subprocess.call(['sh', '/userA/Test/run-my-script.sh'])

but on Windows this is what happens, I run the below python script in Blender then once it gets to the subprocess line Git bash is opened and runs the shell script while blender doesn't wait for it to finish it just prints Hello in its console without waiting for the Git Bash to finish. Any help?

```<code>import bpy
import subprocess
subprocess.call(os.path.abspath('D:/Test/run-my-script.sh'),shell=True)
print('Hello')
</code>```

答:
You can use subprocess.call to do exactly that.

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)

Run the command described by args. Wait for command to complete, then return the returncode attribute.

Edit: I think I have a hunch on what's going on. The command works on your Mac because Macs, I believe, support Bash out of the box (at least something functionally equivalent) while on Windows it sees your attempt to run a ".sh" file and instead fires up Git Bash which I presume performs a couple forks when starting.

Because of this Python thinks that your script is done, the PID is gone.

If I were you I would do this:

Generate a unique, non-existing, absolute path in your "launching" script using the tempfile module.

When launching the script, pass the path you just made as an argument.

When the script starts, have it create a file at the path. When done, delete the file.

The launching script should watch for the creation and deletion of that file to indicate the status of the script.

Hopefully that makes sense.

Body:
I have a python script in blender where it has

subprocess.call(os.path.abspath('D:/Test/run-my-script.sh'),shell=True)

followed by many other code which depends on this shell script to finish. What happens is that it doesn't wait for it to finish, I don't know why? I even tried using Popen   instead of call as shown:

p1 = subprocess.Popen(os.path.abspath('D:/Test/run-my-script.sh'),shell=True)
p1.wait()

and I tried using commuincate but it still didn't work:

p1 = subprocess.Popen(os.path.abspath('D:/Test/run-my-script.sh'),shell=True).communicate()

this shell script works great on MacOS (after changing paths) and waits when using subprocess.call(['sh', '/userA/Test/run-my-script.sh'])

but on Windows this is what happens, I run the below python script in Blender then once it gets to the subprocess line Git bash is opened and runs the shell script while blender doesn't wait for it to finish it just prints Hello in its console without waiting for the Git Bash to finish. Any help?

import bpy
import subprocess
subprocess.call(os.path.abspath('D:/Test/run-my-script.sh'),shell=True)
print('Hello')


问:
Google Analytics - Setting Custom Variable Failed!
i am attempting to set a custom variable on a contact form that tracks when a form submission is success.  However, in my google analytics page the custom variable isn't showing up in Visitor -> Custom Variable.  I understand it takes a few hours for it to refresh but it has been a week.  So, my basic assumption is that it didn't work.  I am using async _gaq.push() to achieve this.  Basically, i set custom variable after my ajax function call to submitting the contact form and within the callback function if success i set the following:

```<code>_gaq.push(['_setCustomVar', 1, 'contact', 'success', 3]);
</code>```

This is my google analytic code in the head.

```<code>var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxx-x']); //my google analytic api key
_gaq.push(['_trackPageview']);
(function() {
     var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
     ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 })();
</code>```

Actually a better question is, does a _gaq.push(['_trackPageview']); need to be called after a _gaq.push(['_setCustomVar', 1, 'contact', 'success', 3]); for it to "register" the _setCustomVar call, and is it ok for me to call _gaq.push(['_trackPageview']); more than once after DOM is loaded via javascript (weather it be off an event or callback ajax function).  Thanks guys.

答:
Have you tried simply _setVar?  We are still using an old method of tracking, but this is the code we use:

```<code>try {
var pageTracker = _gat._getTracker("UA-xxxxxxx-x");
pageTracker._setVar('custom value goes here');
pageTracker._trackPageview();
} catch(err) {}
</code>```

Body:
i am attempting to set a custom variable on a contact form that tracks when a form submission is success.  However, in my google analytics page the custom variable isn't showing up in Visitor -> Custom Variable.  I understand it takes a few hours for it to refresh but it has been a week.  So, my basic assumption is that it didn't work.  I am using async _gaq.push() to achieve this.  Basically, i set custom variable after my ajax function call to submitting the contact form and within the callback function if success i set the following:

_gaq.push(['_setCustomVar', 1, 'contact', 'success', 3]);

This is my google analytic code in the head.

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxx-x']); //my google analytic api key
_gaq.push(['_trackPageview']);
(function() {
     var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
     ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 })();

Actually a better question is, does a _gaq.push(['_trackPageview']); need to be called after a _gaq.push(['_setCustomVar', 1, 'contact', 'success', 3]); for it to "register" the _setCustomVar call, and is it ok for me to call _gaq.push(['_trackPageview']); more than once after DOM is loaded via javascript (weather it be off an event or callback ajax function).  Thanks guys.

Body:
Have you tried simply _setVar?  We are still using an old method of tracking, but this is the code we use:

try {
var pageTracker = _gat._getTracker("UA-xxxxxxx-x");
pageTracker._setVar('custom value goes here');
pageTracker._trackPageview();
} catch(err) {}


问:
uncaught TypeError: (t.data || "").search is not a function
I am new to angular, I am trying to display alert when I click each li, but I am getting an error

uncaught TypeError: (t.data || "").search is not a function

can you guys tell me how to fix it.

relevant code and example:

http://plnkr.co/edit/M05wS03ynxX812u2MATc?p=preview&open=app%2Fapp.component.ts

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

@Component({
  selector: 'my-app',

  styles: [`
    li {
      color: red;
    }
  `],
  template: `

 {{student}}

`
})
export class AppComponent {
  name = 'Angular';
  liArraycontent = ["testing 1", "testing 2", "testing3"]
  this.liClicked = function(e1) {
    alert('a');
  }

}

/*
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
```

答:
You don't need this at typescript class. just remove this in your component.

```<code>liClicked = function(e1) {
  alert(e1);
}
</code>```

also when you use this at template event, you will get AppComponent which is different from javascript. And if you want to access current li element, use $event.target instead.

refer Plunker demo, hope it'll help.

BTW I didn't got the error (t.data || "").search is not a function from the example you provided, maybe you need more explanation.

Body:
You don't need this at typescript class. just remove this in your component.

liClicked = function(e1) {
  alert(e1);
}

also when you use this at template event, you will get AppComponent which is different from javascript. And if you want to access current li element, use $event.target instead.

refer Plunker demo, hope it'll help.

BTW I didn't got the error (t.data || "").search is not a function from the example you provided, maybe you need more explanation.


问:
Visual Studio Team Services build server in Azure
I am trying to create a custom build server for Visual Studio Team Services in Azure. I have installed the build agent and Visual Studio Express on a virtual machine which is running and connected to my project on visualstudio.com as a build agent in the "Default" pool.

However when I tried to run a build I got the following error:

```<code>No agent found in pool 1 which satisfies the specified demands:
msbuild
visualstudio
vstest
Agent.Version -gtVersion 1.98.1
</code>```

MSBuild was already in the list of capabilities on visualstudio.com but not the other two, so I dug through C:\Program Files (x86) and added these two capabilities to the list:

```<code>vstest: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow
visualstudio: C:\Program Files (x86)\Microsoft Visual Studio 14.0
</code>```

The build then runs at least but I get another error during the "Test Assemblies" step. I think the most important part of the error message is Unable to determine the location of vstest.console.exe, here it is in full anyway:

```<code>System.Management.Automation.CmdletInvocationException: Unable to determine the location of vstest.console.exe ---> System.IO.FileNotFoundException: Unable to determine the location of vstest.console.exe
at Microsoft.TeamFoundation.DistributedTask.Task.Internal.PowerShell.InvokeVSTestCmdlet.GetVsTestLocation()
at Microsoft.TeamFoundation.DistributedTask.Task.Internal.PowerShell.InvokeVSTestCmdlet.ProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()
--- End of inner exception stack trace ---
at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspace rs, Boolean performSyncInvoke)
at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, Boolean isSync)
at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
at Microsoft.TeamFoundation.DistributedTask.Handlers.PowerShellHandler.Execute(ITaskContext context, CancellationToken cancellationToken, Int32 timeoutInMinutes)
at Microsoft.TeamFoundation.DistributedTask.Worker.JobRunner.RunTask(ITaskContext context, TaskWrapper task, CancellationTokenSource tokenSource)
</code>```

I have looked and vstest.console.exe is located in the vstest folder I specified above, I've also tried adding this folder to the system PATH but that makes no difference.

How can I set up a working build agent in Azure?

答:
In TFS Build Logs under Test Assemblies I see the error:

System.Management.Automation.CmdletInvocationException: Unable to determine the location of vstest.console.exe

I had VSTest set as Visual Studio 2015, I'm using VS/TFS2017 so switching to Latest solved the problem:

Body:
I am trying to create a custom build server for Visual Studio Team Services in Azure. I have installed the build agent and Visual Studio Express on a virtual machine which is running and connected to my project on visualstudio.com as a build agent in the "Default" pool.

However when I tried to run a build I got the following error:

No agent found in pool 1 which satisfies the specified demands:
msbuild
visualstudio
vstest
Agent.Version -gtVersion 1.98.1

MSBuild was already in the list of capabilities on visualstudio.com but not the other two, so I dug through C:\Program Files (x86) and added these two capabilities to the list:

vstest: C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow
visualstudio: C:\Program Files (x86)\Microsoft Visual Studio 14.0

The build then runs at least but I get another error during the "Test Assemblies" step. I think the most important part of the error message is Unable to determine the location of vstest.console.exe, here it is in full anyway:

System.Management.Automation.CmdletInvocationException: Unable to determine the location of vstest.console.exe ---> System.IO.FileNotFoundException: Unable to determine the location of vstest.console.exe
at Microsoft.TeamFoundation.DistributedTask.Task.Internal.PowerShell.InvokeVSTestCmdlet.GetVsTestLocation()
at Microsoft.TeamFoundation.DistributedTask.Task.Internal.PowerShell.InvokeVSTestCmdlet.ProcessRecord()
at System.Management.Automation.CommandProcessor.ProcessRecord()
--- End of inner exception stack trace ---
at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
at System.Management.Automation.PowerShell.Worker.ConstructPipelineAndDoWork(Runspace rs, Boolean performSyncInvoke)
at System.Management.Automation.PowerShell.Worker.CreateRunspaceIfNeededAndDoWork(Runspace rsToUse, Boolean isSync)
at System.Management.Automation.PowerShell.CoreInvokeHelper[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
at System.Management.Automation.PowerShell.CoreInvoke[TInput,TOutput](PSDataCollection`1 input, PSDataCollection`1 output, PSInvocationSettings settings)
at Microsoft.TeamFoundation.DistributedTask.Handlers.PowerShellHandler.Execute(ITaskContext context, CancellationToken cancellationToken, Int32 timeoutInMinutes)
at Microsoft.TeamFoundation.DistributedTask.Worker.JobRunner.RunTask(ITaskContext context, TaskWrapper task, CancellationTokenSource tokenSource)

I have looked and vstest.console.exe is located in the vstest folder I specified above, I've also tried adding this folder to the system PATH but that makes no difference.

How can I set up a working build agent in Azure?


问:
Leaks Instrument not running in xcode 8.3.2
I have tried following the solution to this question.
All instruments work perfectly but leak instruments cause this error:

An error occurred trying to capture Leaks data, Error retrieving leak information.

I want to be able to use Leak Instrument without any errors.
Image is also shown below.

Please help me. Thanks in advance.

答: i upgrade the Xcode from 8.3.2 to 8.3.3 , it not works. Then I tried running it on true device , it works well.</p>

ContentLicense: CC BY-SA 4.0


问:
Change comment size relative to original size of fill picture in Excel vba
Trying to write a VBA excel macro that will allow me to insert a picture as a pop-up on mouseover of a cell.

I'm accomplishing this by inserting a comment in the cell and setting the comment's fill to be a specified picture.

I would like the picture to maintain its original scaling

After setting the comment to use the picture as a fill background, I can manually right-click the cell, click edit comment, right-click the comment, go to the "size" tab, select "Relative to original picture size" checkbox, and set scale height and size to be 100%, which achieves the desired effect, as shown below:

Recording a macro to see what the VBA to replicate this is results in nothing being recorded.

Using the targetComment.Shape.ScaleHeight 1, msoTrue results in an error:

```<code>Run-time error '-2147024891 (80070005)':
The RelativeToOriginalSize argument applies only to a picture or an OLE object
</code>```

Here is a screenshot of the VBA code that generates this error:

Does anyone know how to access what is in the dialog box via VBA???

答:
Using a comment to show an image with scaling can be done. The trick is to calculate the scaling factor yourself and apply it to the image. I've used the Windows Image Acquisition Automation Layer to access the image file's dimensions.

The example below accesses a JPG image in my Temp directory and adds it to a cell's comment with appropriate scaling.

```<code>Option Explicit

Sub test()
    '--- delete any existing comment just for testing
    If Not Range("C5").Comment Is Nothing Then
        Range("C5").Comment.Delete
    End If
    InsertCommentWithImage Range("C5"), "C:\Temp\laptop.jpg", 1#
End Sub

Sub InsertCommentWithImage(imgCell As Range, _
                           imgPath As String, _
                           imgScale As Double)
    '--- first check if the image file exists in the
    '    specified path
    If Dir(imgPath) <> vbNullString Then
        If imgCell.Comment Is Nothing Then
            imgCell.AddComment
        End If

        '--- establish a Windows Image Acquisition Automation object
        '    to get the image's dimensions
        Dim imageObj As Object
        Set imageObj = CreateObject("WIA.ImageFile")
        imageObj.LoadFile (imgPath)

        Dim width As Long
        Dim height As Long
        width = imageObj.width
        height = imageObj.height

        '--- simple scaling that keeps the image's
        '    original aspect ratio
        With imgCell.Comment
            .Shape.Fill.UserPicture imgPath
            .Shape.height = height * imgScale
            .Shape.width = width * imgScale
        End With
    End If
End Sub
</code>```

Body:
Trying to write a VBA excel macro that will allow me to insert a picture as a pop-up on mouseover of a cell.

I'm accomplishing this by inserting a comment in the cell and setting the comment's fill to be a specified picture.

I would like the picture to maintain its original scaling

After setting the comment to use the picture as a fill background, I can manually right-click the cell, click edit comment, right-click the comment, go to the "size" tab, select "Relative to original picture size" checkbox, and set scale height and size to be 100%, which achieves the desired effect, as shown below:

Recording a macro to see what the VBA to replicate this is results in nothing being recorded.

Using the targetComment.Shape.ScaleHeight 1, msoTrue results in an error:

Run-time error '-2147024891 (80070005)':
The RelativeToOriginalSize argument applies only to a picture or an OLE object

Here is a screenshot of the VBA code that generates this error:

Does anyone know how to access what is in the dialog box via VBA???

Body:
Using a comment to show an image with scaling can be done. The trick is to calculate the scaling factor yourself and apply it to the image. I've used the Windows Image Acquisition Automation Layer to access the image file's dimensions.

The example below accesses a JPG image in my Temp directory and adds it to a cell's comment with appropriate scaling.

Option Explicit

Sub test()
    '--- delete any existing comment just for testing
    If Not Range("C5").Comment Is Nothing Then
        Range("C5").Comment.Delete
    End If
    InsertCommentWithImage Range("C5"), "C:\Temp\laptop.jpg", 1#
End Sub

Sub InsertCommentWithImage(imgCell As Range, _
                           imgPath As String, _
                           imgScale As Double)
    '--- first check if the image file exists in the
    '    specified path
    If Dir(imgPath) <> vbNullString Then
        If imgCell.Comment Is Nothing Then
            imgCell.AddComment
        End If

        '--- establish a Windows Image Acquisition Automation object
        '    to get the image's dimensions
        Dim imageObj As Object
        Set imageObj = CreateObject("WIA.ImageFile")
        imageObj.LoadFile (imgPath)

        Dim width As Long
        Dim height As Long
        width = imageObj.width
        height = imageObj.height

        '--- simple scaling that keeps the image's
        '    original aspect ratio
        With imgCell.Comment
            .Shape.Fill.UserPicture imgPath
            .Shape.height = height * imgScale
            .Shape.width = width * imgScale
        End With
    End If
End Sub


问:
Deploying a webapp to a websphere application server that checks the health of the host server
If i have a webapp deployed to a specific server or host, and this webapp checks the health of the local server its deployed on when you call a get request on its URI.

The problem I am having is that if the server goes down, you can't even make a get request to the health webapp (webapp simply uses a URL object with the localhost and port path and gets the connection code).

Would creating a seperate JVM for the webapp solve this problem? or does the webapp need to be hosted entirely on another server?

i'm a beginner so have mercy.

答: The short answer is not feasible. you will need a third party vendor app to check your server from outside the host itself. i can give you many suggestion. but just try these first, datadog apm and nagios. </p>


问:
JavaScript Crashing Chrome (Infinite Recursion )
When I run this my browser freezes and crashes but I can't figure out how to fix it. I am new to JavaScript and I need some help.</p>

```<code>function Start() {

if (Key1 === true) {
    alert ("1")
    Key1 = false
} else if (Key2 === true) {
    alert ("2")
    Key2 = false
} else {
    window.setTimeout(Start, 1000);
    Start()
}

}
</code>```

答:
Assuming Key1 and Key2 are not defined, you directly execute the last else.

In it, you call Start() twice, once, by a direct call, once by a setTimeout, so every time you call Start, then two more Start will be executed.

You have an infinite recursive call that is expanding with time, the browser cannot keep up and crashes.

Body:
When I run this my browser freezes and crashes but I can't figure out how to fix it. I am new to JavaScript and I need some help.

function Start() {

if (Key1 === true) {
    alert ("1")
    Key1 = false
} else if (Key2 === true) {
    alert ("2")
    Key2 = false
} else {
    window.setTimeout(Start, 1000);
    Start()
}

}


问:
Best way to find max serial num in MySQL database
I have a MySQL database with a column named ID(VARCHAR 60)

The data of ID is linked by  id_num + serial num.

For example, a group data is below

367618648+0001

367618648+0002

51687687+0001

51687687+0002

51687687+0003

51687687+0004

I want to know  the best way to find the max "serial num" for an "id_num"?

答:
Use substring_index().  The following gets the max for all id_nums:

```<code>select substring_index(id, '+', 1) as id_num,
       max(substring_index(id, '+', -1) + 0) as serial_num
from t
group by id_num;
</code>```

Body:
Use substring_index().  The following gets the max for all id_nums:

select substring_index(id, '+', 1) as id_num,
       max(substring_index(id, '+', -1) + 0) as serial_num
from t
group by id_num;


问:
Android Spring Rest template
I'm trying to use spring rest template to do a post request. And i need to return the status code. This is my approach.

RestTemplate restTemplate = new RestTemplate();

MultiValueMap mvm = new LinkedMultiValueMap();

mvm.add("login", "100");
// and some more paramters

String result = restTemplate.postForObject("http://localhost:8080/security_check", mvm, String.class);

But this approach doesn't work for me. It generates an error saying no suitable message converter found.
And i need to know can i use the resttemplate to manage my sessions. I need to manage the session from the android client side.

If any one come across android resttemplate post method and session management please help me. Any help would be greatly appreciated.

Thanks in advance.

答:
See http://forum.springsource.org/showthread.php?t=99064 Pls mark this question as answered or delete it since u asked it on the link I just posted.

And by the way I can take a look at my question regarding a similiar issue... http://forum.springsource.org/showthread.php?t=99690 ;)

Title: Android Spring Rest template


问:
Azure Functions binding redirect
Is it possible to include a web.config or app.config file in the azure functions folder structure to allow assembly binding redirects?</p>

答:
Assuming you are using the latest (June'17) Visual Studio 2017 Function Tooling, I derived a somewhat-reasonable config-based solution for this following a snippet of code posted by npiasecki over on Issue #992.

It would be ideal if this were managed through the framework, but at least being configuration-driven you have a bit more change isolation. I suppose you could also use some pre-build steps or T4 templating that reconciles the versions of the nugets in the project (and their dependencies) before writing out this config or generating code.

So the downside..

.. becomes having to remember to update the BindingRedirects config when you update the NuGet package (this is often a problem in app.configs anyway). You may also have an issue with the config-driven solution if you need to redirect Newtonsoft.

In our case, we were using the new Azure Fluent NuGet that had a dependency on an older version of Microsoft.IdentityModel.Clients.ActiveDirectory than the version of the normal ARM management libraries which are used side-by-side in a particular Function.

local.settings.json

```<code>{
    "IsEncrypted": false,
    "Values": {
        "BindingRedirects": "[ { \"ShortName\": \"Microsoft.IdentityModel.Clients.ActiveDirectory\", \"RedirectToVersion\": \"3.13.9.1126\", \"PublicKeyToken\": \"31bf3856ad364e35\" } ]"
    }
}
</code>```

FunctionUtilities.cs

```<code>using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace Utilities.AzureFunctions
{
    public static class FunctionUtilities
        {
            public class BindingRedirect
            {
                public string ShortName { get; set; }
                public string PublicKeyToken { get; set; }
                public string RedirectToVersion { get; set; }
            }

            public static void ConfigureBindingRedirects()
            {
                var config = Environment.GetEnvironmentVariable("BindingRedirects");
                var redirects = JsonConvert.DeserializeObject<List<BindingRedirect>>(config);
                redirects.ForEach(RedirectAssembly);
            }

            public static void RedirectAssembly(BindingRedirect bindingRedirect)
            {
                ResolveEventHandler handler = null;

                handler = (sender, args) =>
                {
                    var requestedAssembly = new AssemblyName(args.Name);

                    if (requestedAssembly.Name != bindingRedirect.ShortName)
                    {
                        return null;
                    }

                    var targetPublicKeyToken = new AssemblyName("x, PublicKeyToken=" + bindingRedirect.PublicKeyToken)
                        .GetPublicKeyToken();
                    requestedAssembly.Version = new Version(bindingRedirect.RedirectToVersion);
                    requestedAssembly.SetPublicKeyToken(targetPublicKeyToken);
                    requestedAssembly.CultureInfo = CultureInfo.InvariantCulture;

                    AppDomain.CurrentDomain.AssemblyResolve -= handler;

                    return Assembly.Load(requestedAssembly);
                };

                AppDomain.CurrentDomain.AssemblyResolve += handler;
            }
        }
    }
</code>```

Title: Azure Functions binding redirect

Body:
Assuming you are using the latest (June'17) Visual Studio 2017 Function Tooling, I derived a somewhat-reasonable config-based solution for this following a snippet of code posted by npiasecki over on Issue #992.

It would be ideal if this were managed through the framework, but at least being configuration-driven you have a bit more change isolation. I suppose you could also use some pre-build steps or T4 templating that reconciles the versions of the nugets in the project (and their dependencies) before writing out this config or generating code.

So the downside..

.. becomes having to remember to update the BindingRedirects config when you update the NuGet package (this is often a problem in app.configs anyway). You may also have an issue with the config-driven solution if you need to redirect Newtonsoft.

In our case, we were using the new Azure Fluent NuGet that had a dependency on an older version of Microsoft.IdentityModel.Clients.ActiveDirectory than the version of the normal ARM management libraries which are used side-by-side in a particular Function.

local.settings.json

{
    "IsEncrypted": false,
    "Values": {
        "BindingRedirects": "[ { \"ShortName\": \"Microsoft.IdentityModel.Clients.ActiveDirectory\", \"RedirectToVersion\": \"3.13.9.1126\", \"PublicKeyToken\": \"31bf3856ad364e35\" } ]"
    }
}

FunctionUtilities.cs

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace Utilities.AzureFunctions
{
    public static class FunctionUtilities
        {
            public class BindingRedirect
            {
                public string ShortName { get; set; }
                public string PublicKeyToken { get; set; }
                public string RedirectToVersion { get; set; }
            }

            public static void ConfigureBindingRedirects()
            {
                var config = Environment.GetEnvironmentVariable("BindingRedirects");
                var redirects = JsonConvert.DeserializeObject<List<BindingRedirect>>(config);
                redirects.ForEach(RedirectAssembly);
            }

            public static void RedirectAssembly(BindingRedirect bindingRedirect)
            {
                ResolveEventHandler handler = null;

                handler = (sender, args) =>
                {
                    var requestedAssembly = new AssemblyName(args.Name);

                    if (requestedAssembly.Name != bindingRedirect.ShortName)
                    {
                        return null;
                    }

                    var targetPublicKeyToken = new AssemblyName("x, PublicKeyToken=" + bindingRedirect.PublicKeyToken)
                        .GetPublicKeyToken();
                    requestedAssembly.Version = new Version(bindingRedirect.RedirectToVersion);
                    requestedAssembly.SetPublicKeyToken(targetPublicKeyToken);
                    requestedAssembly.CultureInfo = CultureInfo.InvariantCulture;

                    AppDomain.CurrentDomain.AssemblyResolve -= handler;

                    return Assembly.Load(requestedAssembly);
                };

                AppDomain.CurrentDomain.AssemblyResolve += handler;
            }
        }
    }