问:
how to create HTML5 playlist loop feature
I'm trying to create a playlist like youtube but I have a problem with autoplay all videos one by one, i created an on ended event to play the next video when the current playback ends
This is the code

$('video').on('ended', function() {
  // Remove .active class from the active li, select next li sibling.
  var next = $('ul.nav-tabs li.active').removeClass('active').next('li');
  var tabNext = $('.tab-content .active').removeClass('active').next('div');
  var tabNextIn = $('.tab-content .in').removeClass('in').next('div');

  // Did we reach the last element? if so: select first sibling
  if (!next.length) next = next.prevObject.siblings(':first');
  if (!tabNext.length) next = next.prevObject.siblings(':first');
  if (!tabNextIn.length) next = next.prevObject.siblings(':first');

  // Add .active class to the li next in line.
  next.addClass('active');
  tabNext.addClass('active');
  tabNextIn.addClass('in');
});

if ($('.tab-pane').hasClass('active')) {
  $('.active video').attr('autoplay', '');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

I don't understand why the next video not play

I just need to add autoplay attribute to the next video!

https://codepen.io/kemozzz/full/gXEzrp/

答:
Use the following you are not triggering the play after the playback stops see below

$(document).ready(function() {
  setTimeout(function() {
    var vidHeight = $(".video-container").height();
    $(".description").css("height", vidHeight + "px");
  }, 500);
  $(window).resize(function() {
    var vidHeight = $(".video-container").height();
    $(".description").css("height", vidHeight + "px");
  });

  $("ul.nav-tabs a").click(function() {
    let anchor = $(this);
    setTimeout(function() {
      stopvideo();
      removeActiveLi();
      $(this).parent().addClass('active');
      var vidHeight = $(".video-container").height();
      $(".description").css("height", vidHeight + "px");
      let id = anchor.attr('href').replace('#', '');

      $('div#' + id + ' > video').addClass('active');
      playvideo();
    }, 500);
  });

  $('video').on('ended', function() {
    // Remove .active class from the active li, select next li sibling.

    if ($('.active > video').get(0).paused) {

      var next = $('ul.nav-tabs li.active').removeClass('active').next('li');
      var tabNext = $('.tab-content .active').removeClass('active').next('div');
      var tabNextIn = $('.tab-content .in').removeClass('in').next('div');

      // Did we reach the last element? if so: select first sibling
      if (!next.length) next = next.prevObject.siblings(':first');
      if (!tabNext.length) next = next.prevObject.siblings(':first');
      if (!tabNextIn.length) next = next.prevObject.siblings(':first');

      // Add .active class to the li next in line.
      next.addClass('active');
      tabNext.addClass('active');
      tabNextIn.addClass('in');
      playvideo();
    }

  });

  function playvideo() {
    if ($('.tab-pane').hasClass('active')) {
      $('.active > video').get(0).play();
    }
  }

  function stopvideo() {

    $('.active > video').removeClass('active');
    document.querySelector('.active > video').pause();
  }

  function removeActiveLi() {
    $('ul.nav-tabs li.active').removeClass('active');
  }
  playvideo();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.no-padding {
  padding: 0!important;
}

body {
  height: 2000px;
}

.main-container {
  border: 2px solid #000;
  overflow: hidden;
}

.description {
  background-color: #898989;
  padding: 16px 30px;
  overflow: auto;
}

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

.description ul li a {
  background-color: #898989;
  color: #fff;
  padding-bottom: 18px;
  margin-bottom: 18px;
  position: relative;
  border: none;
}

.nav-tabs>li>a:hover {
  border: none;
  border-bottom: 2px solid #fff;
  background-color: #fff;
  color: #555555;
}

.description ul li a>h2 {
  font-weight: 700;
  font-size: 35px;
  margin: 0;
}

.description ul li a>p {
  font-size: 18px;
  line-height: 30px;
  margin-top: 5px;
  margin-bottom: 0;
}

.video-container {
  position: relative;
  z-index: 888;
}

.video-container .tools {
  position: absolute;
  width: 100%;
  height: 40px;
  background-color: #a4a4a4;
  left: 0;
  bottom: 0;
  z-index: 999;
}

.video-container:hover .tools {
  z-index: 1;
}

#style-1::-webkit-scrollbar {
  background-color: #898989;
}

#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #adadad
}

#style-1::-webkit-scrollbar {
  width: 20px;
}

@media(min-width: 992px) {
  .description {
    border-left: 2px solid #000;
  }
  .description ul li a {
    border-bottom: 2px solid #fff;
  }
}

@media(max-width: 991px) {
  .description {
    border-left: 2px solid #000;
    white-space: nowrap;
    padding: 0;
    height: auto!important;
  }
  .description ul li a {
    display: inline-block;
    width: 34%;
    padding: 14px;
    text-align: left;
    overflow: hidden;
    min-height: 252px;
    white-space: normal;
    vertical-align: text-top;
    margin-bottom: 0;
  }
  .description ul li:after {
    content: "";
    display: inline-block;
    width: 2px;
    height: 170px;
    position: absolute;
    right: 6px;
    top: 20px;
    background-color: #fff;
  }
  .description ul li:last-child:after {
    content: "";
    display: none;
  }
  .description ul li a>h2 {
    font-size: 22px;
  }
  .description ul li a>p {
    font-size: 14px;
    line-height: 23px;
  }
}

@media screen and (min-width: 220px) and (max-width: 550px) {
  .description ul li a {
    padding: 8px;
    min-height: 200px;
  }
  .description ul li a h2 {
    font-size: 14px;
  }
  .description ul li a p {
    font-size: 10px;
    line-height: 16px;
  }
}</code>```

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

          <video controls="" width="100%">
                        <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
                        <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

          <video controls="" width="100%">
                        <source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
                        <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

          <video controls="" width="100%">
                        <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
                        <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

          <video controls="" width="100%">
                        <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
                        <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>

Chapter 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt doloremque incidunt.

Chapter 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque cum error nobis.

Chapter 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit.

Chapter 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque.

```

Body:
I'm trying to create a playlist like youtube but I have a problem with autoplay all videos one by one, i created an on ended event to play the next video when the current playback ends
This is the code

$('video').on('ended', function() {
  // Remove .active class from the active li, select next li sibling.
  var next = $('ul.nav-tabs li.active').removeClass('active').next('li');
  var tabNext = $('.tab-content .active').removeClass('active').next('div');
  var tabNextIn = $('.tab-content .in').removeClass('in').next('div');

  // Did we reach the last element? if so: select first sibling
  if (!next.length) next = next.prevObject.siblings(':first');
  if (!tabNext.length) next = next.prevObject.siblings(':first');
  if (!tabNextIn.length) next = next.prevObject.siblings(':first');

  // Add .active class to the li next in line.
  next.addClass('active');
  tabNext.addClass('active');
  tabNextIn.addClass('in');
});

if ($('.tab-pane').hasClass('active')) {
  $('.active video').attr('autoplay', '');
}

I don't understand why the next video not play

I just need to add autoplay attribute to the next video!

https://codepen.io/kemozzz/full/gXEzrp/

Body:
Use the following you are not triggering the play after the playback stops see below

$(document).ready(function() {
  setTimeout(function() {
    var vidHeight = $(".video-container").height();
    $(".description").css("height", vidHeight + "px");
  }, 500);
  $(window).resize(function() {
    var vidHeight = $(".video-container").height();
    $(".description").css("height", vidHeight + "px");
  });

  $("ul.nav-tabs a").click(function() {
    let anchor = $(this);
    setTimeout(function() {
      stopvideo();
      removeActiveLi();
      $(this).parent().addClass('active');
      var vidHeight = $(".video-container").height();
      $(".description").css("height", vidHeight + "px");
      let id = anchor.attr('href').replace('#', '');

      $('div#' + id + ' > video').addClass('active');
      playvideo();
    }, 500);
  });

  $('video').on('ended', function() {
    // Remove .active class from the active li, select next li sibling.

    if ($('.active > video').get(0).paused) {

      var next = $('ul.nav-tabs li.active').removeClass('active').next('li');
      var tabNext = $('.tab-content .active').removeClass('active').next('div');
      var tabNextIn = $('.tab-content .in').removeClass('in').next('div');

      // Did we reach the last element? if so: select first sibling
      if (!next.length) next = next.prevObject.siblings(':first');
      if (!tabNext.length) next = next.prevObject.siblings(':first');
      if (!tabNextIn.length) next = next.prevObject.siblings(':first');

      // Add .active class to the li next in line.
      next.addClass('active');
      tabNext.addClass('active');
      tabNextIn.addClass('in');
      playvideo();
    }

  });

  function playvideo() {
    if ($('.tab-pane').hasClass('active')) {
      $('.active > video').get(0).play();
    }
  }

  function stopvideo() {

    $('.active > video').removeClass('active');
    document.querySelector('.active > video').pause();
  }

  function removeActiveLi() {
    $('ul.nav-tabs li.active').removeClass('active');
  }
  playvideo();
});

.no-padding {
  padding: 0!important;
}

body {
  height: 2000px;
}

.main-container {
  border: 2px solid #000;
  overflow: hidden;
}

.description {
  background-color: #898989;
  padding: 16px 30px;
  overflow: auto;
}

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

.description ul li a {
  background-color: #898989;
  color: #fff;
  padding-bottom: 18px;
  margin-bottom: 18px;
  position: relative;
  border: none;
}

