问:
Disable dynamically generated buttons in jquery
Each time a user selects a checkbox within a row of a table, and clicks save, it will generate a container which will hold the data in a specific format for that selected row.

Note: The data is coming in the table from JSON.

Similarly, the user will also have an option to add the data manually to the same container through a form.

Now, I all these containers or data holders will be appended to a parent container in the dom.

I need to swap each of these data containers, which I've achieved so far.
However, the buttons are not getting disabled or hidden for the first container and the last one.

Here's my script

```<code><script>
    function getData(){
        $('input[name="articles"]:checked').map(function() {
            var content =  JSON.parse(decodeURIComponent(this.value));
            content+= '<div class="container parent><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Name:</label><div class="col-md-8 article-data">'+name+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove">Delete  <span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';
            $('.box').html(content);
        });
        $('.remove').click(function(){
            $(this).parents('.parent').remove();
        });
        resetEvents();
    }
function addName(){
    var name= $("#articleTitle").val();
    content +='<div class="container parent><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Name:</label><div class="col-md-8 article-data">'+Count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove">Delete  <span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';
        $('.box').html(content);
        $('.removeArticle').click(function(){
        $(this).parents('.parent').remove();
    });

}
function handleEvents() {
    $(".top-btn, .down-btn").prop("disabled", false).show();
    $(".parent:first").find(".top-btn").prop("disabled", true).hide();
    $(".parent:last").find(".down-btn").prop("disabled", true).hide();
}
function resetEvents() {
    $(".top-btn, .down-btn").unbind('click');
    handleEvents();
    $('.down-btn').click(function() {
        var toMove1 = $(this).parents('.article-box');
        $(toMove1).insertAfter($(toMove1).next());
        handleEvents();
    });
    $('.top-btn').click(function() {
        var toMove1 = $(this).parents('.article-box');
        $(toMove1).insertBefore($(toMove1).prev());
        handleEvents();
    });
}
</script>
</code>```

The first data holder will not have a top one to swap with. Hence, the top button should be disabled or hidden.

Similarly, the last data holder will not have a down one to swap with. Hence, the down button should be disabled or hidden.

I'm not able to understand what's wrong with what I wrote?

Note: This works perfectly fine if I use hard-coded data holders rather than generating it on runtime.

答:
Here's the complete code.</p>

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

    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
        <style>
            .parent {
                height: 25%;
                width: 90%;
                padding: 1%;
                margin-left: 1%;
                margin-top: 1%;
                border: 1px solid black;

            }

            .parent:nth-child(odd){
                background: skyblue;
            }

            .parent:nth-child(even){
                background: green;
            }

            .disabled-btn {
              cursor: not-allowed;
              opacity: 0.25%;
            }

        </style>
    </head>
    <body>
        <button class="btn btn-primary" onclick="getData()">Get data</button>
        <form>
            <label>Count: </label>
            <input type="text" placeholder="enter a count" id="mycount">
            <button onclick="saveData()">Submit</button>
        </form>
        <div class="box">

        </div>

    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script>
        var content = "";

        function getData(){

                for(var count=0; count<4; count++){

                content+= '<div class="container parent"><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Count:</label><div class="col-md-8 article-data">'+count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove-btn">Delete  <span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';

                }
                $('.box').html(content);

            $('.remove-btn').click(function(){
                $(this).parents('.parent').remove();
            });

            resetEvents();
        }

        function saveData(){
            var count = $("#mycount").val();
            content+= '<div class="container parent"><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Count:</label><div class="col-md-8 article-data">'+count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove-btn">Delete  <span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';

            $('.box').html(content);
            $('.remove-btn').click(function(){
                $(this).parents('.parent').remove();
            });
        }

        function handleEvents() {
                $(".top-btn, .down-btn").prop("disabled", false).show();
                $(".parent:first").find('.top-btn').attr('disabled','disabled');

                $(".parent:first").find(".top-btn").prop("disabled", true).hide();

                $(".parent:last").find(".down-btn").prop("disabled", true).hide();
            }

            function resetEvents() {

                $(".top-btn, .down-btn").unbind('click');

                handleEvents();

                $('.down-btn').click(function() {
                    var toMove1 = $(this).parents('.parent');

                    $(toMove1).insertAfter($(toMove1).next());

                    handleEvents();
                });

                $('.top-btn').click(function() {
                    var toMove1 = $(this).parents('.parent');

                    $(toMove1).insertBefore($(toMove1).prev());
                    handleEvents();
                });

            }

    </script>
    </body>
</html>

            resetEvents();
        }

        function saveData(){
            var count = $("#mycount").val();
            content+= '<div class="container parent><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Count:</label><div class="col-md-8 article-data">'+count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove-btn">Delete  <span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';

            $('.box').html(content);
            $('.remove-btn').click(function(){
                $(this).parents('.parent').remove();
            });
        }

        function handleEvents() {
                $(".top-btn, .down-btn").prop("disabled", false).show();
                $(".parent:first").find('.top-btn').attr('disabled','disabled');

                $(".parent:first").find(".top-btn").prop("disabled", true).hide();

                $(".parent:last").find(".down-btn").prop("disabled", true).hide();
            }

            function resetEvents() {

                $(".top-btn, .down-btn").unbind('click');

                handleEvents();

                $('.down-btn').click(function() {
                    var toMove1 = $(this).parents('.parent');

                    $(toMove1).insertAfter($(toMove1).next());

                    handleEvents();
                });

                $('.top-btn').click(function() {
                    var toMove1 = $(this).parents('.parent');

                    $(toMove1).insertBefore($(toMove1).prev());
                    handleEvents();
                });

            }

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

Body:
Each time a user selects a checkbox within a row of a table, and clicks save, it will generate a container which will hold the data in a specific format for that selected row.

Note: The data is coming in the table from JSON.

Similarly, the user will also have an option to add the data manually to the same container through a form.

Now, I all these containers or data holders will be appended to a parent container in the dom.

I need to swap each of these data containers, which I've achieved so far.
However, the buttons are not getting disabled or hidden for the first container and the last one.

Here's my script

The first data holder will not have a top one to swap with. Hence, the top button should be disabled or hidden.

Similarly, the last data holder will not have a down one to swap with. Hence, the down button should be disabled or hidden.

I'm not able to understand what's wrong with what I wrote?

Note: This works perfectly fine if I use hard-coded data holders rather than generating it on runtime.

Body:
Here's the complete code.

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
        <style>
            .parent {
                height: 25%;
                width: 90%;
                padding: 1%;
                margin-left: 1%;
                margin-top: 1%;
                border: 1px solid black;

            }

            .parent:nth-child(odd){
                background: skyblue;
            }

            .parent:nth-child(even){
                background: green;
            }

            .disabled-btn {
              cursor: not-allowed;
              opacity: 0.25%;
            }

        </style>
    </head>
    <body>
        <button class="btn btn-primary" onclick="getData()">Get data</button>
        <form>
            <label>Count: </label>
            <input type="text" placeholder="enter a count" id="mycount">
            <button onclick="saveData()">Submit</button>
        </form>
        <div class="box">

        </div>

    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script>
        var content = "";

        function getData(){

                for(var count=0; count<4; count++){

                content+= '<div class="container parent"><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Count:</label><div class="col-md-8 article-data">'+count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove-btn">Delete &nbsp;<span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';

                }
                $('.box').html(content);

            $('.remove-btn').click(function(){
                $(this).parents('.parent').remove();
            });

            resetEvents();
        }

        function saveData(){
            var count = $("#mycount").val();
            content+= '<div class="container parent"><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Count:</label><div class="col-md-8 article-data">'+count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove-btn">Delete &nbsp;<span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';

            $('.box').html(content);
            $('.remove-btn').click(function(){
                $(this).parents('.parent').remove();
            });
        }

        function handleEvents() {
                $(".top-btn, .down-btn").prop("disabled", false).show();
                $(".parent:first").find('.top-btn').attr('disabled','disabled');

                $(".parent:first").find(".top-btn").prop("disabled", true).hide();

                $(".parent:last").find(".down-btn").prop("disabled", true).hide();
            }

            function resetEvents() {

                $(".top-btn, .down-btn").unbind('click');

                handleEvents();

                $('.down-btn').click(function() {
                    var toMove1 = $(this).parents('.parent');

                    $(toMove1).insertAfter($(toMove1).next());

                    handleEvents();
                });

                $('.top-btn').click(function() {
                    var toMove1 = $(this).parents('.parent');

                    $(toMove1).insertBefore($(toMove1).prev());
                    handleEvents();
                });

            }

    </script>
    </body>
</html>

            resetEvents();
        }

        function saveData(){
            var count = $("#mycount").val();
            content+= '<div class="container parent><div class="row article-row"><div class="col-md-6 article data-col"><div class="row"><form class="form-horizontal"><div class="form-group"><label class="control-label col-md-4">Count:</label><div class="col-md-8 article-data">'+count+'</div></div></form></div></div><div class="col-md-6 article btn-col"><div class="row del-btn"><button class="btn btn-danger remove-btn">Delete &nbsp;<span class="glyphicon glyphicon-remove"></span></button></div><div class="row updown-btn"><div class="btn-group"><button class="btn btn-primary btn-sm top-btn"><span class="glyphicon glyphicon-arrow-up"></span></button><button class="btn btn-primary btn-sm down-btn"><span class="glyphicon glyphicon-arrow-down"></span></button></div></div></div></div></div>';

            $('.box').html(content);
            $('.remove-btn').click(function(){
                $(this).parents('.parent').remove();
            });
        }

        function handleEvents() {
                $(".top-btn, .down-btn").prop("disabled", false).show();
                $(".parent:first").find('.top-btn').attr('disabled','disabled');

                $(".parent:first").find(".top-btn").prop("disabled", true).hide();

                $(".parent:last").find(".down-btn").prop("disabled", true).hide();
            }

            function resetEvents() {

                $(".top-btn, .down-btn").unbind('click');

                handleEvents();

                $('.down-btn').click(function() {
                    var toMove1 = $(this).parents('.parent');

                    $(toMove1).insertAfter($(toMove1).next());

                    handleEvents();
                });

                $('.top-btn').click(function() {
                    var toMove1 = $(this).parents('.parent');

                    $(toMove1).insertBefore($(toMove1).prev());
                    handleEvents();
                });

            }

    </script>
    </body>
