问:
Can you write GOF Delegation code examples?
We're studying the GOF design patterns and are blocked on the first two paragraphs of delegation. We cannot agree what the code being described in the shown paragraphs would look like.

答:
I guess the main thing that makes this difficult to understand is this passage:

But with inheritance, an inherited operation can always refer to the receiving object through the this member variable in C++ and self in Smalltalk. To achieve the same effect with delegation, the receiver passes itself to the delegate to let the delegated operation refer to the receiver.

Quoting Wikipedia (emphasis mine):

In delegation, an object handles a request by delegating to a second object (the delegate). The delegate is a helper object, but with the original context. With language-level support for delegation, this is done implicitly by having self in the delegate refer to the original (sending) object, not the delegate (receiving object).

Whether it's actually self or this or current or caller is language specific. It means that in languages supporting delegation, the following would work:

```<code>Window
  int width: 640
  int height: 480
  Rectangle rectangle: new Rectangle()
  int Area(): rectangle.Area()

Rectangle
  int Area(): self.width * self.height

Window window: new Window()
print window.Area()
</code>```

This would print the result of 640x480 because the delegate executes Area within the context of the Window instance, although the code is in Rectangle. That is, it uses width and height from the Window through self.

In languages not supporting this automatic context passing, you would need to pass the caller to the delegate instead:

```<code>Window
  int width: 640
  int height: 480
  Rectangle rectangle: new Rectangle()
  int Area(): rectangle.Area(this)

Rectangle
  int Area(context): context.width * context.height

Window window: new Window()
print window.Area()
</code>```

When calling Area() we are passing the Window instance to the delegate (via  this). And the delegate then accesses the width and height members to do it's computation through the explicitly passed argument.

Note that the pseudo language above makes no assumptions about things like types or visibility and we assume we can simply pass around the Windows instance like this and access it's members. Depending on your language uses, your mileage may vary.

So Delegation is really about binding context and not about mere forwarding of method calls. Quoting the Wikipedia page one last time:

Note that "delegation" is often used loosely to refer to the distinct concept of forwarding, where the sending object simply uses the corresponding member on the receiving object, evaluated in the context of the receiving object, not the original object.

Body:
I guess the main thing that makes this difficult to understand is this passage:

But with inheritance, an inherited operation can always refer to the receiving object through the this member variable in C++ and self in Smalltalk. To achieve the same effect with delegation, the receiver passes itself to the delegate to let the delegated operation refer to the receiver.

Quoting Wikipedia (emphasis mine):

In delegation, an object handles a request by delegating to a second object (the delegate). The delegate is a helper object, but with the original context. With language-level support for delegation, this is done implicitly by having self in the delegate refer to the original (sending) object, not the delegate (receiving object).

Whether it's actually self or this or current or caller is language specific. It means that in languages supporting delegation, the following would work:

Window
  int width: 640
  int height: 480
  Rectangle rectangle: new Rectangle()
  int Area(): rectangle.Area()

Rectangle
  int Area(): self.width * self.height

Window window: new Window()
print window.Area()

This would print the result of 640x480 because the delegate executes Area within the context of the Window instance, although the code is in Rectangle. That is, it uses width and height from the Window through self.

In languages not supporting this automatic context passing, you would need to pass the caller to the delegate instead:

Window
  int width: 640
  int height: 480
  Rectangle rectangle: new Rectangle()
  int Area(): rectangle.Area(this)

Rectangle
  int Area(context): context.width * context.height

Window window: new Window()
print window.Area()

When calling Area() we are passing the Window instance to the delegate (via  this). And the delegate then accesses the width and height members to do it's computation through the explicitly passed argument.

Note that the pseudo language above makes no assumptions about things like types or visibility and we assume we can simply pass around the Windows instance like this and access it's members. Depending on your language uses, your mileage may vary.

So Delegation is really about binding context and not about mere forwarding of method calls. Quoting the Wikipedia page one last time:

Note that "delegation" is often used loosely to refer to the distinct concept of forwarding, where the sending object simply uses the corresponding member on the receiving object, evaluated in the context of the receiving object, not the original object.


来源: stackexchange

问:
Why this HashMap not formatted correctly in Jersey/Tomcat?
I'm testing Jersey, I wanted to mack a mock endpoint that produces this JSON object

```<code>{
   "Flight1" : 757,
   "Flight2" : 107,
   "Flight3" : 637,
}
</code>```

so I've written written this resource:

```<code>@GET
@Path("myjson")
@Produces(MediaType.APPLICATION_JSON)
public String getMyJson(@QueryParam ("test1") String lat, @QueryParam("test2") String lng) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("Flight 1", 765);
    map.put("Flight 2", 657);
    map.put("Flight 3", 908);
    return map.toString();
}
</code>```

But then I get this response when I call /myjson

{
       Flight 1=765,
       Flight 2=657,
       Flight 3=908
  }

Jersey already knows which element is a String and which element is an Integer, yet it format then as if they're all numbers.
Also the Json as it stands can not be formatted by the "pretty" formatter, and I believe this makes parsing it difficult by http clients.

So my question are:

Why is this happening?

How to avoid it and write simple mock JSON object for testing that is correctly formatted

答:
You can add the Jaxb annotations to serialize and deserialize the response object directly without converting. For this you need to add the jersey's jaxb library so that when you jersey environment is getting booted, it can enable the auto conversion feature.

Example:

```<code>@Path("jaxbResource")
@Produces("application/xml")
@Consumes("application/xml")
public class UserResource {
    @GET
    public User[] getUserArray() {
    List<User> userList = new ArrayList<User>();
    userList.add(new User(1, "John"));
    ………
    return userList.toArray(new User[userList.size()]);
    }
}

@XmlRootElement
public class User {
    private int id;
    private String name;

    public User() {}

    public User(int id,String name) {
        this.id = id;
        this.name = name;
    }
    ………
}
</code>```

Hope this helps!!!

ContentLicense: CC BY-SA 3.0

Body:
I'm testing Jersey, I wanted to mack a mock endpoint that produces this JSON object

{
   "Flight1" : 757,
   "Flight2" : 107,
   "Flight3" : 637,
}

so I've written written this resource:

@GET
@Path("myjson")
@Produces(MediaType.APPLICATION_JSON)
public String getMyJson(@QueryParam ("test1") String lat, @QueryParam("test2") String lng) {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("Flight 1", 765);
    map.put("Flight 2", 657);
    map.put("Flight 3", 908);
    return map.toString();
}

But then I get this response when I call /myjson

{
       Flight 1=765,
       Flight 2=657,
       Flight 3=908
  }

Jersey already knows which element is a String and which element is an Integer, yet it format then as if they're all numbers.
Also the Json as it stands can not be formatted by the "pretty" formatter, and I believe this makes parsing it difficult by http clients.

So my question are:

Why is this happening?

How to avoid it and write simple mock JSON object for testing that is correctly formatted

Body:
You can add the Jaxb annotations to serialize and deserialize the response object directly without converting. For this you need to add the jersey's jaxb library so that when you jersey environment is getting booted, it can enable the auto conversion feature.

Example:

@Path("jaxbResource")
@Produces("application/xml")
@Consumes("application/xml")
public class UserResource {
    @GET
    public User[] getUserArray() {
    List<User> userList = new ArrayList<User>();
    userList.add(new User(1, "John"));
    ………
    return userList.toArray(new User[userList.size()]);
    }
}

@XmlRootElement
public class User {
    private int id;
    private String name;

    public User() {}

    public User(int id,String name) {
        this.id = id;
        this.name = name;
    }
    ………
}

Hope this helps!!!


问:
How could I profile an .exe-wrapped Windows service written in Java
I want to profile an .exe-wrapped Windows Service that is written in Java EE and is deployed on JBoss 4.2.2 GA, which logs on as Local System. Wrapping was done by using the Tanuki Java service wrapper. My profiler of choice is jProfiler, which cannot detect the aforementioned service. So far, my question seems to be answered here, but to change the logon account of the service stops its proper functionality.

Is there a workaround on jProfiler or another profiler which could I use to profile this service?

答:
You can add VM parameters to a Tanuki service wrapper in wrapper.conf like this:

```<code>wrapper.java.additional.n=...
</code>```

To get the VM parameter for profiling, execute Session->Integration Wizards->New Remote Integration in the JProfiler GUI.

You can also use the "quick attach" functionality in JProfiler to profile a Windows service that is already running. JProfiler will list all services that are running on your local machine when you activate the "Show services" button in the top right corner of the attach dialog.

Body:
You can add VM parameters to a Tanuki service wrapper in wrapper.conf like this:

wrapper.java.additional.n=...

To get the VM parameter for profiling, execute Session->Integration Wizards->New Remote Integration in the JProfiler GUI.

You can also use the "quick attach" functionality in JProfiler to profile a Windows service that is already running. JProfiler will list all services that are running on your local machine when you activate the "Show services" button in the top right corner of the attach dialog.


问:
Firebase upload multiple images in swift
I want to upload multiple images with some text in firebase when user pushed the button. to do that I implemented for loop. Let's say if user picked 3 photos, then I think firebase should look like this

```<code> "Post": {
    "uid": {
      "Text": "some text",
      "imageUrl": "url",
      "imageUrl2": "url2",
      "imageUrl3": "url3"
    }
  }
</code>```

