问:
jQuery smooth scrolling bug double click and others
nowadays I'm doing a website for a consultancy, and I'm using Bootstrap for that, the website contains just one page and for make more practical I put some buttons in a navbar fixed top and the objective of that is when you click on the button, the page scroll to the topic, but I have a problem, when I click twice it seems to have a bug, and when I'm in a specific topic and I want to change clicking another buttom, the page scroll wrong, like a few pixels higher (?????) . I really don't know what is happening, and I tried every js to fix and nothing helped me.

Here is my code:

$(document).ready(function() {
  setBindings();
});

function setBindings() {
  $("nav a").click(function(e) {
    //e.preventDefault();
    e.preventDefault();
    var sectionID = "conteudo-" + e.currentTarget.id;
    $("html body").animate({
      scrollTop: $("#" + sectionID).offset().top
    }, 1000)
  })
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
.capa {
  height: 100%;
  overflow: auto;
  width: 100%;
}

body {
  background-attachment: fixed;
  font-family: Helvetica, Arial, sans-serif;
  overflow-x: hidden;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#barra-navegacao">
            alternar navegação

          </button>

Home

Sobre

Serviços

Contato

Mande seu currículo

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pha

    Saiba mais

Sobre nós

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Serviços

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Serviços

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

```

答:
Very Interesting behavior... It took me a while to figure out but the culprit is css.. Remove css where you give it height and width of 100%, and it works ok.</p>

```<code>     <style>
         body {
          background-attachment: fixed;
          font-family: Helvetica, Arial, sans-serif;
          overflow-x: hidden;
        }

     </style>
    $(document).ready(function() {
    $("nav").find("a").click(function(e) {
        e.preventDefault();
        var section = $(this).attr("href");
        $('html, body').animate({
              scrollTop: $(section).offset().top
           }, 2000);
    });

});
</code>```

Body:
nowadays I'm doing a website for a consultancy, and I'm using Bootstrap for that, the website contains just one page and for make more practical I put some buttons in a navbar fixed top and the objective of that is when you click on the button, the page scroll to the topic, but I have a problem, when I click twice it seems to have a bug, and when I'm in a specific topic and I want to change clicking another buttom, the page scroll wrong, like a few pixels higher (?????) . I really don't know what is happening, and I tried every js to fix and nothing helped me.

Here is my code:

$(document).ready(function() {
  setBindings();
});

function setBindings() {
  $("nav a").click(function(e) {
    //e.preventDefault();
    e.preventDefault();
    var sectionID = "conteudo-" + e.currentTarget.id;
    $("html body").animate({
      scrollTop: $("#" + sectionID).offset().top
    }, 1000)
  })
}

html,
body,
.capa {
  height: 100%;
  overflow: auto;
  width: 100%;
}

body {
  background-attachment: fixed;
  font-family: Helvetica, Arial, sans-serif;
  overflow-x: hidden;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#barra-navegacao">
            alternar navegação

          </button>

Home

Sobre

Serviços

Contato

Mande seu currículo

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pha

    Saiba mais

Sobre nós

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Serviços

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Serviços

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Lorem ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vitae pharetra mi. Quisque sit amet mattis justo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed nibh felis, ultricies vitae nisi in, euismod accumsan diam. Proin congue tempor pharetra. Vestibulum gravida sed velit non efficitur. Vivamus blandit, neque id dignissim ultrices, sapien augue vestibulum velit, a sollicitudin justo dolor ut elit. Donec ultricies euismod mi, id venenatis justo porttitor vitae. Duis elit nisi, faucibus eu velit non, suscipit pellentesque lacus.

Body:
Very Interesting behavior... It took me a while to figure out but the culprit is css.. Remove css where you give it height and width of 100%, and it works ok.

     <style>
         body {
          background-attachment: fixed;
          font-family: Helvetica, Arial, sans-serif;
          overflow-x: hidden;
        }

     </style>
    $(document).ready(function() {
    $("nav").find("a").click(function(e) {
        e.preventDefault();
        var section = $(this).attr("href");
        $('html, body').animate({
              scrollTop: $(section).offset().top
           }, 2000);
    });

});


来源: stackexchange

问:
Does SSL protect documents sent over it?
If I understand correctly, SSL will protect (encrypt) HTTP transfer sent over it. But does this apply only to HTTP commands and responses?

If I GET a plain text file and someone intercepts my transaction, do they see plain text or encrypted text?

答:
From http://whatismyipaddress.com/ssl

A Secured Socket Layer, or SSL, is the usual way that a website creates a secure connection with a web browser. Whenever a web surfer visits a secure site that uses SSL technology, it creates an encrypted link between their browser session and the web server.

From above they don't see plaint text, text will be encrypted.

ContentLicense: CC BY-SA 2.5


问:
join function only echoing 1 product of the database
I made a model function so it will echo the products that belong to the profile user I clicked on, the thing is only the first product of that user gets echoed. For example I have an account that uploaded a total of 7 products and the function only shows the first product on the page..

This are the model functions:

```<code>function getdata_aangeboden($user_id){
  $this->db->select("users.*,products.*");
  $this->db->from('users');
  $this->db->join('products','products.user_id = users.user_id','left');
  $this->db->where('users.user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

    // Gets a list of multiple users.
 function getdata($user_id){
  $this->db->select("*");
  $this->db->from('users');
  $this->db->where('user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }
</code>```

Controller function:

```<code><?php foreach($products as $product) { ?>
  <div class="main-gifts">
      <a href="<?php echo base_url() ?>/Product/details/<?php echo $product->product_id; ?>">
        <img id="fotos" src="<?php echo base_url(); ?>upload/<?php echo $product->product_foto_thumb; ?>">
        </a>
        <div class="products_discription">
            <h3><?php echo $product->product_naam; ?></h3>
            <div class="ophaal_plaats">
                <p>Plaats: <?php  echo $product->ophaal_plaats; ?></p>
            </div>
            <div class="aangeboden_door">
            <p> <?php
                    foreach($userdetail_list as $row){ ?>
              <tr>
                  <td><?php echo $row->voornaam;?></td>
               </tr>
                    <?php } ?></p>
          </div>
          <div class="status">
          </div>
      </div>
        <a href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product->product_id; ?>"><input type="button" class="btn btn-default cb" value="Cadeau bewerken"></input> </a>
  </div>
 <?php } ?>
</code>```

Can someone explain to me why it only shows 1 product and not all the products that belong to the same user_id?
thanks

When I print $products:

```<code>} ?> Array ( [0] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 85 [product_naam] => HIHIHIHI [product_beschrijving] => [ophaal_plaats] => ALLOVER [product_foto] => new_f5cea9c914751e0ad0048800ffec3d05.jpg [product_foto_thumb] => thumb_f5cea9c914751e0ad0048800ffec3d05.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 2 ) [1] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 86 [product_naam] => HUHUUHU [product_beschrijving] => [ophaal_plaats] => NOWHERE [product_foto] => new_ba2430d2b531bc421f27b5f14667cffb.jpg [product_foto_thumb] => thumb_ba2430d2b531bc421f27b5f14667cffb.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 4 ) [2] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 87 [product_naam] => HOHOHO [product_beschrijving] => [ophaal_plaats] => NOIDEA [product_foto] => new_e1dfb9a860859ff882d13435e796578c.jpg [product_foto_thumb] => thumb_e1dfb9a860859ff882d13435e796578c.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 7 ) [3] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 88 [product_naam] => HEHEHE [product_beschrijving] => [ophaal_plaats] => Korea [product_foto] => new_c080495685ed05ab5d4f8a7dcdb8e668.jpg [product_foto_thumb] => thumb_c080495685ed05ab5d4f8a7dcdb8e668.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 8 ) [4] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 89 [product_naam] => ugilh [product_beschrijving] => hjgluhsfkh;sidh fihsdiuhfluisdhauighsudiahguivhadsuihudisahluihvsaduihvluidsahuihv [ophaal_plaats] => Amsterdam [product_foto] => new_c6dd9fa0dc0be0830ed43940b5907115.jpg [product_foto_thumb] => thumb_c6dd9fa0dc0be0830ed43940b5907115.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 1 ) [5] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 93 [product_naam] => 11111 [product_beschrijving] => frfewefwe [ophaal_plaats] => 1111 [product_foto] => new_14de53777d648dcbe31dea26fa031ced.jpg [product_foto_thumb] => thumb_14de53777d648dcbe31dea26fa031ced.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 2 ) [6] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 94 [product_naam] => hiu;ij [product_beschrijving] => hk;h uihucuhsducuisdhuvsdphvjuisjhuvsudih [ophaal_plaats] => Amsterdam [product_foto] => new_f68becfc0741d3a2300f49ed5bcf58a5.jpg [product_foto_thumb] => thumb_f68becfc0741d3a2300f49ed5bcf58a5.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 5 ) )
</code>```

答:
i have found that you have only put the

tr

tag, but not the

table

tag, this may cause a issue,so please review my answer below

```<code><?php
  foreach($products as $product) { ?>
    <div class="main-gifts">
        <a href="<?php echo base_url() ?>/Product/details/<?php echo $product->product_id; ?>">
            <img id="fotos" src="<?php echo base_url(); ?>upload/<?php echo $product->product_foto_thumb; ?>">
        </a>
        <div class="products_discription">
            <h3><?php echo $product->product_naam; ?></h3>
            <div class="ophaal_plaats">
                <p>Plaats: <?php  echo $product->ophaal_plaats; ?></p>
            </div>
            <div class="aangeboden_door">
                <p>
                    <table>
                    <?php
                    foreach($userdetail_list as $row){ ?>
                        <tr>
                            <td><?php echo $row->voornaam;?></td>
                        </tr>
                    <?php } ?>
                    </table>
                </p>
            </div>
            <div class="status">
            </div>
        </div>
        <a href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product->product_id; ?>">
            <input type="button" class="btn btn-default cb" value="Cadeau bewerken">
        </a>
    </div>
<?php } ?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I made a model function so it will echo the products that belong to the profile user I clicked on, the thing is only the first product of that user gets echoed. For example I have an account that uploaded a total of 7 products and the function only shows the first product on the page..