.nav-tabs>li>a:hover {
  border: none;
  border-bottom: 2px solid #fff;
  background-color: #fff;
  color: #555555;
}

.description ul li a>h2 {
  font-weight: 700;
  font-size: 35px;
  margin: 0;
}

.description ul li a>p {
  font-size: 18px;
  line-height: 30px;
  margin-top: 5px;
  margin-bottom: 0;
}

.video-container {
  position: relative;
  z-index: 888;
}

.video-container .tools {
  position: absolute;
  width: 100%;
  height: 40px;
  background-color: #a4a4a4;
  left: 0;
  bottom: 0;
  z-index: 999;
}

.video-container:hover .tools {
  z-index: 1;
}

#style-1::-webkit-scrollbar {
  background-color: #898989;
}

#style-1::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: #adadad
}

#style-1::-webkit-scrollbar {
  width: 20px;
}

@media(min-width: 992px) {
  .description {
    border-left: 2px solid #000;
  }
  .description ul li a {
    border-bottom: 2px solid #fff;
  }
}

@media(max-width: 991px) {
  .description {
    border-left: 2px solid #000;
    white-space: nowrap;
    padding: 0;
    height: auto!important;
  }
  .description ul li a {
    display: inline-block;
    width: 34%;
    padding: 14px;
    text-align: left;
    overflow: hidden;
    min-height: 252px;
    white-space: normal;
    vertical-align: text-top;
    margin-bottom: 0;
  }
  .description ul li:after {
    content: "";
    display: inline-block;
    width: 2px;
    height: 170px;
    position: absolute;
    right: 6px;
    top: 20px;
    background-color: #fff;
  }
  .description ul li:last-child:after {
    content: "";
    display: none;
  }
  .description ul li a>h2 {
    font-size: 22px;
  }
  .description ul li a>p {
    font-size: 14px;
    line-height: 23px;
  }
}

