问:
HTML radio buttons allow the selection of multiple options
I am trying to work on making a test for a website using JavaScript. I am not good at javascript though, so I am at a complete loss.

I don't know why but my radio buttons will let me select multiple in the same section, I thought this was only supposed to happen with checkboxes.

On the issue of the javascript I would like to be able to do something like saying if yes, no, yes are seleted display this results a.with each ansswer being from the next section. I don't know how to reference them though.

This is my HTML:

<form>
<fieldset>

<legend>Have you had your record expunged before?</legend>
<input type="radio" name="yes" id="yes" value="yes" />
 yes

<input type="radio" name="no" id="no" value="no" />
  no
</fieldset>
</form>```

Thank you!

答:
You have to add the same word in the attribute of "name"

Try it :

<form>
   <fieldset>

        <legend>Have you had your record expunged before?</legend>
        <input type="radio" name="choix" id="yes" value="yes" />
         yes

      <input type="radio" name="choix" id="no" value="no" />
        no
   </fieldset>
   <button type="submit">Envoyer</button>
</form>```

Body:
I am trying to work on making a test for a website using JavaScript. I am not good at javascript though, so I am at a complete loss.

I don't know why but my radio buttons will let me select multiple in the same section, I thought this was only supposed to happen with checkboxes.

On the issue of the javascript I would like to be able to do something like saying if yes, no, yes are seleted display this results a.with each ansswer being from the next section. I don't know how to reference them though.

This is my HTML:

<form>
<fieldset>

<legend>Have you had your record expunged before?</legend>
<input type="radio" name="yes" id="yes" value="yes" />
 yes

<input type="radio" name="no" id="no" value="no" />
  no
</fieldset>
</form>

Thank you!

Body:
You have to add the same word in the attribute of "name"

Try it :

<form>
   <fieldset>
      <div class="col">
        <legend>Have you had your record expunged before?</legend>
        <input type="radio" name="choix" id="yes" value="yes" />
        <label for="yes"> yes</label>
      </div>
      <input type="radio" name="choix" id="no" value="no" />
      <label for="no">  no </label>
   </fieldset>
   <button type="submit">Envoyer</button>
</form>


来源: stackexchange

问:
ActiveRecord Query: Create an instance method using scope chaining
I am having difficulty creating a class method through an ActiveRecord query:

I have created a class method called popular_users to sort users by their number of followers, but it is not returning any results. The problem lies with friend_id: self I believe. If I test in the rails console using friend_id: User.first it works. (friend_id is the id of the person being followed)

```<code>class User < ApplicationRecord

  # received friend (ie a follower): other user sends a request which has been accepted by current user
  has_many :friendships
  has_many :received_friendships, class_name: "Friendship", foreign_key: "friend_id"
  has_many :received_friends, -> { where(friendships: { accepted: true}) }, through: :received_friendships, source: :user

  def self.popular_users
    self.joins(:friendships)
        .where(friendships: {accepted: true, friend_id: self})
        .group("users.id")
        .select("users.id, count(friendships) AS followers_count")
        .order("followers_count DESC")
  end
</code>```

I have tried the below method but it results in this error:

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error
  at or near "SELECT"

```<code>  def self.popular_users
    self.joins(:friendships)
        .group("users.id")
        .select("SELECT COUNT(friend_id) FROM friendships WHERE (user_id = :user_id AND accepted = 't')) AS followers_count")
        .order("followers_count DESC")
  end
</code>```

Schema:

```<code>  create_table "friendships", force: :cascade do |t|
    t.integer "user_id"
    t.integer "friend_id"
    t.boolean "accepted", default: false
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "name"
  end
</code>```

UPDATE: This is my answer

```<code>  def self.popular_users
    self.joins("RIGHT JOIN friendships ON friendships.friend_id = users.id AND friendships.accepted = 't'")
        .group("users.id")
        .select("users.id, count(users.id) AS followers_count")
        .order("followers_count DESC")
  end
</code>```

Eg testing in rails console:

```<code>Friendship.create(user_id: 1, friend_id: 2, accepted: true)
Friendship.create(user_id: 4, friend_id: 2, accepted: true)
Friendship.create(user_id: 5, friend_id: 2, accepted: true)
Friendship.create(user_id: 1, friend_id: 3, accepted: true)
Friendship.create(user_id: 2, friend_id: 3, accepted: true)
</code>```

Result returned after typing User.popular_users in console is #<ActiveRecord::Relation [#<User id: 2, followers_count: 3>, #<User id: 3, followers_count: 2>]>

答:
Assuming that two different users can only have one friendship, try the following:

```<code>class User < ApplicationRecord
  # . . .

  def self.popular_users
    self.joins(:friendships)
      .where( friendships: { accepted: true } )
      .group("users.id")
      .select("users.id, COUNT(users.id) AS followers_count")
      .order("COUNT(users.id) DESC")
  end

  # . . .
end
</code>```

The join from users to friendships will pull all rows from friendships for every user (and the where limits the join result to only the accepted friendships you wanted from your original).  For this reason it is sufficient to COUNT(users.id) - this will count the total number of rows (friendships) appearing in the join for each user.

Also, most SQL variants don't allow you to name an alias like you did for followers_count and then use that alias in the ORDER BY clause, so I wrote my answer more generically in case this may also have been part of your problem.

ContentLicense: CC BY-SA 3.0

Body:
I am having difficulty creating a class method through an ActiveRecord query:

I have created a class method called popular_users to sort users by their number of followers, but it is not returning any results. The problem lies with friend_id: self I believe. If I test in the rails console using friend_id: User.first it works. (friend_id is the id of the person being followed)

class User < ApplicationRecord

  # received friend (ie a follower): other user sends a request which has been accepted by current user
  has_many :friendships
  has_many :received_friendships, class_name: "Friendship", foreign_key: "friend_id"
  has_many :received_friends, -> { where(friendships: { accepted: true}) }, through: :received_friendships, source: :user

  def self.popular_users
    self.joins(:friendships)
        .where(friendships: {accepted: true, friend_id: self})
        .group("users.id")
        .select("users.id, count(friendships) AS followers_count")
        .order("followers_count DESC")
  end

I have tried the below method but it results in this error:

ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error
  at or near "SELECT"

  def self.popular_users
    self.joins(:friendships)
        .group("users.id")
        .select("SELECT COUNT(friend_id) FROM friendships WHERE (user_id = :user_id AND accepted = 't')) AS followers_count")
        .order("followers_count DESC")
  end

Schema:

  create_table "friendships", force: :cascade do |t|
    t.integer "user_id"
    t.integer "friend_id"
    t.boolean "accepted", default: false
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "name"
  end

UPDATE: This is my answer

  def self.popular_users
    self.joins("RIGHT JOIN friendships ON friendships.friend_id = users.id AND friendships.accepted = 't'")
        .group("users.id")
        .select("users.id, count(users.id) AS followers_count")
        .order("followers_count DESC")
  end

Eg testing in rails console:

Friendship.create(user_id: 1, friend_id: 2, accepted: true)
Friendship.create(user_id: 4, friend_id: 2, accepted: true)
Friendship.create(user_id: 5, friend_id: 2, accepted: true)
Friendship.create(user_id: 1, friend_id: 3, accepted: true)
Friendship.create(user_id: 2, friend_id: 3, accepted: true)

Result returned after typing User.popular_users in console is #<ActiveRecord::Relation [#<User id: 2, followers_count: 3>, #<User id: 3, followers_count: 2>]>

Body:
Assuming that two different users can only have one friendship, try the following:

class User < ApplicationRecord
  # . . .

  def self.popular_users
    self.joins(:friendships)
      .where( friendships: { accepted: true } )
      .group("users.id")
      .select("users.id, COUNT(users.id) AS followers_count")
      .order("COUNT(users.id) DESC")
  end

  # . . .
end

The join from users to friendships will pull all rows from friendships for every user (and the where limits the join result to only the accepted friendships you wanted from your original).  For this reason it is sufficient to COUNT(users.id) - this will count the total number of rows (friendships) appearing in the join for each user.

Also, most SQL variants don't allow you to name an alias like you did for followers_count and then use that alias in the ORDER BY clause, so I wrote my answer more generically in case this may also have been part of your problem.


问:
HANA Service Layer : Could not establish trust relationship for the SSL/TLS secure channel
I am trying to call SAP HANA Service Layer through my code but I am stumbling upon the below error : So can anyone please help me on this.

Error 1st :

AuthenticationException: The remote certificate is invalid according to the validation procedure.

Error 2nd :

WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Error 3rd :

HttpRequestException: An error occurred while sending the request.

Some more details about the App - I have created the console app in .NET and it executes on the server [HANA Server is locally accessed as both the servers are in the LAN] Linux & Windows Server.

One more thing - My client is not planning to purchase the domain name and SSL certificate for the SAP HANA Service Layer because it will be consumed by my app internally.

The thing is, when I tested the login service via Postman it's working fine and I am getting the session details as well but the same URL is not working through my code so is there anything more I need to do to access the service?

URL - https://172.17.100.35:50000/b1s/v1/Login

```<code>using (var client = new HttpClient())
{
var credentials = new { UserName = "admin", Password = "", "" };
var json = JsonConvert.SerializeObject(credentials);

var response = client.PostAsync(url),
                    new StringContent(json, Encoding.UTF8, "application/json")).Result;

if (response.IsSuccessStatusCode)
{
dynamic content = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);

// Access variables from the returned JSON object
var appHref = content.links.applications.href;
}
}
</code>```

答:
If you are using self signed certificates you have to accepted them first. that can be done by add it to windows certificates ou by the browser!
if you are making cross-domain calls, you need to change the b1s.config

```<code>vim /usr/sap/SAPBusinessOne/ServiceLayer/conf/b1s.conf

(...)
"CorsEnable": true,
 "CorsAllowedOrigins": "*"}
</code>```

do note use * in production MODE <-<<<--

ContentLicense: CC BY-SA 4.0

Body:
I am trying to call SAP HANA Service Layer through my code but I am stumbling upon the below error : So can anyone please help me on this.

Error 1st :

AuthenticationException: The remote certificate is invalid according to the validation procedure.

Error 2nd :

WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

Error 3rd :

HttpRequestException: An error occurred while sending the request.

Some more details about the App - I have created the console app in .NET and it executes on the server [HANA Server is locally accessed as both the servers are in the LAN] Linux & Windows Server.

One more thing - My client is not planning to purchase the domain name and SSL certificate for the SAP HANA Service Layer because it will be consumed by my app internally.

The thing is, when I tested the login service via Postman it's working fine and I am getting the session details as well but the same URL is not working through my code so is there anything more I need to do to access the service?

URL - https://172.17.100.35:50000/b1s/v1/Login

using (var client = new HttpClient())
{
var credentials = new { UserName = "admin", Password = "", "" };
var json = JsonConvert.SerializeObject(credentials);

var response = client.PostAsync(url),
                    new StringContent(json, Encoding.UTF8, "application/json")).Result;

if (response.IsSuccessStatusCode)
{
dynamic content = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);

// Access variables from the returned JSON object
var appHref = content.links.applications.href;
}
}

Body:
If you are using self signed certificates you have to accepted them first. that can be done by add it to windows certificates ou by the browser!
if you are making cross-domain calls, you need to change the b1s.config

