<commit_before>angular.module('mwUI.List')

  //TODO rename to mwListHeader
  .directive('mwListableHeaderBb', function () {
    return {
      require: '^mwListableBb',
      scope: {
        property: '@sort'
      },
      transclude: true,
      replace: true,
      templateUrl: 'uikit/mw-list/directives/templates/mw_list_header.html',
      link: function (scope, elm, attr, mwListCtrl) {
        var ascending = '+',
          descending = '-',
          collection = mwListCtrl.getCollection();

        var getSortOrder = function () {
          if (collection && collection.filterable) {
            collection.filterable.getSortOrder();
          } else {
            return false;
          }
        };

        var sort = function (property, order) {
          var sortOrder = order + property;

          collection.filterable.setSortOrder(sortOrder);
          return collection.fetch();
        };

        scope.toggleSortOrder = function () {
          if (scope.property) {
            var sortOrder = ascending; //default
            if (getSortOrder() === ascending + scope.property) {
              sortOrder = descending;
            }
            sort(scope.property, sortOrder);
          }
        };

        scope.isSelected = function (prefix) {
          var sortOrder = getSortOrder();

          if (sortOrder && prefix) {
            return sortOrder === prefix + scope.property;
          } else if(sortOrder && !prefix){
            return (sortOrder === '+' + scope.property || sortOrder === '-' + scope.property);
          }
        };

        mwListCtrl.registerColumn(scope);

        scope.$on('$destroy', function () {
          mwListCtrl.unRegisterColumn(scope);
        });
      }
    };
  });<commit_msg>Adds missing return statement which caused method to always return undefined<commit_after>angular.module('mwUI.List')

  //TODO rename to mwListHeader
  .directive('mwListableHeaderBb', function () {
    return {
      require: '^mwListableBb',
      scope: {
        property: '@sort'
      },
      transclude: true,
      replace: true,
      templateUrl: 'uikit/mw-list/directives/templates/mw_list_header.html',
      link: function (scope, elm, attr, mwListCtrl) {
        var ascending = '+',
          descending = '-',
          collection = mwListCtrl.getCollection();

        var getSortOrder = function () {
          if (collection && collection.filterable) {
            return collection.filterable.getSortOrder();
          } else {
            return false;
          }
        };

        var sort = function (property, order) {
          var sortOrder = order + property;

          collection.filterable.setSortOrder(sortOrder);
          return collection.fetch();
        };

        scope.toggleSortOrder = function () {
          if (scope.property) {
            var sortOrder = ascending; //default
            if (getSortOrder() === ascending + scope.property) {
              sortOrder = descending;
            }
            sort(scope.property, sortOrder);
          }
        };

        scope.isSelected = function (prefix) {
          var sortOrder = getSortOrder();

          if (sortOrder && prefix) {
            return sortOrder === prefix + scope.property;
          } else if(sortOrder && !prefix){
            return (sortOrder === '+' + scope.property || sortOrder === '-' + scope.property);
          }
        };

        mwListCtrl.registerColumn(scope);

        scope.$on('$destroy', function () {
          mwListCtrl.unRegisterColumn(scope);
        });
      }
    };
  });<|endoftext|>


<commit_before>var storageData = [];
var thumbnails = [];
var DATA_URL = 'http://netfight-img.herokuapp.com/?url=';

$(document).ready(function() {
    $('#js-canvas').attr('width', window.innerWidth);
    $('#js-canvas').attr('height', window.innerHeight);

     // Set the log level
    cutie.Log.level = cutie.Log.VERBOSE;

    // Get data from storage, then kick-off the game
    chrome.storage.local.get('netfight', function(obj) {
        storageData = obj['netfight'];

        async.map(storageData, getBase64, function(err, results){
            thumbnails = results;
            cutie.start("fight");
        });
    });
});

$(window).resize(function() {
    $('#js-canvas').attr('width', window.innerWidth);
    $('#js-canvas').attr('height', window.innerHeight);
    cutie.WIDTH = window.innerWidth;
    cutie.HEIGHT = window.innerHeight;
});

(function() {
    var scene = new cutie.Scene();

    scene.preload = function(loader) {
        loader.loadFile({
            'id': 'astronaut_helmet',
            'src': 'img/astronaut_helmet.png'
        });
        loader.loadFile({
            'id': 'astronaut_helmet_projectile',
            'src': 'img/astronaut_helmet_projectile.png'
        });
        loader.loadFile({
            'id': 'guy_fawkes',
            'src': 'img/guy_fawkes.png'
        });
        loader.loadFile({
            'id': 'guy_fawkes_projectile',
            'src': 'img/guy_fawkes_projectile.png'
        });
        loader.loadFile({
            'id': 'jason_mask',
            'src': 'img/jason_mask.png'
        });
        loader.loadFile({
            'id': 'jason_mask_projectile',
            'src': 'img/jason_mask_projectile.png'
        });
        loader.loadFile({
            'id': 'jester_hat',
            'src': 'img/jester_hat.png'
        });
        loader.loadFile({
            'id': 'jester_hat_projectile',
            'src': 'img/jester_hat_projectile.png'
        });
        loader.loadFile({
            'id': 'mickey_ears',
            'src': 'img/mickey_ears.png'
        });
        loader.loadFile({
            'id': 'mickey_ears_projectile',
            'src': 'img/mickey_ears_projectile.png'
        });
        loader.loadFile({
            'id': 'pope_hat',
            'src': 'img/pope_hat.png'
        });
        loader.loadFile({
            'id': 'pope_hat_projectile',
            'src': 'img/pope_hat_projectile.png'
        });
        loader.loadFile({
            'id': 'saiyan_hair',
            'src': 'img/saiyan_hair.png'
        });
        loader.loadFile({
            'id': 'saiyan_hair_projectile',
            'src': 'img/saiyan_hair_projectile.png'
        });
        loader.loadFile({
            'id': 'wizard_hat',
            'src': 'img/wizard_hat.png'
        });
        loader.loadFile({
            'id': 'wizard_hat_projectile',
            'src': 'img/wizard_hat_projectile.png'
        });
        loader.loadFile({
            'id': 'wolverine',
            'src': 'img/wolverine.png'
        });
        loader.loadFile({
            'id': 'wolverine_projectile',
            'src': 'img/wolverine_projectile.png'
        });
    }

    scene.init = function(preloaded) {
        cutie.Log.d('title.init()');

        // Put images on the stage
        for (var i = 0; i < thumbnails.length; i++) {
            var f = makeFighter(preloaded, thumbnails[i], null);
            f.x = Math.random() * cutie.WIDTH;
            f.y = Math.random() * cutie.HEIGHT;
            this.addChild(f);
        }
    }

    function makeFighter(preloaded, thumbnail, addonId) {
        var bitmap = new cutie.Bitmap(thumbnail);
        return bitmap;
    }

    cutie.registerScene(scene, 'fight');
})();

function getBase64(o, callback) {
    var url = DATA_URL + o.img;
    $.get(url, function(results) {
        var image = new Image();
        image.src = results;
        callback(null, image);
    });
}
<commit_msg>Position fighters.<commit_after>var storageData = [];
var thumbnails = [];
var DATA_URL = 'http://netfight-img.herokuapp.com/?url=';
var fighters = [];

$(document).ready(function() {
    $('#js-canvas').attr('width', window.innerWidth);
    $('#js-canvas').attr('height', window.innerHeight);

     // Set the log level
    cutie.Log.level = cutie.Log.VERBOSE;

    // Get data from storage, then kick-off the game
    chrome.storage.local.get('netfight', function(obj) {
        storageData = obj['netfight'];

        async.map(storageData, getBase64, function(err, results){
            thumbnails = results;
            cutie.start("fight");
        });
    });
});

$(window).resize(function() {
    $('#js-canvas').attr('width', window.innerWidth);
    $('#js-canvas').attr('height', window.innerHeight);
    cutie.WIDTH = window.innerWidth;
    cutie.HEIGHT = window.innerHeight;
});