</html>


来源: stackexchange

问:
How to hide angular element on click event
I have a situation somewhat like this below code. I have a delete button on view cart page when it is pressed an API is called to delete the product and I just hide the product div tag to avoid page reload initially. How to hide multiple products one by one

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.hide = function(){
  //WHAT SHOULD GO HERE
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl" >

<h5 ng-click="hide()" ng-repeat="x in [0,1,2,3,4,5,6]">{{x}}<!-- HOW TO USE ng-hide HERE --></h5>

</div>

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

答:
Update your COntroller like that : </p>

```<code> var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope) {
    $scope.list=[0,1,2,3,4,5,6]
          $scope.hide = function(x){
          //WHAT SHOULD GO HERE
    $scope.list.splice(x, 1);
          }
        });

 <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>

    <div ng-app="myApp" ng-controller="myCtrl" >

    <h5 ng-click="hide($index)" ng-repeat="x in list">{{x}}</h5>

    </div>

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

ContentLicense: CC BY-SA 3.0

Body:
I have a situation somewhat like this below code. I have a delete button on view cart page when it is pressed an API is called to delete the product and I just hide the product div tag to avoid page reload initially. How to hide multiple products one by one

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.hide = function(){
  //WHAT SHOULD GO HERE
  }
});

{{x}}

Body:
Update your COntroller like that :

 var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope) {
    $scope.list=[0,1,2,3,4,5,6]
          $scope.hide = function(x){
          //WHAT SHOULD GO HERE
    $scope.list.splice(x, 1);
          }
        });

 <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>

    <div ng-app="myApp" ng-controller="myCtrl" >

    <h5 ng-click="hide($index)" ng-repeat="x in list">{{x}}</h5>

    </div>

    </body>
    </html>


问:
What's the point of a final virtual function?
Wikipedia has the following example on the C++11 final modifier:

```<code>struct Base2 {
    virtual void f() final;
};

struct Derived2 : Base2 {
    void f(); // ill-formed because the virtual function Base2::f has been marked final
};
</code>```

I don't understand the point of introducing a virtual function and immediately marking it as final. Is this simply a bad example, or is there more to it?

答:
I found another case where for virtual function is useful to be declared as final. This case is part of SonarQube list of warnings. The warning description says:

Calling an overridable member function from a constructor or destructor could result in unexpected behavior when instantiating a subclass which overrides the member function.

For example:

  - By contract, the subclass class constructor starts by calling the parent class constructor.

  - The parent class constructor calls the parent member function and not the one overridden in the child class, which is confusing for child class' developer.

  - It can produce an undefined behavior if the member function is pure virtual in the parent class.

Noncompliant Code Example

```<code>class Parent {
  public:
    Parent() {
      method1();
      method2(); // Noncompliant; confusing because Parent::method2() will always been called even if the method is overridden
    }
    virtual ~Parent() {
      method3(); // Noncompliant; undefined behavior (ex: throws a "pure virtual method called" exception)
    }
  protected:
    void         method1() { /*...*/ }
    virtual void method2() { /*...*/ }
    virtual void method3() = 0; // pure virtual
};

class Child : public Parent {
  public:
    Child() { // leads to a call to Parent::method2(), not Child::method2()
    }
    virtual ~Child() {
      method3(); // Noncompliant; Child::method3() will always be called even if a child class overrides method3
    }
  protected:
    void method2() override { /*...*/ }
    void method3() override { /*...*/ }
};
</code>```

Compliant Solution

```<code>class Parent {
  public:
    Parent() {
      method1();
      Parent::method2(); // acceptable but poor design
    }
    virtual ~Parent() {
      // call to pure virtual function removed
    }
  protected:
    void         method1() { /*...*/ }
    virtual void method2() { /*...*/ }
    virtual void method3() = 0;
};

class Child : public Parent {
  public:
    Child() {
    }
    virtual ~Child() {
      method3(); // method3() is now final so this is okay
    }
  protected:
    void method2() override { /*...*/ }
    void method3() final    { /*...*/ } // this virtual function is "final"
};
</code>```

Body:
Wikipedia has the following example on the C++11 final modifier:

struct Base2 {
    virtual void f() final;
};

struct Derived2 : Base2 {
    void f(); // ill-formed because the virtual function Base2::f has been marked final
};

I don't understand the point of introducing a virtual function and immediately marking it as final. Is this simply a bad example, or is there more to it?

Body:
I found another case where for virtual function is useful to be declared as final. This case is part of SonarQube list of warnings. The warning description says:

Calling an overridable member function from a constructor or destructor could result in unexpected behavior when instantiating a subclass which overrides the member function.

For example:

  - By contract, the subclass class constructor starts by calling the parent class constructor.

  - The parent class constructor calls the parent member function and not the one overridden in the child class, which is confusing for child class' developer.

  - It can produce an undefined behavior if the member function is pure virtual in the parent class.

Noncompliant Code Example

class Parent {
  public:
    Parent() {
      method1();
      method2(); // Noncompliant; confusing because Parent::method2() will always been called even if the method is overridden
    }
    virtual ~Parent() {
      method3(); // Noncompliant; undefined behavior (ex: throws a "pure virtual method called" exception)
    }
  protected:
    void         method1() { /*...*/ }
    virtual void method2() { /*...*/ }
    virtual void method3() = 0; // pure virtual
};

class Child : public Parent {
  public:
    Child() { // leads to a call to Parent::method2(), not Child::method2()
    }
    virtual ~Child() {
      method3(); // Noncompliant; Child::method3() will always be called even if a child class overrides method3
    }
  protected:
    void method2() override { /*...*/ }
    void method3() override { /*...*/ }
};

Compliant Solution

class Parent {
  public:
    Parent() {
      method1();
      Parent::method2(); // acceptable but poor design
    }
    virtual ~Parent() {
      // call to pure virtual function removed
    }
  protected:
    void         method1() { /*...*/ }
    virtual void method2() { /*...*/ }
    virtual void method3() = 0;
};

class Child : public Parent {
  public:
    Child() {
    }
    virtual ~Child() {
      method3(); // method3() is now final so this is okay
    }
  protected:
    void method2() override { /*...*/ }
    void method3() final    { /*...*/ } // this virtual function is "final"
};


问:
Is there an XNOR (Logical biconditional) operator in C#?
I could not find an XNOR operator to provide this truth table:

```
a  b    a XNOR b
----------------
T  T       T
T  F       F
F  T       F
F  F       T
```

Is there a specific operator for this? Or I need to use !(A^B)?

答:
You can use === operator for XNOR.
Just you need to convert a and b to bool.

```<code>if (!!a === !!b) {...}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I could not find an XNOR operator to provide this truth table:

a  b    a XNOR b
----------------
T  T       T
T  F       F
F  T       F
F  F       T

Is there a specific operator for this? Or I need to use !(A^B)?

Body:
You can use === operator for XNOR.
Just you need to convert a and b to bool.

if (!!a === !!b) {...}


问:
HTML required validation message style issue in Bootstrap from field
In my Bootstrap form field with the calendar icon and it's required. However when the error massage is showing it's going to be mess like below image.

HTML code is

```<code><div class="input-group">
     <div class="input-group-addon"><i class="fa fa-calendar"></i></div>
     <input type="text" value="" class="form-control error" name="from" id="from" required">
 </div>
</code>```

Bootstrap CSS below

```<code> .input-group-addon, .input-group-btn, .input-group .form-control {
        display: table-cell;
    }
.input-group-addon, .input-group-btn {
    vertical-align: middle;
    white-space: nowrap;
    width: 1%;
}
.input-group-addon {
    background-color: #eeeeee;
    border: 1px solid #cacaca;
    border-radius: 3px;
    color: #333333;
    font-size: 14px;
    font-weight: normal;
    line-height: 1;
    padding: 6px 12px;
    text-align: center;
}
.input-group .form-control {
    float: left;
    margin-bottom: 0;
    position: relative;
    width: 100%;
    z-index: 2;
}
</code>```

HTML5 required error

```<code><label id="from-error" class="error" for="from">This field is required.</label>
</code>```

So HTML code is like below when error occur

```<code><div class="input-group">
     <div class="input-group-addon"><i class="fa fa-calendar"></i></div>
     <input type="text" value="" class="form-control error" name="from" id="from" required">
<label id="from-error" class="error" for="from">This field is required.</label>
 </div>
</code>```

So How to fix this and set calendar Icon with in lining the field?

答:
Since all the elements inside input-group are display: table-cell, you have to provide display: table-row to the label for it to appear in new line (in a different row as in a table).

EDIT

In case, you want the error to appear exactly below the input and start right after the calendar icon, I would suggest you to use position: absolute instead.

Check edited code snippet:

.input-group-addon,
.input-group-btn,
.input-group .form-control {
  display: table-cell;
}

.input-group-addon,
.input-group-btn {
  vertical-align: middle;
  white-space: nowrap;
  width: 1%;
}

.input-group-addon {
  background-color: #eeeeee;
  border: 1px solid #cacaca;
  border-radius: 3px;
  color: #333333;
  font-size: 14px;
  font-weight: normal;
  line-height: 1;
  padding: 6px 12px;
  text-align: center;
}

.input-group .form-control {
  float: left;
  margin-bottom: 0;
  position: relative;
  width: 100%;
  z-index: 2;
}

/* #from-error {
  display: table-row;
} */

#from-error {
    position: absolute;
    bottom: -32px;
    left: 40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="input-group">
  <div class="input-group-addon"><i class="fa fa-calendar"></i></div>
  <input type="text" value="" class="form-control error" name="from" id="from" required>
  <label id="from-error" class="error" for="from">This field is required.</label>
</div></code>```

Body:
In my Bootstrap form field with the calendar icon and it's required. However when the error massage is showing it's going to be mess like below image.

HTML code is

     <input type="text" value="" class="form-control error" name="from" id="from" required">

Bootstrap CSS below

 .input-group-addon, .input-group-btn, .input-group .form-control {
        display: table-cell;
    }
.input-group-addon, .input-group-btn {
    vertical-align: middle;
    white-space: nowrap;
    width: 1%;
}
.input-group-addon {
    background-color: #eeeeee;
    border: 1px solid #cacaca;
    border-radius: 3px;
    color: #333333;
    font-size: 14px;
    font-weight: normal;
    line-height: 1;
    padding: 6px 12px;
    text-align: center;
}
.input-group .form-control {
    float: left;
    margin-bottom: 0;
    position: relative;
    width: 100%;
    z-index: 2;
}

HTML5 required error

This field is required.

So HTML code is like below when error occur

     <input type="text" value="" class="form-control error" name="from" id="from" required">
This field is required.

So How to fix this and set calendar Icon with in lining the field?

Body:
Since all the elements inside input-group are display: table-cell, you have to provide display: table-row to the label for it to appear in new line (in a different row as in a table).

EDIT

In case, you want the error to appear exactly below the input and start right after the calendar icon, I would suggest you to use position: absolute instead.

Check edited code snippet:

.input-group-addon,
.input-group-btn,
.input-group .form-control {
  display: table-cell;
}

.input-group-addon,
.input-group-btn {
  vertical-align: middle;
  white-space: nowrap;
  width: 1%;
}

.input-group-addon {
  background-color: #eeeeee;
  border: 1px solid #cacaca;
  border-radius: 3px;
  color: #333333;
  font-size: 14px;
  font-weight: normal;
  line-height: 1;
  padding: 6px 12px;
  text-align: center;
}

.input-group .form-control {
  float: left;
  margin-bottom: 0;
  position: relative;
  width: 100%;
  z-index: 2;
}

/* #from-error {
  display: table-row;
} */

#from-error {
    position: absolute;
    bottom: -32px;
    left: 40px;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="input-group">
  <div class="input-group-addon"><i class="fa fa-calendar"></i></div>
  <input type="text" value="" class="form-control error" name="from" id="from" required>
  <label id="from-error" class="error" for="from">This field is required.</label>
</div>


问:
Htaccess rewrite url and remove part from url
Hi I'm trying to do the following.

When the domain is accessed through http it should redirect to https.
When domain contains www it should redirect to https
When domain contains language abbreviation it should remove it.

Possible urls:

1: http://www.example.com/en/how-did-it-all-start

2: http://example.com/en/how-did-it-all-start

3: http://www.example.com/how-did-it-all-start

These domains should redirect with one 301 redirect to
https://example.com/how-did-it-all-start

I have tried numerous things but nothing seams to work when I'm trying to combine it with the www. It now only works for http urls, when I add the www to it, it breaks.

```<code>RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteCond %{REQUEST_URI} ^en/(.*)$ [NC]
RewriteRule ^ https://%1%/%2% [R=301,L]
</code>```

I don't know how to properly combine those to conditions without breaking it.
Tried to do in different ways but until now no success.
Any help would be appreciated.

Thanks in advance.

答:
You need to have [OR] clauses in your conditional with optional matches to handle all 3 cases:

```<code>RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(?:en/)?(.*)$ https://%1/$1 [R=301,L,NE]
</code>```

Body:
Hi I'm trying to do the following.

When the domain is accessed through http it should redirect to https.
When domain contains www it should redirect to https
When domain contains language abbreviation it should remove it.

Possible urls:

1: http://www.example.com/en/how-did-it-all-start

2: http://example.com/en/how-did-it-all-start

3: http://www.example.com/how-did-it-all-start

These domains should redirect with one 301 redirect to
https://example.com/how-did-it-all-start

I have tried numerous things but nothing seams to work when I'm trying to combine it with the www. It now only works for http urls, when I add the www to it, it breaks.

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteCond %{REQUEST_URI} ^en/(.*)$ [NC]
RewriteRule ^ https://%1%/%2% [R=301,L]

I don't know how to properly combine those to conditions without breaking it.
Tried to do in different ways but until now no success.
Any help would be appreciated.

Thanks in advance.

Body:
You need to have [OR] clauses in your conditional with optional matches to handle all 3 cases:

RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(?:en/)?(.*)$ https://%1/$1 [R=301,L,NE]


问:
Get facebook fans count using API 2.8
How to get Facebook fans count using http request in API 2.8

-- I test these requests but not working

This return an array but no Fans Count

```<code>https://graph.facebook.com/v2.8/{APP_ID}?access_token={ACCESS_TOKEN}&edges=fan_count
</code>```

Return

```<code>{
  "category": "Entertainment",
  "link": {APP LINK},
  "name": {NAME},
  "id": {ID}
}
</code>```

-- This throw an error array

```<code>https://graph.facebook.com/v2.8/{APP_ID}?access_token={ACCESS_TOKEN}&fields=likes
</code>```

Return

```<code>{
  "error": {
     "message": "(#100) Tried accessing nonexisting field (likes) on node type (Application)",
     "type": "OAuthException",
     "code": 100,
     "fbtrace_id": "FlkGoTOJ403"
  }
}
</code>```

答:
Use {PAGE_NAME} instead of {APP_ID}

```<code>GET ACCESS TOKEN: https://graph.facebook.com/oauth/access_token?client_id={APP_ID}&client_secret={APP_SECRET_KEY}&grant_type=client_credentials

GET FANS COUNT: https://graph.facebook.com/v2.8/{PAGE_NAME}?access_token={ACCESS_TOKEN}&fields=fan_count
</code>```

Thanks for luschn

Title: Get facebook fans count using API 2.8

Body:
How to get Facebook fans count using http request in API 2.8

-- I test these requests but not working

This return an array but no Fans Count

https://graph.facebook.com/v2.8/{APP_ID}?access_token={ACCESS_TOKEN}&edges=fan_count

Return

{
  "category": "Entertainment",
  "link": {APP LINK},
  "name": {NAME},
  "id": {ID}
}

-- This throw an error array

https://graph.facebook.com/v2.8/{APP_ID}?access_token={ACCESS_TOKEN}&fields=likes

Return

{
  "error": {
     "message": "(#100) Tried accessing nonexisting field (likes) on node type (Application)",
     "type": "OAuthException",
     "code": 100,
     "fbtrace_id": "FlkGoTOJ403"
  }
}

Body:
Use {PAGE_NAME} instead of {APP_ID}

GET ACCESS TOKEN: https://graph.facebook.com/oauth/access_token?client_id={APP_ID}&client_secret={APP_SECRET_KEY}&grant_type=client_credentials

GET FANS COUNT: https://graph.facebook.com/v2.8/{PAGE_NAME}?access_token={ACCESS_TOKEN}&fields=fan_count

Thanks for luschn


问:
Radio and Checkbox Inputs Not Working With scrollOverflow=true (On Mobile Only)
WHAT I AM USING?

I am using FullPage.js with scrollOverflow.

MY SETTINGS

These are my settings

```<code><script>
$(document).ready(function() {
    $('#fullpage').fullpage({
        //Navigation
        sectionsColor: ['#06C', '#C06', '#930', '#06C'],
        anchors: ['aa', 'bb', 'cc', 'dd'],
        menu: '.menu',
        navigation: true,
        scrollOverflow: false, /* True or False Depending */
        scrollBar: true,
        fixedElements: '.header',
        paddingTop: '3em',
        slidesNavigation: true,
        paddingBottom: '1em'
            });
});
</script>
</code>```

PROBLEM EXPLANATION

I have a contact form that has radio and checkboxes inputs but those inputs don't work in mobile devices with scrollOverflow equals to true. They work on desktops though.

If I chancge scrollOverflow to false the inputs work on mobile but scrollOverflow does not works which is needed because the contact form is long for mobile.

LIVE EXAMPLES

You can see scrollOverflow=true (enable) on this live example 1 but radio and checkbox inputs don't work on mobile.

https://gramerlab.com/a1.html

On these example 2 I disabled scrollOverflow=false and the radio and checkbox inputs work on mobile but the scrollOverflow don't works which is bad if the contact form is long and I need to scroll.

https://gramerlab.com/a2.html

Does anyone knows how to fix this?

答:
SOLVED

I just had to add the following lines inside my Internal Script

```<code>scrollOverflowOptions: {
   click:false,
   preventDefaultException: {tagName: /.*/}
}
</code>```

Originally I had this:

```<code><script>
$(document).ready(function() {
    $('#fullpage').fullpage({
        //Navigation
        sectionsColor: ['#06C', '#C06', '#930', '#06C'],
        anchors: ['aa', 'bb', 'cc', 'dd'],
        menu: '.menu',
        navigation: true,
        scrollOverflow: true,
        scrollBar: true,
        fixedElements: '.header',
        paddingTop: '3em',
        slidesNavigation: true,
        paddingBottom: '1em',
    });
});
</script>
</code>```

Now I have this:

```<code><script>
$(document).ready(function() {
    $('#fullpage').fullpage({
        //Navigation
        sectionsColor: ['#06C', '#C06', '#930', '#06C'],
        anchors: ['aa', 'bb', 'cc', 'dd'],
        menu: '.menu',
        navigation: true,
        scrollOverflow: true,
        scrollBar: true,
        fixedElements: '.header',
        paddingTop: '3em',
        slidesNavigation: true,
        paddingBottom: '1em',
        scrollOverflowOptions: {
            click:false,
            preventDefaultException: {tagName: /.*/}
        }
    });
});
</script>
</code>```

I tested in iPhone, Android and Kindle Fire Devices.
In all of them, the test was successful.

Body:
WHAT I AM USING?

I am using FullPage.js with scrollOverflow.

MY SETTINGS

These are my settings

PROBLEM EXPLANATION

I have a contact form that has radio and checkboxes inputs but those inputs don't work in mobile devices with scrollOverflow equals to true. They work on desktops though.

If I chancge scrollOverflow to false the inputs work on mobile but scrollOverflow does not works which is needed because the contact form is long for mobile.

LIVE EXAMPLES

You can see scrollOverflow=true (enable) on this live example 1 but radio and checkbox inputs don't work on mobile.

https://gramerlab.com/a1.html

On these example 2 I disabled scrollOverflow=false and the radio and checkbox inputs work on mobile but the scrollOverflow don't works which is bad if the contact form is long and I need to scroll.

https://gramerlab.com/a2.html

Does anyone knows how to fix this?

Body:
SOLVED

I just had to add the following lines inside my Internal Script

scrollOverflowOptions: {
   click:false,
   preventDefaultException: {tagName: /.*/}
}

Originally I had this:

<script>
$(document).ready(function() {
    $('#fullpage').fullpage({
        //Navigation
        sectionsColor: ['#06C', '#C06', '#930', '#06C'],
        anchors: ['aa', 'bb', 'cc', 'dd'],
        menu: '.menu',
        navigation: true,
        scrollOverflow: true,
        scrollBar: true,
        fixedElements: '.header',
        paddingTop: '3em',
        slidesNavigation: true,
        paddingBottom: '1em',
    });
});
</script>

Now I have this:

<script>
$(document).ready(function() {
    $('#fullpage').fullpage({
        //Navigation
        sectionsColor: ['#06C', '#C06', '#930', '#06C'],
        anchors: ['aa', 'bb', 'cc', 'dd'],
        menu: '.menu',
        navigation: true,
        scrollOverflow: true,
        scrollBar: true,
        fixedElements: '.header',
        paddingTop: '3em',
        slidesNavigation: true,
        paddingBottom: '1em',
        scrollOverflowOptions: {
            click:false,
            preventDefaultException: {tagName: /.*/}
        }
    });
});
</script>

I tested in iPhone, Android and Kindle Fire Devices.
In all of them, the test was successful.


问:
JNLP file not updated for different arguments
I'm facing several problem with JNLP file. I'm trying to disable Java from caching the JNLP file because everytime I run it, I am passing different <argument> to it... however, I can't seems to ether force it to update itself using <update check="always" policy="always"/>. I've also tried to set the Last-Modified attribute in the http response header and that didn't work either.

The jar remained the same, so I can't really use the version attribute to force it to update either...

What is the proper way to either:

Disable JNLP file caching

Force it to always updates the JNLP file

Properly pass in different arguments everytime the JNLP is launch

Here is my JNLP file, note that the <argument> can be different whenever it is launch from the web browser, the JNLP file is dynamically generated from the web:

```<code><jnlp spec="1.0+" codebase="https://blah.blah.com/jnlp/jar/*/">
  <information>
    <title>JNLP Launcher</title>
    <vendor>Blah</vendor>
    <homepage href="http://www.blah.com"/>
    <description>JNLP Launcher</description>
  </information>
  <security>
    <all-permissions/>
  </security>
  <update check="always" policy="always"/>
  <resources>
    <java href="http://java.sun.com/products/autodl/j2se" version="1.7+"/>
    <jar href="https://blah.blah.com/jnlp/jar/LauncherSigned.jar" download="eager" main="true"/>
  </resources>
  <application-desc main-class="com.blah.jnlp.Launcher">
    <argument>{"javawebstart" : "isfullofshit"}</argument>
  </application-desc>
</jnlp>
</code>```

答:
Java web start never updates JNLP file content at client machine. But it performance flawlessly if any of the resource is updated.

For example :

if you commented a helper.jar resource in jnlp file hosted on server. web start does not reflect this change to any of the client which already have the jnlp file downloaded before changes you made to server's .jnlp.

```<code>   <!--jar href="helper.jar"/-->
</code>```

But, if you completely remove the references of classes own by jar file you commented and recompiled all the resources and redeployed them.At this time, unexpectedly java web start becomes proactive and reflects all the changes you have made on the server.

Coming to your point: You are changing your .jnlp file , which means due to some mystical reasons your changes are not going to reflect to the clients .

Solution :

Approach I(Complex):

You have to somehow reflect your changes in any of the jar , so web start can pick them up .Here is a rough sketch :

1.Create a new class as a entry point to your application.

2.In this class check the last modified header of your server's .jnlp file.

3.if last modified date is something different than your local jnlp file.Then ,     simple download the jnlp file from server replace with client jnlp.

4.Restart the .jnlp file on the client .

I did this long time ago , but my requirement was simply reload the .jnlp file when application start up.So , didn't checked the last modified headed for .jnlp file.

```<code>String[] jarSequence= {"demo.jnlp"};
String codebase = "http://localhost:8818/javawsGame/";

DownloadService ds;
try {
ds =
(DownloadService)ServiceManager.lookup("javax.jnlp.DownloadService");

if (ds != null) {

URL url =
new URL(codebase + jarSequence[0]);
boolean cached = ds.isResourceCached(url, null);

if (cached) {
ds.removeResource(url, null);
}

//setMessage(msgSequence[0]);
//setLoadingResource(jarSequence[0]);
DownloadServiceListener dsl = ds.getDefaultProgressWindow();
ds.loadResource(url, null, dsl);

}
//take a breath
Thread.currentThread().sleep(3000);

Process exec = Runtime.getRuntime().exec("javaws path/to/your/demo.jnlp");
exec.waitFor();
System.exit(0);

} catch (Exception e) {

System.out.println("Exception: "+e);
}
</code>```

Approach II (Simple):

1.Clean and simple .Introduce a entry point class say "MainClassArgument.java".

2.Point your .jnlp file to this class as main class .

3.Start instance of your main class ,from this class passing the hardCoded argument to your main class

So using this approach , you need to recompile the class every time you want to change the argument.

This will trick the java web start to reflect your changes to clients immediately.

Hope this helps :)

Note : In question you asked for disabling java web start cache , this will not help as .jnlp file is not cached , It is stored at clients machine. Java Web start documentation never mentioned that it updates the .jnlp file on client side.According to web start , Updates only limited to resource updates nothing else. We have to figure out our own strategy to update out client .jnlp file.

Body:
I'm facing several problem with JNLP file. I'm trying to disable Java from caching the JNLP file because everytime I run it, I am passing different <argument> to it... however, I can't seems to ether force it to update itself using <update check="always" policy="always"/>. I've also tried to set the Last-Modified attribute in the http response header and that didn't work either.

The jar remained the same, so I can't really use the version attribute to force it to update either...

What is the proper way to either:

Disable JNLP file caching

Force it to always updates the JNLP file

Properly pass in different arguments everytime the JNLP is launch

Here is my JNLP file, note that the <argument> can be different whenever it is launch from the web browser, the JNLP file is dynamically generated from the web:

<jnlp spec="1.0+" codebase="https://blah.blah.com/jnlp/jar/*/">
  <information>
    <title>JNLP Launcher</title>
    <vendor>Blah</vendor>
    <homepage href="http://www.blah.com"/>
    <description>JNLP Launcher</description>
  </information>
  <security>
    <all-permissions/>
  </security>
  <update check="always" policy="always"/>
  <resources>
    <java href="http://java.sun.com/products/autodl/j2se" version="1.7+"/>
    <jar href="https://blah.blah.com/jnlp/jar/LauncherSigned.jar" download="eager" main="true"/>
  </resources>
  <application-desc main-class="com.blah.jnlp.Launcher">
    <argument>{"javawebstart" : "isfullofshit"}</argument>
  </application-desc>
</jnlp>

Body:
Java web start never updates JNLP file content at client machine. But it performance flawlessly if any of the resource is updated.

For example :

if you commented a helper.jar resource in jnlp file hosted on server. web start does not reflect this change to any of the client which already have the jnlp file downloaded before changes you made to server's .jnlp.

   <!--jar href="helper.jar"/-->

But, if you completely remove the references of classes own by jar file you commented and recompiled all the resources and redeployed them.At this time, unexpectedly java web start becomes proactive and reflects all the changes you have made on the server.

Coming to your point: You are changing your .jnlp file , which means due to some mystical reasons your changes are not going to reflect to the clients .

Solution :

Approach I(Complex):

You have to somehow reflect your changes in any of the jar , so web start can pick them up .Here is a rough sketch :

1.Create a new class as a entry point to your application.

2.In this class check the last modified header of your server's .jnlp file.

3.if last modified date is something different than your local jnlp file.Then ,     simple download the jnlp file from server replace with client jnlp.

4.Restart the .jnlp file on the client .

I did this long time ago , but my requirement was simply reload the .jnlp file when application start up.So , didn't checked the last modified headed for .jnlp file.

String[] jarSequence= {"demo.jnlp"};
String codebase = "http://localhost:8818/javawsGame/";

DownloadService ds;
try {
ds =
(DownloadService)ServiceManager.lookup("javax.jnlp.DownloadService");

if (ds != null) {

URL url =
new URL(codebase + jarSequence[0]);
boolean cached = ds.isResourceCached(url, null);

if (cached) {
ds.removeResource(url, null);
}

//setMessage(msgSequence[0]);
//setLoadingResource(jarSequence[0]);
DownloadServiceListener dsl = ds.getDefaultProgressWindow();
ds.loadResource(url, null, dsl);

}
//take a breath
Thread.currentThread().sleep(3000);

Process exec = Runtime.getRuntime().exec("javaws path/to/your/demo.jnlp");
exec.waitFor();
System.exit(0);

} catch (Exception e) {

System.out.println("Exception: "+e);
}

Approach II (Simple):

1.Clean and simple .Introduce a entry point class say "MainClassArgument.java".

2.Point your .jnlp file to this class as main class .

3.Start instance of your main class ,from this class passing the hardCoded argument to your main class

So using this approach , you need to recompile the class every time you want to change the argument.

This will trick the java web start to reflect your changes to clients immediately.

Hope this helps :)

Note : In question you asked for disabling java web start cache , this will not help as .jnlp file is not cached , It is stored at clients machine. Java Web start documentation never mentioned that it updates the .jnlp file on client side.According to web start , Updates only limited to resource updates nothing else. We have to figure out our own strategy to update out client .jnlp file.


问:
How to compare same column in the same table in SQL?
Let's say I have a table with following records

```<code>Name             Seq                  Join                     Resign
---------------- ---------------------------------------- ----------------------------
Joe              1                    2001-11-04 00:00:00.000  2005-03-31 00:00:00.000
Joe              2                    2005-04-01 00:00:00.000  NULL
Jane             1                    2011-12-04 00:00:00.000  2013-02-01 00:00:00.000
Jane             2                    2015-05-01 00:00:00.000  NULL
Jack             1                    2001-01-01 00:00:00.000  2002-01-01 00:00:00.000
Jack             2                    2002-01-02 00:00:00.000  2003-01-01 00:00:00.000
Jack             3                    2005-01-01 00:00:00.000  2006-01-01 00:00:00.000
Jack             4                    2006-01-02 00:00:00.000  NULL
</code>```

So I'm trying to find out Employee Join Date, Seq represents hire number, so if an Employee resign and later rejoin the company, the Seq will increase. But the problem is Seq will also increase when Employee get a promotion or move to another department.

In my case, Joe has 2 Seq but he never resigned because his 2nd Join Date = Resign Date + 1. So my final expected result is

Joe, 2001-11-04

Jane, 2015-05-01

Jack, 2005-01-01 (because he resigned after 2nd hire)

Any idea how to get this result without looping?

Note: Seq can be 1,2,3,4 and so on depends on how many promotion or resign/rejoin on each employee

Jack expected result is 2005-01-01 because from 1st hire to 2nd is not an actual resignation because 2nd hire JoinDate = 1st hire ResignDate + 1 2002-01-01 = 2002-01-02 + 1. But from 2nd hire to 3rd hire is an actually resignation because 2003-01-01 != 2005-01-01 + 1. I hope that make sense.

答:
You want the maximum join date where there is no resign date one day before.

I would do this as:

```<code>select t.name, max(t.join)
from t left join
     t tprev
     on t.join = dateadd(day, 1, tprev.resign)
where t.prev.resign is null
group by name;
</code>```

Alternatively, you can do this using seq and lag():

```<code>select name, max(join)
from (select t.*,
             lag(t.resign) over (partition by t.name order by t.seq) as prev_resign
      from t
     ) t
where prev_resign is null or prev_resign <> dateadd(day, -1, resign)
group by name;
</code>```

Body:
Let's say I have a table with following records

Name             Seq                  Join                     Resign
---------------- ---------------------------------------- ----------------------------
Joe              1                    2001-11-04 00:00:00.000  2005-03-31 00:00:00.000
Joe              2                    2005-04-01 00:00:00.000  NULL
Jane             1                    2011-12-04 00:00:00.000  2013-02-01 00:00:00.000
Jane             2                    2015-05-01 00:00:00.000  NULL
Jack             1                    2001-01-01 00:00:00.000  2002-01-01 00:00:00.000
Jack             2                    2002-01-02 00:00:00.000  2003-01-01 00:00:00.000
Jack             3                    2005-01-01 00:00:00.000  2006-01-01 00:00:00.000
Jack             4                    2006-01-02 00:00:00.000  NULL

So I'm trying to find out Employee Join Date, Seq represents hire number, so if an Employee resign and later rejoin the company, the Seq will increase. But the problem is Seq will also increase when Employee get a promotion or move to another department.

In my case, Joe has 2 Seq but he never resigned because his 2nd Join Date = Resign Date + 1. So my final expected result is

Joe, 2001-11-04

Jane, 2015-05-01

Jack, 2005-01-01 (because he resigned after 2nd hire)

Any idea how to get this result without looping?

Note: Seq can be 1,2,3,4 and so on depends on how many promotion or resign/rejoin on each employee

Jack expected result is 2005-01-01 because from 1st hire to 2nd is not an actual resignation because 2nd hire JoinDate = 1st hire ResignDate + 1 2002-01-01 = 2002-01-02 + 1. But from 2nd hire to 3rd hire is an actually resignation because 2003-01-01 != 2005-01-01 + 1. I hope that make sense.

Body:
You want the maximum join date where there is no resign date one day before.

I would do this as:

select t.name, max(t.join)
from t left join
     t tprev
     on t.join = dateadd(day, 1, tprev.resign)
where t.prev.resign is null
group by name;

Alternatively, you can do this using seq and lag():

select name, max(join)
from (select t.*,
             lag(t.resign) over (partition by t.name order by t.seq) as prev_resign
      from t
     ) t
where prev_resign is null or prev_resign <> dateadd(day, -1, resign)
group by name;


问:
Keygen tag in HTML5
So I came across this new tag in HTML5, <keygen>.  I can't quite figure out what it is for, how it is applied, and how it might affect browser behavior.

I understand that this tag is for form encryption, but what is the difference between <keygen> and having a SSL certificate for your domain. Also, what is the challenge attribute?

I'm not planning on using it as it is far from implemented in an acceptable range of browsers, but I am curious as to what EXACTLY this tag does.  All I can find is vague cookie-cutter documentation with no real examples of usage.

Edit:

I have found a VERY informative document, here. This runs through both client-side and server-side implementation of the keygen tag.

I am still curious as to what the benefit of this over a domain SSL certificate would be.

答:
Deprecated

This feature has been removed from the Web standards. Though some
  browsers may still support it, it is in the process of being dropped.
  Avoid using it and update existing code if possible. Be aware that
  this feature may cease to work at any time.

Source

Title: Keygen tag in HTML5


问:
Crittercism Cordova / Phonegap plugin spewing error: [Crittercism] warning: responseCode == 0 should be inside 100-599 for error == nil
I'm building a Cordova app and using the Crittercism plugin for error logging. I am getting a constant stream of errors when I run it from Xcode:

[Crittercism] warning: responseCode == 0 should be inside 100-599 for error == nil

I can't find anything about this in the documentation, stack overflow, the Apteligent website, et cetera. Does anyone have any idea if this is a problem?

Cordova 6.4.0
Cordova iOS 4.3.1
cordova-plugin-apteligent: 3.1.0

Thanks!

答:
Tim, we have released a new version for PhongeGap 3.3.1 as given in the below link: https://www.npmjs.com/package/cordova-plugin-apteligent

This should fix your issue. Please make sure to follow the steps given in the following doc :https://docs.apteligent.com/development_platforms/phonegap.html


问:
how to pass array in ajax call using php
I have an array like this

```Array
(
    [0] => 131

    [1] => 103

    [2] => 21

    [3] => 94

    [4] => 107

    [5] => 130

    [6] => 92

    [7] => 128

    [8] => 115

    [9] => 81
)

```

How to pass this array in ajax call

Javascript Code is:

```<code>$(document).ready(function(){
 var recentchatfriendids = [];
//actual array
 $.ajax({
    url: '/friends/message/getmessagestatus';
    data: {
        recentchatfriendids : recentchatfriendids
    },
    success: function(response){
    },
  });
});
</code>```

答:
Basically you can:

Convert the php array into a JSON string, using json_encode function, eg

$array_variable = array([0] => 131....);
echo json_encode($array_variable,true);

Then use $.ajax({...  to receive the echoed string and manipulate it.

Hope this helps...

Body:
I have an array like this

Array
(
    [0] => 131

    [1] => 103

    [2] => 21

    [3] => 94

    [4] => 107

    [5] => 130

    [6] => 92

    [7] => 128

    [8] => 115

    [9] => 81
)

How to pass this array in ajax call

Javascript Code is:

$(document).ready(function(){
 var recentchatfriendids = [];
//actual array
 $.ajax({
    url: '/friends/message/getmessagestatus';
    data: {
        recentchatfriendids : recentchatfriendids
    },
    success: function(response){
    },
  });
});


问:
swipe hours calculation in data table directly
Im working on a app where I have to work with swipe hours calculation. I have to generate a tool where it will take excel values and calculate hours for all employees in a month. I know how to handle this in sql server but I do not know how to handle directly in data table or dataset. can anybody please help me in solving this issue. uptill now my code so far is as follows.

```<code>using (var pck = new OfficeOpenXml.ExcelPackage())
    {
        using (var stream = File.OpenRead(path))
        {
            pck.Load(stream);
        }
        var ws = pck.Workbook.Worksheets.First();
        System.Data.DataTable tbl = new System.Data.DataTable();
        foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
        {
            tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
        }
        var startRow = hasHeader ? 2 : 1;
        for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
        {
            var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
            DataRow row = tbl.Rows.Add();
            foreach (var cell in wsRow)
            {
                row[cell.Start.Column - 1] = cell.Text;
            }
        }
        return tbl;
    }
if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
    dt = GetDataTableFromExcel(URL, true);
}
</code>```

From here i will get the data table as below

+-----------+---------------------+------------+
| Employeid |   Swipe dateTime    | Event type |
+-----------+---------------------+------------+
| A         | 01-01-2017 09:48:06 | IN         |
| A         | 01-01-2017 10:22:42 | OUT        |
| B         | 01-01-2017 10:22:56 | IN         |
| B         | 01-01-2017 10:36:46 | EXIT       |
| C         | 01-01-2017 10:37:04 | IN         |
| C         | 01-01-2017 12:52:57 | OUT        |
+-----------+---------------------+------------+

now my task is to calculate IN and OUT hours and get the each employee working hours per day,week and month in data table directly.

Please help me on the same.

答:
okay, so try to use the below method.

you may need to change some basic formatting or may be result table structure.

```<code>private DataTable CalculateWorkingHours(DataTable excelSheetDataTable)
{
    //Group all the data rows by user name and respective date
    var dd = excelSheetDataTable.Rows.Cast<DataRow>().GroupBy(c => new { name = c[0].ToString(), date = DateTime.Parse(c[1].ToString()).Date });

    //Create result table and some column in the table
    DataTable result = new DataTable();
    result.Columns.Add("user");
    result.Columns.Add("work hour");
    result.Columns.Add("date");

    // loop all user and their respective date in - out
    foreach (var item in dd)
    {
        // for each user each day order the record by date time.
        var sortByDateTime = item.ToList().OrderBy(c => DateTime.Parse(c[1].ToString()));

        //first in record for the day
        var fIn = sortByDateTime.FirstOrDefault(c => string.Equals(c[2].ToString(), "IN", StringComparison.InvariantCultureIgnoreCase));

        // if first in record for the day exist go further
        if (fIn != null)
        {

           // last out record for the day
            var lOut = sortByDateTime.LastOrDefault(c =>
            {
                return
                    string.Equals(c[2].ToString(), "OUT", StringComparison.InvariantCultureIgnoreCase)
                    ||
                    string.Equals(c[2].ToString(), "Exit", StringComparison.InvariantCultureIgnoreCase);
            });

            // if last out record for the day exist too..
            if (lOut != null)
            {
               // find the first enter date time, last exist date time.
                var fTime = DateTime.Parse(fIn[1].ToString());
                var lTime = DateTime.Parse(lOut[1].ToString());

                //add the new row to the result table,
                var r = result.NewRow();
                r[0] = item.Key.name;
                r[1] = (lTime - fTime).ToString(@"hh\:mm\:ss");
                r[2] = item.Key.date;

                result.Rows.Add(r);
            }
        }
    }
    return result;
}
</code>```

Body:
Im working on a app where I have to work with swipe hours calculation. I have to generate a tool where it will take excel values and calculate hours for all employees in a month. I know how to handle this in sql server but I do not know how to handle directly in data table or dataset. can anybody please help me in solving this issue. uptill now my code so far is as follows.

using (var pck = new OfficeOpenXml.ExcelPackage())
    {
        using (var stream = File.OpenRead(path))
        {
            pck.Load(stream);
        }
        var ws = pck.Workbook.Worksheets.First();
        System.Data.DataTable tbl = new System.Data.DataTable();
        foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
        {
            tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
        }
        var startRow = hasHeader ? 2 : 1;
        for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
        {
            var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
            DataRow row = tbl.Rows.Add();
            foreach (var cell in wsRow)
            {
                row[cell.Start.Column - 1] = cell.Text;
            }
        }
        return tbl;
    }
if (Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
    dt = GetDataTableFromExcel(URL, true);
}

From here i will get the data table as below

+-----------+---------------------+------------+
| Employeid |   Swipe dateTime    | Event type |
+-----------+---------------------+------------+
| A         | 01-01-2017 09:48:06 | IN         |
| A         | 01-01-2017 10:22:42 | OUT        |
| B         | 01-01-2017 10:22:56 | IN         |
| B         | 01-01-2017 10:36:46 | EXIT       |
| C         | 01-01-2017 10:37:04 | IN         |
| C         | 01-01-2017 12:52:57 | OUT        |
+-----------+---------------------+------------+

now my task is to calculate IN and OUT hours and get the each employee working hours per day,week and month in data table directly.

Please help me on the same.

Body:
okay, so try to use the below method.

you may need to change some basic formatting or may be result table structure.

private DataTable CalculateWorkingHours(DataTable excelSheetDataTable)
{
    //Group all the data rows by user name and respective date
    var dd = excelSheetDataTable.Rows.Cast<DataRow>().GroupBy(c => new { name = c[0].ToString(), date = DateTime.Parse(c[1].ToString()).Date });

    //Create result table and some column in the table
    DataTable result = new DataTable();
    result.Columns.Add("user");
    result.Columns.Add("work hour");
    result.Columns.Add("date");

    // loop all user and their respective date in - out
    foreach (var item in dd)
    {
        // for each user each day order the record by date time.
        var sortByDateTime = item.ToList().OrderBy(c => DateTime.Parse(c[1].ToString()));

        //first in record for the day
        var fIn = sortByDateTime.FirstOrDefault(c => string.Equals(c[2].ToString(), "IN", StringComparison.InvariantCultureIgnoreCase));

        // if first in record for the day exist go further
        if (fIn != null)
        {

           // last out record for the day
            var lOut = sortByDateTime.LastOrDefault(c =>
            {
                return
                    string.Equals(c[2].ToString(), "OUT", StringComparison.InvariantCultureIgnoreCase)
                    ||
                    string.Equals(c[2].ToString(), "Exit", StringComparison.InvariantCultureIgnoreCase);
            });

            // if last out record for the day exist too..
            if (lOut != null)
            {
               // find the first enter date time, last exist date time.
                var fTime = DateTime.Parse(fIn[1].ToString());
                var lTime = DateTime.Parse(lOut[1].ToString());

                //add the new row to the result table,
                var r = result.NewRow();
                r[0] = item.Key.name;
                r[1] = (lTime - fTime).ToString(@"hh\:mm\:ss");
                r[2] = item.Key.date;

                result.Rows.Add(r);
            }
        }
    }
    return result;
}


问:
Not able to convert image from url into byte array
I am new to android and I need to save image from url into db and fetch it from db. I an converting image from link into byte array but getting the following error:

Cannot Resolve ByteArrayBuffer

This is the code:

```<code> private byte[] getLogoImage(String url){
    try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = bis.read()) != -1) {
                     baf.append((byte) current);
             }

             return baf.toByteArray();
     } catch (Exception e) {
             Log.d("ImageManager", "Error: " + e.toString());
     }
     return null;
}
</code>```

答:
Try like this

```<code>Bitmap bm = null;
   InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(bis);
       byte[] imageArray = getBytes(bm);