vim /usr/sap/SAPBusinessOne/ServiceLayer/conf/b1s.conf

(...)
"CorsEnable": true,
 "CorsAllowedOrigins": "*"}

do note use * in production MODE <-<<<--


问:
Need MUMPS Sample Code
I am working on an analysis tool for which I need MUMPS sample code. Can anyone provide me MUMPS live code or sample code? Also suggest some links for same.</p>

答:
Look here:

http://www.faqs.org/faqs/m-technology-faq/part2/

Scroll down to (or search for) the section heading "Appendix 6" (without the double-quotes).

HTH
Nathan

ContentLicense: CC BY-SA 2.5

Title: Need MUMPS Sample Code


问:
How can I change this date and time format to yyyy-mm-dd hh:mm:ss using bash, this is from an apache log file
```<code>49,10.96.25.156,1274x40x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-20,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""-"
50,10.96.25.156,1274x41x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-25,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""9myyx9"
</code>```

This is how the log file looks, any help would be appreciated. Thanks!

答:
Here's a pure awk solution:

```<code>#!/usr/bin/env awk -f

BEGIN {
  FS = OFS = ","

  # build our lookup of zero-padded month numbers
  split("Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec", marr, "|")
  for (i = 1; i <= 12; i++) {
    mhash[marr[i]] = sprintf("%02d", i)
  }
}

{
  # 1:dd 2:mmm 3:yyyy 4:hh 5:mi 6:ss
  split($5, dtarr, "[:/]")

  # replace the column with our reformatted date
  $5 = dtarr[3] "-" mhash[dtarr[2]] "-" dtarr[1] " " dtarr[4] ":" dtarr[5] ":" dtarr[6]

  # print the whole line
  print
}
</code>```

To use it:

```<code>$ awk -f redate.awk access_log
49,10.96.25.156,1274x40x1,-,2017-11-02 21:14:31,http-nio-443-exec-20,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""-"
</code>```

Or you can make it executable:

```<code>$ chmod +x redate.awk
</code>```

And run it directly:

```<code>$ ./redate.awk access_log
49,10.96.25.156,1274x40x1,-,2017-11-02 21:14:31,http-nio-443-exec-20,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""-"
</code>```

Body:
49,10.96.25.156,1274x40x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-20,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""-"
50,10.96.25.156,1274x41x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-25,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""9myyx9"

This is how the log file looks, any help would be appreciated. Thanks!

Body:
Here's a pure awk solution:

#!/usr/bin/env awk -f

BEGIN {
  FS = OFS = ","

  # build our lookup of zero-padded month numbers
  split("Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec", marr, "|")
  for (i = 1; i <= 12; i++) {
    mhash[marr[i]] = sprintf("%02d", i)
  }
}

{
  # 1:dd 2:mmm 3:yyyy 4:hh 5:mi 6:ss
  split($5, dtarr, "[:/]")

  # replace the column with our reformatted date
  $5 = dtarr[3] "-" mhash[dtarr[2]] "-" dtarr[1] " " dtarr[4] ":" dtarr[5] ":" dtarr[6]

  # print the whole line
  print
}

To use it:

$ awk -f redate.awk access_log
49,10.96.25.156,1274x40x1,-,2017-11-02 21:14:31,http-nio-443-exec-20,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""-"

Or you can make it executable:

$ chmod +x redate.awk

And run it directly:

$ ./redate.awk access_log
49,10.96.25.156,1274x40x1,-,2017-11-02 21:14:31,http-nio-443-exec-20,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""-"


问:
jQuery multi-faceted filter issue.
I'm building a simple faceted filter to help users find the right condo. A few days ago I got a basic slider to filter out condos by square footage. The next part was getting the checkboxes to work which I posted to SO here and got some help from icecub. Since then I've been working on getting them to work in tandem (for example, checking 2 bedrooms and sliding the slider down to 800 sqft filters the condos by both variables). Got this to work yesterday.

The only issue I'm having is that now the slider only works when one of the two checkbox's are checked. If both or none are checked the slider doesn't work. I'm not sure exactly where my logic is flawed.

Here's a fiddle https://jsfiddle.net/baskinco/mwqkztn8/

and here's the JS

```<code>      // FUNCTIONS
      //make slider textbox equal to slider value
      function printValue(sliderID, textbox) {
        var x = document.getElementById(textbox);
        var y = document.getElementById(sliderID);
        x.value = y.value;
      }

      //get bdrm and slider values
      function getValues() {
        var bdrm1 = false;
        var bdrm2 = false;
        var sliderValue;

        if($("#1bdrm").is(':checked')){
          bdrm1 = true;
        }
        if ($("#2bdrm").is(':checked')){
          bdrm2 = true;
        }
        sliderValue = $("#rangeValue").val();

        runFilter(bdrm1, bdrm2, sliderValue);
      }

      function runFilter(bdrm1, bdrm2, sliderValue) {
        $.each($('.condo-box'), function() {
          $this = $(this);
          condoData = $this.data();
          if(bdrm1 && !bdrm2){
            if ((condoData.bdrms == 1) && (condoData.sqft <= sliderValue)){
              $this.show();
            } else {
              $this.hide();
            }
          } else if(bdrm2 && !bdrm1){
            if ((condoData.bdrms == 2) && (condoData.sqft <= sliderValue)){
              $this.show();
            } else {
              $this.hide();
            }
          } else {
            $this.show();
          }
        });
      }

      // Set values for units
      $('#jackson').data({
         id:1,
         sqft:897,
         bdrms:2
      });
      $('#nicholl').data({
         id:2,
         sqft:808,
         bdrms:2
      });
      $('#atwood').data({
         id:3,
         sqft:1020,
         bdrms:2
      });
      //etc

    //MAIN SCRIPT
      $(document).ready(function() {
        //print slider value to slider textbox
        printValue('slider','rangeValue');

        //when a bdrm box is checked ..
        $("#1bdrm, #2bdrm").click(function(){
          getValues();
        });

        //when the slider is moved
        $("#slider").change(function() {
          getValues();
        });
      });
</code>```

答:
Your else condition isn't checking the sqft and slider, it should be:

```<code>else {
    if ((condoData.sqft <= sliderValue)){
        $this.show();
    } else {
        $this.hide();
    }
}
</code>```

https://jsfiddle.net/mwqkztn8/1/

Or, even simpler, that whole thing could just be:

```<code>$.each($('.condo-box'), function() {
     $this = $(this);
     condoData = $this.data();
     var sqftFilter = (condoData.sqft <= sliderValue);
     var bedFilter = (!bdrm1 && !bdrm2) || (condoData.bdrms == 1 && bdrm1) || (condoData.bdrms == 2 && bdrm2);
     $this.toggle(sqftFilter && bedFilter);
});
</code>```

https://jsfiddle.net/mwqkztn8/3/

Title: jQuery multi-faceted filter issue.

Body:
I'm building a simple faceted filter to help users find the right condo. A few days ago I got a basic slider to filter out condos by square footage. The next part was getting the checkboxes to work which I posted to SO here and got some help from icecub. Since then I've been working on getting them to work in tandem (for example, checking 2 bedrooms and sliding the slider down to 800 sqft filters the condos by both variables). Got this to work yesterday.

The only issue I'm having is that now the slider only works when one of the two checkbox's are checked. If both or none are checked the slider doesn't work. I'm not sure exactly where my logic is flawed.

Here's a fiddle https://jsfiddle.net/baskinco/mwqkztn8/

and here's the JS

      // FUNCTIONS
      //make slider textbox equal to slider value
      function printValue(sliderID, textbox) {
        var x = document.getElementById(textbox);
        var y = document.getElementById(sliderID);
        x.value = y.value;
      }

      //get bdrm and slider values
      function getValues() {
        var bdrm1 = false;
        var bdrm2 = false;
        var sliderValue;

        if($("#1bdrm").is(':checked')){
          bdrm1 = true;
        }
        if ($("#2bdrm").is(':checked')){
          bdrm2 = true;
        }
        sliderValue = $("#rangeValue").val();

        runFilter(bdrm1, bdrm2, sliderValue);
      }

      function runFilter(bdrm1, bdrm2, sliderValue) {
        $.each($('.condo-box'), function() {
          $this = $(this);
          condoData = $this.data();
          if(bdrm1 && !bdrm2){
            if ((condoData.bdrms == 1) && (condoData.sqft <= sliderValue)){
              $this.show();
            } else {
              $this.hide();
            }
          } else if(bdrm2 && !bdrm1){
            if ((condoData.bdrms == 2) && (condoData.sqft <= sliderValue)){
              $this.show();
            } else {
              $this.hide();
            }
          } else {
            $this.show();
          }
        });
      }

      // Set values for units
      $('#jackson').data({
         id:1,
         sqft:897,
         bdrms:2
      });
      $('#nicholl').data({
         id:2,
         sqft:808,
         bdrms:2
      });
      $('#atwood').data({
         id:3,
         sqft:1020,
         bdrms:2
      });
      //etc

    //MAIN SCRIPT
      $(document).ready(function() {
        //print slider value to slider textbox
        printValue('slider','rangeValue');

        //when a bdrm box is checked ..
        $("#1bdrm, #2bdrm").click(function(){
          getValues();
        });

        //when the slider is moved
        $("#slider").change(function() {
          getValues();
        });
      });

Body:
Your else condition isn't checking the sqft and slider, it should be:

else {
    if ((condoData.sqft <= sliderValue)){
        $this.show();
    } else {
        $this.hide();
    }
}

https://jsfiddle.net/mwqkztn8/1/

Or, even simpler, that whole thing could just be:

$.each($('.condo-box'), function() {
     $this = $(this);
     condoData = $this.data();
     var sqftFilter = (condoData.sqft <= sliderValue);
     var bedFilter = (!bdrm1 && !bdrm2) || (condoData.bdrms == 1 && bdrm1) || (condoData.bdrms == 2 && bdrm2);
     $this.toggle(sqftFilter && bedFilter);
});

https://jsfiddle.net/mwqkztn8/3/


问:
PHP simple HTML DOM parser errors
I've started writing a scraper for one site that will also have a crawler, since I need to go through some links, but I'm getting this error :

PHP Fatal error:  Uncaught Error: Call to a member function find() on
null in D:\Projekti\hemrank\simple_html_dom.php:1129 Stack trace:

0 D:\Projekti\hemrank\scrapeit.php(37): simple_html_dom->find('ul')

1 D:\Projekti\hemrank\scrapeit.php(19): ScrapeIt->getAllAddresses()

2 D:\Projekti\hemrank\scrapeit.php(55): ScrapeIt->run()

3 {main}   thrown in D:\Projekti\hemrank\simple_html_dom.php on line 1129

When I var_dump the $html variable I get the full html with all the tags, etc, that's why it's strange to me that it says "Call to a member function find() on null", when there's actually value in the $html. Here's the part of the code that's not working :

```<code>        $html = new simple_html_dom();
        $html->load_file($baseurl);
        if(empty($html)){echo "HTTP Response not received!<br/>\n";exit;}
        $links = array();
        foreach ($html->find('ul') as $ul) {
            if(!empty($ul) && (count($ul)>0))
            foreach ($ul->find('li') as $li) {
                if(!empty($li) && (count($li)>0))
                foreach ($li->find('a') as $a) {
                    $links[] = $a->href;
                }
                else
                    die("NOT AVAILABLE");
            }
        }

        return $links;

    }
</code>```

