问:
Importing Props from Redux directly into function
I have different kinds of interactive forms within my page. Each of them dispatch the same function that sends their data to me via E-Mail. But every time I send this data I would like to add the user profile and E-Mail from within my redux store. I don't want to be forced to pass this information via props, every time.

Is there a way to import props from the redux store directly into my external function, without having it pass it as a prop?

答: The "right" answer is to use the redux-thunk middleware.  Turn your function into a thunk action creator, connect the component, and dispatch the thunk function, then use getState() inside of the thunk to access the values from the store.


来源: stackexchange

问:
Creating multiple arrays which will add up to one final array. Debugging issue. Swift and Xcode
I am trying to create a flashcard app.  I successfully got the app too the point where I could swipe through an array of photos(see code below).

```<code>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.

    }
}
</code>```

but I needed to add a settings page so that the user could choose which word groups they wanted to have displayed, so I have tried to change the code so that the words were split up into groups and I made the groups "active" so that the user could manipulate them in a settings page(if the user turns a word group off then that word group is no longer active). However I have not been able to get this new code to run smooth, it is riddled with bugs.  Can any of you see what is wrong with this new code? as of now I have not made a settings page but when I run the new code I should be able to swipe through all of the pictures just like my original code, However this is not possible currently.  Any help would be much appreciated.  Thanks!

```<code>import UIKit

class SecondViewController: UIViewController , UIGestureRecognizerDelegate  {

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

@IBOutlet weak var imgPhoto: UIImageView!

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

let list1 = List(words:["lake", "lamb", "lamp", "lark", "leaf", "leash", "left", "leg", "lime", "lion", "lips", "list", "lock", "log", "look", "love", "lunch"], active: true)

let list2 = List(words: ["ladder", "ladybug", "laughing", "lawnmower", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning", "listen", "llama"], active: true)

let list3 = List(words: ["alligator", "balance", "ballerina", "balloon", "bowling", "cello", "colors", "curlyhair", "dollar", "dolphin", "elephant", "eyelashes", "gasoline", "goalie", "hula", "jellyfish", "olive", "pillow", "pilot", "polarbear", "rollerskate", "ruler", "silly", "telephone", "television", "tulip", "umbrella", "valentine", "violin", "xylophone", "yellow"], active: true)

let list4 = List(words: ["apple", "ball", "bell", "bubble", "castle", "fall", "fishbowl", "girl", "owl", "pail", "peel", "pool", "smile", "whale", "wheel"], active: true)

let list5 = List(words: ["planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus"], active: true)

let list6 = List(words: ["black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue"], active: true)

let list7 = List(words: ["flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly"], active: true)

let list8 = List(words: ["glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue"], active: true)

let list9 = List(words: ["clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud"], active: true)

let list10 = List(words:["sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow"], active: true)

let list11 = List(words: ["belt", "cold", "dolphin", "elf", "golf", "melt", "milk", "shelf"], active: true)

var imageIndex: NSInteger = 0

override func viewDidLoad() {
    super.viewDidLoad()

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

    var wordLists = [list1, list2, list3, list4, list5, list6, list7, list8, list9, list10, list11]

    var imageList: [String] {

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

            } else {
                return result
            }
        }

        return active

    }

    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 = imageList

            }

            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 > imageList {

                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>```

答:
You're very close; there are a few fixes needed:

Move the imageList computed variable to the class level, instead of inside viewDidLoad.

The imageIndex variable can be an Int instead of an NSInteger. This is not a breaking change, but will make things easier and is better Swift style.

Where you previously used the maxImages variable, you can replace them with imageList.count, which is the total number of elements in the array.

Here is the final, edited code. It compiles; let me know if it works!

```<code>class SecondViewController: UIViewController , UIGestureRecognizerDelegate  {

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

    @IBOutlet weak var imgPhoto: UIImageView!

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

    let list1 = List(words:["lake", "lamb", "lamp", "lark", "leaf", "leash", "left", "leg", "lime", "lion", "lips", "list", "lock", "log", "look", "love", "lunch"], active: true)

    let list2 = List(words: ["ladder", "ladybug", "laughing", "lawnmower", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning", "listen", "llama"], active: true)

    let list3 = List(words: ["alligator", "balance", "ballerina", "balloon", "bowling", "cello", "colors", "curlyhair", "dollar", "dolphin", "elephant", "eyelashes", "gasoline", "goalie", "hula", "jellyfish", "olive", "pillow", "pilot", "polarbear", "rollerskate", "ruler", "silly", "telephone", "television", "tulip", "umbrella", "valentine", "violin", "xylophone", "yellow"], active: true)

    let list4 = List(words: ["apple", "ball", "bell", "bubble", "castle", "fall", "fishbowl", "girl", "owl", "pail", "peel", "pool", "smile", "whale", "wheel"], active: true)

    let list5 = List(words: ["planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus"], active: true)

    let list6 = List(words: ["black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue"], active: true)

    let list7 = List(words: ["flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly"], active: true)

    let list8 = List(words: ["glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue"], active: true)

    let list9 = List(words: ["clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud"], active: true)

    let list10 = List(words:["sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow"], active: true)

    let list11 = List(words: ["belt", "cold", "dolphin", "elf", "golf", "melt", "milk", "shelf"], active: true)

    var imageIndex: Int = 0

    var imageList: [String] {

        let wordLists = [list1, list2, list3, list4, list5, list6, list7, list8, list9, list10, list11]

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

            } else {
                return result
            }
        }

        return active

    }

    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 = imageList.count - 1

                }

                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 > imageList.count - 1 {

                    imageIndex = 0

                }

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

            default:
                break //stops the code/codes nothing.
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a flashcard app.  I successfully got the app too the point where I could swipe through an array of photos(see code below).

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.

    }
}

but I needed to add a settings page so that the user could choose which word groups they wanted to have displayed, so I have tried to change the code so that the words were split up into groups and I made the groups "active" so that the user could manipulate them in a settings page(if the user turns a word group off then that word group is no longer active). However I have not been able to get this new code to run smooth, it is riddled with bugs.  Can any of you see what is wrong with this new code? as of now I have not made a settings page but when I run the new code I should be able to swipe through all of the pictures just like my original code, However this is not possible currently.  Any help would be much appreciated.  Thanks!

import UIKit

class SecondViewController: UIViewController , UIGestureRecognizerDelegate  {

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

@IBOutlet weak var imgPhoto: UIImageView!

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

let list1 = List(words:["lake", "lamb", "lamp", "lark", "leaf", "leash", "left", "leg", "lime", "lion", "lips", "list", "lock", "log", "look", "love", "lunch"], active: true)

let list2 = List(words: ["ladder", "ladybug", "laughing", "lawnmower", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning", "listen", "llama"], active: true)

let list3 = List(words: ["alligator", "balance", "ballerina", "balloon", "bowling", "cello", "colors", "curlyhair", "dollar", "dolphin", "elephant", "eyelashes", "gasoline", "goalie", "hula", "jellyfish", "olive", "pillow", "pilot", "polarbear", "rollerskate", "ruler", "silly", "telephone", "television", "tulip", "umbrella", "valentine", "violin", "xylophone", "yellow"], active: true)

let list4 = List(words: ["apple", "ball", "bell", "bubble", "castle", "fall", "fishbowl", "girl", "owl", "pail", "peel", "pool", "smile", "whale", "wheel"], active: true)

let list5 = List(words: ["planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus"], active: true)

let list6 = List(words: ["black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue"], active: true)

let list7 = List(words: ["flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly"], active: true)

let list8 = List(words: ["glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue"], active: true)

let list9 = List(words: ["clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud"], active: true)

let list10 = List(words:["sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow"], active: true)

let list11 = List(words: ["belt", "cold", "dolphin", "elf", "golf", "melt", "milk", "shelf"], active: true)

var imageIndex: NSInteger = 0

override func viewDidLoad() {
    super.viewDidLoad()

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

    var wordLists = [list1, list2, list3, list4, list5, list6, list7, list8, list9, list10, list11]

    var imageList: [String] {

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

            } else {
                return result
            }
        }

        return active

    }

    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 = imageList

            }

            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 > imageList {

                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.
}
*/

Body:
You're very close; there are a few fixes needed:

Move the imageList computed variable to the class level, instead of inside viewDidLoad.

The imageIndex variable can be an Int instead of an NSInteger. This is not a breaking change, but will make things easier and is better Swift style.

Where you previously used the maxImages variable, you can replace them with imageList.count, which is the total number of elements in the array.

Here is the final, edited code. It compiles; let me know if it works!

class SecondViewController: UIViewController , UIGestureRecognizerDelegate  {

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

    @IBOutlet weak var imgPhoto: UIImageView!

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

    let list1 = List(words:["lake", "lamb", "lamp", "lark", "leaf", "leash", "left", "leg", "lime", "lion", "lips", "list", "lock", "log", "look", "love", "lunch"], active: true)

    let list2 = List(words: ["ladder", "ladybug", "laughing", "lawnmower", "lemon", "leopard", "leprechaun", "letters", "licking", "lifesaver", "lifting", "lightbulb", "lightning", "listen", "llama"], active: true)

    let list3 = List(words: ["alligator", "balance", "ballerina", "balloon", "bowling", "cello", "colors", "curlyhair", "dollar", "dolphin", "elephant", "eyelashes", "gasoline", "goalie", "hula", "jellyfish", "olive", "pillow", "pilot", "polarbear", "rollerskate", "ruler", "silly", "telephone", "television", "tulip", "umbrella", "valentine", "violin", "xylophone", "yellow"], active: true)

    let list4 = List(words: ["apple", "ball", "bell", "bubble", "castle", "fall", "fishbowl", "girl", "owl", "pail", "peel", "pool", "smile", "whale", "wheel"], active: true)

    let list5 = List(words: ["planet", "plank", "plant", "plate", "play", "plum", "plumber", "plus"], active: true)

    let list6 = List(words: ["black", "blanket", "blender", "blocks", "blond", "blood", "blow", "blue"], active: true)

    let list7 = List(words: ["flag", "flipflop", "float", "floor", "flower", "fluffy", "flute", "fly"], active: true)

    let list8 = List(words: ["glacier", "glad", "glasses", "glide", "glitter", "globe", "glove", "glue"], active: true)

    let list9 = List(words: ["clam", "clamp", "clap", "claw", "clean", "climb", "clip", "cloud"], active: true)

    let list10 = List(words:["sled", "sleep", "sleeves", "slice", "slide", "slime", "slip", "slow"], active: true)

    let list11 = List(words: ["belt", "cold", "dolphin", "elf", "golf", "melt", "milk", "shelf"], active: true)

    var imageIndex: Int = 0

    var imageList: [String] {

        let wordLists = [list1, list2, list3, list4, list5, list6, list7, list8, list9, list10, list11]

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

            } else {
                return result
            }
        }

        return active

    }

    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 = imageList.count - 1

                }

                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 > imageList.count - 1 {

                    imageIndex = 0

                }

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

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


问:
How to pass output of one procedure as an argument to another procedure in tcl
I want pass output of one procedure which is a list as an argument to another procedure.Below is a code which I have tried.

```<code>proc distance {n1 n2 nd1 nd2} {
    set x1 [expr int([$n1 set X_])]
    set y1 [expr int([$n1 set Y_])]
    set x2 [expr int([$n2 set X_])]
    set y2 [expr int([$n2 set Y_])]

    set d [expr hypot($x2-$x1,$y2-$y1)]

    return [list $nd1 $nd2 $x1 $y1 $x2 $y2 $d]
}

