问:
Same prediction for each inference
I saved a tensorflow model using tf.saved_model.builder.SavedModelBuilder.
However, when I try to make predictions in java, in most of the time it returns the same results (for fc8 (alexnet) the layer before softmax) in some cases, it produces some real different results and it's most likely to be correct, so from that, I assume that the training is OK.
Did anyone else experienced this? Does anyone have an idea what's wrong?

my Java implementation:

```<code>Tensor image = constructAndExecuteGraphToNormalizeImage(imageBytes);
Tensor result = s.runner().feed("input_tensor", image).feed("Placeholder_1",t).fetch("fc8/fc8").run().get(0);

private static Tensor constructAndExecuteGraphToNormalizeImage(byte[] imageBytes) {
    try (Graph g = new Graph()) {
        TF.GraphBuilder b = new TF.GraphBuilder(g);
        // Some constants specific to the pre-trained model at:
        // https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
        //
        // - The model was trained with images scaled to 224x224 pixels.
        // - The colors, represented as R, G, B in 1-byte each were converted to
        //   float using (value - Mean)/Scale.
        final int H = 227;
        final int W = 227;
        final float mean = 117f;
        final float scale = 1f;

        // Since the graph is being constructed once per execution here, we can use a constant for the
        // input image. If the graph were to be re-used for multiple input images, a placeholder would
        // have been more appropriate.
        final Output input = b.constant("input", imageBytes);
        final Output output =
                b.div(
                        b.sub(
                                b.resizeBilinear(
                                        b.expandDims(
                                                b.cast(b.decodeJpeg(input, 3), DataType.FLOAT),
                                                b.constant("make_batch", 0)),
                                        b.constant("size", new int[] {H, W})),
                                b.constant("mean", mean)),
                        b.constant("scale", scale));
        try (Session s = new Session(g)) {
            return s.runner().fetch(output.op().name()).run().get(0);
        }
    }
}
</code>```

答:
I am assuming that there is no random operation left in your graph, such as dropout. (Seems to be the case, since you often get the same results).

Alas, some operations in tensorflow seem to be non-deterministic, such as reductions and convolutions. We have to live with the fact that tensorflow's nets are stochastic beasts: their performance can be approached statistically but their outputs are non-deterministic.

(I believe some other frameworks such as Theano go farther than tensorflow in proposing deterministic operations.)

Title: Same prediction for each inference

Body:
I saved a tensorflow model using tf.saved_model.builder.SavedModelBuilder.
However, when I try to make predictions in java, in most of the time it returns the same results (for fc8 (alexnet) the layer before softmax) in some cases, it produces some real different results and it's most likely to be correct, so from that, I assume that the training is OK.
Did anyone else experienced this? Does anyone have an idea what's wrong?

my Java implementation:

Tensor image = constructAndExecuteGraphToNormalizeImage(imageBytes);
Tensor result = s.runner().feed("input_tensor", image).feed("Placeholder_1",t).fetch("fc8/fc8").run().get(0);

private static Tensor constructAndExecuteGraphToNormalizeImage(byte[] imageBytes) {
    try (Graph g = new Graph()) {
        TF.GraphBuilder b = new TF.GraphBuilder(g);
        // Some constants specific to the pre-trained model at:
        // https://storage.googleapis.com/download.tensorflow.org/models/inception5h.zip
        //
        // - The model was trained with images scaled to 224x224 pixels.
        // - The colors, represented as R, G, B in 1-byte each were converted to
        //   float using (value - Mean)/Scale.
        final int H = 227;
        final int W = 227;
        final float mean = 117f;
        final float scale = 1f;

        // Since the graph is being constructed once per execution here, we can use a constant for the
        // input image. If the graph were to be re-used for multiple input images, a placeholder would
        // have been more appropriate.
        final Output input = b.constant("input", imageBytes);
        final Output output =
                b.div(
                        b.sub(
                                b.resizeBilinear(
                                        b.expandDims(
                                                b.cast(b.decodeJpeg(input, 3), DataType.FLOAT),
                                                b.constant("make_batch", 0)),
                                        b.constant("size", new int[] {H, W})),
                                b.constant("mean", mean)),
                        b.constant("scale", scale));
        try (Session s = new Session(g)) {
            return s.runner().fetch(output.op().name()).run().get(0);
        }
    }
}


来源: stackexchange

问:
JSSOR AUTO PLAY VIDEO
I have recently installed Jssor slider on my company website ena electronics and im trying to add an autoplay video onto the site.

Using the below code I can get it to play in a webpage but when put into the slider in a div it doesn't work... Am I missing something?

thanks

```<code><video width="320" height="240" controls autoplay>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>
</code>```

答:
For anyone wondering, i managed to get it going with this:</p>

```<code> <!-- #region Jssor Slider Begin -->
        <!-- Generator: Jssor Slider Maker -->
        <!-- Source: http://www.jssor.com -->
        <!-- This code works without jquery library. -->
        <script src="/src/slider/jssor.slider-22.1.8.min.js" type="text/javascript"></script>
        <script>
            jssor_1_slider_init = function () {
                var options = {
                    $AutoPlay: 1,
                    $Idle: 2000,
                    $SlideDuration: 800,
                      $SlideEasing: $Jease$.$OutQuint,
                      $ArrowNavigatorOptions: {
                        $Class: $JssorArrowNavigator$
                      },
                      $BulletNavigatorOptions: {
                        $Class: $JssorBulletNavigator$
                      }
                };

                var jssor_1_slider = new $JssorSlider$('jssor_1', options);

                function SliderParkEventHandler(slideIndex, fromIndex)
                {
                    if(slideIndex == 0)
                    {
                        var video = document.getElementById("myvideo");
                       var button = document.getElementById("play");
                       if (video.paused) {
                          video.play();
                          button.textContent = "||";
                       }
                    }
                }

                jssor_1_slider.$On($JssorSlider$.$EVT_PARK,SliderParkEventHandler);

                /*responsive code begin*/
                /*you can remove responsive code if you don't want the slider scales while window resizing*/
                function ScaleSlider() {
                    var refSize = jssor_1_slider.$Elmt.parentNode.clientWidth;
                    if (refSize) {
                        refSize = Math.min(refSize, 1920);
                        jssor_1_slider.$ScaleWidth(refSize);
                    }
                    else {
                        window.setTimeout(ScaleSlider, 30);
                    }
                }
                ScaleSlider();
                $Jssor$.$AddEvent(window, "load", ScaleSlider);
                $Jssor$.$AddEvent(window, "resize", ScaleSlider);
                $Jssor$.$AddEvent(window, "orientationchange", ScaleSlider);
                /*responsive code end*/
            };
        </script>
        <link rel="stylesheet" href="/src/slider/slider.css" type="text/css"/>

    <div id="jssor_1" style="position: relative; top: 0px; left: 0px; width: 1428px;
        height: 305px;">
        <!-- Loading Screen -->
                <div data-u="loading" style="position: absolute; top: 0px; left: 0px;">
                    <div style="filter: alpha(opacity=70); opacity: 0.7; position: absolute; display: block; top: 0px; left: 0px; width: 100%; height: 100%;"></div>
                    <div style="position:absolute;display:block;background:url('/img/loading.gif') no-repeat center center;top:0px;left:0px;width:100%;height:100%;"></div>
                </div>
        <!-- Slides Container -->
        <div u="slides" style="position: absolute; left: 0px; top: 0px; width: 1428px; height: 305px; overflow: hidden;">
                <div data-idle="15000">
                        <div>
                        <!-- assuming that you placed video in the second slide -->
                        <video id="myvideo" width="1428" height="305" autoplay>
                            <source src="../src/video/products.mp4" type="video/mp4">
                            Your browser does not support the video tag.
                        </video>
                </div>
                    <div>
                        <img data-u="image" src="/img/home/logo.png" alt="Logo"/>
                    </div>
                </div>
                <!-- Bullet Navigator -->
                <div data-u="navigator" class="jssorb05" style="bottom:16px;right:16px;" data-autocenter="1">
                    <!-- bullet navigator item prototype -->
                    <div data-u="prototype" style="width:16px;height:16px;"></div>
                </div>
                <!-- Arrow Navigator -->
                <span data-u="arrowleft" class="jssora22l" style="top:0px;left:8px;width:40px;height:58px;" data-autocenter="2"></span>
                <span data-u="arrowright" class="jssora22r" style="top:0px;right:8px;width:40px;height:58px;" data-autocenter="2"></span>
            </div>
        <!-- Trigger -->
        <script>
            jssor_1_slider_init();
        </script>
    <!-- Jssor Slider End -->
</code>```

ContentLicense: CC BY-SA 3.0

Title: JSSOR AUTO PLAY VIDEO

Body:
I have recently installed Jssor slider on my company website ena electronics and im trying to add an autoplay video onto the site.

Using the below code I can get it to play in a webpage but when put into the slider in a div it doesn't work... Am I missing something?

thanks

<video width="320" height="240" controls autoplay>
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.
</video>

