问:
didSelectRowAtIndexPath not being called because of UI tap Gesture Swift Solution?
I have written my own function to scroll text fields up when the keyboard shows up. In order to dismiss the keyboard by tapping away from the text field, I've created a UITapGestureRecognizer that takes care of resigning first responder on the text field when tapping away.

However, when selecting one of the entries in the auto completed table, didSelectRowAtIndexPath does not get called. Instead, it seems that the tap gesture recognizer is getting called and just resigns first responder.

I'm guessing there's some way to tell the tap gesture recognizer to keep passing the tap message on down to the UITableView, but I can't figure out what it is. There are only solutions for this in objc and posts from over 9 years ago on stack overflow , I was wondering if there was an updated solution to this! Thank you , Here is my code if you would like to see whats going on :

```<code>class ChatLogController : UIViewController, UITextFieldDelegate , UITableViewDelegate , UITableViewDataSource, UIGestureRecognizerDelegate, UIImagePickerControllerDelegate ,UINavigationControllerDelegate  {

var messages = [Message]()

var user : User?{
    didSet{
     observeMessages()
    }
}

@IBOutlet weak var tabelView: UITableView!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var bottomViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var currentMessageRecieverImage: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    configureTableView()

    currentMessageRecieverImage.translatesAutoresizingMaskIntoConstraints = false;
    currentMessageRecieverImage.layer.cornerRadius = 30;
    currentMessageRecieverImage.layer.masksToBounds = true
    currentMessageRecieverImage.contentMode = .scaleAspectFill
    if let currentMessageRecieverUser = user{
        currentMessageRecieverImage.loadImageUsingCacheWithUrlString(urlString: currentMessageRecieverUser.picURL!);
        print(currentMessageRecieverUser.userName!)
    }

    tabelView.delegate = self;
    tabelView.dataSource = self;
    messageTextField.delegate = self;

    let dragAwayFromTextGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleTapAwayFromTextEdit))
    dragAwayFromTextGesture.direction = UISwipeGestureRecognizerDirection.down
    dragAwayFromTextGesture.delegate = self;
    tabelView.addGestureRecognizer(dragAwayFromTextGesture)

    let dragBackToMessages = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeBackToMessages))
    dragBackToMessages.direction = UISwipeGestureRecognizerDirection.right
    dragBackToMessages.delegate = self;
    tabelView.addGestureRecognizer(dragBackToMessages)

    let TapAwayFromTextEditTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapAwayFromTextEdit))
    tabelView.addGestureRecognizer(TapAwayFromTextEditTapGesture)
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

@objc func handleSwipeBackToMessages(){
    dismiss(animated: false, completion: nil)
}

func observeMessages(){
    guard let uid = Auth.auth().currentUser?.uid else{
        return;
    }
    // ref gets user that is logged in
    let ref = Database.database().reference().child("user-messages").child(uid)
    ref.observe(.childAdded) { (snapshot) in
        // gets needed messages
        let messageId = snapshot.key
        let messagesRef = Database.database().reference().child("messages").child(messageId)

        messagesRef.observe(.value, with: { (snapshot) in
            guard let dict = snapshot.value as? [String : AnyObject] else{
                return
            }
            let message = Message()
            message.imageUrl = dict["imageurl"] as? String
            message.fromId = dict["fromid"] as? String
            message.text = dict["text"] as? String
            message.timestamp = dict["timestamp"] as? String
            message.toId = dict["toid"] as? String

            if message.chatPartnerId() == self.user?.toId{
            self.messages.append(message)
            }
            DispatchQueue.main.async {
                self.tabelView.reloadData()
            }

        })
    }

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

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellid" , for: indexPath) as! CustomChatTableViewCell;
    let gray = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
    let red = UIColor(red:1.00, green:0.22, blue:0.37, alpha:1.0)

    let message = messages[indexPath.item]

    if message.toId == user?.toId{

    cell.messageBackground.backgroundColor = red
        cell.messageLabel.textColor = UIColor.white
    }
    else{
        cell.messageBackground.backgroundColor = gray
        cell.messageLabel.textColor = UIColor.black
    }

    cell.messageLabel.text = message.text
    if message.imageUrl != nil{
        //print(message.imageUrl!)
       // cell.messageImageView.image = UIImage(named : "user.jpg")
        cell.messageImageView.loadImageUsingCacheWithUrlString(urlString: message.imageUrl!)
        //print(cell.messageImageView.image.debugDescription)
        cell.messageImageView.isHidden = false;
        cell.messageImageView.translatesAutoresizingMaskIntoConstraints = false;
        cell.messageImageView.contentMode = .scaleAspectFill
        cell.messageLabel.isHidden = true
        cell.messageBackground.isHidden = true;
    }
    else
    {
        cell.messageImageView.isHidden = true;
        cell.selectionStyle = UITableViewCellSelectionStyle.none

        cell.messageLabel.isHidden = false
        cell.messageBackground.isHidden = false;
    }
    return cell;
}

@objc func handleTapAwayFromTextEdit(){
    //print("handle tap away from text edit running ")
    messageTextField.endEditing(true)

}

@IBAction func backToMessageListPressed(_ sender: Any) {
    dismiss(animated: false, completion: nil)
}

@IBAction func infoButtonPressed(_ sender: Any) {

}
// saves text to fire base

@IBAction func sendButtonPressed(_ sender: Any) {

  handleSendMessageToDataBase()
}

func handleSendMessageToDataBase(){
    let ref = Database.database().reference().child("messages")
    // needed for making list in firebase for unique texts
    let childRef = ref.childByAutoId()

    if messageTextField.text == ""{
        return
    }

    if let message = messageTextField.text{

        let toID = user!.toId!
        let fromId = Auth.auth().currentUser!.uid
        let timeStamp : Int =  Int(Int(NSDate().timeIntervalSince1970))
        print(timeStamp)
        let values = ["text" : message , "toid" : toID , "timestamp" : "\(timeStamp)" , "fromid" : fromId]

        childRef.updateChildValues(values, withCompletionBlock: { (error, ref) in
            if error != nil{
                print(error!)
                return
            }

            let userMessagesref = Database.database().reference().child("user-messages").child(fromId)

            let messageID = childRef.key
            userMessagesref.updateChildValues([messageID: 1])

            let recipientUserMessageRef = Database.database().reference().child("user-messages").child(toID)
            recipientUserMessageRef.updateChildValues([messageID: 1])
        })

    }

    messageTextField.text = ""
    messageTextField.endEditing(true)
}

@IBAction func sendImageButtonPressed(_ sender: Any) {

    handleSendImage()

}

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    print("You selected cell #\(indexPath.row)!")
}

func handleSendImage(){

    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self
    present(imagePickerController, animated: true, completion: nil)

}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    dismiss(animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    var selectedImageFromPicker : UIImage?

    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage{
        selectedImageFromPicker = editedImage
    }
    else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage{
        selectedImageFromPicker = originalImage
    }
    if let selectedImage = selectedImageFromPicker{
        uploadToFireBaseUsingSelectedImage(selectedImage : selectedImage)
    }

    dismiss(animated: true, completion: nil)

}

   private func uploadToFireBaseUsingSelectedImage(selectedImage :
UIImage){
    let imageName = NSUUID().uuidString
    let refToStorage = Storage.storage().reference().child("message_images").child(imageName)

if let uploadData = UIImageJPEGRepresentation(selectedImage, 0.2){
    refToStorage.putData(uploadData, metadata: nil, completion: { (metaData, error) in
        if error != nil{
            print("failed to upload firebase image when sending in chatlogcontroller")
            print(error!)
            return
        }
        if let imageURL = metaData?.downloadURL()?.absoluteString{
            self.sendMessageWithImageURL(imageURL: imageURL)
        }

    })

}

}

private func sendMessageWithImageURL(imageURL : String){
    let ref = Database.database().reference().child("messages")
    // needed for making list in firebase for unique texts
    let childRef = ref.childByAutoId()

        let toID = user!.toId!
        let fromId = Auth.auth().currentUser!.uid
        let timeStamp : Int =  Int(Int(NSDate().timeIntervalSince1970))
        print(timeStamp)
        let values = ["imageurl" : imageURL , "toid" : toID , "timestamp" : "\(timeStamp)" , "fromid" : fromId]

        childRef.updateChildValues(values, withCompletionBlock: { (error, ref) in
            if error != nil{
                print(error!)
                return
            }

            let userMessagesref = Database.database().reference().child("user-messages").child(fromId)

            let messageID = childRef.key
            userMessagesref.updateChildValues([messageID: 1])

            let recipientUserMessageRef = Database.database().reference().child("user-messages").child(toID)
            recipientUserMessageRef.updateChildValues([messageID: 1])
        })

}

func textFieldDidBeginEditing(_ textField: UITextField) {

    UIView.animate(withDuration: 0.2, animations:{
        self.bottomViewHeightConstraint.constant = 308;
        self.view.layoutIfNeeded()
    })

}

func textFieldDidEndEditing(_ textField: UITextField) {
    UIView.animate(withDuration: 0.2, animations:{
        self.bottomViewHeightConstraint.constant = 50;
        self.view.layoutIfNeeded()

    })
}

func configureTableView()
{
    tabelView.delegate = self;
    tabelView.dataSource = self;
    tabelView.register(UINib(nibName: "MessageCell" , bundle : nil), forCellReuseIdentifier: "customMessageCell");
    tabelView.allowsSelection = true;

}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.removeObserver(self);

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let message = messages[indexPath.item]

    if message.imageUrl != nil{
        return 200
    }

    return (CGFloat((message.text?.count)! + 70) )
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

    return 80
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    handleSendMessageToDataBase()
    return true
}
</code>```

}

答:
The solution is to set the property cancelsTouchesInView of your TapAwayFromTextEditTapGesture to false. This will cause it to pass on touches to the table view.