proc processDistances {count threshold {filter ""}} {

 global node_

    set distances {}
    for {set i 1} {$i < $count} {incr i} {
        for {set j 1} {$j < $count} {incr j} {
            # Skip self comparisons
            if {$i == $j} continue

            # Apply target filter
            if {$filter ne "" && $j != $filter} continue

            # Get the distance information
            set thisDistance [distance $node_($i) $node_($j) $i $j]

            # Check that the nodes are close enough
            if {[lindex $thisDistance 6] < $threshold} {
                lappend distances $thisDistance
            }
        }
    }

    # Sort the pairs, by distances

    set distances [lsort -real -increasing -index 6 $distances]

Inverse2 {*}$distances
}
$ns at 8.5 [list processDistances $val(nn) 200 41]

proc Inverse2 {m} {

set result [open R.tr w]

lassign [lindex $m 0 2] x1
lassign [lindex $m 0 3] y1
lassign [lindex $m 0 4] d1
lassign [lindex $m 1 2] x2
lassign [lindex $m 1 3] y2
lassign [lindex $m 1 4] d2
lassign [lindex $m 2 2] x3
lassign [lindex $m 2 3] y3
lassign [lindex $m 2 4] d3

set mt {{? ?} {? ?}}
lset mt 0 0 [expr 2*($x1-$x2)]
lset mt 0 1 [expr 2*($y1-$y2)]
lset mt 1 0 [expr 2*($x1-$x3)]
lset mt 1 1 [expr 2*($y1-$y3)]
set const {{?} {?}}
lset const 0 [expr {(pow($x1,2)+pow($y1,2)-pow($d1,2))-(pow($x2,2)+pow($y2,2)-pow($d2,2))}]
lset const 1 [expr {(pow($x1,2)+pow($y1,2)-pow($d1,2))-(pow($x3,2)+pow($y3,2)-pow($d3,2))}]

set x [expr {double([lindex [Inverse3 $mt] 0 0]  * [lindex $const 0]
                   + [lindex [Inverse3 $mt] 0 1] * [lindex $const 1])}]
set y [expr {double([lindex [Inverse3 $mt] 1 0]  * [lindex $const 0]
                   + [lindex [Inverse3 $mt] 1 1] * [lindex $const 1])}]

puts $result "x location of object is: $x \ny location of object is: $y"

 }
</code>```

Error:

```<code>ns: processDistances 42 200 41: wrong # args: should be "Inverse2 m"
    while executing
"Inverse2 {*} $distances"
    (procedure "processDistances" line 32)
    invoked from within
"processDistances 42 200 41"
</code>```

I'm getting output of proc processDistances successfully which is a sorted list but when I pass this output to procedure Inverse2 using command Inverse2 {*}$distances written in processDistances (I have tcl8.5).I'm getting above error.Where I'm dong wrong.please help me out.

答:
I am suggesting you run it just as I replaced it. If this does not work, I'm not sure what you're asking for.</p>

```<code>proc distance {n1 n2 nd1 nd2} {
    set x1 [expr int([$n1 set X_])]
    set y1 [expr int([$n1 set Y_])]
    set x2 [expr int([$n2 set X_])]
    set y2 [expr int([$n2 set Y_])]

    set d [expr hypot($x2-$x1,$y2-$y1)]

    return [list $nd1 $nd2 $x1 $y1 $x2 $y2 $d]
}

proc processDistances {count threshold {filter ""}} {

 global node_

    set distances {}
    for {set i 1} {$i < $count} {incr i} {
        for {set j 1} {$j < $count} {incr j} {
            # Skip self comparisons
            if {$i == $j} continue

            # Apply target filter
            if {$filter ne "" && $j != $filter} continue

            # Get the distance information
            set thisDistance [distance $node_($i) $node_($j) $i $j]

            # Check that the nodes are close enough
            if {[lindex $thisDistance 6] < $threshold} {
                lappend distances $thisDistance
            }
        }
    }

    # Sort the pairs, by distances

    set distances [lsort -real -increasing -index 6 $distances]

#Inverse2 {*}$distances
Inverse2 $distances
}
$ns at 8.5 [list processDistances $val(nn) 200 41]

proc Inverse2 {m} {

set result [open R.tr w]

lassign [lindex $m 0 2] x1
lassign [lindex $m 0 3] y1
lassign [lindex $m 0 4] d1
lassign [lindex $m 1 2] x2
lassign [lindex $m 1 3] y2
lassign [lindex $m 1 4] d2
lassign [lindex $m 2 2] x3
lassign [lindex $m 2 3] y3
lassign [lindex $m 2 4] d3

set mt {{? ?} {? ?}}
lset mt 0 0 [expr 2*($x1-$x2)]
lset mt 0 1 [expr 2*($y1-$y2)]
lset mt 1 0 [expr 2*($x1-$x3)]
lset mt 1 1 [expr 2*($y1-$y3)]
set const {{?} {?}}
lset const 0 [expr {(pow($x1,2)+pow($y1,2)-pow($d1,2))-(pow($x2,2)+pow($y2,2)-pow($d2,2))}]
lset const 1 [expr {(pow($x1,2)+pow($y1,2)-pow($d1,2))-(pow($x3,2)+pow($y3,2)-pow($d3,2))}]

set x [expr {double([lindex [Inverse3 $mt] 0 0]  * [lindex $const 0]
                   + [lindex [Inverse3 $mt] 0 1] * [lindex $const 1])}]
set y [expr {double([lindex [Inverse3 $mt] 1 0]  * [lindex $const 0]
                   + [lindex [Inverse3 $mt] 1 1] * [lindex $const 1])}]

puts $result "x location of object is: $x \ny location of object is: $y"

 }
