问:
C# updating MSAccess data
I'm loading two fields, one from a combo box and the other is a text field.
I want to update the text field with the selection from the combo box.
The display changes, but it's not writing out to the DB.  Any help would be appreciated. - THANKS!!!!!!

```<code>    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'scrumMasterDataSet.Current_Configuration_Settings' table. You can move, or remove it, as needed.
        this.current_Configuration_SettingsTableAdapter.Fill(this.scrumMasterDataSet.Current_Configuration_Settings);
        // TODO: This line of code loads data into the 'scrumMasterDataSet.Teams' table. You can move, or remove it, as needed.
        this.teamsTableAdapter.Fill(this.scrumMasterDataSet.Teams);

    }

    private void team_NamesComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        String status = team_NamesComboBox.Text;
        team_NameTextBox.Text = status;
    }

    private void team_NameTextBox_TextChanged(object sender, EventArgs e)
    {
        //this.teamsTableAdapter.Update(this.scrumMasterDataSet.Teams);
        this.Validate();
        this.current_Configuration_SettingsBindingSource.EndEdit();
        this.current_Configuration_SettingsTableAdapter.Update(this.scrumMasterDataSet.Current_Configuration_Settings);
    }
}
</code>```

}

EDIT:

I'm trying to update the "Current_Configuration_Settings" table with the value the user selects from the "Teams" table.

The "Current_Configuration_Settings" table has 4 fields 'ID', 'Team Name', 'User' and 'Role'

The "Teams" table has two fields 'ID' and 'Team Names'

I have a combo box to select the team name and I copy that over to the 'Team Name' text box that's bound to the Current_Configuration_Settings table.

答:
You aren't actually changing any value in the data table before you call update.

If you're trying to set "Team Name" in the config settings, and assuming the config settings are in row 0, try:

```<code>this.scrumMasterDataSet.Current_Configuration_Settings[0]["Team Name"] = team_NameTextBox.Text;
this.current_Configuration_SettingsTableAdapter.Update(this.scrumMasterDataSet.Current_Configuration_Settings);
</code>```

Title: C# updating MSAccess data

Body:
I'm loading two fields, one from a combo box and the other is a text field.
I want to update the text field with the selection from the combo box.
The display changes, but it's not writing out to the DB.  Any help would be appreciated. - THANKS!!!!!!

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'scrumMasterDataSet.Current_Configuration_Settings' table. You can move, or remove it, as needed.
        this.current_Configuration_SettingsTableAdapter.Fill(this.scrumMasterDataSet.Current_Configuration_Settings);
        // TODO: This line of code loads data into the 'scrumMasterDataSet.Teams' table. You can move, or remove it, as needed.
        this.teamsTableAdapter.Fill(this.scrumMasterDataSet.Teams);

    }

    private void team_NamesComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        String status = team_NamesComboBox.Text;
        team_NameTextBox.Text = status;
    }

    private void team_NameTextBox_TextChanged(object sender, EventArgs e)
    {
        //this.teamsTableAdapter.Update(this.scrumMasterDataSet.Teams);
        this.Validate();
        this.current_Configuration_SettingsBindingSource.EndEdit();
        this.current_Configuration_SettingsTableAdapter.Update(this.scrumMasterDataSet.Current_Configuration_Settings);
    }
}

}

EDIT:

I'm trying to update the "Current_Configuration_Settings" table with the value the user selects from the "Teams" table.

The "Current_Configuration_Settings" table has 4 fields 'ID', 'Team Name', 'User' and 'Role'

The "Teams" table has two fields 'ID' and 'Team Names'

I have a combo box to select the team name and I copy that over to the 'Team Name' text box that's bound to the Current_Configuration_Settings table.

Body:
You aren't actually changing any value in the data table before you call update.

If you're trying to set "Team Name" in the config settings, and assuming the config settings are in row 0, try:

this.scrumMasterDataSet.Current_Configuration_Settings[0]["Team Name"] = team_NameTextBox.Text;
this.current_Configuration_SettingsTableAdapter.Update(this.scrumMasterDataSet.Current_Configuration_Settings);


来源: stackexchange

问:
Vuejs components to wait for initialisation
To give some context, I've a vuejs application using vue-router and vuex.

app.vue Bootstrap code

foo.vue Some component that renders on route /foo

bar.vue Some component that renders on route /bar

When the application starts I need to sync the state reading from device storage. Since this is an async operation it's wrapped on a vue-action and called on app.vue.

When entering the /foo route by the time the component is mounted the $store is not yet update from the device storage

How can all components ensure the initialisation is made before they are mounted?

答:
What I do in these situations is use a v-if on your root <router-view> element to render only when the data you expect to be there has populated, e.g.

```<code><script>
  export default {
    computed: {
      hasLoadedData() {
        // Or whatever criteria you decide on to represent that the
        // app state has finished loading.
        return this.$store.state.something !== null;
      }
    }
  }
</script>

<template>
  <div id="app">
    <router-view v-if="hasLoadedData" />
    <p v-else>Loading...</p>
  </div>
</template>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What I do in these situations is use a v-if on your root <router-view> element to render only when the data you expect to be there has populated, e.g.

<script>
  export default {
    computed: {
      hasLoadedData() {
        // Or whatever criteria you decide on to represent that the
        // app state has finished loading.
        return this.$store.state.something !== null;
      }
    }
  }
</script>

<template>
  <div id="app">
    <router-view v-if="hasLoadedData" />
    <p v-else>Loading...</p>
  </div>
</template>


问:
Read & Write file tag in cocoa app OS X with swift or obj-c
Is there any way to read/write file tags without shell commands? Already tried NSFileManager and CGImageSource classes. No luck so far.

答:
@vadian's answer in Swift 4.0

('NSURLTagNamesKey' has been renamed to 'URLResourceKey.tagNamesKey')

    let url = NSURL(fileURLWithPath: "/Path/to/file.ext")
    var resource : AnyObject?
    do {
        try url.getResourceValue(&resource, forKey: URLResourceKey.tagNamesKey)
        var tags : [String]
        if resource == nil {
            tags = [String]()
        } else {
            tags = resource as! [String]
        }

        print(tags)
        tags += ["Foo"]
        try url.setResourceValue(tags, forKey: URLResourceKey.tagNamesKey)
    } catch let error as NSError {
        print(error)
    }
```

ContentLicense: CC BY-SA 4.0


问:
this pattern-matching is not exhaustive. Ocaml
can someone tell me why does this code# let func [g] a = g a ::[] ;;

output this warning

Warning 8: this pattern-matching is not exhaustive.
  Here is an example of a value that is not matched:
  []

答: The argument [g] will match a single-element list, and bind that element to g. func [f] a will work, but what if the function is applied with an empty list, func [] a, or a list with multiple elements, func [f, g] a? What can it do other than raise an exception? That's what the warning is telling you.


问:
ToLookup, LINQ and Index
I have the following situation (VB.NET, .NET 4):

Generic list of custom objects  letters(Of Letter)

A, B, C, B, D

need a collection containing items and its indexes:

```<code>A (0)
B (1, 3)
C (2)
D (4)
</code>```

Some tries:

```<code>Dim letters As New List(Of Letter)
Dim query As ??? = letters.Select(Function(letter, index) _
                            New With {index, letter})

Dim lookup As Lookup(Of Letter, Integer)
lookup = letters (query).ToLookup(???
</code>```

答:
First use the overload of Select that supports an index to create a tuple(or KeyValuePair) of letter and index. Then use the overload of ToLookUp that takes selectors for both key and value.

You might need to either supply an IEqualityComparer<Letter> to ToLookUp, or override both Letter.Equals and Letter.GetHashCode(). Those two need to be overridden together so they are consistent, or you'll get wrong results.

ContentLicense: CC BY-SA 2.5

Title: ToLookup, LINQ and Index

Body:
I have the following situation (VB.NET, .NET 4):

Generic list of custom objects  letters(Of Letter)

A, B, C, B, D

need a collection containing items and its indexes:

A (0)
B (1, 3)
C (2)
D (4)

Some tries:

Dim letters As New List(Of Letter)
Dim query As ??? = letters.Select(Function(letter, index) _
                            New With {index, letter})