But it returns like this. That tweetImageUrl is the third photo's url which is picked last. also inside storage, there is only one photo which is the third photo as well.

How can I upload images correctly?
Here is my code.

```<code>    func sendTweets() {

         let text = textView.text
         let tweetLength = textView.text.count
         let imagesNumber = imagesArray.count
         format.dateFormat = "yyyy-MM-dd HH:mm"
         let strDate = format.string(from: date as Date)
         let childRef = ref.child("TWEETS").child(uid!).childByAutoId()
         let key = ref.child("TWEETS").child(uid!).childByAutoId().key
         let childStorageRef = storageRef.child("tweetImage").child(uid!).child(key)

  if(tweetLength>0 && imagesNumber>0)
    {

       for image in imagesArray {

        let tweetImage = image
        if let uploadData = UIImagePNGRepresentation(tweetImage) {

         childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if error != nil {
                        print("error")
        } else {

        if let imageUrl = metadata?.downloadURL()?.absoluteString {
          let values = ["Text": text!, "tweetImageUrl": imageUrl, "Date": strDate]  as [String : Any]
            childRef.updateChildValues(values)

              }
            }
          })
        }
      }
       dismiss(animated: true, completion: nil)
    }
         else if(tweetLength>0)
         {
            let values = ["Text": text!, "Date": strDate]  as [String : Any]

         childRef.updateChildValues(values)

         dismiss(animated: true, completion: nil)

         }

         else if(imagesNumber>0)
         {

        for image in imagesArray {

            let tweetImage = image
            if let uploadData = UIImagePNGRepresentation(tweetImage) {

             childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                if error != nil {
                    print("error")
                } else {

            if let imageUrl = metadata?.downloadURL()?.absoluteString {
            let values = ["tweetImageUrl": imageUrl, "Date": strDate]  as [String : Any]
            childRef.updateChildValues(values)
                }
             }
          })
        }
      }
        dismiss(animated: true, completion: nil)
  }  else {
        alertTheUser(title: "error", message: "enter something.")
    }
}//func
</code>```

Also when it comes to retrieve those images and display on the collection view after uploaded, is this proper way to achieve that?
Thank you in advance!

答:
I think this is not the right database structure that you should follow while using firebase.
If you store images like that say imageurl1, imageurl2..., etc. It would be really difficult to fetch those values without knowing the key for it.
I suggest you to follow a structure like

```<code>"Post": {
    "uid": {
      "Text": "some text",
      "images": {
         autoID1: url1,
         autoID2: url2
      }
    }
  }
</code>```

So It would be easy to fetch those URLs

You could append the URLs by using

```<code>let postRef = Database.database().reference(withPath: "Post").child(uid).child("images")
let autoID = postRef.childByAutoID().key
postRef.child(autoID).setValue(url)
</code>```

Body:
I want to upload multiple images with some text in firebase when user pushed the button. to do that I implemented for loop. Let's say if user picked 3 photos, then I think firebase should look like this

 "Post": {
    "uid": {
      "Text": "some text",
      "imageUrl": "url",
      "imageUrl2": "url2",
      "imageUrl3": "url3"
    }
  }

But it returns like this. That tweetImageUrl is the third photo's url which is picked last. also inside storage, there is only one photo which is the third photo as well.

How can I upload images correctly?
Here is my code.

    func sendTweets() {

         let text = textView.text
         let tweetLength = textView.text.count
         let imagesNumber = imagesArray.count
         format.dateFormat = "yyyy-MM-dd HH:mm"
         let strDate = format.string(from: date as Date)
         let childRef = ref.child("TWEETS").child(uid!).childByAutoId()
         let key = ref.child("TWEETS").child(uid!).childByAutoId().key
         let childStorageRef = storageRef.child("tweetImage").child(uid!).child(key)

  if(tweetLength>0 && imagesNumber>0)
    {

       for image in imagesArray {

        let tweetImage = image
        if let uploadData = UIImagePNGRepresentation(tweetImage) {

         childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if error != nil {
                        print("error")
        } else {

        if let imageUrl = metadata?.downloadURL()?.absoluteString {
          let values = ["Text": text!, "tweetImageUrl": imageUrl, "Date": strDate]  as [String : Any]
            childRef.updateChildValues(values)

              }
            }
          })
        }
      }
       dismiss(animated: true, completion: nil)
    }
         else if(tweetLength>0)
         {
            let values = ["Text": text!, "Date": strDate]  as [String : Any]

         childRef.updateChildValues(values)

         dismiss(animated: true, completion: nil)

         }

         else if(imagesNumber>0)
         {

        for image in imagesArray {

            let tweetImage = image
            if let uploadData = UIImagePNGRepresentation(tweetImage) {

             childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                if error != nil {
                    print("error")
                } else {

            if let imageUrl = metadata?.downloadURL()?.absoluteString {
            let values = ["tweetImageUrl": imageUrl, "Date": strDate]  as [String : Any]
            childRef.updateChildValues(values)
                }
             }
          })
        }
      }
        dismiss(animated: true, completion: nil)
  }  else {
        alertTheUser(title: "error", message: "enter something.")
    }
}//func

Also when it comes to retrieve those images and display on the collection view after uploaded, is this proper way to achieve that?
Thank you in advance!

Body:
I think this is not the right database structure that you should follow while using firebase.
If you store images like that say imageurl1, imageurl2..., etc. It would be really difficult to fetch those values without knowing the key for it.
I suggest you to follow a structure like

"Post": {
    "uid": {
      "Text": "some text",
      "images": {
         autoID1: url1,
         autoID2: url2
      }
    }
  }

So It would be easy to fetch those URLs

You could append the URLs by using

let postRef = Database.database().reference(withPath: "Post").child(uid).child("images")
let autoID = postRef.childByAutoID().key
postRef.child(autoID).setValue(url)


问:
Testing a Sinatra application that uses session
How to test Sinatra application which is using session?

```<code>get "/", {}, {'rack.session' =>  { 'foo' => 'blah' } }
</code>```

This code doesn't work for me, I have 'enable :sessions' in my app.

答:
Like Philip suggested, it would work better to manually set the session variable before the get request.</p>

```<code>session[:foo] = 'blah'
get "/"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How to test Sinatra application which is using session?

get "/", {}, {'rack.session' =>  { 'foo' => 'blah' } }

This code doesn't work for me, I have 'enable :sessions' in my app.

Body:
Like Philip suggested, it would work better to manually set the session variable before the get request.

session[:foo] = 'blah'
get "/"

ContentLicense: CC BY-SA 2.5


问:
Find the Max and Min element out of all the nested arrays in javascript
I have a array like so:

```<code>var arr = [[12,45,75], [54,45,2],[23,54,75,2]];
</code>```

I want to find out the largest element and the smallest element out of all the elements in the nested array:

The min should be: 2

and

Max should be 75

I tried the functions below but they do not work:

```<code>    function Max(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let max = Math.max.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.max.apply(window, arrs[i].filter(f)))>max) max=m;
        }
        return max;
    }
    function Min(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let min = Math.min.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.min.apply(window, arrs[i].filter(f)))>min) min=m;
        }
        return min;
    }
</code>```

It gives out Max as 75 and min as 12.

Any guidance will be appreciated.

Also tried other answers in SO but none help.

The answer at Merge/flatten an array of arrays in JavaScript? resolves the problem of merging arrays.

Whereas my problem is to keep the array as is and perform operations.

答:
A ES5 recursive approach by checking the type. It works for deep nested arrays.

var array = [[12, 45, 75], [54, 45, 2], [23, 54, 75, 2]],
    min = array.reduce(function min(a, b) {
        return Math.min(Array.isArray(a) ? a.reduce(min) : a, Array.isArray(b) ? b.reduce(min) : b);
    }),
    max = array.reduce(function max(a, b) {
        return Math.max(Array.isArray(a) ? a.reduce(max) : a, Array.isArray(b) ? b.reduce(max) : b);
    });

console.log(min, max);```
</div>
</div>
</p>

<p>With functions for using as callback.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function flat(f, v) { return Array.isArray(v) ? v.reduce(f) : v; }
function getMin(a, b) { return Math.min(flat(getMin, a), flat(getMin, b)); }
function getMax(a, b) { return Math.max(flat(getMax, a), flat(getMax, b)); }

var array = [[12, 45, 75], [54, 45, 2], [23, 54, 75, 2]],
    min = array.reduce(getMin),
    max = array.reduce(getMax);