</code>```

and after this use below method

```<code>  public static byte[] getBytes(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
    return stream.toByteArray();
}
</code>```

Body:
I am new to android and I need to save image from url into db and fetch it from db. I an converting image from link into byte array but getting the following error:

Cannot Resolve ByteArrayBuffer

This is the code:

 private byte[] getLogoImage(String url){
    try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = bis.read()) != -1) {
                     baf.append((byte) current);
             }

             return baf.toByteArray();
     } catch (Exception e) {
             Log.d("ImageManager", "Error: " + e.toString());
     }
     return null;
}

Body:
Try like this

Bitmap bm = null;
   InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(bis);
       byte[] imageArray = getBytes(bm);

and after this use below method

  public static byte[] getBytes(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
    return stream.toByteArray();
}


问:
Query with Calendar
I am trying to build a query for fetching the events from the native calendar, i have stored description with 1 word from the these 3 words: "google", "yahoo", "stackoverflow"

For example: description="google",

As of now, i have made query as below:

```<code>Cursor eventCursor = getContentResolver().query(builder.build(),
        new String[] {"event_id", "title", "begin", "end", "allDay","description" }, "Calendars._id=" + calId,
        null, "startDay ASC, startMinute ASC");
</code>```

now, i would like to make query with Description part, how do i?? of my current implementation is wrong, please show me a correct way as if you know !!!

Update:

I have done so far:

```<code>public String Fetch_Events_Detail(long From_milliseconds, String kind_website)
 {
  String event_detail = null;

  Uri.Builder builder = calendar_events_URI.buildUpon();
        //long now1 = new Date().getTime();
        ContentUris.appendId(builder, From_milliseconds);
        ContentUris.appendId(builder, From_milliseconds + DateUtils.DAY_IN_MILLIS);

       /* Cursor eventCursor = getContentResolver().query(builder.build(),
                new String[] {"event_id", "title", "begin", "end", "allDay","description" }, "Calendars._id=? and description = ?",
                new String[] { DatabaseUtils.sqlEscapeString(calId),  DatabaseUtils.sqlEscapeString(kind_website)}, "startDay ASC, startMinute ASC");
        */

        Cursor eventCursor = getContentResolver().query(builder.build(),
                new String[] {"event_id", "title", "begin", "end", "allDay","description" },"Calendars._id=" + calId,
                null, "startDay ASC, startMinute ASC");

        if(eventCursor != null)
        {

         while (eventCursor.moveToNext())
         {
            String uid2 = eventCursor.getString(0);
            String event_title = eventCursor.getString(1);
            String event_start = eventCursor.getString(2);
            String event_description = eventCursor.getString(5);

            try
            {
                // SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
             SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                Date resultdate = new Date(Long.parseLong(event_start));

                event_detail=sdf.format(resultdate)+"  "+event_title;
                event_detail.trim();

                if(event_description.trim().equalsIgnoreCase(kind_website))
                {
                 return event_detail;
                }
            }
            catch(NumberFormatException e)
            {
             Log.i("Exception raised", "");
            }
          }
        }

        return null;
 }