From the Apple documentation on this property (with my emphasis):

When this property is true (the default) and the receiver recognizes its gesture, the touches of that gesture that are pending are not delivered to the view and previously delivered touches are cancelled through a touchesCancelled(_:with:) message sent to the view. If a gesture recognizer doesn’t recognize its gesture or if the value of this property is false, the view receives all touches in the multi-touch sequence.

Body:
I have written my own function to scroll text fields up when the keyboard shows up. In order to dismiss the keyboard by tapping away from the text field, I've created a UITapGestureRecognizer that takes care of resigning first responder on the text field when tapping away.

However, when selecting one of the entries in the auto completed table, didSelectRowAtIndexPath does not get called. Instead, it seems that the tap gesture recognizer is getting called and just resigns first responder.

I'm guessing there's some way to tell the tap gesture recognizer to keep passing the tap message on down to the UITableView, but I can't figure out what it is. There are only solutions for this in objc and posts from over 9 years ago on stack overflow , I was wondering if there was an updated solution to this! Thank you , Here is my code if you would like to see whats going on :

class ChatLogController : UIViewController, UITextFieldDelegate , UITableViewDelegate , UITableViewDataSource, UIGestureRecognizerDelegate, UIImagePickerControllerDelegate ,UINavigationControllerDelegate  {

var messages = [Message]()

var user : User?{
    didSet{
     observeMessages()
    }
}

@IBOutlet weak var tabelView: UITableView!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var bottomViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var currentMessageRecieverImage: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    configureTableView()

    currentMessageRecieverImage.translatesAutoresizingMaskIntoConstraints = false;
    currentMessageRecieverImage.layer.cornerRadius = 30;
    currentMessageRecieverImage.layer.masksToBounds = true
    currentMessageRecieverImage.contentMode = .scaleAspectFill
    if let currentMessageRecieverUser = user{
        currentMessageRecieverImage.loadImageUsingCacheWithUrlString(urlString: currentMessageRecieverUser.picURL!);
        print(currentMessageRecieverUser.userName!)
    }

    tabelView.delegate = self;
    tabelView.dataSource = self;
    messageTextField.delegate = self;

    let dragAwayFromTextGesture = UISwipeGestureRecognizer(target: self, action: #selector(handleTapAwayFromTextEdit))
    dragAwayFromTextGesture.direction = UISwipeGestureRecognizerDirection.down
    dragAwayFromTextGesture.delegate = self;
    tabelView.addGestureRecognizer(dragAwayFromTextGesture)

    let dragBackToMessages = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipeBackToMessages))
    dragBackToMessages.direction = UISwipeGestureRecognizerDirection.right
    dragBackToMessages.delegate = self;
    tabelView.addGestureRecognizer(dragBackToMessages)

    let TapAwayFromTextEditTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapAwayFromTextEdit))
    tabelView.addGestureRecognizer(TapAwayFromTextEditTapGesture)
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

@objc func handleSwipeBackToMessages(){
    dismiss(animated: false, completion: nil)
}

func observeMessages(){
    guard let uid = Auth.auth().currentUser?.uid else{
        return;
    }
    // ref gets user that is logged in
    let ref = Database.database().reference().child("user-messages").child(uid)
    ref.observe(.childAdded) { (snapshot) in
        // gets needed messages
        let messageId = snapshot.key
        let messagesRef = Database.database().reference().child("messages").child(messageId)

        messagesRef.observe(.value, with: { (snapshot) in
            guard let dict = snapshot.value as? [String : AnyObject] else{
                return
            }
            let message = Message()
            message.imageUrl = dict["imageurl"] as? String
            message.fromId = dict["fromid"] as? String
            message.text = dict["text"] as? String
            message.timestamp = dict["timestamp"] as? String
            message.toId = dict["toid"] as? String

            if message.chatPartnerId() == self.user?.toId{
            self.messages.append(message)
            }
            DispatchQueue.main.async {
                self.tabelView.reloadData()
            }

        })
    }

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

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellid" , for: indexPath) as! CustomChatTableViewCell;
    let gray = UIColor(red:0.94, green:0.94, blue:0.94, alpha:1.0)
    let red = UIColor(red:1.00, green:0.22, blue:0.37, alpha:1.0)

    let message = messages[indexPath.item]

    if message.toId == user?.toId{

    cell.messageBackground.backgroundColor = red
        cell.messageLabel.textColor = UIColor.white
    }
    else{
        cell.messageBackground.backgroundColor = gray
        cell.messageLabel.textColor = UIColor.black
    }

    cell.messageLabel.text = message.text
    if message.imageUrl != nil{
        //print(message.imageUrl!)
       // cell.messageImageView.image = UIImage(named : "user.jpg")
        cell.messageImageView.loadImageUsingCacheWithUrlString(urlString: message.imageUrl!)
        //print(cell.messageImageView.image.debugDescription)
        cell.messageImageView.isHidden = false;
        cell.messageImageView.translatesAutoresizingMaskIntoConstraints = false;
        cell.messageImageView.contentMode = .scaleAspectFill
        cell.messageLabel.isHidden = true
        cell.messageBackground.isHidden = true;
    }
    else
    {
        cell.messageImageView.isHidden = true;
        cell.selectionStyle = UITableViewCellSelectionStyle.none

        cell.messageLabel.isHidden = false
        cell.messageBackground.isHidden = false;
    }
    return cell;
}

@objc func handleTapAwayFromTextEdit(){
    //print("handle tap away from text edit running ")
    messageTextField.endEditing(true)

}

@IBAction func backToMessageListPressed(_ sender: Any) {
    dismiss(animated: false, completion: nil)
}

@IBAction func infoButtonPressed(_ sender: Any) {

}
// saves text to fire base

@IBAction func sendButtonPressed(_ sender: Any) {

  handleSendMessageToDataBase()
}

func handleSendMessageToDataBase(){
    let ref = Database.database().reference().child("messages")
    // needed for making list in firebase for unique texts
    let childRef = ref.childByAutoId()

    if messageTextField.text == ""{
        return
    }

    if let message = messageTextField.text{

        let toID = user!.toId!
        let fromId = Auth.auth().currentUser!.uid
        let timeStamp : Int =  Int(Int(NSDate().timeIntervalSince1970))
        print(timeStamp)
        let values = ["text" : message , "toid" : toID , "timestamp" : "\(timeStamp)" , "fromid" : fromId]

        childRef.updateChildValues(values, withCompletionBlock: { (error, ref) in
            if error != nil{
                print(error!)
                return
            }

            let userMessagesref = Database.database().reference().child("user-messages").child(fromId)

            let messageID = childRef.key
            userMessagesref.updateChildValues([messageID: 1])

            let recipientUserMessageRef = Database.database().reference().child("user-messages").child(toID)
            recipientUserMessageRef.updateChildValues([messageID: 1])
        })

    }

    messageTextField.text = ""
    messageTextField.endEditing(true)
}

@IBAction func sendImageButtonPressed(_ sender: Any) {

    handleSendImage()

}

func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    print("You selected cell #\(indexPath.row)!")
}

func handleSendImage(){

    let imagePickerController = UIImagePickerController()
    imagePickerController.delegate = self
    present(imagePickerController, animated: true, completion: nil)

}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    dismiss(animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    var selectedImageFromPicker : UIImage?

    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage{
        selectedImageFromPicker = editedImage
    }
    else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage{
        selectedImageFromPicker = originalImage
    }
    if let selectedImage = selectedImageFromPicker{
        uploadToFireBaseUsingSelectedImage(selectedImage : selectedImage)
    }

    dismiss(animated: true, completion: nil)

}

   private func uploadToFireBaseUsingSelectedImage(selectedImage :
UIImage){
    let imageName = NSUUID().uuidString
    let refToStorage = Storage.storage().reference().child("message_images").child(imageName)

if let uploadData = UIImageJPEGRepresentation(selectedImage, 0.2){
    refToStorage.putData(uploadData, metadata: nil, completion: { (metaData, error) in
        if error != nil{
            print("failed to upload firebase image when sending in chatlogcontroller")
            print(error!)
            return
        }
        if let imageURL = metaData?.downloadURL()?.absoluteString{
            self.sendMessageWithImageURL(imageURL: imageURL)
        }

    })

}

}

private func sendMessageWithImageURL(imageURL : String){
    let ref = Database.database().reference().child("messages")
    // needed for making list in firebase for unique texts
    let childRef = ref.childByAutoId()

        let toID = user!.toId!
        let fromId = Auth.auth().currentUser!.uid
        let timeStamp : Int =  Int(Int(NSDate().timeIntervalSince1970))
        print(timeStamp)
        let values = ["imageurl" : imageURL , "toid" : toID , "timestamp" : "\(timeStamp)" , "fromid" : fromId]

        childRef.updateChildValues(values, withCompletionBlock: { (error, ref) in
            if error != nil{
                print(error!)
                return
            }

            let userMessagesref = Database.database().reference().child("user-messages").child(fromId)

            let messageID = childRef.key
            userMessagesref.updateChildValues([messageID: 1])

            let recipientUserMessageRef = Database.database().reference().child("user-messages").child(toID)
            recipientUserMessageRef.updateChildValues([messageID: 1])
        })

}

func textFieldDidBeginEditing(_ textField: UITextField) {

    UIView.animate(withDuration: 0.2, animations:{
        self.bottomViewHeightConstraint.constant = 308;
        self.view.layoutIfNeeded()
    })

}

func textFieldDidEndEditing(_ textField: UITextField) {
    UIView.animate(withDuration: 0.2, animations:{
        self.bottomViewHeightConstraint.constant = 50;
        self.view.layoutIfNeeded()

    })
}