console.log(min, max);</code>```

Body:
I have a array like so:

var arr = [[12,45,75], [54,45,2],[23,54,75,2]];

I want to find out the largest element and the smallest element out of all the elements in the nested array:

The min should be: 2

and

Max should be 75

I tried the functions below but they do not work:

    function Max(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let max = Math.max.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.max.apply(window, arrs[i].filter(f)))>max) max=m;
        }
        return max;
    }
    function Min(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let min = Math.min.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.min.apply(window, arrs[i].filter(f)))>min) min=m;
        }
        return min;
    }

It gives out Max as 75 and min as 12.

Any guidance will be appreciated.

Also tried other answers in SO but none help.

The answer at Merge/flatten an array of arrays in JavaScript? resolves the problem of merging arrays.

Whereas my problem is to keep the array as is and perform operations.

Body:
A ES5 recursive approach by checking the type. It works for deep nested arrays.

var array = [[12, 45, 75], [54, 45, 2], [23, 54, 75, 2]],
    min = array.reduce(function min(a, b) {
        return Math.min(Array.isArray(a) ? a.reduce(min) : a, Array.isArray(b) ? b.reduce(min) : b);
    }),
    max = array.reduce(function max(a, b) {
        return Math.max(Array.isArray(a) ? a.reduce(max) : a, Array.isArray(b) ? b.reduce(max) : b);
    });

console.log(min, max);

With functions for using as callback.

function flat(f, v) { return Array.isArray(v) ? v.reduce(f) : v; }
function getMin(a, b) { return Math.min(flat(getMin, a), flat(getMin, b)); }
function getMax(a, b) { return Math.max(flat(getMax, a), flat(getMax, b)); }

var array = [[12, 45, 75], [54, 45, 2], [23, 54, 75, 2]],
    min = array.reduce(getMin),
    max = array.reduce(getMax);

console.log(min, max);


问:
repeating values and names error in strings.xml and other resources files
repeated names i want to use in color.xml, same names i want to use for different colors, but throwing an error.

Error:Error: Found item
  Color/abc_btn_colored_borderless_text_material more than one time

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="abc_tint_btn_checkable">res/color/abc_tint_btn_checkable.xml</color>
    <color name="abc_tint_btn_checkable">res/color-v23/abc_tint_btn_checkable.xml</color>
    <color name="abc_tint_default">res/color/abc_tint_default.xml</color>
    <color name="abc_tint_default">res/color-v23/abc_tint_default.xml</color>
    <color name="abc_tint_edittext">res/color/abc_tint_edittext.xml</color>
    <color name="abc_tint_edittext">res/color-v23/abc_tint_edittext.xml</color>
</resources>
</code>```

答:
You can't use same name for different colors!

Just like your identity card no.!

Same card no. can't assign to different persons

Body:
repeated names i want to use in color.xml, same names i want to use for different colors, but throwing an error.

Error:Error: Found item
  Color/abc_btn_colored_borderless_text_material more than one time

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="abc_tint_btn_checkable">res/color/abc_tint_btn_checkable.xml</color>
    <color name="abc_tint_btn_checkable">res/color-v23/abc_tint_btn_checkable.xml</color>
    <color name="abc_tint_default">res/color/abc_tint_default.xml</color>
    <color name="abc_tint_default">res/color-v23/abc_tint_default.xml</color>
    <color name="abc_tint_edittext">res/color/abc_tint_edittext.xml</color>
    <color name="abc_tint_edittext">res/color-v23/abc_tint_edittext.xml</color>
</resources>


问:
react-native-fb sdk com.android.support dependency error
```<code> > A problem occurred configuring project ':react-native-fbsdk'.
  > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/<location_to_app>/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           newPtMobile:react-native-fbsdk:unspecified
</code>```

This issue started happening this morning when running react-native run-android without making any changes to the code or adding new packages, it was working fine untill now!

"react-native":"0.50.3", "react-native-fbsdk":"0.6.3"

I can see that I am missing android support libraries in my sdk/extras/android/m2repository/com/android/support subfolders, all the subfolders have the 26.0.0-alpha1 folder as the last one.
I already tried removing support repository and installing again through android studio and downloading the latest android_m2repository manually but the folders are still missing.

What I am having trouble understanding is why google's maven repository (https://dl.google.com/dl/android/maven2/index.html) states that under for example m2repository/com/android/support/appcompat-v7 I should have a folder named 27.0.2 (along with some previous versions which are also missing) but even in the latest android_m2repository which they offer it is also missing!

https://dl.google.com/android/repository/android_m2repository_r48.zip

答:
```<code>CUR_SPACE=.
culpritLocation=$CUR_SPACE/node_modules/react-native-fbsdk/android/build.gradle

sed -i -e 's/com.facebook.android:facebook-android-sdk:4.+/com.facebook.android:facebook-android-sdk:4.26.0/' $culpritLocation

printf "Fixed Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.\n> Could not find com.android.support:appcompat-v7:27.0.1."
printf "fix_rn_fbsdk_google_libraries.sh should be removed at a later time\n"
</code>```

Place the above script in the root of your react-native project, add executing permissions to it, then in package.json within the postinstall property add ./your-script-name.sh;. Ex:

```<code>{
  "name": "AppName",
  "version": "1.28.14",
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "postinstall": "./fix_rn_fbsdk_google_libraries.sh; ./infuse_version.sh;"
  },
  [..]
}
</code>```

If you're not familiar with postinstall scripts, they'll run immediately after running npm install / yarn command.

The proposed solution works with cloud build tools :) and it is only temporary. Future rn-fbsdk releases should fix the issue.

Body:
 > A problem occurred configuring project ':react-native-fbsdk'.
  > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/<location_to_app>/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           newPtMobile:react-native-fbsdk:unspecified

This issue started happening this morning when running react-native run-android without making any changes to the code or adding new packages, it was working fine untill now!

"react-native":"0.50.3", "react-native-fbsdk":"0.6.3"

I can see that I am missing android support libraries in my sdk/extras/android/m2repository/com/android/support subfolders, all the subfolders have the 26.0.0-alpha1 folder as the last one.
I already tried removing support repository and installing again through android studio and downloading the latest android_m2repository manually but the folders are still missing.

What I am having trouble understanding is why google's maven repository (https://dl.google.com/dl/android/maven2/index.html) states that under for example m2repository/com/android/support/appcompat-v7 I should have a folder named 27.0.2 (along with some previous versions which are also missing) but even in the latest android_m2repository which they offer it is also missing!

https://dl.google.com/android/repository/android_m2repository_r48.zip

Body:
CUR_SPACE=.
culpritLocation=$CUR_SPACE/node_modules/react-native-fbsdk/android/build.gradle

sed -i -e 's/com.facebook.android:facebook-android-sdk:4.+/com.facebook.android:facebook-android-sdk:4.26.0/' $culpritLocation

printf "Fixed Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.\n> Could not find com.android.support:appcompat-v7:27.0.1."
printf "fix_rn_fbsdk_google_libraries.sh should be removed at a later time\n"

Place the above script in the root of your react-native project, add executing permissions to it, then in package.json within the postinstall property add ./your-script-name.sh;. Ex:

{
  "name": "AppName",
  "version": "1.28.14",
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "postinstall": "./fix_rn_fbsdk_google_libraries.sh; ./infuse_version.sh;"
  },
  [..]
}

If you're not familiar with postinstall scripts, they'll run immediately after running npm install / yarn command.

The proposed solution works with cloud build tools :) and it is only temporary. Future rn-fbsdk releases should fix the issue.


问:
How do you cast a string representing a Lambda Expression to an System.LINQ.Expressions.Expression
I have a class with a property of type Expression<Func<T,bool>> and I want to set this property with a string like "m => m.A + m.B = m.C".

If I write this as new Type<T>(){propertyName = m => m.A + m.B = m.C} sets this property to a true return.

I want to be able to do this:

```<code>string s = "m => m.A + m.B = m.C";
Type<T> t = new Type<T>(){propertyName = s}

if(t.propertyName){//do something}
</code>```

I have a collection of strings representing these anonymous methods and wish to tests these dynamically based on selectable criteria.

答:
The following link has information about dynamic linq querying. Perhaps reflection over their DLLs might help out.
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Ultimately you will need to use the static factory methods on System.Linq.Expressions.Expression to build the expression.

I make 2 assumptions here:

You really want string s = m.A + m.B

A and B are both properties and not fields

Here is a test class to illustrate my example:

```<code>public class TestClass
{
    public string A { get; set; }
    public string B { get; set; }
}
</code>```

Here is a static class and method that would build the lambda expression, convert to Expression<Func<TestClass, string>>, then compile it to a Func<TestClass, string> that you can run just as any method call.

```<code>public static class TestHelper
{
    public static string GetString()
    {
        var testObject = new TestClass { A = "Hey", B = "Man" }; //Replace TestClass
        var type = testObject.GetType();
        var parameter = Expression.Parameter(type, "m");
        var property1 = Expression.Property(parameter, "A");
        var property2 = Expression.Property(parameter, "B");
        MethodInfo mi = typeof(string).GetMethod("Concat", new Type[] { typeof(string), typeof(string) });
        var concat = Expression.Call(mi, property1, property2);
        var lambda = Expression.Lambda<Func<TestClass, string>>(concat, parameter); //Replace TestClass

        var newFunction = lambda.Compile();
        string s = newFunction(testObject); //Replace TestClass
    }
}
</code>```

Body:
I have a class with a property of type Expression<Func<T,bool>> and I want to set this property with a string like "m => m.A + m.B = m.C".

If I write this as new Type<T>(){propertyName = m => m.A + m.B = m.C} sets this property to a true return.

I want to be able to do this:

string s = "m => m.A + m.B = m.C";
Type<T> t = new Type<T>(){propertyName = s}

