问:
Next and previous not working properly using jQuery
I am working on the next and previous section. When I clicked on next button then it's displaying the next div but it's not working properly because Next button is working infinit.

Same as the previous button. I need to hide the previous button on page load when the user clicked on next button or scroll the mouse wheel than I have to display the previous button.

I tried some code

new WOW().init();
 (function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('gentags').scrollLeft -= (delta*40); // Multiplied by 40
        e.preventDefault();
    }
    if (document.getElementById('gentags').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
        // Firefox
        document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
    }
})();

$('.navigation_right').click(function() {
    $('.current').removeClass('current').hide()
        .next().show().addClass('current');
    if ($('.current').hasClass('last')) {
        $('.navigation_right').attr('disabled', true);
    }
    $('.navigation_left').attr('disabled', null);
});

$('.navigation_left').click(function() {
    $('.current').removeClass('current').hide()
        .prev().show().addClass('current');
    if ($('.current').hasClass('first')) {
        $('.navigation_left').attr('disabled', true);
    }
    $('.navigation_right').attr('disabled', null);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  #gentags {
position:fixed;
margin-top: -.25em;
display: inline-block;
width: 100%;
overflow: hidden;
}

#gentags > div{
    overflow: hidden;
    width:250%;
}

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}
/* optional: show position indicator in red */
::-webkit-scrollbar-thumb {
    background: transparent;
}

.horizontal_scroll .full_screen_100 article{
    width: 11.58%;
    height: 100%;
    float:left;
    border-left: solid 1px #E2E2E2;

}
.active_div{

display: none;
}

  /*Navigation style*/
  .horizontal_scroll_icon_pre_next {
    bottom: 50px;
    left: 0;

    position: fixed;

    width: 100%;
    height: 0;
   /* padding: 0 20px;*/
}
  .horizontal_scroll_icon_pre_next button{
  background-color: transparent;
border: none;
font-size: 0;
color: #7b7b7b;
display: none;
outline: 0;
cursor: pointer;
}
.horizontal_scroll_icon_pre_next button.navigation_left
{
 float: left;
}
.horizontal_scroll_icon_pre_next button.navigation_right
{
 float:right;
}

.horizontal_scroll_icon_pre_next button.active {
    display: block;
}
.horizontal_scroll_icon_pre_next button span {

    font-size: 30px;
}</code>```

 <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/animatecss/3.5.2/animate.min.css">
     <link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">

I want to display this div when articles 7 comes on screen

01
Hover me and scroll mouse wheel

02
Hover me and scroll mouse wheel

03
Hover me and scroll mouse wheel

04
Hover me and scroll mouse wheel

05
Hover me and scroll mouse wheel

06
Hover me and scroll mouse wheel

07
Hover me and scroll mouse wheel

08
Hover me and scroll mouse wheel

        <button class="navigation_left active">Previous</button>
        <button class="navigation_right active">Next</button>

 ```

答:
In your existing code, you are performing operation and then checking for disabled condition. Instead, store current and next element and if next element is available, perform operation. So if next/prev element is not available, no operation will be performed and you do not have to manually disable/enable button.

On prev, you will have to show previous element but you will have to show current element as well.

Since you do not want to go till last element, what you can do is to check if last element is fully visible on screen or not. If it is visible, disable button, else enable it.

function enableDisableButtonState(context, value) {
  $('[class^=navigation_]').attr('disabled', false);
  $(context).attr('disabled', value);
}

$('.navigation_right').click(function() {
  var current = $('.current');
  var nextEl = current.next();
  var lastArticle = $('article:last');
  if (nextEl.length > 0) {
    current.removeClass('current').hide();
    nextEl.addClass('current').show();
  }
  var isInBounds = lastArticle.position().left < ($(document).width() - lastArticle.width());
  enableDisableButtonState(this, isInBounds);
});

$('.navigation_left').click(function() {
  var current = $('.current');
  var prevEL = current.prev();
  if (prevEL.length > 0) {
    current.removeClass('current');
    prevEL.addClass('current').show();
  }
  enableDisableButtonState(this, prevEL.is(':first-child'));
});
```

<p><strong>Sample Code:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>new WOW().init();
(function() {
  function scrollHorizontally(e) {
    e = window.event || e;
    var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
    document.getElementById('gentags').scrollLeft -= (delta * 40); // Multiplied by 40
    e.preventDefault();
  }
  if (document.getElementById('gentags').addEventListener) {
    // IE9, Chrome, Safari, Opera
    document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
    // Firefox
    document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
  } else {
    // IE 6/7/8
    document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
  }
})();

function enableDisableButtonState(context, value) {
  $('[class^=navigation_]').attr('disabled', false);
  $(context).attr('disabled', value);
}

$('.navigation_right').click(function() {
  var current = $('.current');
  var nextEl = current.next();
  var lastArticle = $('article:last');
  if (nextEl.length > 0) {
    current.removeClass('current').hide();
    nextEl.addClass('current').show();
  }
  var isInBounds = lastArticle.position().left < ($(document).width() - lastArticle.width());
  enableDisableButtonState(this, isInBounds);
});

$('.navigation_left').click(function() {
  var current = $('.current');
  var prevEL = current.prev();
  if (prevEL.length > 0) {
    current.removeClass('current');
    prevEL.addClass('current').show();
  }
  enableDisableButtonState(this, prevEL.is(':first-child'));
});</code>```

#gentags {
  position: fixed;
  margin-top: -.25em;
  display: inline-block;
  width: 100%;
  overflow: hidden;
}

#gentags>div {
  overflow: hidden;
  width: 250%;
}

::-webkit-scrollbar {
  width: 0px;
  /* remove scrollbar space */
  background: transparent;
  /* optional: just make scrollbar invisible */
}

/* optional: show position indicator in red */

::-webkit-scrollbar-thumb {
  background: transparent;
}

.horizontal_scroll .full_screen_100 article {
  width: 11.58%;
  height: 100%;
  float: left;
  border-left: solid 1px #E2E2E2;
}

.active_div {
  display: none;
}

/*Navigation style*/

.horizontal_scroll_icon_pre_next {
  bottom: 50px;
  left: 0;
  position: fixed;
  width: 100%;
  height: 0;
  /* padding: 0 20px;*/
}

.horizontal_scroll_icon_pre_next button {
  background-color: transparent;
  border: none;
  font-size: 0;
  color: #7b7b7b;
  display: none;
  outline: 0;
  cursor: pointer;
}

.horizontal_scroll_icon_pre_next button.navigation_left {
  float: left;
}

.horizontal_scroll_icon_pre_next button.navigation_right {
  float: right;
}

.horizontal_scroll_icon_pre_next button.active {
  display: block;
}

.horizontal_scroll_icon_pre_next button span {
  font-size: 30px;
}

.horizontal_scroll {
  overflow: hidden;
}

button[class^='navigation_'] {
  transition: 0.4s;
}

button[class^='navigation_']:disabled {
  opacity: 0.2;
  transition: 0.4s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/animatecss/3.5.2/animate.min.css">
<link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
<!--icon-->
<div class="active_div">
  <h2>I want to display this div when articles 7 comes on screen</h2>
</div>

<div id="gentags">
  <div class="horizontal_scroll">
    <div class="full_screen_100" id="left_scroll">
      <article class="wow fadeInUp first current">
        <div>
          <p class="scroll_number">01</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">02</p><span class="page_slogan">Hover me and scroll mouse wheel </span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">03</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">04</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">05</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">06</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">07</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp last">
        <div>
          <p class="scroll_number">08</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
    </div>
  </div>
</div>

<div class="horizontal_scroll_icon_pre_next">
  <button class="navigation_left active" disabled><span class="lnr lnr-arrow-left"></span>Previous</button>
  <button class="navigation_right active"><span class="lnr lnr-arrow-right"></span>Next</button>
</div>
<!--horizontal_scroll_navigation-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js"></script></code>```

Body:
I am working on the next and previous section. When I clicked on next button then it's displaying the next div but it's not working properly because Next button is working infinit.

Same as the previous button. I need to hide the previous button on page load when the user clicked on next button or scroll the mouse wheel than I have to display the previous button.

I tried some code

new WOW().init();
 (function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('gentags').scrollLeft -= (delta*40); // Multiplied by 40
        e.preventDefault();
    }
    if (document.getElementById('gentags').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
        // Firefox
        document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
    }
})();

$('.navigation_right').click(function() {
    $('.current').removeClass('current').hide()
        .next().show().addClass('current');
    if ($('.current').hasClass('last')) {
        $('.navigation_right').attr('disabled', true);
    }
    $('.navigation_left').attr('disabled', null);
});

$('.navigation_left').click(function() {
    $('.current').removeClass('current').hide()
        .prev().show().addClass('current');
    if ($('.current').hasClass('first')) {
        $('.navigation_left').attr('disabled', true);
    }
    $('.navigation_right').attr('disabled', null);
});

  #gentags {
position:fixed;
margin-top: -.25em;
display: inline-block;
width: 100%;
overflow: hidden;
}

#gentags > div{
    overflow: hidden;
    width:250%;
}

::-webkit-scrollbar {
    width: 0px;  /* remove scrollbar space */
    background: transparent;  /* optional: just make scrollbar invisible */
}
/* optional: show position indicator in red */
::-webkit-scrollbar-thumb {
    background: transparent;
}

