问:
akka http remote address
I'm using Akka HTTP 10.0.9, but struggling to get my unit tests to have a working Remote Address.

eg unit test:

```<code>Get("/").withHeaders(
    RawHeader("Remote-Address", "192.168.1.1"), RawHeader("X-Forwarded-For", "192.168.1.1")
) ~> route ~> check {
    status must_== StatusCodes.OK
}
</code>```

And in the web server code:

```<code>extractClientIP{ clientAddr =>
  complete(s"$clientAddr")
}
</code>```

When running the app via the command line, the client address is returned correctly. But when run via unit tests, the client address always comes back as "Unknown"

What am I doing wrong?

答:
This is caused by akka http can't handle the RawHeader in test. You can solve it by use the Remote-Address object for set the IP for test:

```<code>import akka.http.scaladsl.model.headers.`Remote-Address`
Get().withHeaders(
  `Remote-Address`(RemoteAddress(new InetSocketAddress("192.168.1.1", 23)))
)
</code>```

Title: akka http remote address

Body:
I'm using Akka HTTP 10.0.9, but struggling to get my unit tests to have a working Remote Address.

eg unit test:

Get("/").withHeaders(
    RawHeader("Remote-Address", "192.168.1.1"), RawHeader("X-Forwarded-For", "192.168.1.1")
) ~> route ~> check {
    status must_== StatusCodes.OK
}

And in the web server code:

extractClientIP{ clientAddr =>
  complete(s"$clientAddr")
}

When running the app via the command line, the client address is returned correctly. But when run via unit tests, the client address always comes back as "Unknown"

What am I doing wrong?

Body:
This is caused by akka http can't handle the RawHeader in test. You can solve it by use the Remote-Address object for set the IP for test:

import akka.http.scaladsl.model.headers.`Remote-Address`
Get().withHeaders(
  `Remote-Address`(RemoteAddress(new InetSocketAddress("192.168.1.1", 23)))
)


来源: stackexchange

问:
Has reCaptcha been cracked / hacked / OCR'd / defeated / broken?
Have any programming methods have been used to defeat reCAPTCHA?

I'm interested in seeing evidence and potentially demonstrations that reCAPTCHA in particular has been made obsolete by completely automated, humanless methods.

To clarify, not looking for reCAPTCHA-cheating solutions that involve humans in any way, whether teams tasked with filling out CAPCHAs, porn-seekers, or Mechanical Turk.

I'm also not looking for alternatives to reCAPTCHA, like picking the type of animal, or background fields or javascript trickery.

答:
The weakness of CAPTCHA systems is that people set up rooms full of people in China whose only job it is is to look at a CAPTCHA image and type in the result, which plugs into the automated system that's actually doing the spamming.

Not much you can do about that really.

It's also far cheaper than trying to do image recognition, OCR, etc on the actual image (you may get a response for under $0.01 the other way).

OwnerDisplayName: davebug

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: cletus

ContentLicense: CC BY-SA 2.5


问:
Add UIView rounding logic inside UIView class
I have a custom UIView and I add it to my ViewController like this:

```<code>let myCustomView = Bundle.main.loadNibNamed("MyCustomView", owner: nil, options: nil) as! MyCustomView
myCustomView.layer.cornerRadius = 10
myCustomView.layer.masksToBounds = true
</code>```

I round the corners of the view. But I am wondering, is there a way to move this logic of rounding the corners inside the MyCustomView class?

答:
As you use IB, you may find it more convenient to make an extension of UIView

```<code>extension UIView {
    @IBInspectable var borderColor: UIColor? {
        set {
            layer.borderColor = newValue?.cgColor
        }
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor:color)
            } else {
                return nil
            }
        }
    }

    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
            clipsToBounds = newValue > 0
        }
        get {
            return layer.cornerRadius
        }
    }
}
</code>```

Then you can set those values from Attributes inspector.

Body:
I have a custom UIView and I add it to my ViewController like this:

let myCustomView = Bundle.main.loadNibNamed("MyCustomView", owner: nil, options: nil) as! MyCustomView
myCustomView.layer.cornerRadius = 10
myCustomView.layer.masksToBounds = true

I round the corners of the view. But I am wondering, is there a way to move this logic of rounding the corners inside the MyCustomView class?

Body:
As you use IB, you may find it more convenient to make an extension of UIView

extension UIView {
    @IBInspectable var borderColor: UIColor? {
        set {
            layer.borderColor = newValue?.cgColor
        }
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor:color)
            } else {
                return nil
            }
        }
    }

    @IBInspectable var borderWidth: CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat {
        set {
            layer.cornerRadius = newValue
            clipsToBounds = newValue > 0
        }
        get {
            return layer.cornerRadius
        }
    }
}

Then you can set those values from Attributes inspector.


问:
Android studio enable method suggestions and jump to method definitions [NDK perspective]
AndroidStudio doesn't seem to have any of the coding assistance (method suggestions, jump to method definitions etc) for native C code that it provides for Java. How do I turn this on ?</p>

答:
This should work. However, a lot of people have been complaining about such problems. See if any of the following helps:

Invalidate cache: Go to File > Invalidate Caches / Restart

Make sure Power Save Mode on File menu is disabled

Go to File > Settings. Look for Inspections - ensure that Android and Android Lint is checked, or alternately just set it back to default.
Also, search for Code Completion - ensure the Auto-insert options and Autopopup code completion option is checked


问:
settings page to add or subtract different image arrays. Coding with swift and xcode
I am trying to make a simple flashcard app.

OVERVIEW - To give you the basic run down of the app, all of the flashcards contain an object that has the letter l. Sometimes the word starts with the letter l, sometimes there is a double ll, sometimes the word starts with pl or kl, or sl, etc...

SO FAR - I have made the app so that there is a home page and from the home page you press Go and then it takes you too a second view controller.  From there you can swipe left and right through the flash cards.  I did this by creating an array with all of the images and then adding a swipe gesture (code below)

```<code>//
//  SecondViewController.swift
//  firstapp
//
//  Created by Anthony Rubin on 6/20/17.
//  Copyright © 2017 rubin. All rights reserved.
//

import UIKit

class SecondViewController: UIViewController , UIGestureRecognizerDelegate  {

@IBAction func home(_ sender: Any) {
performSegue(withIdentifier: "home", sender: self)
}

@IBOutlet weak var imgPhoto: UIImageView!

var imageList:[String] = ["alligator", "apple", "balance", "ball", "ballerina", "balloon", "bell", "belt", "black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue", "bowling", "bubble", "bully", "calendar", "castle", "cello", "clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud", "cold", "colors", "crawl", "curlyhair", "dollar", "dolphin", "elephant", "elf", "eyelashes", "fall", "fishbowl", "flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly", "gasoline", "girl", "glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue", "goalie", "golf", "hula", "jellyfish", "ladder", "ladybug", "lake", "lamb", "lamp", "lark", "laughing", "lawnmower", "leaf", "leash", "left", "leg", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning", "lime", "lion", "lips", "list", "listen", "llama", "lock", "log", "look", "love", "lunch", "melt", "milk", "olive", "owl", "pail", "peel", "pillow", "pilot", "planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus", "polarbear", "pool", "rollerskate", "ruler", "shelf", "silly", "sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow", "smile", "telephone", "television", "tulip", "umbrella", "valentine", "violin", "whale", "wheel", "xylophone", "yellow"]
 let maxImages = 135
 var imageIndex: NSInteger = 0

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
imgPhoto.isUserInteractionEnabled = true

    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
    leftSwipe.cancelsTouchesInView = false

    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
    rightSwipe.cancelsTouchesInView = false

    leftSwipe.direction = .left
    rightSwipe.direction = .right

    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe)

}

func Swiped(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {

        switch swipeGesture.direction {

        case UISwipeGestureRecognizerDirection.right :
            print("User swiped right")

            // decrease index first

            imageIndex -= 1

            // check if index is in range

            if imageIndex < 0 {

                imageIndex = maxImages

            }

            imgPhoto.image = UIImage(named: imageList[imageIndex])

        case UISwipeGestureRecognizerDirection.left:
            print("User swiped Left")

            // increase index first

            imageIndex += 1

            // check if index is in range

            if imageIndex > maxImages {

                imageIndex = 0

            }

            imgPhoto.image = UIImage(named: imageList[imageIndex])

        default:
            break //stops the code/codes nothing.

        }
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/
</code>```

THE PROBLEM - I want to create a settings page.  This settings page will have a basic on and off switch for each group of words.  So lets say I do not want any words that have the initial letter l, I would turn the button too the off position and then when I swipe through the images there will be no flashcards with the initial letter l.

settings page

MY IDEA - I imagine that i will have to connect each on and off switch too its corresponding array of words and then code up if, then statements for each button. Then add all of the arrays together.  However im not sure at all how to begin doing this.  I have made a Table view with all the different on and off switches but have not yet added any functionality. I am also not sure how I am going to send the information from my table view to the second view controller.

I know this is alot to ask in one question but any help would be much appreciated.  Thank you

答:
You can use Delegation Pattern to send message from one view controller to another.
For delegation pattern you make your  SecondViewController as delegate of SettingsViewController and set up communication between both classes.

If you have to pass data from SettingsViewController  To SecondViewController

Create protocol in SettingsViewController   as

```<code>protocol SettingsViewControllerDelegate {
    func settingDidFinished(data : [String])
}
</code>```

Create an id in SettingsViewController , so that you can assign any class as its delegate class.

```<code>class SettingsViewController : UIViewController {

// MARK:- Delegate
     var SettingsViewControllerDelegate ?
</code>```