This are the model functions:

function getdata_aangeboden($user_id){
  $this->db->select("users.*,products.*");
  $this->db->from('users');
  $this->db->join('products','products.user_id = users.user_id','left');
  $this->db->where('users.user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

    // Gets a list of multiple users.
 function getdata($user_id){
  $this->db->select("*");
  $this->db->from('users');
  $this->db->where('user_id', $user_id);
  $query = $this->db->get();
  return $query->result();
 }

Controller function:

<?php foreach($products as $product) { ?>

      <a href="<?php echo base_url() ?>/Product/details/<?php echo $product->product_id; ?>">
        <img id="fotos" src="<?php echo base_url(); ?>upload/<?php echo $product->product_foto_thumb; ?>">

<?php echo $product->product_naam; ?>

Plaats: <?php  echo $product->ophaal_plaats; ?>

 <?php
                    foreach($userdetail_list as $row){ ?>

                  <?php echo $row->voornaam;?>

                    <?php } ?>

        <a href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product->product_id; ?>"><input type="button" class="btn btn-default cb" value="Cadeau bewerken"></input>

 <?php } ?>

Can someone explain to me why it only shows 1 product and not all the products that belong to the same user_id?
thanks

When I print $products:

} ?> Array ( [0] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 85 [product_naam] => HIHIHIHI [product_beschrijving] => [ophaal_plaats] => ALLOVER [product_foto] => new_f5cea9c914751e0ad0048800ffec3d05.jpg [product_foto_thumb] => thumb_f5cea9c914751e0ad0048800ffec3d05.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 2 ) [1] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 86 [product_naam] => HUHUUHU [product_beschrijving] => [ophaal_plaats] => NOWHERE [product_foto] => new_ba2430d2b531bc421f27b5f14667cffb.jpg [product_foto_thumb] => thumb_ba2430d2b531bc421f27b5f14667cffb.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 4 ) [2] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 87 [product_naam] => HOHOHO [product_beschrijving] => [ophaal_plaats] => NOIDEA [product_foto] => new_e1dfb9a860859ff882d13435e796578c.jpg [product_foto_thumb] => thumb_e1dfb9a860859ff882d13435e796578c.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 7 ) [3] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 88 [product_naam] => HEHEHE [product_beschrijving] => [ophaal_plaats] => Korea [product_foto] => new_c080495685ed05ab5d4f8a7dcdb8e668.jpg [product_foto_thumb] => thumb_c080495685ed05ab5d4f8a7dcdb8e668.jpg [date_created] => 2017-10-25 [date_updated] => 2017-10-25 [category_id] => 8 ) [4] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 89 [product_naam] => ugilh [product_beschrijving] => hjgluhsfkh;sidh fihsdiuhfluisdhauighsudiahguivhadsuihudisahluihvsaduihvluidsahuihv [ophaal_plaats] => Amsterdam [product_foto] => new_c6dd9fa0dc0be0830ed43940b5907115.jpg [product_foto_thumb] => thumb_c6dd9fa0dc0be0830ed43940b5907115.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 1 ) [5] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 93 [product_naam] => 11111 [product_beschrijving] => frfewefwe [ophaal_plaats] => 1111 [product_foto] => new_14de53777d648dcbe31dea26fa031ced.jpg [product_foto_thumb] => thumb_14de53777d648dcbe31dea26fa031ced.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 2 ) [6] => stdClass Object ( [user_id] => 4 [email] => jeremy@gmail.com [voornaam] => Jeremy [achternaam] => Mathieu [straat] => [huisnummer] => 22 [postcode] => 1223lL [woonplaats] => Rotterdam [wachtwoord] => $2y$10$rO.e4j0dofAUZSWV8sP6yOHYqLzhPkRk9FjBylwbaMMmWRoCBp2oy [beschrijving] => Hallo ik ben Jeremy [geboortedatum] => 2017-06-10 [startdatum] => 2017-06-29 [geslacht] => Man [reset_password_key] => [profiel_foto] => 1498736939jeremy.jpg [product_id] => 94 [product_naam] => hiu;ij [product_beschrijving] => hk;h uihucuhsducuisdhuvsdphvjuisjhuvsudih [ophaal_plaats] => Amsterdam [product_foto] => new_f68becfc0741d3a2300f49ed5bcf58a5.jpg [product_foto_thumb] => thumb_f68becfc0741d3a2300f49ed5bcf58a5.jpg [date_created] => 2017-10-26 [date_updated] => 2017-10-26 [category_id] => 5 ) )

Body:
i have found that you have only put the

tr

tag, but not the

table

tag, this may cause a issue,so please review my answer below

<?php
  foreach($products as $product) { ?>
    <div class="main-gifts">
        <a href="<?php echo base_url() ?>/Product/details/<?php echo $product->product_id; ?>">
            <img id="fotos" src="<?php echo base_url(); ?>upload/<?php echo $product->product_foto_thumb; ?>">
        </a>
        <div class="products_discription">
            <h3><?php echo $product->product_naam; ?></h3>
            <div class="ophaal_plaats">
                <p>Plaats: <?php  echo $product->ophaal_plaats; ?></p>
            </div>
            <div class="aangeboden_door">
                <p>
                    <table>
                    <?php
                    foreach($userdetail_list as $row){ ?>
                        <tr>
                            <td><?php echo $row->voornaam;?></td>
                        </tr>
                    <?php } ?>
                    </table>
                </p>
            </div>
            <div class="status">
            </div>
        </div>
        <a href="<?php echo base_url() ?>/KdGwController/details_bewerken/<?php echo $product->product_id; ?>">
            <input type="button" class="btn btn-default cb" value="Cadeau bewerken">
        </a>
    </div>
<?php } ?>


问:
docker bridging localhost port
There is a chatbot-service running on my local machine at Port 50160. This port is for receiving messages from my nodejs-service in the docker container. To send messages to the chat-service the docker-container has port 8080open. This works fine.

I start it using docker run -p 8080:8080  registry.gitlab.com/abc/def/adapter-xyz.

But sending a response from the docker-container to the chatbot returns the following error in the docker container:

```<code>ChatConnector: message received.
Error: connect ECONNREFUSED 127.0.0.1:50160
    at Object.exports._errnoException (util.js:1020:11)
    at exports._exceptionWithHostPort (util.js:1043:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
</code>```