Body:
For anyone wondering, i managed to get it going with this:

 <!-- #region Jssor Slider Begin -->
        <!-- Generator: Jssor Slider Maker -->
        <!-- Source: http://www.jssor.com -->
        <!-- This code works without jquery library. -->
        <script src="/src/slider/jssor.slider-22.1.8.min.js" type="text/javascript"></script>
        <script>
            jssor_1_slider_init = function () {
                var options = {
                    $AutoPlay: 1,
                    $Idle: 2000,
                    $SlideDuration: 800,
                      $SlideEasing: $Jease$.$OutQuint,
                      $ArrowNavigatorOptions: {
                        $Class: $JssorArrowNavigator$
                      },
                      $BulletNavigatorOptions: {
                        $Class: $JssorBulletNavigator$
                      }
                };

                var jssor_1_slider = new $JssorSlider$('jssor_1', options);

                function SliderParkEventHandler(slideIndex, fromIndex)
                {
                    if(slideIndex == 0)
                    {
                        var video = document.getElementById("myvideo");
                       var button = document.getElementById("play");
                       if (video.paused) {
                          video.play();
                          button.textContent = "||";
                       }
                    }
                }

                jssor_1_slider.$On($JssorSlider$.$EVT_PARK,SliderParkEventHandler);

                /*responsive code begin*/
                /*you can remove responsive code if you don't want the slider scales while window resizing*/
                function ScaleSlider() {
                    var refSize = jssor_1_slider.$Elmt.parentNode.clientWidth;
                    if (refSize) {
                        refSize = Math.min(refSize, 1920);
                        jssor_1_slider.$ScaleWidth(refSize);
                    }
                    else {
                        window.setTimeout(ScaleSlider, 30);
                    }
                }
                ScaleSlider();
                $Jssor$.$AddEvent(window, "load", ScaleSlider);
                $Jssor$.$AddEvent(window, "resize", ScaleSlider);
                $Jssor$.$AddEvent(window, "orientationchange", ScaleSlider);
                /*responsive code end*/
            };
        </script>
        <link rel="stylesheet" href="/src/slider/slider.css" type="text/css"/>

    <div id="jssor_1" style="position: relative; top: 0px; left: 0px; width: 1428px;
        height: 305px;">
        <!-- Loading Screen -->
                <div data-u="loading" style="position: absolute; top: 0px; left: 0px;">
                    <div style="filter: alpha(opacity=70); opacity: 0.7; position: absolute; display: block; top: 0px; left: 0px; width: 100%; height: 100%;"></div>
                    <div style="position:absolute;display:block;background:url('/img/loading.gif') no-repeat center center;top:0px;left:0px;width:100%;height:100%;"></div>
                </div>
        <!-- Slides Container -->
        <div u="slides" style="position: absolute; left: 0px; top: 0px; width: 1428px; height: 305px; overflow: hidden;">
                <div data-idle="15000">
                        <div>
                        <!-- assuming that you placed video in the second slide -->
                        <video id="myvideo" width="1428" height="305" autoplay>
                            <source src="../src/video/products.mp4" type="video/mp4">
                            Your browser does not support the video tag.
                        </video>
                </div>
                    <div>
                        <img data-u="image" src="/img/home/logo.png" alt="Logo"/>
                    </div>
                </div>
                <!-- Bullet Navigator -->
                <div data-u="navigator" class="jssorb05" style="bottom:16px;right:16px;" data-autocenter="1">
                    <!-- bullet navigator item prototype -->
                    <div data-u="prototype" style="width:16px;height:16px;"></div>
                </div>
                <!-- Arrow Navigator -->
                <span data-u="arrowleft" class="jssora22l" style="top:0px;left:8px;width:40px;height:58px;" data-autocenter="2"></span>
                <span data-u="arrowright" class="jssora22r" style="top:0px;right:8px;width:40px;height:58px;" data-autocenter="2"></span>
            </div>
        <!-- Trigger -->
        <script>
            jssor_1_slider_init();
        </script>
    <!-- Jssor Slider End -->


问:
SimpleExoPlayerView Visibility
I have created a app with recycleView listLayout ,which upon clicking a item will lead to a activity with SimpleExoPlayerView and textView.I want to hide SimpleExoPlayerView if there is no videoURL available(I am getting videoURL from JSON file.So there some list items with no videoURL.)

```<code>if (videoUrl == "") {
    playerView.setVisibility(View.INVISIBLE);
}
</code>```

But this is not working. Help me!

答:
```<code>if(TextUtils.isEmpty(videoUrl)) {
}
</code>```

I have updated my code as TextUtils.isEmpty() is preferred over String.equals("")

Title: SimpleExoPlayerView Visibility

Body:
I have created a app with recycleView listLayout ,which upon clicking a item will lead to a activity with SimpleExoPlayerView and textView.I want to hide SimpleExoPlayerView if there is no videoURL available(I am getting videoURL from JSON file.So there some list items with no videoURL.)

if (videoUrl == "") {
    playerView.setVisibility(View.INVISIBLE);
}

But this is not working. Help me!

Body:
if(TextUtils.isEmpty(videoUrl)) {
}

I have updated my code as TextUtils.isEmpty() is preferred over String.equals("")

ContentLicense: CC BY-SA 4.0


问:
Change Git Username to Connect to My Remote Repo
I worked a contract gig recently with a temporary email address and username for git repos. It's over now and the temp username seems to be messing up my old personal repositories in git.

When I try to push origin master

I get:

```<code>remote: Permission to <my-repo>.git denied to <wrong-username>.
</code>```

If I look in git config --list I get the proper username and email - I can't seem to find the location of [wrong-username] and I can't get rid of it. How do I connect back to my remote repository and get rid of this old username that I won't be using in the future?

答:
Did you try the global setup?</p>

```<code>$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com
</code>```

Body:
I worked a contract gig recently with a temporary email address and username for git repos. It's over now and the temp username seems to be messing up my old personal repositories in git.

When I try to push origin master

I get:

remote: Permission to <my-repo>.git denied to <wrong-username>.

If I look in git config --list I get the proper username and email - I can't seem to find the location of [wrong-username] and I can't get rid of it. How do I connect back to my remote repository and get rid of this old username that I won't be using in the future?

Body:
Did you try the global setup?

$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com


问:
Mocha/Chai issue with http get request
i'm having trouble with http response in chai tests, i don't know how can i get the length of the res.body unless by console.log.

it's the test i'm trying to run:

```<code>it('It should have a length of 3061', function(){

        chai.request('http://localhost:8080')
        .get('/api/pac/')
        .end(function(err,res){

            console.log(res.body.length); //it shows 3061
            expect(res.body).to.have.lengthOf(3061); //it causes error "Cannot read property 'body' of undefined"

        });
    });
</code>```

if i try to do an expect with res.body, it returns "Cannot read property 'body' of undefined". But a console.log works.

A console.log(res.body) shows a json with 3061 objects. Each Object have this structure:

```<code>iid : {type : Number},

dnas : [{ _id : Number,
        col : Date,
        reproved : {type : Boolean},
        wave : {type: Number,
                index: true}
        }],
name : { type : String,
       uppercase: true,
       index: true}
</code>```

答:
How about:

```<code>expect(res.body.length).to.equal(3061);
</code>```

Can remember if it's .equal or .be but one of those should work.

Title: Mocha/Chai issue with http get request

Body:
i'm having trouble with http response in chai tests, i don't know how can i get the length of the res.body unless by console.log.

it's the test i'm trying to run:

it('It should have a length of 3061', function(){

        chai.request('http://localhost:8080')
        .get('/api/pac/')
        .end(function(err,res){

            console.log(res.body.length); //it shows 3061
            expect(res.body).to.have.lengthOf(3061); //it causes error "Cannot read property 'body' of undefined"

        });
    });

if i try to do an expect with res.body, it returns "Cannot read property 'body' of undefined". But a console.log works.

A console.log(res.body) shows a json with 3061 objects. Each Object have this structure:

iid : {type : Number},

dnas : [{ _id : Number,
        col : Date,
        reproved : {type : Boolean},
        wave : {type: Number,
                index: true}
        }],
name : { type : String,
       uppercase: true,
       index: true}

Body:
How about:

expect(res.body.length).to.equal(3061);

Can remember if it's .equal or .be but one of those should work.


问:
LCM And GCD in C using recursion or normal method
While trying to do the GCD and LCM program from programming simplified...I am facing problems with the results. I did everything correct(according to me) and even checked word by word but the problem still persists...I am pasting the code of normal method only.</p>
```<code>#include <stdio.h>

int main()
{
    int a, b, x, y, t, gcd, lcm;

    printf("Enter first number :");
    scanf("%d", &a);
    printf("Enter first number :");
    scanf("%d", &b);

    a = x;
    b = y;

    while (b != 0)
    {
        t = b;
        b = a % b;
        a = t;
    }

    gcd = a;
    lcm = (x * y)/gcd;

    printf("Greatest common divisior of %d and %d = %d\n", x, y, gcd);
    printf("Lowest common divisior of %d and %d = %d\n", x, y, lcm);

    getch();
}
</code>```

答:
Try it</p>

```<code>#include<stdio.h>
int main(){
int a,b,lcm,gcd;
printf("enter two value:\n");
scanf("%d%d",&a,&b);
gcd=GCD(a,b);
lcm=LCM(a,b);
printf("LCM=%d and GCD=%d",lcm,gcd);
return 0;
}
int GCD(int a, int b){

while(a!=b){
    if(a>b){
        a=a-b;
    }else{
    b=b-a;
    }
    }
  return a;
}
int LCM(int a, int b){
return (a*b)/GCD(a,b);
}
</code>```

Body:
While trying to do the GCD and LCM program from programming simplified...I am facing problems with the results. I did everything correct(according to me) and even checked word by word but the problem still persists...I am pasting the code of normal method only.

#include <stdio.h>

int main()
{
    int a, b, x, y, t, gcd, lcm;

    printf("Enter first number :");
    scanf("%d", &a);
    printf("Enter first number :");
    scanf("%d", &b);

    a = x;
    b = y;

    while (b != 0)
    {
        t = b;
        b = a % b;
        a = t;
    }

    gcd = a;
    lcm = (x * y)/gcd;

    printf("Greatest common divisior of %d and %d = %d\n", x, y, gcd);
    printf("Lowest common divisior of %d and %d = %d\n", x, y, lcm);

    getch();
}

Body:
Try it