Call protocol method in SettingsViewController  on submit button or wherever required.

```<code> @IBAction private func doneTapped(_ sender: AnyObject) {
        delegate?.settingDidFinished(data : yourSettingsArray)
     }
</code>```

Create an object of SettingsViewController  in SecondViewController  and assign SecondViewController  as delegate of SettingsViewController as

```<code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let settingsVc = segue.destinationViewController as? SettingsViewController {
    settingsVc .delegate = self
    }
}
</code>```

Implement required protocol methods of SettingsViewController in SecondViewController

```<code> extension SecondViewController: SettingsViewControllerDelegate {
     // # 4: "SecondViewController" implements "SettingsViewControllerDelegate " protocols:
     func settingDidFinished(data : [String]) {
         print("Settings finished")  // use settings Array here. Access your settings here and add/substract array as per your requirements.
     }
 }
</code>```

Hope it helps.. Happy Coding..:)

Body:
I am trying to make a simple flashcard app.

OVERVIEW - To give you the basic run down of the app, all of the flashcards contain an object that has the letter l. Sometimes the word starts with the letter l, sometimes there is a double ll, sometimes the word starts with pl or kl, or sl, etc...

SO FAR - I have made the app so that there is a home page and from the home page you press Go and then it takes you too a second view controller.  From there you can swipe left and right through the flash cards.  I did this by creating an array with all of the images and then adding a swipe gesture (code below)

//
//  SecondViewController.swift
//  firstapp
//
//  Created by Anthony Rubin on 6/20/17.
//  Copyright © 2017 rubin. All rights reserved.
//

import UIKit

class SecondViewController: UIViewController , UIGestureRecognizerDelegate  {

@IBAction func home(_ sender: Any) {
performSegue(withIdentifier: "home", sender: self)
}

@IBOutlet weak var imgPhoto: UIImageView!

var imageList:[String] = ["alligator", "apple", "balance", "ball", "ballerina", "balloon", "bell", "belt", "black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue", "bowling", "bubble", "bully", "calendar", "castle", "cello", "clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud", "cold", "colors", "crawl", "curlyhair", "dollar", "dolphin", "elephant", "elf", "eyelashes", "fall", "fishbowl", "flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly", "gasoline", "girl", "glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue", "goalie", "golf", "hula", "jellyfish", "ladder", "ladybug", "lake", "lamb", "lamp", "lark", "laughing", "lawnmower", "leaf", "leash", "left", "leg", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning", "lime", "lion", "lips", "list", "listen", "llama", "lock", "log", "look", "love", "lunch", "melt", "milk", "olive", "owl", "pail", "peel", "pillow", "pilot", "planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus", "polarbear", "pool", "rollerskate", "ruler", "shelf", "silly", "sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow", "smile", "telephone", "television", "tulip", "umbrella", "valentine", "violin", "whale", "wheel", "xylophone", "yellow"]
 let maxImages = 135
 var imageIndex: NSInteger = 0

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
imgPhoto.isUserInteractionEnabled = true

    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
    leftSwipe.cancelsTouchesInView = false

    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(Swiped(gesture:)))
    rightSwipe.cancelsTouchesInView = false

    leftSwipe.direction = .left
    rightSwipe.direction = .right

    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe)

}

func Swiped(gesture: UIGestureRecognizer) {

    if let swipeGesture = gesture as? UISwipeGestureRecognizer {

        switch swipeGesture.direction {

        case UISwipeGestureRecognizerDirection.right :
            print("User swiped right")

            // decrease index first

            imageIndex -= 1

            // check if index is in range

            if imageIndex < 0 {

                imageIndex = maxImages

            }

            imgPhoto.image = UIImage(named: imageList[imageIndex])

        case UISwipeGestureRecognizerDirection.left:
            print("User swiped Left")

            // increase index first

            imageIndex += 1

            // check if index is in range

            if imageIndex > maxImages {

                imageIndex = 0

            }

            imgPhoto.image = UIImage(named: imageList[imageIndex])

        default:
            break //stops the code/codes nothing.

        }
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

THE PROBLEM - I want to create a settings page.  This settings page will have a basic on and off switch for each group of words.  So lets say I do not want any words that have the initial letter l, I would turn the button too the off position and then when I swipe through the images there will be no flashcards with the initial letter l.

settings page

MY IDEA - I imagine that i will have to connect each on and off switch too its corresponding array of words and then code up if, then statements for each button. Then add all of the arrays together.  However im not sure at all how to begin doing this.  I have made a Table view with all the different on and off switches but have not yet added any functionality. I am also not sure how I am going to send the information from my table view to the second view controller.

I know this is alot to ask in one question but any help would be much appreciated.  Thank you

Body:
You can use Delegation Pattern to send message from one view controller to another.
For delegation pattern you make your  SecondViewController as delegate of SettingsViewController and set up communication between both classes.

If you have to pass data from SettingsViewController  To SecondViewController

Create protocol in SettingsViewController   as

protocol SettingsViewControllerDelegate {
    func settingDidFinished(data : [String])
}

Create an id in SettingsViewController , so that you can assign any class as its delegate class.

class SettingsViewController : UIViewController {

// MARK:- Delegate
     var SettingsViewControllerDelegate ?

Call protocol method in SettingsViewController  on submit button or wherever required.

 @IBAction private func doneTapped(_ sender: AnyObject) {
        delegate?.settingDidFinished(data : yourSettingsArray)
     }

Create an object of SettingsViewController  in SecondViewController  and assign SecondViewController  as delegate of SettingsViewController as

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let settingsVc = segue.destinationViewController as? SettingsViewController {
    settingsVc .delegate = self
    }
}

Implement required protocol methods of SettingsViewController in SecondViewController

 extension SecondViewController: SettingsViewControllerDelegate {
     // # 4: "SecondViewController" implements "SettingsViewControllerDelegate " protocols:
     func settingDidFinished(data : [String]) {
         print("Settings finished")  // use settings Array here. Access your settings here and add/substract array as per your requirements.
     }
 }

Hope it helps.. Happy Coding..:)


答:
There's a lot here, but you seem to have made a good start.

If the words and the categories are fairly fixed then the first thing I'd do is split the word list up into the different categories, then you can combine the ones you want for you images using:

```<code>let list1 = ["Bat", "Cow"]
let list2 = ["Frog", "Rabbit"]
let list3 = ["Parrot", "Tiger"]

var imageList: [String] {
  return list1+list2
}
</code>```

You could keep an array of activeLists and then use a reduce function to return the final array:

```<code>var activeLists = [list1, list2]
var imageList: [String] {
    return activeLists.reduce([], {$0 + $1})
}
</code>```

But you'll probably end up needing a more manageable data source than a simple String Array to store the information perhaps:

```<code>struct List {
    let words: [String]
    var active: Bool
}
</code>```

Then you could have:

```<code>let list1 =  List(words: ["Bat", "Cow"], active: true)
let list2 =  List(words: ["Frog", "Rabbit"], active: true)
let list3 =  List(words: ["Parrot", "Tiger"], active: true)
var wordLists = [list1, list2, list3]

var imageList: [String] {

    let active = wordLists.reduce([]) { (result:[String], list:List) in
        if list.active {
            return result + list.words
        } else {
            return result
        }
    }

    return active

}
</code>```

Note: I wouldn't use maxImages as a constant as that will need to change, you can use imageList.count instead.

Regarding sending information, there's a few ways of doing this. One way is to use prepareForSegue to send the information to the new viewController. Something like this:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  if let vc = segue.destination as? SettingsViewController {
    vc.wordLists = wordLists
  }
}
</code>```

Then within Settings you can toggle individual word lists with:

```<code>wordLists[1].active = false
</code>```

An easy way to match up switches to the array reference is to give each UISwitch a Tag within the Storyboard that matches its index in the wordLists Array, hook all of the UISwitches to the same IBAction then when it is triggered use:

```<code>@IBAction func switchAction(_ sender: UISwitch) {
  wordList[sender.tag].active = rollIntoLoanSwitch.isOn
}
</code>```

Then you could use a Delegate to send the information back on each toggle or when you leave the view. Alternatively you can define your word lists in a separate Class, with a singleton and reference it from everywhere, it depends on how many different views you're going to need access to the word lists.

Title: settings page to add or subtract different image arrays. Coding with swift and xcode

Body:
There's a lot here, but you seem to have made a good start.

If the words and the categories are fairly fixed then the first thing I'd do is split the word list up into the different categories, then you can combine the ones you want for you images using:

let list1 = ["Bat", "Cow"]
let list2 = ["Frog", "Rabbit"]
let list3 = ["Parrot", "Tiger"]

var imageList: [String] {
  return list1+list2
}

You could keep an array of activeLists and then use a reduce function to return the final array:

var activeLists = [list1, list2]
var imageList: [String] {
    return activeLists.reduce([], {$0 + $1})
}

But you'll probably end up needing a more manageable data source than a simple String Array to store the information perhaps:

struct List {
    let words: [String]
    var active: Bool
}

Then you could have:

let list1 =  List(words: ["Bat", "Cow"], active: true)
let list2 =  List(words: ["Frog", "Rabbit"], active: true)
let list3 =  List(words: ["Parrot", "Tiger"], active: true)
var wordLists = [list1, list2, list3]

var imageList: [String] {

    let active = wordLists.reduce([]) { (result:[String], list:List) in
        if list.active {
            return result + list.words
        } else {
            return result
        }
    }

    return active

}

Note: I wouldn't use maxImages as a constant as that will need to change, you can use imageList.count instead.

Regarding sending information, there's a few ways of doing this. One way is to use prepareForSegue to send the information to the new viewController. Something like this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  if let vc = segue.destination as? SettingsViewController {
    vc.wordLists = wordLists
  }
}

Then within Settings you can toggle individual word lists with:

wordLists[1].active = false

An easy way to match up switches to the array reference is to give each UISwitch a Tag within the Storyboard that matches its index in the wordLists Array, hook all of the UISwitches to the same IBAction then when it is triggered use:

@IBAction func switchAction(_ sender: UISwitch) {
  wordList[sender.tag].active = rollIntoLoanSwitch.isOn
}

Then you could use a Delegate to send the information back on each toggle or when you leave the view. Alternatively you can define your word lists in a separate Class, with a singleton and reference it from everywhere, it depends on how many different views you're going to need access to the word lists.


问:
How can I use this function?I take it from other project
I am new to php language. I just copy a database connection function from another sample project. The code is below.

```<code>public function getRows($conditions = array()){
    $sql = 'SELECT ';
    $sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
    $sql .= ' FROM '.$this->table;
    if(array_key_exists("where",$conditions)){
        $sql .= ' WHERE ';
        $i = 0;
        foreach($conditions['where'] as $key => $value){
            $pre = ($i > 0)?' AND ':'';
            $sql .= $pre.$key." = '".$value."'";
            $i++;
        }
    }

    if(array_key_exists("order_by",$conditions)){
        $sql .= ' ORDER BY '.$conditions['order_by'];
    }

    if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
        $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
    }elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
        $sql .= ' LIMIT '.$conditions['limit'];
    }

    $query = $this->db->prepare($sql);
    $query->execute();

    if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
        switch($conditions['return_type']){
            case 'count':
                $data = $query->rowCount();
                break;
            case 'single':
                $data = $query->fetch(PDO::FETCH_ASSOC);
                break;
            default:
                $data = '';
        }
    }else{
        if($query->rowCount() > 0){
            $data = $query->fetchAll();
        }
    }
    return !empty($data)?$data:false;
}
</code>```

Can anyone show me example how to use this function?I want to use WHERE,LIMIT,GROUP_BY and SELECT clauses. When I put in an array like this, I got error message " Invalid argument supplied for foreach()"

```<code>$conditions = array('where' => "user_name = '$username'");
$data = $userMo -> getRows($conditions);
</code>```

答:
you are making a mistake, as its said Invalid argument supplied for foreach()

that means its not getting an array, and think if there are multiple WHERE then??

so try this

```<code>$conditions = array('where' => array('user_name' => $username));
</code>```

Body:
I am new to php language. I just copy a database connection function from another sample project. The code is below.

public function getRows($conditions = array()){
    $sql = 'SELECT ';
    $sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
    $sql .= ' FROM '.$this->table;
    if(array_key_exists("where",$conditions)){
        $sql .= ' WHERE ';
        $i = 0;
        foreach($conditions['where'] as $key => $value){
            $pre = ($i > 0)?' AND ':'';
            $sql .= $pre.$key." = '".$value."'";
            $i++;
        }
    }

    if(array_key_exists("order_by",$conditions)){
        $sql .= ' ORDER BY '.$conditions['order_by'];
    }

    if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
        $sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
    }elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
        $sql .= ' LIMIT '.$conditions['limit'];
    }

    $query = $this->db->prepare($sql);
    $query->execute();

    if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
        switch($conditions['return_type']){
            case 'count':
                $data = $query->rowCount();
                break;
            case 'single':
                $data = $query->fetch(PDO::FETCH_ASSOC);
                break;
            default:
                $data = '';
        }
    }else{
        if($query->rowCount() > 0){
            $data = $query->fetchAll();
        }
    }
    return !empty($data)?$data:false;
}

Can anyone show me example how to use this function?I want to use WHERE,LIMIT,GROUP_BY and SELECT clauses. When I put in an array like this, I got error message " Invalid argument supplied for foreach()"

$conditions = array('where' => "user_name = '$username'");
$data = $userMo -> getRows($conditions);

Body:
you are making a mistake, as its said Invalid argument supplied for foreach()

that means its not getting an array, and think if there are multiple WHERE then??

so try this

$conditions = array('where' => array('user_name' => $username));


问:
Unable to Add/Commit to git from Virtualenv
I created an empty repo and initialized a Virtualenv for Python development. After installing the required packages and coming out of the Virtual env by deactivating, I am not able to add/commit to Git.

danis@Daniss-MacBook-Pro:~/Git/Sample-Repo$ git add *
Killed: 9
danis@Daniss-MacBook-Pro:~/Git/Sample-Repo$ git add helloworld
fatal: Unable to create '/Users/danis/Git/Sample-Repo/.git/index.lock': File exists.

Another git process seems to be running in this repository, e.g.
an editor opened by 'git commit'. Please make sure all processes
are terminated then try again. If it still fails, a git process
may have crashed in this repository earlier:
remove the file manually to continue.
```