@media screen and (min-width: 220px) and (max-width: 550px) {
  .description ul li a {
    padding: 8px;
    min-height: 200px;
  }
  .description ul li a h2 {
    font-size: 14px;
  }
  .description ul li a p {
    font-size: 10px;
    line-height: 16px;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container-fluid">
  <div class="row">
    <div class="space"></div>
    <div id="exTab2" class="col-xs-12 no-padding main-container">
      <div class="col-md-9 no-padding video-container tab-content">
        <!-- Item-1 -->
        <div id="1" class="tabs-container tab-pane active">
          <video controls="" width="100%">
                        <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
                        <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>
        </div>
        <div id="2" class="tabs-container tab-pane">
          <!-- Item-2 -->
          <video controls="" width="100%">
                        <source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
                        <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>
        </div>
        <div id="3" class="tabs-container tab-pane">
          <!-- Item-3 -->
          <video controls="" width="100%">
                        <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
                        <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>
        </div>
        <div id="4" class="tabs-container tab-pane">
          <!-- Item-4 -->
          <video controls="" width="100%">
                        <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
                        <source src="test.ogg" type="video/ogg"> Your browser does not support HTML5 video.</video>
        </div>
      </div>
      <!-- Item-2 -->
      <div class="col-md-3 description" id="style-1">
        <ul class="nav nav-tabs">
          <li class="active">
            <a data-toggle="tab" href="#1">
              <h2>Chapter 1</h2>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt doloremque incidunt.
              </p>
            </a>
          </li>
          <li>
            <a data-toggle="tab" href="#2">
              <h2>Chapter 2</h2>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque cum error nobis.</p>
            </a>
          </li>
          <li>
            <a data-toggle="tab" href="#3">
              <h2>Chapter 3</h2>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit.</p>
            </a>
          </li>
          <li>
            <a data-toggle="tab" href="#4">
              <h2>Chapter 4</h2>
              <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A non velit, illo vel neque sunt, rerum doloremque incidunt laudantium aliquid itaque.</p>
            </a>
          </li>
        </ul>
      </div>
    </div>
  </div>
</div>


来源: stackexchange

问:
if else condition of css in jQuery not working
I wrote below code to get my output.

```<code>$(document).ready(function(){
  if ($('.figure').css("left","702px")) {
    $('.level1').css("display", "inline-block");
  } else {
    $('.level1').css("display", "none");
  }
});
</code>```

What I want when my .figure is reach to left 702px. I want to show level1 icon. But now display none is not applying before 702px. That is level1 icon showing before reaching to 702px. Anything wrong ? please help. Even i want to add more conditions that is after some for example left 1500px of .figure then show level2 icon. Thanks.

答:
This is your intended function in vanilla javascript:</p>

```<code>function checkFigureLeft() {
    var figure = document.getElementsByClassName('figure')[0];
    var level1 = document.getElementsByClassName('level1')[0];
    var figureLeft = window.getComputedStyle(figure).getPropertyValue('left');

    if (figureLeft >= '702px') {
        level1.style.display = 'inline-block';
    }

    else {
        level1.style.display = 'none';
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I wrote below code to get my output.

$(document).ready(function(){
  if ($('.figure').css("left","702px")) {
    $('.level1').css("display", "inline-block");
  } else {
    $('.level1').css("display", "none");
  }
});

What I want when my .figure is reach to left 702px. I want to show level1 icon. But now display none is not applying before 702px. That is level1 icon showing before reaching to 702px. Anything wrong ? please help. Even i want to add more conditions that is after some for example left 1500px of .figure then show level2 icon. Thanks.

Body:
This is your intended function in vanilla javascript:

function checkFigureLeft() {
    var figure = document.getElementsByClassName('figure')[0];
    var level1 = document.getElementsByClassName('level1')[0];
    var figureLeft = window.getComputedStyle(figure).getPropertyValue('left');

    if (figureLeft >= '702px') {
        level1.style.display = 'inline-block';
    }

    else {
        level1.style.display = 'none';
    }
}


问:
I've kept a class and its members from Proguards obfuscation, but a static final member is obfuscated?
I have this class

```<code>public class MyClass extends StringType implements ProtectedAgainstProguard {

    private static final String delimiter = "#";
    private static final MyClass singleton = new MyClass ();

    private MyClass() {
        super(someStuff);
    }

    public static MyClass getSingleton() {
        return singleton;
    }

    @Override
    public Object someMethodA() {

    }

    @Override
    public Object someMethodB() {

    }
}
</code>```

Here's my ProGuard config:

```<code>-keep public interface com.example.android.application.ProtectedAgainstProguard
-keep public class * implements com.example.android.application.ProtectedAgainstProguard
-keep class * implements com.example.android.application.ProtectedAgainstProguard
-keep public class * extends com.example.android.application.ProtectedAgainstProguard
-keep class * extends com.example.android.application.ProtectedAgainstProguard
</code>```

and here is the mapping.txt for this class

```<code>com.example.android.domain.MyClass -> com.example.android.domain.MyClass :
    com.example.android.domain.MyClass singleton -> a
    15:16:void <init>() -> <init>
    24:28:java.lang.Object someMethodA() -> someMethodA
    34:38:java.lang.Object someMethodB() -> someMethodB
    12:12:void <clinit>() -> <clinit>
</code>```

As you can see the static final singleton (dont know if its the member or the method, I think its the method, is obfuscated.
How do I tell proguard to just keep its hands off the entire class and everything in it?
I don't want to list particular classes and their particular methods/members that I want to keep, I just want a general rule that says "don't do ANYTHING to a class that implements ProtectedAgainstProguard "

答:
You can use this:--</p>

```<code>-keep interface com.example.android.application.ProtectedAgainstProguard {*;}
-keepclasseswithmembers class * implements com.example.android.application.ProtectedAgainstProguard{*;}
-keepclasseswithmembers interface * extends com.example.android.application.ProtectedAgainstProguard{*;}
</code>```

Body:
I have this class

public class MyClass extends StringType implements ProtectedAgainstProguard {

    private static final String delimiter = "#";
    private static final MyClass singleton = new MyClass ();

    private MyClass() {
        super(someStuff);
    }

    public static MyClass getSingleton() {
        return singleton;
    }

    @Override
    public Object someMethodA() {

    }

    @Override
    public Object someMethodB() {

    }
}

Here's my ProGuard config:

-keep public interface com.example.android.application.ProtectedAgainstProguard
-keep public class * implements com.example.android.application.ProtectedAgainstProguard
-keep class * implements com.example.android.application.ProtectedAgainstProguard
-keep public class * extends com.example.android.application.ProtectedAgainstProguard
-keep class * extends com.example.android.application.ProtectedAgainstProguard

and here is the mapping.txt for this class

com.example.android.domain.MyClass -> com.example.android.domain.MyClass :
    com.example.android.domain.MyClass singleton -> a
    15:16:void <init>() -> <init>
    24:28:java.lang.Object someMethodA() -> someMethodA
    34:38:java.lang.Object someMethodB() -> someMethodB
    12:12:void <clinit>() -> <clinit>

As you can see the static final singleton (dont know if its the member or the method, I think its the method, is obfuscated.
How do I tell proguard to just keep its hands off the entire class and everything in it?
I don't want to list particular classes and their particular methods/members that I want to keep, I just want a general rule that says "don't do ANYTHING to a class that implements ProtectedAgainstProguard "

Body:
You can use this:--

-keep interface com.example.android.application.ProtectedAgainstProguard {*;}
-keepclasseswithmembers class * implements com.example.android.application.ProtectedAgainstProguard{*;}
-keepclasseswithmembers interface * extends com.example.android.application.ProtectedAgainstProguard{*;}


问:
Difference between geodist() and dist() for Geo-Spacial Search
What is the Difference between Geodist(sfield,x,y) and dist(2,x,y,a,b) in Apache Solr for Geo-Spacial Searches ??

dist(2,x,y,0,0) :- calculates the Euclidean distance between (0,0) and (x,y) for each document. Return the Distance between two Vectors (points) in an n-dimensional space.

I was earlier using geodist() distance function for Geo-Spatial searches on my website but its response time was large. so have done a POC(proof of concept) for different distance functions and found that dist(2,x,y,0,0) distance function is relatively taking half of the time. But I want to know the reason behind this and the algorithms which both functions are using to calculate the distance.

I have to make a difference matrix for the same to convey it further.

答:
The main difference is that geodist() is intended to work with spatial field types.

Most spatial implementation are based on Lucene's Points API, which is a BKD Index. This field type is strictly limited to coordinates in lat/lon decimal degrees. Behind the scenes, latitude and longitude are indexed as separate numbers. Four main field types are available for spatial search :

LatLonPointSpatialField

LatLonType (now deprecated) and its non-geodetic twin PointType

SpatialRecursivePrefixTreeFieldType (RPT for short), including RptWithGeometrySpatialField, a derivative

BBoxField (for areas, 4 instances of another field type referred to by numberType)

In geodist (sfield, x, y), sfield is a spatial field type that represents two points (lat,lon), so the direct equivalent using dist() would be to implement dist (2, sfieldX, sfieldY, x, y) with sfieldX and sfieldY being respectively the (lat,lon) coordinates of sfield.

Using dist (power, a, b, ...) you can't query a spatial field type. In order to perform the same spatial search, you would have to specify every point's dimension separately. It would require 2 indexed fields (or values per field at least) for 2 dimensions, 3 for 3d, and so on. That makes a huge difference because you would have to index every coordinates of each point separately.

Besides, you can also use geodist() as is with the BBoxField field type that indexes a single rectangle per document field and supports searching via a bounding box. To do the same with dist() you would have to compute the center point of the box to input each one of its coordinates as a function argument, so it would be too much hassle to yield the same result if you want to use an area as parameter.

Lastly, LatLonPointSpatialField for example does distance calculations based on Haversine formula (Great Circle), BBoxField does it a little faster because the rectangular shape is faster to compute. It's true that dist() may be even faster but remember that requires more field to be indexed, a lot of preprocess at query time to be able to yield the same calculated distance, and, as mentioned by Mats, it wouldn't take the earth' curvature into account.

ContentLicense: CC BY-SA 4.0


问:
invoke jsp from java code and get output
I have a JSP page that show data in some formatted way. the browser can call spring showInfo.do and it is forward to that JSP.
i.e.

```<code>public showInfo(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("info.jsp");
dispatcher.forward(request,response);
}
</code>```

The output of the JSP is html.

Now I want to save this JSP output manually from my java server side code (not in a servlet context), something like this:

```<code>void saveInfo() {
params.setParameter("info1", "data");
String responseStr = Invoke("info.jsp", params);
//save responseStr to disk
}
</code>```

I want to be able to save the html page on disk from a service and make it look the same as a user can see it from a browser. So if the server is offline a user can double click on the saved html file and see in his browser the last info.
Any idea how this can be done?

答:
Oups. The servlet specification requires the servlet container to be able to execute a JSP file. This is commonly done by converting the JSP to plain Java and the generating a servlet class file.

If you are outside of a servlet container you must:
* either fully implement a JSP execution environment, for example by using sources from a servlet container like Tomcat
* or rely on a servlet container to convert the JSP file to a .java or .class servlet and then use the Servlet interface methods on it

Alternatively, you could try to use a headless browser to capture the output of the application.

Body:
I have a JSP page that show data in some formatted way. the browser can call spring showInfo.do and it is forward to that JSP.
i.e.

public showInfo(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher rd = getServletContext().getRequestDispatcher("info.jsp");
dispatcher.forward(request,response);
}

The output of the JSP is html.

Now I want to save this JSP output manually from my java server side code (not in a servlet context), something like this:

void saveInfo() {
params.setParameter("info1", "data");
String responseStr = Invoke("info.jsp", params);
//save responseStr to disk
}

I want to be able to save the html page on disk from a service and make it look the same as a user can see it from a browser. So if the server is offline a user can double click on the saved html file and see in his browser the last info.
Any idea how this can be done?


问:
How does lineage get passed down in RDDs in Apache Spark
Do each RDD point to the same lineage graph

or

when a parent RDD gives its lineage to a new RDD, is the lineage graph copied by the child as well so both the parent and child have different graphs. In this case isn't it memory intensive?

答:
When a transformation(map or filter etc) is called, it is not executed by Spark immediately, instead a lineage is created for each transformation.
A lineage will keep track of what all transformations has to be applied on that RDD,
including the location from where it has to read the data.

For example, consider the following example

```<code>val myRdd = sc.textFile("spam.txt")
val filteredRdd = myRdd.filter(line => line.contains("wonder"))
filteredRdd.count()
</code>```

sc.textFile() and myRdd.filter() do not get executed immediately,
it will be executed only when an Action is called on the RDD - here filteredRdd.count().

An Action is used to either save result to some location or to display it.
RDD lineage information can also be printed by using the command filteredRdd.toDebugString(filteredRdd is the RDD here).
Also, DAG Visualization shows the complete graph in a very intuitive manner as follows:

Body:
When a transformation(map or filter etc) is called, it is not executed by Spark immediately, instead a lineage is created for each transformation.
A lineage will keep track of what all transformations has to be applied on that RDD,
including the location from where it has to read the data.

For example, consider the following example

val myRdd = sc.textFile("spam.txt")
val filteredRdd = myRdd.filter(line => line.contains("wonder"))
filteredRdd.count()

sc.textFile() and myRdd.filter() do not get executed immediately,
it will be executed only when an Action is called on the RDD - here filteredRdd.count().

An Action is used to either save result to some location or to display it.
RDD lineage information can also be printed by using the command filteredRdd.toDebugString(filteredRdd is the RDD here).
Also, DAG Visualization shows the complete graph in a very intuitive manner as follows:


问:
Add URL before image name in PHP
When i store image name in table, want to store name like URL.

For example, I have ready URL like: http://192.168.137.1/NI/uploads/ that I want to add before image name.

I want this result: http://192.168.137.1/NI/uploads/imagename.png

PHP code:

```<code>//We will upload files to this folder
//So one thing don't forget, also create a folder named uploads inside your
project folder i.e. MyApi folder
 define('UPLOAD_PATH', 'uploads/');

 //connecting to database
 $conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('Unable to
 connect');

  //An array to display the response
  $response = array();

   //if the call is an api call
   if(isset($_GET['apicall'])){

    //switching the api call
    switch($_GET['apicall']){

    //if it is an upload call we will upload the image
    case 'uploadpic':

    //first confirming that we have the image and tags in the request
    parameter
   if(isset($_FILES['pic']['name']) && isset($_POST['tags'])){

  //uploading file and storing it to database as well
 try{
 move_uploaded_file($_FILES['pic']['tmp_name'], UPLOAD_PATH . $_FILES['pic']
['name']);

 $stmt = $conn->prepare("INSERT INTO t_table (image,tags)
VALUES (?,?)");

 $stmt->bind_param("ss", $_FILES['pic']['name'],$_POST['tags']);
 if($stmt->execute()){
 $response['error'] = false;
 $response['message'] = 'File uploaded successfully';
 }else{
 throw new Exception("Could not upload file");
 }
 }catch(Exception $e){
 $response['error'] = true;
 $response['message'] = 'Could not upload file';
}

 }else{
 $response['error'] = true;
 $response['message'] = "Required params not available";
 }
</code>```

答:
try this

public function url($patheFile, $imageName)
    {
        return sprintf(
            "%s://%s%s",
            isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
            $_SERVER['SERVER_NAME'],
            $_SERVER['REQUEST_URI']
        );
    }
echo url('uplode', $_FILES['pic']['name'])

Title: Add URL before image name in PHP

Body:
When i store image name in table, want to store name like URL.

For example, I have ready URL like: http://192.168.137.1/NI/uploads/ that I want to add before image name.

I want this result: http://192.168.137.1/NI/uploads/imagename.png

PHP code:

//We will upload files to this folder
//So one thing don't forget, also create a folder named uploads inside your
project folder i.e. MyApi folder
 define('UPLOAD_PATH', 'uploads/');

 //connecting to database
 $conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('Unable to
 connect');

  //An array to display the response
  $response = array();

   //if the call is an api call
   if(isset($_GET['apicall'])){

    //switching the api call
    switch($_GET['apicall']){

    //if it is an upload call we will upload the image
    case 'uploadpic':

    //first confirming that we have the image and tags in the request
    parameter
   if(isset($_FILES['pic']['name']) && isset($_POST['tags'])){

  //uploading file and storing it to database as well
 try{
 move_uploaded_file($_FILES['pic']['tmp_name'], UPLOAD_PATH . $_FILES['pic']
['name']);

 $stmt = $conn->prepare("INSERT INTO t_table (image,tags)
VALUES (?,?)");

 $stmt->bind_param("ss", $_FILES['pic']['name'],$_POST['tags']);
 if($stmt->execute()){
 $response['error'] = false;
 $response['message'] = 'File uploaded successfully';
 }else{
 throw new Exception("Could not upload file");
 }
 }catch(Exception $e){
 $response['error'] = true;
 $response['message'] = 'Could not upload file';
}

 }else{
 $response['error'] = true;
 $response['message'] = "Required params not available";
 }


问:
How do you split a list by space in python?
How do you split a list by space? With the code below, it reads a file with 4 lines of 7 numbers separated by spaces. When it takes the file and then splits it, it splits it by number so if i print item[0], 5 will print instead of 50. here is the code

```<code>def main():
    filename = input("Enter the name of the file: ")
    infile = open(filename, "r")
    for i in range(4):
        data = infile.readline()
        print(data)
        item = data.split()
        print(data[0])

main()
</code>```

the file looks like this

50 60 15 100 60 15 40 /n
100 145 20 150 145 20 45 /n
50 245 25 120 245 25 50 /n
100 360 30 180 360 30 55 /n

答:
```<code>import nltk

tokens = nltk.word_tokenize(TextInTheFile)
</code>```

Try this once you have opened that file.

TextInTheFile is a variable

Body:
How do you split a list by space? With the code below, it reads a file with 4 lines of 7 numbers separated by spaces. When it takes the file and then splits it, it splits it by number so if i print item[0], 5 will print instead of 50. here is the code

def main():
    filename = input("Enter the name of the file: ")
    infile = open(filename, "r")
    for i in range(4):
        data = infile.readline()
        print(data)
        item = data.split()
        print(data[0])

main()

the file looks like this

50 60 15 100 60 15 40 /n
100 145 20 150 145 20 45 /n
50 245 25 120 245 25 50 /n
100 360 30 180 360 30 55 /n

Body:
import nltk

tokens = nltk.word_tokenize(TextInTheFile)

Try this once you have opened that file.

TextInTheFile is a variable


问:
How to understand javascript Generator?
I have a snippet of code

function* dataConsumer() {
   console.log('Started');
   console.log(`1. ${yield}`);
   console.log(`2. ${yield}`);
   return 'result';
}

let genObj = dataConsumer();
genObj.next();```
</div>
</div>
</p>

<p>and the running result is</p>

```Started
```

I don't understand why the second console.log can't output anything. Thanks for help.

答:
Generators are build on the top of Iterators. To understand generator, you need first to understand iterator. See the Documentation.

For a one flow it runs to the nearer yield and terminates the function call. After it when you call again next it will continue from where it was terminated and works again until the nearest yield and when there are no yields or it reaches to the return statement, it just finishes its call.

function* dataConsumer() {
  console.log('Started');
  console.log(`1. ${yield}`); // First `next` terminates before yield. Second `next` passes the value and terminates before the next yield.
  console.log(`2. ${yield}`); // Third call continues from the `yield` part and finishes the function, because we have returned
  return 'result';
}

let genObj = dataConsumer();
genObj.next();
genObj.next('yield1');
genObj.next('yield2'); ```
</div>
</div>
</p>

<p>You also can pass parameters to the <code>next</code> function, which will be put in the <code>yield</code> statement. Also the <code>next</code> function returns an object about the generator state with properties <code>value</code> and <code>done</code>. If function call is not finished, it returns <code>done</code> as false and at the end you can see that this is set to <code>true</code>.</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function* dataConsumer() {
  console.log('Started');
  const x = yield;
  console.log(`1. ${x}`);
  console.log(`2. ${yield}`);
  return 'result';
}

let genObj = dataConsumer();
let result = genObj.next();
console.log(result);

result = genObj.next('x is yield1');
console.log(result);

result = genObj.next('yield2');
console.log(result);

genObj.next(); // This one has nothing to do</code>```

As you can pass parameters to the generator each step, you also can return a value from . You need to write something similar to return something, just replacing return with yield.

function* dataConsumer() {
  yield 1;
  yield 2;
  yield 3;
}

let genObj = dataConsumer();
let result = genObj.next();
console.log(result);

result = genObj.next();
console.log(result);

result = genObj.next();
console.log(result);

result = genObj.next();
console.log(result);```

Title: How to understand javascript Generator?

Body:
I have a snippet of code

function* dataConsumer() {
   console.log('Started');
   console.log(`1. ${yield}`);
   console.log(`2. ${yield}`);
   return 'result';
}

let genObj = dataConsumer();
genObj.next();

and the running result is

Started

I don't understand why the second console.log can't output anything. Thanks for help.

Body:
Generators are build on the top of Iterators. To understand generator, you need first to understand iterator. See the Documentation.

For a one flow it runs to the nearer yield and terminates the function call. After it when you call again next it will continue from where it was terminated and works again until the nearest yield and when there are no yields or it reaches to the return statement, it just finishes its call.

function* dataConsumer() {
  console.log('Started');
  console.log(`1. ${yield}`); // First `next` terminates before yield. Second `next` passes the value and terminates before the next yield.
  console.log(`2. ${yield}`); // Third call continues from the `yield` part and finishes the function, because we have returned
  return 'result';
}

let genObj = dataConsumer();
genObj.next();
genObj.next('yield1');
genObj.next('yield2');

You also can pass parameters to the next function, which will be put in the yield statement. Also the next function returns an object about the generator state with properties value and done. If function call is not finished, it returns done as false and at the end you can see that this is set to true.

function* dataConsumer() {
  console.log('Started');
  const x = yield;
  console.log(`1. ${x}`);
  console.log(`2. ${yield}`);
  return 'result';
}

let genObj = dataConsumer();
let result = genObj.next();
console.log(result);

result = genObj.next('x is yield1');
console.log(result);

result = genObj.next('yield2');
console.log(result);

genObj.next(); // This one has nothing to do

As you can pass parameters to the generator each step, you also can return a value from . You need to write something similar to return something, just replacing return with yield.

function* dataConsumer() {
  yield 1;
  yield 2;
  yield 3;
}

let genObj = dataConsumer();
let result = genObj.next();
console.log(result);

result = genObj.next();
console.log(result);

result = genObj.next();
console.log(result);

result = genObj.next();
console.log(result);


问:
How can I set margin none on first child in rtl?
I have four progress bars in a vertical form in which I want margin none on the first child in rtl. So how can I set margin none on the first child ? I also tried first child property.

.progress-bar-vertical:first-child {
    margin-right: 0px !important;
}
```

答:
If you have the dir property set to rtl on the html tag, you can apply RTL-specific styles like:</p>

```<code>html[dir='rtl'] .progress-bar-vertical:first-child {
    margin: none;
}
</code>```

Body:
If you have the dir property set to rtl on the html tag, you can apply RTL-specific styles like:

html[dir='rtl'] .progress-bar-vertical:first-child {
    margin: none;
}


问:
Jmeter: multiple values for a single Varchar parameter in CSV
I have to parameterize my values

my CSV file looks like(last six parameters are VARCHAR)

```<code>74861,1,'123,122,127',0,0,0,0,0
</code>```

Jmeter considers 123,122,127 as separate argument and gives following error:

Error: number of arguments (10) and number of types (8) are not equal.

答:
You should use double quotes instead of quote,as :

```<code>74861,1,"123,122,127",0,0,0,0,0
</code>```

JMeter allows values to be quoted; this allows the value to contain a delimiter. If "allow quoted data" is enabled, a value may be enclosed in double-quotes. These are removed. To include double-quotes within a quoted field, use two double-quotes. For example:

1,"2,3","4""5" =>

1

2,3

4"5

Body:
I have to parameterize my values

my CSV file looks like(last six parameters are VARCHAR)

74861,1,'123,122,127',0,0,0,0,0

Jmeter considers 123,122,127 as separate argument and gives following error:

Error: number of arguments (10) and number of types (8) are not equal.

Body:
You should use double quotes instead of quote,as :

74861,1,"123,122,127",0,0,0,0,0

JMeter allows values to be quoted; this allows the value to contain a delimiter. If "allow quoted data" is enabled, a value may be enclosed in double-quotes. These are removed. To include double-quotes within a quoted field, use two double-quotes. For example:

1,"2,3","4""5" =>

1

2,3

4"5


问:
ASP.NET webforms listbox - cross-page posting
I'm new to ASP.NET, and I'm having a problem getting a listbox to return the proper data when posting to another page. I have gotten dropdownlists and radio buttons to work. For instance, for dropdownlists, I simply did this:

```<code>Public ReadOnly Property SiteID() As String
    Get
        Return ddlSites.SelectedValue
    End Get
</code>```

Then, on the next page, I successfully returned the value using PreviousPage.SiteID. However, when I try this for a listbox:

```<code>Public ReadOnly Property CustID() As String
    Get
        Return lstLoggedInCustomers.SelectedValue.ToString
    End Get
End Property
</code>```

then call it using PreviousPage, I get an empty string, as SelectedIndex is always returning -1, even though I select an item in the listbox.

答:
In this case you can persist the value in viewstate before redirecting to another page. So from the next page you call just like:

```<code>Public ReadOnly Property CustID() As String
    Get
        Return viewstate("myCustID")
    End Get
End Property
</code>```

I hope it will work.

ContentLicense: CC BY-SA 2.5

Body:
I'm new to ASP.NET, and I'm having a problem getting a listbox to return the proper data when posting to another page. I have gotten dropdownlists and radio buttons to work. For instance, for dropdownlists, I simply did this:

Public ReadOnly Property SiteID() As String
    Get
        Return ddlSites.SelectedValue
    End Get

Then, on the next page, I successfully returned the value using PreviousPage.SiteID. However, when I try this for a listbox:

Public ReadOnly Property CustID() As String
    Get
        Return lstLoggedInCustomers.SelectedValue.ToString
    End Get
End Property

then call it using PreviousPage, I get an empty string, as SelectedIndex is always returning -1, even though I select an item in the listbox.

Body:
In this case you can persist the value in viewstate before redirecting to another page. So from the next page you call just like:

Public ReadOnly Property CustID() As String
    Get
        Return viewstate("myCustID")
    End Get
End Property

I hope it will work.


问:
Crashes after startActivityForResult in API 27
After updating to API 27 and Support library 27.0.2 suddenly I get a lot of these stack traces in Crashlytics:

```<code>Fatal Exception: java.lang.IllegalArgumentException
    at android.os.Parcel.readException(Parcel.java:1544)
    at android.os.Parcel.readException(Parcel.java:1493)
    at android.app.ActivityManagerProxy.isTopOfTask(ActivityManagerNative.java:5108)
    at android.app.Activity.isTopOfTask(Activity.java:5688)
    at android.app.Activity.startActivityForResult(Activity.java:3973)
    at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(Source:54)
    at android.support.v4.app.FragmentActivity.startActivityForResult(Source:67)
</code>```

I call this like:

```<code>ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
startActivityForResult( intent, REQ_ACTION, options.toBundle());
</code>```

I cannot read the source code as it is not released yet. I even tried to replace and use android-26 code, but it's different.

There is a warning for the above call saying that BaseFragmentActivityApi16.startActivityForResult can only called from the same library group, so I fixed it by using ActivityCompat, but I don't think it will solve the crash problem.

Is this a platform issue or can I fix this?

Edit

```<code>if (Build.VERSION.SDK_INT >= 21) {
    ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
    startActivityForResult(intent, REQ_ACTION, options.toBundle());
} else {
    ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
    ActivityCompat.startActivityForResult(this, intent, REQ_ACTION, options.toBundle());
}
</code>```

If I change it to the above according to the link in my comment, Android Studio complaining like above. This might be related to the problem.

答:
You can try this code.    </p>

```<code>startActivityForResult( intent, REQ_ACTION)
overridePendingTransition(R.anim.slide_in_from_right,  R.anim.fade_out);
</code>```

Body:
After updating to API 27 and Support library 27.0.2 suddenly I get a lot of these stack traces in Crashlytics:

Fatal Exception: java.lang.IllegalArgumentException
    at android.os.Parcel.readException(Parcel.java:1544)
    at android.os.Parcel.readException(Parcel.java:1493)
    at android.app.ActivityManagerProxy.isTopOfTask(ActivityManagerNative.java:5108)
    at android.app.Activity.isTopOfTask(Activity.java:5688)
    at android.app.Activity.startActivityForResult(Activity.java:3973)
    at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(Source:54)
    at android.support.v4.app.FragmentActivity.startActivityForResult(Source:67)

I call this like:

ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
startActivityForResult( intent, REQ_ACTION, options.toBundle());

I cannot read the source code as it is not released yet. I even tried to replace and use android-26 code, but it's different.

There is a warning for the above call saying that BaseFragmentActivityApi16.startActivityForResult can only called from the same library group, so I fixed it by using ActivityCompat, but I don't think it will solve the crash problem.

Is this a platform issue or can I fix this?

Edit

if (Build.VERSION.SDK_INT >= 21) {
    ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
    startActivityForResult(intent, REQ_ACTION, options.toBundle());
} else {
    ActivityOptions options = ActivityOptions.makeCustomAnimation(activity, R.anim.slide_in_from_right, R.anim.fade_out);
    ActivityCompat.startActivityForResult(this, intent, REQ_ACTION, options.toBundle());
}

If I change it to the above according to the link in my comment, Android Studio complaining like above. This might be related to the problem.

Body:
You can try this code.

startActivityForResult( intent, REQ_ACTION)
overridePendingTransition(R.anim.slide_in_from_right,  R.anim.fade_out);


问:
Uniqueness in requestcodes of pending intents in triggering alarms
I have a hashmap of (Date, Integer) where Date says the time when I should trigger an Alarm and Integer says for how many days I should repeat the Alarm at that time.

Here, inorder to set multiple alarms using android alarm manager it was said that I should set pending intents with unique request code.

My issue is saying for Example:

```<code>My hashmap values-
9:00 AM - 4 days
3:00 PM - 7 days
</code>```

As of my understanding now I should have total (4+7=)11 pending intents to be set.
now in order to set these alarms, I should have 11 unique request codes..if there are plenty of alarms and the day number increases there are plenty of pending intents to be set where uniqueness is a question mark!

Is that we should generate unique ones or are we having any best solution?

As I'm learning this concept please correct me if I am wrong.

Thanks in Advance!

答:
Let's work with an example, we have two things to schedule

A one time alarm

An alarm for the next 5 days

What you will need is two PendingIntents, one for each.

The one for the one time thing is clear i suppose, you use AlarmManager#set() and you supply a PendingIntent with a unique id.

The other one, you will need to use AlarmManager#setRepeating() and pass in the interval as (milliseconds in a day) assuming you want the alarm to be at same time each day, and this one will one another unique ID.

You end up only needing 2 uniques IDs in total.

For a recurring event, you need one ID, you don't need an ID for each recurrence.

Here is the trick, I am not aware of an API that allows you to restrict a repeating alarm for number of days. So basically whenever your PendingIntent fires, you need to check if this is the last day it should be fired, and if it is, you can use AlarmManager#cancel() to do that.

First idea that comes to mind is calculate the end time of that event, and check every time the intent is fire if you are passed that time or not.

Code example:

```<code>PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(),uniqueid, intent, PendingIntent.FLAG_UPDATE_CURRENT)
long alarmTimeInMillis = ..; // your own value here
long oneDayInterval = 1000 * 60 * 60 * 24; // 24 hours in millis
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, alarmTimeInMillis,
        oneDayInterval, alarmIntent);
</code>```

Also please refer back to documentation to determine which method best fits the accuracy your require.

Body:
I have a hashmap of (Date, Integer) where Date says the time when I should trigger an Alarm and Integer says for how many days I should repeat the Alarm at that time.

Here, inorder to set multiple alarms using android alarm manager it was said that I should set pending intents with unique request code.

My issue is saying for Example:

My hashmap values-
9:00 AM - 4 days
3:00 PM - 7 days

As of my understanding now I should have total (4+7=)11 pending intents to be set.
now in order to set these alarms, I should have 11 unique request codes..if there are plenty of alarms and the day number increases there are plenty of pending intents to be set where uniqueness is a question mark!

Is that we should generate unique ones or are we having any best solution?

As I'm learning this concept please correct me if I am wrong.

Thanks in Advance!

Body:
Let's work with an example, we have two things to schedule

A one time alarm

An alarm for the next 5 days

What you will need is two PendingIntents, one for each.

The one for the one time thing is clear i suppose, you use AlarmManager#set() and you supply a PendingIntent with a unique id.

The other one, you will need to use AlarmManager#setRepeating() and pass in the interval as (milliseconds in a day) assuming you want the alarm to be at same time each day, and this one will one another unique ID.

You end up only needing 2 uniques IDs in total.

For a recurring event, you need one ID, you don't need an ID for each recurrence.

Here is the trick, I am not aware of an API that allows you to restrict a repeating alarm for number of days. So basically whenever your PendingIntent fires, you need to check if this is the last day it should be fired, and if it is, you can use AlarmManager#cancel() to do that.

First idea that comes to mind is calculate the end time of that event, and check every time the intent is fire if you are passed that time or not.

Code example:

PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(),uniqueid, intent, PendingIntent.FLAG_UPDATE_CURRENT)
long alarmTimeInMillis = ..; // your own value here
long oneDayInterval = 1000 * 60 * 60 * 24; // 24 hours in millis
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, alarmTimeInMillis,
        oneDayInterval, alarmIntent);

Also please refer back to documentation to determine which method best fits the accuracy your require.


问:
Synchronous way of handling asynchronous function, two level deep
I am looping over an array to update its values using returned value from called function which internally calls an asynchronous function.

I need to handle asynchronous function in synchronous way which is not being directly called. This is replication of scenario.

```<code>function condition(){
    // Code of this function is not accessible to me.
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            if(parseInt(Math.random() * 100) % 2){
                resolve(true);
            }
            else{
                reject(false)
            }
        }, 1000)
    });
}

async function delayIncrease(value){
    var choice = await condition();

    if(choice) { return ++value; }
    else { return --value; }
}

// Start calling functions
dataArr = [1,2,3,4,5];
for(var i in dataArr){
    dataArr[i] = delayIncrease(dataArr[i]);
}
</code>```

If possible, I would like to have the solution in above structure mentioned.

I have achieved the desired result by adding other function and passing "index" + "new_value" as parameters. This function directly modifies original array and produces desired result. Working example.

```<code>function condition(){
    // Code of this function is not accessible to me.
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            if(parseInt(Math.random() * 100) % 2){
                resolve(true);
            }
            else{
                reject(false)
            }
        }, 1000)
    });
}

function delayIncrease(value, index){
    condition().then(
        function(){ updateData(++value, index) },
        function(){ updateData(--value, index) }
    )
}

function updateData(value, index){
    dataArr[index] = value;
}

dataArr = [1,2,3,4,5];
for(var i in dataArr){
    dataArr[i] = delayIncrease(dataArr[i], i);
}
</code>```

Please provide solution for this requirement in best possible way. Possible solution in Angular 4 way is also appriciated. I thought of writing it in normal JavaScript form as Observables behave nearly same.

I followed this Medium page and http://exploringjs.com

答:
You could do something like this:

```<code>var condition = async () =>
  (parseInt(Math.random() * 100) % 2)
    ? true
    : false

var delayIncrease =  async (value) =>
  (await condition())
    ? ++value
    : --value

var dataArr = [1, 2, 3, 4, 5];
// Start calling functions
Promise.all(
  dataArr.map(
    delayIncrease
  )
)
.then(
  resolve => console.log("results:",resolve)
  ,reject => console.warn("rejected:",reject)
)
</code>```

Once something is async you have to make the entire call stack prior to that function async. If a function calls an async function that that function returns an async value and so does the one calling it and calling it and calling it ...

More info on javascript async and why can be found here.

Since the example provided doesn't have any async api's in there you don't need to do it async:

```<code>var condition = () =>
  (parseInt(Math.random() * 100) % 2)
    ? true
    : false

var delayIncrease =  (value) =>
  (condition())
    ? ++value
    : --value

var dataArr = [1, 2, 3, 4, 5];
// Start calling functions
dataArr.map(
  delayIncrease
)
</code>```

[update]

When you mutate an array of objects and cosole.log it you may not see the values as they actually were when you log it but you see the values as they are right now (this is a "bug" in console.log).

Consider the following:

```<code>var i = -1,arr=[];
while(++i<1){
  arr[i]={};
  arr[i]["name"+i]=i
}

var process = (index) =>
  arr[index]["name"+index]++;

arr.forEach(
  (item,index) =>
    Promise.resolve(index)
    .then(process)
);
console.log("obj at the moment you are looking at it:",arr)
console.log("obj at the moment it is logged:",JSON.stringify(arr))
</code>```

When you expand obj at the moment you are looking at it you see that name0 property of the first element changed to 1.

However; look at obj at the moment it is logged: and see the actual value of the first element in the array. It has name0 of 0.

You may think that the that code runs asynchronous functions in a synchronous way by mutating the object(s) in an array, but you actually experience a "bug" in console.log

Body:
I am looping over an array to update its values using returned value from called function which internally calls an asynchronous function.

I need to handle asynchronous function in synchronous way which is not being directly called. This is replication of scenario.

function condition(){
    // Code of this function is not accessible to me.
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            if(parseInt(Math.random() * 100) % 2){
                resolve(true);
            }
            else{
                reject(false)
            }
        }, 1000)
    });
}