It seems that it cannot send back a response to chatbot (running on my machine). Any idea?

答:
```<code>docker run --network=host
</code>```

can set the network of the container as host, so you can access.127.0.0.1 from the container.
but this doesn't work on osx

Title: docker bridging localhost port

Body:
There is a chatbot-service running on my local machine at Port 50160. This port is for receiving messages from my nodejs-service in the docker container. To send messages to the chat-service the docker-container has port 8080open. This works fine.

I start it using docker run -p 8080:8080  registry.gitlab.com/abc/def/adapter-xyz.

But sending a response from the docker-container to the chatbot returns the following error in the docker container:

ChatConnector: message received.
Error: connect ECONNREFUSED 127.0.0.1:50160
    at Object.exports._errnoException (util.js:1020:11)
    at exports._exceptionWithHostPort (util.js:1043:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)

It seems that it cannot send back a response to chatbot (running on my machine). Any idea?

Body:
docker run --network=host

can set the network of the container as host, so you can access.127.0.0.1 from the container.
but this doesn't work on osx


问:
Preflight request in VueJS with axios
I am a bit stuck with getting a response from the meetup API. The error I am getting:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Here's my code:

```<code>var config = {'Access-Control-Allow-Headers': 'Authorization'}

axios.get(`https://api.meetup.com/self/calendar?&sign=true&photo-host=public&page=20`, {headers: config})
.then(response => {
  console.log(response.data)
  this.posts = response.data
})
.catch(e => {
  this.errors.push(e)
})
</code>```

I've read a little bit on CORS here Cross-Origin Resource Sharing (CORS) but all my attempts in getting this to work have failed.

Can any of you shed some light on this?

Thanks,

Manu

答: your api is not served on same host. either use reverse proxy like nginx or use cors toggle extension.</p>

Title: Preflight request in VueJS with axios

Body:
I am a bit stuck with getting a response from the meetup API. The error I am getting:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

Here's my code:

var config = {'Access-Control-Allow-Headers': 'Authorization'}

axios.get(`https://api.meetup.com/self/calendar?&sign=true&photo-host=public&page=20`, {headers: config})
.then(response => {
  console.log(response.data)
  this.posts = response.data
})
.catch(e => {
  this.errors.push(e)
})

I've read a little bit on CORS here Cross-Origin Resource Sharing (CORS) but all my attempts in getting this to work have failed.

Can any of you shed some light on this?

Thanks,

Manu


问:
RabbitMQ 3.5.6 Could not establish TCP connection to any of the configured hosts (Bunny::TCPConnectionFailedForAllHosts)
I'm trying to connect to RabbitMQ server but always got these errors:

```<code>W, [2015-12-08T15:38:01.993251 #37405]  WARN -- #<Bunny::Session:0x7fe07b894f78 guest@localhost:5672, vhost=/dev_prod, addresses=[localhost:5672]>: An empty frame was received while opening the connection. In RabbitMQ <= 3.1 this could mean an authentication issue.
</code>```

And

```<code>.../.rvm/gems/ruby-2.1.2/gems/bunny-2.2.0/lib/bunny/session.rb:315:in `rescue in start': Could not establish TCP connection to any of the configured hosts (Bunny::TCPConnectionFailedForAllHosts)
</code>```

I'm using Ruby 2.1.2, RabbitMQ 3.5.6 on MAC OS.
Sorry I'm the newbie in RabbitMQ, just trying to use it but cant handle the issue.
Please give me some advises.

答:
this is probably becuase you either did not pass username and password or passed wrong ones.

The defaults are guest and guest both for username and password.

Try to initialize the connection like this:

```<code> conn = Bunny.new(host:  'localhost',
                  port:  '5672',
                  vhost: '/',
                  user:  'guest',
                  pass:  'guest')
 conn.start
</code>```

and see what happens

Body:
I'm trying to connect to RabbitMQ server but always got these errors:

W, [2015-12-08T15:38:01.993251 #37405]  WARN -- #<Bunny::Session:0x7fe07b894f78 guest@localhost:5672, vhost=/dev_prod, addresses=[localhost:5672]>: An empty frame was received while opening the connection. In RabbitMQ <= 3.1 this could mean an authentication issue.

And

.../.rvm/gems/ruby-2.1.2/gems/bunny-2.2.0/lib/bunny/session.rb:315:in `rescue in start': Could not establish TCP connection to any of the configured hosts (Bunny::TCPConnectionFailedForAllHosts)

I'm using Ruby 2.1.2, RabbitMQ 3.5.6 on MAC OS.
Sorry I'm the newbie in RabbitMQ, just trying to use it but cant handle the issue.
Please give me some advises.

Body:
this is probably becuase you either did not pass username and password or passed wrong ones.

The defaults are guest and guest both for username and password.

Try to initialize the connection like this:

 conn = Bunny.new(host:  'localhost',
                  port:  '5672',
                  vhost: '/',
                  user:  'guest',
                  pass:  'guest')
 conn.start

and see what happens


问:
Remove trailing whitespace recursively only at end of file using grep/sed?
Basically, I've got about 1,500 files and the last character of any of these files should not be any type of white space.

How do I check a bunch of files to make sure that they don't end in some form of whitespace?(newline, space, carriage return, tab, etc.)?

答:
```<code>ruby -e 's=ARGF.read;s.rstrip!;print s' file
</code>```

basically, read the whole file, strip the last whitespace if any, and print out the contents. So this solution is not for VERY huge files.

Body:
ruby -e 's=ARGF.read;s.rstrip!;print s' file

basically, read the whole file, strip the last whitespace if any, and print out the contents. So this solution is not for VERY huge files.


问:
edit a JSON file in Robot Framework
I want to add driver=1 to my sample_json.json file but can't figure out a way to write these changes permanently. This code saves the key-value to the object ${json_obj} but does not make any changes to the file sample_json.json

sample_json.json

```<code>{
    "Phones": {

        "debug": "on",

        "phone1": {
            "key":"value"
        },

        "phone2": {
            "key":"value"
        }
    }
}
</code>```

Robot file

```<code>*** Settings ***
Library    JSONLibrary

*** Variables ***
${SUBSCRIBER_A}    phone1

*** Test Cases ***
testcase
   test    ${SUBSCRIBER_A}

*** Keywords ***
test
    [Arguments]    ${SUBSCRIBER_A}
    ${json_obj}=    Load JSON From File     sample_json.json
    ${object_to_add}=   Create Dictionary   driver=1
    ${json_obj}=    Add Object To Json    ${json_obj}    $..${SUBSCRIBER_A}    ${object_to_add}
</code>```

答:
Thanks for helping guys! Following is the code how it was done.
I used the library operating system for writing the changes to the file but first used Convert JSON To String keyword on it.

```<code>*** Settings ***
Library    JSONLibrary
Library    OperatingSystem

*** Variables ***
${SUBSCRIBER_A}    phone1

*** Test Cases ***
testcase
   test    ${SUBSCRIBER_A}

*** Keywords ***
test
    [Arguments]    ${SUBSCRIBER_A}
    ${json_obj}=    Load JSON From File     example.json
    ${object_to_add}=   Create Dictionary   driver=1
    ${json_obj}=    Add Object To Json    ${json_obj}    $..${SUBSCRIBER_A}    ${object_to_add}
    ${new_obj}=    Convert JSON To String    ${json_obj}
    Create File    example.json    ${new_obj}    UTF-8
</code>```

Title: edit a JSON file in Robot Framework

Body:
I want to add driver=1 to my sample_json.json file but can't figure out a way to write these changes permanently. This code saves the key-value to the object ${json_obj} but does not make any changes to the file sample_json.json

sample_json.json

{
    "Phones": {

        "debug": "on",

        "phone1": {
            "key":"value"
        },

        "phone2": {
            "key":"value"
        }
    }
}

Robot file

*** Settings ***
Library    JSONLibrary

*** Variables ***
${SUBSCRIBER_A}    phone1

*** Test Cases ***
testcase
   test    ${SUBSCRIBER_A}

*** Keywords ***
test
    [Arguments]    ${SUBSCRIBER_A}
    ${json_obj}=    Load JSON From File     sample_json.json
    ${object_to_add}=   Create Dictionary   driver=1
    ${json_obj}=    Add Object To Json    ${json_obj}    $..${SUBSCRIBER_A}    ${object_to_add}