Steps Tried so far:

Removed index.lock file using the command rm -f .git/index.lock

Created .gitignore file in the home directory and added .env to it

答: I had the same problem. It keeps trying to add the ".Python@ -> ..." link. If you add ./.Python to your .gitignore, everything works fine. If you clone the repo elsewhere you can add the .Python@ link to the new location of the python installation.

Body:
I created an empty repo and initialized a Virtualenv for Python development. After installing the required packages and coming out of the Virtual env by deactivating, I am not able to add/commit to Git.

danis@Daniss-MacBook-Pro:~/Git/Sample-Repo$ git add *
Killed: 9
danis@Daniss-MacBook-Pro:~/Git/Sample-Repo$ git add helloworld
fatal: Unable to create '/Users/danis/Git/Sample-Repo/.git/index.lock': File exists.

Another git process seems to be running in this repository, e.g.
an editor opened by 'git commit'. Please make sure all processes
are terminated then try again. If it still fails, a git process
may have crashed in this repository earlier:
remove the file manually to continue.

Steps Tried so far:

Removed index.lock file using the command rm -f .git/index.lock

Created .gitignore file in the home directory and added .env to it


问:
how to find a an error message in angular JS using protractor?
error message

MyProtractorCode

How to find the text "VAT Number is required."?

I tried with:

err = element(by.css('.invalid error-msg')).getAttribute();
expect(err.getText()).toEqual('VAT Number is invalid.');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><em class="invalid error-msg">
  <div> VAT Number is required.</div>
</em></code>```

答:
You were almost there, the code should be

err = element(by.css('.invalid.error-msg'));
expect(err.getText()).toEqual('VAT Number is invalid.');```

The getAttribute() will only the the value of an attribute, see here so you need to leave it out. You only use it when you need to know for example the href-value of a link, or the class of a specific element.

In your case you want to verify the text in an element, so it should be the above syntax, see also here

Body:
error message

MyProtractorCode

How to find the text "VAT Number is required."?

I tried with:

err = element(by.css('.invalid error-msg')).getAttribute();
expect(err.getText()).toEqual('VAT Number is invalid.');

 VAT Number is required.

Body:
You were almost there, the code should be

err = element(by.css('.invalid.error-msg'));
expect(err.getText()).toEqual('VAT Number is invalid.');

The getAttribute() will only the the value of an attribute, see here so you need to leave it out. You only use it when you need to know for example the href-value of a link, or the class of a specific element.

In your case you want to verify the text in an element, so it should be the above syntax, see also here


问:
Python decorator with options
I have a module that has a function whose prototype is similar to that of the thread class.

```<code>def do(fn, argtuple=(), kwargdict={}, priority=0,
            block=False, timeout=0, callback=None, daemon=False)

    # do stuff
</code>```

fn is a callable, and argtuple and kwargdict are positional and dictionary arguments that will be passed to the fn callable when it gets called.

I'm now trying to write a decorator for this, but I'm confused. I've never really had a very good grasp on decorators. Is there a way to make a decorator that I can set the options in the above such as timeout, but pass in argtuple and kwargdict when the function is called.

So for example:

```<code>@do(priority=2)
def decoratedTask(arg, dic=3):
    #do stuff

decoratedTask(72)
</code>```

I'm confused how I would pass the runtime argument 72 into the decorated function. I'm thinking the decorator needs to be a class where the __call__ method returns the function call, but I'm unsure the syntax of how to pass in arguments like that.

Does this make sense?

答:
As the other answers have explained, decorators are normally passed a single implicit function argument when invoked by just using their name like this:

```<code>    @deco
    def somefunc(...): pass
</code>```

Which does the same thing as:

```<code>    def somefunc(...): pass
    somefunc = deco(somefunc)
</code>```

The argument in this situation is a compiled version of the function definition that immediately follows. In such cases the decorator returns a callable which is assigned to the function name instead of the compiled function body, as would normally be the case.

However if a decorator function is explicitly given one or more arguments when it's invoked, like this:

```<code>    @deco(args)
    def somefunc(...): pass
</code>```

It becomes equivalent to:

```<code>    def somefunc(...): pass
    somefunc = deco(args)(somefunc)
</code>```

As you can see, things in this case work somewhat differently. The decorator function still returns a callable, only this time that is expected to a "normal" single implicit-argument decorator function, which is then invoked with a function object from the following function definition like before.

Again – as others have pointed out – this makes decorators explicitly passed arguments, decorator factories in the sense that they construct and return 'regular' decorator functions.

In most if not all cases, decorators can be implemented either as a function or a class, since both are callable in Python. Personally I find functions a little easier to understand and so will use that approach in the following. On the other hand, the function approach can become tricky because it often involves one or more nested function definitions.

Here's how you could code a decorator for thedo()function in your module. In the code below I've defined what it does is print out the function's arguments before calling it.