async function delayIncrease(value){
    var choice = await condition();

    if(choice) { return ++value; }
    else { return --value; }
}

// Start calling functions
dataArr = [1,2,3,4,5];
for(var i in dataArr){
    dataArr[i] = delayIncrease(dataArr[i]);
}

If possible, I would like to have the solution in above structure mentioned.

I have achieved the desired result by adding other function and passing "index" + "new_value" as parameters. This function directly modifies original array and produces desired result. Working example.

function condition(){
    // Code of this function is not accessible to me.
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            if(parseInt(Math.random() * 100) % 2){
                resolve(true);
            }
            else{
                reject(false)
            }
        }, 1000)
    });
}

function delayIncrease(value, index){
    condition().then(
        function(){ updateData(++value, index) },
        function(){ updateData(--value, index) }
    )
}

function updateData(value, index){
    dataArr[index] = value;
}

dataArr = [1,2,3,4,5];
for(var i in dataArr){
    dataArr[i] = delayIncrease(dataArr[i], i);
}

Please provide solution for this requirement in best possible way. Possible solution in Angular 4 way is also appriciated. I thought of writing it in normal JavaScript form as Observables behave nearly same.

I followed this Medium page and http://exploringjs.com

Body:
You could do something like this:

var condition = async () =>
  (parseInt(Math.random() * 100) % 2)
    ? true
    : false

