<commit_before>angular.module('Recipeoples.auth', [])

.controller('AuthController', function ($scope, $rootScope, $location, $window, AuthFactory) {
  // Hacky way to logout. Whenever you navigate to the signin page,
  // the currentUser and your cookie are deleted.
  $rootScope.currentUser = null;
  $window.localStorage.removeItem('com.recipeople');

  // Passes in the user to be authenticated, either as new or returning.
  $scope.submit = function() {
    AuthFactory.authenticate($scope.user, $scope.signup)
    .then(function (data) {
      $window.localStorage.setItem('com.recipeople', data.token);
      $rootScope.currentUser = data.user;
      console.log('Set user', $rootScope.currentUser.username);
      $location.path('/');
    })
    .catch(function (error) {
      console.error(error);
    });
  };

})

.factory('AuthFactory', function ($http, $location, $window) {

  //Sends an authentication query either as a new user, or returning.
  var authenticate = function(user, isNew) {
    var path = isNew ? 'signup' : 'signin';

    return $http({
      method: 'POST',
      url: '/api/users/' + path,
      data: user
    })
    .then(function(resp) {
      return resp.data;
    });
  };

  // TODO: Delete once server-side authentication ready.
  // var authenticate = function(user, isNew) {
  //   console.log('Creating dummy token for user', user.username);
  //   return $http({
  //     method: 'GET',
  //     url: '/',
  //     data: {}
  //   })
  //   .then(function(resp) {
  //     console.log('returning dummy token and user');
  //     return {
  //       token: 'iamatoken',
  //       user: {
  //         username: user.username,
  //         image_url: 'https://pbs.twimg.com/profile_images/1044973752/390dfbe9-eccf-41f9-822e-17c8d4c251b4.jpg',
  //         liked: [],
  //         disliked: [],
  //         groups: [],
  //         authored: [],
  //         testid: 1,
  //         friends: []
  //       }
  //     };
  //   });
  // };

  // Checks whether or not a user has an authorization cookie.
  var isAuth = function() {
    return !!$window.localStorage.getItem('com.recipeople');
  };

  // Removes the authorization cookie.
  var signout = function() {
    $window.localStorage.removeItem('com.recipeople');
    $location.path('/signin');
  };

  return {
    authenticate: authenticate,
    isAuth: isAuth,
    signout: signout
  };

});<commit_msg>(fix) Removed setting rootscope on signin, will be handled in profile<commit_after>angular.module('Recipeoples.auth', [])

.controller('AuthController', function ($scope, $rootScope, $location, $window, AuthFactory) {
  // Hacky way to logout. Whenever you navigate to the signin page,
  // the currentUser and your cookie are deleted.
  $rootScope.currentUser = null;
  $window.localStorage.removeItem('com.recipeople');

  // Passes in the user to be authenticated, either as new or returning.
  $scope.submit = function() {
    AuthFactory.authenticate($scope.user, $scope.signup)
    .then(function (data) {
      $window.localStorage.setItem('com.recipeople', data.token);
      // $rootScope.currentUser = data.user;
      // console.log('Set user', $rootScope.currentUser.username);
      $location.path('/');
    })
    .catch(function (error) {
      console.error(error);
    });
  };

})

.factory('AuthFactory', function ($http, $location, $window) {

  //Sends an authentication query either as a new user, or returning.
  var authenticate = function(user, isNew) {
    var path = isNew ? 'signup' : 'signin';

    return $http({
      method: 'POST',
      url: '/api/users/' + path,
      data: user
    })
    .then(function(resp) {
      return resp.data;
    });
  };

  // TODO: Delete once server-side authentication ready.
  // var authenticate = function(user, isNew) {
  //   console.log('Creating dummy token for user', user.username);
  //   return $http({
  //     method: 'GET',
  //     url: '/',
  //     data: {}
  //   })
  //   .then(function(resp) {
  //     console.log('returning dummy token and user');
  //     return {
  //       token: 'iamatoken',
  //       user: {
  //         username: user.username,
  //         image_url: 'https://pbs.twimg.com/profile_images/1044973752/390dfbe9-eccf-41f9-822e-17c8d4c251b4.jpg',
  //         liked: [],
  //         disliked: [],
  //         groups: [],
  //         authored: [],
  //         testid: 1,
  //         friends: []
  //       }
  //     };
  //   });
  // };

  // Checks whether or not a user has an authorization cookie.
  var isAuth = function() {
    return !!$window.localStorage.getItem('com.recipeople');
  };

  // Removes the authorization cookie.
  var signout = function() {
    $window.localStorage.removeItem('com.recipeople');
    $location.path('/signin');
  };

  return {
    authenticate: authenticate,
    isAuth: isAuth,
    signout: signout
  };

});<|endoftext|>


<commit_before>import DS from "ember-data";
import Ember from "ember";

export default DS.Model.extend( {
	node_parent: DS.hasMany("task", { async: true, inverse:null}),

	prerequisities: DS.attr("prerequisite"),
	category: DS.belongsTo("category", { async: true }),

	active: DS.attr("boolean"),

	title: DS.attr("string"),
	body: DS.attr("string"),
	intro: DS.attr("string"),
	max_score: DS.attr("number"),
	solution: DS.attr("string"),
	author: DS.belongsTo("organisator", { async: true }),
	thread: DS.belongsTo("thread",  { async: true }),
	modules: DS.hasMany("module",  { async: true }),
	time_deadline: DS.attr("date"),
	time_published: DS.attr("date"),

	picture_locked: DS.attr("string"),
	picture_active: DS.attr("string"),
	picture_submitted: DS.attr("string"),
	picture_finished: DS.attr("string"),

	picture: Ember.computed("picture_locked", "picture_active", "picture_submitted",
	 "picture_finished", "active", "submissions", "my_score", function() {
	 	if(!this.get("active")) {
	 		return this.get("picture_locked");
	 	}
	 	if(Ember.isEmpty(this.get("submissions"))) {
	 		return this.get("picture_active");
	 	}
	 	if(!this.get("my_score")) {
	 		return this.get("picture_submitted");
	 	}
		return this.get("picture_finished");
	}),

	best_scores: DS.hasMany("score", { async: true}),
	my_score: DS.belongsTo("score", {async: true, inverse:null}),
	submissions: DS.hasMany("submission", { async: true, inverse:null})
});
<commit_msg>Change the way how task picture is chosen<commit_after>import DS from "ember-data";
import Ember from "ember";

export default DS.Model.extend( {
	node_parent: DS.hasMany("task", { async: true, inverse:null}),

	prerequisities: DS.attr("prerequisite"),
	category: DS.belongsTo("category", { async: true }),

	active: DS.attr("boolean"),

	title: DS.attr("string"),
	body: DS.attr("string"),
	intro: DS.attr("string"),
	max_score: DS.attr("number"),
	solution: DS.attr("string"),
	author: DS.belongsTo("organisator", { async: true }),
	thread: DS.belongsTo("thread",  { async: true }),
	modules: DS.hasMany("module",  { async: true }),
	time_deadline: DS.attr("date"),
	time_published: DS.attr("date"),

	/*picture_locked: DS.attr("string"),
	picture_active: DS.attr("string"),
	picture_submitted: DS.attr("string"),
	picture_finished: DS.attr("string"),*/

	picture_base: DS.attr("string"),
	picture_suffix: DS.attr("string"),

	/*picture: Ember.computed("picture_locked", "picture_active", "picture_submitted",
	 "picture_finished", "active", "submissions", "my_score", function() {
	 	if(!this.get("active")) {
	 		return this.get("picture_locked");
	 	}
	 	if(Ember.isEmpty(this.get("submissions"))) {
	 		return this.get("picture_active");
	 	}
	 	if(!this.get("my_score")) {
	 		return this.get("picture_submitted");
	 	}
		return this.get("picture_finished");
	}),*/

	picture: Ember.computed("picture_base", "picture_suffix", "active",
	 "submissions", "my_score", function() {
	 	if(!this.get("active")) {
	 		return this.get("picture_base") + "locked" + this.get("picture_suffix");
	 	}
	 	if(Ember.isEmpty(this.get("submissions"))) {
	 		return this.get("picture_base") + "active" + this.get("picture_suffix");
	 	}
	 	if(!this.get("my_score")) {
	 		return this.get("picture_base") + "submitted" + this.get("picture_suffix");
	 	}
		return this.get("picture_base") + "finished" + this.get("picture_suffix");
	}),

	best_scores: DS.hasMany("score", { async: true}),
	my_score: DS.belongsTo("score", {async: true, inverse:null}),
	submissions: DS.hasMany("submission", { async: true, inverse:null})
});
<|endoftext|>


<commit_before>'use strict';

module.exports = {
	client: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.min.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
			],
			js: [
				'public/lib/angular/angular.min.js',
				'public/lib/angular-resource/angular-resource.min.js',
				'public/lib/angular-animate/angular-animate.min.js',
				'public/lib/angular-ui-router/release/angular-ui-router.min.js',
				'public/lib/angular-ui-utils/ui-utils.min.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
				'public/lib/angular-file-upload/angular-file-upload.min.js',
				'public/lib/javascript-state-machine/state-machine.min.js',
				//'public/lib/sprintf/src/angular-sprintf.js', //TODO: should I use angular service or raw sprintf?
				'public/lib/sprintf/src/sprintf.js',
				'public/lib/lodash.min.js'
			]
		},
		css: 'public/dist/application.min.css',
		js: 'public/dist/application.min.js'
	}
};
<commit_msg>config/assets: corrected path to lodash.min.js for production<commit_after>'use strict';

module.exports = {
	client: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.min.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
			],
			js: [
				'public/lib/angular/angular.min.js',
				'public/lib/angular-resource/angular-resource.min.js',
				'public/lib/angular-animate/angular-animate.min.js',
				'public/lib/angular-ui-router/release/angular-ui-router.min.js',
				'public/lib/angular-ui-utils/ui-utils.min.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
				'public/lib/angular-file-upload/angular-file-upload.min.js',
				'public/lib/javascript-state-machine/state-machine.min.js',
				//'public/lib/sprintf/src/angular-sprintf.js', //TODO: should I use angular service or raw sprintf?
				'public/lib/sprintf/src/sprintf.js',
				'public/lib/lodash/lodash.min.js'
			]
		},
		css: 'public/dist/application.min.css',
		js: 'public/dist/application.min.js'
	}
};
<|endoftext|>