.horizontal_scroll .full_screen_100 article{
    width: 11.58%;
    height: 100%;
    float:left;
    border-left: solid 1px #E2E2E2;

}
.active_div{

display: none;
}

  /*Navigation style*/
  .horizontal_scroll_icon_pre_next {
    bottom: 50px;
    left: 0;

    position: fixed;

    width: 100%;
    height: 0;
   /* padding: 0 20px;*/
}
  .horizontal_scroll_icon_pre_next button{
  background-color: transparent;
border: none;
font-size: 0;
color: #7b7b7b;
display: none;
outline: 0;
cursor: pointer;
}
.horizontal_scroll_icon_pre_next button.navigation_left
{
 float: left;
}
.horizontal_scroll_icon_pre_next button.navigation_right
{
 float:right;
}

.horizontal_scroll_icon_pre_next button.active {
    display: block;
}
.horizontal_scroll_icon_pre_next button span {

    font-size: 30px;
}

 <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/animatecss/3.5.2/animate.min.css">
     <link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">

I want to display this div when articles 7 comes on screen

01
Hover me and scroll mouse wheel

02
Hover me and scroll mouse wheel

03
Hover me and scroll mouse wheel

04
Hover me and scroll mouse wheel

05
Hover me and scroll mouse wheel

06
Hover me and scroll mouse wheel

07
Hover me and scroll mouse wheel

08
Hover me and scroll mouse wheel

        <button class="navigation_left active">Previous</button>
        <button class="navigation_right active">Next</button>

Body:
In your existing code, you are performing operation and then checking for disabled condition. Instead, store current and next element and if next element is available, perform operation. So if next/prev element is not available, no operation will be performed and you do not have to manually disable/enable button.

On prev, you will have to show previous element but you will have to show current element as well.

Since you do not want to go till last element, what you can do is to check if last element is fully visible on screen or not. If it is visible, disable button, else enable it.

function enableDisableButtonState(context, value) {
  $('[class^=navigation_]').attr('disabled', false);
  $(context).attr('disabled', value);
}

$('.navigation_right').click(function() {
  var current = $('.current');
  var nextEl = current.next();
  var lastArticle = $('article:last');
  if (nextEl.length > 0) {
    current.removeClass('current').hide();
    nextEl.addClass('current').show();
  }
  var isInBounds = lastArticle.position().left < ($(document).width() - lastArticle.width());
  enableDisableButtonState(this, isInBounds);
});

$('.navigation_left').click(function() {
  var current = $('.current');
  var prevEL = current.prev();
  if (prevEL.length > 0) {
    current.removeClass('current');
    prevEL.addClass('current').show();
  }
  enableDisableButtonState(this, prevEL.is(':first-child'));
});

Sample Code:

new WOW().init();
(function() {
  function scrollHorizontally(e) {
    e = window.event || e;
    var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
    document.getElementById('gentags').scrollLeft -= (delta * 40); // Multiplied by 40
    e.preventDefault();
  }
  if (document.getElementById('gentags').addEventListener) {
    // IE9, Chrome, Safari, Opera
    document.getElementById('gentags').addEventListener("mousewheel", scrollHorizontally, false);
    // Firefox
    document.getElementById('gentags').addEventListener("DOMMouseScroll", scrollHorizontally, false);
  } else {
    // IE 6/7/8
    document.getElementById('gentags').attachEvent("onmousewheel", scrollHorizontally);
  }
})();

function enableDisableButtonState(context, value) {
  $('[class^=navigation_]').attr('disabled', false);
  $(context).attr('disabled', value);
}

$('.navigation_right').click(function() {
  var current = $('.current');
  var nextEl = current.next();
  var lastArticle = $('article:last');
  if (nextEl.length > 0) {
    current.removeClass('current').hide();
    nextEl.addClass('current').show();
  }
  var isInBounds = lastArticle.position().left < ($(document).width() - lastArticle.width());
  enableDisableButtonState(this, isInBounds);
});

$('.navigation_left').click(function() {
  var current = $('.current');
  var prevEL = current.prev();
  if (prevEL.length > 0) {
    current.removeClass('current');
    prevEL.addClass('current').show();
  }
  enableDisableButtonState(this, prevEL.is(':first-child'));
});

#gentags {
  position: fixed;
  margin-top: -.25em;
  display: inline-block;
  width: 100%;
  overflow: hidden;
}

#gentags>div {
  overflow: hidden;
  width: 250%;
}

::-webkit-scrollbar {
  width: 0px;
  /* remove scrollbar space */
  background: transparent;
  /* optional: just make scrollbar invisible */
}

/* optional: show position indicator in red */

::-webkit-scrollbar-thumb {
  background: transparent;
}

.horizontal_scroll .full_screen_100 article {
  width: 11.58%;
  height: 100%;
  float: left;
  border-left: solid 1px #E2E2E2;
}

.active_div {
  display: none;
}

/*Navigation style*/

.horizontal_scroll_icon_pre_next {
  bottom: 50px;
  left: 0;
  position: fixed;
  width: 100%;
  height: 0;
  /* padding: 0 20px;*/
}

.horizontal_scroll_icon_pre_next button {
  background-color: transparent;
  border: none;
  font-size: 0;
  color: #7b7b7b;
  display: none;
  outline: 0;
  cursor: pointer;
}

.horizontal_scroll_icon_pre_next button.navigation_left {
  float: left;
}

.horizontal_scroll_icon_pre_next button.navigation_right {
  float: right;
}

.horizontal_scroll_icon_pre_next button.active {
  display: block;
}

.horizontal_scroll_icon_pre_next button span {
  font-size: 30px;
}

.horizontal_scroll {
  overflow: hidden;
}

button[class^='navigation_'] {
  transition: 0.4s;
}

button[class^='navigation_']:disabled {
  opacity: 0.2;
  transition: 0.4s;
}

<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/animatecss/3.5.2/animate.min.css">
<link rel="stylesheet" href="https://cdn.linearicons.com/free/1.0.0/icon-font.min.css">
<!--icon-->
<div class="active_div">
  <h2>I want to display this div when articles 7 comes on screen</h2>
</div>

<div id="gentags">
  <div class="horizontal_scroll">
    <div class="full_screen_100" id="left_scroll">
      <article class="wow fadeInUp first current">
        <div>
          <p class="scroll_number">01</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">02</p><span class="page_slogan">Hover me and scroll mouse wheel </span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">03</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">04</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">05</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">06</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp">
        <div>
          <p class="scroll_number">07</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
      <article class="wow fadeInUp last">
        <div>
          <p class="scroll_number">08</p><span class="page_slogan">Hover me and scroll mouse wheel</span></div>
      </article>
    </div>
  </div>
</div>

<div class="horizontal_scroll_icon_pre_next">
  <button class="navigation_left active" disabled><span class="lnr lnr-arrow-left"></span>Previous</button>
  <button class="navigation_right active"><span class="lnr lnr-arrow-right"></span>Next</button>
</div>
<!--horizontal_scroll_navigation-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.min.js"></script>


来源: stackexchange

问:
How to send data to DataTables (for add row)
I have a php file that retrieves information from the database (add.php)

I would like this information to be added to my table (DataTables)

So I try to do that (I deliberately simplified)

Javascript :

```<code>$(document).on("click", "#add", function(){
  $.post("/ajax/add.php", {info: number}).done(function(data){
    $('#fileTable').DataTable().row.add(data).draw();
  });
});
</code>```

In my add.php file, I have my request that gives me this information:

```<code>$request = $bdd->prepare('SELECT * FROM product WHERE ...');
$request->execute();
$info = $request->fetch();
</code>```

The request works is it returns to me:

```<code>$a = $info['a']
$b = $info['b']
$c = $info['c']
$d = $info['d']
</code>```

I would like to return his information in order to add them to the table, so I tried several things (always in my add.php file):

```<code>echo "[$a, $b, $c, $d]";
echo "{0: $a, 1: $b, 2: $c, 3: $d}";
</code>```

It does not work... How to do ?

答:
Try</p>

```<code>header("Content-type:application/json");
$request = $ bdd->prepare('SELECT * FROM product WHERE ...');
$request->execute();
$info = $request->fetch();

echo json_encode($info)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a php file that retrieves information from the database (add.php)

I would like this information to be added to my table (DataTables)

So I try to do that (I deliberately simplified)

Javascript :

$(document).on("click", "#add", function(){
  $.post("/ajax/add.php", {info: number}).done(function(data){
    $('#fileTable').DataTable().row.add(data).draw();
  });
});

In my add.php file, I have my request that gives me this information:

$request = $bdd->prepare('SELECT * FROM product WHERE ...');
$request->execute();
$info = $request->fetch();

The request works is it returns to me:

$a = $info['a']
$b = $info['b']
$c = $info['c']
$d = $info['d']

I would like to return his information in order to add them to the table, so I tried several things (always in my add.php file):

echo "[$a, $b, $c, $d]";
echo "{0: $a, 1: $b, 2: $c, 3: $d}";

It does not work... How to do ?

Body:
Try

header("Content-type:application/json");
$request = $ bdd->prepare('SELECT * FROM product WHERE ...');
$request->execute();
$info = $request->fetch();

echo json_encode($info)


问:
Get relation with extra information from relation table
Im using Laravel and Eloquent to relate two models.

Fairly simple, a webshop has many brands, but I have some extra information stored in the relation table that I need.

How do I get this?

My relation table looks like this:

```<code>brand_id   |    webshop_id    |   url
</code>```

My current statement to get the webshops including the brands is:

```<code>$webshop = Webshop::select()
        ->where('slug', $slug)
        ->with('brands')
        ->first();