Dim lookup As Lookup(Of Letter, Integer)
lookup = letters (query).ToLookup(???


问:
Tableview causes app to crash when dragged to the bottom
When scrolling further than the last post/item in the tableview, the app crashes and I get error message: "Unexpectedly found nil while unwrapping an Optional value". Like it's trying to find another post that isn't there, but i don't know why... Posts in the tableview appears just as they should.

I believe there is something wrong here:

```<code>    func tableView(_ tableView: UITableView, cellForRowAt indexpath: IndexPath) -> UITableViewCell {

    let post = posts[indexpath.row]

    if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexpath) as? PostCell{
        cell.configureCell(post: post)

        return cell
    } else {
        return PostCell()
    }
}
</code>```

(when I remove the else part, I get this error: "Missing return in a function expected to return 'UITableViewCell' )

```<code>var posts = [Post]()
</code>```

Configuring cell:

```<code>func configureCell(post: Post) {

    self.post = post

    if post.altA.isEmpty == false {
        altALabel.text = post.altA["text"] as? String
        if let votes = post.altA["votes"]{
            self.altAVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt A")
    }

    if post.altB.isEmpty == false {
        altBLabel.text = post.altB["text"] as? String
        if let votes = post.altB["votes"]{
            self.altBVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt B")
    }

    if post.altD.isEmpty == false {
        altDLabel.text = post.altD["text"] as? String
        if let votes = post.altD["votes"]{
            self.altDVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt D")
        altDView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
        altDVotesView.removeFromSuperview()
        altDLabelView.removeFromSuperview()
    }

    if post.altC.isEmpty == false {
        altCLabel.text = post.altC["text"] as? String
        if let votes = post.altC["votes"]{
            self.altCVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt C")
        self.altCView.removeFromSuperview()
        self.botBtnsStackView.removeFromSuperview()
    }

import Foundation
</code>```

class Post {

```<code>private var _text: String!
private var _postKey: String!
private var _backgroundImg: Int!

private var _altA: Dictionary<String, Any>!
private var _altB: Dictionary<String, Any>!
private var _altC: Dictionary<String, Any>!
private var _altD: Dictionary<String, Any>!

//TEXT
var text: String {
    return _text
}

//BACKGROUND
var backgroundImg: Int{
    return _backgroundImg
}

//POSTKEY
var postKey: String{
    return _postKey
}

//ALTERNATIVES
var altA: Dictionary<String, Any> {
    return _altA
}

var altB: Dictionary<String, Any> {
    return _altB
}

var altC: Dictionary<String, Any> {
    return _altC
}

var altD: Dictionary<String, Any> {
    return _altD
}

init(postKey: String, postData: Dictionary<String, Any>) {
    self._postKey = postKey

    if let text = postData["text"]{
        self._text = text as! String
    } else {
        self._text = ""
    }

     if let backgroundImg = postData["backgroundImg"]{
        self._backgroundImg = backgroundImg as! Int
    }

    if let altA = postData["altA"]{
        self._altA = altA as! Dictionary<String, Any>
    }

    if let altB = postData["altB"]{
        self._altB = altB as! Dictionary<String, Any>
    }

    if let altC = postData["altC"]{
        self._altC = altC as! Dictionary<String, Any>
    } else {
        let emptyDictionary = [String: Any]()
        self._altC = emptyDictionary
    }

    if let altD = postData["altD"]{
        self._altD = altD as! Dictionary<String, Any>
    } else {
        let emptyDictionary = [String: Any]()
        self._altD = emptyDictionary
    }
}
</code>```

}

rest of the tableview code(nothing special about it):

```<code> func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}
</code>```

答:
Right, so the issue is that you are removing self.altCView and the other views from superview.

You have to remember that cells are reusable, so whenever they go away from screen they're "dequeued" and reused.

So if a cell is originally an altD cell, and you remove all the other superviews, but then it gets reused as an altC cell. trying to set the label will crash the app since removing from superview will deallocate it from memory (if you are using a weak reference which for some reason is default for IBOutlet's. Another tip, make all your IBOutlets strong I just think it's better)

Once views are removed from superview they're gone forever unless you re-add them so I would avoid doing that on code that runs multiple times like cellForRowAtIndex

Try setting them as hidden (or frame as CGZero) (but again, be wary of cell reuse. assume that the cells you get never have the right values so always set to unhidden if you're using them and always set to hidden if you're not using them. its a common mistake to forget to setHidden = false if you do need it. It might still be hidden from the previous time the cell was used)

Body:
When scrolling further than the last post/item in the tableview, the app crashes and I get error message: "Unexpectedly found nil while unwrapping an Optional value". Like it's trying to find another post that isn't there, but i don't know why... Posts in the tableview appears just as they should.

I believe there is something wrong here:

    func tableView(_ tableView: UITableView, cellForRowAt indexpath: IndexPath) -> UITableViewCell {

    let post = posts[indexpath.row]

    if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexpath) as? PostCell{
        cell.configureCell(post: post)

        return cell
    } else {
        return PostCell()
    }
}

(when I remove the else part, I get this error: "Missing return in a function expected to return 'UITableViewCell' )

var posts = [Post]()

Configuring cell:

func configureCell(post: Post) {

    self.post = post

    if post.altA.isEmpty == false {
        altALabel.text = post.altA["text"] as? String
        if let votes = post.altA["votes"]{
            self.altAVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt A")
    }

    if post.altB.isEmpty == false {
        altBLabel.text = post.altB["text"] as? String
        if let votes = post.altB["votes"]{
            self.altBVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt B")
    }

    if post.altD.isEmpty == false {
        altDLabel.text = post.altD["text"] as? String
        if let votes = post.altD["votes"]{
            self.altDVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt D")
        altDView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
        altDVotesView.removeFromSuperview()
        altDLabelView.removeFromSuperview()
    }

    if post.altC.isEmpty == false {
        altCLabel.text = post.altC["text"] as? String
        if let votes = post.altC["votes"]{
            self.altCVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt C")
        self.altCView.removeFromSuperview()
        self.botBtnsStackView.removeFromSuperview()
    }

import Foundation

class Post {

private var _text: String!
private var _postKey: String!
private var _backgroundImg: Int!

private var _altA: Dictionary<String, Any>!
private var _altB: Dictionary<String, Any>!
private var _altC: Dictionary<String, Any>!
private var _altD: Dictionary<String, Any>!

//TEXT
var text: String {
    return _text
}

//BACKGROUND
var backgroundImg: Int{
    return _backgroundImg
}

//POSTKEY
var postKey: String{
    return _postKey
}

//ALTERNATIVES
var altA: Dictionary<String, Any> {
    return _altA
}

var altB: Dictionary<String, Any> {
    return _altB
}

var altC: Dictionary<String, Any> {
    return _altC
}

var altD: Dictionary<String, Any> {
    return _altD
}

init(postKey: String, postData: Dictionary<String, Any>) {
    self._postKey = postKey

    if let text = postData["text"]{
        self._text = text as! String
    } else {
        self._text = ""
    }

     if let backgroundImg = postData["backgroundImg"]{
        self._backgroundImg = backgroundImg as! Int
    }

    if let altA = postData["altA"]{
        self._altA = altA as! Dictionary<String, Any>
    }

    if let altB = postData["altB"]{
        self._altB = altB as! Dictionary<String, Any>
    }

    if let altC = postData["altC"]{
        self._altC = altC as! Dictionary<String, Any>
    } else {
        let emptyDictionary = [String: Any]()
        self._altC = emptyDictionary
    }

    if let altD = postData["altD"]{
        self._altD = altD as! Dictionary<String, Any>
    } else {
        let emptyDictionary = [String: Any]()
        self._altD = emptyDictionary
    }
}

}

rest of the tableview code(nothing special about it):

 func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}


问:
What is the proper way to create an update trigger with a variable getting value from the same table?
I'm creating a update trigger where an employee can never have a salary that is greater than the president's. However I need to subquery the president's salary for comparison and the "new" updated employee's salary.

I originally had the the subquery using from the from employees table but had to make a new table because of the mutating table problem. I don't think creating a new table is plausible solution for a real implementation.

Is there a way I can save the president's salary without creating a new table?

```<code>CREATE OR REPLACE TRIGGER prevent_salary
BEFORE UPDATE ON employees
FOR EACH ROW
    declare pres_sal number(8,2);
BEGIN
    select salary into pres_sal from employees_salary where job_id='AD_PRES';--employees_salary was employees but that gives mutating error

    IF (:new.salary > pres_sal)
        THEN UPDATE employees
        SET salary = :old.salary
        WHERE employee_id = :old.employee_id;
    END IF;
END;
</code>```

答:
You may try this :</p>

```<code>CREATE OR REPLACE TRIGGER prevent_salary
BEFORE UPDATE ON employees
FOR EACH ROW
    declare pres_sal number(8,2);
BEGIN
    select salary into pres_sal from employees_salary where job_id='AD_PRES';--employees_salary was employees but that gives mutating error

    IF (:new.salary > pres_sal)
     Raise_Application_Error (-20101, 'An employee''s salary couldn''t exceed president''s !');
    END IF;
END;
</code>```

Body:
I'm creating a update trigger where an employee can never have a salary that is greater than the president's. However I need to subquery the president's salary for comparison and the "new" updated employee's salary.

I originally had the the subquery using from the from employees table but had to make a new table because of the mutating table problem. I don't think creating a new table is plausible solution for a real implementation.

Is there a way I can save the president's salary without creating a new table?

CREATE OR REPLACE TRIGGER prevent_salary
BEFORE UPDATE ON employees
FOR EACH ROW
    declare pres_sal number(8,2);
BEGIN
    select salary into pres_sal from employees_salary where job_id='AD_PRES';--employees_salary was employees but that gives mutating error

    IF (:new.salary > pres_sal)
        THEN UPDATE employees
        SET salary = :old.salary
        WHERE employee_id = :old.employee_id;
    END IF;
END;

Body:
You may try this :

CREATE OR REPLACE TRIGGER prevent_salary
BEFORE UPDATE ON employees
FOR EACH ROW
    declare pres_sal number(8,2);
BEGIN
    select salary into pres_sal from employees_salary where job_id='AD_PRES';--employees_salary was employees but that gives mutating error

    IF (:new.salary > pres_sal)
     Raise_Application_Error (-20101, 'An employee''s salary couldn''t exceed president''s !');
    END IF;
END;


问:
Tick tack toe: Python numbers displaying differently in different contexts for no reason
I'm not sure exactly how to describe this problem, so apologies if the title was insufficient.

I'm trying to make a piece of code that will put all possible tick-tack-toe boards (0 is blank, 1 is X, 2 is O) into a 2d array (list of lists). I've successfully found a way to do this:

```<code>import math

boxes = []

for m in range (0, 19683):
    boxes.append([m%3, int(math.floor((m%9)/3))])

print(boxes)
</code>```

And it works. But instead of typing out the next seven list items, I thought it would be easier to iterate over them like so:

```<code>boxes = []

for m in range (0, 19683):
    boxes.append([])

    for s in range (0,9):
        boxes[m].append(int(math.floor((m%(3**(m+1)))/(3**m))))

print(boxes)
</code>```

and it just gave me a big array of zeros! I have no idea why changing it to iteration would do this; I tried with both ** and pow(). DOes anyone know what the problem is?

答:
Looking at your code, I think in your second example you could have meant:

```<code>boxes[m].append(int(math.floor((m%(3**(s+1)))/(3**s))))
</code>```

Also, you can utilise itertools.product() to achieve the same kind of outcome:

```<code>boxes = list(product([0, 1, 2], repeat=9))
</code>```

Body:
I'm not sure exactly how to describe this problem, so apologies if the title was insufficient.

I'm trying to make a piece of code that will put all possible tick-tack-toe boards (0 is blank, 1 is X, 2 is O) into a 2d array (list of lists). I've successfully found a way to do this:

import math

boxes = []

for m in range (0, 19683):
    boxes.append([m%3, int(math.floor((m%9)/3))])

print(boxes)

And it works. But instead of typing out the next seven list items, I thought it would be easier to iterate over them like so:

boxes = []

for m in range (0, 19683):
    boxes.append([])

    for s in range (0,9):
        boxes[m].append(int(math.floor((m%(3**(m+1)))/(3**m))))

print(boxes)

and it just gave me a big array of zeros! I have no idea why changing it to iteration would do this; I tried with both ** and pow(). DOes anyone know what the problem is?

Body:
Looking at your code, I think in your second example you could have meant:

boxes[m].append(int(math.floor((m%(3**(s+1)))/(3**s))))

Also, you can utilise itertools.product() to achieve the same kind of outcome:

boxes = list(product([0, 1, 2], repeat=9))


问:
How to open a URL in python
```<code>import urllib

fun open():
    return urllib.urlopen('http://example.com')
</code>```

But when example.com opens it does not render CSS or JavaScript. How can I open the webpage in a web browser?

```<code>@error(404)
def error404(error):
    return webbrowser.open('http://example.com')
</code>```

I am using bottle. Giving me the error:

```<code>TypeError("'bool' object is not iterable",)
</code>```

答:
I think this is the easy way to open a URL using this function</p>

```<code>webbrowser.open_new_tab(url)
</code>```

Title: How to open a URL in python

Body:
import urllib

fun open():
    return urllib.urlopen('http://example.com')

But when example.com opens it does not render CSS or JavaScript. How can I open the webpage in a web browser?

@error(404)
def error404(error):
    return webbrowser.open('http://example.com')

I am using bottle. Giving me the error:

TypeError("'bool' object is not iterable",)

Body:
I think this is the easy way to open a URL using this function

webbrowser.open_new_tab(url)


问:
Retry PowerShell commands if download fails
We use a PowerShell script that someone made to download new Windows Defender virus definitions from Microsoft to a network location.  There are four files that get downloaded.  The problem is, sometimes one or more of the downloads fail due a network or website issue.  So, I would like any download that fails to automatically retry until successful.  Below is what the relevant part of the script looks like.  Any help would be appreciated.</p>

```<code># Source Addresses - Defender for Windows 10, 8.1 ################################

$sourceAVx86 = "http://go.microsoft.com/fwlink/?LinkID=121721&arch=x86"
$sourceNISx86 = "http://go.microsoft.com/fwlink/?LinkID=187316&arch=x86&nri=true"
$sourceAVx64 = "http://go.microsoft.com/fwlink/?LinkID=121721&arch=x64"
$sourceNISx64 = "http://go.microsoft.com/fwlink/?LinkID=187316&arch=x64&nri=true"

# Web client #####################################################################

$wc = New-Object System.Net.WebClient
$wc.Proxy = [System.Net.WebRequest]::DefaultWebProxy
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

# x86 AV #########################################################################

$Dest = "$Destination\x86\" + 'mpam-fe.exe'
$wc.DownloadFile($sourceAVx86, $Dest)

# x86 NIS ########################################################################

$Dest = "$Destination\x86\" + 'nis_full.exe'
$wc.DownloadFile($sourceNISx86, $Dest)

# x64 AV #########################################################################

$Dest = "$Destination\x64\" + 'mpam-fe.exe'
$wc.DownloadFile($sourceAVx64, $Dest)

# x64 NIS ########################################################################

$Dest = "$Destination\x64\" + 'nis_full.exe'
$wc.DownloadFile($sourceNISx64, $Dest)
</code>```

答:
One approach is to test for the existence of the files at the destination.
If the file does not exist, then retry the download. I put in a variable to set how many times it should attempt the download before moving on.</p>

```<code>$maxAttempts = 5 #set the maximum number of attempts in case the download will never succeed.

$sourceAVx86 = "http://go.microsoft.com/fwlink/?LinkID=121721&arch=x86"
$sourceNISx86 = "http://go.microsoft.com/fwlink/?LinkID=187316&arch=x86&nri=true"
$sourceAVx64 = "http://go.microsoft.com/fwlink/?LinkID=121721&arch=x64"
$sourceNISx64 = "http://go.microsoft.com/fwlink/?LinkID=187316&arch=x64&nri=true"

$wc = New-Object System.Net.WebClient
$wc.Proxy = [System.Net.WebRequest]::DefaultWebProxy
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

#Define destination file paths:
$DestAVx86 = "$Destination\x86\" + 'mpam-fe.exe'
$DestNISx86 = "$Destination\x86\" + 'nis_full.exe'
$DestAVx64 = "$Destination\x64\" + 'mpam-fe.exe'
$DestNISx64 = "$Destination\x64\" + 'nis_full.exe'

#Delete old versions of the files if they exist
if (Test-Path $DestAVx86) {
    Remove-Item $DestAVx86
}
if (Test-Path $DestNISx86) {
    Remove-Item $DestNISx86
}
if (Test-Path $DestAVx64) {
    Remove-Item $DestAVx64
}
if (Test-Path $DestNISx64) {
    Remove-Item $DestNISx64
}

$attemptCount = 0
Do {
    $attemptCount++
    $wc.DownloadFile($sourceAVx86, $Dest)
} while (((Test-Path $DestAVx86) -eq $false) -and ($attemptCount -le $maxAttempts))

$attemptCount = 0
Do {
    $attemptCount++
    $wc.DownloadFile($sourceNISx86, $Dest)
} while (((Test-Path $DestNISx86) -eq $false) -and ($attemptCount -le $maxAttempts))

$attemptCount = 0
Do {
    $attemptCount++
    $wc.DownloadFile($sourceAVx64, $Dest)
} while (((Test-Path $DestAVx64) -eq $false) -and ($attemptCount -le $maxAttempts))

$attemptCount = 0
Do {
    $attemptCount++
    $wc.DownloadFile($sourceNISx64, $Dest)
} while (((Test-Path $DestNISx64) -eq $false) -and ($attemptCount -le $maxAttempts))
</code>```

Body:
We use a PowerShell script that someone made to download new Windows Defender virus definitions from Microsoft to a network location.  There are four files that get downloaded.  The problem is, sometimes one or more of the downloads fail due a network or website issue.  So, I would like any download that fails to automatically retry until successful.  Below is what the relevant part of the script looks like.  Any help would be appreciated.

# Source Addresses - Defender for Windows 10, 8.1 ################################

$sourceAVx86 = "http://go.microsoft.com/fwlink/?LinkID=121721&arch=x86"
$sourceNISx86 = "http://go.microsoft.com/fwlink/?LinkID=187316&arch=x86&nri=true"
$sourceAVx64 = "http://go.microsoft.com/fwlink/?LinkID=121721&arch=x64"
$sourceNISx64 = "http://go.microsoft.com/fwlink/?LinkID=187316&arch=x64&nri=true"

# Web client #####################################################################

$wc = New-Object System.Net.WebClient
$wc.Proxy = [System.Net.WebRequest]::DefaultWebProxy
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

# x86 AV #########################################################################

$Dest = "$Destination\x86\" + 'mpam-fe.exe'
$wc.DownloadFile($sourceAVx86, $Dest)

# x86 NIS ########################################################################

$Dest = "$Destination\x86\" + 'nis_full.exe'
$wc.DownloadFile($sourceNISx86, $Dest)

# x64 AV #########################################################################

$Dest = "$Destination\x64\" + 'mpam-fe.exe'
$wc.DownloadFile($sourceAVx64, $Dest)

# x64 NIS ########################################################################

$Dest = "$Destination\x64\" + 'nis_full.exe'
$wc.DownloadFile($sourceNISx64, $Dest)

Body:
One approach is to test for the existence of the files at the destination.
If the file does not exist, then retry the download. I put in a variable to set how many times it should attempt the download before moving on.

$maxAttempts = 5 #set the maximum number of attempts in case the download will never succeed.

$sourceAVx86 = "http://go.microsoft.com/fwlink/?LinkID=121721&arch=x86"
$sourceNISx86 = "http://go.microsoft.com/fwlink/?LinkID=187316&arch=x86&nri=true"
$sourceAVx64 = "http://go.microsoft.com/fwlink/?LinkID=121721&arch=x64"
$sourceNISx64 = "http://go.microsoft.com/fwlink/?LinkID=187316&arch=x64&nri=true"

$wc = New-Object System.Net.WebClient
$wc.Proxy = [System.Net.WebRequest]::DefaultWebProxy
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

#Define destination file paths:
$DestAVx86 = "$Destination\x86\" + 'mpam-fe.exe'
$DestNISx86 = "$Destination\x86\" + 'nis_full.exe'
$DestAVx64 = "$Destination\x64\" + 'mpam-fe.exe'
$DestNISx64 = "$Destination\x64\" + 'nis_full.exe'

#Delete old versions of the files if they exist
if (Test-Path $DestAVx86) {
    Remove-Item $DestAVx86
}
if (Test-Path $DestNISx86) {
    Remove-Item $DestNISx86
}
if (Test-Path $DestAVx64) {
    Remove-Item $DestAVx64
}
if (Test-Path $DestNISx64) {
    Remove-Item $DestNISx64
}

$attemptCount = 0
Do {
    $attemptCount++
    $wc.DownloadFile($sourceAVx86, $Dest)
} while (((Test-Path $DestAVx86) -eq $false) -and ($attemptCount -le $maxAttempts))

$attemptCount = 0
Do {
    $attemptCount++
    $wc.DownloadFile($sourceNISx86, $Dest)
} while (((Test-Path $DestNISx86) -eq $false) -and ($attemptCount -le $maxAttempts))

$attemptCount = 0
Do {
    $attemptCount++
    $wc.DownloadFile($sourceAVx64, $Dest)
} while (((Test-Path $DestAVx64) -eq $false) -and ($attemptCount -le $maxAttempts))

$attemptCount = 0
Do {
    $attemptCount++
    $wc.DownloadFile($sourceNISx64, $Dest)
} while (((Test-Path $DestNISx64) -eq $false) -and ($attemptCount -le $maxAttempts))


问:
C# Can I add values to a listbox with a backgroundwork thread?
I want my background worker to add items to a list box, it appears to do so when debugging but the listbox doesn't show the values. I suspect this is something to do with adding items whilst inside the background worker thread, do I need to add these to an array and then populate the list box from the array during backgroundWorker1_RunWorkerCompleted?

Thanks for the help.

答:
if you are trying to update a database. From a listbox i would suggest creating a dataset.

for instance, if your doing something for each item in a database. Copy the database dataset, by creating new dataset and declaring by mainDataset.

for example:
// the gridview dataset is dataset1

```<code>BackgroundWorker_DoWork(object sender, DoWorkArgs e)
{
     Dataset dataset2 = dataset1;
     foreach(DataGridViewRow row in GridView)
     {
         //do some work
         dataset2.Main.AddMainRow(values to add);
         dataset2.AcceptChanges();
     }
}

BackgroundWorker_WorkCompleted(object sender, DoWorkArgs e)
{
    //Forces UI thread to valitdate dataset
    dataset2.update();

    // Sets file Path
    string FilePath = "Some Path to file";

    dataset2.writexml(FilePath, XmlWriteOptions.WriteSchema);

    //if you use xml to fill your dataset filepath to write should equal path to dataset1 xml
    dataset1.Refresh();
}
</code>```

OwnerDisplayName: Jayne C

Body:
if you are trying to update a database. From a listbox i would suggest creating a dataset.

for instance, if your doing something for each item in a database. Copy the database dataset, by creating new dataset and declaring by mainDataset.

for example:
// the gridview dataset is dataset1

BackgroundWorker_DoWork(object sender, DoWorkArgs e)
{
     Dataset dataset2 = dataset1;
     foreach(DataGridViewRow row in GridView)
     {
         //do some work
         dataset2.Main.AddMainRow(values to add);
         dataset2.AcceptChanges();
     }
}

BackgroundWorker_WorkCompleted(object sender, DoWorkArgs e)
{
    //Forces UI thread to valitdate dataset
    dataset2.update();

    // Sets file Path
    string FilePath = "Some Path to file";

    dataset2.writexml(FilePath, XmlWriteOptions.WriteSchema);

    //if you use xml to fill your dataset filepath to write should equal path to dataset1 xml
    dataset1.Refresh();
}


问:
C++ Infinite Loop repeating
```<code>int departmentNo;
bool depNumIncorrect = false;
do
{
    depNumIncorrect = false;
    cout << "Please enter your department number... ( 1 / 2 / 3 )" << endl;
    cin >> departmentNo;
    if (departmentNo < 1 || departmentNo > 3)
    {
        cout << "Invalid Entry." << endl;
        depNumIncorrect = true;
    }
} while (depNumIncorrect == true);
</code>```

Whenever I input a correct input (1/2/3), the code works fine and continues without looping. Whenever I input an incorrect integer, the code loops as it is supposed to. But when I input a character or a string, it puts the code into an infinite loop. The "Please enter your department number... ( 1 / 2 / 3 )" is repeatedly output to the console.

How could I go about changing this so that it doesn't start an infinite loop when a character or string is input, but rather loops as it is supposed to and allows me to input again?

答: deparmentNo is (I assume) an Int and you have a problem of conversion. As mentioned by others you should clear error flag of std::cin. Moreover you probably should not cin directly into an int but rather to a string , and then attempting conversion to int. The result of conversion attempt (successful or not) would be an additional criteria to check for valid entry</p>

Title: C++ Infinite Loop repeating

Body:
int departmentNo;
bool depNumIncorrect = false;
do
{
    depNumIncorrect = false;
    cout << "Please enter your department number... ( 1 / 2 / 3 )" << endl;
    cin >> departmentNo;
    if (departmentNo < 1 || departmentNo > 3)
    {
        cout << "Invalid Entry." << endl;
        depNumIncorrect = true;
    }
} while (depNumIncorrect == true);

Whenever I input a correct input (1/2/3), the code works fine and continues without looping. Whenever I input an incorrect integer, the code loops as it is supposed to. But when I input a character or a string, it puts the code into an infinite loop. The "Please enter your department number... ( 1 / 2 / 3 )" is repeatedly output to the console.

How could I go about changing this so that it doesn't start an infinite loop when a character or string is input, but rather loops as it is supposed to and allows me to input again?


问:
Wrap text around with image on the right
I have the below html which has an image and text. I want to wrap the text around the image. I have tried float but it does not seem to work. How can I do this?

using bootstrap.min.css classes – panel-body, col-md-12

```<code><div class="row">
  <div class="col-md-12">
    <div class="col-md-4 pull-right">
      <img class="img-responsive shadow"/>
      <p style="text-align:justify;float:left"> Text paragraph </p>
    </div>
  </div>
</div>
</code>```

答:
edit : Cassidy's answer above is a more elegant, bootstrap-centric fix if that's a better fit for what you're doing.

With your img and p tags in the same container, you can control them relative to one another, using float to position them as you've described.

Using the markup you provided, I've created a jsfiddle with some additions. Of course I've had to make a couple assumptions about what you'd like to do, but in this example is a working "wrap" of some text, around an image.

Basically, I've put both elements as siblings inside of a div, and have floated both elements to the left, allowing the larger text on the right to wrap around the img.

Snippet:

img.float_text_left {
  float: left;
  clear: none;
  margin: 15px;
}
span.float_text_right p {
  width: 65%;
  height: auto;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-md-12">
    <div class="col-md-4 pull-right">
       <div class="float_text_right">
       <img class="img-responsive shadow float_text_left" src="http://www.ducatithailand.com/cms-web/upl/MediaGalleries/549/1/MediaGallery_1549306/Color_M-1200S_Grey-01_1067x600.jpg" width="250"/>

     <span>
       <p class=".float_text_right">
      Lorem ipsum dolor amet microdosing authentic mlkshk ugh, ramps next level enamel pin air plant roof party. Fingerstache artisan art party offal church-key PBR&B subway tile letterpress drinking vinegar bespoke farm-to-table yr. Forage hot chicken artisan retro, migas enamel pin seitan sustainable. Bushwick VHS health goth, austin trust fund thundercats beard small batch green juice sartorial street art iPhone 3 wolf moon hashtag. Shabby chic kitsch brunch, lumbersexual narwhal celiac hot chicken vaporware enamel pin polaroid. Tbh neutra hammock organic master cleanse biodiesel franzen fam pour-over etsy heirloom migas roof party.

Messenger bag meditation forage, tumeric wayfarers pabst sartorial schlitz food truck selfies locavore normcore keffiyeh cray. Selfies dreamcatcher mumblecore jean shorts health goth lyft. Distillery blue bottle actually, coloring book PBR&B letterpress meggings single-origin coffee bespoke iPhone migas palo santo poutine cray vexillologist. Slow-carb leggings meggings, fashion axe scenester XOXO single-origin coffee. Deep v pug synth ramps, VHS hammock man bun intelligentsia single-origin coffee.
     </p>
     </span>

      </div>
    </div>
  </div>
</div></code>```

Body:
I have the below html which has an image and text. I want to wrap the text around the image. I have tried float but it does not seem to work. How can I do this?

using bootstrap.min.css classes – panel-body, col-md-12

 Text paragraph

Body:
edit : Cassidy's answer above is a more elegant, bootstrap-centric fix if that's a better fit for what you're doing.

With your img and p tags in the same container, you can control them relative to one another, using float to position them as you've described.

Using the markup you provided, I've created a jsfiddle with some additions. Of course I've had to make a couple assumptions about what you'd like to do, but in this example is a working "wrap" of some text, around an image.

Basically, I've put both elements as siblings inside of a div, and have floated both elements to the left, allowing the larger text on the right to wrap around the img.

Snippet:

img.float_text_left {
  float: left;
  clear: none;
  margin: 15px;
}
span.float_text_right p {
  width: 65%;
  height: auto;
  float: left;
}

<div class="row">
  <div class="col-md-12">
    <div class="col-md-4 pull-right">
       <div class="float_text_right">
       <img class="img-responsive shadow float_text_left" src="http://www.ducatithailand.com/cms-web/upl/MediaGalleries/549/1/MediaGallery_1549306/Color_M-1200S_Grey-01_1067x600.jpg" width="250"/>

     <span>
       <p class=".float_text_right">
      Lorem ipsum dolor amet microdosing authentic mlkshk ugh, ramps next level enamel pin air plant roof party. Fingerstache artisan art party offal church-key PBR&B subway tile letterpress drinking vinegar bespoke farm-to-table yr. Forage hot chicken artisan retro, migas enamel pin seitan sustainable. Bushwick VHS health goth, austin trust fund thundercats beard small batch green juice sartorial street art iPhone 3 wolf moon hashtag. Shabby chic kitsch brunch, lumbersexual narwhal celiac hot chicken vaporware enamel pin polaroid. Tbh neutra hammock organic master cleanse biodiesel franzen fam pour-over etsy heirloom migas roof party.

Messenger bag meditation forage, tumeric wayfarers pabst sartorial schlitz food truck selfies locavore normcore keffiyeh cray. Selfies dreamcatcher mumblecore jean shorts health goth lyft. Distillery blue bottle actually, coloring book PBR&B letterpress meggings single-origin coffee bespoke iPhone migas palo santo poutine cray vexillologist. Slow-carb leggings meggings, fashion axe scenester XOXO single-origin coffee. Deep v pug synth ramps, VHS hammock man bun intelligentsia single-origin coffee.
     </p>
     </span>

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


问:
grep: finding a string that starts and ends with a specific letter in directory
I am teaching myself commands and different ways to use grep. I know how to search for a string in a directory and its sub directories, but I am confused when it comes to searching for a split in the string.

for example: how could I search for all words (string size varies) that starts with a and ends with e. so that I could find ape or apple in text files?

EDIT UPDATE:
I am not sure of the grep version I am using, but I tried using:

" grep -nr "a[A-Za-z]*e" "

this produces the answer by including outputs like ape and apple but it also includes apes which is NOT wanted.

答:
As alluded to in various comments, it is possible to do this using POSIX standard grep -E, but it is not all that notationally convenient.

I used a script file grep-ape.sh containing:

```<code>grep -E -e '(^|[^[:alpha:]])a[[:alpha:]]+e($|[^[:alpha:]])' "$@"
</code>```

The -E enables extended regular expressions.  The -e is optional, but allows me to add extra options as 'file names' after the regular expression.  The regular expression looks for either 'start of line' or a non-alpha character, followed by a, one or more additional alpha characters, an e and either 'end of line' or a non-alpha character.

Given the data file (called, unimaginatively, data):

```<code>I want to tape the apes that ate the grapes.
ape at the start.
Ending with ape
Situating ape in the middle
And an apple too.
But not apples, no way.
The tape ran out.
The apes ran out.
The grapes ran out.
They ate them.
</code>```

I could run grep-ape.sh -n data (demonstrating the usefulness of the -e option, though GNU systems will permute options so you don't necessarily spot the problem), and got:

```<code>1:I want to tape the apes that ate the grapes.
2:ape at the start.
3:Ending with ape
4:Situating ape in the middle
5:And an apple too.
10:They ate them.
</code>```

Using a non-POSIX option -o (supported by GNU and BSD versions of grep) to print only what is matched, I can get the output:

```<code>$ grep-ape.sh -n -o data
1: ate
2:ape
3: ape
4: ape
5: apple
10: ate
$
</code>```

This shows that the regular expression is picking up the acceptable words, even on lines where there are words that would not be acceptable when not in the company of words that are acceptable.

Body:
As alluded to in various comments, it is possible to do this using POSIX standard grep -E, but it is not all that notationally convenient.

I used a script file grep-ape.sh containing:

grep -E -e '(^|[^[:alpha:]])a[[:alpha:]]+e($|[^[:alpha:]])' "$@"

The -E enables extended regular expressions.  The -e is optional, but allows me to add extra options as 'file names' after the regular expression.  The regular expression looks for either 'start of line' or a non-alpha character, followed by a, one or more additional alpha characters, an e and either 'end of line' or a non-alpha character.

Given the data file (called, unimaginatively, data):

I want to tape the apes that ate the grapes.
ape at the start.
Ending with ape
Situating ape in the middle
And an apple too.
But not apples, no way.
The tape ran out.
The apes ran out.
The grapes ran out.
They ate them.

I could run grep-ape.sh -n data (demonstrating the usefulness of the -e option, though GNU systems will permute options so you don't necessarily spot the problem), and got:

1:I want to tape the apes that ate the grapes.
2:ape at the start.
3:Ending with ape
4:Situating ape in the middle
5:And an apple too.
10:They ate them.

Using a non-POSIX option -o (supported by GNU and BSD versions of grep) to print only what is matched, I can get the output:

$ grep-ape.sh -n -o data
1: ate
2:ape
3: ape
4: ape
5: apple
10: ate
$

This shows that the regular expression is picking up the acceptable words, even on lines where there are words that would not be acceptable when not in the company of words that are acceptable.


问:
syntax highlighting in JEditorPane
i want to do tag hightlighting in jeditorpane. if i load a html file in jeditorpane then it should automatically highlight all tags with red foreground color...
for ex.

 &l tHTML &gt

</p>

答: I've had a lot of success using the excellent RSyntaxTextArea component. It's available under the LGPL license too.</p>

Title: syntax highlighting in JEditorPane


问:
Woocommerce deletes all carts
I'm new to woocommerce, I'm having a problem my customers day to day add products to the cart, they finish the order in 5-6 days, but sometimes after 2 days the users are forced logeed out from WP and the carts are cleaned.

Or simply when they log out the cart is empty. I don't want this behavior. Is there some way to save the cart in the DB? or there is other way to fix this behavior?

答:
You may use this filters to adjust the period where products are in cart, remember that they are reduced from stock when added to cart.

```<code>add_filter('wc_session_expiring'   , 'my_wc_session_expiring') );

add_filter('wc_session_expiration' , 'my_wc_session_expiration') );
{

function my_wc_session_expiring($seconds) {
    return (60 * 60 * 24 * 8) - (60 * 60);
}
function my_wc_session_expiration($seconds) {
    return 60 * 60 * 24 * 8;
}
</code>```

This should be adapted to your case.

Let me know if it helps.

Title: Woocommerce deletes all carts

Body:
You may use this filters to adjust the period where products are in cart, remember that they are reduced from stock when added to cart.

add_filter('wc_session_expiring'   , 'my_wc_session_expiring') );

add_filter('wc_session_expiration' , 'my_wc_session_expiration') );
{

function my_wc_session_expiring($seconds) {
    return (60 * 60 * 24 * 8) - (60 * 60);
}
function my_wc_session_expiration($seconds) {
    return 60 * 60 * 24 * 8;
}

This should be adapted to your case.

Let me know if it helps.


问:
Building Python with SSL support in non-standard location
I need to install several Python modules on a RHEL where I don't have root access. At least one of the modules also needs access to Python.h.

In this case I find that the best thing is to install python and it dependencies in ~/local. It usually just works, but this time Python fails to build the SSL module (see details below). Here's the trace of what I'm doing.

So I  downloaded python 6 source and off I went:

```<code>./configure --prefix=/home/fds/rms/local
make >& make.log
</code>```

An inspection to log reveals that ssl module has not been compiled, but there is no mention of the cause (no other occurence of ssl in make or configure):

```<code>Failed to find the necessary bits to build these modules:
_bsddb             _curses            _curses_panel
_hashlib           _sqlite3           _ssl   <----------
</code>```

So I figure, python is not finding any ssl library at all (which is strange, but hey...). So I download openssl-0.9.8r and

```<code>./config --prefix=/home/fds/rms/local shared
make
make install
</code>```

Now back to Python, I ./configure and make again. It fails, but this time it's different:

```<code>Failed to build these modules:
_hashlib           _ssl
</code>```

A closer inspection to the log file reveals this:

```<code>gcc -pthread -shared build/temp.linux-x86_64-2.6/home/fds/rms/installers/Python-2.6.6/Modules/_ssl.o -L/home/fds/rms/local/lib -L/usr/local/lib -lssl -lcrypto -o build/lib.linux-x86_64-2.6/_ssl.so
*** WARNING: renaming "_ssl" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory
</code>```

So now it's picking up the library but not quite getting it right (the file is there where is should be):

```<code>$ find /home/fds/rms/local -iname libssl.so.0.9.8
/home/fds/rms/local/lib/libssl.so.0.9.8
</code>```

Next thing is tracing make and see where is it looking for the file:

```<code>$ strace -f make 2>&1 | grep libssl.so.0.9.8
[pid  5584] open("/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/tls/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or   directory)
[pid  5584] open("/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] write(1, "*** WARNING: renaming \"_ssl\" sin"..., 131*** WARNING: renaming "_ssl" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory
[pid  5584] open("/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] write(1, "*** WARNING: renaming \"_hashlib\""..., 135*** WARNING: renaming "_hashlib" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory
</code>```

Mhhh, it's looking in all the wrong places. I try to give a hint:

```<code>CPPFLAGS="-I/home/fds/rms/local/include -I/home/fds/rms/local/include/openssl" LDFLAGS="-L/home/fds/rms/local/lib" ./configure --prefix=/home/fds/rms/local
</code>```

But nothing changes, and make does not seem to try /home/fds/rms/local/lib at all.

I haven't done this in years, so maybe I'm overlooking something. Can anyone help with the problem?

答:
I have a set of a couple of patches for static openssl and static libintl for 2 and 3 below.

For openssl (first patch) you have to set the env var OPENSSL_ROOT.

This is based on the patch from http://gist.github.com/eddy-geek/9604982 .

For Python 2.7.14:

https://gist.github.com/rkitover/2d9e5baff1f1cc4f2618dee53083bd35

https://gist.github.com/rkitover/afab7ed3ac7ce1860c43a258571c8ae1

For Python 3.6.3:

https://gist.github.com/rkitover/93d89a679705875c59275fb0a8f22b45

https://gist.github.com/rkitover/b18f19eafda3775a9652cc9cdf3ec914

Body:
I need to install several Python modules on a RHEL where I don't have root access. At least one of the modules also needs access to Python.h.

In this case I find that the best thing is to install python and it dependencies in ~/local. It usually just works, but this time Python fails to build the SSL module (see details below). Here's the trace of what I'm doing.

So I  downloaded python 6 source and off I went:

./configure --prefix=/home/fds/rms/local
make >& make.log

An inspection to log reveals that ssl module has not been compiled, but there is no mention of the cause (no other occurence of ssl in make or configure):

Failed to find the necessary bits to build these modules:
_bsddb             _curses            _curses_panel
_hashlib           _sqlite3           _ssl   <----------

So I figure, python is not finding any ssl library at all (which is strange, but hey...). So I download openssl-0.9.8r and

./config --prefix=/home/fds/rms/local shared
make
make install

Now back to Python, I ./configure and make again. It fails, but this time it's different:

Failed to build these modules:
_hashlib           _ssl

A closer inspection to the log file reveals this:

gcc -pthread -shared build/temp.linux-x86_64-2.6/home/fds/rms/installers/Python-2.6.6/Modules/_ssl.o -L/home/fds/rms/local/lib -L/usr/local/lib -lssl -lcrypto -o build/lib.linux-x86_64-2.6/_ssl.so
*** WARNING: renaming "_ssl" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory

So now it's picking up the library but not quite getting it right (the file is there where is should be):

$ find /home/fds/rms/local -iname libssl.so.0.9.8
/home/fds/rms/local/lib/libssl.so.0.9.8

Next thing is tracing make and see where is it looking for the file:

$ strace -f make 2>&1 | grep libssl.so.0.9.8
[pid  5584] open("/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/tls/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or   directory)
[pid  5584] open("/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/x86_64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] write(1, "*** WARNING: renaming \"_ssl\" sin"..., 131*** WARNING: renaming "_ssl" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory
[pid  5584] open("/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/tls/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] open("/usr/lib64/libssl.so.0.9.8", O_RDONLY) = -1 ENOENT (No such file or directory)
[pid  5584] write(1, "*** WARNING: renaming \"_hashlib\""..., 135*** WARNING: renaming "_hashlib" since importing it failed: libssl.so.0.9.8: cannot open shared object file: No such file or directory

Mhhh, it's looking in all the wrong places. I try to give a hint:

CPPFLAGS="-I/home/fds/rms/local/include -I/home/fds/rms/local/include/openssl" LDFLAGS="-L/home/fds/rms/local/lib" ./configure --prefix=/home/fds/rms/local

But nothing changes, and make does not seem to try /home/fds/rms/local/lib at all.

I haven't done this in years, so maybe I'm overlooking something. Can anyone help with the problem?


问:
Running Spark2 from Oozie (CDH)
I am attempting to run a spark job (using spark2-submit) from Oozie, so this job can be run on a schedule.

The job runs just fine when running we run the shell script from command-line under our service account (not Yarn). When we run it as a Oozie Workflow the following happens:

```<code>17/11/16 12:03:55 ERROR spark.SparkContext: Error initializing SparkContext.
org.apache.hadoop.security.AccessControlException: Permission denied:
user=yarn, access=WRITE, inode="/user":hdfs:supergroup:drwxrwxr-x
</code>```

Oozie is running the job as the user Yarn. IT has denied us any ability to change Yarn's permissions in HDFS, and there is not a single reference to the user directory in the Spark script. We have attempted to ssh into the server - though this doesn't work - we have to ssh out of our worker nodes, onto the master.

The shell script:

```<code>spark2-submit --name "SparkRunner" --master yarn --deploy-mode client --class org.package-name.Runner  hdfs://manager-node-hdfs/Analytics/Spark_jars/SparkRunner.jar
</code>```

Any help would be appreciated.

答:
You need to add "<env-var>HADOOP_USER_NAME=${wf:user()}</env-var>" into the shell action of your oozie workflow.xml. So that oozie uses the home directory of the user which has triggred the oozie worklfow rather than using the yarn home directory.

e.g

```<code><action name='shellaction'>
        <shell xmlns="uri:oozie:shell-action:0.1">
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <exec>sparksubmitShellScript.sh</exec>
            <argument>${providearg}</argument>
            <env-var>HADOOP_USER_NAME=${wf:user()}</env-var>
            <file>${appPath}/sparksubmitShellScript.sh#sparksubmitShellScript.sh
            </file>
        </shell>
    </action>
</code>```

Modify as per your workflow
if required you can directly mention the user name as well rather than using the user which triggered the workflow as below

```<code><env-var>HADOOP_USER_NAME=${userName}</env-var>
</code>```

specify userName=usernamevalue in your job.properties

Title: Running Spark2 from Oozie (CDH)

Body:
I am attempting to run a spark job (using spark2-submit) from Oozie, so this job can be run on a schedule.

The job runs just fine when running we run the shell script from command-line under our service account (not Yarn). When we run it as a Oozie Workflow the following happens:

17/11/16 12:03:55 ERROR spark.SparkContext: Error initializing SparkContext.
org.apache.hadoop.security.AccessControlException: Permission denied:
user=yarn, access=WRITE, inode="/user":hdfs:supergroup:drwxrwxr-x

Oozie is running the job as the user Yarn. IT has denied us any ability to change Yarn's permissions in HDFS, and there is not a single reference to the user directory in the Spark script. We have attempted to ssh into the server - though this doesn't work - we have to ssh out of our worker nodes, onto the master.

The shell script:

spark2-submit --name "SparkRunner" --master yarn --deploy-mode client --class org.package-name.Runner  hdfs://manager-node-hdfs/Analytics/Spark_jars/SparkRunner.jar

Any help would be appreciated.

Body:
You need to add "<env-var>HADOOP_USER_NAME=${wf:user()}</env-var>" into the shell action of your oozie workflow.xml. So that oozie uses the home directory of the user which has triggred the oozie worklfow rather than using the yarn home directory.

e.g

<action name='shellaction'>
        <shell xmlns="uri:oozie:shell-action:0.1">
            <job-tracker>${jobTracker}</job-tracker>
            <name-node>${nameNode}</name-node>
            <exec>sparksubmitShellScript.sh</exec>
            <argument>${providearg}</argument>
            <env-var>HADOOP_USER_NAME=${wf:user()}</env-var>
            <file>${appPath}/sparksubmitShellScript.sh#sparksubmitShellScript.sh
            </file>
        </shell>
    </action>

Modify as per your workflow
if required you can directly mention the user name as well rather than using the user which triggered the workflow as below

<env-var>HADOOP_USER_NAME=${userName}</env-var>

specify userName=usernamevalue in your job.properties


答:
Add the float-left class (Bootstrap 4) to the img :)

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />

      <img data-src="holder.js/200x200" class="img-thumbnail img-responsive shadow float-left" alt="200x200" style="width: 200px; height: 200px;" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22200%22%20height%3D%22200%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20200%20200%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15fc706eff6%20text%20%7B%20fill%3Argba(255%2C255%2C255%2C.75)%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15fc706eff6%22%3E%3Crect%20width%3D%22200%22%20height%3D%22200%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2274.4296875%22%20y%3D%22104.5%22%3E200x200%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E"
        data-holder-rendered="true">

 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscingelit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

```

https://getbootstrap.com/docs/4.0/utilities/text/

Title: Wrap text around with image on the right

Body:
Add the float-left class (Bootstrap 4) to the img :)

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
  <div class="col-md-12">
    <div class="col-md-4 pull-right">

      <img data-src="holder.js/200x200" class="img-thumbnail img-responsive shadow float-left" alt="200x200" style="width: 200px; height: 200px;" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22200%22%20height%3D%22200%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20200%20200%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_15fc706eff6%20text%20%7B%20fill%3Argba(255%2C255%2C255%2C.75)%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_15fc706eff6%22%3E%3Crect%20width%3D%22200%22%20height%3D%22200%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2274.4296875%22%20y%3D%22104.5%22%3E200x200%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E"
        data-holder-rendered="true">

      <p class="text-justify"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscingelit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>

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

https://getbootstrap.com/docs/4.0/utilities/text/


问:
Have you ever obtained a significant speedup by using boost::pool?
I've played with boost::pool a few times in places where it seemed to me I was seriously hammering the heap with a lot of object "churn".  Generally I've used boost::object_pool, or boost::pool_alloc as an STL template parameter.  However the result is invariably that performance is virtually unchanged, or significantly worsened.

I'm curious to hear of any success stories with it.

What sort of things should I look for in profiling output which might indicate boost::pool is likely to help ?

Is it just actually pretty hard to improve on good old malloc ?

答:
Blind optimizations are not good. Try to use google memory allocator, you don't even need to recompile your application. You can find what you need to know in here:

http://google-perftools.googlecode.com/svn/trunk/doc/tcmalloc.html

Gaetano

OwnerDisplayName: timday

OwnerDisplayName: kalman


问:
UI best practice question: Cancel button or Cancel link
I have a discussion with a colleague about what the "web standard" is for canceling in an form. In our discussion we have a "change password" page as example. We have a designed "send" button and "cancel" button. Both the same design.

He claims that in web standard a cancel button is no longer a button but a link transferring the user to another page. In my opinion, for those pages including a cancel button it actually is a cancel button which either resets the form and/or send the user to the prevision page.

Who is correct? Link or button... or both? And why? Any links to where this kind of standard is decided?

Br,

Paul Peelen

EDIT
I guess the answer with most votes will be the "correct answer"?

答:
Here is some actual primary research into just this question, I won't add any subjective opinion on top...

Primary & Secondary Actions in Web Forms - probably the best research I've come across into exactly this question

Reset and Cancel Buttons - an article from 2000, pointing out that reset functionality is harmful and cancel functions are often unnecessary

OK–Cancel or Cancel–OK? - sticking to a standard order helps usability

The best answer I could give - test both, see which one works best.

On a side note, I wouldn't call this 'web standard', that has meaning towards front-end web technologies (HTML, CSS etc.), I would say 'UI best practice' fits better.


问:
Configure atomikos for hazelcast
How can i configure Atomikos for HazelCast instance.As per the mastering-hazel cast we can only do it in java.How can i configure like i do for databases.If configuring is java is the way,then how i can make use of TransactionalTask to remove the boilerplate code starting and committing the transactions.i have tried like

```<code>public void insertIntoGridJTA( final List<String> list)
            throws NotSupportedException, SystemException,
            IllegalStateException, RollbackException {
        HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
        HazelcastXAResource xaResource = hazelcast.getXAResource();
        TransactionContext context = xaResource.getTransactionContext();
        hazelcast.executeTransaction(new  TransactionalTask<Object>() {
        public Object execute(TransactionalTaskContext context)
                    throws TransactionException {
                // TODO Auto-generated method stub
            TransactionalMap<Integer, String> map = context.getMap("demo");
            System.out.println("map"+map.getName());
            for (int i = 0; i < list.size(); i++) {
                map.put(i, list.get(i));
            }
                return null;
        }
        });
    }
</code>```

But the transaction is not starting if i am using TransactionalTask

答:
In addition to @noctarius, I have done it like this in the past</p>

```<code>@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private HazelcastXAResource hzXAResource;
@Autowired
private UserTransactionManager userTransactionManager;

@Transactional
public void insert() throws SystemException, RollbackException {
    final Transaction transaction = userTransactionManager.getTransaction();
    transaction.enlistResource(hzXAResource);
    final TransactionContext hzTransactionContext = hzXAResource.getTransactionContext();
    final TransactionalMap<Long, String> hzCustomerMap = hzTransactionContext.getMap("hzCustomerMap");

    // Use a Java 8 stream to print out each tuple of the list
    CUSTOMERS_TEST_DATA.forEach(customer -> {
        log.info("Inserting customer record for {}", customer);
        hzCustomerMap.put(customer.getId(), customer.toString());
    });
    jdbcTemplate.batchUpdate(Sql.SQL_INSERT.getSql(), new BatchPreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setString(1, CUSTOMERS_TEST_DATA.get(i).getFirstName());
            ps.setString(2, CUSTOMERS_TEST_DATA.get(i).getLastName());
        }

        @Override
        public int getBatchSize() {
            return CUSTOMERS_TEST_DATA.size();
        }
    });

    // Uncomment this to test the failure of the transaction
    //        hzCustomerMap.values((Predicate) entry -> {
    //            throw new RuntimeException();
    //        });

    transaction.delistResource(hzXAResource, XAResource.TMSUCCESS);
}
</code>```

Title: Configure atomikos for hazelcast

Body:
How can i configure Atomikos for HazelCast instance.As per the mastering-hazel cast we can only do it in java.How can i configure like i do for databases.If configuring is java is the way,then how i can make use of TransactionalTask to remove the boilerplate code starting and committing the transactions.i have tried like

public void insertIntoGridJTA( final List<String> list)
            throws NotSupportedException, SystemException,
            IllegalStateException, RollbackException {
        HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance();
        HazelcastXAResource xaResource = hazelcast.getXAResource();
        TransactionContext context = xaResource.getTransactionContext();
        hazelcast.executeTransaction(new  TransactionalTask<Object>() {
        public Object execute(TransactionalTaskContext context)
                    throws TransactionException {
                // TODO Auto-generated method stub
            TransactionalMap<Integer, String> map = context.getMap("demo");
            System.out.println("map"+map.getName());
            for (int i = 0; i < list.size(); i++) {
                map.put(i, list.get(i));
            }
                return null;
        }
        });
    }

But the transaction is not starting if i am using TransactionalTask

Body:
In addition to @noctarius, I have done it like this in the past

@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private HazelcastXAResource hzXAResource;
@Autowired
private UserTransactionManager userTransactionManager;

@Transactional
public void insert() throws SystemException, RollbackException {
    final Transaction transaction = userTransactionManager.getTransaction();
    transaction.enlistResource(hzXAResource);
    final TransactionContext hzTransactionContext = hzXAResource.getTransactionContext();
    final TransactionalMap<Long, String> hzCustomerMap = hzTransactionContext.getMap("hzCustomerMap");

    // Use a Java 8 stream to print out each tuple of the list
    CUSTOMERS_TEST_DATA.forEach(customer -> {
        log.info("Inserting customer record for {}", customer);
        hzCustomerMap.put(customer.getId(), customer.toString());
    });
    jdbcTemplate.batchUpdate(Sql.SQL_INSERT.getSql(), new BatchPreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setString(1, CUSTOMERS_TEST_DATA.get(i).getFirstName());
            ps.setString(2, CUSTOMERS_TEST_DATA.get(i).getLastName());
        }

        @Override
        public int getBatchSize() {
            return CUSTOMERS_TEST_DATA.size();
        }
    });

    // Uncomment this to test the failure of the transaction
    //        hzCustomerMap.values((Predicate) entry -> {
    //            throw new RuntimeException();
    //        });

    transaction.delistResource(hzXAResource, XAResource.TMSUCCESS);
}


问:
Google Geocode with PHP
I'm trying to get latitude and longitude from Google's Geocode API. The $url I'm using outputs the correct JSON however something in my script isn't working correctly. It's not outputting the $lati & $longi variables. Please check see the script below:

PHP:

```<code><?php
$address   = 'Tempe AZ';
$address   = urlencode($address);
$url       = "https://maps.google.com/maps/api/geocode/json?sensor=false&address={$address}";
$resp_json = file_get_contents($url);
$resp      = json_decode($resp_json, true);

    if ($resp['status'] == 'OK') {
        // get the important data
        $lati  = $resp['results'][0]['geometry']['location']['lat'];
        $longi = $resp['results'][0]['geometry']['location']['lng'];
        echo $lati;
        echo $longi;

    } else {
        return false;
    }

?>
</code>```

答:
Your script works for me too. Maybe you will get an error calling:

$resp_json = file_get_contents($url);.

If that happens you should do this:

```<code>$resp_json = @file_get_contents($url);
 if ($resp_json === FALSE) {
  ///logic for exception
} else {
  ///do your logic hear
}
</code>```

Title: Google Geocode with PHP

Body:
I'm trying to get latitude and longitude from Google's Geocode API. The $url I'm using outputs the correct JSON however something in my script isn't working correctly. It's not outputting the $lati & $longi variables. Please check see the script below:

PHP:

<?php
$address   = 'Tempe AZ';
$address   = urlencode($address);
$url       = "https://maps.google.com/maps/api/geocode/json?sensor=false&address={$address}";
$resp_json = file_get_contents($url);
$resp      = json_decode($resp_json, true);

    if ($resp['status'] == 'OK') {
        // get the important data
        $lati  = $resp['results'][0]['geometry']['location']['lat'];
        $longi = $resp['results'][0]['geometry']['location']['lng'];
        echo $lati;
        echo $longi;

    } else {
        return false;
    }

?>

Body:
Your script works for me too. Maybe you will get an error calling:

$resp_json = file_get_contents($url);.

If that happens you should do this:

$resp_json = @file_get_contents($url);
 if ($resp_json === FALSE) {
  ///logic for exception
} else {
  ///do your logic hear
}


问:
reactjs - can not read property push of undefined
I have this code. What I want to do is when I click a button 'feature' it will take me to index route. However, React keeps saying 'can not read property push of undefined' What I've done wrong?

route.js

```<code>import React from "react";
import ReactDOM from "react-dom";
import {Router, Route, hashHistory, IndexRoute } from "react-router";

import Layout from "./page/Layout";
import Features from "./page/Features";
import Features from "./page/archive";

const app = document.getElementById('app');

ReactDOM.render(
    <Router history={hashHistory}>
        <Route path="/" component={Layout}>
            <IndexRoute component={Features} />
            <Route path="archive" component={Archive} />
        </Route>
    </Router>, app);
</code>```

Layout component

```<code>import React from "react";
import {Link, Router, Route, hashHistory} from "react-router";
export default class Layout extends React.Component{
    navigate(){
        this.context.router.push('/');
    }
    render(){
        return(
            <div>
                {this.props.children}
                <button onClick={this.navigate.bind(this)}>feature</button>
            </div>
        )
    }
}
</code>```

package.json - partial

```<code>"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.1"
 "history": "^2.0.1",
</code>```

-------------update to jordan's answer-------------

答:
You don't need to use browserHistory anymore.
React-router-dom inject into your component route related props and context.
One of this props is 'history' and on this history object is a function push that you can call and pass the route you want to navigate to.

example in a Class base component, you can create a function like below as an onClick handler to redirect to specific link

```<code>redirectToPage() {
 this.props.history.push('/page'); OR
 this.context.router.history.push('/page');
}
</code>```

while in a function base stateless component

```<code>redirectToSessionStatePage() {
 props.history.push('/page');OR
 context.router.history.push('/page');
}
</code>```

Body:
I have this code. What I want to do is when I click a button 'feature' it will take me to index route. However, React keeps saying 'can not read property push of undefined' What I've done wrong?

route.js

import React from "react";
import ReactDOM from "react-dom";
import {Router, Route, hashHistory, IndexRoute } from "react-router";

import Layout from "./page/Layout";
import Features from "./page/Features";
import Features from "./page/archive";

const app = document.getElementById('app');

ReactDOM.render(
    <Router history={hashHistory}>
        <Route path="/" component={Layout}>
            <IndexRoute component={Features} />
            <Route path="archive" component={Archive} />
        </Route>
    </Router>, app);

Layout component

import React from "react";
import {Link, Router, Route, hashHistory} from "react-router";
export default class Layout extends React.Component{
    navigate(){
        this.context.router.push('/');
    }
    render(){
        return(

                {this.props.children}
                <button onClick={this.navigate.bind(this)}>feature</button>

        )
    }
}

package.json - partial

"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.1"
 "history": "^2.0.1",

-------------update to jordan's answer-------------

Body:
You don't need to use browserHistory anymore.
React-router-dom inject into your component route related props and context.
One of this props is 'history' and on this history object is a function push that you can call and pass the route you want to navigate to.

example in a Class base component, you can create a function like below as an onClick handler to redirect to specific link

redirectToPage() {
 this.props.history.push('/page'); OR
 this.context.router.history.push('/page');
}

while in a function base stateless component

redirectToSessionStatePage() {
 props.history.push('/page');OR
 context.router.history.push('/page');
}


问:
Ionic2 - Base64 PDF
I am currently developing a mobile project using Cordova and Ionic2 using an external database resource that connects to the mobile via REST webServices.

The database has documents pdf saved that you have to send to the mobile and view the same. I am using the pdf in enconding Base64 through the webservices by Json.

I can get the string in base64, but I do not quite understand how to decode it and save it on mobile, which is Android to be able to see it.

答:
I had a similar battle with PDF's, but dealing with them in binary/Blob form.  Similar problem/solution overall.  It seems that PDF opening isn't as simple as it should be across Web/Android/iOS.

Open createObjectURL Blob on Cordova InAppBrowser

Title: Ionic2 - Base64 PDF


问:
Importing module from network
Is there a way to get python to read modules from a network?

We have many machines and it would be a too much effort to update each machine manually each time I change a module so I want python to get the modules from a location on the network.

Any ideas?

答:
How I ended up doing this:

Control Panel\All Control Panel Items\System >> Advanced >> Environment Variables >> System Variables >> New >> Name = PYTHONPATH, value = \server\scriptFolder

Thanks everyone for all the help :)

Title: Importing module from network


问:
Tick tack toe: Python numbers displaying differently in different contexts for no reason
I'm not sure exactly how to describe this problem, so apologies if the title was insufficient.

I'm trying to make a piece of code that will put all possible tick-tack-toe boards (0 is blank, 1 is X, 2 is O) into a 2d array (list of lists). I've successfully found a way to do this:

```<code>import math

boxes = []

for m in range (0, 19683):
    boxes.append([m%3, int(math.floor((m%9)/3))])

print(boxes)
</code>```

And it works. But instead of typing out the next seven list items, I thought it would be easier to iterate over them like so:

```<code>boxes = []

for m in range (0, 19683):
    boxes.append([])

    for s in range (0,9):
        boxes[m].append(int(math.floor((m%(3**(m+1)))/(3**m))))

print(boxes)
</code>```

and it just gave me a big array of zeros! I have no idea why changing it to iteration would do this; I tried with both ** and pow(). DOes anyone know what the problem is?

答:
Let's look at that inner expression:

```<code>math.floor(m%(3**(m+1)))/(3**m)
</code>```

The numerator is simply m: you take it modulus 3^(m+1), which will be larger than m.  The next step is then m / (3**m) -- taken as an integer, this is 0.

In short, your algebra is off.

I recommend that you use itertools.product to get the output you want.

Body:
I'm not sure exactly how to describe this problem, so apologies if the title was insufficient.

I'm trying to make a piece of code that will put all possible tick-tack-toe boards (0 is blank, 1 is X, 2 is O) into a 2d array (list of lists). I've successfully found a way to do this:

import math

boxes = []

for m in range (0, 19683):
    boxes.append([m%3, int(math.floor((m%9)/3))])

print(boxes)

And it works. But instead of typing out the next seven list items, I thought it would be easier to iterate over them like so:

boxes = []

for m in range (0, 19683):
    boxes.append([])

    for s in range (0,9):
        boxes[m].append(int(math.floor((m%(3**(m+1)))/(3**m))))

print(boxes)

and it just gave me a big array of zeros! I have no idea why changing it to iteration would do this; I tried with both ** and pow(). DOes anyone know what the problem is?

Body:
Let's look at that inner expression:

math.floor(m%(3**(m+1)))/(3**m)

The numerator is simply m: you take it modulus 3^(m+1), which will be larger than m.  The next step is then m / (3**m) -- taken as an integer, this is 0.

In short, your algebra is off.

I recommend that you use itertools.product to get the output you want.


问:
C++ - Overwrite Multiple Lines that were Previously Output to Console
If I have a grid of characters displayed in the console, is there any practical way to re-write those multiple lines in order to output an altered grid on those same lines of the console.

e.g, I would like this code:

```<code>#include <iostream>

using namespace std;

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        for (int i=0; i<5; i++) {
                cout << '\r';
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout.flush();
        }

        return 0;
}
</code>```

to output:

```<code>-----
-----
-----
-----
-----
</code>```

then, upon user input, overwrite that with;

```<code>xxxxx
xxxxx
xxxxx
xxxxx
xxxxx
</code>```

I see other examples of people displaying loading bar type displays by outputting '\r' to re-write a single line, but I'm not sure if there is any straightforward way to accomplish that for multiple lines?

I'm using MinGW.

One Solution:

```<code>#include <iostream>
#include <stdio.h>
#include <windows.h>

using namespace std;

void gotoxy( int column, int line )
  {
  COORD coord;
  coord.X = column;
  coord.Y = line;
  SetConsoleCursorPosition(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    coord
    );
  }

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        gotoxy(0,0);

        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout << endl;
        }

        return 0;
}
</code>```

答: You can use SetConsoleCursorPosition to set the cursor position.

Body:
If I have a grid of characters displayed in the console, is there any practical way to re-write those multiple lines in order to output an altered grid on those same lines of the console.

e.g, I would like this code:

#include <iostream>

using namespace std;

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        for (int i=0; i<5; i++) {
                cout << '\r';
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout.flush();
        }

        return 0;
}

to output:

-----
-----
-----
-----
-----

then, upon user input, overwrite that with;

xxxxx
xxxxx
xxxxx
xxxxx
xxxxx

I see other examples of people displaying loading bar type displays by outputting '\r' to re-write a single line, but I'm not sure if there is any straightforward way to accomplish that for multiple lines?

I'm using MinGW.

One Solution:

#include <iostream>
#include <stdio.h>
#include <windows.h>

using namespace std;

void gotoxy( int column, int line )
  {
  COORD coord;
  coord.X = column;
  coord.Y = line;
  SetConsoleCursorPosition(
    GetStdHandle( STD_OUTPUT_HANDLE ),
    coord
    );
  }

int main() {
        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "-";
                }
                cout << endl;
        }

        getchar();

        gotoxy(0,0);

        for (int i=0; i<5; i++) {
                for (int j=0; j<5; j++) {
                        cout << "x";
                }
                cout << endl;
        }

        return 0;
}


问:
PDFBox getNumberOfPages() on Aspose generated doc returns 0
I'm using PDFBox and for some reason when getting the number of pages on a document that was generated with Aspose (aspose.pdf-17.4) PDFBox (2.0.4) returns 0 pages, does anybody know a workaround for it? I tried loading the document and resaving with PDFBox but it didn't seem to work :S

The code is very simple:

```<code>PDDocument doc = new PDDocument();
doc.load(new File (file_path));
int p = dac.getNumberOfPages();
doc.close();
</code>```

Any help is greatly appreciated!

答: I was able to get the correct number of pages after updating with aspose.pdf-17.8 and PDFBox 2.0.8, thanks to Tilman Hausherr for pointing the version.</p>

Body:
I'm using PDFBox and for some reason when getting the number of pages on a document that was generated with Aspose (aspose.pdf-17.4) PDFBox (2.0.4) returns 0 pages, does anybody know a workaround for it? I tried loading the document and resaving with PDFBox but it didn't seem to work :S

The code is very simple:

PDDocument doc = new PDDocument();
doc.load(new File (file_path));
int p = dac.getNumberOfPages();
doc.close();

Any help is greatly appreciated!


问:
What happens when you try to log into Facebook from behind China's great firewall?
For a few clients now, I've had a request to hide the "login with Facebook" feature in China, where Facebook is blocked. There are a couple ways I can think of to do this:

1) Use device locale.

Advantage: super simple!

Disadvantage: Inaccurate— someone in China could have their device set to en_US, and someone in the US could have their phone set to zh_CN. No dice.

2) Use GPS and reverse geocoding.