func configureTableView()
{
    tabelView.delegate = self;
    tabelView.dataSource = self;
    tabelView.register(UINib(nibName: "MessageCell" , bundle : nil), forCellReuseIdentifier: "customMessageCell");
    tabelView.allowsSelection = true;

}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    NotificationCenter.default.removeObserver(self);

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    let message = messages[indexPath.item]

    if message.imageUrl != nil{
        return 200
    }

    return (CGFloat((message.text?.count)! + 70) )
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

    return 80
}

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    handleSendMessageToDataBase()
    return true
}

}


来源: stackexchange

问:
Positioning of footer text
I am trying to add a footer similar to the Airbnb one. I have been able to do the first two columns. However the third one is always slightly below the rest. I've tried:
Position: Absolute (however this makes it disappear)
Position: relative (this works fine however it remove the links from the other two columns).
Float: right and left but doesn't let me move it up.

I'm running out of ideas of what to do so if someone could help me that would be great. here is my code and a image of what I have made.

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 550px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display: table;
  float: left;
  positi
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

  <div class="col-1">
    Revel
    <hr>
    <span> About us       </span>
    <span> Contact us     </span>
    <span> FAQ            </span>
    <span> Careers        </span>
  </div>

  <div class="col-2">
    Event Host
    <hr>
    <span>  Why use Revel  </span>
    <span>  test           </span>
    <span>  test           </span>
    <span>  Join Revel     </span>
  </div>

  <div class="col-3">
    Event Service
    <hr>
    <span> Why partner with Revel  </span>
    <span> Guidebooks              </span>
    <span> FAQ                     </span>
    <span> Partner with Revel      </span>
  </div>

</footer></code>```

enter image description here

答:
You have defined col-1 and col-3 as float, you need to define col-2 also as float: left. See the code below I modified.

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
   -moz-box-shadow: 0 5px 10px -6px black;
        box-shadow: 0 5px 10px -6px black; /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%; /* NOTE: where the footer sits on page */
 }

 .footer-links {
   color: white;
 }
 .footer-links:hover {
   color: black;
 }

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}
.col-1 span{
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
  float: left;
}
.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 550px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display:table;
  float: left;
  positi
}
.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

    <div class="col-1">
         Revel
             <hr>
      <span> About us       </span>
      <span> Contact us     </span>
      <span> FAQ            </span>
      <span> Careers        </span>
      </div>

    <div class="col-2">
         Event Host
         <hr>
      <span>  Why use Revel  </span>
      <span>  test           </span>
      <span>  test           </span>
      <span>  Join Revel     </span>
    </div>

    <div class="col-3">
        Event Service
       <hr>
       <span> Why partner with Revel  </span>
       <span> Guidebooks              </span>
       <span> FAQ                     </span>
       <span> Partner with Revel      </span>
    </div>

  </footer></code>```

ContentLicense: CC BY-SA 3.0

Title: Positioning of footer text

Body:
I am trying to add a footer similar to the Airbnb one. I have been able to do the first two columns. However the third one is always slightly below the rest. I've tried:
Position: Absolute (however this makes it disappear)
Position: relative (this works fine however it remove the links from the other two columns).
Float: right and left but doesn't let me move it up.

I'm running out of ideas of what to do so if someone could help me that would be great. here is my code and a image of what I have made.

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 550px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display: table;
  float: left;
  positi
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

    Revel

     About us
     Contact us
     FAQ
     Careers

    Event Host

      Why use Revel
      test
      test
      Join Revel

    Event Service

     Why partner with Revel
     Guidebooks
     FAQ
     Partner with Revel

enter image description here

Body:
You have defined col-1 and col-3 as float, you need to define col-2 also as float: left. See the code below I modified.

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
   -moz-box-shadow: 0 5px 10px -6px black;
        box-shadow: 0 5px 10px -6px black; /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%; /* NOTE: where the footer sits on page */
 }

 .footer-links {
   color: white;
 }
 .footer-links:hover {
   color: black;
 }

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}
.col-1 span{
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
  float: left;
}
.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 550px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display:table;
  float: left;
  positi
}
.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

<footer>

    <div class="col-1">
         Revel
             <hr>
      <span><a href="#" class="footer-links"> About us       </a></span>
      <span><a href="#" class="footer-links"> Contact us     </a></span>
      <span><a href="#" class="footer-links"> FAQ            </a></span>
      <span><a href="#" class="footer-links"> Careers        </a></span>
      </div>

    <div class="col-2">
         Event Host
         <hr>
      <span> <a href="#" class="footer-links"> Why use Revel  </a></span>
      <span> <a href="#" class="footer-links"> test           </a></span>
      <span> <a href="#" class="footer-links"> test           </a></span>
      <span> <a href="#" class="footer-links"> Join Revel     </a></span>
    </div>

    <div class="col-3">
        Event Service
       <hr>
       <span><a href="#" class="footer-links"> Why partner with Revel  </a></span>
       <span><a href="#" class="footer-links"> Guidebooks              </a></span>
       <span><a href="#" class="footer-links"> FAQ                     </a></span>
       <span><a href="#" class="footer-links"> Partner with Revel      </a></span>
    </div>

  </footer>


问:
How to remove some character from string using PHP
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

```<code>$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);
</code>```

Expected Output

```<code>$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);
</code>```

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

Body:
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);

Expected Output

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

Body:
Try foreach loop for this operation

$datArr=array(array("name"=>"Ram","id"=>1,"date"=>"12/04/2017 05:31:57 AM"),array("name"=>"Rahim","id"=>5,"date"=>"12/03/2017 12:31:57 PM"),array("name"=>"Raj","id"=>4,"date"=>"12/04/2017 05:31:57 PM"));

print_r($datArr);
foreach($datArr as $key=>$value)
{
    $datArr[$key]['date'] = date('m/d/Y H:i:s',strtotime($value['date']));
}

echo "after";
print_r($datArr);

Output of this code

    Array
(
    [0] => Array
        (
            [name] => Ram
            [id] => 1
            [date] => 12/04/2017 05:31:57 AM
        )

    [1] => Array
        (
            [name] => Rahim
            [id] => 5
            [date] => 12/03/2017 12:31:57 PM
        )

    [2] => Array
        (
            [name] => Raj
            [id] => 4
            [date] => 12/04/2017 05:31:57 PM
        )

)
afterArray
(
    [0] => Array
        (
            [name] => Ram
            [id] => 1
            [date] => 12/04/2017 05:31:57
        )

    [1] => Array
        (
            [name] => Rahim
            [id] => 5
            [date] => 12/03/2017 12:31:57
        )

    [2] => Array
        (
            [name] => Raj
            [id] => 4
            [date] => 12/04/2017 17:31:57
        )

)


问:
How do I detect line change event in ace editor?
I am trying to capture a line change event in ace editor. Every time user presses enter the line changes and the console.log shows the current line no. im trying to execute the following code.

```<code>editor.getSession().getRowLength().on('change', function(event) {
    if (lineno ==1){
        //execute abc}
    else if (lineno==2){
        //execute xyz}
});
</code>```

I get the following error

```<code>tryit-ide.js:20 Uncaught TypeError: editor.getSession(...).getRowLength(...).on is not a function
at tryit-ide.js:20
at setUp (arch_ace-editor.js?hash=d1163619d62832acc5c961ddb94093c49630a447:78)
at callback (arch_ace-editor.js?hash=d1163619d62832acc5c961ddb94093c49630a447:98)
at arch_ace-editor.js?hash=d1163619d62832acc5c961ddb94093c49630a447:111
at XMLHttpRequest.request.onreadystatechange (arch_ace-editor.js?hash=d1163619d62832acc5c961ddb94093c49630a447:53)
</code>```

Thank you.

答:
the error just says that you are adding event listener on a number. Try</p>

```<code>editor.session.on('change', function(delta) {
     var lineno = delta.start.row
    if (lineno ==1){
        //execute abc}
    else if (lineno==2){
        //execute xyz}
});
</code>```

Body:
I am trying to capture a line change event in ace editor. Every time user presses enter the line changes and the console.log shows the current line no. im trying to execute the following code.

