<commit_before>'use strict';

(function() {
  angular.module('ncsaas')
    .service('baseEventListController', [
      'baseControllerListClass', 'eventsService', 'EVENTTYPE', baseEventListController]);

  function baseEventListController(baseControllerListClass, eventsService, EVENTTYPE) {
    var ControllerListClass = baseControllerListClass.extend({
      EVENTTYPE: EVENTTYPE,

      init:function() {
        this.service = eventsService;
        this.searchFieldName = 'search';
        this.searchFilters = [
          {
            name: 'event_type',
            title: 'Logged in',
            value: EVENTTYPE.auth_logged_in_with_username
          },
          {
            name: 'event_type',
            title: 'Project creation',
            value: EVENTTYPE.project_creation_succeeded
          },
          {
            name: 'event_type',
            title: 'Organization creation',
            value: EVENTTYPE.customer_creation_succeeded
          }
        ];
        this._super();
      }
    });

    return ControllerListClass;
  }

  angular.module('ncsaas')
    .controller('EventListController', [
      '$scope',
      'baseEventListController',
      'currentStateService',
      'ENV',
      EventListController]);

  function EventListController(
    $scope,
    baseEventListController,
    currentStateService,
    ENV) {
    var controllerScope = this;
    var EventController = baseEventListController.extend({
      init:function() {
        this.controllerScope = controllerScope;
        this.cacheTime = ENV.dashboardEventsCacheTime;
        this._super();

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
      },

      onCustomerUpdate: function() {
        this.getList();
      },

      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        filter = filter || {};
        return currentStateService.getCustomer().then(function(customer) {
          filter['scope'] = customer.url;
          vm.service.defaultFilter.scope = customer.url;
          fn(filter);
        });
      }
    });

    controllerScope.__proto__ = new EventController();
  }

  angular.module('ncsaas')
    .controller('CustomerAlertsListController', [
      '$scope',
      'baseControllerListClass',
      'currentStateService',
      'alertsService',
      'ENTITYLISTFIELDTYPES',
      CustomerAlertsListController]);

  function CustomerAlertsListController(
    $scope,
    baseControllerListClass,
    currentStateService,
    alertsService,
    ENTITYLISTFIELDTYPES) {
    var controllerScope = this;
    var controllerClass = baseControllerListClass.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.service = alertsService;
        this._super();

        this.entityOptions = {
          entityData: {
            noDataText: 'No alerts yet'
          },
          list: [
            {
              name: 'Message',
              propertyName: 'message',
              type: ENTITYLISTFIELDTYPES.noType
            }
          ]
        };

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
      },

      onCustomerUpdate: function() {
        this.getList();
      },

      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        filter = filter || {};
        return currentStateService.getCustomer().then(function(customer) {
          vm.service.defaultFilter.aggregate = 'customer';
          vm.service.defaultFilter.uuid = customer.uuid;
          fn(filter);
        })
      }
    });

    controllerScope.__proto__ = new controllerClass();
  }

  angular.module('ncsaas')
    .controller('DashboardIndexController', ['$scope', '$stateParams', DashboardIndexController]);

    function DashboardIndexController($scope, $stateParams) {
      $scope.activeTab = $stateParams.tab || 'activity';
    }

  angular.module('ncsaas')
    .controller('DashboardCostController', [
      '$scope',
      'baseControllerClass',
      'priceEstimationService',
      'currentStateService',
      DashboardCostController]);

  function DashboardCostController(
    $scope,
    baseControllerClass,
    priceEstimationService,
    currentStateService) {
    var controllerScope = this;
    var EventController = baseControllerClass.extend({
      init: function() {
        this.controllerScope = controllerScope;

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
        this.onCustomerUpdate();
      },

      onCustomerUpdate: function() {
        var vm = this;
        priceEstimationService.pageSize = 1000;
        priceEstimationService.getList().then(function(rows) {
          vm.processChartData(rows);
          vm.processTableData(rows);
        });
      },

      processChartData: function(rows) {
        var labels = [];
        var totals = [];
        rows.forEach(function(row) {
          if (row.scope_type == 'customer') {
            labels.unshift(moment(row.month, 'MM').format('MMMM'));
            totals.unshift(row.total);
          }
        });

      this.chartOptions = {
          bezierCurve: false,
          responsive: true,
          animationEasing: "linear"
        };

        this.costData = {
          labels: labels,
          datasets: [
            {
              fillColor: "rgba(123, 166, 196,0.5)",
              strokeColor: "rgba(123, 166, 196,1)",
              pointColor: "rgba(123, 166, 196,1)",
              pointStrokeColor: "#fff",
              pointHighlightFill: "#fff",
              pointHighlightStroke: "rgba(123, 166, 196,1)",
              data: totals
            }
          ]
        };
      },

      processTableData: function(rows) {
        var results = {};
        for (var i = 0; i < rows.length; i++) {
          var row = rows[i];
          var date = moment(row.month, 'MM').format('MMMM') + ' ' + row.year;
          if (!results.hasOwnProperty(date)) {
            results[date] = {
              total: 0,
              projects: [],
              services: [],
              resources: []
            }
          }
          if (row.scope_type == 'customer') {
            results[date].total = row.total;
          }
          if (row.scope_type == 'project') {
            results[date].projects.push(row);
          }
          if (row.scope_type == 'resource') {
            results[date].resources.push(row);
          }
          if (row.scope_type == 'service') {
            results[date].services.push(row);
          }
          if (row.scope_type == 'serviceprojectlink') {
            results[date].services.push(row);
          }
        }
        var table = [];
        for (var date in results) {
          var row = results[date];
          table.push({
            date: date,
            total: row.total,
            projects: row.projects,
            services: row.services,
            resources: row.resources
          });
        }
        if (table.length > 0) {
          table[0].selected = true;
          table[0].activeTab = 'services';
        }
        this.table = table;
      }
    });

    controllerScope.__proto__ = new EventController();
  }

  angular.module('ncsaas')
    .controller('DashboardActivityController', [
      '$scope',
      'baseControllerClass',
      'projectsService',
      'alertsService',
      'eventsService',
      'eventStatisticsService',
      'resourcesCountService',
      'currentStateService',
      'ENV',
      '$window',
      DashboardActivityController]);

  function DashboardActivityController(
    $scope,
    baseControllerClass,
    projectsService,
    alertsService,
    eventsService,
    eventStatisticsService,
    resourcesCountService,
    currentStateService,
    ENV,
    $window) {
    var controllerScope = this;
    var EventController = baseControllerClass.extend({
      showGraph: true,
      init:function() {
        this.controllerScope = controllerScope;
        this.cacheTime = ENV.dashboardEventsCacheTime;
        this.setSignalHandler('refreshCounts', this.afterActivate.bind(controllerScope));
        this._super();
        this.activeTab = 'activity';
        this.chartOptions = {
          responsive: true,
          scaleShowVerticalLines: false,
          scaleShowGridLines: false,
          bezierCurve: false
        };

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
        this.onCustomerUpdate();
        this.resizeControl();
      },
      resizeControl: function() {
        var vm = this;

        var window = angular.element($window);
        window.bind('resize', function () {
          vm.showGraph = false;
          setTimeout(function() {
            vm.showGraph = true;
            $scope.$apply();
          }, 0);
          $scope.$apply();
        });
      },
      selectProject: function (project) {
        if (project) {
          project.selected =! project.selected;
          this.getProjectResources(project);
          this.getProjectEvents(project);
        }
      },
      onCustomerUpdate: function() {
        this.getCustomerProjects();
        this.getCustomerEvents();
        this.getCustomerAlerts();
      },
      getCustomerAlerts: function () {
        var vm = this;
        currentStateService.getCustomer().then(function(customer) {
          alertsService.getList({'aggregate': 'customer', 'uuid': customer.uuid}).then(function(response) {
            vm.alerts = response;
          })
        })
      },
      getCustomerEvents: function () {
        var vm = this;
        currentStateService.getCustomer().then(function(customer) {
          eventsService.getList({'scope': customer.url}).then(function(response) {
            vm.events = response;
          })
        })
      },
      getCustomerProjects: function() {
        var vm = this;
        projectsService.getList().then(function(response) {
          vm.projects = response;
          for (var i = 0; i < vm.projects.length; i++) {
            vm.projects[i].selected = false;
          }
          vm.selectProject(vm.projects[0]);
        });
      },
      getProjectResources: function (project) {
        if (project.count) {
          return;
        }
        project.count = {};
        project.count.services = project.services.length;
        resourcesCountService.users({'project': project.uuid}).then(function(count) {
          project.count.users = count;
        });
        resourcesCountService.resources({
          'project_uuid': project.uuid,
          'resource_type': ENV.resourceFilters.VMs
        }).then(function(count) {
          project.count.resources = count;
        });
        resourcesCountService.alerts({'scope': project.url}).then(function(count) {
          project.count.alerts = count;
        });
      },
      getProjectEvents: function (project) {
        if (project.chartData) {
          return;
        }
        var end = moment.utc().unix();
        var count = 7;
        var start = moment.utc().subtract(count + 1, 'days').unix();
        eventStatisticsService.getList({
          'scope': project.url,
          'start': start,
          'end': end,
          'points_count': count + 1
        }).then(function(response) {
          var labels = [];
          var total = [];
          for (var i = 0; i < response.length; i++) {
            var date = moment.unix(response[i].point);
            var day = date.format('dddd');
            var value = response[i].object.count;
            labels.push(day);
            total.push(value);
          }

          var points = [];
          for (var i = 1; i < total.length; i++) {
            points[i] = total[i] - total[i-1];
          }
          labels.shift();
          points.shift();

          project.chartData = {
            labels: labels,
            datasets: [
              {
                label: "Events",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: points
              }
            ]
          };
        })
      }
    });

    controllerScope.__proto__ = new EventController();
  }
})();
<commit_msg>Remove refreshCounts event listener from dashboard (SAAS-635)<commit_after>'use strict';

(function() {
  angular.module('ncsaas')
    .service('baseEventListController', [
      'baseControllerListClass', 'eventsService', 'EVENTTYPE', baseEventListController]);

  function baseEventListController(baseControllerListClass, eventsService, EVENTTYPE) {
    var ControllerListClass = baseControllerListClass.extend({
      EVENTTYPE: EVENTTYPE,

      init:function() {
        this.service = eventsService;
        this.searchFieldName = 'search';
        this.searchFilters = [
          {
            name: 'event_type',
            title: 'Logged in',
            value: EVENTTYPE.auth_logged_in_with_username
          },
          {
            name: 'event_type',
            title: 'Project creation',
            value: EVENTTYPE.project_creation_succeeded
          },
          {
            name: 'event_type',
            title: 'Organization creation',
            value: EVENTTYPE.customer_creation_succeeded
          }
        ];
        this._super();
      }
    });

    return ControllerListClass;
  }

  angular.module('ncsaas')
    .controller('EventListController', [
      '$scope',
      'baseEventListController',
      'currentStateService',
      'ENV',
      EventListController]);

  function EventListController(
    $scope,
    baseEventListController,
    currentStateService,
    ENV) {
    var controllerScope = this;
    var EventController = baseEventListController.extend({
      init:function() {
        this.controllerScope = controllerScope;
        this.cacheTime = ENV.dashboardEventsCacheTime;
        this._super();

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
      },

      onCustomerUpdate: function() {
        this.getList();
      },

      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        filter = filter || {};
        return currentStateService.getCustomer().then(function(customer) {
          filter['scope'] = customer.url;
          vm.service.defaultFilter.scope = customer.url;
          fn(filter);
        });
      }
    });

    controllerScope.__proto__ = new EventController();
  }

  angular.module('ncsaas')
    .controller('CustomerAlertsListController', [
      '$scope',
      'baseControllerListClass',
      'currentStateService',
      'alertsService',
      'ENTITYLISTFIELDTYPES',
      CustomerAlertsListController]);

  function CustomerAlertsListController(
    $scope,
    baseControllerListClass,
    currentStateService,
    alertsService,
    ENTITYLISTFIELDTYPES) {
    var controllerScope = this;
    var controllerClass = baseControllerListClass.extend({
      init: function() {
        this.controllerScope = controllerScope;
        this.service = alertsService;
        this._super();

        this.entityOptions = {
          entityData: {
            noDataText: 'No alerts yet'
          },
          list: [
            {
              name: 'Message',
              propertyName: 'message',
              type: ENTITYLISTFIELDTYPES.noType
            }
          ]
        };

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
      },

      onCustomerUpdate: function() {
        this.getList();
      },

      getList: function(filter) {
        var vm = this;
        var fn = this._super.bind(vm);
        filter = filter || {};
        return currentStateService.getCustomer().then(function(customer) {
          vm.service.defaultFilter.aggregate = 'customer';
          vm.service.defaultFilter.uuid = customer.uuid;
          fn(filter);
        })
      }
    });

    controllerScope.__proto__ = new controllerClass();
  }

  angular.module('ncsaas')
    .controller('DashboardIndexController', ['$scope', '$stateParams', DashboardIndexController]);

    function DashboardIndexController($scope, $stateParams) {
      $scope.activeTab = $stateParams.tab || 'activity';
    }

  angular.module('ncsaas')
    .controller('DashboardCostController', [
      '$scope',
      'baseControllerClass',
      'priceEstimationService',
      'currentStateService',
      DashboardCostController]);

  function DashboardCostController(
    $scope,
    baseControllerClass,
    priceEstimationService,
    currentStateService) {
    var controllerScope = this;
    var EventController = baseControllerClass.extend({
      init: function() {
        this.controllerScope = controllerScope;

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
        this.onCustomerUpdate();
      },

      onCustomerUpdate: function() {
        var vm = this;
        priceEstimationService.pageSize = 1000;
        priceEstimationService.getList().then(function(rows) {
          vm.processChartData(rows);
          vm.processTableData(rows);
        });
      },

      processChartData: function(rows) {
        var labels = [];
        var totals = [];
        rows.forEach(function(row) {
          if (row.scope_type == 'customer') {
            labels.unshift(moment(row.month, 'MM').format('MMMM'));
            totals.unshift(row.total);
          }
        });

      this.chartOptions = {
          bezierCurve: false,
          responsive: true,
          animationEasing: "linear"
        };

        this.costData = {
          labels: labels,
          datasets: [
            {
              fillColor: "rgba(123, 166, 196,0.5)",
              strokeColor: "rgba(123, 166, 196,1)",
              pointColor: "rgba(123, 166, 196,1)",
              pointStrokeColor: "#fff",
              pointHighlightFill: "#fff",
              pointHighlightStroke: "rgba(123, 166, 196,1)",
              data: totals
            }
          ]
        };
      },

      processTableData: function(rows) {
        var results = {};
        for (var i = 0; i < rows.length; i++) {
          var row = rows[i];
          var date = moment(row.month, 'MM').format('MMMM') + ' ' + row.year;
          if (!results.hasOwnProperty(date)) {
            results[date] = {
              total: 0,
              projects: [],
              services: [],
              resources: []
            }
          }
          if (row.scope_type == 'customer') {
            results[date].total = row.total;
          }
          if (row.scope_type == 'project') {
            results[date].projects.push(row);
          }
          if (row.scope_type == 'resource') {
            results[date].resources.push(row);
          }
          if (row.scope_type == 'service') {
            results[date].services.push(row);
          }
          if (row.scope_type == 'serviceprojectlink') {
            results[date].services.push(row);
          }
        }
        var table = [];
        for (var date in results) {
          var row = results[date];
          table.push({
            date: date,
            total: row.total,
            projects: row.projects,
            services: row.services,
            resources: row.resources
          });
        }
        if (table.length > 0) {
          table[0].selected = true;
          table[0].activeTab = 'services';
        }
        this.table = table;
      }
    });

    controllerScope.__proto__ = new EventController();
  }

  angular.module('ncsaas')
    .controller('DashboardActivityController', [
      '$scope',
      'baseControllerClass',
      'projectsService',
      'alertsService',
      'eventsService',
      'eventStatisticsService',
      'resourcesCountService',
      'currentStateService',
      'ENV',
      '$window',
      DashboardActivityController]);

  function DashboardActivityController(
    $scope,
    baseControllerClass,
    projectsService,
    alertsService,
    eventsService,
    eventStatisticsService,
    resourcesCountService,
    currentStateService,
    ENV,
    $window) {
    var controllerScope = this;
    var EventController = baseControllerClass.extend({
      showGraph: true,
      init:function() {
        this.controllerScope = controllerScope;
        this.cacheTime = ENV.dashboardEventsCacheTime;
        this._super();
        this.activeTab = 'activity';
        this.chartOptions = {
          responsive: true,
          scaleShowVerticalLines: false,
          scaleShowGridLines: false,
          bezierCurve: false
        };

        $scope.$on('currentCustomerUpdated', this.onCustomerUpdate.bind(this));
        this.onCustomerUpdate();
        this.resizeControl();
      },
      resizeControl: function() {
        var vm = this;

        var window = angular.element($window);
        window.bind('resize', function () {
          vm.showGraph = false;
          setTimeout(function() {
            vm.showGraph = true;
            $scope.$apply();
          }, 0);
          $scope.$apply();
        });
      },
      selectProject: function (project) {
        if (project) {
          project.selected =! project.selected;
          this.getProjectResources(project);
          this.getProjectEvents(project);
        }
      },
      onCustomerUpdate: function() {
        this.getCustomerProjects();
        this.getCustomerEvents();
        this.getCustomerAlerts();
      },
      getCustomerAlerts: function () {
        var vm = this;
        currentStateService.getCustomer().then(function(customer) {
          alertsService.getList({'aggregate': 'customer', 'uuid': customer.uuid}).then(function(response) {
            vm.alerts = response;
          })
        })
      },
      getCustomerEvents: function () {
        var vm = this;
        currentStateService.getCustomer().then(function(customer) {
          eventsService.getList({'scope': customer.url}).then(function(response) {
            vm.events = response;
          })
        })
      },
      getCustomerProjects: function() {
        var vm = this;
        projectsService.getList().then(function(response) {
          vm.projects = response;
          for (var i = 0; i < vm.projects.length; i++) {
            vm.projects[i].selected = false;
          }
          vm.selectProject(vm.projects[0]);
        });
      },
      getProjectResources: function (project) {
        if (project.count) {
          return;
        }
        project.count = {};
        project.count.services = project.services.length;
        resourcesCountService.users({'project': project.uuid}).then(function(count) {
          project.count.users = count;
        });
        resourcesCountService.resources({
          'project_uuid': project.uuid,
          'resource_type': ENV.resourceFilters.VMs
        }).then(function(count) {
          project.count.resources = count;
        });
        resourcesCountService.alerts({'scope': project.url}).then(function(count) {
          project.count.alerts = count;
        });
      },
      getProjectEvents: function (project) {
        if (project.chartData) {
          return;
        }
        var end = moment.utc().unix();
        var count = 7;
        var start = moment.utc().subtract(count + 1, 'days').unix();
        eventStatisticsService.getList({
          'scope': project.url,
          'start': start,
          'end': end,
          'points_count': count + 1
        }).then(function(response) {
          var labels = [];
          var total = [];
          for (var i = 0; i < response.length; i++) {
            var date = moment.unix(response[i].point);
            var day = date.format('dddd');
            var value = response[i].object.count;
            labels.push(day);
            total.push(value);
          }

          var points = [];
          for (var i = 1; i < total.length; i++) {
            points[i] = total[i] - total[i-1];
          }
          labels.shift();
          points.shift();

          project.chartData = {
            labels: labels,
            datasets: [
              {
                label: "Events",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "rgba(220,220,220,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: points
              }
            ]
          };
        })
      }
    });

    controllerScope.__proto__ = new EventController();
  }
})();
<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc function
 * @name grafterizerApp.controller:TransformationnewCtrl
 * @description
 * # TransformationnewCtrl
 * Controller of the grafterizerApp
 */
angular.module('grafterizerApp')
  .controller('TransformationNewCtrl', function (
  	$scope,
    $stateParams,
    ontotextAPI,
    $rootScope,
    $state,
    $mdToast,
    $mdDialog,
    transformationDataModel,
    generateClojure) {

  	$scope.document = {
  		title: "New transformation",
  		description: "",
  	};

  	$scope.clojure = "";
    $scope.pipeline = new transformationDataModel.Pipeline([]);
    $scope.transformation = new transformationDataModel.Transformation([], [], [$scope.pipeline], []);

    window.canard = $scope;

    $rootScope.actions = {
    	save: function(){
        // var transformationJSON = JSON.stringify($scope.transformation);
        var clojure = generateClojure.fromTransformation($scope.transformation);
        ontotextAPI.newTransformation({
            '@context': ontotextAPI.getContextDeclaration(),
            '@type': 'dcat:Transformation',
            'dct:title': $scope.document.title,
            'dct:description': $scope.document.description,
            'dcat:public': $scope.document['dct:public'] ? 'true': 'false',
            'dct:modified': moment().format("YYYY-MM-DD"),
            'dcat:transformationType': 'pipe',
            'dcat:transformationCommand': 'my-pipe'
          }, clojure, $scope.transformation)
          .success(function(data){
            $mdToast.show(
              $mdToast.simple()
                .content('Transformation saved')
                .position('bottom left')
                .hideDelay(6000)
              );
            $state.go('transformations.transformation', {
              id: data['@id']
            });
          });
	        /*Transformation.create({
	        	uri: "about:blank",
	        	name: $scope.document.title,
	        	metadata: $scope.document.description,
	        	clojure: $scope.clojure
	        }, function(data) {
	        	$state.go('transformations.transformation', {
	        		id: data.id
	        	});
	        }, function(err) {
	  			$mdToast.show(
			      $mdToast.simple()
			        .content('An error occured: '+err.statusText)
			        .position('right top')
			        .hideDelay(6000)
		        );
	        });*/
    	}
    };
    $scope.$watch('fileUpload', function(){
      if ($scope.fileUpload) {
        // TODO
        $mdToast.show(
          $mdToast.simple()
            .content('You need to save the transformation first')
            .position('bottom left')
            .hideDelay(6000)
          );
      }
    });

    $scope.editPrefixers = function () {
        $scope.originalPrefixers = [];
        angular.copy($scope.transformation.prefixers, $scope.originalPrefixers);
        $mdDialog.show({
            templateUrl: 'views/editprefixes.html',
            controller: 'EditprefixersCtrl',
            scope: $scope.$new(false, $scope)
        }).then(function() {
        }, function() {
            angular.copy($scope.originalPrefixers, $scope.transformation.prefixers);
        });
    };

    $scope.defineCustomFunctions = function () {
        $scope.originalCustomFunctionDeclarations = [];
        angular.copy($scope.transformation.customFunctionDeclarations, $scope.originalCustomFunctionDeclarations);
        $mdDialog.show({
            templateUrl: 'views/createcustomfunction.html',
            controller: 'CustomfunctionsdialogcontrollerCtrl',
            scope: $scope.$new(false, $scope)
        }).then(function() {
        }, function() {
            angular.copy($scope.originalCustomFunctionDeclarations, $scope.transformation.customFunctionDeclarations);
        });
    };
  });
<commit_msg>Added default functions for integer column and string column<commit_after>'use strict';

/**
 * @ngdoc function
 * @name grafterizerApp.controller:TransformationnewCtrl
 * @description
 * # TransformationnewCtrl
 * Controller of the grafterizerApp
 */
angular.module('grafterizerApp')
    .controller('TransformationNewCtrl', function (
                $scope,
                 $stateParams,
                 ontotextAPI,
                 $rootScope,
                 $state,
                 $mdToast,
                 $mdDialog,
                 transformationDataModel,
                 generateClojure) {

    $scope.document = {
        title: "New transformation",
        description: "",
    };
    var integerColumn = new transformationDataModel.CustomFunctionDeclaration("integerColumn", "(defn integerColumn [s] (Integer/parseInt s))");
    var stringColumn = new transformationDataModel.CustomFunctionDeclaration("stringColumn", "(defn stringColumn [str] (s str))");
    $scope.clojure = "";
    $scope.pipeline = new transformationDataModel.Pipeline([]);
    $scope.transformation = new transformationDataModel.Transformation([integerColumn, stringColumn], [], [$scope.pipeline], []);

    window.canard = $scope;

    $rootScope.actions = {
        save: function(){
            // var transformationJSON = JSON.stringify($scope.transformation);
            var clojure = generateClojure.fromTransformation($scope.transformation);
            ontotextAPI.newTransformation({
                '@context': ontotextAPI.getContextDeclaration(),
                '@type': 'dcat:Transformation',
                'dct:title': $scope.document.title,
                'dct:description': $scope.document.description,
                'dcat:public': $scope.document['dct:public'] ? 'true': 'false',
                'dct:modified': moment().format("YYYY-MM-DD"),
                'dcat:transformationType': 'pipe',
                'dcat:transformationCommand': 'my-pipe'
            }, clojure, $scope.transformation)
                .success(function(data){
                $mdToast.show(
                    $mdToast.simple()
                    .content('Transformation saved')
                    .position('bottom left')
                    .hideDelay(6000)
                );
                $state.go('transformations.transformation', {
                    id: data['@id']
                });
            });
            /*Transformation.create({
	        	uri: "about:blank",
	        	name: $scope.document.title,
	        	metadata: $scope.document.description,
	        	clojure: $scope.clojure
	        }, function(data) {
	        	$state.go('transformations.transformation', {
	        		id: data.id
	        	});
	        }, function(err) {
	  			$mdToast.show(
			      $mdToast.simple()
			        .content('An error occured: '+err.statusText)
			        .position('right top')
			        .hideDelay(6000)
		        );
	        });*/
        }
    };
    $scope.$watch('fileUpload', function(){
        if ($scope.fileUpload) {
            // TODO
            $mdToast.show(
                $mdToast.simple()
                .content('You need to save the transformation first')
                .position('bottom left')
                .hideDelay(6000)
            );
        }
    });

    $scope.editPrefixers = function () {
        $scope.originalPrefixers = [];
        angular.copy($scope.transformation.prefixers, $scope.originalPrefixers);
        $mdDialog.show({
            templateUrl: 'views/editprefixes.html',
            controller: 'EditprefixersCtrl',
            scope: $scope.$new(false, $scope)
        }).then(function() {
        }, function() {
            angular.copy($scope.originalPrefixers, $scope.transformation.prefixers);
        });
    };

    $scope.defineCustomFunctions = function () {
        $scope.originalCustomFunctionDeclarations = [];
        angular.copy($scope.transformation.customFunctionDeclarations, $scope.originalCustomFunctionDeclarations);
        $mdDialog.show({
            templateUrl: 'views/createcustomfunction.html',
            controller: 'CustomfunctionsdialogcontrollerCtrl',
            scope: $scope.$new(false, $scope)
        }).then(function() {
        }, function() {
            angular.copy($scope.originalCustomFunctionDeclarations, $scope.transformation.customFunctionDeclarations);
        });
    };
});
<|endoftext|>


<commit_before>/*jshint browser: true, jquery: true */
/*global clique, _, tangelo */

$(function () {
    "use strict";

    var launch = function (cfg) {
        var graph,
            view,
            info,
            linkInfo;

        window.graph = graph = new clique.Graph({
            adapter: tangelo.getPlugin("mongo").Mongo,
            options: {
                host: cfg.host || "localhost",
                database: cfg.database,
                collection: cfg.collection
            }
        });

        $.getJSON("assets/tangelo/anb/get_filenames", {
            host: cfg.host,
            db: cfg.database,
            coll: cfg.collection
        }).then(function (filenames) {
            $("#filename").autocomplete({
                source: filenames,
                minLength: 0
            }).focus(function () {
                $(this).autocomplete("search", $(this).val());
            });
        });

        (function () {
            var request = null,
                action;

            action = _.debounce(function () {
                var filename = $("#filename").val();

                if (request) {
                    request.abort();
                }

                request = $.getJSON("assets/tangelo/anb/get_nodes", {
                    host: cfg.host,
                    db: cfg.database,
                    coll: cfg.collection,
                    filename: filename
                }).then(function (nodes) {
                    request = null;

                    console.log("good");

                    $("#label").autocomplete({
                        source: nodes,
                        minLength: 0
                    }).focus(function () {
                        $(this).autocomplete("search", $(this).val());
                    });
                });
            }, 300);

            $("#filename").on("input", action);
            $("#filename").on("autocompleteselect", action);
        }());

        $("#submit").on("click", function () {
            var label = $("#label").val().trim(),
                filename = $("#filename").val().trim(),
                spec = {},
                delsearch = $("#delsearch").prop("checked");

            if (label === "" && filename === "") {
                return;
            }

            if (filename) {
                spec.filename = filename;
            }

            if (label) {
                spec.label = label;
            }

            graph.adapter.findNode(spec)
                .then(function (center) {
                    if (center) {
                        graph.addNode(center);
                    }
                });
        });

        window.view = view = new clique.view.Cola({
            model: graph,
            el: "#content"
        });

        window.info = info = new clique.view.SelectionInfo({
            model: view.selection,
            el: "#info",
            graph: graph
        });
        info.render();

        linkInfo = new clique.view.LinkInfo({
            model: view.linkSelection,
            el: "#link-info",
            graph: graph
        });
        linkInfo.render();
    };

    $.getJSON("anb.json").then(launch, _.bind(launch, {}));
});
<commit_msg>Removing errant console.log() statement<commit_after>/*jshint browser: true, jquery: true */
/*global clique, _, tangelo */

$(function () {
    "use strict";

    var launch = function (cfg) {
        var graph,
            view,
            info,
            linkInfo;

        window.graph = graph = new clique.Graph({
            adapter: tangelo.getPlugin("mongo").Mongo,
            options: {
                host: cfg.host || "localhost",
                database: cfg.database,
                collection: cfg.collection
            }
        });

        $.getJSON("assets/tangelo/anb/get_filenames", {
            host: cfg.host,
            db: cfg.database,
            coll: cfg.collection
        }).then(function (filenames) {
            $("#filename").autocomplete({
                source: filenames,
                minLength: 0
            }).focus(function () {
                $(this).autocomplete("search", $(this).val());
            });
        });

        (function () {
            var request = null,
                action;

            action = _.debounce(function () {
                var filename = $("#filename").val();

                if (request) {
                    request.abort();
                }

                request = $.getJSON("assets/tangelo/anb/get_nodes", {
                    host: cfg.host,
                    db: cfg.database,
                    coll: cfg.collection,
                    filename: filename
                }).then(function (nodes) {
                    request = null;

                    $("#label").autocomplete({
                        source: nodes,
                        minLength: 0
                    }).focus(function () {
                        $(this).autocomplete("search", $(this).val());
                    });
                });
            }, 300);

            $("#filename").on("input", action);
            $("#filename").on("autocompleteselect", action);
        }());

        $("#submit").on("click", function () {
            var label = $("#label").val().trim(),
                filename = $("#filename").val().trim(),
                spec = {},
                delsearch = $("#delsearch").prop("checked");

            if (label === "" && filename === "") {
                return;
            }

            if (filename) {
                spec.filename = filename;
            }

            if (label) {
                spec.label = label;
            }

            graph.adapter.findNode(spec)
                .then(function (center) {
                    if (center) {
                        graph.addNode(center);
                    }
                });
        });

        window.view = view = new clique.view.Cola({
            model: graph,
            el: "#content"
        });

        window.info = info = new clique.view.SelectionInfo({
            model: view.selection,
            el: "#info",
            graph: graph
        });
        info.render();

        linkInfo = new clique.view.LinkInfo({
            model: view.linkSelection,
            el: "#link-info",
            graph: graph
        });
        linkInfo.render();
    };

    $.getJSON("anb.json").then(launch, _.bind(launch, {}));
});
<|endoftext|>


<commit_before>
// = entities
// location
// datetime
// weather_type: snow, rain, hail, thunder, sunny, cloudy
// weather_temperature: very cold, cold, neutral, warm, very warm
// weather_sentiment: negative, positive, neutral

var WEATHER_API;
var MIN_CONFIDENCE;

var util = require('util');

var INTENT = {
  OTHER: "weather_other",
  QUERY: "weather_query",
  STATEMENT: "weather_statement",
  TIME_QUERY: "weather_time_query"
}

exports.config = function(min_confidence, weather_api) {
    WEATHER_API = weather_api;
    MIN_CONFIDENCE = min_confidence;
}

exports.processReply = function(reply, callback) {
    if(!reply) {
        callback(false, "Ignored as wit failed to parse");
        return;
    }

    if(reply.outcome.confidence < MIN_CONFIDENCE) {
        callback(false, "Ignored as confidence ("+reply.outcome.confidence+") was below "+MIN_CONFIDENCE+".");

    } else {
        var weatherIntent = new WeatherIntent(reply);

        switch(weatherIntent.getIntentType()) {
            case INTENT.OTHER:
                callback(false, "Ignored as wit was unsure of type");
                console.info("Treated as other and ignored");
                break;
            case INTENT.QUERY:
            case INTENT.TIME_QUERY:
                processWeatherQuery(weatherIntent, callback);
                break;
            case INTENT.STATEMENT:
                callback(false, "Would have attempted to parse statement");
                console.info("Would have attempted ot treat as a statement.");
                break;
            default:
                console.warn("Unknown Wit intent type: '"+reply.outcome.intent+"'");
                callback(false, "Ignored as '"+reply.outcome.intent+"' is not a known type");
        }
    }
}

function WeatherIntent(witReply) {
    var witReply = witReply;
    var entities = witReply.outcome.entities;

    this.getIntentType = function() {
        return witReply.outcome.intent
    }

    this.getIsManchester = function() {
        var isManchester = false;

        if(entities.location) {
          if(Array.isArray(entities.location)) {
              entities.location.forEach(function(value) {
                  if(value.value.toLowerCase().indexOf('manchester') > -1)
                      isManchester = true;
              });
          } else {
              if(entities.location.value.toLowerCase().indexOf('manchester') > -1)
                  isManchester = true;
          }
        }

        return isManchester;
    }

    this.getTimePeriod = function() {
        var timePeriod = { from: new Date(), to: new Date(), name: 'today' }
        timePeriod.to.setHours(timePeriod.to.getHours()+3); // dates in the past have unknown weather

        if(entities.datetime) {
            if(Array.isArray(entities.datetime)) {
                // @todo Prefer today, avoid in the past, select one after today if exists
                //entities.datetime.forEach(function(value) {
                timePeriod.from = entities.datetime[0].value.from;
                timePeriod.to = entities.datetime[0].value.to;
                timePeriod.name = entities.datetime[0].body;
                //}
            } else {
                timePeriod.from = entities.datetime.value.from;
                timePeriod.to = entities.datetime.value.to;
                timePeriod.name = entities.datetime.body;
            }
            timePeriod.from = new Date(timePeriod.from);
            timePeriod.to = new Date(timePeriod.to);
        }

        return timePeriod;
    }

    this.getFromUnixTime = function() {
        return this.getTimePeriod().from.getTime() / 1000;
    }

    this.getToUnixTime = function() {
        return this.getTimePeriod().to.getTime() / 1000;
    }

    this.getAverageUnixTime = function() {
        return Math.round((this.getFromUnixTime() +
                           this.getToUnixTime()) / 2);
    }

    this.getWeatherType = function() {
        var weatherType = false;

        if(entities.weather_type) {
           weatherType = entities.weather_type.value;
        }

        return weatherType;
    }

    this.getWeatherTemperature = function() {
        var weatherTemperature = false;

        if(entities.weather_temperature) {
           weatherTemperature = entities.weather_temperature.value;
        }

        return weatherTemperature;
    }
}

function processIntent(intent, callback) {
    console.info(util.format('Processing weather query from @%s "%s"', reply.user.screen_name, reply.msg_body))

    // weather_type: snow, rain, hail, thunder, sunny, cloudy
    // weather_temperature: very cold, cold, neutral, warm, very warm

    switch(intent.getIntentType()) {
        case INTENT.QUERY: processWeatherQuery(intent, callback); break;
        case INTENT.STATEMENT: processWeatherStatement(intent, callback); break;
        case INTENT.TIME_QUERY: processWeatherTimeQuery(intent, callback); break;
        default:
            callback(false, "Ignored as '"+reply.outcome.intent+"' is not a known type");
    }
}

function processWeatherTimeQuery(intent, callback) {
    console.error("Not implemented yet!");
}

function processWeatherStatement(intent, callback) {
    console.error("Not implemented yet!");
};

function processWeatherQuery(intent, callback) {

    var averageDate = intent.getAverageUnixTime();
    var weatherType = intent.getWeatherType();
    var weatherTemperature = intent.getWeatherTemperature();
    var timePeriod = intent.getTimePeriod();

    WEATHER_API.getWeatherAt(averageDate, function(weather, queriedTimestamp) {

        if(typeof weather === 'undefined') {
          console.error('Unable to get weather at ' + queriedTimestamp, weather);
          return;
        }

        var weatherTypeString = getWeatherTypeString(weatherType, weather, timePeriod.name);
        var weatherTemperatureString = getWeatherTemperatureString(weatherTemperature, weather, timePeriod.name);

        var weatherString = capitaliseFirstLetter(weather.description);

        if(weather.temp_min != weather.temp_max)
          weatherString += " with highs of "+Math.round(weather.temp_max)+"\u2103 and lows of "+Math.round(weather.temp_min)+"\u2103.";
        else
          weatherString += " with an average of "+weather.temp+"\u2103."

        var tweet = "";

        if(weatherTypeString)
          tweet += weatherTypeString + " ";
        else if(weatherTemperatureString)
          tweet += weatherTemperatureString + " ";

        // Avoid short tweets, add extra detail!
        if(!weatherTypeString && !weatherTemperatureString)
          tweet = "The forecast for "+timePeriod.name+" is: " + weatherString;
        else
          tweet += weatherString;

        callback(tweet);
    });
}

function getWeatherTypeString(type, weather, periodName) {

    // weather_type: snow, rain, hail, thunder, sunny, cloudy
    // weather API: 'clear x', 'few clouds x', 'scattered clouds x', 'broken clouds x', 'drizzle x', 'rain x', 'thunder x', 'snow x', 'mist'

    if(type && weather.mapping) {
        if(type == 'snow')
           if(weather.mapping == 'snow')
               return ("Yes! It looks like it is going to snow " + periodName + "!");
           else
               return ("No, it's not going to snow " + periodName + ".");

        else if(type == 'rain')
           if(weather.mapping == 'rain')
               return ("Unfortunately it looks like it is going to rain " + periodName + ".");
           else if(weather.mapping == 'drizzle')
               return ("It looks like there's going to be a little rain " + periodName + ".");
           else
               return ("Good news, there's no rain forecast " + periodName + "!");

        /*else if(type == 'hail' && weather.mapping == 'hail')
           if(weather.mapping == 'hail')
               return ("Hail is forecast "+timePeriod.name."!");
           else
               return ("There's no hail forecast "+timePeriod.name);*/

        else if(type == 'thunder')
           if(weather.mapping == 'thunder')
               return ("Yes, a thunderstorm is forecast " + periodName + "!");
           else
               return ("Luckily there's no thunder forecast " + periodName + ".");

        else if(type == 'sunny')
           if(weather.mapping == 'clear')
               return ("Sun is forecast " + periodName + ", it's going to be around "+Math.round(weather.temp)+" degrees!");
           else if(weather.mapping == 'few clouds')
               return ("It should be sunny " + periodName + ", but there will be a few clouds.");
           else
               return ("It doesn't like it's going to be sunny " + periodName + ".");

        else if(type == 'cloudy')
           if(weather.mapping == 'scattered clouds')
               return ("There is a little cloud forecast " + periodName + ".");
           else if(weather.mapping == 'broken clouds')
               return ("There will be heavy cloud " + periodName + ".");
           else
               return ("There's no cloud forecast " + periodName + ".");
    }

    return;
}

function getWeatherTemperatureString(temperature, weather, periodName) {

    // weather_temperature: very cold, cold, neutral, warm, very warm
    if(temperature !== false) {
        if(weather.temp < 5)
            if(temperature == 'very cold')
                return ("Yes, it's going to be very cold " + periodName + ".");
            else
                return ("Luckily it's going to be "+Math.round(weather.temp)+" " + periodName + ", so not too cold!");

        else if(weather.temp < 10)
            if(temperature == 'cold')
                return ("It looks like it's going to be cold " + periodName + ".");
            else
                return ("It's going to be "+Math.round(weather.temp)+" degrees " + periodName + ".");

        else if(weather.temp < 15)
            if(temperature == 'neutral')
                return ("It's going to be an average temperature " + periodName + ".");
            else
                return ("No, it's going to be average " + periodName + ".");

        else if(weather.temp < 20)
            if(temperature == 'warm')
                return ("It should be warmer than usual " + periodName + ".");
            else
                return ("It's going to be warmer than usual " + periodName + ".");

        else if(weather.temp >= 20)
            if(temperature == 'very warm')
                return ("Yes, it should be very warm " + periodName + ".");
            else
                return ("No, it's going to be very warm " + periodName + ".");
    }

    return;
}

function capitaliseFirstLetter(string)
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}<commit_msg>Add detail to wit reply on mention<commit_after>
// = entities
// location
// datetime
// weather_type: snow, rain, hail, thunder, sunny, cloudy
// weather_temperature: very cold, cold, neutral, warm, very warm
// weather_sentiment: negative, positive, neutral

var WEATHER_API;
var MIN_CONFIDENCE;

var util = require('util');

var INTENT = {
  OTHER: "weather_other",
  QUERY: "weather_query",
  STATEMENT: "weather_statement",
  TIME_QUERY: "weather_time_query"
}

exports.config = function(min_confidence, weather_api) {
    WEATHER_API = weather_api;
    MIN_CONFIDENCE = min_confidence;
}

exports.processReply = function(reply, callback, mention) {
    if(typeof mention === 'undefined')
        mention = false;

    if(!reply) {
        callback(false, "Ignored as wit failed to parse");
        return;
    }

    if(reply.outcome.confidence < MIN_CONFIDENCE) {
        callback(false, "Ignored as confidence ("+reply.outcome.confidence+") was below "+MIN_CONFIDENCE+".");

    } else {
        var weatherIntent = new WeatherIntent(reply);

        //mentions should never be statements as a "question" is implicit (I think)
        if(mention && (weatherIntent.getIntentType() != INTENT.QUERY
                       || weatherIntent.getIntentType() != INTENT.TIME_QUERY)) {

            var replyIntro = ["I'm sorry, I don't know what that means",
                              "I don't understand you, please try again",
                              "I don't understand",
                              "I can only reply to questions about the weather"
                             ]
            var replyEnd =   ["Try asking a question, for example 'will it rain today?'",
                              "Ask me about the weather e.g. 'what will the weather be this weekend?'",
                              "Try a question e.g. 'will it rain tomorrow afternoon?'",
                              "Please ask a clear question about the weather!"
                             ]

            var start = replyIntro[Math.floor(Math.random() * replyIntro.length)];
            var end = replyEnd[Math.floor(Math.random() * replyEnd.length)];
            console.warn("Wit didn't understand mention '"+ reply.msg_body +"'")
            callback(reply + ". " + end);
            return;
        }

        switch(weatherIntent.getIntentType()) {
            case INTENT.OTHER:
                callback(false, "Ignored as wit was unsure of type");
                console.info("Treated as other and ignored");
                break;
            case INTENT.QUERY:
            case INTENT.TIME_QUERY:
                processWeatherQuery(weatherIntent, callback);
                break;
            case INTENT.STATEMENT:
                callback(false, "Would have attempted to parse statement");
                console.info("Would have attempted ot treat as a statement.");
                break;
            default:
                console.warn("Unknown Wit intent type: '"+reply.outcome.intent+"'");
                callback(false, "Ignored as '"+reply.outcome.intent+"' is not a known type");
        }
    }
}

function WeatherIntent(witReply) {
    var witReply = witReply;
    var entities = witReply.outcome.entities;

    this.getIntentType = function() {
        return witReply.outcome.intent
    }

    this.setIntentType = function(intent) {
        witReply.outcome.intent = intent;
    }

    this.getIsManchester = function() {
        var isManchester = false;

        if(entities.location) {
          if(Array.isArray(entities.location)) {
              entities.location.forEach(function(value) {
                  if(value.value.toLowerCase().indexOf('manchester') > -1)
                      isManchester = true;
              });
          } else {
              if(entities.location.value.toLowerCase().indexOf('manchester') > -1)
                  isManchester = true;
          }
        }

        return isManchester;
    }

    this.getTimePeriod = function() {
        var timePeriod = { from: new Date(), to: new Date(), name: 'today' }
        timePeriod.to.setHours(timePeriod.to.getHours()+3); // dates in the past have unknown weather

        if(entities.datetime) {
            if(Array.isArray(entities.datetime)) {
                // @todo Prefer today, avoid in the past, select one after today if exists
                //entities.datetime.forEach(function(value) {
                timePeriod.from = entities.datetime[0].value.from;
                timePeriod.to = entities.datetime[0].value.to;
                timePeriod.name = entities.datetime[0].body;
                //}
            } else {
                timePeriod.from = entities.datetime.value.from;
                timePeriod.to = entities.datetime.value.to;
                timePeriod.name = entities.datetime.body;
            }
            timePeriod.from = new Date(timePeriod.from);
            timePeriod.to = new Date(timePeriod.to);
        }

        return timePeriod;
    }

    this.getFromUnixTime = function() {
        return this.getTimePeriod().from.getTime() / 1000;
    }

    this.getToUnixTime = function() {
        return this.getTimePeriod().to.getTime() / 1000;
    }

    this.getAverageUnixTime = function() {
        return Math.round((this.getFromUnixTime() +
                           this.getToUnixTime()) / 2);
    }

    this.getWeatherType = function() {
        var weatherType = false;

        if(entities.weather_type) {
           weatherType = entities.weather_type.value;
        }

        return weatherType;
    }

    this.getWeatherTemperature = function() {
        var weatherTemperature = false;

        if(entities.weather_temperature) {
           weatherTemperature = entities.weather_temperature.value;
        }

        return weatherTemperature;
    }
}

function processIntent(intent, callback) {
    console.info(util.format('Processing weather query from @%s "%s"', reply.user.screen_name, reply.msg_body))

    // weather_type: snow, rain, hail, thunder, sunny, cloudy
    // weather_temperature: very cold, cold, neutral, warm, very warm

    switch(intent.getIntentType()) {
        case INTENT.QUERY: processWeatherQuery(intent, callback); break;
        case INTENT.STATEMENT: processWeatherStatement(intent, callback); break;
        case INTENT.TIME_QUERY: processWeatherTimeQuery(intent, callback); break;
        default:
            callback(false, "Ignored as '"+reply.outcome.intent+"' is not a known type");
    }
}

function processWeatherTimeQuery(intent, callback) {
    console.error("Not implemented yet!");
}

function processWeatherStatement(intent, callback) {
    console.error("Not implemented yet!");
};

function processWeatherQuery(intent, callback) {

    var averageDate = intent.getAverageUnixTime();
    var weatherType = intent.getWeatherType();
    var weatherTemperature = intent.getWeatherTemperature();
    var timePeriod = intent.getTimePeriod();

    WEATHER_API.getWeatherAt(averageDate, function(weather, queriedTimestamp) {

        if(typeof weather === 'undefined') {
          console.error('Unable to get weather at ' + queriedTimestamp, weather);
          return;
        }

        var weatherTypeString = getWeatherTypeString(weatherType, weather, timePeriod.name);
        var weatherTemperatureString = getWeatherTemperatureString(weatherTemperature, weather, timePeriod.name);

        var weatherString = capitaliseFirstLetter(weather.description);

        if(weather.temp_min != weather.temp_max)
          weatherString += " with highs of "+Math.round(weather.temp_max)+"\u2103 and lows of "+Math.round(weather.temp_min)+"\u2103.";
        else
          weatherString += " with an average of "+weather.temp+"\u2103."

        var tweet = "";

        if(weatherTypeString)
          tweet += weatherTypeString + " ";
        else if(weatherTemperatureString)
          tweet += weatherTemperatureString + " ";

        // Avoid short tweets, add extra detail!
        if(!weatherTypeString && !weatherTemperatureString)
          tweet = "The forecast for "+timePeriod.name+" is: " + weatherString;
        else
          tweet += weatherString;

        callback(tweet);
    });
}