if(t.propertyName){//do something}

I have a collection of strings representing these anonymous methods and wish to tests these dynamically based on selectable criteria.

Body:
The following link has information about dynamic linq querying. Perhaps reflection over their DLLs might help out.
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Ultimately you will need to use the static factory methods on System.Linq.Expressions.Expression to build the expression.

I make 2 assumptions here:

You really want string s = m.A + m.B

A and B are both properties and not fields

Here is a test class to illustrate my example:

public class TestClass
{
    public string A { get; set; }
    public string B { get; set; }
}

Here is a static class and method that would build the lambda expression, convert to Expression<Func<TestClass, string>>, then compile it to a Func<TestClass, string> that you can run just as any method call.

public static class TestHelper
{
    public static string GetString()
    {
        var testObject = new TestClass { A = "Hey", B = "Man" }; //Replace TestClass
        var type = testObject.GetType();
        var parameter = Expression.Parameter(type, "m");
        var property1 = Expression.Property(parameter, "A");
        var property2 = Expression.Property(parameter, "B");
        MethodInfo mi = typeof(string).GetMethod("Concat", new Type[] { typeof(string), typeof(string) });
        var concat = Expression.Call(mi, property1, property2);
        var lambda = Expression.Lambda<Func<TestClass, string>>(concat, parameter); //Replace TestClass

        var newFunction = lambda.Compile();
        string s = newFunction(testObject); //Replace TestClass
    }
}


问:
How to determine graphics capabilities of an x11 terminal window
The standard xterm program has a Tek4014 emulation for some simple graphics output. This is however not implemented in most (all?) sucessors, like rxvt, gnome-terminal, or kterm.

However, almost all X11 terminals report xterm as (part of) the environment variable TERM, which makes it difficult for a program to determine whether the underlying terminal has graphics capabilities.

Is it possible to find that out programmatically? And, are there modern terminal windows (beside xterm) that implement Tek4014 graphics, maybe as an add-on?

答:
Actually kterm provides Tek4014 emulation according to its menus.  You are probably referring to KDE konsole, which does not.  TeraTerm (a Windows application) reportedly also supports the feature.

Back to the point: there is no useful method for telling if a given terminal supports a given feature.  Some terminals return status information which tells what type of terminal it is, and what optional features it may have (based on the device responses from DEC and similar terminals).  The Tektronix terminal had no such status query/response (refer to XTerm Control Sequences).

Relying upon the status responses in any case doesn't give much assurance since some developers hard-code responses to match xterm.

Since the terminal will not tell you, the only way to verify that would be by actual inspection.  Someone might construct a program that could do screendumps and verify that the terminal responds to the sequences, but there's still the pitfall that the switching between vt100(or similar) and tek4014 may not be done with the same escape sequence used in xterm.  After all, that escape sequence is not in the standard repertoire of any hardware terminal.


问:
i am not able to query the sub document in mongodb
i am not able to query results in this query,
i want result based on detail.type (like fetch record where detail.type="one") and fetch only first 10 records in detail.numbers array       </p>

```<code>{
            "_id" : ObjectId("5a27b609e101b6092b4ebf91"),
            "city" : "Mumbai",
            "detail" : [
                {
                    "type" : "One",
                    "name" : "Some name",
                    "_id" : ObjectId("5a27b609e101b6092b4ebf92"),
                    "numbers" : [
                        "72598xxx78",
                        "81301xxx88",
                        "83302xxx30",
                        "84309xxx43",
                        "85309xxx77",
                        "86309xxx61",
                        "87270xxx88",
                        "85272xxx36",
                        "88272xxx23",
                        "85276xxx01"
                    ]
                },
                {
                    "name" : "Some name",
                    "type" : "two",
                    "_id" : ObjectId("5a28e954d4f5a30527d92a32"),
                    "contact" : [
                        "72598xxx78",
                        "81301xxx88",
                        "83302xxx30",
                        "84309xxx43",
                        "85309xxx77",
                        "86309xxx61",
                        "87270xxx88",
                        "85272xxx36",
                        "88272xxx23",
                        "85276xxx01"
                    ]
                },
    ]
    }
</code>```

答:
MongoDB facilitates querying over array elements using $elemMatch operator.

According to description as mentioned into above question as a solution to it please try executing following MongoDB query to fetch required data from MongoDB collection.

```<code>db.collection.find({
    detail: {
        $elemMatch: {
            type: 'One'
        }
    }
}, {
    _id: 1,
    city: 1,
    'detail.$': 1
})
</code>```

Body:
i am not able to query results in this query,
i want result based on detail.type (like fetch record where detail.type="one") and fetch only first 10 records in detail.numbers array

{
            "_id" : ObjectId("5a27b609e101b6092b4ebf91"),
            "city" : "Mumbai",
            "detail" : [
                {
                    "type" : "One",
                    "name" : "Some name",
                    "_id" : ObjectId("5a27b609e101b6092b4ebf92"),
                    "numbers" : [
                        "72598xxx78",
                        "81301xxx88",
                        "83302xxx30",
                        "84309xxx43",
                        "85309xxx77",
                        "86309xxx61",
                        "87270xxx88",
                        "85272xxx36",
                        "88272xxx23",
                        "85276xxx01"
                    ]
                },
                {
                    "name" : "Some name",
                    "type" : "two",
                    "_id" : ObjectId("5a28e954d4f5a30527d92a32"),
                    "contact" : [
                        "72598xxx78",
                        "81301xxx88",
                        "83302xxx30",
                        "84309xxx43",
                        "85309xxx77",
                        "86309xxx61",
                        "87270xxx88",
                        "85272xxx36",
                        "88272xxx23",
                        "85276xxx01"
                    ]
                },
    ]
    }

Body:
MongoDB facilitates querying over array elements using $elemMatch operator.

According to description as mentioned into above question as a solution to it please try executing following MongoDB query to fetch required data from MongoDB collection.

db.collection.find({
    detail: {
        $elemMatch: {
            type: 'One'
        }
    }
}, {
    _id: 1,
    city: 1,
    'detail.$': 1
})


问:
Vertically align elements in one layout with elements in another to be at same level?
I have horizontal linear layout with two vertical linear layouts in it. Each vertical layout contains 5 TextViews and looks like this:

As you see the 5 textviews from the first layout are at the same vertical  level with the 5 textviews from the second layout. But when I change the elements of the second layout to be EditTexts it starts looking like that:

What can I do to align TextViews with their corresponding EditTexts to be at the exact same vertical level? I can change the margin top and bottom to all TextViews. But it's a lot of work and after that they are not at the exact same level. I'm using Xamarin.Android.

答:
You can do easily by TableLayout it will stretch with views height and width evenly

```<code><TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*">
<TableRow>
    <TextView
        android:padding="16dp"
        android:text="Text 1"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />
    <EditText android:hint="Edit text 1" />
</TableRow>
<TableRow>
    <TextView
        android:padding="16dp"
        android:text="Text 2"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

    <EditText android:hint="Edit text 2" />
</TableRow>
<TableRow>
    <TextView
        android:padding="16dp"
        android:text="Text 3"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />
    <EditText android:hint="Edit text 3" />
</TableRow>
<TableRow>
    <TextView
        android:padding="16dp"
        android:text="Text 4"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />
    <EditText android:hint="Edit text 4" />
</TableRow>
<TableRow>
    <TextView
        android:padding="16dp"
        android:text="Text 5"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />
    <EditText android:hint="Edit text 5" />
</TableRow>
</code>```

Body:
You can do easily by TableLayout it will stretch with views height and width evenly

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*">
<TableRow>
    <TextView
        android:padding="16dp"
        android:text="Text 1"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />
    <EditText android:hint="Edit text 1" />
</TableRow>
<TableRow>
    <TextView
        android:padding="16dp"
        android:text="Text 2"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />

    <EditText android:hint="Edit text 2" />
</TableRow>
<TableRow>
    <TextView
        android:padding="16dp"
        android:text="Text 3"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />
    <EditText android:hint="Edit text 3" />
</TableRow>
<TableRow>
    <TextView
        android:padding="16dp"
        android:text="Text 4"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />
    <EditText android:hint="Edit text 4" />
</TableRow>
<TableRow>
    <TextView
        android:padding="16dp"
        android:text="Text 5"
        android:textAppearance="@style/TextAppearance.AppCompat.Title" />
    <EditText android:hint="Edit text 5" />
</TableRow>


问:
how to show datetime from 2017-12-06 13:07:00+05:30 fromat to 2017-12-06 18:37:00 format in Python
I would like to convert timezone of datetime column in dataframe in python. This is how i did it.

```<code>df.dtypes
Out[11]:
x1                 object
x2                 object
event_time datetime64[ns]
x3                float64
dtype: object

type(df.event_time)
Out[12]: pandas.core.series.Series
</code>```

But the results look like this

```<code>df['event_time'].dt.tz_localize('Asia/Kolkata')
Out[2]:
0       2017-12-06 13:07:00+05:30
1       2017-12-06 13:06:00+05:30
2       2017-12-06 13:05:00+05:30
3       2017-12-06 13:04:00+05:30
4       2017-12-06 13:03:00+05:30
5       2017-12-06 13:02:00+05:30
6       2017-12-06 13:01:00+05:30
7       2017-12-06 13:00:00+05:30
8       2017-12-06 12:59:00+05:30
9       2017-12-06 12:58:00+05:30
10      2017-12-06 12:57:00+05:30
11      2017-12-06 12:56:00+05:30
12      2017-12-06 12:55:00+05:30
</code>```

Is there a way i can show datetime like below

```<code> 0       2017-12-06 18:37:00
 1       2017-12-06 18:36:00
</code>```

Also, I am interested in changing the timezone by using +05:30 instead of using the zone name 'Asia/Kolkata'

```<code>EDIT :

 df = pd.DataFrame({'event_time': [pd.Timestamp('2017-12-06 13:07:00'),pd.Timestamp('2017-12-06 13:06:00')]})

df['event_time'] = df['event_time'].dt.tz_localize('Asia/Kolkata')

print (df)
                 event_time
0 2017-12-06 13:07:00+05:30
1 2017-12-06 13:06:00+05:30

df['event_time'] = df['event_time'].dt.tz_localize('Asia/Kolkata').dt.tz_convert('UTC').dt.tz_localize(None)
  File "<ipython-input-24-ee54cb3c6b25>", line 1
    df['event_time'] = df['event_time'].dt.tz_localize('Asia/Kolkata').dt.tz_convert('UTC').dt.tz_localize(None)
                                                                                ^
SyntaxError: invalid character in identifier
</code>```

Body:
I would like to convert timezone of datetime column in dataframe in python. This is how i did it.

df.dtypes
Out[11]:
x1                 object
x2                 object
event_time datetime64[ns]
x3                float64
dtype: object

type(df.event_time)
Out[12]: pandas.core.series.Series

But the results look like this

df['event_time'].dt.tz_localize('Asia/Kolkata')
Out[2]:
0       2017-12-06 13:07:00+05:30
1       2017-12-06 13:06:00+05:30
2       2017-12-06 13:05:00+05:30
3       2017-12-06 13:04:00+05:30
4       2017-12-06 13:03:00+05:30
5       2017-12-06 13:02:00+05:30
6       2017-12-06 13:01:00+05:30
7       2017-12-06 13:00:00+05:30
8       2017-12-06 12:59:00+05:30
9       2017-12-06 12:58:00+05:30
10      2017-12-06 12:57:00+05:30
11      2017-12-06 12:56:00+05:30
12      2017-12-06 12:55:00+05:30

Is there a way i can show datetime like below

 0       2017-12-06 18:37:00
 1       2017-12-06 18:36:00

Also, I am interested in changing the timezone by using +05:30 instead of using the zone name 'Asia/Kolkata'

EDIT :

 df = pd.DataFrame({'event_time': [pd.Timestamp('2017-12-06 13:07:00'),pd.Timestamp('2017-12-06 13:06:00')]})

df['event_time'] = df['event_time'].dt.tz_localize('Asia/Kolkata')

print (df)
                 event_time
0 2017-12-06 13:07:00+05:30
1 2017-12-06 13:06:00+05:30

df['event_time'] = df['event_time'].dt.tz_localize('Asia/Kolkata').dt.tz_convert('UTC').dt.tz_localize(None)
  File "<ipython-input-24-ee54cb3c6b25>", line 1
    df['event_time'] = df['event_time'].dt.tz_localize('Asia/Kolkata').dt.tz_convert('UTC').dt.tz_localize(None)
                                                                                ^
SyntaxError: invalid character in identifier

Body:
I believe you need:

df = pd.DataFrame({'event_time': [pd.Timestamp('2017-12-06 13:07:00'),
                                     pd.Timestamp('2017-12-06 13:06:00')]})

df['event_time'] = df['event_time'].dt.tz_localize('Asia/Kolkata')
print (df)
                 event_time
0 2017-12-06 13:07:00+05:30
1 2017-12-06 13:06:00+05:30

df['event_time'] = df['event_time'].dt.tz_convert('UTC').dt.tz_localize(None)
print (df)
           event_time
0 2017-12-06 07:37:00
1 2017-12-06 07:36:00


问:
Python inheritance (OOP)
I want create inheritor (descadent) of python's class time. I use solving from next script, but I obtain message cannot create "builtin_function_or method" instance. Where is problem,please?

```<code>from time import time as time
import _classA

class UserTime(time):
    def __init__(self):
        pass
</code>```

答:
Based on the Python docs for time.time, the time that you've imported there is a function, not a class, which is why you're getting that error message.

datetime.time may be what you need instead.

Title: Python inheritance (OOP)

Body:
I want create inheritor (descadent) of python's class time. I use solving from next script, but I obtain message cannot create "builtin_function_or method" instance. Where is problem,please?

from time import time as time
import _classA

class UserTime(time):
    def __init__(self):
        pass


问:
Upgrade Python Sphinx with easy_install
I'm using Portable Python 2.7.6.1 and I installed Sphinx 1.5.1 in order to create my manuals. As Sphinx made already a lot of progress in the last months I was trying to update to the newest version Sphinx 1.6.5, but I was unable to upgrade using the easy_install Tool.

I tried:

```<code>easy_install-2.7.exe -U sphinx
</code>```

And it says:

```<code>Searching for sphinx
Reading http://pypi.python.org/simple/sphinx/
Couldn't retrieve index page for 'sphinx'
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
Best match: sphinx 1.5.1
Processing sphinx-1.5.1-py2.7.egg
sphinx 1.5.1 is already the active version in easy-install.pth
</code>```

After that I was trying to force the version, but this also failed:

```<code>easy_install-2.7.exe -m 1.6.5 sphinx
</code>```

This is what is says:

```<code>Searching for 1.6.5
Reading http://pypi.python.org/simple/1.6.5/
Couldn't find index page for '1.6.5' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for 1.6.5
Best match: None
Traceback (most recent call last):
  File "C:\Data\Frank\Programme\Portable Python 2.7.6.1\App\Scripts\easy_install-2.7-script.py", line 8, in <module>
    load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install-2.7')()
  File "C:\Data\Frank\Programme\Portable Python 2.7.6.1\App\lib\site-packages\setuptools\command\easy_install.py", line 1712, in main
    with_ei_usage(lambda:
  File "C:\Data\Frank\Programme\Portable Python 2.7.6.1\App\lib\site-packages\setuptools\command\easy_install.py", line 1700, in with_ei_usage
    return f()
</code>```

What I'm doing wrong here? Maybe removing sphinx would help, but there is seemingly no command switch in easy-install for that.

答:
The documentation of easy_install is straightforward. See upgrading a package.

You don’t need to do anything special to upgrade a package: just install the new version, either by requesting a specific version, e.g.:

```<code>easy_install "SomePackage==2.0"
</code>```

So this should do it:

```<code>easy_install "Sphinx==1.6.5"
</code>```

See also uninstalling packages with easy_install.

If you want to delete the currently installed version of a package (or all versions of a package), you should first run:

```<code>easy_install -m PackageName
</code>```

This will ensure that Python doesn’t continue to search for a package you’re planning to remove. After you’ve done this, you can safely delete the .egg files or directories, along with any scripts you wish to remove.

Title: Upgrade Python Sphinx with easy_install

Body:
I'm using Portable Python 2.7.6.1 and I installed Sphinx 1.5.1 in order to create my manuals. As Sphinx made already a lot of progress in the last months I was trying to update to the newest version Sphinx 1.6.5, but I was unable to upgrade using the easy_install Tool.

I tried:

easy_install-2.7.exe -U sphinx

And it says:

Searching for sphinx
Reading http://pypi.python.org/simple/sphinx/
Couldn't retrieve index page for 'sphinx'
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
Best match: sphinx 1.5.1
Processing sphinx-1.5.1-py2.7.egg
sphinx 1.5.1 is already the active version in easy-install.pth

After that I was trying to force the version, but this also failed:

easy_install-2.7.exe -m 1.6.5 sphinx

This is what is says:

Searching for 1.6.5
Reading http://pypi.python.org/simple/1.6.5/
Couldn't find index page for '1.6.5' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for 1.6.5
Best match: None
Traceback (most recent call last):
  File "C:\Data\Frank\Programme\Portable Python 2.7.6.1\App\Scripts\easy_install-2.7-script.py", line 8, in <module>
    load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install-2.7')()
  File "C:\Data\Frank\Programme\Portable Python 2.7.6.1\App\lib\site-packages\setuptools\command\easy_install.py", line 1712, in main
    with_ei_usage(lambda:
  File "C:\Data\Frank\Programme\Portable Python 2.7.6.1\App\lib\site-packages\setuptools\command\easy_install.py", line 1700, in with_ei_usage
    return f()

What I'm doing wrong here? Maybe removing sphinx would help, but there is seemingly no command switch in easy-install for that.

Body:
The documentation of easy_install is straightforward. See upgrading a package.

You don’t need to do anything special to upgrade a package: just install the new version, either by requesting a specific version, e.g.:

easy_install "SomePackage==2.0"

So this should do it:

easy_install "Sphinx==1.6.5"

See also uninstalling packages with easy_install.

If you want to delete the currently installed version of a package (or all versions of a package), you should first run:

easy_install -m PackageName

This will ensure that Python doesn’t continue to search for a package you’re planning to remove. After you’ve done this, you can safely delete the .egg files or directories, along with any scripts you wish to remove.


问:
Combinations with repetition of letters with weight from list
I have four letters with different weights as

```<code>letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]
</code>```

I want to get the combinations of letters which weight = 2. The letter can be repeatedly chose and order is not important. The result can be list or array or any forms but with this combinations

```<code>comb_w2 = ['CC','NN','NC','O','S']
</code>```

Here C and N has weight = 1 so combining two letters have weight = 2: The possible combinations are 'CC','NN','NC'

O and S has weight = 2 already so it cannot combine with other letters. Is there any libraries for calculating this? I saw itertools but it gives only the number of possibility, not the combinations.

答:
My answer ended up being very similar to Turksarama's. Namely, if you need the combination of results, you have to sort the letters and use a set to get rid of the duplicates. My approach is more succinct, but requires calling set() with the function call.

```<code>letters = ['C', 'N', 'O', 'S']
weights = [1, 1, 2, 2]
items = list(zip(weights, letters))

def combinations(items, max_weight, weight=0, word=''):
    if weight == max_weight:
        yield ''.join(sorted(word))
    items_allowed = [(w, l) for w, l in items if max_weight - weight >= w]
    for w, l in items_allowed:
        for result in combinations(items_allowed, max_weight, weight+w, word+l):
            yield result

print(set(combinations(items, 2)))
</code>```

Body:
I have four letters with different weights as

letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]

I want to get the combinations of letters which weight = 2. The letter can be repeatedly chose and order is not important. The result can be list or array or any forms but with this combinations

comb_w2 = ['CC','NN','NC','O','S']

Here C and N has weight = 1 so combining two letters have weight = 2: The possible combinations are 'CC','NN','NC'

O and S has weight = 2 already so it cannot combine with other letters. Is there any libraries for calculating this? I saw itertools but it gives only the number of possibility, not the combinations.

Body:
My answer ended up being very similar to Turksarama's. Namely, if you need the combination of results, you have to sort the letters and use a set to get rid of the duplicates. My approach is more succinct, but requires calling set() with the function call.

letters = ['C', 'N', 'O', 'S']
weights = [1, 1, 2, 2]
items = list(zip(weights, letters))

def combinations(items, max_weight, weight=0, word=''):
    if weight == max_weight:
        yield ''.join(sorted(word))
    items_allowed = [(w, l) for w, l in items if max_weight - weight >= w]
    for w, l in items_allowed:
        for result in combinations(items_allowed, max_weight, weight+w, word+l):
            yield result

print(set(combinations(items, 2)))


问:
Sort ListView bound to ObservableCollection in XAML
I have a ListView that is bound through XAML to an ObservableCollection. I used to do the sorting in code behind but there are many operations where I would have to keep in mind that the sorting needs to be refreshed.

So I wanted to make it more clean and make the sorting directly in XAML more dynamically.

Unfortunately I cannot find tags/attributes to do this. All examples I find are for WPF applications using <CollectionViewSource.SortDescription> which seems to be not supported in XAML, at least for now.

I found a AdvancedCollectionView control in the UWP Community Toolkit which I then used. This control uses the existing ObservableCollection and the ListView (source) is now bound to this AdvancedCollectionView.

It seems to work - so what's the problem.
1) I now have to use a huge Nu-Get package with many licenses (which I should have read :-) )
2) I implemented INotifyPropertyChanged for the class that is bound to the ListView (the single item) so that the ListView gets refreshed when a property, e.g. the Title of an item changes. This used to work earlier, before I switched to AdvancedCollectionView but now the event raiser throws a NullReferenceExcpetion.

