问:
Why does my promise chain not run sequentially when I use an exported module, but it does when I don't export the module?
I'm trying to get data as a csv from a URL in one file, and then convert that csv in another javascript file to a JSON object using a promise chain. The problem is, it's trying to convert the csv to json before the callback has actually retrieved the csv.

(Note: I realise I'm using the request library which is now deprecated, and will change it once I have the promise chain working).

File 1 (getting the csv data from the url) is below. I need to poll the url until it's populated with the data (usually takes about 5 mins - there are authentication steps beforehand, but they work fine so I'm omitting them to simplify this.) This returns a promise, which is exported as get_csv(). The promise resolves for a csv string.

```<code>const request = require('request');

const csv_url = foo;

module.exports.get_csv = () => {
  return new Promise ((resolve, reject) => {
    function poll_url () {
      request.get({url: csv_url
      }, (error, response, body) => {
        if (error) console.error(error);
        data_csv = body;
        if (data_csv === ''){
          console.log("data_csv is blank.");
        } else {
          clearInterval(intervalID);
          console.log("data_csv has been populated!");
          resolve(data_csv);
        }
      })
    }

    pollURL()
    var intervalID = setInterval(poll_url, 60000);
  })
};
</code>```

JS file 2 (changing the csv data to json) is below. It's meant to just add a .then() to the promise from file 1, which would transform the data from csv to json and then console.log() the json data.

```<code>const data = require('./get_csv_data');   // File 1
const csv = require('csvtojson');

new Promise ((resolve, reject) => {
  const data_csv_string = data.get_csv()
  resolve(data_csv_string);
})

.then(
  (data_csv_string) => {
    console.log(data_csv_string);                        // for debugging - giving undefined
    csv({output: "json"}).fromString(data_csv_string)    // "Cannot read property 'toString' of undefined"
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)
</code>```

The problem is the .then() of file 2 doesn't wait for the first promise's callback to be completed. The console prints out:

```<code>undefined
(node:10691) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'toString' of undefined
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv has been populated!
</code>```

What I can't wrap my head around is, if I put the .then() clause below at the end of File 1, it does work. What am I doing wrong?

```<code>.then(
  (data_csv_string) => {
    console.log(data_csv_string);
    csv({output: "json"}).fromString(data_csv_string)
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)
</code>```

答:
This block

```<code>new Promise ((resolve, reject) => {
  const data_csv_string = data.get_csv()
  resolve(data_csv_string);
})
.then(
</code>```

is wrong. If you want to wrap something (possibly a promise, possibly a value) within a promise, do

```<code>Promise.resolve(data.get_csv())
    .then(//...
</code>```

But, as you know that data.get_csv() already returns a promise, there's no need for that. Just replace your Promise constructor with

```<code>data.get_csv()
    .then(//...
</code>```

And by the way, there's a Node util for promisifying callback-based functions: util.promisify.

Body:
I'm trying to get data as a csv from a URL in one file, and then convert that csv in another javascript file to a JSON object using a promise chain. The problem is, it's trying to convert the csv to json before the callback has actually retrieved the csv.

(Note: I realise I'm using the request library which is now deprecated, and will change it once I have the promise chain working).

File 1 (getting the csv data from the url) is below. I need to poll the url until it's populated with the data (usually takes about 5 mins - there are authentication steps beforehand, but they work fine so I'm omitting them to simplify this.) This returns a promise, which is exported as get_csv(). The promise resolves for a csv string.

const request = require('request');

const csv_url = foo;

module.exports.get_csv = () => {
  return new Promise ((resolve, reject) => {
    function poll_url () {
      request.get({url: csv_url
      }, (error, response, body) => {
        if (error) console.error(error);
        data_csv = body;
        if (data_csv === ''){
          console.log("data_csv is blank.");
        } else {
          clearInterval(intervalID);
          console.log("data_csv has been populated!");
          resolve(data_csv);
        }
      })
    }

    pollURL()
    var intervalID = setInterval(poll_url, 60000);
  })
};

JS file 2 (changing the csv data to json) is below. It's meant to just add a .then() to the promise from file 1, which would transform the data from csv to json and then console.log() the json data.

const data = require('./get_csv_data');   // File 1
const csv = require('csvtojson');

new Promise ((resolve, reject) => {
  const data_csv_string = data.get_csv()
  resolve(data_csv_string);
})