#include<stdio.h>
int main(){
int a,b,lcm,gcd;
printf("enter two value:\n");
scanf("%d%d",&a,&b);
gcd=GCD(a,b);
lcm=LCM(a,b);
printf("LCM=%d and GCD=%d",lcm,gcd);
return 0;
}
int GCD(int a, int b){

while(a!=b){
    if(a>b){
        a=a-b;
    }else{
    b=b-a;
    }
    }
  return a;
}
int LCM(int a, int b){
return (a*b)/GCD(a,b);
}


问:
JSP displays blank data
I going crazy here trying to figure out, why my JSP doesn't display data in the table.Seems like servlet connects to MySQL and populates data, however I can not push that data to JSP.setAttribute() method is working(objects are there). I can't extract specific information and display it formatted form in the browser.If someone can point me out how troubleshoot this issue... Why JSTL expression doesn't load proper info.Eclipse doesn't return any errors and whole application compiles.... It's just displays empty page.Below you can find the code.

HINT: I was testing if LIST can be pushed and objects can be displayed.It worked, so objects are "visible" to JSP.When I try to load specific info (username, password or email) it returns blank. Thanks for any help/hints.

Below you can find the code.

UserBean.java

```<code>package com.admin;

public class UserBean {
    private String password;
    private String firstname;
    private String lastname;
    private String email;
    private String usertype;
    private String datecreated;
    private String username;

    public UserBean(){};

    public UserBean(String username2, String password2, String firstname2, String lastname2, String email2,
            String usertype2, String datecreated2) {
    }

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getUsertype() {
        return usertype;
    }
    public void setUsertype(String usertype) {
        this.usertype = usertype;
    }
    public String getDatecreated() {
        return datecreated;
    }
    public void setDatecreated(String datecreated) {
        this.datecreated = datecreated;
    }

}
</code>```

User.DAO.java

```<code>package com.admin;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.clientdb.ConnectionManager;

public class UserDAO {

    public static List<UserBean> listOfUsers()
    {
        List<UserBean> userList=new ArrayList<>();
        String query="SELECT * FROM users";

        try
        {
            Connection conn = ConnectionManager.getConnection();
            Statement stm = conn.createStatement();
            ResultSet rs = stm.executeQuery(query);

            while(rs.next())
            {
                String username=rs.getString("username");
                String password=rs.getString("password");
                String firstname=rs.getString("firstname");
                String lastname=rs.getString("lastname");
                String email=rs.getString("email");
                String usertype=rs.getString("usertype");
                String datecreated=rs.getString("date_created");

                UserBean user=new UserBean(username,password,firstname,lastname,email,usertype,datecreated);
                userList.add(user);
            }
            stm.close();
            rs.close();
            conn.close();
        }
        catch(Exception ex){System.out.println(ex);}

        return userList;

}}
</code>```

UserAdmin.java

```<code>package com.admin;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserAdmin extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            List<UserBean> userList = UserDAO.listOfUsers();
            request.getSession().setAttribute("userList",userList);
    request.getRequestDispatcher("userlist.jsp").forward(request,response);
        }
}
</code>```

userlist.jsp

```<code>    <table class="table table-hover"  style="margin-top:20px;">
  <thead>
    <tr>
      <th>Username</th>
      <th>Password</th>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th>User Type</th>
      <th>Date Created</th>
    </tr>
  </thead>
  <tbody>
  <c:forEach items="${userList}" var="user">
    <tr>
      <td><c:out value="${user.username}"/></td>
      <td><c:out value="${user.password}"/></td>
      <td><c:out value="${user.firstname}"/></td>
      <td><c:out value="${user.lastname}"/></td>
      <td><c:out value="${user.email}"/></td>
      <td><c:out value="${user.usertype}"/></td>
      <td><c:out value="${user.datecreated}"/></td>
      <td>
        <a href="reset.html" role="button" class="btn btn-primary">RESET</a>
        <!--  <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#userDeleteModal">DELETE</button>-->
        <a href="deleteUser.do?email=${user.email}" role="button" class="btn btn-danger">DELETE</a>
      </td>
    </tr>
  </c:forEach>
  </tbody>
</table>
</code>```

答:
Try this:  </p>

```<code> <c:forEach items="${sessionScope.userList}" var="user">
        <tr>
          <td><c:out value="${user.username}"/></td>
          <td><c:out value="${user.password}"/></td>
          <td><c:out value="${user.firstname}"/></td>
          <td><c:out value="${user.lastname}"/></td>
          <td><c:out value="${user.email}"/></td>
          <td><c:out value="${user.usertype}"/></td>
          <td><c:out value="${user.datecreated}"/></td>
          <td>
            <a href="reset.html" role="button" class="btn btn-primary">RESET</a>
            <!--  <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#userDeleteModal">DELETE</button>-->
            <a href="deleteUser.do?email=${user.email}" role="button" class="btn btn-danger">DELETE</a>
          </td>
        </tr>
 </c:forEach>
</code>```

Title: JSP displays blank data

Body:
I going crazy here trying to figure out, why my JSP doesn't display data in the table.Seems like servlet connects to MySQL and populates data, however I can not push that data to JSP.setAttribute() method is working(objects are there). I can't extract specific information and display it formatted form in the browser.If someone can point me out how troubleshoot this issue... Why JSTL expression doesn't load proper info.Eclipse doesn't return any errors and whole application compiles.... It's just displays empty page.Below you can find the code.

HINT: I was testing if LIST can be pushed and objects can be displayed.It worked, so objects are "visible" to JSP.When I try to load specific info (username, password or email) it returns blank. Thanks for any help/hints.

Below you can find the code.

UserBean.java

package com.admin;

public class UserBean {
    private String password;
    private String firstname;
    private String lastname;
    private String email;
    private String usertype;
    private String datecreated;
    private String username;

    public UserBean(){};

    public UserBean(String username2, String password2, String firstname2, String lastname2, String email2,
            String usertype2, String datecreated2) {
    }

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getUsertype() {
        return usertype;
    }
    public void setUsertype(String usertype) {
        this.usertype = usertype;
    }
    public String getDatecreated() {
        return datecreated;
    }
    public void setDatecreated(String datecreated) {
        this.datecreated = datecreated;
    }

}

User.DAO.java

package com.admin;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.clientdb.ConnectionManager;

public class UserDAO {

    public static List<UserBean> listOfUsers()
    {
        List<UserBean> userList=new ArrayList<>();
        String query="SELECT * FROM users";

        try
        {
            Connection conn = ConnectionManager.getConnection();
            Statement stm = conn.createStatement();
            ResultSet rs = stm.executeQuery(query);

            while(rs.next())
            {
                String username=rs.getString("username");
                String password=rs.getString("password");
                String firstname=rs.getString("firstname");
                String lastname=rs.getString("lastname");
                String email=rs.getString("email");
                String usertype=rs.getString("usertype");
                String datecreated=rs.getString("date_created");

                UserBean user=new UserBean(username,password,firstname,lastname,email,usertype,datecreated);
                userList.add(user);
            }
            stm.close();
            rs.close();
            conn.close();
        }
        catch(Exception ex){System.out.println(ex);}

        return userList;

}}

UserAdmin.java

package com.admin;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserAdmin extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            List<UserBean> userList = UserDAO.listOfUsers();
            request.getSession().setAttribute("userList",userList);
    request.getRequestDispatcher("userlist.jsp").forward(request,response);
        }
}

userlist.jsp

      Username
      Password
      First Name
      Last Name
      Email
      User Type
      Date Created

  <c:forEach items="${userList}" var="user">

      <c:out value="${user.username}"/>
      <c:out value="${user.password}"/>
      <c:out value="${user.firstname}"/>
      <c:out value="${user.lastname}"/>
      <c:out value="${user.email}"/>
      <c:out value="${user.usertype}"/>
      <c:out value="${user.datecreated}"/>

        RESET

        DELETE

  </c:forEach>

Body:
Try this:

 <c:forEach items="${sessionScope.userList}" var="user">
        <tr>
          <td><c:out value="${user.username}"/></td>
          <td><c:out value="${user.password}"/></td>
          <td><c:out value="${user.firstname}"/></td>
          <td><c:out value="${user.lastname}"/></td>
          <td><c:out value="${user.email}"/></td>
          <td><c:out value="${user.usertype}"/></td>
          <td><c:out value="${user.datecreated}"/></td>
          <td>
            <a href="reset.html" role="button" class="btn btn-primary">RESET</a>
            <!--  <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#userDeleteModal">DELETE</button>-->
            <a href="deleteUser.do?email=${user.email}" role="button" class="btn btn-danger">DELETE</a>
          </td>
        </tr>
 </c:forEach>


问:
How do I install django-ckeditor?
In Stack Overflow there's two questions about this editor, and nobody answers!!!

So I'm asking how to install this Django package to my project??
I've followed these steps already, have no errors, nothing, and still the form stays the same. Why??

Edit: heres model

```<code>from datetime import datetime

from django.db                import models
from django.utils.translation import ugettext_lazy as _, ugettext
from ckeditor.fields          import RichTextField

class Newsletter(models.Model):

    title = models.CharField(
        _(u'Title'),
        max_length=200,
        help_text=_(u'Newsletter title'),
        )

    body = RichTextField()

    date = models.DateField(
         _(u'Date'),
         help_text=_(u'Set date when this newsletter should be send')
    )

    class Meta:
        ordering = ['title',]
</code>```

forms.py

```<code>from models import Newsletter, Mail
class NewsletterForm(forms.ModelForm):
    class Meta:
       model = Newsletter
</code>```

view:

```<code>from newsletter.models import Newsletter, Mail
from newsletter.forms  import NewsletterForm, MailForm

def newsletters_add(request):
    form = NewsletterForm()
    tpl  = "form_newsletter.html"

    return render_to_response(tpl, RequestContext(request, {
        'form': form,
    }))
</code>```

All form outputed succesfully with {{ form }} tag

settings.py (of the project)