```<code>def do(fn, args=tuple(), kwargs={}, priority=0,
       block=False, timeout=0, callback=None, daemon=False):
    # show arguments
    print ('in do(): fn={!r}, args={}, kwargs={}, priority={},\n'
           '         block={}, timeout={}, callback={}, daemon={}'
           .format(fn.__name__, args, kwargs, priority,
                   block, timeout, callback, daemon))
    # and call function 'fn' with its arguments
    print ('  calling {}({}, {})'.format(
               fn.__name__,
               ', '.join(map(str, args)) if args else '',
               ', '.join('{}={}'.format(k, v) for k,v in kwargs.items())
                    if kwargs else '')
          )
    fn(*args, **kwargs)

def do_decorator(**do_kwargs):
    def decorator(fn):
        def decorated(*args, **kwargs):
            do(fn, args, kwargs, **do_kwargs)
        return decorated
    return decorator

@do_decorator(priority=2)
def decoratedTask(arg, dic=42):
    print 'in decoratedTask(): arg={}, dic={}'.format(arg, dic)

decoratedTask(72, dic=3)
</code>```

Output:

in do(): fn='decoratedTask', args=(72,), kwargs={'dic': 42}, priority=2,
         block=False, timeout=0, callback=None, daemon=False
  calling decoratedTask(72, dic=3)
in decoratedTask(): arg=72, dic=3
```

Here's a blow-by-blow account of how this complicated looking stuff works:

The outer decorator functiondo_decorator(), defines another inner decorator function which it returns, here creatively nameddecorator.

Whatdecoratordoes is define what happens to functions that are decorated in a simple 'no arguments' scenario—which here is defining and returning yet another – but final – nested function calleddecorated, which just calls the module'sdo()function and passes it both the arguments if any from the point of invocation, along with those intended for thedo()function's use.

This usage case is somewhat complicated by the fact that both the outer decorator and the functions being decorated have keyword arguments. Extra care is required to ensure that the names of the keywords for each are unique so they don't conflict (and that the mutablekwargsargument default value is not unintentionally changed by something in thedo()function).

Title: Python decorator with options

Body:
I have a module that has a function whose prototype is similar to that of the thread class.

def do(fn, argtuple=(), kwargdict={}, priority=0,
            block=False, timeout=0, callback=None, daemon=False)

    # do stuff

fn is a callable, and argtuple and kwargdict are positional and dictionary arguments that will be passed to the fn callable when it gets called.

I'm now trying to write a decorator for this, but I'm confused. I've never really had a very good grasp on decorators. Is there a way to make a decorator that I can set the options in the above such as timeout, but pass in argtuple and kwargdict when the function is called.

So for example:

@do(priority=2)
def decoratedTask(arg, dic=3):
    #do stuff

decoratedTask(72)

I'm confused how I would pass the runtime argument 72 into the decorated function. I'm thinking the decorator needs to be a class where the __call__ method returns the function call, but I'm unsure the syntax of how to pass in arguments like that.

Does this make sense?

Body:
As the other answers have explained, decorators are normally passed a single implicit function argument when invoked by just using their name like this:

    @deco
    def somefunc(...): pass

Which does the same thing as:

    def somefunc(...): pass
    somefunc = deco(somefunc)

The argument in this situation is a compiled version of the function definition that immediately follows. In such cases the decorator returns a callable which is assigned to the function name instead of the compiled function body, as would normally be the case.

However if a decorator function is explicitly given one or more arguments when it's invoked, like this:

    @deco(args)
    def somefunc(...): pass

It becomes equivalent to:

    def somefunc(...): pass
    somefunc = deco(args)(somefunc)

As you can see, things in this case work somewhat differently. The decorator function still returns a callable, only this time that is expected to a "normal" single implicit-argument decorator function, which is then invoked with a function object from the following function definition like before.

Again – as others have pointed out – this makes decorators explicitly passed arguments, decorator factories in the sense that they construct and return 'regular' decorator functions.

In most if not all cases, decorators can be implemented either as a function or a class, since both are callable in Python. Personally I find functions a little easier to understand and so will use that approach in the following. On the other hand, the function approach can become tricky because it often involves one or more nested function definitions.

Here's how you could code a decorator for thedo()function in your module. In the code below I've defined what it does is print out the function's arguments before calling it.

def do(fn, args=tuple(), kwargs={}, priority=0,
       block=False, timeout=0, callback=None, daemon=False):
    # show arguments
    print ('in do(): fn={!r}, args={}, kwargs={}, priority={},\n'
           '         block={}, timeout={}, callback={}, daemon={}'
           .format(fn.__name__, args, kwargs, priority,
                   block, timeout, callback, daemon))
    # and call function 'fn' with its arguments
    print ('  calling {}({}, {})'.format(
               fn.__name__,
               ', '.join(map(str, args)) if args else '',
               ', '.join('{}={}'.format(k, v) for k,v in kwargs.items())
                    if kwargs else '')
          )
    fn(*args, **kwargs)

def do_decorator(**do_kwargs):
    def decorator(fn):
        def decorated(*args, **kwargs):
            do(fn, args, kwargs, **do_kwargs)
        return decorated
    return decorator

@do_decorator(priority=2)
def decoratedTask(arg, dic=42):
    print 'in decoratedTask(): arg={}, dic={}'.format(arg, dic)

decoratedTask(72, dic=3)

Output:

in do(): fn='decoratedTask', args=(72,), kwargs={'dic': 42}, priority=2,
         block=False, timeout=0, callback=None, daemon=False
  calling decoratedTask(72, dic=3)
in decoratedTask(): arg=72, dic=3

Here's a blow-by-blow account of how this complicated looking stuff works:

The outer decorator functiondo_decorator(), defines another inner decorator function which it returns, here creatively nameddecorator.

Whatdecoratordoes is define what happens to functions that are decorated in a simple 'no arguments' scenario—which here is defining and returning yet another – but final – nested function calleddecorated, which just calls the module'sdo()function and passes it both the arguments if any from the point of invocation, along with those intended for thedo()function's use.

This usage case is somewhat complicated by the fact that both the outer decorator and the functions being decorated have keyword arguments. Extra care is required to ensure that the names of the keywords for each are unique so they don't conflict (and that the mutablekwargsargument default value is not unintentionally changed by something in thedo()function).


问:
Swift 3.0 Map Returns to Previous MapView
I have a mapView with annotations with detail disclosure that when clicked on, moves to a new viewController. Then when the user selects to go back to the mapView from the detail disclosure, I want the mapView to have the same view that the user had before clicking on the detail disclosure. Below is the code I have set up so far, however, when the user clicks back from the detail disclosure, the map zooms out. I am not sure how to recreate the previous view.

Detail Disclosure VC:

```<code>// here by segueing, I want to communicate to the MapView VC that the map should remain the same
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "backButtonTapped" )
    {
        let destinationVC = segue.destination as! TabBarVC
        mapStatus = "wentBack"
        print("The value of mapStatus after seguing is \(mapStatus)")
        destinationVC.selectedIndex = 1

    }

}
</code>```

MapView VC:

```<code> override func viewDidAppear(_ animated: Bool) {
    // here if the mapStatus is not the correct value (the user never used the detail disclosure), the map will just snap onto the current location

    if mapStatus == "wentBack" {
       print("Do not update location")

       // assuming appropriate code is placed here but I am not sure what it is

    } else {
        print("Updated Current Location")
    let center = CLLocationCoordinate2D(latitude: self.lastLocation.coordinate.latitude, longitude: self.lastLocation.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    map.setRegion(region, animated: true)

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if #available(iOS 8.0, *) {
            locationManager.requestAlwaysAuthorization()
        } else {
            // Fallback on earlier versions
        }
        let noLocation = CLLocationCoordinate2D()
        let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200)
        map.setRegion(viewRegion, animated: false)

    }
    }