</code>```

Then I can look through $webshop->brands but the column "url" is not accesable.

答:
On your Webshop model:

```<code>public function brands()
{
    return $this->belongsToMany('App\Brand')->withPivot('url');
}
</code>```

Then just do

```<code>foreach ($webshop->brands as $brand)
{
    echo $brand->pivot->url; // your url
}
</code>```

Body:
Im using Laravel and Eloquent to relate two models.

Fairly simple, a webshop has many brands, but I have some extra information stored in the relation table that I need.

How do I get this?

My relation table looks like this:

brand_id   |    webshop_id    |   url

My current statement to get the webshops including the brands is:

$webshop = Webshop::select()
        ->where('slug', $slug)
        ->with('brands')
        ->first();

Then I can look through $webshop->brands but the column "url" is not accesable.

Body:
On your Webshop model:

public function brands()
{
    return $this->belongsToMany('App\Brand')->withPivot('url');
}

Then just do

foreach ($webshop->brands as $brand)
{
    echo $brand->pivot->url; // your url
}


问:
Exposing kubernetes service locally (without minikube)
I'm using lxc/lxd to play with the kubenetes cluster.

Is there a way to expose a deployed service locally without using minikube, so that I could access it from the local machine?
I can access it from any of the nodes in the cluster but not from outside.

答:
Do you want to acccess the pod being served by the service? if yes, you can use kubectl port-forward to connect to your pod and access it locally

Here is an example:

If you have a service which forwards all the requests to a pod ( nginx ) at port number 80 you can configure it to your local port as follows

kubectl port-forward -n default nginx-5767f4d585-hgtfj 8081:80

Here is the syntax of the same

kubectl port-forward -n NAMESPACE ${POD} local-port:pod-port

If you want to connect to your service directly, you need to do it via kubectl proxy

Here is a reference

Hope it helps.


答:
When looking at datatables docs, it seems that the add() function should take a JSON object.

I'm not certain what you are passing to it.

You may need to do this:

```<code>var table = $('#fileTable');
table.row.add(JSON.stringify(data)).draw();
</code>```

Failing that, console.log(data) and this will help you understand what you are currently passing to the add() function

Title: How to send data to DataTables (for add row)

Body:
When looking at datatables docs, it seems that the add() function should take a JSON object.

I'm not certain what you are passing to it.

You may need to do this:

var table = $('#fileTable');
table.row.add(JSON.stringify(data)).draw();

Failing that, console.log(data) and this will help you understand what you are currently passing to the add() function


问:
How to mock SqlQuery
I'm new in writing tests and Mock. I'm trying to figure it out how to mock Raw SQL to retrieve data. Here's what I have:

I have DataContext.cs

```<code>public class DataContext : DbContext
{
    public DataContext()
         : base("Main")
    {
    }

    public virtual DbSet<DbBook> Books { get; set; }
    public virtual DbSet<DbMovie> Movies { get; set; }
}
</code>```

I have controller BooksController.cs

```<code>public class BooksController : ApiController
{
    private readonly BookDataContext _db;
    public BooksController ()
    {
        _db = new BookDataContext();
    }

    public BooksController (BookDataContext context)
    {
        _db = context;
    }

    [HttpGet]
    [Route("books")]
    public Book GetBooks()
    {
        using (var dbContextTransaction = _db.Database.BeginTransaction())
        {
            var test = _db.Books.SqlQuery("select * from BOOK");
            var test2 = from b in _db.Books
                            orderby b.Books
                            select b;
        }
    }
}
</code>```

And I have test

```<code>[TestMethod]
public void GetBook()
{
    var data = new List<DbBook>
    {
        new DbBook{ Book = "Book1"},
        new DbBook{ Book = "Book2"}
    }.AsQueryable();

    var mockSet = new Mock<DbSet<DbScriptId>>();
    mockSet.As<IQueryable<DbBook>>().Setup(m =>
    m.Provider).Returns(data.Provider);
    mockSet.As<IQueryable<DbBook>>().Setup(m =>
    m.Expression).Returns(data.Expression);
    mockSet.As<IQueryable<DbBook>>().Setup(m =>
    m.ElementType).Returns(data.ElementType);
    mockSet.As<IQueryable<DbBook>>().Setup(m =>
    m.GetEnumerator()).Returns(data.GetEnumerator());
    mockSet.Setup(m => m.Find(It.IsAny<object[]>()))
         .Returns<object[]>(sc => data.SingleOrDefault());

    var mockContext = new Mock<DataContext>();
    mockContext.Setup(c => c.Books).Returns(mockSet.Object);

    var controller = new BooksController (mockContext.Object);
    var books = controller.GetBook();
}
</code>```

I can retrieve data using Linq (test2) but using SqlQuery I always get null (test). How to change that using SqlQuery I get same result as using Linq? Also I'm getting to know that creating InMemory database actually creates some lists (type=IQueriable) in background, not database. Can you please provide some explanation and resolution for this issue?

答:
How about this. (not sure if I understand your question right)

```<code> var queryMock = new Mock<DbSqlQuery<DbBook>>();
 queryMock.Setup(x => x.GetEnumerator()).Returns(data.GetEnumerator());

 mockSet.Setup(m => m.SqlQuery(It.IsAny<string>(), It.IsAny<object[]>())).Returns(queryMock.Object);
</code>```

This example assumes that all queries will return all items.

Title: How to mock SqlQuery

Body:
I'm new in writing tests and Mock. I'm trying to figure it out how to mock Raw SQL to retrieve data. Here's what I have:

I have DataContext.cs

public class DataContext : DbContext
{
    public DataContext()
         : base("Main")
    {
    }

    public virtual DbSet<DbBook> Books { get; set; }
    public virtual DbSet<DbMovie> Movies { get; set; }
}

I have controller BooksController.cs

public class BooksController : ApiController
{
    private readonly BookDataContext _db;
    public BooksController ()
    {
        _db = new BookDataContext();
    }

    public BooksController (BookDataContext context)
    {
        _db = context;
    }

    [HttpGet]
    [Route("books")]
    public Book GetBooks()
    {
        using (var dbContextTransaction = _db.Database.BeginTransaction())
        {
            var test = _db.Books.SqlQuery("select * from BOOK");
            var test2 = from b in _db.Books
                            orderby b.Books
                            select b;
        }
    }
}

And I have test

[TestMethod]
public void GetBook()
{
    var data = new List<DbBook>
    {
        new DbBook{ Book = "Book1"},
        new DbBook{ Book = "Book2"}
    }.AsQueryable();

    var mockSet = new Mock<DbSet<DbScriptId>>();
    mockSet.As<IQueryable<DbBook>>().Setup(m =>
    m.Provider).Returns(data.Provider);
    mockSet.As<IQueryable<DbBook>>().Setup(m =>
    m.Expression).Returns(data.Expression);
    mockSet.As<IQueryable<DbBook>>().Setup(m =>
    m.ElementType).Returns(data.ElementType);
    mockSet.As<IQueryable<DbBook>>().Setup(m =>
    m.GetEnumerator()).Returns(data.GetEnumerator());
    mockSet.Setup(m => m.Find(It.IsAny<object[]>()))
         .Returns<object[]>(sc => data.SingleOrDefault());

    var mockContext = new Mock<DataContext>();
    mockContext.Setup(c => c.Books).Returns(mockSet.Object);

    var controller = new BooksController (mockContext.Object);
    var books = controller.GetBook();
}

I can retrieve data using Linq (test2) but using SqlQuery I always get null (test). How to change that using SqlQuery I get same result as using Linq? Also I'm getting to know that creating InMemory database actually creates some lists (type=IQueriable) in background, not database. Can you please provide some explanation and resolution for this issue?

Body:
How about this. (not sure if I understand your question right)

 var queryMock = new Mock<DbSqlQuery<DbBook>>();
 queryMock.Setup(x => x.GetEnumerator()).Returns(data.GetEnumerator());

 mockSet.Setup(m => m.SqlQuery(It.IsAny<string>(), It.IsAny<object[]>())).Returns(queryMock.Object);

This example assumes that all queries will return all items.


问:
How to implement Array.prototype.sort default compare function?

Background

I need to implement a function with the same behaviour as the default compare function of Array.prototype.sort

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

After reading the documentation I stumbled upon this:

The default sort order is according to string Unicode code points.

What does this mean? Does it mean I convert every object to a string?

If so, assuming I have the array [2, "a", { hello: "world" }] would these steps be correct?

convert [2, "a", { hello: "world" }] to ["2", "a", '{ hello: "world" }']

convert the first character of every string to a Number

order by that number

Question

How do I implement a compare function that given any object, behaves exactly as the compare function from sort?

Notes

Reading the ECMA specification:

http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.sort

I now believe that if comparefn is undefined, then they use this algorithm as a default:

http://www.ecma-international.org/ecma-262/6.0/#sec-sortcompare

Can someone confirm?

答:
Solution

After reading the ECMA spec and asking around, I arrived to a defaultCompare function that simulates the default behaviour of Array.prototype.sort() in chrome:

```<code>const defaultCompare = ( x, y ) => {
    //INFO: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
    //ECMA specification: http://www.ecma-international.org/ecma-262/6.0/#sec-sortcompare

    if( x === undefined && y === undefined )
        return 0;

    if( x === undefined )
        return 1;

    if( y === undefined )
        return -1;

    const xString = toString(x);
    const yString = toString(y);

    if( xString < yString )
        return -1;

    if( xString > yString )
        return 1;

    return 0;
};