Advantage: You are actually measuring if the person is currently in the territory you've marked as 'restricted'.

Disadvantage: Requires the user to give you location permissions. Unclear what to do as a fallback if the user declines permissions. Some apps don't use GPS for anything else, and adding it just for this would be overkill.

3) Use a reachability check to http://facebook.com.

Advantage: You're going beyond checking whether the user is in an arbitrary location and actually checking to see whether facebook is currently restricted. If China stops blocking Facebook, your app starts supporting it immediately.

Disadvantage: You end up hiding the login UI if you're offline (which might not be a huge problem, because Facebook login won't work offline no matter where in the world you are).

Big unknown: What happens in China when you try to log into Facebook? Does it return a 404? Redirect to another site? Google searches around this (as linked above) just return things along the lines of "how to get around the Great Firewall" rather than "here's what actually happens when it's blocked".

So, the question: What happens when you try to log into Facebook from behind China's great firewall?

答:
Trying to access Facebook in mainland China would result in error, like 403 Forbidden or 404 Not Found.

GPS Might not be a good idea, because the GPS signal in China is drifted, and as a result many cities located on the boundary would get overlapped GPS position, including southern Shenzhen/northern Hong Kong, Zhuhai/Macau, NE China/Russia and such.

How about reading the Mobile Country Code? So that users who are using Chinese sim card in their iphone can be identified and the option for facebook login can be disabled. But this trick would not be useful on iPod/iPad. It would also affect Chinese users roaming outside their country. How about checking if the IP address belong to a Chinese ISP?