(function() {
    var scene = new cutie.Scene();

    scene.preload = function(loader) {
        loader.loadFile({
            'id': 'astronaut_helmet',
            'src': 'img/astronaut_helmet.png'
        });
        loader.loadFile({
            'id': 'astronaut_helmet_projectile',
            'src': 'img/astronaut_helmet_projectile.png'
        });
        loader.loadFile({
            'id': 'guy_fawkes',
            'src': 'img/guy_fawkes.png'
        });
        loader.loadFile({
            'id': 'guy_fawkes_projectile',
            'src': 'img/guy_fawkes_projectile.png'
        });
        loader.loadFile({
            'id': 'jason_mask',
            'src': 'img/jason_mask.png'
        });
        loader.loadFile({
            'id': 'jason_mask_projectile',
            'src': 'img/jason_mask_projectile.png'
        });
        loader.loadFile({
            'id': 'jester_hat',
            'src': 'img/jester_hat.png'
        });
        loader.loadFile({
            'id': 'jester_hat_projectile',
            'src': 'img/jester_hat_projectile.png'
        });
        loader.loadFile({
            'id': 'mickey_ears',
            'src': 'img/mickey_ears.png'
        });
        loader.loadFile({
            'id': 'mickey_ears_projectile',
            'src': 'img/mickey_ears_projectile.png'
        });
        loader.loadFile({
            'id': 'pope_hat',
            'src': 'img/pope_hat.png'
        });
        loader.loadFile({
            'id': 'pope_hat_projectile',
            'src': 'img/pope_hat_projectile.png'
        });
        loader.loadFile({
            'id': 'saiyan_hair',
            'src': 'img/saiyan_hair.png'
        });
        loader.loadFile({
            'id': 'saiyan_hair_projectile',
            'src': 'img/saiyan_hair_projectile.png'
        });
        loader.loadFile({
            'id': 'wizard_hat',
            'src': 'img/wizard_hat.png'
        });
        loader.loadFile({
            'id': 'wizard_hat_projectile',
            'src': 'img/wizard_hat_projectile.png'
        });
        loader.loadFile({
            'id': 'wolverine',
            'src': 'img/wolverine.png'
        });
        loader.loadFile({
            'id': 'wolverine_projectile',
            'src': 'img/wolverine_projectile.png'
        });
    }

    scene.init = function(preloaded) {
        cutie.Log.d('title.init()');

        // Create fighters
        var cx = cutie.WIDTH/2;
        var cy = cutie.HEIGHT/2;
        var angleOffset = (Math.PI * 2) / thumbnails.length;
        var angle = angleOffset / 2;
        var radius = cutie.HEIGHT/4;
        for (var i = 0; i < thumbnails.length; i++) {
            var f = makeFighter(preloaded, thumbnails[i], null);
            f.x = Math.cos(angle) * radius + cx;
            f.y = Math.sin(angle) * radius + cy;
            angle += angleOffset;
            fighters.push(f);
            this.addChild(f);
        }
    }

    function makeFighter(preloaded, thumbnail, addonId) {
        var bitmap = new cutie.Bitmap(thumbnail);
        bitmap.regX = bitmap.image.width/2;
        bitmap.regY = bitmap.image.height/2;
        bitmap.scaleX = bitmap.scaleY = 0.4;
        return bitmap;
    }

    cutie.registerScene(scene, 'fight');
})();

function getBase64(o, callback) {
    var url = DATA_URL + o.img;
    $.get(url, function(results) {
        var image = new Image();
        image.src = results;
        callback(null, image);
    });
}<|endoftext|>


<commit_before>/**
 * @module Lights, Camera
 * @submodule Camera
 * @for p5
 * @requires core
 */

'use strict';

var p5 = require('../core/core');

/**
 * Sets camera position
 * @method camera
 * @param  {Number} x  camera postion value on x axis
 * @param  {Number} y  camera postion value on y axis
 * @param  {Number} z  camera postion value on z axis
 * @return {p5}        the p5 object
 * @example
 *

 *
 * function setup(){
 *   createCanvas(100, 100, WEBGL);
 * }
 * function draw(){
 *  //move the camera away from the plane by a sin wave
 *  camera(0, 0, sin(frameCount * 0.01) * 100);
 *  plane(120, 120);
 * }
 *
 *

 */
p5.prototype.camera = function(x, y, z){
  var args = new Array(arguments.length);
  for (var i = 0; i < args.length; ++i) {
    args[i] = arguments[i];
  }
  this._validateParameters(
    'camera',
    args,
    ['Number', 'Number', 'Number']
  );
  //what it manipulates is the model view matrix
  this._renderer.translate(-x, -y, -z);
};

/**
 * Sets perspective camera
 * @method  perspective
 * @param  {Number} fovy   camera frustum vertical field of view,
 *                         from bottom to top of view, in degrees
 * @param  {Number} aspect camera frustum aspect ratio
 * @param  {Number} near   frustum near plane length
 * @param  {Number} far    frustum far plane length
 * @return {p5}            the p5 object
 * @example
 *

 *
 * //drag mouse to toggle the world!
 * //you will see there's a vanish point
 * function setup(){
 *   createCanvas(100, 100, WEBGL);
 *   perspective(60 / 180 * PI, width/height, 0.1, 100);
 * }
 * function draw(){
 *  background(200);
 *  orbitControl();
 *  for(var i = -1; i < 2; i++){
 *     for(var j = -2; j < 3; j++){
 *       push();
 *       translate(i*160, 0, j*160);
 *       box(40, 40, 40);
 *       pop();
 *     }
 *   }
 * }
 *
 *

 */
p5.prototype.perspective = function(fovy,aspect,near,far) {
  var args = new Array(arguments.length);
  for (var i = 0; i < args.length; ++i) {
    args[i] = arguments[i];
  }
  this._validateParameters(
    'perspective',
    args,
    ['Number', 'Number', 'Number', 'Number']
  );
  this._renderer.uPMatrix = p5.Matrix.identity();
  this._renderer.uPMatrix.perspective(fovy,aspect,near,far);
  this._renderer._setCamera = true;
};

/**
 * Setup ortho camera
 * @method  ortho
 * @param  {Number} left   camera frustum left plane
 * @param  {Number} right  camera frustum right plane
 * @param  {Number} bottom camera frustum bottom plane
 * @param  {Number} top    camera frustum top plane
 * @param  {Number} near   camera frustum near plane
 * @param  {Number} far    camera frustum far plane
 * @return {p5}            the p5 object
 * @example
 *

 *
 * //drag mouse to toggle the world!
 * //there's no vanish point
 * function setup(){
 *   createCanvas(100, 100, WEBGL);
 *   ortho(-width/2, width/2, height/2, -height/2, 0.1, 100);
 * }
 * function draw(){
 *  background(200);
 *  orbitControl();
 *  for(var i = -1; i < 2; i++){
 *     for(var j = -2; j < 3; j++){
 *       push();
 *       translate(i*160, 0, j*160);
 *       box(40, 40, 40);
 *       pop();
 *     }
 *   }
 * }
 *
 *

 */
p5.prototype.ortho = function(left,right,bottom,top,near,far) {
  var args = new Array(arguments.length);
  for (var i = 0; i < args.length; ++i) {
    args[i] = arguments[i];
  }
  this._validateParameters(
    'ortho',
    args,
      ['Number', 'Number', 'Number', 'Number', 'Number', 'Number']
  );
  left /= this.width;
  right /= this.width;
  top /= this.height;
  bottom /= this.height;
  this._renderer.uPMatrix = p5.Matrix.identity();
  this._renderer.uPMatrix.ortho(left,right,bottom,top,near,far);
  this._renderer._setCamera = true;
};

module.exports = p5;
<commit_msg>fixes bug where perspective() function was not resetting Projection matrix<commit_after>/**
 * @module Lights, Camera
 * @submodule Camera
 * @for p5
 * @requires core
 */

'use strict';

var p5 = require('../core/core');

/**
 * Sets camera position
 * @method camera
 * @param  {Number} x  camera postion value on x axis
 * @param  {Number} y  camera postion value on y axis
 * @param  {Number} z  camera postion value on z axis
 * @return {p5}        the p5 object
 * @example
 *

 *
 * function setup(){
 *   createCanvas(100, 100, WEBGL);
 * }
 * function draw(){
 *  //move the camera away from the plane by a sin wave
 *  camera(0, 0, sin(frameCount * 0.01) * 100);
 *  plane(120, 120);
 * }
 *
 *

 */
p5.prototype.camera = function(x, y, z){
  var args = new Array(arguments.length);
  for (var i = 0; i < args.length; ++i) {
    args[i] = arguments[i];
  }
  this._validateParameters(
    'camera',
    args,
    ['Number', 'Number', 'Number']
  );
  //what it manipulates is the model view matrix
  this._renderer.translate(-x, -y, -z);
};

/**
 * Sets perspective camera
 * @method  perspective
 * @param  {Number} fovy   camera frustum vertical field of view,
 *                         from bottom to top of view, in degrees
 * @param  {Number} aspect camera frustum aspect ratio
 * @param  {Number} near   frustum near plane length
 * @param  {Number} far    frustum far plane length
 * @return {p5}            the p5 object
 * @example
 *

 *
 * //drag mouse to toggle the world!
 * //you will see there's a vanish point
 * function setup(){
 *   createCanvas(100, 100, WEBGL);
 *   perspective(60 / 180 * PI, width/height, 0.1, 100);
 * }
 * function draw(){
 *  background(200);
 *  orbitControl();
 *  for(var i = -1; i < 2; i++){
 *     for(var j = -2; j < 3; j++){
 *       push();
 *       translate(i*160, 0, j*160);
 *       box(40, 40, 40);
 *       pop();
 *     }
 *   }
 * }
 *
 *

 */