So I'm now asking myself if there isn't really a more Out-of-the-Box way to do the simple task of sorting a ListView by a bound property?

答:
Apparently the issue with the AdvancedCollectionView occurs because there is currently a bug when no Filter property has been set.

I replaced the NuGet-Package with the complete source and debugged it to locate the error in the ItemOnPropertyChanged where it threw the NullReferenceException on line:

```<code>filterResult = _filter(item);
</code>```

because "_filter" was null.

I reporeted the bug and it looks like a fix will be in version 2.2 of the Community Toolkit:
https://github.com/Microsoft/UWPCommunityToolkit/issues/1686

Body:
Apparently the issue with the AdvancedCollectionView occurs because there is currently a bug when no Filter property has been set.

I replaced the NuGet-Package with the complete source and debugged it to locate the error in the ItemOnPropertyChanged where it threw the NullReferenceException on line:

filterResult = _filter(item);

because "_filter" was null.

I reporeted the bug and it looks like a fix will be in version 2.2 of the Community Toolkit:
https://github.com/Microsoft/UWPCommunityToolkit/issues/1686


问:
Another unnamed CacheManager already exists when using Hibernate L2 ehcache and spring boot enabledCache
I have an application that have more than 100 domain model i want to integrate ehcache and hibernate L2cache ,my application used ehcache for cache some of service s methods . my CacheConfiguration is like this