const toString = obj => {
    //ECMA specification: http://www.ecma-international.org/ecma-262/6.0/#sec-tostring

    if( obj === null )
        return "null";

    if( typeof obj === "boolean" ||  typeof obj === "number" )
        return (obj).toString();

    if( typeof obj === "string" )
        return obj;

    if( typeof obj === "symbol" )
        throw new TypeError();

    //we know we have an object. perhaps return JSON.stringify?
    return (obj).toString();
};

module.exports = defaultCompare;
</code>```

How can I test it?

You can test this function like the following:

```<code>const arr = [ undefined, null, 3, 2, 'B', 'a', 'b', 'A',
{ hello: "world"}, { goodnight: 'moon'} ]

assertEql( arr.sort(), arr.sort(defaultCompare) ); //true
</code>```

The outputs should be equal, provided you test them in the same browser.

Body:
Solution

After reading the ECMA spec and asking around, I arrived to a defaultCompare function that simulates the default behaviour of Array.prototype.sort() in chrome:

const defaultCompare = ( x, y ) => {
    //INFO: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
    //ECMA specification: http://www.ecma-international.org/ecma-262/6.0/#sec-sortcompare

    if( x === undefined && y === undefined )
        return 0;

    if( x === undefined )
        return 1;

    if( y === undefined )
        return -1;

    const xString = toString(x);
    const yString = toString(y);

    if( xString < yString )
        return -1;

    if( xString > yString )
        return 1;

    return 0;
};

const toString = obj => {
    //ECMA specification: http://www.ecma-international.org/ecma-262/6.0/#sec-tostring

    if( obj === null )
        return "null";

    if( typeof obj === "boolean" ||  typeof obj === "number" )
        return (obj).toString();

    if( typeof obj === "string" )
        return obj;

    if( typeof obj === "symbol" )
        throw new TypeError();

    //we know we have an object. perhaps return JSON.stringify?
    return (obj).toString();
};

module.exports = defaultCompare;

How can I test it?

You can test this function like the following:

const arr = [ undefined, null, 3, 2, 'B', 'a', 'b', 'A',
{ hello: "world"}, { goodnight: 'moon'} ]

assertEql( arr.sort(), arr.sort(defaultCompare) ); //true

The outputs should be equal, provided you test them in the same browser.

ContentLicense: CC BY-SA 4.0


问:
How can I make my animation transition smoothly?
I am trying to make an animation of a panel attached with two string though a nail swing from left to right like a pendulum. Here is the animation code and transition function. For the demo, you can check the snippet below:

.headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
  0%,
  50%,
  100% {
    transform: rotate(0deg);
    transform-origin: 50% -50%;
  }
  25% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  75% {
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="headline">
  <div class="box">
    <span class="panel">Test Panel</span>
  </div>
</div></code>```

It worked somehow but the animation is robotic and not very smooth and natural. Could you please point out how to improve this animation.

I also can use jQuery for this case if you need to use JS.

答:
Similar to @Kushtrim's answer, but I have added a negative animation-delay so that the pendulum starts swinging from the bottom, rather than suddenly jumping to -25deg. Using this technique it is possible to start an animation mid way. Here are the relevant modified rules:

```<code>.headline .panel:hover {
      animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
      animation: pendulum 2s infinite;
      animation-delay: -1.3s /* I added this */
}

@keyframes pendulum {
  0% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  50% {
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
  100% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
}
</code>```

And a Fiddle: https://jsfiddle.net/125wps7s/

The animation-delay time requires trial and error to get right. I just picked a value that seemed close enough.

Body:
I am trying to make an animation of a panel attached with two string though a nail swing from left to right like a pendulum. Here is the animation code and transition function. For the demo, you can check the snippet below:

.headline {
  display: flex;
  justify-content: center;
  margin-bottom: 40px;
  margin-top: 150px;
}

.headline .box {
  position: relative;
  top: 10px;
  left: -70px;
}

.headline .box:after {
  content: "";
  width: 45px;
  height: 45px;
  background: black;
  position: absolute;
  border-radius: 50%;
  top: -85px;
  left: 105px;
  z-index: 10;
}

.headline .panel {
  background: white;
  color: #ff004f;
  font-size: 46px;
  font-family: "Quicksand", sans-serif;
  padding: 10px;
  font-weight: 700;
  max-width: 250px;
  display: block;
  line-height: 46px;
  position: relative;
}

.headline .panel:hover {
  animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
  animation: pendulum 2s infinite;
}

.headline .panel:before {
  content: "";
  width: 155px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(8px) rotate(148deg);
  position: absolute;
  top: -40px;
  left: -16px;
  border-radius: 5px;
}

.headline .panel:after {
  content: "";
  width: 150px;
  height: 10px;
  background: white;
  display: block;
  transform: translateX(-10px) rotate(-148deg);
  position: absolute;
  top: -40px;
  right: -18px;
}

@keyframes pendulum {
  0%,
  50%,
  100% {
    transform: rotate(0deg);
    transform-origin: 50% -50%;
  }
  25% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  75% {
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
}

body {
  background-color: #EEE;
}

    Test Panel

It worked somehow but the animation is robotic and not very smooth and natural. Could you please point out how to improve this animation.

I also can use jQuery for this case if you need to use JS.

Body:
Similar to @Kushtrim's answer, but I have added a negative animation-delay so that the pendulum starts swinging from the bottom, rather than suddenly jumping to -25deg. Using this technique it is possible to start an animation mid way. Here are the relevant modified rules:

.headline .panel:hover {
      animation-timing-function: cubic-bezier(0.120, 0.485, 0.950, 0.475);
      animation: pendulum 2s infinite;
      animation-delay: -1.3s /* I added this */
}

@keyframes pendulum {
  0% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
  50% {
    transform: rotate(25deg);
    transform-origin: 50% -50%;
  }
  100% {
    transform: rotate(-25deg);
    transform-origin: 50% -50%;
  }
}

And a Fiddle: https://jsfiddle.net/125wps7s/

The animation-delay time requires trial and error to get right. I just picked a value that seemed close enough.


问:
Google Maps Polyline click between points
Using Google Maps api 3, I have a polyline with a click event. I need to find out between which two points in the path the user has clicked. Ideally the index of the points.

Below is a sample page mostly taken direct from google docs, but added the click event. The actual app has much more complex polylines.

Is there are way to do this?

Many thanks

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Polylines</title>
<style>
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  </style>
 </head>
 <body>
      <div id="map"></div>
      <script>
      function initMap() {
          var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 3,
          center: {lat: 0, lng: -180},
          mapTypeId: 'terrain'
      });

      var flightPlanCoordinates = [
         {lat: 37.772, lng: -122.214},
         {lat: 21.291, lng: -157.821},
         {lat: -18.142, lng: 178.431},
         {lat: -27.467, lng: 153.027}
      ];

      var poly = new google.maps.Polyline({
         path: flightPlanCoordinates,
         geodesic: true,
         strokeColor: '#FF0000',
         strokeOpacity: 1.0,
         strokeWeight: 2
       });

       poly.setMap(map);

       google.maps.event.addListener(poly, 'click', function(e) {
         alert(JSON.stringify(e));
       });

     }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MYAPIKEY&callback=initMap">