</code>```

Thanx

答:
```<code>Cursor eventCursor = getContentResolver().query(builder.build(),
        new String[] {"event_id", "title", "begin", "end", "allDay","description" }, "Calendars._id=? and description = ?",
        new String[] { DatabaseUtils.sqlEscapeString(calId),  DatabaseUtils.sqlEscapeString(description)}, "startDay ASC, startMinute ASC");
</code>```

Try this without calId

```<code>Cursor eventCursor = getContentResolver().query(builder.build(),
        new String[] {"event_id", "title", "begin", "end", "allDay","description" }, "description = ?",
        new String[] {DatabaseUtils.sqlEscapeString(description)}, "startDay ASC, startMinute ASC");
</code>```

ContentLicense: CC BY-SA 2.5

Title: Query with Calendar

Body:
I am trying to build a query for fetching the events from the native calendar, i have stored description with 1 word from the these 3 words: "google", "yahoo", "stackoverflow"

For example: description="google",

As of now, i have made query as below:

Cursor eventCursor = getContentResolver().query(builder.build(),
        new String[] {"event_id", "title", "begin", "end", "allDay","description" }, "Calendars._id=" + calId,
        null, "startDay ASC, startMinute ASC");

now, i would like to make query with Description part, how do i?? of my current implementation is wrong, please show me a correct way as if you know !!!

Update:

I have done so far:

public String Fetch_Events_Detail(long From_milliseconds, String kind_website)
 {
  String event_detail = null;

  Uri.Builder builder = calendar_events_URI.buildUpon();
        //long now1 = new Date().getTime();
        ContentUris.appendId(builder, From_milliseconds);
        ContentUris.appendId(builder, From_milliseconds + DateUtils.DAY_IN_MILLIS);

       /* Cursor eventCursor = getContentResolver().query(builder.build(),
                new String[] {"event_id", "title", "begin", "end", "allDay","description" }, "Calendars._id=? and description = ?",
                new String[] { DatabaseUtils.sqlEscapeString(calId),  DatabaseUtils.sqlEscapeString(kind_website)}, "startDay ASC, startMinute ASC");
        */

        Cursor eventCursor = getContentResolver().query(builder.build(),
                new String[] {"event_id", "title", "begin", "end", "allDay","description" },"Calendars._id=" + calId,
                null, "startDay ASC, startMinute ASC");

        if(eventCursor != null)
        {

         while (eventCursor.moveToNext())
         {
            String uid2 = eventCursor.getString(0);
            String event_title = eventCursor.getString(1);
            String event_start = eventCursor.getString(2);
            String event_description = eventCursor.getString(5);

            try
            {
                // SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
             SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                Date resultdate = new Date(Long.parseLong(event_start));

                event_detail=sdf.format(resultdate)+"  "+event_title;
                event_detail.trim();

                if(event_description.trim().equalsIgnoreCase(kind_website))
                {
                 return event_detail;
                }
            }
            catch(NumberFormatException e)
            {
             Log.i("Exception raised", "");
            }
          }
        }

        return null;
 }

Thanx

Body:
Cursor eventCursor = getContentResolver().query(builder.build(),
        new String[] {"event_id", "title", "begin", "end", "allDay","description" }, "Calendars._id=? and description = ?",
        new String[] { DatabaseUtils.sqlEscapeString(calId),  DatabaseUtils.sqlEscapeString(description)}, "startDay ASC, startMinute ASC");

Try this without calId

Cursor eventCursor = getContentResolver().query(builder.build(),
        new String[] {"event_id", "title", "begin", "end", "allDay","description" }, "description = ?",
        new String[] {DatabaseUtils.sqlEscapeString(description)}, "startDay ASC, startMinute ASC");


问:
dojo toggle divs based on class name
I want to toggle a content div in a container by clicking on the header. The site uses DOJO.

I have a jsfiddle here: http://jsfiddle.net/cyuwLzkf/90/

I want this behavior for all containers of the same class. I know how to do this in jquery, but not in dojo

     This is my heading

  This is the content of my message that should be hidden by default and toggled by clicking the header.

```