function getWeatherTypeString(type, weather, periodName) {

    // weather_type: snow, rain, hail, thunder, sunny, cloudy
    // weather API: 'clear x', 'few clouds x', 'scattered clouds x', 'broken clouds x', 'drizzle x', 'rain x', 'thunder x', 'snow x', 'mist'

    if(type && weather.mapping) {
        if(type == 'snow')
           if(weather.mapping == 'snow')
               return ("Yes! It looks like it is going to snow " + periodName + "!");
           else
               return ("No, it's not going to snow " + periodName + ".");

        else if(type == 'rain')
           if(weather.mapping == 'rain')
               return ("Unfortunately it looks like it is going to rain " + periodName + ".");
           else if(weather.mapping == 'drizzle')
               return ("It looks like there's going to be a little rain " + periodName + ".");
           else
               return ("Good news, there's no rain forecast " + periodName + "!");

        /*else if(type == 'hail' && weather.mapping == 'hail')
           if(weather.mapping == 'hail')
               return ("Hail is forecast "+timePeriod.name."!");
           else
               return ("There's no hail forecast "+timePeriod.name);*/

        else if(type == 'thunder')
           if(weather.mapping == 'thunder')
               return ("Yes, a thunderstorm is forecast " + periodName + "!");
           else
               return ("Luckily there's no thunder forecast " + periodName + ".");

        else if(type == 'sunny')
           if(weather.mapping == 'clear')
               return ("Sun is forecast " + periodName + ", it's going to be around "+Math.round(weather.temp)+" degrees!");
           else if(weather.mapping == 'few clouds')
               return ("It should be sunny " + periodName + ", but there will be a few clouds.");
           else
               return ("It doesn't like it's going to be sunny " + periodName + ".");

        else if(type == 'cloudy')
           if(weather.mapping == 'scattered clouds')
               return ("There is a little cloud forecast " + periodName + ".");
           else if(weather.mapping == 'broken clouds')
               return ("There will be heavy cloud " + periodName + ".");
           else
               return ("There's no cloud forecast " + periodName + ".");
    }

    return;
}

function getWeatherTemperatureString(temperature, weather, periodName) {

    // weather_temperature: very cold, cold, neutral, warm, very warm
    if(temperature !== false) {
        if(weather.temp < 5)
            if(temperature == 'very cold')
                return ("Yes, it's going to be very cold " + periodName + ".");
            else
                return ("Luckily it's going to be "+Math.round(weather.temp)+" " + periodName + ", so not too cold!");

        else if(weather.temp < 10)
            if(temperature == 'cold')
                return ("It looks like it's going to be cold " + periodName + ".");
            else
                return ("It's going to be "+Math.round(weather.temp)+" degrees " + periodName + ".");

        else if(weather.temp < 15)
            if(temperature == 'neutral')
                return ("It's going to be an average temperature " + periodName + ".");
            else
                return ("No, it's going to be average " + periodName + ".");

        else if(weather.temp < 20)
            if(temperature == 'warm')
                return ("It should be warmer than usual " + periodName + ".");
            else
                return ("It's going to be warmer than usual " + periodName + ".");

        else if(weather.temp >= 20)
            if(temperature == 'very warm')
                return ("Yes, it should be very warm " + periodName + ".");
            else
                return ("No, it's going to be very warm " + periodName + ".");
    }

    return;
}

function capitaliseFirstLetter(string)
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}<|endoftext|>


<commit_before>import { moduleForComponent } from 'ember-qunit';
import { skip } from 'qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('curriculum-inventory-sequence-block-dates-duration-editor', 'Integration | Component | curriculum inventory sequence block dates duration editor', {
  integration: true
});

skip('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#curriculum-inventory-sequence-block-dates-duration-editor}}
      template block text
    {{/curriculum-inventory-sequence-block-dates-duration-editor}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});
<commit_msg>Implemented integration test for dates/duration editor component.<commit_after>import Ember from 'ember';
import { moduleForComponent } from 'ember-qunit';
import { test } from 'qunit';
import hbs from 'htmlbars-inline-precompile';
import moment from 'moment';
import { openDatepicker } from 'ember-pikaday/helpers/pikaday';
import wait from 'ember-test-helpers/wait';

const { Object } = Ember;

moduleForComponent(
  'curriculum-inventory-sequence-block-dates-duration-editor',
  'Integration | Component | curriculum inventory sequence block dates duration editor',
  {
    integration: true
  }
);

test('it renders', function(assert) {
  let block = Object.create({
    startDate: moment('2016-04-23').toDate(),
    endDate: moment('2016-06-02').toDate(),
    duration: 10
  });
  this.set('sequenceBlock', block);
  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor sequenceBlock=sequenceBlock}}`);
  assert.equal(this.$('.start-date label').text().trim(), 'Start:', 'Start date is labeled correctly.');
  assert.equal(
    this.$('.start-date input').val(),
    moment(block.startDate).format('M/D/YYYY'),
    'Start date input has correct value.'
  );
  assert.equal(this.$('.end-date label').text().trim(), 'End:', 'End date input is labeled correctly.');
  assert.equal(
    this.$('.end-date input').val(),
    moment(block.endDate).format('M/D/YYYY'),
    'End date input has correct value.'
  );
  assert.equal(this.$('.duration label').text().trim(), 'Duration (in Days):', 'Duration input is labeled correctly.');
  assert.equal(this.$('.duration input').val(), block.duration, 'Duration input has correct value.');
  assert.equal(this.$('.buttons .done').length, 1, 'Done button is present.');
  assert.equal(this.$('.buttons .cancel').length, 1, 'Cancel button is present.');
});

test('save', function(assert) {
  assert.expect(3);
  const newStartDate = moment('2016-10-30');
  const newEndDate = moment('2016-11-02');
  const newDuration = '5';
  let block = Object.create({
    startDate: moment('2016-04-23').toDate(),
    endDate: moment('2016-06-02').toDate(),
    duration: 5
  });
  let saveAction = function(startDate, endDate, duration) {
    assert.equal(moment(startDate).format('YYYY-MM-DD'), newStartDate.format('YYYY-MM-DD'), 'New start date on save.');
    assert.equal(moment(endDate).format('YYYY-MM-DD'), newEndDate.format('YYYY-MM-DD'), 'New end date on save.');
    assert.equal(duration, newDuration, 'New duration on save');
  };
  this.set('block', block);
  this.set('saveAction', saveAction);
  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor sequenceBlock=block save=saveAction}}`);
  let interactor = openDatepicker(this.$('.start-date input'));
  interactor.selectDate(newStartDate.toDate());
  interactor = openDatepicker(this.$('.end-date input'));
  interactor.selectDate(newEndDate.toDate());
  this.$('.duration input').val(newDuration);
  this.$('.duration input').trigger('change');
  this.$('.buttons .done').click();
});

test('save with date range and a zero duration', function(assert) {
  assert.expect(3);
  const newStartDate = moment('2016-10-30');
  const newEndDate = moment('2016-11-02');
  const newDuration = '0';
  let block = Object.create();
  let saveAction = function(startDate, endDate, duration) {
    assert.equal(moment(startDate).format('YYYY-MM-DD'), newStartDate.format('YYYY-MM-DD'), 'New start date on save.');
    assert.equal(moment(endDate).format('YYYY-MM-DD'), newEndDate.format('YYYY-MM-DD'), 'New end date on save.');
    assert.equal(duration, newDuration, 'New duration on save');
  };
  this.set('block', block);
  this.set('saveAction', saveAction);
  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor sequenceBlock=block save=saveAction}}`);
  let interactor = openDatepicker(this.$('.start-date input'));
  interactor.selectDate(newStartDate.toDate());
  interactor = openDatepicker(this.$('.end-date input'));
  interactor.selectDate(newEndDate.toDate());
  this.$('.duration input').val(newDuration);
  this.$('.duration input').trigger('change');
  this.$('.buttons .done').click();
});

test('save with non-zero duration and no date range', function(assert) {
  assert.expect(3);
  const newDuration = '5';
  let block = Object.create();

  let saveAction = function(startDate, endDate, duration) {
    assert.equal(startDate, null, 'NULL for start date on save.');
    assert.equal(endDate, null, 'NULL for end date on save.');
    assert.equal(duration, newDuration, 'New duration on save.');
  };
  this.set('block', block);
  this.set('saveAction', saveAction);
  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor sequenceBlock=block save=saveAction}}`);
  this.$('.duration input').val(newDuration);
  this.$('.duration input').trigger('change');
  this.$('.buttons .done').click();
});

test('cancel', function(assert) {
  assert.expect(1);
  let block = Object.create({
    startDate: moment('2016-04-23').toDate(),
    endDate: moment('2016-06-02').toDate(),
    duration: 10
  });
  let cancelAction = function() {
    assert.ok(true, 'Cancel action got invoked.')
  };
  this.set('block', block);
  this.set('cancel', cancelAction);
  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor sequenceBlock=block cancel=cancel}}`);
  this.$('.buttons .cancel').click();
});

test('save fails if end-date is older than start-date', function(assert) {
  assert.expect(2);
  const newStartDate = moment('2016-10-30');
  const newEndDate = moment('2013-11-02');
  let block = Object.create({ duration: 0 });
  let saveAction = function() {
    assert.ok(false, 'Save action should have not been invoked.');
  };
  this.set('block', block);
  this.set('saveAction', saveAction);
  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor sequenceBlock=block save=saveAction}}`);
  assert.equal(this.$('.validation-error-message').length, 0, 'No initial validation errors.');
  let interactor = openDatepicker(this.$('.start-date input'));
  interactor.selectDate(newStartDate.toDate());
  interactor = openDatepicker(this.$('.end-date input'));
  interactor.selectDate(newEndDate.toDate());
  this.$('.buttons .done').click();
  return wait().then(() => {
    assert.ok(this.$('.validation-error-message').length, 1, 'Validation error shows.');
  });
});

test('save fails on missing duration', function(assert) {
  assert.expect(2);
  let block = Object.create({
    startDate: moment('2016-04-23').toDate(),
    endDate: moment('2016-06-02').toDate(),
    duration: 10
  });
  let saveAction = function() {
    assert.ok(false, 'Save action should have not been invoked.');
  };
  this.set('block', block);
  this.set('saveAction', saveAction);
  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor sequenceBlock=block save=saveAction}}`);
  assert.equal(this.$('.validation-error-message').length, 0, 'No initial validation errors.');
  this.$('.duration input').val('');
  this.$('.duration input').trigger('change');
  this.$('.buttons .done').click();
  return wait().then(() => {
    assert.ok(this.$('.validation-error-message').length, 1, 'Validation error shows.');
  });
});

test('save fails on invalid duration', function(assert) {
  assert.expect(2);
  let block = Object.create({
    startDate: moment('2016-04-23').toDate(),
    endDate: moment('2016-06-02').toDate(),
    duration: 10
  });
  let saveAction = function() {
    assert.ok(false, 'Save action should have not been invoked.');
  };
  this.set('block', block);
  this.set('saveAction', saveAction);
  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor sequenceBlock=block save=saveAction}}`);
  assert.equal(this.$('.validation-error-message').length, 0, 'No initial validation errors.');
  this.$('.duration input').val('-10');
  this.$('.duration input').trigger('change');
  this.$('.buttons .done').click();
  return wait().then(() => {
    assert.ok(this.$('.validation-error-message').length, 1, 'Validation error shows.');
  });
});

test('save fails if neither date range nor duration is provided', function(assert) {
  assert.expect(2);
  let block = Object.create({ duration: 0 });
  let saveAction = function() {
    assert.ok(false, 'Save action should have not been invoked.');
  };
  this.set('block', block);
  this.set('saveAction', saveAction);
  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor sequenceBlock=block save=saveAction}}`);
  assert.equal(this.$('.validation-error-message').length, 0, 'No initial validation errors.');
  this.$('.buttons .done').click();
  return wait().then(() => {
    assert.ok(this.$('.validation-error-message').length, 1, 'Validation error shows.');
  });
});

test('save fails if start-date is given but no end-date is provided', function(assert) {
  assert.expect(2);
  let block = Object.create({ duration: 0 });
  let saveAction = function() {
    assert.ok(false, 'Save action should have not been invoked.');
  };
  this.set('block', block);
  this.set('saveAction', saveAction);
  this.render(hbs`{{curriculum-inventory-sequence-block-dates-duration-editor sequenceBlock=block save=saveAction}}`);
  assert.equal(this.$('.validation-error-message').length, 0, 'No initial validation errors.');
  let interactor = openDatepicker(this.$('.start-date input'));
  interactor.selectDate(new Date());
  this.$('.buttons .done').click();
  return wait().then(() => {
    assert.ok(this.$('.validation-error-message').length, 1, 'Validation error shows.');
  });
});

test('save fails on invalid duration', function(assert) {
  // @todo implement [ST 2016/11/03]
  assert.ok(true);
});
<|endoftext|>


<commit_before>import program from "commander";
import { resolve, join } from "path";
import { expand } from "config-expander";
import { prepareDatabase } from "./database";
import { prepareHttpServer } from "./http";
import { version, description } from "../package.json";

program
  .description(description)
  .version(version)
  .option("-c, --config <directory>", "use config from directory")
  .action(async args => {
    const configDir = process.env.CONFIGURATION_DIRECTORY || program.config;

    // some constants used while loading the configuration
    const constants = {
      basedir: configDir || process.cwd(), // where is the config file located
      installdir: resolve(__dirname, ".."), // make references to the installdir possible
      statedir: process.env.STATE_DIRECTORY || process.cwd()
    };

    // default config if none is given
    const defaultConfig = {
      database: {
        path: "level.db"
      },
      http: {
        port: 123456
      }
    };

    // load config and expand expressions ${something} inside
    const config = await expand(
      configDir ? "${include('config.json')}" : defaultConfig,
      {
        constants
      }
    );

    if (process.env.PORT !== undefined) {
      port = parseInt(process.env.PORT, 10);
      if (Number.isNaN(port)) {
        port = process.env.PORT;
      }

      config.http.port = port;
    }

    console.log(JSON.strinfify(process.env));
    console.log(JSON.strinfify(config));

    // prepare the database with the config
    const db = await prepareDatabase(config);

    // prepare the web-server with the config and the database
    const http = await prepareHttpServer(config, db);
  })
  .parse(process.argv);
<commit_msg>fix:typo<commit_after>import program from "commander";
import { resolve, join } from "path";
import { expand } from "config-expander";
import { prepareDatabase } from "./database";
import { prepareHttpServer } from "./http";
import { version, description } from "../package.json";

program
  .description(description)
  .version(version)
  .option("-c, --config <directory>", "use config from directory")
  .action(async args => {
    const configDir = process.env.CONFIGURATION_DIRECTORY || program.config;

    // some constants used while loading the configuration
    const constants = {
      basedir: configDir || process.cwd(), // where is the config file located
      installdir: resolve(__dirname, ".."), // make references to the installdir possible
      statedir: process.env.STATE_DIRECTORY || process.cwd()
    };

    // default config if none is given
    const defaultConfig = {
      database: {
        path: "level.db"
      },
      http: {
        port: 123456
      }
    };

    // load config and expand expressions ${something} inside
    const config = await expand(
      configDir ? "${include('config.json')}" : defaultConfig,
      {
        constants
      }
    );

    if (process.env.PORT !== undefined) {
      port = parseInt(process.env.PORT, 10);
      if (Number.isNaN(port)) {
        port = process.env.PORT;
      }

      config.http.port = port;
    }

    console.log(JSON.stringify(process.env));
    console.log(JSON.stringify(config));

    // prepare the database with the config
    const db = await prepareDatabase(config);

    // prepare the web-server with the config and the database
    const http = await prepareHttpServer(config, db);
  })
  .parse(process.argv);
<|endoftext|>


<commit_before>/**
* Node dependencies
**/
import fs from 'fs';
import path from 'path';
import os from 'os';
import { fork } from 'child_process';

/**
* NPM dependencies
**/
import { CLIEngine } from 'eslint';
import glob from 'glob';

/**
* Local dependencies
**/
import { formatResults } from './formatter';

const cpuCount = os.cpus().length;

function getIgnorePatterns(options) {
  let ignorePath = path.join(options.cwd || process.cwd(), '.eslintignore');
  try {
    const ignore = fs.readFileSync(
      ignorePath, 'utf8'
    ).trim().split('\n');

    if (options.ignorePattern) {
      ignore.push(options.ignorePattern);
    }
    return ignore;
  } catch (e) {
    return [];
  }
}

function hasEslintCache(options) {
  const cacheLocation = (
    options.cacheFile || options.cacheLocation || path.join(
      options.cwd || process.cwd(), '.eslintcache'
    )
  );
  try {
    fs.accessSync(path.resolve(cacheLocation), fs.F_OK);
    return true;
  } catch (e) {
    return false;
  }
}

function getFilesByPatterns(patterns, options) {
  const ignore = getIgnorePatterns(options);
  let files = [];

  patterns.forEach(pattern => {
    let isFile = false;
    let isFolder = false;
    try {
      const stats = fs.lstatSync(pattern);
      isFile = stats.isFile();
      isFolder = stats.isDirectory();
    } catch (e) {
      //no-op
    }

    if (isFile) {
      files.push(pattern);
    } else {
      const path = isFolder ? `${pattern.replace(/\'|\"|\/$/g, '')}/**` :
        pattern.replace(/\'|\"|\/$/g, '');
      const newFiles = glob.sync(
        path, { cwd: options.cwd || process.cwd(), nodir: true, ignore }
      );
      files = files.concat(newFiles);
    }
  });

  return files;
}

function eslintFork(options, files) {
  return new Promise((resolve, reject) => {
    const eslintChild = fork(path.resolve(__dirname, 'linter'));
    eslintChild.on('message', (report) => {
      if (report.errorCount || report.warningCount) {
        console.log(formatResults(report.results));
      }
      resolve(report);
    });
    eslintChild.on('exit', (code) => {
      if (code !== 0) {
        reject('Linting failed');
      }
    });
    eslintChild.send({options, files});
  });
}

export default class Linter {
  constructor (options) {
    this._options = options;
    this._engine = new CLIEngine(options);
  }

  run (files) {
    return new Promise((resolve) => {
      const report = this._engine.executeOnFiles(files);
      if (this._options.fix) {
        this._engine.outputFixes(report);
      }

      if (this._options.quiet) {
        report.results = this._engine.getErrorResults(report.results);
      }
      resolve(report);
    });
  }

  execute(patterns) {
    return new Promise((resolve, reject) => {
      const files = getFilesByPatterns(
        patterns, this._options
      );

      const hasCache = hasEslintCache(this._options);

      if (!hasCache && files.length > 50 && cpuCount >= 2) {
        // too many items, need to spawn process (if machine has multi-core)
        const totalCount = {
          errorCount: 0,
          warningCount: 0
        };
        const chunckedPromises = [];
        const chunkSize = Math.ceil(files.length / cpuCount);
        for (let i = 0; i < files.length; i += chunkSize) {
          const chunkedPaths = files.slice(i, i + chunkSize);
          const chunckedPromise = eslintFork(
            this._options, chunkedPaths
          );
          chunckedPromise.then((report) => {
            totalCount.errorCount += report.errorCount;
            totalCount.warningCount += report.warningCount;
          });
          chunckedPromises.push(chunckedPromise);
        }
        Promise.all(chunckedPromises).then(() => {
          resolve(totalCount);
        });
      } else {
        this.run(files).then((report) => {
          if (report.errorCount || report.warningCount) {
            console.log(formatResults(report.results));
          }
          resolve(report);
        }, reject);
      }
    });
  }
}

process.on('message', ({options, files}) => {
  // make sure to ignore message to other nested processes
  if (files) {
    new Linter(options).run(files).then((report) => {
      process.send(report);
    }, (err) => {
      console.log(err);
      process.exit(1);
    });
  }
});
<commit_msg>should pass<commit_after>/**
* Node dependencies
**/
import fs from 'fs';
import path from 'path';
import os from 'os';
import { fork } from 'child_process';

/**
* NPM dependencies
**/
import { CLIEngine } from 'eslint';
import glob from 'glob';

/**
* Local dependencies
**/
import { formatResults } from './formatter

const cpuCount = os.cpus().length;

function getIgnorePatterns(options) {
  let ignorePath = path.join(options.cwd || process.cwd(), '.eslintignore');
  try {
    const ignore = fs.readFileSync(
      ignorePath, 'utf8'
    ).trim().split('\n');

    if (options.ignorePattern) {
      ignore.push(options.ignorePattern);
    }
    return ignore;
  } catch (e) {
    return [];
  }
}

function hasEslintCache(options) {
  const cacheLocation = (
    options.cacheFile || options.cacheLocation || path.join(
      options.cwd || process.cwd(), '.eslintcache'
    )
  );
  try {
    fs.accessSync(path.resolve(cacheLocation), fs.F_OK);
    return true;
  } catch (e) {
    return false;
  }
}

function getFilesByPatterns(patterns, options) {
  const ignore = getIgnorePatterns(options);
  let files = [];

  patterns.forEach(pattern => {
    let isFile = false;
    let isFolder = false;
    try {
      const stats = fs.lstatSync(pattern);
      isFile = stats.isFile();
      isFolder = stats.isDirectory();
    } catch (e) {
      //no-op
    }

    if (isFile) {
      files.push(pattern);
    } else {
      const path = isFolder ? `${pattern.replace(/\'|\"|\/$/g, '')}/**` :
        pattern.replace(/\'|\"|\/$/g, '');
      const newFiles = glob.sync(
        path, { cwd: options.cwd || process.cwd(), nodir: true, ignore }
      );
      files = files.concat(newFiles);
    }
  });

  return files;
}

function eslintFork(options, files) {
  return new Promise((resolve, reject) => {
    const eslintChild = fork(path.resolve(__dirname, 'linter'));
    eslintChild.on('message', (report) => {
      if (report.errorCount || report.warningCount) {
        console.log(formatResults(report.results));
      }
      resolve(report);
    });
    eslintChild.on('exit', (code) => {
      if (code !== 0) {
        reject('Linting failed');
      }
    });
    eslintChild.send({options, files});
  });
}

export default class Linter {
  constructor (options) {
    this._options = options;
    this._engine = new CLIEngine(options);
  }

  run (files) {
    return new Promise((resolve) => {
      const report = this._engine.executeOnFiles(files);
      if (this._options.fix) {
        this._engine.outputFixes(report);
      }

      if (this._options.quiet) {
        report.results = this._engine.getErrorResults(report.results);
      }
      resolve(report);
    });
  }

  execute(patterns) {
    return new Promise((resolve, reject) => {
      const files = getFilesByPatterns(
        patterns, this._options
      );

      const hasCache = hasEslintCache(this._options);

      if (!hasCache && files.length > 50 && cpuCount >= 2) {
        // too many items, need to spawn process (if machine has multi-core)
        const totalCount = {
          errorCount: 0,
          warningCount: 0
        };
        const chunckedPromises = [];
        const chunkSize = Math.ceil(files.length / cpuCount);
        for (let i = 0; i < files.length; i += chunkSize) {
          const chunkedPaths = files.slice(i, i + chunkSize);
          const chunckedPromise = eslintFork(
            this._options, chunkedPaths
          );
          chunckedPromise.then((report) => {
            totalCount.errorCount += report.errorCount;
            totalCount.warningCount += report.warningCount;
          });
          chunckedPromises.push(chunckedPromise);
        }
        Promise.all(chunckedPromises).then(() => {
          resolve(totalCount);
        });
      } else {
        this.run(files).then((report) => {
          if (report.errorCount || report.warningCount) {
            console.log(formatResults(report.results));
          }
          resolve(report);
        }, reject);
      }
    });
  }
}

process.on('message', ({options, files}) => {
  // make sure to ignore message to other nested processes
  if (files) {
    new Linter(options).run(files).then((report) => {
      process.send(report);
    }, (err) => {
      console.log(err);
      process.exit(1);
    });
  }
});
<|endoftext|>


<commit_before>// PolarBot
// logger.js

const fs = require('fs');

// Logs a discordJS-message -object
exports.logMessage = function(message) {
    var content =
        currentTime() +
        message.channel.server +
        '/' + message.channel.name + ' - ' +
        message.sender.username +
        ': ' + message.cleanContent;
    console.log(content);
    logToFile(content);
}

// Logs a message
exports.log = function(content) {
    content = currentTime() + content;
    console.log(content);
    logToFile(content);
}

// Logs a message into log.txt
function logToFile(content) {
    // Add a line to log.txt
    fs.appendFile('log.txt', content + '\n', function(err) {
        if (err) {
            console.log('An error occurred when logging to file: ' + err);
        }
    });
}

// Get current time in a nice, log-friendly format
function currentTime() {
    var curTime = new Date();
    var date = formatTime(curTime.getDate());
    var month = formatTime((curTime.getMonth() + 1).toString());
    var year = formatTime(curTime.getFullYear());
    var hour = formatTime(curTime.getHours());
    var minute = formatTime(curTime.getMinutes());
    curTime =
        date + '.' +
        month + '.' +
        year + ' ' +
        hour + ':' +
        minute + ' ';
    return curTime;
}

// Adds a 0 if given number's length is 1
function formatTime(num) {
    var format = '';
    if (num.length == 1) {
        format += '0';
    }
    format += num;
    return format;
}

// Not in use, use local time
function toHHMM(date) {
    var txt = '';
    var hours = '';
    var minutes = '';
    hours = date.getHours().toString();
    minutes = date.getMinutes().toString();
    if (hours.length == 1) hours = '0' + hours;
    if (minutes.length == 1) minutes = '0' + minutes;
    txt += hours;
    txt += ':';
    txt += minutes;
    return txt;
}
<commit_msg>fixed time formating<commit_after>// PolarBot
// logger.js

const fs = require('fs');

// Logs a discordJS-message -object
exports.logMessage = function(message) {
    var content =
        currentTime() +
        message.channel.server +
        '/' + message.channel.name + ' - ' +
        message.sender.username +
        ': ' + message.cleanContent;
    console.log(content);
    logToFile(content);
}

// Logs a message
exports.log = function(content) {
    content = currentTime() + content;
    console.log(content);
    logToFile(content);
}

// Logs a message into log.txt
function logToFile(content) {
    // Add a line to log.txt
    fs.appendFile('log.txt', content + '\n', function(err) {
        if (err) {
            console.log('An error occurred when logging to file: ' + err);
        }
    });
}

// Get current time in a nice, log-friendly format
function currentTime() {
    var curTime = new Date();
    var date = formatTime(curTime.getDate());
    var month = formatTime((curTime.getMonth() + 1).toString());
    var year = formatTime(curTime.getFullYear());
    var hour = formatTime(curTime.getHours());
    var minute = formatTime(curTime.getMinutes());
    curTime =
        date + '.' +
        month + '.' +
        year + ' ' +
        hour + ':' +
        minute + ' ';
    return curTime;
}

// Adds a 0 if given number's length is 1
function formatTime(num) {
    var format = '';
    num = num.toString();
    if (num.length == 1) {
        format += '0';
    }
    format += num;
    return format;
}

// Not in use, use local time
function toHHMM(date) {
    var txt = '';
    var hours = '';
    var minutes = '';
    hours = date.getHours().toString();
    minutes = date.getMinutes().toString();
    if (hours.length == 1) hours = '0' + hours;
    if (minutes.length == 1) minutes = '0' + minutes;
    txt += hours;
    txt += ':';
    txt += minutes;
    return txt;
}
<|endoftext|>


<commit_before>var socket = require('./socket');
var stairway = require('./stairway');

var index = 0;

function setHarmonicBase(value) {
  socket.emit('update', {
    type: 'harmonic',
    value: value
  });
}

function next() {
  if (index > stairway.length - 1) {
    index = 0;
  }
  setHarmonicBase(stairway[index]);
  index++;
}

function play() {
  next();
  if (index !== stairway.length - 1) {
    window.setTimeout(play, 500);
  }
}

global.setHarmonicBase = setHarmonicBase;
global.play = play;
<commit_msg>Some more cleanup<commit_after>var socket = require('./socket');
var stairway = require('./stairway');

var index = 0;

function setHarmonicBase(value) {
  socket.emit('update', {
    type: 'harmonic',
    value: value
  });
}

function next() {
  if (index > stairway.length - 1) {
    index = 0;
  }
  setHarmonicBase(stairway[index]);
  index++;
}

function play() {
  next();
  if (index !== stairway.length - 1) {
    window.setTimeout(play, 500);
  }
}

global.note = global.freq = setHarmonicBase;
global.play = play;
<|endoftext|>