p5.prototype.perspective = function(fovy,aspect,near,far) {
  var args = new Array(arguments.length);
  for (var i = 0; i < args.length; ++i) {
    args[i] = arguments[i];
  }
  this._renderer.uPMatrix = p5.Matrix.identity();
  this._renderer.uPMatrix.perspective(fovy,aspect,near,far);
  this._renderer._isSetCamera = true;
};

/**
 * Setup ortho camera
 * @method  ortho
 * @param  {Number} left   camera frustum left plane
 * @param  {Number} right  camera frustum right plane
 * @param  {Number} bottom camera frustum bottom plane
 * @param  {Number} top    camera frustum top plane
 * @param  {Number} near   camera frustum near plane
 * @param  {Number} far    camera frustum far plane
 * @return {p5}            the p5 object
 * @example
 *

 *
 * //drag mouse to toggle the world!
 * //there's no vanish point
 * function setup(){
 *   createCanvas(100, 100, WEBGL);
 *   ortho(-width/2, width/2, height/2, -height/2, 0.1, 100);
 * }
 * function draw(){
 *  background(200);
 *  orbitControl();
 *  for(var i = -1; i < 2; i++){
 *     for(var j = -2; j < 3; j++){
 *       push();
 *       translate(i*160, 0, j*160);
 *       box(40, 40, 40);
 *       pop();
 *     }
 *   }
 * }
 *
 *

 */
p5.prototype.ortho = function(left,right,bottom,top,near,far) {
  var args = new Array(arguments.length);
  for (var i = 0; i < args.length; ++i) {
    args[i] = arguments[i];
  }
  this._validateParameters(
    'ortho',
    args,
      ['Number', 'Number', 'Number', 'Number', 'Number', 'Number']
  );
  left /= this.width;
  right /= this.width;
  top /= this.height;
  bottom /= this.height;
  this._renderer.uPMatrix = p5.Matrix.identity();
  this._renderer.uPMatrix.ortho(left,right,bottom,top,near,far);
  this._renderer._setCamera = true;
};

module.exports = p5;
<|endoftext|>


<commit_before>angular.module('Aggie')

.controller('IncidentsIndexController', [
  '$state',
  '$scope',
  '$rootScope',
  '$timeout',
  '$stateParams',
  'FlashService',
  'incidents',
  'users',
  'incidentStatusOptions',
  'veracityOptions',
  'Incident',
  'Socket',
  'Queue',
  'paginationOptions',
  function($state, $scope, $rootScope, $timeout, $stateParams, flash, incidents, users, incidentStatusOptions, veracityOptions, Incident, Socket, Queue, paginationOptions) {
    $scope.searchParams = $stateParams;
    $scope.incidents = incidents.results;
    $scope.statusOptions = incidentStatusOptions;
    $scope.veracityOptions = veracityOptions;

    $scope.users = users.map(function(u) {
      return {
        value: u.username,
        label: u.username
      };
    });

    $rootScope.$watch('currentUser', function(user) {
      if (!user) { return }
      $scope.users.unshift({
        label: 'Assigned to me',
        value: user.username
      });
    });

    $scope.incidentsById = {};
    $scope.visibleIncidents = new Queue(paginationOptions.perPage);
    $scope.newIncidents = new Queue(paginationOptions.perPage);
    $scope.statusOptions = incidentStatusOptions;

    $scope.pagination = {
      page: parseInt($stateParams.page) || 1,
      total: incidents.total,
      visibleTotal: incidents.total,
      perPage: paginationOptions.perPage,
      start: 0,
      end: 0
    };

    var init = function() {
      $scope.incidentsById = $scope.incidents.reduce(groupById, {});

      var visibleIncidents = paginate($scope.incidents);
      $scope.visibleIncidents.addMany(visibleIncidents);

      if ($scope.isFirstPage()) {
        Socket.emit('incidentQuery', searchParams());
        Socket.on('incidents', $scope.handleNewIncidents);
      }
    };

    var removeDuplicates = function(incidents) {
      return incidents.reduce(function(memo, incident) {
        if (!(incident._id in $scope.incidentsById)) {
          memo.push(incident);
        }
        return memo;
      }, []);
    };

    var groupById = function(memo, item) {
      memo[item._id] = item;
      return memo;
    };

    $scope.search = function(params) {
      $scope.$evalAsync(function() {
        $state.go('incidents', searchParams(params), { reload: true });
      });
    };

    var searchParams = function(newParams) {
      var params = $scope.searchParams;
      params.page = 1;
      for (var key in newParams) {
        params[key] = newParams[key];
      }
      return params;
    };

    var paginate = function(items) {
      var page = $scope.pagination.page,
        perPage = $scope.pagination.perPage,
        total = $scope.pagination.total,
        start = (page - 1) * perPage,
        end = (page * perPage) - 1;

      $scope.pagination.start = Math.min(start + 1, total);
      $scope.pagination.end = Math.min(end + 1, total);

      if ($scope.searchParams.title || $scope.searchParams.location) {
        $scope.pagination.visibleTotal = items.length;
        return items.slice(start, end);
      } else {
        return items;
      }
    }

    $scope.handleNewIncidents = function(incidents) {
      var uniqueIncidents = removeDuplicates(incidents);
      $scope.pagination.total += uniqueIncidents.length;
      $scope.pagination.visibleTotal += uniqueIncidents.length;
      $scope.pagination.visibleTotal = Math.min($scope.pagination.visibleTotal, 100)
      $scope.newIncidents.addMany(uniqueIncidents);
    };

    $scope.displayNewIncidents = function() {
      var incidents = $scope.newIncidents.toArray();
      $scope.incidents.concat(incidents);
      incidents.reduce(groupById, $scope.incidents);
      $scope.visibleIncidents.addMany(incidents);
      $scope.newIncidents = new Queue(paginationOptions.perPage);
    };

    $scope.removeSelected = function() {
      var selected = $scope.incidents.filter(function(item) { return item.selected; });
      if (!selected.length) return;
      var ids = selected.map(function(item) { return item._id; });

      Incident.removeSelected({ids: ids}, function () {
        flash.setNotice('Incidents were successfully deleted.');
        $rootScope.$state.go('incidents', {}, { reload: true });
      }, function() {
        flash.setAlertNow('Incident failed to be deleted.');
      });
    };

    $scope.clearSearch = function() {
      $scope.search({ page: null, title: null, locationName: null});
    };

    $scope.noFilters = function () {
      return $scope.searchParams.assignedTo === null &&
        $scope.searchParams.veracity === null;
    };

    $scope.clearFilters = function() {
      $scope.search({
        assignedTo: null,
        veracity: null
      });
    };

    $scope.isFirstPage = function() {
      return $scope.pagination.page == 1;
    };

    $scope.isLastPage = function() {
      return $scope.pagination.end >= $scope.pagination.visibleTotal;
    };

    $scope.nextPage = function() {
      if (!$scope.isLastPage()) {
        $scope.search($scope.currentPage + 1);
      }
    };

    $scope.prevPage = function() {
      if (!$scope.isFirstPage()) {
        search($scope.currentPage - 1);
      };
    };

    $scope.isUnassigned = function(incident) {
      return !this.isRelevant(incident) && !this.isIrrelevant(incident);
    };

    $scope.saveIncident = function(incident) {
      Incident.save({ id: incident._id }, incident, function() {
      }, function() {
        flash.setAlertNow("Sorry, but that incident couldn't be saved for some reason");
      });
    };

    $scope.viewIncident = function(event, incident) {
      if (angular.element(event.target)[0].tagName == 'TD') {
        $state.go('incident', { id: incident._id });
      }
    };

    $scope.delete = function(incident) {
      Incident.delete({id: incident._id}, function(){
        flash.setNotice('Incident was successfully deleted.');
        $rootScope.$state.go('incidents', {}, { reload: true });
      }, function() {
        flash.setAlertNow('Incident failed to be deleted.');
      });
    };

    (fireDigestEveryThirtySeconds = function() {
      $timeout(fireDigestEveryThirtySeconds, 30 * 1000);
    })();

    init();
  }
]);
<commit_msg>more cleanup<commit_after>angular.module('Aggie')

