问:
Angular ui-calendar auto refresh on form submission
i am using angular ui-calendar for displaying a series of leaves.The data for this is fed from the REST services.I can add a leave to the database also.The problem is that when i add a leave detail to the database it does not automatically reflect in the calendar.If i refresh the page the data will be reflected. Basically what I want to do is when I submit the form (closing the modal) the data to be displayed in the calendar. Thank you in advance.Following is my code
My controller

app.factory('calendarSer', ['$http', '$rootScope', 'uiCalendarConfig', function($http, $rootScope, uiCalendarConfig) {

    return {
        displayCalendar: function($scope) {

            $http.get("rest/leave/holidayList", {}).success(function(data, status, headers, config) {
                $scope.holidayList = data;
                $calendar = $('[ui-calendar]');
                var date = new Date(),
                    d = date.getDate(),
                    m = date.getMonth(),
                    y = date.getFullYear();
                $scope.changeView = function(view) {
                    $calendar.fullCalendar('changeView', view);
                };
                var m = null;
                if ($scope.selectable == "Yes") {
                    m = true;
                } else {
                    m = false;
                }
                /* config object */
                $scope.uiConfig = {
                    calendar: {
                        lang: 'da',

                        height: 400,
                        editable: true,
                        selectable: m,
                        header: {
                            left: 'month basicWeek basicDay',
                            center: 'title',
                            right: 'today prev,next'
                        },
                        eventClick: function(date, jsEvent, view) {
                            $scope.alertMessage = (date.title + ' was clicked ');
                            alert("clicked" + date.title);
                        },

                        select: function(start, end, allDay) {

                            var obj = {};
                            obj.startDate = start.toDate();
                            obj.endDate = moment(end - 1 * 24 * 3600 * 1000).format('YYYY-MM-DD');

                            $rootScope.selectionDate = obj;
                            $("#modal1").openModal();
                            //    calendar.fullCalendar('unselect');
                        },
                        dayRender: function(date, cell) {
                            var today = new Date();
                            today = moment(today).toDate();
                            var end = new Date();
                            end = moment(end).toDate();
                            end.setDate(today.getDate() + 7);
                            date = moment(date).toDate();
                            angular.forEach($scope.holidayList, function(value) {

                                if (((moment(value.holiday_date).format("YYYY-MM-DD")) == moment(date).format("YYYY-MM-DD"))) {
                                    cell.css("background-color", "#2bbbad");
                                    //$('.date').text('Today');
                                    cell.prepend("" + value.description + "");
                                    cell.prepend("
")
                                }
                            });
                        },
                        eventRender: $scope.eventRender,
                    }
                };
                console.log($scope.holidayList);
            }).error(function(data, status, headers, config) {
                alert("error from holidaylist");
            });

            $scope.events = [];
            $scope.eventSources = [$scope.events];
            $http.get($scope.url, {
                cache: true,
                params: {}
            }).then(function(data) {

                console.log(data);
                $scope.events.slice(0, $scope.events.length);
                angular.forEach(data.data, function(value) {

                    console.log(value.title);
                    if (value.approvalStatus == "Approved") {
                        var k = '#114727';
                    } else {
                        k = '#b20000'
                    }
                    $scope.events.push({
                        title: value.signum,
                        description: value.signum,
                        start: value.startDate,
                        end: value.endDate,
                        allDay: value.isHalfDay,
                        stick: true,
                        status: value.approvalStatus,
                        backgroundColor: k
                    });
                });
            });
        }
    }

}]);```
</div>
</div>
</p>

<p>g-include</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="controllerid">
   <div class="row" >
      <div class="col s10 m10 l10">
         <div id="calendar" ui-calendar="uiConfig.calendar" ng-model="eventSources" calendar="myCalendar"></div>
      </div>
   </div></code>```

Apply Leave

      <form class="col s12" id="form1">

               <input id="num" type="text" class="validate" ng-model="test.num"> num

               <input id="ename" type="text" class="validate" ng-model="test.title"> Employee Name

      <form class="col s12">

      <input id="startDate" type="text" class="validate" value="{{selectionDate.startDate | date}}" readonly  >

      <input id="endDate" type="text" class="validate"  value="{{selectionDate.endDate | date}}" readonly>

      <input type="checkbox" id="test6" ng-model="test.isHalfDay" /> Half Day

      <input id="description" type="text" class="validate" ng-model="test.description"> Description

      </form>

      <button class="btn waves-effect waves-light" type="submit" ng-click="add()" name="action"> Submit send
      </button>

```
</div>
</div>

and my add controller
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>app.controller("MyAddController", function($scope, $http,$rootScope,calendarSer) {
 $scope.test = {};
    $scope.add = function() {
     $("#modal1").closeModal();
     $scope.test1=$rootScope.selectionDate;

     var jsonData = JSON.stringify($.extend({}, $scope.test, $scope.test1));
     console.log(""+jsonData);

     $http({
         url: "rest/leave/create",
         method: "POST",
         data: jsonData,
         headers: {'Content-Type': 'application/json'}

        }).success(function(data, status, headers, config) {
            if (data) {
             console.log("Entered in the add controller");
                $scope.data = data;
                $scope.url="rest/leave/list";
               $scope.selectable="Yes";
                calendarSer.displayCalendar($scope);
                $("#popupmodal").openModal();
                console.log("Exited in the add controller");

            }
        }).error(function(data, status, headers, config) {
            alert("error from create leave");
        })
    }
});</code>```

ANy help would be appreciated

答:
In your "success" function after you run the "create" function, you can simply add the event to fullCalendar using the same data, via the built-in "renderEvent" function.

Something like this (I don't know Angular, so you may need to adjust this slightly to get your calendar element into context, but hopefully you understand the idea). I am also assuming that jsonData contains all the relevant event data which we can use for this:

```<code>.success(function(data, status, headers, config) {
            if (data) {
                console.log("Entered in the add controller");
                $scope.data = data;
                //add the event to the calendar UI without refreshing the events
                $('[ui-calendar]').fullCalendar("renderEvent",
                  {
                    start: jsonData.startDate,
                    end: jsonData.endDate,
                    title: jsonData.title
                  },
                  true //make it stick even when the view changes
               );
                $scope.url="rest/leave/list";
                $scope.selectable="Yes";
                calendarSer.displayCalendar($scope);
                $("#popupmodal").openModal();
                console.log("Exited in the add controller");
            }
</code>```

You may need to add more fields, or you may need to get momentJS to parse the values in startDate / endDate, depending exactly what those fields output.

The "renderEvent" method can be found in the fullCalendar documentation here: https://fullcalendar.io/docs/event_rendering/renderEvent/

Body:
i am using angular ui-calendar for displaying a series of leaves.The data for this is fed from the REST services.I can add a leave to the database also.The problem is that when i add a leave detail to the database it does not automatically reflect in the calendar.If i refresh the page the data will be reflected. Basically what I want to do is when I submit the form (closing the modal) the data to be displayed in the calendar. Thank you in advance.Following is my code
My controller

app.factory('calendarSer', ['$http', '$rootScope', 'uiCalendarConfig', function($http, $rootScope, uiCalendarConfig) {

    return {
        displayCalendar: function($scope) {

            $http.get("rest/leave/holidayList", {}).success(function(data, status, headers, config) {
                $scope.holidayList = data;
                $calendar = $('[ui-calendar]');
                var date = new Date(),
                    d = date.getDate(),
                    m = date.getMonth(),
                    y = date.getFullYear();
                $scope.changeView = function(view) {
                    $calendar.fullCalendar('changeView', view);
                };
                var m = null;
                if ($scope.selectable == "Yes") {
                    m = true;
                } else {
                    m = false;
                }
                /* config object */
                $scope.uiConfig = {
                    calendar: {
                        lang: 'da',

                        height: 400,
                        editable: true,
                        selectable: m,
                        header: {
                            left: 'month basicWeek basicDay',
                            center: 'title',
                            right: 'today prev,next'
                        },
                        eventClick: function(date, jsEvent, view) {
                            $scope.alertMessage = (date.title + ' was clicked ');
                            alert("clicked" + date.title);
                        },

                        select: function(start, end, allDay) {

                            var obj = {};
                            obj.startDate = start.toDate();
                            obj.endDate = moment(end - 1 * 24 * 3600 * 1000).format('YYYY-MM-DD');

                            $rootScope.selectionDate = obj;
                            $("#modal1").openModal();
                            //    calendar.fullCalendar('unselect');
                        },
                        dayRender: function(date, cell) {
                            var today = new Date();
                            today = moment(today).toDate();
                            var end = new Date();
                            end = moment(end).toDate();
                            end.setDate(today.getDate() + 7);
                            date = moment(date).toDate();
                            angular.forEach($scope.holidayList, function(value) {

                                if (((moment(value.holiday_date).format("YYYY-MM-DD")) == moment(date).format("YYYY-MM-DD"))) {
                                    cell.css("background-color", "#2bbbad");
                                    //$('.date').text('Today');
                                    cell.prepend("" + value.description + "");
                                    cell.prepend("
")
                                }
                            });
                        },
                        eventRender: $scope.eventRender,
                    }
                };
                console.log($scope.holidayList);
            }).error(function(data, status, headers, config) {
                alert("error from holidaylist");
            });

            $scope.events = [];
            $scope.eventSources = [$scope.events];
            $http.get($scope.url, {
                cache: true,
                params: {}
            }).then(function(data) {

                console.log(data);
                $scope.events.slice(0, $scope.events.length);
                angular.forEach(data.data, function(value) {

                    console.log(value.title);
                    if (value.approvalStatus == "Approved") {
                        var k = '#114727';
                    } else {
                        k = '#b20000'
                    }
                    $scope.events.push({
                        title: value.signum,
                        description: value.signum,
                        start: value.startDate,
                        end: value.endDate,
                        allDay: value.isHalfDay,
                        stick: true,
                        status: value.approvalStatus,
                        backgroundColor: k
                    });
                });
            });
        }
    }

}]);

g-include

Apply Leave

      <form class="col s12" id="form1">

               <input id="num" type="text" class="validate" ng-model="test.num"> num

               <input id="ename" type="text" class="validate" ng-model="test.title"> Employee Name

      <form class="col s12">

      <input id="startDate" type="text" class="validate" value="{{selectionDate.startDate | date}}" readonly  >

      <input id="endDate" type="text" class="validate"  value="{{selectionDate.endDate | date}}" readonly>

      <input type="checkbox" id="test6" ng-model="test.isHalfDay" /> Half Day

      <input id="description" type="text" class="validate" ng-model="test.description"> Description

      </form>

      <button class="btn waves-effect waves-light" type="submit" ng-click="add()" name="action"> Submit send
      </button>

and my add controller

app.controller("MyAddController", function($scope, $http,$rootScope,calendarSer) {
 $scope.test = {};
    $scope.add = function() {
     $("#modal1").closeModal();
     $scope.test1=$rootScope.selectionDate;

     var jsonData = JSON.stringify($.extend({}, $scope.test, $scope.test1));
     console.log(""+jsonData);

     $http({
         url: "rest/leave/create",
         method: "POST",
         data: jsonData,
         headers: {'Content-Type': 'application/json'}

        }).success(function(data, status, headers, config) {
            if (data) {
             console.log("Entered in the add controller");
                $scope.data = data;
                $scope.url="rest/leave/list";
               $scope.selectable="Yes";
                calendarSer.displayCalendar($scope);
                $("#popupmodal").openModal();
                console.log("Exited in the add controller");

            }
        }).error(function(data, status, headers, config) {
            alert("error from create leave");
        })
    }
});

ANy help would be appreciated

Body:
In your "success" function after you run the "create" function, you can simply add the event to fullCalendar using the same data, via the built-in "renderEvent" function.

Something like this (I don't know Angular, so you may need to adjust this slightly to get your calendar element into context, but hopefully you understand the idea). I am also assuming that jsonData contains all the relevant event data which we can use for this:

.success(function(data, status, headers, config) {
            if (data) {
                console.log("Entered in the add controller");
                $scope.data = data;
                //add the event to the calendar UI without refreshing the events
                $('[ui-calendar]').fullCalendar("renderEvent",
                  {
                    start: jsonData.startDate,
                    end: jsonData.endDate,
                    title: jsonData.title
                  },
                  true //make it stick even when the view changes
               );
                $scope.url="rest/leave/list";
                $scope.selectable="Yes";
                calendarSer.displayCalendar($scope);
                $("#popupmodal").openModal();
                console.log("Exited in the add controller");
            }

You may need to add more fields, or you may need to get momentJS to parse the values in startDate / endDate, depending exactly what those fields output.

The "renderEvent" method can be found in the fullCalendar documentation here: https://fullcalendar.io/docs/event_rendering/renderEvent/


来源: stackexchange

问:
Understanding how label works when elements hidden
I am trying to understand, how a can label work in conjunction with elements states like input[type="type=""]:checked or input[type=""]:unchecked.I got a very basic example which I am trying to work out, but I cannot make the label a circle or square that can have a check mark or unchecked when clicked. What makes the label have that outlook and showing checked and unchecked state? Does the label need to have a width and height? If so do I need to make it a block level element.

```<code>input[type="checkbox"]{
  width:0;
  heigh:0;
/*   or display:none? */
}
label{
  position:relative;
    width: 20px;
    height: 20px;
    cursor: pointer;
}
label:before,
label:after{
  font-size:50px;
}
label:before{
  content: '\f096'; /
   //Can be some good example
}
label:after{
  content: '\f00c';
  //Can be some good example
}
input[type="checkbox"]:checked{
  content:"check"
  //Can be some good example
}
input[type="checkbox"]:unchecked{
  content:"x"
  //Can be some good example
}
</code>```

Something achievable like this but without text next to labels as I want checkbox based on styling.

答:
If you want a custom look and behavior for your checkboxes, you'll have to use some trickery. This involves using CSS to hide your checkboxes and draw a stylable box instead + a ✔ character when your checkbox is selected.

Here's a pretty basic example :

var items = document.getElementsByClassName("item");

for (var i=0; i < items.length; i++) {
  items[i].addEventListener("click", function(){
      var checkbox = this.querySelector("input[type='checkbox']");
      checkbox.checked = checkbox.checked ? false : true;
      this.classList.toggle("selected", checkbox.checked);
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.item {
   padding: 5px 30px 5px 30px;
   display: block;
   font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
 }

 .item:hover {
   cursor: pointer;
 }

 .checker {
  border-color: #333;
  position: absolute;
  background: #fff;
  width:14px;
  height:14px;
  border: 2px solid #999;
  left: 10px;
  z-index: -5;
  display: block;
}

.selected .checker {
  border-color: #2199cb;
}

.checker input {
  height: 18px;
  width: 18px;
  opacity: 0;
  border: none;
  background: none;
}

.selected .checker:after {
  color: #ef8730;
  width: 16px;
  z-index: 99;
  font-size: 28px;
  margin-top: -40px;
  float: right;
  content: "\2714";
}</code>```

    <input type="checkbox">

  Item 1

    <input type="checkbox" checked>

  Item 2

    <input type="checkbox">

  Item 3

```

See also this JSFiddle demo

ContentLicense: CC BY-SA 3.0

Body:
I am trying to understand, how a can label work in conjunction with elements states like input[type="type=""]:checked or input[type=""]:unchecked.I got a very basic example which I am trying to work out, but I cannot make the label a circle or square that can have a check mark or unchecked when clicked. What makes the label have that outlook and showing checked and unchecked state? Does the label need to have a width and height? If so do I need to make it a block level element.

input[type="checkbox"]{
  width:0;
  heigh:0;
/*   or display:none? */
}
label{
  position:relative;
    width: 20px;
    height: 20px;
    cursor: pointer;
}
label:before,
label:after{
  font-size:50px;
}
label:before{
  content: '\f096'; /
   //Can be some good example
}
label:after{
  content: '\f00c';
  //Can be some good example
}
input[type="checkbox"]:checked{
  content:"check"
  //Can be some good example
}
input[type="checkbox"]:unchecked{
  content:"x"
  //Can be some good example
}

Something achievable like this but without text next to labels as I want checkbox based on styling.

Body:
If you want a custom look and behavior for your checkboxes, you'll have to use some trickery. This involves using CSS to hide your checkboxes and draw a stylable box instead + a ✔ character when your checkbox is selected.

Here's a pretty basic example :

var items = document.getElementsByClassName("item");

for (var i=0; i < items.length; i++) {
  items[i].addEventListener("click", function(){
      var checkbox = this.querySelector("input[type='checkbox']");
      checkbox.checked = checkbox.checked ? false : true;
      this.classList.toggle("selected", checkbox.checked);
  });
}

.item {
   padding: 5px 30px 5px 30px;
   display: block;
   font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
 }

 .item:hover {
   cursor: pointer;
 }

 .checker {
  border-color: #333;
  position: absolute;
  background: #fff;
  width:14px;
  height:14px;
  border: 2px solid #999;
  left: 10px;
  z-index: -5;
  display: block;
}

.selected .checker {
  border-color: #2199cb;
}

.checker input {
  height: 18px;
  width: 18px;
  opacity: 0;
  border: none;
  background: none;
}

.selected .checker:after {
  color: #ef8730;
  width: 16px;
  z-index: 99;
  font-size: 28px;
  margin-top: -40px;
  float: right;
  content: "\2714";
}

<div class="item">
  <label class="checker">
    <input type="checkbox">
  </label>
  Item 1
</div>
<div class="item selected">
  <label class="checker">
    <input type="checkbox" checked>
  </label>
  Item 2
</div>
<div class="item">
  <label class="checker">
    <input type="checkbox">
  </label>
  Item 3
</div>

See also this JSFiddle demo


问:
Adobe CQ: Java error- java.lang.IllegalArgumentException: could not find helper- not able to find handlebar helper
I am getting below error on Adobe CQ template while rendering a handlebar template on client-side

java.lang.IllegalArgumentException: could not find helper: 'if_gt'
  {{#if_gt data.item.num_comments 5}} ... {{/if_gt}}

Below is the handlebar template which is failing to render

```<code>{{{{rawBlock}}}}
    <ul class="comment-container"></ul>

    <script id="comment-template" type="text/x-handlebars-template">
        {{#each data.item}}
            <li class="comment-copy">
                <h2>
                    {{this.firstName}} {{this.lastName}}<span class="separator">|</span>{{this.address}}<span class="separator">|</span><time datetime="2016-10-01" pubdate="true">{{this.dateCreated}}</time>
                </h2>
                <p>{{this.content}}</p>
            </li>
        {{/each}}
    </script>
    <div class="load-more-blogs load-more"></div>
    <script id="loadmore-template" type="text/x-handlebars-template">
        {{#if_gt data.item.num_comments 5}}
            <form action="/lm/the-taste-collection/blog/loadmore/" method="post">
                <input type="hidden" name="xref_id" value="{{data.item.xref_id}}">
                <input type="hidden" name="pages" value="6-26">
                <a href="" class="submit" data-wt="true">LOAD MORE</a>
            </form>
        {{/if_gt}}
    </script>
{{{{/rawBlock}}}}
</code>```

Below is the handlebar registration code.

```<code>Handlebars.registerHelper('if_gt', function (a, b, opts) {
    if (a > b) {
        return opts.fn(this);
    } else {
        return opts.inverse(this);
    }
});
</code>```

Note: This piece of code is run on Adobe CQ 6.2 platform

答:
According to the docs the Handlebars helper must also be implemented server side as an OSGi Service.

Custom helpers must be implemented on the server-side as well as the client-side, especially when passing data.  For SCF, most templates are compiled and rendered on the server-side as the server generates the HTML for a given component when the page is requested.

https://docs.adobe.com/docs/en/aem/6-2/develop/communities/scf/handlebars-helpers.html#Server-side

Body:
I am getting below error on Adobe CQ template while rendering a handlebar template on client-side

java.lang.IllegalArgumentException: could not find helper: 'if_gt'
  {{#if_gt data.item.num_comments 5}} ... {{/if_gt}}

Below is the handlebar template which is failing to render

{{{{rawBlock}}}}

{{{{/rawBlock}}}}

Below is the handlebar registration code.

Handlebars.registerHelper('if_gt', function (a, b, opts) {
    if (a > b) {
        return opts.fn(this);
    } else {
        return opts.inverse(this);
    }
});

Note: This piece of code is run on Adobe CQ 6.2 platform


问:
Get last inserted item per day
Is there a feature in mongodb that I can use to get the last inserted item per day ? I have a collection where I need to get the last inserted item per day, the data is grouped on an hourly basis like in the structure below.

```<code>{
   timestamp: 2017-05-04T09:00:00.000+0000,
   data: {}
},
{
   timestamp: 2017-05-04T10:00:00.000+0000,
   data: {}
}
</code>```

I thought about using a projection but I am not quite sure how I could do this.

Edit: Also, since mongodb stores data in UTC, I would like to account for the offset as well.

答:
You can $sort and use $last for the item, with rounding out the grouping key to each day:

db.collection.aggregate([
  { "$sort": { "timestamp": 1 } },
  { "$group": {
     "_id": {
       "$add": [
         { "$subtract": [
           { "$subtract": [ "$timestamp", new Date(0) ] },
           { "$mod": [
             { "$subtract": [ "$timestamp", new Date(0) ] },
             1000 * 60 * 60 * 24
           ]}
         ]},
         new Date(0)
       ]
     },
     "lastDoc": { "$last": "$$ROOT" }
  }}
])
```

<p>So the sort makes things appear in order, and then the grouping <code>_id</code> is rounded for each day by some date math. You subtract the epoch date from the current date to make it a number. Use the modulus to round to a day, then add the epoch date to the number to return a <code>Date</code>.</p>

<p>So stepping through the math we have getting the timestamp value from the date with the <code>$subract</code> line. We do this a couple of times:</p>

<pre class="lang-js prettyprint-override"><code>{ "$subtract": [ "$timestamp", new Date(0) ] }

// Is roughly internally like
ISODate("2017-06-06T10:44:37.627Z") - ISODate("1970-01-01T00:00:00Z")
1496745877627
</code>```

Then there is the modulo with $mod which when applied to the numeric value returns the difference. The 1000 milliseconds * 60 seconds * 60 * minutes * 24 hours gives the other argument:

 { "$mod": [
   { "$subtract": [ "$timestamp", new Date(0) ] },
   1000 * 60 * 60 * 24
 ]}

 // Equivalent to
 1496745877627 % (1000 * 60 * 60 * 24)
 38677627
```

<p>Then there is the wrapping <code>$subtract</code> of the two numbers:</p>

<pre class="lang-js prettyprint-override"><code> { "$subtract": [
   { "$subtract": [ "$timestamp", new Date(0) ] },
   { "$mod": [
     { "$subtract": [ "$timestamp", new Date(0) ] },
     1000 * 60 * 60 * 24
   ]}
 ]}

 // Subtract "difference" of the modulo to a day
 // from the milliseconds value of the current date
 1496745877627 - 38677627

 1496707200000
</code>```

Then add back to the epoch date value to create a date rounded to the current day, which to the aggregation pipeline basically looks like providing the millisecond value to the constructor:

new Date(1496707200000)
ISODate("2017-06-06T00:00:00Z")
```

Which takes the timestamp value and subrtacts out the difference of the divisor from "one day" and ends up at the time at the "start of day".

Just using $$ROOT here to represent the whole document. But any document path provided to $last here provides the result.

Title: Get last inserted item per day

Body:
Is there a feature in mongodb that I can use to get the last inserted item per day ? I have a collection where I need to get the last inserted item per day, the data is grouped on an hourly basis like in the structure below.

{
   timestamp: 2017-05-04T09:00:00.000+0000,
   data: {}
},
{
   timestamp: 2017-05-04T10:00:00.000+0000,
   data: {}
}

I thought about using a projection but I am not quite sure how I could do this.

Edit: Also, since mongodb stores data in UTC, I would like to account for the offset as well.

Body:
You can $sort and use $last for the item, with rounding out the grouping key to each day:

db.collection.aggregate([
  { "$sort": { "timestamp": 1 } },
  { "$group": {
     "_id": {
       "$add": [
         { "$subtract": [
           { "$subtract": [ "$timestamp", new Date(0) ] },
           { "$mod": [
             { "$subtract": [ "$timestamp", new Date(0) ] },
             1000 * 60 * 60 * 24
           ]}
         ]},
         new Date(0)
       ]
     },
     "lastDoc": { "$last": "$$ROOT" }
  }}
])

So the sort makes things appear in order, and then the grouping _id is rounded for each day by some date math. You subtract the epoch date from the current date to make it a number. Use the modulus to round to a day, then add the epoch date to the number to return a Date.

So stepping through the math we have getting the timestamp value from the date with the $subract line. We do this a couple of times:

{ "$subtract": [ "$timestamp", new Date(0) ] }

// Is roughly internally like
ISODate("2017-06-06T10:44:37.627Z") - ISODate("1970-01-01T00:00:00Z")
1496745877627

Then there is the modulo with $mod which when applied to the numeric value returns the difference. The 1000 milliseconds * 60 seconds * 60 * minutes * 24 hours gives the other argument:

 { "$mod": [
   { "$subtract": [ "$timestamp", new Date(0) ] },
   1000 * 60 * 60 * 24
 ]}

 // Equivalent to
 1496745877627 % (1000 * 60 * 60 * 24)
 38677627

Then there is the wrapping $subtract of the two numbers:

 { "$subtract": [
   { "$subtract": [ "$timestamp", new Date(0) ] },
   { "$mod": [
     { "$subtract": [ "$timestamp", new Date(0) ] },
     1000 * 60 * 60 * 24
   ]}
 ]}

 // Subtract "difference" of the modulo to a day
 // from the milliseconds value of the current date
 1496745877627 - 38677627

 1496707200000

Then add back to the epoch date value to create a date rounded to the current day, which to the aggregation pipeline basically looks like providing the millisecond value to the constructor:

new Date(1496707200000)
ISODate("2017-06-06T00:00:00Z")

Which takes the timestamp value and subrtacts out the difference of the divisor from "one day" and ends up at the time at the "start of day".

Just using $$ROOT here to represent the whole document. But any document path provided to $last here provides the result.


问:
reactjs dangerouslySetInnerHTML and dynamically adding classes to links
I'm new to reactjs and working on a project that is pushing json data to the template.

json structure

```<code>"description" : "Some text with a <a href=\"/de/datenschutz\">link</a> and another <a href=\"/de/cookie-richtlinie\">link</a>",
</code>```

I propose using the following on the template

```<code><p className='paragraph-margin-bottom-10 text--font-size-14 paragraph--justified' dangerouslySetInnerHTML={{ __html: lang.privacy[0].description }} />
</code>```

but in terms of the output - I would maybe need to append a set of classes to ALL links. What is the best practice for this

so the links render with the following

```<code><a class="text--font-size-14 hyperlink-primary" href="#">link</a>
</code>```

答:
I can imagine that many people will not agree with me. You can actually do this. But you shouldn't. It is bad enough that you want to use dangerouslySetInnerHTML. It is possible to parse html but there are many edge cases that you would need to handle.

Either tell your backend that they should return the links with proper classes or target the links inside the description directly with css.

See some similar question like: Using regular expressions to parse HTML: why not?
Using regular expressions to parse HTML: why not?

This is how I would do it. I will write the regex later if you run into some problems. I don't have much time to spare right now. Hope it will help. :)

```<code>import React from 'react';
import { render } from 'react-dom';

const htmlFromApi = 'some html from API'

const attachClassesToLinks = (htmlWithLinks) => {
  // do something special
  return htmlWithLinks
}

const App = () => (
  <div>
    <h1>My Component</h1>
    <p dangerouslySetInnerHTML={{ __html: attachClassesToLinks(htmlFromApi) }} />
  </div>
);

render(<App />, document.getElementById('root'));
</code>```

Body:
I'm new to reactjs and working on a project that is pushing json data to the template.

json structure

"description" : "Some text with a link and another link",

I propose using the following on the template

but in terms of the output - I would maybe need to append a set of classes to ALL links. What is the best practice for this

so the links render with the following

link

Body:
I can imagine that many people will not agree with me. You can actually do this. But you shouldn't. It is bad enough that you want to use dangerouslySetInnerHTML. It is possible to parse html but there are many edge cases that you would need to handle.

Either tell your backend that they should return the links with proper classes or target the links inside the description directly with css.

See some similar question like: Using regular expressions to parse HTML: why not?
Using regular expressions to parse HTML: why not?

This is how I would do it. I will write the regex later if you run into some problems. I don't have much time to spare right now. Hope it will help. :)

import React from 'react';
import { render } from 'react-dom';

const htmlFromApi = 'some html from API'

const attachClassesToLinks = (htmlWithLinks) => {
  // do something special
  return htmlWithLinks
}

const App = () => (
  <div>
    <h1>My Component</h1>
    <p dangerouslySetInnerHTML={{ __html: attachClassesToLinks(htmlFromApi) }} />
  </div>
);

render(<App />, document.getElementById('root'));


问:
Is number recognition on iPhone possible in real-time?
I need to recognise numbers from the camera image on iPhone, in real-time. I know there will be no more than 5 digits on the image.

Is this problem realistic to solve given the computational specifications of the iPhone?
Does anyone have any experience using the Tesseract OCR library, and do you think it could be solved by using it?

答:
There is free SDK for that: http://rtrsdk.com/ Supports both iOS and Andorid, works in real-time, helps you capture any text, numbers should not be a problem.

Disclaimer: I work for ABBYY

ContentLicense: CC BY-SA 2.5


问:
How to format and convert varchar to datetime in mysql
I need to cast a varchar to a datetime so i can find out max and min values. The varchar that i have is like this format:  'Mon, 24 May 2010 21:24:39 +0000' and I need to cast to: '2010-05-24 21:24:39'. I am using mysql server. Need help.</p>

答:
```<code>SELECT STR_TO_DATE(Myvarchar, '%a, %d %b %Y %T') FROM table1
</code>```

This will turn it into a format in the column with which you can then run less than and greater than, min and max queries. You can run queries on it leaving it as a string but it will of course have less performance than a new column with the proper datetime type in it rather than a varchar. You won't notice a performance problem though if there are not too many rows.

So you might end up running this:

```<code>SELECT MAX(STR_TO_DATE(Myvarchar, '%a, %d %b %Y %T')) FROM table1
</code>```

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date

Body:
SELECT STR_TO_DATE(Myvarchar, '%a, %d %b %Y %T') FROM table1

This will turn it into a format in the column with which you can then run less than and greater than, min and max queries. You can run queries on it leaving it as a string but it will of course have less performance than a new column with the proper datetime type in it rather than a varchar. You won't notice a performance problem though if there are not too many rows.

So you might end up running this:

SELECT MAX(STR_TO_DATE(Myvarchar, '%a, %d %b %Y %T')) FROM table1

https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_str-to-date


问:
JQuery bind on multiple same name ID
I have one table generated by PHP

```<code><div class="mailbox-list">
    <ul>
    <?php while ($row=$database->fetch_array($result)){?>
        <li id="emal_new" name="<?php echo $row["id"];?>">
            <a href="#" >
            <div class="mail-checkbox">
                <input class="filled-in" id="<?php echo $row["id"];?>" type="checkbox">
                <label for="<?php echo $row["id"];?>"></label>
            </div>
            <h5 class="mail-author">VPN Access Manager</h5>
            <h4 class="mail-title"><?php echo $row["naslov"]; ?></h4>
            <p class="hide-on-small-and-down mail-text">
            <?php $poruka_kratka = clear_mail($row['poruka']);
            echo text($poruka_kratka,"75")?></p>
            <div class="position-top-right p f-12 mail-date"><?php echo $row["datum"]; ?></div>

            </a>
        <div id ="user-result" />
        </li>

    <?php }?>
    </ul>
</div>
</code>```

And my JQCODE is:

```<code><script>
$(document).ready(function() {
var x_timer;
$("#emal_new").bind('click', function (e){
clearTimeout(x_timer);
var email_id = $(this).attr("name");
x_timer = setTimeout(function(){
check_email_id_ajax(email_id);
}, 100);
});

function check_email_id_ajax(email_id){
$("#user-result").html('<img style="width: 24px; height:24px;" src="<?php echo WWW; echo 'includes/themes/'.THEME_NAME.'';?>/img/ajax.gif" />');
$.post('ajax/mailbox.php',{'email_id':email_id}, function(data) {
$("#user-result").html(data);
});
}

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

And i have about 30 and more data in table and only first at table works with that jquery bind? How can bind work on all
 objects?

I need when i click on some row in table call ajax for more information about that row called by name.

Thanks!

答:
This is expected behaviors as Identifiers in HTML must be unique, Use a common class to bind event handlers, also I would recommend you to use data-* prefix custom attribute to store arbitary data, which can be accessed using .data()

Change the HTML as

```<code> <li class="emal_new" data-name="<?php echo $row["id"];?>">
     <div class="user-result"></div>
 </li>
</code>```

Script

```<code>$(document).ready(function() {
    var x_timer;
    $(".emal_new").on('click', function(e) {

        var email_id = $(this).data("name");
      var userResult = $(this).find('.user-result')

        if (x_timer)
            clearTimeout(x_timer);
        x_timer = setTimeout(function() {
            check_email_id_ajax(email_id);
        }, 100);
    });

    function check_email_id_ajax(userResult, email_id) {
        userResult.html(TheHTML);

        $.post('ajax/mailbox.php', {
            'email_id': email_id
        }, function(data) {
            userResult.html(data);
        });
    }
});
</code>```

Also not .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7

Title: JQuery bind on multiple same name ID

Body:
I have one table generated by PHP

    <?php while ($row=$database->fetch_array($result)){?>
        <li id="emal_new" name="<?php echo $row["id"];?>">

                <input class="filled-in" id="<?php echo $row["id"];?>" type="checkbox">
                <label for="<?php echo $row["id"];?>">

VPN Access Manager

<?php echo $row["naslov"]; ?>

            <?php $poruka_kratka = clear_mail($row['poruka']);
            echo text($poruka_kratka,"75")?>

<?php echo $row["datum"]; ?>

    <?php }?>

And my JQCODE is:

And i have about 30 and more data in table and only first at table works with that jquery bind? How can bind work on all
 objects?

I need when i click on some row in table call ajax for more information about that row called by name.

Thanks!

Body:
This is expected behaviors as Identifiers in HTML must be unique, Use a common class to bind event handlers, also I would recommend you to use data-* prefix custom attribute to store arbitary data, which can be accessed using .data()

Change the HTML as

 <li class="emal_new" data-name="<?php echo $row["id"];?>">
     <div class="user-result"></div>
 </li>

Script

$(document).ready(function() {
    var x_timer;
    $(".emal_new").on('click', function(e) {

        var email_id = $(this).data("name");
      var userResult = $(this).find('.user-result')

        if (x_timer)
            clearTimeout(x_timer);
        x_timer = setTimeout(function() {
            check_email_id_ajax(email_id);
        }, 100);
    });

    function check_email_id_ajax(userResult, email_id) {
        userResult.html(TheHTML);

        $.post('ajax/mailbox.php', {
            'email_id': email_id
        }, function(data) {
            userResult.html(data);
        });
    }
});

Also not .bind() has been deprecated. It was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7


问:
Centering a Label vertically in a horizontal layout
I am having a bit of a problem with centering my QLabel vertically within a QHBoxLayout. The relevant piece of my code is below:

```<code>QFrame* topBar = new QFrame();
topBar->setStyleSheet("background-color: #2c3d50;border-bottom: 3px solid #2c92b6;");
topBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
topBar->setFixedHeight(24);

QHBoxLayout* topBarLayout = new QHBoxLayout();
    QLabel* label = new QLabel("MSFT");
    label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
    label->setStyleSheet("font-size: 15px;font-weight: bold;border: 0px;");
    label->setMinimumHeight(15);
    topBarLayout->addWidget(label);

topBar->setLayout(topBarLayout);
topLayout->addWidget(topBar);
</code>```

My local goal is to have the label vertically centered. What I tried:

Qt::AlignVCenter - had no impact

QSizePolicy::PreferredSize and QSizePolicy::Expanding caused the label to be vertically shrunk without minimumHeight/fixedHeight, where I hoped it to expand freely to the height of the parent

Changing the minimumHeight or adding padding/margin:, which only continue to move the QLabel downwards.

My ultimate goal is to create a bar (that dark blue thing in the photo) of fixed height and variable width, with labels and buttons (e.g. caption, close, maximize etc.) aligned on the both sides, regardless of the bar's width.

Internets say that adding yet another QBoxLayout to center the Label vertically could solve the problem, but I will be adding lots of components to that bar, so this "solution" would be very impractical.

TL;DR: How does one align a Label (or simply its text) vertically within a horizontal layout?

答:
Try to change top/bottom margins of the layout and keep Qt::AlignVCenter:

```<code>topBarLayout->setContentsMargins(9,0,9,5);
</code>```

Body:
I am having a bit of a problem with centering my QLabel vertically within a QHBoxLayout. The relevant piece of my code is below:

QFrame* topBar = new QFrame();
topBar->setStyleSheet("background-color: #2c3d50;border-bottom: 3px solid #2c92b6;");
topBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
topBar->setFixedHeight(24);

QHBoxLayout* topBarLayout = new QHBoxLayout();
    QLabel* label = new QLabel("MSFT");
    label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
    label->setStyleSheet("font-size: 15px;font-weight: bold;border: 0px;");
    label->setMinimumHeight(15);
    topBarLayout->addWidget(label);

topBar->setLayout(topBarLayout);
topLayout->addWidget(topBar);

My local goal is to have the label vertically centered. What I tried:

Qt::AlignVCenter - had no impact

QSizePolicy::PreferredSize and QSizePolicy::Expanding caused the label to be vertically shrunk without minimumHeight/fixedHeight, where I hoped it to expand freely to the height of the parent

Changing the minimumHeight or adding padding/margin:, which only continue to move the QLabel downwards.

My ultimate goal is to create a bar (that dark blue thing in the photo) of fixed height and variable width, with labels and buttons (e.g. caption, close, maximize etc.) aligned on the both sides, regardless of the bar's width.

Internets say that adding yet another QBoxLayout to center the Label vertically could solve the problem, but I will be adding lots of components to that bar, so this "solution" would be very impractical.

TL;DR: How does one align a Label (or simply its text) vertically within a horizontal layout?

Body:
Try to change top/bottom margins of the layout and keep Qt::AlignVCenter:

topBarLayout->setContentsMargins(9,0,9,5);


问:
RecyclewView with nested gridView adjust height
I'm trying to create this view:

It´s Rerecyclew with a Gridview for each item.
So when you press the plus item I've to add a new item to the Gridview and adjust the RecyclewView item height.

But i can't make it with a wrap_content and i don´t know why.

Activity Layout

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_scenes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</LinearLayout>
</code>```

RecyclewView Item

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <GridView
        android:id="@+id/gv_scene_items"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:gravity="center"
        android:columnWidth="50dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#eaeaea" />

</LinearLayout>
</code>```

GridView Item (just for example)

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="@color/liloColorBlue">

</LinearLayout>
</code>```

Can you help me to get the example view?

Thank you.

答:
You can do this very easily.
Change the recyclerView height in xml to:

```<code><android.support.v7.widget.RecyclerView
    android:id="@+id/rv_scenes"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical" />
</code>```

This will automatically adjust the layouts.

Hope this helps.

Body:
I'm trying to create this view:

It´s Rerecyclew with a Gridview for each item.
So when you press the plus item I've to add a new item to the Gridview and adjust the RecyclewView item height.

But i can't make it with a wrap_content and i don´t know why.

Activity Layout

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_scenes"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</LinearLayout>

RecyclewView Item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <GridView
        android:id="@+id/gv_scene_items"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:gravity="center"
        android:columnWidth="50dp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#eaeaea" />

</LinearLayout>

GridView Item (just for example)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="@color/liloColorBlue">

</LinearLayout>

Can you help me to get the example view?

Thank you.

Body:
You can do this very easily.
Change the recyclerView height in xml to:

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv_scenes"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical" />

This will automatically adjust the layouts.

Hope this helps.


问:
python, index errors
I've got some code which draws data from an xml file but it seems to have randomly starting throwing;

```<code>Traceback (most recent call last):
  File "C:\Users\mike\Documents\python\arl xml\turn 24 reader", line 52, in <module>
    unitCount   = getText(evoNode.getElementsByTagName("count")[0].childNodes)
IndexError: list index out of range
</code>```

it was fine for the first couple of times I ran it then, I dunno if I changed it or not by accident, but now it's throwing the error.

This is an example of the section of the xml it's trying to use;

```<code>- <unit>
  <count>1200</count>
  <type>Zweihander Doppelsoldners</type>
  <typeid>102</typeid>
  </unit>
</code>```

and here's the code that it's complains about;

```<code>   for unitNode in node.getElementsByTagName('unit'):
      unitName      = getText(evoNode.getElementsByTagName("type")[0].childNodes)
      unitId     = getText(evoNode.getElementsByTagName("typeid")[0].childNodes)
      unitCount   = getText(evoNode.getElementsByTagName("count")[0].childNodes)

      unitList.append("%s x %s" % (unitName, unitCount))
</code>```

While I accept that it complains about the count line first because count is the highest of the three on the xml file in the units section I'm still not sure why it's complaining, given that it succesfully runs a very similar set of code from which that was cloned and editted.

Anyone know what I can do or can suggest ways to refine the question?

答:
As gimel said you should check getElementsByTagName("count") if it returns non empty list, but back to your problem:

If you said that it was working before then my guess that the problem is with the source where you get the XML.

Title: python, index errors

Body:
I've got some code which draws data from an xml file but it seems to have randomly starting throwing;

Traceback (most recent call last):
  File "C:\Users\mike\Documents\python\arl xml\turn 24 reader", line 52, in <module>
    unitCount   = getText(evoNode.getElementsByTagName("count")[0].childNodes)
IndexError: list index out of range

it was fine for the first couple of times I ran it then, I dunno if I changed it or not by accident, but now it's throwing the error.

This is an example of the section of the xml it's trying to use;

- <unit>
  <count>1200</count>
  <type>Zweihander Doppelsoldners</type>
  <typeid>102</typeid>
  </unit>

and here's the code that it's complains about;

   for unitNode in node.getElementsByTagName('unit'):
      unitName      = getText(evoNode.getElementsByTagName("type")[0].childNodes)
      unitId     = getText(evoNode.getElementsByTagName("typeid")[0].childNodes)
      unitCount   = getText(evoNode.getElementsByTagName("count")[0].childNodes)

      unitList.append("%s x %s" % (unitName, unitCount))

While I accept that it complains about the count line first because count is the highest of the three on the xml file in the units section I'm still not sure why it's complaining, given that it succesfully runs a very similar set of code from which that was cloned and editted.

Anyone know what I can do or can suggest ways to refine the question?

OwnerDisplayName: Maiku Mori


问:
c# how to clear textboxes of user control from main form
I have one form which contain the my user control. How to clear all then textbox of that user control using a button in my main form?## Heading ##</p>

答:
You can use this method to clear all TextBoxes, just call it from your main form:</p>

```<code>public void ClearTextBoxes(bool searchRecursively = true)
{
    Action<Control.ControlCollection, bool> clearTextBoxes = null;
    clearTextBoxes = (controls, searchChildren) =>
    {
        foreach (Control c in controls)
        {
            TextBox txt = c as TextBox;
            txt?.Clear();
            if (searchChildren && c.HasChildren)
                clearTextBoxes(c.Controls, true);
        }
    };

    clearTextBoxes(this.Controls, searchRecursively);
}
</code>```

Body:
You can use this method to clear all TextBoxes, just call it from your main form:

public void ClearTextBoxes(bool searchRecursively = true)
{
    Action<Control.ControlCollection, bool> clearTextBoxes = null;
    clearTextBoxes = (controls, searchChildren) =>
    {
        foreach (Control c in controls)
        {
            TextBox txt = c as TextBox;
            txt?.Clear();
            if (searchChildren && c.HasChildren)
                clearTextBoxes(c.Controls, true);
        }
    };

    clearTextBoxes(this.Controls, searchRecursively);
}


问:
Using adaptive grammars
I'm trying to implement a language (or family of languages) whose grammar can be changed dynamically. I have found no examples that serve as study cases.

Can you give me some reference to any that are actually used in the real world (even from the academic world)?

Does it make sense to implement a Domain-Specific Languages with a dynamic grammar?

答: Katahdin is an obvious choice. There is also PFront, and good old parsing macros in Common Lisp as well.</p>

Title: Using adaptive grammars


问:
mbenford/ngTagsInput Multiple tags without key property
I am trying to use mbenford/ngTagsInput directive as below

```<code><tags-input name="skill" ng-model="storage.skills" placeholder="specializations"
min-tags="1" add-on-enter="true" min-length="1" key-property="id" display-property="name" required>
    <auto-complete source="getSkillSearch($query)" highlight-matched-text="true" min-length="1"></auto-complete>
</tags-input>
</code>```

Here if you see i have set the key property as id, when i add new tags(which does not have the key property), the directive does not allow me to do so more than once .

https://github.com/mbenford/ngTagsInput/issues/509 (Something very similar), but no solution to this. Is their a workaround or i am missing something very silly.

答:
There is a property called onTagAdding. Provide a function that creates an id for the tag on adding. Here's an example:

HTML

```<code><tags-input name="skill" ng-model="storage.skills" placeholder="specializations"
min-tags="1" add-on-enter="true" min-length="1" key-property="id" display-property="name" on-tag-adding="createId($tag)" required>
<auto-complete source="getSkillSearch($query)" highlight-matched-text="true" min-length="1"></auto-complete>
</tags-input>
</code>```

SCRIPT

```<code>$scope.createId= function(tag) {
    // Only do this if tag.id is undefined
    if(angular.isUndefined(tag.id) {
       tag.id= tag.name; // or create a random value
    }
};
</code>```

Body:
I am trying to use mbenford/ngTagsInput directive as below

<tags-input name="skill" ng-model="storage.skills" placeholder="specializations"
min-tags="1" add-on-enter="true" min-length="1" key-property="id" display-property="name" required>
    <auto-complete source="getSkillSearch($query)" highlight-matched-text="true" min-length="1"></auto-complete>
</tags-input>

Here if you see i have set the key property as id, when i add new tags(which does not have the key property), the directive does not allow me to do so more than once .

https://github.com/mbenford/ngTagsInput/issues/509 (Something very similar), but no solution to this. Is their a workaround or i am missing something very silly.

Body:
There is a property called onTagAdding. Provide a function that creates an id for the tag on adding. Here's an example:

HTML

<tags-input name="skill" ng-model="storage.skills" placeholder="specializations"
min-tags="1" add-on-enter="true" min-length="1" key-property="id" display-property="name" on-tag-adding="createId($tag)" required>
<auto-complete source="getSkillSearch($query)" highlight-matched-text="true" min-length="1"></auto-complete>
</tags-input>

SCRIPT

$scope.createId= function(tag) {
    // Only do this if tag.id is undefined
    if(angular.isUndefined(tag.id) {
       tag.id= tag.name; // or create a random value
    }
};


问:
Angular 2: how to update service variable in a module's component so that the variable in lazy module updates automatically?
Below is a link to project on Plunker. where there are two components eager and lazy, also there is shared service which is used on both components.

How to update service variable in a module's component so that the variable in lazy module updates automatically?

```<code>[Plunker example][1]
[1]: https://plnkr.co/edit/L2ypUQZiltSPXnLlxBoa?p=preview
</code>```

答:
You have this behavior because of child injector created new instance of the service. For creating one instance of the service for application, you should use .forRoot() method

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SomeComponent } from './other.component';
import { SharedModule } from './shared/index'
import { SomeService } from './some.service';

@NgModule({
  imports: [CommonModule, SharedModule],
  declarations: [ SomeComponent ],
  exports: [ SomeComponent ]
})
export class OtherModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      // here you put services to share
      providers: [SomeService]
    }
  }
}

// and in AppModule
@NgModule({
  imports: [
    CommonModule,
    SharedModule,
    OtherModule.forRoot()
  ],
  declarations: [ SomeComponent ],
  exports: [ SomeComponent ]
})```

It will allow you to use one instance of SomeService in your components.

I've updated your plunker. Pleas, have a look on changed example

Body:
Below is a link to project on Plunker. where there are two components eager and lazy, also there is shared service which is used on both components.

How to update service variable in a module's component so that the variable in lazy module updates automatically?

[Plunker example][1]
[1]: https://plnkr.co/edit/L2ypUQZiltSPXnLlxBoa?p=preview

Body:
You have this behavior because of child injector created new instance of the service. For creating one instance of the service for application, you should use .forRoot() method

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';

import { SomeComponent } from './other.component';
import { SharedModule } from './shared/index'
import { SomeService } from './some.service';

@NgModule({
  imports: [CommonModule, SharedModule],
  declarations: [ SomeComponent ],
  exports: [ SomeComponent ]
})
export class OtherModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      // here you put services to share
      providers: [SomeService]
    }
  }
}

// and in AppModule
@NgModule({
  imports: [
    CommonModule,
    SharedModule,
    OtherModule.forRoot()
  ],
  declarations: [ SomeComponent ],
  exports: [ SomeComponent ]
})

It will allow you to use one instance of SomeService in your components.

I've updated your plunker. Pleas, have a look on changed example


问:
How I can give a link to the caption of audio post on the wall
Hey!! I have made an application through which I am publishing an audio file to the wall in facebook. Further I want to give a clickable caption, that when get a click take me to some url. Can somebdy plz help me in sorting it out....

Thanx in advance...!

答:
You need to send media as an attachment with your publish request.

```<code>{"media": [{
    "type": "music",
    "src": "URL_OF_MEDIA",
    "title": "NAME_OF_AUDIO_CLIP",
    "artist": "ARTIST",
    "album": "ALBUM"
}]}
</code>```

Docs here: http://developers.facebook.com/docs/guides/attachments

Body:
You need to send media as an attachment with your publish request.

{"media": [{
    "type": "music",
    "src": "URL_OF_MEDIA",
    "title": "NAME_OF_AUDIO_CLIP",
    "artist": "ARTIST",
    "album": "ALBUM"
}]}

Docs here: http://developers.facebook.com/docs/guides/attachments


问:
Detecting variations in a data set
I have a data set with this structure:

ContractNumber | MonthlyPayment | Duration | StartDate | EndDate

One contract number can occur many times as this data set is a consolidation of different reports with the same structure.

Now I want to filter / find the contract numbers in which MonthlyPayment and/or Duration and/or StartDate and/or EndDate differ.

Example (note that Contract Number is not a Primary key):

```<code>ContractNumber | MonthlyPayment | Duration | StartDate  | EndDate
           001 |            500 |       12 | 01.01.2015 | 31.12.2015
           001 |            500 |       12 | 01.01.2015 | 31.12.2015
           001 |            500 |       12 | 01.01.2015 | 31.12.2015
           002 |           1500 |       24 | 01.01.2014 | 31.12.2017
           002 |           1500 |       24 | 01.01.2014 | 31.12.2017
           002 |           1500 |       24 | 01.01.2014 | 31.12.2018
</code>```

With this sample data set, I would need to retrieve 002 with a specific query. 001 is the the same and does not Change, but 002 changes over time.

Besides of writing a VBA script running over an Excel, I don't have any solid idea on how to solve this with SQL

My first idea would be a SQL Approach with grouping, where same values are grouped together, but not the different ones. I am currently experimenting on this one. My attempt is currently:

1.) Have the usual table

2.) Create a second table / query with this structure:

ContractNumber | AVG(MonthlyPayment) | AVG(Duration) | AVG(StartDate) | AVG(EndDate)

Which I created with Grouping.

E.G.

Table 1.)

```<code>ContractNumber | MonthlyPayment
             1 | 10
             1 | 10
             1 | 20
             2 | 300
             2 | 300
             2 | 300
</code>```

Table 2.)

```<code>ContractNumber | AVG(MonthlyPayment)
             1 | 13.3
             2 | 300
</code>```

3) Now I want to find the distinct contract number where - in this example only the MonthlyPayment - does not equal to the average (it should be the same - otherwise we have a variation which I need to find).

Do you have any idea how I could solve this? I would otherwise start writing a VBA or Python script. I have the data set in CSV, so for now I could also do it with MySQL, Power Bi or Excel.

I need to perform this Analysis once, so I would not Need a full approach, so the queries can be splitted into different steps.

Very appreciated! Thank you very much.

答:
To find all contract numbers with differences, use:</p>

```<code>select ContractNumber
from
(
select distinct ContractNumber,  MonthlyPayment , Duration , StartDate , EndDate
from MyTable
) x
group by ContractNumber
having count(*) >1
</code>```

Title: Detecting variations in a data set

Body:
I have a data set with this structure:

ContractNumber | MonthlyPayment | Duration | StartDate | EndDate

One contract number can occur many times as this data set is a consolidation of different reports with the same structure.

Now I want to filter / find the contract numbers in which MonthlyPayment and/or Duration and/or StartDate and/or EndDate differ.

Example (note that Contract Number is not a Primary key):

ContractNumber | MonthlyPayment | Duration | StartDate  | EndDate
           001 |            500 |       12 | 01.01.2015 | 31.12.2015
           001 |            500 |       12 | 01.01.2015 | 31.12.2015
           001 |            500 |       12 | 01.01.2015 | 31.12.2015
           002 |           1500 |       24 | 01.01.2014 | 31.12.2017
           002 |           1500 |       24 | 01.01.2014 | 31.12.2017
           002 |           1500 |       24 | 01.01.2014 | 31.12.2018

With this sample data set, I would need to retrieve 002 with a specific query. 001 is the the same and does not Change, but 002 changes over time.

Besides of writing a VBA script running over an Excel, I don't have any solid idea on how to solve this with SQL

My first idea would be a SQL Approach with grouping, where same values are grouped together, but not the different ones. I am currently experimenting on this one. My attempt is currently:

1.) Have the usual table

2.) Create a second table / query with this structure:

ContractNumber | AVG(MonthlyPayment) | AVG(Duration) | AVG(StartDate) | AVG(EndDate)

Which I created with Grouping.

E.G.

Table 1.)

ContractNumber | MonthlyPayment
             1 | 10
             1 | 10
             1 | 20
             2 | 300
             2 | 300
             2 | 300

Table 2.)

ContractNumber | AVG(MonthlyPayment)
             1 | 13.3
             2 | 300

3) Now I want to find the distinct contract number where - in this example only the MonthlyPayment - does not equal to the average (it should be the same - otherwise we have a variation which I need to find).

Do you have any idea how I could solve this? I would otherwise start writing a VBA or Python script. I have the data set in CSV, so for now I could also do it with MySQL, Power Bi or Excel.

I need to perform this Analysis once, so I would not Need a full approach, so the queries can be splitted into different steps.

Very appreciated! Thank you very much.

Body:
To find all contract numbers with differences, use:

select ContractNumber
from
(
select distinct ContractNumber,  MonthlyPayment , Duration , StartDate , EndDate
from MyTable
) x
group by ContractNumber
having count(*) >1


问:
trouble getting cv.transform to work
I'd like to use the same affine matrix M on some individual (x,y) points as I use on images with cv2.warpAffine. It seems cv2.transform is the way to go .  When I try send an Nx2 matrix of points I get negged (

```<code>   src = np.array([
        [x1,y1],[x2,y2],[x3,y3],[x4,y4]],  dtype = "float32")
    print('source shape '+str(src.shape))
    dst=cv2.transform(src,M)

cv2.error: /home/jeremy/sw/opencv-3.1.0/modules/core/src/matmul.cpp:1947: error: (-215) scn == m.cols || scn + 1 == m.cols in function transform
</code>```

I can get the transform I want just using numpy arithmetic :

```<code>    dst = np.dot(src,M[:,0:2]) +M[:,2]
    print('dest:{}'.format(dst))
</code>```

But would like to understand whats going on .  The docs say that cv2.transform wants a number of channels equal to number of columns in M  but I'm not clear what the channels would be - maybe an 'x' channel and 'y' channel, but then would would the third be, and what would the different rows signify?

答:
OpenCV on Python often wants points in the form

```<code>np.array([ [[x1, y1]], ..., [[xn, yn]] ])
</code>```

This is not clear in the documentation for cv2.transform() but is more clear in the documentation for other functions that use points, like cv2.perspectiveTransform() where they mention coordinates to be on separate channels:

src – input two-channel or three-channel floating-point array

Transforms can also be used in 3D (using a 4x4 perspective transformation matrix) so that would explain the ability to use two- or three-channel arrays in cv2.transform().

Title: trouble getting cv.transform to work

Body:
I'd like to use the same affine matrix M on some individual (x,y) points as I use on images with cv2.warpAffine. It seems cv2.transform is the way to go .  When I try send an Nx2 matrix of points I get negged (

   src = np.array([
        [x1,y1],[x2,y2],[x3,y3],[x4,y4]],  dtype = "float32")
    print('source shape '+str(src.shape))
    dst=cv2.transform(src,M)

cv2.error: /home/jeremy/sw/opencv-3.1.0/modules/core/src/matmul.cpp:1947: error: (-215) scn == m.cols || scn + 1 == m.cols in function transform

I can get the transform I want just using numpy arithmetic :

    dst = np.dot(src,M[:,0:2]) +M[:,2]
    print('dest:{}'.format(dst))

But would like to understand whats going on .  The docs say that cv2.transform wants a number of channels equal to number of columns in M  but I'm not clear what the channels would be - maybe an 'x' channel and 'y' channel, but then would would the third be, and what would the different rows signify?

Body:
OpenCV on Python often wants points in the form

np.array([ [[x1, y1]], ..., [[xn, yn]] ])

This is not clear in the documentation for cv2.transform() but is more clear in the documentation for other functions that use points, like cv2.perspectiveTransform() where they mention coordinates to be on separate channels:

src – input two-channel or three-channel floating-point array

Transforms can also be used in 3D (using a 4x4 perspective transformation matrix) so that would explain the ability to use two- or three-channel arrays in cv2.transform().


问:
Empty spans move other spans up
```<code>  <span style="float:left; padding-right: 5px;">
    <span style="display:block;">Harvard</span>
    <span>John Smith</span>
  </span>

  <span style="float:left; padding-right: 5px;">
    <span style="display:block;">Chicago</span>
    <span>Tucker Max</span>
  </span>

  <span style="float:left; padding-right: 5px;">
    <span style="display:block;"></span>
    <span>Rihanna</span>
  </span>

  <span style="float:left; padding-right: 5px;">
    <span style="display:block;">NYU</span>
    <span>Peter Simpson</span>
  </span>
 //... and many more
</code>```

The first span contains the university, the second span contains the name of the person. Now my problem is that whenever a I have a person who did not go to uni, I want to simply leave it blank.

But when I do that the name of the person moves up and is not aligned with the other names anymore. So in my example, Rihanna moves up:

I could write something like - or no uni, but I would much prefer to have a blank field there, as its just more tidy. I  would also much prefer to have a CSS based solution.

Edit: If people downvote this, let me know why at least.

答:
```<code><span style="float:left; padding-right: 5px;">
  <span style="visibility:hidden;">&nbsp</span><!-- Change is in this line -->
  <span>Rihanna</span>
</span>
</code>```

You can use "visibility:hidden" style. That way the height/width from the span will still be used while hiding the element.

Title: Empty spans move other spans up

Body:
    Harvard
    John Smith

    Chicago
    Tucker Max

    Rihanna

    NYU
    Peter Simpson

 //... and many more

The first span contains the university, the second span contains the name of the person. Now my problem is that whenever a I have a person who did not go to uni, I want to simply leave it blank.

But when I do that the name of the person moves up and is not aligned with the other names anymore. So in my example, Rihanna moves up:

I could write something like - or no uni, but I would much prefer to have a blank field there, as its just more tidy. I  would also much prefer to have a CSS based solution.

Edit: If people downvote this, let me know why at least.

Body:
<span style="float:left; padding-right: 5px;">
  <span style="visibility:hidden;">&nbsp</span><!-- Change is in this line -->
  <span>Rihanna</span>
</span>

You can use "visibility:hidden" style. That way the height/width from the span will still be used while hiding the element.


问:
Fatal error : Cannot use [] for reading
I used implode in my request SQL, for a checkBox for multiple choice.

```<code>if ($this->_count == 0) {
    $this->_sqlWhere.="`piecearticles`.`ID_Article`=`article`.`ID_Article` AND `piecearticles`.`Designiation`=`article`.`Designiation` AND `article`.`ID_LRU`=`lru`.`ID_LRU` AND lru.LRU IN (" . implode(",", $this->_lru[]) . ")";
    $this->_count++;
}
</code>```

When I run it return an error:

```<code>Fatal error: Cannot use [] for reading
</code>```

Is't the implode a cause to this error or in my request ?

答:
The error is what the error says - you can't use [] when you're trying to read an array. You can do;

```<code>implode(",", $this->_lru)
</code>```

Or

```<code>implode(",", array("a2", "b"))
</code>```

You only use the square brackets when you want to write into an array.

Title: Fatal error : Cannot use [] for reading

Body:
I used implode in my request SQL, for a checkBox for multiple choice.

if ($this->_count == 0) {
    $this->_sqlWhere.="`piecearticles`.`ID_Article`=`article`.`ID_Article` AND `piecearticles`.`Designiation`=`article`.`Designiation` AND `article`.`ID_LRU`=`lru`.`ID_LRU` AND lru.LRU IN (" . implode(",", $this->_lru[]) . ")";
    $this->_count++;
}

When I run it return an error:

Fatal error: Cannot use [] for reading

Is't the implode a cause to this error or in my request ?

Body:
The error is what the error says - you can't use [] when you're trying to read an array. You can do;

implode(",", $this->_lru)

Or

implode(",", array("a2", "b"))

You only use the square brackets when you want to write into an array.


问:
Containerized Kafka client errors when producing messages to the host Kafka server
There are a number of similar types of queries on stackoverflow, but none quite match the problem that I am seeing.

I have a zookeeper/kafka setup on my server which work perfectly.  One can produce

```<code>bin/kafka-console-producer.sh --broker-list 192.168.2.80:9092 --topic test
</code>```

and consume

```<code>bin/kafka-console-consumer.sh --bootstrap-server 192.168.2.80:9092 --topic test --from-beginning
</code>```

locally on the Linux Ubuntu 16.04 server.

From a Docker container - also running Ubuntu 16.04 - I want to produce and consume.  The container's Kafka code was copied from that on the server.
Firstly I can create a new topic

```<code>bin/kafka-topics.sh --create --zookeeper 192.168.2.80:2181 --replication-factor 1 --partitions 1 --topic test2
</code>```

from the container and then list it again

```<code>bin/kafka-topics.sh --list --zookeeper 192.168.2.80:2181
</code>```

However when I try to produce new messages, using the above (kafka-console-producer.sh) command it fails with the following message:

```<code>[2017-06-05 13:59:05,317] ERROR Error when sending message to topic test2  with key: null, value: 2 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for test2-0: 1526 ms has passed since batch creation plus linger time
</code>```

immediately after entering the text of the message and pressing enter.

It may seem strange running a Docker container on the same host, but once this works I will move the container to a separate host for production.

My kafka server.properties file:

```<code>listeners=PLAINTEXT://0.0.0.0:9092
</code>```

Kafka version:

```<code>2.12-0.10.2.1
</code>```

Docker version:

```<code>Docker version 1.12.6, build 78d1802
</code>```

答:
Aha!
After further reading and the answers given above the solution came. As is often the case it is an easy one.
A simple edit of the kafka server.properties file:

```<code>advertised.listeners=PLAINTEXT://192.168.2.80:9092
</code>```

Also note, the parameter 'listeners' is not set in this file.

Body:
There are a number of similar types of queries on stackoverflow, but none quite match the problem that I am seeing.

I have a zookeeper/kafka setup on my server which work perfectly.  One can produce

bin/kafka-console-producer.sh --broker-list 192.168.2.80:9092 --topic test

and consume

bin/kafka-console-consumer.sh --bootstrap-server 192.168.2.80:9092 --topic test --from-beginning

locally on the Linux Ubuntu 16.04 server.

From a Docker container - also running Ubuntu 16.04 - I want to produce and consume.  The container's Kafka code was copied from that on the server.
Firstly I can create a new topic

bin/kafka-topics.sh --create --zookeeper 192.168.2.80:2181 --replication-factor 1 --partitions 1 --topic test2

from the container and then list it again

bin/kafka-topics.sh --list --zookeeper 192.168.2.80:2181

However when I try to produce new messages, using the above (kafka-console-producer.sh) command it fails with the following message:

[2017-06-05 13:59:05,317] ERROR Error when sending message to topic test2  with key: null, value: 2 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for test2-0: 1526 ms has passed since batch creation plus linger time

immediately after entering the text of the message and pressing enter.

It may seem strange running a Docker container on the same host, but once this works I will move the container to a separate host for production.

My kafka server.properties file:

listeners=PLAINTEXT://0.0.0.0:9092

Kafka version:

2.12-0.10.2.1

Docker version:

Docker version 1.12.6, build 78d1802

Body:
Aha!
After further reading and the answers given above the solution came. As is often the case it is an easy one.
A simple edit of the kafka server.properties file:

advertised.listeners=PLAINTEXT://192.168.2.80:9092

Also note, the parameter 'listeners' is not set in this file.


问:
execute lua string as lua code
I want to share lua modules with coworkers. In order to get the latest version of shared modules I want to store and fetch them with a web server.

My questions is:

Is it possible to load lua code directly from http request or string?

I want to achieve something like that :

```<code>module = [[
    local sharedModule = {}
    function sharedModule.greet(name) print("hello " .. name) end
    return sharedModule
]]
greeter = require (module)
greeter.greet("john")
</code>```

Maybe this is not the right thing to do. Is there a better approach than this one?

答:
There's a whole section in Programming in Lua devoted to that. Your needs will be directly fulfilled with loadstring in Lua 5.1 and older, or load in Lua 5.2 and newer.

I would carefully verify the code you're actually executing, though. At the very least, version it (running a wrong version would most probably end up in all sorts of problems, if the code being run depends on the environment being in a certain state). Optimally checksum and sign the code, and verify the signature before doing anything. If your environment isn't protected, this is essentially a huge backdoor opening.

You could also use rings library to isolate the code you're running within the Lua environment itself. It might not be airtight security-wise, but should at least prevent the received code from crashing your application if/when it goes awry.

Title: execute lua string as lua code

Body:
I want to share lua modules with coworkers. In order to get the latest version of shared modules I want to store and fetch them with a web server.

My questions is:

Is it possible to load lua code directly from http request or string?

I want to achieve something like that :

module = [[
    local sharedModule = {}
    function sharedModule.greet(name) print("hello " .. name) end
    return sharedModule
]]
greeter = require (module)
greeter.greet("john")

Maybe this is not the right thing to do. Is there a better approach than this one?

ContentLicense: CC BY-SA 4.0


问:
Angular controller not able to read update from service. Any advice?
I have a situation where within my angular service, I have a number of properties. These properties are linked to the controller.

Service:

```<code>angular.module('...')
    .factory('PollServ', function PollServ($http, ...) {

        var service = {
            question: '',
            votes: [[]]
        }

        ...

        // make http request to API
        var request = $http({ ...

        // once the value is retrieved, update properties
        request.then(function (res) {

            service.question = res.data.question;
            ...
    }
</code>```

Controller:

```<code>angular.module('...')
    .controller('PollCtrl', function PollCtrl(..., PollServ) {
        $scope.question = PollServ.question;
        $scope.votes = PollServ.votes;
        ...
</code>```

Now, although the votes are being updated properly, the question is not. I am not doing anything different, except the fact that votes is an array and question is just a regular string. I think the array may have something to do with being able to dynamically update, but not the simple string.

How can I get it to work, without unnecessary turning the string into an array as well?

答:
You said it yourself - the question is a string and thus will not be updated in your controller/view.

What you could do is turning the question into an object. For example:

In Factory

```<code>var service = {
    question: {
        name: ''
    },
    votes: [[]]
}

...

service.question.name = res.data.question;
</code>```

You then need to change the reference in your view to question.name.

Body:
I have a situation where within my angular service, I have a number of properties. These properties are linked to the controller.

Service:

angular.module('...')
    .factory('PollServ', function PollServ($http, ...) {

        var service = {
            question: '',
            votes: [[]]
        }

        ...

        // make http request to API
        var request = $http({ ...

        // once the value is retrieved, update properties
        request.then(function (res) {

            service.question = res.data.question;
            ...
    }

Controller:

angular.module('...')
    .controller('PollCtrl', function PollCtrl(..., PollServ) {
        $scope.question = PollServ.question;
        $scope.votes = PollServ.votes;
        ...

Now, although the votes are being updated properly, the question is not. I am not doing anything different, except the fact that votes is an array and question is just a regular string. I think the array may have something to do with being able to dynamically update, but not the simple string.

How can I get it to work, without unnecessary turning the string into an array as well?

Body:
You said it yourself - the question is a string and thus will not be updated in your controller/view.

What you could do is turning the question into an object. For example:

In Factory

var service = {
    question: {
        name: ''
    },
    votes: [[]]
}

...

service.question.name = res.data.question;

You then need to change the reference in your view to question.name.


问:
Bind FormBuilder input value with another input's value
I have a form with name and milestone inputs. I want my milestones input value to be Milestone: + name and to be updated automatically as my user types a name.

I am trying to use ngModel binding in order to achieve this.

```<code><!-- My name input -->
<input mdInput [(ngModel)]="phaseName" formControlName="name" placeholder="Nom" required>
</code>```

And in my ts components constructor:

```<code>public phaseForm: FormGroup;
phaseName: string;

this.phaseForm = fb.group({
        'name': ['', Validators.required],
        'milestone': ['Milestone: ' + this.phaseName, Validators.required]
    });
</code>```

But as the default value of milestone is set in the constructor, it does not update as my user types a name, what should I add or do in order to achieve my binding?

答:
you can set like that. after init form builder in ngOnInit() method.
  if you can use input box inside formgroup. it's already two way
  binding so no need bind a value. if you want to get form value.

```<code>for eg : const phaseFormValue = this.pahseForm.value;
 console.log(phaseFormValue.name);

ngOnInit(): void {
 this.phaseForm.setValue({milestone:'Milestone: ' + this.phaseName});
}
</code>```

if you can use input box outside. then try this code.

```<code><input mdInput [(ngModel)]="phaseName" (keypress)="handleKeyboardEvent($event)" placeholder="Name">
</code>```

// component

```<code>@HostListener('document:keypress', ['$event'])
    handleKeyboardEvent(event: KeyboardEvent): void {
            this.phaseForm.setValue({milestone:'Milestone: ' + this.phaseName});
    };
</code>```

Body:
I have a form with name and milestone inputs. I want my milestones input value to be Milestone: + name and to be updated automatically as my user types a name.

I am trying to use ngModel binding in order to achieve this.

<input mdInput [(ngModel)]="phaseName" formControlName="name" placeholder="Nom" required>

And in my ts components constructor:

public phaseForm: FormGroup;
phaseName: string;

this.phaseForm = fb.group({
        'name': ['', Validators.required],
        'milestone': ['Milestone: ' + this.phaseName, Validators.required]
    });

But as the default value of milestone is set in the constructor, it does not update as my user types a name, what should I add or do in order to achieve my binding?

Body:
you can set like that. after init form builder in ngOnInit() method.
  if you can use input box inside formgroup. it's already two way
  binding so no need bind a value. if you want to get form value.

for eg : const phaseFormValue = this.pahseForm.value;
 console.log(phaseFormValue.name);

ngOnInit(): void {
 this.phaseForm.setValue({milestone:'Milestone: ' + this.phaseName});
}

if you can use input box outside. then try this code.

<input mdInput [(ngModel)]="phaseName" (keypress)="handleKeyboardEvent($event)" placeholder="Name">

// component

@HostListener('document:keypress', ['$event'])
    handleKeyboardEvent(event: KeyboardEvent): void {
            this.phaseForm.setValue({milestone:'Milestone: ' + this.phaseName});
    };


问:
Hadoop wordcount Pseudodistributed mode error Exit code:127
I have installed Hadoop 2.7.1 stable version. I followed Tom White's book for installation in Pseudodistributed mode. I did set all environment variables like JAVA_HOME, HADOOP_HOME, PATH etc.. I configured yarn-site.xml, hdfs-site.xml, core-site.xml, mapred-site.xml.

I copied the sample file file.txt using following command.

```<code>$hadoop fs -copyFromLocal textFiles/file.txt file.txt
</code>```

which shows me

```<code>Found 2 items
-rw-r--r--   1 RAMA supergroup       3737 2015-12-27 21:52 file.txt
drwxr-xr-x   - RAMA supergroup          0 2015-12-27 22:17 input
</code>```

When I am executing the wordcount program in hadoop-mapreduce-examples-2.7.1.jar using below command

```<code>RAMAs-MacBook-Pro:hadoop-2.7.1 RAMA$ hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.1.jar wordcount file.txt output
</code>```

it is throwing me following exception, for which I am not able to find any feasible solution.

```<code>15/12/27 22:41:52 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
15/12/27 22:41:53 INFO client.RMProxy: Connecting to ResourceManager at localhost/127.0.0.1:8032
15/12/27 22:41:53 INFO input.FileInputFormat: Total input paths to process : 1
15/12/27 22:41:53 INFO mapreduce.JobSubmitter: number of splits:1
15/12/27 22:41:53 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1451216397139_0020
15/12/27 22:41:54 INFO impl.YarnClientImpl: Submitted application application_1451216397139_0020
15/12/27 22:41:54 INFO mapreduce.Job: The url to track the job: http://192.168.1.6:8088/proxy/application_1451216397139_0020/
15/12/27 22:41:54 INFO mapreduce.Job: Running job: job_1451216397139_0020
15/12/27 22:41:57 INFO mapreduce.Job: Job job_1451216397139_0020 running in uber mode : false
15/12/27 22:41:57 INFO mapreduce.Job:  map 0% reduce 0%
15/12/27 22:41:57 INFO mapreduce.Job: Job job_1451216397139_0020 failed with state FAILED due to: Application application_1451216397139_0020 failed 2 times due to AM Container for appattempt_1451216397139_0020_000002 exited with  exitCode: 127
For more detailed output, check application tracking page:http://192.168.1.6:8088/cluster/app/application_1451216397139_0020Then, click on links to logs of each attempt.
Diagnostics: Exception from container-launch.
Container id: container_1451216397139_0020_02_000001
Exit code: 127
Stack trace: ExitCodeException exitCode=127:
at org.apache.hadoop.util.Shell.runCommand(Shell.java:545)
at org.apache.hadoop.util.Shell.run(Shell.java:456)
at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:722)
at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:211)
at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:302)
at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:82)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Container exited with a non-zero exit code 127
Failing this attempt. Failing the application.
15/12/27 22:41:57 INFO mapreduce.Job: Counters: 0
</code>```

Any suggestions/comments is of great help...

答: In hadoop-env.sh, explicitly add the java home path in JAVA_HOME variable.</p>

Body:
I have installed Hadoop 2.7.1 stable version. I followed Tom White's book for installation in Pseudodistributed mode. I did set all environment variables like JAVA_HOME, HADOOP_HOME, PATH etc.. I configured yarn-site.xml, hdfs-site.xml, core-site.xml, mapred-site.xml.

I copied the sample file file.txt using following command.

$hadoop fs -copyFromLocal textFiles/file.txt file.txt

which shows me

Found 2 items
-rw-r--r--   1 RAMA supergroup       3737 2015-12-27 21:52 file.txt
drwxr-xr-x   - RAMA supergroup          0 2015-12-27 22:17 input

When I am executing the wordcount program in hadoop-mapreduce-examples-2.7.1.jar using below command

RAMAs-MacBook-Pro:hadoop-2.7.1 RAMA$ hadoop jar share/hadoop/mapreduce/hadoop-mapreduce-examples-2.7.1.jar wordcount file.txt output

it is throwing me following exception, for which I am not able to find any feasible solution.

15/12/27 22:41:52 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
15/12/27 22:41:53 INFO client.RMProxy: Connecting to ResourceManager at localhost/127.0.0.1:8032
15/12/27 22:41:53 INFO input.FileInputFormat: Total input paths to process : 1
15/12/27 22:41:53 INFO mapreduce.JobSubmitter: number of splits:1
15/12/27 22:41:53 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1451216397139_0020
15/12/27 22:41:54 INFO impl.YarnClientImpl: Submitted application application_1451216397139_0020
15/12/27 22:41:54 INFO mapreduce.Job: The url to track the job: http://192.168.1.6:8088/proxy/application_1451216397139_0020/
15/12/27 22:41:54 INFO mapreduce.Job: Running job: job_1451216397139_0020
15/12/27 22:41:57 INFO mapreduce.Job: Job job_1451216397139_0020 running in uber mode : false
15/12/27 22:41:57 INFO mapreduce.Job:  map 0% reduce 0%
15/12/27 22:41:57 INFO mapreduce.Job: Job job_1451216397139_0020 failed with state FAILED due to: Application application_1451216397139_0020 failed 2 times due to AM Container for appattempt_1451216397139_0020_000002 exited with  exitCode: 127
For more detailed output, check application tracking page:http://192.168.1.6:8088/cluster/app/application_1451216397139_0020Then, click on links to logs of each attempt.
Diagnostics: Exception from container-launch.
Container id: container_1451216397139_0020_02_000001
Exit code: 127
Stack trace: ExitCodeException exitCode=127:
at org.apache.hadoop.util.Shell.runCommand(Shell.java:545)
at org.apache.hadoop.util.Shell.run(Shell.java:456)
at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:722)
at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:211)
at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:302)
at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:82)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Container exited with a non-zero exit code 127
Failing this attempt. Failing the application.
15/12/27 22:41:57 INFO mapreduce.Job: Counters: 0

Any suggestions/comments is of great help...