var delayIncrease =  async (value) =>
  (await condition())
    ? ++value
    : --value

var dataArr = [1, 2, 3, 4, 5];
// Start calling functions
Promise.all(
  dataArr.map(
    delayIncrease
  )
)
.then(
  resolve => console.log("results:",resolve)
  ,reject => console.warn("rejected:",reject)
)

Once something is async you have to make the entire call stack prior to that function async. If a function calls an async function that that function returns an async value and so does the one calling it and calling it and calling it ...

More info on javascript async and why can be found here.

Since the example provided doesn't have any async api's in there you don't need to do it async:

var condition = () =>
  (parseInt(Math.random() * 100) % 2)
    ? true
    : false

var delayIncrease =  (value) =>
  (condition())
    ? ++value
    : --value

var dataArr = [1, 2, 3, 4, 5];
// Start calling functions
dataArr.map(
  delayIncrease
)

[update]

When you mutate an array of objects and cosole.log it you may not see the values as they actually were when you log it but you see the values as they are right now (this is a "bug" in console.log).

Consider the following:

var i = -1,arr=[];
while(++i<1){
  arr[i]={};
  arr[i]["name"+i]=i
}

var process = (index) =>
  arr[index]["name"+index]++;

arr.forEach(
  (item,index) =>
    Promise.resolve(index)
    .then(process)
);
console.log("obj at the moment you are looking at it:",arr)
console.log("obj at the moment it is logged:",JSON.stringify(arr))