editor.getSession().getRowLength().on('change', function(event) {
    if (lineno ==1){
        //execute abc}
    else if (lineno==2){
        //execute xyz}
});

I get the following error

tryit-ide.js:20 Uncaught TypeError: editor.getSession(...).getRowLength(...).on is not a function
at tryit-ide.js:20
at setUp (arch_ace-editor.js?hash=d1163619d62832acc5c961ddb94093c49630a447:78)
at callback (arch_ace-editor.js?hash=d1163619d62832acc5c961ddb94093c49630a447:98)
at arch_ace-editor.js?hash=d1163619d62832acc5c961ddb94093c49630a447:111
at XMLHttpRequest.request.onreadystatechange (arch_ace-editor.js?hash=d1163619d62832acc5c961ddb94093c49630a447:53)

Thank you.

Body:
the error just says that you are adding event listener on a number. Try

editor.session.on('change', function(delta) {
     var lineno = delta.start.row
    if (lineno ==1){
        //execute abc}
    else if (lineno==2){
        //execute xyz}
});


答:
Basically you are missing float: left on .col-2 and .col-3. This will bring the third link group to the top. Then, you can set the line-height on .col-3 to ensure that it aligns horizontally with the other two groups.

Also note that in the snippet below I have set a minimum width on the body to ensure that the columns don't wrap.

body {
  min-width: 800px;
}

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
  float: left;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 50px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display: table;
  float: left;
  line-height: 40px;
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

  <div class="col-1">
    Revel
    <hr>
    <span> About us       </span>
    <span> Contact us     </span>
    <span> FAQ            </span>
    <span> Careers        </span>
  </div>

  <div class="col-2">
    Event Host
    <hr>
    <span>  Why use Revel  </span>
    <span>  test           </span>
    <span>  test           </span>
    <span>  Join Revel     </span>
  </div>

  <div class="col-3">
    Event Service
    <hr>
    <span> Why partner with Revel  </span>
    <span> Guidebooks              </span>
    <span> FAQ                     </span>
    <span> Partner with Revel      </span>
  </div>

</footer></code>```

Title: Positioning of footer text

Body:
Basically you are missing float: left on .col-2 and .col-3. This will bring the third link group to the top. Then, you can set the line-height on .col-3 to ensure that it aligns horizontally with the other two groups.

Also note that in the snippet below I have set a minimum width on the body to ensure that the columns don't wrap.

body {
  min-width: 800px;
}

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
  float: left;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 50px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display: table;
  float: left;
  line-height: 40px;
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

<footer>

  <div class="col-1">
    Revel
    <hr>
    <span><a href="#" class="footer-links"> About us       </a></span>
    <span><a href="#" class="footer-links"> Contact us     </a></span>
    <span><a href="#" class="footer-links"> FAQ            </a></span>
    <span><a href="#" class="footer-links"> Careers        </a></span>
  </div>

  <div class="col-2">
    Event Host
    <hr>
    <span> <a href="#" class="footer-links"> Why use Revel  </a></span>
    <span> <a href="#" class="footer-links"> test           </a></span>
    <span> <a href="#" class="footer-links"> test           </a></span>
    <span> <a href="#" class="footer-links"> Join Revel     </a></span>
  </div>

  <div class="col-3">
    Event Service
    <hr>
    <span><a href="#" class="footer-links"> Why partner with Revel  </a></span>
    <span><a href="#" class="footer-links"> Guidebooks              </a></span>
    <span><a href="#" class="footer-links"> FAQ                     </a></span>
    <span><a href="#" class="footer-links"> Partner with Revel      </a></span>
  </div>

</footer>


问:
Android Google Maps API Security Exception on API23
Here's the exception i got :

```<code>java.lang.SecurityException
:com.google.android.gms.DynamiteModulesB line 50297 in az.c()
my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION

az : android.support.transition.TransitionIcs
c() : android.support.transition.TransitionIcs$CompatListener mCompatListener

com.google.maps.api.android.lib6.impl
:com.google.android.gms.DynamiteModulesB line 50297 in az.c()
com.google.android.gms.maps.internal
:com.google.android.gms.DynamiteModulesB line 274 in l.onTransact()
android.os
Binder.java line 387 in Binder.transact()
com.google.android.gms.maps.internal
line -1 IGoogleMapDelegate$zza$a.setMyLocationEnabled()
com.google.android.gms.maps
line -1 GoogleMap.setMyLocationEnabled()
SourceFile line 214 in MapsActivity.onMapReady()
com.google.android.gms.maps
line -1 MapFragment$a$1.zza()
com.google.android.gms.maps.internal
line -1 zzo$zza.onTransact()
android.os
Binder.java line 387 in Binder.transact()
com.google.android.gms.maps.internal
:com.google.android.gms.DynamiteModulesB line 82 in bw.a()
com.google.maps.api.android.lib6.impl
:com.google.android.gms.DynamiteModulesB line 1805 in bf.run()
android.os
Handler.java line 739 in Handler.handleCallback()
android.os
Handler.java line 95 in Handler.dispatchMessage()
android.os
Looper.java line 234 in Looper.loop()
android.app
ActivityThread.java line 5526 in ActivityThread.main()
java.lang.reflect
Method.java line -2 in Method.invoke()
com.android.internal.os
ZygoteInit.java line 726 in ZygoteInit$Method
</code>```

i have a map fragment using getMap method and show the current location of user if location is enabled in device, but sometimes it gives me the above exception, i've added some location permission check in my code, but i don't know what i've missed...

thanks for help

here is some additional data :

```<code>compileSdkVersion 25
minSdkVersion 15
targetSdkVersion 25

    @Override
public void onMapReady(final GoogleMap map) {
    map.setMyLocationEnabled(true);
}
</code>```

答:
From the standard documentation from Google (and modified a bit):

https://developer.android.com/training/permissions/requesting.html

```<code>    // Assume this is the current activity, and 22 is app specific chose your favorite number and define it in your app somewhere as a final int
    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    22);

            // ACCESS_FINE_LOCATION is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }
</code>```

Where you also need:

```<code>@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 22: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
</code>```

Body:
Here's the exception i got :

java.lang.SecurityException
:com.google.android.gms.DynamiteModulesB line 50297 in az.c()
my location requires permission ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION

az : android.support.transition.TransitionIcs
c() : android.support.transition.TransitionIcs$CompatListener mCompatListener

com.google.maps.api.android.lib6.impl
:com.google.android.gms.DynamiteModulesB line 50297 in az.c()
com.google.android.gms.maps.internal
:com.google.android.gms.DynamiteModulesB line 274 in l.onTransact()
android.os
Binder.java line 387 in Binder.transact()
com.google.android.gms.maps.internal
line -1 IGoogleMapDelegate$zza$a.setMyLocationEnabled()
com.google.android.gms.maps
line -1 GoogleMap.setMyLocationEnabled()
SourceFile line 214 in MapsActivity.onMapReady()
com.google.android.gms.maps
line -1 MapFragment$a$1.zza()
com.google.android.gms.maps.internal
line -1 zzo$zza.onTransact()
android.os
Binder.java line 387 in Binder.transact()
com.google.android.gms.maps.internal
:com.google.android.gms.DynamiteModulesB line 82 in bw.a()
com.google.maps.api.android.lib6.impl
:com.google.android.gms.DynamiteModulesB line 1805 in bf.run()
android.os
Handler.java line 739 in Handler.handleCallback()
android.os
Handler.java line 95 in Handler.dispatchMessage()
android.os
Looper.java line 234 in Looper.loop()
android.app
ActivityThread.java line 5526 in ActivityThread.main()
java.lang.reflect
Method.java line -2 in Method.invoke()
com.android.internal.os
ZygoteInit.java line 726 in ZygoteInit$Method

i have a map fragment using getMap method and show the current location of user if location is enabled in device, but sometimes it gives me the above exception, i've added some location permission check in my code, but i don't know what i've missed...

thanks for help

here is some additional data :

compileSdkVersion 25
minSdkVersion 15
targetSdkVersion 25

    @Override
public void onMapReady(final GoogleMap map) {
    map.setMyLocationEnabled(true);
}

Body:
From the standard documentation from Google (and modified a bit):

https://developer.android.com/training/permissions/requesting.html

    // Assume this is the current activity, and 22 is app specific chose your favorite number and define it in your app somewhere as a final int
    // Here, thisActivity is the current activity
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    22);

            // ACCESS_FINE_LOCATION is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }

Where you also need:

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 22: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}


问:
Which language should I use for [many reads, few big writes DB] with [many concurrent connections]?
Which language would you recommend for use on a dynamic web-page with many users connected.  I am not using flash or anything like that, interactivity is all Javascript/HTML.

My basic two restrictions are:

plays nicely with mySQL or if you have other specific recommendations for db I am all-ears.

It has to be able to keep up with tons of concurrent connections that are all reading small subsets of all the content (so very cache-able) and occasionally posting plaintext (not very frequently, but voluminous -- say

I am really interested in learning a new language as a personal-programmer-expand-my-horizons initiative, so I don't want to use a java server back-end, because that's something I'm very familiar with (and I would really need something with better thread management than apache).  I'm coding proficient (but not fluent) Javascript, and would be open to JS options in addition to everything else.

Things I have looked into and figure they might be relevant, but I'm not sure how:

Node.js

Thanks for your input!

I also tagged this "web-application-design" and I feel that many programmers neglect to notice that figuring out the basic structure of your program and how the methods and objects will interoperate beforehand is absolutely 100% part of the design phase.

答: PHP, although the choice of language is less important than the database and the storage engine used in that database. MySQL is supported by any major language nowadays.</p>

ContentLicense: CC BY-SA 2.5


问:
Access parent module
I am splitting my project into several module for reusability purpose.
Currently there is 3 level of module

Main activity -> list of item -> item detail

some method/variable I declared at main activity that item detail need to use it also, is that possible item detail access method/variable from list of item or main activity? or I should pull those method or variable into another module?

main activity .gradle

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation project(path: ":list_of_item")
}
</code>```

list of item .gradle

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation project(path: ":item_detail")
}
</code>```

答:
No, you can't access methods in Parent module from child Module.You can access things only if you add them as dependency to your module.

Main activity can access both

list_item can access itemdetail

But in your case, it's not preferred to add parent module as dependent to child as it will create circular dependency.
so to avoid that, create a common module which can be added to all the modules as dependency and move common methods/variables to it.

Title: Access parent module

Body:
I am splitting my project into several module for reusability purpose.
Currently there is 3 level of module

Main activity -> list of item -> item detail

some method/variable I declared at main activity that item detail need to use it also, is that possible item detail access method/variable from list of item or main activity? or I should pull those method or variable into another module?

main activity .gradle

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation project(path: ":list_of_item")
}

list of item .gradle

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation project(path: ":item_detail")
}


答:
Try this. It is a simple and easy to understand example. substr function is used to take a part of the string from starting 0 to length - 2 for excluding AM/PM

```<code>foreach($datArr as $key => $value){
    $datArr[$key]['date'] = substr($value['date'], 0, strlen($value['date'])-2);
}
print_r($datArr);
</code>```

Happy Coding :-)

Title: How to remove some character from string using PHP

Body:
Try this. It is a simple and easy to understand example. substr function is used to take a part of the string from starting 0 to length - 2 for excluding AM/PM

foreach($datArr as $key => $value){
    $datArr[$key]['date'] = substr($value['date'], 0, strlen($value['date'])-2);
}
print_r($datArr);

Happy Coding :-)


问:
Jmeter : getting 401 error
Does any one knows how to solve it with regular expression? here  i am putting screen shot with valid access token and error response token.
thanks in advance.

Valid response token

invalid response token

and Regular expression exctracter

it is fine if you guys have any other solution for this unauthorized access thing.

答:
Add JSON Extractor as a child of the authserver request and configure it as follows:

Variable Names: anything meaningful, i.e. token

JSON Path expressions: $.access_token

Add HTTP Header Manager as a child of the student request and configure it to send Authorization header with the value of Bearer ${token}

Going forward you can go for an alternative way of recording a JMeter test which is capable of exporting the recorded requests in SmartJMX mode with automatic correlation of dynamic parameters applied so you will be able to save your time for more creative work. See How to Cut Your JMeter Scripting Time by 80% article for more details.

Title: Jmeter : getting 401 error


问:
Java 8 Stream: Defining collectors based on other collectors
I'm new to using Java 8 Stream APIs but I'm looking to use it for the following problem.  Say I have a POJO called InputRecord containing name, fieldA, and fieldB properties that can represent each row record of the following:

```<code>name | fieldA | fieldB
----------------------
A    | 100    | 1.1
A    | 150    | 2.0
B    | 200    | 1.5
A    | 120    | 1.3
</code>```

InputRecord would look like:

```<code>public class InputRecord {
    private String name;
    private Integer fieldA;
    private BigDecimal fieldB;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getFieldA() {
        return fieldA;
    }

    public void setFieldA(Integer fieldA) {
        this.fieldA = fieldA;
    }

    public BigDecimal getFieldB() {
        return fieldB;
    }

    public void setFieldB(BigDecimal fieldB) {
        this.fieldB = fieldB;
    }
}
</code>```

Those four records above need to be combined into two records grouped by name, where:

Property fieldA is summed

Property fieldB is summed

The combined records includes a fieldC property which is the result of multiplying the accumulating sums of both fieldA and fieldB.

Therefore the results for above would be:

```<code>name | sumOfFieldA | sumOfFieldB | fieldC (sumOfFieldA*sumOfFieldB)
-------------------------------------------------------------------
A    | 370         | 4.4         | 1628
B    | 200         | 1.5         | 300
</code>```

A different POJO called OutputRecord would represent each row record of the combined records:

```<code>public class OutputRecord {
    private String name;
    private Integer sumOfFieldA;
    private BigDecimal sumOfFieldB;
    private BigDecimal fieldC;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSumOfFieldA() {
        return sumOfFieldA;
    }

    public void setSumOfFieldA(Integer sumOfFieldA) {
        this.sumOfFieldA = sumOfFieldA;
    }

    public BigDecimal getSumOfFieldB() {
        return sumOfFieldB;
    }

    public void setSumOfFieldB(BigDecimal sumOfFieldB) {
        this.sumOfFieldB = sumOfFieldB;
    }

    public BigDecimal getFieldC() {
        return fieldC;
    }

    public void setFieldC(BigDecimal fieldC) {
        this.fieldC = fieldC;
    }
}
</code>```

What are some good approaches/solutions for transforming a list of InputRecords into a list of OutputRecords?

I was seeing if the following link would help but I got stuck trying to put collectors for fieldA and fieldB together in order to form a new collector for fieldC:
Java 8 Stream: groupingBy with multiple Collectors

```<code>Collector<InputRecord, ?, Integer> fieldACollector = Collectors.summingInt(InputRecord::getFieldA);
Collector<InputRecord, ?, BigDecimal> fieldBCollector = Collectors.reducing(BigDecimal.ZERO, InputRecord::getFieldB, BigDecimal::add);

List<Collector<InputRecord, ?, ?>> collectors = Arrays.asList(fieldACollector, fieldBCollector); // need a fieldCCollector object in the list
</code>```

The collectors object would then be used to create a complexCollector object (as per the accepted answer by Tagir Valeev in the above link).

答:
You can can use combine and aggregate functions to generate the list of OutputRecords from List of InputRecords.</p>

```<code>Map<String, OutputRecord> result = inputRecords.stream().collect(() -> new HashMap<>(),
                (HashMap<String, OutputRecord> map, InputRecord inObj) -> {
                    OutputRecord out = map.get(inObj.getName());
                    if (out == null) {
                        out = new OutputRecord();
                        out.setName(inObj.getName());
                        out.setSumOfFieldA(inObj.getFieldA());
                        out.setSumOfFieldB(inObj.getFieldB());
                    } else {

                        Integer s = out.getSumOfFieldA();
                        out.setSumOfFieldA(s + inObj.getFieldA());
                        BigDecimal bd = out.getSumOfFieldB();
                        out.setSumOfFieldB(bd.add(inObj.getFieldB()));
                    }
                    out.setFieldC(out.getSumOfFieldB().multiply(new BigDecimal(out.getSumOfFieldA())));
                    map.put(out.getName(), out);

                }, (HashMap<String, OutputRecord> out1, HashMap<String, OutputRecord> out2) -> {
                    out1.putAll(out2);
                });

        System.out.println(result);
</code>```

Body:
I'm new to using Java 8 Stream APIs but I'm looking to use it for the following problem.  Say I have a POJO called InputRecord containing name, fieldA, and fieldB properties that can represent each row record of the following:

name | fieldA | fieldB
----------------------
A    | 100    | 1.1
A    | 150    | 2.0
B    | 200    | 1.5
A    | 120    | 1.3

InputRecord would look like:

public class InputRecord {
    private String name;
    private Integer fieldA;
    private BigDecimal fieldB;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getFieldA() {
        return fieldA;
    }

    public void setFieldA(Integer fieldA) {
        this.fieldA = fieldA;
    }

    public BigDecimal getFieldB() {
        return fieldB;
    }

    public void setFieldB(BigDecimal fieldB) {
        this.fieldB = fieldB;
    }
}

Those four records above need to be combined into two records grouped by name, where:

Property fieldA is summed

Property fieldB is summed

The combined records includes a fieldC property which is the result of multiplying the accumulating sums of both fieldA and fieldB.

Therefore the results for above would be:

name | sumOfFieldA | sumOfFieldB | fieldC (sumOfFieldA*sumOfFieldB)
-------------------------------------------------------------------
A    | 370         | 4.4         | 1628
B    | 200         | 1.5         | 300

A different POJO called OutputRecord would represent each row record of the combined records:

public class OutputRecord {
    private String name;
    private Integer sumOfFieldA;
    private BigDecimal sumOfFieldB;
    private BigDecimal fieldC;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSumOfFieldA() {
        return sumOfFieldA;
    }

    public void setSumOfFieldA(Integer sumOfFieldA) {
        this.sumOfFieldA = sumOfFieldA;
    }

    public BigDecimal getSumOfFieldB() {
        return sumOfFieldB;
    }

    public void setSumOfFieldB(BigDecimal sumOfFieldB) {
        this.sumOfFieldB = sumOfFieldB;
    }

    public BigDecimal getFieldC() {
        return fieldC;
    }

    public void setFieldC(BigDecimal fieldC) {
        this.fieldC = fieldC;
    }
}

What are some good approaches/solutions for transforming a list of InputRecords into a list of OutputRecords?

I was seeing if the following link would help but I got stuck trying to put collectors for fieldA and fieldB together in order to form a new collector for fieldC:
Java 8 Stream: groupingBy with multiple Collectors

Collector<InputRecord, ?, Integer> fieldACollector = Collectors.summingInt(InputRecord::getFieldA);
Collector<InputRecord, ?, BigDecimal> fieldBCollector = Collectors.reducing(BigDecimal.ZERO, InputRecord::getFieldB, BigDecimal::add);

List<Collector<InputRecord, ?, ?>> collectors = Arrays.asList(fieldACollector, fieldBCollector); // need a fieldCCollector object in the list

The collectors object would then be used to create a complexCollector object (as per the accepted answer by Tagir Valeev in the above link).

Body:
You can can use combine and aggregate functions to generate the list of OutputRecords from List of InputRecords.

Map<String, OutputRecord> result = inputRecords.stream().collect(() -> new HashMap<>(),
                (HashMap<String, OutputRecord> map, InputRecord inObj) -> {
                    OutputRecord out = map.get(inObj.getName());
                    if (out == null) {
                        out = new OutputRecord();
                        out.setName(inObj.getName());
                        out.setSumOfFieldA(inObj.getFieldA());
                        out.setSumOfFieldB(inObj.getFieldB());
                    } else {

                        Integer s = out.getSumOfFieldA();
                        out.setSumOfFieldA(s + inObj.getFieldA());
                        BigDecimal bd = out.getSumOfFieldB();
                        out.setSumOfFieldB(bd.add(inObj.getFieldB()));
                    }
                    out.setFieldC(out.getSumOfFieldB().multiply(new BigDecimal(out.getSumOfFieldA())));
                    map.put(out.getName(), out);

                }, (HashMap<String, OutputRecord> out1, HashMap<String, OutputRecord> out2) -> {
                    out1.putAll(out2);
                });

        System.out.println(result);


问:
Unexpected "=" in mutate statement
I am trying to impute outliers in a tibble by replacing them with NAs. Below is my code:

```<code>for (i in colnames(numTable)){
  m <- mean(pull(numTable[,i]), na.rm=TRUE)
  s<-sd(pull(numTable[,i]),na.rm=TRUE)
  numTable %>%
         mutate(numTable[,i] = replace(numTable[,i], abs(numTable[,i]-m)>3*s,na.rm=TRUE), NA)
}
</code>```

NumTable Looks like this:

I keep getting error messages that says

```<code>Error: unexpected '=' in:
      " numTable %>%
        mutate(numTable[,i] ="
</code>```

Please help me. Thanks.

答:
@akrun's suggested version works, but it has a couple of typos.  After correcting those, the following line of code runs without errors:

```<code>numTable %>% mutate_all(funs(replace(., abs(. - mean(., na.rm = TRUE)) > 3 * sd(., na.rm = TRUE), NA)))
</code>```

I tested this with the first two columns of your data.  Since the inequality condition is not met in those columns, I re-ran it changing the "3 * sd" to "1 * sd" and obtained the following, which I think reflects what you want:

```<code># A tibble: 6 x 2
  M     R
  <dbl> <dbl>
1   138    NA
2   240    14
3    NA     6
4    NA    NA
5   239    20
6   253    10
</code>```

If you're unsure of what's going on here, I suggest you start with a simplified version, such as:

```<code>numTable %>% mutate_all(funs(. * 100))
</code>```

and then gradually convert it over to the code provided by @akrun.

Title: Unexpected "=" in mutate statement

Body:
I am trying to impute outliers in a tibble by replacing them with NAs. Below is my code:

for (i in colnames(numTable)){
  m <- mean(pull(numTable[,i]), na.rm=TRUE)
  s<-sd(pull(numTable[,i]),na.rm=TRUE)
  numTable %>%
         mutate(numTable[,i] = replace(numTable[,i], abs(numTable[,i]-m)>3*s,na.rm=TRUE), NA)
}

NumTable Looks like this:

I keep getting error messages that says

Error: unexpected '=' in:
      " numTable %>%
        mutate(numTable[,i] ="

Please help me. Thanks.

Body:
@akrun's suggested version works, but it has a couple of typos.  After correcting those, the following line of code runs without errors:

numTable %>% mutate_all(funs(replace(., abs(. - mean(., na.rm = TRUE)) > 3 * sd(., na.rm = TRUE), NA)))

I tested this with the first two columns of your data.  Since the inequality condition is not met in those columns, I re-ran it changing the "3 * sd" to "1 * sd" and obtained the following, which I think reflects what you want:

# A tibble: 6 x 2
  M     R
  <dbl> <dbl>
1   138    NA
2   240    14
3    NA     6
4    NA    NA
5   239    20
6   253    10

If you're unsure of what's going on here, I suggest you start with a simplified version, such as:

numTable %>% mutate_all(funs(. * 100))

and then gradually convert it over to the code provided by @akrun.


问:
Cannot fetch data from MySQL
this is my validation page

```<code> <html>
    <body>
    <?php
    function error_found(){
      header("Location: login.php");
    }
    set_error_handler('error_found');
    ?>
    <?php
    $con=mysqli_connect('localhost','root','','mydb');
    session_start();
    if(isset($_POST['loginbtn'])){
    $email=$_POST['email'];
    $password=$_POST['pwd'];
    $result=mysqli_query($con,'select * from myguests where email="'.$email.'" and password="'.$password.'"');
    if(mysqli_num_rows($result)==1)
    {
        $_SESSION['email']= $email;
        header("Location: welcome.php");
    }
    else
        echo"INVALID ACCOUNT";

    }

    ?>

    </body>
    </html>
</code>```

this is my user profile page

```<code><html>
    <body>

    <?php
     require_once 'valid.php';
        session_start();
    echo"welcome  " .$_SESSION['email'];
    $res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email=".$_SESSION['email']);
     $userRow=mysqli_fetch_array($res);
     echo $userRow;
    ?>
    <br><a href="logout.php">logout</a>
    </body>
    </html>

>
</code>```

I am not able to fetch the data from the database it shows me the error.I think I made mistake in declaring a session variable to the SQL query

答:
You have an error in commented line check.</p>

```<code>$res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email='".$_SESSION['email']."'"); // this line has an issue with "'"

<html>
    <body>

    <?php
     require_once 'valid.php';
        session_start();
    echo"welcome  " .$_SESSION['email'];
    $res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email='".$_SESSION['email']."'"); // Missing "'" in query to enclosed parameter.
     $userRow=mysqli_fetch_array($res);
     echo $userRow;
    ?>
    <br><a href="logout.php">logout</a>
    </body>
    </html>
</code>```

Title: Cannot fetch data from MySQL

Body:
this is my validation page

    <?php
    function error_found(){
      header("Location: login.php");
    }
    set_error_handler('error_found');
    ?>
    <?php
    $con=mysqli_connect('localhost','root','','mydb');
    session_start();
    if(isset($_POST['loginbtn'])){
    $email=$_POST['email'];
    $password=$_POST['pwd'];
    $result=mysqli_query($con,'select * from myguests where email="'.$email.'" and password="'.$password.'"');
    if(mysqli_num_rows($result)==1)
    {
        $_SESSION['email']= $email;
        header("Location: welcome.php");
    }
    else
        echo"INVALID ACCOUNT";

    }

    ?>

this is my user profile page

    <?php
     require_once 'valid.php';
        session_start();
    echo"welcome  " .$_SESSION['email'];
    $res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email=".$_SESSION['email']);
     $userRow=mysqli_fetch_array($res);
     echo $userRow;
    ?>

logout

>

I am not able to fetch the data from the database it shows me the error.I think I made mistake in declaring a session variable to the SQL query

Body:
You have an error in commented line check.

$res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email='".$_SESSION['email']."'"); // this line has an issue with "'"

<html>
    <body>

    <?php
     require_once 'valid.php';
        session_start();
    echo"welcome  " .$_SESSION['email'];
    $res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email='".$_SESSION['email']."'"); // Missing "'" in query to enclosed parameter.
     $userRow=mysqli_fetch_array($res);
     echo $userRow;
    ?>
    <br><a href="logout.php">logout</a>
    </body>
    </html>


问:
uwp multi views update GridView
Thanks in advance.

as I know, The first view that’s created when your app starts is called the main view, and Other views, including all views that you create by calling CreateNewView in your app code, are secondary views.

I also know, I can't update UI in thread if they are NOT UI Thread.

I've searched for a long time on net, but haven't found anything. Please help and try to give some ideas how to achieve this.

Here is my code, has been simplified for simplicity：

If I load Items in Page when it start:

```<code>public sealed partial class MainPage : Page
{
    private ObservableCollection<Item> Items;//a GridView bind in this.

    public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;

            Items=  new ObservableCollection<Item>();

            Update();
        }
    async void Update()
    {
        //such as I have a lot of Items
        foreach(Item i in Itemlist)
        {
            Items.add(i);
        }
    }
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        CoreApplicationView newView = CoreApplication.CreateNewView();
        int newViewId = 0;
        await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            Frame frame = new Frame();
            frame.Navigate(typeof(MainPage), null);
            Window.Current.Content = frame;
            // You have to activate the window in order to show it later.
            Window.Current.Activate();

            newViewId = ApplicationView.GetForCurrentView().Id;
        });
        bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
    }
}
</code>```

Here is Problem:

as we know, ObservableCollection<T> have NotifyCollectionChangedEventHandler, when data changed, it will Notify UI thread.

But secondary views(a New MainPage), when it run, UpDate() method change the Items list, then error(a GridView Bind in this).

the application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"
   at Windows.UI.Xaml.Controls.Image.put_Source(ImageSource value)
   at APP1.MainPage.XamlBindingSetters.Set_Windows_UI_Xaml_Controls_Image_Source(Image obj, ImageSource value, String targetNullValue)
   at APP1.MainPage.MainPage_obj2_Bindings.Update_image(BitmapImage obj, Int32 phase)
   at APP1.MainPage.MainPage_obj2_Bindings.Update_(FloderItem obj, Int32 phase)
   at APP1.MainPage.MainPa

my Opinion is the data changed, and The ObservableCollection invoke a Event to update secondary view's UI, but not in UI thread.

I think if NotifyCollectionChangedEvent in UI thread, it be fine.

anybody have ideas? thanks a lot.

答:
I did find the good way to solve this problem.

as I said,  I can't update UI in thread if they are NOT UI Thread, but my problem is not this.

In MainPage, I use a static object in MainPage class.......then I create a new View, the code also try to use this static obj.

cancel the static flag, I solve this problem.

Title: uwp multi views update GridView

Body:
Thanks in advance.

as I know, The first view that’s created when your app starts is called the main view, and Other views, including all views that you create by calling CreateNewView in your app code, are secondary views.

I also know, I can't update UI in thread if they are NOT UI Thread.

I've searched for a long time on net, but haven't found anything. Please help and try to give some ideas how to achieve this.

Here is my code, has been simplified for simplicity：

If I load Items in Page when it start:

public sealed partial class MainPage : Page
{
    private ObservableCollection<Item> Items;//a GridView bind in this.

    public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;

            Items=  new ObservableCollection<Item>();

            Update();
        }
    async void Update()
    {
        //such as I have a lot of Items
        foreach(Item i in Itemlist)
        {
            Items.add(i);
        }
    }
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        CoreApplicationView newView = CoreApplication.CreateNewView();
        int newViewId = 0;
        await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            Frame frame = new Frame();
            frame.Navigate(typeof(MainPage), null);
            Window.Current.Content = frame;
            // You have to activate the window in order to show it later.
            Window.Current.Activate();

            newViewId = ApplicationView.GetForCurrentView().Id;
        });
        bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
    }
}

Here is Problem:

as we know, ObservableCollection<T> have NotifyCollectionChangedEventHandler, when data changed, it will Notify UI thread.

But secondary views(a New MainPage), when it run, UpDate() method change the Items list, then error(a GridView Bind in this).

the application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"
   at Windows.UI.Xaml.Controls.Image.put_Source(ImageSource value)
   at APP1.MainPage.XamlBindingSetters.Set_Windows_UI_Xaml_Controls_Image_Source(Image obj, ImageSource value, String targetNullValue)
   at APP1.MainPage.MainPage_obj2_Bindings.Update_image(BitmapImage obj, Int32 phase)
   at APP1.MainPage.MainPage_obj2_Bindings.Update_(FloderItem obj, Int32 phase)
   at APP1.MainPage.MainPa

my Opinion is the data changed, and The ObservableCollection invoke a Event to update secondary view's UI, but not in UI thread.

I think if NotifyCollectionChangedEvent in UI thread, it be fine.

anybody have ideas? thanks a lot.


问:
Is the  tag purely semantic or can i use it like a
 tag and style it?
Since HTML5 introduced some new tags such as header, footer, aside, nav, etc. I wanted to know if it was good practice to use those tags like they were a div tag?

Let me explain:

I want to have a fixed menu on my website that stays fixed on the top as the user scrolls down the page, so I created a header tag and then i used CSS and gave it a position: fixed; and gave it some other rules...

^Is this recommended? (Giving the header tag some styles)
Or is the header tag only used for markup purposes?

Should I create a div tag inside the header tag and style that div tag? Or is it fine to just style the header tag?

```<code><header>