.controller('IncidentsIndexController', [
  '$state',
  '$scope',
  '$rootScope',
  '$timeout',
  '$stateParams',
  'FlashService',
  'incidents',
  'users',
  'incidentStatusOptions',
  'veracityOptions',
  'Incident',
  'Socket',
  'Queue',
  'paginationOptions',
  function($state, $scope, $rootScope, $timeout, $stateParams, flash, incidents, users, incidentStatusOptions, veracityOptions, Incident, Socket, Queue, paginationOptions) {
    $scope.searchParams = $stateParams;
    $scope.incidents = incidents.results;
    $scope.statusOptions = incidentStatusOptions;
    $scope.veracityOptions = veracityOptions;

    $scope.users = users.map(function(u) {
      return {
        value: u.username,
        label: u.username
      };
    });

    $rootScope.$watch('currentUser', function(user) {
      if (!user) { return }
      $scope.users.unshift({
        label: 'Assigned to me',
        value: user.username
      });
    });

    $scope.incidentsById = {};
    $scope.visibleIncidents = new Queue(paginationOptions.perPage);
    $scope.newIncidents = new Queue(paginationOptions.perPage);
    $scope.statusOptions = incidentStatusOptions;

    $scope.pagination = {
      page: parseInt($stateParams.page) || 1,
      total: incidents.total,
      visibleTotal: incidents.total,
      perPage: paginationOptions.perPage,
      start: 0,
      end: 0
    };

    var init = function() {
      $scope.incidentsById = $scope.incidents.reduce(groupById, {});

      var visibleIncidents = paginate($scope.incidents);
      $scope.visibleIncidents.addMany(visibleIncidents);

      if ($scope.isFirstPage()) {
        Socket.emit('incidentQuery', searchParams());
        Socket.on('incidents', $scope.handleNewIncidents);
      }
    };

    var removeDuplicates = function(incidents) {
      return incidents.reduce(function(memo, incident) {
        if (!(incident._id in $scope.incidentsById)) {
          memo.push(incident);
        }
        return memo;
      }, []);
    };

    var groupById = function(memo, item) {
      memo[item._id] = item;
      return memo;
    };

    $scope.search = function(params) {
      $scope.$evalAsync(function() {
        $state.go('incidents', searchParams(params), { reload: true });
      });
    };

    var searchParams = function(newParams) {
      var params = $scope.searchParams;
      params.page = 1;
      for (var key in newParams) {
        params[key] = newParams[key];
      }
      return params;
    };

    var paginate = function(items) {
      var page = $scope.pagination.page,
        perPage = $scope.pagination.perPage,
        total = $scope.pagination.total,
        start = (page - 1) * perPage,
        end = (page * perPage) - 1;

      $scope.pagination.start = Math.min(start + 1, total);
      $scope.pagination.end = Math.min(end + 1, total);

      if ($scope.searchParams.title || $scope.searchParams.location) {
        $scope.pagination.visibleTotal = items.length;
        return items.slice(start, end);
      } else {
        return items;
      }
    }

    var filterSelected = function (items) {
      return items.reduce(function(memo, item) {
        if (item.selected) memo.push(item._id);
        return memo;
      }, []);
    }

    $scope.handleNewIncidents = function(incidents) {
      var uniqueIncidents = removeDuplicates(incidents);
      $scope.pagination.total += uniqueIncidents.length;
      $scope.pagination.visibleTotal += uniqueIncidents.length;
      $scope.pagination.visibleTotal = Math.min($scope.pagination.visibleTotal, 100)
      $scope.newIncidents.addMany(uniqueIncidents);
    };

    $scope.displayNewIncidents = function() {
      var incidents = $scope.newIncidents.toArray();
      $scope.incidents.concat(incidents);
      incidents.reduce(groupById, $scope.incidents);
      $scope.visibleIncidents.addMany(incidents);
      $scope.newIncidents = new Queue(paginationOptions.perPage);
    };

    $scope.removeSelected = function() {
      var ids = filterSelected($scope.incidents);
      if (!ids.length) return;

      Incident.removeSelected({ids: ids}, function() {
        flash.setNotice('Incidents were successfully deleted.');
        $rootScope.$state.go('incidents', {}, { reload: true });
      }, function() {
        flash.setAlertNow('Incidents failed to be deleted.');
      });
    };

    $scope.clearSearch = function() {
      $scope.search({ page: null, title: null, locationName: null});
    };

    $scope.noFilters = function () {
      return $scope.searchParams.assignedTo === null &&
        $scope.searchParams.veracity === null;
    };

    $scope.clearFilters = function() {
      $scope.search({
        assignedTo: null,
        veracity: null
      });
    };

    $scope.isFirstPage = function() {
      return $scope.pagination.page == 1;
    };

    $scope.isLastPage = function() {
      return $scope.pagination.end >= $scope.pagination.visibleTotal;
    };

    $scope.nextPage = function() {
      if (!$scope.isLastPage()) {
        $scope.search($scope.currentPage + 1);
      }
    };

    $scope.prevPage = function() {
      if (!$scope.isFirstPage()) {
        search($scope.currentPage - 1);
      };
    };

    $scope.isUnassigned = function(incident) {
      return !this.isRelevant(incident) && !this.isIrrelevant(incident);
    };

    $scope.saveIncident = function(incident) {
      Incident.save({ id: incident._id }, incident, function() {
      }, function() {
        flash.setAlertNow("Sorry, but that incident couldn't be saved for some reason");
      });
    };

    $scope.viewIncident = function(event, incident) {
      if (angular.element(event.target)[0].tagName == 'TD') {
        $state.go('incident', { id: incident._id });
      }
    };

    $scope.delete = function(incident) {
      Incident.delete({id: incident._id}, function(){
        flash.setNotice('Incident was successfully deleted.');
        $rootScope.$state.go('incidents', {}, { reload: true });
      }, function() {
        flash.setAlertNow('Incident failed to be deleted.');
      });
    };

    (fireDigestEveryThirtySeconds = function() {
      $timeout(fireDigestEveryThirtySeconds, 30 * 1000);
    })();

    init();
  }
]);
<|endoftext|>


<commit_before>config = require('./lib/config')

var express = require('express');
var fs = require('fs');
var http = require('http');
var https = require('https');
var everyauth = require('everyauth');

var app = module.exports = express();

// Everyauth
everyauth.github
  .appId(config.gh_clientId)
  .appSecret(config.gh_secret)
  .findOrCreateUser( function (sess, accessToken, accessTokenExtra, ghUser) {
    console.log('find user')
    // return usersByGhId[ghUser.id] || (usersByGhId[ghUser.id] = addUser('github', ghUser));
})
  .redirectPath('/board');

app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());

  app.use(express.cookieParser());
  app.use(express.session({secret: config.redis_secret}));
  app.use(everyauth.middleware());

  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));

});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

app.get('/', function(req, res) {
  res.render('login');
  res.end();
});

app.get('/board', function(req, res) {
  if (everyauth.loggedIn) {
    res.render('board');
    res.end();
  } else {
    return res.redirect('/');
  }
});

app.listen(process.env.PORT || 4000);
<commit_msg>Go Back.<commit_after>config = require('./lib/config')

var express = require('express');
var fs = require('fs');
var http = require('http');
var https = require('https');
var everyauth = require('everyauth');

var app = module.exports = express();

// Everyauth
everyauth.github
  .appId(config.gh_clientId)
  .appSecret(config.gh_secret)
  .findOrCreateUser( function (sess, accessToken, accessTokenExtra, ghUser) {
    console.log('find user')
    // return usersByGhId[ghUser.id] || (usersByGhId[ghUser.id] = addUser('github', ghUser));
})
  .redirectPath('/board');

app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());

  app.use(express.cookieParser());
  app.use(express.session({secret: config.redis_secret}));
  app.use(everyauth.middleware());

  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));

});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

app.get('/', function(req, res) {
  res.render('login');
});

app.get('/board', function(req, res) {
      res.send(req.user);
    //res.render('board');
});

app.listen(process.env.PORT || 4000);
<|endoftext|>


<commit_before>/**
Copyright (c) 2018 Espruino Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Author: Alfie Kirkpatrick (jugglingcats@akirkpatrick.com)
**/

(function () {
  var PREFIX = "tcp://"; // prefix to use with -p option for hostname/ip address

  if (typeof require === 'undefined') return; // definitely not node!

  var net;
  try {
    net = require("net");
  } catch (e) {
    console.log("Require net failed - Node Socket disabled");
    return;
  }

  var socket;

  var getPorts = function (callback) {
    var uri = Espruino.Config.SERIAL_TCPIP;
    if (uri.trim() != "") {
      var ips = uri.trim().split(";");
      var portList = [];
      ips.forEach(function (s) {
        s = s.trim();
        console.log("ADDING", s);
        if (s.length) portList.push({ path: s, description: "Network connection", type: "socket" });
      })
      callback(portList);
    } else
      callback();
  };

  var openSerial = function (serialPort, openCallback, receiveCallback, disconnectCallback) {
    if (serialPort.substr(0, 6) != 'tcp://') {
      console.error("Invalid connection " + JSON.stringify(serialPort));
      return;
    }
    var host = serialPort.substr(6);
    var port = 23;
    if (host.indexOf(":") >= 0) {
      var i = host.indexOf(":");
      port = parseInt(host.substr(i + 1).trim());
      host = host.substr(0, i).trim();
      if (host == "") host = "localhost";
    }

    socket = net.createConnection(port, host, function (createInfo) {
      openCallback("Ok");
    });
    socket.on("data", function (data) {
      if (receiveCallback !== undefined) {
        var a = new Uint8Array(data.length);
        for (var i = 0; i < data.length; i++)
          a[i] = data[i];
        receiveCallback(a.buffer);
      }
    });
    socket.on("error", function (info) {
      console.error("RECEIVE ERROR:", JSON.stringify(info));
      // node will close the connection
    });
    socket.on("end", function () {
      if (disconnectCallback !== undefined) {
        disconnectCallback();
      }
    });
  };

  var closeSerial = function () {
    if (socket) {
      socket.end();
    }
  };

  var writeSerial = function (data, callback) {
    socket.write(data, undefined, callback);
  };

  Espruino.Core.Serial.devices.push({
    "name": "Node Socket",
    "getPorts": getPorts,
    "open": openSerial,
    "write": writeSerial,
    "close": closeSerial,
  });
})();
<commit_msg>Remove unwanted logging<commit_after>/**
Copyright (c) 2018 Espruino Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Author: Alfie Kirkpatrick (jugglingcats@akirkpatrick.com)
**/

