<commit_before>'use strict';

angular.module('eMarketApp').directive('itemView',
    function(User, Restangular, ProductBids, SellerInfo, Product, Helper) {
      return {
        templateUrl: 'views/itemView.html',
        restrict: 'E',
        scope: {},
        replace: true,
        controller: function($scope, $filter, Patterns, $element) {

          $scope.patternPlaceBid = Patterns.item.placeBid;
          $scope.patternBuyItNow = Patterns.item.buyItNow;

          var page = $($element[0]);

          var placeBidPopup = page.find('#itemView-placeBidPopup');
          var buyItNowPopup = page.find('#itemView-buyItNowPopup');

          var statusPopup = page.find('#itemView-statusPopup');
          var statusPopupMessage = page.find('#itemView-statusPopupMessage');

          $scope.submitBid = function() {

            statusPopup.off();
            placeBidPopup.off();
            $scope.item.isBidItem = 1;
            $.mobile.loading('show');
            User.me().all('bids').post($scope.item).then(function() {
              $.mobile.loading('hide');
              placeBidPopup.popup('close');
              statusPopup.on({
                popupafterclose: function() {
                  setTimeout(function() {
                    $.mobile.changePage('#home-user');
                  });
                }
              });
              placeBidPopup.on({
                popupafterclose: function() {
                  statusPopupMessage.text('Bid Submitted Successfully');
                  setTimeout(function() {
                    statusPopup.popup('open');
                    placeBidPopup.off();
                  }, 250);
                }
              });
            }, function(err) {
              $.mobile.loading('hide');
              placeBidPopup.popup('close');
              placeBidPopup.on({
                popupafterclose: function() {
                  statusPopupMessage.text('Could not place the bid. Bidding probably has ended.');
                  setTimeout(function() {
                    statusPopup.popup('open');
                    placeBidPopup.off();
                  }, 250);
                }
              });
              console.log('Error bid', err);
            });
          };

          $scope.submitCart = function() {

            statusPopup.off();
            buyItNowPopup.off();

            $scope.item.isBidItem = 0;
            $.mobile.loading('show');
            User.me().all('cartItems').post($scope.item).then(function() {
              $.mobile.loading('hide');
              buyItNowPopup.popup('close');
              statusPopup.on({
                popupafterclose: function() {
                  setTimeout(function() {
                    $.mobile.changePage('#home-user');
                  });
                }
              });
              buyItNowPopup.on({
                popupafterclose: function() {
                  statusPopupMessage.text('Product(s) have been placed in cart.');
                  setTimeout(function() {
                    statusPopup.popup('open');
                    buyItNowPopup.off();
                  }, 250);
                }
              });
            }, function(err) {
              $.mobile.loading('hide');
              buyItNowPopup.popup('close');
              buyItNowPopup.on({
                popupafterclose: function() {
                  statusPopupMessage.text('Could not place product in cart.');
                  setTimeout(function() {
                    statusPopup.popup('open');
                    buyItNowPopup.off();
                  }, 250);
                }
              });
              console.log('Error placing product in cart', err);
            });
          };

        },
        link: function(scope, elem) {

          var page = $(elem[0]);

          var placeBidBtn = page.find('#itemView-placeBidBtn');
          var buyItNowBtn = page.find('#itemView-buyItNowBtn');
          var productBidsLink = page.find('#itemView-productBidsLink');
          //      var buyItNowPopup = page.find('#itemView-buyItNowPopup');
          //      var addedToCartPopup = page.find('#itemView-addedToCartPopup');
          var countdownTimer = page.find('#countdown-timer');

          page.on('pagebeforeshow', function() {

            // Set the product to scope item
            scope.item = {}; // delete any previous values
            scope.item = Product.getItem();
            scope.item.amountToBuy = 1;
            scope.item.isBidItem = null;
            scope.item.bidAmount = null;

            // Set sellerId into a service
            SellerInfo.sellerId = scope.item.sellerId;
            SellerInfo.sellerName = scope.item.sellerName;

            // Remove any state from the other object.
            scope.nextMinBid = null;

            var currentDate = new Date();

            if(new Date(scope.item.bidEndDate) > currentDate && scope.item.quantityRemaining > 0) {
              scope.activateTimer = true;
              var bidEndDateStr = Helper.formatDate(scope.item.bidEndDate, 'yyyy/MM/dd HH:mm:ss');
              countdownTimer.countdown(bidEndDateStr, function(event) {
                countdownTimer.html(event.strftime('%-ww %-dd %Hh %Mm %Ss'));
              });
            } else {
              scope.activateTimer = false;
            }

            if(scope.item && scope.item.currentBid === null) {
              productBidsLink.addClass('ui-disabled');
            } else {
              productBidsLink.removeClass('ui-disabled');
            }

            if(scope.item && User.userId === scope.item.sellerId) {
              buyItNowBtn.addClass('ui-disabled');
              placeBidBtn.addClass('ui-disabled');
            } else {
              if(new Date(scope.item.bidEndDate) < currentDate || scope.item.quantityRemaining <= 0) {
                placeBidBtn.addClass('ui-disabled');
              } else {
                placeBidBtn.removeClass('ui-disabled');
              }
              if(scope.item.quantityRemaining <= 0) {
                buyItNowBtn.addClass('ui-disabled');
              } else {
                buyItNowBtn.removeClass('ui-disabled');
              }
            }

            if(scope.item.currentBid < scope.item.startingBidPrice) {
              scope.nextMinBid = scope.item.startingBidPrice + 5;
            }
            else {
              scope.nextMinBid = scope.item.currentBid + 5;
            }

            Restangular.one('sellers', scope.item.sellerId).one('avgRating').get().then(function(avg) {
              //scope.sellerRating = avg;
              SellerInfo.sellerAvgRate = avg.avgRating;
            });

            User.me().all('browsedItems').post({productId: Product.getItem().id});
          });

          page.on('pagehide', function() {
//            countdownTimer.countdown('destroy');
//            countdownTimer.remove();
          });

          scope.setNextBid = function() {
            scope.item.bidAmount = scope.nextMinBid;
          };

          scope.setProductId = function(productId) {
            ProductBids.productId = productId;
          };

        }
      };
    });
<commit_msg>itemview popups now works.<commit_after>'use strict';

angular.module('eMarketApp').directive('itemView',
    function(User, Restangular, ProductBids, SellerInfo, Product, Helper) {
      return {
        templateUrl: 'views/itemView.html',
        restrict: 'E',
        scope: {},
        replace: true,
        controller: function($scope, $filter, Patterns, $element) {

          $scope.patternPlaceBid = Patterns.item.placeBid;
          $scope.patternBuyItNow = Patterns.item.buyItNow;

          var page = $($element[0]);

          var placeBidPopup = page.find('#itemView-placeBidPopup');
          var buyItNowPopup = page.find('#itemView-buyItNowPopup');

          var statusPopup = page.find('#itemView-statusPopup');
          var statusPopupMessage = page.find('#itemView-statusPopupMessage');

          $scope.submitBid = function() {

            statusPopup.off();
            placeBidPopup.off();
            $scope.item.isBidItem = 1;
            $.mobile.loading('show');
            User.me().all('bids').post($scope.item).then(function() {
              $.mobile.loading('hide');
              statusPopup.on({
                popupafterclose: function() {
                  setTimeout(function() {
                    $.mobile.changePage('#home-user');
                  });
                }
              });
              placeBidPopup.on({
                popupafterclose: function() {
                  statusPopupMessage.text('Bid Submitted Successfully');
                  setTimeout(function() {
                    statusPopup.popup('open');
                    placeBidPopup.off();
                  }, 250);
                }
              });
              placeBidPopup.popup('close');
            }, function(err) {
              $.mobile.loading('hide');
              placeBidPopup.on({
                popupafterclose: function() {
                  statusPopupMessage.text('Could not place the bid. Bidding probably has ended.');
                  setTimeout(function() {
                    statusPopup.popup('open');
                    placeBidPopup.off();
                  }, 250);
                }
              });
              placeBidPopup.popup('close');
              console.log('Error bid', err);
            });
          };

          $scope.submitCart = function() {

            statusPopup.off();
            buyItNowPopup.off();

            $scope.item.isBidItem = 0;
            $.mobile.loading('show');
            User.me().all('cartItems').post($scope.item).then(function() {
              $.mobile.loading('hide');
              statusPopup.on({
                popupafterclose: function() {
                  setTimeout(function() {
                    $.mobile.changePage('#home-user');
                  });
                }
              });
              buyItNowPopup.on({
                popupafterclose: function() {
                  statusPopupMessage.text('Product(s) have been placed in cart.');
                  setTimeout(function() {
                    statusPopup.popup('open');
                    buyItNowPopup.off();
                  }, 250);
                }
              });
              buyItNowPopup.popup('close');
            }, function(err) {
              $.mobile.loading('hide');
              buyItNowPopup.on({
                popupafterclose: function() {
                  statusPopupMessage.text('Could not place product in cart.');
                  setTimeout(function() {
                    statusPopup.popup('open');
                    buyItNowPopup.off();
                  }, 250);
                }
              });
              buyItNowPopup.popup('close');
              console.log('Error placing product in cart', err);
            });
          };

        },
        link: function(scope, elem) {

          var page = $(elem[0]);

          var placeBidBtn = page.find('#itemView-placeBidBtn');
          var buyItNowBtn = page.find('#itemView-buyItNowBtn');
          var productBidsLink = page.find('#itemView-productBidsLink');
          //      var buyItNowPopup = page.find('#itemView-buyItNowPopup');
          //      var addedToCartPopup = page.find('#itemView-addedToCartPopup');
          var countdownTimer = page.find('#countdown-timer');

          page.on('pagebeforeshow', function() {

            // Set the product to scope item
            scope.item = {}; // delete any previous values
            scope.item = Product.getItem();
            scope.item.amountToBuy = 1;
            scope.item.isBidItem = null;
            scope.item.bidAmount = null;

            // Set sellerId into a service
            SellerInfo.sellerId = scope.item.sellerId;
            SellerInfo.sellerName = scope.item.sellerName;

            // Remove any state from the other object.
            scope.nextMinBid = null;

            var currentDate = new Date();

            if(new Date(scope.item.bidEndDate) > currentDate && scope.item.quantityRemaining > 0) {
              scope.activateTimer = true;
              var bidEndDateStr = Helper.formatDate(scope.item.bidEndDate, 'yyyy/MM/dd HH:mm:ss');
              countdownTimer.countdown(bidEndDateStr, function(event) {
                countdownTimer.html(event.strftime('%-ww %-dd %Hh %Mm %Ss'));
              });
            } else {
              scope.activateTimer = false;
            }

            if(scope.item && scope.item.currentBid === null) {
              productBidsLink.addClass('ui-disabled');
            } else {
              productBidsLink.removeClass('ui-disabled');
            }

            if(scope.item && User.userId === scope.item.sellerId) {
              buyItNowBtn.addClass('ui-disabled');
              placeBidBtn.addClass('ui-disabled');
            } else {
              if(new Date(scope.item.bidEndDate) < currentDate || scope.item.quantityRemaining <= 0) {
                placeBidBtn.addClass('ui-disabled');
              } else {
                placeBidBtn.removeClass('ui-disabled');
              }
              if(scope.item.quantityRemaining <= 0) {
                buyItNowBtn.addClass('ui-disabled');
              } else {
                buyItNowBtn.removeClass('ui-disabled');
              }
            }

            if(scope.item.currentBid < scope.item.startingBidPrice) {
              scope.nextMinBid = scope.item.startingBidPrice + 5;
            }
            else {
              scope.nextMinBid = scope.item.currentBid + 5;
            }

            Restangular.one('sellers', scope.item.sellerId).one('avgRating').get().then(function(avg) {
              //scope.sellerRating = avg;
              SellerInfo.sellerAvgRate = avg.avgRating;
            });

            User.me().all('browsedItems').post({productId: Product.getItem().id});
          });

          page.on('pagehide', function() {
//            countdownTimer.countdown('destroy');
//            countdownTimer.remove();
          });

          scope.setNextBid = function() {
            scope.item.bidAmount = scope.nextMinBid;
          };

          scope.setProductId = function(productId) {
            ProductBids.productId = productId;
          };

        }
      };
    });
<|endoftext|>


<commit_before>define([
  'mps',
  'backbone',
  'widgets/models/WidgetModel',
  'countries/presenters/PresenterClass'
], function(mps, Backbone, WidgetModel, PresenterClass) {

  'use strict';

  var WidgetPresenter = PresenterClass.extend({

    init: function(view, setup) {
      this.view = view;
      this._super();
      this.model = new WidgetModel(setup.model);
      this.status = new (Backbone.Model.extend({
        defaults: setup.status
      }));
      this._setListeners();
    },

    _setListeners: function() {
      this.status.on('change:tabs', this.setTab, this);
    },

    _subscriptions: [{
      'Compare/reflection': function(id,slugw_compare,status) {
        if (this.model.get('id') == id && this.model.get('slugw') == slugw_compare) {
          this.status.set(status);
        }
      },
      'Lock/toggle': function(id,lock) {
        if (this.model.get('id') == id) {
          var tabs = _.clone(this.status.get('tabs'));
          tabs.lock = lock;
          this.status.set('tabs', tabs);
        }
      },
      'Threshold/change': function(thresh) {
        this.thresh = thresh;
      },

    }],

    changeTab: function(position) {
      // ******
      // CAREFUL: if you add anything new to the widgets.json
      //          remember to add it inside CompareGridPresenter (getTabsOptions function) and inside widgetPresenter (changeTab function)
      //          You must add it to views/api/v1/widgets/show.json.rabl (If you don't, the API won't send the new parameter)
      // ******
      var tabs = _.clone(this.status.get('tabs'));
      var t = _.findWhere(this.model.get('tabs'), { position: position });
      tabs = {
        type: t.type,
        position: position,
        unit: (t.switch) ? t['switch'][0]['unit'] : null,
        start_date: (t.range) ? t['range'][0] : null,
        end_date: (t.range) ? t['range'][t['range'].length - 1] : null,
        thresh: (t.thresh) ? this.thresh : 0,
        section: (t.sectionswitch) ? t['sectionswitch'][0]['unit'] : null,
        template: (t.template) ? t['template'] : null,
        lock: (this.status.get('tabs').lock != null && this.status.get('tabs').lock != undefined) ? this.status.get('tabs').lock : true,
      }
      this.status.set('tabs',tabs);
    },

    changeStatus: function(status) {
      this.status.set(status);
    },

    setTab: function() {
      this.view.setTab();
      this.publish();
    },

    publish: function() {
      mps.publish('Options/updated', [this.model.get('id'),this.model.get('slugw'),this.status.toJSON()]);
      if (this.status.get('tabs').lock) {
        mps.publish('Compare/reflection', [this.model.get('id'),this.model.get('slugw_compare'),this.status.toJSON()]);
      }
    },

    deleteWidget: function() {
      mps.publish('Widgets/delete', [this.model.get('id')]);
    },

    destroy: function() {
      this.unsubscribe();
    }

  });

  return WidgetPresenter;

});
<commit_msg>Bug fixed<commit_after>define([
  'mps',
  'backbone',
  'widgets/models/WidgetModel',
  'countries/presenters/PresenterClass'
], function(mps, Backbone, WidgetModel, PresenterClass) {

  'use strict';

  var WidgetPresenter = PresenterClass.extend({

    init: function(view, setup) {
      this.view = view;
      this._super();
      this.model = new WidgetModel(setup.model);
      this.status = new (Backbone.Model.extend({
        defaults: setup.status
      }));
      this._setListeners();
      this.thresh = 30;
    },

    _setListeners: function() {
      this.status.on('change:tabs', this.setTab, this);
    },

    _subscriptions: [{
      'Compare/reflection': function(id,slugw_compare,status) {
        if (this.model.get('id') == id && this.model.get('slugw') == slugw_compare) {
          this.status.set(status);
        }
      },
      'Lock/toggle': function(id,lock) {
        if (this.model.get('id') == id) {
          var tabs = _.clone(this.status.get('tabs'));
          tabs.lock = lock;
          this.status.set('tabs', tabs);
        }
      },
      'Threshold/change': function(thresh) {
        this.thresh = thresh;
      },

    }],

    changeTab: function(position) {
      // ******
      // CAREFUL: if you add anything new to the widgets.json
      //          remember to add it inside CompareGridPresenter (getTabsOptions function) and inside widgetPresenter (changeTab function)
      //          You must add it to views/api/v1/widgets/show.json.rabl (If you don't, the API won't send the new parameter)
      // ******
      var tabs = _.clone(this.status.get('tabs'));
      var t = _.findWhere(this.model.get('tabs'), { position: position });
      tabs = {
        type: t.type,
        position: position,
        unit: (t.switch) ? t['switch'][0]['unit'] : null,
        start_date: (t.range) ? t['range'][0] : null,
        end_date: (t.range) ? t['range'][t['range'].length - 1] : null,
        thresh: (t.thresh) ? this.thresh : 0,
        section: (t.sectionswitch) ? t['sectionswitch'][0]['unit'] : null,
        template: (t.template) ? t['template'] : null,
        lock: (this.status.get('tabs').lock != null && this.status.get('tabs').lock != undefined) ? this.status.get('tabs').lock : true,
      }
      this.status.set('tabs',tabs);
    },

    changeStatus: function(status) {
      this.status.set(status);
    },

    setTab: function() {
      this.view.setTab();
      this.publish();
    },

    publish: function() {
      mps.publish('Options/updated', [this.model.get('id'),this.model.get('slugw'),this.status.toJSON()]);
      if (this.status.get('tabs').lock) {
        mps.publish('Compare/reflection', [this.model.get('id'),this.model.get('slugw_compare'),this.status.toJSON()]);
      }
    },

    deleteWidget: function() {
      mps.publish('Widgets/delete', [this.model.get('id')]);
    },

    destroy: function() {
      this.unsubscribe();
    }

  });

  return WidgetPresenter;

});
<|endoftext|>


<commit_before>import DS from 'ember-data';
import Firebase from 'firebase';

export default DS.DateTransform.extend({
    serialize: function(date) {
        if (date === Firebase.ServerValue.TIMESTAMP){
            return date;
        }

        // to timestamp
        return new Date(date).getTime();
    }
});
<commit_msg>revert date fix<commit_after>import DS from 'ember-data';
import Firebase from 'firebase';

export default DS.DateTransform.extend({
    serialize: function(date) {
        if (date === Firebase.ServerValue.TIMESTAMP){
            return date;
        }

        // to timestamp
        //return new Date(date).getTime();
        return this._super(date);
    }
});
<|endoftext|>


<commit_before>var globals = require('lib/globals');
exports.dayWindow = function(opts) {
  var instance = Ti.UI.createWindow({
    title: opts.title,
    backgroundColor: '#fff'
  });
  instance.orientationModes = [Ti.UI.PORTRAIT];
  var today = new Date(opts.arg);

  // Android Specific Code
  if (globals.osname === 'android') {
    instance.backgroundColor = "#111111";
    instance.activity.onCreateOptionsMenu = function(e) {
      var menu = e.menu;
      var menuItem = menu.add({title:"Refresh"});
      menuItem.addEventListener("click", function(e) {
        Ti.App.fireEvent('events.update');
      });
    };
  }

  // iPhone Specific Code
  if (globals.osname === 'iphone') {
    var refresh = Ti.UI.createButton({
      systemButton:Ti.UI.iPhone.SystemButton.REFRESH
    });
    refresh.addEventListener('click', function(e) {
      Ti.App.fireEvent('events.update');
    });
    instance.rightNavButton = refresh;
  }

  var myDateString = today.getFullYear() + "-" + ('0' + (today.getMonth() + 1)).slice(-2) + "-" + ('0' + today.getDate()).slice(-2);
  var events = globals.slcdbGetEvents(myDateString);
  var data = [];
  while (events.isValidRow()) {
    var row = Ti.UI.createTableViewRow();
    row.header = globals.secondsToTime(events.fieldByName('datefrom')) + '-' + globals.secondsToTime(events.fieldByName('dateto'));
    row.selectionStyle = "none";
    var title = globals.html_decode(events.fieldByName('title'));
    var content = Ti.UI.createLabel({
      text: title
    });
    if (events.fieldByName('eventtype') == "Workshop") {
      row.hasChild = true;
      row.selectionStyle = 1;
    }
    row.add(content);
    data.push(row);
    events.next();
  }
  var tableView = Ti.UI.createTableView({
    data:data
  });

  tableView.addEventListener('click', function(f){
    if (f.rowData.hasChild) {
      Ti.App.fireEvent('day.click', {
        header: f.rowData.header,
        title: f.row.children[0].text,
        date: today,
        callback: false
      });
    }
  });
  instance.add(tableView);

  return instance;
}
<commit_msg>Put in reminder to remove this file since it is no longer used.<commit_after>// THIS FILE MAY BE REMOVED BEFORE TESTING
// WARNING: NONE OF THIS CODE IS ACUTALLY NEEDED
var globals = require('lib/globals');
exports.dayWindow = function(opts) {
  var instance = Ti.UI.createWindow({
    title: opts.title,
    backgroundColor: '#fff'
  });
  instance.orientationModes = [Ti.UI.PORTRAIT];
  var today = new Date(opts.arg);

  // Android Specific Code
  if (globals.osname === 'android') {
    instance.backgroundColor = "#111111";
    instance.activity.onCreateOptionsMenu = function(e) {
      var menu = e.menu;
      var menuItem = menu.add({title:"Refresh"});
      menuItem.addEventListener("click", function(e) {
        Ti.App.fireEvent('events.update');
      });
    };
  }

  // iPhone Specific Code
  if (globals.osname === 'iphone') {
    var refresh = Ti.UI.createButton({
      systemButton:Ti.UI.iPhone.SystemButton.REFRESH
    });
    refresh.addEventListener('click', function(e) {
      Ti.App.fireEvent('events.update');
    });
    instance.rightNavButton = refresh;
  }

  var myDateString = today.getFullYear() + "-" + ('0' + (today.getMonth() + 1)).slice(-2) + "-" + ('0' + today.getDate()).slice(-2);
  var events = globals.slcdbGetEvents(myDateString);
  var data = [];
  while (events.isValidRow()) {
    var row = Ti.UI.createTableViewRow();
    row.header = globals.secondsToTime(events.fieldByName('datefrom')) + '-' + globals.secondsToTime(events.fieldByName('dateto'));
    row.selectionStyle = "none";
    var title = globals.html_decode(events.fieldByName('title'));
    var content = Ti.UI.createLabel({
      text: title
    });
    if (events.fieldByName('eventtype') == "Workshop") {
      row.hasChild = true;
      row.selectionStyle = 1;
    }
    row.add(content);
    data.push(row);
    events.next();
  }
  var tableView = Ti.UI.createTableView({
    data:data
  });

  tableView.addEventListener('click', function(f){
    if (f.rowData.hasChild) {
      Ti.App.fireEvent('day.click', {
        header: f.rowData.header,
        title: f.row.children[0].text,
        date: today,
        callback: false
      });
    }
  });
  instance.add(tableView);

  return instance;
}
<|endoftext|>


<commit_before>(function() {
    var Ext = window.Ext4 || window.Ext;

    /**
     *
     */
    Ext.define('Rally.apps.iterationtrackingboard.IterationTrackingTreeGrid', {
        extend: 'Rally.ui.grid.TreeGrid',
        alias: 'widget.rallyiterationtrackingtreegrid',

        requires: [
            'Rally.apps.iterationtrackingboard.IterationTrackingTreeView',
            'Rally.ui.renderer.RendererFactory'
        ],

        config: {
            viewConfig: {
                xtype: 'rallyiterationtrackingtreeview'
            },

            /**
             * @cfg {String}
             * @inheritdoc
             */
            treeColumnDataIndex: 'FormattedID',

            /**
             * @cfg {String}
             * @inheritdoc
             */
            treeColumnHeader: 'ID',

            /**
             * @cfg {boolean}
             * @inheritdoc
             */
            treeColumnResizable: false,

            /**
             * @cfg {Array}
             * Array of configurations for summary e.g. {field: 'PlanEstimate', type: 'sum', units: 'pt'}
             */
            summaryColumns: [
                {
                    field: 'PlanEstimate',
                    type: 'sum',
                    units: 'pt'
                },
                {
                    field: 'TaskEstimateTotal',
                    type: 'sum',
                    units: 'hr'
                },
                {
                    field: 'TaskRemainingTotal',
                    type: 'sum',
                    units: 'hr'
                }
            ],

            treeColumnRenderer: function (value, metaData, record, rowIdx, colIdx, store) {
                store = store.treeStore || store;
                return Rally.ui.renderer.RendererFactory.getRenderTemplate(store.model.getField('FormattedID')).apply(record.data);
            }
        }
    });
})();
<commit_msg>S70871: updated IterationTrackingTreeGrid to specify the help link text for the no data display<commit_after>(function() {
    var Ext = window.Ext4 || window.Ext;

    /**
     *
     */
    Ext.define('Rally.apps.iterationtrackingboard.IterationTrackingTreeGrid', {
        extend: 'Rally.ui.grid.TreeGrid',
        alias: 'widget.rallyiterationtrackingtreegrid',

        requires: [
            'Rally.apps.iterationtrackingboard.IterationTrackingTreeView',
            'Rally.ui.renderer.RendererFactory'
        ],

        config: {
            viewConfig: {
                xtype: 'rallyiterationtrackingtreeview'
            },

            /**
             * @cfg {String}
             * @inheritdoc
             */
            treeColumnDataIndex: 'FormattedID',

            /**
             * @cfg {String}
             * @inheritdoc
             */
            treeColumnHeader: 'ID',

            /**
             * @cfg {boolean}
             * @inheritdoc
             */
            treeColumnResizable: false,

            /**
             * @cfg {Array}
             * Array of configurations for summary e.g. {field: 'PlanEstimate', type: 'sum', units: 'pt'}
             */
            summaryColumns: [
                {
                    field: 'PlanEstimate',
                    type: 'sum',
                    units: 'pt'
                },
                {
                    field: 'TaskEstimateTotal',
                    type: 'sum',
                    units: 'hr'
                },
                {
                    field: 'TaskRemainingTotal',
                    type: 'sum',
                    units: 'hr'
                }
            ],

            treeColumnRenderer: function (value, metaData, record, rowIdx, colIdx, store) {
                store = store.treeStore || store;
                return Rally.ui.renderer.RendererFactory.getRenderTemplate(store.model.getField('FormattedID')).apply(record.data);
            },

            noDataHelpLink: {
                url: "https://help.rallydev.com/tracking-iterations#filter",
                title: "Filter Help Page"
            }
        }
    });
})();
<|endoftext|>


<commit_before>app.section('ledgerlist');
viewModel.LedgerList = {}; var ll = viewModel.LedgerList;

ll.templateLedgerList = {
	_id: "",
    title: "",
    type: 1,
    group: [],
    periode: moment().format(),
    opening: "",
    in: 0,
    out: 0,
    balance: 0,
}
ll.templateFilter = {
	startdate: moment().format(),
	enddate: moment().format(),
}
ll.dataType = ko.observableArray([
	{text: "Group", value: 1},
	{text: "Account", value: 0},
]);
ll.searchField = ko.observable('');
ll.configLedgerList = ko.mapping.fromJS(ll.templateLedgerList);
ll.configFilter = ko.mapping.fromJS(ll.templateFilter);
ll.ledgerListData = ko.observableArray([]);
ll.dataGroup = ko.observableArray([]);
ll.tempCheckIdLedger = ko.observableArray([]);
ll.ledgerListColumns = ko.observableArray([
	{headerTemplate: "<input type='checkbox' class='ledgercheckall' onclick=\"ll.checkDeleteData(this, 'ledgerall')\"/>", width: 50, attributes: { style: "text-align: center;" }, template: function (d) {
		return [
			"<input type='checkbox' class='ledgercheck' idcheck='"+d._id+"' onclick=\"ll.checkDeleteData(this, 'ledger')\" />"
		].join(" ");
	}},
	{ field: "_id", title: "ID" },
	{ field: "title", title: "Title" },
	{ field: "type", title: "Type", template: function(d){
		if (d.type == 1)
			return ["Group"].join(" ");
		else
			return ["Account"].join(" ");
	} },
	{ field: "group", title: "Group", template: function (d) {
		var html = [];
		for (var i = 0; i < d.group.length; i++) {
			html.push('' + d.group[i] + '');
		}
		return html.join(', ');
	} },
	{ field: "period", title: "Period" },
	{ field: "in", title: "In" },
	{ field: "out", title: "Out" },
	{ field: "balance", title: "Balance" },
]);

ll.getMonthDateRange = function() {
    var startDate = moment([parseInt(moment().format('YYYY')), parseInt(moment().format('MM')) - 1]);
    var endDate = moment(startDate).endOf('month');
    ll.configFilter.startdate(startDate.toDate());
    ll.configFilter.enddate(endDate.toDate());
}
ll.getLedgerList = function(){
	app.ajaxPost("/account/getaccount", { search: ll.searchField(), startdate: ll.configFilter.startdate(), enddate: ll.configFilter.enddate() }, function (res) {
		if (!app.isFine(res)) {
			return;
		}

		ll.ledgerListData(res.data);
	});
};
ll.addLedgerList = function() {
	app.mode("edit");
	ko.mapping.fromJS(ll.templateLedgerList, ll.configLedgerList);
};
ll.removeLedgerList = function(){
	if (ll.tempCheckIdLedger().length === 0) {
		swal({
			title: "",
			text: 'You havent choose any ledger list to delete',
			type: "warning",
			confirmButtonColor: "#DD6B55",
			confirmButtonText: "OK",
			closeOnConfirm: true
		});
	}else{
		swal({
		    title: "Are you sure?",
		    text: 'Efs(s) '+ll.tempCheckIdLedger().toString()+' will be deleted',
		    type: "warning",
		    showCancelButton: true,
		    confirmButtonColor: "#DD6B55",
		    confirmButtonText: "Delete",
		    closeOnConfirm: true
		}, function() {
			setTimeout(function () {
				app.ajaxPost("/account/removeaccount", { _id: ll.tempCheckIdLedger() }, function (res) {
					if (!app.isFine(res)) {
						return;
					}
					ll.backToFront();
					swal({ title: "Ledger List(s) successfully deleted", type: "success" });
				});
			}, 1000);
		});
	}
};
ll.selectGridLedgerList = function(){
	app.wrapGridSelect(".grid-efs", ".btn", function (d) {
		ll.editLedger(d._id);
		ll.tempCheckIdLedger.push(d._id);
	});
};
ll.editLedger = function(_id){
	ko.mapping.fromJS(ll.templateLedgerList, ll.configLedgerList);
	app.ajaxPost("/account/editaccount", { _id: _id }, function (res) {
		if (!app.isFine(res)) {
			return;
		}

		app.mode("edit");
		app.resetValidation(".form-add-efs");
		ko.mapping.fromJS(res.data, ll.configLedgerList);
		for (var i in res.data.group){
			$('#grouptype').ecLookupDD('addLookup', {_id: res.data.group[i]});
		}
	});
};
ll.backToFront = function(){
	app.mode("");
	ll.getLedgerList();
	$('#grouptype').ecLookupDD('clear');
};
ll.saveLedgerList = function(){
	if (!app.isFormValid(".form-add-efs")) {
		return;
	}
	var param = ko.mapping.toJS(ll.configLedgerList), grouptype = $('#grouptype').ecLookupDD('get'), groupid = [];
	for (var i in grouptype){
		groupid.push(grouptype[i]._id);
	}
	param.group = groupid;
	param.type = parseInt(param.type);
	app.ajaxPost("/account/saveaccount", param, function (res) {
        if (!app.isFine(res)) {
            return;
        }
		ll.backToFront();
    });
};
ll.checkDeleteData = function(elem, e){
	if (e === 'ledger'){
		if ($(elem).prop('checked') === true){
			ll.tempCheckIdLedger.push($(elem).attr('idcheck'));
		} else {
			ll.tempCheckIdLedger.remove( function (item) { return item === $(elem).attr('idcheck'); } );
		}
	} if (e === 'ledgerall'){
		if ($(elem).prop('checked') === true){
			$('.ledgercheck').each(function(index) {
				$(this).prop("checked", true);
				ll.tempCheckIdLedger.push($(this).attr('idcheck'));
			});
		} else {
			var idtemp = '';
			$('.ledgercheck').each(function(index) {
				$(this).prop("checked", false);
				idtemp = $(this).attr('idcheck');
				ll.tempCheckIdLedger.remove( function (item) { return item === idtemp; } );
			});
		}
	}
};

$(function (){
	ll.getMonthDateRange();
	ll.getLedgerList();
	$('#grouptype').ecLookupDD({
		dataSource:{
			url: "/account/getallgroup",
			call: 'post',
			callData: {},
			resultData: function(a){
				return a.data;
			}
		},
		inputType: 'multiple',
		inputSearch: "_id",
		idField: "_id",
		idText: "_id",
		displayFields: "_id",
		statementversion: false,
	});
});<commit_msg>no message<commit_after>app.section('ledgerlist');
viewModel.LedgerList = {}; var ll = viewModel.LedgerList;

ll.templateLedgerList = {
	_id: "",
    title: "",
    type: 1,
    group: [],
    periode: moment().format(),
    opening: "",
    in: 0,
    out: 0,
    balance: 0,
}
ll.templateFilter = {
	startdate: moment().format(),
	enddate: moment().format(),
}
ll.dataType = ko.observableArray([
	{text: "Group", value: 1},
	{text: "Account", value: 0},
]);
ll.searchField = ko.observable('');
ll.configLedgerList = ko.mapping.fromJS(ll.templateLedgerList);
ll.configFilter = ko.mapping.fromJS(ll.templateFilter);
ll.ledgerListData = ko.observableArray([]);
ll.dataGroup = ko.observableArray([]);
ll.tempCheckIdLedger = ko.observableArray([]);
ll.ledgerListColumns = ko.observableArray([
	{headerTemplate: "<input type='checkbox' class='ledgercheckall' onclick=\"ll.checkDeleteData(this, 'ledgerall')\"/>", width: 50, attributes: { style: "text-align: center;" }, template: function (d) {
		return [
			"<input type='checkbox' class='ledgercheck' idcheck='"+d._id+"' onclick=\"ll.checkDeleteData(this, 'ledger')\" />"
		].join(" ");
	}},
	{ field: "_id", title: "ID" },
	{ field: "title", title: "Title" },
	{ field: "type", title: "Type", template: function(d){
		if (d.type == 1)
			return ["Group"].join(" ");
		else
			return ["Account"].join(" ");
	} },
	{ field: "group", title: "Group", template: function (d) {
		var html = [];
		for (var i = 0; i < d.group.length; i++) {
			html.push('' + d.group[i] + '');
		}
		return html.join(', ');
	} },
	// { field: "period", title: "Period" },
	{ field: "opening", title: "Opening" },
	{ field: "in", title: "In" },
	{ field: "out", title: "Out" },
	{ field: "balance", title: "Balance" },
]);

ll.getMonthDateRange = function() {
    var startDate = moment([parseInt(moment().format('YYYY')), parseInt(moment().format('MM')) - 1]);
    var endDate = moment(startDate).endOf('month');
    ll.configFilter.startdate(startDate.toDate());
    ll.configFilter.enddate(endDate.toDate());
}
ll.getLedgerList = function(){
	app.ajaxPost("/account/getaccount", { search: ll.searchField(), startdate: ll.configFilter.startdate(), enddate: ll.configFilter.enddate() }, function (res) {
		if (!app.isFine(res)) {
			return;
		}

		ll.ledgerListData(res.data);
	});
};
ll.addLedgerList = function() {
	app.mode("edit");
	ko.mapping.fromJS(ll.templateLedgerList, ll.configLedgerList);
};
ll.removeLedgerList = function(){
	if (ll.tempCheckIdLedger().length === 0) {
		swal({
			title: "",
			text: 'You havent choose any ledger list to delete',
			type: "warning",
			confirmButtonColor: "#DD6B55",
			confirmButtonText: "OK",
			closeOnConfirm: true
		});
	}else{
		swal({
		    title: "Are you sure?",
		    text: 'Efs(s) '+ll.tempCheckIdLedger().toString()+' will be deleted',
		    type: "warning",
		    showCancelButton: true,
		    confirmButtonColor: "#DD6B55",
		    confirmButtonText: "Delete",
		    closeOnConfirm: true
		}, function() {
			setTimeout(function () {
				app.ajaxPost("/account/removeaccount", { _id: ll.tempCheckIdLedger() }, function (res) {
					if (!app.isFine(res)) {
						return;
					}
					ll.backToFront();
					swal({ title: "Ledger List(s) successfully deleted", type: "success" });
				});
			}, 1000);
		});
	}
};
ll.selectGridLedgerList = function(){
	app.wrapGridSelect(".grid-efs", ".btn", function (d) {
		ll.editLedger(d._id);
		ll.tempCheckIdLedger.push(d._id);
	});
};
ll.editLedger = function(_id){
	ko.mapping.fromJS(ll.templateLedgerList, ll.configLedgerList);
	app.ajaxPost("/account/editaccount", { _id: _id }, function (res) {
		if (!app.isFine(res)) {
			return;
		}

		app.mode("edit");
		app.resetValidation(".form-add-efs");
		ko.mapping.fromJS(res.data, ll.configLedgerList);
		for (var i in res.data.group){
			$('#grouptype').ecLookupDD('addLookup', {_id: res.data.group[i]});
		}
	});
};
ll.backToFront = function(){
	app.mode("");
	ll.getLedgerList();
	$('#grouptype').ecLookupDD('clear');
};
ll.saveLedgerList = function(){
	if (!app.isFormValid(".form-add-efs")) {
		return;
	}
	var param = ko.mapping.toJS(ll.configLedgerList), grouptype = $('#grouptype').ecLookupDD('get'), groupid = [];
	for (var i in grouptype){
		groupid.push(grouptype[i]._id);
	}
	param.group = groupid;
	param.type = parseInt(param.type);
	app.ajaxPost("/account/saveaccount", param, function (res) {
        if (!app.isFine(res)) {
            return;
        }
		ll.backToFront();
    });
};
ll.checkDeleteData = function(elem, e){
	if (e === 'ledger'){
		if ($(elem).prop('checked') === true){
			ll.tempCheckIdLedger.push($(elem).attr('idcheck'));
		} else {
			ll.tempCheckIdLedger.remove( function (item) { return item === $(elem).attr('idcheck'); } );
		}
	} if (e === 'ledgerall'){
		if ($(elem).prop('checked') === true){
			$('.ledgercheck').each(function(index) {
				$(this).prop("checked", true);
				ll.tempCheckIdLedger.push($(this).attr('idcheck'));
			});
		} else {
			var idtemp = '';
			$('.ledgercheck').each(function(index) {
				$(this).prop("checked", false);
				idtemp = $(this).attr('idcheck');
				ll.tempCheckIdLedger.remove( function (item) { return item === idtemp; } );
			});
		}
	}
};

$(function (){
	ll.getMonthDateRange();
	ll.getLedgerList();
	$('#grouptype').ecLookupDD({
		dataSource:{
			url: "/account/getallgroup",
			call: 'post',
			callData: {},
			resultData: function(a){
				return a.data;
			}
		},
		inputType: 'multiple',
		inputSearch: "_id",
		idField: "_id",
		idText: "_id",
		displayFields: "_id",
		statementversion: false,
	});
});<|endoftext|>


<commit_before>$(document).ready(function () {
  var timeData = [],
    temperatureData = [],
    humidityData = [],
  pm2Data = [],
  pm10Data = [];
 //---------yanji start 1/2------------

  //20170913
  var pm10Data = [],
      pm25Data = [];
  var result;
 // android 20170912 23:29
  var humilength = humidityData.length;
  // 20170913
  var templength = temperatureData.length;
  var pm10length = pm10Data.length;
  var pm25length = pm25Data.length;
  var rpmData = [];
  var rpm2Data = [];

   var aaaa = 50;
  //---------yanji end 1/2------------
  document.getElementById("pm2").innerHTML = "50";
  document.getElementById("pm10").innerHTML = "30";
  document.getElementById("temp").innerHTML = "10";
  document.getElementById("humi").innerHTML = "80";
  document.getElementById("rpm").innerHTML = "1200";
  document.getElementById("rpm2").innerHTML = "1000";
  var data = {
    labels: timeData,
    datasets: [
      {
        fill: false,
        label: 'Temp',
        yAxisID: 'Temperature',
        borderColor: "rgba(255, 204, 0, 1)",
        pointBoarderColor: "rgba(255, 204, 0, 1)",
        backgroundColor: "rgba(255, 204, 0, 0.4)",
        pointHoverBackgroundColor: "rgba(255, 204, 0, 1)",
        pointHoverBorderColor: "rgba(255, 204, 0, 1)",
        data: temperatureData
      },
      {
        fill: false,
        label: 'pm2.5',
        yAxisID: 'pm2.5',
        borderColor: "rgba(255, 131, 131, 1)",
        pointBoarderColor: "rgba(255, 131, 131, 1)",
        backgroundColor: "rgba(255, 131, 131, 0.4)",
        pointHoverBackgroundColor: "rgba(255, 131, 131, 1)",
        pointHoverBorderColor: "rgba(255, 131, 131, 1)",
        data: pm2Data
      }
    ]
  }

  var basicOption = {
    title: {
      display: true,
      text: 'Temperature & pm2.5 Real-time Data',
      fontSize: 15
    },
    scales: {
      yAxes: [{
        id: 'Temperature',
        type: 'linear',
        scaleLabel: {
          labelString: 'Temp(C)',
          display: true
        },
        position: 'left',
      }, {
          id: 'pm2.5',
          type: 'linear',
          scaleLabel: {
            labelString: 'pm2.5(ug/m3)',
            display: true
          },
          position: 'right'
        }]
    }
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////

  var data2 = {
    labels: timeData,
    datasets: [
      {
        fill: false,
        label: 'Motor1',
        yAxisID: 'Motor1',
        borderColor: "rgba(255, 204, 0, 1)",
        pointBoarderColor: "rgba(255, 204, 0, 1)",
        backgroundColor: "rgba(255, 204, 0, 0.4)",
        pointHoverBackgroundColor: "rgba(255, 204, 0, 1)",
        pointHoverBorderColor: "rgba(255, 204, 0, 1)",
        data: rpmData
      },
      {
        fill: false,
        label: 'Motor2',
        yAxisID: 'Motor2',
        borderColor: "rgba(255, 131, 131, 1)",
        pointBoarderColor: "rgba(255, 131, 131, 1)",
        backgroundColor: "rgba(255, 131, 131, 0.4)",
        pointHoverBackgroundColor: "rgba(255, 131, 131, 1)",
        pointHoverBorderColor: "rgba(255, 131, 131, 1)",
        data: rpm2Data
      }
    ]
  }

  var basicOption2 = {
    title: {
      display: true,
      text: 'Mortor1 & Mortor2 Real-time Data',
      fontSize: 15
    },
    scales: {
      yAxes: [{
        id: 'Motor1',
        type: 'linear',
        scaleLabel: {
          labelString: 'rpm(r/min)',
          display: true
        },
        position: 'left',
      }, {
          id: 'Motor2',
          type: 'linear',
          scaleLabel: {
            labelString: 'rpm(r/min)',
            display: true
          },
          position: 'right'
        }]
    }
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////

  //Get the context of the canvas element we want to select
  var ctx = document.getElementById("myChart").getContext("2d");
  var optionsNoAnimation = { animation: false }
  var myLineChart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: basicOption
  });
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  var ctx2 = document.getElementById("myChart2").getContext("2d");
  var optionsNoAnimation2 = { animation: false }
  var myLineChart2 = new Chart(ctx2, {
    type: 'line',
    data: data2,
    options: basicOption2
  });
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  var ws = new WebSocket('wss://' + location.host);
  ws.onopen = function () {
    console.log('Successfully connect WebSocket');
  }
  ws.onmessage = function (message) {
    console.log('receive message' + message.data);
    try {
      var obj = JSON.parse(message.data);
      if(!obj.time || !obj.params.Temperature) {
        return;
      }
      document.getElementById("pm2").innerHTML = obj.params.pm2;
  	  document.getElementById("pm10").innerHTML = obj.params.pm10;
	  document.getElementById("temp").innerHTML = obj.params.Temperature;
	  document.getElementById("humi").innerHTML = obj.params.Humidity;
	  document.getElementById("rpm").innerHTML = obj.params.rpm;
	  document.getElementById("rpm2").innerHTML = obj.params.rpm2;
      timeData.push(obj.time);
      temperatureData.push(obj.params.Temperature);
      // only keep no more than 50 points in the line chart
      const maxLen = 10;
      var len = timeData.length;
      if (len > maxLen) {
        timeData.shift();
        temperatureData.shift();
      }

      if (obj.params.Humidity) {
        humidityData.push(obj.params.Humidity);
      }
      if (humidityData.length > maxLen) {
        humidityData.shift();
      }
	  if (obj.params.pm2) {
		  pm2Data.push(obj.params.pm2);
	  }
	  if (pm2Data.length > maxLen)
	  {
		  pm2Data.shift();
	  }
	  if (obj.params.rpm) {
		  rpmData.push(obj.params.rpm);
	  }
	  if (rpmData.length > maxLen)
	  {
		  rpmData.shift();
	  }
	  if (obj.params.rpm2) {
		  rpm2Data.push(obj.params.rpm2);
	  }
	  if (rpm2Data.length > maxLen)
	  {
		  rpm2Data.shift();
	  }

 myLineChart2.update();

      myLineChart.update();

 //---------yanji start 2/2------------
  //20170913 pm Data push
      pm10Data.push(obj.params.pm10);
      pm25Data.push(obj.params.pm2);

      //android 20170912 23:29
//       if(humilength==0 || templength == 0 || pm10length ==0 || pm25length ==0){

//            }
//           }else{
//             humilength = humidityData.length;
//             templength = temperatureData.length;
//             pm10length = pm10Data.length;
//             pm25length = pm25Data.length;
//            insertDatas(pm25Data[pm25length],humidityData[humilength],temperatureData[templength],humidityData[humilength]);
//         }
      //20170913

     if((pm25length<pm25Data.length || pm25length == pm25Data.length)&&(pm10length<pm10Data.length || pm10length == pm10Data.length)&&(templength<temperatureData.length || templength == temperatureData.length)&&(humilength<humidityData.length || humilength == humidityData.length)){
          pm25length = pm25Data.length;
          pm10length = pm10Data.length;
          humilength = humidityData.length;
          templength = temperatureData.length;

          insertDatas(pm25Data[pm25length-1],pm10Data[pm10length-1],temperatureData[templength-1],humidityData[humilength-1]);

          }

      //android 20170912 23:29
      function insertDatas(p2,p1,t,h){
         var p2State;
         if(p2<31){
           p2State = "좋음";
         }else if(p2<81){
           p2State = "보통";
         }else if(p2<151){
           p2State = "나쁨";
         }else{
           p2State = "매우나쁨";
         }
         Ao.showResult(p2,p1,t,h,p2State);
      }

//---------yanji end 2/2------------

    } catch (err) {
      console.error(err);
    }
  }
});
<commit_msg>Update index.js<commit_after>$(document).ready(function () {
  var timeData = [],
    temperatureData = [],
    humidityData = [],
  pm2Data = [],
  pm10Data = [];
 //---------yanji start 1/2------------

  //20170913
  var pm10Data = [],
      pm25Data = [];
  var result;
 // android 20170912 23:29
  var humilength = humidityData.length;
  // 20170913
  var templength = temperatureData.length;
  var pm10length = pm10Data.length;
  var pm25length = pm25Data.length;
  var rpmData = [];
  var rpm2Data = [];

   var aaaa = 50;
  //---------yanji end 1/2------------
  document.getElementById("pm2").innerHTML = "50";
  document.getElementById("pm10").innerHTML = "30";
  document.getElementById("temp").innerHTML = "10";
  document.getElementById("humi").innerHTML = "80";
  document.getElementById("rpm").innerHTML = "1200";
  document.getElementById("rpm2").innerHTML = "1000";
  var data = {
    labels: timeData,
    datasets: [
      {
        fill: false,
        label: 'Temp',
        yAxisID: 'Temperature',
        borderColor: "rgba(255, 204, 0, 1)",
        pointBoarderColor: "rgba(255, 204, 0, 1)",
        backgroundColor: "rgba(255, 204, 0, 0.4)",
        pointHoverBackgroundColor: "rgba(255, 204, 0, 1)",
        pointHoverBorderColor: "rgba(255, 204, 0, 1)",
        data: temperatureData
      },
      {
        fill: false,
        label: 'pm2.5',
        yAxisID: 'pm2.5',
        borderColor: "rgba(255, 131, 131, 1)",
        pointBoarderColor: "rgba(255, 131, 131, 1)",
        backgroundColor: "rgba(255, 131, 131, 0.4)",
        pointHoverBackgroundColor: "rgba(255, 131, 131, 1)",
        pointHoverBorderColor: "rgba(255, 131, 131, 1)",
        data: pm2Data
      }
    ]
  }

  var basicOption = {
    title: {
      display: true,
      text: 'Temperature & pm2.5 Real-time Data',
      fontSize: 15
    },
    scales: {
      yAxes: [{
        id: 'Temperature',
        type: 'linear',
        scaleLabel: {
          labelString: 'Temp(C)',
          display: true
        },
        position: 'left',
      }, {
          id: 'pm2.5',
          type: 'linear',
          scaleLabel: {
            labelString: 'pm2.5(ug/m3)',
            display: true
          },
          position: 'right'
        }]
    }
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////

  var data2 = {
    labels: timeData,
    datasets: [
      {
        fill: false,
        label: 'Motor1',
        yAxisID: 'Motor1',
        borderColor: "rgba(255, 204, 0, 1)",
        pointBoarderColor: "rgba(255, 204, 0, 1)",
        backgroundColor: "rgba(255, 204, 0, 0.4)",
        pointHoverBackgroundColor: "rgba(255, 204, 0, 1)",
        pointHoverBorderColor: "rgba(255, 204, 0, 1)",
        data: rpmData
      },
      {
        fill: false,
        label: 'Motor2',
        yAxisID: 'Motor2',
        borderColor: "rgba(255, 131, 131, 1)",
        pointBoarderColor: "rgba(255, 131, 131, 1)",
        backgroundColor: "rgba(255, 131, 131, 0.4)",
        pointHoverBackgroundColor: "rgba(255, 131, 131, 1)",
        pointHoverBorderColor: "rgba(255, 131, 131, 1)",
        data: rpm2Data
      }
    ]
  }

  var basicOption2 = {
    title: {
      display: true,
      text: 'Mortor1 & Mortor2 Real-time Data',
      fontSize: 15
    },
    scales: {
      yAxes: [{
        id: 'Motor1',
        type: 'linear',
        scaleLabel: {
          labelString: 'rpm(r/min)',
          display: true
        },
        position: 'left',
      }, {
          id: 'Motor2',
          type: 'linear',
          scaleLabel: {
            labelString: 'rpm(r/min)',
            display: true
          },
          position: 'right'
        }]
    }
  }

  ///////////////////////////////////////////////////////////////////////////////////////////////////

  //Get the context of the canvas element we want to select
  var ctx = document.getElementById("myChart").getContext("2d");
  var optionsNoAnimation = { animation: false }
  var myLineChart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: basicOption
  });
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  var ctx2 = document.getElementById("myChart2").getContext("2d");
  var optionsNoAnimation2 = { animation: false }
  var myLineChart2 = new Chart(ctx2, {
    type: 'line',
    data: data2,
    options: basicOption2
  });
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  var ws = new WebSocket('wss://' + location.host);
  ws.onopen = function () {
    console.log('Successfully connect WebSocket');
  }
  ws.onmessage = function (message) {
    console.log('receive message' + message.data);
    try {
      var obj = JSON.parse(message.data);
      if(!obj.time || !obj.params.Temperature) {
        return;
      }
      document.getElementById("pm2").innerHTML = obj.params.pm2;
  	  document.getElementById("pm10").innerHTML = obj.params.pm10;
	  document.getElementById("temp").innerHTML = obj.params.Temperature;
	  document.getElementById("humi").innerHTML = obj.params.Humidity;
	  document.getElementById("rpm").innerHTML = obj.params.rpm;
	  document.getElementById("rpm2").innerHTML = obj.params.rpm2;
      timeData.push(obj.time);
      temperatureData.push(obj.params.Temperature);
      // only keep no more than 50 points in the line chart
      const maxLen = 10;
      var len = timeData.length;
      if (len > maxLen) {
        timeData.shift();
        temperatureData.shift();
      }

      if (obj.params.Humidity) {
        humidityData.push(obj.params.Humidity);
      }
      if (humidityData.length > maxLen) {
        humidityData.shift();
      }
	  if (obj.params.pm2) {
		  pm2Data.push(obj.params.pm2);
	  }
	  if (pm2Data.length > maxLen)
	  {
		  pm2Data.shift();
	  }
	  if (obj.params.rpm) {
		  alert(obj.params.rpm);
		  rpmData.push(obj.params.rpm);
	  }
	  if (rpmData.length > maxLen)
	  {
		  rpmData.shift();
	  }
	  if (obj.params.rpm2) {
		  rpm2Data.push(obj.params.rpm2);
	  }
	  if (rpm2Data.length > maxLen)
	  {
		  rpm2Data.shift();
	  }

 myLineChart2.update();

      myLineChart.update();

 //---------yanji start 2/2------------
  //20170913 pm Data push
      pm10Data.push(obj.params.pm10);
      pm25Data.push(obj.params.pm2);

      //android 20170912 23:29
//       if(humilength==0 || templength == 0 || pm10length ==0 || pm25length ==0){

//            }
//           }else{
//             humilength = humidityData.length;
//             templength = temperatureData.length;
//             pm10length = pm10Data.length;
//             pm25length = pm25Data.length;
//            insertDatas(pm25Data[pm25length],humidityData[humilength],temperatureData[templength],humidityData[humilength]);
//         }
      //20170913

     if((pm25length<pm25Data.length || pm25length == pm25Data.length)&&(pm10length<pm10Data.length || pm10length == pm10Data.length)&&(templength<temperatureData.length || templength == temperatureData.length)&&(humilength<humidityData.length || humilength == humidityData.length)){
          pm25length = pm25Data.length;
          pm10length = pm10Data.length;
          humilength = humidityData.length;
          templength = temperatureData.length;

          insertDatas(pm25Data[pm25length-1],pm10Data[pm10length-1],temperatureData[templength-1],humidityData[humilength-1]);

          }

      //android 20170912 23:29
      function insertDatas(p2,p1,t,h){
         var p2State;
         if(p2<31){
           p2State = "좋음";
         }else if(p2<81){
           p2State = "보통";
         }else if(p2<151){
           p2State = "나쁨";
         }else{
           p2State = "매우나쁨";
         }
         Ao.showResult(p2,p1,t,h,p2State);
      }

//---------yanji end 2/2------------

    } catch (err) {
      console.error(err);
    }
  }
});
<|endoftext|>


<commit_before>define(['jquery'], function ($) {
  var Carousel = function (target) {
    var self = this;

    // ELEMENT REFERENCES ---------------------------------------------------

    self.$wrapper = $(target);
    self.$toggleButtonContainer = $('.mentor-story-nav', target);
    self.$toggleButtons = $('.mentor-story-nav a', target);
    self.$nextButton = $('.go-forward', target);
    self.$backButton = $('.go-back', target);
    self.$slides = $('.poster-image-container div', target);
    self.$spinner = $('.spinner', target);

    // PROPERTIES -----------------------------------------------------------

    self.totalStories = self.$slides.length;
    self.imageLoading = false;

    // SETUP ----------------------------------------------------------------

    var randomIndex = Math.floor(Math.random() * self.totalStories);

    self.changeStory(self.getStoryByNumber(randomIndex));

    // EVENT BINDING --------------------------------------------------------

    self.$toggleButtons.on('click', function () {
      var storyId = this.getAttribute('data-id');

      self.changeStory(storyId);
    });

    self.$nextButton.on('click', function () {
      var currentIndex = $('.mentor-story-nav a').index($('.mentor-story-nav a.active'));
      var storyId = self.getStoryByNumber(currentIndex + 1);

      self.changeStory(storyId);
    });

    self.$backButton.on('click', function () {
      var currentIndex = $('.mentor-story-nav a').index($('.mentor-story-nav a.active'));
      var storyId = self.getStoryByNumber(currentIndex - 1);

      self.changeStory(storyId);
    });
  };

  Carousel.prototype.changeStory = function (storyId) {
    var self = this;
    var $posterWrapper = $('#poster-' + storyId);
    var $posterImg = $('img', $posterWrapper);

    function showStory() {
      $posterWrapper.css('background-image', 'url(' + $posterImg.data('src') + ')').addClass('active');
      self.imageLoading = false;
    }

    self.$toggleButtons.removeClass('active');

    $('.mentor-story-nav a[data-id="' + storyId + '"]').addClass('active');
    $('.mentor-stories article.active').removeClass('active');
    $('.poster-image-container > div.active').removeClass('active');
    $('#story-' + storyId).addClass('active');

    self.imageLoading = true;

    // Lazy load poster frame if needed
    if (!$posterImg.attr('src')) {
      self.showSpinner();

      $posterImg.one('load', function () {
        self.$spinner.hide();
        showStory();
      });

      $posterImg.attr('src', $posterImg.data('src'));
    } else {
      showStory();
    }

    var currentIndex = $('.mentor-story-nav a').index($('.mentor-story-nav a.active'));

    if (currentIndex === 0) {
      self.$backButton.hide();
    } else {
      self.$backButton.show();
    }

    if (currentIndex >= self.totalStories - 1) {
      self.$nextButton.hide();
    } else {
      self.$nextButton.show();
    }
  };

  Carousel.prototype.showSpinner = function () {
    var self = this;

    // Delay showing spinner a bit in case image is cached or loads fast
    setTimeout(function () {
      if (self.imageLoading) {
        self.$spinner.show();
      }
    }, 500);
  };

  Carousel.prototype.getStoryByNumber = function (n) {
    var self = this;

    // Convert 0 index > selector nth-child, which starts with one
    n = n + 1;
    return self.$toggleButtonContainer.find('a:nth-child(' + n + ')').attr('data-id');
  };

  return Carousel;
});
<commit_msg>GA Event Tracking on Carousel<commit_after>define(['jquery', 'analytics'], function ($, analytics) {
  var Carousel = function (target) {
    var self = this;

    // ELEMENT REFERENCES ---------------------------------------------------

    self.$wrapper = $(target);
    self.$toggleButtonContainer = $('.mentor-story-nav', target);
    self.$toggleButtons = $('.mentor-story-nav a', target);
    self.$nextButton = $('.go-forward', target);
    self.$backButton = $('.go-back', target);
    self.$slides = $('.poster-image-container div', target);
    self.$spinner = $('.spinner', target);

    // PROPERTIES -----------------------------------------------------------

    self.totalStories = self.$slides.length;
    self.imageLoading = false;

    // SETUP ----------------------------------------------------------------

    var randomIndex = Math.floor(Math.random() * self.totalStories);

    self.changeStory(self.getStoryByNumber(randomIndex));

    // EVENT BINDING --------------------------------------------------------

    self.$toggleButtons.on('click', function () {
      var storyId = this.getAttribute('data-id');

      self.changeStory(storyId);
      analytics.event("Click Homepage Carousel", {label: "Toggle Index"});
    });

    self.$nextButton.on('click', function () {
      var currentIndex = $('.mentor-story-nav a').index($('.mentor-story-nav a.active'));
      var storyId = self.getStoryByNumber(currentIndex + 1);

      self.changeStory(storyId);
      analytics.event("Click Homepage Carousel", {label: "Next"});
    });

    self.$backButton.on('click', function () {
      var currentIndex = $('.mentor-story-nav a').index($('.mentor-story-nav a.active'));
      var storyId = self.getStoryByNumber(currentIndex - 1);

      self.changeStory(storyId);
      analytics.event("Click Homepage Carousel", {label: "Back"});
    });
  };

  Carousel.prototype.changeStory = function (storyId) {
    var self = this;
    var $posterWrapper = $('#poster-' + storyId);
    var $posterImg = $('img', $posterWrapper);

    function showStory() {
      $posterWrapper.css('background-image', 'url(' + $posterImg.data('src') + ')').addClass('active');
      self.imageLoading = false;
    }

    self.$toggleButtons.removeClass('active');

    $('.mentor-story-nav a[data-id="' + storyId + '"]').addClass('active');
    $('.mentor-stories article.active').removeClass('active');
    $('.poster-image-container > div.active').removeClass('active');
    $('#story-' + storyId).addClass('active');

    self.imageLoading = true;

    // Lazy load poster frame if needed
    if (!$posterImg.attr('src')) {
      self.showSpinner();

      $posterImg.one('load', function () {
        self.$spinner.hide();
        showStory();
      });

      $posterImg.attr('src', $posterImg.data('src'));
    } else {
      showStory();
    }

    var currentIndex = $('.mentor-story-nav a').index($('.mentor-story-nav a.active'));

    if (currentIndex === 0) {
      self.$backButton.hide();
    } else {
      self.$backButton.show();
    }

    if (currentIndex >= self.totalStories - 1) {
      self.$nextButton.hide();
    } else {
      self.$nextButton.show();
    }
  };

  Carousel.prototype.showSpinner = function () {
    var self = this;

    // Delay showing spinner a bit in case image is cached or loads fast
    setTimeout(function () {
      if (self.imageLoading) {
        self.$spinner.show();
      }
    }, 500);
  };

  Carousel.prototype.getStoryByNumber = function (n) {
    var self = this;

    // Convert 0 index > selector nth-child, which starts with one
    n = n + 1;
    return self.$toggleButtonContainer.find('a:nth-child(' + n + ')').attr('data-id');
  };

  return Carousel;
});
<|endoftext|>


<commit_before><commit_msg>DevTools: Turn pause on exceptions off by default (as in Web Inspector and Firebug).<commit_after><|endoftext|>


<commit_before>import { List as list } from 'immutable';
import React, { useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { DateTime } from 'luxon';
import { compose } from 'redux';

import { dataPropTypes } from '~client/prop-types/net-worth/view';
import { SumCashEasyAccess, SumCashOther, SumStocks, SumPension } from '~client/components/NetWorthView/sum-by-category';
import NetWorthViewRow from '~client/components/NetWorthView/net-worth-view-row';

import './style.scss';

const withIsoDates = data => data.map(({ date, ...rest }) => ({
    date,
    dateIso: DateTime.fromISO(date),
    ...rest
}));

const sortByIsoDate = rows => rows.sort(({ dateIso: dateA }, { dateIso: dateB }) => dateA - dateB);

const withoutSkipValues = rows => rows.map(({ values, ...rest }) => ({
    values: values.filter(({ skip }) => !skip),
    ...rest
}));

const FTI_START = DateTime.fromISO(process.env.BIRTH_DATE);

const withFTI = rows => rows.map((row, index) => {
    const { years } = row.dateIso.diff(FTI_START, 'years').toObject();

    const pastYear = rows.slice(Math.max(0, index - 11), index + 1);
    const pastYearAverageSpend = pastYear.reduce((sum, { spend }) => sum + spend, 0) * 12 / pastYear.length;

    const fti = netWorthValue => netWorthValue * years / pastYearAverageSpend;

    return { ...row, fti };
});

export default function NetWorthView({ rowDates, spending, data, categories, subcategories, page, setPage, numPages }) {
    const netWorthDateToRowIndex = useCallback(date => rowDates.findIndex(value =>
        value.year === date.year && value.month === date.month
    ), [rowDates]);

    const withSpend = useCallback(rows => rows.map(row => {
        let spend = 0;
        const rowIndex = netWorthDateToRowIndex(row.dateIso);
        if (rowIndex !== -1) {
            spend = spending.get(rowIndex);
        }

        return { ...row, spend };
    }), [spending, netWorthDateToRowIndex]);

    const rows = useMemo(() => compose(
        withFTI,
        withSpend,
        withoutSkipValues,
        sortByIsoDate,
        withIsoDates
    )(data || []), [data, withSpend]);

    if (!(categories && subcategories)) {
        return null;
    }

    const dataProps = { rows, categories, subcategories };

    return (

{'View'}

                        <SumCashEasyAccess {...dataProps} />
                        <SumStocks {...dataProps} />
                        {'Assets'}
                        {'Liabilities'}
                        {'Net Worth'}
                        {'Expenses'}
                        {'FTI'}

                        <SumCashOther {...dataProps} />
                        <SumPension {...dataProps} />
                        {'Total (£)'}
                        {'Total (£)'}

                            {'Can retire when FTI > 1000 consistently'}

                        {'Date'}

                    {rows.map(row => (
                        <NetWorthViewRow key={row.id} row={row} {...dataProps} />
                    ))}

                {'Page: '}

{new Array(numPages).fill(0)
                    .map((item, index) => (

 setPage(index)}
                            className={classNames({ active: page === index })}
                        >{index + 1}

                    ))
                }

    );
}

NetWorthView.propTypes = {
    page: PropTypes.number,
    setPage: PropTypes.func.isRequired,
    numPages: PropTypes.number,
    rowDates: PropTypes.instanceOf(list).isRequired,
    spending: PropTypes.instanceOf(list).isRequired,
    ...dataPropTypes
};
<commit_msg>[rm immutable] <NetWorthView /><commit_after>import React, { useCallback, useMemo } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { DateTime } from 'luxon';
import { compose } from 'redux';

import { dataPropTypes } from '~client/prop-types/net-worth/view';
import { SumCashEasyAccess, SumCashOther, SumStocks, SumPension } from '~client/components/NetWorthView/sum-by-category';
import NetWorthViewRow from '~client/components/NetWorthView/net-worth-view-row';

import './style.scss';

const withIsoDates = data => data.map(({ date, ...rest }) => ({
    date,
    dateIso: DateTime.fromISO(date),
    ...rest
}));

const sortByIsoDate = rows => rows.sort(({ dateIso: dateA }, { dateIso: dateB }) => dateA - dateB);

const withoutSkipValues = rows => rows.map(({ values, ...rest }) => ({
    values: values.filter(({ skip }) => !skip),
    ...rest
}));

const FTI_START = DateTime.fromISO(process.env.BIRTH_DATE);

const withFTI = rows => rows.map((row, index) => {
    const { years } = row.dateIso.diff(FTI_START, 'years').toObject();

    const pastYear = rows.slice(Math.max(0, index - 11), index + 1);
    const pastYearAverageSpend = pastYear.reduce((sum, { spend }) => sum + spend, 0) * 12 / pastYear.length;

    const fti = netWorthValue => netWorthValue * years / pastYearAverageSpend;

    return { ...row, fti };
});

export default function NetWorthView({ rowDates, spending, data, categories, subcategories, page, setPage, numPages }) {
    const netWorthDateToRowIndex = useCallback(date => rowDates.findIndex(value =>
        value.year === date.year && value.month === date.month
    ), [rowDates]);

    const withSpend = useCallback(rows => rows.map(row => {
        let spend = 0;
        const rowIndex = netWorthDateToRowIndex(row.dateIso);
        if (rowIndex !== -1) {
            spend = spending.get(rowIndex);
        }

        return { ...row, spend };
    }), [spending, netWorthDateToRowIndex]);

    const rows = useMemo(() => compose(
        withFTI,
        withSpend,
        withoutSkipValues,
        sortByIsoDate,
        withIsoDates
    )(data || []), [data, withSpend]);

    if (!(categories && subcategories)) {
        return null;
    }

    const dataProps = { rows, categories, subcategories };

    return (

{'View'}

                        <SumCashEasyAccess {...dataProps} />
                        <SumStocks {...dataProps} />
                        {'Assets'}
                        {'Liabilities'}
                        {'Net Worth'}
                        {'Expenses'}
                        {'FTI'}

                        <SumCashOther {...dataProps} />
                        <SumPension {...dataProps} />
                        {'Total (£)'}
                        {'Total (£)'}

                            {'Can retire when FTI > 1000 consistently'}

                        {'Date'}

                    {rows.map(row => (
                        <NetWorthViewRow key={row.id} row={row} {...dataProps} />
                    ))}

                {'Page: '}

{new Array(numPages).fill(0)
                    .map((item, index) => (

 setPage(index)}
                            className={classNames({ active: page === index })}
                        >{index + 1}

                    ))
                }

    );
}

NetWorthView.propTypes = {
    page: PropTypes.number,
    setPage: PropTypes.func.isRequired,
    numPages: PropTypes.number,
    rowDates: PropTypes.arrayOf(PropTypes.instanceOf(DateTime).isRequired).isRequired,
    spending: PropTypes.arrayOf(PropTypes.number.isRequired).isRequired,
    ...dataPropTypes
};
<|endoftext|>


<commit_before>$(document).ready(function () {

	//variables declaration
	var tableData=[], tableDataReverse=[];

	//Display empty chart initially
	$("#chart").shieldChart({
                theme: "light",
                exportOptions: {
                    image: false,
                    print: false
                },
                primaryHeader: {
                    text: "Pressure, termperature and vibration statistics over six interval"
                },
                zoomMode: "xy",
                seriesSettings: {
                    bar: {
                        barOffset: 0
                    }
                },
                axisX: {
                    categoricalValues: ["1st", "2nd", "3rd", "4th", "5th", "6th"]
                },
                axisY: {
                    title: {
                        text: "Value statistics"
                    }
                },
                dataSeries: [{
                    seriesType: "bar",
                    collectionAlias: "Pressure",
                    data: [0, 0, 0, 0, 0, 0]
                }, {
                    seriesType: "bar",
                    collectionAlias: "Temperature",
                    data: [0, 0, 0, 0, 0, 0]
                }, {
                    seriesType: "bar",
                    collectionAlias: "Vibration",
                    data: [0, 0, 0, 0]
                }]
            });

	$("#grid").shieldGrid({
            dataSource: {
				data: tableDataReverse
			},
			events: {
                dataBound: gridDataBound
            },
			rowHover: false,
            scrolling: {
                virtual: true
            },
            sorting: true,
            columnReorder: true,
            columns: [
                { field: "key", title: "Key" },
                { field: "value", title: "Value" }
            ]
        });

	//updating table (live)
    function refreshGird() {
        var grid = $("#grid").swidget(),
            initialOptions = grid.initialOptions;
        initialOptions.dataSource = {
            data: tableDataReverse
        };
        grid.refresh(initialOptions);
    }

	//styling table (assigning red/green colour)
	function gridDataBound(e) {
		var data = e.target.dataSource.view;
		var rows = e.target.contentTable.find(">tbody>tr");
		for (var i = 0; i < data.length; i++) {
            var item = data[i];
            if (item.message == thresholdMsg) {
                $(rows[i].cells[3]).addClass("red");
            }
            if (item.message == msg) {
                $(rows[i].cells[3]).addClass("green");
            }
        }
    }

	//websocket connection
	var ws = new WebSocket('wss://' + location.host);

	ws.onopen = function () {
		console.log('Successfully connect WebSocket');
	}

	//websocket receiving messages
	ws.onmessage = function (message) {
		console.log('Receive message via websocket in client side: ' + message.data);
		try {
			var obj = JSON.parse(message.data);

			$("#chart").shieldChart({
                theme: "light",
                exportOptions: {
                    image: false,
                    print: false
                },
                primaryHeader: {
                    text: "Pressure, termperature and vibration statistics over six interval"
                },
                zoomMode: "xy",
                seriesSettings: {
                    bar: {
                        barOffset: 0
                    }
                },
                axisX: {
                    categoricalValues: ["1st", "2nd", "3rd", "4th", "5th", "6th"]
                },
                axisY: {
                    title: {
                        text: "Value statistics"
                    }
                },
                dataSeries: [{
                    seriesType: "bar",
                    collectionAlias: "Pressure",
                    data: [parseInt(obj.pressure[0].Value), parseInt(obj.pressure[1].Value), parseInt(obj.pressure[2].Value), parseInt(obj.pressure[3].Value), parseInt(obj.pressure[4].Value), parseInt(obj.pressure[5].Value)]
                }, {
                    seriesType: "bar",
                    collectionAlias: "Temperature",
                    data: [parseInt(obj.temp[0].Value), parseInt(obj.temp[1].Value), parseInt(obj.temp[2].Value), parseInt(obj.temp[3].Value), parseInt(obj.temp[4].Value), parseInt(obj.temp[5].Value)]
                }, {
                    seriesType: "bar",
                    collectionAlias: "Vibration",
                    data: [parseInt(obj.vibration[0].Value), parseInt(obj.vibration[1].Value), parseInt(obj.vibration[2].Value), parseInt(obj.vibration[3].Value)]
                }]
            });

						tableData.push({
							key: "Time of reading",
							value: obj.timeOfReading
						});
						tableData.push({
							key: "Internal temperature",
							value: obj.internalTemperature
						});
						tableData.push({
							key: "Daily flow",
							value: obj.dailyFlow
						});
						tableData.push({
							key: "Daily reverse flow",
							value: obj.dailyReverseFlow
						});
						tableData.push({
							key: "Peak flow rate",
							value: obj.peakFlowRate
						});
						tableData.push({
							key: "Peak flow rate time",
							value: obj.peakFlowRateTime
						});
						tableData.push({
							key: "Event time",
							value: obj.eventTime
						});

			tableDataReverse = tableData.slice(0);

			refreshGird();
			}
		catch (err) {
		  console.error(err);
		}
	}
});<commit_msg>trying grid code21<commit_after>$(document).ready(function () {

	//variables declaration
	var tableData=[], tableDataReverse=[];

	//Display empty chart initially
	$("#chart").shieldChart({
                theme: "light",
                exportOptions: {
                    image: false,
                    print: false
                },
                primaryHeader: {
                    text: "Pressure, termperature and vibration statistics over six interval"
                },
                zoomMode: "xy",
                seriesSettings: {
                    bar: {
                        barOffset: 0
                    }
                },
                axisX: {
                    categoricalValues: ["1st", "2nd", "3rd", "4th", "5th", "6th"]
                },
                axisY: {
                    title: {
                        text: "Value statistics"
                    }
                },
                dataSeries: [{
                    seriesType: "bar",
                    collectionAlias: "Pressure",
                    data: [0, 0, 0, 0, 0, 0]
                }, {
                    seriesType: "bar",
                    collectionAlias: "Temperature",
                    data: [0, 0, 0, 0, 0, 0]
                }, {
                    seriesType: "bar",
                    collectionAlias: "Vibration",
                    data: [0, 0, 0, 0]
                }]
            });

	$("#grid").shieldGrid({
            dataSource: {
				data: tableDataReverse
			},
			events: {
                dataBound: gridDataBound
            },
			rowHover: false,
            scrolling: {
                virtual: true
            },
            sorting: true,
            columnReorder: true,
            columns: [
                { field: "key", title: "Key" },
                { field: "value", title: "Value" }
            ]
        });

	//updating table (live)
    function refreshGird() {
        var grid = $("#grid").swidget(),
            initialOptions = grid.initialOptions;
        initialOptions.dataSource = {
            data: tableDataReverse
        };
        grid.refresh(initialOptions);
    }

	//styling table (assigning red/green colour)
	function gridDataBound(e) {
		var data = e.target.dataSource.view;
		var rows = e.target.contentTable.find(">tbody>tr");
		for (var i = 0; i < data.length; i++) {
            var item = data[i];
            if (item.message == thresholdMsg) {
                $(rows[i].cells[3]).addClass("red");
            }
            if (item.message == msg) {
                $(rows[i].cells[3]).addClass("green");
            }
        }
    }

	//websocket connection
	var ws = new WebSocket('wss://' + location.host);

	ws.onopen = function () {
		console.log('Successfully connect WebSocket');
	}

	//websocket receiving messages
	ws.onmessage = function (message) {
		console.log('Receive message via websocket in client side: ' + message.data);
		try {
			var obj = JSON.parse(message.data);

			$("#chart").shieldChart({
                theme: "light",
                exportOptions: {
                    image: false,
                    print: false
                },
                primaryHeader: {
                    text: "Pressure, termperature and vibration statistics over six interval"
                },
                zoomMode: "xy",
                seriesSettings: {
                    bar: {
                        barOffset: 0
                    }
                },
                axisX: {
                    categoricalValues: ["1st", "2nd", "3rd", "4th", "5th", "6th"]
                },
                axisY: {
                    title: {
                        text: "Value statistics"
                    }
                },
                dataSeries: [{
                    seriesType: "bar",
                    collectionAlias: "Pressure",
                    data: [parseInt(obj.pressure[0].Value), parseInt(obj.pressure[1].Value), parseInt(obj.pressure[2].Value), parseInt(obj.pressure[3].Value), parseInt(obj.pressure[4].Value), parseInt(obj.pressure[5].Value)]
                }, {
                    seriesType: "bar",
                    collectionAlias: "Temperature",
                    data: [parseInt(obj.temp[0].Value), parseInt(obj.temp[1].Value), parseInt(obj.temp[2].Value), parseInt(obj.temp[3].Value), parseInt(obj.temp[4].Value), parseInt(obj.temp[5].Value)]
                }, {
                    seriesType: "bar",
                    collectionAlias: "Vibration",
                    data: [parseInt(obj.vibration[0].Value), parseInt(obj.vibration[1].Value), parseInt(obj.vibration[2].Value), parseInt(obj.vibration[3].Value)]
                }]
            });

						tableData.push({
							key: "Time of reading",
							value: obj.timeOfReading
						});
						tableData.push({
							key: "Internal temperature",
							value: obj.internalTemperature
						});
						tableData.push({
							key: "Daily flow",
							value: obj.dailyFlow
						});
						tableData.push({
							key: "Daily reverse flow",
							value: obj.dailyReverseFlow
						});
						tableData.push({
							key: "Peak flow rate",
							value: obj.peakFlowRate
						});
						tableData.push({
							key: "Peak flow rate time",
							value: obj.peakFlowRateTime
						});
						tableData.push({
							key: "Event time",
							value: obj.eventTime
						});

			tableDataReverse = tableData.slice(0);

			$("#grid").shieldGrid({
            dataSource: {
				data: tableDataReverse
			},
			events: {
                dataBound: gridDataBound
            },
			rowHover: false,
            scrolling: {
                virtual: true
            },
            sorting: true,
            columnReorder: true,
            columns: [
                { field: "key", title: "Key" },
                { field: "value", title: "Value" }
            ]
			});

			//refreshGird();
			}
		catch (err) {
		  console.error(err);
		}
	}
});<|endoftext|>


<commit_before>import React        from 'react';
import { connect }  from 'react-redux';
import LogoutButton from '../sessions/logout_button';
import Spinner      from '../spinner';

class Header extends React.Component {
  render() {
    const { currentUser } = this.props;

    return (

            <Spinner />

            { currentUser.first_name } { currentUser.last_name }

            <LogoutButton />

    );
  }
}

const mapStateToProps = (state) => ({
  currentUser: state.session.currentUser
});

export default connect(mapStateToProps)(Header);
<commit_msg>fix header<commit_after>import React        from 'react';
import { connect }  from 'react-redux';
import LogoutButton from '../sessions/logout_button';
import Spinner      from '../spinner';

class Header extends React.Component {
  render() {
    const { currentUser } = this.props;

    return (

            <Spinner />

            { currentUser.first_name } { currentUser.last_name }

            <LogoutButton />

    );
  }
}

const mapStateToProps = (state) => ({
  currentUser: state.session.currentUser
});

export default connect(mapStateToProps)(Header);
<|endoftext|>


<commit_before>angular.module('PassApp')
.factory('ApiService', function($http){
	var o = {};
	var baseUrl = "http://localhost:3000";

	o.getResults = function(id){
		console.log(id);
		return;
	}

	o.postResults = function(data){
		console.log(data);
		$http.post(baseUrl + '/result', data).then(function(response){
			console.log(response);
		}).catch(function(err){
			console.log("Error on posting results");
		})
	}

	return o;
})<commit_msg>Add get result by id to api service<commit_after>angular.module('PassApp')
.factory('ApiService', function($http, $q){
	var o = {};
	var baseUrl = "http://localhost:3000";

	o.createExam = function(data){
		$http.post(baseUrl + '/exam', data).then(function(response){
			console.log(response);
		}).catch(function(err){
			console.log("Error creating exams");
		});
	}

	o.postResults = function(data){
		console.log(data);
		$http.post(baseUrl + '/result', data).then(function(response){
			console.log(response);
		}).catch(function(err){
			console.log("Error on posting results");
		})
	}

	return o;
})<|endoftext|>