</header>
</code>```

OR

```<code><header>
 <div id="header>

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

This question also applies to the footer tag and those new HTML5 tags that are used for markup.

答:
The header tag can be styled directly as same as styling div tags. just give id/class for the header as you give id/class to the div tags.

If you are planning to do a fixed nav bar at the top i would suggest for using nav tags instead of header.

Correct me if i am wrong

Title: Is the <header> tag purely semantic or can i use it like a <div> tag and style it?

Body:
Since HTML5 introduced some new tags such as header, footer, aside, nav, etc. I wanted to know if it was good practice to use those tags like they were a div tag?

Let me explain:

I want to have a fixed menu on my website that stays fixed on the top as the user scrolls down the page, so I created a header tag and then i used CSS and gave it a position: fixed; and gave it some other rules...

^Is this recommended? (Giving the header tag some styles)
Or is the header tag only used for markup purposes?

Should I create a div tag inside the header tag and style that div tag? Or is it fine to just style the header tag?

OR

This question also applies to the footer tag and those new HTML5 tags that are used for markup.


问:
AM charts - duration split up in y axis
In am Charts, i have users list as category and duration (hh:mm:ss) in value axis graph. I had set grid count to 24 but, its not working as expected (1 hr * 24 steps). Its being set as 2000 secs steps. I tried changing a lot of parameter.