(function () {
  var PREFIX = "tcp://"; // prefix to use with -p option for hostname/ip address

  if (typeof require === 'undefined') return; // definitely not node!

  var net;
  try {
    net = require("net");
  } catch (e) {
    console.log("Require net failed - Node Socket disabled");
    return;
  }

  var socket;

  var getPorts = function (callback) {
    var uri = Espruino.Config.SERIAL_TCPIP;
    if (uri.trim() != "") {
      var ips = uri.trim().split(";");
      var portList = [];
      ips.forEach(function (s) {
        s = s.trim();
        if (s.length) portList.push({ path: s, description: "Network connection", type: "socket" });
      })
      callback(portList);
    } else
      callback();
  };

  var openSerial = function (serialPort, openCallback, receiveCallback, disconnectCallback) {
    if (serialPort.substr(0, 6) != 'tcp://') {
      console.error("Invalid connection " + JSON.stringify(serialPort));
      return;
    }
    var host = serialPort.substr(6);
    var port = 23;
    if (host.indexOf(":") >= 0) {
      var i = host.indexOf(":");
      port = parseInt(host.substr(i + 1).trim());
      host = host.substr(0, i).trim();
      if (host == "") host = "localhost";
    }

    socket = net.createConnection(port, host, function (createInfo) {
      openCallback("Ok");
    });
    socket.on("data", function (data) {
      if (receiveCallback !== undefined) {
        var a = new Uint8Array(data.length);
        for (var i = 0; i < data.length; i++)
          a[i] = data[i];
        receiveCallback(a.buffer);
      }
    });
    socket.on("error", function (info) {
      console.error("RECEIVE ERROR:", JSON.stringify(info));
      // node will close the connection
    });
    socket.on("end", function () {
      if (disconnectCallback !== undefined) {
        disconnectCallback();
      }
    });
  };

  var closeSerial = function () {
    if (socket) {
      socket.end();
    }
  };

  var writeSerial = function (data, callback) {
    socket.write(data, undefined, callback);
  };

  Espruino.Core.Serial.devices.push({
    "name": "Node Socket",
    "getPorts": getPorts,
    "open": openSerial,
    "write": writeSerial,
    "close": closeSerial,
  });
})();
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import './FilterSidebar.less';
import fuzzysearch from 'fuzzysearch';
import FilterSidebarComponentItem from '../FilterSidebarComponentItem';

export default
class FilterSidebar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      filterInputValue: ''
    };
    this.handleClickOutside = this.handleClickOutside.bind(this);
  }

  componentDidMount() {
    document.body.addEventListener('click', this.handleClickOutside);
    this.refs.searchInput.focus();
  }

  componentWillUnmount() {
    document.body.removeEventListener('click', this.handleClickOutside);
  }

  filterComponentsLists(componentsInfo, filterText) {
    return componentsInfo.filter(component => {
      return fuzzysearch(filterText.toLowerCase(), component.name.toLowerCase())
    })
  }

  handleFilterInputChange(e) {
    this.setState({ filterInputValue: e.target.value })
  }

  collapseBy(list, by) {
    return list.reduce((results, current) => {
      return results.some(result => result[by] === current[by]) ? results : results.concat([current]);
    }, []);
  }

  handleClickOutside(event) {
    if (!this.props.hideOnOutsideClick) {
      return false;
    }
    event.preventDefault();
    let hasParent = (node, parent) => {
      if (node.parentNode) {
        return node.parentNode === parent || hasParent(node.parentNode, parent);
      }
      return false;
    };
    if (event.target !== this._container && !hasParent(event.target, this._container)) {
      this.props.onHide();
    }
    return false;
  }

  render() {
    let preparedComponentsList = this.filterComponentsLists(this.props.componentsInfo, this.state.filterInputValue);
    preparedComponentsList = this.collapseBy(preparedComponentsList, 'name');
    preparedComponentsList = preparedComponentsList.sort(
      (component1, component2) => component1.name > component2.name ? 1 : -1
    );
    return (

 { this._container = container }}
        className="filter-sidebar"
      >

          <input
            className="filter-sidebar__filter-input form-control"
            type="text"
            ref="searchInput"
            placeholder="Component name"
            onChange={(e) => this.handleFilterInputChange(e)}
          />

            {preparedComponentsList.map((component, index) => (
              <FilterSidebarComponentItem
                key={index}
                currentComponent={this.props.currentComponent}
                component={component}
                componentsInfo={this.props.componentsInfo}
                onComponentChange={this.props.onComponentChange}
              />
            ))}

    )
  }
}

FilterSidebar.propTypes = {
  currentComponent: PropTypes.object,
  componentsInfo: PropTypes.arrayOf(PropTypes.object).isRequired,
  onComponentChange: PropTypes.func,
  onHide: PropTypes.func,
  hideOnOutsideClick: PropTypes.bool
};
FilterSidebar.defaultProps = {
  currentComponent: {},
  componentsInfo: [],
  hideOnOutsideClick: false
};
<commit_msg>Fix - can't mouse click on mobile view<commit_after>import React, { Component, PropTypes } from 'react';
import './FilterSidebar.less';
import fuzzysearch from 'fuzzysearch';
import FilterSidebarComponentItem from '../FilterSidebarComponentItem';

export default
class FilterSidebar extends Component {
  constructor(props) {
    super(props);
    this.state = {
      filterInputValue: ''
    };
    this.handleClickOutside = this.handleClickOutside.bind(this);
  }

  componentDidMount() {
    document.body.addEventListener('click', this.handleClickOutside);
    this.refs.searchInput.focus();
  }

  componentWillUnmount() {
    document.body.removeEventListener('click', this.handleClickOutside);
  }

  filterComponentsLists(componentsInfo, filterText) {
    return componentsInfo.filter(component => {
      return fuzzysearch(filterText.toLowerCase(), component.name.toLowerCase());
    });
  }

  handleFilterInputChange(e) {
    this.setState({ filterInputValue: e.target.value });
  }

  collapseBy(list, by) {
    return list.reduce((results, current) => {
      return results.some(result => result[by] === current[by]) ? results : results.concat([current]);
    }, []);
  }

  handleClickOutside(event) {
    if (!this.props.hideOnOutsideClick) {
      return false;
    }
    let hasParent = (node, parent) => {
      if (node.parentNode) {
        return node.parentNode === parent || hasParent(node.parentNode, parent);
      }
      return false;
    };
    if (event.target !== this._container && !hasParent(event.target, this._container)) {
      this.props.onHide();
    }
    return false;
  }

  render() {
    let preparedComponentsList = this.filterComponentsLists(this.props.componentsInfo, this.state.filterInputValue);
    preparedComponentsList = this.collapseBy(preparedComponentsList, 'name');
    preparedComponentsList = preparedComponentsList.sort(
      (component1, component2) => component1.name > component2.name ? 1 : -1
    );
    return (

 { this._container = container }}
        className="filter-sidebar"
      >

          <input
            className="filter-sidebar__filter-input form-control"
            type="text"
            ref="searchInput"
            placeholder="Component name"
            onChange={(e) => this.handleFilterInputChange(e)}
          />

            {preparedComponentsList.map((component, index) => (
              <FilterSidebarComponentItem
                key={index}
                currentComponent={this.props.currentComponent}
                component={component}
                componentsInfo={this.props.componentsInfo}
                onComponentChange={this.props.onComponentChange}
              />
            ))}

    )
  }
}

FilterSidebar.propTypes = {
  currentComponent: PropTypes.object,
  componentsInfo: PropTypes.arrayOf(PropTypes.object).isRequired,
  onComponentChange: PropTypes.func,
  onHide: PropTypes.func,
  hideOnOutsideClick: PropTypes.bool
};
FilterSidebar.defaultProps = {
  currentComponent: {},
  componentsInfo: [],
  hideOnOutsideClick: false
};
<|endoftext|>