```<code>CKEDITOR_MEDIA_PREFIX  = "/media/ckeditor/"
CKEDITOR_UPLOAD_PATH   = "/www/vhosts/sender/media/newsletter/uploads/"
CKEDITOR_UPLOAD_PREFIX = "http://******/media/newsletter/uploads/"
CKEDITOR_RESTRICT_BY_USER = True

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'Basic',
    },
}

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'django.contrib.admin',
    #'tagging',
    'debug_toolbar',
    'ckeditor',
    'mailer',
    'newsletter'

)
</code>```

答: The media needed to display the widget correctly should be stored in the form's media object. You can output the tag for needed js in your template with {{ form.media }}. The admin should do this automatically, while in your custom views you have to do it yourself... See the django documentation on form media for more information!

Title: How do I install django-ckeditor?

Body:
In Stack Overflow there's two questions about this editor, and nobody answers!!!

So I'm asking how to install this Django package to my project??
I've followed these steps already, have no errors, nothing, and still the form stays the same. Why??

Edit: heres model

from datetime import datetime

from django.db                import models
from django.utils.translation import ugettext_lazy as _, ugettext
from ckeditor.fields          import RichTextField

class Newsletter(models.Model):

    title = models.CharField(
        _(u'Title'),
        max_length=200,
        help_text=_(u'Newsletter title'),
        )

    body = RichTextField()

    date = models.DateField(
         _(u'Date'),
         help_text=_(u'Set date when this newsletter should be send')
    )

    class Meta:
        ordering = ['title',]

forms.py

from models import Newsletter, Mail
class NewsletterForm(forms.ModelForm):
    class Meta:
       model = Newsletter

view:

from newsletter.models import Newsletter, Mail
from newsletter.forms  import NewsletterForm, MailForm

def newsletters_add(request):
    form = NewsletterForm()
    tpl  = "form_newsletter.html"

    return render_to_response(tpl, RequestContext(request, {
        'form': form,
    }))

All form outputed succesfully with {{ form }} tag

settings.py (of the project)

CKEDITOR_MEDIA_PREFIX  = "/media/ckeditor/"
CKEDITOR_UPLOAD_PATH   = "/www/vhosts/sender/media/newsletter/uploads/"
CKEDITOR_UPLOAD_PREFIX = "http://******/media/newsletter/uploads/"
CKEDITOR_RESTRICT_BY_USER = True

CKEDITOR_CONFIGS = {
    'default': {
        'toolbar': 'Basic',
    },
}

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',
    'django.contrib.admin',
    #'tagging',
    'debug_toolbar',
    'ckeditor',
    'mailer',
    'newsletter'

)

ContentLicense: CC BY-SA 2.5


问:
How do i remove a item from a Listbox when it has been chosen and a button has been pressed
I am creating a application to be used on a fridge, so that the user can see the items in the fridge by a List box on a GUI screen and then when they remove a item they can press on that item on the list box and press remove where that item will be removed from the List box.

However I have come across a problem in terms of how do I remove a item from a list by using the button (If That Makes Any sense).

Here is my code;

```<code>  def Pud():
        window = Tk()
        window.title('Listbox Example')

        def dialog():
***#########Somehere around here i belive should be where the item is removed from the list box########***

            box.showinfo('Selection','Item taken from the fridge: \n'+ \
            listbox.get(listbox.curselection()))

        frame = Frame(window)

        listbox = Listbox(window)
        listbox.pack()
        Items_In_Fridge = ['Milk', 'Butter']
        for widget in Items_In_Fridge:
            listbox.insert(0, widget)

        btn = Button(window,text = 'Remove This Item',command=dialog)

        btn.pack(side = RIGHT,padx = 5)
        listbox.pack(side = LEFT)

        window.mainloop()
</code>```

I know where the code should be however I am not sure what the code is or how to format it in terms of what I need, I have done multiple methods of trying to complete this but without being successful.

Any help would be greatly appreciated I am using python 3

答:
Capture the response of your dialog. If the user says 'yes', delete the item.</p>

```<code>response = messagebox.askquestion ('Delete Item','Delete the item taken from the fridge?\n'+ \
    listbox.get(listbox.curselection()))
if response == 'yes':
    listbox.delete(listbox.curselection())
</code>```

Body:
I am creating a application to be used on a fridge, so that the user can see the items in the fridge by a List box on a GUI screen and then when they remove a item they can press on that item on the list box and press remove where that item will be removed from the List box.

However I have come across a problem in terms of how do I remove a item from a list by using the button (If That Makes Any sense).

Here is my code;

  def Pud():
        window = Tk()
        window.title('Listbox Example')

        def dialog():
***#########Somehere around here i belive should be where the item is removed from the list box########***

            box.showinfo('Selection','Item taken from the fridge: \n'+ \
            listbox.get(listbox.curselection()))

        frame = Frame(window)

        listbox = Listbox(window)
        listbox.pack()
        Items_In_Fridge = ['Milk', 'Butter']
        for widget in Items_In_Fridge:
            listbox.insert(0, widget)

        btn = Button(window,text = 'Remove This Item',command=dialog)

        btn.pack(side = RIGHT,padx = 5)
        listbox.pack(side = LEFT)

        window.mainloop()

I know where the code should be however I am not sure what the code is or how to format it in terms of what I need, I have done multiple methods of trying to complete this but without being successful.

Any help would be greatly appreciated I am using python 3

Body:
Capture the response of your dialog. If the user says 'yes', delete the item.

response = messagebox.askquestion ('Delete Item','Delete the item taken from the fridge?\n'+ \
    listbox.get(listbox.curselection()))
if response == 'yes':
    listbox.delete(listbox.curselection())


问:
ReactiveX in REST API without UI
I'm starting to study ReactiveX and couldn't understand the advantages in a REST API, or any api that doesn't have a UI associated.

For instance, I'm building a Spring Boot REST API that is consumed by a Angular webapp (and eventually other apps) that is hosted on a different machine. Whenever I send a request from the webapp I'll use promises to handle the result without blocking.

So it that case, does it make sense to use ReactiveX (RxJava in that case) in the Spring Boot application? What advantages would it bring?

答:
With ReactiveX you can do different calls asyncronous at the same time and when all these calls are done you do something (like dissmiss progressbar ) and to do that you must use the zip operator : http://reactivex.io/documentation/operators/zip.html

You can make also perform asyncronous tasks one after the other. you can filter the first call and give its response to the second. You can do this by filter and FlatMap operators :

http://reactivex.io/documentation/operators/flatmap.html

http://reactivex.io/documentation/operators/filter.html

Title: ReactiveX in REST API without UI


问:
jQuery Selector From Table
I have a table like below:

```<code><table>
<tr>
    <td>james</td>
    <td>sawyer</td>
    <td><button id="getVal">Get</button></td>
<tr>
<tr>
    <td>kate</td>
    <td>deluna</td>
    <td><button id="getVal">Get</button></td>
<tr>
<tr>
    <td>tupac</td>
    <td>shakur</td>
    <td><button id="getVal">Get</button></td>
<tr>
</table>
</code>```

I want to click 'Get' button then get all td value in tr. I try this code but it's not working.

```<code><script type="text/javascript">
    $(document).ready(function() {
        $('#getVal').click(function () {
         var name    = $(this).find('td:first');
         var surname = $(this).find('td:second');
        });
    });
</script>
</code>```

How can i do that? Please help me!

答:
```<code>Please try this one
</code>```

 $(document).ready(function() {
        $('.getVal').click(function () {
         var name    = $(this).parents('tr').find('td:nth-child(1)').text();
     var surname = $(this).parents('tr').find('td:nth-child(2)').text();

    alert(name);
    alert(surname)

        });
    });```
<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>
<table>
<tr>
    <td>james</td>
    <td>sawyer</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>kate</td>
    <td>deluna</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>tupac</td>
    <td>shakur</td>
    <td><button class="getVal">Get</button></td>
<tr>
</table></code>```

Title: jQuery Selector From Table

Body:
I have a table like below:

    james
    sawyer
    <button id="getVal">Get</button>

    kate
    deluna
    <button id="getVal">Get</button>

    tupac
    shakur
    <button id="getVal">Get</button>

I want to click 'Get' button then get all td value in tr. I try this code but it's not working.

How can i do that? Please help me!