<commit_before>var _ = require('underscore');
var CronJob = require('cron').CronJob;

module.exports = function(robot) {
  var REMARKS = [
    "DID SOMEBODY SAY PLANVIEW? BECAUSE I LOVE PLANVIEW!",
    "I'VE GOT A FEVER, AND THE ONLY PERSCRIPTION IS MORE PLANVIEW!",
    "YO, HO, HO! I'M A PLANVIEW PRO!",
    "WHEN I GROW UP I WANT TO BE A GLOBAL LEADER IN PORTFOLIO MANAGEMENT AND PROJECT COLLABORATION, JUST LIKE PLANVIEW!"
  ];

  var IMAGES = [
    'http://media.vandahm.com/work/planview/drudge-alert.gif',
    'http://media.vandahm.com/work/planview/dick-jones.jpg'
  ]

  function randomRemark() {
    return _.sample(REMARKS);
  }

  function beHonest() {
    return 'Ok, ok, Planview is a steaming pile of portfolio management and project collaboration.'
  }

  function randomImage() {
    return _.sample(IMAGES);
  }

  function roomsToAlert() {
    return (process.env.HUBOT_PLANVIEW_ROOMS || "").split(",")
  }

  function planviewAlert() {
    _.each(roomsToAlert(), function(room) {
      var message = "@all PLANVIEW ALERT! " + randomImage();
      robot.messageRoom(room, message);
    });
  }

  robot.hear(/planview/i, function(msg) {
    msg.reply(randomRemark());
  });

  robot.hear(/tell us how you really feel/, function(msg) {
    msg.reply(beHonest());
  });

  var job = new CronJob('0 14 * * 5', planviewAlert, null, true, 'America/Chicago');
};
<commit_msg>Add missing semicolon on beHonest method return<commit_after>var _ = require('underscore');
var CronJob = require('cron').CronJob;