My sample data : https://live.amcharts.com/iMWNh/

Here, the duration split up is not working as expected in 1 hr split ups of 24 grids. My input data is in seconds.

Any advice ?

答:
This helped me ! Hope someone finds it useful.

Hi,

Unfortunately, what you require would be impossible to implement using
  Live Editor, due to some of its limitation.

However, it's possible using amCharts.

I have made necessary changes here:

https://codepen.io/team/amcharts/pen/55fe695a57e33657e9d5feb33423d481?editors=0010

```<code>AmCharts.useUTC = true;
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"categoryField": "category",
"rotate": true,
"startDuration": 1,
"backgroundAlpha": 0.8,
"categoryAxis": {
    "gridPosition": "start"
},
"trendLines": [],
"graphs": [
    {
        "balloonText": "[[title]] of [[category]]:[[value]]",
        "fillAlphas": 1,
        "id": "AmGraph-1",
        "title": "Online(secs)",
        "type": "column",
        "valueField": "Online(sec)"
    },
    {
        "balloonText": "[[title]] of [[category]]:[[value]]",
        "fillAlphas": 1,
        "id": "AmGraph-2",
        "title": "Offline(secs)",
        "type": "column",
        "valueField": "Offline(sec)"
    }
],
"guides": [],
"valueAxes": [
    {
        "id": "ValueAxis-1",
        "maximum": 86400000,
        "stackType": "regular",
        "strictMinMax": true,
        "autoGridCount": false,
        "autoRotateCount": 0,
        "gridCount": 24,
        "labelRotation": 50.4,
        "title": "",
        "titleRotation": 0,
  "type": "date",
  "minPeriod": "hh",
  "boldPeriodBeginning": false,
  "markPeriodChange": false
    }
],
"allLabels": [],
"balloon": {},
"legend": {
    "enabled": true,
    "useGraphSettings": true
},
"titles": [
    {
        "id": "Title-1",
        "size": 15,
        "text": "Chart Title"
    }
],
"dataProvider": [
    {
        "category": "Diana",
        "Online(sec)": 7200000,
        "Offline(sec)": 79200000
    },
    {
        "category": "Clarke",
        "Online(sec)": 18000000,
        "Offline(sec)": 68400000
    },
    {
        "category": "Bruce",
        "Online(sec)": 3600000,
        "Offline(sec)": 7200000
    }
]
});
</code>```