.then(
  (data_csv_string) => {
    console.log(data_csv_string);                        // for debugging - giving undefined
    csv({output: "json"}).fromString(data_csv_string)    // "Cannot read property 'toString' of undefined"
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)

The problem is the .then() of file 2 doesn't wait for the first promise's callback to be completed. The console prints out:

undefined
(node:10691) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'toString' of undefined
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv is blank.
data_csv has been populated!

What I can't wrap my head around is, if I put the .then() clause below at the end of File 1, it does work. What am I doing wrong?

.then(
  (data_csv_string) => {
    console.log(data_csv_string);
    csv({output: "json"}).fromString(data_csv_string)
    .then((data_json_string) => {
      console.log(data_json_string);
    })
  }
)

Body:
This block

new Promise ((resolve, reject) => {
  const data_csv_string = data.get_csv()
  resolve(data_csv_string);
})
.then(

is wrong. If you want to wrap something (possibly a promise, possibly a value) within a promise, do

Promise.resolve(data.get_csv())
    .then(//...

But, as you know that data.get_csv() already returns a promise, there's no need for that. Just replace your Promise constructor with

data.get_csv()
    .then(//...

And by the way, there's a Node util for promisifying callback-based functions: util.promisify.


来源: stackexchange

问:
How to share video on WhatsApp without using UIActivityViewController?
I am currently trying to enable the functionality to share a video on WhatsApp but without using UIActivityViewController, as Tik Tok does for example. When you click on "share" on WhatsApp, it directly redirects you to WhatsApp and contacts pop up so that you can share the video.

I kinda succeeded in sharing it but with ActivityViewController, this way:

```<code> let path = Bundle.main.url(forResource: "Rap God", withExtension: "mp4")!.relativePath
 let fileUrl = NSURL(fileURLWithPath: path)
 controller = UIDocumentInteractionController(url: fileUrl as URL)
 controller.uti = "net.whatsapp.movie"
 controller.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
</code>```

I would be glad to know someone can help me out.

答:
Try using UIApplication's canOpenURL(_:) and open(_:options:completionHandler:),

```<code>let urlString = "https://stackoverflow.com/questions/60282744/how-to-share-video-on-whatsapp-without-using-uiactivityviewcontroller"
let shareString = "whatsapp://send?text=\(urlString)"
if let url = URL(string: shareString), UIApplication.shared.canOpenURL(url)  {
    UIApplication.shared.open(url, options: [:]) { (completed) in
        print(completed)
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am currently trying to enable the functionality to share a video on WhatsApp but without using UIActivityViewController, as Tik Tok does for example. When you click on "share" on WhatsApp, it directly redirects you to WhatsApp and contacts pop up so that you can share the video.

I kinda succeeded in sharing it but with ActivityViewController, this way:

 let path = Bundle.main.url(forResource: "Rap God", withExtension: "mp4")!.relativePath
 let fileUrl = NSURL(fileURLWithPath: path)
 controller = UIDocumentInteractionController(url: fileUrl as URL)
 controller.uti = "net.whatsapp.movie"
 controller.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)

I would be glad to know someone can help me out.

Body:
Try using UIApplication's canOpenURL(_:) and open(_:options:completionHandler:),

let urlString = "https://stackoverflow.com/questions/60282744/how-to-share-video-on-whatsapp-without-using-uiactivityviewcontroller"
let shareString = "whatsapp://send?text=\(urlString)"
if let url = URL(string: shareString), UIApplication.shared.canOpenURL(url)  {
    UIApplication.shared.open(url, options: [:]) { (completed) in
        print(completed)
    }
}


问:
How to iterate over a nested Ruby hash to add a new key/value pair based on existing key/value data?

I have a nested hash of data:

```<code>munsters = {
  "Herman" => { "age" => 32, "gender" => "male" },
  "Lily" => { "age" => 30, "gender" => "female" },
  "Grandpa" => { "age" => 402, "gender" => "male" },
  "Eddie" => { "age" => 10, "gender" => "male" },
  "Marilyn" => { "age" => 23, "gender" => "female"}
}
</code>```

I want to loop through the hash for each member and look up their age in the nested hash.

For each member, I want to add a new key/value pair to the existing nested hash called "age_group".

The value of each member's "age_group" will be dependent on their age. For example, if the age is above 65 years I want to have their age_group read "senior", etc.

Problems I'm running into:

I'm confused how I would access just the "age" key_value pair of the nested hash when the first key is different for each member of the family. Meaning, I can't do something like munsters["age"] because that returns nil (assuming because "age" is nested).

If I had a simple (un-nested) hash it's pretty straightforward. Example of a non-nested hash:

```<code>ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }
</code>```

I would then likely loop though like this:

```<code>age_group = {}

ages.each do |k, v|
  if v >= 65
    puts "#{k}'s age of #{v} makes them a senior!"
    age_group.merge!("age_group": "senior")
  elsif v > 17 && v < 65
    puts "#{k}'s age of #{v} makes them an adult"
    age_group.merge!("age_group": "adult")
  else
    puts "#{k}'s age of #{v} makes them a kid."
    age_group.merge!("age_group": "kid")
  end
end
</code>```

For the nested hash, I'm able to access the entire nested hash like this:

```<code>munsters.each do |k, v|
  v.each do |k2, v2|
    p "k2 is #{k2} and v2 is #{v2}"
  end
end
</code>```

But that still only returns the entire nested hash to the console instead of just the age:

k2 is age and v2 is 32
k2 is gender and v2 is male
```

答:
In addition to @MurifoX answer, you can use #transform_values

```<code>ages.transform_values do |value|
  if value["age"] >= 65
    value["age_group"] = "senior"
  elsif value["age"] > 17 && value["age"] < 65
    value["age_group"] = "adult"
  else
    value["age_group"] = "kid"
  end
end
</code>```

Body:
I have a nested hash of data:

munsters = {
  "Herman" => { "age" => 32, "gender" => "male" },
  "Lily" => { "age" => 30, "gender" => "female" },
  "Grandpa" => { "age" => 402, "gender" => "male" },
  "Eddie" => { "age" => 10, "gender" => "male" },
  "Marilyn" => { "age" => 23, "gender" => "female"}
}

I want to loop through the hash for each member and look up their age in the nested hash.

For each member, I want to add a new key/value pair to the existing nested hash called "age_group".

The value of each member's "age_group" will be dependent on their age. For example, if the age is above 65 years I want to have their age_group read "senior", etc.

Problems I'm running into:

I'm confused how I would access just the "age" key_value pair of the nested hash when the first key is different for each member of the family. Meaning, I can't do something like munsters["age"] because that returns nil (assuming because "age" is nested).

If I had a simple (un-nested) hash it's pretty straightforward. Example of a non-nested hash:

ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }

I would then likely loop though like this:

age_group = {}

ages.each do |k, v|
  if v >= 65
    puts "#{k}'s age of #{v} makes them a senior!"
    age_group.merge!("age_group": "senior")
  elsif v > 17 && v < 65
    puts "#{k}'s age of #{v} makes them an adult"
    age_group.merge!("age_group": "adult")
  else
    puts "#{k}'s age of #{v} makes them a kid."
    age_group.merge!("age_group": "kid")
  end
end

For the nested hash, I'm able to access the entire nested hash like this:

munsters.each do |k, v|
  v.each do |k2, v2|
    p "k2 is #{k2} and v2 is #{v2}"
  end
end

But that still only returns the entire nested hash to the console instead of just the age:

k2 is age and v2 is 32
k2 is gender and v2 is male

Body:
In addition to @MurifoX answer, you can use #transform_values

ages.transform_values do |value|
  if value["age"] >= 65
    value["age_group"] = "senior"
  elsif value["age"] > 17 && value["age"] < 65
    value["age_group"] = "adult"
  else
    value["age_group"] = "kid"
  end
end


问:
Video still playing when bootstrap modal closes
Modal window is closed, but the video keeps playing. I want to stop video when the modal window is closed.

I tried different ways, with a YouTube video and Vimeo it's work, but it's doesn't with MP4.

$(document).ready(function() {
  var $videoSrc;
  $(".video-btn").click(function() {
$videoSrc = $(this).data("src");
  });
  console.log($videoSrc);
  $("#myModal").on("shown.bs.modal", function(e) {
$("#video").attr(
  "src",
  $videoSrc + "?autoplay=1&modestbranding=1&showinfo=0"
);
  });
  $("#myModal").on("hide.bs.modal", function(e) {
   $("#video").attr("src", $videoSrc);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <img src="https://tinyjpg.com/images/social/website.jpg?v=1&quality=80&format=jpeg" class="video-btn" data-toggle="modal" data-src="https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4"  data-target="#myModal">

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                    <!-- 16:9 aspect ratio -->
                    <div class="embed-responsive embed-responsive-16by9">
                        <iframe class="embed-responsive-item" src="" id="video"   allow="autoplay"></iframe>
                    </div>
                </div>
</body>
</html></code>```

答:
On modal hide you again adding the video source, as the $videoSrc variable holds the video link. You should remove the video source on hide.

Working Example.

$(document).ready(function() {
  var $videoSrc;
  $(".video-btn").click(function() {
    $videoSrc = $(this).data("src");
  });
  $("#myModal").on("shown.bs.modal", function(e) {
    $("#video").attr(
      "src",
      $videoSrc + "?autoplay=1&modestbranding=1&showinfo=0"
    );
  });
  $("#myModal").on("hide.bs.modal", function(e) {
    $("#video").attr("src", ""); // Remove the video source.
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <img src="https://tinyjpg.com/images/social/website.jpg?v=1&quality=80&format=jpeg" class="video-btn" data-toggle="modal" data-src="https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4"  data-target="#myModal">

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                    <!-- 16:9 aspect ratio -->
                    <div class="embed-responsive embed-responsive-16by9">
                        <iframe class="embed-responsive-item" src="" id="video"   allow="autoplay"></iframe>
                    </div>
                </div>
</body>
</html></code>```

Body:
Modal window is closed, but the video keeps playing. I want to stop video when the modal window is closed.

I tried different ways, with a YouTube video and Vimeo it's work, but it's doesn't with MP4.

$(document).ready(function() {
  var $videoSrc;
  $(".video-btn").click(function() {
$videoSrc = $(this).data("src");
  });
  console.log($videoSrc);
  $("#myModal").on("shown.bs.modal", function(e) {
$("#video").attr(
  "src",
  $videoSrc + "?autoplay=1&modestbranding=1&showinfo=0"
);
  });
  $("#myModal").on("hide.bs.modal", function(e) {
   $("#video").attr("src", $videoSrc);
  });
});

link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

Body:
On modal hide you again adding the video source, as the $videoSrc variable holds the video link. You should remove the video source on hide.

Working Example.

$(document).ready(function() {
  var $videoSrc;
  $(".video-btn").click(function() {
    $videoSrc = $(this).data("src");
  });
  $("#myModal").on("shown.bs.modal", function(e) {
    $("#video").attr(
      "src",
      $videoSrc + "?autoplay=1&amp;modestbranding=1&amp;showinfo=0"
    );
  });
  $("#myModal").on("hide.bs.modal", function(e) {
    $("#video").attr("src", ""); // Remove the video source.
  });
});

<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <img src="https://tinyjpg.com/images/social/website.jpg?v=1&quality=80&format=jpeg" class="video-btn" data-toggle="modal" data-src="https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4"  data-target="#myModal">

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <!-- 16:9 aspect ratio -->
                    <div class="embed-responsive embed-responsive-16by9">
                        <iframe class="embed-responsive-item" src="" id="video"   allow="autoplay"></iframe>
                    </div>
                </div>
</body>
</html>


问:
Time since in php dateTime object in seconds

Possible Duplicate:

  Date to timestamp (PHP)?

How do I get the current time in seconds since 1st january 1970 in php?

does the dateTime object support anything since as

```<code>$date1 = new DateTime("01/01/1970");
$return = since($date1, date.now());
</code>```

The problem I get here is I could just do something like ((minutes=hours *60)*60)

Is there a nicer way?

答:
You can use the time() function:
http://php.net/manual/en/function.time.php

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  Date to timestamp (PHP)?

How do I get the current time in seconds since 1st january 1970 in php?

does the dateTime object support anything since as

$date1 = new DateTime("01/01/1970");
$return = since($date1, date.now());

The problem I get here is I could just do something like ((minutes=hours *60)*60)

Is there a nicer way?


问:
Display a ArrayList with in a JList (Swing)
I'm having an issue when I try to display a JList with an ArrayList. I'm using Action Listeners to execute all this:

```<code>ContactArray contactObject = new ContactArray();
</code>```

```<code>addContactBtn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String firstName = firstNameField.getText();
        String lastName = lastNameField.getText();
        contactObject.addName(firstName + " " + lastName);
        // contactObject.getNames().forEach(System.out::println);
    }
});
viewContactButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String[] contacts = contactObject.getNames().toArray(new String[0]);
        contactList = new JList(contacts);
        contactList.setVisibleRowCount(5);
        contactList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(new JScrollPane(contactList));
    }
});
</code>```

ContactArray class:

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ContactArray {

    private List<String> names;

    public ContactArray() {
        this.names = new ArrayList<>();
    }

    //add a name to list
    public void addName(String name) {
        if (!Objects.nonNull(names)) {
            this.names = new ArrayList<>();
        }
        this.names.add(name);
    }

    //get the name attribute
    public List<String> getNames() {
        if (!Objects.nonNull(names)) {
            this.names = new ArrayList<>();
        }
        return this.names;
    }

}
</code>```

I have managed to print the full names to the console with contactObject.getNames().forEach(System.out::println);which I put in comments, but can't seem to add them to JList. Normally, when I press on viewContactButton, it should display it.

Also, I'm using the Swing GUI form from IntelliJ IDEA.

Thanks for any help :)

答:
I have managed to print the full names to the console

Well, you placed that code in the wrong place. The code should be placed when you actually use the List to create the JList. (ie. Maybe you have code somewhere that accidentally deletes the List sometime after it is created and before it is used)

I'm having an issue when I try to display a JList with an ArrayList

Well is the problem the ArrayList or did you also try to hardcode data in the JList? In order to solve a problem you need to know what the real problem is. Always first try to display hard coded data instead of dynamic data.

```<code>add(new JScrollPane(contactList));
</code>```

I would guess the real problem is the above statement.

Whenever you add components to a visible frame the basic code should be:

```<code>add(...);
revalidate();
repaint();
</code>```

You need to invoke the layout manager of the panel. Otherwise the component has a size of 0, so there is nothing to paint.

Body:
I'm having an issue when I try to display a JList with an ArrayList. I'm using Action Listeners to execute all this:

ContactArray contactObject = new ContactArray();

addContactBtn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String firstName = firstNameField.getText();
        String lastName = lastNameField.getText();
        contactObject.addName(firstName + " " + lastName);
        // contactObject.getNames().forEach(System.out::println);
    }
});
viewContactButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String[] contacts = contactObject.getNames().toArray(new String[0]);
        contactList = new JList(contacts);
        contactList.setVisibleRowCount(5);
        contactList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(new JScrollPane(contactList));
    }
});

ContactArray class:

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ContactArray {

    private List<String> names;

    public ContactArray() {
        this.names = new ArrayList<>();
    }

    //add a name to list
    public void addName(String name) {
        if (!Objects.nonNull(names)) {
            this.names = new ArrayList<>();
        }
        this.names.add(name);
    }

    //get the name attribute
    public List<String> getNames() {
        if (!Objects.nonNull(names)) {
            this.names = new ArrayList<>();
        }
        return this.names;
    }

}

I have managed to print the full names to the console with contactObject.getNames().forEach(System.out::println);which I put in comments, but can't seem to add them to JList. Normally, when I press on viewContactButton, it should display it.

Also, I'm using the Swing GUI form from IntelliJ IDEA.

Thanks for any help :)

Body:
I have managed to print the full names to the console

Well, you placed that code in the wrong place. The code should be placed when you actually use the List to create the JList. (ie. Maybe you have code somewhere that accidentally deletes the List sometime after it is created and before it is used)

I'm having an issue when I try to display a JList with an ArrayList

Well is the problem the ArrayList or did you also try to hardcode data in the JList? In order to solve a problem you need to know what the real problem is. Always first try to display hard coded data instead of dynamic data.

add(new JScrollPane(contactList));

I would guess the real problem is the above statement.

Whenever you add components to a visible frame the basic code should be:

add(...);
revalidate();
repaint();

You need to invoke the layout manager of the panel. Otherwise the component has a size of 0, so there is nothing to paint.


问:
Remove squiggly lines from displaying for Prettier/ESlint
How to remove squiggly lines from showing on VS Code for ESlint & Prettier setup. I want ESlint to do its work, format and fix errors on save but don't want to see the squiggly lines. Not sure if its even possible as I couldn't find any info on this. Looks like Prettier is causing all the unwanted squiggly lines</p>

答:
See this answer here. You edit settings.json and set "eslint.enable": false in VS Code. There is an extension that does it too.

This disables it in VS Code. Then you run eslint as a background task using https://www.npmjs.com/package/eslint-watch or similar.


问:
MSTest .trx file display using Xunit Plugin and Jenkins Piepline
I'm trying to display MStest, Nunit3, Nunit2 results using Xunit Plugin and using Jenkins pipeline and have not been successful with the same.
I can't find proper documentation for the Xunit Plugin and all the various required parameters for the same.

I got the following links but they don't help much
https://www.cloudbees.com/blog/xunit-and-pipeline
https://wiki.jenkins.io/display/JENKINS/xUnit+Plugin

Does anyone know how to use the Xunit Plugin for displaying mstest, nunit3 and nunit2 results in jenkins pipeline?

Following is the code I used for MStest report parsing and got errors.
I'm pretty new to pipelines in Jenkins and any help / pointers are greatly appreciated! Thanks in advance!!

Following is my pipeline code

```<code>pipeline {
    agent any
    stages {
        stage('Copy Test Reports') {
            agent {
                node {
                    label 'test'
                    customWorkspace "C:\\jenkins\\workspace\\tests"
                }
            }
            steps {
                echo 'Hello world!'
                bat '''copy \\\\Precheck.xml .
                copy \\\\*.trx .'''
            }
            post {
                always {
                    xunit (
                        thresholds: [$class: 'FailedThreshold', unstableThreshold: '1'],
                        tools: [$class: 'MSTest', pattern: '*.trx']
                    )
                }
            }
        }
    }
}

Error:
Missing required parameter: "thresholdMode" @ line 19, column 21.
                       xunit (
                       ^

WorkflowScript: 19: Missing required parameter: "testTimeMargin" @ line 19, column 21.
                       xunit (
                       ^
</code>```

答:
I had to do it a little differently with the plugin so I'm posting my solution in case it helps -

```<code>xunit(
    [MSTest(deleteOutputFiles: true,
            failIfNotNew: true,
            pattern: '*.trx',
            skipNoTestFiles: false,
            stopProcessingIfError: true)
    ])
</code>```

Note, this expects that your trx files are in the root of your workspace.  If they aren't you'll need to copy them into there.

Body:
I'm trying to display MStest, Nunit3, Nunit2 results using Xunit Plugin and using Jenkins pipeline and have not been successful with the same.
I can't find proper documentation for the Xunit Plugin and all the various required parameters for the same.

I got the following links but they don't help much
https://www.cloudbees.com/blog/xunit-and-pipeline
https://wiki.jenkins.io/display/JENKINS/xUnit+Plugin

Does anyone know how to use the Xunit Plugin for displaying mstest, nunit3 and nunit2 results in jenkins pipeline?

Following is the code I used for MStest report parsing and got errors.
I'm pretty new to pipelines in Jenkins and any help / pointers are greatly appreciated! Thanks in advance!!

Following is my pipeline code

pipeline {
    agent any
    stages {
        stage('Copy Test Reports') {
            agent {
                node {
                    label 'test'
                    customWorkspace "C:\\jenkins\\workspace\\tests"
                }
            }
            steps {
                echo 'Hello world!'
                bat '''copy \\\\Precheck.xml .
                copy \\\\*.trx .'''
            }
            post {
                always {
                    xunit (
                        thresholds: [$class: 'FailedThreshold', unstableThreshold: '1'],
                        tools: [$class: 'MSTest', pattern: '*.trx']
                    )
                }
            }
        }
    }
}

Error:
Missing required parameter: "thresholdMode" @ line 19, column 21.
                       xunit (
                       ^

WorkflowScript: 19: Missing required parameter: "testTimeMargin" @ line 19, column 21.
                       xunit (
                       ^

Body:
I had to do it a little differently with the plugin so I'm posting my solution in case it helps -

xunit(
    [MSTest(deleteOutputFiles: true,
            failIfNotNew: true,
            pattern: '*.trx',
            skipNoTestFiles: false,
            stopProcessingIfError: true)
    ])

Note, this expects that your trx files are in the root of your workspace.  If they aren't you'll need to copy them into there.


问:
Why does itoa expect a signed character instead of an unsigned?
Learning embedded C while working in MPLAB X with a PIC24FJ128GB204.

So far, I've mostly heard that you should use unsigned types as much as possible (especially?) on embedded devices, so I've started to use uint8_t arrays to hold strings. However, if I call itoa from stdlib.h, it expects a pointer to a signed char (int8_t) array:

extern char *    itoa(char * buf, int val, int base);

This is made specifically clear when I try to compile after using itoa on an unsigned array:

```<code>main.c:317:9: warning: pointer targets in passing argument 1 of 'itoa' differ in signedness
c:\program files (x86)\microchip\xc16\v1.36\bin\bin\../..\include/stdlib.h:131:15: note: expected 'char *' but argument is of type 'unsigned char *'
</code>```

Searching for implementations of itoa on other platforms, that seems to be the common case.

Why is that?

(I've also noticed that most implementations expect value/pointer/radix whereas -for some reason- the stdlib.h from Microchip expects the pointer first. It took me a while to realize this.)

答:
char as signed or unsigned is a compromise of decades ago -  It made sense then to bring a level of consistency to compilers of the day.

itoa(), although not a standard C library function, follows that convention, in that the string is made up of char.

Many library functions use a string pointer.  itoa() does too and handles the internal workings as unsigned char.  Keep in mind, a string is to represent text, not numbers - so the signedness of the char in itself is not a great concern.  Of course the point of itoa() is to take a number (int) and form a string.

The C library treats char functionally "as if" it were unsigned char in many cases.

int fgetc() returns a value of EOF or in the unsigned char range.

printf()  "%c": "the int argument is converted to an unsigned char, and
the resulting character is written."

<string.h> "For all functions in this subclause, each character shall be interpreted as if it had the type unsigned char (and therefore every possible object representation is valid and has a different value)."

<ctype.h> "In all cases the argument is an int, the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF.

Body:
Learning embedded C while working in MPLAB X with a PIC24FJ128GB204.

So far, I've mostly heard that you should use unsigned types as much as possible (especially?) on embedded devices, so I've started to use uint8_t arrays to hold strings. However, if I call itoa from stdlib.h, it expects a pointer to a signed char (int8_t) array:

extern char *    itoa(char * buf, int val, int base);

This is made specifically clear when I try to compile after using itoa on an unsigned array:

main.c:317:9: warning: pointer targets in passing argument 1 of 'itoa' differ in signedness
c:\program files (x86)\microchip\xc16\v1.36\bin\bin\../..\include/stdlib.h:131:15: note: expected 'char *' but argument is of type 'unsigned char *'

Searching for implementations of itoa on other platforms, that seems to be the common case.

Why is that?

(I've also noticed that most implementations expect value/pointer/radix whereas -for some reason- the stdlib.h from Microchip expects the pointer first. It took me a while to realize this.)


问:
How to configure my vim to help me find the definition of terms?
For example, when I encounter:

```<code>funcMiracle (argMagic);
</code>```

I want to press a button, and woosh, I immediately jump to the definition of funcMiracle, regardless of it is in the current file or not.

答:
Install exuberant ctags on your machine. Then, from the command line, in your project root:

```<code>ctags -R
</code>```

Pressing ctrl-[ in Vim will then jump to the definition of the symbol. After the jump, ctrl-T will take you back where you just came from.

Body:
For example, when I encounter:

funcMiracle (argMagic);

I want to press a button, and woosh, I immediately jump to the definition of funcMiracle, regardless of it is in the current file or not.

Body:
Install exuberant ctags on your machine. Then, from the command line, in your project root:

ctags -R

Pressing ctrl-[ in Vim will then jump to the definition of the symbol. After the jump, ctrl-T will take you back where you just came from.


问:
refer to range of columns by name in R
I need help with something that might be fairly simple in R. I want to refer to a range of columns in a data frame (e.g., extracting a few select variables). However, I don't know their column numbers. Normally, if I wanted to extract columns 4-10 i would say mydata[,4:10].

However, given that I don't know the column numbers, I would want to refer to them by name. Is there an easy way to do this? in sas or spss it is fairly easy to refer to a range of variables by name. Alternatively, is there an easy way to figure out which column number corresponds to a variable name in R?

答:
You can call the column numbers by their names:

```<code>set.seed(1234)
> mydf <- data.frame(A = runif(5, 1, 2),
                     + B = runif(5, 3, 4),
                     + C = runif(5, 5, 6),
                     + D = runif(5, 7, 8),
                     + E = runif(5, 9, 10))
> mydf
mydf[c(match("A", names(mydf)):match("B", names(mydf)))]
         A        B
1 1.113703 3.640311
2 1.622299 3.009496
3 1.609275 3.232551
4 1.623379 3.666084
5 1.860915 3.514251
</code>```

Here you can see that the match()-call actually gives the column number:

```<code>> c(match("A", names(mydf)):match("B", names(mydf)))
[1] 1 2
</code>```

I hope this is also helpful, it is similar to Neal's answer.

Title: refer to range of columns by name in R

Body:
You can call the column numbers by their names:

set.seed(1234)
> mydf <- data.frame(A = runif(5, 1, 2),
                     + B = runif(5, 3, 4),
                     + C = runif(5, 5, 6),
                     + D = runif(5, 7, 8),
                     + E = runif(5, 9, 10))
> mydf
mydf[c(match("A", names(mydf)):match("B", names(mydf)))]
         A        B
1 1.113703 3.640311
2 1.622299 3.009496
3 1.609275 3.232551
4 1.623379 3.666084
5 1.860915 3.514251

Here you can see that the match()-call actually gives the column number:

> c(match("A", names(mydf)):match("B", names(mydf)))
[1] 1 2

I hope this is also helpful, it is similar to Neal's answer.


问:
Azure DevOps wait until another build in same CI is done
Is there any way of making the build in VSTS/Azure DevOps wait until another build in the same CI is done. I want to be able to use the Hosted agent but be able to do that. I don't want to use my own agent. </p>

答:
If you are using Classic way of configuring Azure Pipelines (Not using YAML),

then you may try to add Agent.Name equals "One of the available Agent name" condition in Demands section.
You will find "Demands" section  where you configure Agent Pool in Azure Pipelines.


问:
Is there a way to make a multiset?
Is there a way to create a multiset in python? I have my set here:
{'a', 'u', 'i', 'o', 'e'} but I would like to have repeated characters, but still unorganised. Thanks

答:
This is not possible in python since a set in python is by definition meant to be unique.

You can however install external packages to implement a multiset:

```<code>pip install multiset
</code>```

Title: Is there a way to make a multiset?

Body:
This is not possible in python since a set in python is by definition meant to be unique.

You can however install external packages to implement a multiset:

pip install multiset


问:
list the files with minimum sequence
I have some files in a directory as below (not necessarily sorted):

```<code>A_10
A_20
A_30
B_10
B_30
C_10
C_20
D_20
D_30
E_10
E_20
E_30
</code>```

10, 20 and 30 are the sequence numbers of A,B,C,D,E respectively.

I want to select only those files with minimum sequence of all A,B,C,D,E
the output should be :

```<code>A_10
B_10
C_10
D_20
E_10
</code>```

could anybody help me?

Title: list the files with minimum sequence

Body:
I have some files in a directory as below (not necessarily sorted):

A_10
A_20
A_30
B_10
B_30
C_10
C_20
D_20
D_30
E_10
E_20
E_30

10, 20 and 30 are the sequence numbers of A,B,C,D,E respectively.

I want to select only those files with minimum sequence of all A,B,C,D,E
the output should be :

A_10
B_10
C_10
D_20
E_10

could anybody help me?

Body:
perl -le '
  print join $/,
    grep !$_{( split "_" )[0]}++,
      sort glob "*_*"
  '

or:

printf '%s\n' *_* | sort | awk -F_ '!_[$1]++'

or:

printf '%s\n' *_* | sort -t_ -uk1,1


问:
Calculate maximum of column values with common value in another column in PostgreSQL
I am trying to calculalate maximum of column values with common id.

I have following table as input

```<code>TABLE 1:

| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA502 | abcdef | 2.2   |
| UA504 | yzab   | 8.8   |
| UA504 | lmnop  | 2.8   |
| UA503 | uvwx   | 8.6   |
| UA503 | ghijk  | 2.6   |

</code>```

The desired output is:

```<code>| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA504 | yzab   | 8.8   |
| UA503 | uvwx   | 8.6   |
</code>```

I am running following WITH query (max_calc) with groupby and max function on the output of another WITH query (union_data; TABLE 1).

```<code>max_calc as(

  select id, seq, max(score)
  from union_data
  GROUP BY id

  )

select * from max_calc
;

</code>```

The error I am getting is:

```<code> Query Error: error: column "union_data.seq" must appear in the GROUP BY clause or be used in an aggregate function
</code>```

I do not understand this error. I am grouping the data based on common id not seq. Why I should include column "union_data.seq" in GROUPBY.

Thanks

答:
GMB's answer is the best answer for three columns (and duly upvoted).  If you want more aggregations, though, you can emulate a "first" aggregation function using arrays:</p>

```<code>  select id,
         (array_agg(seq order by score desc))[1] as seq,
         max(score)
  from union_data
  group by id;
</code>```

Body:
I am trying to calculalate maximum of column values with common id.

I have following table as input

TABLE 1:

| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA502 | abcdef | 2.2   |
| UA504 | yzab   | 8.8   |
| UA504 | lmnop  | 2.8   |
| UA503 | uvwx   | 8.6   |
| UA503 | ghijk  | 2.6   |

The desired output is:

| id    | seq    | score |
| ----- | ------ | ----- |
| UA502 | qrst   | 8.2   |
| UA504 | yzab   | 8.8   |
| UA503 | uvwx   | 8.6   |

I am running following WITH query (max_calc) with groupby and max function on the output of another WITH query (union_data; TABLE 1).

max_calc as(

  select id, seq, max(score)
  from union_data
  GROUP BY id

  )

select * from max_calc
;

The error I am getting is:

 Query Error: error: column "union_data.seq" must appear in the GROUP BY clause or be used in an aggregate function

I do not understand this error. I am grouping the data based on common id not seq. Why I should include column "union_data.seq" in GROUPBY.

Thanks

Body:
GMB's answer is the best answer for three columns (and duly upvoted).  If you want more aggregations, though, you can emulate a "first" aggregation function using arrays:

  select id,
         (array_agg(seq order by score desc))[1] as seq,
         max(score)
  from union_data
  group by id;


问:
C# windows form button to execute SQL Query
I'm new to programming so please bear with me as I learn. I've been looking for days for a way to make this work, trying different solutions that I have found on here and other sites. I am using user input to create my connection string, and button 1 works great to verify that a connection has been established, button 2 not so much. I am trying to create a button that once pushed will execute a SQL command and provide the results from the command.

This is what I have so far, its button 2 that I have not been able to get to work yet.

using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp4
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
       }

       private void Form1_Load(object sender, EventArgs e)
       {

       }

       private void textBox1_TextChanged(object sender, EventArgs e)
       {

       }

       private void textBox2_TextChanged(object sender, EventArgs e)
       {

       }

       private void textBox3_TextChanged(object sender, EventArgs e)
       {

       }
       private void textBox4_TextChanged(object sender, EventArgs e)
       {

       }
       private void textBox5_TextChanged(object sender, EventArgs e)
       {

       }

       private void button1_Click(object sender, EventArgs e)
       {
           {
               string ServerName = textBox1.Text;
               string Database = textBox2.Text;
               string Username = textBox3.Text;
               string Pass = textBox4.Text;

               string connetionString;
               SqlConnection cnn;
               connetionString = @"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + ";";
               cnn = new SqlConnection(connetionString);
               try
               {
                   cnn.Open();
                   MessageBox.Show("Connection Open  !");
                   cnn.Close();
               }
               catch (Exception) { MessageBox.Show("Login Failed, Information is Incorrect"); }
           }
       }

       private void button2_Click(object sender, EventArgs e)
       {
           string ServerName = textBox1.Text;
           string Database = textBox2.Text;
           string Username = textBox3.Text;
           string Pass = textBox4.Text;
           string results = textBox5.Text;

           string connetionString;
           SqlConnection cnn;
           connetionString = @"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + ";";
           string userInput = "";
           var process = new Process();
           var startInfo = new ProcessStartInfo();
           startInfo.WindowStyle = ProcessWindowStyle.Hidden;
           startInfo.FileName = "cmd.exe";
           startInfo.Arguments = string.Format(@"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + "; "" SELECT count(*) from participanthistory, SELECT count(*) from postransaction where communicated = 0, userInput);

           process.StartInfo = startInfo;
           process.Start();
       }

       }

   }
```

<p>I am trying to get the button to run this sql:</p>

<pre class="lang-sql prettyprint-override"><code>select count(*) from history
select count(*) from results where communicated = 0
</code>```

I can run the SQL Query in SSMS no problem its just getting it to launch from the GUI I'm creating.

Any help is greatly appreciated.

答:
Something like this, open the connection with the connection string the user imputed, then read the returned rows and their fields   </p>

```<code>SqlDataReader reader = null;
     using (SqlConnection connection = new SqlConnection(_sqlConnectionStringFromUserImput))
                    {
                        connection.Open();
                        if (connection.State == ConnectionState.Open)
                        {
                            SqlCommand sqlCommand =
                                new SqlCommand(
                                    "select count(*) from history",
                                    connection)
                                {
                                    CommandType = CommandType.Text,
                                    CommandTimeout = 20
                                };
                            reader = sqlCommand.ExecuteReader();
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    DateTime datetimefield = reader.GetFieldValue<DateTime>(0);
                                    string stringField = reader.GetFieldValue<string>(1);
                                }
                            }
                            reader.Close();
        }
                        connection.Close();
                    }
</code>```

Body:
I'm new to programming so please bear with me as I learn. I've been looking for days for a way to make this work, trying different solutions that I have found on here and other sites. I am using user input to create my connection string, and button 1 works great to verify that a connection has been established, button 2 not so much. I am trying to create a button that once pushed will execute a SQL command and provide the results from the command.

This is what I have so far, its button 2 that I have not been able to get to work yet.

using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp4
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
       }

       private void Form1_Load(object sender, EventArgs e)
       {

       }

       private void textBox1_TextChanged(object sender, EventArgs e)
       {

       }

       private void textBox2_TextChanged(object sender, EventArgs e)
       {

       }

       private void textBox3_TextChanged(object sender, EventArgs e)
       {

       }
       private void textBox4_TextChanged(object sender, EventArgs e)
       {

       }
       private void textBox5_TextChanged(object sender, EventArgs e)
       {

       }

       private void button1_Click(object sender, EventArgs e)
       {
           {
               string ServerName = textBox1.Text;
               string Database = textBox2.Text;
               string Username = textBox3.Text;
               string Pass = textBox4.Text;

               string connetionString;
               SqlConnection cnn;
               connetionString = @"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + ";";
               cnn = new SqlConnection(connetionString);
               try
               {
                   cnn.Open();
                   MessageBox.Show("Connection Open  !");
                   cnn.Close();
               }
               catch (Exception) { MessageBox.Show("Login Failed, Information is Incorrect"); }
           }
       }

       private void button2_Click(object sender, EventArgs e)
       {
           string ServerName = textBox1.Text;
           string Database = textBox2.Text;
           string Username = textBox3.Text;
           string Pass = textBox4.Text;
           string results = textBox5.Text;

           string connetionString;
           SqlConnection cnn;
           connetionString = @"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + ";";
           string userInput = "";
           var process = new Process();
           var startInfo = new ProcessStartInfo();
           startInfo.WindowStyle = ProcessWindowStyle.Hidden;
           startInfo.FileName = "cmd.exe";
           startInfo.Arguments = string.Format(@"Data Source= " + ServerName + ";Initial Catalog= " + Database + ";User ID=" + Username + ";Password= " + Pass + "; "" SELECT count(*) from participanthistory, SELECT count(*) from postransaction where communicated = 0, userInput);

           process.StartInfo = startInfo;
           process.Start();
       }

       }

   }

I am trying to get the button to run this sql:

select count(*) from history
select count(*) from results where communicated = 0

I can run the SQL Query in SSMS no problem its just getting it to launch from the GUI I'm creating.

Any help is greatly appreciated.

Body:
Something like this, open the connection with the connection string the user imputed, then read the returned rows and their fields

SqlDataReader reader = null;
     using (SqlConnection connection = new SqlConnection(_sqlConnectionStringFromUserImput))
                    {
                        connection.Open();
                        if (connection.State == ConnectionState.Open)
                        {
                            SqlCommand sqlCommand =
                                new SqlCommand(
                                    "select count(*) from history",
                                    connection)
                                {
                                    CommandType = CommandType.Text,
                                    CommandTimeout = 20
                                };
                            reader = sqlCommand.ExecuteReader();
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    DateTime datetimefield = reader.GetFieldValue<DateTime>(0);
                                    string stringField = reader.GetFieldValue<string>(1);
                                }
                            }
                            reader.Close();
        }
                        connection.Close();
                    }


问:
iOS 10 Notification Content Extension: using NSURLSession?
I'm trying to create a new Notification Content Extension in iOS 10 for local notifications where the notification view controller responsible for the content extension downloads an image from the network and renders it in a UIImageView. I have the Notification Content Extension target set up with an appropriate Info.plist and the content extension works beautifully for simple things like rendering a label with some content, for example the sample code that comes in the template:

```<code>func didReceive(_ notification: UNNotification) {
    self.label.text = notification.request.content.body
}
</code>```

However, when I try to introduce NSURLSession (or URLSession in Swift 3) into the mix, the notification content totally fails to load - not even the label gets set anymore:

```<code>func didReceive(_ notification: UNNotification) {

    self.label.text = notification.request.content.body
    let session = URLSession.shared()
    let url = URL(string: "https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World")!

    let task = session.downloadTask(with: url) { (fileURL, response, error) in
        if let path = fileURL?.path {
            DispatchQueue.main.async {
                self.imageView.image = UIImage(contentsOfFile:path)
            }
        }
    }
    task.resume()
}
</code>```

Is the usage of NSURLSession in the notification content extension not allowed? Is my extension possibly being killed before the download completes? If so, how could I ensure that it's not killed so I can download and render the image?

答:
It's actually possible to download images in a Notification Content Extension. However, your code contains two problems:

The URL is not valid.

The fileURL returned by the downloadTask methode is deleted as soon as the function runs out of scope, which is already the case when you try to access the fileURLfrom another thread. Instead it's better to catch the fileURL content in a data variable and use that to produce an image in the main thread

Slightly corrected code:

```<code>guard let url = URL(string: "https://betamagic.nl/images/coredatalab_hero_01.jpg") else {
    return
}

let task = URLSession.shared.downloadTask(with: url) { (fileURL, response, error) in
    if let fileURL = fileURL,
        let data = try? Data(contentsOf: fileURL) {
        DispatchQueue.main.async {
            self.imageView.image = UIImage(data: data)
        }
     }
}
task.resume()
</code>```

Body:
I'm trying to create a new Notification Content Extension in iOS 10 for local notifications where the notification view controller responsible for the content extension downloads an image from the network and renders it in a UIImageView. I have the Notification Content Extension target set up with an appropriate Info.plist and the content extension works beautifully for simple things like rendering a label with some content, for example the sample code that comes in the template:

func didReceive(_ notification: UNNotification) {
    self.label.text = notification.request.content.body
}

However, when I try to introduce NSURLSession (or URLSession in Swift 3) into the mix, the notification content totally fails to load - not even the label gets set anymore:

func didReceive(_ notification: UNNotification) {

    self.label.text = notification.request.content.body
    let session = URLSession.shared()
    let url = URL(string: "https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World")!

    let task = session.downloadTask(with: url) { (fileURL, response, error) in
        if let path = fileURL?.path {
            DispatchQueue.main.async {
                self.imageView.image = UIImage(contentsOfFile:path)
            }
        }
    }
    task.resume()
}

Is the usage of NSURLSession in the notification content extension not allowed? Is my extension possibly being killed before the download completes? If so, how could I ensure that it's not killed so I can download and render the image?

Body:
It's actually possible to download images in a Notification Content Extension. However, your code contains two problems:

The URL is not valid.

The fileURL returned by the downloadTask methode is deleted as soon as the function runs out of scope, which is already the case when you try to access the fileURLfrom another thread. Instead it's better to catch the fileURL content in a data variable and use that to produce an image in the main thread

Slightly corrected code:

guard let url = URL(string: "https://betamagic.nl/images/coredatalab_hero_01.jpg") else {
    return
}

let task = URLSession.shared.downloadTask(with: url) { (fileURL, response, error) in
    if let fileURL = fileURL,
        let data = try? Data(contentsOf: fileURL) {
        DispatchQueue.main.async {
            self.imageView.image = UIImage(data: data)
        }
     }
}
task.resume()


问:
Flutter : Change accent color on runtime
How to change accent color on runtime in flutter?

```<code>Color scolor = Colors.green;
...
...
new MaterialApp(

      theme: new ThemeData(
        brightness: Brightness.light,
        accentColor:  scolor,
        ),
 home: new SetAccentColor());

class SetAccentColor extends StatefulWidget {
  @override
  _SetAccentColor createState() => _SetAccentColor();
}

class _SetAccentColor extends State<SetAccentColor > {
...
...
@override
  Widget build(BuildContext context) {
 return Scaffold(
        body: Builder(
            builder: (context) => Container(
                  child: FutureBuilder<List<ColorDBModel>>(
                          future: ColorDBProvider.db.getAllColorModels(),
                          builder: (BuildContext context, AsyncSnapshot<List<ColorDBModel>> snapshot) {

 if (snapshot.data[0].ColorName == "red")
scolor = Colors.red;
else
scolor = Colors.blue;
...
...
...
}
}
}
</code>```

These are the important parts of the code. But accentColor isnt changing according to the changes in scolor.

答:
you can do using provider package easily.

Make sure you add package in pubspec.yaml file.

```<code>import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ThemeChange extends ChangeNotifier {
  Color accentColor = Colors.green;
  void changeColor(Color color) {
    this.accentColor = color;
    notifyListeners();
  }
}

void main() {
  // for bloc transition trace
  //BlocSupervisor.delegate = SimpleBlocDelegate();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ThemeChange>(
      create: (context) => ThemeChange(),
      child: Consumer<ThemeChange>(builder: (context, themechange, child) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(accentColor: themechange.accentColor),
          initialRoute: '/',
          home: Scaffold(body: HomeWidget()),
        );
      }),
    );
  }
}

class HomeWidget extends StatelessWidget {
  const HomeWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: RaisedButton(
            onPressed: () {
              Provider.of<ThemeChange>(context, listen: false)
                  .changeColor(Colors.teal);
            },
            child: Text("change accent color"),
            color: Provider.of<ThemeChange>(context).accentColor,
          ),
        ),
      ),
    );
  }
}
</code>```

Body:
How to change accent color on runtime in flutter?

Color scolor = Colors.green;
...
...
new MaterialApp(

      theme: new ThemeData(
        brightness: Brightness.light,
        accentColor:  scolor,
        ),
 home: new SetAccentColor());

class SetAccentColor extends StatefulWidget {
  @override
  _SetAccentColor createState() => _SetAccentColor();
}

class _SetAccentColor extends State<SetAccentColor > {
...
...
@override
  Widget build(BuildContext context) {
 return Scaffold(
        body: Builder(
            builder: (context) => Container(
                  child: FutureBuilder<List<ColorDBModel>>(
                          future: ColorDBProvider.db.getAllColorModels(),
                          builder: (BuildContext context, AsyncSnapshot<List<ColorDBModel>> snapshot) {

 if (snapshot.data[0].ColorName == "red")
scolor = Colors.red;
else
scolor = Colors.blue;
...
...
...
}
}
}

These are the important parts of the code. But accentColor isnt changing according to the changes in scolor.

Body:
you can do using provider package easily.

Make sure you add package in pubspec.yaml file.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ThemeChange extends ChangeNotifier {
  Color accentColor = Colors.green;
  void changeColor(Color color) {
    this.accentColor = color;
    notifyListeners();
  }
}

void main() {
  // for bloc transition trace
  //BlocSupervisor.delegate = SimpleBlocDelegate();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ThemeChange>(
      create: (context) => ThemeChange(),
      child: Consumer<ThemeChange>(builder: (context, themechange, child) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(accentColor: themechange.accentColor),
          initialRoute: '/',
          home: Scaffold(body: HomeWidget()),
        );
      }),
    );
  }
}

class HomeWidget extends StatelessWidget {
  const HomeWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Center(
          child: RaisedButton(
            onPressed: () {
              Provider.of<ThemeChange>(context, listen: false)
                  .changeColor(Colors.teal);
            },
            child: Text("change accent color"),
            color: Provider.of<ThemeChange>(context).accentColor,
          ),
        ),
      ),
    );
  }
}


问:
Pass object property as a pointer in javascript
Consider the following script:

```<code>let object = {
    text1: 'this is text1',
    text2: 'this is text2'
}

class Translate {
   constructor() {
     this.localization = null;
     this.lateForTheShow = [];

     init();
   }

   async init() {
      /** Perform an ajax call to fetch a localization file **/
      this.localization = await ajaxCall(...);

      for (let i in this.lateForTheShow) {
         this.translate(this.lateForTheShow[i].originalText, this.lateForTheShow[i].referencedVariable);
      }
   }

   translate(text, &pointer) {
      if (this.localization === null) {
        this.lateForTheShow.push({
             referencedVariable: pointer,
             originalText: text
        });
     } else {
       text = this.localization[text];
     }

     pointer = text;
  }
}

let TranslateObj = new Translate();
TranslateObj.translate(object.text1, object.text1);
</code>```

The above code is not a valid javascript code, because you can't pass pointers to variables in javascript (at least certainly not the PHP way I did pass them). Something like this could be done in PHP although, and I am wondering if something simmilar could be achiavable in javascript, or not?

答: Objects are passed by reference in JavaScript, so make it an object and you have a pointer.</p>

Body:
Consider the following script:

let object = {
    text1: 'this is text1',
    text2: 'this is text2'
}

class Translate {
   constructor() {
     this.localization = null;
     this.lateForTheShow = [];

     init();
   }

   async init() {
      /** Perform an ajax call to fetch a localization file **/
      this.localization = await ajaxCall(...);

      for (let i in this.lateForTheShow) {
         this.translate(this.lateForTheShow[i].originalText, this.lateForTheShow[i].referencedVariable);
      }
   }

   translate(text, &pointer) {
      if (this.localization === null) {
        this.lateForTheShow.push({
             referencedVariable: pointer,
             originalText: text
        });
     } else {
       text = this.localization[text];
     }

     pointer = text;
  }
}

let TranslateObj = new Translate();
TranslateObj.translate(object.text1, object.text1);

The above code is not a valid javascript code, because you can't pass pointers to variables in javascript (at least certainly not the PHP way I did pass them). Something like this could be done in PHP although, and I am wondering if something simmilar could be achiavable in javascript, or not?


问:
Content negotiation ignored when using browser Back button
Here's the situation:

I have a web application which response to a request for a list of resources, lets say:

```<code>/items
</code>```

This is initially requested directly by the web browser by navigating to that path. The browser uses it's standard "Accept" header which includes "text/html" and my application notices this and returns the HTML content for the item list.

Within the returned HTML is some JavaScript (jQuery), which then does an ajax request to retrieve the actual data:

```<code>/items
</code>```

Only this time, the "Accept" header is explicitly set to "application/json". Again, my application notices this and JSON is correctly returned to the request, the data is inserted into the page, and everything is happy.

Here comes the problem: The user navigates to another page, and later presses the BACK button. They are then prompted to save a file. This turns out to be the JSON data of the item list.

So far I've confirmed this to happen in both Google Chrome and Firefox 3.5.

There's two possible types of answers here:

How can I fix the problem. Is
there some magic combination of
Cache-Control headers, or other
voodoo which cause the browser to do
the right thing here?

If you think I am doing something
horribly wrong here, how should I go
about this? I'm seeking correctness,
but also trying not to sacrifice
flexibility.

If it helps, the application is a JAX-RS web application, using Restlet 2.0m4. I can provide sample request/response headers if it's helpful but I believe the issue is completely reproducible.

答:
I know this question is old, but just in case anyone else runs into this:

I was having this same problem with a Rails application using jQuery, and I fixed it by telling the browser not to cache the JSON response with the solution given here to a different question:

jQuery $.getJSON works only once for each control. Doesn't reach the server again

The problem only seemed to occur with Chrome and Firefox.  Safari was handling the back behavior okay without explicitly having to tell it to not cache.

ContentLicense: CC BY-SA 2.5

Body:
Here's the situation:

I have a web application which response to a request for a list of resources, lets say:

/items

This is initially requested directly by the web browser by navigating to that path. The browser uses it's standard "Accept" header which includes "text/html" and my application notices this and returns the HTML content for the item list.

Within the returned HTML is some JavaScript (jQuery), which then does an ajax request to retrieve the actual data:

/items

Only this time, the "Accept" header is explicitly set to "application/json". Again, my application notices this and JSON is correctly returned to the request, the data is inserted into the page, and everything is happy.

Here comes the problem: The user navigates to another page, and later presses the BACK button. They are then prompted to save a file. This turns out to be the JSON data of the item list.

So far I've confirmed this to happen in both Google Chrome and Firefox 3.5.

There's two possible types of answers here:

How can I fix the problem. Is
there some magic combination of
Cache-Control headers, or other
voodoo which cause the browser to do
the right thing here?

If you think I am doing something
horribly wrong here, how should I go
about this? I'm seeking correctness,
but also trying not to sacrifice
flexibility.

If it helps, the application is a JAX-RS web application, using Restlet 2.0m4. I can provide sample request/response headers if it's helpful but I believe the issue is completely reproducible.


答:
It sounds like you want a list:

```<code>vowels = ['a','u','a','i','o','e']
</code>```

A list can take repeated characters and is unordered.
This is the doc page for lists if you want to find out more

Title: Is there a way to make a multiset?

Body:
Is there a way to create a multiset in python? I have my set here:
{'a', 'u', 'i', 'o', 'e'} but I would like to have repeated characters, but still unorganised. Thanks

Body:
It sounds like you want a list:

vowels = ['a','u','a','i','o','e']

A list can take repeated characters and is unordered.
This is the doc page for lists if you want to find out more


问:
Null pointer error with hideSoftInputFromWindow
I get a null pointer exception at this row:

```<code>public void hideKeyboard(){
InputMethodManager inputManager = (InputMethodManager)
            this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);
}
</code>```

This is called from the following method:

```<code>@Override
public void onBackPressed() {
    super.onBackPressed();
    hideKeyboard();
}
</code>```

This is in the only activity. The back button is pressed from a fragment.

STACK:

```<code>09-28 19:14:40.301: E/InputEventSender(30324): Exception dispatching finished signal.
09-28 19:14:40.301: E/MessageQueue-JNI(30324): Exception in MessageQueue callback: handleReceiveCallback
09-28 19:14:40.325: E/MessageQueue-JNI(30324): java.lang.NullPointerException
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.example.ecohelp.MainActivity.hideKeyboard(MainActivity.java:75)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.example.ecohelp.MainActivity.onBackPressed(MainActivity.java:31)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.app.Activity.onKeyUp(Activity.java:2159)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.KeyEvent.dispatch(KeyEvent.java:2647)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.app.Activity.dispatchKeyEvent(Activity.java:2389)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1860)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3791)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3774)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3516)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3666)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:1982)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1698)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1689)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1959)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.os.MessageQueue.nativePollOnce(Native Method)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.os.MessageQueue.next(MessageQueue.java:132)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.os.Looper.loop(Looper.java:124)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.app.ActivityThread.main(ActivityThread.java:5103)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at java.lang.reflect.Method.invokeNative(Native Method)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at java.lang.reflect.Method.invoke(Method.java:525)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at dalvik.system.NativeStart.main(Native Method)
</code>```

答:
The warning stoped after I checked that the Input Manager was also != null</p>

```<code>View view = this.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (view != null && imm != null) {
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
</code>```

Body:
I get a null pointer exception at this row:

public void hideKeyboard(){
InputMethodManager inputManager = (InputMethodManager)
            this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
            InputMethodManager.HIDE_NOT_ALWAYS);
}

This is called from the following method:

@Override
public void onBackPressed() {
    super.onBackPressed();
    hideKeyboard();
}

This is in the only activity. The back button is pressed from a fragment.

STACK:

09-28 19:14:40.301: E/InputEventSender(30324): Exception dispatching finished signal.
09-28 19:14:40.301: E/MessageQueue-JNI(30324): Exception in MessageQueue callback: handleReceiveCallback
09-28 19:14:40.325: E/MessageQueue-JNI(30324): java.lang.NullPointerException
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.example.ecohelp.MainActivity.hideKeyboard(MainActivity.java:75)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.example.ecohelp.MainActivity.onBackPressed(MainActivity.java:31)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.app.Activity.onKeyUp(Activity.java:2159)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.KeyEvent.dispatch(KeyEvent.java:2647)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.app.Activity.dispatchKeyEvent(Activity.java:2389)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1860)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3791)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3774)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3516)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3666)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:1982)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1698)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1689)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1959)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.os.MessageQueue.nativePollOnce(Native Method)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.os.MessageQueue.next(MessageQueue.java:132)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.os.Looper.loop(Looper.java:124)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at android.app.ActivityThread.main(ActivityThread.java:5103)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at java.lang.reflect.Method.invokeNative(Native Method)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at java.lang.reflect.Method.invoke(Method.java:525)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-28 19:14:40.325: E/MessageQueue-JNI(30324):  at dalvik.system.NativeStart.main(Native Method)

Body:
The warning stoped after I checked that the Input Manager was also != null

View view = this.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (view != null && imm != null) {
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


问:
limit query time in the client side of PostgreSQL
I'm trying to query the PostgreSQL database, but this is a public server and I really don't want to waste a lot of CPU for a long time.

So I wonder if there is some way to limit my query time for a specific duration, for example, 3/5/10 minutes.

I assume that there is syntax like limit but not for results amount but for query duration.

Thanks for any kind of help.

答:
Set statement_timeout, then your query will be terminated with an error if it exceeds that limit.

According to this documentation:

statement_timeout (integer)

Abort any statement that takes more than
the specified number of milliseconds, starting from the time the
command arrives at the server from the client. If
log_min_error_statement is set to ERROR or lower, the statement that
timed out will also be logged. A value of zero (the default) turns
this off.

Setting statement_timeout in postgresql.conf is not recommended
because it would affect all sessions.


答:
In JavaScript, objects are passed by reference by default. And only some types like strings, numbers, etc., are passed by value.

Example: pass by value

function myFunction(arg0 /*arg0 is the copied variable */) {
  arg0 += 10;
  console.log(aVar); //displays 15
} //goodbye arg0…

var aVar = 5;
console.log(aVar); //displays 5
myFunction(aVar);
console.log(aVar); //still displays 5
```
<p><strong>Example:</strong> pass by reference</p>
<pre class="lang-js prettyprint-override"><code>function myFunction(arg0) {
  arg0.val = "I'm still a string!";
  console.log(arg0.val); //displays "I'm still a string!"
}

var aVar = {val: "I'm a string!"};
console.log(aVar.val); //displays "I'm a string!"
myFunction(aVar.val);
console.log(aVar.val); //displays "I'm still a string!"
</code>```

A short answer to your question is that there's no way to pass a pointer, that I know of, but you can achieve similar behaviour by playing with the objects. JavaScript can be a messed up language in some cases.

References:

The code examples were taken from https://www.htmlgoodies.com/html5/javascript/passing-javascript-function-arguments-by-reference.html

There's also a better explanation of how it works in JavaScript

Title: Pass object property as a pointer in javascript

Body:
In JavaScript, objects are passed by reference by default. And only some types like strings, numbers, etc., are passed by value.

Example: pass by value

function myFunction(arg0 /*arg0 is the copied variable */) {
  arg0 += 10;
  console.log(aVar); //displays 15
} //goodbye arg0…

var aVar = 5;
console.log(aVar); //displays 5
myFunction(aVar);
console.log(aVar); //still displays 5

Example: pass by reference

function myFunction(arg0) {
  arg0.val = "I'm still a string!";
  console.log(arg0.val); //displays "I'm still a string!"
}

var aVar = {val: "I'm a string!"};
console.log(aVar.val); //displays "I'm a string!"
myFunction(aVar.val);
console.log(aVar.val); //displays "I'm still a string!"

A short answer to your question is that there's no way to pass a pointer, that I know of, but you can achieve similar behaviour by playing with the objects. JavaScript can be a messed up language in some cases.

References:

The code examples were taken from https://www.htmlgoodies.com/html5/javascript/passing-javascript-function-arguments-by-reference.html

There's also a better explanation of how it works in JavaScript


问:
How do I capture video from my laptop's camera using C#
I'm new to C# and I'm trying to capture video from my laptop's camera using C#. I found some info at MSDN VideoCaptureDevices and CaptureSource. Also I added windowsbase.dll into my references.  The above class and methods I'm not able to use.

How can the above classes be used without using Silverlight concepts?

答:
windowsbase.dll is part of Windows Presentation Foundation (which has a lot of overlap with Silverlight). To use types from windowsbase.dll you'll need a WPF application (with all the learning curve if you don't know any WPF).

If you want a GUI application then WPF is a good approach.

(Otherwise: please update the question with more context.)


问:
Video still playing when bootstrap modal closes
Modal window is closed, but the video keeps playing. I want to stop video when the modal window is closed.

I tried different ways, with a YouTube video and Vimeo it's work, but it's doesn't with MP4.

$(document).ready(function() {
  var $videoSrc;
  $(".video-btn").click(function() {
$videoSrc = $(this).data("src");
  });
  console.log($videoSrc);
  $("#myModal").on("shown.bs.modal", function(e) {
$("#video").attr(
  "src",
  $videoSrc + "?autoplay=1&modestbranding=1&showinfo=0"
);
  });
  $("#myModal").on("hide.bs.modal", function(e) {
   $("#video").attr("src", $videoSrc);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <img src="https://tinyjpg.com/images/social/website.jpg?v=1&quality=80&format=jpeg" class="video-btn" data-toggle="modal" data-src="https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4"  data-target="#myModal">

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                    <!-- 16:9 aspect ratio -->
                    <div class="embed-responsive embed-responsive-16by9">
                        <iframe class="embed-responsive-item" src="" id="video"   allow="autoplay"></iframe>
                    </div>
                </div>
</body>
</html></code>```

答:
When you close the model, it does not call the player to stop playing the video. You can you add onclick="javascript::player.api('pause')" in your model close button.

```<code><button type="button" onclick="javascript::player.api('pause')" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button
</code>```

It should resolve your issue.

Body:
Modal window is closed, but the video keeps playing. I want to stop video when the modal window is closed.

I tried different ways, with a YouTube video and Vimeo it's work, but it's doesn't with MP4.

$(document).ready(function() {
  var $videoSrc;
  $(".video-btn").click(function() {
$videoSrc = $(this).data("src");
  });
  console.log($videoSrc);
  $("#myModal").on("shown.bs.modal", function(e) {
$("#video").attr(
  "src",
  $videoSrc + "?autoplay=1&modestbranding=1&showinfo=0"
);
  });
  $("#myModal").on("hide.bs.modal", function(e) {
   $("#video").attr("src", $videoSrc);
  });
});

link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

Body:
When you close the model, it does not call the player to stop playing the video. You can you add onclick="javascript::player.api('pause')" in your model close button.

<button type="button" onclick="javascript::player.api('pause')" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button

It should resolve your issue.


问:
Chrome 80 css grid large descendants cause grid to grow
When a grid has a fixed width and height, and a descendent of the grid has a width or height that is larger than that of the grid, the descendent forces the grid to 'grow' to fit it. In previous versions of Chrome (pre 80), and the latest version of Firefox (73.0 at the time of writing this) the descendants of the grid respected the grid's bounds. I've had a look the release log for this update and can't seem to find any mention of changes to grid or grid-template-rows/columns.

Expected Behaviour (Pre Chrome 80/Firefox)

Actual Behaviour (Chrome 80)

Below is a minimal snippet to reproduce the problem.

```

My question is, is this a chrome bug, or is this chrome aligning to the css grid spec?

答:
The reason for this is the implementation of a CSS Grid spec change regarding the contribution of grid tracks spanning both finitely and infinitely sized tracks. I've raised an issue about this as well.

Gladly the Chromium development team agreed that this change is not web compatible and causing too much breakage. It is already reverted on M80, M81 and M82 branches, and is going to be delivered with the reverted behaviour (pre-80-behaviour) this week in respin 116 (80.0.3987.116).

Edit: As of now, the new Chrome version is out and fixes these problems.

Edit 2: Because the Chromium team was the only browser team that actually implemented the aformentioned spec change, and they decided to revert it, the developer that implemented the changes raised an issue@CSSWG. Link yourself to that if you wanna see where this is going.

Body:
When a grid has a fixed width and height, and a descendent of the grid has a width or height that is larger than that of the grid, the descendent forces the grid to 'grow' to fit it. In previous versions of Chrome (pre 80), and the latest version of Firefox (73.0 at the time of writing this) the descendants of the grid respected the grid's bounds. I've had a look the release log for this update and can't seem to find any mention of changes to grid or grid-template-rows/columns.

Expected Behaviour (Pre Chrome 80/Firefox)

Actual Behaviour (Chrome 80)

Below is a minimal snippet to reproduce the problem.

My question is, is this a chrome bug, or is this chrome aligning to the css grid spec?


问:
How can I prevent any auto-upgrades of Mono (Xamarin) on Windows (Visual Studio) to stay synced with Mac?
I use Xamarin on Windows and Mac (on Mac for iOS apps).

The issue is that on Windows the Mono (Xamarin.iOS) is repeatedly updating itself and from time to time I've got this:

The Xamarin.Ios SDK version installed on Mac is not compatible with
  this version of Visual Studio. Would you like us to install
  xamarin.ios ... for you? This will overwrite any existing Xamarin.ios
  installation on your mac.

It's not an issue to upgrade Mac, but it is when I just need to run some code quickly and instead having that request for the update, and must spend some time for handling that. (What's more proplematic that some updates of Xamarin.iOS require newer version of XCode, which leads for me to stuck with the updates for two or more hours!!!)

However, I can't find who (what app/launcher) initiates the update of Xamarin. I've already turned off Visual Studio any auto-updates in the Scheduler etc., but the issue is still happening.

I need to control myself when I want to upgrade Xamarin exactly!

Any thoughts?

答:
The issue was posted at Microsoft's.

As it was mentioned there:

This is indeed a known side effect of not having a direct dependency
  on our Windows bits to our Mono bits required on the Mac. It’s an
  infrastructure issue that made us need to rely on the published
  products to identify what Mono version is required for the known
  Xamarin.iOS. Due to that problem, while we know what exact Xamarin.iOS
  version we need to install on the Mac, we look for the latest Mono
  version published on the corresponding channel. That makes any new
  Mono update on that channel to change the requirements for pairing a
  given Visual Studio version to a Mac. On other words, you cannot avoid
  that Mono update from Visual Studio on Windows and pairing to the Mac,
  because the connection flow will detect an incompatible Mono version
  on the Mac, which is not correct.

We’re already working on an improved mechanism where Visual Studio on
  Windows knows exactly what’s the Mono dependency and do not rely on
  any updates for that, which should allow our users to stay on a given
  version without changing the Mono requirement on the Mac without an
  explicit update on Visual Studio.

As of Dec 04, 2019 it's been mentioned it's available in Preview. So, I assume, this must be fixed at least in v16.5 version of Visual Studio.


问:
How can I use sprintf() for print to a char *?
I am doing a c program for an university project. I have the nex code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

...

int main(int argc, char const *argv[])
{
    ...
    char * resolve = 0;
    sprintf(resolve, "%s,%s\n", HTTP_HEADER, ERR_404);
    printf("%s", resolve);
    return 0;
}
</code>```

I am getting Segmentation Fault in the line of the sprintf, Is somehow manner to get this work.
P.D: HTTP_HEADER and ERR_404 are strings defined.

答:
As the pointer resolve is a null pointer then using it to write to memory invokes undefined behavior.

You should allocate enough space where you are going to write the two strings.

It can be done the following way.

```<code>size_t n = strlen( HTTP_HEADER );

char *resolve = malloc( n + strlen( ERR_404 ) + 3 );

strcpy( resolve, HTTP_HEADER );
resolve[n] = ',';

++n;

strcpy( resolve + n, ERR_404 );
strcat( resolve + n, "\n" );

printf("%s", resolve);

//...

free( resolve );
resolve = NULL;
</code>```

Body:
I am doing a c program for an university project. I have the nex code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

...

int main(int argc, char const *argv[])
{
    ...
    char * resolve = 0;
    sprintf(resolve, "%s,%s\n", HTTP_HEADER, ERR_404);
    printf("%s", resolve);
    return 0;
}

I am getting Segmentation Fault in the line of the sprintf, Is somehow manner to get this work.
P.D: HTTP_HEADER and ERR_404 are strings defined.

Body:
As the pointer resolve is a null pointer then using it to write to memory invokes undefined behavior.

You should allocate enough space where you are going to write the two strings.

It can be done the following way.

size_t n = strlen( HTTP_HEADER );

char *resolve = malloc( n + strlen( ERR_404 ) + 3 );

strcpy( resolve, HTTP_HEADER );
resolve[n] = ',';

++n;

strcpy( resolve + n, ERR_404 );
strcat( resolve + n, "\n" );

printf("%s", resolve);

//...

free( resolve );
resolve = NULL;