问:
Finding max value using reduce
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

```<code>{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])
</code>```

This is what I have so far:

```<code>(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)
</code>```

This produces the outcome:

```<code>{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}
</code>```

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

答:
Here is how I would do it.  I used spyx-pretty from the Tupelo library to make visualizing the intermediate steps easier (API docs can be found here).  The code:

```<code>(ns tst.demo.core
  (:use demo.core
        tupelo.test)
  (:require [tupelo.core :as t]
            [clojure.string :as str] ))
(t/refer-tupelo)

(def table
  [{:product "Pencil" :city "Toronto" :year "2010" :sales "2653.00"}
   {:product "Pencil" :city "Oshawa" :year "2010" :sales "525.00"}
   {:product "Bread" :city "Toronto" :year "2010" :sales "136,264.00"}
   {:product "Bread" :city "Oshawa" :year "nil" :sales "242,634.00"}
   {:product "Bread" :city "Ottawa" :year "2011" :sales "426,164.00"}])

(defn str->double
  "Convert a string like '2,123.97' to a double like 2123.97 "
  [str-val]
  (let [no-commas (str/replace str-val #"," "")
        dbl-val   (Double/parseDouble no-commas)]
    dbl-val))

(dotest
  (let [table-num (forv [item table]
                    (update item :sales str->double))
        grouped   (group-by :product table-num)
        >>        (spyx-pretty grouped)
        group-max (forv [group grouped]
                    (do
                      (spyx-pretty group)
                      (let [records        (xsecond group)
                            >>             (spyx-pretty records)
                            records-sorted (sort-by :sales > records)
                            >>             (spyx-pretty records-sorted)
                            max-rec        (xfirst records-sorted)
                            ]
                        (spyx max-rec))))]
    (spyx-pretty group-max)))
</code>```

The results are:

```<code>---------------------------------------
   Clojure 1.9.0-beta1    Java 9.0.1
---------------------------------------

Testing tst.demo.core

grouped =>
{"Pencil"
 [{:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}
  {:product "Pencil", :city "Oshawa", :year "2010", :sales 525.0}],
 "Bread"
 [{:product "Bread", :city "Toronto", :year "2010", :sales 136264.0}
  {:product "Bread", :city "Oshawa", :year "nil", :sales 242634.0}
  {:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}]}

group =>
["Pencil"
 [{:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}
  {:product "Pencil", :city "Oshawa", :year "2010", :sales 525.0}]]

records =>
[{:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}
 {:product "Pencil", :city "Oshawa", :year "2010", :sales 525.0}]

records-sorted =>
({:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}
 {:product "Pencil", :city "Oshawa", :year "2010", :sales 525.0})
max-rec => {:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}

group =>
["Bread"
 [{:product "Bread", :city "Toronto", :year "2010", :sales 136264.0}
  {:product "Bread", :city "Oshawa", :year "nil", :sales 242634.0}
  {:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}]]

records =>
[{:product "Bread", :city "Toronto", :year "2010", :sales 136264.0}
 {:product "Bread", :city "Oshawa", :year "nil", :sales 242634.0}
 {:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}]

records-sorted =>
({:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}
 {:product "Bread", :city "Oshawa", :year "nil", :sales 242634.0}
 {:product "Bread", :city "Toronto", :year "2010", :sales 136264.0})
max-rec => {:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}

group-max =>
[{:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}
 {:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}]
</code>```

Note that the 1st step is to convert all string sales values to floating point. Then, it is easiest if we use the built-in function group-by to separate out pencils from Bread, etc.  I like to keep each step separate for ease of thinking, and also so I can put debug printouts at each step.

IMHO this is more straightforward than using the REPL, as I can stay in my favorite IDE/editor and the stuff I type is saved in a file rather than disappearing as soon as I hit .

Title: Finding max value using reduce

Body:
New to clojure with a java background. I have the following table and need to transform the table to a hash-map that maps products to the city that has the highest sale. For example, the output should look like:

{"Pencil": "Toronto"
"Bread": "Ottawa"}

(def table [
    {:product "Pencil"
    :city "Toronto"
    :year "2010"
    :sales "2653.00"}
    {:product "Pencil"
    :city "Oshawa"
    :year "2010"
    :sales "525.00"}
    {:product "Bread"
    :city "Toronto"
    :year "2010"
    :sales "136,264.00"}
    {:product "Bread"
    :city "Oshawa"
    :year "nil"
    :sales "242,634.00"}
    {:product "Bread"
    :city "Ottawa"
    :year "2011"
    :sales "426,164.00"}])

This is what I have so far:

(reduce (fn [product-cities {:keys [product sales]}]
         (update-in product-cities [product] (fnil conj []) sales))
       {}
       table)

This produces the outcome:

{"Bread"
["136,264.00"
"242,634.00"
"426,164.00"],
 "Pencil" ["2653.00" "525.00"]}

How can i compare the sales of each city and and only keep the name of the city with the highest sales? Having a really tough time with this. Thanks

Body:
Here is how I would do it.  I used spyx-pretty from the Tupelo library to make visualizing the intermediate steps easier (API docs can be found here).  The code:

(ns tst.demo.core
  (:use demo.core
        tupelo.test)
  (:require [tupelo.core :as t]
            [clojure.string :as str] ))
(t/refer-tupelo)

(def table
  [{:product "Pencil" :city "Toronto" :year "2010" :sales "2653.00"}
   {:product "Pencil" :city "Oshawa" :year "2010" :sales "525.00"}
   {:product "Bread" :city "Toronto" :year "2010" :sales "136,264.00"}
   {:product "Bread" :city "Oshawa" :year "nil" :sales "242,634.00"}
   {:product "Bread" :city "Ottawa" :year "2011" :sales "426,164.00"}])