Body:
Thanks for helping guys! Following is the code how it was done.
I used the library operating system for writing the changes to the file but first used Convert JSON To String keyword on it.

*** Settings ***
Library    JSONLibrary
Library    OperatingSystem

*** Variables ***
${SUBSCRIBER_A}    phone1

*** Test Cases ***
testcase
   test    ${SUBSCRIBER_A}

*** Keywords ***
test
    [Arguments]    ${SUBSCRIBER_A}
    ${json_obj}=    Load JSON From File     example.json
    ${object_to_add}=   Create Dictionary   driver=1
    ${json_obj}=    Add Object To Json    ${json_obj}    $..${SUBSCRIBER_A}    ${object_to_add}
    ${new_obj}=    Convert JSON To String    ${json_obj}
    Create File    example.json    ${new_obj}    UTF-8


问:
Vertical aligning doesn't work on first page load
I'm trying to vertically center a div using

```<code>.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
</code>```

however, I've noticed that on first page load, it doesn't work well. The div moves up to the top of the page. On refresh, everything works properly and the div is vertically centered. What can I do to solve this?

答:
To vertically center content of div you can use flex https://css-tricks.com/snippets/css/a-guide-to-flexbox/#article-header-id-7</p>

```<code>display: flex;
align-items: center;
</code>```

Body:
I'm trying to vertically center a div using

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

however, I've noticed that on first page load, it doesn't work well. The div moves up to the top of the page. On refresh, everything works properly and the div is vertically centered. What can I do to solve this?

Body:
To vertically center content of div you can use flex https://css-tricks.com/snippets/css/a-guide-to-flexbox/#article-header-id-7

display: flex;
align-items: center;


问:
Laravel 5.5 The page has expired due to inactivity error while sending form
I'am using laravel 5.5 and it gives me that "The page has expired due to inactivity. Please refresh and try again." This is awkward because I never encounter this error. Same codes but different laravel version..

My form;

```<code>{!! Form::open(['url'=>'admin/save-social']) !!}
{{ Form::label('pinterest', 'Pinterest;', ['class' => 'control-label']) }}
{{ Form::text('pinterest', null, ['class' => 'form-control'])}}
{{ Form::label('linkedn', 'Linkedn;', ['class' => 'control-label'])}}
{{ Form::text('linkedn', null, ['class' => 'form-control'])}}
{{ Form::label('facebook', 'Facebook;', ['class' => 'control-label']) }}
{{ Form::text('facebook', null, ['class' => 'form-control']) }}
{{ Form::label('twitter', 'Twitter;', ['class' => 'control-label']) }}
{{ Form::text('twitter', null, ['class' => 'form-control']) }}
{{ Form::label('instagram', 'İnstagram;', ['class' => 'control-label']) }}
{{ Form::text('instagram', null, ['class' => 'form-control']) }}
{{ Form::submit('Save', ['class'=>'btn btn-success btn-lg btn-block']) }}
{!! Form::close()!!}
</code>```

And config/session.php

```<code><?php

return [
    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => 120,
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => null,
    'table' => 'sessions',
    'store' => null,
    'lottery' => [2, 100],
    'cookie' => env(
        'SESSION_COOKIE',
        str_slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),
    'path' => '/',
    'domain' => env('SESSION_DOMAIN', null),
    'secure' => env('SESSION_SECURE_COOKIE', false),
    'http_only' => true,
    'same_site' => null,
];
</code>```

答:
Try out the following statements:

```<code>php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
</code>```

It worked for me. Enjoy

Body:
I'am using laravel 5.5 and it gives me that "The page has expired due to inactivity. Please refresh and try again." This is awkward because I never encounter this error. Same codes but different laravel version..

My form;

{!! Form::open(['url'=>'admin/save-social']) !!}
{{ Form::label('pinterest', 'Pinterest;', ['class' => 'control-label']) }}
{{ Form::text('pinterest', null, ['class' => 'form-control'])}}
{{ Form::label('linkedn', 'Linkedn;', ['class' => 'control-label'])}}
{{ Form::text('linkedn', null, ['class' => 'form-control'])}}
{{ Form::label('facebook', 'Facebook;', ['class' => 'control-label']) }}
{{ Form::text('facebook', null, ['class' => 'form-control']) }}
{{ Form::label('twitter', 'Twitter;', ['class' => 'control-label']) }}
{{ Form::text('twitter', null, ['class' => 'form-control']) }}
{{ Form::label('instagram', 'İnstagram;', ['class' => 'control-label']) }}
{{ Form::text('instagram', null, ['class' => 'form-control']) }}
{{ Form::submit('Save', ['class'=>'btn btn-success btn-lg btn-block']) }}
{!! Form::close()!!}

And config/session.php

<?php

return [
    'driver' => env('SESSION_DRIVER', 'file'),
    'lifetime' => 120,
    'expire_on_close' => false,
    'encrypt' => false,
    'files' => storage_path('framework/sessions'),
    'connection' => null,
    'table' => 'sessions',
    'store' => null,
    'lottery' => [2, 100],
    'cookie' => env(
        'SESSION_COOKIE',
        str_slug(env('APP_NAME', 'laravel'), '_').'_session'
    ),
    'path' => '/',
    'domain' => env('SESSION_DOMAIN', null),
    'secure' => env('SESSION_SECURE_COOKIE', false),
    'http_only' => true,
    'same_site' => null,
];

Body:
Try out the following statements:

php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

It worked for me. Enjoy


问:
Is it possible to output a VPC peering connection request id using CloudFormation template?
I wrote a CloudFormation template, which among other stuff also creates a VPC peering connection.

If you are familiar with VPC peerings then you know that after the creation, a request is created and waiting for approval.

I'd like to add to the outputs portion of the CloudFormation template the VPC peering connection request id.

Is that possible? I couldn't find the way...

Edit:

This is the relevant portion of the template:

```<code>"Resources" : {
  "VPC": {
    "Type" : "AWS::EC2::VPC",
    "Description" : "Choose which VPC the security groups should be deployed to",
    "Properties" : {
      "CidrBlock" : "172.51.0.0/16",
      "EnableDnsSupport" : "true",
      "EnableDnsHostnames" : "true",
      "InstanceTenancy" : "default"
    }
  },

  "VPCPeering" : {
    "Type" : "AWS::EC2::VPCPeeringConnection",
    "Properties" : {
      "PeerVpcId" : "vpc-2XXXXXb",
      "VpcId" : { "Ref" : "VPC" }
    }
  },
</code>```

I'm using Jenkins with the CloudFormation plugin to issue the creation of a new stack.

I want the new stack to automatically create peering between the VPC that the stack creates and the existing management VPC.

My plan was to issue the creation through the template, and then once the creation completes, I intended to use AWS Cli (from Jenkins) to accept the peering request and since this step requires me to know the vpc peering request id, then I wanted to output it using the "Outputs" : {} section of the template.

Can it be done?

答:
This AWS article describes the workaround

"This article describes a procedure that allows a requester_account to both request and approve the peering connection. To do so, the peer_account must create a cross-account role that the requester_account can use to accept the peering request..."

Body:
I wrote a CloudFormation template, which among other stuff also creates a VPC peering connection.

If you are familiar with VPC peerings then you know that after the creation, a request is created and waiting for approval.

I'd like to add to the outputs portion of the CloudFormation template the VPC peering connection request id.

Is that possible? I couldn't find the way...

Edit:

This is the relevant portion of the template:

"Resources" : {
  "VPC": {
    "Type" : "AWS::EC2::VPC",
    "Description" : "Choose which VPC the security groups should be deployed to",
    "Properties" : {
      "CidrBlock" : "172.51.0.0/16",
      "EnableDnsSupport" : "true",
      "EnableDnsHostnames" : "true",
      "InstanceTenancy" : "default"
    }
  },

  "VPCPeering" : {
    "Type" : "AWS::EC2::VPCPeeringConnection",
    "Properties" : {
      "PeerVpcId" : "vpc-2XXXXXb",
      "VpcId" : { "Ref" : "VPC" }
    }
  },

I'm using Jenkins with the CloudFormation plugin to issue the creation of a new stack.

I want the new stack to automatically create peering between the VPC that the stack creates and the existing management VPC.

My plan was to issue the creation through the template, and then once the creation completes, I intended to use AWS Cli (from Jenkins) to accept the peering request and since this step requires me to know the vpc peering request id, then I wanted to output it using the "Outputs" : {} section of the template.

Can it be done?


问:
Using matplotlib to plot a distribution of time occurrences. I would like the x axis to have hours (12:00 PM) rather than integers (12)
Here's my plot, which is generated using the following code:

```<code>bins = np.linspace(0,24,25)
plt.hist(hours,bins, edgecolor='black', linewidth = 1.2, color = 'red')
</code>```

I would like the x axis to show 24 entries, from 12:00AM to 11:00 PM ideally rotated left 90 degrees.

I see two paths: convert the actual data to time values so the histogram reads in time values or simply add a custom x axis with 12:00AM, 1:00 AM, etc. What's the easiest / cleanest approach here? I'm not familiar with how to do either. For reference, "hours" is a int64 array.

答:
To get a nice time format on the xaxis, the idea could be to calculate the histogram in terms of numbers which can be interpreted as datetimes.

In case you only have times, you would not mind too much about the actual date. So dividing the data by 24 gives fraction of a day. Since matplotlib interpretes numbers as days since 0001-01-01 UTC, plus 1, one then needs to add some whole number >=2 not to run into trouble with negative dates.

Then usual matplotlib.dates locators and formatters can be used to get nice ticklabels. "%I:%M %p" would give the time representation in hours by 12 with am/pm appendix.

```<code>import numpy as np; np.random.seed(3)
import matplotlib.pyplot as plt
import matplotlib.dates

data = np.random.normal(12,7, size=200)
data = data[(data >=0) & (data <24)]

f = lambda x: 2+x/24.
bins=np.arange(25)
plt.hist(f(data), bins=f(bins))

plt.gca().xaxis.set_major_locator(matplotlib.dates.HourLocator())
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%I:%M %p"))
plt.setp(plt.gca().get_xticklabels(),rotation=90)
plt.tight_layout()
plt.show()
</code>```

(This would hence be the histogram of datetimes of the 2nd of january 0001.)

Body:
Here's my plot, which is generated using the following code:

bins = np.linspace(0,24,25)
plt.hist(hours,bins, edgecolor='black', linewidth = 1.2, color = 'red')

I would like the x axis to show 24 entries, from 12:00AM to 11:00 PM ideally rotated left 90 degrees.

I see two paths: convert the actual data to time values so the histogram reads in time values or simply add a custom x axis with 12:00AM, 1:00 AM, etc. What's the easiest / cleanest approach here? I'm not familiar with how to do either. For reference, "hours" is a int64 array.

Body:
To get a nice time format on the xaxis, the idea could be to calculate the histogram in terms of numbers which can be interpreted as datetimes.

In case you only have times, you would not mind too much about the actual date. So dividing the data by 24 gives fraction of a day. Since matplotlib interpretes numbers as days since 0001-01-01 UTC, plus 1, one then needs to add some whole number >=2 not to run into trouble with negative dates.

Then usual matplotlib.dates locators and formatters can be used to get nice ticklabels. "%I:%M %p" would give the time representation in hours by 12 with am/pm appendix.

import numpy as np; np.random.seed(3)
import matplotlib.pyplot as plt
import matplotlib.dates

data = np.random.normal(12,7, size=200)
data = data[(data >=0) & (data <24)]

f = lambda x: 2+x/24.
bins=np.arange(25)
plt.hist(f(data), bins=f(bins))

plt.gca().xaxis.set_major_locator(matplotlib.dates.HourLocator())
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%I:%M %p"))
plt.setp(plt.gca().get_xticklabels(),rotation=90)
plt.tight_layout()
plt.show()

(This would hence be the histogram of datetimes of the 2nd of january 0001.)


问:
How do you enumerate OptionSetType in Swift?
I have a custom OptionSetType struct in Swift. How can I enumerate all values of an instance?

This is my OptionSetType:

```<code>struct WeekdaySet: OptionSetType {
    let rawValue: UInt8

    init(rawValue: UInt8) {
        self.rawValue = rawValue
    }

    static let Sunday        = WeekdaySet(rawValue: 1 << 0)
    static let Monday        = WeekdaySet(rawValue: 1 << 1)
    static let Tuesday       = WeekdaySet(rawValue: 1 << 2)
    static let Wednesday     = WeekdaySet(rawValue: 1 << 3)
    static let Thursday      = WeekdaySet(rawValue: 1 << 4)
    static let Friday        = WeekdaySet(rawValue: 1 << 5)
    static let Saturday      = WeekdaySet(rawValue: 1 << 6)
}
</code>```

I would like to something like this:

```<code>let weekdays: WeekdaySet = [.Monday, .Tuesday]
for weekday in weekdays {
    // Do something with weekday
}
</code>```

答:
Based on the previous answers I created a generic Swift 4 solution with IteratorProtocol:

```<code>public struct OptionSetIterator<Element: OptionSet>: IteratorProtocol where Element.RawValue == Int {
    private let value: Element

    public init(element: Element) {
        self.value = element
    }

    private lazy var remainingBits = value.rawValue
    private var bitMask = 1

    public mutating func next() -> Element? {
        while remainingBits != 0 {
            defer { bitMask = bitMask &* 2 }
            if remainingBits & bitMask != 0 {
                remainingBits = remainingBits & ~bitMask
                return Element(rawValue: bitMask)
            }
        }
        return nil
    }
}
</code>```

Then in OptionSet extension implement makeIterator()

assuming your OptionSets will be Int:

```<code>extension OptionSet where Self.RawValue == Int {
   public func makeIterator() -> OptionSetIterator<Self> {
      return OptionSetIterator(element: self)
   }
}
</code>```

Right now every time you create an OptionSet, just conform it to Sequence.

```<code>struct WeekdaySet: OptionSet, Sequence {
    let rawValue: Int

    ...
}
</code>```

You should now be able to iterate over it:

```<code>let weekdays: WeekdaySet = [.monday, .tuesday]
for weekday in weekdays {
    // Do something with weekday
}
</code>```

I'd also create a typealias to be explicit on what is used:

typealias SequenceOptionSet = OptionSet & Sequence

Body:
I have a custom OptionSetType struct in Swift. How can I enumerate all values of an instance?

This is my OptionSetType:

struct WeekdaySet: OptionSetType {
    let rawValue: UInt8

    init(rawValue: UInt8) {
        self.rawValue = rawValue
    }

    static let Sunday        = WeekdaySet(rawValue: 1 << 0)
    static let Monday        = WeekdaySet(rawValue: 1 << 1)
    static let Tuesday       = WeekdaySet(rawValue: 1 << 2)
    static let Wednesday     = WeekdaySet(rawValue: 1 << 3)
    static let Thursday      = WeekdaySet(rawValue: 1 << 4)
    static let Friday        = WeekdaySet(rawValue: 1 << 5)
    static let Saturday      = WeekdaySet(rawValue: 1 << 6)
}

I would like to something like this:

let weekdays: WeekdaySet = [.Monday, .Tuesday]
for weekday in weekdays {
    // Do something with weekday
}

Body:
Based on the previous answers I created a generic Swift 4 solution with IteratorProtocol:

public struct OptionSetIterator<Element: OptionSet>: IteratorProtocol where Element.RawValue == Int {
    private let value: Element

    public init(element: Element) {
        self.value = element
    }

    private lazy var remainingBits = value.rawValue
    private var bitMask = 1

    public mutating func next() -> Element? {
        while remainingBits != 0 {
            defer { bitMask = bitMask &* 2 }
            if remainingBits & bitMask != 0 {
                remainingBits = remainingBits & ~bitMask
                return Element(rawValue: bitMask)
            }
        }
        return nil
    }
}

Then in OptionSet extension implement makeIterator()

assuming your OptionSets will be Int:

extension OptionSet where Self.RawValue == Int {
   public func makeIterator() -> OptionSetIterator<Self> {
      return OptionSetIterator(element: self)
   }
}

Right now every time you create an OptionSet, just conform it to Sequence.

struct WeekdaySet: OptionSet, Sequence {
    let rawValue: Int

    ...
}

You should now be able to iterate over it:

let weekdays: WeekdaySet = [.monday, .tuesday]
for weekday in weekdays {
    // Do something with weekday
}

I'd also create a typealias to be explicit on what is used:

typealias SequenceOptionSet = OptionSet & Sequence

ContentLicense: CC BY-SA 4.0


问:
Android Studio - HorizontalScollView not moving
I am doing some Android Studio courses. As part of this I am working on a mock-up music player app. The app should be mostly XML as not functionality needs to be added.
I am trying to build e Discover (new music) screen, where you have media like views. To do this, I want to implement an HorizontalScrollView.
The problem is that my scroll view doesn't move. The xml code looks fine to me and I also googled this but did not find anything that would help my situation.

Would very much appreciate some clarification on this. Here is my code:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alexcojocaru.vibes.Discover">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5px"
            android:text="Recommendations"
            android:textColor="#cc3300" />

        <HorizontalScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fillViewport="true"
            android:padding="5px"
            android:scrollbars="horizontal">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="5px"
                        android:src="@drawable/bear" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="My Name is Bear"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Nahko"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/omam" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Beneath The Skin"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:id="@+id/textView"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Of Monsters and Men"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/jmj" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Essential Recollection"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Jean-Michel Jarre"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/ram" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Random Access Memories"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Daft Punk"
                        android:textSize="10sp" />

                </LinearLayout>

            </LinearLayout>

        </HorizontalScrollView>

    </LinearLayout>

</LinearLayout>
</code>```

答:
Please change HorizontalScrollView as follows</p>

```<code><HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:padding="5px"
    android:scrollbars="horizontal">
</code>```

Body:
I am doing some Android Studio courses. As part of this I am working on a mock-up music player app. The app should be mostly XML as not functionality needs to be added.
I am trying to build e Discover (new music) screen, where you have media like views. To do this, I want to implement an HorizontalScrollView.
The problem is that my scroll view doesn't move. The xml code looks fine to me and I also googled this but did not find anything that would help my situation.

Would very much appreciate some clarification on this. Here is my code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.alexcojocaru.vibes.Discover">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="5px"
            android:text="Recommendations"
            android:textColor="#cc3300" />

        <HorizontalScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fillViewport="true"
            android:padding="5px"
            android:scrollbars="horizontal">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="5px"
                        android:src="@drawable/bear" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="My Name is Bear"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Nahko"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/omam" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Beneath The Skin"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:id="@+id/textView"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Of Monsters and Men"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/jmj" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Essential Recollection"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Jean-Michel Jarre"
                        android:textSize="10sp" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingLeft="13px">

                    <ImageView
                        android:layout_width="120dp"
                        android:layout_height="120dp"
                        android:padding="6px"
                        android:src="@drawable/ram" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Random Access Memories"
                        android:textColor="#000000"
                        android:textSize="11sp" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="5px"
                        android:text="Daft Punk"
                        android:textSize="10sp" />

                </LinearLayout>

            </LinearLayout>

        </HorizontalScrollView>

    </LinearLayout>

</LinearLayout>

Body:
Please change HorizontalScrollView as follows

<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:padding="5px"
    android:scrollbars="horizontal">


问:
Prevent stretching of an image while keeping dimensions
Is there a way to prevent the stretching of an image, to crop it somehow but keep the dimensions..?

img {
  width: 90px;
  height: 120px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://i.pinimg.com/736x/d4/c3/dc/d4c3dc946ae1e087d24def574215e266--image-search-google-search.jpg" alt=""></code>```

答:
If you want to make the image fit a defined container with fixed dimensions, you can use object-fit:cover:

div {
  height: 120px;
  width: 90px;
}

img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <img src="https://i.pinimg.com/736x/d4/c3/dc/d4c3dc946ae1e087d24def574215e266--image-search-google-search.jpg" alt="">
</div></code>```

Body:
If you want to make the image fit a defined container with fixed dimensions, you can use object-fit:cover:

div {
  height: 120px;
  width: 90px;
}

img {
  height: 100%;
  width: 100%;
  object-fit: cover;
}

<div>
  <img src="https://i.pinimg.com/736x/d4/c3/dc/d4c3dc946ae1e087d24def574215e266--image-search-google-search.jpg" alt="">
</div>


问:
Android Life cycle
In what cases on Destroy method is not called but application is killed out? I didn't make such situation, but need to do it. So I need to get a situation where on Destroy method will not be called but application will be killed?</p>

答: app is running that time you can press home button, check app is running in background that time you can directly kill this app. this scenario onDestroy method didn't call.</p>

Title: Android Life cycle


问:
Android - clickable items from JSON
I know there are many similar questions and answers here, but nothing worked for my case.

I created a simple JSON list using fragment - according to this tutorial http://androidbeginnerstutorial.blogspot.sk/2015/06/json-parsing-using-fragment-with.html

It is working fine, but I want to have all items from the list clickable, so after click another page appears with some more info from the same JSON.

I tried to implement to ActorAdapter.java inside

```<code>public View getView(int position, View convertView, ViewGroup parent) {
</code>```

I created something like

```<code> itemView.setOnClickListener(new OnClickListener() {
Intent intent = new Intent(context, SingleitemView.class);
})
</code>```

but not sure what else to put there to get it work.

I have already created the SingleitemView class.

Can you please help me? Thank you.

Here is my code from ActorAdapter.java:

```<code>import java.io.InputStream;
import java.util.ArrayList;

import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;

public class ActorAdapter extends ArrayAdapter<Actors> {
    ArrayList<Actors> actorList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        actorList = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
            holder.tvName = (TextView) v.findViewById(R.id.tvName);
            holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
            holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
            holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
            holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
            holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
            holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        holder.imageview.setImageResource(R.drawable.ic_launcher);
        new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
        holder.tvName.setText(actorList.get(position).getName());
        holder.tvDescription.setText(actorList.get(position).getDescription());
        holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
        holder.tvCountry.setText(actorList.get(position).getCountry());
        holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
        holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
        holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());

   v.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Intent intent = new Intent(view.getContext(), SingleitemView.class);
        intent.putExtra("name", "XXXXXX");
        view.getContext().startActivity(intent);
    }
});

        return v;

    }

    static class ViewHolder {
        public ImageView imageview;
        public TextView tvName;
        public TextView tvDescription;
        public TextView tvDOB;
        public TextView tvCountry;
        public TextView tvHeight;
        public TextView tvSpouse;
        public TextView tvChildren;

    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {

            bmImage.setImageBitmap(result);
        }

    }
}
</code>```

and the SingleitemView.java - that is supposed to be the new activity after click

```<code>    import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.widget.TextView;