There were quite a few changes:

1) Remove the duration from value axis, and set its type: "date;

2) Make values in data non-string (remove quotes around them) and convert
  to milliseconds, since JavaScript deals in milliseconds;

3) Similarly convert maximum in valueAxis to milliseconds as well;

4) Set the following two settings for valueAxis: (so that it does not try to
  format the first hour differently)

"boldPeriodBeginning": false, "markPeriodChange": false

5) Finally, set AmCharts.useUTC = false before chart code. (this ensures that
  timestamps are not being recalculated to local time zone)

I hope you find this useful.

Yours sincerely,

Martynas Majeris

amCharts

Title: AM charts - duration split up in y axis

Body:
This helped me ! Hope someone finds it useful.

Hi,

Unfortunately, what you require would be impossible to implement using
  Live Editor, due to some of its limitation.

However, it's possible using amCharts.

I have made necessary changes here:

https://codepen.io/team/amcharts/pen/55fe695a57e33657e9d5feb33423d481?editors=0010

AmCharts.useUTC = true;
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"categoryField": "category",
"rotate": true,
"startDuration": 1,
"backgroundAlpha": 0.8,
"categoryAxis": {
    "gridPosition": "start"
},
"trendLines": [],
"graphs": [
    {
        "balloonText": "[[title]] of [[category]]:[[value]]",
        "fillAlphas": 1,
        "id": "AmGraph-1",
        "title": "Online(secs)",
        "type": "column",
        "valueField": "Online(sec)"
    },
    {
        "balloonText": "[[title]] of [[category]]:[[value]]",
        "fillAlphas": 1,
        "id": "AmGraph-2",
        "title": "Offline(secs)",
        "type": "column",
        "valueField": "Offline(sec)"
    }
],
"guides": [],
"valueAxes": [
    {
        "id": "ValueAxis-1",
        "maximum": 86400000,
        "stackType": "regular",
        "strictMinMax": true,
        "autoGridCount": false,
        "autoRotateCount": 0,
        "gridCount": 24,
        "labelRotation": 50.4,
        "title": "",
        "titleRotation": 0,
  "type": "date",
  "minPeriod": "hh",
  "boldPeriodBeginning": false,
  "markPeriodChange": false
    }
],
"allLabels": [],
"balloon": {},
"legend": {
    "enabled": true,
    "useGraphSettings": true
},
"titles": [
    {
        "id": "Title-1",
        "size": 15,
        "text": "Chart Title"
    }
],
"dataProvider": [
    {
        "category": "Diana",
        "Online(sec)": 7200000,
        "Offline(sec)": 79200000
    },
    {
        "category": "Clarke",
        "Online(sec)": 18000000,
        "Offline(sec)": 68400000
    },
    {
        "category": "Bruce",
        "Online(sec)": 3600000,
        "Offline(sec)": 7200000
    }
]
});

There were quite a few changes:

1) Remove the duration from value axis, and set its type: "date;

2) Make values in data non-string (remove quotes around them) and convert
  to milliseconds, since JavaScript deals in milliseconds;

3) Similarly convert maximum in valueAxis to milliseconds as well;

4) Set the following two settings for valueAxis: (so that it does not try to
  format the first hour differently)

"boldPeriodBeginning": false, "markPeriodChange": false

5) Finally, set AmCharts.useUTC = false before chart code. (this ensures that
  timestamps are not being recalculated to local time zone)

I hope you find this useful.

Yours sincerely,

Martynas Majeris

amCharts


问:
Get the content from iframe of external url
I need to get the content(Complete html) of a page (say.: someotherdomain.com/somepage) loaded in iframe from an asp.net mvc (C#) application without using webclient or httpwebrequest.</p>

答: That's simply not possible. Your browser blocks the javascript in external sites (when in frame), just like with Ajax requests.</p>


答:
Use rtrim to remove the tailing chars like this,</p>

```<code>$datArr = array_map(function($v){
    $v['date'] = rtrim($v['date'], " APMapm");
    return $v;
}, $datArr);
</code>```

Body:
I need to remove some character from string search by value using PHP. I am explaining my code below.

Current Data

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57 AM"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57 PM"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57 PM"
    )
);

Expected Output

$datArr = array(
    array(
        "name" => "Ram",
        "id" => 1,
        "date" => "12/04/2017 05:31:57"
    ),
    array(
        "name" => "Rahim",
        "id" => 5,
        "date" => "12/03/2017 12:31:57"
    ),
    array(
        "name" => "Raj",
        "id" => 4,
        "date" => "12/04/2017 05:31:57"
    )
);

From the above array there is a date field value and I need to remove the AM/PM from all date using PHP.

Body:
Use rtrim to remove the tailing chars like this,

$datArr = array_map(function($v){
    $v['date'] = rtrim($v['date'], " APMapm");
    return $v;
}, $datArr);


答:
How do you deserialize the XML? You don't have complex type in the XML file as I understand, or do you?

You can try this for both actually( complex types and regular types):

```<code>DATA: xml_utils TYPE REF TO if_ixml.xml_utils = cl_ixml=>create( ).
      xml_stream_factory TYPE REF TO if_ixml_stream_factory.xml_stream_factory = xml_utils->create_stream_factory( ).
DATA: xml_input_stream TYPE REF TO if_ixml_istream.xml_input_stream = xml_stream_factory->create_istream_uri( system_id = 'file://test.xml' ).
DAtA: example_data type z_s_your_structure.

" Deserialize XML
CALL TRANSFORMATION id
   SOURCE XML       = xml_input_stream
   RESULT data_node = example_data.
</code>```

For more information, you can check these links, 1, 2.

Title: How to deserialize XML-content to ABAP data fields properly?