(defn str->double
  "Convert a string like '2,123.97' to a double like 2123.97 "
  [str-val]
  (let [no-commas (str/replace str-val #"," "")
        dbl-val   (Double/parseDouble no-commas)]
    dbl-val))

(dotest
  (let [table-num (forv [item table]
                    (update item :sales str->double))
        grouped   (group-by :product table-num)
        >>        (spyx-pretty grouped)
        group-max (forv [group grouped]
                    (do
                      (spyx-pretty group)
                      (let [records        (xsecond group)
                            >>             (spyx-pretty records)
                            records-sorted (sort-by :sales > records)
                            >>             (spyx-pretty records-sorted)
                            max-rec        (xfirst records-sorted)
                            ]
                        (spyx max-rec))))]
    (spyx-pretty group-max)))

The results are:

---------------------------------------
   Clojure 1.9.0-beta1    Java 9.0.1
---------------------------------------

Testing tst.demo.core

grouped =>
{"Pencil"
 [{:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}
  {:product "Pencil", :city "Oshawa", :year "2010", :sales 525.0}],
 "Bread"
 [{:product "Bread", :city "Toronto", :year "2010", :sales 136264.0}
  {:product "Bread", :city "Oshawa", :year "nil", :sales 242634.0}
  {:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}]}

group =>
["Pencil"
 [{:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}
  {:product "Pencil", :city "Oshawa", :year "2010", :sales 525.0}]]

records =>
[{:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}
 {:product "Pencil", :city "Oshawa", :year "2010", :sales 525.0}]

records-sorted =>
({:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}
 {:product "Pencil", :city "Oshawa", :year "2010", :sales 525.0})
max-rec => {:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}

group =>
["Bread"
 [{:product "Bread", :city "Toronto", :year "2010", :sales 136264.0}
  {:product "Bread", :city "Oshawa", :year "nil", :sales 242634.0}
  {:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}]]

records =>
[{:product "Bread", :city "Toronto", :year "2010", :sales 136264.0}
 {:product "Bread", :city "Oshawa", :year "nil", :sales 242634.0}
 {:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}]

records-sorted =>
({:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}
 {:product "Bread", :city "Oshawa", :year "nil", :sales 242634.0}
 {:product "Bread", :city "Toronto", :year "2010", :sales 136264.0})
max-rec => {:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}

group-max =>
[{:product "Pencil", :city "Toronto", :year "2010", :sales 2653.0}
 {:product "Bread", :city "Ottawa", :year "2011", :sales 426164.0}]

Note that the 1st step is to convert all string sales values to floating point. Then, it is easiest if we use the built-in function group-by to separate out pencils from Bread, etc.  I like to keep each step separate for ease of thinking, and also so I can put debug printouts at each step.

IMHO this is more straightforward than using the REPL, as I can stay in my favorite IDE/editor and the stuff I type is saved in a file rather than disappearing as soon as I hit .


来源: stackexchange

问:
Format a phone number as a user types using pure JavaScript
I've got an input field in the body of my document, and I need to format it as the user types. It should have parenthesis around the area code and a dash between the three and four digits after that.

Ex: (123) 456 - 7890

As the user types it should look something like:

(12

(123)

(123) 456

(123) 456 - 78

(123) 456 - 7890

答:
To add some additional ease for the user, I'd actually update the string to automatically include a ")" or "-" as the user reaches certain characters, to prevent them from adding, say two dashes. (555)555--5555</p>

```<code>if(size === 0) {
    input = input;
}
else if (size === 3) {
    input = '('+input.substring(0,3)+') '
}
else if (size < 4) {
    input = '('+input;
}
else if (size === 6) {
    input = '('+input.substring(0,3)+') '+input.substring(3,6)+' -';
}
else if (size > 6) {
    input = '('+input.substring(0,3)+') '+input.substring(3,6)+' - '+input.substring(6,10);
}
return input
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To add some additional ease for the user, I'd actually update the string to automatically include a ")" or "-" as the user reaches certain characters, to prevent them from adding, say two dashes. (555)555--5555

if(size === 0) {
    input = input;
}
else if (size === 3) {
    input = '('+input.substring(0,3)+') '
}
else if (size < 4) {
    input = '('+input;
}
else if (size === 6) {
    input = '('+input.substring(0,3)+') '+input.substring(3,6)+' -';
}
else if (size > 6) {
    input = '('+input.substring(0,3)+') '+input.substring(3,6)+' - '+input.substring(6,10);
}
return input


问:
How do I dynamically set HTML5 data- attributes using react?
I'd like to render an HTML5 attribute of a <select> input so that I can use jquery image picker with react. My code is:

```<code>var Book = React.createClass({
    render: function() {
        return (
            <option data-img-src="{this.props.imageUrl}" value="1">{this.props.title}</option>
</code>```

The issue is that even though {this.props.imageUrl} is getting properly passed as a prop, it isn't rendering in the HTML - it just renders as {this.props.imageUrl}. How can I make the variable pass through properly into the HTML?

答:
Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

```<code><Option data-img-src='value' ... />
</code>```

And then in the component, because of the dashes, you need to refer to the prop in quotes.

```<code>// @flow
class Option extends React.Component {

  props: {
    'data-img-src': string
  }
</code>```

And when you refer to it later, you don't use the dot syntax

```<code>  render () {
    return (
      <option data-img-src={this.props['data-img-src']} >...</option>
    )
  }
}
</code>```

Or use camel case

```<code><Option dataImgSrc='value' ... />
</code>```

And then in the component, you need to convert.

```<code>// @flow
class Option extends React.Component {

  props: {
    dataImgSrc: string
  }
</code>```

And when you refer to it later, you use the dot syntax

```<code>  render () {
    return (
      <option data-img-src={this.props.dataImgSrc} >...</option>
    )
  }
}
</code>```

Mainly just realize data- attributes and aria- attributes are treated specially.  You are allowed to use hyphens in the attribute name in those two cases.

Body:
I'd like to render an HTML5 attribute of a <select> input so that I can use jquery image picker with react. My code is:

var Book = React.createClass({
    render: function() {
        return (
            <option data-img-src="{this.props.imageUrl}" value="1">{this.props.title}</option>

The issue is that even though {this.props.imageUrl} is getting properly passed as a prop, it isn't rendering in the HTML - it just renders as {this.props.imageUrl}. How can I make the variable pass through properly into the HTML?

Body:
Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

<Option data-img-src='value' ... />

And then in the component, because of the dashes, you need to refer to the prop in quotes.

// @flow
class Option extends React.Component {

  props: {
    'data-img-src': string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props['data-img-src']} >...</option>
    )
  }
}

Or use camel case

<Option dataImgSrc='value' ... />

And then in the component, you need to convert.

// @flow
class Option extends React.Component {

  props: {
    dataImgSrc: string
  }

And when you refer to it later, you use the dot syntax

  render () {
    return (
      <option data-img-src={this.props.dataImgSrc} >...</option>
    )
  }
}

Mainly just realize data- attributes and aria- attributes are treated specially.  You are allowed to use hyphens in the attribute name in those two cases.

ContentLicense: CC BY-SA 4.0


问:
Android: Convert Stream to String without running out of memory
I have an android client that communicates with the server via REST-ful endpoints and JSON. Because of this, I have the need to retrieve the full server response prior to converting it into a Hash. I have this code in place to do that (found on the internet someplace):

```<code>private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
</code>```

The code works for the most part, however I am seeing reports of crashes in the field from clients with an OutOfMemory exception on the line:

```<code>    while ((line = reader.readLine()) != null) {
</code>```

The full stack trace is:

```<code>java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:200)
    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
    at java.lang.Thread.run(Thread.java:1102)
Caused by: java.lang.OutOfMemoryError
    at java.lang.String.(String.java:468)
    at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:659)
    at java.lang.StringBuilder.toString(StringBuilder.java:664)
    at java.io.BufferedReader.readLine(BufferedReader.java:448)
    at com.appspot.myapp.util.RestClient.convertStreamToString(RestClient.java:303)
    at com.appspot.myapp.util.RestClient.executeRequest(RestClient.java:281)
    at com.appspot.myapp.util.RestClient.Execute(RestClient.java:178)
    at com.appspot.myapp.$LoadProfilesTask.doInBackground(GridViewActivity.java:1178)
    at com.appspot.myapp.$LoadProfilesTask.doInBackground(GridViewActivity.java:1)
    at android.os.AsyncTask$2.call(AsyncTask.java:185)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    ... 4 more
</code>```

My question: is there any way to solve this problem aside from sending smaller chunks of data from the server?

Thanks!

答:
In general, the answer is no, but you can certainly tune the conditions that cause you to run out of memory. In particular, if you send string length ahead of your stream, you will be able to create a StringBuilder with correct array size inside of it. Arrays cannot be resized after creation, so if you run out of array capacity in StringBuilder, the implementation has to allocate a new array (typically twice the size to avoid too many resizes) and then copy the old array contents. Consider stream of size X, to resize StringBuilder that just happened to be a X-1 capacity, you need almost X*3 amount of memory. Sizing StringBuilder such that resizes are avoided will allow you squeeze larger streams into memory.

Another thing you may want to do is to tune the amount of memory available to your server process. Use a switch like -Xmx1024m when launching the server process.

Of course, it would be much better to revise your algorithm to not require the entire stream to be held in memory. It will enable you to handle more clients with the same amount of hardware.

ContentLicense: CC BY-SA 2.5

Body:
I have an android client that communicates with the server via REST-ful endpoints and JSON. Because of this, I have the need to retrieve the full server response prior to converting it into a Hash. I have this code in place to do that (found on the internet someplace):

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

The code works for the most part, however I am seeing reports of crashes in the field from clients with an OutOfMemory exception on the line:

    while ((line = reader.readLine()) != null) {

The full stack trace is:

java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:200)
    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
    at java.lang.Thread.run(Thread.java:1102)
Caused by: java.lang.OutOfMemoryError
    at java.lang.String.(String.java:468)
    at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:659)
    at java.lang.StringBuilder.toString(StringBuilder.java:664)
    at java.io.BufferedReader.readLine(BufferedReader.java:448)
    at com.appspot.myapp.util.RestClient.convertStreamToString(RestClient.java:303)
    at com.appspot.myapp.util.RestClient.executeRequest(RestClient.java:281)
    at com.appspot.myapp.util.RestClient.Execute(RestClient.java:178)
    at com.appspot.myapp.$LoadProfilesTask.doInBackground(GridViewActivity.java:1178)
    at com.appspot.myapp.$LoadProfilesTask.doInBackground(GridViewActivity.java:1)
    at android.os.AsyncTask$2.call(AsyncTask.java:185)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    ... 4 more

My question: is there any way to solve this problem aside from sending smaller chunks of data from the server?

Thanks!


问:
Can i change the location where netbeans stores project groups
I work on three different computers. However, I store my sources in dropbox, thus I have access from all computers to the same sources. I need to access the same project group from those computers. How can I achieve it?</p>

答:
You can store all of your NetBeans settings in DropBox (including the project group). Start NetBeans with the --userdir argument like this:

```<code>netbeans.exe --userdir C:\MyOtherUserdir
</code>```

You may want to copy your current user directory to your DropBox folder first so that you don't have to reconfigure all of your NetBeans settings and recreate the project group.

See http://wiki.netbeans.org/FaqAlternateUserdir for more information.

Body:
You can store all of your NetBeans settings in DropBox (including the project group). Start NetBeans with the --userdir argument like this:

netbeans.exe --userdir C:\MyOtherUserdir

You may want to copy your current user directory to your DropBox folder first so that you don't have to reconfigure all of your NetBeans settings and recreate the project group.

See http://wiki.netbeans.org/FaqAlternateUserdir for more information.


问:
installing varnish in ubuntu 16.04
Tried with 2 different approaches to setup varnish on ubuntu 16.04 in azure but not sure whether the approach of installation is correct.

Referred with different websites all seems to be same set of commands.

Approach 1

```<code>sudo apt-get update
sudo apt-get upgrade
sudo apt-get install varnish

.........
.........
Setting up libvarnishapi1 (4.1.1-1ubuntu0.2) ...
Setting up manpages-dev (4.04-2) ...
Setting up libjemalloc1 (3.6.0-9ubuntu1) ...
Setting up varnish (4.1.1-1ubuntu0.2) ...
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(group) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
Processing triggers for libc-bin (2.23-0ubuntu9) ...
Processing triggers for systemd (229-4ubuntu21) ...
Processing triggers for ureadahead (0.100.0-19) ...
</code>```

Is the above installation is correct since it gives sent invalidate.

Approach 2

```<code>sudo curl http://repo.varnish-cache.org/debian/GPG-key.txt | sudo apt-key add -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   580  100   580    0     0   1172      0 --:--:-- --:--:-- --:--:--  1171
gpg: no valid OpenPGP data found.

sudo echo "deb http://repo.varnish-cache.org/ubuntu/ precise varnish-3.0" | sudo tee -a /etc/apt/sources.list

sudo apt-get update
</code>```

Doing a update will result in below error.

```<code>W: The repository 'http://repo.varnish-cache.org/ubuntu precise Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://repo.varnish-cache.org/ubuntu/dists/precise/varnish-3.0/binary-amd64/Packages  410  repo [IP: 176.58.90.154 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.
</code>```

Not sure both the approaches are correct as both are giving some errors.

答: You may refer "How to install Varnish on Ubuntu Server 16.04".</p>

Title: installing varnish in ubuntu 16.04

Body:
Tried with 2 different approaches to setup varnish on ubuntu 16.04 in azure but not sure whether the approach of installation is correct.

Referred with different websites all seems to be same set of commands.

Approach 1

sudo apt-get update
sudo apt-get upgrade
sudo apt-get install varnish

.........
.........
Setting up libvarnishapi1 (4.1.1-1ubuntu0.2) ...
Setting up manpages-dev (4.04-2) ...
Setting up libjemalloc1 (3.6.0-9ubuntu1) ...
Setting up varnish (4.1.1-1ubuntu0.2) ...
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(group) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
sent invalidate(passwd) request, exiting
sent invalidate(group) request, exiting
Processing triggers for libc-bin (2.23-0ubuntu9) ...
Processing triggers for systemd (229-4ubuntu21) ...
Processing triggers for ureadahead (0.100.0-19) ...

Is the above installation is correct since it gives sent invalidate.

Approach 2

sudo curl http://repo.varnish-cache.org/debian/GPG-key.txt | sudo apt-key add -
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   580  100   580    0     0   1172      0 --:--:-- --:--:-- --:--:--  1171
gpg: no valid OpenPGP data found.

sudo echo "deb http://repo.varnish-cache.org/ubuntu/ precise varnish-3.0" | sudo tee -a /etc/apt/sources.list

sudo apt-get update

Doing a update will result in below error.

W: The repository 'http://repo.varnish-cache.org/ubuntu precise Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://repo.varnish-cache.org/ubuntu/dists/precise/varnish-3.0/binary-amd64/Packages  410  repo [IP: 176.58.90.154 80]
E: Some index files failed to download. They have been ignored, or old ones used instead.

Not sure both the approaches are correct as both are giving some errors.


问:
Kentor AuthServices Sending AuthnRequests Asp.Net Core
I have an Asp.Net Core web application in which I'm currently in the process of implementing a SP-initiated SSO using Kentor AuthServices. Now, I received the metadata file from the idP in the following format:

```<code><?xml version="1.0" encoding="UTF-8"?>
<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
 xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
 entityID="https://exampleidp.com">
<md:IDPSSODescriptor
 protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
<md:KeyDescriptor use="signing">
   <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
      <X509Data>
         <X509Certificate>ExampleCertificate</X509Certificate>
      </X509Data>
   </KeyInfo>
</md:KeyDescriptor>
<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified
</md:NameIDFormat>
<md:SingleSignOnService
 Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
 Location="https://exampleidp.com/loginpage"/>
<md:SingleLogoutService
 Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
 Location="https://exampleidp.com/logoutpage"/>
<saml:Attribute Name="accountID"
 NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
 FriendlyName="accountID"/>
<saml:Attribute Name="email"
 NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
 FriendlyName="email"/>
<saml:Attribute Name="firstName"
 NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
 FriendlyName="firstName"/>
<saml:Attribute Name="lastName"
 NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
 FriendlyName="lastName"/>
</md:IDPSSODescriptor>
<md:ContactPerson contactType="technical">
   <md:GivenName>Exampleidp</md:GivenName>
   <md:SurName>Support</md:SurName>
   <md:EmailAddress>exampleidp.support@exampleidp.com</md:EmailAddress>
</md:ContactPerson>
<md:Organization>
   <md:OrganizationName xml:lang="en">Example Idp</md:OrganizationName>
   <md:OrganizationDisplayName xml:lang="en">Example Idp</md:OrganizationDisplayName>
   <md:OrganizationURL xml:lang="en">http://exampleidp.com/</md:OrganizationURL>
</md:Organization>
</md:EntityDescriptor>
</code>```

along with two certificates for signing. In my Startup.cs I have added the following code snippet in ConfigureServices:

```<code>.AddSaml2(options =>
        {
            options.SPOptions.EntityId = new EntityId("http://myapp.com");
            options.IdentityProviders.Add(
                new IdentityProvider(
                    new EntityId("myapp.com/Metadata.xml"), options.SPOptions)
                {
                    LoadMetadata = true
                });
        })
</code>```

and the following code snippet in Configure:

```<code>app.UseAuthentication();
</code>```

UPDATE

After looking through the source code more I was finally able to wrap my head around and generate AuthnRequests like the following (which I verified with the idP):

```<code><saml2p:AuthnRequest xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
 xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"
 ID="idcc70905185a04a94b05282e0c544e086" Version="2.0" IssueInstant="2017-
 11-13T14:47:56Z"
 ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
 AssertionConsumerServiceURL="http://myapp.com/saml">
    <saml2:Issuer>http://myapp.com</saml2:Issuer>
    <saml2p:NameIDPolicy Format="urn:oasis:names:tc:SAML:1.1:nameid-
     format:unspecified" AllowCreate="true" />
</saml2p:AuthnRequest>
</code>```

EDIT: My main concern now is how I need to send the AuthnRequest to the idP. It appears, if I'm on the right track, that I need to deflate and encode the AuthnRequest in order for the idP to properly handle it. I'm wondering how I might go about achieving this (it also looks like I may need to include RelayState information?) either using existing Kentor code or possibly it's easy enough to do myself?

答:
FINAL UPDATE WITH ANSWER: After much research and poking around I was finally able to resolve what ended up being my last issue which was setting the AuthnRequest to the proper deflated and base64 encoded string that needed to be sent to the idP. I achieved this using the following chunk of code:

```<code>var param = "";
        var bytes = Encoding.UTF8.GetBytes(authnRequest.ToXElement().ToString());
        using (var output = new MemoryStream())
        {
            using (var zip = new DeflateStream(output, CompressionMode.Compress))
            {
                zip.Write(bytes, 0, bytes.Length);
            }
            var base64String = Convert.ToBase64String(output.ToArray());
            param =  HttpUtility.UrlEncode(base64String);
        }
</code>```

which triggered the proper response by the idP so I am now able to properly trigger a SSO for my SP and grab the response values from the idP.

Body:
I have an Asp.Net Core web application in which I'm currently in the process of implementing a SP-initiated SSO using Kentor AuthServices. Now, I received the metadata file from the idP in the following format:

<?xml version="1.0" encoding="UTF-8"?>
<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
 xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
 entityID="https://exampleidp.com">
<md:IDPSSODescriptor
 protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
<md:KeyDescriptor use="signing">
   <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
      <X509Data>
         <X509Certificate>ExampleCertificate</X509Certificate>
      </X509Data>
   </KeyInfo>
</md:KeyDescriptor>
<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified
</md:NameIDFormat>
<md:SingleSignOnService
 Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
 Location="https://exampleidp.com/loginpage"/>
<md:SingleLogoutService
 Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
 Location="https://exampleidp.com/logoutpage"/>
<saml:Attribute Name="accountID"
 NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
 FriendlyName="accountID"/>
<saml:Attribute Name="email"
 NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
 FriendlyName="email"/>
<saml:Attribute Name="firstName"
 NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
 FriendlyName="firstName"/>
<saml:Attribute Name="lastName"
 NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
 FriendlyName="lastName"/>
</md:IDPSSODescriptor>
<md:ContactPerson contactType="technical">
   <md:GivenName>Exampleidp</md:GivenName>
   <md:SurName>Support</md:SurName>
   <md:EmailAddress>exampleidp.support@exampleidp.com</md:EmailAddress>
</md:ContactPerson>
<md:Organization>
   <md:OrganizationName xml:lang="en">Example Idp</md:OrganizationName>
   <md:OrganizationDisplayName xml:lang="en">Example Idp</md:OrganizationDisplayName>
   <md:OrganizationURL xml:lang="en">http://exampleidp.com/</md:OrganizationURL>
</md:Organization>
</md:EntityDescriptor>

along with two certificates for signing. In my Startup.cs I have added the following code snippet in ConfigureServices:

.AddSaml2(options =>
        {
            options.SPOptions.EntityId = new EntityId("http://myapp.com");
            options.IdentityProviders.Add(
                new IdentityProvider(
                    new EntityId("myapp.com/Metadata.xml"), options.SPOptions)
                {
                    LoadMetadata = true
                });
        })

and the following code snippet in Configure:

app.UseAuthentication();

UPDATE

After looking through the source code more I was finally able to wrap my head around and generate AuthnRequests like the following (which I verified with the idP):

<saml2p:AuthnRequest xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"
 xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"
 ID="idcc70905185a04a94b05282e0c544e086" Version="2.0" IssueInstant="2017-
 11-13T14:47:56Z"
 ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
 AssertionConsumerServiceURL="http://myapp.com/saml">
    <saml2:Issuer>http://myapp.com</saml2:Issuer>
    <saml2p:NameIDPolicy Format="urn:oasis:names:tc:SAML:1.1:nameid-
     format:unspecified" AllowCreate="true" />
</saml2p:AuthnRequest>

EDIT: My main concern now is how I need to send the AuthnRequest to the idP. It appears, if I'm on the right track, that I need to deflate and encode the AuthnRequest in order for the idP to properly handle it. I'm wondering how I might go about achieving this (it also looks like I may need to include RelayState information?) either using existing Kentor code or possibly it's easy enough to do myself?

Body:
FINAL UPDATE WITH ANSWER: After much research and poking around I was finally able to resolve what ended up being my last issue which was setting the AuthnRequest to the proper deflated and base64 encoded string that needed to be sent to the idP. I achieved this using the following chunk of code:

var param = "";
        var bytes = Encoding.UTF8.GetBytes(authnRequest.ToXElement().ToString());
        using (var output = new MemoryStream())
        {
            using (var zip = new DeflateStream(output, CompressionMode.Compress))
            {
                zip.Write(bytes, 0, bytes.Length);
            }
            var base64String = Convert.ToBase64String(output.ToArray());
            param =  HttpUtility.UrlEncode(base64String);
        }

which triggered the proper response by the idP so I am now able to properly trigger a SSO for my SP and grab the response values from the idP.


问:
Heroku Hobby server still sleeps or issue with NodeJS?
I've noticed that my NodeJS application which resides on a Heroku Hobby server after no activity does a "soft restart". By that I mean it doesn't do big actions like reinitialize the ORM system or recreates the HTTP server, however it does seem to forget callback functions and global variables or any variables that were dynamically created and held in memory.

Does Heroku still "sleep" even with the Hobby plan or is it something related to NodeJS?

答:
As indicated by Heroku's documentation, Hobby dynos do not sleep.

However, dynos of all types are restarted frequently:

Automatic dyno restarts

The dyno manager restarts all your app’s dynos whenever you:

create a new release by deploying new code

change your config vars

change your add-ons

run heroku restart

Dynos are also restarted (cycled) at least once per day to help maintain the health of applications running on Heroku. Any changes to the local filesystem will be deleted.

I'm not entirely clear what you mean by

it does seem to forget callback functions and global variables or any variables that were dynamically created and held in memory

but at least some of these things could happen due to automatic dyno restarts. Certainly anything that only exists in memory will be lost.

You could manually restart your dynos using heroku ps:restart and see if that replicates the behaviour you are seeing. You may need to adjust your code to survive being restarted.


问:
Warning when presenting a UIViewController
I am creating another instance my main view controller and presenting it.

```<code>MainViewController *sm = [[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];
[self presentModalViewController:sm animated:NO];
[sm release];
</code>```

This gives the following errors

warning: receiver 'MainViewController' is a forward class and corresponding @interface may not exist

warning: incompatible Objective-C types 'struct MainViewController *', expected 'struct UIViewController *' when passing argument 1 of 'presentModalViewController:animated:' from distinct Objective-C type

What am I doing wrong? How can I present the current version of MainViewController that exists?

答:
You have a forward declaration in your header file

```<code>@class MainViewController;
</code>```

but you do not import the header file in your implementation file.

Add

```<code>#import "MainViewController.h"
</code>```

to the top of the .m file.

Body:
I am creating another instance my main view controller and presenting it.

MainViewController *sm = [[MainViewController alloc]initWithNibName:@"MainViewController" bundle:nil];
[self presentModalViewController:sm animated:NO];
[sm release];

This gives the following errors

warning: receiver 'MainViewController' is a forward class and corresponding @interface may not exist

warning: incompatible Objective-C types 'struct MainViewController *', expected 'struct UIViewController *' when passing argument 1 of 'presentModalViewController:animated:' from distinct Objective-C type

What am I doing wrong? How can I present the current version of MainViewController that exists?

Body:
You have a forward declaration in your header file

@class MainViewController;

but you do not import the header file in your implementation file.

Add

#import "MainViewController.h"

to the top of the .m file.


问:
Bind to ViewModel from ContextMenu in ListBox Item
I have a ViewModel with a command 'OpenCommand', a flag 'IsConextMenuVisible' and an observable list 'Links'.

```<code>public ObservableList<string> Links { get; set; }
public bool IsContextMenuVisible { get; set; }
public ICommand OpenCommand { get; set; }
</code>```

in XAML i want the following to work.

```<code><ListBox ItemsSource="{Binding Links}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding}">
        <TextBlock.ContextMenu>
           <ContextMenu Visibility="{Binding IsContextMenuVisible, Converter={StaticResource BoolToVisibiltyHiddenConverter}}">
             <MenuItem Header="Open" Command="{Binding OpenCommand}" CommandParameter="{Binding}"/>
           </ContextMenu>
        </Textblock.ContextMenu>
      </TextBlock>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
</code>```

I've already tried some binding expressions for the inner bindings on the ContextMenu, but nothing seems to work. Something like:

```<code>Visibility="{Binding Path=DataContext.IsContextMenuVisible,
             Converter={StaticResource BoolToVisibilityCollapsedConverter},
             RelativeSource={RelativeSource AncestorType=ListBox}}"
</code>```

答:
This is "problematic" as the kids say because the context menu isn't in the visual tree, so no flavor of RelativeSource is going to work.

You can often bind to properties of PlacementTarget, but in this case you need a visual ancestor of the PlacementTarget, and RelativeSource won't do an ancestor of something else.

In WPF, when there's a gap in the visual tree, the last ditch option is always a BindingProxy. Here's what that class looks like (including the URL of the StackOverflow question I stole it from -- that class has been copied and pasted around many, many questions and answers on this site):

```<code>//  https://stackoverflow.com/questions/24452264/bindingproxy-binding-to-the-indexed-property
public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}
</code>```

And you would use it like this. First create the BindingProxy as a resource, in a location where it can "see" the desired element:

```<code><Window.Resources>
    <local:BoolToVisibiltyHiddenConverter x:Key="BoolToVisibiltyHiddenConverter" />

    <!-- {Binding} with no path will be the window's datacontext, the main viewmodel. -->
    <local:BindingProxy Data="{Binding}" x:Key="MainViewModelBindingProxy" />
</Window.Resources>
</code>```

And then use it for the Source of the binding. The desired DataContext will be the Data property of the proxy object, so provide paths relative to Data:

```<code><TextBlock.ContextMenu>
    <ContextMenu
        Visibility="{Binding Data.IsContextMenuVisible,
            Converter={StaticResource BoolToVisibiltyHiddenConverter},
             Source={StaticResource MainViewModelBindingProxy}}"
        >
        <MenuItem
            Header="Open"
            Command="{Binding OpenCommand}"
            CommandParameter="{Binding}"
            />
    </ContextMenu>
</TextBlock.ContextMenu>
</code>```

Now you've got another problem: The menu is still popping up. It just doesn't happen to be visible. If the user right clicks, it'll pop up invisibly, and suddenly appear when IsContextMenuVisible changes to true. That's not what you want.

You could omit the converter and just bind directly to ContextMenu.IsEnabled: It'll still pop up, but it'll be grayed out. This is consistent with common Windows UI practice.

You could also have a style trigger so that the TextBlock only has a ContextMenu when you want it to have one. Because that trigger is on the TextBlock, it's in the visual tree we can use a conventional RelativeSource for the binding.

```<code><TextBlock Text="{Binding}">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Style.Triggers>
                <DataTrigger
                    Binding="{Binding Data.IsContextMenuVisible,
                        RelativeSource={RelativeSource AncestorType=ListBox}}"
                    Value="True">
                    <Setter Property="ContextMenu">
                        <Setter.Value>
                            <ContextMenu >
                                <MenuItem
                                    Header="Open"
                                    Command="{Binding OpenCommand}"
                                    CommandParameter="{Binding}"
                                    />
                            </ContextMenu>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>
</code>```

Body:
I have a ViewModel with a command 'OpenCommand', a flag 'IsConextMenuVisible' and an observable list 'Links'.

public ObservableList<string> Links { get; set; }
public bool IsContextMenuVisible { get; set; }
public ICommand OpenCommand { get; set; }

in XAML i want the following to work.

<ListBox ItemsSource="{Binding Links}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding}">
        <TextBlock.ContextMenu>
           <ContextMenu Visibility="{Binding IsContextMenuVisible, Converter={StaticResource BoolToVisibiltyHiddenConverter}}">
             <MenuItem Header="Open" Command="{Binding OpenCommand}" CommandParameter="{Binding}"/>
           </ContextMenu>
        </Textblock.ContextMenu>
      </TextBlock>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

I've already tried some binding expressions for the inner bindings on the ContextMenu, but nothing seems to work. Something like:

Visibility="{Binding Path=DataContext.IsContextMenuVisible,
             Converter={StaticResource BoolToVisibilityCollapsedConverter},
             RelativeSource={RelativeSource AncestorType=ListBox}}"

Body:
This is "problematic" as the kids say because the context menu isn't in the visual tree, so no flavor of RelativeSource is going to work.

You can often bind to properties of PlacementTarget, but in this case you need a visual ancestor of the PlacementTarget, and RelativeSource won't do an ancestor of something else.

In WPF, when there's a gap in the visual tree, the last ditch option is always a BindingProxy. Here's what that class looks like (including the URL of the StackOverflow question I stole it from -- that class has been copied and pasted around many, many questions and answers on this site):

//  https://stackoverflow.com/questions/24452264/bindingproxy-binding-to-the-indexed-property
public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

And you would use it like this. First create the BindingProxy as a resource, in a location where it can "see" the desired element:

<Window.Resources>
    <local:BoolToVisibiltyHiddenConverter x:Key="BoolToVisibiltyHiddenConverter" />

    <!-- {Binding} with no path will be the window's datacontext, the main viewmodel. -->
    <local:BindingProxy Data="{Binding}" x:Key="MainViewModelBindingProxy" />
</Window.Resources>

And then use it for the Source of the binding. The desired DataContext will be the Data property of the proxy object, so provide paths relative to Data:

<TextBlock.ContextMenu>
    <ContextMenu
        Visibility="{Binding Data.IsContextMenuVisible,
            Converter={StaticResource BoolToVisibiltyHiddenConverter},
             Source={StaticResource MainViewModelBindingProxy}}"
        >
        <MenuItem
            Header="Open"
            Command="{Binding OpenCommand}"
            CommandParameter="{Binding}"
            />
    </ContextMenu>
</TextBlock.ContextMenu>

Now you've got another problem: The menu is still popping up. It just doesn't happen to be visible. If the user right clicks, it'll pop up invisibly, and suddenly appear when IsContextMenuVisible changes to true. That's not what you want.

You could omit the converter and just bind directly to ContextMenu.IsEnabled: It'll still pop up, but it'll be grayed out. This is consistent with common Windows UI practice.

You could also have a style trigger so that the TextBlock only has a ContextMenu when you want it to have one. Because that trigger is on the TextBlock, it's in the visual tree we can use a conventional RelativeSource for the binding.

<TextBlock Text="{Binding}">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Style.Triggers>
                <DataTrigger
                    Binding="{Binding Data.IsContextMenuVisible,
                        RelativeSource={RelativeSource AncestorType=ListBox}}"
                    Value="True">
                    <Setter Property="ContextMenu">
                        <Setter.Value>
                            <ContextMenu >
                                <MenuItem
                                    Header="Open"
                                    Command="{Binding OpenCommand}"
                                    CommandParameter="{Binding}"
                                    />
                            </ContextMenu>
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>


问:
Run cmd bat file in PHP
I am trying to run a .bat file from PHP in a WAMP server on Windows. Below is my code, the first "if" statement runs and prints "Successful" to the screen. So, the function "exec" is running, but no file has been copied. Any help or advice please.

```<code>// Function run bat file
private function run_bat(){

    $path = 'wamp\www\application\common\get_file.bat';
    $batchCmd = "C:\\".$path;
    echo "<br>".$batchCmd;
    //if(exec('cmd /c '.$batchCmd)){
    if(exec($batchCmd)){
        echo '<br>Successful';
        return TRUE;
    } else {
        echo '<br>Error in run bat';
        return FALSE;
    }
} // end function run bat file
</code>```

my bat file just copies one file to a new folder. The other file is on a networked drive.

答:
To run a bat script, you should use cmd /c filename. So you have to change the code to something like this

```<code>$batchCmd = "cmd /c C:\\" . $path;
</code>```

Title: Run cmd bat file in PHP

Body:
I am trying to run a .bat file from PHP in a WAMP server on Windows. Below is my code, the first "if" statement runs and prints "Successful" to the screen. So, the function "exec" is running, but no file has been copied. Any help or advice please.

// Function run bat file
private function run_bat(){

    $path = 'wamp\www\application\common\get_file.bat';
    $batchCmd = "C:\\".$path;
    echo "
".$batchCmd;
    //if(exec('cmd /c '.$batchCmd)){
    if(exec($batchCmd)){
        echo '
Successful';
        return TRUE;
    } else {
        echo '
Error in run bat';
        return FALSE;
    }
} // end function run bat file

my bat file just copies one file to a new folder. The other file is on a networked drive.

Body:
To run a bat script, you should use cmd /c filename. So you have to change the code to something like this

$batchCmd = "cmd /c C:\\" . $path;


问:
Convert datetime list from string format to datetime object
I am trying to convert list of datatime objects given in form a string to individual datetime objects.

```<code>e.g. x = "[datetime.datetime(2014, 12, 14, 0, 0), datetime.datetime(2015, 5, 4, 0, 0), datetime.datetime(2015, 5, 26, 0, 0), datetime.datetime(2015, 9, 26, 0, 0)]"
</code>```

I tried using 'ast.literal_eval(x)' and then I can use strftime to get the format, but ast.literal throws 'ValueError: malformed string' error.

How do I extract datetime from this ?

答:
ast.literal_eval() is specifically very limited in what types it supports. You'd be better off serialising your data to a different format, so don't use str(inputlist) but find some other serialisation.

If you are stuck with the current format, you could use a regex:

```<code>from datetime import datetime
import re

dt_constructor = re.compile(r'datetime\.datetime\((\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+)\)')

result = [datetime(*map(int, group)) for group in dt_constructor.findall(x)]
</code>```

The regular expression extracts the numeric arguments in the string for each datetime.datetime() call, and converts those to integers before passing them to the datetime() constructor.

Demo:

```<code>>>> from datetime import datetime
>>> import re
>>> dt_constructor = re.compile(r'datetime\.datetime\((\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+)\)')
>>> x = "[datetime.datetime(2014, 12, 14, 0, 0), datetime.datetime(2015, 5, 4, 0, 0), datetime.datetime(2015, 5, 26, 0, 0), datetime.datetime(2015, 9, 26, 0, 0)]"
>>> [datetime(*map(int, group)) for group in dt_constructor.findall(x)]
[datetime.datetime(2014, 12, 14, 0, 0), datetime.datetime(2015, 5, 4, 0, 0), datetime.datetime(2015, 5, 26, 0, 0), datetime.datetime(2015, 9, 26, 0, 0)]
</code>```

Body:
I am trying to convert list of datatime objects given in form a string to individual datetime objects.

e.g. x = "[datetime.datetime(2014, 12, 14, 0, 0), datetime.datetime(2015, 5, 4, 0, 0), datetime.datetime(2015, 5, 26, 0, 0), datetime.datetime(2015, 9, 26, 0, 0)]"

I tried using 'ast.literal_eval(x)' and then I can use strftime to get the format, but ast.literal throws 'ValueError: malformed string' error.

How do I extract datetime from this ?

Body:
ast.literal_eval() is specifically very limited in what types it supports. You'd be better off serialising your data to a different format, so don't use str(inputlist) but find some other serialisation.

If you are stuck with the current format, you could use a regex:

from datetime import datetime
import re

dt_constructor = re.compile(r'datetime\.datetime\((\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+)\)')

result = [datetime(*map(int, group)) for group in dt_constructor.findall(x)]

The regular expression extracts the numeric arguments in the string for each datetime.datetime() call, and converts those to integers before passing them to the datetime() constructor.

Demo:

>>> from datetime import datetime
>>> import re
>>> dt_constructor = re.compile(r'datetime\.datetime\((\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+)\)')
>>> x = "[datetime.datetime(2014, 12, 14, 0, 0), datetime.datetime(2015, 5, 4, 0, 0), datetime.datetime(2015, 5, 26, 0, 0), datetime.datetime(2015, 9, 26, 0, 0)]"
>>> [datetime(*map(int, group)) for group in dt_constructor.findall(x)]
[datetime.datetime(2014, 12, 14, 0, 0), datetime.datetime(2015, 5, 4, 0, 0), datetime.datetime(2015, 5, 26, 0, 0), datetime.datetime(2015, 9, 26, 0, 0)]


问:
Is there a way to turn TortoiseSVN using svn:mergeinfo off?
When I'm doing a TortoiseSVN merge, it includes a bunch of directories, and some files into the modified files, even though there are no actual changes.

It changes the property svn:mergeinfo.

Is there any reason why these properties set on the directory/files are needed? Is there any way to get around not doing these changes to svn:mergeinfo?

I usually just revert the items then commit, but this wastes extra time.

答:
The command given in Stack Overflow question Remove unnecessary svn:mergeinfo properties will remove any extra mergeinfo.

```<code>From the root of the project do:

svn propdel svn:mergeinfo -R
svn revert .
svn ci -m "Removed mergeinfo"
</code>```

OwnerDisplayName: Brian R. Bondy

LastEditorDisplayName: Brian R. Bondy

Body:
The command given in Stack Overflow question Remove unnecessary svn:mergeinfo properties will remove any extra mergeinfo.

From the root of the project do:

svn propdel svn:mergeinfo -R
svn revert .
svn ci -m "Removed mergeinfo"


问:
Cassandra phi_convict_threshold explained
Can anyone point me to a good explanation of how is phi_convict_threshold calculated in cassandra (not the one from datastax documentation but more detailed)? </p>

答: "Cassandra: The Definitive Guide, 2nd edition" has (IMHO) quite good description of it.  And it refers to original paper "The φ accrual failure detector"</p>


答:
You should probably run it like this

```<code>system("cmd /c C: path_to_your_file");
</code>```

in your case

```<code>system("cmd /c  $batchCmd ");
</code>```

or go for

```<code>exec("c:\WINDOWS\system32\cmd.exe /c START  $batchCmd" );
</code>```

Title: Run cmd bat file in PHP

Body:
You should probably run it like this

system("cmd /c C: path_to_your_file");

in your case

system("cmd /c  $batchCmd ");

or go for

exec("c:\WINDOWS\system32\cmd.exe /c START  $batchCmd" );


问:
MySQL query for maximum duplicate value(s)
```<code>| b_id |
+------+
|   10 |
|   10 |
|   20 |
|   30 |
|   40 |
|   40 |
|   70 |
|   40 |
|   10 |
</code>```

Very Similar to mysql query for maximum duplicate value I need the b_id(s) that have the most entries.

The posted solution

```<code>select b_id, count(b_id)
from books
group by b_id
order by count(b_id) desc
limit 1;
</code>```

doesn't work for me, as it only shows one of the b_ids that repeat the maximum number of time.
My required result here is

```<code>| b_id | reps |
+------+------+
|   10 |    3 |
|   40 |    3 |
</code>```

答:
Try this.. </p>

```<code> select b_id, count(b_id)
    from books
    group by b_id
    having count(b_id) = (select count(b_id) as count_bid from books group by b_id order by count_bid desc limit 1)
</code>```

Body:
| b_id |
+------+
|   10 |
|   10 |
|   20 |
|   30 |
|   40 |
|   40 |
|   70 |
|   40 |
|   10 |

Very Similar to mysql query for maximum duplicate value I need the b_id(s) that have the most entries.

The posted solution

select b_id, count(b_id)
from books
group by b_id
order by count(b_id) desc
limit 1;

doesn't work for me, as it only shows one of the b_ids that repeat the maximum number of time.
My required result here is

| b_id | reps |
+------+------+
|   10 |    3 |
|   40 |    3 |

Body:
Try this..

 select b_id, count(b_id)
    from books
    group by b_id
    having count(b_id) = (select count(b_id) as count_bid from books group by b_id order by count_bid desc limit 1)


问:
How to use an iterator to print class objects in a list
I currently have a program that creates an object. I can see that the object is successfully created with a describe method I have. I put this object into a list by doing this:

```<code>list<GameObject*> roomObjects5;
auto * obj1 = new GameObject(&o1name,&o1desc,&o1key);
roomObjects5.push_back(obj1);
</code>```

I'm now trying to print through this list called roomObjects 5 using an iterator:

```<code>  void print(const list<GameObject>& s) {
        list<GameObject>::iterator i;
        for( i = s.front(); i != s.end(); ++i)
            cout << *i << " ";

        cout << endl;
    }
</code>```

However there is an error

class 'const gameObject' is not compatible with
  class'list::iterator

and

Binary operator '<<' cant be applied to the expressions 'ostream' and
  'GameObject'

and when I run I get the error:

error: a function-definition is not allowed here before '{' token
     void print(const list& s) {
                                           ^

mingw32-make.exe[3]: * [CMakeFiles/textadv.dir/main.cpp.obj] Error 1
  CMakeFiles\textadv.dir\build.make:61: recipe for target
  'CMakeFiles/textadv.dir/main.cpp.obj' failed mingw32-make.exe[2]:
  [CMakeFiles/textadv.dir/all] Error 2 CMakeFiles\Makefile2:66: recipe
  for target 'CMakeFiles/textadv.dir/all' failed mingw32-make.exe[1]:
   [CMakeFiles/textadv.dir/rule] Error 2 CMakeFiles\Makefile2:78: recipe for target 'CMakeFiles/textadv.dir/rule' failed
  mingw32-make.exe: * [textadv] Error 2 Makefile:117: recipe for
  target 'textadv' failed

Could anyone help me please?

Updated:

```<code>> void print(const list<GameObject>& s) {
>     list<GameObject *>::iterator i;
>     for (i = s.front(); i != s.end(); ++i)
>         cout << *(*i) << " ";
>
>     cout << endl; }
</code>```

I'm now trying this and i'm getting the error

Class 'const GameObject' is not compatible with class
  'list::iterator'

Update 2:

I'm now trying this:

void print(const list& s) {
    list::iterator i;

```<code>for(auto i = s.front(); i != s.end(); ++i)
    cout << *(*i) << " ";
    cout << endl;
</code>```

}

and getting errors with the

```<code>i != s.end
</code>```

line

'cant compare structures'

and

```<code>++i
</code>```

Expression of type GameObject is neither numeric nor a pointer

and

```<code>*(*i)
</code>```

'Pointer type is required'

答:
As per the documentation on list::front():

Returns a reference to the first element in the list container.

Unlike member list::begin, which returns an iterator to this same element, this function returns a direct reference.

Calling this function on an empty container causes undefined behavior.

Instead of using front() use begin() which returns the iterator. Moreover,
you are passing const list<GameObject>& and your original list is list<GameObject*>. Your function cannot accept your list. The code would look like:

```<code> void print(const list<GameObject*>& s) {
     for (auto i = s.begin(); i != s.end(); ++i)
          cout << *(*i) << " ";
     cout << endl;
 }
</code>```

Update: it seems you are not overloading ostream& operator << (ostream& out, GameObject& gObj). You should define it:

```<code>ostream& operator << (ostream& out, GameObject& gObj){
    out << gObj.(whatever you want to print out from GameObject);
    return out;
}
</code>```

Update 2:

I have made a dummy code for testing and it is working correctly:

```<code>#include <iostream>
#include <list>

using namespace std;

class Noob {
public:
  int bad_data;
};

ostream& operator << (ostream& s, Noob& noob) {
  s << noob.bad_data;
  return s;
}

void print(const list<Noob*> list) {
  for (auto i = list.begin(); i != list.end(); ++i)
    cout << *(*i) << " ";
}

int main() {
  list<Noob*> list;
  for (int i = 0; i < 10; i++)
    list.push_back(new Noob());

  print(list);
  return 0;
}
</code>```

Ouput:

```<code>0 0 0 0 0 0 0 0 0 0
</code>```

Body:
I currently have a program that creates an object. I can see that the object is successfully created with a describe method I have. I put this object into a list by doing this:

list<GameObject*> roomObjects5;
auto * obj1 = new GameObject(&o1name,&o1desc,&o1key);
roomObjects5.push_back(obj1);

I'm now trying to print through this list called roomObjects 5 using an iterator:

  void print(const list<GameObject>& s) {
        list<GameObject>::iterator i;
        for( i = s.front(); i != s.end(); ++i)
            cout << *i << " ";

        cout << endl;
    }

However there is an error

class 'const gameObject' is not compatible with
  class'list::iterator

and

Binary operator '<<' cant be applied to the expressions 'ostream' and
  'GameObject'

and when I run I get the error:

error: a function-definition is not allowed here before '{' token
     void print(const list& s) {
                                           ^

mingw32-make.exe[3]: * [CMakeFiles/textadv.dir/main.cpp.obj] Error 1
  CMakeFiles\textadv.dir\build.make:61: recipe for target
  'CMakeFiles/textadv.dir/main.cpp.obj' failed mingw32-make.exe[2]:
  [CMakeFiles/textadv.dir/all] Error 2 CMakeFiles\Makefile2:66: recipe
  for target 'CMakeFiles/textadv.dir/all' failed mingw32-make.exe[1]:
   [CMakeFiles/textadv.dir/rule] Error 2 CMakeFiles\Makefile2:78: recipe for target 'CMakeFiles/textadv.dir/rule' failed
  mingw32-make.exe: * [textadv] Error 2 Makefile:117: recipe for
  target 'textadv' failed

Could anyone help me please?

Updated:

> void print(const list<GameObject>& s) {
>     list<GameObject *>::iterator i;
>     for (i = s.front(); i != s.end(); ++i)
>         cout << *(*i) << " ";
>
>     cout << endl; }

I'm now trying this and i'm getting the error

Class 'const GameObject' is not compatible with class
  'list::iterator'

Update 2:

I'm now trying this:

void print(const list& s) {
    list::iterator i;

for(auto i = s.front(); i != s.end(); ++i)
    cout << *(*i) << " ";
    cout << endl;

}

and getting errors with the

i != s.end

line

'cant compare structures'

and

++i

Expression of type GameObject is neither numeric nor a pointer

and

*(*i)

'Pointer type is required'

Body:
As per the documentation on list::front():

Returns a reference to the first element in the list container.

Unlike member list::begin, which returns an iterator to this same element, this function returns a direct reference.

Calling this function on an empty container causes undefined behavior.

Instead of using front() use begin() which returns the iterator. Moreover,
you are passing const list<GameObject>& and your original list is list<GameObject*>. Your function cannot accept your list. The code would look like:

 void print(const list<GameObject*>& s) {
     for (auto i = s.begin(); i != s.end(); ++i)
          cout << *(*i) << " ";
     cout << endl;
 }

Update: it seems you are not overloading ostream& operator << (ostream& out, GameObject& gObj). You should define it:

ostream& operator << (ostream& out, GameObject& gObj){
    out << gObj.(whatever you want to print out from GameObject);
    return out;
}

Update 2:

I have made a dummy code for testing and it is working correctly:

#include <iostream>
#include <list>

using namespace std;

class Noob {
public:
  int bad_data;
};

ostream& operator << (ostream& s, Noob& noob) {
  s << noob.bad_data;
  return s;
}

void print(const list<Noob*> list) {
  for (auto i = list.begin(); i != list.end(); ++i)
    cout << *(*i) << " ";
}

int main() {
  list<Noob*> list;
  for (int i = 0; i < 10; i++)
    list.push_back(new Noob());

  print(list);
  return 0;
}

Ouput:

0 0 0 0 0 0 0 0 0 0


问:
Node Sass couldn't find a binding for your current environment
I am having issues building an app because node-sass keeps failing with the error.

ERROR in Missing binding /Users/warren/Sites/random-docs/my-cms/node_modules/node-sass/vendor/darwin-x64-11/binding.node

  Node Sass could not find a binding for your current environment: OS X 64-bit with Node 0.10.x

I have tried running

```<code>npm rebuild node-sass
</code>```

which says

Binary is fine; exiting.

When running node -v I get v6.2.2

Which is different to what the sass error says "Node 0.10.x". I can't figure out why it is getting the wrong version. I have also tried removing the node_modules folder and running npm update or npm install, both of which did not resolve the issue. Any ideas?

答:
For people that switched to nvm from system node, if you haven't removed the ~/.npm and ~/.node-gyp folder this problem can arise since perhaps the node version within ~/.node-gyp could be different.

In any case those folders should be removed.

Body:
I am having issues building an app because node-sass keeps failing with the error.

ERROR in Missing binding /Users/warren/Sites/random-docs/my-cms/node_modules/node-sass/vendor/darwin-x64-11/binding.node

  Node Sass could not find a binding for your current environment: OS X 64-bit with Node 0.10.x

I have tried running

npm rebuild node-sass

which says

Binary is fine; exiting.

When running node -v I get v6.2.2

Which is different to what the sass error says "Node 0.10.x". I can't figure out why it is getting the wrong version. I have also tried removing the node_modules folder and running npm update or npm install, both of which did not resolve the issue. Any ideas?


问:
Passing messages to the view
I use Alertify.js to display confirmation messages, etc. in my views. I've been struggling to find a good way to pass the message from controller to view.

I have a janky-feeling setup using TempData that works, but only if I'm returning a view, rather than a redirect, which is pretty useless.

I was initially going to add this capability to a base viewmodel, but RedirectToAction doesn't support passing viewmodels.

I either need to make the TempData stick around longer or use a different process entirely.

What I use now:

```<code>public class AlertifyMessages
{
    public List<AlertifyMessage> Messages { get; private set; } = new List<AlertifyMessage>();
    public void Add(AlertifyType type, string message, string callbackUrl = null)
    {
        Messages.Add(new AlertifyMessage(type, message, callbackUrl));
    }
}

public class AlertifyMessage
{
    public AlertifyType Type { get; set; }
    public string Message { get; set; }
    public string CallbackUrl { get; set; }
    public AlertifyMessage(AlertifyType type, string message, string callbackUrl)
    {
        Type = type;
        Message = message;
        CallbackUrl = callbackUrl;
    }
}

public enum AlertifyType
{
    Log,
    Error,
    Success
}

/// <summary>
/// Applies Alertify messages to TempData after action method runs
/// <para>Can only be used with <see cref="BaseController"/></para>
/// </summary>
public class AlertifyAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        BaseController bc = (BaseController)context.Controller;
        bc.TempData["Alertify"] = bc.AlertifyMessages;
    }
}