</script>
</code>```

答:
Try:</p>

```<code>    poly.addListener('click', function () {
         getPathVariableCode(poly);
     });
 poly.setMap(map);

    function getPathVariableCode(line){
    var codeStr = '  var linePath = [\n';
    var pathArr = line.getPath();
    for (var i = 0; i < pathArr.length; i++){
        codeStr += '    {lat: ' + pathArr.getAt(i).lat() + ', lng: ' + pathArr.getAt(i).lng() + '}' ;
        if (i !== pathArr.length-1) {
            codeStr += ',\n';
        };

    };

    codeStr += '\n  ];';

    //the coordinates path it´s print on the console of the browser

    console.log (codeStr);
    console.log(pathArr.length);

};
</code>```

Body:
Using Google Maps api 3, I have a polyline with a click event. I need to find out between which two points in the path the user has clicked. Ideally the index of the points.

Below is a sample page mostly taken direct from google docs, but added the click event. The actual app has much more complex polylines.

Is there are way to do this?

Many thanks

<!DOCTYPE html>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Polylines</title>

Body:
Try:

    poly.addListener('click', function () {
         getPathVariableCode(poly);
     });
 poly.setMap(map);

    function getPathVariableCode(line){
    var codeStr = '  var linePath = [\n';
    var pathArr = line.getPath();
    for (var i = 0; i < pathArr.length; i++){
        codeStr += '    {lat: ' + pathArr.getAt(i).lat() + ', lng: ' + pathArr.getAt(i).lng() + '}' ;
        if (i !== pathArr.length-1) {
            codeStr += ',\n';
        };

    };

    codeStr += '\n  ];';

    //the coordinates path it´s print on the console of the browser

    console.log (codeStr);
    console.log(pathArr.length);

};


问:
c++ conversion string- unsigned char
I have a string value:
std::string bl="0x"+"a0"; //where a0 is a heva number. I did add 0x because i want my      vector

```<code>std::vector<unsigned char>vect;
</code>```

vect.push_back(bl.begin(), bl.end()); //error  is not working.

Need help. What to do?
I am working in ubuntu c++ code.

答:
Do not use push_back(...), it classically can not push an interval, it pushs the one item. You can use assign(begin, end) or insert(iter_position, vect_begin, vect_end).

For example:

```<code>vect.assign(bl.begin(), bl.end());
vect.insert(vect.begin(), bl.begin(), bl.end());
vect.push_back(bl[0]); // '0'
vect.push_back(bl[1]); // 'x'
vect.push_back(bl[2]); // 'a'
vect.push_back(bl[3]); // '0'
</code>```

ContentLicense: CC BY-SA 2.5

Title: c++ conversion string- unsigned char

Body:
I have a string value:
std::string bl="0x"+"a0"; //where a0 is a heva number. I did add 0x because i want my      vector

std::vector<unsigned char>vect;

vect.push_back(bl.begin(), bl.end()); //error  is not working.

Need help. What to do?
I am working in ubuntu c++ code.

Body:
Do not use push_back(...), it classically can not push an interval, it pushs the one item. You can use assign(begin, end) or insert(iter_position, vect_begin, vect_end).

For example:

vect.assign(bl.begin(), bl.end());
vect.insert(vect.begin(), bl.begin(), bl.end());
vect.push_back(bl[0]); // '0'
vect.push_back(bl[1]); // 'x'
vect.push_back(bl[2]); // 'a'
vect.push_back(bl[3]); // '0'


问:
How to perform a $setIsSubset on MongoDB using C# driver?
I am trying to use $setIsSubset operator in MongoDB.

Documentation says I should wrote this :

```<code>var values = Enumerable.Range(0, 10).ToArray();
var result = myCollection.Find(x => x.ExternalKeys.IsSubsetOf(values)).ToList();
</code>```

However, I got the following exception :

An unhandled exception of type 'System.ArgumentException' occurred in
  MongoDB.Driver.dll

Additional information: Unsupported filter:
  {myCollection}{ExternalKeys}.IsSubsetOf(value(System.Int32[])).

ExternalKeys property is declared as Hashset<int>

I am using MongoDB 3.4 and C# Driver 2.4.4 which AFAIK are latest versions.

答:
You would actually want $in here for "at least one of" [40, 30, 20] to match in the target array. This is done with AnyIn()

```<code>myCollection.Find(
  Builders<BsonDocument>.Filter.AnyIn( x => x.ExternalKeys, new[] { 40, 30, 20 } )
).ToList();
</code>```

$in is not just for arrays but is essentially a list of possible values that can match a property. It's just that MongoDB treats an array as matching "any of it's values" as well.

So that's actually what you are looking for in what you are calling a "subset", since the target is a "subset" of what it is being compared to where any element intersects.

Body:
I am trying to use $setIsSubset operator in MongoDB.

Documentation says I should wrote this :

var values = Enumerable.Range(0, 10).ToArray();
var result = myCollection.Find(x => x.ExternalKeys.IsSubsetOf(values)).ToList();

However, I got the following exception :

An unhandled exception of type 'System.ArgumentException' occurred in
  MongoDB.Driver.dll

Additional information: Unsupported filter:
  {myCollection}{ExternalKeys}.IsSubsetOf(value(System.Int32[])).

ExternalKeys property is declared as Hashset<int>

I am using MongoDB 3.4 and C# Driver 2.4.4 which AFAIK are latest versions.

Body:
You would actually want $in here for "at least one of" [40, 30, 20] to match in the target array. This is done with AnyIn()

myCollection.Find(
  Builders<BsonDocument>.Filter.AnyIn( x => x.ExternalKeys, new[] { 40, 30, 20 } )
).ToList();

$in is not just for arrays but is essentially a list of possible values that can match a property. It's just that MongoDB treats an array as matching "any of it's values" as well.

So that's actually what you are looking for in what you are calling a "subset", since the target is a "subset" of what it is being compared to where any element intersects.


问:
jupyter kernel restarting issue
i get this message when i run the jupyter notebook "The kernel has died, and the automatic restart has failed. It is possible the kernel cannot be restarted. If you are not able to restart the kernel, you will still be able to save the notebook, but running code will no longer work until the notebook is reopened."

```<code> http://localhost:8888/?token=bc7dc2e3b31daedf0c88a9dc766aa8e74e7d03aba7934770
[I 16:13:18.114 NotebookApp] Accepting one-time-token-authenticated connection from ::1
[W 16:13:24.226 NotebookApp] 404 GET /nbextensions/widgets/notebook/js/extension.js?v=20171117161317 (::1) 13.01ms referer
=http://localhost:8888/notebooks/TensorFlow-Book-master/ch02_basics/Concept01_defining_tensors.ipynb
Could not import runpy module
Traceback (most recent call last):
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\BDU\Enivronments\TensorFlow-Book-master\ch02_basics\types.py", line 3, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
[I 16:13:24.594 NotebookApp] Kernel started: 8b5449c6-2f01-4546-9ceb-1f036b9443e5
[I 16:13:27.535 NotebookApp] KernelRestarter: restarting kernel (1/5)
Could not import runpy module
Traceback (most recent call last):
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\BDU\Enivronments\TensorFlow-Book-master\ch02_basics\types.py", line 3, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
[I 16:13:30.541 NotebookApp] KernelRestarter: restarting kernel (2/5)
Could not import runpy module
Traceback (most recent call last):
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\BDU\Enivronments\TensorFlow-Book-master\ch02_basics\types.py", line 3, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
[I 16:13:33.542 NotebookApp] KernelRestarter: restarting kernel (3/5)
Could not import runpy module
Traceback (most recent call last):
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\BDU\Enivronments\TensorFlow-Book-master\ch02_basics\types.py", line 3, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
[W 16:13:34.667 NotebookApp] Timeout waiting for kernel_info reply from 8b5449c6-2f01-4546-9ceb-1f036b9443e5
[I 16:13:36.562 NotebookApp] KernelRestarter: restarting kernel (4/5)
WARNING:root:kernel 8b5449c6-2f01-4546-9ceb-1f036b9443e5 restarted
Could not import runpy module
Traceback (most recent call last):
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\BDU\Enivronments\TensorFlow-Book-master\ch02_basics\types.py", line 3, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
[W 16:13:39.592 NotebookApp] KernelRestarter: restart failed
[W 16:13:39.592 NotebookApp] Kernel 8b5449c6-2f01-4546-9ceb-1f036b9443e5 died, removing from map.
ERROR:root:kernel 8b5449c6-2f01-4546-9ceb-1f036b9443e5 restarted failed!
[W 16:13:39.629 NotebookApp] 410 DELETE /api/sessions/d1b11c7a-e718-4f3e-aaf4-ebd6b66e10ec (::1): Kernel deleted before se
ssion
[W 16:13:39.630 NotebookApp] Kernel deleted before session
[W 16:13:39.631 NotebookApp] 410 DELETE /api/sessions/d1b11c7a-e718-4f3e-aaf4-ebd6b66e10ec (::1) 3.00ms referer=http://loc
alhost:8888/notebooks/TensorFlow-Book-master/ch02_basics/Concept01_defining_tensors.ipynb
</code>```

please help me to resolve

Regards
Lokesh

答:
As far as I can see, you failed to import tensorflow:

import tensorflow as tf ModuleNotFoundError: No module named
  'tensorflow'

So you should fix that first and install it.

Title: jupyter kernel restarting issue

Body:
i get this message when i run the jupyter notebook "The kernel has died, and the automatic restart has failed. It is possible the kernel cannot be restarted. If you are not able to restart the kernel, you will still be able to save the notebook, but running code will no longer work until the notebook is reopened."

 http://localhost:8888/?token=bc7dc2e3b31daedf0c88a9dc766aa8e74e7d03aba7934770
[I 16:13:18.114 NotebookApp] Accepting one-time-token-authenticated connection from ::1
[W 16:13:24.226 NotebookApp] 404 GET /nbextensions/widgets/notebook/js/extension.js?v=20171117161317 (::1) 13.01ms referer
=http://localhost:8888/notebooks/TensorFlow-Book-master/ch02_basics/Concept01_defining_tensors.ipynb
Could not import runpy module
Traceback (most recent call last):
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\BDU\Enivronments\TensorFlow-Book-master\ch02_basics\types.py", line 3, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
[I 16:13:24.594 NotebookApp] Kernel started: 8b5449c6-2f01-4546-9ceb-1f036b9443e5
[I 16:13:27.535 NotebookApp] KernelRestarter: restarting kernel (1/5)
Could not import runpy module
Traceback (most recent call last):
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\BDU\Enivronments\TensorFlow-Book-master\ch02_basics\types.py", line 3, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
[I 16:13:30.541 NotebookApp] KernelRestarter: restarting kernel (2/5)
Could not import runpy module
Traceback (most recent call last):
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\BDU\Enivronments\TensorFlow-Book-master\ch02_basics\types.py", line 3, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
[I 16:13:33.542 NotebookApp] KernelRestarter: restarting kernel (3/5)
Could not import runpy module
Traceback (most recent call last):
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\BDU\Enivronments\TensorFlow-Book-master\ch02_basics\types.py", line 3, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
[W 16:13:34.667 NotebookApp] Timeout waiting for kernel_info reply from 8b5449c6-2f01-4546-9ceb-1f036b9443e5
[I 16:13:36.562 NotebookApp] KernelRestarter: restarting kernel (4/5)
WARNING:root:kernel 8b5449c6-2f01-4546-9ceb-1f036b9443e5 restarted
Could not import runpy module
Traceback (most recent call last):
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\runpy.py", line 14, in <module>
    import importlib.machinery # importlib first so we can test #15386 via -m
  File "c:\users\bdu\appdata\local\programs\python\python36\lib\importlib\__init__.py", line 57, in <module>
    import types
  File "C:\Users\BDU\Enivronments\TensorFlow-Book-master\ch02_basics\types.py", line 3, in <module>
    import tensorflow as tf
ModuleNotFoundError: No module named 'tensorflow'
[W 16:13:39.592 NotebookApp] KernelRestarter: restart failed
[W 16:13:39.592 NotebookApp] Kernel 8b5449c6-2f01-4546-9ceb-1f036b9443e5 died, removing from map.
ERROR:root:kernel 8b5449c6-2f01-4546-9ceb-1f036b9443e5 restarted failed!
[W 16:13:39.629 NotebookApp] 410 DELETE /api/sessions/d1b11c7a-e718-4f3e-aaf4-ebd6b66e10ec (::1): Kernel deleted before se
ssion
[W 16:13:39.630 NotebookApp] Kernel deleted before session
[W 16:13:39.631 NotebookApp] 410 DELETE /api/sessions/d1b11c7a-e718-4f3e-aaf4-ebd6b66e10ec (::1) 3.00ms referer=http://loc
alhost:8888/notebooks/TensorFlow-Book-master/ch02_basics/Concept01_defining_tensors.ipynb

please help me to resolve

Regards
Lokesh


问:
@RunWith(Cucumber.class) and @Autowired MockMvc
I try to use MockMvc within Cucumber tests but no spring dependencies are resolved.

I've create this class :

```<code>@RunWith(Cucumber.class)
@CucumberOptions(format = "pretty", features = "src/test/resources/features"})
@SpringBootTest
public class CucumberTest {

}
</code>```

to run cucumber feature

And this class for steps :

```<code>@WebMvcTest(VersionController.class)
@AutoConfigureWebMvc
public class VersionControllerSteps {