Body:
Please try this one

 $(document).ready(function() {
        $('.getVal').click(function () {
         var name    = $(this).parents('tr').find('td:nth-child(1)').text();
     var surname = $(this).parents('tr').find('td:nth-child(2)').text();

    alert(name);
    alert(surname)

        });
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
    <td>james</td>
    <td>sawyer</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>kate</td>
    <td>deluna</td>
    <td><button class="getVal">Get</button></td>
<tr>
<tr>
    <td>tupac</td>
    <td>shakur</td>
    <td><button class="getVal">Get</button></td>
<tr>
</table>


问:
How to use tm package for text analytics in Hebrew or Arabic
I would like to use tm package for Hebrew or Arabic text analysis. I tried several methods to see if tm will be able to process some words but i ran into an error, Is there a way to solve this issue?</p>

```<code> text  <- "הנוסעים חיכו זמן רב לנסיעה"
 Encoding(text)
#[1] "unknown"
 Encoding(text)  <- "UTF-8"
 ap.corpus <- Corpus(DataframeSource(data.frame(text)))
 ap.corpus <- tm_map(ap.corpus, removePunctuation)
 ap.corpus <- tm_map(ap.corpus, content_transformer(tolower))
Error in FUN(content(x), ...) :
  invalid input 'הנוסעים חיכו זמן רב לנסיעה' in 'utf8towcs'
</code>```

答:
From the tm vignette:

The second argument readerControl of the corpus constructor has to be
  a list with the named components reader and language. (...) Finally, the
  second component language sets the texts’ language (preferably using
  ISO 639-2 codes).

From Wikipedia, the ISO 639-2 code for Arabic is ara and for Hebrew heb. So maybe try this:

```<code> ap.corpus <- Corpus(DataframeSource(data.frame(text), readerControl = list(language = "heb")))
</code>```

Edit: Glad you found the answer. When the wrong encoding is used this error comes up:

R tm package invalid input in 'utf8towcs'

FUN-error after running 'tolower' while making Twitter wordcloud

Body:
I would like to use tm package for Hebrew or Arabic text analysis. I tried several methods to see if tm will be able to process some words but i ran into an error, Is there a way to solve this issue?

 text  <- "הנוסעים חיכו זמן רב לנסיעה"
 Encoding(text)
#[1] "unknown"
 Encoding(text)  <- "UTF-8"
 ap.corpus <- Corpus(DataframeSource(data.frame(text)))
 ap.corpus <- tm_map(ap.corpus, removePunctuation)
 ap.corpus <- tm_map(ap.corpus, content_transformer(tolower))
Error in FUN(content(x), ...) :
  invalid input 'הנוסעים חיכו זמן רב לנסיעה' in 'utf8towcs'

Body:
From the tm vignette:

The second argument readerControl of the corpus constructor has to be
  a list with the named components reader and language. (...) Finally, the
  second component language sets the texts’ language (preferably using
  ISO 639-2 codes).

From Wikipedia, the ISO 639-2 code for Arabic is ara and for Hebrew heb. So maybe try this:

 ap.corpus <- Corpus(DataframeSource(data.frame(text), readerControl = list(language = "heb")))

Edit: Glad you found the answer. When the wrong encoding is used this error comes up:

R tm package invalid input in 'utf8towcs'

FUN-error after running 'tolower' while making Twitter wordcloud


问:
Get rid of text content in xml
I need to validate XML and XSD not very acceptable (default one uses too many xsd:sequence and trick with xsd:choice makes validation too acceptable (not sure this is right word))

So, is there good way to turn this

```<code><?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>
</code>```

Into this

```<code><?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en"></title>
    <author></author>
    <year></year>
    <price></price>
  </book>
  <book category="children">
    <title lang="en"></title>
    <author></author>
    <year></year>
    <price></price>
  </book>
  <book category="web">
    <title lang="en"></title>
    <author></author>
    <year></year>
    <price></price>
  </book>
</bookstore>
</code>```

On windows with python/java/go ? Its not one-time job, I need to do it automatically

答:
The right tool for XML transformations is XSLT. This one is dead easy. In XSLT 3.0 it's

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform version="3.0">
  <xsl:output indent="yes"/>
  <xsl:mode on-no-match="shallow-copy"/>
  <xsl:template match="text()"/>
</xsl:stylesheet>
</code>```

You said a Java solution is OK, so download Saxon-HE 9.8 and run this as

```<code>java net.sf.saxon.Transform -s:in.xml -xsl:trans.xsl -o:out.xml
</code>```

If you prefer to use an XSLT 1.0 or 2.0 processor you can replace the xsl:mode declaration with the identity template rule which is easily googled.

Title: Get rid of text content in xml

Body:
I need to validate XML and XSD not very acceptable (default one uses too many xsd:sequence and trick with xsd:choice makes validation too acceptable (not sure this is right word))

So, is there good way to turn this

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="children">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

Into this

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
  <book category="cooking">
    <title lang="en"></title>
    <author></author>
    <year></year>
    <price></price>
  </book>
  <book category="children">
    <title lang="en"></title>
    <author></author>
    <year></year>
    <price></price>
  </book>
  <book category="web">
    <title lang="en"></title>
    <author></author>
    <year></year>
    <price></price>
  </book>
</bookstore>

On windows with python/java/go ? Its not one-time job, I need to do it automatically

Body:
The right tool for XML transformations is XSLT. This one is dead easy. In XSLT 3.0 it's

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform version="3.0">
  <xsl:output indent="yes"/>
  <xsl:mode on-no-match="shallow-copy"/>
  <xsl:template match="text()"/>
</xsl:stylesheet>

You said a Java solution is OK, so download Saxon-HE 9.8 and run this as

java net.sf.saxon.Transform -s:in.xml -xsl:trans.xsl -o:out.xml

If you prefer to use an XSLT 1.0 or 2.0 processor you can replace the xsl:mode declaration with the identity template rule which is easily googled.


问:
Get first record change timestamp when grouped by two columns SQL Server
I have a table that tracks versions history.I need to get the record the shows the first version change timestamp to the most recent version.

EDIT: Added more records to illustrate what I am looking for.
For example

```<code>id  version     timestamp
(123, 1.5, '2015-03-28 08:21:04'),
(123, 1.5, '2015-03-28 07:21:04'),
(123, 1.5, '2015-03-27 07:21:04'), <-- Latest version,first change for id 123
(123, 1.2, '2015-03-22 12:58:24'),
(123, 1.2, '2015-03-21 13:32:05'),
(123, 1.0, '2015-03-21 09:18:37'),
(123, 1.0, '2015-03-20 04:44:59'),
(234, 1.5, '2016-10-15 23:08:09'), <-- Latest version,first change for id 234
(345, 1.5, '2016-10-10 15:18:09'),
(345, 1.5, '2016-09-02 21:30:00'),
(345, 1.5, '2016-09-01 21:30:00'),
(345, 1.5, '2016-08-02 21:30:00'), <-- Latest version,first change for id 345
(345, 1.0, '2016-07-02 21:30:00')
</code>```

Expected output

```<code>id  version     timestamp
(123, 1.5, '2015-03-27 07:21:04')
(234, 1.5, '2016-10-15 23:08:09')
(345, 1.5, '2016-08-02 21:30:00')
</code>```

I was able to get this by using temp tables.I get the min(dt_create) for each id and version and store it in a temp table.Then I get the max date from this table for each id and then join it again to get the version.Is there a better way to do this?

```<code>create table #temp_version
(
       id varchar(22) NOT NULL,
       version varchar(50) NOT NULL,
       dt_create datetime NOT null
)

insert into #temp_version
select  id,version,min(dt_create) as dt_create
from [version_history] (nolock)
group by id,version

create table #temp_min_date
(
      id varchar(22) NOT NULL,
      dt_create datetime NOT null
)

insert into #temp_min_date
select id,max(dt_create)
from #temp_version
group by id

select a.id,a.version,a.dt_create
from #temp_version a
join #temp_date b on a.id = b.id and
a.dt_create=b.dt_create

drop table #temp_date
drop table #temp_version
</code>```

答:
Solution without CTE or subquery:</p>

```<code>SELECT TOP(1) WITH TIES
    id,
    version,
    dt_create = timestamp
FROM [version_history]
ORDER BY ROW_NUMBER() OVER (PARTITION BY id ORDER BY version desc, timestamp)
</code>```

Body:
I have a table that tracks versions history.I need to get the record the shows the first version change timestamp to the most recent version.

EDIT: Added more records to illustrate what I am looking for.
For example

id  version     timestamp
(123, 1.5, '2015-03-28 08:21:04'),
(123, 1.5, '2015-03-28 07:21:04'),
(123, 1.5, '2015-03-27 07:21:04'), <-- Latest version,first change for id 123
(123, 1.2, '2015-03-22 12:58:24'),
(123, 1.2, '2015-03-21 13:32:05'),
(123, 1.0, '2015-03-21 09:18:37'),
(123, 1.0, '2015-03-20 04:44:59'),
(234, 1.5, '2016-10-15 23:08:09'), <-- Latest version,first change for id 234
(345, 1.5, '2016-10-10 15:18:09'),
(345, 1.5, '2016-09-02 21:30:00'),
(345, 1.5, '2016-09-01 21:30:00'),
(345, 1.5, '2016-08-02 21:30:00'), <-- Latest version,first change for id 345
(345, 1.0, '2016-07-02 21:30:00')

Expected output

id  version     timestamp
(123, 1.5, '2015-03-27 07:21:04')
(234, 1.5, '2016-10-15 23:08:09')
(345, 1.5, '2016-08-02 21:30:00')

I was able to get this by using temp tables.I get the min(dt_create) for each id and version and store it in a temp table.Then I get the max date from this table for each id and then join it again to get the version.Is there a better way to do this?

create table #temp_version
(
       id varchar(22) NOT NULL,
       version varchar(50) NOT NULL,
       dt_create datetime NOT null
)

insert into #temp_version
select  id,version,min(dt_create) as dt_create
from [version_history] (nolock)
group by id,version

create table #temp_min_date
(
      id varchar(22) NOT NULL,
      dt_create datetime NOT null
)

insert into #temp_min_date
select id,max(dt_create)
from #temp_version
group by id

select a.id,a.version,a.dt_create
from #temp_version a
join #temp_date b on a.id = b.id and
a.dt_create=b.dt_create

drop table #temp_date
drop table #temp_version

Body:
Solution without CTE or subquery:

SELECT TOP(1) WITH TIES
    id,
    version,
    dt_create = timestamp
FROM [version_history]
ORDER BY ROW_NUMBER() OVER (PARTITION BY id ORDER BY version desc, timestamp)


问:
SharePoint PnP .. Set value for ModerationStatus
I tried to set the "_ModerationStatus" in a SharePoint List with enabled content approval. I do it with SharePoint PnP (ClientSide).

I tried:

```<code>Set-PnPListItem -List $item.parentlist -Identity $item -Values @{"_ModerationStatus" = 0}
</code>```

But nothing happens. I can change every fieldof the item. I tried several format of 0 or "0" or "Approved" or "Genehmigt" .. but without any effect.

Can anyone help me?

答:
You set a list items _ModerationStatus by accessing the list item property directly.

```<code>$item["_ModerationStatus"] = 0
$item.Update()
Execute-PnPQuery
</code>```

I have tested this on a list with content approval enabled. Hopefully it works for you too

Body:
I tried to set the "_ModerationStatus" in a SharePoint List with enabled content approval. I do it with SharePoint PnP (ClientSide).

I tried:

Set-PnPListItem -List $item.parentlist -Identity $item -Values @{"_ModerationStatus" = 0}

But nothing happens. I can change every fieldof the item. I tried several format of 0 or "0" or "Approved" or "Genehmigt" .. but without any effect.

Can anyone help me?

Body:
You set a list items _ModerationStatus by accessing the list item property directly.

$item["_ModerationStatus"] = 0
$item.Update()
Execute-PnPQuery

I have tested this on a list with content approval enabled. Hopefully it works for you too


问:
Java reflection not agreeing with method declaration
Sorry about the length of this question.  I'm new to Java and I've come across something that is really stumping me.  I'm so new to Java that I don't even know all the terminology yet, so please bear with me; I have about 3 years of PHP experience (mostly procedural, not OO), but very little Java.  I'm also aware that debugging with System.out.println is the Wrong Way to do it, but it works and it's what I'm used to (insert joke about PHP programmers here if you must).  I'm still trying to figure out how to use the NetBeans debugger.

I'm working on adding a feature to a web application that uses Struts (1.x).  The problem I'm having seems to be that a method is declared to want a String passed to it, but doing Reflection on that method says it wants String[] (a string array).  I'm constrained in that I can't really make major structural changes to the app, and of course I have to make sure that I don't break anything in the app that is currently working, so I'm trying to make my changes in the context of what's already there.  So, to the problem...

Here is where the method is declared (many many lines cut from these to show only what I hope are the relevant bits):

AEReportBean.java:

```<code>public class AEReportBean {
    private String selectedDownloadFields = null;

    public String getSelectedDownloadFields() {
        return selectedDownloadFields;
    }

    // Note that there is no overloading of this function anywhere, this is the only declaration.
    public void setSelectedDownloadFields(String selectedDownloadFields) {
        this.selectedDownloadFields = selectedDownloadFields;
    }
}
</code>```

When the user clicks Submit on the form, it gets handled by AEReportSubmitAction.java:

```<code>public class AEReportSubmitAction extends BaseAction {
    public ActionForward doExecute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response
        ) throws Exception {
        // This works fine, the paramater is getting passed in the request:
        System.out.println("URL parameter: " + request.getParameter("selectedDownloadFields");

        AEReportBean bean = new AEReportBean(request.getLocale(), 0);

        PropertyUtil.setAllFromRequest(request, bean);
        // This prints "Null", meaning the setAllFromRequest line above is failing to set this property.
        System.out.println("AEReportSubmitAction.java - bean.getSelectedDownloadFields() after setAllFromRequest: " + bean.getSelectedDownloadFields());
    }
}
</code>```

PropertyUtil.setAllFromRequest() is where the magic, and the real problem, happens:

```<code>public class PropertyUtil {
    /**
     * Takes all the parameters from the request object and if there's a matching
     * mutator method in the bean, sets it
     */
    static public void setAllFromRequest(ServletRequest request, Object out) {
        // Iterate through all the request parameter names and try to set each one.
        for (Enumeration parameterNames = request.getParameterNames(); parameterNames.hasMoreElements();) {
            String name = (String) parameterNames.nextElement();
            try {
                PropertyUtil.setSimpleProperty(out, name, request.getParameter(name));
            }
            catch (Exception e) {
                log.info("Exception while setting properties from the Request. parameterName=" + name, e);
            }
        }
    }

    /**
     * Sets the property from an object using the object's mutator method.
     * Assumes naming conventions for accessor methods
     * @param bean the object to get the property from
     * @param property the name of the property to obtain
     * @param newProperty the object to set
     */
    // NOTE: This just seems to be a wrapper for the method below it...
    static public void setSimpleProperty(Object bean, String property, Object newProperty) throws Exception {
        PropertyUtil.setSimpleProperty(bean, property, newProperty, null);
    }

    /**
     * Sets the property from an object using the object's mutator method.
     * Assumes naming conventions for accessor methods
     * @param bean the object to get the property from
     * @param property the name of the property to obtain
     * @param newProperty the object to set
     */
    static public void setSimpleProperty(Object bean, String property, Object newProperty, Class type) throws Exception {
        // Capitalize the first letter in the property and append "set" to the front
        String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
        Method method;

        Class[] parameters;

        // If the Type was passed in when this method was called, simply add it to the Class array.
        if (type != null) {
            parameters = new Class[]{type};
        }
        // If the Type was not specified, determine the Type's class by calling getClass() on it; that class will be used below to call the appropriate setter method.
        else {
            parameters = new Class[]{newProperty.getClass()};
        }

        // Here's the reflection problem...
        // Iterate through all the methods in the bean.  If the method is named "setSelectedDownloadFields", print out some info about it.
        for (Method m : bean.getClass().getMethods()) {
            if (m.getName().equals("setSelectedDownloadFields")) {
                // newProperty is the incoming data that ultimately comes from the HTML form field.
                System.out.println("newProperty.getClass(): " + newProperty.getClass()); // Prints "class java.lang.String"

                    // Added for Cameron Skinner in comments.
                    System.out.println("m.toGenericString: " + m.toGenericString()); // Prints "public void com.[company deleted].bean.AEReportBean.setSelectedDownloadFields(java.lang.String[])"

                System.out.println("m.getName(): " + m.getName()); // Prints "setSelectedDownloadFields"
                System.out.println("parameters:");
                for (Class c : m.getParameterTypes()) {
                    System.out.println("--c.getCanonicalName(): " + c.getCanonicalName()); // Prints "java.lang.String[]"
                    System.out.println("--c.getName(): " + c.getName()); // Prints "[Ljava.lang.String;"
                }
            }
        }

        // And here's where it fails...
        try {
            System.out.println("bean.getClass(): " + bean.getClass());  // Prints "class com.[company deleted].bean.AEReportBean"
            System.out.println("methodName: " + methodName); // Prints "setSelectedDownloadFields"
            System.out.println("for (Class p : parameters):");
            for (Class p : parameters) {
                System.out.println("--p.getCanonicalName(): " + p.getCanonicalName()); // Prints "java.lang.String"
            }

            // Here it looks for a method called, effectively, AEReportBean.setSelectedDownloadFields(String s), but above we see that reflection is showing it as AEReportBean.setSelectedDownloadFields(String[] s), so the try block fails.
            method = bean.getClass().getMethod(methodName, parameters);
        }
        catch (NoSuchMethodException e) {
            // All lines below here also fail until it bombs out with the exception at the bottom...

            // If no method can be found, then see if it's a primitive type that
            // has been wrapped
            Class valueClass = newProperty.getClass();
            //System.out.println("valueClass.toString() = " + valueClass.toString());
            try {
                if (valueClass.equals(Integer.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{int.class});
                }
                else if (valueClass.equals(Double.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{double.class});
                }
                else if (valueClass.equals(Long.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{long.class});
                }
                else if (valueClass.equals(Float.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{float.class});
                }
                else {
                    throw new Exception(e.getMessage());
                }
            }
            catch (NoSuchMethodException ex) {
                throw new Exception(ex.getMessage());
            }
        }

        // If it had gotten to this point, it would call the method with the appropriate parameters, and the property would be set.
        try {
            // Now execute the method
            method.invoke(bean, new Object[]{newProperty});
        }
        catch (Exception ex) {
            throw new Exception(ex.getMessage());
        }
    }
}
</code>```

I really don't know what I'm missing here, but there must be something.  Other HTML form elements on the same page work perfectly.  Please let me know if any more information is needed.  Thanks!

答:
The code results doesn't lie. It's basically telling that the class isn't what you expect it to be. You've multiple AEReportBean classes of different versions in the classpath of your project, possibly in different packages, and the wrong one has been imported or got precedence in classloading. Do a Type/Class search in Netbeans to find all classes by the given name in the classpath (I don't do Netbeans, but in Eclispe it's Ctrl+Shift+T, the Netbeans equivalent is probably Alt+Shift+O).

Update: another possible cause is that Netbeans didn't build the project automatically on save of the source file (an IDE should create/refresh .class files during build). Look somewhere in settings.

Body:
Sorry about the length of this question.  I'm new to Java and I've come across something that is really stumping me.  I'm so new to Java that I don't even know all the terminology yet, so please bear with me; I have about 3 years of PHP experience (mostly procedural, not OO), but very little Java.  I'm also aware that debugging with System.out.println is the Wrong Way to do it, but it works and it's what I'm used to (insert joke about PHP programmers here if you must).  I'm still trying to figure out how to use the NetBeans debugger.

I'm working on adding a feature to a web application that uses Struts (1.x).  The problem I'm having seems to be that a method is declared to want a String passed to it, but doing Reflection on that method says it wants String[] (a string array).  I'm constrained in that I can't really make major structural changes to the app, and of course I have to make sure that I don't break anything in the app that is currently working, so I'm trying to make my changes in the context of what's already there.  So, to the problem...

Here is where the method is declared (many many lines cut from these to show only what I hope are the relevant bits):

AEReportBean.java:

public class AEReportBean {
    private String selectedDownloadFields = null;

    public String getSelectedDownloadFields() {
        return selectedDownloadFields;
    }

    // Note that there is no overloading of this function anywhere, this is the only declaration.
    public void setSelectedDownloadFields(String selectedDownloadFields) {
        this.selectedDownloadFields = selectedDownloadFields;
    }
}

When the user clicks Submit on the form, it gets handled by AEReportSubmitAction.java:

public class AEReportSubmitAction extends BaseAction {
    public ActionForward doExecute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response
        ) throws Exception {
        // This works fine, the paramater is getting passed in the request:
        System.out.println("URL parameter: " + request.getParameter("selectedDownloadFields");

        AEReportBean bean = new AEReportBean(request.getLocale(), 0);

        PropertyUtil.setAllFromRequest(request, bean);
        // This prints "Null", meaning the setAllFromRequest line above is failing to set this property.
        System.out.println("AEReportSubmitAction.java - bean.getSelectedDownloadFields() after setAllFromRequest: " + bean.getSelectedDownloadFields());
    }
}

PropertyUtil.setAllFromRequest() is where the magic, and the real problem, happens:

public class PropertyUtil {
    /**
     * Takes all the parameters from the request object and if there's a matching
     * mutator method in the bean, sets it
     */
    static public void setAllFromRequest(ServletRequest request, Object out) {
        // Iterate through all the request parameter names and try to set each one.
        for (Enumeration parameterNames = request.getParameterNames(); parameterNames.hasMoreElements();) {
            String name = (String) parameterNames.nextElement();
            try {
                PropertyUtil.setSimpleProperty(out, name, request.getParameter(name));
            }
            catch (Exception e) {
                log.info("Exception while setting properties from the Request. parameterName=" + name, e);
            }
        }
    }

    /**
     * Sets the property from an object using the object's mutator method.
     * Assumes naming conventions for accessor methods
     * @param bean the object to get the property from
     * @param property the name of the property to obtain
     * @param newProperty the object to set
     */
    // NOTE: This just seems to be a wrapper for the method below it...
    static public void setSimpleProperty(Object bean, String property, Object newProperty) throws Exception {
        PropertyUtil.setSimpleProperty(bean, property, newProperty, null);
    }

    /**
     * Sets the property from an object using the object's mutator method.
     * Assumes naming conventions for accessor methods
     * @param bean the object to get the property from
     * @param property the name of the property to obtain
     * @param newProperty the object to set
     */
    static public void setSimpleProperty(Object bean, String property, Object newProperty, Class type) throws Exception {
        // Capitalize the first letter in the property and append "set" to the front
        String methodName = "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
        Method method;

        Class[] parameters;

        // If the Type was passed in when this method was called, simply add it to the Class array.
        if (type != null) {
            parameters = new Class[]{type};
        }
        // If the Type was not specified, determine the Type's class by calling getClass() on it; that class will be used below to call the appropriate setter method.
        else {
            parameters = new Class[]{newProperty.getClass()};
        }

        // Here's the reflection problem...
        // Iterate through all the methods in the bean.  If the method is named "setSelectedDownloadFields", print out some info about it.
        for (Method m : bean.getClass().getMethods()) {
            if (m.getName().equals("setSelectedDownloadFields")) {
                // newProperty is the incoming data that ultimately comes from the HTML form field.
                System.out.println("newProperty.getClass(): " + newProperty.getClass()); // Prints "class java.lang.String"

                    // Added for Cameron Skinner in comments.
                    System.out.println("m.toGenericString: " + m.toGenericString()); // Prints "public void com.[company deleted].bean.AEReportBean.setSelectedDownloadFields(java.lang.String[])"

                System.out.println("m.getName(): " + m.getName()); // Prints "setSelectedDownloadFields"
                System.out.println("parameters:");
                for (Class c : m.getParameterTypes()) {
                    System.out.println("--c.getCanonicalName(): " + c.getCanonicalName()); // Prints "java.lang.String[]"
                    System.out.println("--c.getName(): " + c.getName()); // Prints "[Ljava.lang.String;"
                }
            }
        }

        // And here's where it fails...
        try {
            System.out.println("bean.getClass(): " + bean.getClass());  // Prints "class com.[company deleted].bean.AEReportBean"
            System.out.println("methodName: " + methodName); // Prints "setSelectedDownloadFields"
            System.out.println("for (Class p : parameters):");
            for (Class p : parameters) {
                System.out.println("--p.getCanonicalName(): " + p.getCanonicalName()); // Prints "java.lang.String"
            }

            // Here it looks for a method called, effectively, AEReportBean.setSelectedDownloadFields(String s), but above we see that reflection is showing it as AEReportBean.setSelectedDownloadFields(String[] s), so the try block fails.
            method = bean.getClass().getMethod(methodName, parameters);
        }
        catch (NoSuchMethodException e) {
            // All lines below here also fail until it bombs out with the exception at the bottom...

            // If no method can be found, then see if it's a primitive type that
            // has been wrapped
            Class valueClass = newProperty.getClass();
            //System.out.println("valueClass.toString() = " + valueClass.toString());
            try {
                if (valueClass.equals(Integer.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{int.class});
                }
                else if (valueClass.equals(Double.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{double.class});
                }
                else if (valueClass.equals(Long.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{long.class});
                }
                else if (valueClass.equals(Float.class)) {
                    method = bean.getClass().getMethod(methodName, new Class[]{float.class});
                }
                else {
                    throw new Exception(e.getMessage());
                }
            }
            catch (NoSuchMethodException ex) {
                throw new Exception(ex.getMessage());
            }
        }

        // If it had gotten to this point, it would call the method with the appropriate parameters, and the property would be set.
        try {
            // Now execute the method
            method.invoke(bean, new Object[]{newProperty});
        }
        catch (Exception ex) {
            throw new Exception(ex.getMessage());
        }
    }
}

I really don't know what I'm missing here, but there must be something.  Other HTML form elements on the same page work perfectly.  Please let me know if any more information is needed.  Thanks!


问:
How to remove rows from a data frame when a % of columns have a value less than specified?
I have some data that I want to filter. I want to be able to say, "If a specified percentage of each row contains a value less than indicated, remove that row from the data frame.

Here is some sample data.

```<code>       Sample1, Sample2, Sample3, Sample4, Sample5, Sample6
Item1   0   0   0   0   0   0
Item2   478 440 522 578 1066 1045
Item3   16  14  9   6   6   20
</code>```

Let's say I want rows with 50% of columns with a value of less than 10 to be removed.  So in that scenario Item1 row is removed, and Item3 row is removed.

If I change the criteria to be 50% of columns with a value of less than 7, then only Item1 goes, and Item2 and Item3 remain.

What's a neat way to accomplish this in R?  This is a simple issue and I want to avoid writing messy code to accomplish it.  From what I've read so far I should be doing this with lapply() maybe?  I appreciate any insight.

答:
You can do this just by indexing.  </p>

```<code>## reproduce your data
df = read.table(text="ItemNum Sample1 Sample2 Sample3 Sample4 Sample5 Sample6
Item1   0   0   0   0   0   0
Item2   478 440 522 578 1066 1045
Item3   16  14  9   6   6   20",
header=TRUE, stringsAsFactors=FALSE)

df = df[which(rowSums(df[,2:7] < 10) < 3), ]
df
   ItemNum Sample1 Sample2 Sample3 Sample4 Sample5 Sample6
2   Item2     478     440     522     578    1066    1045
</code>```

Body:
I have some data that I want to filter. I want to be able to say, "If a specified percentage of each row contains a value less than indicated, remove that row from the data frame.

Here is some sample data.

       Sample1, Sample2, Sample3, Sample4, Sample5, Sample6
Item1   0   0   0   0   0   0
Item2   478 440 522 578 1066 1045
Item3   16  14  9   6   6   20

Let's say I want rows with 50% of columns with a value of less than 10 to be removed.  So in that scenario Item1 row is removed, and Item3 row is removed.

If I change the criteria to be 50% of columns with a value of less than 7, then only Item1 goes, and Item2 and Item3 remain.

What's a neat way to accomplish this in R?  This is a simple issue and I want to avoid writing messy code to accomplish it.  From what I've read so far I should be doing this with lapply() maybe?  I appreciate any insight.

Body:
You can do this just by indexing.

## reproduce your data
df = read.table(text="ItemNum Sample1 Sample2 Sample3 Sample4 Sample5 Sample6
Item1   0   0   0   0   0   0
Item2   478 440 522 578 1066 1045
Item3   16  14  9   6   6   20",
header=TRUE, stringsAsFactors=FALSE)

df = df[which(rowSums(df[,2:7] < 10) < 3), ]
df
   ItemNum Sample1 Sample2 Sample3 Sample4 Sample5 Sample6
2   Item2     478     440     522     578    1066    1045


问:
How to cancel incomplete task on ExecutorService
I have submitted two tasks, task1 & task2 to the ExecutorService. Task2 needs 5 seconds to complete, and task1 need 10 seconds.

How can I stop the task(s) submitted (ie: task1) when task2 completes and continues the rest of logic?

Here's my code so far:

```<code>public class mt_poc {
    public static void action_1 () throws InterruptedException {
        System.out.println("action_1 invoke " );
        Thread.sleep(10000);
        action_2 ();
        System.out.println("action_1 done" );
    }

    public static void action_2() throws InterruptedException {
        System.out.println("action_2 invoke " );
        Thread.sleep(5000);
        System.out.println("action_2 done " );
    }

    public static void main(String[] args) {
        System.out.println("TEST");
        Runnable task1 = new Runnable() {
            public void run() {
                try {
                    action_1 ();
                }
                catch(InterruptedException e) {
                    System.out.println("action_1 invoke interrupted");
                }
                System.out.println("action_1 invoke run is over" );
                }
            };

        Runnable task2 = new Runnable() {
            public void run() {
                try {
                    action_2 ();
                }
                catch(InterruptedException e) {
                   System.out.println("action_2 invoke interrupted");
                }
                System.out.println("action_2 invoke run is over" );
                }
            };

        ExecutorService executor = Executors.newFixedThreadPool(2);

        try {
            executor.submit(task1);
            executor.submit(task2);
            // cancel uncomplete task
            executor.shutdown();
            executor.awaitTermination(5, TimeUnit.SECONDS);
            // continues the rest of logic
        } catch (InterruptedException e) {
                e.printStackTrace();
        }

        System.out.println("Shutdown executor");
    }
}
</code>```

答:
You have to retrieve the Future objects from the submit function.

These are used to control the running thread and get the status of it.
If you have the futures, call Future2.get(). This will block the thread until the Task2 is finished. No you can use Future1.cancel(true) to abort the other thread.

But pausing and resuming is not possible. See Java ExecutorService pause/resume a specific thread

If you want such specific behaviour you need to use Threads.

But why you want to do this in seperate Threads as it would be much simpler and efficient t use a single one.

Body:
I have submitted two tasks, task1 & task2 to the ExecutorService. Task2 needs 5 seconds to complete, and task1 need 10 seconds.

How can I stop the task(s) submitted (ie: task1) when task2 completes and continues the rest of logic?

Here's my code so far:

public class mt_poc {
    public static void action_1 () throws InterruptedException {
        System.out.println("action_1 invoke " );
        Thread.sleep(10000);
        action_2 ();
        System.out.println("action_1 done" );
    }

    public static void action_2() throws InterruptedException {
        System.out.println("action_2 invoke " );
        Thread.sleep(5000);
        System.out.println("action_2 done " );
    }

    public static void main(String[] args) {
        System.out.println("TEST");
        Runnable task1 = new Runnable() {
            public void run() {
                try {
                    action_1 ();
                }
                catch(InterruptedException e) {
                    System.out.println("action_1 invoke interrupted");
                }
                System.out.println("action_1 invoke run is over" );
                }
            };

        Runnable task2 = new Runnable() {
            public void run() {
                try {
                    action_2 ();
                }
                catch(InterruptedException e) {
                   System.out.println("action_2 invoke interrupted");
                }
                System.out.println("action_2 invoke run is over" );
                }
            };

        ExecutorService executor = Executors.newFixedThreadPool(2);

        try {
            executor.submit(task1);
            executor.submit(task2);
            // cancel uncomplete task
            executor.shutdown();
            executor.awaitTermination(5, TimeUnit.SECONDS);
            // continues the rest of logic
        } catch (InterruptedException e) {
                e.printStackTrace();
        }

        System.out.println("Shutdown executor");
    }
}


问:
Remove jumps like peaks and steps in timeseries
I have quite a few sensors in the field that measure water pressure. In the past the height of these sensors have been changed quite a few times creating jumps in the timeseries. Since these timeseries are continuous and I have a manual measurement I should technically be able to remove the jumps (by hand this is easy, but there are too many measurements so I need to do it in python).

I've tried removing the jumps using a median filter but this doesn't really work.

My code:

```<code>    # filter out noise in signal (peaks)
    minimumPeak = 0.03 # filter peaks larger than 0.03m
    filtered_value = np.array(im.median_filter(data['value'], 5))
    noise = np.array((filtered_value-data['value']).abs() > minimumPeak)
    data.loc[noise, 'value'] = filtered_value[noise]
</code>```

data is pandas dataframe containing two columns: 'datetime' and 'value'.

I've also tried to do this manually and got it working in a simple case, but not well in any other. Any idea how I would filter out the jumps?

An example is shown in the picture below (yellow indicating the jumps, red the measurement by hand (it is very well possible that this measurement is not in the beginning as it is in this example))

答:
You can try it like this:</p>

```<code>import numpy as np
import matplotlib.pyplot as plt
import h5py
%matplotlib inline

# I'm not sure that you need all of this packedges

filepath = 'measurment.hdf5'

with h5py.File(filepath, 'r') as hdf:
    data_y = hdf['y'][:]
    data_x = hdf['x'][:]

data = data_y

delta_max = 1 # maximum difference in y between two points
delta = 0 # running correction value
data_cor = [] # corrected array
data_cor.append(data[0:1]) # we append two first points

for i in range(len(data_x)-2): # two first points are allready appended
    i += 2
    delta_i = data[i] - data[i-1]
    if np.abs(delta_i) > delta_max:
        delta += (delta_i - (data_cor[i-1] - data_cor[i-2]))
        data_cor.append(data[i]-delta)
    else:
        data_cor.append(data[i]-delta)

plt.plot(data_x, data_cor)
</code>```

Body:
I have quite a few sensors in the field that measure water pressure. In the past the height of these sensors have been changed quite a few times creating jumps in the timeseries. Since these timeseries are continuous and I have a manual measurement I should technically be able to remove the jumps (by hand this is easy, but there are too many measurements so I need to do it in python).

I've tried removing the jumps using a median filter but this doesn't really work.

My code:

    # filter out noise in signal (peaks)
    minimumPeak = 0.03 # filter peaks larger than 0.03m
    filtered_value = np.array(im.median_filter(data['value'], 5))
    noise = np.array((filtered_value-data['value']).abs() > minimumPeak)
    data.loc[noise, 'value'] = filtered_value[noise]

data is pandas dataframe containing two columns: 'datetime' and 'value'.

I've also tried to do this manually and got it working in a simple case, but not well in any other. Any idea how I would filter out the jumps?

An example is shown in the picture below (yellow indicating the jumps, red the measurement by hand (it is very well possible that this measurement is not in the beginning as it is in this example))

Body:
You can try it like this:

import numpy as np
import matplotlib.pyplot as plt
import h5py
%matplotlib inline

# I'm not sure that you need all of this packedges

filepath = 'measurment.hdf5'

with h5py.File(filepath, 'r') as hdf:
    data_y = hdf['y'][:]
    data_x = hdf['x'][:]

data = data_y

delta_max = 1 # maximum difference in y between two points
delta = 0 # running correction value
data_cor = [] # corrected array
data_cor.append(data[0:1]) # we append two first points

for i in range(len(data_x)-2): # two first points are allready appended
    i += 2
    delta_i = data[i] - data[i-1]
    if np.abs(delta_i) > delta_max:
        delta += (delta_i - (data_cor[i-1] - data_cor[i-2]))
        data_cor.append(data[i]-delta)
    else:
        data_cor.append(data[i]-delta)

plt.plot(data_x, data_cor)


问:
tshark error at epoch time filtering
I have a pcap file and I want to filter out some packets based on their epoch timestamp with tshark.

I have a timestamp t1. I need the packets, whose epoch timestamp is "later" than t1.
The timestamp t1 is extracted from an other pcap file. So far so good.

In the following lines I convert the timestamp t1 (1499351908.01) to the datetime format p (2017-07-06 10:38:28). I am doing this because tshark needs a notation like this for filtering. Otherwise an error occurs.

```<code>t1_c = DT.datetime.fromtimestamp(t1)
p = t1_c.strftime('%Y-%m-%d %H:%M:%S')
</code>```

In the following line I specifiy the input and output file and the tshark filter:

```<code>os.system('tshark -r test_in.pcap -w test_out.pcap -Y "frame.time >= p"')
</code>```

So if I run my code, this tshark error occurs:

```<code>tshark: "p" is not a valid absolute time. Example: "Nov 12, 1999 08:55:44.123" or "2011-07-04 12:34:56"
</code>```

What is wrong? Is the filtering notation wrong?

Thanks in advance!

答:
Simply rewriting p in your string won't substitute it. Here is what your line should look like :</p>

```<code>os.system('tshark -r test_in.pcap -w test_out.pcap -Y "frame.time >= {}"'.format(p))
</code>```

Title: tshark error at epoch time filtering

Body:
I have a pcap file and I want to filter out some packets based on their epoch timestamp with tshark.

I have a timestamp t1. I need the packets, whose epoch timestamp is "later" than t1.
The timestamp t1 is extracted from an other pcap file. So far so good.

In the following lines I convert the timestamp t1 (1499351908.01) to the datetime format p (2017-07-06 10:38:28). I am doing this because tshark needs a notation like this for filtering. Otherwise an error occurs.

t1_c = DT.datetime.fromtimestamp(t1)
p = t1_c.strftime('%Y-%m-%d %H:%M:%S')

In the following line I specifiy the input and output file and the tshark filter:

os.system('tshark -r test_in.pcap -w test_out.pcap -Y "frame.time >= p"')

So if I run my code, this tshark error occurs:

tshark: "p" is not a valid absolute time. Example: "Nov 12, 1999 08:55:44.123" or "2011-07-04 12:34:56"

What is wrong? Is the filtering notation wrong?

Thanks in advance!

Body:
Simply rewriting p in your string won't substitute it. Here is what your line should look like :

os.system('tshark -r test_in.pcap -w test_out.pcap -Y "frame.time >= {}"'.format(p))


问:
How to add new element to existing 2d string array?
How to add new element to 2d string array in c#?
Ex. I have a array

```<code>string [,] x = new string[,]{{"1","a"},{"2","b"}};
</code>```

Now I want to increase the length array and add "3" and "c" to the top.

答:
Array's are immutable in terms of length. Once defined, objects cannot be added into them.

You need a expandable collection for that like List of your custom class.

```<code>public class FooBar
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}
</code>```

and list like

```<code>var fooBars = new List<FooBar>
{
    new FooBar() {Foo = "1", Bar = "a"},
    new FooBar() {Foo = "2", Bar = "b"},
};

fooBars.Add(new FooBar() {Foo = "3", Bar = "c"});
</code>```

Also you can now convert the collection to Array like this

```<code>var myArray = fooBars.ToArray();
</code>```

Body:
How to add new element to 2d string array in c#?
Ex. I have a array

string [,] x = new string[,]{{"1","a"},{"2","b"}};

Now I want to increase the length array and add "3" and "c" to the top.

Body:
Array's are immutable in terms of length. Once defined, objects cannot be added into them.

You need a expandable collection for that like List of your custom class.

public class FooBar
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}

and list like

var fooBars = new List<FooBar>
{
    new FooBar() {Foo = "1", Bar = "a"},
    new FooBar() {Foo = "2", Bar = "b"},
};

fooBars.Add(new FooBar() {Foo = "3", Bar = "c"});

Also you can now convert the collection to Array like this

var myArray = fooBars.ToArray();