module.exports = function(robot) {
  var REMARKS = [
    "DID SOMEBODY SAY PLANVIEW? BECAUSE I LOVE PLANVIEW!",
    "I'VE GOT A FEVER, AND THE ONLY PERSCRIPTION IS MORE PLANVIEW!",
    "YO, HO, HO! I'M A PLANVIEW PRO!",
    "WHEN I GROW UP I WANT TO BE A GLOBAL LEADER IN PORTFOLIO MANAGEMENT AND PROJECT COLLABORATION, JUST LIKE PLANVIEW!"
  ];

  var IMAGES = [
    'http://media.vandahm.com/work/planview/drudge-alert.gif',
    'http://media.vandahm.com/work/planview/dick-jones.jpg'
  ]

  function randomRemark() {
    return _.sample(REMARKS);
  }

  function beHonest() {
    return 'Ok, ok, Planview is a steaming pile of portfolio management and project collaboration.';
  }

  function randomImage() {
    return _.sample(IMAGES);
  }

  function roomsToAlert() {
    return (process.env.HUBOT_PLANVIEW_ROOMS || "").split(",")
  }

  function planviewAlert() {
    _.each(roomsToAlert(), function(room) {
      var message = "@all PLANVIEW ALERT! " + randomImage();
      robot.messageRoom(room, message);
    });
  }

  robot.hear(/planview/i, function(msg) {
    msg.reply(randomRemark());
  });

  robot.hear(/tell us how you really feel/, function(msg) {
    msg.reply(beHonest());
  });

  var job = new CronJob('0 14 * * 5', planviewAlert, null, true, 'America/Chicago');
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2009 Henrik Joreteg
 * License: BSD style, http://projects.joreteg.com/licenses/BSD.html
 *
 * Parts copyright (c) 2012 Kaj Magnus Lindberg
 * License: BSD style.
 */
(function($) {
    jQuery.showMessage = function(message, options){
        // defaults
        settings = jQuery.extend({
             id: 'sliding_message_box',
             position: 'bottom',
             lineHeight: '160%',
             color: 'white',
             backgroundColor: 'rgb(143, 177, 240)',
             delay: 5000,
             speed: 500,
             fontSize: '24px'
        }, options);

        var elem = $('#' + settings.id);
        var delayed;

        // generate message div if it doesn't exist
        if(elem.length == 0){
            elem = $('

').attr('id', settings.id);

            elem.css({'z-index': '999',
                      'color': settings.color,
                      'background-color': settings.backgroundColor,
                      'text-align': 'center',
                      'position': 'absolute',
                      'position': 'fixed',
                      'left': '0',
                      'width': '100%',
                      'line-height': settings.lineHeight,
                      'font-size': settings.fontSize
                      });

            $('body').append(elem);
        }

        elem.html(message);

        // Animate in.
        if(settings.position == 'bottom'){
            elem.css('bottom', '-' + elem.height() + 'px');
            elem.animate({bottom:'0'}, settings.speed);
        }
        else if(settings.position == 'top'){
            elem.css('top', '-' + elem.height() + 'px');
            elem.animate({top:'0'}, settings.speed);
        }

        // Animate out.
        var animOutSettings = {};
        animOutSettings[settings.position] = -elem.height();
        var animOut = function() {
            elem.animate(animOutSettings, settings.speed);
        };
        setTimeout(animOut, settings.delay);
    }
})(jQuery);

<commit_msg>Upgrade slidingmessage plugin: don't restart animation too early.<commit_after>/**
 * Copyright (c) 2009 Henrik Joreteg
 * License: BSD style, http://projects.joreteg.com/licenses/BSD.html
 *
 * Parts copyright (c) 2012 Kaj Magnus Lindberg
 * License: BSD style.
 */
(function($) {
    jQuery.showMessage = function(message, options){

        settings = jQuery.extend({
             id: 'sliding_message_box',
             position: 'bottom',
             lineHeight: '160%',
             color: 'white',
             backgroundColor: 'rgb(143, 177, 240)',
             delay: 5000,
             speed: 500,
             fontSize: '24px'
        }, options);

        var elem = $('#' + settings.id);
        var delayed;

        // Don't restart slide in animation, if message already visible.
        if (elem.is(':visible'))
          return;

        // generate message div if it doesn't exist
        if(elem.length == 0){
            elem = $('

').attr('id', settings.id);

            elem.css({'z-index': '999',
                      'color': settings.color,
                      'background-color': settings.backgroundColor,
                      'text-align': 'center',
                      'position': 'absolute',
                      'position': 'fixed',
                      'left': '0',
                      'width': '100%',
                      'line-height': settings.lineHeight,
                      'font-size': settings.fontSize
                      });

            $('body').append(elem);
        }

        elem.html(message);
        elem.show();

        // Animate in.
        if(settings.position == 'bottom'){
            elem.css('bottom', '-' + elem.height() + 'px');
            elem.animate({bottom:'0'}, settings.speed);
        }
        else if(settings.position == 'top'){
            elem.css('top', '-' + elem.height() + 'px');
            elem.animate({top:'0'}, settings.speed);
        }

        // Animate out.
        var animOutSettings = {};
        animOutSettings[settings.position] = -elem.height();
        var animOut = function() {
            elem.animate(animOutSettings, settings.speed);
            elem.hide();
        };
        setTimeout(animOut, settings.delay);
    }
})(jQuery);

<|endoftext|>


<commit_before>;(sharp = function() {

  // NOTE: This functions are implemented with NO ORDER

  this.microtime = function(getFloat) {
    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10);
    return (getFloat) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
  }

  this.today = function(glue) {
      glue = glue || "-"
      var date = new Date()
      return (date.getDate() < 10 ? '0' : '') + date.getDate() + glue + (date.getMonth() < 10 ? '0' : '') + (date.getMonth() + 1) + glue + date.getFullYear()
  }

  this.random = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min)
  }

  this.trim = function(str) {
    return str.replace(/^\s+|\s+$/g, '')
  }

  this.inArray = function(needle, haystack) {
    return haystack.indexOf(needle) !== -1 ? true : false
  }

  this.isBoolean = function(_var) {
    return (_var === true || _var === false)
  }

  this.isString = function(_var) {
    return (typeof _var === 'string')
  }

  this.isObject = function(_var) {
    if (Object.prototype.toString.call(_var) === '[object Array]') return false
    return (_var !== null && typeof _var === 'object')
  }

  this.isNull = function(_var) {
    return (_var === null)
  }

  this.escape = function(_var) {
    return (_var + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0')
  }

  this.stripTags = function(_var, _allowed) {
    _allowed = (((_allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('')
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi
    var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi
    return _var.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) {
        return _allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''
    })
  }

  this.capitalize = function(_str) {
    return _str.replace(/(^|\s)([a-z])/g, function(m, p1, p2) {
        return p1 + p2.toUpperCase();
    });
  }

  this.inArray = function(_array, _item) {
    var i = _array.length
    while (i--) {
        if (_array[i] === _item) return true
    }
    return false
  }

  this.dump = function(_arr, _level) {
    var dumped_text = ""
    if (!_level) _level = 0
    var level_padding = ""
    for (var j = 0; j < _level + 1; j++) level_padding += "    "
      if (typeof(_arr) == 'object') {
        for (var item in _arr) {
          var value = _arr[item]
          if (typeof(value) == 'object') {
            dumped_text += level_padding + "'" + item + "' ...\n"
            dumped_text += dump(value, _level + 1)
          } else {
            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n"
          }
        }
      } else {
          dumped_text = "===>" + _arr + "<===(" + typeof(_arr) + ")"
      }
      return dumped_text
  }

  this.functionExists = function(_functionName) {
    return (typeof window[_functionName] === 'function'))
  }

  this.merge = function(_obj1, _obj2){
    var res = {};
    for (var attrname in _obj1) {
      if(this.isObject(_obj1[attrname])){
        res[attrname] = this.merge(_obj1[attrname], _obj2[attrname])
      }else{
        res[attrname] = _obj1[attrname];
      }
    }
    for (var attrname in _obj2) {
      if(this.isObject(_obj2[attrname])){
        res[attrname] = merge(_obj1[attrname], _obj2[attrname])
      }else{
        res[attrname] = _obj2[attrname];
      }
    }
    return res;
  }

  this.escapeHTML = function(_text) {
    var replacements = {"<": "<", ">": ">","&": "&", """: """};
    return _text.replace(/[<>&"]/g, function(character) {
      return replacements[character];
    });
  }

}());
<commit_msg>Update sharp.js<commit_after>;(sharp = function() {

  // NOTE: This functions are implemented with NO ORDER

  this.microtime = function(getFloat) {
    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10);
    return (getFloat) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
  } // End this.microtime

  this.today = function(glue) {
      glue = glue || "-"
      var date = new Date()
      return (date.getDate() < 10 ? '0' : '') + date.getDate() + glue + (date.getMonth() < 10 ? '0' : '') + (date.getMonth() + 1) + glue + date.getFullYear()
  } // End this.today

  this.random = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min)
  } // End this.random

  this.trim = function(str) {
    return str.replace(/^\s+|\s+$/g, '')
  } // End this.trim

  this.inArray = function(needle, haystack) {
    return haystack.indexOf(needle) !== -1 ? true : false
  } // End this.inArray

  this.isBoolean = function(_var) {
    return (_var === true || _var === false)
  } // End this.isBoolean

  this.isString = function(_var) {
    return (typeof _var === 'string')
  } // End this.isString

  this.isObject = function(_var) {
    if (Object.prototype.toString.call(_var) === '[object Array]') return false
    return (_var !== null && typeof _var === 'object')
  } // End this.isObject

  this.isNull = function(_var) {
    return (_var === null)
  } // End this.isNull

  this.escape = function(_var) {
    return (_var + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0')
  } // End this.escape

  this.stripTags = function(_var, _allowed) {
    _allowed = (((_allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('')
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi
    var commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi
    return _var.replace(commentsAndPhpTags, '').replace(tags, function($0, $1) {
        return _allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : ''
    })
  } // End this.stripTags

  this.capitalize = function(_str) {
    return _str.replace(/(^|\s)([a-z])/g, function(m, p1, p2) {
        return p1 + p2.toUpperCase();
    });
  } // End this.capitalize

  this.inArray = function(_array, _item) {
    var i = _array.length
    while (i--) {
        if (_array[i] === _item) return true
    }
    return false
  } // End this.inArray

  this.dump = function(_arr, _level) {
    var dumped_text = ""
    if (!_level) _level = 0
    var level_padding = ""
    for (var j = 0; j < _level + 1; j++) level_padding += "    "
      if (typeof(_arr) == 'object') {
        for (var item in _arr) {
          var value = _arr[item]
          if (typeof(value) == 'object') {
            dumped_text += level_padding + "'" + item + "' ...\n"
            dumped_text += dump(value, _level + 1)
          } else {
            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n"
          }
        }
      } else {
          dumped_text = "===>" + _arr + "<===(" + typeof(_arr) + ")"
      }
      return dumped_text
  } // End this.dump

  this.functionExists = function(_functionName) {
    return (typeof window[_functionName] === 'function'))
  } // End this.functionExists

  this.merge = function(_obj1, _obj2){
    var res = {};
    for (var attrname in _obj1) {
      if(this.isObject(_obj1[attrname])){
        res[attrname] = this.merge(_obj1[attrname], _obj2[attrname])
      }else{
        res[attrname] = _obj1[attrname];
      }
    }
    for (var attrname in _obj2) {
      if(this.isObject(_obj2[attrname])){
        res[attrname] = merge(_obj1[attrname], _obj2[attrname])
      }else{
        res[attrname] = _obj2[attrname];
      }
    }
    return res;
  } // End this.merge

  this.escapeHTML = function(_text) {
    var replacements = {"<": "<", ">": ">","&": "&", """: """};
    return _text.replace(/[<>&"]/g, function(character) {
      return replacements[character];
    });
  } // End this.escapeHTML

  this.fade = function(selector, duration, type){
    duration = parseInt(duration, 10) || 1000
    var interval = duration / 100
    type = type || 'out';
    var e = null;
    var selector_type = selector.substr(0, 1);
    selector = selector.substr(1, selector.length);

    var apply_fade = function(element){
        var style = element.style;
        switch(type){
            case 'in':
                fade_in(style);
                break;
            case 'out':
                fade_out(style);
                break;
        }
    }

    var fade_out = function(style){
        var op = 1;
        style.opacity = op;
        var timer = setInterval(function () {
        if (op <= 0.1){
            clearInterval(timer);
                style.display = 'none';
            }
            style.opacity = op;
            style.filter = 'alpha(opacity=' + op * 100 + ")";
            op -= op * 0.1;
        }, interval);
    }

    var fade_in = function(style){
        var op = 0.1;
        style.display = 'block';
        style.opacity = op;
        var timer = setInterval(function () {
            if (op >= 1){ clearInterval(timer); }
            style.opacity = op;
            style.filter = 'alpha(opacity=' + op * 100 + ")";
            op += op * 0.1;
        }, interval);
    }

    switch(selector_type){
        case '.':
            // Applies to all elements with the class
            var elements = document.getElementsByClassName(selector)
            for(var i = 0; i < elements.length; i++){
                apply_fade(elements[i])
            }
            break;
        case '#':
            // Applies to the first element found
            e = document.getElementById(selector);
            var style = e.style;
            apply_fade(e);
            break;
    }
  } // End this.fade

}());
<|endoftext|>


<commit_before>var _ = require('underscore');
var deepInsightsIntegrationSpecHelpers = require('./deep-insights-integration-spec-helpers');
var MapIntegration = require('../../../../javascripts/cartodb3/deep-insights-integration/map-integration');

describe('deep-insights-integrations/map-integration', function () {
  var mapElement;

  beforeAll(function () {
    spyOn(_, 'debounce').and.callFake(function (func) {
      return function () {
        func.apply(this, arguments);
      };
    });
  });

  beforeEach(function (done) {
    jasmine.Ajax.install();

    // Mock Map instantiation response
    jasmine.Ajax.stubRequest(new RegExp(/api\/v1\/map/)).andReturn({
      status: 200,
      contentType: 'application/json; charset=utf-8',
      responseText: '{ "layergroupid": "123456789", "metadata": { "layers": [] } }'
    });

    var onDashboardCreated = function (dashboard) {
      var fakeObjects = deepInsightsIntegrationSpecHelpers.createFakeObjects(dashboard);
      _.extend(this, fakeObjects);

      spyOn(this.diDashboardHelpers.getDashboard(), 'onStateChanged').and.callThrough();
      spyOn(this.stateDefinitionModel, 'updateState');

      // Track map integration
      this.integration = MapIntegration.track({
        diDashboardHelpers: this.diDashboardHelpers,
        editorModel: this.editorModel,
        mapDefinitionModel: this.mapDefinitionModel,
        stateDefinitionModel: this.stateDefinitionModel,
        visDefinitionModel: this.visDefinitionModel
      });

      done();
    }.bind(this);

    mapElement = deepInsightsIntegrationSpecHelpers.createFakeDOMElement();

    deepInsightsIntegrationSpecHelpers.createFakeDashboard(mapElement, onDashboardCreated);
  });

  afterEach(function () {
    this.integration._mapDefinitionModel.off();
    this.integration._map.off();
    this.integration._vis.off();
    this.integration = null;
    document.body.removeChild(mapElement);
    jasmine.Ajax.uninstall();
  });

  it('mapViewSizeChanged', function () {
    var map = this.diDashboardHelpers.visMap();
    spyOn(map, 'getMapViewSize').and.returnValue({
      x: 120,
      y: 133
    });

    spyOn(this.mapDefinitionModel, 'setMapViewSize').and.callThrough();

    map.trigger('mapViewSizeChanged');
    expect(this.mapDefinitionModel.setMapViewSize).toHaveBeenCalled();
    expect(this.mapDefinitionModel.getMapViewSize()).toEqual({
      x: 120,
      y: 133
    });
  });

  describe('when vis reloads', function () {
    it('should increment changes', function () {
      this.diDashboardHelpers.getMap().trigger('reload');
      expect(this.visDefinitionModel.get('visChanges')).toBe(1);
    });
  });

  describe('visMetadata', function () {
    beforeEach(function () {
      spyOn(this.mapDefinitionModel, 'setImageExportMetadata');
      spyOn(this.mapDefinitionModel, 'setStaticImageURLTemplate');
    });

    it('should update vis metadata when state changes', function () {
      this.diDashboardHelpers.getDashboard()._dashboard.vis.trigger('dataviewsFetched');
      this.diDashboardHelpers.visMap().set('center', [10, 20]);
      expect(this.mapDefinitionModel.setImageExportMetadata).toHaveBeenCalled();
      expect(this.mapDefinitionModel.setStaticImageURLTemplate).toHaveBeenCalled();
    });

    it('update vis metadata when vis reload', function () {
      this.diDashboardHelpers.getMap().trigger('reload');
      expect(this.mapDefinitionModel.setImageExportMetadata).toHaveBeenCalled();
      expect(this.mapDefinitionModel.setStaticImageURLTemplate).toHaveBeenCalled();
    });
  });

  describe('max/min zoom changes', function () {
    beforeEach(function () {
      this.diDashboardHelpers.visMap().set({
        minZoom: 1,
        maxZoom: 20,
        zoom: 12
      });
      this.mapDefinitionModel.set({
        minZoom: 0,
        maxZoom: 15
      });
      // Avoid HTTP requests setting img src to nothing
      this.diDashboardHelpers.getDashboard()._dashboard.dashboardView.$('img').attr('src', '');
    });

    it('should change max and min zoom of the map if changes in map-definition-model', function () {
      expect(this.diDashboardHelpers.visMap().get('minZoom')).toBe(0);
      expect(this.diDashboardHelpers.visMap().get('maxZoom')).toBe(15);
    });

    it('should change map zoom if maxZoom is not as high as the current one', function () {
      expect(this.diDashboardHelpers.visMap().get('zoom')).toBe(12);
      this.mapDefinitionModel.set({
        minZoom: 0,
        maxZoom: 9
      });
      // Avoid HTTP requests setting img src to nothing
      this.diDashboardHelpers.getDashboard()._dashboard.dashboardView.$('img').attr('src', '');
      expect(this.diDashboardHelpers.visMap().get('zoom')).toBe(9);
    });
  });

  describe('legends option', function () {
    it('when activating legends', function () {
      var vis = this.diDashboardHelpers.getMap();

      this.mapDefinitionModel.set({legends: true});
      expect(vis.settings.get('showLegends')).toBe(true);
      this.mapDefinitionModel.set({legends: false});
      expect(vis.settings.get('showLegends')).toBe(false);
    });
  });

  describe('scrollwheel option', function () {
    it('when activating scrollwheel', function () {
      var map = this.diDashboardHelpers.visMap();
      spyOn(map, 'enableScrollWheel');
      spyOn(map, 'disableScrollWheel');

      this.mapDefinitionModel.set({scrollwheel: !this.mapDefinitionModel.get('scrollwheel')});
      this.mapDefinitionModel.set({scrollwheel: !this.mapDefinitionModel.get('scrollwheel')});

      expect(map.enableScrollWheel).toHaveBeenCalled();
      expect(map.disableScrollWheel).toHaveBeenCalled();
    });
  });

  describe('stateDefinitionModel', function () {
    beforeEach(function () {
      // All "widgets dataviews" fetched, ready to listen state changes
      this.diDashboardHelpers.getDashboard()._dashboard.vis.trigger('dataviewsFetched');
    });

    it('should be bind to state changes', function () {
      expect(this.diDashboardHelpers.getDashboard().onStateChanged).toHaveBeenCalled();
    });

    it('should change state model when there is any state map change from DI', function () {
      expect(this.diDashboardHelpers.getDashboard().onStateChanged).toHaveBeenCalled();
      this.diDashboardHelpers.visMap().set('center', [10, 20]);
      expect(this.stateDefinitionModel.updateState).toHaveBeenCalled();
    });

    it('should change state model when there is any state widget change from DI', function () {
      expect(this.diDashboardHelpers.getDashboard().onStateChanged).toHaveBeenCalled();
      // Simulate a widget change
      this.diDashboardHelpers.getDashboard()._dashboard.widgets._widgetsCollection.trigger('change');
      expect(this.stateDefinitionModel.updateState).toHaveBeenCalled();
    });

    it('should set bounds in CARTO.js map when state triggers a "boundsSet" event', function () {
      var bounds = [ 808 ];
      spyOn(this.diDashboardHelpers, 'setBounds');
      this.stateDefinitionModel.setBounds(bounds);
      expect(this.diDashboardHelpers.setBounds).toHaveBeenCalledWith(bounds);
    });
  });

  describe('edition option', function () {
    it('when changing edition', function () {
      spyOn(this.diDashboardHelpers, 'forceResize');
      var checked = this.editorModel.get('edition');
      this.editorModel.set({ edition: !checked });
      expect(this.diDashboardHelpers.forceResize).toHaveBeenCalled();
    });
  });
});
<commit_msg>Add test for vis error:limit<commit_after>var _ = require('underscore');
var deepInsightsIntegrationSpecHelpers = require('./deep-insights-integration-spec-helpers');
var MapIntegration = require('../../../../javascripts/cartodb3/deep-insights-integration/map-integration');
var AppNotifications = require('../../../../javascripts/cartodb3/app-notifications');

describe('deep-insights-integrations/map-integration', function () {
  var mapElement;

  beforeAll(function () {
    spyOn(_, 'debounce').and.callFake(function (func) {
      return function () {
        func.apply(this, arguments);
      };
    });
  });

  beforeEach(function (done) {
    jasmine.Ajax.install();
    AppNotifications.init();

    // Mock Map instantiation response
    jasmine.Ajax.stubRequest(new RegExp(/api\/v1\/map/)).andReturn({
      status: 200,
      contentType: 'application/json; charset=utf-8',
      responseText: '{ "layergroupid": "123456789", "metadata": { "layers": [] } }'
    });

    var onDashboardCreated = function (dashboard) {
      var fakeObjects = deepInsightsIntegrationSpecHelpers.createFakeObjects(dashboard);
      _.extend(this, fakeObjects);

      spyOn(this.diDashboardHelpers.getDashboard(), 'onStateChanged').and.callThrough();
      spyOn(this.stateDefinitionModel, 'updateState');

      // Track map integration
      this.integration = MapIntegration.track({
        diDashboardHelpers: this.diDashboardHelpers,
        editorModel: this.editorModel,
        mapDefinitionModel: this.mapDefinitionModel,
        stateDefinitionModel: this.stateDefinitionModel,
        visDefinitionModel: this.visDefinitionModel
      });

      done();
    }.bind(this);

    mapElement = deepInsightsIntegrationSpecHelpers.createFakeDOMElement();

    deepInsightsIntegrationSpecHelpers.createFakeDashboard(mapElement, onDashboardCreated);
  });

  afterEach(function () {
    this.integration._mapDefinitionModel.off();
    this.integration._map.off();
    this.integration._vis.off();
    this.integration = null;
    document.body.removeChild(mapElement);
    jasmine.Ajax.uninstall();
    AppNotifications.off();
  });

  it('mapViewSizeChanged', function () {
    var map = this.diDashboardHelpers.visMap();
    spyOn(map, 'getMapViewSize').and.returnValue({
      x: 120,
      y: 133
    });

    spyOn(this.mapDefinitionModel, 'setMapViewSize').and.callThrough();

    map.trigger('mapViewSizeChanged');
    expect(this.mapDefinitionModel.setMapViewSize).toHaveBeenCalled();
    expect(this.mapDefinitionModel.getMapViewSize()).toEqual({
      x: 120,
      y: 133
    });
  });

  describe('when vis reloads', function () {
    it('should increment changes', function () {
      this.diDashboardHelpers.getMap().trigger('reload');
      expect(this.visDefinitionModel.get('visChanges')).toBe(1);
    });
  });

  describe('visMetadata', function () {
    beforeEach(function () {
      spyOn(this.mapDefinitionModel, 'setImageExportMetadata');
      spyOn(this.mapDefinitionModel, 'setStaticImageURLTemplate');
    });

    it('should update vis metadata when state changes', function () {
      this.diDashboardHelpers.getDashboard()._dashboard.vis.trigger('dataviewsFetched');
      this.diDashboardHelpers.visMap().set('center', [10, 20]);
      expect(this.mapDefinitionModel.setImageExportMetadata).toHaveBeenCalled();
      expect(this.mapDefinitionModel.setStaticImageURLTemplate).toHaveBeenCalled();
    });

    it('update vis metadata when vis reload', function () {
      this.diDashboardHelpers.getMap().trigger('reload');
      expect(this.mapDefinitionModel.setImageExportMetadata).toHaveBeenCalled();
      expect(this.mapDefinitionModel.setStaticImageURLTemplate).toHaveBeenCalled();
    });
  });

  describe('max/min zoom changes', function () {
    beforeEach(function () {
      this.diDashboardHelpers.visMap().set({
        minZoom: 1,
        maxZoom: 20,
        zoom: 12
      });
      this.mapDefinitionModel.set({
        minZoom: 0,
        maxZoom: 15
      });
      // Avoid HTTP requests setting img src to nothing
      this.diDashboardHelpers.getDashboard()._dashboard.dashboardView.$('img').attr('src', '');
    });

    it('should change max and min zoom of the map if changes in map-definition-model', function () {
      expect(this.diDashboardHelpers.visMap().get('minZoom')).toBe(0);
      expect(this.diDashboardHelpers.visMap().get('maxZoom')).toBe(15);
    });

    it('should change map zoom if maxZoom is not as high as the current one', function () {
      expect(this.diDashboardHelpers.visMap().get('zoom')).toBe(12);
      this.mapDefinitionModel.set({
        minZoom: 0,
        maxZoom: 9
      });
      // Avoid HTTP requests setting img src to nothing
      this.diDashboardHelpers.getDashboard()._dashboard.dashboardView.$('img').attr('src', '');
      expect(this.diDashboardHelpers.visMap().get('zoom')).toBe(9);
    });
  });

  describe('legends option', function () {
    it('when activating legends', function () {
      var vis = this.diDashboardHelpers.getMap();

      this.mapDefinitionModel.set({legends: true});
      expect(vis.settings.get('showLegends')).toBe(true);
      this.mapDefinitionModel.set({legends: false});
      expect(vis.settings.get('showLegends')).toBe(false);
    });
  });

  describe('scrollwheel option', function () {
    it('when activating scrollwheel', function () {
      var map = this.diDashboardHelpers.visMap();
      spyOn(map, 'enableScrollWheel');
      spyOn(map, 'disableScrollWheel');

      this.mapDefinitionModel.set({scrollwheel: !this.mapDefinitionModel.get('scrollwheel')});
      this.mapDefinitionModel.set({scrollwheel: !this.mapDefinitionModel.get('scrollwheel')});

      expect(map.enableScrollWheel).toHaveBeenCalled();
      expect(map.disableScrollWheel).toHaveBeenCalled();
    });
  });

  describe('stateDefinitionModel', function () {
    beforeEach(function () {
      // All "widgets dataviews" fetched, ready to listen state changes
      this.diDashboardHelpers.getDashboard()._dashboard.vis.trigger('dataviewsFetched');
    });

    it('should be bind to state changes', function () {
      expect(this.diDashboardHelpers.getDashboard().onStateChanged).toHaveBeenCalled();
    });

    it('should change state model when there is any state map change from DI', function () {
      expect(this.diDashboardHelpers.getDashboard().onStateChanged).toHaveBeenCalled();
      this.diDashboardHelpers.visMap().set('center', [10, 20]);
      expect(this.stateDefinitionModel.updateState).toHaveBeenCalled();
    });

    it('should change state model when there is any state widget change from DI', function () {
      expect(this.diDashboardHelpers.getDashboard().onStateChanged).toHaveBeenCalled();
      // Simulate a widget change
      this.diDashboardHelpers.getDashboard()._dashboard.widgets._widgetsCollection.trigger('change');
      expect(this.stateDefinitionModel.updateState).toHaveBeenCalled();
    });

    it('should set bounds in CARTO.js map when state triggers a "boundsSet" event', function () {
      var bounds = [ 808 ];
      spyOn(this.diDashboardHelpers, 'setBounds');
      this.stateDefinitionModel.setBounds(bounds);
      expect(this.diDashboardHelpers.setBounds).toHaveBeenCalledWith(bounds);
    });
  });

  describe('edition option', function () {
    it('when changing edition', function () {
      spyOn(this.diDashboardHelpers, 'forceResize');
      var checked = this.editorModel.get('edition');
      this.editorModel.set({ edition: !checked });
      expect(this.diDashboardHelpers.forceResize).toHaveBeenCalled();
    });
  });

  describe('when vis error:limit', function () {
    it('should add the error to AppNotifications', function () {
      spyOn(AppNotifications, 'addNotification');
      var error = { type: 'test', message: 'some message' };
      this.diDashboardHelpers.visMap().trigger('error:limit', error);

      expect(AppNotifications.addNotification).toHaveBeenCalledWith(error);
    });
  });
});
<|endoftext|>


<commit_before>import angular from "angular";
import { attach, delay } from "../../utils.js";
import { DomCache } from "../../cstm-ng-utils.js";
import Immutable from "immutable";

const serviceDependencies = ["$scope", "$element"];
function genComponentConf() {
  let template = `

Person Detail Picker

              {{detail.fieldname}}

          <input
            type="text"
            id="{{detail.name}}"
            class="pp__detail__input"
            ng-model="detail.value"
            ng-keyup="::self.updateDetails(detail)"
            ng-class="{'pp__detail__input--withreset' : self.showResetButton(detail.name)}"
          />
          <svg class="pp__detail__icon clickable"
            style="--local-primary:var(--won-primary-color);"
            ng-if="self.showResetButton(detail.name)"
            ng-click="self.resetPersonDetail(detail.name)">
              <use xlink:href="#ico36_close" href="#ico36_close"></use>
          </svg>

    `;

  // DONE rewrite this from tag picker to person picker
  // DONE -> Map decide on some sort of data structure
  // DONE add to create-isseeks
  // TODO: styling
  // DONE add details to draft
  // DONE add details to RDF
  // TODO: display details in info

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      this.domCache = new DomCache(this.$element);

      window.pp4dbg = this;

      // TODO: require name & skills!
      this.addedPerson = Immutable.Map();
      // Map([
      //   ["name", undefined],
      //   ["title", undefined],
      //   ["company", undefined],
      //   ["position", undefined],
      //   ["skills", undefined],
      //   ["bio", undefined],
      // ]);
      this.personDetails = [
        { fieldname: "Name", name: "name", value: undefined }, // s:name
        { fieldname: "Academic Title", name: "title", value: undefined },
        { fieldname: "Company", name: "company", value: undefined },
        { fieldname: "Position", name: "position", value: undefined },
        { fieldname: "Skills Title", name: "skills", value: undefined },
        { fieldname: "Bio", name: "bio", value: undefined },
      ];
      this.visibleResetButtons = new Set();

      delay(0).then(() => this.showInitialPerson());
    }

    showInitialPerson() {
      if (this.initialPerson && this.initialPerson.size > 0) {
        for (let [detail, value] of this.initialPerson.entries()) {
          this.addedPerson = this.addedPerson.set(detail, value);

          // TODO: how does this die when skills is an array?
          let personIndex = this.personDetails.findIndex(
            personDetail => personDetail.name === detail
          );
          if (personIndex !== -1 && detail !== "skills") {
            this.personDetails[personIndex].value = value;
          } else if (personIndex !== -1 && detail === "skills") {
            let valueText = value.size > 0 ? value.toJS() : [];
            this.personDetails[personIndex].value = valueText.toString();
          }
          if (value && value.length > 0) {
            this.visibleResetButtons.add(detail);
          }
        }
      }

      this.$scope.$apply();
    }

    updateDetails(detail) {
      // split between skills and everything else because skills should be a list
      if (detail.value) {
        if (detail.name !== "skills") {
          this.addedPerson = this.addedPerson.set(detail.name, detail.value);
        } else if (detail.value.length > 0) {
          const skills = Immutable.fromJS(detail.value.split(/(,\s|,)/) || []);
          this.addedPerson = this.addedPerson.set(detail.name, skills);
        }

        this.onPersonUpdated({ person: this.addedPerson });

        if (detail.value.length > 0) {
          this.visibleResetButtons.add(detail.name);
        } else {
          this.visibleResetButtons.delete(detail.name);
        }
      } else {
        this.addedPerson = this.addedPerson.set(detail.name, undefined);
        this.onPersonUpdated({ person: this.addedPerson });
        this.visibleResetButtons.delete(detail.name);
      }
    }

    showResetButton(detail) {
      return this.visibleResetButtons.has(detail);
    }

    resetPersonDetail(detail) {
      this.addedPerson = this.addedPerson.set(detail, undefined);
      this.visibleResetButtons.delete(detail);
      let personIndex = this.personDetails.findIndex(
        personDetail => personDetail.name === detail
      );
      if (personIndex !== -1) {
        this.personDetails[personIndex].value = "";
      }
      //this.textfieldna().value = "";
      this.onPersonUpdated({ person: this.addedPerson });
      //this.showResetButton = false;
    }

    // textfieldnNg() {
    //   return this.domCache.ng(".tp__input__inner");
    // }

    // textfieldn() {
    //   return this.domCache.dom(".tp__input__inner");
    // }
  }
  Controller.$inject = serviceDependencies;

  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      onPersonUpdated: "&",
      initialPerson: "=",
    },
    template: template,
  };
}