<commit_before>export class CalendarController {

    constructor(
        bcCalendarConfig
    ) {
        'ngInject';

        this.bcCalendarConfig = bcCalendarConfig;

        console.log('config: ', bcCalendarConfig);

        this._activate();

    }

    _activate() {
        this.startDate = this.startDate || this.bcCalendarConfig.startDate;

        console.log('startDate: ', this.startDate);

    }

}

<commit_msg>isBeforeToday now working, added in service<commit_after>export class CalendarController {

    constructor(
        bcCalendarConfig, bcCalendarService
    ) {
        'ngInject';

        this.bcCalendarConfig = bcCalendarConfig;
        this.bcCalendarService = bcCalendarService;

        console.log('config: ', bcCalendarConfig);

        this._activate();

    }

    _activate() {
        // Define the starting day of the calendar
        this.startDate = this.startDate || this.bcCalendarConfig.startDate;

        console.log('startDate: ', this.startDate);

    }

    /**
     * Check to see if the day is prior to the current date
     * This is used to disable the unselectable days
     * TODO: Can I really not just compare dates?
     *
     * @param {Date} day
     * @return {Bool} isBefore
     */
    isBeforeToday(date) {
        const dateDayOfMonth = moment(date).date();
        const doMonthsMatch = this.bcCalendarService.doMonthsMatch(this.startDate, date);
        const todayOfMonth = moment(this.startDate).date();

        // If both days are in the same month and the passed day comes earlier than today
        return (doMonthsMatch && (dateDayOfMonth < todayOfMonth));
    }

    isSelectedDay() {
    }

    isToday() {
    }

    selectDate() {
    }

}

<|endoftext|>


<commit_before>app.directive('pdfViewer',
    function ($compile, $timeout, $rootScope, $location, $routeParams) {
        return {
            restrict: 'E',

            terminal: true,

            scope: {
                source: '@',
                currentPageNumber: '=',
                showControl: '=',
                pdfId: '@'
            },

            templateUrl: '/angular/views/pdf-viewer.html',

            link: function (scope, element, attrs) {
                if (!PDFJS.PDFViewer || !PDFJS.getDocument) {
                    alert('Please build the library and components using\n' +
                        '  `node make generic components`');
                }

                scope.pageToView = 1;
                scope.scale = 1.0;
                scope.totalPage = 1;

                scope.container = element[0].getElementsByClassName('viewerContainer');
                scope.container = scope.container[0];

                scope.calculateSlideNavigationProgress = function (newSlideNumber) {
                    if (scope.totalPage > 0) {
                        var progressBar = element[0].getElementsByClassName('slideNavigationCurrentProgress');
                        progressBar[0].style.width = ((newSlideNumber / scope.totalPage) * 100) + "%";
                    }
                };

                attrs.$observe('pdfId', function (pdfId) {
                    $rootScope.pdfId = pdfId;
                });

                attrs.$observe('source', function (pdfFilePath) {
                    //console.log(pdfFilePath);
                    if (pdfFilePath) {
                        PDFJS.getDocument(pdfFilePath).then(function (pdfDocument) {

                            if (attrs.currentPageNumber) {
                                scope.pageToView = parseInt(attrs.currentPageNumber);
                            }

                            //console.log("Started loading pdf");
                            scope.totalPage = pdfDocument.numPages;

                            // Initialize CountPrint
                            // TODO - Load real annotations data
                            var data = [];
                            for (var i = 0; i < scope.totalPage; i++) {
                                data.push(Math.floor(Math.random() * (10 + 1)));
                            }

                            var countPrint = new CountPrint(data, {
                                container: 'countprint',
                                tooltip: 'countprint-tooltip',
                                maxValue: 10,
                                colorful: true
                            });

                            countPrint.onCountSelected = function (selectedPage) {
                                $rootScope.setPageNumber(selectedPage);
                            };

                            scope.calculateSlideNavigationProgress(scope.currentPageNumber);

                            // this will apply totalpage to the html
                            $timeout(function () {
                                scope.$apply();
                            });

                            // Document loaded, retrieving the page.
                            return pdfDocument.getPage(scope.pageToView).then(function (pdfPage) {
                                // Creating the page view with default parameters.
                                scope.pdfPageView = new PDFJS.PDFPageView({
                                    container: scope.container,
                                    id: scope.pageToView,
                                    scale: scope.scale,
                                    defaultViewport: pdfPage.getViewport(scope.scale),

                                    // We can enable text/annotations layers, if needed
                                    textLayerFactory: new PDFJS.DefaultTextLayerFactory(),
                                    annotationsLayerFactory: new PDFJS.DefaultAnnotationsLayerFactory()
                                });

                                // Associates the actual page with the view, and drawing it
                                scope.pdfPageView.setPdfPage(pdfPage);
                                scope.scale = scope.scale * scope.container.clientWidth / scope.pdfPageView.width;

                                scope.pdfPageView.update(scope.scale, 0);

                                scope.pdfIsLoaded = true;

                                $rootScope.$broadcast('onPdfPageChange', [scope.currentPageNumber, scope.totalPage]);

                                return scope.pdfPageView.draw();
                            });
                        });
                    }
                });

            }, /*end link*/

            controller: function ($scope, $rootScope, $compile, $http, $attrs, $location, $routeParams) {
                $scope.currentPageNumber = 1;
                $scope.pdfIsLoaded = false;
                $scope.totalPage = 0;
                $scope.currentTab = "";
                $scope.currentNavPageNumber = $scope.currentPageNumber;
                $rootScope.switchShowAnnoZones = "On";

                $scope.$watch("currentPageNumber", function (newVal, oldVal) {
                    if (newVal != oldVal) {
                        $scope.currentNavPageNumber = newVal;

                        $timeout(function () {
                            $scope.$apply();
                        });
                    }
                });

                $scope.$watch("currentNavPageNumber", function (newVal, oldVal) {
                    if (newVal != oldVal) {
                        if (newVal.length == 0) {
                            return;
                        } else if (isNaN(newVal)) {
                            $scope.currentNavPageNumber = oldVal;

                        } else if (!(parseInt(newVal) >= 1 && parseInt(newVal) <= $scope.totalPage)) {
                            $scope.currentNavPageNumber = oldVal;
                        }
                    }
                });

                $("#inpFieldCurrPage").bind("keydown keypress", function (event) {
                    if (event.which === 13) {
                        $timeout(function () {
                            $rootScope.setPageNumber(parseInt($scope.currentNavPageNumber));
                            $scope.$apply();
                        });

                        event.preventDefault();
                    }

                });

                $scope.changePageNumber = function (value) {
                    $rootScope.setPageNumber($scope.currentPageNumber + value);
                };

                $rootScope.setPageNumber = function (value) {
                    if ((value) <= $scope.totalPage && (value) >= 1) {
                        $scope.currentPageNumber = parseInt(value);

                        $scope.setHistoryStack($scope.currentPageNumber);

                        $timeout(function () {
                            $scope.changeSlide($scope.currentPageNumber);
                            $scope.$apply();
                        });
                    }
                };

                $scope.changeSlide = function (newSlideNumber) {
                    $rootScope.clearTagNameErrors();
                    $scope.pdfIsLoaded = false;

                    $scope.pageToView = newSlideNumber;

                    $scope.calculateSlideNavigationProgress(newSlideNumber);

                    PDFJS.getDocument($scope.source).then(function (pdfDocument) {
                        pdfDocument.getPage($scope.pageToView).then(function (pdfPage) {
                            $scope.pdfPageView.setPdfPage(pdfPage);
                            $scope.pdfPageView.draw().catch(function () {
                            });

                            //console.log("Slide Changed");
                            $scope.pdfIsLoaded = true;

                            $rootScope.$broadcast('onPdfPageChange', [newSlideNumber, $scope.totalPage]);

                            /* todo: move this somewhere else
                             drawAnnZonesWhenPDFAndDBDone();
                             */
                        });
                    });
                };

                $scope.setHistoryStack = function (pageNumber) {
                    $location.search('slidePage', pageNumber);
                };

                $scope.changePageNumberBasedOnUrl = function () {
                    var q = $location.search();

                    if (q.slidePage) {
                        var pageNumFromUrl = parseInt(q.slidePage);

                        if ($scope.currentPageNumber != pageNumFromUrl && pageNumFromUrl > 0 && pageNumFromUrl <= $scope.totalPage) {
                            // we are back from somewhere we read it from the url.
                            $scope.currentPageNumber = pageNumFromUrl;
                            $scope.changeSlide($scope.currentPageNumber);
                        }
                    }
                };

                $scope.switchShowAnnotationZone = function () {
                    if ($rootScope.switchShowAnnoZones == "On") {
                        $rootScope.switchShowAnnoZones = "Off";
                    } else {
                        $rootScope.switchShowAnnoZones = "On";
                    }

                };

                function adjustPdfScale() {
                    //console.log("Adjusting PDF Scale");
                    if (typeof $scope.pdfPageView != 'undefined') {
                        if ($scope.scale == 0)
                            $scope.scale = 1.0;

                        $scope.scale = $scope.scale * $scope.container.clientWidth / $scope.pdfPageView.width;
                        $scope.pdfPageView.update($scope.scale, 0);
                        $scope.pdfPageView.draw().catch(function () {
                        });

                        $rootScope.currCanWidth = $('#annotationZone').width();

                        $rootScope.currCanHeight = $('#annotationZone').height();

                        $rootScope.$broadcast("pdfScaleChanged", [$rootScope.currCanWidth, $rootScope.currCanHeight]);

                    }
                };

                $(window).resize(function (event) {
                    //console.log("Registered resize. Got tab: " + $scope.currentTab +", callerId: "+event.target);
                    //console.log($location.search().tab)
                    if (($location.search().tab == "pdf" || $location.search().tab == undefined || $location.search().tab == "no") && $.isWindow(event.target)) {
                        //console.log("Got called on resize");
                        adjustPdfScale();
                    }
                });

                $scope.$on('onAfterInitTreeNode', function (node) {
                    //console.log("Got called");
                    //if($scope.pdfReady) {
                    //console.log(node);
                    $rootScope.pdfId = node.targetScope.pdfFile._id;
                    //}
                });

                $scope.$on('onNodeTabChange', function (event, tab) {
                    //console.log("Registered tab change. Got tab: " + tab);
                    $scope.currentTab = tab;
                    if (tab == "pdf") {
                        adjustPdfScale();
                    }
                });

                $scope.$on('onPdfPageChange', function (event, params) {
                    setCurrentCanvasHeight(parseInt($('#annotationZone').height()));

                    $rootScope.currCanWidth = $('#annotationZone').width();

                    $rootScope.currCanHeight = $('#annotationZone').height();

                    $rootScope.$broadcast("pdfScaleChanged", [$rootScope.currCanWidth, $rootScope.currCanHeight]);
                });

                // onload
                $scope.$watch('totalPage', function (newVal, oldVal) {
                    if (oldVal !== newVal) {
                        $scope.changePageNumberBasedOnUrl();
                    }
                });

                $scope.$on('$routeUpdate', function (next, current) {
                    if (!$location.search().slidePage) {
                        if (current.params.tab && current.params.tab == 'pdf')
                            $scope.setHistoryStack($scope.currentPageNumber);
                    } else {
                        var sp = parseInt($location.search().slidePage);
                        if (sp > 0 && sp != $scope.currentPageNumber && sp <= $scope.totalPage) {
                            $scope.changePageNumberBasedOnUrl();
                        }
                    }
                });
            }
        };
    });