When you expand obj at the moment you are looking at it you see that name0 property of the first element changed to 1.

However; look at obj at the moment it is logged: and see the actual value of the first element in the array. It has name0 of 0.

You may think that the that code runs asynchronous functions in a synchronous way by mutating the object(s) in an array, but you actually experience a "bug" in console.log


问:
Conditionals won't work
Okay so me and my friend are programming a small basic torture game and when I try to run my part of the code, some of the if/elif it will not run as if they were False when they seem True

```<code>lives = 5
lives_1 = 13
random_number = random.randint(0,100)
random_number_1 = random.randit(0,1000)
        while lives > 0:
            print random_number # delete in final product
            print "'You have %d chances to save your partner'" % (lives)
            guess_0 = int(raw_input("Guess a number from 1 to 100 "))
            print "You have guessed %d" % (guess_0)
            proceed_2 = raw_input("Press 'Enter' to proceed")
            if guess_0 != random_number: # This works
                print "It is incorrect, your partner loses a finger"
                lives -= 1
                continue
            elif guess_0 == random_number: # This works
                print "It is correct you and your partner get to walk free"
                print "GAME OVER"
                break
            elif guess > random_number: # Doesn't work
                print "'LOWER!'"
            elif guess < random_number: # Doesn't work
                print "'HIGHER!'"
        else:
            print "GAME OVER"

    while lives_1 > 0:
        print random_number_1 # delete in final product
        print "'You ha-- %d ch---e-'" % (lives_1)
        guess_1 = raw_input("What should you do? ")
        proceed_1 = raw_input("Press Enter to proceed")
        print "You decided to shout {}".format(guess_1)
        if guess_1 == random_number_1:
            print "The cult has decided to let you go" # doesn't work
            break
        elif guess_1 != random_number_1: # Works but also works when false
            lives_1 -= 1
            if lives_1 < 5:
                print "Tears begin to blind you as you're nearing death"
            continue
        elif guess_1 < random_number_1: # doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'Higher'"
        elif guess_1 > random_number_1: #doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'LOWER...'"
    else:
        print "GAME OVER"
</code>```

I want it to print out larger or larger than 3 but as you can see it won't. I have the same problem with the other one.

For the second while function, when I enter a number lower or larger than random_number(_1) it won't print out larger or lower and if I enter the value for random_number(_1) it won't run. I can't see anything wrong please help

答:
You may avoid to use the while loop until you are obliged, it may be better with a for loop.

In case of a bug appear on exit loop condition, while loop could end with infinite loop, which may result to a computer freeze or heavy ressource load ...

Title: Conditionals won't work

Body:
Okay so me and my friend are programming a small basic torture game and when I try to run my part of the code, some of the if/elif it will not run as if they were False when they seem True

lives = 5
lives_1 = 13
random_number = random.randint(0,100)
random_number_1 = random.randit(0,1000)
        while lives > 0:
            print random_number # delete in final product
            print "'You have %d chances to save your partner'" % (lives)
            guess_0 = int(raw_input("Guess a number from 1 to 100 "))
            print "You have guessed %d" % (guess_0)
            proceed_2 = raw_input("Press 'Enter' to proceed")
            if guess_0 != random_number: # This works
                print "It is incorrect, your partner loses a finger"
                lives -= 1
                continue
            elif guess_0 == random_number: # This works
                print "It is correct you and your partner get to walk free"
                print "GAME OVER"
                break
            elif guess > random_number: # Doesn't work
                print "'LOWER!'"
            elif guess < random_number: # Doesn't work
                print "'HIGHER!'"
        else:
            print "GAME OVER"

    while lives_1 > 0:
        print random_number_1 # delete in final product
        print "'You ha-- %d ch---e-'" % (lives_1)
        guess_1 = raw_input("What should you do? ")
        proceed_1 = raw_input("Press Enter to proceed")
        print "You decided to shout {}".format(guess_1)
        if guess_1 == random_number_1:
            print "The cult has decided to let you go" # doesn't work
            break
        elif guess_1 != random_number_1: # Works but also works when false
            lives_1 -= 1
            if lives_1 < 5:
                print "Tears begin to blind you as you're nearing death"
            continue
        elif guess_1 < random_number_1: # doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'Higher'"
        elif guess_1 > random_number_1: #doesn't work
            print "You squeel in agony as one of your nails were ripped off"
            print "'LOWER...'"
    else:
        print "GAME OVER"