Body:
When reading the XML content in ABAP internal table fields via XSLT, sometimes the value cannot be read or an exception appears: Error during deserialization. How can I select the right data type for ABAP itab fields, if I now the XML data type?
e.g.

XML Data Type.......|......Format....|.............ABAP Data Type..........

string 250..........................|..........Text............|.....................?

string 250.........................|..Date yyy-mm-dd..|.....................?

string 250.........................|.Date PARAM-4....|......................?

string 250.........................|..Time hh:mm........|....................?

string 250........................|..Number z9(4)........|...................?

string 250........................|.. Number 9(4).........|................. ?

string 250........................|..Number 9(7)..........|.................?

string 250........................|..Number 9(6)...........|................?

string 250........................|..Number z9(2).........|..................?

string 250........................|..Number 9(5)...........|.................?

string 250........................|..Number d9(2).........|.................?

string 250........................|..Number 9(19).........|.................?

string 250........................|..Number 9(17) v9(2)|.................?

string 250........................|.Number Delco price|.................?

string 250........................|Number Delco amount|.................?

string 250........................|Number customer invoice amount|.................?

string 250........................|..Number PARAM-3.......|.................?

Please note that

xml = version="1.0" encoding="UTF-8" standalone="true"

PARM-3 = Decimal separator used in field formats “,” or “.”

PARM-4 = Date format used in field formats “dd-mm-yyyy” or “yyyy-mm-dd”

Number format:

9(X): an X-digit integer formatted with leading zeros and no sign e.g. 9(2) "01”

v: implicit decimal place e.g. 9(2)v9(2) formats 1.1 as “0110”

d: decimal mark as specified by PARM-3, either , or . e.g. 9(2)d9(2) formats 1.1 as “01,10” or “01.10”

z: supress leading zeros and include sign if negative
e.g. z9(6)d9(2) “ -1.10”

%: include per cent character e.g. z9(2)d9(2)% “ 20.00%”

Delco price: z9(X)d9(Y) where Y is BillingDocument/DeliverCompany/CurrencyPricingMinorUnits and X is the
number of remaining digits in the field

Delco amount: z9(X)d9(Y) where Y is
BillingDocument/DeliverCompany/CurrencyMinorUnits and X is the number of
remaining digits in the field

Customer invoice amount: z9(X)d9(Y) where Y is
BillingDocument/InvoiceCustomer/MinorUnits and X is the number of
remaining digits in the field

Body:
How do you deserialize the XML? You don't have complex type in the XML file as I understand, or do you?

You can try this for both actually( complex types and regular types):

DATA: xml_utils TYPE REF TO if_ixml.xml_utils = cl_ixml=>create( ).
      xml_stream_factory TYPE REF TO if_ixml_stream_factory.xml_stream_factory = xml_utils->create_stream_factory( ).
DATA: xml_input_stream TYPE REF TO if_ixml_istream.xml_input_stream = xml_stream_factory->create_istream_uri( system_id = 'file://test.xml' ).
DAtA: example_data type z_s_your_structure.

" Deserialize XML
CALL TRANSFORMATION id
   SOURCE XML       = xml_input_stream
   RESULT data_node = example_data.

For more information, you can check these links, 1, 2.


问:
Python Tk _tkinter.TclError: invalid command name ".42818376"
I am getting the error mentioned in the title of the post I really just want this to work.  Been working on this problem for a while now and it is frustrating.  My ultimate goal is to obtain the values for the varables text, chkvar, and v.

Thanks to anyone who can reply and help on this!!

```<code>#!C:/Python27/python.exe

from Tkinter import *
import ImageTk, Image

root = Tk()
root.title('HADOUKEN!')

def killwindow():
  root.destroy()

text = Text(root, height=16, width=40)
scroll = Scrollbar(root, command=text.yview)

text.configure(yscrollcommand=scroll.set)

text.grid(sticky=E)
scroll.grid(row=0,column=1,sticky='ns')

text.focus()

chkvar = IntVar()
chkvar.set(0)
c = Checkbutton(root, text="CaseIt", variable=chkvar)
c.grid(row=1,column=0,sticky=W)

v = ""
radio1 = Radiobutton(root, text="Src", variable=v, value=1)
radio1.grid(row=1,column=0)
radio1.focus()

radio2 = Radiobutton(root, text="Dst", variable=v, value=2)
radio2.grid(row=2,column=0)

b1 = Button(root, text="Submit", command=killwindow)
b1.grid(row=1, column=2)

img = ImageTk.PhotoImage(Image.open("Hadoken.gif"))
panel = Label(root, image = img)
panel.grid(row=0, column=2)

root.mainloop()

tk1 = text.get(text)
tk2 = chkvar.get(chkvar)
tk3 = v.get(v)

print tk1
print tk2
print tk3
</code>```

答:
The program didn't make it through the variable getting, so it never reported the incorrect method calls.  I made a few changes to the original code (added a textval StringVar,  and changed the v variable to another IntVar).  I had a feeling the "associated variables" wouldn't have a problem, and didn't need to be included in the killwindow code.  The only variable I grab in killwindow is the text data.

Working code (changed lines marked with #++) :

```<code>#!C:/Python27/python.exe

from Tkinter import *
import ImageTk, Image

root = Tk()
root.title('HADOUKEN!')

textval = StringVar() #++ added

def killwindow():
    textval.set(text.get('1.0',END)) #++ grab contents before destruction
    root.destroy()

text = Text(root, height=16, width=40)
scroll = Scrollbar(root, command=text.yview)

text.configure(yscrollcommand=scroll.set)

text.grid(sticky=E)
scroll.grid(row=0,column=1,sticky='ns')

text.focus()

chkvar = IntVar()
chkvar.set(0)
c = Checkbutton(root, text="CaseIt", variable=chkvar)
c.grid(row=1,column=0,sticky=W)

v = IntVar() #++ changed
v.set(1) #++ initial value
radio1 = Radiobutton(root, text="Src", variable=v, value=1)
radio1.grid(row=1,column=0)
radio1.focus()

radio2 = Radiobutton(root, text="Dst", variable=v, value=2)
radio2.grid(row=2,column=0)

b1 = Button(root, text="Submit", command=killwindow)
b1.grid(row=1, column=2)

img = ImageTk.PhotoImage(Image.open("Hadoken.gif"))
panel = Label(root, image = img)

panel.grid(row=0, column=2)

root.mainloop()

# windows are destroyed at this point

tk1 = textval.get() #++ changed
tk2 = chkvar.get() #++ changed
tk3 = v.get() #++ changed

print tk1
print tk2
print tk3
</code>```

Body:
I am getting the error mentioned in the title of the post I really just want this to work.  Been working on this problem for a while now and it is frustrating.  My ultimate goal is to obtain the values for the varables text, chkvar, and v.

Thanks to anyone who can reply and help on this!!

#!C:/Python27/python.exe

from Tkinter import *
import ImageTk, Image

root = Tk()
root.title('HADOUKEN!')

def killwindow():
  root.destroy()

text = Text(root, height=16, width=40)
scroll = Scrollbar(root, command=text.yview)

text.configure(yscrollcommand=scroll.set)

text.grid(sticky=E)
scroll.grid(row=0,column=1,sticky='ns')

text.focus()

chkvar = IntVar()
chkvar.set(0)
c = Checkbutton(root, text="CaseIt", variable=chkvar)
c.grid(row=1,column=0,sticky=W)

v = ""
radio1 = Radiobutton(root, text="Src", variable=v, value=1)
radio1.grid(row=1,column=0)
radio1.focus()

radio2 = Radiobutton(root, text="Dst", variable=v, value=2)
radio2.grid(row=2,column=0)

b1 = Button(root, text="Submit", command=killwindow)
b1.grid(row=1, column=2)

img = ImageTk.PhotoImage(Image.open("Hadoken.gif"))
panel = Label(root, image = img)
panel.grid(row=0, column=2)

root.mainloop()

tk1 = text.get(text)
tk2 = chkvar.get(chkvar)
tk3 = v.get(v)

print tk1
print tk2
print tk3

Body:
The program didn't make it through the variable getting, so it never reported the incorrect method calls.  I made a few changes to the original code (added a textval StringVar,  and changed the v variable to another IntVar).  I had a feeling the "associated variables" wouldn't have a problem, and didn't need to be included in the killwindow code.  The only variable I grab in killwindow is the text data.

Working code (changed lines marked with #++) :

#!C:/Python27/python.exe

from Tkinter import *
import ImageTk, Image

root = Tk()
root.title('HADOUKEN!')

textval = StringVar() #++ added

def killwindow():
    textval.set(text.get('1.0',END)) #++ grab contents before destruction
    root.destroy()

text = Text(root, height=16, width=40)
scroll = Scrollbar(root, command=text.yview)

text.configure(yscrollcommand=scroll.set)

text.grid(sticky=E)
scroll.grid(row=0,column=1,sticky='ns')

text.focus()

chkvar = IntVar()
chkvar.set(0)
c = Checkbutton(root, text="CaseIt", variable=chkvar)
c.grid(row=1,column=0,sticky=W)

v = IntVar() #++ changed
v.set(1) #++ initial value
radio1 = Radiobutton(root, text="Src", variable=v, value=1)
radio1.grid(row=1,column=0)
radio1.focus()

radio2 = Radiobutton(root, text="Dst", variable=v, value=2)
radio2.grid(row=2,column=0)

b1 = Button(root, text="Submit", command=killwindow)
b1.grid(row=1, column=2)

img = ImageTk.PhotoImage(Image.open("Hadoken.gif"))
panel = Label(root, image = img)

panel.grid(row=0, column=2)

root.mainloop()

# windows are destroyed at this point

tk1 = textval.get() #++ changed
tk2 = chkvar.get() #++ changed
tk3 = v.get() #++ changed

print tk1
print tk2
print tk3