```<code> package org.roshan.framework.config;

import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.ehcache.jsr107.Eh107Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
@AutoConfigureAfter(value = {DatabaseConfiguration.class})
public class CacheConfiguration {

    private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
    private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration;

    @PreDestroy
    public void destroy() {
        log.info("Remove Cache Manager metrics");
        log.info("Closing Cache Manager");
    }

    public CacheConfiguration(JHipsterProperties jHipsterProperties) {
        JHipsterProperties.Cache.Ehcache ehcache = jHipsterProperties.getCache().getEhcache();

        jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
                CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
                        ResourcePoolsBuilder.heap(ehcache.getMaxEntries()))
                        .withExpiry(Expirations.timeToLiveExpiration(Duration.of(ehcache.getTimeToLiveSeconds(), TimeUnit.SECONDS)))
                        .build()
        );
    }

    @Bean
    public JCacheManagerCustomizer cacheManagerCustomizer() {
        log.debug("Starting Ehcache");

        return cm -> {
            // some cache for using in method of service
            cm.createCache("baseInfoCache", jcacheConfiguration);
            cm.createCache("attachments", jcacheConfiguration);
        };
    }

}
</code>```

in application.yml change hibernate cache config like this

```<code>spring:
    devtools:
        restart:
            enabled: true
        livereload:
            enabled: true # we use gulp + BrowserSync for livereload
    application:
        name: roshanframework
    jpa:
        open-in-view: true
        hibernate:
            ddl-auto: none
        properties:
              hibernate.cache.use_second_level_cache: true
              hibernate.cache.use_query_cache: false
              hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
              hibernate.generate_statistics: false
              hibernate.dialect : org.hibernate.dialect.MySQL5Dialect
              #hibernate.default_schema : ihsl
              hibernate.show_sql : true
              hibernate.current_session_context_class:  org.springframework.orm.hibernate5.SpringSessionContext
</code>```

but when i start my application i get exception that i have 2 cachemanager how solve this problem .

```<code>The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]
    at org.hibernate.cache.ehcache.EhCacheRegionFactory.start(EhCacheRegionFactory.java:90)
    at org.hibernate.cache.spi.RegionFactory.start(RegionFactory.java:63)
    at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:71)
    at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:28)
    at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:20)
    at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:58)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
    ... 45 common frames omitted
Caused by: net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]
    at net.sf.ehcache.CacheManager.assertNoCacheManagerExistsWithSameName(CacheManager.java:626)
    at net.sf.ehcache.CacheManager.init(CacheManager.java:391)
    at net.sf.ehcache.CacheManager.<init>(CacheManager.java:269)
    at org.hibernate.cache.ehcache.EhCacheRegionFactory.start(EhCacheRegionFactory.java:69)
    ... 51 common frames omitted
</code>```

I dont know why two cache manager exist? how can change configuration to using one cache manager for both hibernate and methods?

答:
I also ran into this problem recently.
Soln is to use "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory" as hibernate factory_class.</p>

```<code>spring:
    jpa:
      properties:
        hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
</code>```

Body:
I have an application that have more than 100 domain model i want to integrate ehcache and hibernate L2cache ,my application used ehcache for cache some of service s methods . my CacheConfiguration is like this

 package org.roshan.framework.config;

import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.ehcache.jsr107.Eh107Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableCaching
@AutoConfigureAfter(value = {DatabaseConfiguration.class})
public class CacheConfiguration {

    private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class);
    private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration;

    @PreDestroy
    public void destroy() {
        log.info("Remove Cache Manager metrics");
        log.info("Closing Cache Manager");
    }

    public CacheConfiguration(JHipsterProperties jHipsterProperties) {
        JHipsterProperties.Cache.Ehcache ehcache = jHipsterProperties.getCache().getEhcache();

        jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
                CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
                        ResourcePoolsBuilder.heap(ehcache.getMaxEntries()))
                        .withExpiry(Expirations.timeToLiveExpiration(Duration.of(ehcache.getTimeToLiveSeconds(), TimeUnit.SECONDS)))
                        .build()
        );
    }

    @Bean
    public JCacheManagerCustomizer cacheManagerCustomizer() {
        log.debug("Starting Ehcache");

        return cm -> {
            // some cache for using in method of service
            cm.createCache("baseInfoCache", jcacheConfiguration);
            cm.createCache("attachments", jcacheConfiguration);
        };
    }

}

in application.yml change hibernate cache config like this

spring:
    devtools:
        restart:
            enabled: true
        livereload:
            enabled: true # we use gulp + BrowserSync for livereload
    application:
        name: roshanframework
    jpa:
        open-in-view: true
        hibernate:
            ddl-auto: none
        properties:
              hibernate.cache.use_second_level_cache: true
              hibernate.cache.use_query_cache: false
              hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.EhCacheRegionFactory
              hibernate.generate_statistics: false
              hibernate.dialect : org.hibernate.dialect.MySQL5Dialect
              #hibernate.default_schema : ihsl
              hibernate.show_sql : true
              hibernate.current_session_context_class:  org.springframework.orm.hibernate5.SpringSessionContext