export default angular
  .module("won.owner.components.personPicker", [])
  .directive("wonPersonPicker", genComponentConf).name;
<commit_msg>Removed bio detail and updated regex<commit_after>import angular from "angular";
import { attach, delay } from "../../utils.js";
import { DomCache } from "../../cstm-ng-utils.js";
import Immutable from "immutable";

const serviceDependencies = ["$scope", "$element"];
function genComponentConf() {
  let template = `

Person Detail Picker

              {{detail.fieldname}}

          <input
            type="text"
            id="{{detail.name}}"
            class="pp__detail__input"
            ng-model="detail.value"
            ng-keyup="::self.updateDetails(detail)"
            ng-class="{'pp__detail__input--withreset' : self.showResetButton(detail.name)}"
          />
          <svg class="pp__detail__icon clickable"
            style="--local-primary:var(--won-primary-color);"
            ng-if="self.showResetButton(detail.name)"
            ng-click="self.resetPersonDetail(detail.name)">
              <use xlink:href="#ico36_close" href="#ico36_close"></use>
          </svg>

    `;

  // DONE rewrite this from tag picker to person picker
  // DONE -> Map decide on some sort of data structure
  // DONE add to create-isseeks
  // TODO: styling
  // DONE add details to draft
  // DONE add details to RDF
  // DONE display details in info
  // TODO: test matching

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      this.domCache = new DomCache(this.$element);

      window.pp4dbg = this;

      // TODO: require name & skills!
      this.addedPerson = Immutable.Map();

      this.personDetails = [
        { fieldname: "Name", name: "name", value: undefined },
        { fieldname: "Academic Title", name: "title", value: undefined },
        { fieldname: "Company", name: "company", value: undefined },
        { fieldname: "Position", name: "position", value: undefined },
        { fieldname: "Skills", name: "skills", value: undefined },
        //{ fieldname: "Bio", name: "bio", value: undefined },
      ];
      this.visibleResetButtons = new Set();

      delay(0).then(() => this.showInitialPerson());
    }

    showInitialPerson() {
      if (this.initialPerson && this.initialPerson.size > 0) {
        for (let [detail, value] of this.initialPerson.entries()) {
          this.addedPerson = this.addedPerson.set(detail, value);

          let personIndex = this.personDetails.findIndex(
            personDetail => personDetail.name === detail
          );
          if (personIndex !== -1 && detail !== "skills") {
            this.personDetails[personIndex].value = value;
          } else if (personIndex !== -1 && detail === "skills") {
            let valueText = value.size > 0 ? value.toJS() : [];
            this.personDetails[personIndex].value = valueText.toString();
          }
          if (value && value.size > 0) {
            this.visibleResetButtons.add(detail);
          }
        }
      }

      this.$scope.$apply();
    }

    updateDetails(detail) {
      // split between skills and everything else because skills should be a list
      if (detail.value) {
        if (detail.name !== "skills") {
          this.addedPerson = this.addedPerson.set(detail.name, detail.value);
        } else if (detail.value.length > 0) {
          let skills = Immutable.fromJS(detail.value.trim().split(/\s*,\s*/));
          skills = skills.filter(skill => skill.length > 0);
          this.addedPerson = this.addedPerson.set(detail.name, skills);
        }

        this.onPersonUpdated({ person: this.addedPerson });

        if (detail.value.length > 0) {
          this.visibleResetButtons.add(detail.name);
        } else {
          this.visibleResetButtons.delete(detail.name);
        }
      } else {
        this.addedPerson = this.addedPerson.set(detail.name, undefined);
        this.onPersonUpdated({ person: this.addedPerson });
        this.visibleResetButtons.delete(detail.name);
      }
    }

    showResetButton(detail) {
      return this.visibleResetButtons.has(detail);
    }

    resetPersonDetail(detail) {
      this.addedPerson = this.addedPerson.set(detail, undefined);
      this.visibleResetButtons.delete(detail);
      let personIndex = this.personDetails.findIndex(
        personDetail => personDetail.name === detail
      );
      if (personIndex !== -1) {
        this.personDetails[personIndex].value = "";
      }
      //this.textfieldna().value = "";
      this.onPersonUpdated({ person: this.addedPerson });
      //this.showResetButton = false;
    }

    // textfieldnNg() {
    //   return this.domCache.ng(".tp__input__inner");
    // }

    // textfieldn() {
    //   return this.domCache.dom(".tp__input__inner");
    // }
  }
  Controller.$inject = serviceDependencies;

  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      onPersonUpdated: "&",
      initialPerson: "=",
    },
    template: template,
  };
}