<commit_msg>updated countprint<commit_after>app.directive('pdfViewer',
    function ($compile, $timeout, $rootScope, $location, $routeParams) {
        return {
            restrict: 'E',

            terminal: true,

            scope: {
                source: '@',
                currentPageNumber: '=',
                showControl: '=',
                pdfId: '@'
            },

            templateUrl: '/angular/views/pdf-viewer.html',

            link: function (scope, element, attrs) {
                if (!PDFJS.PDFViewer || !PDFJS.getDocument) {
                    alert('Please build the library and components using\n' +
                        '  `node make generic components`');
                }

                scope.pageToView = 1;
                scope.scale = 1.0;
                scope.totalPage = 1;

                scope.container = element[0].getElementsByClassName('viewerContainer');
                scope.container = scope.container[0];

                scope.calculateSlideNavigationProgress = function (newSlideNumber) {
                    if (scope.totalPage > 0) {
                        var progressBar = element[0].getElementsByClassName('slideNavigationCurrentProgress');
                        progressBar[0].style.width = ((newSlideNumber / scope.totalPage) * 100) + "%";
                    }
                };

                attrs.$observe('pdfId', function (pdfId) {
                    $rootScope.pdfId = pdfId;
                });

                attrs.$observe('source', function (pdfFilePath) {
                    //console.log(pdfFilePath);
                    if (pdfFilePath) {
                        PDFJS.getDocument(pdfFilePath).then(function (pdfDocument) {

                            if (attrs.currentPageNumber) {
                                scope.pageToView = parseInt(attrs.currentPageNumber);
                            }

                            //console.log("Started loading pdf");
                            scope.totalPage = pdfDocument.numPages;

                            // Initialize CountPrint
                            // TODO - Load real annotations data
                            var annotations = [
                                {page: 1},
                                {page: 1},
                                {page: 1},
                                {page: 2},
                                {page: 2},
                                {page: 2},
                                {page: 2},
                                {page: 2},
                                {page: 3},
                                {page: 2},
                                {page: 11},
                                {page: 7},
                                {page: 3},
                                {page: 20},
                                {page: 20},
                                {page: 20},
                                {page: 20},
                                {page: 20},
                                {page: 20},
                                {page: 20},
                                {page: 20},
                                {page: 20},
                                {page: 20}
                            ];

                            var countPrint = new CountPrint({
                                segments: annotations,
                                segmentKey: 'page',
                                totalSegments: 30,
                                container: 'countprint',
                                tooltip: 'countprint-tooltip',
                                maxValue: 10,
                                colorful: true
                            });

                            countPrint.onCountSelected = function (selectedPage) {
                                $rootScope.setPageNumber(selectedPage);
                            };

                            scope.calculateSlideNavigationProgress(scope.currentPageNumber);

                            // this will apply totalpage to the html
                            $timeout(function () {
                                scope.$apply();
                            });

                            // Document loaded, retrieving the page.
                            return pdfDocument.getPage(scope.pageToView).then(function (pdfPage) {
                                // Creating the page view with default parameters.
                                scope.pdfPageView = new PDFJS.PDFPageView({
                                    container: scope.container,
                                    id: scope.pageToView,
                                    scale: scope.scale,
                                    defaultViewport: pdfPage.getViewport(scope.scale),

                                    // We can enable text/annotations layers, if needed
                                    textLayerFactory: new PDFJS.DefaultTextLayerFactory(),
                                    annotationsLayerFactory: new PDFJS.DefaultAnnotationsLayerFactory()
                                });

                                // Associates the actual page with the view, and drawing it
                                scope.pdfPageView.setPdfPage(pdfPage);
                                scope.scale = scope.scale * scope.container.clientWidth / scope.pdfPageView.width;

                                scope.pdfPageView.update(scope.scale, 0);

                                scope.pdfIsLoaded = true;

                                $rootScope.$broadcast('onPdfPageChange', [scope.currentPageNumber, scope.totalPage]);

                                return scope.pdfPageView.draw();
                            });
                        });
                    }
                });

            }, /*end link*/

            controller: function ($scope, $rootScope, $compile, $http, $attrs, $location, $routeParams) {
                $scope.currentPageNumber = 1;
                $scope.pdfIsLoaded = false;
                $scope.totalPage = 0;
                $scope.currentTab = "";
                $scope.currentNavPageNumber = $scope.currentPageNumber;
                $rootScope.switchShowAnnoZones = "On";

                $scope.$watch("currentPageNumber", function (newVal, oldVal) {
                    if (newVal != oldVal) {
                        $scope.currentNavPageNumber = newVal;

                        $timeout(function () {
                            $scope.$apply();
                        });
                    }
                });

                $scope.$watch("currentNavPageNumber", function (newVal, oldVal) {
                    if (newVal != oldVal) {
                        if (newVal.length == 0) {
                            return;
                        } else if (isNaN(newVal)) {
                            $scope.currentNavPageNumber = oldVal;

                        } else if (!(parseInt(newVal) >= 1 && parseInt(newVal) <= $scope.totalPage)) {
                            $scope.currentNavPageNumber = oldVal;
                        }
                    }
                });

                $("#inpFieldCurrPage").bind("keydown keypress", function (event) {
                    if (event.which === 13) {
                        $timeout(function () {
                            $rootScope.setPageNumber(parseInt($scope.currentNavPageNumber));
                            $scope.$apply();
                        });

                        event.preventDefault();
                    }

                });

                $scope.changePageNumber = function (value) {
                    $rootScope.setPageNumber($scope.currentPageNumber + value);
                };

                $rootScope.setPageNumber = function (value) {
                    if ((value) <= $scope.totalPage && (value) >= 1) {
                        $scope.currentPageNumber = parseInt(value);

                        $scope.setHistoryStack($scope.currentPageNumber);

                        $timeout(function () {
                            $scope.changeSlide($scope.currentPageNumber);
                            $scope.$apply();
                        });
                    }
                };

                $scope.changeSlide = function (newSlideNumber) {
                    $rootScope.clearTagNameErrors();
                    $scope.pdfIsLoaded = false;

                    $scope.pageToView = newSlideNumber;

                    $scope.calculateSlideNavigationProgress(newSlideNumber);

                    PDFJS.getDocument($scope.source).then(function (pdfDocument) {
                        pdfDocument.getPage($scope.pageToView).then(function (pdfPage) {
                            $scope.pdfPageView.setPdfPage(pdfPage);
                            $scope.pdfPageView.draw().catch(function () {
                            });

                            //console.log("Slide Changed");
                            $scope.pdfIsLoaded = true;

                            $rootScope.$broadcast('onPdfPageChange', [newSlideNumber, $scope.totalPage]);

                            /* todo: move this somewhere else
                             drawAnnZonesWhenPDFAndDBDone();
                             */
                        });
                    });
                };

                $scope.setHistoryStack = function (pageNumber) {
                    $location.search('slidePage', pageNumber);
                };

                $scope.changePageNumberBasedOnUrl = function () {
                    var q = $location.search();

                    if (q.slidePage) {
                        var pageNumFromUrl = parseInt(q.slidePage);

                        if ($scope.currentPageNumber != pageNumFromUrl && pageNumFromUrl > 0 && pageNumFromUrl <= $scope.totalPage) {
                            // we are back from somewhere we read it from the url.
                            $scope.currentPageNumber = pageNumFromUrl;
                            $scope.changeSlide($scope.currentPageNumber);
                        }
                    }
                };

                $scope.switchShowAnnotationZone = function () {
                    if ($rootScope.switchShowAnnoZones == "On") {
                        $rootScope.switchShowAnnoZones = "Off";
                    } else {
                        $rootScope.switchShowAnnoZones = "On";
                    }

                };

                function adjustPdfScale() {
                    //console.log("Adjusting PDF Scale");
                    if (typeof $scope.pdfPageView != 'undefined') {
                        if ($scope.scale == 0)
                            $scope.scale = 1.0;

                        $scope.scale = $scope.scale * $scope.container.clientWidth / $scope.pdfPageView.width;
                        $scope.pdfPageView.update($scope.scale, 0);
                        $scope.pdfPageView.draw().catch(function () {
                        });

                        $rootScope.currCanWidth = $('#annotationZone').width();

                        $rootScope.currCanHeight = $('#annotationZone').height();

                        $rootScope.$broadcast("pdfScaleChanged", [$rootScope.currCanWidth, $rootScope.currCanHeight]);

                    }
                };

                $(window).resize(function (event) {
                    //console.log("Registered resize. Got tab: " + $scope.currentTab +", callerId: "+event.target);
                    //console.log($location.search().tab)
                    if (($location.search().tab == "pdf" || $location.search().tab == undefined || $location.search().tab == "no") && $.isWindow(event.target)) {
                        //console.log("Got called on resize");
                        adjustPdfScale();
                    }
                });

                $scope.$on('onAfterInitTreeNode', function (node) {
                    //console.log("Got called");
                    //if($scope.pdfReady) {
                    //console.log(node);
                    $rootScope.pdfId = node.targetScope.pdfFile._id;
                    //}
                });

                $scope.$on('onNodeTabChange', function (event, tab) {
                    //console.log("Registered tab change. Got tab: " + tab);
                    $scope.currentTab = tab;
                    if (tab == "pdf") {
                        adjustPdfScale();
                    }
                });

                $scope.$on('onPdfPageChange', function (event, params) {
                    setCurrentCanvasHeight(parseInt($('#annotationZone').height()));

                    $rootScope.currCanWidth = $('#annotationZone').width();

                    $rootScope.currCanHeight = $('#annotationZone').height();

                    $rootScope.$broadcast("pdfScaleChanged", [$rootScope.currCanWidth, $rootScope.currCanHeight]);
                });

                // onload
                $scope.$watch('totalPage', function (newVal, oldVal) {
                    if (oldVal !== newVal) {
                        $scope.changePageNumberBasedOnUrl();
                    }
                });

                $scope.$on('$routeUpdate', function (next, current) {
                    if (!$location.search().slidePage) {
                        if (current.params.tab && current.params.tab == 'pdf')
                            $scope.setHistoryStack($scope.currentPageNumber);
                    } else {
                        var sp = parseInt($location.search().slidePage);
                        if (sp > 0 && sp != $scope.currentPageNumber && sp <= $scope.totalPage) {
                            $scope.changePageNumberBasedOnUrl();
                        }
                    }
                });
            }
        };
    });