</code>```

Body:
I want pass output of one procedure which is a list as an argument to another procedure.Below is a code which I have tried.

proc distance {n1 n2 nd1 nd2} {
    set x1 [expr int([$n1 set X_])]
    set y1 [expr int([$n1 set Y_])]
    set x2 [expr int([$n2 set X_])]
    set y2 [expr int([$n2 set Y_])]

    set d [expr hypot($x2-$x1,$y2-$y1)]

    return [list $nd1 $nd2 $x1 $y1 $x2 $y2 $d]
}

proc processDistances {count threshold {filter ""}} {

 global node_

    set distances {}
    for {set i 1} {$i < $count} {incr i} {
        for {set j 1} {$j < $count} {incr j} {
            # Skip self comparisons
            if {$i == $j} continue

            # Apply target filter
            if {$filter ne "" && $j != $filter} continue

            # Get the distance information
            set thisDistance [distance $node_($i) $node_($j) $i $j]

            # Check that the nodes are close enough
            if {[lindex $thisDistance 6] < $threshold} {
                lappend distances $thisDistance
            }
        }
    }

    # Sort the pairs, by distances

    set distances [lsort -real -increasing -index 6 $distances]

Inverse2 {*}$distances
}
$ns at 8.5 [list processDistances $val(nn) 200 41]

proc Inverse2 {m} {

set result [open R.tr w]

lassign [lindex $m 0 2] x1
lassign [lindex $m 0 3] y1
lassign [lindex $m 0 4] d1
lassign [lindex $m 1 2] x2
lassign [lindex $m 1 3] y2
lassign [lindex $m 1 4] d2
lassign [lindex $m 2 2] x3
lassign [lindex $m 2 3] y3
lassign [lindex $m 2 4] d3

set mt {{? ?} {? ?}}
lset mt 0 0 [expr 2*($x1-$x2)]
lset mt 0 1 [expr 2*($y1-$y2)]
lset mt 1 0 [expr 2*($x1-$x3)]
lset mt 1 1 [expr 2*($y1-$y3)]
set const {{?} {?}}
lset const 0 [expr {(pow($x1,2)+pow($y1,2)-pow($d1,2))-(pow($x2,2)+pow($y2,2)-pow($d2,2))}]
lset const 1 [expr {(pow($x1,2)+pow($y1,2)-pow($d1,2))-(pow($x3,2)+pow($y3,2)-pow($d3,2))}]

set x [expr {double([lindex [Inverse3 $mt] 0 0]  * [lindex $const 0]
                   + [lindex [Inverse3 $mt] 0 1] * [lindex $const 1])}]
set y [expr {double([lindex [Inverse3 $mt] 1 0]  * [lindex $const 0]
                   + [lindex [Inverse3 $mt] 1 1] * [lindex $const 1])}]

puts $result "x location of object is: $x \ny location of object is: $y"

 }

Error:

ns: processDistances 42 200 41: wrong # args: should be "Inverse2 m"
    while executing
"Inverse2 {*} $distances"
    (procedure "processDistances" line 32)
    invoked from within
"processDistances 42 200 41"

I'm getting output of proc processDistances successfully which is a sorted list but when I pass this output to procedure Inverse2 using command Inverse2 {*}$distances written in processDistances (I have tcl8.5).I'm getting above error.Where I'm dong wrong.please help me out.

Body:
I am suggesting you run it just as I replaced it. If this does not work, I'm not sure what you're asking for.

proc distance {n1 n2 nd1 nd2} {
    set x1 [expr int([$n1 set X_])]
    set y1 [expr int([$n1 set Y_])]
    set x2 [expr int([$n2 set X_])]
    set y2 [expr int([$n2 set Y_])]

    set d [expr hypot($x2-$x1,$y2-$y1)]

    return [list $nd1 $nd2 $x1 $y1 $x2 $y2 $d]
}

proc processDistances {count threshold {filter ""}} {

 global node_

    set distances {}
    for {set i 1} {$i < $count} {incr i} {
        for {set j 1} {$j < $count} {incr j} {
            # Skip self comparisons
            if {$i == $j} continue

            # Apply target filter
            if {$filter ne "" && $j != $filter} continue

            # Get the distance information
            set thisDistance [distance $node_($i) $node_($j) $i $j]

            # Check that the nodes are close enough
            if {[lindex $thisDistance 6] < $threshold} {
                lappend distances $thisDistance
            }
        }
    }

    # Sort the pairs, by distances

    set distances [lsort -real -increasing -index 6 $distances]

#Inverse2 {*}$distances
Inverse2 $distances
}
$ns at 8.5 [list processDistances $val(nn) 200 41]

proc Inverse2 {m} {

set result [open R.tr w]

lassign [lindex $m 0 2] x1
lassign [lindex $m 0 3] y1
lassign [lindex $m 0 4] d1
lassign [lindex $m 1 2] x2
lassign [lindex $m 1 3] y2
lassign [lindex $m 1 4] d2
lassign [lindex $m 2 2] x3
lassign [lindex $m 2 3] y3
lassign [lindex $m 2 4] d3

set mt {{? ?} {? ?}}
lset mt 0 0 [expr 2*($x1-$x2)]
lset mt 0 1 [expr 2*($y1-$y2)]
lset mt 1 0 [expr 2*($x1-$x3)]
lset mt 1 1 [expr 2*($y1-$y3)]
set const {{?} {?}}
lset const 0 [expr {(pow($x1,2)+pow($y1,2)-pow($d1,2))-(pow($x2,2)+pow($y2,2)-pow($d2,2))}]
lset const 1 [expr {(pow($x1,2)+pow($y1,2)-pow($d1,2))-(pow($x3,2)+pow($y3,2)-pow($d3,2))}]

set x [expr {double([lindex [Inverse3 $mt] 0 0]  * [lindex $const 0]
                   + [lindex [Inverse3 $mt] 0 1] * [lindex $const 1])}]
set y [expr {double([lindex [Inverse3 $mt] 1 0]  * [lindex $const 0]
                   + [lindex [Inverse3 $mt] 1 1] * [lindex $const 1])}]

puts $result "x location of object is: $x \ny location of object is: $y"

 }


问:
How to disable or enable a bootstrap submit button if checked checkbox
I need to enable or disable a bootstrap submit button on a form if a checkbox is cheched or not</p>

```<code>echo "<div class='panel panel-danger'><div class='panel-heading'>OBSERVACIONES</div><div class='panel-body'>";
echo "<div class='input-group'>";
echo "<label class='checkbox-inline'><input type='checkbox' name='visto' id='visto' value=''> Visto bueno del Responsable</label>";
echo "</div>";
echo "</div>";

...

echo "<input type='submit' class='btn btn-primary' value='SAVE' name='grabaperaus' formaction='update.php'>";
</code>```

答:
With Jquery

HTML:

```<code><input type='checkbox' data-toggle='inputid'/>
<input id='inputid'/>
</code>```

JAVASCRIPT:

```<code>function toggle(target) {
    var toggle = $(target).data("toggle");
    if (toggle) {
        var obj = $("#" + toggle);
        if (target.checked ==false) {
            obj.attr("disabled", "disabled");
        } else {
            obj.removeAttr("disabled");
        }
    }
}

$("input:checkbox").each(function(){toggle(this);}).on('input',function(){toggle(this);});
</code>```

Body:
I need to enable or disable a bootstrap submit button on a form if a checkbox is cheched or not

echo "

OBSERVACIONES

";
echo "
";
echo "<input type='checkbox' name='visto' id='visto' value=''> Visto bueno del Responsable";
echo "
";
echo "
";

...

echo "<input type='submit' class='btn btn-primary' value='SAVE' name='grabaperaus' formaction='update.php'>";

Body:
With Jquery

HTML:

<input type='checkbox' data-toggle='inputid'/>
<input id='inputid'/>

JAVASCRIPT:

function toggle(target) {
    var toggle = $(target).data("toggle");
    if (toggle) {
        var obj = $("#" + toggle);
        if (target.checked ==false) {
            obj.attr("disabled", "disabled");
        } else {
            obj.removeAttr("disabled");
        }
    }
}

$("input:checkbox").each(function(){toggle(this);}).on('input',function(){toggle(this);});

ContentLicense: CC BY-SA 4.0


问:
Insert variable in Echo String
I am using the following code to calculate the time difference between a post and the current time:

```<code>function format_interval(DateInterval $interval) {
            $result = "";
            if ($interval->y) { $result .= $interval->format("%y y "); }
            if ($interval->m) { $result .= $interval->format("%m m "); }
            if ($interval->d) { $result .= $interval->format("%d d "); }
            if ($interval->h) { $result .= $interval->format("%h h "); }
            if ($interval->i) { $result .= $interval->format("%i m "); }
            if ($interval->s) { $result .= $interval->format("%s s "); }

            return $result;
        }

        $first_date = new DateTime($row['updatecomment']);
        $second_date = new DateTime("now");

        $difference = $first_date->diff($second_date);

        $post_date = format_interval($difference);