I'm not sure how to add the show/hide to multiple elements or how to select the content div that is inside the same container as the header that has just been clicked.
It might also be possible to add the show/hide to the container itself. If that is easier.

答:
This is fixed code form your fiddle:

require(["dojo/query", "dojo/dom", "dojo/dom-class", "dojo/on", "dojo/domReady!"],
    function(query, dom, domClass, on){

    query(".container").forEach(function(node){
 var header, content;
  header = node.getElementsByClassName("header")[0];
  content = node.getElementsByClassName("content")[0];
 on(header, "click", function(){
        domClass.contains(content, "hidden")? domClass.replace(content, "show", "hidden"):
                                         domClass.replace(content, "hidden", "show");
});
})

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.foo {
    /* add custom css */
}
.container{
  display: block;
  width: 200px;
  border: 1px solid black;
}
.container .header {
  background-color: grey;
}
.hidden {
  display: none;
}
.show {
  display: block;
}</code>```

    Add markup here

     This is my heading

      This is the content of my message that should be hidden by default and toggled by clicking the header.

 Here a second container that needs same behaviour

     This is my heading 2

      And some other content that should be hidden.

```

Title: dojo toggle divs based on class name

Body:
I want to toggle a content div in a container by clicking on the header. The site uses DOJO.

I have a jsfiddle here: http://jsfiddle.net/cyuwLzkf/90/

I want this behavior for all containers of the same class. I know how to do this in jquery, but not in dojo

     This is my heading

  This is the content of my message that should be hidden by default and toggled by clicking the header.

I'm not sure how to add the show/hide to multiple elements or how to select the content div that is inside the same container as the header that has just been clicked.
It might also be possible to add the show/hide to the container itself. If that is easier.

Body:
This is fixed code form your fiddle:

require(["dojo/query", "dojo/dom", "dojo/dom-class", "dojo/on", "dojo/domReady!"],
    function(query, dom, domClass, on){

    query(".container").forEach(function(node){
 var header, content;
  header = node.getElementsByClassName("header")[0];
  content = node.getElementsByClassName("content")[0];
 on(header, "click", function(){
        domClass.contains(content, "hidden")? domClass.replace(content, "show", "hidden"):
                                         domClass.replace(content, "hidden", "show");
});
})

});

.foo {
    /* add custom css */
}
.container{
  display: block;
  width: 200px;
  border: 1px solid black;
}
.container .header {
  background-color: grey;
}
.hidden {
  display: none;
}
.show {
  display: block;
}

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.12.1/dojo/dojo.js"></script>

<div>
    Add markup here
    <div class="container">
     <div class="header">
     This is my heading
     </div>
      <div class="content hidden">
      This is the content of my message that should be hidden by default and toggled by clicking the header.
      </div>
    </div>

    <h2> Here a second container that needs same behaviour</h2>
    <div class="container">
     <div class="header">
     This is my heading 2
     </div>
      <div class="content hidden">
      And some other content that should be hidden.
      </div>
    </div>

</div>


问:
How to enter data in the Windows Authentication pop up in Protractor?
I am writing E2E(Using Protractor) test cases for an Angular app. Whenever I hit the application URL, it asks me for Windows authentication and I am unable to enter the Username and Password in the Authentication popup. Is there any way to fill the pop-up form my test case file? Please suggest.</p>

答:
If it is basic HTTP Authentication that you are looking for - This when you see a windows pop-up when you manually open the url - You can avoid that by two ways

1.Change baseUrl = http://example.com TO baseUrl = http://username:password@example.com

Or you can have a browser.get('http://username:password@example.com')

This will do the basic HTTP Authentication for you !!!


问:
sql query to get multiplication of two rows of two different tables and insert the answer to one of the two table
I have two tables tblemployee, tblEmpSalary. I want to take the MonthlySalary form the tblEmployee and multiply it with the attendance in the tblEmpSalary and insert the answer to the tblEmpSalary table totalsalary column. Anyone kindly help me please.

```<code>tblEmployee
>EmpId
>Empname
>MonthlySalary

tblEmpSalary
>SalaryId
>EmpId
>Month
>Year
>AttendanceOfCurrentMonth
>TotalSalaryOfMonth
</code>```

I want the TotalSalaryOfMonth to be the

multiplication of MonthlySalary and AttendanceOfCurrentMonth

for each specific employee

答:
Try this </p>

```<code>UPDATE tblEmpSalary set TotalSalaryOfMonth=e.MonthlySalary*s.AttendanceOfCurrentMonth
from tblEmployee e join tblEmpSalary s ON e.empId=s.empId
</code>```

Body:
I have two tables tblemployee, tblEmpSalary. I want to take the MonthlySalary form the tblEmployee and multiply it with the attendance in the tblEmpSalary and insert the answer to the tblEmpSalary table totalsalary column. Anyone kindly help me please.

tblEmployee
>EmpId
>Empname
>MonthlySalary

tblEmpSalary
>SalaryId
>EmpId
>Month
>Year
>AttendanceOfCurrentMonth
>TotalSalaryOfMonth

I want the TotalSalaryOfMonth to be the

multiplication of MonthlySalary and AttendanceOfCurrentMonth

for each specific employee

Body:
Try this

UPDATE tblEmpSalary set TotalSalaryOfMonth=e.MonthlySalary*s.AttendanceOfCurrentMonth
from tblEmployee e join tblEmpSalary s ON e.empId=s.empId


问:
How Can I ALTER COLUMN to NOT NULL and ADD PRIMARY KEY in the same SQL
I have a column my_id which is already set as varchar(50) NULL. Now I want to alter it to NOT NULL and add it as primary key for that table. Since there is no other primary keys yet.
I have written like below.

```<code>ALTER TABLE my_details
ALTER COLUMN my_id varchar(50) NOT NULL;

ALTER TABLE my_details
ADD PRIMARY KEY (my_id);
</code>```

But I get an error:

Cannot define PRIMARY KEY constraint on nullable column in table 'my_details'. Could not create constraint. See previous errors.

How to write a single query for this?

答:
Just place a GO between two commands, to execute them separately:

```<code>ALTER TABLE my_details
ALTER COLUMN my_id varchar(50) NOT NULL;

GO

ALTER TABLE my_details
ADD PRIMARY KEY (my_id);
</code>```

Body:
I have a column my_id which is already set as varchar(50) NULL. Now I want to alter it to NOT NULL and add it as primary key for that table. Since there is no other primary keys yet.
I have written like below.

ALTER TABLE my_details
ALTER COLUMN my_id varchar(50) NOT NULL;

ALTER TABLE my_details
ADD PRIMARY KEY (my_id);

But I get an error:

Cannot define PRIMARY KEY constraint on nullable column in table 'my_details'. Could not create constraint. See previous errors.

How to write a single query for this?

Body:
Just place a GO between two commands, to execute them separately:

ALTER TABLE my_details
ALTER COLUMN my_id varchar(50) NOT NULL;

GO

ALTER TABLE my_details
ADD PRIMARY KEY (my_id);


问:
Android Studio, pass to next page if one out of two text fields are filled
So I  basically want to know how would I  allow the user to proceed to the next page when they hit pay if either txtCode or StreetCode is filled, only one of these two needs to be filled in order to pass to the next page but how would i get that to work as currently they both must filled to pass to the next page.</p>

```<code>    btnPay = (Button)findViewById(R.id.btnPay);/** REFERENCE THE PAY BUTTON*/
    btnPay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {/** SETS ONCLICKLISTENER TO LISTEN FOR BUTTON CLICK*/
            /** REFERENCES ALL VARIABLE TO FIELDS IN LAYOUT */
             txtReg = (EditText)findViewById(R.id.txtReg);
             txtCode = (EditText)findViewById(R.id.txtCode);
             txtStreetName = (EditText)findViewById(R.id.txtStreetName);

             dlCostTime = (Spinner)findViewById(R.id.dlCostTime);

            if( txtReg.getText().toString().trim().equals(""))
            {
                txtReg.setError("required!");
            }
            if( txtCode.getText().toString().trim().equals(""))
            {
                txtCode.setError("required!");
            }
            if( txtStreetName.getText().toString().trim().equals(""))
            {
                txtStreetName.setError("required!");
            }

            else{
                final Button btnPay = (Button) findViewById(R.id.btnPay);

                btnPay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent payIntent = new Intent(UserAreaActivity.this, PaymentActivity.class);// creates intent to open payment details
                        UserAreaActivity.this.startActivity(payIntent);//Performs intent to open payment page
                    }
                });

            }
</code>```

答:
Replace this code </p>

```<code> btnPay = (Button) findViewById(R.id.btnPay);/** REFERENCE THE PAY BUTTON*/
    btnPay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {/** SETS ONCLICKLISTENER TO LISTEN FOR BUTTON CLICK*/
            /** REFERENCES ALL VARIABLE TO FIELDS IN LAYOUT */
            txtReg = (EditText) findViewById(R.id.txtReg);
            txtCode = (EditText) findViewById(R.id.txtCode);
            txtStreetName = (EditText) findViewById(R.id.txtStreetName);

            dlCostTime = (Spinner) findViewById(R.id.dlCostTime);

            if (txtCode.getText().toString().trim().length() > 0 || txtStreetName.getText().toString().trim().length() > 0) {
                final Button btnPay = (Button) findViewById(R.id.btnPay);

                btnPay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent payIntent = new Intent(UserAreaActivity.this, PaymentActivity.class);// creates intent to open payment details
                        UserAreaActivity.this.startActivity(payIntent);//Performs intent to open payment page
                    }
                });
            } else if (txtStreetName.getText().toString().trim().length() == 0) {
                txtStreetName.setError("required!");
            } else if (txtReg.getText().toString().trim().length() == 0) {
                txtReg.setError("required!");
            } else if (txtCode.getText().toString().trim().length() == 0) {
                txtCode.setError("required!");
            }
        }
    }
</code>```

Body:
So I  basically want to know how would I  allow the user to proceed to the next page when they hit pay if either txtCode or StreetCode is filled, only one of these two needs to be filled in order to pass to the next page but how would i get that to work as currently they both must filled to pass to the next page.

    btnPay = (Button)findViewById(R.id.btnPay);/** REFERENCE THE PAY BUTTON*/
    btnPay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {/** SETS ONCLICKLISTENER TO LISTEN FOR BUTTON CLICK*/
            /** REFERENCES ALL VARIABLE TO FIELDS IN LAYOUT */
             txtReg = (EditText)findViewById(R.id.txtReg);
             txtCode = (EditText)findViewById(R.id.txtCode);
             txtStreetName = (EditText)findViewById(R.id.txtStreetName);

             dlCostTime = (Spinner)findViewById(R.id.dlCostTime);

            if( txtReg.getText().toString().trim().equals(""))
            {
                txtReg.setError("required!");
            }
            if( txtCode.getText().toString().trim().equals(""))
            {
                txtCode.setError("required!");
            }
            if( txtStreetName.getText().toString().trim().equals(""))
            {
                txtStreetName.setError("required!");
            }

            else{
                final Button btnPay = (Button) findViewById(R.id.btnPay);

                btnPay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent payIntent = new Intent(UserAreaActivity.this, PaymentActivity.class);// creates intent to open payment details
                        UserAreaActivity.this.startActivity(payIntent);//Performs intent to open payment page
                    }
                });

            }