    @Autowired
    private MockMvc mvc;

    private MvcResult result;

    @When("^the client calls /version$")
    public void the_client_issues_GET_version() throws Throwable {
        result = mvc.perform(get("/version")).andDo(print()).andReturn();
    }

    @Then("^the client receives status code of (\\d+)$")
    public void the_client_receives_status_code_of(int statusCode) throws Throwable {
        assertThat(result.getResponse().getStatus()).isEqualTo(statusCode);
    }

    @And("^the client receives server version (.+)$")
    public void the_client_receives_server_version_body(String version) throws Throwable {
        assertThat(result.getResponse().getContentAsString()).isEqualTo(version);
    }
}
</code>```

but this throw exception :

```<code>java.lang.NullPointerException
at com.example.rest.VersionControllerSteps.the_client_issues_GET_version(VersionControllerSteps.java:30)
at ✽.When the client calls /version(version.feature:8)
</code>```

Here is the .feature :

```<code>Feature: the version can be retrieved

  As a api user
  I want to know which api version is exposed
  In order to be a good api user

  Scenario: client makes call to GET /version
    When the client calls /version
    Then the client receives status code of 200
    And the client receives server version 1.0
</code>```

How to configure my test to use cucumber and spring-boot ?

Thanks in advance.

答:
From your code listing and error log, it is not clear if it is a problem of cucumber+spring setup or just an application error.

The stack trace points at line 30, which is throwing the null pointer exception. From your code listing it looks it may be due to the result.getResponse().getContentAsString() instructions.

It may be worth checking if your controller is actually returning a body. For instance you may need to mark the returned value with the @ResponseBody annotation

```<code>   @RequestMapping(
     value = "/campaigns/new",
     method = RequestMethod.GET,
    )
    public @ResponseBody String vers() {
        return "1.0.1";
    }
</code>```

Body:
I try to use MockMvc within Cucumber tests but no spring dependencies are resolved.

I've create this class :

@RunWith(Cucumber.class)
@CucumberOptions(format = "pretty", features = "src/test/resources/features"})
@SpringBootTest
public class CucumberTest {

}

to run cucumber feature

And this class for steps :

@WebMvcTest(VersionController.class)
@AutoConfigureWebMvc
public class VersionControllerSteps {

    @Autowired
    private MockMvc mvc;

    private MvcResult result;

    @When("^the client calls /version$")
    public void the_client_issues_GET_version() throws Throwable {
        result = mvc.perform(get("/version")).andDo(print()).andReturn();
    }

    @Then("^the client receives status code of (\\d+)$")
    public void the_client_receives_status_code_of(int statusCode) throws Throwable {
        assertThat(result.getResponse().getStatus()).isEqualTo(statusCode);
    }

    @And("^the client receives server version (.+)$")
    public void the_client_receives_server_version_body(String version) throws Throwable {
        assertThat(result.getResponse().getContentAsString()).isEqualTo(version);
    }
}

but this throw exception :

java.lang.NullPointerException
at com.example.rest.VersionControllerSteps.the_client_issues_GET_version(VersionControllerSteps.java:30)
at ✽.When the client calls /version(version.feature:8)

Here is the .feature :

Feature: the version can be retrieved

  As a api user
  I want to know which api version is exposed
  In order to be a good api user

  Scenario: client makes call to GET /version
    When the client calls /version
    Then the client receives status code of 200
    And the client receives server version 1.0

How to configure my test to use cucumber and spring-boot ?

Thanks in advance.

Body:
From your code listing and error log, it is not clear if it is a problem of cucumber+spring setup or just an application error.

The stack trace points at line 30, which is throwing the null pointer exception. From your code listing it looks it may be due to the result.getResponse().getContentAsString() instructions.

It may be worth checking if your controller is actually returning a body. For instance you may need to mark the returned value with the @ResponseBody annotation

   @RequestMapping(
     value = "/campaigns/new",
     method = RequestMethod.GET,
    )
    public @ResponseBody String vers() {
        return "1.0.1";
    }


问:
Circuit-Breaker status in Turbine Dashboard
Turbine dashboard is used to aggregate Hystrix metrics stream from a cluster of nodes. The Circuit-Breaker status is displayed on the Turbine dashboard as Open or Closed.

What is the logic used for arriving at the Circuit-Breaker status for the cluster? Does it represent the status of the Circuit-Breakers in the majority of nodes from the cluster, or is it some other logic based on time in a state, % of nodes, etc.?

答:
If all hosts are in the Open state, then the text will be green and display Open.

If all hosts are in the Closed state, then the text will be red and display
Closed.

If some hosts are in the Closed state then the text will go orange and display how many are in the Open state and how many are in the Closed state.
It looks something like:

```<code>{Open: 1, Closed: 4}
</code>```

The logic behind this can be seen in the source of the Hystrix dashboard hystrixCircuit.html

Body:
If all hosts are in the Open state, then the text will be green and display Open.

If all hosts are in the Closed state, then the text will be red and display
Closed.

If some hosts are in the Closed state then the text will go orange and display how many are in the Open state and how many are in the Closed state.
It looks something like:

{Open: 1, Closed: 4}

The logic behind this can be seen in the source of the Hystrix dashboard hystrixCircuit.html


问:
Compilation of MPI "hello world" fails
Today I tried to compile the classical MPI "hello world" program

```<code>#include <stdio.h>
#include <mpi.h>

int main(int argc, char** argv)
{
    MPI_Init(&argc, &argv);

    int rank;
    int size;

    MPI_Comm_rank(MPI_COMM_WORLD,&rank);
    MPI_Comm_size(MPI_COMM_WORLD,&size);

    printf("I am rank %d of %d\n", rank, size);

    MPI_Finalize();

    return 0;
}
</code>```

To do so I installed openMPI, lam, lam-devel (for mpicc). I tried to follow the answer given in this old thread adressing this problem, which lead to an installation of automake, autoconf, libtool and from here I also came to install coreutils. Unfortunatelly I still get the following error-message when trying to compile the above code

```<code>mpicc hello.c   -o hello
gcc: error: libtool:: Datei oder Verzeichnis nicht gefunden
gcc: error: link:: Datei oder Verzeichnis nicht gefunden
mpicc: No such file or directory
</code>```

Requesting the compiler version gives

```<code>mpicc --version
gcc (SUSE Linux) 4.8.5
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

答:
Can you try mpic++ instead:

```<code>mpic++ hello.c   -o hello
</code>```

It is working on my machine

I used openmpi:

```<code>sudo apt-get install openmpi-bin
</code>```

Title: Compilation of MPI "hello world" fails

Body:
Today I tried to compile the classical MPI "hello world" program

#include <stdio.h>
#include <mpi.h>

int main(int argc, char** argv)
{
    MPI_Init(&argc, &argv);

    int rank;
    int size;

    MPI_Comm_rank(MPI_COMM_WORLD,&rank);
    MPI_Comm_size(MPI_COMM_WORLD,&size);

    printf("I am rank %d of %d\n", rank, size);

    MPI_Finalize();

    return 0;
}