</code>```

答:
So it turns out that the map does not persist because viewDidLoad is being called when the user hits back on the detail disclosure (using a prepareForSegue). I used

```<code>@IBAction func backButtonTapped(_ sender: UIBarButtonItem) {
    self.dismiss(animated: true)
    mapStatus = "wentBack"

}
</code>```

In order to just dismiss the viewController, and only calling viewDidAppear and not viewDidLoad.

Body:
I have a mapView with annotations with detail disclosure that when clicked on, moves to a new viewController. Then when the user selects to go back to the mapView from the detail disclosure, I want the mapView to have the same view that the user had before clicking on the detail disclosure. Below is the code I have set up so far, however, when the user clicks back from the detail disclosure, the map zooms out. I am not sure how to recreate the previous view.

Detail Disclosure VC:

// here by segueing, I want to communicate to the MapView VC that the map should remain the same
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "backButtonTapped" )
    {
        let destinationVC = segue.destination as! TabBarVC
        mapStatus = "wentBack"
        print("The value of mapStatus after seguing is \(mapStatus)")
        destinationVC.selectedIndex = 1

    }

}

MapView VC:

 override func viewDidAppear(_ animated: Bool) {
    // here if the mapStatus is not the correct value (the user never used the detail disclosure), the map will just snap onto the current location

    if mapStatus == "wentBack" {
       print("Do not update location")

       // assuming appropriate code is placed here but I am not sure what it is

    } else {
        print("Updated Current Location")
    let center = CLLocationCoordinate2D(latitude: self.lastLocation.coordinate.latitude, longitude: self.lastLocation.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    map.setRegion(region, animated: true)

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        if #available(iOS 8.0, *) {
            locationManager.requestAlwaysAuthorization()
        } else {
            // Fallback on earlier versions
        }
        let noLocation = CLLocationCoordinate2D()
        let viewRegion = MKCoordinateRegionMakeWithDistance(noLocation, 200, 200)
        map.setRegion(viewRegion, animated: false)

    }
    }

Body:
So it turns out that the map does not persist because viewDidLoad is being called when the user hits back on the detail disclosure (using a prepareForSegue). I used

@IBAction func backButtonTapped(_ sender: UIBarButtonItem) {
    self.dismiss(animated: true)
    mapStatus = "wentBack"

}

In order to just dismiss the viewController, and only calling viewDidAppear and not viewDidLoad.


问:
Trying to get jQuery to change a different img src when clicked
I've got 2 seperate divs that change background img src when clicked which works fine, but I would like it to change the other image its present with. E.g. div 1 is pressed and becomes "open", if div2 is "open" it then becomes closed. My jQuery is rather limited and have it functioning where it can change the image, but need to figure out how to apply the "closed" class to images that haven't just been clicked. Ideally it would use the attr() so I can add more later.

jQuery

$(".box").on("click", function() {

      // need to make this function select the other div.
      if ($(this).hasClass("closed")) {
        $(this).addClass("open").removeClass("closed");
      } else {
        $(this).addClass("closed").removeClass("open");
      }

      var id = $(this).attr("data-id");
      $(this).toggleClass("open");
      $(".hideDivs").hide();
      $("#" + id).show();
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> .container {
      width: 640px;
      height: 450px;
      background-color: #eee;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
    }

    .text-primary {
      font-size: 14px;
      text-align: center;
      margin-bottom: 5px;
    }

    .box {
      cursor: pointer;
      width: 90px;
      height: 180px;
      display:block;
      margin:auto;
      background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/closed_vo1pn2.png");
    }

    .open {
      background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/open_ihcmuz.png");
    }

    .closed {
      background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/closed_vo1pn2.png");
    }

    .hideDivs {
      display: none;
    }

    .panel-body {
      padding: 10px;
      margin-top: 5px;
    }

    .title {
      font-weight: bold;
      font-size: 14px;
    }</code>```

              Practices for safe packaging of cooked foods

Label and date all food.

Package high-risk food in small batches for refrigeration and return to refrigerated storage as soon as possible (within 20 minutes).

Store packaging products in a clean environment and protect from contamination.

              Practices for safe freezing of cooked foods

When packaging food for freezing, cover or wrap, label and date (production and freezing date) all foods.

Freeze food in small quantities to ensure food is frozen quickly.

Do not overload freezer units and ensure air can circulate.

Do not freeze foods that have been cooked then refrigerated and reheated.

```

答:
This might be a better approach:

```<code>$(".box").on("click", function() {
    // Hide all detail divs
    $(".hideDivs").hide();

    if ($(this).is(".closed")) {
        // Close other open boxes
        $(".box.open").removeClass("open").addClass("closed");
        // Open this box and show the corresponding details div
        $(this).removeClass("closed").addClass("open");
        var id = $(this).attr("data-id");
        $("#" + id).show();
    } else {
        // Close this box
        $(this).removeClass("open").addClass("closed");
    }

});
</code>```

Also, I would recommend changing your HTML to have your 'box' elements also have a 'closed' class, so you do not repeat/need the CSS background attribute on the 'box' class.

See it working on this fiddle

Body:
I've got 2 seperate divs that change background img src when clicked which works fine, but I would like it to change the other image its present with. E.g. div 1 is pressed and becomes "open", if div2 is "open" it then becomes closed. My jQuery is rather limited and have it functioning where it can change the image, but need to figure out how to apply the "closed" class to images that haven't just been clicked. Ideally it would use the attr() so I can add more later.

jQuery

$(".box").on("click", function() {

      // need to make this function select the other div.
      if ($(this).hasClass("closed")) {
        $(this).addClass("open").removeClass("closed");
      } else {
        $(this).addClass("closed").removeClass("open");
      }

      var id = $(this).attr("data-id");
      $(this).toggleClass("open");
      $(".hideDivs").hide();
      $("#" + id).show();
    });

 .container {
      width: 640px;
      height: 450px;
      background-color: #eee;
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
    }

    .text-primary {
      font-size: 14px;
      text-align: center;
      margin-bottom: 5px;
    }

    .box {
      cursor: pointer;
      width: 90px;
      height: 180px;
      display:block;
      margin:auto;
      background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/closed_vo1pn2.png");
    }

    .open {
      background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/open_ihcmuz.png");
    }

    .closed {
      background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/closed_vo1pn2.png");
    }

    .hideDivs {
      display: none;
    }

    .panel-body {
      padding: 10px;
      margin-top: 5px;
    }

    .title {
      font-weight: bold;
      font-size: 14px;
    }

              Practices for safe packaging of cooked foods

Label and date all food.

Package high-risk food in small batches for refrigeration and return to refrigerated storage as soon as possible (within 20 minutes).

Store packaging products in a clean environment and protect from contamination.

              Practices for safe freezing of cooked foods

When packaging food for freezing, cover or wrap, label and date (production and freezing date) all foods.

Freeze food in small quantities to ensure food is frozen quickly.

Do not overload freezer units and ensure air can circulate.

Do not freeze foods that have been cooked then refrigerated and reheated.

Body:
This might be a better approach:

$(".box").on("click", function() {
    // Hide all detail divs
    $(".hideDivs").hide();

    if ($(this).is(".closed")) {
        // Close other open boxes
        $(".box.open").removeClass("open").addClass("closed");
        // Open this box and show the corresponding details div
        $(this).removeClass("closed").addClass("open");
        var id = $(this).attr("data-id");
        $("#" + id).show();
    } else {
        // Close this box
        $(this).removeClass("open").addClass("closed");
    }

});

Also, I would recommend changing your HTML to have your 'box' elements also have a 'closed' class, so you do not repeat/need the CSS background attribute on the 'box' class.

See it working on this fiddle


问:
Bootstrap Tabs or Alternatives?
Is it possible to have tabs like bootstrap .nav-tabs but instead of an anchor tag it will change the content below it?

Im looking for something like this:

Home

Menu 1

Menu 2

Menu 3

```

But without the anchor tags but will just change the active tab and change the content below it.

If bootstrap is not the best option let me know

答:
You can use button instead of anchor. You will need to click something to change the menu. Bootstrap has nav-pills class also which work for menu. Else you can create div instead of anchor tag, and write jquery to hide or display content. For showing the active tab, you can remove .active class from all other divs, and add it to current one clicked.

Bootstrap for tabs is a very easy to follow option. Stick with it if there is no other specific project requirement. For learning purpose, you can also give zurb foundation a try. It is also very good framework.

Title: Bootstrap Tabs or Alternatives?

Body:
Is it possible to have tabs like bootstrap .nav-tabs but instead of an anchor tag it will change the content below it?

Im looking for something like this:

Home

Menu 1

Menu 2

Menu 3

But without the anchor tags but will just change the active tab and change the content below it.

If bootstrap is not the best option let me know


问:
Laravel 5.4 change password
I am currently working on the profile page wherein the user can change its password. I created a new function changePassword() in the UserController

```<code>public function changePassword(Request $request, User $employee) {
    $validator = Validator::make($data, [
        'password' => 'required|string|min:6|confirmed',
        'password_confirmation' => 'required|string|min:6|same:password'
    ]);

    if ($validator->fails()) {
        Session::flash('error', "Fill-out the form correctly. Try again!");
        return redirect()->back()->withErrors($validator);
    }

    $employee->password = bcrypt($request->password);
    $employee->save();
    return view('users.show', ['employee'=>$employee]);
}
</code>```

I created this new route in web.php above the resource route of the User model

```<code>Route::put('users/{user}', 'UserController@changePassword')->name('users.changePassword');
</code>```

I am getting a MethodNotAllowedHttpException every time I click the submit button. I think the problem is the route but I am not sure. Is there a Laravel functionality aside the one that sends email, because I want the users to change its password without using email. Thanks!

Here is my form

```<code>{!! Form::model($employee, ['method'=>'PUT', 'route'=>['users.changePassword', $employee]]) !!}
</code>```

答:
Do you set parameter for route?</p>

```<code>{!! Form::Model($user, ['action' => ['UserController@changePassword', $user->id],'method' => 'PUT']) !!}

{!! Form::close() !!}
</code>```

Title: Laravel 5.4 change password

Body:
I am currently working on the profile page wherein the user can change its password. I created a new function changePassword() in the UserController

public function changePassword(Request $request, User $employee) {
    $validator = Validator::make($data, [
        'password' => 'required|string|min:6|confirmed',
        'password_confirmation' => 'required|string|min:6|same:password'
    ]);

    if ($validator->fails()) {
        Session::flash('error', "Fill-out the form correctly. Try again!");
        return redirect()->back()->withErrors($validator);
    }

    $employee->password = bcrypt($request->password);
    $employee->save();
    return view('users.show', ['employee'=>$employee]);
}

I created this new route in web.php above the resource route of the User model

Route::put('users/{user}', 'UserController@changePassword')->name('users.changePassword');

I am getting a MethodNotAllowedHttpException every time I click the submit button. I think the problem is the route but I am not sure. Is there a Laravel functionality aside the one that sends email, because I want the users to change its password without using email. Thanks!

Here is my form

{!! Form::model($employee, ['method'=>'PUT', 'route'=>['users.changePassword', $employee]]) !!}

Body:
Do you set parameter for route?

{!! Form::Model($user, ['action' => ['UserController@changePassword', $user->id],'method' => 'PUT']) !!}

{!! Form::close() !!}