[Alertify]
public class BaseController : Controller
{
    public BaseController()
    {
        AlertifyMessages = new AlertifyMessages();
    }

    public AlertifyMessages AlertifyMessages { get; set; }
}
</code>```

Usage:

```<code>public class MyController : BaseController
{
    public ActionResult Index()
    {
        AlertifyMessages.Add(AlertifyType.Success, "Yay!", Url.Action("Index"));
        return View(/*new ViewModel()*/);
    }
}
// Then loop through and display messages in view using TempData
</code>```

Edit

The accepted answer is correct, but to avoid tons of refactoring, I just added another filter to my attribute, below:

```<code>private const string alertify = "Alertify";
public override void OnActionExecuting(ActionExecutingContext context)
{
    BaseController bc = (BaseController)context.Controller;
    bc.Messages = (bc.TempData[alertify] == null) ? new AlertifyMessages() : (AlertifyMessages)bc.TempData[alertify];
    // Faster? Better? Harder? Stronger?
    //bc.Messages = (AlertifyMessages)bc.TempData[alertify] ?? new AlertifyMessages();
}
</code>```

答:
With your current code the OnResultExecuting will be executed 2 times in the course of your redirect.

Let's say you are doing redirect like this,

```<code>public ActionResult Save(SomeViewModel model)
{
    AlertifyMessages.Add(AlertifyType.Success, "Yay!", Url.Action("Index"));
    return RedirectToAction("Index");
}
public ActionResult Index()
{
    return View();
}
</code>```

Here when you return a result from the Save action method, it will executes the OnResultExecuting method of your AlertifyMessages filter whichs read the AlertifyMessages property value of the controller and set that to TempData.

Now since it is a redirect response, your browser will issue a new GET request to Index action, And for that action method also, it will execute the code inside OnResultExecuting and it will try to read the AlertifyMessages property and set that to TempData. But now your AlertifyMessages does not have any value because you did not set that in your Index action method. Remember Http is stateless. Index action method call here is like a totally new call and that call will create a new instance of the controller.

The solution is to reinitialize the AlertifyMessages property value. You can read it from the TempData

```<code>public ActionResult Index()
{
    AlertifyMessages = TempData["Alertify"] as AlertifyMessages;
    return View();
}
</code>```

Title: Passing messages to the view

Body:
I use Alertify.js to display confirmation messages, etc. in my views. I've been struggling to find a good way to pass the message from controller to view.

I have a janky-feeling setup using TempData that works, but only if I'm returning a view, rather than a redirect, which is pretty useless.

I was initially going to add this capability to a base viewmodel, but RedirectToAction doesn't support passing viewmodels.

I either need to make the TempData stick around longer or use a different process entirely.

What I use now:

public class AlertifyMessages
{
    public List<AlertifyMessage> Messages { get; private set; } = new List<AlertifyMessage>();
    public void Add(AlertifyType type, string message, string callbackUrl = null)
    {
        Messages.Add(new AlertifyMessage(type, message, callbackUrl));
    }
}

public class AlertifyMessage
{
    public AlertifyType Type { get; set; }
    public string Message { get; set; }
    public string CallbackUrl { get; set; }
    public AlertifyMessage(AlertifyType type, string message, string callbackUrl)
    {
        Type = type;
        Message = message;
        CallbackUrl = callbackUrl;
    }
}

public enum AlertifyType
{
    Log,
    Error,
    Success
}

///
/// Applies Alertify messages to TempData after action method runs
/// <para>Can only be used with <see cref="BaseController"/></para>
///
public class AlertifyAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        BaseController bc = (BaseController)context.Controller;
        bc.TempData["Alertify"] = bc.AlertifyMessages;
    }
}

[Alertify]
public class BaseController : Controller
{
    public BaseController()
    {
        AlertifyMessages = new AlertifyMessages();
    }

    public AlertifyMessages AlertifyMessages { get; set; }
}

Usage:

public class MyController : BaseController
{
    public ActionResult Index()
    {
        AlertifyMessages.Add(AlertifyType.Success, "Yay!", Url.Action("Index"));
        return View(/*new ViewModel()*/);
    }
}
// Then loop through and display messages in view using TempData

Edit

The accepted answer is correct, but to avoid tons of refactoring, I just added another filter to my attribute, below:

private const string alertify = "Alertify";
public override void OnActionExecuting(ActionExecutingContext context)
{
    BaseController bc = (BaseController)context.Controller;
    bc.Messages = (bc.TempData[alertify] == null) ? new AlertifyMessages() : (AlertifyMessages)bc.TempData[alertify];
    // Faster? Better? Harder? Stronger?
    //bc.Messages = (AlertifyMessages)bc.TempData[alertify] ?? new AlertifyMessages();
}

Body:
With your current code the OnResultExecuting will be executed 2 times in the course of your redirect.

Let's say you are doing redirect like this,

public ActionResult Save(SomeViewModel model)
{
    AlertifyMessages.Add(AlertifyType.Success, "Yay!", Url.Action("Index"));
    return RedirectToAction("Index");
}
public ActionResult Index()
{
    return View();
}

Here when you return a result from the Save action method, it will executes the OnResultExecuting method of your AlertifyMessages filter whichs read the AlertifyMessages property value of the controller and set that to TempData.

Now since it is a redirect response, your browser will issue a new GET request to Index action, And for that action method also, it will execute the code inside OnResultExecuting and it will try to read the AlertifyMessages property and set that to TempData. But now your AlertifyMessages does not have any value because you did not set that in your Index action method. Remember Http is stateless. Index action method call here is like a totally new call and that call will create a new instance of the controller.

The solution is to reinitialize the AlertifyMessages property value. You can read it from the TempData

public ActionResult Index()
{
    AlertifyMessages = TempData["Alertify"] as AlertifyMessages;
    return View();
}


问:
How can I restrict input into a TextInputCell in GWT?
I'm trying to restrict input into a GWT TextInputCell for things like monetary values, dates, SSNs, etc. I'd like to restrict the character that they can type in to the field using a regular expression (ideally). I'm guessing that the only way to do this is to override the onBrowserEvent method on the TextInputCell, but I haven't been able to get it to work.

What is the best way to mask my input cells?

答:
The onBrowserEvent method receives a NativeEvent, which has a preventDefault method. You probably want to call that preventDefault method whenever getKeyCode on the native event returns a character that you want to block.

See also the KeyCodes class, which can be handy for testing for special keys.


问:
access count number of records with criteria celebrity
i was looking for a solution for my problem for along time, i wish you help me
i have a table with a two column first is a name and two is a town i need to count Sarah from Egpyt how many it repeated but here is the trick i need the result like table 2 below is it possible</p>

```<code>Name    town
Sarah   Egypt
John    Germany
Mick    France
Sarah   Egypt
Sarah   USA
John    Germany
Mick    France
John    Germany