export default angular
  .module("won.owner.components.personPicker", [])
  .directive("wonPersonPicker", genComponentConf).name;
<|endoftext|>


<commit_before>'use strict';

describe('Controller Tests', function () {

    describe('HealthController', function () {
        var $scope; // actual implementations
        var createController; // local utility functions

        beforeEach(inject(function ($injector) {
            $scope = $injector.get('$rootScope').$new();
            var locals = {
                '$scope': $scope
            };
            createController = function() {
                $injector.get('$controller')('HealthController', locals);
            };
            createController();
        }));

        describe('isHealthObject and hasSubSystem', function () {
            it('should verify empty object is not a health property leaf', function () {
                expect($scope.isHealthObject({})).toBe(false);
                expect($scope.hasSubSystem({})).toBe(false);
            });

            it('should verify object with property status and no subsystems is a health property leaf', function () {
                var healthObject = {
                    'status': 'UP'
                };
                expect($scope.isHealthObject(healthObject)).toBe(true);
                expect($scope.hasSubSystem(healthObject)).toBe(false);
            });

            it('should verify that object property status and unrecognized objects is a health property leaf', function () {
                var healthObject = {
                    'status': 'UP',
                    'subsystem': {
                        'hello': 'UP'
                    }
                };
                expect($scope.isHealthObject(healthObject)).toBe(true);
                expect($scope.hasSubSystem(healthObject)).toBe(false);
            });

            it('should verify object with property status but with subsystems is NOT a health property leaf', function () {
                var healthObject = {
                    'status': 'UP',
                    'subsystem': {
                        'status': 'UP'
                    }
                };
                expect($scope.isHealthObject(healthObject)).toBe(true);
                expect($scope.hasSubSystem(healthObject)).toBe(true);
            });

        });

        describe('transformHealthData', function () {
            it('should flatten empty health data', function () {
                var data = {};
                var expected = [];
                expect($scope.transformHealthData(data)).toEqual(expected);
            });

            it('should flatten health data with no subsystems', function () {
                var data = {
                    'status': 'UP',
                    'db': {
                        'status': 'UP',
                        'database': 'H2',
                        'hello': '1'
                    },
                    'mail': {
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    }
                };
                var expected = [
                    {
                        'name': 'db',
                        'status': 'UP',
                        'details': {
                            'database': 'H2',
                            'hello': '1'
                        }
                    },
                    {
                        'name': 'mail',
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    }
                ];
                expect($scope.transformHealthData(data)).toEqual(expected);
            });

            it('should flatten health data with subsystems at level 1, main system has no additional information', function () {
                var data = {
                    'status': 'UP',
                    'db': {
                        'status': 'UP',
                        'database': 'H2',
                        'hello': '1'
                    },
                    'mail': {
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    'system': {
                        'status': 'DOWN',
                        'subsystem1': {
                            'status': 'UP',
                            'property1': 'system.subsystem1.property1'
                        },
                        'subsystem2': {
                            'status': 'DOWN',
                            'error': 'system.subsystem1.error',
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                };
                var expected = [
                    {
                        'name': 'db',
                        'status': 'UP',
                        'details': {
                            'database': 'H2',
                            'hello': '1'
                        }
                    },
                    {
                        'name': 'mail',
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    {
                        'name': 'system.subsystem1',
                        'status': 'UP',
                        'details': {
                            'property1': 'system.subsystem1.property1'
                        }
                    },
                    {
                        'name': 'system.subsystem2',
                        'status': 'DOWN',
                        'error': 'system.subsystem1.error',
                        'details': {
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                ];
                expect($scope.transformHealthData(data)).toEqual(expected);
            });

            it('should flatten health data with subsystems at level 1, main system has additional information', function () {
                var data = {
                    'status': 'UP',
                    'db': {
                        'status': 'UP',
                        'database': 'H2',
                        'hello': '1'
                    },
                    'mail': {
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    'system': {
                        'status': 'DOWN',
                        'property1': 'system.property1',
                        'subsystem1': {
                            'status': 'UP',
                            'property1': 'system.subsystem1.property1'
                        },
                        'subsystem2': {
                            'status': 'DOWN',
                            'error': 'system.subsystem1.error',
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                };
                var expected = [
                    {
                        'name': 'db',
                        'status': 'UP',
                        'details': {
                            'database': 'H2',
                            'hello': '1'
                        }
                    },
                    {
                        'name': 'mail',
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    {
                        'name': 'system',
                        'status': 'DOWN',
                        'details': {
                            'property1': 'system.property1'
                        }
                    },
                    {
                        'name': 'system.subsystem1',
                        'status': 'UP',
                        'details': {
                            'property1': 'system.subsystem1.property1'
                        }
                    },
                    {
                        'name': 'system.subsystem2',
                        'status': 'DOWN',
                        'error': 'system.subsystem1.error',
                        'details': {
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                ];
                expect($scope.transformHealthData(data)).toEqual(expected);
            });

            it('should flatten health data with subsystems at level 1, main system has additional error', function () {
                var data = {
                    'status': 'UP',
                    'db': {
                        'status': 'UP',
                        'database': 'H2',
                        'hello': '1'
                    },
                    'mail': {
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    'system': {
                        'status': 'DOWN',
                        'error': 'show me',
                        'subsystem1': {
                            'status': 'UP',
                            'property1': 'system.subsystem1.property1'
                        },
                        'subsystem2': {
                            'status': 'DOWN',
                            'error': 'system.subsystem1.error',
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                };
                var expected = [
                    {
                        'name': 'db',
                        'status': 'UP',
                        'details': {
                            'database': 'H2',
                            'hello': '1'
                        }
                    },
                    {
                        'name': 'mail',
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    {
                        'name': 'system',
                        'status': 'DOWN',
                        'error': 'show me'
                    },
                    {
                        'name': 'system.subsystem1',
                        'status': 'UP',
                        'details': {
                            'property1': 'system.subsystem1.property1'
                        }
                    },
                    {
                        'name': 'system.subsystem2',
                        'status': 'DOWN',
                        'error': 'system.subsystem1.error',
                        'details': {
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                ];
                expect($scope.transformHealthData(data)).toEqual(expected);
            });
        });

        describe('getModuleName(path, name)', function () {
            it('should show both path and name if defined', function () {
                expect($scope.getModuleName('path', 'name')).toEqual('path' + $scope.separator + 'name');
            });

            it('should show only path if name is not defined', function () {
                expect($scope.getModuleName('path')).toEqual('path');
                expect($scope.getModuleName('path', '')).toEqual('path');
                expect($scope.getModuleName('path', null)).toEqual('path');
            });

            it('should show only name if path is not defined', function () {
                expect($scope.getModuleName(null, 'name')).toEqual('name');
                expect($scope.getModuleName('', 'name')).toEqual('name');
            });

            it('should show empty string if neither name nor path is defined', function () {
                expect($scope.getModuleName()).toEqual('');
            });
        });
    });
});
<commit_msg>fix health controller test with controlleras syntax<commit_after>'use strict';

describe('Controller Tests', function () {

    describe('HealthController', function () {
        var $scope; // actual implementations
        var createController; // local utility functions

        beforeEach(inject(function ($injector) {
            $scope = $injector.get('$rootScope').$new();
            var locals = {
                '$scope': $scope
            };
            createController = function() {
                $injector.get('$controller')('HealthController as vm', locals);
            };
            createController();
        }));

        describe('isHealthObject and hasSubSystem', function () {
            it('should verify empty object is not a health property leaf', function () {
                expect($scope.vm.isHealthObject({})).toBe(false);
                expect($scope.vm.hasSubSystem({})).toBe(false);
            });

            it('should verify object with property status and no subsystems is a health property leaf', function () {
                var healthObject = {
                    'status': 'UP'
                };
                expect($scope.vm.isHealthObject(healthObject)).toBe(true);
                expect($scope.vm.hasSubSystem(healthObject)).toBe(false);
            });

            it('should verify that object property status and unrecognized objects is a health property leaf', function () {
                var healthObject = {
                    'status': 'UP',
                    'subsystem': {
                        'hello': 'UP'
                    }
                };
                expect($scope.vm.isHealthObject(healthObject)).toBe(true);
                expect($scope.vm.hasSubSystem(healthObject)).toBe(false);
            });

            it('should verify object with property status but with subsystems is NOT a health property leaf', function () {
                var healthObject = {
                    'status': 'UP',
                    'subsystem': {
                        'status': 'UP'
                    }
                };
                expect($scope.vm.isHealthObject(healthObject)).toBe(true);
                expect($scope.vm.hasSubSystem(healthObject)).toBe(true);
            });

        });

        describe('transformHealthData', function () {
            it('should flatten empty health data', function () {
                var data = {};
                var expected = [];
                expect($scope.vm.transformHealthData(data)).toEqual(expected);
            });

            it('should flatten health data with no subsystems', function () {
                var data = {
                    'status': 'UP',
                    'db': {
                        'status': 'UP',
                        'database': 'H2',
                        'hello': '1'
                    },
                    'mail': {
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    }
                };
                var expected = [
                    {
                        'name': 'db',
                        'status': 'UP',
                        'details': {
                            'database': 'H2',
                            'hello': '1'
                        }
                    },
                    {
                        'name': 'mail',
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    }
                ];
                expect($scope.vm.transformHealthData(data)).toEqual(expected);
            });

            it('should flatten health data with subsystems at level 1, main system has no additional information', function () {
                var data = {
                    'status': 'UP',
                    'db': {
                        'status': 'UP',
                        'database': 'H2',
                        'hello': '1'
                    },
                    'mail': {
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    'system': {
                        'status': 'DOWN',
                        'subsystem1': {
                            'status': 'UP',
                            'property1': 'system.subsystem1.property1'
                        },
                        'subsystem2': {
                            'status': 'DOWN',
                            'error': 'system.subsystem1.error',
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                };
                var expected = [
                    {
                        'name': 'db',
                        'status': 'UP',
                        'details': {
                            'database': 'H2',
                            'hello': '1'
                        }
                    },
                    {
                        'name': 'mail',
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    {
                        'name': 'system.subsystem1',
                        'status': 'UP',
                        'details': {
                            'property1': 'system.subsystem1.property1'
                        }
                    },
                    {
                        'name': 'system.subsystem2',
                        'status': 'DOWN',
                        'error': 'system.subsystem1.error',
                        'details': {
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                ];
                expect($scope.vm.transformHealthData(data)).toEqual(expected);
            });

            it('should flatten health data with subsystems at level 1, main system has additional information', function () {
                var data = {
                    'status': 'UP',
                    'db': {
                        'status': 'UP',
                        'database': 'H2',
                        'hello': '1'
                    },
                    'mail': {
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    'system': {
                        'status': 'DOWN',
                        'property1': 'system.property1',
                        'subsystem1': {
                            'status': 'UP',
                            'property1': 'system.subsystem1.property1'
                        },
                        'subsystem2': {
                            'status': 'DOWN',
                            'error': 'system.subsystem1.error',
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                };
                var expected = [
                    {
                        'name': 'db',
                        'status': 'UP',
                        'details': {
                            'database': 'H2',
                            'hello': '1'
                        }
                    },
                    {
                        'name': 'mail',
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    {
                        'name': 'system',
                        'status': 'DOWN',
                        'details': {
                            'property1': 'system.property1'
                        }
                    },
                    {
                        'name': 'system.subsystem1',
                        'status': 'UP',
                        'details': {
                            'property1': 'system.subsystem1.property1'
                        }
                    },
                    {
                        'name': 'system.subsystem2',
                        'status': 'DOWN',
                        'error': 'system.subsystem1.error',
                        'details': {
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                ];
                expect($scope.vm.transformHealthData(data)).toEqual(expected);
            });

            it('should flatten health data with subsystems at level 1, main system has additional error', function () {
                var data = {
                    'status': 'UP',
                    'db': {
                        'status': 'UP',
                        'database': 'H2',
                        'hello': '1'
                    },
                    'mail': {
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    'system': {
                        'status': 'DOWN',
                        'error': 'show me',
                        'subsystem1': {
                            'status': 'UP',
                            'property1': 'system.subsystem1.property1'
                        },
                        'subsystem2': {
                            'status': 'DOWN',
                            'error': 'system.subsystem1.error',
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                };
                var expected = [
                    {
                        'name': 'db',
                        'status': 'UP',
                        'details': {
                            'database': 'H2',
                            'hello': '1'
                        }
                    },
                    {
                        'name': 'mail',
                        'status': 'UP',
                        'error': 'mail.a.b.c'
                    },
                    {
                        'name': 'system',
                        'status': 'DOWN',
                        'error': 'show me'
                    },
                    {
                        'name': 'system.subsystem1',
                        'status': 'UP',
                        'details': {
                            'property1': 'system.subsystem1.property1'
                        }
                    },
                    {
                        'name': 'system.subsystem2',
                        'status': 'DOWN',
                        'error': 'system.subsystem1.error',
                        'details': {
                            'property2': 'system.subsystem2.property2'
                        }
                    }
                ];
                expect($scope.vm.transformHealthData(data)).toEqual(expected);
            });
        });

        describe('getModuleName(path, name)', function () {
            it('should show both path and name if defined', function () {
                expect($scope.vm.getModuleName('path', 'name')).toEqual('path' + $scope.vm.separator + 'name');
            });

            it('should show only path if name is not defined', function () {
                expect($scope.vm.getModuleName('path')).toEqual('path');
                expect($scope.vm.getModuleName('path', '')).toEqual('path');
                expect($scope.vm.getModuleName('path', null)).toEqual('path');
            });

            it('should show only name if path is not defined', function () {
                expect($scope.vm.getModuleName(null, 'name')).toEqual('name');
                expect($scope.vm.getModuleName('', 'name')).toEqual('name');
            });

            it('should show empty string if neither name nor path is defined', function () {
                expect($scope.vm.getModuleName()).toEqual('');
            });
        });
    });
});
<|endoftext|>


<commit_before>AppModules.Draw = function (self) {
  return {
    eventMarkers: function (force, data, names) {
      if (!data) {
        $.when(self.Fetch.zoneEvents(force, self.Player.server, self.Get.mapInd()), self.Fetch.eventNames()).done(function (dat1, dat2) {
          self.Draw.eventMarkers(force, dat1, dat2);
        });
      } else {
        self.Label.clear('e');
        var mapInd = self.Get.mapInd(1),
          map = self.Maps.load(mapInd);
        if (!map) return console.log('OOPS NO MAP. hence NO EVENT for you');
        for (var idx in data.events) {
          var uid = data.events[idx].event_id,
            event = names[uid],
            status = data.events[idx].state,
            skip = {
              Inactive: 1,
              Warmup: 2,
              Fail: 1,
              Active: 3,
              Success: 1,
              Preperation: 2
            }[status] - 1;
          if ( /*skip > 1 &&*/ event) {
            var ll = self.Geo.pos2ll(event.location.center, mapInd, 1);
            var radius = event.location.radius || 1000;
            var polyArray = [];
            radius = radius / map.mRect[2] * map.cRect[2];
            switch (event.location.type) {
            case 'poly':
              polyArray = [];
              for(var i in event.location.points)
                polyArray.push(self.Geo.pos2ll(event.location.points[i],mapInd,1));
              //TODO : Poly events.. :/
            case 'sphere':
            case 'cylinder':
              self.Label.add('e', event.name, { // sector-name
                map: self.map,
                position: ll,
                  type:event.location.type,
                  positions:polyArray,
                flags: event.flags,
                status: skip,
                label: event.name,
                desc: event.flags.join(',') + '(' + status + ') ' + event.name,
                radius: radius
              });
              break;
            default:
              console.log('unknown event type:', event)
            }
          }
        }
      }
    },
    mapMarkers: function (map) {
      var types = {
        skill_challenges: 'skill',
        points_of_interest: 'poi',
        tasks: 'tasks'
      };
      map = map || self.Maps.load(self.Get.mapInd(1));
      self.Label.clear('s');
      self.Label.clear('i');
      for (var sector in map.sectors) {
        sector = map.sectors[sector];
        self.Label.add('s', sector.name, { // sector-name
          map: self.map,
          position: self.Geo.a2ll(sector.coord),
          label: '' + sector.name + '',
          alt: sector.level || '',
          max: 7,
          min: 6,
          css: 'font-size:1.1em;color:silver;'
        });
      }
      for (var type in types)
        for (var ind in map[type]) {
          var itm = map[type][ind];
          var _type = types[type];
          var _objText, _obj;
          if (itm.type) _type = itm.type;
          if (itm.objective) {
            var _skip = 'Help Assist sure on at the and in up for with of to how How off his her their against into'.split(' ');
            var i = 3;
            _skip = _.object(_skip, _skip);
            _objText = [];
            _obj = itm.objective.split(' ').reverse();
            while (i--) {
              while (_skip[_obj[_obj.length - 1]]) _obj.pop();
              _objText.push(_obj.pop());
            }
            _objText = _objText.join(' ').replace(/\.|,/, '').split('');
            _objText[0] = _objText[0].toUpperCase();
            _objText = _objText.join('');
          }
          self.Label.add('i', itm.name || itm.task_id || Math.random() , {
            map: self.map,
            position: self.Geo.a2ll(itm.coord),
            icon: _type,
            label: itm.name || (_objText ? _objText + ' ' + itm.level : _type),
            alt: itm.objective || itm.level || '',
            desc: (itm.objective ? itm.objective : itm.name || _type) + (itm.poi_id?'\nChat code: ' + self.Get.chatCode(4, itm.poi_id):''),
            max: 7,
            sMin: 6,
            min: 4,
            css: 'color:#dff;'
          });
        } // itm,type
    }, // draw.mapMarkers
    worldMarkers: function (data, realMapsData) {
      if (!data) {
        $.when(self.Fetch.world(self.Get.continent()), self.Fetch.realMaps()).done(function (dat1, dat2) {
          self.Draw.worldMarkers(dat1, dat2);
        });
      } else {
        self.Label.clear('r');
        self.Label.clear('m');
        for (var regionInd in data.regions) {
          var region = data.regions[regionInd];
          self.Label.add('r', region.name, {
            map: self.map,
            position: self.Geo.a2ll(region.label_coord),
            label: region.name,
            css: 'color:tan;font-size:1.7em'
          });
          for (var ind in region.maps) {
            var map = _.assign({}, region.maps[ind]);
            var cRect = self.Rect.fromArray(map.continent_rect);
            var mRect = self.Rect.fromArray(map.map_rect);
            _.assign(map, {
              cRect: cRect,
              mRect: mRect,
              isInstance: !realMapsData[ind]
            });
            self.Maps.save(ind, map);
            if (realMapsData[ind]) {
              self.Label.add('m', map.name, {
                map: self.map,
                position: self.Geo.p2ll({
                  x: cRect[0] + cRect[2] / 2,
                  y: cRect[1] + cRect[3] / 2
                }),
                label: '' + map.name + '',
                alt: (map.min_level + map.max_level ? (map.min_level == map.max_level ? map.max_level : map.min_level + '-' + map.max_level) : ''),
                max: 6,
                min: 3,
                css: 'color:#ff8;font-size:1.5em'
              });
            }
          } // each maps end
        } // each region end
      } // !!data end
    }
  }
};<commit_msg>eventmarkers-Player linker usage, distinguish prep/active<commit_after>AppModules.Draw = function (self) {
  return {
    eventMarkers: function (force, data, names) {
      if (!data) {
        $.when(self.Fetch.zoneEvents(force, self.Player.linker.server, self.Get.mapInd(1)), self.Fetch.eventNames()).done(function (dat1, dat2) {
          self.Draw.eventMarkers(force, dat1, dat2);
        });
      } else {
        self.Label.clear('e');
        var mapInd = self.Get.mapInd(1),
          map = self.Maps.load(mapInd);
        if (!map) return console.log('OOPS NO MAP. hence NO EVENT for you');
        for (var idx in data.events) {
          var uid = data.events[idx].event_id,
            event = names[uid],
            status = data.events[idx].state,
            skip = {
              Inactive: 1,
              Warmup: 2,
              Fail: 1,
              Active: 4,
              Success: 1,
              Preparation: 3
            }[status] - 1;
          if ( /*skip > 1 &&*/ event) {
            var ll = self.Geo.pos2ll(event.location.center, mapInd, 1);
            var radius = event.location.radius || 1000;
            var polyArray = [];
            radius = radius / map.mRect[2] * map.cRect[2];
            switch (event.location.type) {
            case 'poly':
              polyArray = [];
              for(var i in event.location.points)
                polyArray.push(self.Geo.pos2ll(event.location.points[i],mapInd,1));
              //TODO : Poly events.. :/
            case 'sphere':
            case 'cylinder':
              self.Label.add('e', event.name, { // sector-name
                map: self.map,
                position: ll,
                  type:event.location.type,
                  positions:polyArray,
                flags: event.flags,
                status: skip,
                label: event.name,
                desc: event.flags.join(',').replace('group_event','[Group]') + '(' + status + ') ' + event.name,
                radius: radius
              });
              break;
            default:
              console.log('unknown event type:', event)
            }
          }
        }
      }
    },
    mapMarkers: function (map) {
      var types = {
        skill_challenges: 'skill',
        points_of_interest: 'poi',
        tasks: 'tasks'
      };
      map = map || self.Maps.load(self.Get.mapInd(1));
      self.Label.clear('s');
      self.Label.clear('i');
      for (var sector in map.sectors) {
        sector = map.sectors[sector];
        self.Label.add('s', sector.name, { // sector-name
          map: self.map,
          position: self.Geo.a2ll(sector.coord),
          label: '' + sector.name + '',
          alt: sector.level || '',
          max: 7,
          min: 6,
          css: 'font-size:1.1em;color:silver;'
        });
      }
      for (var type in types)
        for (var ind in map[type]) {
          var itm = map[type][ind];
          var _type = types[type];
          var _objText, _obj;
          if (itm.type) _type = itm.type;
          if (itm.objective) {
            var _skip = 'Help Assist sure on at the and in up for with of to how How off his her their against into'.split(' ');
            var i = 3;
            _skip = _.object(_skip, _skip);
            _objText = [];
            _obj = itm.objective.split(' ').reverse();
            while (i--) {
              while (_skip[_obj[_obj.length - 1]]) _obj.pop();
              _objText.push(_obj.pop());
            }
            _objText = _objText.join(' ').replace(/\.|,/, '').split('');
            _objText[0] = _objText[0].toUpperCase();
            _objText = _objText.join('');
          }
          self.Label.add('i', itm.name || itm.task_id || Math.random() , {
            map: self.map,
            position: self.Geo.a2ll(itm.coord),
            icon: _type,
            label: itm.name || (_objText ? _objText + ' ' + itm.level : _type),
            alt: itm.objective || itm.level || '',
            desc: (itm.objective ? itm.objective : itm.name || _type) + (itm.poi_id?'\nChat code: ' + self.Get.chatCode(4, itm.poi_id):''),
            max: 7,
            sMin: 6,
            min: 4,
            css: 'color:#dff;'
          });
        } // itm,type
    }, // draw.mapMarkers
    worldMarkers: function (data, realMapsData) {
      if (!data) {
        $.when(self.Fetch.world(self.Get.continent()), self.Fetch.realMaps()).done(function (dat1, dat2) {
          self.Draw.worldMarkers(dat1, dat2);
        });
      } else {
        self.Label.clear('r');
        self.Label.clear('m');
        for (var regionInd in data.regions) {
          var region = data.regions[regionInd];
          self.Label.add('r', region.name, {
            map: self.map,
            position: self.Geo.a2ll(region.label_coord),
            label: region.name,
            css: 'color:tan;font-size:1.7em'
          });
          for (var ind in region.maps) {
            var map = _.assign({}, region.maps[ind]);
            var cRect = self.Rect.fromArray(map.continent_rect);
            var mRect = self.Rect.fromArray(map.map_rect);
            _.assign(map, {
              cRect: cRect,
              mRect: mRect,
              isInstance: !realMapsData[ind]
            });
            self.Maps.save(ind, map);
            if (realMapsData[ind]) {
              self.Label.add('m', map.name, {
                map: self.map,
                position: self.Geo.p2ll({
                  x: cRect[0] + cRect[2] / 2,
                  y: cRect[1] + cRect[3] / 2
                }),
                label: '' + map.name + '',
                alt: (map.min_level + map.max_level ? (map.min_level == map.max_level ? map.max_level : map.min_level + '-' + map.max_level) : ''),
                max: 6,
                min: 3,
                css: 'color:#ff8;font-size:1.5em'
              });
            }
          } // each maps end
        } // each region end
      } // !!data end
    }
  }
};<|endoftext|>


<commit_before>var socket;

var username = 'TestUser';

$(function() {
	$.material.init();
	socket = io();

	// TODO
	populateCards();
	setUsernameField();
	onResize();
});

$(".cah-card").click(function() {
	if(!$(this).hasClass('selected-card') && !$(this).hasClass('cah-card-black')) {
		var checkbox = $(this).find('.card-checkbox');
		if(checkbox.css('display') == 'none') {
			deselectCards();
			$(this).addClass('selected-card');
			checkbox.fadeIn(400).css('display', 'inline-block');
		}
	}
});

if(!isMobile())
	$('#chat-input').focusout(function() {
		var el = $(this);
		setTimeout(function() {
			el.focus();
		});
	});

$(document).keypress(function(e) {
    if(e.which == 13)
		sendChatFromInput();
});

function onResize() {
	var docWidth = $(document).width();
	var docHeight = $(document).height();

	$('#chatbox').height(docHeight - $('#playfield').outerHeight() - $('#the-navbar').outerHeight());
	$('#chat-input').width(docWidth - $('#username-field').outerWidth() - 15);
	$('#chat-contents').height($('#chatbox').height() - $('#chat-input').height() - $('#chat-header').height() - 3);
	$('#chat-messages').width(docWidth - 200);
	$('#chat-messages').height($('#chat-contents').height());
	$('#spanel-lobby-interface').css('line-height', $('#chat-contents').height() + "px");
}
$(window).resize(onResize);

function deselectCards() {
	$('.selected-card').each(function(e) {
		$(this).removeClass('selected-card');
		var checkbox = $(this).find('.card-checkbox');
		checkbox.fadeOut(400);
	});
}

function populateCards() {
	$('.cah-card').each(function(e) {
		var html = "
" + findSpaces($(this).attr('data-text')) + "

<input type='checkbox' class='card-selector-checkbox' disabled='true' checked>
" + $(this).attr('data-deck') + "
";

		$(this).html(html);
	});

	$.material.init();
}

function findSpaces(str) {
	return str.replace("_", "___");
}

function setUsernameField() {
	$('#username-field').text(username);
}

function sendChatFromInput() {
	var input = clean($('#chat-input').val());
	var contents = $('#chat-messages');

	if(input.length > 0) {
		var text = "" + username + ": " + input;
		sendChat(text);
		$('#chat-input').val('');
		updateSendButton();
		contents.scrollTop(contents[0].scrollHeight);
	}
}
$('#send-msg-button').click(sendChatFromInput);

function sendChat(text) {
	if(text.length > 0) {
		var contents = $('#chat-messages');
		contents.append("

" + text + "

");
	}
}

// Utils

function isMobile() {
	return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

function clean(text) {
	return $('').text(text).html();
}<commit_msg>Remove the stupid force focus hack.<commit_after>var socket;

var username = 'TestUser';

$(function() {
	$.material.init();
	socket = io();

	// TODO
	populateCards();
	setUsernameField();
	onResize();
});

$(".cah-card").click(function() {
	if(!$(this).hasClass('selected-card') && !$(this).hasClass('cah-card-black')) {
		var checkbox = $(this).find('.card-checkbox');
		if(checkbox.css('display') == 'none') {
			deselectCards();
			$(this).addClass('selected-card');
			checkbox.fadeIn(400).css('display', 'inline-block');
		}
	}
});

$(document).keypress(function(e) {
    if(e.which == 13)
		sendChatFromInput();
});

function onResize() {
	var docWidth = $(document).width();
	var docHeight = $(document).height();

	$('#chatbox').height(docHeight - $('#playfield').outerHeight() - $('#the-navbar').outerHeight());
	$('#chat-input').width(docWidth - $('#username-field').outerWidth() - 15);
	$('#chat-contents').height($('#chatbox').height() - $('#chat-input').height() - $('#chat-header').height() - 3);
	$('#chat-messages').width(docWidth - 200);
	$('#chat-messages').height($('#chat-contents').height());
	$('#spanel-lobby-interface').css('line-height', $('#chat-contents').height() + "px");
}
$(window).resize(onResize);

function deselectCards() {
	$('.selected-card').each(function(e) {
		$(this).removeClass('selected-card');
		var checkbox = $(this).find('.card-checkbox');
		checkbox.fadeOut(400);
	});
}

function populateCards() {
	$('.cah-card').each(function(e) {
		var html = "
" + findSpaces($(this).attr('data-text')) + "

<input type='checkbox' class='card-selector-checkbox' disabled='true' checked>
" + $(this).attr('data-deck') + "
";

		$(this).html(html);
	});

	$.material.init();
}

function findSpaces(str) {
	return str.replace("_", "___");
}

function setUsernameField() {
	$('#username-field').text(username);
}

function sendChatFromInput() {
	var input = clean($('#chat-input').val());
	var contents = $('#chat-messages');

	if(input.length > 0) {
		var text = "" + username + ": " + input;
		sendChat(text);
		$('#chat-input').val('');
		updateSendButton();
		contents.scrollTop(contents[0].scrollHeight);
	}
}
$('#send-msg-button').click(sendChatFromInput);

function sendChat(text) {
	if(text.length > 0) {
		var contents = $('#chat-messages');
		contents.append("

" + text + "

");
	}
}

function clean(text) {
	return $('').text(text).html();
}<|endoftext|>


<commit_before>function sayHello() {
	document.write('Hello');
}
<commit_msg>[27] testing...<commit_after>function sayHello() {
	document.write('Hello, Scott');
}
<|endoftext|>


<commit_before>/********************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Evangelos Pappas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
/********************************************/

'use strict';

var request = require('request');

/**
 * Basic User info
 * @param redis
 * @param conf
 * @returns {{}}
 * @constructor
 */
module.exports = function User(redis, conf) {

    return {};
};
<commit_msg>Model, user.js -- rename redis->dbTrait<commit_after>/********************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Evangelos Pappas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
/********************************************/

'use strict';

var request = require('request');

/**
 * Basic User info
 * @param dbTrait
 * @param conf
 * @returns {{}}
 * @constructor
 */
module.exports = function User(dbTrait, conf) {

    return {};
};
<|endoftext|>