问:
My script parses all the links again and again from a infinite scrolling webpage
I've written a script using python in combination with selenium to get all the company links from a webpage which doesn't display all the links until scrolled downmost. However, when I run my script, I get desired links but there are lots of duplicates being scraped along. At this point, I can't get any idea how can I modify my script to get the unique links. Here is what I've tried so far:</p>

```<code>from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://fortune.com/fortune500/list/')
while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(3)

    for items in driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]"):
        item = items.find_elements_by_xpath('.//a')[0]
        print(item.get_attribute("href"))

driver.close()
</code>```

答:
You can try below code:

```<code>from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.common.exceptions import TimeoutException

my_links = []
while True:
    try:
        current_length = len(my_links)
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        wait(driver, 10).until(lambda: len(driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]//a")) > current_length)
        my_links.extend([a.get_attribute("href") for a in driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]//a")])
    except TimeoutException:
        break

my_links = set(my_links)
</code>```

This should allow you to scroll down and collect new links while it's possible. Finally with set() you can leave only unique values

Body:
I've written a script using python in combination with selenium to get all the company links from a webpage which doesn't display all the links until scrolled downmost. However, when I run my script, I get desired links but there are lots of duplicates being scraped along. At this point, I can't get any idea how can I modify my script to get the unique links. Here is what I've tried so far:

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('http://fortune.com/fortune500/list/')
while True:
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(3)

    for items in driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]"):
        item = items.find_elements_by_xpath('.//a')[0]
        print(item.get_attribute("href"))

driver.close()

Body:
You can try below code:

from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.common.exceptions import TimeoutException

my_links = []
while True:
    try:
        current_length = len(my_links)
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        wait(driver, 10).until(lambda: len(driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]//a")) > current_length)
        my_links.extend([a.get_attribute("href") for a in driver.find_elements_by_xpath("//li[contains(concat(' ', @class, ' '), ' small-12 ')]//a")])
    except TimeoutException:
        break

my_links = set(my_links)

This should allow you to scroll down and collect new links while it's possible. Finally with set() you can leave only unique values


问:
Using a Python subprocess call to invoke a Python script
I have a Python script that needs to invoke another Python script in the same directory. I did this:

```<code>from subprocess import call
call('somescript.py')
</code>```

I get the following error:

```<code>call('somescript.py')
File "/usr/lib/python2.6/subprocess.py", line 480, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child

raise child_exception
OSError: [Errno 2] No such file or directory
</code>```

I have the script somescript.py in the same folder though. Am I missing something here?

答:
What's wrong with

```<code>import sys
from os.path import dirname, abspath

local_dir = abspath(dirname(__file__))
sys.path.append(local_dir)

import somescript
</code>```

or better still wrap the functionality in a function, e.g. baz, then do this.

```<code>import sys
from os.path import dirname, abspath

local_dir = abspath(dirname(__file__))
sys.path.append(local_dir)

import somescript
somescript.baz()
</code>```

There seem to be a lot of scripts starting python processes or forking, is that a requirement?

ContentLicense: CC BY-SA 4.0

Body:
I have a Python script that needs to invoke another Python script in the same directory. I did this:

from subprocess import call
call('somescript.py')

I get the following error:

call('somescript.py')
File "/usr/lib/python2.6/subprocess.py", line 480, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child

raise child_exception
OSError: [Errno 2] No such file or directory

I have the script somescript.py in the same folder though. Am I missing something here?

Body:
What's wrong with

import sys
from os.path import dirname, abspath

local_dir = abspath(dirname(__file__))
sys.path.append(local_dir)

import somescript

or better still wrap the functionality in a function, e.g. baz, then do this.

import sys
from os.path import dirname, abspath

local_dir = abspath(dirname(__file__))
sys.path.append(local_dir)

import somescript
somescript.baz()

There seem to be a lot of scripts starting python processes or forking, is that a requirement?


问:
Define listview in resource file with only ItemSource changing
I created the following ListView to display some data (removed extraneous markup):

```<code><ListView ItemsSource="{Binding NewYorkResidents}">
    <ListView.Header>
        <Style>
            <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
        </Style>
    </ListView.Header>
    <ListView.HeaderTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="60"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="Name" Grid.Column="0" />
                <TextBlock Text="Address" Grid.Column="1" />
            </Grid>
        </DataTemplate>
    </ListView.HeaderTemplate>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="60"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding Name}" Grid.Column="0" />
                <TextBlock Text="{Binding Address}" Grid.Column="1" />
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

Now I want to reuse this exact same ListView + markup in a different view, just with a different ItemsSource (though it will bind to the same data type).

What is the best way to reuse the ListView and just specifiy the ItemsSource? I'm hoping to be able to do something like this:

```<code><ListView DataTemplate="MyTemplate" ItemsSource=<some new binding> />
</code>```

and still have it show the ListView headers and Name and Address TextBlocks using data from the ItemsSource.

Making a ControlTemplate doesn't seem like the right thing because I am specifiying actual data in the list view also (such as binding to name and address).

Is there a better way to create some type of resource so I can reuse this?

答:
Define the header template and item template in resource dictionary and add reference of them in your code. you can reuse this templates.

```<code>   <DataTemplate x:Key="HeaderTemplate1">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="60"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <TextBlock Text="Name" Grid.Column="0" />
            <TextBlock Text="Address" Grid.Column="1" />
        </Grid>
    </DataTemplate>

    <DataTemplate x:Key="ListViewTemplate1">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="60"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Name}" Grid.Column="0" />
            <TextBlock Text="{Binding clothing1}" Grid.Column="1" />
        </Grid>
    </DataTemplate>

  <ListView HeaderTemplate="{StaticResource HeaderTemplate1}" ItemTemplate="{StaticResource ListViewTemplate1}"/>
</code>```

for more information on Item template:
https://learn.microsoft.com/en-us/windows/uwp/controls-and-patterns/listview-item-templates

Body:
I created the following ListView to display some data (removed extraneous markup):

<ListView ItemsSource="{Binding NewYorkResidents}">
    <ListView.Header>

    </ListView.Header>
    <ListView.HeaderTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="60"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="Name" Grid.Column="0" />
                <TextBlock Text="Address" Grid.Column="1" />
            </Grid>
        </DataTemplate>
    </ListView.HeaderTemplate>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="60"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Text="{Binding Name}" Grid.Column="0" />
                <TextBlock Text="{Binding Address}" Grid.Column="1" />
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Now I want to reuse this exact same ListView + markup in a different view, just with a different ItemsSource (though it will bind to the same data type).

What is the best way to reuse the ListView and just specifiy the ItemsSource? I'm hoping to be able to do something like this:

<ListView DataTemplate="MyTemplate" ItemsSource=<some new binding> />

and still have it show the ListView headers and Name and Address TextBlocks using data from the ItemsSource.

Making a ControlTemplate doesn't seem like the right thing because I am specifiying actual data in the list view also (such as binding to name and address).

Is there a better way to create some type of resource so I can reuse this?

Body:
Define the header template and item template in resource dictionary and add reference of them in your code. you can reuse this templates.

   <DataTemplate x:Key="HeaderTemplate1">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="60"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <TextBlock Text="Name" Grid.Column="0" />
            <TextBlock Text="Address" Grid.Column="1" />
        </Grid>
    </DataTemplate>

    <DataTemplate x:Key="ListViewTemplate1">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="60"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <TextBlock Text="{Binding Name}" Grid.Column="0" />
            <TextBlock Text="{Binding clothing1}" Grid.Column="1" />
        </Grid>
    </DataTemplate>

  <ListView HeaderTemplate="{StaticResource HeaderTemplate1}" ItemTemplate="{StaticResource ListViewTemplate1}"/>

for more information on Item template:
https://learn.microsoft.com/en-us/windows/uwp/controls-and-patterns/listview-item-templates


问:
What algorithms can group characters into words?
I have some text generated by some lousy OCR software.

The output contains mixture of words and space-separated characters, which should have been grouped into words. For example,

```<code>Expr e s s i o n Syntax
S u m m a r y o f T e r minology
</code>```

should have been

```<code>Expression Syntax
Summary of Terminology
</code>```

What algorithms can group characters into words?

If I program in Python, C#, Java, C or C++, what libraries provide the implementation of the algorithms?

Thanks.

答:
Minimal approach:

In your input, remove the space before any single letter words. Mark the final words created as part of this somehow (prefix them with a symbol not in the input, for example).

Get a dictionary of English words, sorted longest to shortest.

For each marked word in your input, find the longest match and break that off as a word. Repeat on the characters left over in the original "word" until there's nothing left over. (In the case where there's no match just leave it alone.)

More sophisticated, overkill approach:

The problem of splitting words without spaces is a real-world problem in languages commonly written without spaces, such as Chinese and Japanese. I'm familiar with Japanese so I'll mainly speak with reference to that.

Typical approaches use a dictionary and a sequence model. The model is trained to learn transition properties between labels - part of speech tagging, combined with the dictionary, is used to figure out the relative likelihood of different potential places to split words. Then the most likely sequence of splits for a whole sentence is solved for using (for example) the Viterbi algorithm.

Creating a system like this is almost certainly overkill if you're just cleaning OCR data, but if you're interested it may be worth looking into.

A sample case where the more sophisticated approach will work and the simple one won't:

input: Playforthefunofit

simple output: Play forth efunofit (forth is longer than for)

sophistiated output: Play for the fun of it (forth efunofit is a low-frequency - that is, unnatural - transition, while for the is not)

You can work around the issue with the simple approach to some extent by adding common short-word sequences to your dictionary as units. For example, add forthe as a dictionary word, and split it in a post processing step.

Hope that helps - good luck!

Body:
I have some text generated by some lousy OCR software.

The output contains mixture of words and space-separated characters, which should have been grouped into words. For example,

Expr e s s i o n Syntax
S u m m a r y o f T e r minology

should have been

Expression Syntax
Summary of Terminology

What algorithms can group characters into words?

If I program in Python, C#, Java, C or C++, what libraries provide the implementation of the algorithms?

Thanks.


问:
Codename One - How to close all Tabs (via code)
I have Tabs component in my form. Tabs are used for navigation.
There are situations, where I need to close all tabs and open new one at index 0. To close all tabs I use this method:

```<code>void close(int from) {
    int to = tabs.getTabCount() - 1;
    for (int i = to; i >= from; i--) {
        tabs.removeTabAt(i);
    }
    if (from > 0)
        tabs.setSelectedIndex(from - 1);
}