Body:
Replace this code

 btnPay = (Button) findViewById(R.id.btnPay);/** REFERENCE THE PAY BUTTON*/
    btnPay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {/** SETS ONCLICKLISTENER TO LISTEN FOR BUTTON CLICK*/
            /** REFERENCES ALL VARIABLE TO FIELDS IN LAYOUT */
            txtReg = (EditText) findViewById(R.id.txtReg);
            txtCode = (EditText) findViewById(R.id.txtCode);
            txtStreetName = (EditText) findViewById(R.id.txtStreetName);

            dlCostTime = (Spinner) findViewById(R.id.dlCostTime);

            if (txtCode.getText().toString().trim().length() > 0 || txtStreetName.getText().toString().trim().length() > 0) {
                final Button btnPay = (Button) findViewById(R.id.btnPay);

                btnPay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent payIntent = new Intent(UserAreaActivity.this, PaymentActivity.class);// creates intent to open payment details
                        UserAreaActivity.this.startActivity(payIntent);//Performs intent to open payment page
                    }
                });
            } else if (txtStreetName.getText().toString().trim().length() == 0) {
                txtStreetName.setError("required!");
            } else if (txtReg.getText().toString().trim().length() == 0) {
                txtReg.setError("required!");
            } else if (txtCode.getText().toString().trim().length() == 0) {
                txtCode.setError("required!");
            }
        }
    }