I want it to print out larger or larger than 3 but as you can see it won't. I have the same problem with the other one.

For the second while function, when I enter a number lower or larger than random_number(_1) it won't print out larger or lower and if I enter the value for random_number(_1) it won't run. I can't see anything wrong please help


问:
Updating dataframe column names based on values given in another dataframe
I am very new to python. I am trying to rename the columns of a data frame based on another dataframe.

Essentially My data looks like

DataFrame1

```<code>A    B    C   D
1    2    3   4
</code>```

I have another table that looks like this' DataFrame2

```<code>Col1    Col2
A       E
B       Q
C       R
D       Z
</code>```

I want to rename the columns of my first data frame based on this table so that it will come out: Note. The columns name order are not same.

```<code>E    Q    R    Z
1    2    3    4
</code>```

答:
Use rename by dictionary created by zip:

```<code>d = dict(zip(df1['Col1'], df1['Col2']))
df = df.rename(columns=d)
print (df)
   E  Q  R  Z
0  1  2  3  4
</code>```

Body:
I am very new to python. I am trying to rename the columns of a data frame based on another dataframe.

Essentially My data looks like

DataFrame1

A    B    C   D
1    2    3   4

I have another table that looks like this' DataFrame2

Col1    Col2
A       E
B       Q
C       R
D       Z

I want to rename the columns of my first data frame based on this table so that it will come out: Note. The columns name order are not same.

E    Q    R    Z
1    2    3    4

Body:
Use rename by dictionary created by zip:

d = dict(zip(df1['Col1'], df1['Col2']))
df = df.rename(columns=d)
print (df)
   E  Q  R  Z
0  1  2  3  4


问:
Create a method in an eloquent relationship
I have two models. One is Order and the other is Item. An order can have many items, and an item can have only one order.

I have this inside of my Order model:

```<code>public function items() {
    return $this->hasMany('App\Item', 'OrderNumber', 'OrderNumber');
}
</code>```

And here's my Item model:

```<code>function order() {
    return $this->belongsTo('App\Order');
}
</code>```

I'd like to have a function that can get the total of all of the items for an order. For example, I want to be able to use $order->items->totalPrice() to retrieve the total.

I've tried adding this to the Item model, with no luck.

```<code>public function totalPrice() {

    $total = 0;

    foreach($this as $item) {
        $total += $item->AmountPaid;
    }

    return $total;

}
</code>```

Here's the error I'm getting:

```<code>Undefined property: Illuminate\Database\Eloquent\Collection::$totalPrice
</code>```

What is the best/cleanest way to do what I'm trying to achieve? Even better, does Laravel have a built in method for totalling up?

答:
You may try something like this:

```<code>$order = Order::with('items')->find(10);
$total = $order->totalPrice();
</code>```

In your Order model, you need to write:

```<code>public function totalPrice()
{
    $total = 0;

    if (!empty($this->items)) {
        foreach($this->items as $item) {
            $total += $item->AmountPaid;
        }
    }

    return $total;
}
</code>```

Not the most elegant way, but might be worth looking into.

Body:
I have two models. One is Order and the other is Item. An order can have many items, and an item can have only one order.

I have this inside of my Order model:

public function items() {
    return $this->hasMany('App\Item', 'OrderNumber', 'OrderNumber');
}

And here's my Item model:

function order() {
    return $this->belongsTo('App\Order');
}

I'd like to have a function that can get the total of all of the items for an order. For example, I want to be able to use $order->items->totalPrice() to retrieve the total.

I've tried adding this to the Item model, with no luck.

public function totalPrice() {

    $total = 0;

    foreach($this as $item) {
        $total += $item->AmountPaid;
    }

    return $total;

}

Here's the error I'm getting:

Undefined property: Illuminate\Database\Eloquent\Collection::$totalPrice

What is the best/cleanest way to do what I'm trying to achieve? Even better, does Laravel have a built in method for totalling up?

Body:
You may try something like this:

$order = Order::with('items')->find(10);
$total = $order->totalPrice();

In your Order model, you need to write:

public function totalPrice()
{
    $total = 0;

    if (!empty($this->items)) {
        foreach($this->items as $item) {
            $total += $item->AmountPaid;
        }
    }

    return $total;
}

Not the most elegant way, but might be worth looking into.


问:
I have two images, If I ,,hover" over the second, the first must change on this second image
 first  src=>img/header.jpg alt=>first />

second src=>img/pexels-photo-261146.jpeg alt=>second />

second:hover - first background-image:url(img/pexels-photo-261146.jpeg);

答:
Try to be more clear on what you're asking because I'm not quite understanding, but wat I can deduce is that you want to change the first image when you hover the second one. What you should try to do is something like

```<code><image1 id="change">
<image2 onmouseover="changeFirst(change);">

function changeFirst(String id){
    $("#id").attr("src", "secondImage.jpg");
}
</code>```

Like this your function in Jquery recieves the id of the tag that you want to change the src attribute and the you can change the image.

Body:
Try to be more clear on what you're asking because I'm not quite understanding, but wat I can deduce is that you want to change the first image when you hover the second one. What you should try to do is something like

<image1 id="change">
<image2 onmouseover="changeFirst(change);">

function changeFirst(String id){
    $("#id").attr("src", "secondImage.jpg");
}

Like this your function in Jquery recieves the id of the tag that you want to change the src attribute and the you can change the image.


问:
Undo in Python with a very large state. Is it possible?
This appears simple, but I can't find a good solution.

It's the old 'pass by reference'/ 'pass by value' / 'pass by object reference' problem. I understand what is happening, but I can't find a good work around.

I am aware of solutions for small problems, but my state is very large and extremely expensive to save/ recalculate. Given these constraints, I can't find a solution.

Here is some simple pseudocode to illustrate what I would like to do (if Python would let me pass by reference):

```<code>class A:
    def __init__(self,x):
        self.g=x
        self.changes=[]
    def change_something(self,what,new): # I want to pass 'what' by reference
        old=what # and then de-reference it here to read the value
        self.changes.append([what,old]) # store a reference
        what=new # dereference and change the value
    def undo_changes():
        for c in self.changes:
            c[0]=c[1] # dereference and restore old value
</code>```

Edit: Adding some more pseudocode to show how I would like the use the above

```<code>test=A(1) # initialise test.g as 1

print(test.g)
out: 1

test.change_something(test.g,2)
# if my imaginary code above functioned as described in its comments,
# this would change test.g to 2 and store the old value in the list of changes

print(test.g)
out: 2

test.undo_changes()

print(test.g)
out: 1
</code>```

Obviously the above code doesnt work in python due to being 'pass by object reference'. Also I'd like to be able to undo a single change, not just all of them as in the code above.

The thing is... I can't seem to find a good work around. There are solutions out there like these:

Do/Undo using command pattern in Python

making undo in python

Which involve storing a stack of commands. 'Undo' then involves removing the last command and then re-building the final state by taking the initial state and re-applying everything but the last command. My state is too large for this to be feasible, the issues are:

The state is very large. Saving it entirely is prohibitively expensive.

'Do' operations are costly (making recalculating from a saved state infeasible).

Do operations are also non-deterministic, relying on random input.

Undo operations are very frequent

I have one idea, which is to ensure that EVERYTHING is stored in lists, and writing my code so that everything is stored, read from and written to these lists. Then in the code above I can pass the list name and list index every time I want to read/write a variable.

Essentially this amounts to building my own memory architecture and C-style pointer system within Python!
This works, but seems a little... ridiculous? Surely there is a better way?

答:
Okay so I have come up with an answer... but it's ugly! I doubt it's the best solution. It uses exec() which I am told is bad practice and to be avoided if at all possible. EDIT: see below!

Old code using exec():

```<code>class A:
    def __init__(self,x):
        self.old=0
        self.g=x
        self.h=x*10
        self.changes=[]
    def change_something(self,what,new):
        whatstr='self.'+what
        exec('self.old='+whatstr)
        self.changes.append([what,self.old])
        exec(whatstr+'=new')
    def undo_changes(self):
        for c in self.changes:
            exec('self.'+c[0]+'=c[1]')
    def undo_last_change(self):
        c = self.changes[-1]
        exec('self.'+c[0]+'=c[1]')
        self.changes.pop()
</code>```

Thanks to barny, here's a much nicer version using getattr and setattr:

```<code>class A:
    def __init__(self,x):
        self.g=x
        self.h=x*10
        self.changes=[]
    def change_something(self,what,new):
        self.changes.append([what,getattr(self,what)])
        setattr(self,what,new)
    def undo_changes(self):
        for c in self.changes:
            setattr(self,c[0],c[1])
    def undo_last_change(self):
        c = self.changes[-1]
        setattr(self,c[0],c[1])
        self.changes.pop()
</code>```

To demonstrate, the input:

```<code>print("demonstrate changing one value")
b=A(1)
print('g=',b.g)
b.change_something('g',2)
print('g=',b.g)
b.undo_changes()
print('g=',b.g)

print("\ndemonstrate changing two values and undoing both")
b.change_something('h',3)
b.change_something('g',4)
print('g=', b.g, 'h=',b.h)
b.undo_changes()
print('g=', b.g, 'h=',b.h)

print("\ndemonstrate changing two values and undoing one")
b.change_something('h',30)
b.change_something('g',40)
print('g=', b.g, 'h=',b.h)
b.undo_last_change()
print('g=', b.g, 'h=',b.h)
</code>```

returns:

```<code>demonstrate changing one value
g= 1
g= 2
g= 1

demonstrate changing two values and undoing both
g= 4 h= 3
g= 1 h= 10

demonstrate changing two values and undoing one
g= 40 h= 30
g= 1 h= 30
</code>```

EDIT 2: Actually... after further testing, my initial version with exec() has some advantages over the second. If the class contains a second class, or list, or whatever, the exec() version has no trouble updating a list within a class within a class, however the second version will fail.

Body:
This appears simple, but I can't find a good solution.

It's the old 'pass by reference'/ 'pass by value' / 'pass by object reference' problem. I understand what is happening, but I can't find a good work around.

I am aware of solutions for small problems, but my state is very large and extremely expensive to save/ recalculate. Given these constraints, I can't find a solution.

Here is some simple pseudocode to illustrate what I would like to do (if Python would let me pass by reference):

class A:
    def __init__(self,x):
        self.g=x
        self.changes=[]
    def change_something(self,what,new): # I want to pass 'what' by reference
        old=what # and then de-reference it here to read the value
        self.changes.append([what,old]) # store a reference
        what=new # dereference and change the value
    def undo_changes():
        for c in self.changes:
            c[0]=c[1] # dereference and restore old value

Edit: Adding some more pseudocode to show how I would like the use the above

test=A(1) # initialise test.g as 1

print(test.g)
out: 1

test.change_something(test.g,2)
# if my imaginary code above functioned as described in its comments,
# this would change test.g to 2 and store the old value in the list of changes

print(test.g)
out: 2

test.undo_changes()

print(test.g)
out: 1

Obviously the above code doesnt work in python due to being 'pass by object reference'. Also I'd like to be able to undo a single change, not just all of them as in the code above.

The thing is... I can't seem to find a good work around. There are solutions out there like these:

Do/Undo using command pattern in Python

making undo in python

Which involve storing a stack of commands. 'Undo' then involves removing the last command and then re-building the final state by taking the initial state and re-applying everything but the last command. My state is too large for this to be feasible, the issues are:

The state is very large. Saving it entirely is prohibitively expensive.

'Do' operations are costly (making recalculating from a saved state infeasible).

Do operations are also non-deterministic, relying on random input.

Undo operations are very frequent

I have one idea, which is to ensure that EVERYTHING is stored in lists, and writing my code so that everything is stored, read from and written to these lists. Then in the code above I can pass the list name and list index every time I want to read/write a variable.

Essentially this amounts to building my own memory architecture and C-style pointer system within Python!
This works, but seems a little... ridiculous? Surely there is a better way?

Body:
Okay so I have come up with an answer... but it's ugly! I doubt it's the best solution. It uses exec() which I am told is bad practice and to be avoided if at all possible. EDIT: see below!

Old code using exec():

class A:
    def __init__(self,x):
        self.old=0
        self.g=x
        self.h=x*10
        self.changes=[]
    def change_something(self,what,new):
        whatstr='self.'+what
        exec('self.old='+whatstr)
        self.changes.append([what,self.old])
        exec(whatstr+'=new')
    def undo_changes(self):
        for c in self.changes:
            exec('self.'+c[0]+'=c[1]')
    def undo_last_change(self):
        c = self.changes[-1]
        exec('self.'+c[0]+'=c[1]')
        self.changes.pop()

Thanks to barny, here's a much nicer version using getattr and setattr:

class A:
    def __init__(self,x):
        self.g=x
        self.h=x*10
        self.changes=[]
    def change_something(self,what,new):
        self.changes.append([what,getattr(self,what)])
        setattr(self,what,new)
    def undo_changes(self):
        for c in self.changes:
            setattr(self,c[0],c[1])
    def undo_last_change(self):
        c = self.changes[-1]
        setattr(self,c[0],c[1])
        self.changes.pop()

To demonstrate, the input:

print("demonstrate changing one value")
b=A(1)
print('g=',b.g)
b.change_something('g',2)
print('g=',b.g)
b.undo_changes()
print('g=',b.g)

print("\ndemonstrate changing two values and undoing both")
b.change_something('h',3)
b.change_something('g',4)
print('g=', b.g, 'h=',b.h)
b.undo_changes()
print('g=', b.g, 'h=',b.h)

print("\ndemonstrate changing two values and undoing one")
b.change_something('h',30)
b.change_something('g',40)
print('g=', b.g, 'h=',b.h)
b.undo_last_change()
print('g=', b.g, 'h=',b.h)

returns:

demonstrate changing one value
g= 1
g= 2
g= 1

demonstrate changing two values and undoing both
g= 4 h= 3
g= 1 h= 10

demonstrate changing two values and undoing one
g= 40 h= 30
g= 1 h= 30

EDIT 2: Actually... after further testing, my initial version with exec() has some advantages over the second. If the class contains a second class, or list, or whatever, the exec() version has no trouble updating a list within a class within a class, however the second version will fail.


问:
How to transfer paramenters to Partial View in ASP.NET MVC?
On the Details view I want to display a grid from other table. How to implement it better? I'm trying to do it in a such a way (error: Cannot implicitly convert type 'void' to 'object'):

```<code><%= Html.RenderPartial("~/Views/Appartament/Index.ascx", new { id  = Model.blockhouse_id })%>
</code>```

Here is the code from details view:

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<testMVC.Models.Blockhouse>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Details</h2>

        <p>
            blockhouse_id:
            <%= Html.Encode(Model.blockhouse_id) %>
        </p>
        <p>
            name:
            <%= Html.Encode(Model.name) %>
        </p>

         <p>
            Appartaments:
            <%= Html.RenderPartial("~/Views/Appartament/Index.ascx", new { id  = Model.blockhouse_id })%>
        </p>

</asp:Content>
</code>```

And the code of the Index.ascx controller:

```<code>public ActionResult Index(int blockhouse_id)
        {
            var _appartament = apt.GetBlockAppartaments(blockhouse_id).ToList();
            return View("Index", _appartament);
        }
</code>```

答:
RenderPartial doesn't have a return value.

Instead of

```<code><%= %>
</code>```

Use

```<code><% %>
</code>```

ASP.NET MVC RenderPartial Compiler Error

As for Razor, instead of

```<code>@
</code>```

Use

```<code>@{ }
</code>```

Body:
On the Details view I want to display a grid from other table. How to implement it better? I'm trying to do it in a such a way (error: Cannot implicitly convert type 'void' to 'object'):

<%= Html.RenderPartial("~/Views/Appartament/Index.ascx", new { id  = Model.blockhouse_id })%>

Here is the code from details view:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<testMVC.Models.Blockhouse>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Details

            blockhouse_id:
            <%= Html.Encode(Model.blockhouse_id) %>

            name:
            <%= Html.Encode(Model.name) %>

            Appartaments:
            <%= Html.RenderPartial("~/Views/Appartament/Index.ascx", new { id  = Model.blockhouse_id })%>

</asp:Content>

And the code of the Index.ascx controller:

public ActionResult Index(int blockhouse_id)
        {
            var _appartament = apt.GetBlockAppartaments(blockhouse_id).ToList();
            return View("Index", _appartament);
        }

Body:
RenderPartial doesn't have a return value.

Instead of

<%= %>

Use

<% %>

ASP.NET MVC RenderPartial Compiler Error

As for Razor, instead of

@

Use

@{ }


问:
What is Lineage In Spark?
How lineage helps to recompute data?

For example, I'm having several nodes computing data for 30 minutes each. If one fails after 15 minutes, can we recompute data processed in 15 minutes again using lineage without giving 15 minutes again?

答:
When a transformation (map or filter etc.) is called, it is not executed by Spark immediately, instead a lineage is created for each transformation. A lineage will keep track of what all transformations has to be applied on that RDD, including the location from where it has to read the data.

For example, consider the following example

```<code>val myRdd = sc.textFile("spam.txt")
val filteredRdd = myRdd.filter(line => line.contains("wonder"))
filteredRdd.count()
</code>```

sc.textFile() and myRdd.filter() do not get executed immediately, it will be executed only when an Action is called on the RDD - here filteredRdd.count().

An Action is used to either save result to some location or to display it. RDD lineage information can also be printed by using the command filteredRdd.toDebugString (filteredRdd is the RDD here). Also, DAG Visualization shows the complete graph in a very intuitive manner as follows:

Title: What is Lineage In Spark?

Body:
When a transformation (map or filter etc.) is called, it is not executed by Spark immediately, instead a lineage is created for each transformation. A lineage will keep track of what all transformations has to be applied on that RDD, including the location from where it has to read the data.

For example, consider the following example

val myRdd = sc.textFile("spam.txt")
val filteredRdd = myRdd.filter(line => line.contains("wonder"))
filteredRdd.count()

sc.textFile() and myRdd.filter() do not get executed immediately, it will be executed only when an Action is called on the RDD - here filteredRdd.count().

An Action is used to either save result to some location or to display it. RDD lineage information can also be printed by using the command filteredRdd.toDebugString (filteredRdd is the RDD here). Also, DAG Visualization shows the complete graph in a very intuitive manner as follows: