<commit_before>/**************************************************
 *  Copyright (c) 2014 AnsibleWorks, Inc.
 */
  /**
 *  @ngdoc function
 *  @name lib.ansible.function:Socket
 *  @description
 *  Socket.js
 *
 *  Wrapper for lib/socket.io-client/dist/socket.io.js.
 */

/* global io */

'use strict';
/**
 * @ngdoc method
 * @name lib.ansible.function:Socket#SocketIO
 * @methodOf lib.ansible.function:Socket
 * @description
 */
angular.module('SocketIO', ['AuthService', 'Utilities'])

    .factory('Socket', ['$rootScope', '$location', '$log', 'Authorization', 'Store', function ($rootScope, $location, $log, Authorization, Store) {
        return function(params) {
            var scope = params.scope,
                host = $location.host(),
                endpoint = params.endpoint,
                protocol = $location.protocol(),
                config, socketPort,
                url;

            // Since some pages are opened in a new tab, we might get here before AnsibleConfig is available.
            // In that case, load from local storage.
            if ($AnsibleConfig) {
                socketPort = $AnsibleConfig.websocket_port;
            }
            else {
                $log.debug('getting web socket port from local storage');
                config = Store('AnsibleConfig');
                socketPort = config.websocket_port;
            }
            url = protocol + '://' + host + ':' + socketPort + '/socket.io/' + endpoint;
            $log.debug('opening socket connection to: ' + url);

            function getSocketTip(status) {
                var result = '';
                switch(status) {
                    case 'error':
                        result = "Live events: error connecting to the Tower server. Click for troubleshooting help.";
                        break;
                    case 'connecting':
                        result = "Live events: attempting to connect to the Tower server. Click for troubleshooting help.";
                        break;
                    case "ok":
                        result = "Live events: connected. Pages containing job status information will automatically update in real-time.";
                }
                return result;
            }

            return {
                scope: scope,
                url:  url,
                socket: null,

                init: function() {
                    var self = this,
                        token = Authorization.getToken();
                    if (!$rootScope.sessionTimer || ($rootScope.sessionTimer && !$rootScope.sessionTimer.isExpired())) {
                        // We have a valid session token, so attempt socket connection
                        $log.debug('Socket connecting to: ' + url);
                        self.scope.socket_url = url;
                        self.socket = io.connect(url, {
                            headers:
                            {
                                'Authorization': 'Token ' + token,      // i don't think these are actually inserted into the header--jt
                                'X-Auth-Token': 'Token ' + token
                            },
                            'connect timeout': 3000,
                            'try multiple transports': false,
                            'max reconneciton attemps': 3,
                            'reconnection limit': 3000
                        });

                        self.socket.on('connection', function() {
                            $log.debug('Socket connecting...');
                            self.scope.$apply(function () {
                                self.scope.socketStatus = 'connecting';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('connect', function() {
                            $log.debug('Socket connection established');
                            self.scope.$apply(function () {
                                self.scope.socketStatus = 'ok';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('connect_failed', function(reason) {
                            var r = reason || 'connection refused by host';
                            $log.error('Socket connection failed: ' + r);
                            self.scope.$apply(function () {
                                self.scope.socketStatus = 'error';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });

                        });
                        self.socket.on('diconnect', function() {
                            $log.debug('Socket disconnected');
                            self.scope.$apply(function() {
                                self.socketStatus = 'error';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('error', function(reason) {
                            var r = reason || 'connection refused by host';
                            $log.debug('Socket error: ' + r);
                            self.scope.$apply(function() {
                                self.scope.socketStatus = 'error';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('reconnecting', function() {
                            $log.debug('Socket attempting reconnect...');
                            self.scope.$apply(function() {
                                self.scope.socketStatus = 'connecting';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('reconnect', function() {
                            $log.debug('Socket reconnected');
                            self.scope.$apply(function() {
                                self.scope.socketStatus = 'ok';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('reconnect_failed', function(reason) {
                            $log.error('Socket reconnect failed: ' + reason);
                            self.scope.$apply(function() {
                                self.scope.socketStatus = 'error';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                    }
                    else {
                        // encountered expired token, redirect to login page
                        $rootScope.sessionTimer.expireSession();
                        $location.url('/login');
                    }
                },
                checkStatus: function() {
                    // Check connection status
                    var self = this;
                    if (self.socket.socket.connected) {
                        self.scope.socketStatus = 'ok';
                    }
                    else if (self.socket.socket.connecting || self.socket.socket.reconnecting) {
                        self.scope.socketStatus = 'connecting';
                    }
                    else {
                        self.scope.socketStatus = 'error';
                    }
                    self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                    return self.scope.socketStatus;
                },
                on: function (eventName, callback) {
                    var self = this;
                    self.socket.on(eventName, function () {
                        var args = arguments;
                        self.scope.$apply(function () {
                            callback.apply(self.socket, args);
                        });
                    });
                },
                emit: function (eventName, data, callback) {
                    var self = this;
                    self.socket.emit(eventName, data, function () {
                        var args = arguments;
                        self.scope.$apply(function () {
                            if (callback) {
                                callback.apply(self.socket, args);
                            }
                        });
                    });
                },
                getUrl: function() {
                    return url;
                }
            };
        };
    }]);
<commit_msg>Socket.js error message<commit_after>/**************************************************
 *  Copyright (c) 2014 AnsibleWorks, Inc.
 */
  /**
 *  @ngdoc function
 *  @name lib.ansible.function:Socket
 *  @description
 *  Socket.js
 *
 *  Wrapper for lib/socket.io-client/dist/socket.io.js.
 */

/* global io */

'use strict';
/**
 * @ngdoc method
 * @name lib.ansible.function:Socket#SocketIO
 * @methodOf lib.ansible.function:Socket
 * @description
 */
angular.module('SocketIO', ['AuthService', 'Utilities'])

    .factory('Socket', ['$rootScope', '$location', '$log', 'Authorization', 'Store', function ($rootScope, $location, $log, Authorization, Store) {
        return function(params) {
            var scope = params.scope,
                host = $location.host(),
                endpoint = params.endpoint,
                protocol = $location.protocol(),
                config, socketPort,
                url;

            // Since some pages are opened in a new tab, we might get here before AnsibleConfig is available.
            // In that case, load from local storage.
            if ($AnsibleConfig) {
                socketPort = $AnsibleConfig.websocket_port;
            }
            else {
                $log.debug('getting web socket port from local storage');
                config = Store('AnsibleConfig');
                socketPort = config.websocket_port;
            }
            url = protocol + '://' + host + ':' + socketPort + '/socket.io/' + endpoint;
            $log.debug('opening socket connection to: ' + url);

            function getSocketTip(status) {
                var result = '';
                switch(status) {
                    case 'error':
                        result = "Live events: error connecting to the Tower server. Click for troubleshooting help.";
                        break;
                    case 'connecting':
                        result = "Live events: attempting to connect to the Tower server. Click for troubleshooting help.";
                        break;
                    case "ok":
                        result = "Live events: connected. Pages containing job status information will automatically update in real-time.";
                }
                return result;
            }

            return {
                scope: scope,
                url:  url,
                socket: null,

                init: function() {
                    var self = this,
                        token = Authorization.getToken();
                    if (!$rootScope.sessionTimer || ($rootScope.sessionTimer && !$rootScope.sessionTimer.isExpired())) {
                        // We have a valid session token, so attempt socket connection
                        $log.debug('Socket connecting to: ' + url);
                        self.scope.socket_url = url;
                        self.socket = io.connect(url, {
                            headers:
                            {
                                'Authorization': 'Token ' + token,      // i don't think these are actually inserted into the header--jt
                                'X-Auth-Token': 'Token ' + token
                            },
                            'connect timeout': 3000,
                            'try multiple transports': false,
                            'max reconneciton attemps': 3,
                            'reconnection limit': 3000
                        });

                        self.socket.on('connection', function() {
                            $log.debug('Socket connecting...');
                            self.scope.$apply(function () {
                                self.scope.socketStatus = 'connecting';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('connect', function() {
                            $log.debug('Socket connection established');
                            self.scope.$apply(function () {
                                self.scope.socketStatus = 'ok';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('connect_failed', function(reason) {
                            var r = reason || 'connection refused by host';
                            $log.error('Socket connection failed: ' + r);
                            self.scope.$apply(function () {
                                self.scope.socketStatus = 'error';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });

                        });
                        self.socket.on('diconnect', function() {
                            $log.debug('Socket disconnected');
                            self.scope.$apply(function() {
                                self.socketStatus = 'error';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('error', function(reason) {
                            var r = reason || 'connection refused by host';
                            $log.debug('Socket error: ' + r);
                            $log.error('Socket error: ' + r);
                            self.scope.$apply(function() {
                                self.scope.socketStatus = 'error';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('reconnecting', function() {
                            $log.debug('Socket attempting reconnect...');
                            self.scope.$apply(function() {
                                self.scope.socketStatus = 'connecting';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('reconnect', function() {
                            $log.debug('Socket reconnected');
                            self.scope.$apply(function() {
                                self.scope.socketStatus = 'ok';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                        self.socket.on('reconnect_failed', function(reason) {
                            $log.error('Socket reconnect failed: ' + reason);
                            self.scope.$apply(function() {
                                self.scope.socketStatus = 'error';
                                self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                            });
                        });
                    }
                    else {
                        // encountered expired token, redirect to login page
                        $rootScope.sessionTimer.expireSession();
                        $location.url('/login');
                    }
                },
                checkStatus: function() {
                    // Check connection status
                    var self = this;
                    if (self.socket.socket.connected) {
                        self.scope.socketStatus = 'ok';
                    }
                    else if (self.socket.socket.connecting || self.socket.socket.reconnecting) {
                        self.scope.socketStatus = 'connecting';
                    }
                    else {
                        self.scope.socketStatus = 'error';
                    }
                    self.scope.socketTip = getSocketTip(self.scope.socketStatus);
                    return self.scope.socketStatus;
                },
                on: function (eventName, callback) {
                    var self = this;
                    self.socket.on(eventName, function () {
                        var args = arguments;
                        self.scope.$apply(function () {
                            callback.apply(self.socket, args);
                        });
                    });
                },
                emit: function (eventName, data, callback) {
                    var self = this;
                    self.socket.emit(eventName, data, function () {
                        var args = arguments;
                        self.scope.$apply(function () {
                            if (callback) {
                                callback.apply(self.socket, args);
                            }
                        });
                    });
                },
                getUrl: function() {
                    return url;
                }
            };
        };
    }]);
<|endoftext|>


<commit_before>const models = {
  page: require('../models/page'),
  user: require('../models/user')
}

const remove = [
  '_id',
  'id',
  'password',
  '__v'
]

exports.one = function *(type, _id) {
  const query = models[type].where({ _id })

  try {
    var item = yield query.findOne()
  } catch (err) {
    return log('Couldn\'t load ' + type + 's', err)
  }

  var attributes = item.toObject()

  for (var property of remove) {
    delete attributes[property]
  }

  return {
    id: _id,
    type: type.toLowerCase(),
    attributes
  }
}

exports.all = function *(type) {
  const plural = type + 's'

  try {
    var items = yield models[type].find()
  } catch (err) {
    return log('Couldn\'t load ' + plural, err)
  }

  var list = []

  for (var item in items) {
    var attributes = items[item].toObject()
    var id = attributes.id

    for (var property of remove) {
      delete attributes[property]
    }

    list.push({
      id,
      type: plural,
      attributes
    })
  }

  return list
}
<commit_msg>Use _id if id is not set<commit_after>const models = {
  page: require('../models/page'),
  user: require('../models/user')
}

const remove = [
  '_id',
  'id',
  'password',
  '__v'
]

exports.one = function *(type, _id) {
  const query = models[type].where({ _id })

  try {
    var item = yield query.findOne()
  } catch (err) {
    return log('Couldn\'t load ' + type + 's', err)
  }

  var attributes = item.toObject()

  for (var property of remove) {
    delete attributes[property]
  }

  return {
    id: _id,
    type: type.toLowerCase(),
    attributes
  }
}

exports.all = function *(type) {
  const plural = type + 's'

  try {
    var items = yield models[type].find()
  } catch (err) {
    return log('Couldn\'t load ' + plural, err)
  }

  var list = []

  for (var item in items) {
    var attributes = items[item].toObject()
    var id = attributes.id || attributes._id

    for (var property of remove) {
      delete attributes[property]
    }

    list.push({
      id,
      type: plural,
      attributes
    })
  }

  return list
}
<|endoftext|>


<commit_before>// Gruntfile task enhancer
//
// Bart van der Schoor
//

var util = require('util');
var path = require('path');
var lib = require('./lib');

/*jshint -W098 */

// duckpatch decorator
function defaultTaskData(data) {
	data.params = data.params || {};
	data.plugins = data.plugins || [];
	data.groups = data.groups || [];
	return data;
}

// power-boost grunt and return gtx api
function wrapGrunt(grunt) {
	'use strict';

	// de-clutter
	var _ = grunt.util._;
	var forEach = _.forEach;
	var hasOwnProp = lib.hasOwnProp;

	// assemble
	var gtx = {
		grunt: grunt,
		debug: false
	};
	grunt.gtx = gtx;

	var prefix = '';
	var taskMap = {};
	var macros = {};
	var selections = {};
	var config = {};
	var isInit = false;
	var useAutoLoad = false;
	var autoLoadOptions = {};
	var createdAliases = [];
	var defaultMacroOptions = {
		concurrent: 1
	};
	var loadNpmPlugins = [];
	var implicitDependPlugins = [];

	// odd pathing but necessary for issues with cwd (from the tests)
	grunt.loadTasks(path.resolve(__dirname, '..', 'tasks'));

	function addAlias(name, body) {
		console.log('addAlias: ' + name + ' ' + typeof body);
		createdAliases.push({name: name, tasks: body});
		grunt.registerTask(name, body);
	}

	function addTaskList(name, label, tasks, concurrentLimit) {
		//parallel
		if (concurrentLimit > 1) {
			lib.pushUnique(implicitDependPlugins, 'grunt-concurrent');

			//chain name
			var concurrentID = lib.getNameUID(prefix, label);
			var cfg = {
				tasks: tasks,
				options: {
					logConcurrentOutput: false,
					limit: concurrentLimit
				}};
			gtx.configFor('concurrent', concurrentID, cfg);

			addAlias(name + ':' + label, ['concurrent:' + concurrentID]);
			addAlias(name + ':' + label + ':single', tasks);
		}
		else {
			addAlias(name + ':' + label, tasks);
		}
	}

	// magically load tasks
	gtx.loadAuto = function (options) {
		useAutoLoad = true;
		autoLoadOptions = grunt.util._.extend({}, options, autoLoadOptions);
	};

	// load from node_modules
	gtx.loadNpm = function () {
		forEach(lib.splitify(arguments), function (name) {
			lib.pushUnique(loadNpmPlugins, name);
			//grunt.loadNpmTasks(name);
		});
	};
	// load from path
	gtx.loadTasks = function () {
		forEach(lib.splitify(arguments), function (name) {
			grunt.loadTasks(name);
		});
	};

	// helper
	gtx.call = function (name, func) {
		grunt.log.writeln('call ' + name + ' ' + (typeof func));
		if (arguments.length === 1) {
			func = name;
			name = lib.getNameUID(prefix);
		}
		addAlias(name, func);
		return name;
	};

	// alias for registerTask
	gtx.alias = function (name) {
		var arr = [];
		for (var i = 1; i < arguments.length; i++) {
			lib.splitifyValueInto(arguments[i], arr);
		}

		forEach(arr, function (elem, index, arr) {
			if (typeof elem === 'function') {
				arr[index] = gtx.call(elem);
			}
		});

		forEach(lib.splitify(name), function (name) {
			// lets add a copy for safety
			addAlias(name, arr.slice(0));
		});
		return name;
	};

	// copy a classic config object into the main tree
	gtx.config = function (cfg) {
		var targets = [];
		forEach(cfg, function (pluginData, pluginName) {
			if (pluginName === 'pkg') {
				config[pluginName] = pluginData;
			}
			else {
				forEach(pluginData, function (targetData, targetName) {
					var name = gtx.configFor(pluginName, targetName, targetData);
					targets.push(name);
				});
			}
		});
		return targets;
	};

	// add data for a target, possibly generate a name
	gtx.configFor = function (pluginName, targetName, data) {
		if (arguments.length <= 2) {
			data = targetName;
			targetName = lib.getNameUID();
		}
		//TODO add proper map object
		if (!hasOwnProp(config, pluginName)) {
			config[pluginName] = {};
		}
		//TODO validate uniqueness?
		config[pluginName][targetName] = data;
		return pluginName + ':' + targetName;
	};

	// directly set options
	gtx.options = function (pluginName, targetName, options) {
		//TODO there must be a better way to do this
		if (arguments.length <= 2) {
			if (!hasOwnProp(config, pluginName)) {
				config[pluginName] = {options: options};
			}
			else {
				config[pluginName].options = options;
			}
		}
		else {
			if (!hasOwnProp(config, pluginName)) {
				config[pluginName] = {};
			}
			if (!hasOwnProp(config[pluginName], targetName)) {
				config[pluginName][targetName] = {};
			}
			config[pluginName][targetName].options = options;
		}
	};

	// for debugging
	gtx.dumpConfig = function (depth) {
		grunt.log.writeln('-> dumpConfig');
		grunt.log.writeln(util.inspect(config, false, depth || 10));
	};
	// for hackability
	gtx.getConfig = function () {
		return config;
	};

	gtx.log = function (message, sender) {
		return gtx.configFor('gtx-log', {message: message, sender: sender});
	};

	// define a macro
	gtx.define = function (type, func, options) {
		if (arguments.length < 1) {
			throw (new Error('expected at least 1 argument'));
		}
		if (arguments.length === 1) {
			func = type;
			type = lib.getNameUID('gtx-macro');
		}
		options = _.defaults(options || {}, defaultMacroOptions);
		if (hasOwnProp(macros, type)) {
			throw(new Error('cannot override macros type:' + type));
		}
		macros[type] = {
			func: func,
			options: options
		};

		// return factory (easy and/or needed for anonymous macros
		return function (id, params, groups) {
			return gtx.create(id, type, params, groups);
		};
	};

	// create instance from defined macro
	gtx.create = function (id, type, params, groups) {
		if (arguments.length < 2) {
			throw (new Error('expected at least 2 arguments'));
		}
		//TODO add proper map
		if (!hasOwnProp(macros, type)) {
			throw(new Error('missing macros type: ' + type));
		}
		// store data
		groups = lib.splitify(groups);

		forEach(lib.splitify(id), function (id) {
			taskMap[id] = defaultTaskData({
				id: id,
				type: type,
				params: params,
				groups: groups
			});
		});
	};

	// create anonymous macro instance, return name
	gtx.anon = function (type, params, groups) {
		if (arguments.length < 1) {
			throw (new Error('expected at least 1 argument'));
		}
		var id = lib.getNameUID(type);
		gtx.create(id, type, params, groups);
		return id;
	};

	// use a selector to create alias for matches
	//TODO (re)implement this
	gtx.select = function (id, selector) {
		selections[id] = selector;
	};

	// closurefest 3000
	gtx.finalise = function (cfg) {
		if (isInit) {
			throw (new Error('multiple calls to finalise() detected'));
		}
		isInit = true;

		if (cfg) {
			gtx.config(cfg);
		}

		var groups = {};
		var types = {};
		var plugins = {};
		var all = [];

		// import config
		forEach(config, function (plugin, pluginName) {
			if (pluginName === 'pkg') {
				return;
			}
			if (pluginName === 'options') {
				return;
			}
			//TODO is this correct? what about random user data?
			forEach(plugin, function (target, targetName) {
				if (targetName === 'options') {
					return;
				}
				var data = defaultTaskData({
					id: targetName,
					type: pluginName,
					plugins: [pluginName]
				});
				lib.pushHash(plugins, pluginName, data);
				all.push(data);
			});
		});

		// add macro instances
		forEach(taskMap, function (data) {

			all.push(data);

			var tasks = [];
			var alias = 'gtx:' + data.id;
			var macro = macros[data.type];

			// helper closures for easy access
			// TODO find a way to move these to own file/place
			var addTask = function (pluginName, targetName, targetData) {
				if (arguments.length < 2) {
					throw (new Error('expected at least 2 arguments'));
				}
				if (arguments.length === 2) {
					targetData = targetName;
					targetName = lib.getNameUID(prefix, data.id);
				}

				gtx.configFor(pluginName, targetName, targetData);

				lib.pushUnique(data.plugins, pluginName);
				lib.pushHash(plugins, pluginName, data);

				lib.pushUnique(tasks, pluginName + ':' + targetName);
			};
			var runTask = function (plugin, target) {
				if (arguments.length < 1) {
					throw (new Error('expected at least 1 argument'));
				}
				if (arguments.length === 2) {
					lib.pushUnique(tasks, plugin + ':' + target);
				} else {
					lib.pushUnique(tasks, plugin);
				}
			};
			var addGroup = function (group) {
				if (arguments.length < 1) {
					throw (new Error('expected at least 1 argument'));
				}
				forEach(lib.splitify(group), function (groupName) {
					lib.pushHash(groups, groupName, alias);
				});
			};
			var callFunc = function (func) {
				if (arguments.length < 1) {
					throw (new Error('expected at least 1 argument'));
				}
				var targetName = lib.getNameUID(prefix, data.id);
				grunt.log.writeln('callFunc ' + func);
				gtx.call(targetName, func);
				lib.pushUnique(tasks, targetName);
			};
			var doLog = function (value) {
				lib.pushUnique(tasks, gtx.log(value, data.id));
			};

			// custom context
			var context = {
				grunt: grunt,
				config: config,
				// add the helpers
				add: addTask,
				tag: addGroup,
				run: runTask,
				call: callFunc,
				getUID: lib.getNameUID,
				getParam: lib.getParamAccessor(data.id, data.params),
				log: doLog
			};

			//console.log('execute macro ' + data.id + ':' + data.type);

			// execute
			macro.func.apply(null, [context, data.id]);

			// add it!
			addAlias(alias, tasks);

			// keep type
			lib.pushHash(types, data.type, alias);

			// add to groups
			if (data.groups) {
				forEach(data.groups, function (groupName) {
					lib.pushHash(groups, groupName, alias);
				});
			}
		});

		// add combi aliases
		forEach(groups, function (tasks, id) {
			addAlias('gtx-group:' + id, tasks);
		});

		forEach(types, function (tasks, type) {
			var macro = macros[type];
			//addAlias('gtx-type:' + type, tasks);
			addTaskList('gtx-type', type, tasks, macro.options.concurrent);
		});

		// TODO re-implement selector

		// process auto-load
		if (useAutoLoad) {
			//TODO re-implement autoLoad() properly since we know what plugins were used
			//load everything for now
			require('load-grunt-tasks')(grunt, autoLoadOptions);
			if (grunt.file.exists('./tasks')) {
				grunt.loadTasks('./tasks');
			}
		}

		// add these
		if (loadNpmPlugins.length > 0) {
			//grunt.log.writeln('loading plugins: ' + loadNpmPlugins.join(', '));
			loadNpmPlugins.forEach(function (plugin) {
				grunt.loadNpmTasks(plugin);
			});
		}
		implicitDependPlugins = _.difference(implicitDependPlugins, loadNpmPlugins);
		if (implicitDependPlugins.length > 0) {
			//grunt.log.writeln('implicitly loading plugins: ' + implicitDependPlugins.join(', '));
			implicitDependPlugins.forEach(function (plugin) {
				grunt.loadNpmTasks(plugin);
			});
		}

		// booya
		if (gtx.debug) {
			grunt.log.writeln(util.inspect(taskMap, false, 2));
			grunt.log.writeln();
			gtx.dumpConfig();
			grunt.log.writeln();
			grunt.log.writeln(util.inspect(createdAliases));
		}

		// add it all
		grunt.initConfig(config);
	};

	// shadowmonkeyduckwraps
	gtx.registerTask = gtx.alias;
	gtx.loadNpmTasks = gtx.loadNpm;
	gtx.initConfig = gtx.config;
	gtx.registerMultiTaskt = grunt.registerMultiTaskt;
	gtx.multi = grunt.registerMultiTaskt;

	//add some lazy utils

	// handy
	gtx.extendObject = function (source, extend) {
		var ret = {};
		forEach(arguments, function (arg) {
			ret = lib.copyTo(ret, arg);
		});
		return ret;
	};

	// merge paths + literals
	gtx.readJSON = function (paths) {
		var ret = {};
		forEach(arguments, function (arg) {
			if (typeof arg === 'string') {
				ret = lib.copyTo(ret, grunt.file.readJSON(arg));
			}
			else {
				ret = lib.copyTo(ret, arg);
			}
		});
		return ret;
	};

	// merge paths + literals
	gtx.readYAML = function (paths) {
		var ret = {};
		forEach(arguments, function (arg) {
			if (typeof arg === 'string') {
				ret = lib.copyTo(ret, grunt.file.readYAML(arg));
			}
			else {
				ret = lib.copyTo(ret, arg);
			}
		});
		return ret;
	};

	// wheee
	return gtx;
}

module.exports = {
	wrap: wrapGrunt
};
<commit_msg>removed lingering console.log()<commit_after>// Gruntfile task enhancer
//
// Bart van der Schoor
//

var util = require('util');
var path = require('path');
var lib = require('./lib');

/*jshint -W098 */

// duckpatch decorator
function defaultTaskData(data) {
	data.params = data.params || {};
	data.plugins = data.plugins || [];
	data.groups = data.groups || [];
	return data;
}

// power-boost grunt and return gtx api
function wrapGrunt(grunt) {
	'use strict';

	// de-clutter
	var _ = grunt.util._;
	var forEach = _.forEach;
	var hasOwnProp = lib.hasOwnProp;

	// assemble
	var gtx = {
		grunt: grunt,
		debug: false
	};
	grunt.gtx = gtx;

	var prefix = '';
	var taskMap = {};
	var macros = {};
	var selections = {};
	var config = {};
	var isInit = false;
	var useAutoLoad = false;
	var autoLoadOptions = {};
	var createdAliases = [];
	var defaultMacroOptions = {
		concurrent: 1
	};
	var loadNpmPlugins = [];
	var implicitDependPlugins = [];

	// odd pathing but necessary for issues with cwd (from the tests)
	grunt.loadTasks(path.resolve(__dirname, '..', 'tasks'));

	function addAlias(name, body) {
		createdAliases.push({name: name, tasks: body});
		grunt.registerTask(name, body);
	}

	function addTaskList(name, label, tasks, concurrentLimit) {
		//parallel
		if (concurrentLimit > 1) {
			lib.pushUnique(implicitDependPlugins, 'grunt-concurrent');

			//chain name
			var concurrentID = lib.getNameUID(prefix, label);
			var cfg = {
				tasks: tasks,
				options: {
					logConcurrentOutput: false,
					limit: concurrentLimit
				}};
			gtx.configFor('concurrent', concurrentID, cfg);

			addAlias(name + ':' + label, ['concurrent:' + concurrentID]);
			addAlias(name + ':' + label + ':single', tasks);
		}
		else {
			addAlias(name + ':' + label, tasks);
		}
	}

	// magically load tasks
	gtx.loadAuto = function (options) {
		useAutoLoad = true;
		autoLoadOptions = grunt.util._.extend({}, options, autoLoadOptions);
	};

	// load from node_modules
	gtx.loadNpm = function () {
		forEach(lib.splitify(arguments), function (name) {
			lib.pushUnique(loadNpmPlugins, name);
			//grunt.loadNpmTasks(name);
		});
	};
	// load from path
	gtx.loadTasks = function () {
		forEach(lib.splitify(arguments), function (name) {
			grunt.loadTasks(name);
		});
	};

	// helper
	gtx.call = function (name, func) {
		grunt.log.writeln('call ' + name + ' ' + (typeof func));
		if (arguments.length === 1) {
			func = name;
			name = lib.getNameUID(prefix);
		}
		addAlias(name, func);
		return name;
	};

	// alias for registerTask
	gtx.alias = function (name) {
		var arr = [];
		for (var i = 1; i < arguments.length; i++) {
			lib.splitifyValueInto(arguments[i], arr);
		}

		forEach(arr, function (elem, index, arr) {
			if (typeof elem === 'function') {
				arr[index] = gtx.call(elem);
			}
		});

		forEach(lib.splitify(name), function (name) {
			// lets add a copy for safety
			addAlias(name, arr.slice(0));
		});
		return name;
	};

	// copy a classic config object into the main tree
	gtx.config = function (cfg) {
		var targets = [];
		forEach(cfg, function (pluginData, pluginName) {
			if (pluginName === 'pkg') {
				config[pluginName] = pluginData;
			}
			else {
				forEach(pluginData, function (targetData, targetName) {
					var name = gtx.configFor(pluginName, targetName, targetData);
					targets.push(name);
				});
			}
		});
		return targets;
	};

	// add data for a target, possibly generate a name
	gtx.configFor = function (pluginName, targetName, data) {
		if (arguments.length <= 2) {
			data = targetName;
			targetName = lib.getNameUID();
		}
		//TODO add proper map object
		if (!hasOwnProp(config, pluginName)) {
			config[pluginName] = {};
		}
		//TODO validate uniqueness?
		config[pluginName][targetName] = data;
		return pluginName + ':' + targetName;
	};

	// directly set options
	gtx.options = function (pluginName, targetName, options) {
		//TODO there must be a better way to do this
		if (arguments.length <= 2) {
			if (!hasOwnProp(config, pluginName)) {
				config[pluginName] = {options: options};
			}
			else {
				config[pluginName].options = options;
			}
		}
		else {
			if (!hasOwnProp(config, pluginName)) {
				config[pluginName] = {};
			}
			if (!hasOwnProp(config[pluginName], targetName)) {
				config[pluginName][targetName] = {};
			}
			config[pluginName][targetName].options = options;
		}
	};

	// for debugging
	gtx.dumpConfig = function (depth) {
		grunt.log.writeln('-> dumpConfig');
		grunt.log.writeln(util.inspect(config, false, depth || 10));
	};
	// for hackability
	gtx.getConfig = function () {
		return config;
	};

	gtx.log = function (message, sender) {
		return gtx.configFor('gtx-log', {message: message, sender: sender});
	};

	// define a macro
	gtx.define = function (type, func, options) {
		if (arguments.length < 1) {
			throw (new Error('expected at least 1 argument'));
		}
		if (arguments.length === 1) {
			func = type;
			type = lib.getNameUID('gtx-macro');
		}
		options = _.defaults(options || {}, defaultMacroOptions);
		if (hasOwnProp(macros, type)) {
			throw(new Error('cannot override macros type:' + type));
		}
		macros[type] = {
			func: func,
			options: options
		};

		// return factory (easy and/or needed for anonymous macros
		return function (id, params, groups) {
			return gtx.create(id, type, params, groups);
		};
	};

	// create instance from defined macro
	gtx.create = function (id, type, params, groups) {
		if (arguments.length < 2) {
			throw (new Error('expected at least 2 arguments'));
		}
		//TODO add proper map
		if (!hasOwnProp(macros, type)) {
			throw(new Error('missing macros type: ' + type));
		}
		// store data
		groups = lib.splitify(groups);

		forEach(lib.splitify(id), function (id) {
			taskMap[id] = defaultTaskData({
				id: id,
				type: type,
				params: params,
				groups: groups
			});
		});
	};

	// create anonymous macro instance, return name
	gtx.anon = function (type, params, groups) {
		if (arguments.length < 1) {
			throw (new Error('expected at least 1 argument'));
		}
		var id = lib.getNameUID(type);
		gtx.create(id, type, params, groups);
		return id;
	};

	// use a selector to create alias for matches
	//TODO (re)implement this
	gtx.select = function (id, selector) {
		selections[id] = selector;
	};

	// closurefest 3000
	gtx.finalise = function (cfg) {
		if (isInit) {
			throw (new Error('multiple calls to finalise() detected'));
		}
		isInit = true;

		if (cfg) {
			gtx.config(cfg);
		}

		var groups = {};
		var types = {};
		var plugins = {};
		var all = [];

		// import config
		forEach(config, function (plugin, pluginName) {
			if (pluginName === 'pkg') {
				return;
			}
			if (pluginName === 'options') {
				return;
			}
			//TODO is this correct? what about random user data?
			forEach(plugin, function (target, targetName) {
				if (targetName === 'options') {
					return;
				}
				var data = defaultTaskData({
					id: targetName,
					type: pluginName,
					plugins: [pluginName]
				});
				lib.pushHash(plugins, pluginName, data);
				all.push(data);
			});
		});

		// add macro instances
		forEach(taskMap, function (data) {

			all.push(data);

			var tasks = [];
			var alias = 'gtx:' + data.id;
			var macro = macros[data.type];

			// helper closures for easy access
			// TODO find a way to move these to own file/place
			var addTask = function (pluginName, targetName, targetData) {
				if (arguments.length < 2) {
					throw (new Error('expected at least 2 arguments'));
				}
				if (arguments.length === 2) {
					targetData = targetName;
					targetName = lib.getNameUID(prefix, data.id);
				}

				gtx.configFor(pluginName, targetName, targetData);

				lib.pushUnique(data.plugins, pluginName);
				lib.pushHash(plugins, pluginName, data);

				lib.pushUnique(tasks, pluginName + ':' + targetName);
			};
			var runTask = function (plugin, target) {
				if (arguments.length < 1) {
					throw (new Error('expected at least 1 argument'));
				}
				if (arguments.length === 2) {
					lib.pushUnique(tasks, plugin + ':' + target);
				} else {
					lib.pushUnique(tasks, plugin);
				}
			};
			var addGroup = function (group) {
				if (arguments.length < 1) {
					throw (new Error('expected at least 1 argument'));
				}
				forEach(lib.splitify(group), function (groupName) {
					lib.pushHash(groups, groupName, alias);
				});
			};
			var callFunc = function (func) {
				if (arguments.length < 1) {
					throw (new Error('expected at least 1 argument'));
				}
				var targetName = lib.getNameUID(prefix, data.id);
				grunt.log.writeln('callFunc ' + func);
				gtx.call(targetName, func);
				lib.pushUnique(tasks, targetName);
			};
			var doLog = function (value) {
				lib.pushUnique(tasks, gtx.log(value, data.id));
			};

			// custom context
			var context = {
				grunt: grunt,
				config: config,
				// add the helpers
				add: addTask,
				tag: addGroup,
				run: runTask,
				call: callFunc,
				getUID: lib.getNameUID,
				getParam: lib.getParamAccessor(data.id, data.params),
				log: doLog
			};

			//console.log('execute macro ' + data.id + ':' + data.type);

			// execute
			macro.func.apply(null, [context, data.id]);

			// add it!
			addAlias(alias, tasks);

			// keep type
			lib.pushHash(types, data.type, alias);

			// add to groups
			if (data.groups) {
				forEach(data.groups, function (groupName) {
					lib.pushHash(groups, groupName, alias);
				});
			}
		});

		// add combi aliases
		forEach(groups, function (tasks, id) {
			addAlias('gtx-group:' + id, tasks);
		});

		forEach(types, function (tasks, type) {
			var macro = macros[type];
			//addAlias('gtx-type:' + type, tasks);
			addTaskList('gtx-type', type, tasks, macro.options.concurrent);
		});

		// TODO re-implement selector

		// process auto-load
		if (useAutoLoad) {
			//TODO re-implement autoLoad() properly since we know what plugins were used
			//load everything for now
			require('load-grunt-tasks')(grunt, autoLoadOptions);
			if (grunt.file.exists('./tasks')) {
				grunt.loadTasks('./tasks');
			}
		}

		// add these
		if (loadNpmPlugins.length > 0) {
			//grunt.log.writeln('loading plugins: ' + loadNpmPlugins.join(', '));
			loadNpmPlugins.forEach(function (plugin) {
				grunt.loadNpmTasks(plugin);
			});
		}
		implicitDependPlugins = _.difference(implicitDependPlugins, loadNpmPlugins);
		if (implicitDependPlugins.length > 0) {
			//grunt.log.writeln('implicitly loading plugins: ' + implicitDependPlugins.join(', '));
			implicitDependPlugins.forEach(function (plugin) {
				grunt.loadNpmTasks(plugin);
			});
		}

		// booya
		if (gtx.debug) {
			grunt.log.writeln(util.inspect(taskMap, false, 2));
			grunt.log.writeln();
			gtx.dumpConfig();
			grunt.log.writeln();
			grunt.log.writeln(util.inspect(createdAliases));
		}

		// add it all
		grunt.initConfig(config);
	};

	// shadowmonkeyduckwraps
	gtx.registerTask = gtx.alias;
	gtx.loadNpmTasks = gtx.loadNpm;
	gtx.initConfig = gtx.config;
	gtx.registerMultiTaskt = grunt.registerMultiTaskt;
	gtx.multi = grunt.registerMultiTaskt;

	//add some lazy utils

	// handy
	gtx.extendObject = function (source, extend) {
		var ret = {};
		forEach(arguments, function (arg) {
			ret = lib.copyTo(ret, arg);
		});
		return ret;
	};

	// merge paths + literals
	gtx.readJSON = function (paths) {
		var ret = {};
		forEach(arguments, function (arg) {
			if (typeof arg === 'string') {
				ret = lib.copyTo(ret, grunt.file.readJSON(arg));
			}
			else {
				ret = lib.copyTo(ret, arg);
			}
		});
		return ret;
	};

	// merge paths + literals
	gtx.readYAML = function (paths) {
		var ret = {};
		forEach(arguments, function (arg) {
			if (typeof arg === 'string') {
				ret = lib.copyTo(ret, grunt.file.readYAML(arg));
			}
			else {
				ret = lib.copyTo(ret, arg);
			}
		});
		return ret;
	};

	// wheee
	return gtx;
}

module.exports = {
	wrap: wrapGrunt
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { Grid, Container, Row, Col, Form, FormGroup, FormControl, ControlLabel, Input, Button, ButtonGroup, Glyphicon } from 'react-bootstrap';
import {Field, reduxForm} from 'redux-form';
import ModuleList from '../modules/ModuleList';
import ModuleSelector from './ModuleSelector';

class TenantForm extends Component {
  static propTypes = {
    handleSubmit: PropTypes.func.isRequired,
    cancelForm: PropTypes.func.isRequired,
    submitLabel: PropTypes.string,
    disableFields: PropTypes.bool
  };

  static defaultProps = {
    submitLabel: 'Submit',
    disableFields: false,
    tenantModules: []
  };

  render() {
    const {
      handleSubmit,
      pristine,
      submitting,
      reset,
      cancelForm,
      submitLabel,
      disableFields
    } = this.props;
    let tenantid = (this.props.initialValues ? this.props.initialValues.id : null);
    return (

        <Form inline>

{(submitLabel==='Add' ? 'Add ' :
                 (submitLabel==='Save' ? 'Edit ' :
                   (submitLabel === 'Delete' ? 'Delete ' : '') : '') : '')}
          Tenant

          <Row>
            <Col componentClass={ControlLabel} sm={2}>
              Name
            </Col>
            <Col sm={10}>
              <Field name="name" component="input" type='text' disabled={disableFields} placeholder="Tenant's name" />
            </Col>
          </Row>

          <Row>
            <Col componentClass={ControlLabel} sm={2}>
              Description
            </Col>
            <Col sm={10}>
              <Field name="description" component="input" type='text' disabled={disableFields} placeholder='Description of this tenant' />
            </Col>
          </Row>

          <ButtonGroup>
            <Button bsStyle='primary' disabled={pristine || submitting} onClick={handleSubmit}>{submitLabel} Tenant</Button>
            <Button disabled={ pristine || submitting } onClick={reset}>Reset</Button>
            <Button disabled={submitting} onClick={cancelForm}>Cancel</Button>
          </ButtonGroup>
        </Form>

        <ModuleSelector tenantid={tenantid} />

    );
  }
}

export default reduxForm(
  {
    form: 'tenantForm'
  }
)(TenantForm);
<commit_msg>Avoids premature back-end request for tenant's modules.<commit_after>import React, { Component, PropTypes } from 'react';
import { Grid, Container, Row, Col, Form, FormGroup, FormControl, ControlLabel, Input, Button, ButtonGroup, Glyphicon } from 'react-bootstrap';
import {Field, reduxForm} from 'redux-form';
import ModuleList from '../modules/ModuleList';
import ModuleSelector from './ModuleSelector';

class TenantForm extends Component {
  static propTypes = {
    handleSubmit: PropTypes.func.isRequired,
    cancelForm: PropTypes.func.isRequired,
    submitLabel: PropTypes.string,
    disableFields: PropTypes.bool
  };

  static defaultProps = {
    submitLabel: 'Submit',
    disableFields: false,
    tenantModules: []
  };

  render() {
    const {
      handleSubmit,
      pristine,
      submitting,
      reset,
      cancelForm,
      submitLabel,
      disableFields
    } = this.props;
    let tenantid = (this.props.initialValues ? this.props.initialValues.id : null);
    return (

        <Form inline>

{(submitLabel==='Add' ? 'Add ' :
                 (submitLabel==='Save' ? 'Edit ' :
                   (submitLabel === 'Delete' ? 'Delete ' : '') : '') : '')}
          Tenant

          <Row>
            <Col componentClass={ControlLabel} sm={2}>
              Name
            </Col>
            <Col sm={10}>
              <Field name="name" component="input" type='text' disabled={disableFields} placeholder="Tenant's name" />
            </Col>
          </Row>

          <Row>
            <Col componentClass={ControlLabel} sm={2}>
              Description
            </Col>
            <Col sm={10}>
              <Field name="description" component="input" type='text' disabled={disableFields} placeholder='Description of this tenant' />
            </Col>
          </Row>

          <ButtonGroup>
            <Button bsStyle='primary' disabled={pristine || submitting} onClick={handleSubmit}>{submitLabel} Tenant</Button>
            <Button disabled={ pristine || submitting } onClick={reset}>Reset</Button>
            <Button disabled={submitting} onClick={cancelForm}>Cancel</Button>
          </ButtonGroup>
        </Form>

        {tenantid ? <ModuleSelector tenantid={tenantid} /> : null}

    );
  }
}

export default reduxForm(
  {
    form: 'tenantForm'
  }
)(TenantForm);
<|endoftext|>


<commit_before>/**
 * Component Class
 * The base class for all ui components
 *
 * @class UI.Component
 * @extends {UI}
 * @return {parent} Class
 * @example (start code)	new UI.Context(object); (end)
 * @author [moolego,r2d2]
 * @copyright © 1999-2015 - Jerome D. Vial. All Rights reserved.
 */
define([
	'UI/Component/Binding',
	'UI/Component/Method',
	'UI/Component/Location',
	'UI/Component/Drag',
	'UI/Component/Resize'
], function(
	Binding,
	Method,
	Location,
	Drag,
	Resize
) {

	var _log = __debug('ui:component');

	var exports = new Class({

		Implements: [
			Events,
			Options,
			Binding,
			Method,
			Location,
			Drag,
			Resize
		],

		name: 'component',

		component: 'component',

		options: {
			lib: 'ui',
			prefix: 'ui-',

			component: 'component',
			name: 'component',
			type: null,
			element: {
				attr: ['class', 'styles', 'events', 'id', 'name', 'html', 'title'],
				tag: 'span',
				type: null
			}
		},

		/**
		 * Constructor
		 * @param  {Object} options [description]
		 * @return {Object}         [description]
		 */
		initialize: function(options) {
			this.setOptions(options);

			this.fireEvent('init');

			this._initOptions();
			this._initElement();
			this._initEvents();
			this._initBinding();

			return this;
		},

		/**
		 * Setter for the state of the component
		 * @param {string} state active/disable etc...
		 */
		setState: function(state) {
			this.element.removeClass('state-' + this.state);

			if (state) {
				this.element.addClass('state-' + state);
			}

			this.state = state;
			this.fireEvent('state', state);

			return this;
		},

		/**
		 * [addComponent description]
		 * @param {Object} node
		 */
		addComponent: function(node) {
			_log.debug('addComponent', node);
			if (!node.component) {
				node.component = 'container';
			}

			node.container = this.element;
			node.main = this.main;

			//_log.debug(node);

			var container = new UI[node.component.capitalize()](node);

			this.addEvent('resize', function() {
				container.fireEvent('resize');
			});

			this.node.push(container);
			this.layout[this.main][container.name] = container;
			//ui.node[this.main][node.name] = container;
		},

		/**
		 * [_initOptions description]
		 * @return {void}
		 */
		_initOptions: function() {
			var opts = this.options;
			//this.name = this.options.name;
			this.main = opts.main || opts.name;

			//ui.node = ui.node || {};
			//ui.node[this.main] = ui.node[this.main] || {};

			this.layout = opts.layout || {};
			this.layout[this.main] = this.layout[this.main] || {};

			this.dragHandlers = opts.dragHandlers || [];
		},

		/**
		 * [_initState description]
		 * @return {void}
		 */
		_initState: function() {
			this.setState(this.options.state);
		},

		/**
		 * [_initElement description]
		 * @return {void}
		 */
		_initElement: function() {
			_log.debug('_initElement');

			var opts = this.options;

			this.fireEvent('create');

			this._initElementType();
			var prop = this._initProps();

			var tag = opts.tag || opts.element.tag;
			//var name = opts.name || opts.element.name;

			var element = new Element(tag, prop);

			element.store('_instance', this);

			this.element = element;
			this.content = element;

			this.fireEvent('created');

			if (opts.container && opts.container !== 'window') {
				//_log.debug('_initElement', opts.name, opts.container);
				this.inject(opts.container);
				this.fireEvent('injected');
			}

			this._initState();
			this._initClass();
		},

		/**
		 * [_initProps description]
		 * @return {Object}
		 */
		_initProps: function() {
			_log.debug('_initProps');

			var opts = this.options;
			var prop = {};
			var props = [
				'id', 'name', 'type',
				'klass', 'styles',
				'html', 'title',
				'events'
			];
			//var cuts = ['name', 'tag'];

			for (var i = 0; i < props.length; i++) {
				var name = props[i];

				if (name === 'klass') {
					name = 'class';
				}

				//_log.debug('-', name, props[i]);

				if (opts.element.attr[name]) {
					prop[name] = opts.element.attr[props[i]];
				}
			}

			return prop;
		},

		/**
		 * [_initElementType description]
		 * @return {void}
		 */
		_initElementType: function() {},

		/**
		 * [_initClass description]
		 * @return {void}
		 */
		_initClass: function() {
			var opts = this.options;

			//this.element.addClass(opts.prefix + opts.name);
			var klass = opts.klass || opts.element.klass;

			if (klass) {
				this.element.addClass(klass);
			}

			if (opts.type && typeOf(opts.type) !== undefined) {
				this.element.addClass('type-' + opts.type);
			}

			if (opts.state && typeOf(opts.state) !== undefined) {
				this.element.addClass('state-' + opts.state);
			}
		},

		/**
		 * [_initEvents description]
		 * @return {void}
		 */
		_initEvents: function() {
			//_log.debug('_initEvents');
			var self = this;
			var opts = this.options;

			this.addEvents({
				/**
				 * @ignore
				 */
				injected: function() {
					if (opts.resizable && self._initResizer) {
						self._initResizer();
					}
				},
				/**
				 * @ignore
				 */
				device: function(device) {
					//_log.debug('device', device);
					self.device = device;
				}
			});

			if (this.options.draggable && this.enableDrag) {
				this.enableDrag();
			}
		},

		/**
		 * [getName description]
		 * @return {string} name
		 */
		getName: function() {
			return this.options.name || this.name;
		},

		/**
		 * set html to element
		 * @param {string} source - (string) source's html
		 * @return {Object}
		 * @deprecated Use setContent instead
		 */
		setHtmlContent: function(source) {
			this.content.set('html', source);
			this.fireEvent('loadComplete');
			this.fireEvent('resize');

			return this;
		},

		/**
		 * set content of the element
		 * @param {string} content [description]
		 */
		setContent: function(content) {
			this.content.set('html', content);

			this.fireEvent('resize');

			return this;
		},

		/**
		 * [inject description]
		 * @param  {Object} container
		 * @param  {string} position
		 * @return {Object}
		 */
		inject: function(container, position) {
			_log.debug('inject', container, position);

			this.fireEvent('inject');

			if (typeOf(container) === 'element') {
				this.container = container;
			} else if (typeOf(container) === 'object') {
				if (container.element) {
					this.container = container.element;
				}
			}

			//_log.debug('container', container);
			if (container && container.component !== 'window') {
				//_log.debug('element', this.element, this.container);
				//if (!this.container )
				this.element.inject(this.container, position);
				/*this.element
				else this.element.inject(this.element, position);*/
			}

			if (this.setSize) {
				this.setSize();
			}

			//this.size = this.element.getSize();
			//ui.controller.element.register(this);

			this.isInjected = true;
			this.fireEvent('injected');

			return this;
		}
	});

	return exports;
});
<commit_msg>fix component setState<commit_after>/**
 * Component Class
 * The base class for all ui components
 *
 * @class UI.Component
 * @extends {UI}
 * @return {parent} Class
 * @example (start code)	new UI.Context(object); (end)
 * @author [moolego,r2d2]
 * @copyright © 1999-2015 - Jerome D. Vial. All Rights reserved.
 */
define([
	'UI/Component/Binding',
	'UI/Component/Method',
	'UI/Component/Location',
	'UI/Component/Drag',
	'UI/Component/Resize'
], function(
	Binding,
	Method,
	Location,
	Drag,
	Resize
) {

	var _log = __debug('ui:component');

	var exports = new Class({

		Implements: [
			Events,
			Options,
			Binding,
			Method,
			Location,
			Drag,
			Resize
		],

		name: 'component',

		component: 'component',

		options: {
			lib: 'ui',
			prefix: 'ui-',

			component: 'component',
			name: 'component',
			type: null,
			element: {
				attr: ['class', 'styles', 'events', 'id', 'name', 'html', 'title'],
				tag: 'span',
				type: null
			}
		},

		/**
		 * Constructor
		 * @param  {Object} options [description]
		 * @return {Object}         [description]
		 */
		initialize: function(options) {
			this.setOptions(options);

			this.fireEvent('init');

			this._initOptions();
			this._initElement();
			this._initEvents();
			this._initBinding();

			return this;
		},

		/**
		 * Setter for the state of the component
		 * @param {string} state active/disable etc...
		 */
		setState: function(state) {
			_log.debug('setState', state, this);

			if (state === null) {
				state = 'disabled';
			}

			this.element.removeClass('state-' + this.state);

			if (state) {
				this.element.addClass('state-' + state);
			}

			this.state = state;
			this.fireEvent('state', state);

			return this;
		},

		/**
		 * [addComponent description]
		 * @param {Object} node
		 */
		addComponent: function(node) {
			_log.debug('addComponent', node);
			if (!node.component) {
				node.component = 'container';
			}

			node.container = this.element;
			node.main = this.main;

			//_log.debug(node);

			var container = new UI[node.component.capitalize()](node);

			this.addEvent('resize', function() {
				container.fireEvent('resize');
			});

			this.node.push(container);
			this.layout[this.main][container.name] = container;
			//ui.node[this.main][node.name] = container;
		},

		/**
		 * [_initOptions description]
		 * @return {void}
		 */
		_initOptions: function() {
			var opts = this.options;
			//this.name = this.options.name;
			this.main = opts.main || opts.name;

			//ui.node = ui.node || {};
			//ui.node[this.main] = ui.node[this.main] || {};

			this.layout = opts.layout || {};
			this.layout[this.main] = this.layout[this.main] || {};

			this.dragHandlers = opts.dragHandlers || [];
		},

		/**
		 * [_initState description]
		 * @return {void}
		 */
		_initState: function() {
			if (this.options.state) {
				this.setState(this.options.state);
			}
		},

		/**
		 * [_initElement description]
		 * @return {void}
		 */
		_initElement: function() {
			_log.debug('_initElement');

			var opts = this.options;

			this.fireEvent('create');

			this._initElementType();
			var prop = this._initProps();

			var tag = opts.tag || opts.element.tag;
			//var name = opts.name || opts.element.name;

			var element = new Element(tag, prop);

			element.store('_instance', this);

			this.element = element;
			this.content = element;

			this.fireEvent('created');

			if (opts.container && opts.container !== 'window') {
				//_log.debug('_initElement', opts.name, opts.container);
				this.inject(opts.container);
				this.fireEvent('injected');
			}

			this._initState();
			this._initClass();
		},

		/**
		 * [_initProps description]
		 * @return {Object}
		 */
		_initProps: function() {
			_log.debug('_initProps');

			var opts = this.options;
			var prop = {};
			var props = [
				'id', 'name', 'type',
				'klass', 'styles',
				'html', 'title',
				'events'
			];
			//var cuts = ['name', 'tag'];

			for (var i = 0; i < props.length; i++) {
				var name = props[i];

				if (name === 'klass') {
					name = 'class';
				}

				//_log.debug('-', name, props[i]);

				if (opts.element.attr[name]) {
					prop[name] = opts.element.attr[props[i]];
				}
			}

			return prop;
		},

		/**
		 * [_initElementType description]
		 * @return {void}
		 */
		_initElementType: function() {},

		/**
		 * [_initClass description]
		 * @return {void}
		 */
		_initClass: function() {
			var opts = this.options;

			//this.element.addClass(opts.prefix + opts.name);
			var klass = opts.klass || opts.element.klass;

			if (klass) {
				this.element.addClass(klass);
			}

			if (opts.type && typeOf(opts.type) !== undefined) {
				this.element.addClass('type-' + opts.type);
			}

			if (opts.state && typeOf(opts.state) !== undefined) {
				this.element.addClass('state-' + opts.state);
			}
		},

		/**
		 * [_initEvents description]
		 * @return {void}
		 */
		_initEvents: function() {
			//_log.debug('_initEvents');
			var self = this;
			var opts = this.options;

			this.addEvents({
				/**
				 * @ignore
				 */
				injected: function() {
					if (opts.resizable && self._initResizer) {
						self._initResizer();
					}
				},
				/**
				 * @ignore
				 */
				device: function(device) {
					//_log.debug('device', device);
					self.device = device;
				}
			});

			if (this.options.draggable && this.enableDrag) {
				this.enableDrag();
			}
		},

		/**
		 * [getName description]
		 * @return {string} name
		 */
		getName: function() {
			return this.options.name || this.name;
		},

		/**
		 * set html to element
		 * @param {string} source - (string) source's html
		 * @return {Object}
		 * @deprecated Use setContent instead
		 */
		setHtmlContent: function(source) {
			this.content.set('html', source);
			this.fireEvent('loadComplete');
			this.fireEvent('resize');

			return this;
		},

		/**
		 * set content of the element
		 * @param {string} content [description]
		 */
		setContent: function(content) {
			this.content.set('html', content);

			this.fireEvent('resize');

			return this;
		},

		/**
		 * [inject description]
		 * @param  {Object} container
		 * @param  {string} position
		 * @return {Object}
		 */
		inject: function(container, position) {
			_log.debug('inject', container, position);

			this.fireEvent('inject');

			if (typeOf(container) === 'element') {
				this.container = container;
			} else if (typeOf(container) === 'object') {
				if (container.element) {
					this.container = container.element;
				}
			}

			//_log.debug('container', container);
			if (container && container.component !== 'window') {
				//_log.debug('element', this.element, this.container);
				//if (!this.container )
				this.element.inject(this.container, position);
				/*this.element
				else this.element.inject(this.element, position);*/
			}

			if (this.setSize) {
				this.setSize();
			}

			//this.size = this.element.getSize();
			//ui.controller.element.register(this);

			this.isInjected = true;
			this.fireEvent('injected');

			return this;
		}
	});

	return exports;
});
<|endoftext|>


<commit_before>require('babel-register');

const gulp = require('gulp');
const livereload = require('gulp-livereload');
const metalsmith = require('gulp-metalsmith');
const htmlmin = require('gulp-htmlmin');

const layouts = require('metalsmith-layouts');
const markdown = require('metalsmith-markdown');
const permalinks = require('metalsmith-permalinks');
const discover_hbs_helpers = require('metalsmith/discover-hbs-helpers');
const each = require('metalsmith/each');

const del = require('del');
const path = require('path');
const uniq = require('lodash/uniq');
const {cat} = require('core/functional');

const env = require('gulp/env');
const content_env = env.content;

gulp
	.task('content-clean', [], () => del(path.join(content_env.outputDir, '**/.html')))
	.task('content', ['content-clean'], () => gulp.src(path.join(content_env.matterDir, '**'))
		.pipe(metalsmith({
			metadata: content_env.metadata,
			use: [
				discover_hbs_helpers({
					directory: content_env.helpersDir
				}),
				each({
					iteratee: (file, metadata, next) => {
						metadata.styles =
							uniq(cat(['style'], metadata.styles || []))
								.map(style => env.sass.prefix(style));
						metadata.applets =
							uniq(metadata.applets || [])
								.map(applet => env.applets.prefix(applet));
						next();
					}
				}),
				markdown(),
				permalinks({
					pattern: ':collection/:title'
				}),
				layouts({
					directory: content_env.layoutsDir,
					partials: content_env.partialsDir,
					engine: 'handlebars',
					default: 'index.hbs'
				})
			]
		}))
		.pipe(htmlmin({collapseWhitespace: true}))
		.pipe(gulp.dest(content_env.outputDir))
		.pipe(livereload())
	)
	.task('content-watch', ['content'], () => gulp.watch(
		[
			path.join(content_env.matterDir, '**'),
			path.join(content_env.layoutsDir, '**/*.hbs'),
			path.join(content_env.partialsDir, '**/*.hbs'),
			path.join(content_env.helpersDir, '**/*.js')
		],
		['content']
	));

module.exports = {
	build: 'content',
	clean: 'content-clean',
	watch: 'content-watch'
};
<commit_msg>apply navigation plugin<commit_after>require('babel-register');

const gulp = require('gulp');
const livereload = require('gulp-livereload');
const metalsmith = require('gulp-metalsmith');
const htmlmin = require('gulp-htmlmin');

const layouts = require('metalsmith-layouts');
const markdown = require('metalsmith-markdown');
const permalinks = require('metalsmith-permalinks');
const discover_hbs_helpers = require('metalsmith/discover-hbs-helpers');
const each = require('metalsmith/each');
const navigation = require('metalsmith/navigation');

const del = require('del');
const path = require('path');
const uniq = require('lodash/uniq');
const {cat} = require('core/functional');

const env = require('gulp/env');
const content_env = env.content;

gulp
	.task('content-clean', [], () => del(path.join(content_env.outputDir, '**/.html')))
	.task('content', ['content-clean'], () => gulp.src(path.join(content_env.matterDir, '**'))
		.pipe(metalsmith({
			metadata: content_env.metadata,
			use: [
				discover_hbs_helpers({
					directory: content_env.helpersDir
				}),
				each({
					iteratee: (file, metadata, next) => {
						metadata.styles =
							uniq(cat(['style'], metadata.styles || []))
								.map(style => env.sass.prefix(style));
						metadata.applets =
							uniq(metadata.applets || [])
								.map(applet => env.applets.prefix(applet));
						next();
					}
				}),
				markdown(),
				permalinks({
					pattern: ':collection/:title'
				}),
				navigation(),
				layouts({
					directory: content_env.layoutsDir,
					partials: content_env.partialsDir,
					engine: 'handlebars',
					default: 'index.hbs'
				})
			]
		}))
		.pipe(htmlmin({collapseWhitespace: true}))
		.pipe(gulp.dest(content_env.outputDir))
		.pipe(livereload())
	)
	.task('content-watch', ['content'], () => gulp.watch(
		[
			path.join(content_env.matterDir, '**'),
			path.join(content_env.layoutsDir, '**/*.hbs'),
			path.join(content_env.partialsDir, '**/*.hbs'),
			path.join(content_env.helpersDir, '**/*.js')
		],
		['content']
	));

module.exports = {
	build: 'content',
	clean: 'content-clean',
	watch: 'content-watch'
};
<|endoftext|>


<commit_before>/**
 * Created by kevinkreuzer on 14.05.17.
 */

export default class LoginController {

    constructor(authService, $mdDialog) {
        this.authService = authService
        this.$mdDialog = $mdDialog
    }

    login() {
        this.isLoginInProcess = true
        this.authService.login(this.username, this.password)
            .then(_ => {
                this.isLoginInProcess = false
                this.closeDialog()
            })
    }

    closeDialog() {
        this.$mdDialog.cancel();
    }
}
<commit_msg>kk: Fix JSHint Warning<commit_after>/**
 * Created by kevinkreuzer on 14.05.17.
 */

export default class LoginController {

    constructor(authService, $mdDialog) {
        this.authService = authService
        this.$mdDialog = $mdDialog
    }

    login() {
        this.isLoginInProcess = true
        this.authService.login(this.username, this.password)
            .then(() => {
                this.isLoginInProcess = false
                this.closeDialog()
            })
    }

    closeDialog() {
        this.$mdDialog.cancel();
    }
}
<|endoftext|>


<commit_before>
Ext.ns('Ext.ux', 'Ext.ux.direct');

/**
 * @namespace   Ext.ux.direct
 * @class       Ext.ux.direct.ZendFrameworkProvider
 * @extends     Ext.direct.RemotingProvider
 * @author      Peter
 * @author      Based on work from Cornelius Weiss <c.weiss@metaways.de>
 * @copyright   Based on Copyright (c) 2009 Metaways Infosystems GmbH (http://www.metaways.de)
 *
 * Ext.Direct provider for seamless integration with Zend_Json_Server
 *
 *  Ext.Direct.addProvider(Ext.apply(Ext.app.JSONRPC_API, {
        'type'     : 'zfprovider',
        'url'      : Ext.app.JSONRPC_API
    }));
 *
 */
Ext.ux.direct.ZendFrameworkProvider = Ext.extend(Ext.direct.RemotingProvider, {

    // private
    getCallData: function(t){
        return {
            jsonrpc: '2.0',
            method: t.action + '.' + t.method,
            params: t.data,
            id: t.tid
        };
    },

	// private
    onData: function(opt, success, xhr) {
		var rpcresponse;
		try {
			rpcresponse = Ext.decode(xhr.responseText);
		} catch(e){
			if(console && console.error){
				console.error('Non-valid JSON encountered. Ignoring: ' + e.message || '');
				console.log(xhr.responseText);
			}
		}

		// batch of results:
		if (Ext.isArray(rpcresponse)) {
			var rpcresponses = rpcresponse;

			xhr.responseText = [];
			Ext.each(rpcresponses, function(rpcresponse){
				xhr.responseText.push({
					type: rpcresponse ? rpcresponse.result ? 'rpc' : 'exception' : 'exception',
					error: rpcresponse ? rpcresponse.error ? rpcresponse.error : null : 'Network error',
					result: rpcresponse ? rpcresponse.result : null,
					tid: rpcresponse ? rpcresponse.id : null
				});
			});
		// single result:
		} else {
			xhr.responseText= {
				type: rpcresponse ? rpcresponse.result ? 'rpc' : 'exception' : 'exception',
				error: rpcresponse ? rpcresponse.error ? rpcresponse.error : null : 'Network error',
				result: rpcresponse ? rpcresponse.result : null,
				tid: rpcresponse ? rpcresponse.id : null
			};
		}
        Ext.ux.direct.ZendFrameworkProvider.superclass.onData.apply(this, arguments);
    }

});

Ext.Direct.PROVIDERS.zfprovider = Ext.ux.direct.ZendFrameworkProvider;
<commit_msg>Log invalid JSON<commit_after>
Ext.ns('Ext.ux', 'Ext.ux.direct');

/**
 * @namespace   Ext.ux.direct
 * @class       Ext.ux.direct.ZendFrameworkProvider
 * @extends     Ext.direct.RemotingProvider
 * @author      Peter
 * @author      Based on work from Cornelius Weiss <c.weiss@metaways.de>
 * @copyright   Based on Copyright (c) 2009 Metaways Infosystems GmbH (http://www.metaways.de)
 *
 * Ext.Direct provider for seamless integration with Zend_Json_Server
 *
 *  Ext.Direct.addProvider(Ext.apply(Ext.app.JSONRPC_API, {
        'type'     : 'zfprovider',
        'url'      : Ext.app.JSONRPC_API
    }));
 *
 */
Ext.ux.direct.ZendFrameworkProvider = Ext.extend(Ext.direct.RemotingProvider, {

    // private
    getCallData: function(t){
        return {
            jsonrpc: '2.0',
            method: t.action + '.' + t.method,
            params: t.data,
            id: t.tid
        };
    },

	// private
    onData: function(opt, success, xhr) {
		var rpcresponse;
		try {
			rpcresponse = Ext.decode(xhr.responseText);
		} catch(e){
			if(console && console.error){
				console.error('Non-valid JSON encountered. Ignoring: ' + e.message || '');
				console.error(xhr.responseText);
			}
		}

		// batch of results:
		if (Ext.isArray(rpcresponse)) {
			var rpcresponses = rpcresponse;

			xhr.responseText = [];
			Ext.each(rpcresponses, function(rpcresponse){
				xhr.responseText.push({
					type: rpcresponse ? rpcresponse.result ? 'rpc' : 'exception' : 'exception',
					error: rpcresponse ? rpcresponse.error ? rpcresponse.error : null : 'Network error',
					result: rpcresponse ? rpcresponse.result : null,
					tid: rpcresponse ? rpcresponse.id : null
				});
			});
		// single result:
		} else {
			xhr.responseText= {
				type: rpcresponse ? rpcresponse.result ? 'rpc' : 'exception' : 'exception',
				error: rpcresponse ? rpcresponse.error ? rpcresponse.error : null : 'Network error',
				result: rpcresponse ? rpcresponse.result : null,
				tid: rpcresponse ? rpcresponse.id : null
			};
		}
        Ext.ux.direct.ZendFrameworkProvider.superclass.onData.apply(this, arguments);
    }

});

Ext.Direct.PROVIDERS.zfprovider = Ext.ux.direct.ZendFrameworkProvider;
<|endoftext|>


<commit_before>// Includes file dependencies
define([
    "jquery",
    "backbone",
    "parse",
    "backform",
    "../helpers/PromiseFailReport"
], function( $, Backbone, Parse, Backform, PromiseFailReport) {

    // Extends Backbone.View
    var View = Backbone.View.extend( {

        // The View Constructor
        initialize: function () {
            _.bindAll(this, "render", "submit");
        },

        register: function(troupe, user) {
            var self = this;
            self.troupe = troupe;
            self.user = user;

            var roles = {};
            return Parse.Promise.when(self.troupe.get_roles()).then(function (inroles) {
                roles = inroles;
                var promises = _.map(self.troupe.title_options, function (title) {
                    var u = roles[title].getUsers();
                    var q = u.query();
                    q.equalTo("objectId", self.user.id);
                    return q.count().then(function (count) {
                        roles[title] = count;
                        console.log("Setting up role " + title + " count with " + count);
                    })
                });
                return Parse.Promise.when(promises);
            }).then(function () {
                var role = _.findKey(roles, function (count, key, rolesagain) {
                    console.log("Got " + count + " for " + key);
                    if (_.isFinite(count) && count > 0) {
                        return true;
                    }
                    return false;
                })
                console.log("I found this user with a role of " + role);
                return Parse.Promise.as(role);
            }).then(function (role) {
                self.user.set("role", role);
                self.form = new Backform.Form({
                    el: "#troupe-edit-staff-form",
                    model: self.user,
                    fields: [
                        {name: "username", label: "Username", control: "uneditable-input"},
                        {name: "realname", label: "Name", control: "uneditable-input"},
                        {
                            name: "role",
                            label: "Role",
                            control: "select",
                            options: [
                                {label: "Lead Storyteller", value: "LST"},
                                {label: "Assistant Storyteller", value: "AST"},
                                {label: "Narrator", value: "Narrator"},
                                {label: "Not on Staff", value: undefined}
                            ]
                        },
                        {control: "spacer"},
                        {control: "button", label: "Save"}
                    ],
                });
                self.render();
            }).fail(function(error) {
                if (_.isArray(error)) {
                    _.each(error, function(e) {
                        console.log("Something failed" + e.message);
                    })
                } else {
                    console.log("error updating experience" + error.message);
                }
            });
        },

        events: {
            "submit": "submit",
        },

        submit: function (e) {
            var self = this;
            e.preventDefault();
            var role = self.user.get("role");
            var roles_to_remove = _.slice(self.troupe.title_options),
                roles_to_add = [];
            if (!_.isUndefined(role)) {
                roles_to_add.push(role);
                roles_to_remove = _.xor(roles_to_remove, roles_to_add);
            }

            var alter_roles = function (roles) {
                _.each(roles_to_remove, function (title) {
                    var u = roles[title].getUsers();
                    console.log(u);
                    u.remove(self.user);
                });
                _.each(roles_to_add, function (title) {
                    roles[title].getUsers().add(self.user);
                })
                var to_save = _.values(roles);
                var promises = _.map(to_save, function (s) {
                    return s.save().fail(PromiseFailReport);
                })
                return Parse.Promise.when(promises);
            }

            return Parse.Promise
                .when(self.troupe.get_roles())
                .then(alter_roles)
                .then(function () {
                    return self.troupe.get_generic_roles();
                })
                .then(alter_roles)
                .always(function () {
                    window.location.hash = "#troupe/" + self.troupe.id;
                }).fail(PromiseFailReport);
        },

        // Renders all of the Category models on the UI
        render: function() {
            var self = this;

            self.form.render();
            this.$el.enhanceWithin();

            // Maintains chainability
            return this;

        }

    } );

    // Returns the View class
    return View;

} );
<commit_msg>Allow removal of staff members<commit_after>// Includes file dependencies
define([
    "jquery",
    "backbone",
    "parse",
    "backform",
    "../helpers/PromiseFailReport"
], function( $, Backbone, Parse, Backform, PromiseFailReport) {

    // Extends Backbone.View
    var View = Backbone.View.extend( {

        // The View Constructor
        initialize: function () {
            _.bindAll(this, "render", "submit");
        },

        register: function(troupe, user) {
            var self = this;
            self.troupe = troupe;
            self.user = user;

            var roles = {};
            return Parse.Promise.when(self.troupe.get_roles()).then(function (inroles) {
                roles = inroles;
                var promises = _.map(self.troupe.title_options, function (title) {
                    var u = roles[title].getUsers();
                    var q = u.query();
                    q.equalTo("objectId", self.user.id);
                    return q.count().then(function (count) {
                        roles[title] = count;
                        console.log("Setting up role " + title + " count with " + count);
                    })
                });
                return Parse.Promise.when(promises);
            }).then(function () {
                var role = _.findKey(roles, function (count, key, rolesagain) {
                    console.log("Got " + count + " for " + key);
                    if (_.isFinite(count) && count > 0) {
                        return true;
                    }
                    return false;
                })
                console.log("I found this user with a role of " + role);
                return Parse.Promise.as(role);
            }).then(function (role) {
                self.user.set("role", role);
                self.form = new Backform.Form({
                    el: "#troupe-edit-staff-form",
                    model: self.user,
                    fields: [
                        {name: "username", label: "Username", control: "uneditable-input"},
                        {name: "realname", label: "Name", control: "uneditable-input"},
                        {
                            name: "role",
                            label: "Role",
                            control: "select",
                            options: [
                                {label: "Lead Storyteller", value: "LST"},
                                {label: "Assistant Storyteller", value: "AST"},
                                {label: "Narrator", value: "Narrator"},
                                {label: "Not on Staff", value: "None"}
                            ]
                        },
                        {control: "spacer"},
                        {control: "button", label: "Save"}
                    ],
                });
                self.render();
            }).fail(function(error) {
                if (_.isArray(error)) {
                    _.each(error, function(e) {
                        console.log("Something failed" + e.message);
                    })
                } else {
                    console.log("error updating experience" + error.message);
                }
            });
        },

        events: {
            "submit": "submit",
        },

        submit: function (e) {
            var self = this;
            e.preventDefault();
            var role = self.user.get("role");
            var roles_to_remove = _.slice(self.troupe.title_options),
                roles_to_add = [];
            if (role != "None") {
                roles_to_add.push(role);
                roles_to_remove = _.xor(roles_to_remove, roles_to_add);
            }

            var alter_roles = function (roles) {
                _.each(roles_to_remove, function (title) {
                    var u = roles[title].getUsers();
                    console.log(u);
                    u.remove(self.user);
                });
                _.each(roles_to_add, function (title) {
                    roles[title].getUsers().add(self.user);
                })
                var to_save = _.values(roles);
                var promises = _.map(to_save, function (s) {
                    return s.save().fail(PromiseFailReport);
                })
                return Parse.Promise.when(promises);
            }

            return Parse.Promise
                .when(self.troupe.get_roles())
                .then(alter_roles)
                .then(function () {
                    return self.troupe.get_generic_roles();
                })
                .then(alter_roles)
                .always(function () {
                    window.location.hash = "#troupe/" + self.troupe.id;
                }).fail(PromiseFailReport);
        },

        // Renders all of the Category models on the UI
        render: function() {
            var self = this;

            self.form.render();
            this.$el.enhanceWithin();

            // Maintains chainability
            return this;

        }

    } );

    // Returns the View class
    return View;

} );
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.3.3
(function() {
  var Hem, argv, compilers, css, fs, help, optimist, path, pkg, specs, strata;

  path = require('path');

  fs = require('fs');

  optimist = require('optimist');

  strata = require('strata');

  compilers = require('./compilers');

  pkg = require('./package');

  css = require('./css');

  specs = require('./specs');

  argv = optimist.usage(['  usage: hem COMMAND', '    server  start a dynamic development server', '    build   serialize application to disk', '    watch   build & watch disk for changes'].join("\n")).alias('p', 'port').alias('d', 'debug').argv;

  help = function() {
    optimist.showHelp();
    return process.exit();
  };

  Hem = (function() {

    Hem.exec = function(command, options) {
      return (new this(options)).exec(command);
    };

    Hem.include = function(props) {
      var key, value, _results;
      _results = [];
      for (key in props) {
        value = props[key];
        _results.push(this.prototype[key] = value);
      }
      return _results;
    };

    Hem.prototype.compilers = compilers;

    Hem.prototype.options = {
      slug: './slug.json',
      css: './css',
      libs: [],
      "public": './public',
      paths: ['./app'],
      dependencies: [],
      port: process.env.PORT || argv.port || 9294,
      cssPath: '/application.css',
      jsPath: '/application.js',
      test: './test',
      testPublic: './test/public',
      testPath: '/test',
      specs: './test/specs',
      specsPath: '/specs.js'
    };

    function Hem(options) {
      var key, value, _ref;
      if (options == null) {
        options = {};
      }
      for (key in options) {
        value = options[key];
        this.options[key] = value;
      }
      _ref = this.readSlug();
      for (key in _ref) {
        value = _ref[key];
        this.options[key] = value;
      }
    }

    Hem.prototype.server = function() {
      var _this = this;
      strata.use(strata.contentLength);
      strata.get(this.options.cssPath, this.cssPackage().createServer());
      strata.get(this.options.jsPath, this.hemPackage().createServer());
      strata.map(this.options.testPath, function(app) {
        if (path.existsSync(_this.options.specs)) {
          app.get(_this.options.specsPath, _this.specsPackage().createServer());
        }
        if (path.existsSync(_this.options.testPublic)) {
          return app.use(strata.file, _this.options.testPublic, ['index.html', 'index.htm']);
        }
      });
      if (path.existsSync(this.options["public"])) {
        strata.use(strata.file, this.options["public"], ['index.html', 'index.htm']);
      }
      return strata.run({
        port: this.options.port
      });
    };

    Hem.prototype.build = function() {
      var source;
      source = this.hemPackage().compile(!argv.debug);
      fs.writeFileSync(path.join(this.options["public"], this.options.jsPath), source);
      source = this.cssPackage().compile();
      return fs.writeFileSync(path.join(this.options["public"], this.options.cssPath), source);
    };

    Hem.prototype.watch = function() {
      var dir, lib, _i, _len, _ref, _results,
        _this = this;
      this.build();
      _ref = ((function() {
        var _j, _len, _ref, _results1;
        _ref = this.options.libs;
        _results1 = [];
        for (_j = 0, _len = _ref.length; _j < _len; _j++) {
          lib = _ref[_j];
          _results1.push(path.dirname(lib));
        }
        return _results1;
      }).call(this)).concat(this.options.css, this.options.paths);
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        dir = _ref[_i];
        if (!path.existsSync(dir)) {
          continue;
        }
        _results.push(require('watch').watchTree(dir, function(file, curr, prev) {
          if (curr && (curr.nlink === 0 || +curr.mtime !== +(prev != null ? prev.mtime : void 0))) {
            console.log("" + file + " changed.  Rebuilding.");
            return _this.build();
          }
        }));
      }
      return _results;
    };

    Hem.prototype.exec = function(command) {
      if (command == null) {
        command = argv._[0];
      }
      if (!this[command]) {
        return help();
      }
      this[command]();
      switch (command) {
        case 'build':
          return console.log('Built application');
        case 'watch':
          return console.log('Watching application');
      }
    };

    Hem.prototype.readSlug = function(slug) {
      if (slug == null) {
        slug = this.options.slug;
      }
      if (!(slug && path.existsSync(slug))) {
        return {};
      }
      return JSON.parse(fs.readFileSync(slug, 'utf-8'));
    };

    Hem.prototype.cssPackage = function() {
      return css.createPackage(this.options.css);
    };

    Hem.prototype.hemPackage = function() {
      return pkg.createPackage({
        dependencies: this.options.dependencies,
        paths: this.options.paths,
        libs: this.options.libs
      });
    };

    Hem.prototype.specsPackage = function() {
      return specs.createPackage(this.options.specs);
    };

    return Hem;

  })();

  module.exports = Hem;

}).call(this);
<commit_msg>compiled<commit_after>// Generated by CoffeeScript 1.3.3
(function() {
  var Hem, argv, compilers, css, fs, help, optimist, path, pkg, specs, strata;

  path = require('path');

  fs = require('fs');

  optimist = require('optimist');

  strata = require('strata');

  compilers = require('./compilers');

  pkg = require('./package');

  css = require('./css');

  specs = require('./specs');

  argv = optimist.usage(['  usage: hem COMMAND', '    server  start a dynamic development server', '    build   serialize application to disk', '    watch   build & watch disk for changes'].join("\n")).alias('p', 'port').alias('d', 'debug').argv;

  help = function() {
    optimist.showHelp();
    return process.exit();
  };

  Hem = (function() {

    Hem.exec = function(command, options) {
      return (new this(options)).exec(command);
    };

    Hem.include = function(props) {
      var key, value, _results;
      _results = [];
      for (key in props) {
        value = props[key];
        _results.push(this.prototype[key] = value);
      }
      return _results;
    };

    Hem.prototype.compilers = compilers;

    Hem.prototype.options = {
      slug: './slug.json',
      css: './css',
      libs: [],
      "public": './public',
      paths: ['./app'],
      dependencies: [],
      port: process.env.PORT || argv.port || 9294,
      cssPath: '/application.css',
      jsPath: '/application.js',
      test: './test',
      testPublic: './test/public',
      testPath: '/test',
      specs: './test/specs',
      specsPath: '/test/specs.js'
    };

    function Hem(options) {
      var key, value, _ref;
      if (options == null) {
        options = {};
      }
      for (key in options) {
        value = options[key];
        this.options[key] = value;
      }
      _ref = this.readSlug();
      for (key in _ref) {
        value = _ref[key];
        this.options[key] = value;
      }
    }

    Hem.prototype.server = function() {
      var _this = this;
      strata.use(strata.contentLength);
      strata.map(this.options.cssPath, function(app) {
        return app.run(_this.cssPackage().createServer());
      });
      strata.map(this.options.jsPath, function(app) {
        return app.run(_this.hemPackage().createServer());
      });
      if (fs.existsSync(this.options.specs)) {
        strata.map(this.options.specsPath, function(app) {
          return app.run(_this.specsPackage().createServer());
        });
      }
      if (fs.existsSync(this.options.testPublic)) {
        strata.map(this.options.testPath, function(app) {
          return app.use(strata.file, _this.options.testPublic, ['index.html', 'index.htm']);
        });
      }
      if (fs.existsSync(this.options["public"])) {
        strata.use(strata.file, this.options["public"], ['index.html', 'index.htm']);
      }
      return strata.run({
        port: this.options.port
      });
    };

    Hem.prototype.build = function() {
      var source;
      source = this.hemPackage().compile(!argv.debug);
      fs.writeFileSync(path.join(this.options["public"], this.options.jsPath), source);
      source = this.cssPackage().compile();
      return fs.writeFileSync(path.join(this.options["public"], this.options.cssPath), source);
    };

    Hem.prototype.watch = function() {
      var dir, lib, _i, _len, _ref, _results,
        _this = this;
      this.build();
      _ref = ((function() {
        var _j, _len, _ref, _results1;
        _ref = this.options.libs;
        _results1 = [];
        for (_j = 0, _len = _ref.length; _j < _len; _j++) {
          lib = _ref[_j];
          _results1.push(path.dirname(lib));
        }
        return _results1;
      }).call(this)).concat(this.options.css, this.options.paths);
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        dir = _ref[_i];
        if (!fs.existsSync(dir)) {
          continue;
        }
        _results.push(require('watch').watchTree(dir, function(file, curr, prev) {
          if (curr && (curr.nlink === 0 || +curr.mtime !== +(prev != null ? prev.mtime : void 0))) {
            console.log("" + file + " changed.  Rebuilding.");
            return _this.build();
          }
        }));
      }
      return _results;
    };

    Hem.prototype.exec = function(command) {
      if (command == null) {
        command = argv._[0];
      }
      if (!this[command]) {
        return help();
      }
      this[command]();
      switch (command) {
        case 'build':
          return console.log('Built application');
        case 'watch':
          return console.log('Watching application');
      }
    };

    Hem.prototype.readSlug = function(slug) {
      if (slug == null) {
        slug = this.options.slug;
      }
      if (!(slug && fs.existsSync(slug))) {
        return {};
      }
      return JSON.parse(fs.readFileSync(slug, 'utf-8'));
    };

    Hem.prototype.cssPackage = function() {
      return css.createPackage(this.options.css);
    };

    Hem.prototype.hemPackage = function() {
      return pkg.createPackage({
        dependencies: this.options.dependencies,
        paths: this.options.paths,
        libs: this.options.libs
      });
    };

    Hem.prototype.specsPackage = function() {
      return specs.createPackage(this.options.specs);
    };

    return Hem;

  })();

  module.exports = Hem;

}).call(this);
<|endoftext|>


<commit_before>/* eslint no-console: 0 */
'use strict';

const irc = require('irc');

const server = process.env.IRC_SERVER;
const user = process.env.IRC_USER;
const channel = process.env.IRC_CHANNEL;

const client = module.exports.client = new irc.Client(server, user, {
  autoConnect: false,
  autoRejoin: true,
  channels: [channel],
  showErrors: true,
});

client.connect(5, function() {
  console.log(new Date(), '[IRC]', 'Connected!');
});

if (process.env.NODE_ENV !== 'testing') {
  client.on('registered', function clientOnRegisterd(message) {
    console.log(new Date(), '[IRC]', message.args[1]);
  });
}

client.on('error', function clientOnError(error) {
  console.error(error);
  console.error('Shutting Down...');
  process.exit(1);
});

module.exports.notify = function ircPost(nodes, callback) {
  nodes.forEach(function nodesForEach(node) {
    // let name = `[${node.name}](${jenkins}/computer/${node.name})`;

    if (node.offline) {
      client.say(channel, `Jenkins slave ${node.name} is offline`);
    } else {
      client.say(channel, `Jenkins slave ${node.name} is online`);
    }
  });

  callback(null);
};
<commit_msg>Add missing function expression name<commit_after>/* eslint no-console: 0 */
'use strict';

const irc = require('irc');

const server = process.env.IRC_SERVER;
const user = process.env.IRC_USER;
const channel = process.env.IRC_CHANNEL;

const client = module.exports.client = new irc.Client(server, user, {
  autoConnect: false,
  autoRejoin: true,
  channels: [channel],
  showErrors: true,
});

client.connect(5, function clientConnectCb() {
  console.log(new Date(), '[IRC]', 'Connected!');
});

if (process.env.NODE_ENV !== 'testing') {
  client.on('registered', function clientOnRegisterd(message) {
    console.log(new Date(), '[IRC]', message.args[1]);
  });
}

client.on('error', function clientOnError(error) {
  console.error(error);
  console.error('Shutting Down...');
  process.exit(1);
});

module.exports.notify = function ircPost(nodes, callback) {
  nodes.forEach(function nodesForEach(node) {
    // let name = `[${node.name}](${jenkins}/computer/${node.name})`;

    if (node.offline) {
      client.say(channel, `Jenkins slave ${node.name} is offline`);
    } else {
      client.say(channel, `Jenkins slave ${node.name} is online`);
    }
  });

  callback(null);
};
<|endoftext|>


<commit_before>var util = require('util')

var output
var LEVELS = {
  VERBOSE: 1,
  INFO: 2,
  WARN: 3,
  ERROR: 4,
  SILENT: 5
}

module.exports = {
  levels: LEVELS,

  read: function () {
    return output
  },

  reset: function () {
    output = ''
    module.exports.level(LEVELS.INFO)
  },

  level: function (level) {
    for (var l in LEVELS) {
      var methodName = l.toLowerCase()
      if (normalize(level) <= LEVELS[l]) {
        module.exports[methodName] = console.error
      } else {
        module.exports[methodName] = silentLogger
      }
    }
  }
}

module.exports.reset()

// private

function normalize (level) {
  for (var l in LEVELS) {
    if (level === LEVELS[l] ||
      l === String(level).toUpperCase()) {
      return LEVELS[l]
    }
  }

  return LEVELS.INFO
}

function silentLogger () {
  output += util.format.apply(util, arguments) + '\n'
}
<commit_msg>Strip the stacktrace from printed errors<commit_after>var util = require('util')

var output
var LEVELS = {
  VERBOSE: 1,
  INFO: 2,
  WARN: 3,
  ERROR: 4,
  SILENT: 5
}

module.exports = {
  levels: LEVELS,

  read: function () {
    return output
  },

  reset: function () {
    output = ''
    module.exports.level(LEVELS.INFO)
  },

  level: function (level) {
    for (var l in LEVELS) {
      var methodName = l.toLowerCase()
      if (normalize(level) <= LEVELS[l]) {
        module.exports[methodName] = formatError(console.error)
      } else {
        module.exports[methodName] = silentLogger
      }
    }
  }
}

module.exports.reset()

// private

function normalize (level) {
  for (var l in LEVELS) {
    if (level === LEVELS[l] ||
      l === String(level).toUpperCase()) {
      return LEVELS[l]
    }
  }

  return LEVELS.INFO
}

function formatError (f) {
  return function () {
    f.apply(null, Array.from(arguments, function (arg) {
      return arg instanceof Error ? arg.message : arg
    }))
  }
}

function silentLogger () {
  output += util.format.apply(util, arguments) + '\n'
}
<|endoftext|>