public class SingleitemView extends Activity {
// Declare Variables
String name;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from singleitemview.xml
    setContentView(R.layout.singleitemview);

    Intent i = getIntent();
    // Get the result of rank
    name = i.getStringExtra("name");

    // Locate the TextViews in singleitemview.xml
    TextView txtname = (TextView) findViewById(R.id.name);

    // Set results to the TextViews
    txtname.setText(name);

}
</code>```

}

答:
It looks like You want to open an activity on item click :

```<code>itemView.setOnClickListener(new OnClickListener() {
Intent intent = new Intent(context, SingleitemView.class);
context.startActivity(intent);
});
</code>```

Read more about Intent Here.

Title: Android - clickable items from JSON

Body:
I know there are many similar questions and answers here, but nothing worked for my case.

I created a simple JSON list using fragment - according to this tutorial http://androidbeginnerstutorial.blogspot.sk/2015/06/json-parsing-using-fragment-with.html

It is working fine, but I want to have all items from the list clickable, so after click another page appears with some more info from the same JSON.

I tried to implement to ActorAdapter.java inside

public View getView(int position, View convertView, ViewGroup parent) {

I created something like

 itemView.setOnClickListener(new OnClickListener() {
Intent intent = new Intent(context, SingleitemView.class);
})

but not sure what else to put there to get it work.

I have already created the SingleitemView class.

Can you please help me? Thank you.

Here is my code from ActorAdapter.java:

import java.io.InputStream;
import java.util.ArrayList;

import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;

public class ActorAdapter extends ArrayAdapter<Actors> {
    ArrayList<Actors> actorList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        Resource = resource;
        actorList = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
            holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
            holder.tvName = (TextView) v.findViewById(R.id.tvName);
            holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
            holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
            holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
            holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
            holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
            holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        holder.imageview.setImageResource(R.drawable.ic_launcher);
        new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
        holder.tvName.setText(actorList.get(position).getName());
        holder.tvDescription.setText(actorList.get(position).getDescription());
        holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
        holder.tvCountry.setText(actorList.get(position).getCountry());
        holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
        holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
        holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());

   v.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Intent intent = new Intent(view.getContext(), SingleitemView.class);
        intent.putExtra("name", "XXXXXX");
        view.getContext().startActivity(intent);
    }
});

        return v;

    }

    static class ViewHolder {
        public ImageView imageview;
        public TextView tvName;
        public TextView tvDescription;
        public TextView tvDOB;
        public TextView tvCountry;
        public TextView tvHeight;
        public TextView tvSpouse;
        public TextView tvChildren;

    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {

            bmImage.setImageBitmap(result);
        }

    }
}

and the SingleitemView.java - that is supposed to be the new activity after click

    import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.widget.TextView;

public class SingleitemView extends Activity {
// Declare Variables
String name;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from singleitemview.xml
    setContentView(R.layout.singleitemview);

    Intent i = getIntent();
    // Get the result of rank
    name = i.getStringExtra("name");

    // Locate the TextViews in singleitemview.xml
    TextView txtname = (TextView) findViewById(R.id.name);

    // Set results to the TextViews
    txtname.setText(name);

}

}

Body:
It looks like You want to open an activity on item click :

itemView.setOnClickListener(new OnClickListener() {
Intent intent = new Intent(context, SingleitemView.class);
context.startActivity(intent);
});

Read more about Intent Here.


问:
Show error on wordpress data Bases Connection Error
my wordpress website unexpectedly down when traffic is increasing. it will automatically correct when there is no user browse the website. here is my site url:

http://himachal-news.com

答: if your site is popular go for dedicated linux hosting, with enough memory. I think you currently you have shared hosting, that has shared and limited resources.</p>


问:
Insert full qualification in code notification
I am using resharper tool for reviewing my code but when I comes to the line

```<code>DataSet dsContactFormInfo=null;
</code>```

then resharper shows a notification that use full qualification after this it will become like this

```<code> System.Data.DataSet dsContactFormInfo=null;
</code>```

So actually what is the difference If I use System.Data.DataSet in place of Dataset?

does it make any effect in performance of code in point of optimization?

答:
ReSharper is is just giving you an option for formatting your code.

There is no difference at run time since the compiler will look at your using statements at the top of the file, find the unique accessible type DataSet within them and use that. If there are multiple options you'll get a compile error, otherwise the successfully compiled referenced dll will use System.Data.DataSet in your example, regardless of which you wrote in the source code.

Body:
I am using resharper tool for reviewing my code but when I comes to the line

DataSet dsContactFormInfo=null;

then resharper shows a notification that use full qualification after this it will become like this

 System.Data.DataSet dsContactFormInfo=null;

So actually what is the difference If I use System.Data.DataSet in place of Dataset?

does it make any effect in performance of code in point of optimization?


问:
verifying a list using moq
Given the calling code

```<code>List<Person> loginStaff = new List<Person>();