Name    town    duplicate
Sarah   Egypt      1
John    Germany    1
Mick    France     1
Sarah   Egypt      2
Sarah   USA        1
John    Germany    2
Mick    France     2
John    Germany    3
</code>```

答:
You can use this query :

```<code>SET @row_number:=1;
SET @name:='';
SET @town:='';
    SELECT @row_number:=CASE WHEN @name=name and @town=town THEN @row_number+1
      ELSE 1 END AS row_number, @name:=name, @town:=town
    FROM Table1 order by name, town;
</code>```

Check SQL HERE

Body:
i was looking for a solution for my problem for along time, i wish you help me
i have a table with a two column first is a name and two is a town i need to count Sarah from Egpyt how many it repeated but here is the trick i need the result like table 2 below is it possible

Name    town
Sarah   Egypt
John    Germany
Mick    France
Sarah   Egypt
Sarah   USA
John    Germany
Mick    France
John    Germany

Name    town    duplicate
Sarah   Egypt      1
John    Germany    1
Mick    France     1
Sarah   Egypt      2
Sarah   USA        1
John    Germany    2
Mick    France     2
John    Germany    3

Body:
You can use this query :

SET @row_number:=1;
SET @name:='';
SET @town:='';
    SELECT @row_number:=CASE WHEN @name=name and @town=town THEN @row_number+1
      ELSE 1 END AS row_number, @name:=name, @town:=town
    FROM Table1 order by name, town;

Check SQL HERE


问:
Which design pattern does Java Swing use?
To be clear, I'm not asking which design pattern to use in my program. I'm asking which design pattern has been used in the creation of the Swing library and the event system used within it. I'm currently studying a Bachelor of Information Technology, and one of the trial exam questions asked me to describe the Event Model used in swing, and then went on to elaborate that the specific pattern used is the Chain of Responsibility design pattern. However, after doing some research, I stumbled across this article:

https://www.developer.com/java/data/understanding-and-using-the-java-delegation-event-model.html

Which states that from Java 1.1 onwards (and we're up to Java 8 now, almost Java 9), the approach to event handling was based on the "delegation event model" instead. However, while the article is dated November 9, 2016, it made me wonder about the validity of its content, hence the question here. I was hoping some more experienced programmers could give an up to date, and concrete answer.

答:
If i understand correct your question
For example
Command designe pattern used in
Action (javax.swing.Action) </p>


问:
Vue.js validator isn't showing errors
Here's the prop's validator:

```<code>props: {
    task: {
      id: {
        type: Number,
        validator: function(value) {
          if (value < 5) {
            console.log("error");
            return false;
          }
          return true;
        }
      }
</code>```

here's the data I'm sending:

```<code>export default {
  name: "tasklist",
  data() {
    return {
      tasks: [
        {
          id: 1}
</code>```

According to the validator I made I shouldn't have it to pass without a warning.
And I don't get any warning does anyone knows what I can do to get an error there.

答:
You can't put a validator or specify the type of a specific property of a component's prop like you are trying to do.

You can specify the type of the task prop as Object, and then add a validator function to validate the type and value of the task object's id property.

Here's an example:

Vue.component('task', {
  template: `<div>{{ task.name }}</div>`,
  props: {
    task: {
      type: Object,
      validator(task) {
        if (typeof task.id !== 'number') {
          console.error("error: task id should be a number");
          return false;
        }

        if (task.id < 5) {
          console.error("error: task id should not be less than 5");
          return false;
        }
      }
    }
  }
})

new Vue({ el: '#app' })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.js"></script>
<div id="app">
  <task :task="{ name: 'foo', id: 1 }"></task>
  <task :task="{ name: 'bar', id: '9' }"></task>
  <task :task="{ name: 'baz', id: 6 }"></task>
</div></code>```

Title: Vue.js validator isn't showing errors

Body:
Here's the prop's validator:

props: {
    task: {
      id: {
        type: Number,
        validator: function(value) {
          if (value < 5) {
            console.log("error");
            return false;
          }
          return true;
        }
      }

here's the data I'm sending:

export default {
  name: "tasklist",
  data() {
    return {
      tasks: [
        {
          id: 1}

According to the validator I made I shouldn't have it to pass without a warning.
And I don't get any warning does anyone knows what I can do to get an error there.

Body:
You can't put a validator or specify the type of a specific property of a component's prop like you are trying to do.

You can specify the type of the task prop as Object, and then add a validator function to validate the type and value of the task object's id property.

Here's an example:

Vue.component('task', {
  template: `<div>{{ task.name }}</div>`,
  props: {
    task: {
      type: Object,
      validator(task) {
        if (typeof task.id !== 'number') {
          console.error("error: task id should be a number");
          return false;
        }

        if (task.id < 5) {
          console.error("error: task id should not be less than 5");
          return false;
        }
      }
    }
  }
})

new Vue({ el: '#app' })

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.js"></script>
<div id="app">
  <task :task="{ name: 'foo', id: 1 }"></task>
  <task :task="{ name: 'bar', id: '9' }"></task>
  <task :task="{ name: 'baz', id: 6 }"></task>
</div>


问:
How can I get the public IP and port my WCF service runs on?
I'm fairly new to WCF. I want to send the client an URL, which points to a file on the server, so the client can download\view it.

So my idea is that I add the relative path to the IP the service is listening on.

Like http://86.1.2.3:8123/myfolder/myfile.rar

The problem is, that every solution I found gives back

```<code>   localhost:someport/mysite
</code>```

Obviously, this is not really useful for the client.

Is there even a way to get the public IP from the code on which the service is hosted?

Or should I just include the address in the config file, and change it whenever the IP changes?

EDIT: Thanks for the quick help guys, I will just include it in the config file then.

答: Well, first of all, if you have no server application running (I.E Apache, etc), nothing will be able to connect to your endpoint. You may use a service like WAMP for this. Second, you need to forward whatever port you're using to be able to serve the file (this is done on your router config). No, there is no way to predict what the IP of the server it's connecting to is going to be ahead of time. This will have to be added to the client codebase manually. Finally, if this is going to be used in a production environment, I would STRONGLY recommend that you do not use something like WAMP, or a local environment at all, for something like this.</p>

Body:
I'm fairly new to WCF. I want to send the client an URL, which points to a file on the server, so the client can download\view it.

So my idea is that I add the relative path to the IP the service is listening on.

Like http://86.1.2.3:8123/myfolder/myfile.rar

The problem is, that every solution I found gives back

   localhost:someport/mysite

Obviously, this is not really useful for the client.

Is there even a way to get the public IP from the code on which the service is hosted?

Or should I just include the address in the config file, and change it whenever the IP changes?

EDIT: Thanks for the quick help guys, I will just include it in the config file then.


问:
html email with background-image style not shown
I am creating an email template which has to display images from external website. I had placed some  tags for rendering the images and there are some  tags with background-image property set in inline css of the elements.

Now, when an email is received in outlook, the images are not displayed (this is expected as the images are not embedded). And I click the download images to see the images properly. The images in  tag are only shown and the background-image for the  is not rendered.

Any views on solving this problem?

Thanks!

答: Background images are not supported in Outlook. As a best practice, you should never use background images in HTML emails. If you must have a background, you can use and image PLUS a solid color. Those with email clients that support background images will get the images, and those that don't support it will fall back to the solid color.</p>