<|endoftext|>


<commit_before>import _   from 'lodash';
import Joi from 'joi';

function mapType(key, attribute) {
    switch (key) {
        // NUMBER TYPES
        case 'BIGINT':
        case 'INTEGER':
            return Joi.number().integer();

        case 'DECIMAL':
        case 'DOUBLE':
        case 'FLOAT':
            return Joi.number();

        // STRING TYPES
        case 'STRING':
        case 'TEXT':
            return Joi.string();
       case 'UUID':
            return Joi.string().guid();

        case 'ENUM':
            return Joi.string().allow(attribute.values);

        case 'DATEONLY':
        case 'DATE':
            return Joi.date();

        // OTHER TYPES
        case 'BLOB':
            return Joi.any();
        case 'BOOLEAN':
            return Joi.boolean();
        case 'ARRAY':
            return Joi.array().sparse();
        case 'JSON':
        case 'JSONB':
            return Joi.object();

        default:
            return Joi.any();
    }
}

function mapValidator(joi, validator, key) {
    if (validator === false) { return joi; }

    switch (key) {
        case 'is':
            return joi.regex(validator);
        case 'isEmail':
            return joi.email();
        case 'isUrl':
            return joi.uri();
        case 'isIP':
            return joi.ip();
        case 'isIPv4':
            return joi.ip({ version: ['ipv4'] });
        case 'isIPv6':
            return joi = joi.ip({ version: ['ipv6'] });
        case 'min':
            return joi.min(validator);
        case 'max':
            return joi.max(validator);
        case 'notEmpty':
            return joi.min(1);
        default:
            return joi;
    }
}

export default function (attribute) {
    let joi = mapType(_.get(attribute, 'type.key', ''), attribute);

    // Add model comments to schema description
    if (attribute.comment) {
        joi = joi.description(attribute.comment);
    }

    if (attribute.allowNull === false) {
        joi = joi.required();
    } else {
        joi = joi.allow(null);
    }

    if (attribute.defaultValue && !_.isObject(attribute.defaultValue) && !_.isFunction(attribute.defaultValue)) {
        joi = joi.default(attribute.defaultValue);
    }

    _.each(attribute.validate, (validator, key) => {
        joi = mapValidator(joi, validator, key);
    });

    return joi;
}
<commit_msg>:lipstick: style(map): linting<commit_after>import _   from 'lodash';
import Joi from 'joi';

function mapType(key, attribute) {
    switch (key) {
        // NUMBER TYPES
        case 'BIGINT':
        case 'INTEGER':
            return Joi.number().integer();

        case 'DECIMAL':
        case 'DOUBLE':
        case 'FLOAT':
            return Joi.number();

        // STRING TYPES
        case 'STRING':
        case 'TEXT':
            return Joi.string();
        case 'UUID':
            return Joi.string().guid();
        case 'ENUM':
            return Joi.string().allow(attribute.values);

        case 'DATEONLY':
        case 'DATE':
            return Joi.date();

        // OTHER TYPES
        case 'BLOB':
            return Joi.any();
        case 'BOOLEAN':
            return Joi.boolean();
        case 'ARRAY':
            return Joi.array().sparse();
        case 'JSON':
        case 'JSONB':
            return Joi.object();

        default:
            return Joi.any();
    }
}

function mapValidator(joi, validator, key) {
    if (validator === false) { return joi; }

    switch (key) {
        case 'is':
            return joi.regex(validator);
        case 'isEmail':
            return joi.email();
        case 'isUrl':
            return joi.uri();
        case 'isIP':
            return joi.ip();
        case 'isIPv4':
            return joi.ip({ version: ['ipv4'] });
        case 'isIPv6':
            return joi = joi.ip({ version: ['ipv6'] });
        case 'min':
            return joi.min(validator);
        case 'max':
            return joi.max(validator);
        case 'notEmpty':
            return joi.min(1);
        default:
            return joi;
    }
}

export default function (attribute) {
    let joi = mapType(_.get(attribute, 'type.key', ''), attribute);

    // Add model comments to schema description
    if (attribute.comment) {
        joi = joi.description(attribute.comment);
    }

    if (attribute.allowNull === false) {
        joi = joi.required();
    } else {
        joi = joi.allow(null);
    }

    if (attribute.defaultValue && !_.isObject(attribute.defaultValue) && !_.isFunction(attribute.defaultValue)) {
        joi = joi.default(attribute.defaultValue);
    }

    _.each(attribute.validate, (validator, key) => {
        joi = mapValidator(joi, validator, key);
    });

    return joi;
}
<|endoftext|>