loginStaff.add(new Person{FirstName = "John", LastName = "Doe"});

this._iViewLoginPanel.Staff = loginStaff;
</code>```

What is the syntax for verifying that there exists a staff by the name of john doe and that there is at least one staff being set? Currently, all the examples that I've seen are pretty basic, using only It.IsAny or Staff = some basic type but none actually verify data within complex types like lists.

My assert looks like

```<code>this._mockViewLoginPanel.VerifySet(x=> x.Staff = It.IsAny<List<Person>>());
</code>```

which only checks the type given to the setter but not the size or items within the list itself. I've tried to do something like this:

```<code>        this._mockViewLoginPanel.VerifySet(
           x =>
           {
               List<string> expectedStaffs = new List<string>{"John Doe", "Joe Blow", "A A", "Blah"};
               foreach (Person staff in x.Staff)
               {
                   if (!expectedStaffs.Contains(staff.FirstName + " " + staff.LastName))
                       return false;
               }
               return true;
           });
</code>```

But that tells me that the lambda statement body cannot be converted to an expression tree.
Then i got the idea of putting the statement body into a function and running that, but during runtime I get:

System.ArgumentException: Expression is not a property setter invocation.

Update:
In light of the first two answers to use assert, I tried that method but found that even after setting Staff to a non null list, it still shows up in debug as null. So this is how the full test looks

```<code>[TestMethod]
public void When_The_Presenter_Is_Created_Then_All_CP_Staff_Is_Added_To_Dropdown()
{
    this._mockViewLoginPanel = new Mock<IViewLoginPanel>();

    PresenterLoginPanel target = new PresenterLoginPanel(this._mockViewLoginPanel.Object);

    this._mockViewLoginPanel
        .VerifySet(x => x.Staff = It.IsAny<List<Person>>());

    Assert.AreEqual(5, this._mockViewLoginPanel.Object.Staff.Count);
}
</code>```

And somewhere within the constructor of PresenterLoginPanel

```<code>public PresenterLoginPanel
{
    private IViewLoginPanel _iViewLoginPanel;

    public PresenterLoginPanel(IViewLoginPanel panel)
    {
        this._iViewLoginPanel = panel;
        SomeFunction();
    }

    SomeFunction() {
        List<Person> loginStaff = new List<Person>();

        loginStaff.add(new Person{FirstName = "John", LastName = "Doe"});

        this._iViewLoginPanel.Staff = loginStaff;
    }
}
</code>```

When i debug to the next line, this._iViewLoginPanel.Staff is null which is what's causing the null exception in the assert.

答:
Rather than using the mock's methods, you can use NUnit methods to make assertions about the contents of the mock object.

Once you've assigned the list to the object and verified it has been set, use assertions to check specifics, such as the item count and that the first object matches what you expect it to contain.

```<code>Assert.That(this._mockViewLoginPanel.Object.Staff.Length, Is.EqualTo(1));
Assert.That(this._mockViewLoginPanel.Object.Staff[0], Is.Not.Null);
Assert.That(this._mockViewLoginPanel.Object.Staff[0], Is.EqualTo(loginStaff[0]));
</code>```

Edit

After further investigation this comes down to Mock Behaviour.  The properties Staff and Person weren't setup properly.

Do setup them up, alter your mock creation to this:

```<code>var _mockViewLoginPanel = new Mock<IViewLoginPanel>(MockBehavior.Strict);
_mockViewLoginPanel.SetupAllProperties();
</code>```

A complete code listing of a demo is:

```<code>public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public interface IViewLoginPanel
{
    IList<Person> Staff { get; set; }
}

public class PresenterLoginPanel {

    private IViewLoginPanel _iViewLoginPanel;

    public PresenterLoginPanel(IViewLoginPanel panel)
    {
        _iViewLoginPanel = panel;
        SomeFunction();
    }

    public void SomeFunction()
    {
        List<Person> loginStaff = new List<Person>();

        loginStaff.Add(new Person{FirstName = "John", LastName = "Doe"});

        _iViewLoginPanel.Staff = loginStaff;
    }

    public IViewLoginPanel ViewLoginPanel
    {
        get { return _iViewLoginPanel; }
    }
}