Is this a common problem with PHP simple HTML DOM parser, is there a solution or should I switch to some other kind of scraping?

答:
I suggest the following change:

$html->load_file($baseurl); to $html = file_get_html($baseurl);

On my VPS server it works with $html->load_file($baseurl); but on my dedicated local server it only works with $html = file_get_html($baseurl);

This solved my problem:
- Call to a member function find() on null
- simple_html_dom.php on line 1129

Title: PHP simple HTML DOM parser errors

Body:
I've started writing a scraper for one site that will also have a crawler, since I need to go through some links, but I'm getting this error :

PHP Fatal error:  Uncaught Error: Call to a member function find() on
null in D:\Projekti\hemrank\simple_html_dom.php:1129 Stack trace:

0 D:\Projekti\hemrank\scrapeit.php(37): simple_html_dom->find('ul')

1 D:\Projekti\hemrank\scrapeit.php(19): ScrapeIt->getAllAddresses()

2 D:\Projekti\hemrank\scrapeit.php(55): ScrapeIt->run()

3 {main}   thrown in D:\Projekti\hemrank\simple_html_dom.php on line 1129

When I var_dump the $html variable I get the full html with all the tags, etc, that's why it's strange to me that it says "Call to a member function find() on null", when there's actually value in the $html. Here's the part of the code that's not working :

        $html = new simple_html_dom();
        $html->load_file($baseurl);
        if(empty($html)){echo "HTTP Response not received!
\n";exit;}
        $links = array();
        foreach ($html->find('ul') as $ul) {
            if(!empty($ul) && (count($ul)>0))
            foreach ($ul->find('li') as $li) {
                if(!empty($li) && (count($li)>0))
                foreach ($li->find('a') as $a) {
                    $links[] = $a->href;
                }
                else
                    die("NOT AVAILABLE");
            }
        }

        return $links;

    }

Is this a common problem with PHP simple HTML DOM parser, is there a solution or should I switch to some other kind of scraping?


问:
Open a PDF using VBA in Excel
I'm trying to open all appropriate PDFs found in the same directory as my Excel workbook using VBA.  I've added the Adobe Acrobat xx.x Type Library reference to the project.  But when I try to create the .App object I get a "Run-time error '429':" error.

What am I missing?

Here's the code;

```<code>Sub ImportNames()
Dim BlrInfoFileList() As String, NbrOfFiles As Integer, FileNameStr As String
Dim X As Integer, pdfApp As AcroApp, pdfDoc As AcroAVDoc

'Find all of the Contact Information PDFs
FileNameStr = Dir(ThisWorkbook.Path & "\*Contact Information.pdf")
NbrOfFiles = 0
Do Until FileNameStr = ""
    NbrOfFiles = NbrOfFiles + 1
    ReDim Preserve BlrInfoFileList(NbrOfFiles)
    BlrInfoFileList(NbrOfFiles) = FileNameStr
    FileNameStr = Dir()
Loop

For X = 1 To NbrOfFiles
    FileNameStr = ThisWorkbook.Path & "\" & BlrInfoFileList(X)
    Set pdfApp = CreateObject("AcroExch.App")
    pdfApp.Hide

    Set pdfDoc = CreateObject("AcroExch.AVDoc")
    pdfDoc.Open FileNameStr, vbNormalFocus

    SendKeys ("^a")
    SendKeys ("^c")
    SendKeys "%{F4}"

    ThisWorkbook.Sheets("Raw Data").Range("A1").Select
    SendKeys ("^v")
    Set pdfApp = Nothing
    Set pdfDoc = Nothing

    'Process Raw Data and Clear the sheet for the next PDF Document
Next X
End Sub
</code>```

答:
Hope this helps. I was able to open pdf files from all subfolders of a folder and copy content to the macro enabled workbook using shell as recommended above.Please see below the code .

```<code>Sub ConsolidateWorkbooksLTD()
Dim adobeReaderPath As String
Dim pathAndFileName As String
Dim shellPathName As String
Dim fso, subFldr, subFlodr
Dim FolderPath
Dim Filename As String
Dim Sheet As Worksheet
Dim ws As Worksheet
Dim HK As String
Dim s As String
Dim J As String
Dim diaFolder As FileDialog
Dim mFolder As String
Dim Basebk As Workbook
Dim Actbk As Workbook

Application.ScreenUpdating = False

Set Basebk = ThisWorkbook

' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
MsgBox diaFolder.SelectedItems(1) & "\"
mFolder = diaFolder.SelectedItems(1) & "\"
Set diaFolder = Nothing
Set fso = CreateObject("Scripting.FileSystemObject")
Set FolderPath = fso.GetFolder(mFolder)
For Each subFldr In FolderPath.SubFolders
subFlodr = subFldr & "\"
Filename = Dir(subFldr & "\*.csv*")
Do While Len(Filename) > 0
J = Filename
J = Left(J, Len(J) - 4) & ".pdf"
   Workbooks.Open Filename:=subFldr & "\" & Filename, ReadOnly:=True
   For Each Sheet In ActiveWorkbook.Sheets
   Set Actbk = ActiveWorkbook
   s = ActiveWorkbook.Name
   HK = Left(s, Len(s) - 4)
   If InStrRev(HK, "_S") <> 0 Then
   HK = Right(HK, Len(HK) - InStrRev(HK, "_S"))
   Else
   HK = Right(HK, Len(HK) - InStrRev(HK, "_L"))
   End If
   Sheet.Copy After:=ThisWorkbook.Sheets(1)
   ActiveSheet.Name = HK

   ' Open pdf file to copy SIC Decsription
   pathAndFileName = subFlodr & J
   adobeReaderPath = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"
   shellPathName = adobeReaderPath & " """ & pathAndFileName & """"
   Call Shell( _
    pathname:=shellPathName, _
    windowstyle:=vbNormalFocus)
    Application.Wait Now + TimeValue("0:00:2")

    SendKeys "%vpc"
    SendKeys "^a", True
    Application.Wait Now + TimeValue("00:00:2")

    ' send key to copy
     SendKeys "^c"
    ' wait 2 secs
     Application.Wait Now + TimeValue("00:00:2")
      ' activate this workook and paste the data
        ThisWorkbook.Activate
        Set ws = ThisWorkbook.Sheets(HK)
        Range("O1:O5").Select
        ws.Paste

        Application.Wait Now + TimeValue("00:00:3")
        Application.CutCopyMode = False
        Application.Wait Now + TimeValue("00:00:3")
       Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
       ' send key to close pdf file
        SendKeys "^q"
       Application.Wait Now + TimeValue("00:00:3")
 Next Sheet
 Workbooks(Filename).Close SaveAs = True
 Filename = Dir()
Loop
Next
Application.ScreenUpdating = True
End Sub
</code>```

I wrote the piece of code to copy from pdf and csv to the macro enabled workbook and you may need to fine tune as per your requirement

Regards,
Hema Kasturi

Title: Open a PDF using VBA in Excel

Body:
I'm trying to open all appropriate PDFs found in the same directory as my Excel workbook using VBA.  I've added the Adobe Acrobat xx.x Type Library reference to the project.  But when I try to create the .App object I get a "Run-time error '429':" error.

What am I missing?

Here's the code;

Sub ImportNames()
Dim BlrInfoFileList() As String, NbrOfFiles As Integer, FileNameStr As String
Dim X As Integer, pdfApp As AcroApp, pdfDoc As AcroAVDoc

'Find all of the Contact Information PDFs
FileNameStr = Dir(ThisWorkbook.Path & "\*Contact Information.pdf")
NbrOfFiles = 0
Do Until FileNameStr = ""
    NbrOfFiles = NbrOfFiles + 1
    ReDim Preserve BlrInfoFileList(NbrOfFiles)
    BlrInfoFileList(NbrOfFiles) = FileNameStr
    FileNameStr = Dir()
Loop

For X = 1 To NbrOfFiles
    FileNameStr = ThisWorkbook.Path & "\" & BlrInfoFileList(X)
    Set pdfApp = CreateObject("AcroExch.App")
    pdfApp.Hide

    Set pdfDoc = CreateObject("AcroExch.AVDoc")
    pdfDoc.Open FileNameStr, vbNormalFocus

    SendKeys ("^a")
    SendKeys ("^c")
    SendKeys "%{F4}"

    ThisWorkbook.Sheets("Raw Data").Range("A1").Select
    SendKeys ("^v")
    Set pdfApp = Nothing
    Set pdfDoc = Nothing

    'Process Raw Data and Clear the sheet for the next PDF Document
Next X
End Sub

Body:
Hope this helps. I was able to open pdf files from all subfolders of a folder and copy content to the macro enabled workbook using shell as recommended above.Please see below the code .

Sub ConsolidateWorkbooksLTD()
Dim adobeReaderPath As String
Dim pathAndFileName As String
Dim shellPathName As String
Dim fso, subFldr, subFlodr
Dim FolderPath
Dim Filename As String
Dim Sheet As Worksheet
Dim ws As Worksheet
Dim HK As String
Dim s As String
Dim J As String
Dim diaFolder As FileDialog
Dim mFolder As String
Dim Basebk As Workbook
Dim Actbk As Workbook

Application.ScreenUpdating = False

Set Basebk = ThisWorkbook

' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
MsgBox diaFolder.SelectedItems(1) & "\"
mFolder = diaFolder.SelectedItems(1) & "\"
Set diaFolder = Nothing
Set fso = CreateObject("Scripting.FileSystemObject")
Set FolderPath = fso.GetFolder(mFolder)
For Each subFldr In FolderPath.SubFolders
subFlodr = subFldr & "\"
Filename = Dir(subFldr & "\*.csv*")
Do While Len(Filename) > 0
J = Filename
J = Left(J, Len(J) - 4) & ".pdf"
   Workbooks.Open Filename:=subFldr & "\" & Filename, ReadOnly:=True
   For Each Sheet In ActiveWorkbook.Sheets
   Set Actbk = ActiveWorkbook
   s = ActiveWorkbook.Name
   HK = Left(s, Len(s) - 4)
   If InStrRev(HK, "_S") <> 0 Then
   HK = Right(HK, Len(HK) - InStrRev(HK, "_S"))
   Else
   HK = Right(HK, Len(HK) - InStrRev(HK, "_L"))
   End If
   Sheet.Copy After:=ThisWorkbook.Sheets(1)
   ActiveSheet.Name = HK

   ' Open pdf file to copy SIC Decsription
   pathAndFileName = subFlodr & J
   adobeReaderPath = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"
   shellPathName = adobeReaderPath & " """ & pathAndFileName & """"
   Call Shell( _
    pathname:=shellPathName, _
    windowstyle:=vbNormalFocus)
    Application.Wait Now + TimeValue("0:00:2")

    SendKeys "%vpc"
    SendKeys "^a", True
    Application.Wait Now + TimeValue("00:00:2")

    ' send key to copy
     SendKeys "^c"
    ' wait 2 secs
     Application.Wait Now + TimeValue("00:00:2")
      ' activate this workook and paste the data
        ThisWorkbook.Activate
        Set ws = ThisWorkbook.Sheets(HK)
        Range("O1:O5").Select
        ws.Paste

        Application.Wait Now + TimeValue("00:00:3")
        Application.CutCopyMode = False
        Application.Wait Now + TimeValue("00:00:3")
       Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
       ' send key to close pdf file
        SendKeys "^q"
       Application.Wait Now + TimeValue("00:00:3")
 Next Sheet
 Workbooks(Filename).Close SaveAs = True
 Filename = Dir()
Loop
Next
Application.ScreenUpdating = True
End Sub

I wrote the piece of code to copy from pdf and csv to the macro enabled workbook and you may need to fine tune as per your requirement

Regards,
Hema Kasturi


问:
Unity Android ARCore object size
Anyone know how to make objects smaller in ARCore. The object I am instantiating is gigantic and scaling the prefab down in the editor doesn't seem to help? There are a bunch of child objects to the parent object I am instantiating if that helps at all.</p>

答:
Simply modifying the instantiated object's transform.localScale should do the trick. Something like:

GameObject go = GameObject.Instantiate(myPrefab);
go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);

Title: Unity Android ARCore object size


问:
Setting up Oracle DB as Destination with SSIS, encountering errors (ORA-12154)
I've had a frustrating time attempting to connect to an Oracle DB as a destination via SSIS so I can export some data into it.

I have Oracle ODAC components installed, tnsnames.ora set up properly, TNSNAMES in the NAMES.DIRECTORY_PATH attribute in sqlnet.ora, Attunity installed on my computer etc. I have even managed to connect to the database in question in the SSIS server explorer, and am able to access all its tables etc.

However I can't seem to find out how to actually connect to that Oracle DB as a destination in an SSIS Project. I started a new package, switched to data flow, selected 'OLE DB Destination' and attempted to create a new connection with either 'Oracle Provider for OLE DB' or 'Microsoft OLE DB Provider for Oracle'. Both only let me cite the server name and user name + password, and when I enter the same ones I used to establish the SSIS server explorer connection I get an 'ORA-12154: TNS: could not resolve the connect identifier specified' error.

I have spent a lot of time trying to fix this but keep running into a brick wall. Any idea what I'm doing wrong or what I could do to establish a connection?

答:
Are you using 32 or 64 bit Windows? I've struggled with some Oracle connections in the past and I made the mistake with mixing up 32 and 64 bit Oracle drivers and settings. Visual Studio is 32 bit and uses those drivers by default, you can go to project properties and change the VS to use 64 bit runtime if necessary.

This could be helpful also: https://stackoverflow.com/a/18098573/5605866


问:
do's and don'ts for writing mysql queries
One thing I always wonder while writing query is that am I writing most optimized query or not? I know certain things like:

1) using SELECT field1, filed2 instead of SELECT *

2) Giving proper indexes to the tables

but I am sure there are more things that should be kept in mind for writing queries, since most of the database can only grow more and optimal query will help in execution time. Can you share some tips and tricks on writing queries?

答:
One more thing I found today is regarding the difference between COUNT(*) and COUNT(col)

Using COUNT(*) is faster than COUNT(col)

MYISAM tables cached number of rows in this table, for innoDB doesn't cache row count and may be slower without WHERE clause

It is better to use NOT NULL column for both MYISAM and innoDB than some other column where Null is allowed.

More details here


问:
Fetch polyfill has different Response-object in internet explorer 11
I'm currently struggeling with Internet Explorer 11 and the Fetch API.

I have the following fetch-call unsing TypeScript:

```<code>await fetch(theForm.action, { method: theForm.method, body: formData, credentials: "include" })
    .then((response: Response) => {
        if (response.status === 500)
            throw Error(response.statusText);

        if (response.redirected && response.url)
            return window.location.href = response.url;

        return response.json();
    })
    .catch((error: Error) => {
        return this.setState({ isSubmitting: false, internalServerError: error });
    });
</code>```

The code is ts-compiled to ES2015 and then down to ES5 using babel. I've also added babel-polyfill. The example code works as expected on other browsers than IE.
As it turns out, the Response-object in IE is totally different and don't even has the property redirected and url is always empty.

Is there any polyfill I should use to make this work in IE? And, if not, what would be a good workaround?

答:
MDN's browser compatibility table for Response says that the redirected attribute isn't available on IE.

<img src="https://i.stack.imgur.com/rai4j.png" alt="MDN's browser compatibility table for Response">

You could try using a polyfill like https://github.com/github/fetch along with the API suggestion on https://github.com/github/fetch#obtaining-the-response-url.

Body:
I'm currently struggeling with Internet Explorer 11 and the Fetch API.

I have the following fetch-call unsing TypeScript:

await fetch(theForm.action, { method: theForm.method, body: formData, credentials: "include" })
    .then((response: Response) => {
        if (response.status === 500)
            throw Error(response.statusText);

        if (response.redirected && response.url)
            return window.location.href = response.url;

        return response.json();
    })
    .catch((error: Error) => {
        return this.setState({ isSubmitting: false, internalServerError: error });
    });

The code is ts-compiled to ES2015 and then down to ES5 using babel. I've also added babel-polyfill. The example code works as expected on other browsers than IE.
As it turns out, the Response-object in IE is totally different and don't even has the property redirected and url is always empty.

Is there any polyfill I should use to make this work in IE? And, if not, what would be a good workaround?

Body:
MDN's browser compatibility table for Response says that the redirected attribute isn't available on IE.

You could try using a polyfill like https://github.com/github/fetch along with the API suggestion on https://github.com/github/fetch#obtaining-the-response-url.


问:
cx_freeze: ModuleNotFoundError and program stopped working
I have a console mode program that I would like to distribute with cx_Freeze. I have just downloaded python 3.6.3 (both amd64 and win32 version) on a newly installed win 10 machine. I have installed cx_Freeze 5.1 from wheels (not from pypi). Then I have built both amd64 and win32 versions of the program. If I try to execute that exe file on the same machine where I have built it, I get this error:

```<code>Fatal Python error: Py_Initialize: unable to load the file system codec
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\encodings\__init__.py", line 31, in <module>
ModuleNotFoundError: No module named 'codecs'
</code>```

I have the same error on both architectures. The setup file looks like this:

```<code>#!/usr/bin/env python3
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {
    "packages": [
        "os", "io", "copy", "struct", "hashlib", "random",
        "urllib", "pycurl", "json", "multiprocessing",
        "cryptography",
        "tornado", "watchdog", "pathtools"
    ],
    "includes": [
        "cryptography", "urllib.parse",
    ],
    "include_files": ["tmp", "server.ini", "client.ini"],
    "excludes": ["tkinter"],
}

setup(
    name="BlindBackup",
    version="1.0",
    description="BlindBackup",
    options={"build_exe": build_exe_options},
    executables=[
        Executable("backup.py", base=None),
        Executable("bsync.py", base=None),
        Executable("server.py", base=None),
    ]
)
</code>```

In other words, I have specified the "codecs" package explicitly.

What is wrong?

UPDATE There is a file called library.zip in the distribution dir. It contains codecs.pyc but the exe file does not see it. If I extract all files from that zip, then I get a different error message:

```<code>C:\Python\Projects\blindbackup\build\exe.win-amd64-3.6>backup.exe
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 14, in run
    module.run()
  File "C:\Program Files\Python36\lib\site-packages\cx_Freeze\initscripts\Console.py", line 22, in run
    importer = zipimport.zipimporter(os.path.dirname(os.__file__))
zipimport.ZipImportError: not a Zip file
</code>```

I guess that the problem is with the code that tries to import modules from the library.zip file? But not sure how to fix it.

答:
The solution was this:

install cx_freeze 6, because version 5 does not support python 3.6 (apparently)

install pywin32 (although it was not required for my program)

add all missing pyd files to "includes" and all missing packages to "packages" section it the setup script.

Body:
I have a console mode program that I would like to distribute with cx_Freeze. I have just downloaded python 3.6.3 (both amd64 and win32 version) on a newly installed win 10 machine. I have installed cx_Freeze 5.1 from wheels (not from pypi). Then I have built both amd64 and win32 versions of the program. If I try to execute that exe file on the same machine where I have built it, I get this error:

Fatal Python error: Py_Initialize: unable to load the file system codec
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\encodings\__init__.py", line 31, in <module>
ModuleNotFoundError: No module named 'codecs'

I have the same error on both architectures. The setup file looks like this:

#!/usr/bin/env python3
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {
    "packages": [
        "os", "io", "copy", "struct", "hashlib", "random",
        "urllib", "pycurl", "json", "multiprocessing",
        "cryptography",
        "tornado", "watchdog", "pathtools"
    ],
    "includes": [
        "cryptography", "urllib.parse",
    ],
    "include_files": ["tmp", "server.ini", "client.ini"],
    "excludes": ["tkinter"],
}

setup(
    name="BlindBackup",
    version="1.0",
    description="BlindBackup",
    options={"build_exe": build_exe_options},
    executables=[
        Executable("backup.py", base=None),
        Executable("bsync.py", base=None),
        Executable("server.py", base=None),
    ]
)

In other words, I have specified the "codecs" package explicitly.

What is wrong?

UPDATE There is a file called library.zip in the distribution dir. It contains codecs.pyc but the exe file does not see it. If I extract all files from that zip, then I get a different error message:

C:\Python\Projects\blindbackup\build\exe.win-amd64-3.6>backup.exe
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\cx_Freeze\initscripts\__startup__.py", line 14, in run
    module.run()
  File "C:\Program Files\Python36\lib\site-packages\cx_Freeze\initscripts\Console.py", line 22, in run
    importer = zipimport.zipimporter(os.path.dirname(os.__file__))
zipimport.ZipImportError: not a Zip file

I guess that the problem is with the code that tries to import modules from the library.zip file? But not sure how to fix it.


问:
Move-ADObject - input object cannot be found to any parameters for the command - error
Not exactly sure why I am getting this error - input object cannot be bound to any parameters for the command either because the commmand does not take pipeline input and its properties do not match any of the parameters that take pipeline input. Any assistance is appreciated

Code snippet below

```<code>$Session = New-PSSession -ComputerName DC1 -Credential $Cred
Import-Module ActiveDirectory -PSSession $Session
$comp = $env:COMPUTERNAME
if ($ComputerName -eq $null) {
Invoke-Command -Session $session  -ScriptBlock {$using:PC
}
if($comp.substring(5,3) -imatch "Dbs"){
Get-ADObject $PC |
Move-ADObject  -Targetpath "ou=Database,
dc=com,dc=company,dc=net"
Write-Host "Moved to Datbases"}

 }

Remove-PSSession -Session $Session
</code>```

答:
You are both piping in the output of Get-ADComputer and also defining the -Identity property which are conflicting. Chose one way or the other.

```<code>Get-ADComputer $comp | Move-ADObject -Targetpath "ou=Database, dc=com,dc=company,dc=net"
</code>```

or

```<code>$ADComputer = Get-ADComputer $comp
Move-ADObject -Identity $ADComputer -Targetpath "ou=Database, dc=com,dc=company,dc=net"
</code>```

Body:
Not exactly sure why I am getting this error - input object cannot be bound to any parameters for the command either because the commmand does not take pipeline input and its properties do not match any of the parameters that take pipeline input. Any assistance is appreciated

Code snippet below

$Session = New-PSSession -ComputerName DC1 -Credential $Cred
Import-Module ActiveDirectory -PSSession $Session
$comp = $env:COMPUTERNAME
if ($ComputerName -eq $null) {
Invoke-Command -Session $session  -ScriptBlock {$using:PC
}
if($comp.substring(5,3) -imatch "Dbs"){
Get-ADObject $PC |
Move-ADObject  -Targetpath "ou=Database,
dc=com,dc=company,dc=net"
Write-Host "Moved to Datbases"}

 }

Remove-PSSession -Session $Session

Body:
You are both piping in the output of Get-ADComputer and also defining the -Identity property which are conflicting. Chose one way or the other.

Get-ADComputer $comp | Move-ADObject -Targetpath "ou=Database, dc=com,dc=company,dc=net"

or

$ADComputer = Get-ADComputer $comp
Move-ADObject -Identity $ADComputer -Targetpath "ou=Database, dc=com,dc=company,dc=net"


问:
Finding a key in an object that’s true AND matches en entry in an array
I have an array like this:

```<code>baseBreakpoints: [
    'xLarge',
    'large',
    'largeMedium',
    'medium',
    'smallMedium',
    'small',
    'xSmall'
]
</code>```

… and I have an object like this:

```<code>breakpoints = {
    "gtMedium": true,
    "xLarge": true,
    "gtLargeMedium": true,
    "giant": false,
    "small": false,
    "ltLargeMedium": false,
    "gtLarge": true,
    "xSmall": false,
    "largeMedium": false,
    "medium": false,
    "gtSmall": true,
    "large": false,
    "smallMedium": false
}
</code>```

I need to find the key in the object that’s true and exists in the array. For example, in this example above the value would be xLarge since xLarge === true in the object and exists in the breakpoints array.

Any suggestions? Lodash is already a dependency in the project, if that helps.

答:
You could filter baseBreakpoints by looking up breakpoints.

var baseBreakpoints = ['xLarge', 'large', 'largeMedium', 'medium', 'smallMedium', 'small', 'xSmall'],
    breakpoints = { gtMedium: true, xLarge: true, gtLargeMedium: true, giant: false, small: false, ltLargeMedium: false, gtLarge: true, xSmall: false, largeMedium: false, medium: false, gtSmall: true, large: false, smallMedium: false },
    result = baseBreakpoints.filter(k => breakpoints[k]);

console.log(result);```
</div>
</div>
</p>

<p>ES5</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var baseBreakpoints = ['xLarge', 'large', 'largeMedium', 'medium', 'smallMedium', 'small', 'xSmall'],
    breakpoints = { gtMedium: true, xLarge: true, gtLargeMedium: true, giant: false, small: false, ltLargeMedium: false, gtLarge: true, xSmall: false, largeMedium: false, medium: false, gtSmall: true, large: false, smallMedium: false },
    result = baseBreakpoints.filter(function (k) { return breakpoints[k]; });

console.log(result);</code>```

Body:
I have an array like this:

baseBreakpoints: [
    'xLarge',
    'large',
    'largeMedium',
    'medium',
    'smallMedium',
    'small',
    'xSmall'
]

… and I have an object like this:

breakpoints = {
    "gtMedium": true,
    "xLarge": true,
    "gtLargeMedium": true,
    "giant": false,
    "small": false,
    "ltLargeMedium": false,
    "gtLarge": true,
    "xSmall": false,
    "largeMedium": false,
    "medium": false,
    "gtSmall": true,
    "large": false,
    "smallMedium": false
}

I need to find the key in the object that’s true and exists in the array. For example, in this example above the value would be xLarge since xLarge === true in the object and exists in the breakpoints array.

Any suggestions? Lodash is already a dependency in the project, if that helps.

Body:
You could filter baseBreakpoints by looking up breakpoints.

var baseBreakpoints = ['xLarge', 'large', 'largeMedium', 'medium', 'smallMedium', 'small', 'xSmall'],
    breakpoints = { gtMedium: true, xLarge: true, gtLargeMedium: true, giant: false, small: false, ltLargeMedium: false, gtLarge: true, xSmall: false, largeMedium: false, medium: false, gtSmall: true, large: false, smallMedium: false },
    result = baseBreakpoints.filter(k => breakpoints[k]);

console.log(result);

ES5

var baseBreakpoints = ['xLarge', 'large', 'largeMedium', 'medium', 'smallMedium', 'small', 'xSmall'],
    breakpoints = { gtMedium: true, xLarge: true, gtLargeMedium: true, giant: false, small: false, ltLargeMedium: false, gtLarge: true, xSmall: false, largeMedium: false, medium: false, gtSmall: true, large: false, smallMedium: false },
    result = baseBreakpoints.filter(function (k) { return breakpoints[k]; });

console.log(result);


答:
you can try this approach.

the first condition check if the key is truthy, the second one test if in the array there's a match.

This solution compared to the other correct answers returns a pure string rather then a filtered array.

let baseBreakpoints = ['xLarge', 'large', 'largeMedium', 'medium',
'smallMedium', 'small', 'xSmall'];

let breakpoints = {
    "gtMedium": true,
    "xLarge": true,
    "gtLargeMedium": true,
    "giant": false,
    "small": false,
    "ltLargeMedium": false,
    "gtLarge": true,
    "xSmall": false,
    "largeMedium": false,
    "medium": false,
    "gtSmall": true,
    "large": false,
    "smallMedium": false
}

let key = Object.keys(breakpoints).find(key => {
   return breakpoints[key]
     && baseBreakpoints.some(breakpoint => breakpoint === key);
})

console.log(key);```

Title: Finding a key in an object that’s true AND matches en entry in an array


问:
Is this the right way to test if a field has been left empty?
This is inside a function, so that any textField passed as argument can respond to the method checkForEmptyFields:

```<code>textField.addTarget(self, action: #selector(checkForEmptyFields(sender:)),
for: UIControlEvents.editingChanged)
</code>```

This is the method checkForEmptyFields:

```<code> func checkForEmptyFields(sender:UITextField){

        self.loginButton.isEnabled = (sender.text?.trim().isEmpty)! == false

    }
</code>```

This is a simple extension of String for manage the trimming:

```<code>extension String
{
    func trim() -> String
    {
        return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
    }
}
</code>```

Anything seems to work just fine but I'd like to know if this is the right way to proceed and if I forgot something important (or I made any mistake). Thanks!

答:
Per my comment above, don't force unwrap. Really!

I'd probably handle it like…

```<code>func checkForEmptyFields(sender: UITextField) {
    if let trimmedText = sender.text?.trim(), !trimmedText.isEmpty {
        loginButton.isEnabled = true
    } else {
        loginButton.isEnabled = false
    }
}
</code>```

It's more verbose, but I think this clearly states your intent - nil coalescing can sometimes be confusing to read and debug (should it be ?? true or ?? false?)

Body:
This is inside a function, so that any textField passed as argument can respond to the method checkForEmptyFields:

textField.addTarget(self, action: #selector(checkForEmptyFields(sender:)),
for: UIControlEvents.editingChanged)

This is the method checkForEmptyFields:

 func checkForEmptyFields(sender:UITextField){

        self.loginButton.isEnabled = (sender.text?.trim().isEmpty)! == false

    }

This is a simple extension of String for manage the trimming:

extension String
{
    func trim() -> String
    {
        return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
    }
}

Anything seems to work just fine but I'd like to know if this is the right way to proceed and if I forgot something important (or I made any mistake). Thanks!

Body:
Per my comment above, don't force unwrap. Really!

I'd probably handle it like…

func checkForEmptyFields(sender: UITextField) {
    if let trimmedText = sender.text?.trim(), !trimmedText.isEmpty {
        loginButton.isEnabled = true
    } else {
        loginButton.isEnabled = false
    }
}

It's more verbose, but I think this clearly states your intent - nil coalescing can sometimes be confusing to read and debug (should it be ?? true or ?? false?)


问:
python schedule jobs with different timezones
I want to schedule a python function to run everyday at a certain time for a list of customers with different timezones.

This is basically what I want to do:

```<code>import schedule
import time

def job(text):
    print("Hello " + text)

def add_job(user_tz, time, text):
    schedule.every().day.at(time).do(job(text))
    # the above adds all jobs at local time, I want to use different timezones with these

def run_job():
    while(1):
        schedule.run_pending()
        time.sleep(1)

if __name__=='__main__':
    add_job('America/New_York', "12:00", 'New York')
    add_job('Europe/London', "12:00", 'London')
    run_job()
</code>```

I am using this for posting/receiving some stuff using flask and an external API.

Celery or heroku scheduler or something heavy is not what I am looking for, something lightweight and pythonic for debian(or nix) env would be ideal. I have looked into scheduler, tzcron and APScheduler, but could not figure out how we would be able to use them with timezones.

Also I tried using crontab but could not figure out how to add jobs at run time, since I want to be able to add/remove jobs using the above mentioned functions at runtime as well.

I have some experience with python, but its my first problem with timezones and I dont know much about this, so please feel free to enlighten me if there is something I missed or if there is any other way of doing it.

Thanks!

答:
The arrow library is great for this, and much simpler than the standard date/time (imo). arrow docs.

```<code>import arrow
from datetime import datetime

now = datetime.now()
atime = arrow.get(now)
print(now)
print (atime)

eastern = atime.to('US/Eastern')
print (eastern)
print (eastern.datetime)

2017-11-17 09:53:58.700546
2017-11-17T09:53:58.700546+00:00
2017-11-17T04:53:58.700546-05:00
2017-11-17 04:53:58.700546-05:00
</code>```

I would change your "add_job" method modify all of my incoming dates to a standard time zone (utc for example).

Body:
I want to schedule a python function to run everyday at a certain time for a list of customers with different timezones.

This is basically what I want to do:

import schedule
import time

def job(text):
    print("Hello " + text)

def add_job(user_tz, time, text):
    schedule.every().day.at(time).do(job(text))
    # the above adds all jobs at local time, I want to use different timezones with these

def run_job():
    while(1):
        schedule.run_pending()
        time.sleep(1)

if __name__=='__main__':
    add_job('America/New_York', "12:00", 'New York')
    add_job('Europe/London', "12:00", 'London')
    run_job()

I am using this for posting/receiving some stuff using flask and an external API.

Celery or heroku scheduler or something heavy is not what I am looking for, something lightweight and pythonic for debian(or nix) env would be ideal. I have looked into scheduler, tzcron and APScheduler, but could not figure out how we would be able to use them with timezones.

Also I tried using crontab but could not figure out how to add jobs at run time, since I want to be able to add/remove jobs using the above mentioned functions at runtime as well.

I have some experience with python, but its my first problem with timezones and I dont know much about this, so please feel free to enlighten me if there is something I missed or if there is any other way of doing it.

Thanks!

Body:
The arrow library is great for this, and much simpler than the standard date/time (imo). arrow docs.

import arrow
from datetime import datetime

now = datetime.now()
atime = arrow.get(now)
print(now)
print (atime)

eastern = atime.to('US/Eastern')
print (eastern)
print (eastern.datetime)

2017-11-17 09:53:58.700546
2017-11-17T09:53:58.700546+00:00
2017-11-17T04:53:58.700546-05:00
2017-11-17 04:53:58.700546-05:00

I would change your "add_job" method modify all of my incoming dates to a standard time zone (utc for example).


问:
Angular2 - How to close WebSocketSubject underlying socket
Is there a way to obtain the socket being subscribed by WebSocketSubject?

When a certain condition happens I need to close the underlying socket.

I tried to close it by complete() but it didn't close the socket. The unsubscribed doesn't work either.

Could anybody help me? Or point me in the right direction?

答:
You can call unsubscribe() directly on the WebSocketSubject instance that unsubscribes all observers:

```<code>const subject = Observable.webSocket(...);

...

subject.unsubscribe();
</code>```

See source code: https://github.com/ReactiveX/rxjs/blob/master/src/observable/dom/WebSocketSubject.ts#L269

Body:
You can call unsubscribe() directly on the WebSocketSubject instance that unsubscribes all observers:

const subject = Observable.webSocket(...);

...

subject.unsubscribe();

See source code: https://github.com/ReactiveX/rxjs/blob/master/src/observable/dom/WebSocketSubject.ts#L269


问:
Error on taking screenshot in Selenium c#
I am trying to take screenshot in Selenium C# with a simple code below

```<code>public void takeScreenshot()
    {
        Screenshot screenshot = ((ITakesScreenshot)DriverContext.Driver).GetScreenshot();
        screenshot.SaveAsFile(@"C:\images\image.png", ImageFormat.Png);
    }
</code>```

As soon as I call this method in me test code, it throws the error:

```<code>System.InvalidOperationException: unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-
extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
(Session info: chrome=58.0.3029.110)
(Driver info: chromedriver=2.27.440174
(e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 10.0.10586 x86_64)
</code>```

I researched quite a bit and found that

this might be due to old chrome driver version for which I installed the latest one but it still gives the error

The website might not be navigating to www for which I checked by navigating to www.google.com, but it still does not work.

I am not sure how to resolve this issue. Any suggestion would be helpful.

答:
I'm using this in my TearDown and it's working for me - maybe something with what DriverContext.Driver is resolving to at that point?</p>

```<code>[TearDown]
    public void TearDown()
    {
        if (TestContext.CurrentContext.Result.Outcome != ResultState.Success)
        {
            var screenshot = ((ITakesScreenshot)browser).GetScreenshot();
            var filename = TestContext.CurrentContext.Test.MethodName + "_screenshot_" + DateTime.Now.Ticks + ".jpg";
            var path = "C:\\Temp\\" + filename;
            screenshot.SaveAsFile(path , ScreenshotImageFormat.Jpeg);
            TestContext.AddTestAttachment(path);
        }
        browser.Quit();
    }
</code>```

Body:
I am trying to take screenshot in Selenium C# with a simple code below

public void takeScreenshot()
    {
        Screenshot screenshot = ((ITakesScreenshot)DriverContext.Driver).GetScreenshot();
        screenshot.SaveAsFile(@"C:\images\image.png", ImageFormat.Png);
    }

As soon as I call this method in me test code, it throws the error:

System.InvalidOperationException: unknown error: cannot get automation extension
from unknown error: page could not be found: chrome-
extension://aapnijgdinlhnhlmodcfapnahmbfebeb/_generated_background_page.html
(Session info: chrome=58.0.3029.110)
(Driver info: chromedriver=2.27.440174
(e97a722caafc2d3a8b807ee115bfb307f7d2cfd9),platform=Windows NT 10.0.10586 x86_64)

I researched quite a bit and found that

this might be due to old chrome driver version for which I installed the latest one but it still gives the error

The website might not be navigating to www for which I checked by navigating to www.google.com, but it still does not work.

I am not sure how to resolve this issue. Any suggestion would be helpful.

Body:
I'm using this in my TearDown and it's working for me - maybe something with what DriverContext.Driver is resolving to at that point?

[TearDown]
    public void TearDown()
    {
        if (TestContext.CurrentContext.Result.Outcome != ResultState.Success)
        {
            var screenshot = ((ITakesScreenshot)browser).GetScreenshot();
            var filename = TestContext.CurrentContext.Test.MethodName + "_screenshot_" + DateTime.Now.Ticks + ".jpg";
            var path = "C:\\Temp\\" + filename;
            screenshot.SaveAsFile(path , ScreenshotImageFormat.Jpeg);
            TestContext.AddTestAttachment(path);
        }
        browser.Quit();
    }


问:
convert constexpr n-dimensional array of one type to constexpr n-dimensional array of a different type
Using C++11 or C++14:

I have a:

```<code>constexpr double [2][3][4] = some value;
</code>```

I want constexpr int [2][3][4] from this.

(Actually I will want constexpr my_type [2][3][4], but that should be trivially solvable once int works.)

The only solution I came up with was a container class with operator[] overloaded so it behaves like an array. Is there a way to keep standard array syntax? Or possibly std::array<std::array...>> without creating a new class?

I do not want the input to be std::array - that is a constraint of the system. The input must be C compatible. The converted array can be C++.

答:
If you accept a constexpr std::array<std::array<int, 4U>, 3U>, 2U>, well... using <s>SFINAE</s> tag-dispatching, std::rank, decltype(), auto as return type and std::index_sequence (so a C++14 solution) you can ping-pong play with a getArray() and his helper getArrayH() functions as follows

NOTE: answer modified (improved, IMHO) taking inspiration from a Julius's example (thanks!)

```<code>#include <array>
#include <iostream>
#include <type_traits>

template <typename T>
std::integral_constant<bool, std::rank<T>::value != 0U> isArray ();

template <typename targetT, typename origT, std::size_t Dim>
constexpr auto getArray (origT(&)[Dim]);

template <typename targetT, typename arrT, std::size_t ... Is>
constexpr auto getArrayH (arrT const & arr,
                          std::false_type const &,
                          std::index_sequence<Is...> const &)
 { return std::array<targetT, sizeof...(Is)>{ { targetT(arr[Is])... } }; }

template <typename targetT, typename arrT, std::size_t ... Is>
constexpr auto getArrayH (arrT const & arr,
                          std::true_type const &,
                          std::index_sequence<Is...> const &)
 { return std::array<decltype(getArray<targetT>(arr[0])), sizeof...(Is)>
           { { getArray<targetT>(arr[Is])... } }; }

template <typename targetT, typename origT, std::size_t Dim>
constexpr auto getArray (origT(&arr)[Dim])
 { return getArrayH<targetT>(arr, decltype(isArray<origT>()){},
                             std::make_index_sequence<Dim>{}); }

int main ()
 {
   constexpr double ad3[2][3][4]
    { { { 1.0, 2.0, 3.0, 4.0 },
        { 2.1, 3.1, 4.1, 5.1 },
        { 3.2, 4.2, 5.2, 6.2 } },
      { { 6.3, 5.3, 4.3, 3.3 },
        { 5.4, 4.4, 3.4, 2.4 },
        { 4.5, 3.5, 2.5, 1.5 } } };

   for ( auto const & ad2 : ad3 )
      for ( auto const & ad1 : ad2 )
         for ( auto const & ad0 : ad1 )
            std::cout << ad0 << ' ';

   std::cout << std::endl;

   constexpr auto ai3 = getArray<int>(ad3);

   static_assert(std::is_same<decltype(ai3),
      std::array<std::array<std::array<int, 4U>, 3U>, 2U> const>{}, "!");

   for ( auto const & ai2 : ai3 )
      for ( auto const & ai1 : ai2 )
         for ( auto const & ai0 : ai1 )
            std::cout << ai0 << ' ';

   std::cout << std::endl;
 }
</code>```

Body:
Using C++11 or C++14:

I have a:

constexpr double [2][3][4] = some value;

I want constexpr int [2][3][4] from this.

(Actually I will want constexpr my_type [2][3][4], but that should be trivially solvable once int works.)

The only solution I came up with was a container class with operator[] overloaded so it behaves like an array. Is there a way to keep standard array syntax? Or possibly std::array<std::array...>> without creating a new class?

I do not want the input to be std::array - that is a constraint of the system. The input must be C compatible. The converted array can be C++.

Body:
If you accept a constexpr std::array<std::array<int, 4U>, 3U>, 2U>, well... using <s>SFINAE</s> tag-dispatching, std::rank, decltype(), auto as return type and std::index_sequence (so a C++14 solution) you can ping-pong play with a getArray() and his helper getArrayH() functions as follows

NOTE: answer modified (improved, IMHO) taking inspiration from a Julius's example (thanks!)

#include <array>
#include <iostream>
#include <type_traits>

template <typename T>
std::integral_constant<bool, std::rank<T>::value != 0U> isArray ();

template <typename targetT, typename origT, std::size_t Dim>
constexpr auto getArray (origT(&)[Dim]);

template <typename targetT, typename arrT, std::size_t ... Is>
constexpr auto getArrayH (arrT const & arr,
                          std::false_type const &,
                          std::index_sequence<Is...> const &)
 { return std::array<targetT, sizeof...(Is)>{ { targetT(arr[Is])... } }; }

template <typename targetT, typename arrT, std::size_t ... Is>
constexpr auto getArrayH (arrT const & arr,
                          std::true_type const &,
                          std::index_sequence<Is...> const &)
 { return std::array<decltype(getArray<targetT>(arr[0])), sizeof...(Is)>
           { { getArray<targetT>(arr[Is])... } }; }

template <typename targetT, typename origT, std::size_t Dim>
constexpr auto getArray (origT(&arr)[Dim])
 { return getArrayH<targetT>(arr, decltype(isArray<origT>()){},
                             std::make_index_sequence<Dim>{}); }

int main ()
 {
   constexpr double ad3[2][3][4]
    { { { 1.0, 2.0, 3.0, 4.0 },
        { 2.1, 3.1, 4.1, 5.1 },
        { 3.2, 4.2, 5.2, 6.2 } },
      { { 6.3, 5.3, 4.3, 3.3 },
        { 5.4, 4.4, 3.4, 2.4 },
        { 4.5, 3.5, 2.5, 1.5 } } };

   for ( auto const & ad2 : ad3 )
      for ( auto const & ad1 : ad2 )
         for ( auto const & ad0 : ad1 )
            std::cout << ad0 << ' ';

   std::cout << std::endl;

   constexpr auto ai3 = getArray<int>(ad3);

   static_assert(std::is_same<decltype(ai3),
      std::array<std::array<std::array<int, 4U>, 3U>, 2U> const>{}, "!");

   for ( auto const & ai2 : ai3 )
      for ( auto const & ai1 : ai2 )
         for ( auto const & ai0 : ai1 )
            std::cout << ai0 << ' ';

   std::cout << std::endl;
 }


问:
Displaying the amount of memory allocated
Hi
I'm writing some test stuff to see the amount of memory that allocated displayed correctly

in Windows TasK manager. Below is the code;

```<code>int main(int argc,char* argv[])
{
 struct stat st;
 char commandXCopy[200];
 char commandDelete[200];

 char *fNames[2^16];
 int i =0;
    char *ptr = (char *)malloc(sizeof(char) * 2^32);
     printf("\nTEST");

    if(!ptr)
            printf("\nCan not allocate");
    else
            printf("\nMemory allocate");

     while(1==1)
     {
     };
</code>```

I try to make huge allocations from stack and heap. But all I see on task manager->processes is ~800K.

And I don't see "Can not allocate" message either.

I have Windows 32bit XP Pro and use gcc and application is a dos application.

gcc test.c

Regards

答:
I think you may be suffering under a misapprehension: 2^32 is not 232 (4G, assuming your bytes are eight bits long, which I will for the purposes of this answer) in C.

^ is the bitwise XOR operator. So what you're actually allocating is:

```<code>     binary        hex     decimal
    ---------      ----    -------
    0010 0000      0x20      32
xor 0000 0010      0x02       2
    =========
    0010 0010      0x22      34
</code>```

or 34 bytes. Similarly, 2^31 would give you 29 bytes so what you may think should be a 2G difference (232 - 231) is really only 5 bytes.

If you want to do powers in C, you should look at the pow() function but I doubt you'll be able to get 4G of memory (perhaps on a 64-bit OS but even then, that's an awful lot).

And just one other thing: sizeof(char) is always 1 - there's no need to multiply by it.

Body:
Hi
I'm writing some test stuff to see the amount of memory that allocated displayed correctly

in Windows TasK manager. Below is the code;

int main(int argc,char* argv[])
{
 struct stat st;
 char commandXCopy[200];
 char commandDelete[200];

 char *fNames[2^16];
 int i =0;
    char *ptr = (char *)malloc(sizeof(char) * 2^32);
     printf("\nTEST");

    if(!ptr)
            printf("\nCan not allocate");
    else
            printf("\nMemory allocate");

     while(1==1)
     {
     };

I try to make huge allocations from stack and heap. But all I see on task manager->processes is ~800K.

And I don't see "Can not allocate" message either.

I have Windows 32bit XP Pro and use gcc and application is a dos application.

gcc test.c

Regards

Body:
I think you may be suffering under a misapprehension: 2^32 is not 232 (4G, assuming your bytes are eight bits long, which I will for the purposes of this answer) in C.

^ is the bitwise XOR operator. So what you're actually allocating is:

     binary        hex     decimal
    ---------      ----    -------
    0010 0000      0x20      32
xor 0000 0010      0x02       2
    =========
    0010 0010      0x22      34

or 34 bytes. Similarly, 2^31 would give you 29 bytes so what you may think should be a 2G difference (232 - 231) is really only 5 bytes.

If you want to do powers in C, you should look at the pow() function but I doubt you'll be able to get 4G of memory (perhaps on a 64-bit OS but even then, that's an awful lot).

And just one other thing: sizeof(char) is always 1 - there's no need to multiply by it.


问:
filter several json files with select elements
The code below (in the interactive snippet) works well as long as there is only one select Item, it let's me choose chapters from a json file and prints them below.

How can I have several  elements that are from two different arrays?
Of course I have to change arr into another variable name.
But how do I specify which select element I want to feed?

Disclaimer: I got the code from here and don't completely understand how it works

javascript and html

var arr = [{
    "Content": ["
Heading of Paragraph1

the actual pargraph1
"],
    "Titel": ["Heading of Paragraph1"]
  },
  {
    "Content": ["
Heading of Paragraph2

the actual pargraph2
"],
    "Titel": ["Heading of Paragraph2"]
  }, {
    "Content": ["
Heading of Paragraph3

the actual pargraph3
"],
    "Titel": ["Heading of Paragraph3"]
  }
];

//prepare the options first
var options = arr.map( function( item ){
   return "<option value='" + item.Titel[0] + "'>"+ item.Titel[0] + "</option>"
} ).join( "" );

//set all the options to select and then bind change event
$( "select" ).html( options ).change( function(){
   $( "#paraContent" ).html( "" );
   var val = $(this).val();
   $( "#paraContent" ).html( val.map( function( title ){
      return arr.find( (s) => s.Titel[0] == title ).Content[0];
   }).join( "
" ) )
   //console.log(val);
}); ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/returnselected_paragraphs.js">
    <select name="pargraphs" multiple>
    </select>
    <p id="paraContent">

    </p>
    <input type="submit">
  </form></code>```

this is what I tried

https://jsfiddle.net/rba1amo7/

As you can see, it's loading the second dataset into both elements

答:
The code from @coderbyheart overwrote the content of the paragraph, so I made it an extra parameter. this does what I want

var arr = [{
        "Content": ["
Heading of Paragraph1

the actual pargraph1
"],
        "Titel": ["Heading of Paragraph1"]
      },
      {
        "Content": ["
Heading of Paragraph2

the actual pargraph2
"],
        "Titel": ["Heading of Paragraph2"]
      }, {
        "Content": ["
Heading of Paragraph3

the actual pargraph3
"],
        "Titel": ["Heading of Paragraph3"]
      }
    ];

var arr2 = [
    {
        "Content": ["
Heading of Paragraph4

the actual pargraph4
"],
        "Titel": ["Heading of Paragraph4"]
      }
];

const fillSelect = (data, select,para) => {
    // prepare the options first
    var options = data.map(item => "<option value='" + item.Titel[0] + "'>"+ item.Titel[0] + "</option>").join( "" );

    //set all the options to select and then bind change event
    select
        .html( options )
        .change(function() {
            para.html( "" );
            var val = $(this).val();
            para.html( val.map( title => data.find( s => s.Titel[0] == title ).Content[0]).join( "
" ) )
    });
}

// Now you can reuse the code:

fillSelect(arr, $('select[name=pargraphs]'),$( "#paraContent" ));
fillSelect(arr2, $('select[name=pargraphs2]'),$( "#paraContent2" ));
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action="/returnselected_paragraphs.js">
        <select name="pargraphs" multiple>
        </select>
        <select name="pargraphs2" multiple>
        </select>
        <p id="paraContent">
        </p>
        <p id="paraContent2">
        </p>

      </form></code>```

Body:
The code below (in the interactive snippet) works well as long as there is only one select Item, it let's me choose chapters from a json file and prints them below.

How can I have several  elements that are from two different arrays?
Of course I have to change arr into another variable name.
But how do I specify which select element I want to feed?

Disclaimer: I got the code from here and don't completely understand how it works

javascript and html

var arr = [{
    "Content": ["
Heading of Paragraph1

the actual pargraph1
"],
    "Titel": ["Heading of Paragraph1"]
  },
  {
    "Content": ["
Heading of Paragraph2

the actual pargraph2
"],
    "Titel": ["Heading of Paragraph2"]
  }, {
    "Content": ["
Heading of Paragraph3

the actual pargraph3
"],
    "Titel": ["Heading of Paragraph3"]
  }
];

//prepare the options first
var options = arr.map( function( item ){
   return "<option value='" + item.Titel[0] + "'>"+ item.Titel[0] + "</option>"
} ).join( "" );

//set all the options to select and then bind change event
$( "select" ).html( options ).change( function(){
   $( "#paraContent" ).html( "" );
   var val = $(this).val();
   $( "#paraContent" ).html( val.map( function( title ){
      return arr.find( (s) => s.Titel[0] == title ).Content[0];
   }).join( "
" ) )
   //console.log(val);
});

<form action="/returnselected_paragraphs.js">
    <select name="pargraphs" multiple>
    </select>

    <input type="submit">
  </form>

this is what I tried

https://jsfiddle.net/rba1amo7/

As you can see, it's loading the second dataset into both elements

Body:
The code from @coderbyheart overwrote the content of the paragraph, so I made it an extra parameter. this does what I want

var arr = [{
        "Content": ["<h2>Heading of Paragraph1</h2><p>the actual pargraph1</p>"],
        "Titel": ["Heading of Paragraph1"]
      },
      {
        "Content": ["<h2>Heading of Paragraph2</h2><p>the actual pargraph2</p>"],
        "Titel": ["Heading of Paragraph2"]
      }, {
        "Content": ["<h2>Heading of Paragraph3</h2><p>the actual pargraph3</p>"],
        "Titel": ["Heading of Paragraph3"]
      }
    ];

var arr2 = [
    {
        "Content": ["<h2>Heading of Paragraph4</h2><p>the actual pargraph4</p>"],
        "Titel": ["Heading of Paragraph4"]
      }
];

const fillSelect = (data, select,para) => {
    // prepare the options first
    var options = data.map(item => "<option value='" + item.Titel[0] + "'>"+ item.Titel[0] + "</option>").join( "" );

    //set all the options to select and then bind change event
    select
        .html( options )
        .change(function() {
            para.html( "" );
            var val = $(this).val();
            para.html( val.map( title => data.find( s => s.Titel[0] == title ).Content[0]).join( "</br>" ) )
    });
}

// Now you can reuse the code:

fillSelect(arr, $('select[name=pargraphs]'),$( "#paraContent" ));
fillSelect(arr2, $('select[name=pargraphs2]'),$( "#paraContent2" ));

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form action="/returnselected_paragraphs.js">
        <select name="pargraphs" multiple>
        </select>
        <select name="pargraphs2" multiple>
        </select>
        <p id="paraContent">
        </p>
        <p id="paraContent2">
        </p>

      </form>


问:
Accessing data within a JSON object using javascript
I have the following JSON object returned and I want to access all the "title" values. I have been able to get a new object of all the "pages," but not the "titles." I have tried everything except the correct thing! The "similar" questions on here are straight forward array access questions. This seems to involve nested arrays. Please help! Thanks.

```<code>{
    "batchcomplete": "",
    "continue": {
        "gsroffset": 15,
        "continue": "gsroffset||"
    },
    "query": {
        "pages": {
            "22989": {
                "pageid": 22989,
                "ns": 0,
                "title": "Paris",
                "index": 1
            },
            "59134": {
                "pageid": 59134,
                "ns": 0,
                "title": "Paris Commune",
                "index": 13
            },
            "61371": {
                "pageid": 61371,
                "ns": 0,
                "title": "Paris (disambiguation)",
                "index": 2
            },
            "64129": {
                "pageid": 64129,
                "ns": 0,
                "title": "Catacombs of Paris",
                "index": 11
            },
            "76286": {
                "pageid": 76286,
                "ns": 0,
                "title": "Disneyland Paris",
                "index": 15
            },
            "89106": {
                "pageid": 89106,
                "ns": 0,
                "title": "Paris–Brest–Paris",
                "index": 8
            },
            "357488": {
                "pageid": 357488,
                "ns": 0,
                "title": "Paris Saint-Germain F.C.",
                "index": 10
            },
            "868936": {
                "pageid": 868936,
                "ns": 0,
                "title": "Paris Gun",
                "index": 14
            },
            "2397134": {
                "pageid": 2397134,
                "ns": 0,
                "title": "Paris (Paris Hilton album)",
                "index": 6
            },
            "7618874": {
                "pageid": 7618874,
                "ns": 0,
                "title": "Paris syndrome",
                "index": 9
            },
            "11217925": {
                "pageid": 11217925,
                "ns": 0,
                "title": "Paris Hilton",
                "index": 7
            },
            "23528038": {
                "pageid": 23528038,
                "ns": 0,
                "title": "Paris Jackson (actress)",
                "index": 5
            },
            "30242372": {
                "pageid": 30242372,
                "ns": 0,
                "title": "Paris Agreement",
                "index": 4
            },
            "45259235": {
                "pageid": 45259235,
                "ns": 0,
                "title": "Paris Laxmi",
                "index": 12
            },
            "55340805": {
                "pageid": 55340805,
                "ns": 0,
                "title": "Paris Paris",
                "index": 3
            }
        }
    }
}
</code>```

It wants me to add more details, but I don't know what else I can add.

答:
This uses Object.keys to enumerate over the pages in the JSON.</p>

```<code>"use strict"
const DATA = //your Map
const pages = DATA.query.pages;
const keys = Object.keys(pages); // returns an array of the ID numbers that are properties in each page
let titles = [keys.length]; // initialize an output array

for(let i=0; i < keys.length; i++){
    titles[i] = pages[keys[i]].title;
};
</code>```

Body:
I have the following JSON object returned and I want to access all the "title" values. I have been able to get a new object of all the "pages," but not the "titles." I have tried everything except the correct thing! The "similar" questions on here are straight forward array access questions. This seems to involve nested arrays. Please help! Thanks.

{
    "batchcomplete": "",
    "continue": {
        "gsroffset": 15,
        "continue": "gsroffset||"
    },
    "query": {
        "pages": {
            "22989": {
                "pageid": 22989,
                "ns": 0,
                "title": "Paris",
                "index": 1
            },
            "59134": {
                "pageid": 59134,
                "ns": 0,
                "title": "Paris Commune",
                "index": 13
            },
            "61371": {
                "pageid": 61371,
                "ns": 0,
                "title": "Paris (disambiguation)",
                "index": 2
            },
            "64129": {
                "pageid": 64129,
                "ns": 0,
                "title": "Catacombs of Paris",
                "index": 11
            },
            "76286": {
                "pageid": 76286,
                "ns": 0,
                "title": "Disneyland Paris",
                "index": 15
            },
            "89106": {
                "pageid": 89106,
                "ns": 0,
                "title": "Paris–Brest–Paris",
                "index": 8
            },
            "357488": {
                "pageid": 357488,
                "ns": 0,
                "title": "Paris Saint-Germain F.C.",
                "index": 10
            },
            "868936": {
                "pageid": 868936,
                "ns": 0,
                "title": "Paris Gun",
                "index": 14
            },
            "2397134": {
                "pageid": 2397134,
                "ns": 0,
                "title": "Paris (Paris Hilton album)",
                "index": 6
            },
            "7618874": {
                "pageid": 7618874,
                "ns": 0,
                "title": "Paris syndrome",
                "index": 9
            },
            "11217925": {
                "pageid": 11217925,
                "ns": 0,
                "title": "Paris Hilton",
                "index": 7
            },
            "23528038": {
                "pageid": 23528038,
                "ns": 0,
                "title": "Paris Jackson (actress)",
                "index": 5
            },
            "30242372": {
                "pageid": 30242372,
                "ns": 0,
                "title": "Paris Agreement",
                "index": 4
            },
            "45259235": {
                "pageid": 45259235,
                "ns": 0,
                "title": "Paris Laxmi",
                "index": 12
            },
            "55340805": {
                "pageid": 55340805,
                "ns": 0,
                "title": "Paris Paris",
                "index": 3
            }
        }
    }
}

It wants me to add more details, but I don't know what else I can add.

Body:
This uses Object.keys to enumerate over the pages in the JSON.

"use strict"
const DATA = //your Map
const pages = DATA.query.pages;
const keys = Object.keys(pages); // returns an array of the ID numbers that are properties in each page
let titles = [keys.length]; // initialize an output array

for(let i=0; i < keys.length; i++){
    titles[i] = pages[keys[i]].title;
};


问:
What's the smallest subset of language features you need to bootstrap it's compiler?
What would be the absolute necessary core features of a language (inspired from C) as a sub-language which can be used to write a compiler for the whole language?</p>

答:
You need a while loop, if, one true integer variable, and a way to read and write a file. That's it. (Actually, the file reading and writing part is nice-to-have, but not strictly necessary – You only need it to get information into and out of the program. And if you can read and write a file, then you don't need the integer variable anymore, since you can use the file as a temporary store.)

while, if and one integer variable is Turing-complete, i.e. it can compute any Turing-computable function. A compiler is a Turing-computable function. A compiler which cannot take any input or produce any output is pretty boring, so you need to have a way to read some input and write some output.


问:
Qt doesn't seem to process resource file
I've created resource file in Qt, and I try to access those resources from my application but I'm getting an error:

```<code>:-1: error: [debug/qrc_Resources.cpp] Error 2
</code>```

Where my resource file is called Resource.qrc. Any ideas how to overcome it?

答:
This error can be caused by a lot of different things. It's a stupid error because it just tells you there is an error without telling you directly what the error is. But you can find out what caused the error by going to the Compile Output tab. Usually the cause of the error is the first thing in red. This is what I had in my case:

Here the first thing in red (which I circled in orange to make it visible) says "virtual memory exhausted: Cannot allocate memory" which means that the compiler was out of memory (which makes sense because my qrc_resource.cpp file was 33MB large).

What you should do to solve the problem depends on what the cause of the error is. In my case, since the compiler was out of memory, the solution was to allow my virtual machine to use more memory. But if the cause of your error is different, the solution for you might completely different.

It's really stupid that it just says "error 1" and nothing else and you have to look at the compile output to find out what the error actually is. I wish they will fix that in a future version of GCC. In the mean time, you can see what the error is in the Compile Output tab.

Body:
I've created resource file in Qt, and I try to access those resources from my application but I'm getting an error:

:-1: error: [debug/qrc_Resources.cpp] Error 2

Where my resource file is called Resource.qrc. Any ideas how to overcome it?


问:
Project Not deploy on emulator in xamarin android native app
Console Output Message:

Additionally, check Build->Configuration Manager to ensure this
  project is set to Deploy for this configuration.

答:
The error message indicates you are not deploying the created binary to the device.

In Visual Studio open the dropdown that says "Debug", select "Configuration Manager" and make sure the checkbox "Deploy" is set for your Android project for the configuration you use.


问:
optimal solution to sort contours of image by their areas using which OpenCV 3 and python 3
What is the best (optimal) solution to sort contours of within an image using OpenCV 3 and Python 3?
I try this. Is it the best solution?

```<code>_, contours, _ = cv2.findContours(image , cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
areas = list(map(lambda c : cv2.contourArea(c), contours))
contoursWithAreas = zip(contours, areas)
sortedContoursWithArea = sorted(contoursWithAreas, key=lambda s : s[1])
sortedContours ,sortedAreas = zip(*sortedContoursWithArea)
</code>```

finally we have sorted Contours by areas in sortedContours variable.

答:
As we all know, the contours is a list of np.ndarray. So we cann't avoid using numpy. Then why not use np.argsort()?

```<code>cnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]
areas = np.array([cv2.contourArea(cnt) for cnt in cnts])
idxs  = areas.argsort()
cnts2 = [cnts[i] for i in idxs]
</code>```

Body:
What is the best (optimal) solution to sort contours of within an image using OpenCV 3 and Python 3?
I try this. Is it the best solution?

_, contours, _ = cv2.findContours(image , cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
areas = list(map(lambda c : cv2.contourArea(c), contours))
contoursWithAreas = zip(contours, areas)
sortedContoursWithArea = sorted(contoursWithAreas, key=lambda s : s[1])
sortedContours ,sortedAreas = zip(*sortedContoursWithArea)

finally we have sorted Contours by areas in sortedContours variable.

Body:
As we all know, the contours is a list of np.ndarray. So we cann't avoid using numpy. Then why not use np.argsort()?

cnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]
areas = np.array([cv2.contourArea(cnt) for cnt in cnts])
idxs  = areas.argsort()
cnts2 = [cnts[i] for i in idxs]


问:
How to keep checkboxes checked after form submit?
I have some checkboxes in an array generated dynamically using a while loop like in the code below. When the checkbox(es) are checked and the form submitted, the value is passed to a PHP variable. However, after the form is submitted and the page loads, the checkboxes do not remain checked. How do I make it so that they stay checked after the form is submitted and the page reloads?

```<code>...
<form method="POST">
    <input type="checkbox" name="checkArr[]" value="2">
    <input type="checkbox" name="checkArr[]" value="6">
    <input type="checkbox" name="checkArr[]" value="1">
    <input type="checkbox" name="checkArr[]" value="11">
    <input type="submit" name="submit-form">
</form>
...
<?php
if (isset($_REQUEST['submit-form']) && isset($_REQUEST['checkArr'])) {
    $checkedNumbers = implode(',', $_REQUEST['checkArr']);
}
?>
</code>```

Thanks in advance.

答:
Figured it out. Changed the input boxes to:</p>

```<code><input type="checkbox" name="checkArr[]" value="$dynamic_val" <?php (in_array($dynamic_val, $checkArr) ? ' checked' : '');?>>
</code>```

Body:
I have some checkboxes in an array generated dynamically using a while loop like in the code below. When the checkbox(es) are checked and the form submitted, the value is passed to a PHP variable. However, after the form is submitted and the page loads, the checkboxes do not remain checked. How do I make it so that they stay checked after the form is submitted and the page reloads?

...
<form method="POST">
    <input type="checkbox" name="checkArr[]" value="2">
    <input type="checkbox" name="checkArr[]" value="6">
    <input type="checkbox" name="checkArr[]" value="1">
    <input type="checkbox" name="checkArr[]" value="11">
    <input type="submit" name="submit-form">
</form>
...
<?php
if (isset($_REQUEST['submit-form']) && isset($_REQUEST['checkArr'])) {
    $checkedNumbers = implode(',', $_REQUEST['checkArr']);
}
?>

Thanks in advance.

Body:
Figured it out. Changed the input boxes to:

<input type="checkbox" name="checkArr[]" value="$dynamic_val" <?php (in_array($dynamic_val, $checkArr) ? ' checked' : '');?>>


问:
Large eCommerce site: Is it time for HTML5?
I currently work for a large company and I design for their high-traffic ecommerce website. We support tens-of-thousands of users across a variety of browsers. Our current browser stats point to most people using either Firefox 3+ and IE8. There are about 5% of users still on IE6.

Is it time to start coding for the future and impliment HTML5 across the site? Is it a responsible thing to do or should I wait a year for people to upgrade to better supporting browsers?

Thank you.

答:
I would say that the 5% of users still on IE6 will probably remain on IE6. They either aren't interested in upgrading (perhaps they don't know about these things), or are restricted to IE6 by security policies in their workplace. In particular I've found that a number of our clients are not upgrading from IE6 because their IT teams consider it to be too big a change, or their existing software is not compatible with anything else.

Therefore, my advice is: go HTML5. With a bit of work you can work around IE6's deficiencies (look at Modernizr, CSS3PIE for ideas). And that way, the other 95% of customers get a better experience.


问:
Laravel 5 with Xdebug always throws "The payload is invalid."
I configured Xdebug on VScode to debug my laravel application. But, when I start to debug, laravel always throws this error: Exception has occurred. Illuminate\Contracts\Encryption\DecryptException: The payload is invalid.

I already tried to run php artisan optimize.

Anyone here already faced this issue? I'm using Laravel 5.5

Ps. I tried to debug a Laravel 4 application. It worked without any issues. So, I think it may be something specific for Laravel 5.

答: The @ceejayoz comment solved the issue. I run php artisan otimize, and the clear all my cookies on the browser, and it started to work properly. </p>