</code>```

I would then like to enter $post_date into the following echo string:

```<code>if ($row['comment'] != null) {
            echo '<div class="rowComment">' . '<div class="postComment" id="postcomment">' . $row['comment'] . '</div>' . '<div class="row3_a">' . "Posted: '.$post_date.' . Ago" . '</div>' . '</div>';
</code>```

However, what I current get in return is:

```<code>Posted: '..' . Ago
</code>```

I've searched the forums to get to this point. I feel I am very close, but I am just not getting the time difference output.

答:
You have a few mismatched quotes.</p>

```<code>if ($row['comment'] != null)
            echo '<div class="rowComment">' . '<div class="postComment" id="postcomment">' . $row['comment'] . '</div>' . '<div class="row3_a">' . "Posted: $post_date Ago" . '</div></div>';
</code>```

Title: Insert variable in Echo String

Body:
I am using the following code to calculate the time difference between a post and the current time:

function format_interval(DateInterval $interval) {
            $result = "";
            if ($interval->y) { $result .= $interval->format("%y y "); }
            if ($interval->m) { $result .= $interval->format("%m m "); }
            if ($interval->d) { $result .= $interval->format("%d d "); }
            if ($interval->h) { $result .= $interval->format("%h h "); }
            if ($interval->i) { $result .= $interval->format("%i m "); }
            if ($interval->s) { $result .= $interval->format("%s s "); }

            return $result;
        }

        $first_date = new DateTime($row['updatecomment']);
        $second_date = new DateTime("now");

        $difference = $first_date->diff($second_date);

        $post_date = format_interval($difference);

I would then like to enter $post_date into the following echo string:

if ($row['comment'] != null) {
            echo '
' . '
' . $row['comment'] . '
' . '
' . "Posted: '.$post_date.' . Ago" . '
' . '
';

However, what I current get in return is:

Posted: '..' . Ago

I've searched the forums to get to this point. I feel I am very close, but I am just not getting the time difference output.

Body:
You have a few mismatched quotes.

if ($row['comment'] != null)
            echo '<div class="rowComment">' . '<div class="postComment" id="postcomment">' . $row['comment'] . '</div>' . '<div class="row3_a">' . "Posted: $post_date Ago" . '</div></div>';


问:
Getting PDF TextObjects with PDFBox
I have a PDF from which I extracted a page using PDFBox:

```<code>(...)
File input = new File("C:\\temp\\sample.pdf");
document = PDDocument.load(input);
List allPages = document.getDocumentCatalog().getAllPages();
PDPage page = (PDPage) allPages.get(2);
PDStream contents = page.getContents();
if (contents != null) {
System.out.println(contents.getInputStreamAsString());
(...)
</code>```

This gives the following result, which looks like something you'd expect, based on the PDF spec.

```<code>q
/GS0 gs
/Fm0 Do
Q
/Span <</Lang (en-US)/MCID 88 >>BDC
BT
/CS0 cs 0 0 0  scn
/GS1 gs
/T1_0 1 Tf
8.5 0 0 8.5 70.8661 576 Tm
(This page has been intentionally left blank.)Tj
ET
EMC
1 1 1  scn
/GS0 gs
22.677 761.102 28.346 32.599 re
f
/Span <</Lang (en-US)/MCID 89 >>BDC
BT
0.531 0.53 0.528  scn
/T1_1 1 Tf
9 0 0 9 45.7136 761.1024 Tm
(2)Tj
ET
EMC
q
0 g
/Fm1 Do
Q
</code>```

What I'm looking for is to extract the PDF TextObjects (as described in par 5.3 of the PDF spec) on the page as java Objects, so basically the pieces between BT an ET (two of 'en on this page).
They should at least contain everything between the brackets preceding 'Tj' as a String, and an x and y coördinate based on the 'Tm' (or a 'Td' operator, etc.). Other attributes would be a bonus, but are not required.

The PDFTextStripper seems to give me either each character with attributes as a TextPosition (too much noise for my purpose), or all the Text as one long String.

Does PDFBox have a feature that parses a Page and provides TextObjects like this that I missed? Or else, if I am to extend PDFBox to get what I need, where should I start? Any help is welcome.

EDIT: Found another question here, that gives inspiration on how I might build what I need. If I succeed, I'll check back. Still looking forward to any help you may have, though.

Thanks,

Phil

答:
I added a version of the Phil response with pdfbox-2.0.1 </p>

```<code>import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.pdfparser.PDFStreamParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.cos.COSFloat;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSString;

public class TextExtractor {
  public static void main(String[] args) {
    try {
      File input = new File("src\\test\\resources\\files\\file1.pdf");
      PDDocument document = PDDocument.load(input);
      PDPageTree allPages = document.getDocumentCatalog().getPages();
      // just parsing page 2 here, as it's only a sample
      PDPage page = allPages.get(0);
      PDFStreamParser parser = new PDFStreamParser(page);
      parser.parse();
      List tokens = parser.getTokens();
      boolean parsingTextObject = false; // boolean to check whether the token
                                         // being parsed is part of a TextObject
      PDFTextObject textobj = new PDFTextObject();
      for (int i = 0; i < tokens.size(); i++) {
        Object next = tokens.get(i);
        if (next instanceof Operator) {
          Operator op = (Operator) next;
          switch (op.getName()) {
          case "BT":
            // BT: Begin Text.
            parsingTextObject = true;
            textobj = new PDFTextObject();
            break;
          case "ET":
            parsingTextObject = false;
            System.out.println("Text: " + textobj.getText() + "@" + textobj.getX() + "," + textobj.getY());
            break;
          case "Tj":
            textobj.setText();
            break;
          case "Tm":
            textobj.setMatrix();
            break;
          default:
            System.out.println("unsupported operation " + op);
          }
          textobj.clearAllAttributes();
        } else if (parsingTextObject) {
          textobj.addAttribute(next);
        } else {
          System.out.println("ignore "+next.getClass()+" -> "+next);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  static class PDFTextObject{
      private List attributes = new ArrayList<Object>();
      private String text = "";
      private float x = -1;
      private float y = -1;

      public void clearAllAttributes(){
          attributes = new ArrayList<Object>();
      }

      public void addAttribute(Object anAttribute){
          attributes.add(anAttribute);
      }

      public void setText(){
          //Move the contents of the attributes to the text attribute.
          for (int i = 0; i < attributes.size(); i++){
              if (attributes.get(i) instanceof COSString){
                  COSString aString = (COSString) attributes.get(i);
                  text = text + aString.getString();
              }
              else {
                  System.out.println("Whoops! Wrong type of property...");
              }
          }
      }

      public String getText(){
          return text;
      }

      public void setMatrix(){
          //Move the contents of the attributes to the x and y attributes.
          //A Matrix has 6 attributes, the last two of which are x and y
          for (int i = 4; i < attributes.size(); i++){
              float curval = -1;
              if (attributes.get(i) instanceof COSInteger){
                  COSInteger aCOSInteger = (COSInteger) attributes.get(i);
                  curval = aCOSInteger.floatValue();

              }
              if (attributes.get(i) instanceof COSFloat){
                  COSFloat aCOSFloat = (COSFloat) attributes.get(i);
                  curval = aCOSFloat.floatValue();
              }
              switch(i) {
                  case 4:
                      x = curval;
                      break;
                  case 5:
                      y = curval;
                      break;
              }
          }
      }

      public float getX(){
          return x;
      }

      public float getY(){
          return y;
      }
  }
}
</code>```

Title: Getting PDF TextObjects with PDFBox

Body:
I have a PDF from which I extracted a page using PDFBox:

(...)
File input = new File("C:\\temp\\sample.pdf");
document = PDDocument.load(input);
List allPages = document.getDocumentCatalog().getAllPages();
PDPage page = (PDPage) allPages.get(2);
PDStream contents = page.getContents();
if (contents != null) {
System.out.println(contents.getInputStreamAsString());
(...)

This gives the following result, which looks like something you'd expect, based on the PDF spec.

q
/GS0 gs
/Fm0 Do
Q
/Span <</Lang (en-US)/MCID 88 >>BDC
BT
/CS0 cs 0 0 0  scn
/GS1 gs
/T1_0 1 Tf
8.5 0 0 8.5 70.8661 576 Tm
(This page has been intentionally left blank.)Tj
ET
EMC
1 1 1  scn
/GS0 gs
22.677 761.102 28.346 32.599 re
f
/Span <</Lang (en-US)/MCID 89 >>BDC
BT
0.531 0.53 0.528  scn
/T1_1 1 Tf
9 0 0 9 45.7136 761.1024 Tm
(2)Tj
ET
EMC
q
0 g
/Fm1 Do
Q

What I'm looking for is to extract the PDF TextObjects (as described in par 5.3 of the PDF spec) on the page as java Objects, so basically the pieces between BT an ET (two of 'en on this page).
They should at least contain everything between the brackets preceding 'Tj' as a String, and an x and y coördinate based on the 'Tm' (or a 'Td' operator, etc.). Other attributes would be a bonus, but are not required.

The PDFTextStripper seems to give me either each character with attributes as a TextPosition (too much noise for my purpose), or all the Text as one long String.

Does PDFBox have a feature that parses a Page and provides TextObjects like this that I missed? Or else, if I am to extend PDFBox to get what I need, where should I start? Any help is welcome.

EDIT: Found another question here, that gives inspiration on how I might build what I need. If I succeed, I'll check back. Still looking forward to any help you may have, though.

Thanks,

Phil

Body:
I added a version of the Phil response with pdfbox-2.0.1

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.pdfparser.PDFStreamParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.cos.COSFloat;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSString;

public class TextExtractor {
  public static void main(String[] args) {
    try {
      File input = new File("src\\test\\resources\\files\\file1.pdf");
      PDDocument document = PDDocument.load(input);
      PDPageTree allPages = document.getDocumentCatalog().getPages();
      // just parsing page 2 here, as it's only a sample
      PDPage page = allPages.get(0);
      PDFStreamParser parser = new PDFStreamParser(page);
      parser.parse();
      List tokens = parser.getTokens();
      boolean parsingTextObject = false; // boolean to check whether the token
                                         // being parsed is part of a TextObject
      PDFTextObject textobj = new PDFTextObject();
      for (int i = 0; i < tokens.size(); i++) {
        Object next = tokens.get(i);
        if (next instanceof Operator) {
          Operator op = (Operator) next;
          switch (op.getName()) {
          case "BT":
            // BT: Begin Text.
            parsingTextObject = true;
            textobj = new PDFTextObject();
            break;
          case "ET":
            parsingTextObject = false;
            System.out.println("Text: " + textobj.getText() + "@" + textobj.getX() + "," + textobj.getY());
            break;
          case "Tj":
            textobj.setText();
            break;
          case "Tm":
            textobj.setMatrix();
            break;
          default:
            System.out.println("unsupported operation " + op);
          }
          textobj.clearAllAttributes();
        } else if (parsingTextObject) {
          textobj.addAttribute(next);
        } else {
          System.out.println("ignore "+next.getClass()+" -> "+next);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  static class PDFTextObject{
      private List attributes = new ArrayList<Object>();
      private String text = "";
      private float x = -1;
      private float y = -1;

      public void clearAllAttributes(){
          attributes = new ArrayList<Object>();
      }

      public void addAttribute(Object anAttribute){
          attributes.add(anAttribute);
      }

      public void setText(){
          //Move the contents of the attributes to the text attribute.
          for (int i = 0; i < attributes.size(); i++){
              if (attributes.get(i) instanceof COSString){
                  COSString aString = (COSString) attributes.get(i);
                  text = text + aString.getString();
              }
              else {
                  System.out.println("Whoops! Wrong type of property...");
              }
          }
      }

      public String getText(){
          return text;
      }

      public void setMatrix(){
          //Move the contents of the attributes to the x and y attributes.
          //A Matrix has 6 attributes, the last two of which are x and y
          for (int i = 4; i < attributes.size(); i++){
              float curval = -1;
              if (attributes.get(i) instanceof COSInteger){
                  COSInteger aCOSInteger = (COSInteger) attributes.get(i);
                  curval = aCOSInteger.floatValue();

              }
              if (attributes.get(i) instanceof COSFloat){
                  COSFloat aCOSFloat = (COSFloat) attributes.get(i);
                  curval = aCOSFloat.floatValue();
              }
              switch(i) {
                  case 4:
                      x = curval;
                      break;
                  case 5:
                      y = curval;
                      break;
              }
          }
      }

      public float getX(){
          return x;
      }

      public float getY(){
          return y;
      }
  }
}


问:
Filter to Month-Day Interval
I have a data frame with daily observations across years. I would like to filter to a range, such as "March 10 to May 12" every year. Perhaps it's my poor googling skills, but I couldn't find some sort of month-day construction.

Here's a sample df:

```<code>set.seed(123)

dates <- seq.Date(from=as.Date("1970-01-01"), to=as.Date("2007-08-31"), by="days")

sample.df <- data.frame(date=dates,
                        data=rnorm(length(dates)))
</code>```

Another addition to complicate is to keep a range that crosses over years, such as "December 10 to February 2." It can be assumed all needed dates are contained within the dataframe, but might need to make some NA such as when the dataframe goes to 2007, so we cannot do December 10, 2007 to February 2, 2008.

答:
This works for any number of years and for arbitrarily complex logical conditions. No packages are used.</p>

```<code>monthday <- format(sample.df$date, "%m%d")

sample.df[ monthday >= "0310" & monthday <= "0512", ]   # mar 10 - may 12

sample.df[ monthday <= "0202" | monthday >= "1210", ]   # dec 10 - feb 02

sample.df[ monthday <= "0202" |
           (monthday >= "0310" & monthday <= "0512") |
           monthday >= "1210", ]   # both
</code>```

Title: Filter to Month-Day Interval

Body:
I have a data frame with daily observations across years. I would like to filter to a range, such as "March 10 to May 12" every year. Perhaps it's my poor googling skills, but I couldn't find some sort of month-day construction.

Here's a sample df:

set.seed(123)

dates <- seq.Date(from=as.Date("1970-01-01"), to=as.Date("2007-08-31"), by="days")

sample.df <- data.frame(date=dates,
                        data=rnorm(length(dates)))

Another addition to complicate is to keep a range that crosses over years, such as "December 10 to February 2." It can be assumed all needed dates are contained within the dataframe, but might need to make some NA such as when the dataframe goes to 2007, so we cannot do December 10, 2007 to February 2, 2008.

Body:
This works for any number of years and for arbitrarily complex logical conditions. No packages are used.

monthday <- format(sample.df$date, "%m%d")

sample.df[ monthday >= "0310" & monthday <= "0512", ]   # mar 10 - may 12

sample.df[ monthday <= "0202" | monthday >= "1210", ]   # dec 10 - feb 02

sample.df[ monthday <= "0202" |
           (monthday >= "0310" & monthday <= "0512") |
           monthday >= "1210", ]   # both


问:
Reduce the amount of decimals positions using bash printf without rounding
I am using printf to restrict the amount of decimal places of a number to 3 decimal places

```<code>printf "%.3f\n" 8.577772
8.578
</code>```

I want to truncate this number to 3 decimal places WITHOUT rounding up so that it prints as 8.577.

Solutions with printf are preferred.

答:
Assuming this is a variable, which can have any number of places before the decimal:</p>

```<code>$ var=8.577772
$ printf "%s.%.3s\n" $( echo $var | tr '.' ' ' )
8.577

$ var=134.56789
$ printf "%s.%.3s\n" $( echo $var | tr '.' ' ' )
134.567
</code>```

Body:
I am using printf to restrict the amount of decimal places of a number to 3 decimal places

printf "%.3f\n" 8.577772
8.578

I want to truncate this number to 3 decimal places WITHOUT rounding up so that it prints as 8.577.

Solutions with printf are preferred.

Body:
Assuming this is a variable, which can have any number of places before the decimal:

$ var=8.577772
$ printf "%s.%.3s\n" $( echo $var | tr '.' ' ' )
8.577

$ var=134.56789
$ printf "%s.%.3s\n" $( echo $var | tr '.' ' ' )
134.567


问:
Why is using refs slowing down my React application?
I need a few refs of elements to be stored in Redux so that the elements can be focused on.

I have this dropdown:

```<code>            <BasicSelect
                selectRef={(e) => this.storeRef('make', e) } ... />
</code>```

And here is storeRef:

```<code>storeRef(list, ref)
{
    if(this.state.refsStored[list]) {
        return;
    } else {
        this.props.storeSelectRef(list, ref);
        var refState = Object.assign({}, this.state.refsStored);
        refState[list] = true;
        this.setState({refsStored: refState});
    }
}
</code>```

From this, it should store the ref once, then simply return after comparing.

However, every time a option in the dropdown of  <BasicSelect> is clicked on, the application hangs for a <1s (noticable), and then continues on.

If I change storeRef to the following (obviously the intended result doesn't work):

```<code>storeRef(list, ref) {
    return;
}
</code>```

The dropdown selection is super fast, and all is good. So how come this comparison if(this.state.refsStored[list]) is significantly slow?

答:
Don't put refs into component state.  Component state should only be used for things that you will need when rendering, and should cause a re-render when you update them.  Save refs directly onto the component instance:

```<code><BasicSelect selectRef={selectInstance => this.selectInstance = selectInstance} />
</code>```

I'm also kind of confused what selectRef is as a prop, to be honest, but I assume that the <BasicSelect> component forwards that ref on to an underlying <select>tag?

Anyway, the key point is that you are causing unnecessary re-renders every time because you're calling setState().  Don't do that.

Body:
I need a few refs of elements to be stored in Redux so that the elements can be focused on.

I have this dropdown:

            <BasicSelect
                selectRef={(e) => this.storeRef('make', e) } ... />

And here is storeRef:

storeRef(list, ref)
{
    if(this.state.refsStored[list]) {
        return;
    } else {
        this.props.storeSelectRef(list, ref);
        var refState = Object.assign({}, this.state.refsStored);
        refState[list] = true;
        this.setState({refsStored: refState});
    }
}

From this, it should store the ref once, then simply return after comparing.

However, every time a option in the dropdown of  <BasicSelect> is clicked on, the application hangs for a <1s (noticable), and then continues on.

If I change storeRef to the following (obviously the intended result doesn't work):

storeRef(list, ref) {
    return;
}

The dropdown selection is super fast, and all is good. So how come this comparison if(this.state.refsStored[list]) is significantly slow?

Body:
Don't put refs into component state.  Component state should only be used for things that you will need when rendering, and should cause a re-render when you update them.  Save refs directly onto the component instance:

<BasicSelect selectRef={selectInstance => this.selectInstance = selectInstance} />

I'm also kind of confused what selectRef is as a prop, to be honest, but I assume that the <BasicSelect> component forwards that ref on to an underlying <select>tag?

Anyway, the key point is that you are causing unnecessary re-renders every time because you're calling setState().  Don't do that.


问:
javascript array - separate values and values of values by single quotes
I have an array that looks like this:

```<code>var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
</code>```

I want to return the results like this:

```<code>'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'
</code>```

This is what I have done so far:

```<code>includes = tagsI.map(tag => `'${tag}'`).join(',')
</code>```

But this only separates by commas and single quotes the values.. not the values of the values as well.

How can I do this?

Thank you

答:
How about using reduce :

    var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];

        //V1 : compatible with all browsers
    var result = array.reduce((acc, elem, index, arr)=>{
      var n_arr = elem.split(",").map(map_elem=> `'${map_elem}'`);
      n_arr.forEach(fe_elem => acc.push(fe_elem));
      return acc;
    }, []).join(",");

    console.log(result);
    document.querySelector("#res1").innerHTML = result;

        //V2: compatible with some browsers
    var result2 = array.reduce((acc, elem, index, arr)=>{
      var n_arr = elem.split(",").map(map_elem=>`'${map_elem}'`);
      acc.push(...n_arr);
      return acc;
    }, []).join(",");

    console.log(result2)
    document.querySelector("#res2").innerHTML = result2;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <p id="res1"></p>

  <p id="res2"></p>

</body></code>```

The principle is the following :

We have an initial Array "array" in which we stored strings (["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"])

For each string in the array:

We split in an array the said string by ","

We surround each element of this array by quotes

We add each of these elements to the array that will be used as the result variable

We created a string joining by ","

PS: If you want an array instead of a string, just remove the join(",")

Body:
I have an array that looks like this:

var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]

I want to return the results like this:

'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'

This is what I have done so far:

includes = tagsI.map(tag => `'${tag}'`).join(',')

But this only separates by commas and single quotes the values.. not the values of the values as well.

How can I do this?

Thank you

Body:
How about using reduce :

    var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];

        //V1 : compatible with all browsers
    var result = array.reduce((acc, elem, index, arr)=>{
      var n_arr = elem.split(",").map(map_elem=> `'${map_elem}'`);
      n_arr.forEach(fe_elem => acc.push(fe_elem));
      return acc;
    }, []).join(",");

    console.log(result);
    document.querySelector("#res1").innerHTML = result;

        //V2: compatible with some browsers
    var result2 = array.reduce((acc, elem, index, arr)=>{
      var n_arr = elem.split(",").map(map_elem=>`'${map_elem}'`);
      acc.push(...n_arr);
      return acc;
    }, []).join(",");

    console.log(result2)
    document.querySelector("#res2").innerHTML = result2;

<body>

  <p id="res1"></p>

  <p id="res2"></p>

</body>

The principle is the following :

We have an initial Array "array" in which we stored strings (["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"])

For each string in the array:

We split in an array the said string by ","

We surround each element of this array by quotes

We add each of these elements to the array that will be used as the result variable

We created a string joining by ","

PS: If you want an array instead of a string, just remove the join(",")


问:
Block focus/select in a ReadOnly textbox
Someone knows how to block the focus/select in a read-only textbox (ReadOnly = true), without using enabled = false?

Thanks!

答:
I'm not sure I understand fully why you would want that. A read only text box allows selection to allow users to copy the text in there for other purposes. What I assume from your question is that you don't want the TextBox to accept input focus when a user is tabbing through controls, which I've seen to be a more common requirement.

You can achieve this via code:

```<code>TextBox1.TabStop = False
</code>```

to ensure that tab doesn't direct focus to the readonly textbox. You can also achieve this in the designer using the same property as the screenshot shows.

Body:
I'm not sure I understand fully why you would want that. A read only text box allows selection to allow users to copy the text in there for other purposes. What I assume from your question is that you don't want the TextBox to accept input focus when a user is tabbing through controls, which I've seen to be a more common requirement.

You can achieve this via code:

TextBox1.TabStop = False

to ensure that tab doesn't direct focus to the readonly textbox. You can also achieve this in the designer using the same property as the screenshot shows.


答:
I think it's impossible to restrict rounding because printf uses IEEE 754 for its inner representation.
Use regexp instead:</p>

```<code>echo "34234.23423423" | grep -oE '[0-9]*\.[0-9]{3}'
</code>```

Title: Reduce the amount of decimals positions using bash printf without rounding

Body:
I think it's impossible to restrict rounding because printf uses IEEE 754 for its inner representation.
Use regexp instead:

echo "34234.23423423" | grep -oE '[0-9]*\.[0-9]{3}'


问:
Including the CUB header triggers many Visual Studio Intellisense errors
Whenever i include <cub/cub.cuh> header file, visual studio's IntelliSense reports thousands of errors.

As you can see in the attached screenshot, application consists of empty main() function and a include line.

I have defined additional include directories and additional library directories in project properties. I have not made any other changes.

My setup consist of visual studio community 2015, cuda 8.0.61 and cub 1.7.0 library.

Is there anything I can do to fix this error?

答:
I would like to thank Robert Crovella for pointing me in the right direction.

Permanent solution:

```<code>#ifndef __INTELLISENSE__

#include <cub/cub.cuh>

// And other troublesome libraries or code-blocks....

#endif
</code>```

The Visual Studio's __INTELLISENSE__ macro is only defined when Visual Studio itself parses the file, not during compilation. Therefore anything inside a code block above will not be checked by IntelliSense algorithms.

Workaround: (my 1st attempt to fix this problem, can be ignored).

Step #1:

In the Visual Studio's Error List window change option Build + IntelliSense to Build Only

Step #2

In visual Studio go to: Tools > Options > Text Editor > C/C++ > Advanced and change Disable Error Reporting from False to True

Explanation:

This will turn off IntelliSense error check functionality, and by extension will solve my problem. This partial solution will force me to rely only on compiler (build) output, but that is not an issue.

Like I said, this solution is more like a workaround around <s>without any serious or critical penalty</s> in IntelliSense functionality, NOT a permanent fix. <s>But it works fine</s>.

Disadvantages:

in my current project, there are functions that are cub wrappers, those functions sometimes are not detected by an autocomplete.

Also if the total error count reaches IntelliSense limit, IntelliSense will stop working. (edit: "without any serious or critical penalty" went straight out of the window...).

Body:
I would like to thank Robert Crovella for pointing me in the right direction.

Permanent solution:

#ifndef __INTELLISENSE__

#include <cub/cub.cuh>

// And other troublesome libraries or code-blocks....

#endif

The Visual Studio's __INTELLISENSE__ macro is only defined when Visual Studio itself parses the file, not during compilation. Therefore anything inside a code block above will not be checked by IntelliSense algorithms.

Workaround: (my 1st attempt to fix this problem, can be ignored).

Step #1:

In the Visual Studio's Error List window change option Build + IntelliSense to Build Only

Step #2

In visual Studio go to: Tools > Options > Text Editor > C/C++ > Advanced and change Disable Error Reporting from False to True

Explanation:

This will turn off IntelliSense error check functionality, and by extension will solve my problem. This partial solution will force me to rely only on compiler (build) output, but that is not an issue.

Like I said, this solution is more like a workaround around <s>without any serious or critical penalty</s> in IntelliSense functionality, NOT a permanent fix. <s>But it works fine</s>.

Disadvantages:

in my current project, there are functions that are cub wrappers, those functions sometimes are not detected by an autocomplete.

Also if the total error count reaches IntelliSense limit, IntelliSense will stop working. (edit: "without any serious or critical penalty" went straight out of the window...).


问:
Symfony: Add Column to Doctrine Entity
I'm trying to learn the basics of Symfony, and have come across a problem that baffles me.

I'm trying to write Data to a SQL Table, following (mostly) the instructions from the documentation ( http://symfony.com/doc/current/book/doctrine.html ). I created an entity via

```<code>$ php bin/console doctrine:generate:entity
</code>```

and it is mapped to my DB Table correctly, I can read and write, no problem. After that I added a column to my table and the corresponding lines to my Entity:

```<code>/**
 *  @var string
 *
 *  @ORM\Column(name="User_Credentials", type="text")
 */
private $userCredentials;
</code>```

Then I tried creating the setters and getters, but no changes were made, just a backup of my Entity. So I added getter and setter myself, but when attempting to write to the DB the corresponding column is ommited, remaining empty. No errors are given. I checked and re-checked for typos or other sytax errors, but could not find any. When doing

```<code>$ php bin/console doctrine:schema:update --dump-sql
</code>```

I get

```<code>ALTER TABLE st_users DROP User_Credentials;
</code>```

So it seems my Column is completely ignored. I cleared the cache repatedly, which changed nothing. I am, obviously, lost. Any hint as to the right path will be appreciated.

Thank you.

答:
I added a column to my table and the corresponding lines to my Entity

The concept of Symfony is to add column only to entity, but not to table itself.

Then, when you execute

```<code>php bin/console doctrine:schema:update --force
</code>```

Symfony would detect that you have a new column and it will add column to the table automatically.

PS. Regarding clearing a cache. In case apc cache is enabled in Symfony - you also need to restart Apache or php-fpm process. Otherwise it will ignore new annotations.

Title: Symfony: Add Column to Doctrine Entity

Body:
I'm trying to learn the basics of Symfony, and have come across a problem that baffles me.

I'm trying to write Data to a SQL Table, following (mostly) the instructions from the documentation ( http://symfony.com/doc/current/book/doctrine.html ). I created an entity via

$ php bin/console doctrine:generate:entity

and it is mapped to my DB Table correctly, I can read and write, no problem. After that I added a column to my table and the corresponding lines to my Entity:

/**
 *  @var string
 *
 *  @ORM\Column(name="User_Credentials", type="text")
 */
private $userCredentials;

Then I tried creating the setters and getters, but no changes were made, just a backup of my Entity. So I added getter and setter myself, but when attempting to write to the DB the corresponding column is ommited, remaining empty. No errors are given. I checked and re-checked for typos or other sytax errors, but could not find any. When doing

$ php bin/console doctrine:schema:update --dump-sql

I get

ALTER TABLE st_users DROP User_Credentials;

So it seems my Column is completely ignored. I cleared the cache repatedly, which changed nothing. I am, obviously, lost. Any hint as to the right path will be appreciated.

Thank you.

Body:
I added a column to my table and the corresponding lines to my Entity

The concept of Symfony is to add column only to entity, but not to table itself.

Then, when you execute

php bin/console doctrine:schema:update --force

Symfony would detect that you have a new column and it will add column to the table automatically.

PS. Regarding clearing a cache. In case apc cache is enabled in Symfony - you also need to restart Apache or php-fpm process. Otherwise it will ignore new annotations.


问:
CSScript: Inject System.linq inside "CreateFunc"
This code:

```<code> func = CSScript.CreateFunc<int>(@"int f(int[] inputs) { return inputs.Max(); }");

 int max = func(new int[]{ 235,123,675,111 });
</code>```

is throwing:

error CS1061: 'System.Array' does not contain a definition for 'Max' and no extension method 'Max' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

I need to inject System.Linq inside my function "func"

....How can I do that?

答:
This is from the CS-Script Documentation:

Hints And Tips

When you need to reference many assemblies (and particularly when these assemblies are commonly used) it is convenient to combine all //css_reference statements into single file containing no code and include this file into your primary script.

The following code includes linq.includes.cs file containing references to all assemblies required for programming against LINQ:

```<code>//css_include linq.includes.cs;
using System;

class Test
{
    static public void Main( string [] args)
    {
        ....
</code>```

This is the content of the linq.includes.cs file:

```<code>//css_ref System.Core;
//css_ref System.Data.ComponentModel;
//css_ref System.Data.DataSetExtensions;
//css_ref System.Xml;
//css_ref System.Xml.Linq;
</code>```

Body:
This code:

 func = CSScript.CreateFunc<int>(@"int f(int[] inputs) { return inputs.Max(); }");

 int max = func(new int[]{ 235,123,675,111 });

is throwing:

error CS1061: 'System.Array' does not contain a definition for 'Max' and no extension method 'Max' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

I need to inject System.Linq inside my function "func"

....How can I do that?

Body:
This is from the CS-Script Documentation:

Hints And Tips

When you need to reference many assemblies (and particularly when these assemblies are commonly used) it is convenient to combine all //css_reference statements into single file containing no code and include this file into your primary script.

The following code includes linq.includes.cs file containing references to all assemblies required for programming against LINQ:

//css_include linq.includes.cs;
using System;

class Test
{
    static public void Main( string [] args)
    {
        ....

This is the content of the linq.includes.cs file:

//css_ref System.Core;
//css_ref System.Data.ComponentModel;
//css_ref System.Data.DataSetExtensions;
//css_ref System.Xml;
//css_ref System.Xml.Linq;


问:
HTTP authentication logout via PHP
What is the correct way to log out of HTTP authentication protected folder?

There are workarounds that can achieve this, but they are potentially dangerous because they can be buggy or don't work in certain situations / browsers. That is why I am looking for correct and clean solution.

答:
Mu. No correct way exists, not even one that's consistent across browsers.

This is a problem that comes from the HTTP specification (section 15.6):

Existing HTTP clients and user agents typically retain authentication
    information indefinitely. HTTP/1.1. does not provide a method for a
    server to direct clients to discard these cached credentials.

On the other hand, section 10.4.2 says:

If the request already included Authorization credentials, then the 401
   response indicates that authorization has been refused for those
   credentials. If the 401 response contains the same challenge as the
   prior response, and the user agent has already attempted
   authentication at least once, then the user SHOULD be presented the
   entity that was given in the response, since that entity might
   include relevant diagnostic information.

In other words, you may be able to show the login box again (as @Karsten says), but the browser doesn't have to honor your request - so don't depend on this (mis)feature too much.

OwnerDisplayName: JS

ContentLicense: CC BY-SA 2.5

Title: HTTP authentication logout via PHP

LastEditorDisplayName: JS

OwnerDisplayName: Piskvor

LastEditorDisplayName: Piskvor


问:
C++ custom exception message not displaying
I am trying to create a custom exception class, throw it, and display the error message, but I am doing something wrong, causing the exception to not get thrown and the message to not get printed.

Here's the exception class:

```<code>class UnbalancedParenthesesException : public std::exception {
  int line_number {0};
public:
  UnbalancedParenthesesException(int line_number) :
    line_number { line_number }
    {}

  virtual const char* what() const throw() {
    std::string exception_message =
      "Papentheses imbalance at line " + std::to_string(line_number) + "\n";

    return exception_message.c_str();
  }
};
</code>```

I am trying totry/throw/catch as follows:

```<code>void handle_closed_paren(int line_number) {
  try {
    if (definitely_unbalanced()) {
      throw UnbalancedParenthesesException(line_number);
    }
  } catch (const UnbalancedParenthesesException& e) {
      std::out << e.what() << "\n";
}
</code>```

There is nothing pertinent to this error in the console.

Thanks in advance.

答:
Your what() method is creating a local std::string variable and then returning a pointer to its internal data, which will be left dangling when the std::string goes out of scope and is destroyed when what() exits.

You need to store your error message in a std::string that is a member of the class so it does not go out of scope prematurely. Fortunately, std::exception already has an internal std::string for that purpose.  So, instead of formatting the error message in what() itself, you should format it in your derived constructor and pass it to the base class constructor, letting the base what() method return it as-is:

```<code>class UnbalancedParenthesesException : public std::exception
{
    int mLineNumber;
public:
    UnbalancedParenthesesException(int line_number) : std::exception("Parentheses imbalance at line " + std::to_string(line_number)), mLineNumber(line_number) {}

    // optional, if the catcher needs access to the value
    int lineNumber() const { return mLineNumber; }
};
</code>```

Body:
I am trying to create a custom exception class, throw it, and display the error message, but I am doing something wrong, causing the exception to not get thrown and the message to not get printed.

Here's the exception class:

class UnbalancedParenthesesException : public std::exception {
  int line_number {0};
public:
  UnbalancedParenthesesException(int line_number) :
    line_number { line_number }
    {}

  virtual const char* what() const throw() {
    std::string exception_message =
      "Papentheses imbalance at line " + std::to_string(line_number) + "\n";

    return exception_message.c_str();
  }
};

I am trying totry/throw/catch as follows:

void handle_closed_paren(int line_number) {
  try {
    if (definitely_unbalanced()) {
      throw UnbalancedParenthesesException(line_number);
    }
  } catch (const UnbalancedParenthesesException& e) {
      std::out << e.what() << "\n";
}

There is nothing pertinent to this error in the console.

Thanks in advance.

Body:
Your what() method is creating a local std::string variable and then returning a pointer to its internal data, which will be left dangling when the std::string goes out of scope and is destroyed when what() exits.

You need to store your error message in a std::string that is a member of the class so it does not go out of scope prematurely. Fortunately, std::exception already has an internal std::string for that purpose.  So, instead of formatting the error message in what() itself, you should format it in your derived constructor and pass it to the base class constructor, letting the base what() method return it as-is:

class UnbalancedParenthesesException : public std::exception
{
    int mLineNumber;
public:
    UnbalancedParenthesesException(int line_number) : std::exception("Parentheses imbalance at line " + std::to_string(line_number)), mLineNumber(line_number) {}

    // optional, if the catcher needs access to the value
    int lineNumber() const { return mLineNumber; }
};


问:
How to detect no voice from user and run the next audio file in Html5 and Javascript
I'm trying to make my little project like AI, what I mean is I have a some audio files as an array. And I use annyang API as a voice command to start running the program. After the first audio file is done playing. The program pauses. And I will say some sentenses until the program detects no voice from me for 3 seconds(or even longer). It will play the second audio file and then pause again. This program will loop until all audio files have played. Is there anyway to do this?

Here is my code so far.

```<code>    <script>
        if (annyang)
        {

            var commands = {

            '1': function()
            {
                var playList = ["1_hello", "2_how_old", "3_what_did_you_make"]

                var dir = "sound/";
                var extention = ".wav";
                var index = 1;
                var count = 4;

                var agent = navigator.userAgent.toLowerCase();

                if(agent.indexOf('firefox') != -1 || agent.indexOf('opera') != -1)
                    {
                        extention = ".wav";
                    }

                audio = new Audio();

                audio.src = dir + playList[0] + extention;
                audio.load();
                setTimeout(function(){audio.play();}, 1000);

                audio.onended = function()
                {
                    if(index < playList.length)
                    {
                            audio.src = dir + playList[index] + extention;
                            audio.load();
                            setTimeout(function(){audio.play();}, 1000);
                            index++;

                    }
                }

                audio.loop = false;
            }
        };

        annyang.debug(true);

        annyang.addCommands(commands);

        }

    </script>
</code>```

I have found a visualizing sound that might do it, but I'm not sure how.

I have been struggling with this for a week. And Can't really find solutions for this. I'm open to jQuery as well. Thank you in advance.

答:
You can use annyang.addCallback and annyang.addRemoveback to add or remove callbacks for events annyang fires.

According to the API documentation the event we are probably intested in is soundstart https://github.com/TalAter/annyang/blob/master/docs/README.md

soundstart - Fired as soon as any sound (possibly speech) has been
  detected. This will fire once per Speech Recognition starting.

We can add or remove call backs to fire when this event is fired.

When can track when these events were fired and execute logic to play a song if more than 3 seconds has elapsed.

Here is some baseline psuedo code. I don't have a microphone so I can test.

```<code>var monitorId=0;
function monitorSound()
{
    if(monitorId&& monitorId>0) return;
    monitorId=window.setInterval(trackSound,1000);
}
var lastSound= new Date();
function trackSound() {
    var now = new Date();
    if (now-lastSound)>3000)
    {
        stopListening();
        playNextAudio();
        return;
    }
}

function startListening() {
    annyang.addCallback('startsound', onSoundHeard);
}
function stopListening()
{
    // stop the loop tracking when the last sound was heard.
    window.clearInterval(monitorId);
    monitorId=0;
    // Remove onSoundHeard from being called on start:
    annyang.removeCallback('startsound', onSoundHeard);
}

var playList = ['mydir/mysong1.wav','mydir/mysong2.wav','mydir/mysong2.wav'];
var audioIndex=0;
function playNextAudio(){
    if(index==playList.length-1) return; -- we have played all audio
    // play the next audio
    audio = new Audio();
    audio.src = playList[index++];
    audio.load();
    setTimeout(function(){audio.play();}, 1000);

    audio.onended = startListening

}
function onSoundHeard() {
    lastSound= new Date();
}
</code>```

Body:
I'm trying to make my little project like AI, what I mean is I have a some audio files as an array. And I use annyang API as a voice command to start running the program. After the first audio file is done playing. The program pauses. And I will say some sentenses until the program detects no voice from me for 3 seconds(or even longer). It will play the second audio file and then pause again. This program will loop until all audio files have played. Is there anyway to do this?

Here is my code so far.

I have found a visualizing sound that might do it, but I'm not sure how.

I have been struggling with this for a week. And Can't really find solutions for this. I'm open to jQuery as well. Thank you in advance.

Body:
You can use annyang.addCallback and annyang.addRemoveback to add or remove callbacks for events annyang fires.

According to the API documentation the event we are probably intested in is soundstart https://github.com/TalAter/annyang/blob/master/docs/README.md

soundstart - Fired as soon as any sound (possibly speech) has been
  detected. This will fire once per Speech Recognition starting.

We can add or remove call backs to fire when this event is fired.

When can track when these events were fired and execute logic to play a song if more than 3 seconds has elapsed.

Here is some baseline psuedo code. I don't have a microphone so I can test.

var monitorId=0;
function monitorSound()
{
    if(monitorId&& monitorId>0) return;
    monitorId=window.setInterval(trackSound,1000);
}
var lastSound= new Date();
function trackSound() {
    var now = new Date();
    if (now-lastSound)>3000)
    {
        stopListening();
        playNextAudio();
        return;
    }
}

function startListening() {
    annyang.addCallback('startsound', onSoundHeard);
}
function stopListening()
{
    // stop the loop tracking when the last sound was heard.
    window.clearInterval(monitorId);
    monitorId=0;
    // Remove onSoundHeard from being called on start:
    annyang.removeCallback('startsound', onSoundHeard);
}

var playList = ['mydir/mysong1.wav','mydir/mysong2.wav','mydir/mysong2.wav'];
var audioIndex=0;
function playNextAudio(){
    if(index==playList.length-1) return; -- we have played all audio
    // play the next audio
    audio = new Audio();
    audio.src = playList[index++];
    audio.load();
    setTimeout(function(){audio.play();}, 1000);

    audio.onended = startListening

}
function onSoundHeard() {
    lastSound= new Date();
}


问:
MySQL LIKE, effect of extra wildcards on performance
Say I have a set of database rows containing data like:

Blah1-Blah2-Blah3

Blah1-Blah3-Blah2

Would a LIKE query using "Blah1-%" be faster/slower than a query using "Blah1-%-%". Obviously in my example they will retrieve both rows, but hopefully you get where I'm coming from; is it better to include all the information you have in regards to what the string contains to the query, or omit information if you can.

My thinking is more information in the query could lead to an index being better utilised, or because its a more complex query it would actually slow it down. I've got a decent amount of experience with databases but haven't got my head around what a key does on a technical level; this might be a stupid question to someone who knows!

答:
"Blah1-%-%" would not find "Blah1-foo", but the other one would.  That aside,...

The main time involved in a query is fetching the row, especially if it needs to be red from disk, and parsing it.  The cost of any expressions, include LIKE with an extra wildcard, are minor.

All the Optimizer does with LIKE is decide whether it starts with a wildcard (thereby not allowing an index) or not (thereby letting the Optimizer consider an index).


问:
css Ellipsis, event on 3 dots hovering
I have a little question, i have too long text in my cell in table in html, so i use text-overflow property set on ellipsis in css like in this example from w3c: https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_text-overflow
and I wonder if I can make for example that popup will show up after hover on that 3 dots on the end of text, is that possible without complicated js code? Or i have to make my own piece of code that will show 3 dots instead of rest of text and then attach on hover function to them or something ?</p>

答:
You can use title attribute of element to achieve your objective without writing any extra code. Just run following snippet and hover over the text to see the result.

.ellipses {
    white-space: nowrap;
    width: 12em;
    overflow: hidden;
    text-overflow: ellipsis;
    border: 1px solid #000000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="ellipses" title="This is some long text that will not fit in the box">This is some long text that will not fit in the box</div></code>```

Title: css Ellipsis, event on 3 dots hovering

Body:
You can use title attribute of element to achieve your objective without writing any extra code. Just run following snippet and hover over the text to see the result.

.ellipses {
    white-space: nowrap;
    width: 12em;
    overflow: hidden;
    text-overflow: ellipsis;
    border: 1px solid #000000;
}

<div class="ellipses" title="This is some long text that will not fit in the box">This is some long text that will not fit in the box</div>


问:
React: Click on a component to change parents state
Pretty new to React, can't quite figure out how to fix this.
I want to click on a component (Project) and have this change the state of the parent, determining what is then rendered.

App.js, in the App component, has

```<code>constructor(props){
  super(props);
  this.state = {
    load: ''
  }
}

handleClick(e){
  this.setState({load: e.target.value});
  console.log("Clicked!");
  console.log(e);
  console.log(e.target.value);
}

display(load){
  if (load === 'bmi') {
    return <Bmi />
  }
  else return "";
}

render() {
    return (
      <div className="App">

      <div className="App-header">

        <h2>Projects</h2>

      </div>
      <div className="box">
        <Project projectName="BMI Calculator"
           projectDescription="A simple React program, using sliders to select weight and height to calculate BMI."
           imgAddress="https://cdn.vertex42.com/ExcelTemplates/Images/bmi-chart.gif"
           value="bmi"
           onClick={this.handleClick}/>

        <Project projectName="..."
           projectDescription="..."

        <Project projectName="Something Else"
           projectDescription="Describing that other thing that I did." />
      </div>
      <div className={this.state.item}>
        {this.display(this.state.item)}
      </div>

  </div>

);
}
</code>```

Project is called from Project.js, which has:

```<code>render(){
    return(
        <div className="third" value={this.props.value} onClick={this.props.onClick}>

            <h3>{this.props.projectName}</h3>

            <div className="container">

                <img src={this.props.imgAddress} className="image" />

                <div className="middle">

                    <div className="text">{this.props.projectDescription}</div>

                </div>

            </div>

        </div>
    )
}
</code>```

When I click on the first  the console shows:

```<code>clicked!
Proxy {dispatchConfig: Object, _targetInst: ReactDOMComponent, nativeEvent: MouseEvent, type: "click", target: img.image…}
undefined
</code>```

Because of the target: img.image shown in the console, I tried giving that element th same value, onClick properties as div.third, but that didn't work.
I then tried giving that to all the elements in the render of Project.js but that did not work either.

答:
You can pass the function as a prop from the parent to the child. Don't forget to use .bind(this), it was missing in your project... at the constructor level, or at component level with this.handleClick.bind(this). You can also use _handleClick instead of handleClick (does the same).

```<code>// PARENT
class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.state = { name: 'bob' }
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(e) {
    e.preventDefault()
    this.setState({
     name : 'anita'
    })
  }

  render() {
    return (
      <div>
      {this.state.name}
      <Child handleClick={this.handleClick} />
      </div>
    )
  }
}

// CHILD
class Child extends React.Component {
  render() {
    return <button onClick={this.props.handleClick} />
  }
}
</code>```

Body:
Pretty new to React, can't quite figure out how to fix this.
I want to click on a component (Project) and have this change the state of the parent, determining what is then rendered.

App.js, in the App component, has

constructor(props){
  super(props);
  this.state = {
    load: ''
  }
}

handleClick(e){
  this.setState({load: e.target.value});
  console.log("Clicked!");
  console.log(e);
  console.log(e.target.value);
}

display(load){
  if (load === 'bmi') {
    return <Bmi />
  }
  else return "";
}

render() {
    return (

Projects

        <Project projectName="BMI Calculator"
           projectDescription="A simple React program, using sliders to select weight and height to calculate BMI."
           imgAddress="https://cdn.vertex42.com/ExcelTemplates/Images/bmi-chart.gif"
           value="bmi"
           onClick={this.handleClick}/>

        <Project projectName="..."
           projectDescription="..."

        <Project projectName="Something Else"
           projectDescription="Describing that other thing that I did." />

        {this.display(this.state.item)}

);
}

Project is called from Project.js, which has:

render(){
    return(

{this.props.projectName}

{this.props.projectDescription}

    )
}

When I click on the first  the console shows:

clicked!
Proxy {dispatchConfig: Object, _targetInst: ReactDOMComponent, nativeEvent: MouseEvent, type: "click", target: img.image…}
undefined

Because of the target: img.image shown in the console, I tried giving that element th same value, onClick properties as div.third, but that didn't work.
I then tried giving that to all the elements in the render of Project.js but that did not work either.

Body:
You can pass the function as a prop from the parent to the child. Don't forget to use .bind(this), it was missing in your project... at the constructor level, or at component level with this.handleClick.bind(this). You can also use _handleClick instead of handleClick (does the same).

// PARENT
class Parent extends React.Component {
  constructor(props) {
    super(props)
    this.state = { name: 'bob' }
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(e) {
    e.preventDefault()
    this.setState({
     name : 'anita'
    })
  }

  render() {
    return (
      <div>
      {this.state.name}
      <Child handleClick={this.handleClick} />
      </div>
    )
  }
}

// CHILD
class Child extends React.Component {
  render() {
    return <button onClick={this.props.handleClick} />
  }
}


问:
How to do get request from website that is protected?
Site is protected with username and password. How can i do get some data from that page if it is protected. Any suggestion? When i access it i need to enter username and password to get content. I owe that site and i know username and password but it need to be protected because its in develop mode.</p>

答: Send an authentication request simulating the login form (using $http) to gain an authenticated session, then request the data as normal.


问:
Square App API (Scheduling)
Currently does the Square App API include SquareUp's scheduling service that they provide?

I have looked everywhere and have not manage to find anything about scheduling for the API

答: There are no APIs for Square Appointments at this time. </p>

Title: Square App API (Scheduling)