To do so I installed openMPI, lam, lam-devel (for mpicc). I tried to follow the answer given in this old thread adressing this problem, which lead to an installation of automake, autoconf, libtool and from here I also came to install coreutils. Unfortunatelly I still get the following error-message when trying to compile the above code

mpicc hello.c   -o hello
gcc: error: libtool:: Datei oder Verzeichnis nicht gefunden
gcc: error: link:: Datei oder Verzeichnis nicht gefunden
mpicc: No such file or directory

Requesting the compiler version gives

mpicc --version
gcc (SUSE Linux) 4.8.5
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Body:
Can you try mpic++ instead:

mpic++ hello.c   -o hello

It is working on my machine

I used openmpi:

sudo apt-get install openmpi-bin


问:
Clear ObservableCollection throws exception
I have a Xamarin app implementing a search functionality where results are grouped. Therefore I used a Grouped Listview.

```<code>private async void SearchRecipient()
{
    IList<Recipient> recipients = null;

    if (!string.IsNullOrWhiteSpace(RecipientSearched))
    {
        recipients = await _service.GetRecipients(RecipientSearched.ToLower());

        FilteredRecipients.Clear();
        _userGroupedList.Clear();
        _officeGroupedList.Clear();

        if (recipients != null)
        {
            foreach (var r in recipients)
            {
                // Some logic to populate collections
                _userGroupedList.Add(selectable);
                _officeGroupedList.Add(selectable);
            }

            if (_userGroupedList.Count > 0)
                FilteredRecipients.Add(_userGroupedList);
            if (_officeGroupedList.Count > 0)
                FilteredRecipients.Add(_officeGroupedList);
        }
    }
}
</code>```

FilteredRecipients is an ObservableCollection, while _userGroupedList and _officeGroupedList are List.

```<code>public SearchRecipientPageModel()
{
    FilteredRecipients = new ObservableCollection<GroupedRecipientModel>();
    _userGroupedList = new GroupedRecipientModel("User");
    _officeGroupedList = new GroupedRecipientModel("Office");
}
</code>```

Search works and grouping as well. The problem happens when I repeat a search a second time and FilteredRecipients.Clear() throws the following exception:

```<code>System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'
</code>```

UPDATE
Problems seems to happen only when some item of the result is selected with a checkbox. I think is due to my Checkbox Renderer implementation, because I substituted Checkbox with a Switch and it seems to work. I have had some problems to make it working in TwoWay Mode Binding, but maybe I didn't fix it correctly.

```<code>    public class CustomCheckBox : View
{
    public bool Checked
    {
        get => (bool)GetValue(CheckedProperty);
        set => SetValue(CheckedProperty, value);
    }

    public ICommand Command
    {
        get => (ICommand)GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    public object CommandParameter
    {
        get => GetValue(CommandParameterProperty);
        set => SetValue(CommandParameterProperty, value);
    }

    public static readonly BindableProperty CommandParameterProperty =
                                BindableProperty.Create("CommandParameter", typeof(object), typeof(CustomCheckBox), default(object));

    public static readonly BindableProperty CheckedProperty =
                                BindableProperty.Create("Checked", typeof(bool), typeof(CustomCheckBox), default(bool), propertyChanged: OnChecked);

    public static readonly BindableProperty CommandProperty =
                BindableProperty.Create("Command", typeof(ICommand), typeof(CustomCheckBox), default(ICommand));

    private static void OnChecked(BindableObject bindable, object oldValue, object newValue)
    {
        if (bindable is CustomCheckBox checkbox)
        {
            object parameter = checkbox.CommandParameter ?? newValue;

            if (checkbox.Command != null && checkbox.Command.CanExecute(parameter))
                checkbox.Command.Execute(parameter);
        }
    }
}
</code>```

Renderer

```<code>public class CustomCheckBoxRenderer : ViewRenderer<CustomCheckBox, CheckBox>
{
    protected override void OnElementChanged(ElementChangedEventArgs<CustomCheckBox> e)
    {
        base.OnElementChanged(e);
        if (Control == null && Element != null)
            SetNativeControl(new CheckBox());

        if (Control != null)
        {
            Control.IsChecked = Element.Checked;
            Control.Checked += (s, r) => { Element.Checked = true; };
            Control.Unchecked += (s, r) => { Element.Checked = false; };
        }
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        if (e.PropertyName == nameof(Element.Checked))
            Control.IsChecked = Element.Checked;
    }
}
</code>```

Moreover I am still investigating a bug of this renderer since Checked event is raised twice each time.

答:
Try below code instead of clear()

```<code>FilteredRecipients = new ObservableCollection<YourModel>();
</code>```

Edit

Solution for Checked event is raised twice each time.

```<code>if (e.OldElement != null)
{
      Control.Checked -= (s, r) => { Element.Checked = true; };
      Control.Unchecked -= (s, r) => { Element.Checked = false; };
}

if (e.NewElement != null)
{
      Control.Checked += (s, r) => { Element.Checked = true; };
      Control.Unchecked += (s, r) => { Element.Checked = false; };
}
</code>```

Body:
I have a Xamarin app implementing a search functionality where results are grouped. Therefore I used a Grouped Listview.

private async void SearchRecipient()
{
    IList<Recipient> recipients = null;

    if (!string.IsNullOrWhiteSpace(RecipientSearched))
    {
        recipients = await _service.GetRecipients(RecipientSearched.ToLower());

        FilteredRecipients.Clear();
        _userGroupedList.Clear();
        _officeGroupedList.Clear();

        if (recipients != null)
        {
            foreach (var r in recipients)
            {
                // Some logic to populate collections
                _userGroupedList.Add(selectable);
                _officeGroupedList.Add(selectable);
            }

            if (_userGroupedList.Count > 0)
                FilteredRecipients.Add(_userGroupedList);
            if (_officeGroupedList.Count > 0)
                FilteredRecipients.Add(_officeGroupedList);
        }
    }
}

FilteredRecipients is an ObservableCollection, while _userGroupedList and _officeGroupedList are List.

public SearchRecipientPageModel()
{
    FilteredRecipients = new ObservableCollection<GroupedRecipientModel>();
    _userGroupedList = new GroupedRecipientModel("User");
    _officeGroupedList = new GroupedRecipientModel("Office");
}

Search works and grouping as well. The problem happens when I repeat a search a second time and FilteredRecipients.Clear() throws the following exception:

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'

UPDATE
Problems seems to happen only when some item of the result is selected with a checkbox. I think is due to my Checkbox Renderer implementation, because I substituted Checkbox with a Switch and it seems to work. I have had some problems to make it working in TwoWay Mode Binding, but maybe I didn't fix it correctly.

    public class CustomCheckBox : View
{
    public bool Checked
    {
        get => (bool)GetValue(CheckedProperty);
        set => SetValue(CheckedProperty, value);
    }

    public ICommand Command
    {
        get => (ICommand)GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    public object CommandParameter
    {
        get => GetValue(CommandParameterProperty);
        set => SetValue(CommandParameterProperty, value);
    }

    public static readonly BindableProperty CommandParameterProperty =
                                BindableProperty.Create("CommandParameter", typeof(object), typeof(CustomCheckBox), default(object));

    public static readonly BindableProperty CheckedProperty =
                                BindableProperty.Create("Checked", typeof(bool), typeof(CustomCheckBox), default(bool), propertyChanged: OnChecked);

    public static readonly BindableProperty CommandProperty =
                BindableProperty.Create("Command", typeof(ICommand), typeof(CustomCheckBox), default(ICommand));

    private static void OnChecked(BindableObject bindable, object oldValue, object newValue)
    {
        if (bindable is CustomCheckBox checkbox)
        {
            object parameter = checkbox.CommandParameter ?? newValue;

            if (checkbox.Command != null && checkbox.Command.CanExecute(parameter))
                checkbox.Command.Execute(parameter);
        }
    }
}

Renderer

public class CustomCheckBoxRenderer : ViewRenderer<CustomCheckBox, CheckBox>
{
    protected override void OnElementChanged(ElementChangedEventArgs<CustomCheckBox> e)
    {
        base.OnElementChanged(e);
        if (Control == null && Element != null)
            SetNativeControl(new CheckBox());

        if (Control != null)
        {
            Control.IsChecked = Element.Checked;
            Control.Checked += (s, r) => { Element.Checked = true; };
            Control.Unchecked += (s, r) => { Element.Checked = false; };
        }
    }

    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        if (e.PropertyName == nameof(Element.Checked))
            Control.IsChecked = Element.Checked;
    }
}

Moreover I am still investigating a bug of this renderer since Checked event is raised twice each time.

Body:
Try below code instead of clear()

FilteredRecipients = new ObservableCollection<YourModel>();

Edit

Solution for Checked event is raised twice each time.

if (e.OldElement != null)
{
      Control.Checked -= (s, r) => { Element.Checked = true; };
      Control.Unchecked -= (s, r) => { Element.Checked = false; };
}

if (e.NewElement != null)
{
      Control.Checked += (s, r) => { Element.Checked = true; };
      Control.Unchecked += (s, r) => { Element.Checked = false; };
}


问:
How to make a calendar

As a homework assignment, I need to recreate this screenshot with pure code. I currently got stuck with making the calendar. When I tried to make mine for some reason I can't get the numerical days under the day itself. As you can see there are seven days in a row but 8 numerical days in a row. How could I fix this