void closeAll() {
    close(0);
}
</code>```

This works, but not always. Sometimes I recieve two exceptions:

```<code>[EDT] 0:0:8,436 - Exception: java.lang.IndexOutOfBoundsException - Index: 1, Size: 0
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at com.codename1.ui.Container.getComponentAt(Container.java:1551)
    at com.codename1.ui.Container.doLayout(Container.java:1520)
    at com.codename1.ui.Container.layoutContainer(Container.java:1509)
    at com.codename1.ui.Container.doLayout(Container.java:1522)
    at com.codename1.ui.Container.layoutContainer(Container.java:1509)
    at com.codename1.ui.Container.paint(Container.java:1406)
    at com.codename1.ui.Component.internalPaintImpl(Component.java:1333)
    at com.codename1.ui.Component.paintInternalImpl(Component.java:1307)
    at com.codename1.ui.Component.paintInternal(Component.java:1282)
    at com.codename1.ui.Component.paintInternal(Component.java:1250)
    at com.codename1.ui.Component.paintComponent(Component.java:1535)
    at com.codename1.ui.Component.paintComponent(Component.java:1482)
    at com.codename1.impl.CodenameOneImplementation.paintDirty(CodenameOneImplementation.java:588)
    at com.codename1.impl.javase.JavaSEPort.paintDirty(JavaSEPort.java:1279)
    at com.codename1.ui.Display.edtLoopImpl(Display.java:1077)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:999)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.elementData(ArrayList.java:418)
    at java.util.ArrayList.get(ArrayList.java:431)
    at com.codename1.ui.Container.getComponentAt(Container.java:1551)
    at com.codename1.ui.Tabs$1.actionPerformed(Tabs.java:573)
    at com.codename1.ui.util.EventDispatcher.fireActionSync(EventDispatcher.java:459)
    at com.codename1.ui.util.EventDispatcher.access$100(EventDispatcher.java:45)
    at com.codename1.ui.util.EventDispatcher$CallbackClass.run(EventDispatcher.java:95)
    at com.codename1.ui.Display.processSerialCalls(Display.java:1154)
    at com.codename1.ui.Display.edtLoopImpl(Display.java:1098)
    at com.codename1.ui.Display.flushEdt(Display.java:886)
    at com.codename1.ui.Form.showModal(Form.java:1762)
    at com.codename1.ui.Dialog.showModal(Dialog.java:1085)
    at com.codename1.ui.Dialog.show(Dialog.java:553)
    at com.codename1.ui.Dialog.showPackedImpl(Dialog.java:1389)
    at com.codename1.ui.Dialog.showPacked(Dialog.java:1297)
    at com.codename1.ui.Dialog.showImpl(Dialog.java:1041)
    at com.codename1.ui.Dialog.show(Dialog.java:1019)
    at com.codename1.ui.Dialog.show(Dialog.java:975)
    at com.codename1.ui.Dialog.show(Dialog.java:764)
    at com.codename1.ui.Dialog.show(Dialog.java:717)
    at com.codename1.ui.Dialog.show(Dialog.java:682)
    at com.codename1.ui.Dialog.show(Dialog.java:623)
    at com.codename1.ui.Dialog.show(Dialog.java:778)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:1012)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
</code>```

So what is the right way to close all tabs?

ADDED

Exceptions are thrown only if closeAll() is invoked from sheduled Runnable. I use Runnable to close tabs after tabs slide end.

答:
If this works sometimes I would suggest checking where the remove all comes from and wrapping that with a callSerially(). There are two potential failures:

EDT violation

Event queue still has tasks to perform that rely on the tabs being there

Both issues will be resolved with a callSerially.

Body:
I have Tabs component in my form. Tabs are used for navigation.
There are situations, where I need to close all tabs and open new one at index 0. To close all tabs I use this method:

void close(int from) {
    int to = tabs.getTabCount() - 1;
    for (int i = to; i >= from; i--) {
        tabs.removeTabAt(i);
    }
    if (from > 0)
        tabs.setSelectedIndex(from - 1);
}

void closeAll() {
    close(0);
}

This works, but not always. Sometimes I recieve two exceptions:

[EDT] 0:0:8,436 - Exception: java.lang.IndexOutOfBoundsException - Index: 1, Size: 0
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at com.codename1.ui.Container.getComponentAt(Container.java:1551)
    at com.codename1.ui.Container.doLayout(Container.java:1520)
    at com.codename1.ui.Container.layoutContainer(Container.java:1509)
    at com.codename1.ui.Container.doLayout(Container.java:1522)
    at com.codename1.ui.Container.layoutContainer(Container.java:1509)
    at com.codename1.ui.Container.paint(Container.java:1406)
    at com.codename1.ui.Component.internalPaintImpl(Component.java:1333)
    at com.codename1.ui.Component.paintInternalImpl(Component.java:1307)
    at com.codename1.ui.Component.paintInternal(Component.java:1282)
    at com.codename1.ui.Component.paintInternal(Component.java:1250)
    at com.codename1.ui.Component.paintComponent(Component.java:1535)
    at com.codename1.ui.Component.paintComponent(Component.java:1482)
    at com.codename1.impl.CodenameOneImplementation.paintDirty(CodenameOneImplementation.java:588)
    at com.codename1.impl.javase.JavaSEPort.paintDirty(JavaSEPort.java:1279)
    at com.codename1.ui.Display.edtLoopImpl(Display.java:1077)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:999)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.elementData(ArrayList.java:418)
    at java.util.ArrayList.get(ArrayList.java:431)
    at com.codename1.ui.Container.getComponentAt(Container.java:1551)
    at com.codename1.ui.Tabs$1.actionPerformed(Tabs.java:573)
    at com.codename1.ui.util.EventDispatcher.fireActionSync(EventDispatcher.java:459)
    at com.codename1.ui.util.EventDispatcher.access$100(EventDispatcher.java:45)
    at com.codename1.ui.util.EventDispatcher$CallbackClass.run(EventDispatcher.java:95)
    at com.codename1.ui.Display.processSerialCalls(Display.java:1154)
    at com.codename1.ui.Display.edtLoopImpl(Display.java:1098)
    at com.codename1.ui.Display.flushEdt(Display.java:886)
    at com.codename1.ui.Form.showModal(Form.java:1762)
    at com.codename1.ui.Dialog.showModal(Dialog.java:1085)
    at com.codename1.ui.Dialog.show(Dialog.java:553)
    at com.codename1.ui.Dialog.showPackedImpl(Dialog.java:1389)
    at com.codename1.ui.Dialog.showPacked(Dialog.java:1297)
    at com.codename1.ui.Dialog.showImpl(Dialog.java:1041)
    at com.codename1.ui.Dialog.show(Dialog.java:1019)
    at com.codename1.ui.Dialog.show(Dialog.java:975)
    at com.codename1.ui.Dialog.show(Dialog.java:764)
    at com.codename1.ui.Dialog.show(Dialog.java:717)
    at com.codename1.ui.Dialog.show(Dialog.java:682)
    at com.codename1.ui.Dialog.show(Dialog.java:623)
    at com.codename1.ui.Dialog.show(Dialog.java:778)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:1012)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

So what is the right way to close all tabs?

ADDED

Exceptions are thrown only if closeAll() is invoked from sheduled Runnable. I use Runnable to close tabs after tabs slide end.


问:
Trouble with if statements
```<code>function lessThanNinety(num) {

//return true if num is less than ninety
//otherwise return false
//code here
}
</code>```

Here is the problem, here is my solution.

```<code>function lessThanNinety(num) {
if (number < 90) {
    return true;
}
else {
    return false;
}

}
var number = 50;
</code>```

Where am I going wrong? Thanks

答:
Seems like you are using wrong variable name, change variable number to num:

```<code>function lessThanNinety(num) {
if (num < 90) {
    return true;
}
else {
    return false;
}

}
</code>```

and you will need to call the function:

```<code>var number = 50;
lessThanNinety(number);
</code>```

Title: Trouble with if statements

Body:
function lessThanNinety(num) {

//return true if num is less than ninety
//otherwise return false
//code here
}

Here is the problem, here is my solution.

function lessThanNinety(num) {
if (number < 90) {
    return true;
}
else {
    return false;
}

}
var number = 50;

Where am I going wrong? Thanks

Body:
Seems like you are using wrong variable name, change variable number to num:

function lessThanNinety(num) {
if (num < 90) {
    return true;
}
else {
    return false;
}

}

and you will need to call the function:

var number = 50;
lessThanNinety(number);


问:
How to store MySQL date in Javascript array?
I have searched over the Internet, there is a lot of way to store MySQL records into Javascript array though PHP, like this one. However I can't really store the date record in Javascript.

Let say,

My MySQL date record rows in column called holiday_date: 2017-06-25, 2017-06-26, 2017-06-27.

How can I store in Javascript after I converted them into json by

```<code><?php
    $sql = "SELECT public_holiday.holiday_date
            FROM public_holiday";
    $result = mysqli_query($conn, $sql);

    $result_array = Array();

    while($row = mysqli_fetch_assoc($result))
    {
         $result_array[] = $row;
    }

    $json_array = json_encode($result_array);

    echo $json_array;
  ?>