问:
override .ToString()
I would like to override the .ToString() function so that whenever I get a double
it outputs only 5 digits after the decimal point.

How do I reffer to the object the .ToString is working on, inside the override function?
In other words what shell I put instead of the XXX in the following code?

```<code>public override string ToString()
{
    if (XXX.GetType().Name == "Double")
        return (Math.Round(XXX, 5));
}
</code>```

答:
While the "F5" or "#.#####" solves the specifics of the original post, as the title is rather broader ("override .ToString()"), I thought I'd add that you can also create an extension method which overloads ToString().

So, for example, an extension method of:

```<code>    public static string ToString(this double value, int roundTo, string roundSuffix)
    {
        string rounded = value.ToString($"#.{new String('#', roundTo)}");
        if (rounded != value.ToString())
        {
            rounded = $"{rounded}{roundSuffix}";
        }
        return rounded;
    }
</code>```

Would produce "5.25 was rounded" if passed

```<code>double d = 5.2514;
string formatted = d.ToString(2, " was rounded");
</code>```

or "5.2" if passed

```<code>double d = 5.2;
string formatted = d.ToString(2, " was rounded");
</code>```

(just on the off chance there's some weird use case where someone wants to do something like that!)

You shouldn't attempt to override ToString() with a method that has the same signature as one of the built-in ToString() overloads however, as while the IDE will see it, it will never call the extension method (see How to call extension method which has the same name as an existing method? for details)

Title: override .ToString()

Body:
I would like to override the .ToString() function so that whenever I get a double
it outputs only 5 digits after the decimal point.

How do I reffer to the object the .ToString is working on, inside the override function?
In other words what shell I put instead of the XXX in the following code?

public override string ToString()
{
    if (XXX.GetType().Name == "Double")
        return (Math.Round(XXX, 5));
}

Body:
While the "F5" or "#.#####" solves the specifics of the original post, as the title is rather broader ("override .ToString()"), I thought I'd add that you can also create an extension method which overloads ToString().

So, for example, an extension method of:

    public static string ToString(this double value, int roundTo, string roundSuffix)
    {
        string rounded = value.ToString($"#.{new String('#', roundTo)}");
        if (rounded != value.ToString())
        {
            rounded = $"{rounded}{roundSuffix}";
        }
        return rounded;
    }

Would produce "5.25 was rounded" if passed

double d = 5.2514;
string formatted = d.ToString(2, " was rounded");

or "5.2" if passed

double d = 5.2;
string formatted = d.ToString(2, " was rounded");

(just on the off chance there's some weird use case where someone wants to do something like that!)

You shouldn't attempt to override ToString() with a method that has the same signature as one of the built-in ToString() overloads however, as while the IDE will see it, it will never call the extension method (see How to call extension method which has the same name as an existing method? for details)


问:
Is it possible to do a TLS handshake event in Tomcat?
I'm running an application (web service) in tomcat with TLS enabled (with certificates both for the client and the server).

I want that my application will be able to send audit message (logging) when TLS handshake fails. For example I want to log when:

the client certificate is expired,

the client certificate is unknown (not in the server trust store)

any other  handshake failure

Is there any event that I can catch and handle in order to do that?

My application is web service based and is running in tomcat. Tomcat is handling all network and the TLS layers, and the application does not aware of that.

As I don't open any socket myself, where should I catch this Exception?

答:
I'm not aware of anything you can add to Tomcat.

Put an Apache HTTPD in front and use a separate, configured, SSL log.

OwnerDisplayName: Yonatan Maman

LastEditorDisplayName: Yonatan Maman


问:
CMake v3.4.1 finds CUDA 7.5 instead of CUDA 8.0 on Ubuntu 16.04
I am trying to install the GPU support for XGBoost but I get the following error when I try to build it with CMake:

```<code>CMake Error at /usr/local/share/cmake-3.4/Modules/FindPackageHandleStandardArgs.cmake:148 (message):
Could NOT find CUDA: Found unsuitable version "7.5", but required is at
least "8.0" (found /usr)
</code>```

I only installed CUDA 8.0 and the environmental variables in .bashrc are specified as:

```<code>export PATH=/usr/local/cuda-8.0/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
</code>```

How can I have CMake detect the right CUDA version?

答:
PATH and LD_LIBRARY_PATH have no effect on cmake, so what you have tried will not work.

If you look at the documentation for find_package it is possible to provide a PATHS argument to tell cmake to look in non-standard locations

Unfortunately, if you look at the source for XGBoost's CMakeLists.txt, you can see it calls find_package(CUDA ...), but doesn't allow the user to provide a PATHS option

```<code>if(USE_CUDA)
  find_package(CUDA 8.0 REQUIRED)
  ...
endif()
</code>```

As such you are left with 2 options:

Edit XGBoost's CMakeLists.txt file, and add PATHS /usr/local/cuda-8.0 to the find_package call

Install cuda-8.0 into a standard location (eg: use /usr/local as your PREFIX, not /usr/local/cuda-8.0)

Body:
I am trying to install the GPU support for XGBoost but I get the following error when I try to build it with CMake:

CMake Error at /usr/local/share/cmake-3.4/Modules/FindPackageHandleStandardArgs.cmake:148 (message):
Could NOT find CUDA: Found unsuitable version "7.5", but required is at
least "8.0" (found /usr)

I only installed CUDA 8.0 and the environmental variables in .bashrc are specified as:

export PATH=/usr/local/cuda-8.0/bin${PATH:+:${PATH}}
export LD_LIBRARY_PATH=/usr/local/cuda-8.0/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}

How can I have CMake detect the right CUDA version?

Body:
PATH and LD_LIBRARY_PATH have no effect on cmake, so what you have tried will not work.

If you look at the documentation for find_package it is possible to provide a PATHS argument to tell cmake to look in non-standard locations

Unfortunately, if you look at the source for XGBoost's CMakeLists.txt, you can see it calls find_package(CUDA ...), but doesn't allow the user to provide a PATHS option

if(USE_CUDA)
  find_package(CUDA 8.0 REQUIRED)
  ...
endif()

As such you are left with 2 options:

Edit XGBoost's CMakeLists.txt file, and add PATHS /usr/local/cuda-8.0 to the find_package call

Install cuda-8.0 into a standard location (eg: use /usr/local as your PREFIX, not /usr/local/cuda-8.0)