What changes do I need to make on my code to fix it
This is the HTML code:

```<code><h2>Calendar</h2>

<p class="october">October 2017</p>
<ul class="weekdays">
  <li>M</li>
  <li>T</li>
  <li>W</li>
  <li>T</li>
  <li>F</li>
  <li>S</li>
  <li>S</li>
</ul>

<ul class="days">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li><span class="active">10</span></li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
  <li>19</li>
  <li>20</li>
  <li>21</li>
  <li>22</li>
  <li>23</li>
  <li>24</li>
  <li>25</li>
  <li>26</li>
  <li>27</li>
  <li>28</li>
  <li>29</li>
  <li>30</li>
  <li>31</li>
</ul>
</code>```

And my CSS code:

```<code>/* Calendar */
.october{
  text-align: center;
}
.weekdays {
    margin: 0;
    padding: 10px 0;
    background-color: #cccccc;
    text-align: center;
}

.weekdays li {
    display: inline-block;
    color: #ffffff;
    width: 10%;
    text-align: center;
}

.days {
    text-align: center;
    padding: 10px 0;
    background: #eee;
    margin: 0;
}

.days li {
    list-style-type: none;
    display: inline-block;
    width: 10%;
    text-align: center;
    margin-bottom: 5px;
    font-size:12px;
    color: #777;
}

.days li .active {
    color: #3c8cd7 !important
}
</code>```

P.S. I'm not completely done with everything else that's why it still looks sloppy

答:
You can try thi. it will show you a nice result of the calondar, play with css to have the exact one in the picture..

All what is inside  separate it in the css file..

```<code><!DOCTYPE html>
<html>
<head>

<style>
* {box-sizing: border-box;}
ul {list-style-type: none;}
body {font-family: Verdana, sans-serif;}

.month {
    padding: 70px 25px;
    width: 100%;
    background: #1abc9c;
    text-align: center;
}

.month ul {
    margin: 0;
    padding: 0;
}

.month ul li {
    color: white;
    font-size: 20px;
    text-transform: uppercase;
    letter-spacing: 3px;
}

.month .prev {
    float: left;
    padding-top: 10px;
}

.month .next {
    float: right;
    padding-top: 10px;
}

.weekdays {
    margin: 0;
    padding: 10px 0;
    background-color: #ddd;
}

.weekdays li {
    display: inline-block;
    width: 13.6%;
    color: #666;
    text-align: center;
}

.days {
    padding: 10px 0;
    background: #eee;
    margin: 0;
}

.days li {
    list-style-type: none;
    display: inline-block;
    width: 13.6%;
    text-align: center;
    margin-bottom: 5px;
    font-size:12px;
    color: #777;
}

.days li .active {
    padding: 5px;
    background: #1abc9c;
    color: white !important
}

/* Add media queries for smaller screens */
@media screen and (max-width:720px) {
    .weekdays li, .days li {width: 13.1%;}
}

@media screen and (max-width: 420px) {
    .weekdays li, .days li {width: 12.5%;}
    .days li .active {padding: 2px;}
}

@media screen and (max-width: 290px) {
    .weekdays li, .days li {width: 12.2%;}
}
</style>
</head>
<body>

<h1>CSS Calendar</h1>

<div class="month">
  <ul>
    <li class="prev">❮</li>
    <li class="next">❯</li>
    <li>
      August<br>
      <span style="font-size:18px">2017</span>
    </li>
  </ul>
</div>

<ul class="weekdays">
  <li>Mo</li>
  <li>Tu</li>
  <li>We</li>
  <li>Th</li>
  <li>Fr</li>
  <li>Sa</li>
  <li>Su</li>
</ul>

<ul class="days">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li><span class="active">10</span></li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
  <li>19</li>
  <li>20</li>
  <li>21</li>
  <li>22</li>
  <li>23</li>
  <li>24</li>
  <li>25</li>
  <li>26</li>
  <li>27</li>
  <li>28</li>
  <li>29</li>
  <li>30</li>
  <li>31</li>
</ul>

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

Title: How to make a calendar

Body:
As a homework assignment, I need to recreate this screenshot with pure code. I currently got stuck with making the calendar. When I tried to make mine for some reason I can't get the numerical days under the day itself. As you can see there are seven days in a row but 8 numerical days in a row. How could I fix this

What changes do I need to make on my code to fix it
This is the HTML code:

Calendar

October 2017

M

T

W

T

F

S

S

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

And my CSS code:

/* Calendar */
.october{
  text-align: center;
}
.weekdays {
    margin: 0;
    padding: 10px 0;
    background-color: #cccccc;
    text-align: center;
}

.weekdays li {
    display: inline-block;
    color: #ffffff;
    width: 10%;
    text-align: center;
}

.days {
    text-align: center;
    padding: 10px 0;
    background: #eee;
    margin: 0;
}

.days li {
    list-style-type: none;
    display: inline-block;
    width: 10%;
    text-align: center;
    margin-bottom: 5px;
    font-size:12px;
    color: #777;
}

.days li .active {
    color: #3c8cd7 !important
}

P.S. I'm not completely done with everything else that's why it still looks sloppy

Body:
You can try thi. it will show you a nice result of the calondar, play with css to have the exact one in the picture..

All what is inside  separate it in the css file..

<!DOCTYPE html>
<html>
<head>

<style>
* {box-sizing: border-box;}
ul {list-style-type: none;}
body {font-family: Verdana, sans-serif;}

.month {
    padding: 70px 25px;
    width: 100%;
    background: #1abc9c;
    text-align: center;
}

.month ul {
    margin: 0;
    padding: 0;
}

.month ul li {
    color: white;
    font-size: 20px;
    text-transform: uppercase;
    letter-spacing: 3px;
}

.month .prev {
    float: left;
    padding-top: 10px;
}

.month .next {
    float: right;
    padding-top: 10px;
}

.weekdays {
    margin: 0;
    padding: 10px 0;
    background-color: #ddd;
}

.weekdays li {
    display: inline-block;
    width: 13.6%;
    color: #666;
    text-align: center;
}

.days {
    padding: 10px 0;
    background: #eee;
    margin: 0;
}

.days li {
    list-style-type: none;
    display: inline-block;
    width: 13.6%;
    text-align: center;
    margin-bottom: 5px;
    font-size:12px;
    color: #777;
}

.days li .active {
    padding: 5px;
    background: #1abc9c;
    color: white !important
}

/* Add media queries for smaller screens */
@media screen and (max-width:720px) {
    .weekdays li, .days li {width: 13.1%;}
}

@media screen and (max-width: 420px) {
    .weekdays li, .days li {width: 12.5%;}
    .days li .active {padding: 2px;}
}

@media screen and (max-width: 290px) {
    .weekdays li, .days li {width: 12.2%;}
}
</style>
</head>
<body>

<h1>CSS Calendar</h1>

<div class="month">
  <ul>
    <li class="prev">&#10094;</li>
    <li class="next">&#10095;</li>
    <li>
      August<br>
      <span style="font-size:18px">2017</span>
    </li>
  </ul>
</div>

<ul class="weekdays">
  <li>Mo</li>
  <li>Tu</li>
  <li>We</li>
  <li>Th</li>
  <li>Fr</li>
  <li>Sa</li>
  <li>Su</li>
</ul>

<ul class="days">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li><span class="active">10</span></li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
  <li>19</li>
  <li>20</li>
  <li>21</li>
  <li>22</li>
  <li>23</li>
  <li>24</li>
  <li>25</li>
  <li>26</li>
  <li>27</li>
  <li>28</li>
  <li>29</li>
  <li>30</li>
  <li>31</li>
</ul>

</body>
</html>


问:
validation of input text field in html using javascript
```<code><script type='text/javascript'>
function required()
{
    var empt = document.forms["form1"]["Name"].value;
    if (empt == "")
    {
        alert("Please input a Value");
        return false;
    }
}
</script>

<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/><br />
<input type="text" name="address line1" value="Address Line 1"/><br />
</code>```

I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.

答:
```<code>```<form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" />
<input type="submit"/>
</form>```

<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.EnableFocusOnError(false);
    frmvalidator.EnableMsgsTogether();
    frmvalidator.addValidation("name","req","Plese Enter Name");

</script>

before using above code you have to add the gen_validatorv31.js js file
</code>```

Body:
<form name="form1" method="" action="">
<input type="text" name="name" value="Name"/>

<input type="text" name="address line1" value="Address Line 1"/>

I have more than one input text field, each having their default value. Before I submit the form I have to verify whether all fields are filled. So far i got the javascript to check for null since different text boxes have different default value. How can I write a javascript to verify that user has entered data? I mean, the script must identify that input data is other than default and null.

Body:
<pre><form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" />
<input type="submit"/>
</form></pre>

<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.EnableFocusOnError(false);
    frmvalidator.EnableMsgsTogether();
    frmvalidator.addValidation("name","req","Plese Enter Name");

</script>

before using above code you have to add the gen_validatorv31.js js file


问:
Access to Laravel 5 app locally from an external device
I've looked for a solution in the web, but I've not found a solution yet.
I need to access to my Laravel 5 app from my iPhone, but I'm in develop, so I don't want to publish my app on a web server.

If you have a link to follow, that you assure it works, It's perfect for me.

Thank you!

答: If you are having trouble using the accepted answers method, and you get page not found or similar errors, this is likely due to your firewall settings. </p>