but when i start my application i get exception that i have 2 cachemanager how solve this problem .

The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]
    at org.hibernate.cache.ehcache.EhCacheRegionFactory.start(EhCacheRegionFactory.java:90)
    at org.hibernate.cache.spi.RegionFactory.start(RegionFactory.java:63)
    at org.hibernate.internal.CacheImpl.<init>(CacheImpl.java:71)
    at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:28)
    at org.hibernate.engine.spi.CacheInitiator.initiateService(CacheInitiator.java:20)
    at org.hibernate.service.internal.SessionFactoryServiceRegistryImpl.initiateService(SessionFactoryServiceRegistryImpl.java:58)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
    ... 45 common frames omitted
Caused by: net.sf.ehcache.CacheException: Another unnamed CacheManager already exists in the same VM. Please provide unique names for each CacheManager in the config or do one of following:
1. Use one of the CacheManager.create() static factory methods to reuse same CacheManager with same name or create one if necessary
2. Shutdown the earlier cacheManager before creating new one with same name.
The source of the existing CacheManager is: DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]
    at net.sf.ehcache.CacheManager.assertNoCacheManagerExistsWithSameName(CacheManager.java:626)
    at net.sf.ehcache.CacheManager.init(CacheManager.java:391)
    at net.sf.ehcache.CacheManager.<init>(CacheManager.java:269)
    at org.hibernate.cache.ehcache.EhCacheRegionFactory.start(EhCacheRegionFactory.java:69)
    ... 51 common frames omitted

I dont know why two cache manager exist? how can change configuration to using one cache manager for both hibernate and methods?

Body:
I also ran into this problem recently.
Soln is to use "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory" as hibernate factory_class.

spring:
    jpa:
      properties:
        hibernate.cache.region.factory_class: org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory


问:
Scroll sticky header not working
I have attempted to use the basic HTML, CSS and also Javascript to make the header, "Category" fixed to the top like the sticky header when scrolled but mine isn't working. I have done researched on how it was done but I can't seem to implement it into my work here. I am a newbie here, still learning how to code. Help is much appreciated thanks.

Here's the code.

     var wrap = $("#wrap");