</code>```

?

I have tried to store them into a javascript date array like

```<code>var holidays = [<?php //sample array for example
        $loop_one = true;
        foreach ($result_array as $date)
        {
            if ($loop_one)
            {
                echo "'new Date(\'$date\')'";
                $loop_one=false;
            }
            else
            {
                echo ", 'new Date(\'$date\')'";
            }
        }
?>];
</code>```

but all of these are invalid.

I need your help, much appreciated.

答:
Your while loop should be like this and push the date into new array

```<code><?php

$result_array = Array();

while($row = mysqli_fetch_assoc($result))
{
     $result_array[] = $row['public_holiday.holiday_dat'];
}

 //$result_array contains date like this $result_array = ['2017-06-26', '2017-06-27'];

?>
</code>```

Javascript example

```<code><script>

    var holidays = [<?php $result_array = ['2017-06-26', '2017-06-27']; //sample array for example
    $loop_one = true;
    foreach ($result_array as $date) {

        if ($loop_one) {
            echo "'new Date(\'$date\')'";

            $loop_one=false;
        } else {
            echo ", 'new Date(\'$date\')'";
        }
    }
?>];

 console.log(holidays);

</script>
</code>```

Update 1: Finally your code should be like this

```<code><?php
    $sql = "SELECT public_holiday.holiday_date FROM public_holiday";

    $result = mysqli_query($conn, $sql);

    $result_array = Array();

    while($row = mysqli_fetch_assoc($result))
    {
        $result_array[] = $row['public_holiday.holiday_dat'];
    }

?>
<script>

    var holidays = [<?php
    $loop_one = true;
    foreach ($result_array as $date) {

        if ($loop_one) {
            echo "'new Date(\'$date\')'";

            $loop_one=false;
        } else {
            echo ", 'new Date(\'$date\')'";
        }
    }
?>];

 console.log(holidays);

</script>
</code>```

Body:
I have searched over the Internet, there is a lot of way to store MySQL records into Javascript array though PHP, like this one. However I can't really store the date record in Javascript.

Let say,

My MySQL date record rows in column called holiday_date: 2017-06-25, 2017-06-26, 2017-06-27.

How can I store in Javascript after I converted them into json by

<?php
    $sql = "SELECT public_holiday.holiday_date
            FROM public_holiday";
    $result = mysqli_query($conn, $sql);

    $result_array = Array();

    while($row = mysqli_fetch_assoc($result))
    {
         $result_array[] = $row;
    }

    $json_array = json_encode($result_array);

    echo $json_array;
  ?>

?

I have tried to store them into a javascript date array like

var holidays = [<?php //sample array for example
        $loop_one = true;
        foreach ($result_array as $date)
        {
            if ($loop_one)
            {
                echo "'new Date(\'$date\')'";
                $loop_one=false;
            }
            else
            {
                echo ", 'new Date(\'$date\')'";
            }
        }
?>];

but all of these are invalid.

I need your help, much appreciated.

Body:
Your while loop should be like this and push the date into new array

<?php

$result_array = Array();

while($row = mysqli_fetch_assoc($result))
{
     $result_array[] = $row['public_holiday.holiday_dat'];
}

 //$result_array contains date like this $result_array = ['2017-06-26', '2017-06-27'];

?>

Javascript example

<script>

    var holidays = [<?php $result_array = ['2017-06-26', '2017-06-27']; //sample array for example
    $loop_one = true;
    foreach ($result_array as $date) {

        if ($loop_one) {
            echo "'new Date(\'$date\')'";

            $loop_one=false;
        } else {
            echo ", 'new Date(\'$date\')'";
        }
    }
?>];

 console.log(holidays);

</script>

Update 1: Finally your code should be like this

<?php
    $sql = "SELECT public_holiday.holiday_date FROM public_holiday";

    $result = mysqli_query($conn, $sql);

    $result_array = Array();

    while($row = mysqli_fetch_assoc($result))
    {
        $result_array[] = $row['public_holiday.holiday_dat'];
    }

?>
<script>

    var holidays = [<?php
    $loop_one = true;
    foreach ($result_array as $date) {

        if ($loop_one) {
            echo "'new Date(\'$date\')'";

            $loop_one=false;
        } else {
            echo ", 'new Date(\'$date\')'";
        }
    }
?>];

 console.log(holidays);

</script>


问:
Swift get date five years prior to today
I have this validation code, I want to add another part to it where it checks to make sure that the date selected in not more than fives years in the past from today. Thoughts!</p>

```<code>let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium
    let date1 = dateFormatter.date (from: termStartDate.text!)

    guard let startDate = date1 , startDate < Date() else {
        let alert = UIAlertController(title: "Input Error", message: "Select Date less than today", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

        self.present(alert, animated: true, completion: nil)
        return
    }
</code>```

答:
You can grab the date five years back from now with this one-liner:

```<code>let fiveYearsAgoDate = Calendar.current.date(byAdding: .year, value: -5, to: Date())
</code>```

Since you may not be using a UIDatePicker (many apps use a numeric key pad that inserts separators, such as /, between days, months, and years), this is a viable option to validate user input. Otherwise, if using a UIDatePicker, setting the maximum and minimum dates is the way to go.

Body:
I have this validation code, I want to add another part to it where it checks to make sure that the date selected in not more than fives years in the past from today. Thoughts!

let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium
    let date1 = dateFormatter.date (from: termStartDate.text!)

    guard let startDate = date1 , startDate < Date() else {
        let alert = UIAlertController(title: "Input Error", message: "Select Date less than today", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

        self.present(alert, animated: true, completion: nil)
        return
    }

Body:
You can grab the date five years back from now with this one-liner:

let fiveYearsAgoDate = Calendar.current.date(byAdding: .year, value: -5, to: Date())

Since you may not be using a UIDatePicker (many apps use a numeric key pad that inserts separators, such as /, between days, months, and years), this is a viable option to validate user input. Otherwise, if using a UIDatePicker, setting the maximum and minimum dates is the way to go.


问:
Does it safe to save important keys on gradle?
I have some important keys in my application and I want to know where its the best place to put them. I also have enabled my proguard but when I decompile the app the keys steel visible, I was thinking put them on gradle.</p>

答: You can store those keys in the shared preference file with some encryption mechanism.</p>


问:
apache ant runs properly but ask me for some other things also
When I use Apache-Ant following :

```<code>ant -version
Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre1.8.0_111\lib\tools.jar
Apache Ant(TM) version 1.10.1 compiled on February 2 2017
</code>```

However, it works properly but why it shows this and how can I resolve this?

Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre1.8.0_111\lib\tools.jar

答:
It is because, you have installed JRE while it is required to install JDK.

Please refer System Requirements of Ant

For the current version of Ant, you will also need a JDK installed on your system, version 1.4 or later required, 1.7 or later strongly recommended. The more up-to-date the version of Java , the more Ant tasks you get.

Note: If a JDK is not present, only the JRE runtime, then many tasks will not work.

So, install JDK and

set JAVA_HOME correctly

add %JAVA_HOME%\bin to PATH

Body:
When I use Apache-Ant following :

ant -version
Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre1.8.0_111\lib\tools.jar
Apache Ant(TM) version 1.10.1 compiled on February 2 2017

However, it works properly but why it shows this and how can I resolve this?

Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre1.8.0_111\lib\tools.jar


问:
HTML5 Email input pattern attribute
I’m trying to make a html5 form that contains one email input, one check box input, and one submit input.
I'm trying to use the pattern attribute for the email input but I don't know what to place in this attribute. I do know that I'm supposed to use a regular expression that must match the JavaScript Pattern production but I don't know how to do this.

What I'm trying to get this attribute to do is to check to make sure that the email contains one @ and at least one or more dot and if possible check to see if the address after the @ is a real address. If I can't do this through this attribute then I'll consider using JavaScript but for checking for one @ and one or more dot I do want to use the pattern attribute for sure.

The pattern attribute needs to check for:

Only one @

One or more dot

And if possible check to see if the address after the @ is a valid address

An alternative to this one is to use a JavaScript but for all the other conditions I do not want to use a JavaScript.

Title: HTML5 Email input pattern attribute

Body: ^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$


问:
Add UIView rounding logic inside UIView class
I have a custom UIView and I add it to my ViewController like this:

```<code>let myCustomView = Bundle.main.loadNibNamed("MyCustomView", owner: nil, options: nil) as! MyCustomView
myCustomView.layer.cornerRadius = 10
myCustomView.layer.masksToBounds = true
</code>```

I round the corners of the view. But I am wondering, is there a way to move this logic of rounding the corners inside the MyCustomView class?

答:
Yes - If you're loading a nib with a custom view, that nib is very likely referring to another class. If that's the case, you can move the logic inside the class itself.

That said, I really like Lawliet's suggestion of making a UIView extension with IBInspectable properties. The downside to that approach is that every single view now has these properties, which creates a certain overhead and potential for clashes.

Body:
I have a custom UIView and I add it to my ViewController like this:

let myCustomView = Bundle.main.loadNibNamed("MyCustomView", owner: nil, options: nil) as! MyCustomView
myCustomView.layer.cornerRadius = 10
myCustomView.layer.masksToBounds = true

I round the corners of the view. But I am wondering, is there a way to move this logic of rounding the corners inside the MyCustomView class?