问:
How to generate different headers in first page and other pages in poi word XWPF?
I want to generate different headers in first page and other pages in poi word, So I used XWPFHeaderFooterPolicy.FIRST and XWPFHeaderFooterPolicy.DEFAULT. when I using XWPFHeaderFooterPolicy.DEFAULT I can insert my header successfully, but when I change to XWPFHeaderFooterPolicy.FIRST, I cannot see there is a header in my first page, this is my code in below, what's wrong with it? thanks!  </p>

```<code>XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.FIRST);
      paragraph = header.createParagraph();
      paragraph.setAlignment(ParagraphAlignment.LEFT);
      run = paragraph.createRun();
      run.setText("header");
</code>```

答:
There is nothing in that class to tell Word to display different first page headers. You will need the most recent version of POI, and then create the header from XWPFDocument using:

```<code>XWPFDocument.createHeader(HeaderFooterType.FIRST);
</code>```

Otherwise you need to break into the CT classes and in the section properties set the titlePg property. I don't recommend this approach though as it is likely to change.

Body:
I want to generate different headers in first page and other pages in poi word, So I used XWPFHeaderFooterPolicy.FIRST and XWPFHeaderFooterPolicy.DEFAULT. when I using XWPFHeaderFooterPolicy.DEFAULT I can insert my header successfully, but when I change to XWPFHeaderFooterPolicy.FIRST, I cannot see there is a header in my first page, this is my code in below, what's wrong with it? thanks!

XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.FIRST);
      paragraph = header.createParagraph();
      paragraph.setAlignment(ParagraphAlignment.LEFT);
      run = paragraph.createRun();
      run.setText("header");

Body:
There is nothing in that class to tell Word to display different first page headers. You will need the most recent version of POI, and then create the header from XWPFDocument using:

XWPFDocument.createHeader(HeaderFooterType.FIRST);

Otherwise you need to break into the CT classes and in the section properties set the titlePg property. I don't recommend this approach though as it is likely to change.


问:
spring-data-cassandra set consistency level
I am using spring-data-cassandra (1.3.1.RELEASE) to connect to a cassandra database. Is there a way to change the consistency level in spring-data-cassandra.
By default it is level 1 (What is the default consistency level in spring-data-cassandra?). But how to change that?

Thank you!

答:
As of spring-data-cassandra release 1.5, consistency level is already configurable (see org.springframework.cassandra.core.QueryOptions#setConsistencyLevel(org.springframework.cassandra.core.ConsistencyLevel))

It may be specified as a part of QueryOptions either for a single query via org.springframework.cassandra.core.CqlOperations#execute(java.lang.String, org.springframework.cassandra.core.QueryOptions) , or for all types of queries via org.springframework.cassandra.core.CqlTemplate#addQueryOptions

Also it's possible to set consistency level via WriteOptions and then pass them to org.springframework.data.cassandra.core.CassandraOperations#insert(T, org.springframework.cassandra.core.WriteOptions)