wrap.on("scroll", function(e) {

  if (this.scrollTop > 100) {
    wrap.addClass("fix-category");
  } else {
    wrap.removeClass("fix-category");
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
            <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">

               <!-- jQuery first, then Tether, then Bootstrap JS. -->
            <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

          </head>
          <body>

          <div role="main" ng-controller="cartController" ng-init="init()">
          <div class="wrap" id="wrap">

          <header>
           <nav class="navbar navbar-toggleable-md navbar-light bg-faded fixed-top" style="background-color: #ffffff;">
          <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>

          <img class="cursor-pointer hidelogo" src="" width="50" height="60" id="rsvp_logo" alt="Logo">

          <div class="collapse navbar-collapse justify-content-end" id="navbarNav">
            <ul class="navbar-nav">
              <li class="nav-item active dropdown">
                <i class="fa fa-globe" aria-hidden="true"></i>
                 <span id="selected" class="caret">Language </span>
                 <div class="dropdown-menu" aria-labelledby="languageDropdown">
                  English
                  中文
                </div>
              </li>

              <li class="nav-item dropdown">
                <i class="fa fa-sort-amount-asc" aria-hidden="true"></i>
                <span id="sort" class="caret">Sort</span>
                  <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink" ng-model="selectedOrder">
                  Category
                  Date and Time
                  Availability
                </div>
              </li>
              <li class="nav-item">
                <i class="fa fa-filter" aria-hidden="true"></i>
                Topics
              </li>
               <li class="nav-item">
                <i class="fa fa-print" aria-hidden="true"></i> Print
              </li>
              <li class="nav-item">
                <i class="fa fa-shopping-cart" aria-hidden="true"></i>
                Cart
              </li>
            </ul>
          </div>
        </nav>
          </header>

   <div class="container">
  <div class="jumbotron blue">
      <div class="row">
      <div class="col white" >
     Activity
      </div>
       <div class="col white">
       <i class="fa fa-calendar-o" aria-hidden="true"></i>
     Date

      </div>
       <div class="col white">
          <i class="fa fa-map-marker" aria-hidden="true"></i>

        Venue
         </div>
        </div>
        </div>
    </div>

     <div class="category">
         <b>Category 1</b>
    </div>

<div class="container">
<div class="row">
<div class="col">
National Senior Volunteer Month Opening Ceremony
</div>

<div class="col">
30 December 2017<br>
</div>

<div class="col">
9.00am - 12.00pm
</div>

<div class="col">
Auditorium
</div>

<div class="col">
<!-- <td ng-class="getTableColourBySection(colourIndex, 'defaultCellClass')">
    <input ng-if='(session.session_id != null && session.roles[0].attendee_count < session.roles[0].count) || checkboxSessions[session.session_id] == true' ng-model="checkboxSessions[session.session_id]" ng-change="checkSelectedSession(session, checkboxSessions[session.session_id])" type="checkbox">
       <span ng-if="session.session_id == null">No Session </span>
          <span ng-if="session.attendance_count >= session.activity.target_number">Session full</span>
    <span ng-if="session.roles[0].attendee_count >= session.roles[0].count">Full Session </span>
       </td> -->
       <b>18 available</b>
 </div>
<div class="col">
       <button type="button" class="btn btn-primary btn-lg" id="btnAdd" ng-submit="add()">
       <span><i class="fa fa-plus" aria-hidden="true"></i> <b>ADD</b></span>
   </button>
</div>

<div class="col">
 <button class="btn btn-light btn-lg" type="button" data-toggle="collapse" data-target="#demo">Detail
  <span><i id="toggle-demo" class="fa fa-caret-down" aria-hidden="true"></i></span>
</button>
     </div>
      </div>
         </div>
      <div id="demo" class="col collapse in">
   </div>

<div class="category">
  <b>Enrichment and Learning</b>
</div>

            </body>
            </html>

    <style>

    .category
    {
      width: 100%;
      height: 40px;
      background : #EEEEEE;
      padding: 5px;
    }

    .header
    {
     height: 100px;
    }

    .wrap
    {
     overflow: auto;
     position: relative;
    }

    .fix-category .category
    {
     position:fixed;
     height: 40px;
     left: 0;
        font-family: 'Lato', sans-serif;
    }
    </style></code>```

答:
this fixes it. Use top prop in CSS to position fixed category, and also if using jQuery then you can use $(window).scrollTop() > XX

var wrap = $("#wrap");

$(window).on("scroll", function(e) {

  if ( $(window).scrollTop() > 100) {
    wrap.addClass("fix-category");
  } else {
    wrap.removeClass("fix-category");
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.category
    {
      width: 100%;
      height: 40px;
      background : #EEEEEE;
      padding: 5px;
    }

    .header
    {
     height: 100px;
    }

    .wrap
    {
     overflow: auto;
     position: relative;
    }

    .fix-category .category
    {
     position:fixed;
     height: 40px;
     left: 0;
      top: 55px;
      font-family: 'Lato', sans-serif;
    }</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
            <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">

          <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

          </button>

                 Language

                  English
                  中文

                Sort

                  Category
                  Date and Time
                  Availability

                Topics

                 Print

                Cart

     Activity

     Date

        Venue

         Category 1

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

```

Title: Scroll sticky header not working

Body:
I have attempted to use the basic HTML, CSS and also Javascript to make the header, "Category" fixed to the top like the sticky header when scrolled but mine isn't working. I have done researched on how it was done but I can't seem to implement it into my work here. I am a newbie here, still learning how to code. Help is much appreciated thanks.

Here's the code.

     var wrap = $("#wrap");

wrap.on("scroll", function(e) {

  if (this.scrollTop > 100) {
    wrap.addClass("fix-category");
  } else {
    wrap.removeClass("fix-category");
  }

});

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
            <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">

          <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

          </button>

                 Language

                  English
                  中文

                Sort

                  Category
                  Date and Time
                  Availability

                Topics

                 Print

                Cart

     Activity

     Date

        Venue

         Category 1

National Senior Volunteer Month Opening Ceremony

30 December 2017

9.00am - 12.00pm

Auditorium

       18 available

       <button type="button" class="btn btn-primary btn-lg" id="btnAdd" ng-submit="add()">
        ADD
   </button>

 <button class="btn btn-light btn-lg" type="button" data-toggle="collapse" data-target="#demo">Detail

</button>

  Enrichment and Learning

Body:
this fixes it. Use top prop in CSS to position fixed category, and also if using jQuery then you can use $(window).scrollTop() > XX

var wrap = $("#wrap");

$(window).on("scroll", function(e) {

  if ( $(window).scrollTop() > 100) {
    wrap.addClass("fix-category");
  } else {
    wrap.removeClass("fix-category");
  }

});

.category
    {
      width: 100%;
      height: 40px;
      background : #EEEEEE;
      padding: 5px;
    }

    .header
    {
     height: 100px;
    }

    .wrap
    {
     overflow: auto;
     position: relative;
    }

    .fix-category .category
    {
     position:fixed;
     height: 40px;
     left: 0;
      top: 55px;
      font-family: 'Lato', sans-serif;
    }

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
            <link rel="stylesheet" type="text/css" href="../../css/register-dev.css">

               <!-- jQuery first, then Tether, then Bootstrap JS. -->
            <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

          </head>
          <body>

          <div role="main" ng-controller="cartController" ng-init="init()">
          <div class="wrap" id="wrap">

          <header>
           <nav class="navbar navbar-toggleable-md navbar-light bg-faded fixed-top" style="background-color: #ffffff;">
          <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>

          <a class="navbar-brand" href="#">
          <img class="cursor-pointer hidelogo" src="" width="50" height="60" id="rsvp_logo" alt="Logo">
        </a>
          <div class="collapse navbar-collapse justify-content-end" id="navbarNav">
            <ul class="navbar-nav">
              <li class="nav-item active dropdown">
                <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown"
                aria-haspopup="true" aria-expanded="false"><i class="fa fa-globe" aria-hidden="true"></i>
                 <span id="selected" class="caret">Language </span></a>
                 <div class="dropdown-menu" aria-labelledby="languageDropdown">
                  <a class="dropdown-item" href="#">English</a>
                  <a class="dropdown-item" href="#">中文</a>
                </div>
              </li>

              <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown"
                aria-haspopup="true" aria-expanded="false"><i class="fa fa-sort-amount-asc" aria-hidden="true"></i>
                <span id="sort" class="caret">Sort</span></a>
                  <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink" ng-model="selectedOrder">
                  <a class="dropdown-item" href="#">Category</a>
                  <a class="dropdown-item" href="#">Date and Time</a>
                  <a class="dropdown-item" href="#">Availability</a>
                </div>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#"><i class="fa fa-filter" aria-hidden="true"></i>
                Topics</a>
              </li>
               <li class="nav-item">
                <a class="nav-link" href="print.html"><i class="fa fa-print" aria-hidden="true"></i> Print</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="cart.html"><i class="fa fa-shopping-cart" aria-hidden="true"></i>
                Cart</a>
              </li>
            </ul>
          </div>
        </nav>
          </header>

   <div class="container">
  <div class="jumbotron blue">
      <div class="row">
      <div class="col white" >
     Activity
      </div>
       <div class="col white">
       <i class="fa fa-calendar-o" aria-hidden="true"></i>
     Date

      </div>
       <div class="col white">
          <i class="fa fa-map-marker" aria-hidden="true"></i>

        Venue
         </div>
        </div>
        </div>
    </div>

     <div class="category">
         <b>Category 1</b>
    </div>
    <div>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
<br><br>
Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
    </div>
        <div>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
<br><br>
Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

    </div>


问:
Quick successful exit from C++ with lots of objects allocated
I'm looking for a way to quickly exit a C++ that has allocated a lot of structures in memory using C++ classes.  The program finishes correctly, but after the final "return" in the program, all of the auto-destructors kick in.  The problem is the program has allocated about 15GB of memory through lots of C++ class structures, and this auto-destruct process takes about 1 more hour itself to complete as it walks through all of the structures - even though I don't care about the results.  The program only took 1 hour to complete the task up to this point.  I would like to just return to the OS and let it do its normal wholesale process allocation deletion - which is very quick.  I've been doing this by manually killing the process during the cleanup stage - but am looking for a better programic solution.

I would like to return a success to the OS, but don't care to keep any of the memory content.  The program does perform a lot of dynamic allocation/deallocation during the normal processing, so it's not just simple heap management.

Any opinions?

答:
In Standard C++ you only have abort(), but that has the process return failure to the OS.

On many platforms (Unix, MS Windows) you can use _exit() to exit the program without running cleanup and destructors.


问:
How to build Python Lambda for Alexa skill with sequence of statements?
I am building Alexa skill for my application. When your ask's 'what is my account status?' this intent return sequence of statements related to user's account. API gives following response

```<code>response = [{
..
text: 'Total orders are 41, Delivered 28'
..
},
{
..
text: 'Today orders are 12, Delivered 2'
..
},
{}]
</code>```

How to build response sequence based on API response?

With this intent, I get the response from API with set statements Alexa should prompt each statement one by one. If the user said 'next' in between any of the statement while Alexa prompting then it goes to next statement in the response array.

答:
Since you mentioned Python, I would suggest to take a look at Flask-ask, which provides you with two main responses type: statement and question.

As sid8491 mentioned, you will need to store info in sessions to keep track of which response (from json) needs to be returned. You can use redis for this purpose, using this python library.

Assuming the json response is stored in db (or somewhere), and can be accessed in a list, let's say your interaction model looks something like this:

```<code>{
    "languageModel": {
        "intents": [
            {
                "name": "NextIntent",
                "samples": ["next", "tell me more"]
            },
            {
                "name": "StopIntent",
                "samples": ["stop"]
            },
            {
                "name": "StatusIntent",
                "samples": ["what is my account status"]
            }
        ],
        "invocationName": "orders"
    }
}
</code>```

You can use following steps (using redis and flask-ask for this example):

on 'StatusIntent', store session and return first response:

```<code>redis.set("session_key", 0)
return statement(response[0]) # assuming responses are stored in a list
</code>```

on 'NextIntent', get value stored in session, if present return next response

```<code>value = redis.get("session_key")
if not value:  # session is expired
    return statement("I don't understand")
redis.set("session_key", int(value)+1)
return statement(response[int(value)+1])
</code>```

on 'StopIntent', remove "session_key" from redis

```<code>redis.delete("session_key")
return statement("Ok. I am here if you need me.")
</code>```

It's not the actual code but simply intended to give you an idea. Hope it helps.

:)

Body:
I am building Alexa skill for my application. When your ask's 'what is my account status?' this intent return sequence of statements related to user's account. API gives following response

response = [{
..
text: 'Total orders are 41, Delivered 28'
..
},
{
..
text: 'Today orders are 12, Delivered 2'
..
},
{}]

How to build response sequence based on API response?

With this intent, I get the response from API with set statements Alexa should prompt each statement one by one. If the user said 'next' in between any of the statement while Alexa prompting then it goes to next statement in the response array.

Body:
Since you mentioned Python, I would suggest to take a look at Flask-ask, which provides you with two main responses type: statement and question.

As sid8491 mentioned, you will need to store info in sessions to keep track of which response (from json) needs to be returned. You can use redis for this purpose, using this python library.

Assuming the json response is stored in db (or somewhere), and can be accessed in a list, let's say your interaction model looks something like this:

{
    "languageModel": {
        "intents": [
            {
                "name": "NextIntent",
                "samples": ["next", "tell me more"]
            },
            {
                "name": "StopIntent",
                "samples": ["stop"]
            },
            {
                "name": "StatusIntent",
                "samples": ["what is my account status"]
            }
        ],
        "invocationName": "orders"
    }
}

You can use following steps (using redis and flask-ask for this example):

on 'StatusIntent', store session and return first response:

redis.set("session_key", 0)
return statement(response[0]) # assuming responses are stored in a list

on 'NextIntent', get value stored in session, if present return next response

value = redis.get("session_key")
if not value:  # session is expired
    return statement("I don't understand")
redis.set("session_key", int(value)+1)
return statement(response[int(value)+1])

on 'StopIntent', remove "session_key" from redis

redis.delete("session_key")
return statement("Ok. I am here if you need me.")

It's not the actual code but simply intended to give you an idea. Hope it helps.

:)


问:
Cassandra Sync and Async, which one is faster to get back the result set?
I'm making some tests on Datastax Cassandra. The case is described as below:

Prerequisite: 1 Cassandra Server, a table with a complex primary key (username, id), the Selection query like this: "select * from table_name where username='abc'; and the result set is the set of 16 rows.

Case 1: execute the query on DevCenter and it takes 1676 ms to finish

Case 2: execute synchronously the query on Java Driver by using "session.execute(statement)" and it takes 441 ms to finish

Case 3: execute the query on Java Driver by using the asynchronous solution as introduced in https://docs.datastax.com/en/developer/java-driver/3.3/manual/async/ and it takes 1121 ms to finish

Is there someone tell me circumstances where the sync/async is more faster?

答: There is no worth to use async approach only for one query but it will give you performance boost for big number of queries, because your code will not wait previous queries to execute next query. </p>


问:
Why cant we print a variable with html names included in it?
I am trying to learn ReactJS.

I have a html selections option as

<option value="navigate">Navigate to <URL> </option>

and I have obtained the selected text in my script

let type = document.getElementById
   ('stepType').options[document.getElementById('stepType').selectedIndex].text;

when i console.log(type) i am getting "Navigate to <URL>"

but when i try to update my div's inner html, all that is getting printed is "Navigate to "

Thanks for putting up with my stupid question, but I would really like to know what is happening underneath, since i know let type = "Navigate to <URL>" would work.

答:
to avoid XXS attach React will render text. If you want to render html use </p>

```<code><div dangerouslySetInnerHTML={{__html: "Navigate to <URL>"}}/>
</code>```

Body:
to avoid XXS attach React will render text. If you want to render html use

<div dangerouslySetInnerHTML={{__html: "Navigate to &lt;URL&gt;"}}/>