[TestFixture]
public class PresenterLoginPanelTests
{
    [Test]
    public void When_The_Presenter_Is_Created_Then_All_CP_Staff_Is_Added_To_Dropdown()
    {
        var _mockViewLoginPanel = new Mock<IViewLoginPanel>(MockBehavior.Strict);
        _mockViewLoginPanel.SetupAllProperties();

        PresenterLoginPanel target = new PresenterLoginPanel(_mockViewLoginPanel.Object);

        _mockViewLoginPanel.VerifySet(x => x.Staff = It.IsAny<List<Person>>());

        Assert.AreEqual(5, _mockViewLoginPanel.Object.Staff.Count);
    }

}
</code>```

Title: verifying a list using moq

Body:
Given the calling code

List<Person> loginStaff = new List<Person>();

loginStaff.add(new Person{FirstName = "John", LastName = "Doe"});

this._iViewLoginPanel.Staff = loginStaff;

What is the syntax for verifying that there exists a staff by the name of john doe and that there is at least one staff being set? Currently, all the examples that I've seen are pretty basic, using only It.IsAny or Staff = some basic type but none actually verify data within complex types like lists.

My assert looks like

this._mockViewLoginPanel.VerifySet(x=> x.Staff = It.IsAny<List<Person>>());

which only checks the type given to the setter but not the size or items within the list itself. I've tried to do something like this:

        this._mockViewLoginPanel.VerifySet(
           x =>
           {
               List<string> expectedStaffs = new List<string>{"John Doe", "Joe Blow", "A A", "Blah"};
               foreach (Person staff in x.Staff)
               {
                   if (!expectedStaffs.Contains(staff.FirstName + " " + staff.LastName))
                       return false;
               }
               return true;
           });

But that tells me that the lambda statement body cannot be converted to an expression tree.
Then i got the idea of putting the statement body into a function and running that, but during runtime I get:

System.ArgumentException: Expression is not a property setter invocation.

Update:
In light of the first two answers to use assert, I tried that method but found that even after setting Staff to a non null list, it still shows up in debug as null. So this is how the full test looks

[TestMethod]
public void When_The_Presenter_Is_Created_Then_All_CP_Staff_Is_Added_To_Dropdown()
{
    this._mockViewLoginPanel = new Mock<IViewLoginPanel>();

    PresenterLoginPanel target = new PresenterLoginPanel(this._mockViewLoginPanel.Object);

    this._mockViewLoginPanel
        .VerifySet(x => x.Staff = It.IsAny<List<Person>>());

    Assert.AreEqual(5, this._mockViewLoginPanel.Object.Staff.Count);
}

And somewhere within the constructor of PresenterLoginPanel

public PresenterLoginPanel
{
    private IViewLoginPanel _iViewLoginPanel;

    public PresenterLoginPanel(IViewLoginPanel panel)
    {
        this._iViewLoginPanel = panel;
        SomeFunction();
    }

    SomeFunction() {
        List<Person> loginStaff = new List<Person>();

        loginStaff.add(new Person{FirstName = "John", LastName = "Doe"});

        this._iViewLoginPanel.Staff = loginStaff;
    }
}

When i debug to the next line, this._iViewLoginPanel.Staff is null which is what's causing the null exception in the assert.

Body:
Rather than using the mock's methods, you can use NUnit methods to make assertions about the contents of the mock object.

Once you've assigned the list to the object and verified it has been set, use assertions to check specifics, such as the item count and that the first object matches what you expect it to contain.

Assert.That(this._mockViewLoginPanel.Object.Staff.Length, Is.EqualTo(1));
Assert.That(this._mockViewLoginPanel.Object.Staff[0], Is.Not.Null);
Assert.That(this._mockViewLoginPanel.Object.Staff[0], Is.EqualTo(loginStaff[0]));

Edit

After further investigation this comes down to Mock Behaviour.  The properties Staff and Person weren't setup properly.

Do setup them up, alter your mock creation to this:

var _mockViewLoginPanel = new Mock<IViewLoginPanel>(MockBehavior.Strict);
_mockViewLoginPanel.SetupAllProperties();

A complete code listing of a demo is:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public interface IViewLoginPanel
{
    IList<Person> Staff { get; set; }
}

public class PresenterLoginPanel {

    private IViewLoginPanel _iViewLoginPanel;

    public PresenterLoginPanel(IViewLoginPanel panel)
    {
        _iViewLoginPanel = panel;
        SomeFunction();
    }

    public void SomeFunction()
    {
        List<Person> loginStaff = new List<Person>();

        loginStaff.Add(new Person{FirstName = "John", LastName = "Doe"});

        _iViewLoginPanel.Staff = loginStaff;
    }

    public IViewLoginPanel ViewLoginPanel
    {
        get { return _iViewLoginPanel; }
    }
}

[TestFixture]
public class PresenterLoginPanelTests
{
    [Test]
    public void When_The_Presenter_Is_Created_Then_All_CP_Staff_Is_Added_To_Dropdown()
    {
        var _mockViewLoginPanel = new Mock<IViewLoginPanel>(MockBehavior.Strict);
        _mockViewLoginPanel.SetupAllProperties();

        PresenterLoginPanel target = new PresenterLoginPanel(_mockViewLoginPanel.Object);

        _mockViewLoginPanel.VerifySet(x => x.Staff = It.IsAny<List<Person>>());

        Assert.AreEqual(5, _mockViewLoginPanel.Object.Staff.Count);
    }

}


问:
Can't modify the icon of DXRibbonWindow in WPF
I tried to custome the icon of DXRibbonWindow by adding Icon=<Icon url> in DXRibbonWindow tag, like this:

<DXRibbonWindow Icon="<Icon Url>" ... ></RXRibbonWindow>

but it doesn't work, the icon remains as default, how can i custom the window icon?

答:
Are you using a URL or a file path? I believe the property will only work with a correctly formatted file path to a suitable file type.

Here is an example from DevExpress for reference:

```<code>Icon="/WpfApplication9;component/Images/webcam_32.ico">
</code>```

Body:
Are you using a URL or a file path? I believe the property will only work with a correctly formatted file path to a suitable file type.

Here is an example from DevExpress for reference:

Icon="/WpfApplication9;component/Images/webcam_32.ico">


问:
Script required
Suppose we have a table #temp1, what we required here is, we want an additional column ABC and in that, we want to print the output as (10-10 = 0), (20-10) = 10, (30-10 = 20), (40-10 = 30) and (50-10 = 40)

So, we have created a table and insert script below.

```<code>Create table #temp1 (ID Int Identity(1,1),Name varchar(10),Series bigint)

insert into #temp1 values('A',10)
insert into #temp1 values('B',20)
insert into #temp1 values('C',30)
insert into #temp1 values('D',40)
insert into #temp1 values('E',50)
</code>```

I tried as below, where its incrementing the values rows by rows.

```<code>select ID,Name,Series, SUM(series) over(order by series asc Rows Between Unbounded Preceding and Current Row) ranking from #temp1
</code>```

Output should be:

```<code>ID|Name|Series|ABC
1 |  A |  10  | 0
2 |  B |  20  | 10
3 |  C |  30  | 20
4 |  D |  40  | 30
5 |  E |  50  | 40
</code>```

Can anyone here me, how to do that.

答:
Agree with Sami. Unless something else is intended from the query that was attempted, it seems like it should not be Series - 10, but rather series - the first series value in the table?

If that is the case, then the answer should be

```<code>select ID,Name,Series, Series - MIN(series) over
(order by series asc Rows Between unbounded Preceding and Current Row) ABC from #temp1
</code>```

Title: Script required

Body:
Suppose we have a table #temp1, what we required here is, we want an additional column ABC and in that, we want to print the output as (10-10 = 0), (20-10) = 10, (30-10 = 20), (40-10 = 30) and (50-10 = 40)

So, we have created a table and insert script below.

Create table #temp1 (ID Int Identity(1,1),Name varchar(10),Series bigint)

insert into #temp1 values('A',10)
insert into #temp1 values('B',20)
insert into #temp1 values('C',30)
insert into #temp1 values('D',40)
insert into #temp1 values('E',50)

I tried as below, where its incrementing the values rows by rows.

select ID,Name,Series, SUM(series) over(order by series asc Rows Between Unbounded Preceding and Current Row) ranking from #temp1

Output should be:

ID|Name|Series|ABC
1 |  A |  10  | 0
2 |  B |  20  | 10
3 |  C |  30  | 20
4 |  D |  40  | 30
5 |  E |  50  | 40

Can anyone here me, how to do that.

Body:
Agree with Sami. Unless something else is intended from the query that was attempted, it seems like it should not be Series - 10, but rather series - the first series value in the table?

If that is the case, then the answer should be

select ID,Name,Series, Series - MIN(series) over
(order by series asc Rows Between unbounded Preceding and Current Row) ABC from #temp1