<commit_before>/* jshint indent: false */ // TODO: ENYO-3311
/**
 * Represents a directory or a file in {HermesFileTree}
 *
 * @class hermes.Node
 * @augments {enyo.Node}
 */

/* global ares */

enyo.kind({
	name: "hermes.Node",
	kind: "Node",
	events: {
		onItemDown: "",
		onItemDragstart: "",
		onItemDragenter: "",
		onItemDragover: "",
		onItemDragleave: "",
		onItemUp: "",
		onItemDrop: "",
		onItemDragend: "",
		onFileClick: "",
		onFolderClick: "",
		onFileDblClick: "",
		onNodeRightClick: "",
		onAdjustScroll: ""
	},
	published: {
		service: null,

		// allows subnodes to be draggable or not (not per default).
		dragAllowed: false
	},
	handlers: {
		ondown: "down",
		ondragstart: "dragstart",
		ondragenter: "dragenter",
		ondragover: "dragover",
		ondragleave: "dragleave",
		onup: "up",
		ondrop: "drop",
		ondragend: "dragend"
	},
	attributes: {
		dropTarget: "true"
	},

	// expandable nodes may only be opened by tapping the icon; tapping the content label
	// will fire the nodeTap event, but will not expand the node.
	onlyIconExpands: true,

	debug: false,

	// used to deactivate Hermes right-click menu and allow the
	// browser one on the caption item of the node
	debugContextMenu: false,

	create: function() {
		ares.setupTraceLogger(this);	// Setup this.trace() function according to this.debug value
		this.inherited(arguments);
	},
	/** @private */
	down: function(inSender, inEvent) {
		if (inEvent.which === 1) {
			this.doItemDown(inEvent);
		}

		return true;
	},
	/** @private */
	dragstart: function(inSender, inEvent) {
		if(!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDragstart(inEvent);
		return true;
	},
	/** @private */
	dragenter: function(inSender, inEvent) {
		if (!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDragenter(inEvent);
		return true;
	},
	/** @private */
	dragover: function(inSender, inEvent) {
		if (!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDragover(inEvent);
		return true;
	},
	/** @private */
	dragleave: function(inSender, inEvent) {
		if (!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDragleave(inEvent);
		return true;
	},
	/** @private */
	up: function (inSender, inEvent) {
		if (inEvent.which === 1) {
			this.doItemUp(inEvent);
		}

		return true;
	},
	/** @private */
	drop: function(inSender, inEvent) {
		if (!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDrop(inEvent);
		return true;
	},
	/** @private */
	dragend: function(inSender, inEvent) {
		if (!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDragend(inEvent);
		return true;
	},

	// Note: this function does not recurse
	updateNodes: function() {
		this.startLoading(this);
		this.trace(this) ;
		return this.service.listFiles(this.file && this.file.id)
			.response(this, function(inSender, inFiles) {
				var sortedFiles = inFiles.sort(this.fileNameSort) ;
				if (inFiles && !this.showing) {
					this.show();
				}

				this.trace("updating node content of ", this.name, this," with ", sortedFiles ) ;
				this.updateNodeContent(sortedFiles);
				this.render() ;
			})
			.response(this, function() {
				this.stopLoading();
			})
			.error(this, function() {
				this.stopLoading();
			})
			;
	},
	startLoading: function() {
		this.$.extra.setContent(' ');
	},
	stopLoading: function() {
		this.$.extra.setContent("");
	},
	updateNodeContent: function(files) {
		var i = 0, rfiles, tfiles, res, newNode, k = 0, nfiles;

		this.trace( "updateNodeContent on", this ) ;

		// Add dir property to files, which is a project-relative path
		enyo.forEach(files, function(f) {
			this.trace("updateNodeContent loop on",f) ;
			if (f.isDir) {
				f.dir = (this.file.dir || "/") + f.name + "/";
			} else {
				f.dir = (this.file.dir || "/");
			}
		}.bind(this));
		rfiles = this.filesToNodes( files ) ; // with prefix in name

		// detach visual subnodes
		tfiles = this.getNodeFiles() ;
		for ( var j = 0; j < tfiles.length; j++ ) {
			this.removeControl( tfiles[j] );
		}

		nfiles = [];

		// rearrange visual subnodes accordingly to file nodes order
		while ( k < tfiles.length || i < rfiles.length ) {
			res = k >= tfiles.length ? 1
			    : i >= rfiles.length ? -1
			    : this.fileNameSort( tfiles[k], rfiles[i] );

			switch(res) {
				case -1:
					this.trace( tfiles[k].name, "was removed" ) ;
					tfiles[k].destroy() ;

					k++;

					break;
				case 0:
					this.trace( tfiles[k].name, "is kept" ) ;
					this.addControl( tfiles[k] ) ;

					k++;
					i++;

					break;
				case 1:
					this.trace( rfiles[i].name, "was created" ) ;
					if (this.dragAllowed) {
						newNode = this.createComponent( rfiles[i], {kind: "hermes.Node", classes: "hermesFileTree-node", dragAllowed: true, attributes: {draggable : true}} ) ;
					} else {
						newNode = this.createComponent( rfiles[i], {kind: "hermes.Node", classes: "hermesFileTree-node"} ) ;
					}
					newNode.setService(this.service);
					this.trace( newNode, "has been created " ) ;

					nfiles = this.getNodeFiles() ;
					/*
					 FIXME: allow to manually change
					 PhoneGap parameters from Ares.
					 DEMANDS to relad Ares after each
					 project.json manual change

						if (nfiles[i].name === '$project.json') {
							// project.json file is internal to Ares
							nfiles[i].hide();
						}
					 */

					i++;

					break;
			}
		}

		this.$.client.render();
	},
	compareFiles: function(inFilesA, inFilesB) {
		if (inFilesA.length != inFilesB.length) {
			return false;
		}
		for (var i in inFilesA) {
			var f0 = inFilesA[i], f1 = inFilesB[i];
			if (f0.id !== f1.id) {
				return false;
			}
		}
		return true;
	},
	// Sort files by name, case-insensitively
	// TODO: I18N, and possibly platform-specific sort order
	fileNameSort: function(a, b) {
		var lowA, lowB;
		lowA=a.name.toLowerCase();
		lowB=b.name.toLowerCase();
		// compare lower-case version of name
		if (lowA < lowB) {
			return -1;
		} else if (lowB < lowA) {
			return 1;
		} else {
			// Files that differ only in case are sorted lexicographically
			if (a.name < b.name) {
				return -1;
			} else if (b.name < a.name) {
				return 1;
			} else {
				return 0;
			}
		}
	},
	getNodeFiles: function() {
		var hasPrefix = function(e){
			return (e.name.slice(0,1) === '$') ;
		} ;
		// getComponents only return the graphical items
		return this.getControls().filter( hasPrefix ).sort(this.fileNameSort) ;
	},

	/**
	 * getNodeNamed
	 * @public
	 * @param {String} name
	 * @return a hermes.Node for a file or a directory named passed in parameter
	 *
	 */

	getNodeNamed: function(name) {
		var nameMatch = function(e){
			return (e.name === '$'+ name) ;
		} ;

		return this.getControls().filter( nameMatch )[0];
	},

	/**
	 * getNodeWithId
	 * @public
	 * @param {String} id
	 * @return a hermes.Node for a file or a directory id passed in parameter
	 *
	 */

	getNodeWithId: function (id) {
		var idMatch = function(e){
			return (e.file && e.file.id === id) ;
		} ;
		return this.getControls().filter( idMatch )[0];
	},

	filesToNodes: function(inFiles) {
		var nodes = [], f;
		inFiles.sort(this.fileNameSort); // TODO: Other sort orders
		for (var i=0; i < inFiles.length; i++) {
			f=inFiles[i];
			f.service = this.service;
			nodes.push({
				file: f,
				name: '$' + f.name, // prefix avoids clobberring non-files components like icon
				content: f.name,
				expandable: f.isDir,
				icon: "$services/assets/images/" + (f.isDir ? "folder.png" : "file.png")
			});
		}
		return nodes;
	},
	nodeExpand: function(inSender, inEvent) {
		this.trace(inSender, "=>", inEvent);

		var subnode = inEvent.originator;
		this.trace("nodeExpand called while node Expanded is ", subnode.expanded) ;
		// update icon for expanded state
		if (subnode.file.isDir) {
			subnode.setIcon("$services/assets/images/" + (subnode.expanded ? "folder-open.png" : "folder.png"));
		}
		// handle lazy-load when expanding
		if (subnode.expanded) {
			subnode.updateNodes().
				response(this, function() {
					subnode.effectExpanded();
				});
			// tell the event originator that node expansion should be deferred
			inEvent.wait = true;
		}
		// handled here (don't bubble)
		return true;
	},

	// All parameters are optional.
	// - toSelectId is optional. refresh will select this entry if specified.
	//   Nothing is selected otherwise.
	// - tracker is an internal parameter used in inner refreshFileTree calls
	refreshTree: function(tracker, belowTop, toSelectId) {
		this.trace(this) ;

		this.trace('running refreshTree with ' +
			 this.controls.length + ' controls with content ' + this.content +
			 ' force select ' + toSelectId );

		tracker.inc() ; // for updadeNodes
		this.updateNodes().
			response(this, function(inSender, inFiles) {
				// expand node if it has clients (sub-nodes) and is expanded
				this.effectExpanded();

				enyo.forEach(this.getNodeFiles(), function(f) {
					var c = this.$[f.name] ; // c is a node
					this.trace('running INNER function of refreshTree on ' + f.name +
								 ' id ' + c.file.id);
					if ( c.file.id === toSelectId ) {
						this.trace('force select of ', c.file.id);
						c.doNodeTap();

						// force a "click" event when the item is selected
						this.doFolderClick({file: c.file});
					}
					c.effectExpanded() ;
					if (f.expanded) {
						tracker.inc() ; // for inner calls to refreshTree
						c.refreshTree(tracker, 1, toSelectId );
					}
				}, this);
				tracker.dec(); // end updateNodes
			}).
			error(this, function(inSender, inError) {
				var errMsg = "*** Error refreshing the file list (" + inError + ")";
				try {
					errMsg += ": " + enyo.json.parse(inSender.xhrResponse.body).message;
				} catch(e) {
				}
				this.warn(errMsg);
			});

		if( belowTop ) {
			tracker.dec(); // run only for inner calls to refreshTree
		}
		this.trace("refreshTree done") ;
	},
	followNodePath: function (nodes, waypoints, next) {
		if (nodes.length > 0) {
			this.updateNodes().response(this, function () {
				var track = this.getNodeNamed(nodes.shift());
				if (track) {
					waypoints.push(track);
					track.followNodePath(nodes, waypoints, next);
				} else {
					if (typeof next === 'function') {
						next();
					}
				}
			})
			.error(this, function (inSender, inError) {
				if (typeof next === 'function') {
					next(inError);
				}
			});
		} else {
			if (typeof next === 'function') {
				next();
			}
		}
	}
});
<commit_msg>ENYO-3570: remove dead code<commit_after>/* jshint indent: false */ // TODO: ENYO-3311
/**
 * Represents a directory or a file in {HermesFileTree}
 *
 * @class hermes.Node
 * @augments {enyo.Node}
 */

/* global ares */

enyo.kind({
	name: "hermes.Node",
	kind: "Node",
	events: {
		onItemDown: "",
		onItemDragstart: "",
		onItemDragenter: "",
		onItemDragover: "",
		onItemDragleave: "",
		onItemUp: "",
		onItemDrop: "",
		onItemDragend: "",
		onFileClick: "",
		onFolderClick: "",
		onNodeRightClick: "",
		onAdjustScroll: ""
	},
	published: {
		service: null,

		// allows subnodes to be draggable or not (not per default).
		dragAllowed: false
	},
	handlers: {
		ondown: "down",
		ondragstart: "dragstart",
		ondragenter: "dragenter",
		ondragover: "dragover",
		ondragleave: "dragleave",
		onup: "up",
		ondrop: "drop",
		ondragend: "dragend"
	},
	attributes: {
		dropTarget: "true"
	},

	// expandable nodes may only be opened by tapping the icon; tapping the content label
	// will fire the nodeTap event, but will not expand the node.
	onlyIconExpands: true,

	debug: false,

	// used to deactivate Hermes right-click menu and allow the
	// browser one on the caption item of the node
	debugContextMenu: false,

	create: function() {
		ares.setupTraceLogger(this);	// Setup this.trace() function according to this.debug value
		this.inherited(arguments);
	},
	/** @private */
	down: function(inSender, inEvent) {
		if (inEvent.which === 1) {
			this.doItemDown(inEvent);
		}

		return true;
	},
	/** @private */
	dragstart: function(inSender, inEvent) {
		if(!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDragstart(inEvent);
		return true;
	},
	/** @private */
	dragenter: function(inSender, inEvent) {
		if (!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDragenter(inEvent);
		return true;
	},
	/** @private */
	dragover: function(inSender, inEvent) {
		if (!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDragover(inEvent);
		return true;
	},
	/** @private */
	dragleave: function(inSender, inEvent) {
		if (!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDragleave(inEvent);
		return true;
	},
	/** @private */
	up: function (inSender, inEvent) {
		if (inEvent.which === 1) {
			this.doItemUp(inEvent);
		}

		return true;
	},
	/** @private */
	drop: function(inSender, inEvent) {
		if (!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDrop(inEvent);
		return true;
	},
	/** @private */
	dragend: function(inSender, inEvent) {
		if (!inEvent.dataTransfer) {
			return true;
		}

		this.doItemDragend(inEvent);
		return true;
	},

	// Note: this function does not recurse
	updateNodes: function() {
		this.startLoading(this);
		this.trace(this) ;
		return this.service.listFiles(this.file && this.file.id)
			.response(this, function(inSender, inFiles) {
				var sortedFiles = inFiles.sort(this.fileNameSort) ;
				if (inFiles && !this.showing) {
					this.show();
				}

				this.trace("updating node content of ", this.name, this," with ", sortedFiles ) ;
				this.updateNodeContent(sortedFiles);
				this.render() ;
			})
			.response(this, function() {
				this.stopLoading();
			})
			.error(this, function() {
				this.stopLoading();
			})
			;
	},
	startLoading: function() {
		this.$.extra.setContent(' ');
	},
	stopLoading: function() {
		this.$.extra.setContent("");
	},
	updateNodeContent: function(files) {
		var i = 0, rfiles, tfiles, res, newNode, k = 0, nfiles;

		this.trace( "updateNodeContent on", this ) ;

		// Add dir property to files, which is a project-relative path
		enyo.forEach(files, function(f) {
			this.trace("updateNodeContent loop on",f) ;
			if (f.isDir) {
				f.dir = (this.file.dir || "/") + f.name + "/";
			} else {
				f.dir = (this.file.dir || "/");
			}
		}.bind(this));
		rfiles = this.filesToNodes( files ) ; // with prefix in name

		// detach visual subnodes
		tfiles = this.getNodeFiles() ;
		for ( var j = 0; j < tfiles.length; j++ ) {
			this.removeControl( tfiles[j] );
		}

		nfiles = [];

		// rearrange visual subnodes accordingly to file nodes order
		while ( k < tfiles.length || i < rfiles.length ) {
			res = k >= tfiles.length ? 1
			    : i >= rfiles.length ? -1
			    : this.fileNameSort( tfiles[k], rfiles[i] );

			switch(res) {
				case -1:
					this.trace( tfiles[k].name, "was removed" ) ;
					tfiles[k].destroy() ;

					k++;

					break;
				case 0:
					this.trace( tfiles[k].name, "is kept" ) ;
					this.addControl( tfiles[k] ) ;

					k++;
					i++;

					break;
				case 1:
					this.trace( rfiles[i].name, "was created" ) ;
					if (this.dragAllowed) {
						newNode = this.createComponent( rfiles[i], {kind: "hermes.Node", classes: "hermesFileTree-node", dragAllowed: true, attributes: {draggable : true}} ) ;
					} else {
						newNode = this.createComponent( rfiles[i], {kind: "hermes.Node", classes: "hermesFileTree-node"} ) ;
					}
					newNode.setService(this.service);
					this.trace( newNode, "has been created " ) ;

					nfiles = this.getNodeFiles() ;
					/*
					 FIXME: allow to manually change
					 PhoneGap parameters from Ares.
					 DEMANDS to relad Ares after each
					 project.json manual change

						if (nfiles[i].name === '$project.json') {
							// project.json file is internal to Ares
							nfiles[i].hide();
						}
					 */

					i++;

					break;
			}
		}

		this.$.client.render();
	},
	compareFiles: function(inFilesA, inFilesB) {
		if (inFilesA.length != inFilesB.length) {
			return false;
		}
		for (var i in inFilesA) {
			var f0 = inFilesA[i], f1 = inFilesB[i];
			if (f0.id !== f1.id) {
				return false;
			}
		}
		return true;
	},
	// Sort files by name, case-insensitively
	// TODO: I18N, and possibly platform-specific sort order
	fileNameSort: function(a, b) {
		var lowA, lowB;
		lowA=a.name.toLowerCase();
		lowB=b.name.toLowerCase();
		// compare lower-case version of name
		if (lowA < lowB) {
			return -1;
		} else if (lowB < lowA) {
			return 1;
		} else {
			// Files that differ only in case are sorted lexicographically
			if (a.name < b.name) {
				return -1;
			} else if (b.name < a.name) {
				return 1;
			} else {
				return 0;
			}
		}
	},
	getNodeFiles: function() {
		var hasPrefix = function(e){
			return (e.name.slice(0,1) === '$') ;
		} ;
		// getComponents only return the graphical items
		return this.getControls().filter( hasPrefix ).sort(this.fileNameSort) ;
	},

	/**
	 * getNodeNamed
	 * @public
	 * @param {String} name
	 * @return a hermes.Node for a file or a directory named passed in parameter
	 *
	 */

	getNodeNamed: function(name) {
		var nameMatch = function(e){
			return (e.name === '$'+ name) ;
		} ;

		return this.getControls().filter( nameMatch )[0];
	},

	/**
	 * getNodeWithId
	 * @public
	 * @param {String} id
	 * @return a hermes.Node for a file or a directory id passed in parameter
	 *
	 */

	getNodeWithId: function (id) {
		var idMatch = function(e){
			return (e.file && e.file.id === id) ;
		} ;
		return this.getControls().filter( idMatch )[0];
	},

	filesToNodes: function(inFiles) {
		var nodes = [], f;
		inFiles.sort(this.fileNameSort); // TODO: Other sort orders
		for (var i=0; i < inFiles.length; i++) {
			f=inFiles[i];
			f.service = this.service;
			nodes.push({
				file: f,
				name: '$' + f.name, // prefix avoids clobberring non-files components like icon
				content: f.name,
				expandable: f.isDir,
				icon: "$services/assets/images/" + (f.isDir ? "folder.png" : "file.png")
			});
		}
		return nodes;
	},
	nodeExpand: function(inSender, inEvent) {
		this.trace(inSender, "=>", inEvent);

		var subnode = inEvent.originator;
		this.trace("nodeExpand called while node Expanded is ", subnode.expanded) ;
		// update icon for expanded state
		if (subnode.file.isDir) {
			subnode.setIcon("$services/assets/images/" + (subnode.expanded ? "folder-open.png" : "folder.png"));
		}
		// handle lazy-load when expanding
		if (subnode.expanded) {
			subnode.updateNodes().
				response(this, function() {
					subnode.effectExpanded();
				});
			// tell the event originator that node expansion should be deferred
			inEvent.wait = true;
		}
		// handled here (don't bubble)
		return true;
	},

	// All parameters are optional.
	// - toSelectId is optional. refresh will select this entry if specified.
	//   Nothing is selected otherwise.
	// - tracker is an internal parameter used in inner refreshFileTree calls
	refreshTree: function(tracker, belowTop, toSelectId) {
		this.trace(this) ;

		this.trace('running refreshTree with ' +
			 this.controls.length + ' controls with content ' + this.content +
			 ' force select ' + toSelectId );

		tracker.inc() ; // for updadeNodes
		this.updateNodes().
			response(this, function(inSender, inFiles) {
				// expand node if it has clients (sub-nodes) and is expanded
				this.effectExpanded();

				enyo.forEach(this.getNodeFiles(), function(f) {
					var c = this.$[f.name] ; // c is a node
					this.trace('running INNER function of refreshTree on ' + f.name +
								 ' id ' + c.file.id);
					if ( c.file.id === toSelectId ) {
						this.trace('force select of ', c.file.id);
						c.doNodeTap();

						// force a "click" event when the item is selected
						this.doFolderClick({file: c.file});
					}
					c.effectExpanded() ;
					if (f.expanded) {
						tracker.inc() ; // for inner calls to refreshTree
						c.refreshTree(tracker, 1, toSelectId );
					}
				}, this);
				tracker.dec(); // end updateNodes
			}).
			error(this, function(inSender, inError) {
				var errMsg = "*** Error refreshing the file list (" + inError + ")";
				try {
					errMsg += ": " + enyo.json.parse(inSender.xhrResponse.body).message;
				} catch(e) {
				}
				this.warn(errMsg);
			});

		if( belowTop ) {
			tracker.dec(); // run only for inner calls to refreshTree
		}
		this.trace("refreshTree done") ;
	},
	followNodePath: function (nodes, waypoints, next) {
		if (nodes.length > 0) {
			this.updateNodes().response(this, function () {
				var track = this.getNodeNamed(nodes.shift());
				if (track) {
					waypoints.push(track);
					track.followNodePath(nodes, waypoints, next);
				} else {
					if (typeof next === 'function') {
						next();
					}
				}
			})
			.error(this, function (inSender, inError) {
				if (typeof next === 'function') {
					next(inError);
				}
			});
		} else {
			if (typeof next === 'function') {
				next();
			}
		}
	}
});
<|endoftext|>


<commit_before>var urljoin = require('url-join');

var SKVS_API_URL = "http://skvs"
var APPS_API_URL = "http://app-manager"

if (process.env.NODE_ENV == 'development') {
  SKVS_API_URL = "http://127.0.0.1:8080"
  APPS_API_URL = "http://127.0.0.1:8081"
}

module.exports = {
  skvsApiUrl: function(path) {
    return urljoin(SKVS_API_URL, path);
  }

  appsApiUrl: function(path) {
    return urljoin(APPS_API_URL, path)
  }
}
<commit_msg>add missing comma<commit_after>var urljoin = require('url-join');

var SKVS_API_URL = "http://skvs"
var APPS_API_URL = "http://app-manager"

if (process.env.NODE_ENV == 'development') {
  SKVS_API_URL = "http://127.0.0.1:8080"
  APPS_API_URL = "http://127.0.0.1:8081"
}

module.exports = {
  skvsApiUrl: function(path) {
    return urljoin(SKVS_API_URL, path);
  },

  appsApiUrl: function(path) {
    return urljoin(APPS_API_URL, path)
  }
}
<|endoftext|>


<commit_before>(function (mw, $, kWidget) {
	"use strict";

	mw.PluginManager.add('audioSelector', mw.KBaseComponent.extend({

		defaultConfig: {
			"parent": "controlsContainer",
			"order": 61,
			"displayImportance": 'low',
			"align": "right",
			"iconClass": "icon-audio",
			"showTooltip": true,
			"labelWidthPercentage": 33,
			"defaultStream": -1, // -1 is auto
			"maxNumOfStream": 4,
			"enableKeyboardShortcuts": true,
			"keyboardShortcutsMap": {
				"nextStream": 221,   // Add ] Sign for next stream
				"prevStream": 219,   // Add [ Sigh for previous stream
				"defaultStream": 220 // Add \ Sigh for default stream
			}
		},

		isDisabled: false,
		streams: [],
		streamsReady: false,
		streamEnded: false,

		setup: function () {
			this.addBindings();
			var defaultTrack = this.getConfig('defaultStream');
			if (defaultTrack > -1) {
				this.getPlayer().audioTrack = {
					defaultTrack: this.getConfig('defaultStream')
				};
			}
			this.setConfig('defaultStream', 0);
		},
		destroy: function () {
			this._super();
			this.getComponent().remove();
		},
		addBindings: function () {
			var _this = this;

			this.bind('playerReady', function () {
				if (!_this.streamsReady) {
					_this.onDisable();
					_this.getPlayer().triggerHelper("updatePropertyEvent",{"plugin": _this.pluginName, "property": "sources", "items": [{'label':gM("mwe-timedtext-no-audio"),'value':gM("mwe-timedtext-no-audio")}], "selectedItem": gM("mwe-timedtext-no-audio")});
				}
			});

			this.bind( 'audioTracksReceived' ,function(e,data){
				if ( data.languages && data.languages.length > 0 ) {
					var tracks = data.languages;
					_this.streams = tracks;
					_this.setStream(_this.getDefaultStream());
					_this.buildMenu();
					_this.streamsReady = true;
					_this.onEnable();
				}
			});

			this.bind('audioTrackIndexChanged', function (e, arg) {
				_this.externalSetStream(arg);
			});

			if (this.getConfig('enableKeyboardShortcuts')) {
				this.bind('addKeyBindCallback', function (e, addKeyCallback) {
					_this.addKeyboardShortcuts(addKeyCallback);
				});
			}

			this.embedPlayer.bindHelper("propertyChangedEvent", function(event, data){
				if ( data.plugin === _this.pluginName ){
					if ( data.property === "sources" ){
						_this.getMenu().$el.find("li a")[data.value].click();
					}
				}
			});
		},

		addKeyboardShortcuts: function (addKeyCallback) {
			var _this = this;
			// Add ] Sign for next stream
			addKeyCallback(this.getConfig("keyboardShortcutsMap").nextStream, function () {
				_this.setStream(_this.getNextStream());
			});
			// Add [ Sigh for previous stream
			addKeyCallback(this.getConfig("keyboardShortcutsMap").prevStream, function () {
				_this.setStream(_this.getPrevStream());
			});
			// Add \ Sigh for default stream
			addKeyCallback(this.getConfig("keyboardShortcutsMap" ).defaultStream, function () {
				_this.setStream(_this.getDefaultStream());
			});
		},
		getNextStream: function () {
			if (this.streams[this.getCurrentStreamIndex() + 1]) {
				return this.streams[this.getCurrentStreamIndex() + 1];
			}
			return this.streams[this.getCurrentStreamIndex()];
		},
		getPrevStream: function () {
			if (this.streams[this.getCurrentStreamIndex() - 1]) {
				return this.streams[this.getCurrentStreamIndex() - 1];
			}
			return this.streams[this.getCurrentStreamIndex()];
		},
		getDefaultStream: function () {
			return this.streams[(this.getConfig('defaultStream'))];
		},
		getCurrentStreamIndex: function () {
			var _this = this;
			var index = null;
			$.each(this.streams, function (idx, stream) {
				if (_this.currentStream == stream) {
					index = idx;
					return false;
				}
			});
			return index;
		},
		buildMenu: function () {
			var _this = this;

			// Destroy old menu
			this.getMenu().destroy();

			if (!this.streams.length) {
				this.log("Error with getting streams");
				//this.destroy();
				return;
			}
			var items = [];
			$.each(this.streams, function (streamIndex, stream) {
				_this.addStreamToMenu(streamIndex, stream);
				items.push({'label':stream.label, 'value':stream.label});
			});
			var actualWidth = this.getMenu().$el.width();
			var labelWidthPercentage = parseInt(this.getConfig("labelWidthPercentage")) / 100;
			var labelWidth = this.getPlayer().getWidth() * labelWidthPercentage;
			if (actualWidth > labelWidth) {
				this.getMenu().$el.find('a').width(labelWidth);
			}
			this.getMenu().setActive({'key': 'id', 'val': this.getCurrentStreamIndex()});
			// dispatch event to be used by a master plugin if defined
			this.getPlayer().triggerHelper("updatePropertyEvent",{"plugin": this.pluginName, "property": "sources", "items": items, "selectedItem": this.getMenu().$el.find('.active a').text()});

		},
		addStreamToMenu: function (id, stream) {
			var _this = this;
			var active = (this.getCurrentStreamIndex() == id);
			var streamName = stream.label;
			this.getMenu().addItem({
				'label': streamName,
				'attributes': {
					'id': id
				},
				'callback': function () {
					_this.setStream(stream);
				},
				'active': active
			});
			this.getMenu().$el.find("a").addClass("truncateText");
		},
		externalSetStream: function (id) {
			var stream = this.streams[id.index];
			if (stream) {
				this.setStream(stream);
			} else {
				this.log("Error - invalid stream id");
			}
		},
		setStream: function (stream) {
			if (this.currentStream !== stream ) {
				this.currentStream = stream;
				this.embedPlayer.triggerHelper('switchAudioTrack', {index: stream.index});
			}
		},
		toggleMenu: function () {
			if (this.isDisabled) {
				return;
			}
			this.getMenu().toggle();
		},
		getComponent: function () {
			var _this = this;
			if (!this.$el) {
				var $menu = $('<ul />');
				//TODO: need icon from Shlomit!
				var $button = $('<button />')
					.addClass('btn icon-audio')
					.attr('title', gM('mwe-embedplayer-select_audio'))
					.click(function (e) {
						_this.toggleMenu();
					});
				this.setAccessibility($button, gM('mwe-embedplayer-select_audio'));
				this.$el = $('<div />')
					.addClass('dropup' + this.getCssClass())
					.append($button, $menu);
			}
			return this.$el;
		},
		getMenu: function () {
			if (!this.menu) {
				this.menu = new mw.KMenu(this.getComponent().find('ul'), {
					tabIndex: this.getBtn().attr('tabindex')
				});
			}
			return this.menu;
		},
		getBtn: function () {
			return this.getComponent().find('button');
		},
		onEnable: function () {
			this.isDisabled = false;
			this.updateTooltip(gM('mwe-embedplayer-select_audio'));
			this.getBtn().removeClass('disabled');
		},
		onDisable: function () {
			this.isDisabled = true;
			this.updateTooltip(gM('mwe-embedplayer-select_audio'));
			this.getComponent().removeClass('open');
			this.getBtn().addClass('disabled');
		}
	}));

})(window.mw, window.jQuery, kWidget);<commit_msg>add audio selector plugin to the quality settings smart container<commit_after>(function (mw, $, kWidget) {
	"use strict";

	mw.PluginManager.add('audioSelector', mw.KBaseComponent.extend({

		defaultConfig: {
			"parent": "controlsContainer",
			"order": 61,
			"displayImportance": 'low',
			"align": "right",
			"iconClass": "icon-audio",
			"showTooltip": true,
			"labelWidthPercentage": 33,
			"defaultStream": -1, // -1 is auto
			"maxNumOfStream": 4,
			"enableKeyboardShortcuts": true,
			"smartContainer": "qualitySettings",
			'smartContainerCloseEvent': 'switchAudioTrack',
			"title": gM( 'mwe-embedplayer-select_audio'),
			"keyboardShortcutsMap": {
				"nextStream": 221,   // Add ] Sign for next stream
				"prevStream": 219,   // Add [ Sigh for previous stream
				"defaultStream": 220 // Add \ Sigh for default stream
			}
		},

		isDisabled: false,
		streams: [],
		streamsReady: false,
		streamEnded: false,

		setup: function () {
			this.addBindings();
			var defaultTrack = this.getConfig('defaultStream');
			if (defaultTrack > -1) {
				this.getPlayer().audioTrack = {
					defaultTrack: this.getConfig('defaultStream')
				};
			}
			this.setConfig('defaultStream', 0);
		},
		destroy: function () {
			this._super();
			this.getComponent().remove();
		},
		addBindings: function () {
			var _this = this;

			this.bind('playerReady', function () {
				if (!_this.streamsReady) {
					_this.onDisable();
					_this.getPlayer().triggerHelper("updatePropertyEvent",{"plugin": _this.pluginName, "property": "sources", "items": [{'label':gM("mwe-timedtext-no-audio"),'value':gM("mwe-timedtext-no-audio")}], "selectedItem": gM("mwe-timedtext-no-audio")});
				}
			});

			this.bind( 'audioTracksReceived' ,function(e,data){
				if ( data.languages && data.languages.length > 0 ) {
					var tracks = data.languages;
					_this.streams = tracks;
					_this.setStream(_this.getDefaultStream());
					_this.buildMenu();
					_this.streamsReady = true;
					_this.onEnable();
				}
			});

			this.bind('audioTrackIndexChanged', function (e, arg) {
				_this.externalSetStream(arg);
			});

			if (this.getConfig('enableKeyboardShortcuts')) {
				this.bind('addKeyBindCallback', function (e, addKeyCallback) {
					_this.addKeyboardShortcuts(addKeyCallback);
				});
			}

			this.embedPlayer.bindHelper("propertyChangedEvent", function(event, data){
				if ( data.plugin === _this.pluginName ){
					if ( data.property === "sources" ){
						_this.getMenu().$el.find("li a")[data.value].click();
					}
				}
			});
		},

		addKeyboardShortcuts: function (addKeyCallback) {
			var _this = this;
			// Add ] Sign for next stream
			addKeyCallback(this.getConfig("keyboardShortcutsMap").nextStream, function () {
				_this.setStream(_this.getNextStream());
			});
			// Add [ Sigh for previous stream
			addKeyCallback(this.getConfig("keyboardShortcutsMap").prevStream, function () {
				_this.setStream(_this.getPrevStream());
			});
			// Add \ Sigh for default stream
			addKeyCallback(this.getConfig("keyboardShortcutsMap" ).defaultStream, function () {
				_this.setStream(_this.getDefaultStream());
			});
		},
		getNextStream: function () {
			if (this.streams[this.getCurrentStreamIndex() + 1]) {
				return this.streams[this.getCurrentStreamIndex() + 1];
			}
			return this.streams[this.getCurrentStreamIndex()];
		},
		getPrevStream: function () {
			if (this.streams[this.getCurrentStreamIndex() - 1]) {
				return this.streams[this.getCurrentStreamIndex() - 1];
			}
			return this.streams[this.getCurrentStreamIndex()];
		},
		getDefaultStream: function () {
			return this.streams[(this.getConfig('defaultStream'))];
		},
		getCurrentStreamIndex: function () {
			var _this = this;
			var index = null;
			$.each(this.streams, function (idx, stream) {
				if (_this.currentStream == stream) {
					index = idx;
					return false;
				}
			});
			return index;
		},
		buildMenu: function () {
			var _this = this;

			// Destroy old menu
			this.getMenu().destroy();

			if (!this.streams.length) {
				this.log("Error with getting streams");
				//this.destroy();
				return;
			}
			var items = [];
			$.each(this.streams, function (streamIndex, stream) {
				_this.addStreamToMenu(streamIndex, stream);
				items.push({'label':stream.label, 'value':stream.label});
			});
			var actualWidth = this.getMenu().$el.width();
			var labelWidthPercentage = parseInt(this.getConfig("labelWidthPercentage")) / 100;
			var labelWidth = this.getPlayer().getWidth() * labelWidthPercentage;
			if (actualWidth > labelWidth) {
				this.getMenu().$el.find('a').width(labelWidth);
			}
			this.getMenu().setActive({'key': 'id', 'val': this.getCurrentStreamIndex()});
			// dispatch event to be used by a master plugin if defined
			this.getPlayer().triggerHelper("updatePropertyEvent",{"plugin": this.pluginName, "property": "sources", "items": items, "selectedItem": this.getMenu().$el.find('.active a').text()});

		},
		addStreamToMenu: function (id, stream) {
			var _this = this;
			var active = (this.getCurrentStreamIndex() == id);
			var streamName = stream.label;
			this.getMenu().addItem({
				'label': streamName,
				'attributes': {
					'id': id
				},
				'callback': function () {
					_this.setStream(stream);
				},
				'active': active
			});
			this.getMenu().$el.find("a").addClass("truncateText");
		},
		externalSetStream: function (id) {
			var stream = this.streams[id.index];
			if (stream) {
				this.setStream(stream);
			} else {
				this.log("Error - invalid stream id");
			}
		},
		setStream: function (stream) {
			if (this.currentStream !== stream ) {
				this.currentStream = stream;
				this.embedPlayer.triggerHelper('switchAudioTrack', {index: stream.index});
			}
		},
		toggleMenu: function () {
			if (this.isDisabled) {
				return;
			}
			this.getMenu().toggle();
		},
		getComponent: function () {
			var _this = this;
			if (!this.$el) {
				var $menu = $('<ul />');
				//TODO: need icon from Shlomit!
				var $button = $('<button />')
					.addClass('btn icon-audio')
					.attr('title', gM('mwe-embedplayer-select_audio'))
					.click(function (e) {
						_this.toggleMenu();
					});
				this.setAccessibility($button, gM('mwe-embedplayer-select_audio'));
				this.$el = $('<div />')
					.addClass('dropup' + this.getCssClass())
					.append($button, $menu);
			}
			return this.$el;
		},
		getMenu: function () {
			if (!this.menu) {
				this.menu = new mw.KMenu(this.getComponent().find('ul'), {
					tabIndex: this.getBtn().attr('tabindex')
				});
			}
			return this.menu;
		},
		getBtn: function () {
			return this.getComponent().find('button');
		},
		onEnable: function () {
			this.isDisabled = false;
			this.updateTooltip(gM('mwe-embedplayer-select_audio'));
			this.getBtn().removeClass('disabled');
		},
		onDisable: function () {
			this.isDisabled = true;
			this.updateTooltip(gM('mwe-embedplayer-select_audio'));
			this.getComponent().removeClass('open');
			this.getBtn().addClass('disabled');
		}
	}));

})(window.mw, window.jQuery, kWidget);<|endoftext|>


<commit_before>( function( mw, $ ) {"use strict";

// Class defined in resources/class/class.js
mw.KBasePlugin = Class.extend({
	asyncInit: false,
	init: function( embedPlayer, callback, pluginName ){

		// Save to local scope
		this.embedPlayer = embedPlayer;
		this.initCompleteCallback = callback;
		this.pluginName = pluginName;

		this.bindPostFix = '.' + pluginName;

		this.setDefaults();

		var safeEnviornment = this.isSafeEnviornment();
		var _this = this;

		// Check if jQuery Deferrer
		if( typeof safeEnviornment == 'object' && safeEnviornment.promise ){
			safeEnviornment.done(function(isSafe){
				if( !isSafe ){
					_this.destroy();
				}
			});
		} else if( typeof safeEnviornment == 'boolean' && ! safeEnviornment ) {
			this.initCompleteCallback();
			return false;
		}

		// Add onConfigChange binding
		this.bindConfigChangeEvent();

		// Call plugin setup method
		this.setup();

		// Run initCompleteCallback
		if( this.asyncInit === false ) {
			this.initCompleteCallback();
		}

		return this;
	},
	setDefaults: function( obj ){
		obj = obj || this.defaultConfig;
		var _this = this;
		// Set default configuration for the plugin
		if( $.isPlainObject(obj) ) {
			$.each( obj, function( key, value ) {
				if( _this.getConfig( key ) === undefined ) {
					_this.setConfig( key, value, true );
				}
			});
		}
	},
	isSafeEnviornment: function(){
		return true;
	},
	setup: function() {},
	getPlayer: function() {
		return this.embedPlayer;
	},
	getConfig: function( attr, raw ) {
		if( raw ){
			return this.embedPlayer.getRawKalturaConfig( this.pluginName, attr );
		}
		return this.embedPlayer.getKalturaConfig( this.pluginName, attr );
	},
	setConfig: function( attr, value, quiet ) {
		this.embedPlayer.setKalturaConfig( this.pluginName, attr, value, quiet );
	},
	getTemplateHTML: function( data ){
		var _this = this;
		// Setup empty object
		data = data || {};
		// Add out plugin instance
		data.self = this;
		data.player = this.embedPlayer;
		data.entry = this.embedPlayer.kalturaPlayerMetaData;
		data.entryMetadata = this.embedPlayer.kalturaEntryMetaData;

		// First get template from 'template' config
		var rawHTML = this.getConfig( 'template', true );
		if( !rawHTML ){
			var templatePath = this.getConfig( 'templatePath' );
			if( !templatePath || !window.kalturaIframePackageData.templates[ templatePath ]) {
				this.log('getTemplateHTML:: Template not found');
				return '';
			}
			rawHTML = window.kalturaIframePackageData.templates[ templatePath ];
		}
		var transformedHTML = mw.util.tmpl( rawHTML, data );
		var evaluatedHTML = $.trim( this.embedPlayer.evaluate( transformedHTML ) );
		var $templateHtml = $( '' + evaluatedHTML + '' );

		$templateHtml
			.find('[data-click],[data-notification]')
			.click(function(e){
				var data = $(this).data();
				return _this.handleClick( e, data );
			});

		return $templateHtml;
	},
	handleClick: function( e, data ){

		e.preventDefault();

		// Trigger local callback for data-click property
		if( data.click && $.isFunction(this[data.click]) ){
			this[data.click]( e, data );
		}

		if( data.notification ){
			this.getPlayer().sendNotification( data.notification, data );
		}

		return false;
	},
	bind: function( eventName, callback ){
		var bindEventsString = '',
			events = eventName.split(" "),
			totalEvents = events.length,
			i = 0,
			space = ' ';

		for( i; i<totalEvents; i++ ){
			if( i == (totalEvents-1) ){
				space = '';
			}
			bindEventsString += events[ i ] + this.bindPostFix + space;
		}
		return this.embedPlayer.bindHelper( bindEventsString, callback);
	},
	unbind: function( eventName ){
		eventName += this.bindPostFix;
		return this.embedPlayer.unbindHelper( eventName );
	},
	log: function( msg ){
		mw.log( this.pluginName + '::' + msg );
	},
	bindConfigChangeEvent: function(){
		var _this = this;
		if( typeof this.onConfigChange !== 'function' ){
			return ;
		}
		this.bind('Kaltura_ConfigChanged', function(event, pluginName, property, value){
			if( pluginName === _this.pluginName ){
				_this.onConfigChange( property, value );
			}
		});
	},
	getKalturaClient: function() {
		if( ! this.kClient ) {
			this.kClient = mw.kApiGetPartnerClient( this.embedPlayer.kwidgetid );
		}
		return this.kClient;
	},
	destroy: function(){
		this.unbind();
	}
});

} )( window.mw, window.jQuery );<commit_msg>KBasePlugin: Support for HTML forms submission in templates<commit_after>( function( mw, $ ) {"use strict";

// Class defined in resources/class/class.js
mw.KBasePlugin = Class.extend({
	asyncInit: false,
	init: function( embedPlayer, callback, pluginName ){

		// Save to local scope
		this.embedPlayer = embedPlayer;
		this.initCompleteCallback = callback;
		this.pluginName = pluginName;

		this.bindPostFix = '.' + pluginName;

		this.setDefaults();

		var safeEnviornment = this.isSafeEnviornment();
		var _this = this;

		// Check if jQuery Deferrer
		if( typeof safeEnviornment == 'object' && safeEnviornment.promise ){
			safeEnviornment.done(function(isSafe){
				if( !isSafe ){
					_this.destroy();
				}
			});
		} else if( typeof safeEnviornment == 'boolean' && ! safeEnviornment ) {
			this.initCompleteCallback();
			return false;
		}

		// Add onConfigChange binding
		this.bindConfigChangeEvent();

		// Call plugin setup method
		this.setup();

		// Run initCompleteCallback
		if( this.asyncInit === false ) {
			this.initCompleteCallback();
		}

		return this;
	},
	setDefaults: function( obj ){
		obj = obj || this.defaultConfig;
		var _this = this;
		// Set default configuration for the plugin
		if( $.isPlainObject(obj) ) {
			$.each( obj, function( key, value ) {
				if( _this.getConfig( key ) === undefined ) {
					_this.setConfig( key, value, true );
				}
			});
		}
	},
	isSafeEnviornment: function(){
		return true;
	},
	setup: function() {},
	getPlayer: function() {
		return this.embedPlayer;
	},
	getConfig: function( attr, raw ) {
		if( raw ){
			return this.embedPlayer.getRawKalturaConfig( this.pluginName, attr );
		}
		return this.embedPlayer.getKalturaConfig( this.pluginName, attr );
	},
	setConfig: function( attr, value, quiet ) {
		this.embedPlayer.setKalturaConfig( this.pluginName, attr, value, quiet );
	},
	getTemplateHTML: function( data ){
		var _this = this;
		// Setup empty object
		data = data || {};
		// Add out plugin instance
		data.self = this;
		data.player = this.embedPlayer;
		data.entry = this.embedPlayer.kalturaPlayerMetaData;
		data.entryMetadata = this.embedPlayer.kalturaEntryMetaData;

		// First get template from 'template' config
		var rawHTML = this.getConfig( 'template', true );
		if( !rawHTML ){
			var templatePath = this.getConfig( 'templatePath' );
			if( !templatePath || !window.kalturaIframePackageData.templates[ templatePath ]) {
				this.log('getTemplateHTML:: Template not found');
				return '';
			}
			rawHTML = window.kalturaIframePackageData.templates[ templatePath ];
		}
		var transformedHTML = mw.util.tmpl( rawHTML, data );
		var evaluatedHTML = $.trim( this.embedPlayer.evaluate( transformedHTML ) );
		var $templateHtml = $( '' + evaluatedHTML + '' );

		$templateHtml
			.find('[data-click],[data-notification]')
			.click(function(e){
				var data = $(this).data();
				return _this.handleClick( e, data );
			});

		// Handle form submission
		$templateHtml.find('[data-submit]').submit(function(e){
			var cb = $(this).data('submit');
			if( $.isFunction( _this[cb] ) ) {
				_this[cb](e);
			}
			return false;
		});

		return $templateHtml;
	},
	handleClick: function( e, data ){

		e.preventDefault();

		// Trigger local callback for data-click property
		if( data.click && $.isFunction(this[data.click]) ){
			this[data.click]( e, data );
		}

		if( data.notification ){
			this.getPlayer().sendNotification( data.notification, data );
		}

		return false;
	},
	bind: function( eventName, callback ){
		var bindEventsString = '',
			events = eventName.split(" "),
			totalEvents = events.length,
			i = 0,
			space = ' ';

		for( i; i<totalEvents; i++ ){
			if( i == (totalEvents-1) ){
				space = '';
			}
			bindEventsString += events[ i ] + this.bindPostFix + space;
		}
		return this.embedPlayer.bindHelper( bindEventsString, callback);
	},
	unbind: function( eventName ){
		eventName += this.bindPostFix;
		return this.embedPlayer.unbindHelper( eventName );
	},
	log: function( msg ){
		mw.log( this.pluginName + '::' + msg );
	},
	bindConfigChangeEvent: function(){
		var _this = this;
		if( typeof this.onConfigChange !== 'function' ){
			return ;
		}
		this.bind('Kaltura_ConfigChanged', function(event, pluginName, property, value){
			if( pluginName === _this.pluginName ){
				_this.onConfigChange( property, value );
			}
		});
	},
	getKalturaClient: function() {
		if( ! this.kClient ) {
			this.kClient = mw.kApiGetPartnerClient( this.embedPlayer.kwidgetid );
		}
		return this.kClient;
	},
	destroy: function(){
		this.unbind();
	}
});

} )( window.mw, window.jQuery );<|endoftext|>


<commit_before>const hardLimit = 10

/**
 * Increment the "slot not found" counter.
 * When the counter reach its limit, the "notExtracted" flag is set and will make trigger the "On not found" transition.
 * @hidden true
 * @param retryAttempts The maximum number of times a slot extraction gets retried
 */
const slotNotFound = async retryAttempts => {
  if (!session.extractedSlots.notFound) {
    session.extractedSlots.notFound = 1
  }

  if (session.extractedSlots.notFound < Math.min(Number(retryAttempts), hardLimit) {
    session.extractedSlots.notFound++
  } else {
    temp.notExtracted = 'true'
  }
}

return slotNotFound(args.retryAttempts)
<commit_msg>fix(basic-skills): synthax error<commit_after>const hardLimit = 10

/**
 * Increment the "slot not found" counter.
 * When the counter reach its limit, the "notExtracted" flag is set and will make trigger the "On not found" transition.
 * @hidden true
 * @param retryAttempts The maximum number of times a slot extraction gets retried
 */
const slotNotFound = async retryAttempts => {
  if (!session.extractedSlots.notFound) {
    session.extractedSlots.notFound = 1
  }

  if (session.extractedSlots.notFound < Math.min(Number(retryAttempts), hardLimit)) {
    session.extractedSlots.notFound++
  } else {
    temp.notExtracted = 'true'
  }
}

return slotNotFound(args.retryAttempts)
<|endoftext|>


<commit_before>(function() {

	var Helper = require('./helper.js');

	var Geocoder = require('./geocoder.js');

	/**
	* Geocoder Facotry
	*/
	var GeocoderFactory = {

		/**
		* Return an http adapter by name
		* @param  <string> adapterName adapter name
		* @return <object>
		*/
		_getHttpAdapter: function(adapterName) {

			if (adapterName === 'http') {
				var HttpAdapter = new require('./httpadapter/httpadapter.js');

				return new HttpAdapter(require('http'));
			}

			if (adapterName === 'https') {
				var HttpsAdapter = new require('./httpadapter/httpadapter.js');

				return new HttpsAdapter(require('https'));
			}
		},
		/**
		* Return a geocoder adapter by name
		* @param  <string> adapterName adapter name
		* @return <object>
		*/
		_getGeocoder: function(geocoderName, adapter, extra) {
			if (geocoderName === 'google') {
				var GoogleGeocoder = new require('./geocoder/googlegeocoder.js');

				return new GoogleGeocoder(adapter, {clientId: extra.clientId, apiKey: extra.apiKey, language: extra.language});
			}
            if (geocoderName === 'agol') {
                var AGOLGeocoder = new require('./geocoder/agolgeocoder.js');

                return new AGOLGeocoder(adapter, {client_id:extra.client_id, client_secret:extra.client_secret});
            }
			if (geocoderName === 'freegeoip') {
				var FreegeoipGeocoder = new require('./geocoder/freegeoipgeocoder.js');

				return new FreegeoipGeocoder(adapter);
			}
			if (geocoderName === 'datasciencetoolkit') {
				var DataScienceToolkitGeocoder = new require('./geocoder/datasciencetoolkitgeocoder.js');

				return new DataScienceToolkitGeocoder(adapter, {host: extra.host});
			}
			if (geocoderName === 'openstreetmap') {
				var OpenStreetMapGeocoder = new require('./geocoder/openstreetmapgeocoder.js');

				return new OpenStreetMapGeocoder(adapter, {language: extra.language});
			}
			if (geocoderName === 'mapquest') {
				var MapQuestGeocoder = new require('./geocoder/mapquestgeocoder.js');

				return new MapQuestGeocoder(adapter, extra.apiKey);
			}
			if (geocoderName === 'openmapquest') {
				var OpenMapQuestGeocoder = new require('./geocoder/openmapquestgeocoder.js');

				return new OpenMapQuestGeocoder(adapter, extra.apiKey);
			}
			if (geocoderName === 'nominatimmapquest') {
				var NominatimMapquestGeocoder = new require('./geocoder/nominatimmapquestgeocoder.js');

				return new NominatimMapquestGeocoder(adapter, {language: extra.language});
			}
			if (geocoderName === 'tomtom') {
				var TomTomGeocoder = new require('./geocoder/tomtomgeocoder.js');

				return new TomTomGeocoder(adapter, {apiKey: extra.apiKey});
			}
      if (geocoderName === 'smartystreets') {
        var SmartyStreets = new require('./geocoder/smartystreetsgeocoder.js');

        return new SmartyStreets(adapter, extra.auth_id, extra.auth_token);
      }

			throw new Error('No geocoder provider find for : ' + geocoderName);
		},
		/**
		* Return an formatter adapter by name
		* @param  <string> adapterName adapter name
		* @return <object>
		*/
		_getFormatter: function(formatterName, extra) {
			if (formatterName === 'gpx') {
				var GpxFormatter = new require('./formatter/gpxformatter.js');

				return new GpxFormatter();
			}

			if (formatterName === 'string') {
				var StringFormatter = new require('./formatter/stringformatter.js');

				return new StringFormatter(extra.formatterPattern);
			}
		},
		/**
		* Return a geocoder
		* @param  <string|object> geocoderAdapter Geocoder adapter name or adapter object
		* @param  <string|object> httpAdapter     Http adapter name or adapter object
		* @param  <array>         extra           Extra parameters array
		* @return <object>
		*/
		getGeocoder: function(geocoderAdapter, httpAdapter, extra) {

			if (!httpAdapter || httpAdapter === 'undefined') {
				httpAdapter = 'http';
			}

			if (!extra || extra == 'undefinded') {
				extra = {};
			}

			if (Helper.isString(httpAdapter)) {
				httpAdapter = this._getHttpAdapter(httpAdapter);
			}

			if (Helper.isString(geocoderAdapter)) {
				geocoderAdapter = this._getGeocoder(geocoderAdapter, httpAdapter, extra);
			}

			formatter = extra.formatter;

			if (Helper.isString(formatter)) {
				formatter = this._getFormatter(formatter, extra);
			}

			var geocoder = new Geocoder(geocoderAdapter, formatter);

			return geocoder;
		}

	};

	module.exports = GeocoderFactory;

})();
<commit_msg>Added OpenCage to the factory list<commit_after>(function() {

	var Helper = require('./helper.js');

	var Geocoder = require('./geocoder.js');

	/**
	* Geocoder Facotry
	*/
	var GeocoderFactory = {

		/**
		* Return an http adapter by name
		* @param  <string> adapterName adapter name
		* @return <object>
		*/
		_getHttpAdapter: function(adapterName) {

			if (adapterName === 'http') {
				var HttpAdapter = new require('./httpadapter/httpadapter.js');

				return new HttpAdapter(require('http'));
			}

			if (adapterName === 'https') {
				var HttpsAdapter = new require('./httpadapter/httpadapter.js');

				return new HttpsAdapter(require('https'));
			}
		},
		/**
		* Return a geocoder adapter by name
		* @param  <string> adapterName adapter name
		* @return <object>
		*/
		_getGeocoder: function(geocoderName, adapter, extra) {
			if (geocoderName === 'google') {
				var GoogleGeocoder = new require('./geocoder/googlegeocoder.js');

				return new GoogleGeocoder(adapter, {clientId: extra.clientId, apiKey: extra.apiKey, language: extra.language});
			}
            if (geocoderName === 'agol') {
                var AGOLGeocoder = new require('./geocoder/agolgeocoder.js');

                return new AGOLGeocoder(adapter, {client_id:extra.client_id, client_secret:extra.client_secret});
            }
			if (geocoderName === 'freegeoip') {
				var FreegeoipGeocoder = new require('./geocoder/freegeoipgeocoder.js');

				return new FreegeoipGeocoder(adapter);
			}
			if (geocoderName === 'datasciencetoolkit') {
				var DataScienceToolkitGeocoder = new require('./geocoder/datasciencetoolkitgeocoder.js');

				return new DataScienceToolkitGeocoder(adapter, {host: extra.host});
			}
			if (geocoderName === 'openstreetmap') {
				var OpenStreetMapGeocoder = new require('./geocoder/openstreetmapgeocoder.js');

				return new OpenStreetMapGeocoder(adapter, {language: extra.language});
			}
			if (geocoderName === 'mapquest') {
				var MapQuestGeocoder = new require('./geocoder/mapquestgeocoder.js');

				return new MapQuestGeocoder(adapter, extra.apiKey);
			}
			if (geocoderName === 'openmapquest') {
				var OpenMapQuestGeocoder = new require('./geocoder/openmapquestgeocoder.js');

				return new OpenMapQuestGeocoder(adapter, extra.apiKey);
			}
			if (geocoderName === 'opencage') {
				var OpenCageGeocoder = new require('./geocoder/opencagegeocoder.js');
				return new OpenCageGeocoder(adapter, extra.apiKey, extra);
			}
			if (geocoderName === 'nominatimmapquest') {
				var NominatimMapquestGeocoder = new require('./geocoder/nominatimmapquestgeocoder.js');

				return new NominatimMapquestGeocoder(adapter, {language: extra.language});
			}
			if (geocoderName === 'tomtom') {
				var TomTomGeocoder = new require('./geocoder/tomtomgeocoder.js');

				return new TomTomGeocoder(adapter, {apiKey: extra.apiKey});
			}
      if (geocoderName === 'smartystreets') {
        var SmartyStreets = new require('./geocoder/smartystreetsgeocoder.js');

        return new SmartyStreets(adapter, extra.auth_id, extra.auth_token);
      }

			throw new Error('No geocoder provider find for : ' + geocoderName);
		},
		/**
		* Return an formatter adapter by name
		* @param  <string> adapterName adapter name
		* @return <object>
		*/
		_getFormatter: function(formatterName, extra) {
			if (formatterName === 'gpx') {
				var GpxFormatter = new require('./formatter/gpxformatter.js');

				return new GpxFormatter();
			}

			if (formatterName === 'string') {
				var StringFormatter = new require('./formatter/stringformatter.js');

				return new StringFormatter(extra.formatterPattern);
			}
		},
		/**
		* Return a geocoder
		* @param  <string|object> geocoderAdapter Geocoder adapter name or adapter object
		* @param  <string|object> httpAdapter     Http adapter name or adapter object
		* @param  <array>         extra           Extra parameters array
		* @return <object>
		*/
		getGeocoder: function(geocoderAdapter, httpAdapter, extra) {

			if (!httpAdapter || httpAdapter === 'undefined') {
				httpAdapter = 'http';
			}

			if (!extra || extra == 'undefinded') {
				extra = {};
			}

			if (Helper.isString(httpAdapter)) {
				httpAdapter = this._getHttpAdapter(httpAdapter);
			}

			if (Helper.isString(geocoderAdapter)) {
				geocoderAdapter = this._getGeocoder(geocoderAdapter, httpAdapter, extra);
			}

			formatter = extra.formatter;

			if (Helper.isString(formatter)) {
				formatter = this._getFormatter(formatter, extra);
			}

			var geocoder = new Geocoder(geocoderAdapter, formatter);

			return geocoder;
		}

	};

	module.exports = GeocoderFactory;

})();
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import {
  StyleSheet,
  Text,
  View,
} from 'react-native';

class Story extends Component{
  render() {
    return (
      <View style={styles.container}>
        <Text>Story 7</Text>
      </View>
    )
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
   fontSize: 20,
   alignSelf: 'center',
   margin: 40
  },
});

module.exports = Story;
<commit_msg>Fill in stories class with title,content and add selectors to styles<commit_after>import React, { Component } from 'react';

import {
  StyleSheet,
  Text,
  View,
} from 'react-native';

class Story extends Component{
  render() {
    return (
      <View style={styles.container}>
        <Text>Day 7</Text>
          <Text style={styles.title}> My neighbor Amira </Text>
          <Text style={styles.content}> Today I met another girl my age named Amira, her family is like mine...</Text>
      </View>
    )
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
   fontSize: 20,
   alignSelf: 'center',
   margin: 40
  },
  content: {
    alignSelf: 'center',
    fontSize: 21,
    marginTop: 10,
    marginBottom: 5,
  }
});

module.exports = Story;
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
    path = require('path'),
    mongoose = require('mongoose'),
  users = require('../../controllers/users.server.controller');
  var User = mongoose.model('User');
  var FB = require('fb');
  var errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
        var iframe = JSON.stringify(profile);
        console.log(JSON.stringify(profile));
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        var Friendslists ='';

        FB.api('/me/friends', function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }
            var Friends='';

            Friends = JSON.stringify(res.data,["name"]).replace(/name/g,'displayName');

            show_results(res,Friends);

            console.log('FriendsList1:' + Friends);
            console.log('Facebook.id:' + res.data[0].id);
            console.log('Friend.Name:' + res.data[0].name);
        });

        function show_results(results,friend) {

           Friendslists = JSON.stringify(results.data,["name"]).replace(/name/g,'displayName');

            console.log('newFRIENDSlist::'+friend);

            var parent = User.find({
                $or:friend
            });

            var cursor = User.find({$or:friend}, function(err, cursor) {

                console.log('results::'+ JSON.stringify(results));

            });

            console.log("parent::"+ cursor);

            cursor.exec(function (err, person) {
                if (err) {
                    console.log("parent error"+errorHandler.getErrorMessage(err));
                    return errorHandler.getErrorMessage(err);
                }
                console.log('person:::%s .',person); // Space Ghost is a talk show host.
            });

          }

    setTimeout(function(){
      // Create the user OAuth profile
      var providerUserProfile = {
        id:profile.id,
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        friends:Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

    },Math.random() * 2000);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<commit_msg>global declaration<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
    path = require('path'),
    mongoose = require('mongoose'),
  users = require('../../controllers/users.server.controller');
  var User = mongoose.model('User');
  var FB = require('fb');
  var errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;
        var iframe = JSON.stringify(profile);
        console.log(JSON.stringify(profile));
      providerData.accessToken = accessToken;
      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        var Friendslists ='';

        FB.api('/me/friends', function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }
            var Friends='';

            Friends = JSON.stringify(res.data,["name"]).replace(/name/g,'displayName');

            show_results(res,Friends);

            console.log('FriendsList1:' + Friends);
            console.log('Facebook.id:' + res.data[0].id);
            console.log('Friend.Name:' + res.data[0].name);
        });

        function show_results(results,friend) {

           Friendslists = JSON.stringify(results.data,["name"]).replace(/name/g,'displayName');

            console.log('newFRIENDSlist::'+friend);

            var parent = User.find({
                $or:friend
            });

            var cursor = User.find({$or:friend}, function(err, cursor) {

                if (err) {
                    console.log("parent error"+errorHandler.getErrorMessage(err));
                    return errorHandler.getErrorMessage(err);
                }

                console.log('results::'+ JSON.stringify(results));

            });

            console.log("parent::"+ cursor);

            cursor.exec(function (err, person) {
                if (err) {
                    console.log("parent error"+errorHandler.getErrorMessage(err));
                    return errorHandler.getErrorMessage(err);
                }
                console.log('person:::%s .',person); // Space Ghost is a talk show host.
            });

          }

    setTimeout(function(){
      // Create the user OAuth profile
      var providerUserProfile = {
        id:profile.id,
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        friends:Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

    },Math.random() * 2000);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<|endoftext|>


<commit_before>'use strict'
const slapp  = require('../slackSetup.js').slapp
const getRadius = require('../radius.js').getRadius
const tinyurl = require('tinyurl');

//db imports
const firebase    = require('../firebaseSetup.js'),
      db = firebase.db,
      snaps = firebase.snaps,
      tags = firebase.tags,
      users = firebase.users

let jaywalk  = function() {
  let randomNum = 0;
  slapp.command('/jaywalk', (msg, text) => {
    randomNum = (Math.floor(Math.random() * 1400) + 200)

    msg
      .say({
        text: '',
        attachments: [{
          text: 'Where do you want to Jaywalk to?',
          fallback: 'Where to today?',
          callback_id: 'doit_confirm_callback',
          actions: [{
              name: 'answer',
              text: 'Boomtown',
              type: 'button',
              value: 'boomtown'
            },
            {
              name: 'answer',
              text: 'WeWork',
              type: 'button',
              value: 'wework'
            }
          ]
        }]
      })
        .route('getDbinfo', {
          id: text
        })
  })
  .route('getDbinfo', (msg, state) => {
    let answer = msg.body.actions[0].value
    // user may not have typed text as their next action, ask again and re-route
    // if (!randSnap || !randTag) {
    //   return msg
    //     .say("Whoops, you just have to pick a button...")
    //     .say('Click a button!')
    //     .route('getid1', state)
    // }
    let body
    let testSnapLocation

    if(answer == 'boomtown'){
      testSnapLocation = getRadius(39.758451,-105.007625) //test: snap #1055
    }else if(answer == 'wework'){
      testSnapLocation = getRadius(40.018689, -105.279993) //test: snap #1055
    }else{
      return msg
        .say("Whoops, you just have to pick a button...")
        .say('Click a button!')
        .route('getDbinfo', state)
    }
    let snapLat = snaps
      .orderByChild('lat')
      .startAt(testSnapLocation[5].lat + "-") // "-"makes a string for query
      .endAt(testSnapLocation[1].lat + "-")
      .once('value')
      .then(function(snap) {
        snap.forEach(function(data) {
          //if returns lng within radius (east/west)
          if (data.val().lng <= radius[0].lng && data.val().lng >= radius[3].lng  && count <4) {
            // console.log(data.val().title)
            let body = data.val()
            count ++
            let callback = function(picUrl){
              msg.say({
                  text: `Deal ${count}: \n
                              ${body.description}\n
                              ${picUrl}\n
                              ${body.address}\n`
              }) //end msg.say
            }
            tinyurl.shorten(body.picture, function(res) {
              callback(res)
            })

          } //end if (lng checker)
        }) //end foreach
      }) //end .then
  }
}
module.exports = {
  jaywalk: jaywalk()
}

<commit_msg>forgot count var<commit_after>'use strict'
const slapp  = require('../slackSetup.js').slapp
const getRadius = require('../radius.js').getRadius
const tinyurl = require('tinyurl');

//db imports
const firebase    = require('../firebaseSetup.js'),
      db = firebase.db,
      snaps = firebase.snaps,
      tags = firebase.tags,
      users = firebase.users

let jaywalk  = function() {
  let randomNum = 0;
  slapp.command('/jaywalk', (msg, text) => {
    randomNum = (Math.floor(Math.random() * 1400) + 200)

    msg
      .say({
        text: '',
        attachments: [{
          text: 'Where do you want to Jaywalk to?',
          fallback: 'Where to today?',
          callback_id: 'doit_confirm_callback',
          actions: [{
              name: 'answer',
              text: 'Boomtown',
              type: 'button',
              value: 'boomtown'
            },
            {
              name: 'answer',
              text: 'WeWork',
              type: 'button',
              value: 'wework'
            }
          ]
        }]
      })
        .route('getDbinfo', {
          id: text
        })
  })
  .route('getDbinfo', (msg, state) => {
    let answer = msg.body.actions[0].value
    // user may not have typed text as their next action, ask again and re-route
    // if (!randSnap || !randTag) {
    //   return msg
    //     .say("Whoops, you just have to pick a button...")
    //     .say('Click a button!')
    //     .route('getid1', state)
    // }
    let testSnapLocation

    if(answer == 'boomtown'){
      testSnapLocation = getRadius(39.758451,-105.007625) //test: snap #1055
    }else if(answer == 'wework'){
      testSnapLocation = getRadius(40.018689, -105.279993) //test: snap #1055
    }else{
      return msg
        .say("Whoops, you just have to pick a button...")
        .say('Click a button!')
        .route('getDbinfo', state)
    }
    let snapLat = snaps
      .orderByChild('lat')
      .startAt(testSnapLocation[5].lat + "-") // "-"makes a string for query
      .endAt(testSnapLocation[1].lat + "-")
      .once('value')
      .then(function(snap) {
        let body
        let count = 0
        snap.forEach(function(data) {
          //if returns lng within radius (east/west)
          if (data.val().lng <= radius[0].lng && data.val().lng >= radius[3].lng  && count <4) {
            // console.log(data.val().title)
            let body = data.val()
            count ++
            let callback = function(picUrl){
              msg.say({
                  text: `Deal ${count}: \n
                              ${body.description}\n
                              ${picUrl}\n
                              ${body.address}\n`
              }) //end msg.say
            }
            tinyurl.shorten(body.picture, function(res) {
              callback(res)
            })

          } //end if (lng checker)
        }) //end foreach
      }) //end .then
  }
}
module.exports = {
  jaywalk: jaywalk()
}

<|endoftext|>


<commit_before>'use strict'
const slapp = require('../slackSetup.js').slapp
const getRadius = require('../radius.js').getRadius
const tinyurl = require('tinyurl');
const request = require('request')
const where = require('node-where')

// route functions
const snapsByGeo = require('./routes/snapsByGeoRoute.js').snapsByGeo
const routeFuncs = require('./routes/routesIndex.js')
const yes = require('./routes/yes.js').yes
const addressToGeo = require('./routes/addressToGeo.js').addressToGeo
const appDl = require('./routes/appDlRoute.js').appDl
const teamSettings = require('../teamSettings.js').teamSettings

const notify = require('./notifySlash.js').notify

//db imports
const firebase    = require('../firebaseSetup.js'),
      db = firebase.db,
      snaps = firebase.snaps,
      tags = firebase.tags,
      users = firebase.users,
      slackDb = firebase.slackDb

let jayBtns={
  text: "",
  attachments: [{
    text: 'How can I help?',
    fallback: 'Where to today?',
    callback_id: 'jaywalk_callback',
    color: 'good',
    actions: [
      {
        name: 'answer',
        text: 'Find deals',
        type: 'button',
        value: 'address'
      },{
        name: 'answer',
        text: 'Settings',
        type: 'button',
        value: 'settings'
      },{
        name: 'answer',
        text: 'Download app',
        type: 'button',
        value: 'app'
      }
    ]
  }]
}

const jaywalk = function() {
  let state = { requested: Date.now() }
  let teamId = ''
  let teamInfo = {}
  let answer

  slapp.command('/jaywalk', (msg, text) => {
    return teamInfo = slackDb
      .child(msg.body.team_id)
      .once("value")
      .then(function(obj){
        console.log('.then')

        if(!obj.val()){
          msg
            .say({text:`Welcome to Jaywalk! To get better results, please enter the address or your buisness name and city.`})
            .route('new_address', state, 60)
        } else{
          teamInfo = obj.val()
            msg
              .say(jayBtns)
              .route('requestToDatabase', state, 60)
        }
      })
      .then(function(stuff){
        console.log('stuff')
      })
  })

// slapp.action('jaywalk_callback', 'answer', (msg, value) => {

  .route('requestToDatabase', (msg, state) => {
    if(msg.body.actions==undefined){      // try callback then remove this
      msg.route('requestToDatabase', state, 60)
    }else{
      answer = msg.body.actions[0].value
      if(answer == 'app'){
        appDl(teamInfo,msg,state)
      }else if(answer == 'address'){
        yes(teamInfo,msg,state)
        //https://jaywalk-geo.herokuapp.com/geoloc.htm
        // .route('handleGeoLoc', state, 60)
      }else if(answer == 'settings'){
        teamSettings(teamInfo,msg,state)
      }else if(answer == 'notifications'){
        notify(teamInfo,msg,state)
      }else{ //handle error
        return msg
          .say("Whoops, you just have to pick a button...")
          .say('Click a button!')
          .route('requestToDatabase', state, 60)
      }
    } //end else(actions undefined checker)
  }) //end .route('requestToDatabase')
  // }) //end callback
  .route('relaventAsk', (msg,state) => {
    routeFuncs.relaventAsk(msg,state)
  })//end .route(relaventAsk)
  .route('address_geo', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    where.is(text,function(err,result){
      /*
        result.get('')=>
        address,streetNumber, street,streetAddress,city,region,
        regionCode, postalCode, country, countryCode, lat, lng
      */
      if (result) {
        let lat = result.get('lat')
        let lng = result.get('lng')
        snapsByGeo(lat,lng,msg,state)
      }
    })
  })
  .route('new_address', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    console.log(text)
  })
}
module.exports = {
  jaywalk:jaywalk(),
  jayBtns:jayBtns
}

<commit_msg>asdf.<commit_after>'use strict'
const slapp = require('../slackSetup.js').slapp
const getRadius = require('../radius.js').getRadius
const tinyurl = require('tinyurl');
const request = require('request')
const where = require('node-where')

// route functions
const snapsByGeo = require('./routes/snapsByGeoRoute.js').snapsByGeo
const routeFuncs = require('./routes/routesIndex.js')
const yes = require('./routes/yes.js').yes
const addressToGeo = require('./routes/addressToGeo.js').addressToGeo
const appDl = require('./routes/appDlRoute.js').appDl
const teamSettings = require('../teamSettings.js').teamSettings

const notify = require('./notifySlash.js').notify

//db imports
const firebase    = require('../firebaseSetup.js'),
      db = firebase.db,
      snaps = firebase.snaps,
      tags = firebase.tags,
      users = firebase.users,
      slackDb = firebase.slackDb

let jayBtns={
  text: "",
  attachments: [{
    text: 'How can I help?',
    fallback: 'Where to today?',
    callback_id: 'jaywalk_callback',
    color: 'good',
    actions: [
      {
        name: 'answer',
        text: 'Find deals',
        type: 'button',
        value: 'address'
      },{
        name: 'answer',
        text: 'Settings',
        type: 'button',
        value: 'settings'
      },{
        name: 'answer',
        text: 'Download app',
        type: 'button',
        value: 'app'
      }
    ]
  }]
}

const jaywalk = function() {
  let state = { requested: Date.now() }
  let teamId = ''
  let teamInfo = {}
  let answer

  slapp.command('/jaywalk', (msg, text) => {
    return teamInfo = slackDb
      .child(msg.body.team_id)
      .once("value")
      .then(function(obj){
        if(!obj.val()){
          console.log('!obj')
          msg
            .say({text:`Welcome to Jaywalk! To get better results, please enter the address or your buisness name and city.`})
            .route('new_address', state, 60)
        } else{
          teamInfo = obj.val()
            msg
              .say(jayBtns)
              .route('requestToDatabase', state, 60)
        }
      })
      .then(function(stuff){
        console.log('stuff')
      })
  })

// slapp.action('jaywalk_callback', 'answer', (msg, value) => {

  .route('requestToDatabase', (msg, state) => {
    if(msg.body.actions==undefined){      // try callback then remove this
      msg.route('requestToDatabase', state, 60)
    }else{
      answer = msg.body.actions[0].value
      if(answer == 'app'){
        appDl(teamInfo,msg,state)
      }else if(answer == 'address'){
        yes(teamInfo,msg,state)
        //https://jaywalk-geo.herokuapp.com/geoloc.htm
        // .route('handleGeoLoc', state, 60)
      }else if(answer == 'settings'){
        teamSettings(teamInfo,msg,state)
      }else if(answer == 'notifications'){
        notify(teamInfo,msg,state)
      }else{ //handle error
        return msg
          .say("Whoops, you just have to pick a button...")
          .say('Click a button!')
          .route('requestToDatabase', state, 60)
      }
    } //end else(actions undefined checker)
  }) //end .route('requestToDatabase')
  // }) //end callback
  .route('relaventAsk', (msg,state) => {
    routeFuncs.relaventAsk(msg,state)
  })//end .route(relaventAsk)
  .route('address_geo', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    where.is(text,function(err,result){
      /*
        result.get('')=>
        address,streetNumber, street,streetAddress,city,region,
        regionCode, postalCode, country, countryCode, lat, lng
      */
      if (result) {
        let lat = result.get('lat')
        let lng = result.get('lng')
        snapsByGeo(lat,lng,msg,state)
      }
    })
  })
  .route('new_address', (msg,state) => {
    let text = (msg.body.event && msg.body.event.text) || ''
    console.log(text)
  })
}
module.exports = {
  jaywalk:jaywalk(),
  jayBtns:jayBtns
}

<|endoftext|>


<commit_before>/**
 * Add the defineProperty method if it doesn't exist yet,
 * this will only support .value setters
 *
 * @author    Jelle De Loecker   <jelle@codedor.be>
 * @since     0.1.0
 * @version   0.1.0
 */
if (!Object.defineProperty || (typeof navigator !== 'undefined' && navigator.appVersion.indexOf('MSIE 8') > -1)) {
	Object.defineProperty = function defineProperty(obj, name, settings) {
		obj[name] = settings.value;
	};
}

/**
 * Define a non-enumerable property
 *
 * @author    Jelle De Loecker   <jelle@codedor.be>
 * @since     0.1.0
 * @version   0.1.0
 *
 * @param     {Object}   target   The object to add the property to
 * @param     {String}   name     The name of the property
 * @param     {Object}   value    The value of the property
 */
Object.defineProperty(Object, 'defineValue', {
	value: function defineValue(target, name, value) {
		Object.defineProperty(target, name, {
			value: value,
			enumerable: false,
			configurable: false,
			writeable: false
		});
	}
});

(function() {

var defineProperty = Object.defineProperty,
    defineValue    = Object.defineValue;

/**
 * Get the shared value between the 2 arrays
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Array}     arr            The array to test agains
 * @param    {Function}  CastFunction   Function to use to cast values
 *
 * @return   {Array}
 */
defineValue(Array.prototype, 'shared', function shared(arr, CastFunction) {

	// Make sure the given value to match against is an array
	if (!Array.isArray(arr)) {
		arr = [arr];
	}

	// Go over every item in the array, and return the ones they have in common
	return this.filter(function(value) {

		var test, i;

		// Cast the value if a cast function is given
		value = CastFunction ? CastFunction(value) : value;

		// Go over every item in the second array
		for (i = 0; i < arr.length; i++) {

			// Also cast that value
			test = CastFunction ? CastFunction(arr[i]) : arr[i];

			// If the values match, add this value to the array
			if (value == test) {
				return true;
			}
		}

		return false;
	});
});

/**
 * Get the values from the first array that are not in the second array,
 * basically: remove all the values in the second array from the first one
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Array}     arr            The array to test agains
 * @param    {Function}  CastFunction   Function to use to cast values
 *
 * @return   {Array}
 */
defineValue(Array.prototype, 'difference', function difference(arr, CastFunction) {

	// Make sure the given value to match against is an array
	if (!Array.isArray(arr)) {
		arr = [arr];
	}

	// Go over every item in the array,
	// and return the ones that are not in the second array
	return this.filter(function(value, index) {

		var test, i;

		// Cast the value if a cast function is given
		value = CastFunction ? CastFunction(value) : value;

		// Go over every item in the second array
		for (i = 0; i < arr.length; i++) {

			// Also cast that value
			test = CastFunction ? CastFunction(arr[i]) : arr[i];

			// If the values match, we should NOT add this
			if (value == test) {
				return false;
			}
		}

		return true;
	});
});

/**
 * Get all the values that are either in the first or in the second array,
 * but not in both
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Array}     arr            The array to test agains
 * @param    {Function}  CastFunction   Function to use to cast values
 *
 * @return   {Array}
 */
defineValue(Array.prototype, 'exclusive', function exclusive(arr, CastFunction) {

	// Get all the shared values
	var shared = this.shared(arr);

	// Return the merged differences between the 2
	return this.difference(shared).concat(arr.difference(shared));
});

/**
 * Hash a (small) string very fast
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @return   {Number}
 */
defineValue(String.prototype, 'numberHash', function hash() {

	var str = this,
	    res = 0,
	    len = str.length,
	    i   = -1;

	while (++i < len) {
		res = res * 31 + str.charCodeAt(i);
	}

	return res;
});

// Generate the crc32 table
var crc32table = (function() {
	var value, pos, i;
	var table = [];

	for (pos = 0; pos < 256; ++pos) {
		value = pos;
		for (i = 0; i < 8; ++i) {
			value = (value & 1) ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
		}
		table[pos] = value >>> 0;
	}

	return table;
})();

/**
 * Generate a checksum (crc32 hash)
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @return   {String}
 */
defineValue(String.prototype, 'checksum', function checksum() {

	var str = this,
	    crc = 0 ^ (-1),
	    i;

	for (i = 0; i < str.length; i++ ) {
		crc = (crc >>> 8) ^ crc32table[(crc ^ str.charCodeAt(i)) & 0xFF];
	}

	return (crc ^ (-1)) >>> 0;
});

/**
 * Get all the placeholders inside a string
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @return   {Array}
 */
defineValue(String.prototype, 'placeholders', function placeholders() {

	var regex  = /:(.*?)(?:\/|$)/g,
	    result = [],
	    match;

	while (match = regex.exec(this)) {
		if (typeof match[1] !== 'undefined') {
			result.push(match[1]);
		}
	}

	return result;
});

/**
 * Replace all the placeholders inside a string
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}   values
 *
 * @return   {String}
 */
defineValue(String.prototype, 'fillPlaceholders', function fillPlaceholders(values) {

	var result = ''+this,
	    params,
	    value,
	    regex,
	    match,
	    repl,
	    ori,
	    i;

	if (values && typeof values == 'object') {
		params = this.placeholders();

		for (i = 0; i < params.length; i++) {

			regex = new RegExp('(:' + params[i] + ')(?:\\/|$)', 'g');
			value = Object.path(values, params[i]);

			if (value || value === 0) {

				while (match = regex.exec(result)) {

					// Get the original value
					ori = match[0];

					// Generate the replacement
					repl = ori.replace(match[1], value);

					// Replace the original with the replacement in the string
					result = result.replace(ori, repl);
				}
			}
		}
	}

	return result;
});

/**
 * Get the value of the given property path
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}   obj
 * @param    {String}   path   The dot notation path
 *
 * @return   {Mixed}
 */
defineValue(Object, 'path', function path(obj, path) {

	var pieces,
	    result,
	    here,
	    key,
	    end,
	    i;

	if (typeof path !== 'string') {
		return;
	}

	pieces = path.split('.');

	here = obj;

	// Go over every piece in the path
	for (i = 0; i < pieces.length; i++) {

		// Get the current key
		key = pieces[i];

		if (here !== null && here !== undefined) {
			here = here[key];

			// Is this the final piece?
			end = ((i+1) == pieces.length);

			if (end) {
				result = here;
			}
		}
	}

	return result;
});

/**
 * See if the given path exists inside an object,
 * even if that value is undefined
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}   obj
 * @param    {String}   path   The dot notation path
 *
 * @return   {Mixed}
 */
defineValue(Object, 'exists', function exists(obj, path) {

	var pieces = path.split('.'),
	    result = false,
	    hereType,
	    here,
	    key,
	    end,
	    i;

	// Set the object as the current position
	here = obj;

	// Go over every piece in the path
	for (i = 0; i < pieces.length; i++) {

		// Get the current key
		key = pieces[i];
		hereType = typeof here;

		if (here === null || here === undefined) {
			return false;
		}

		if (here !== null && here !== undefined) {

			// Is this the final piece?
			end = ((i+1) == pieces.length);

			if (end) {
				if (here[key] || ((hereType == 'object' || hereType == 'function') && key in here)) {
					result = true;
				}
				break;
			}

			here = here[key];
		}
	}

	return result;
});

/**
 * Determine if the object is empty
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}   obj
 * @param    {Boolean}  includePrototype   If true, prototypal properties also count
 *
 * @return   {Boolean}
 */
defineValue(Object, 'isEmpty', function isEmpty(obj, includePrototype) {

	var key;

	if (!obj) {
		return true;
	}

	for(key in obj) {
		if (includePrototype || obj.hasOwnProperty(key)) {
			return false;
		}
	}

	return true;
});

/**
 * Cast a variable to an array.
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Mixed}   variable
 */
defineValue(Array, 'cast', function cast(variable) {

	if (Array.isArray(variable)) {
		// Return the variable unmodified if it's already an array
		return variable;
	} else {
		// Return the variable wrapped in an array otherwise
		return [variable];
	}
});

/**
 * Iterate over an object's properties
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}     obj
 * @param    {Function}   fnc
 */
defineValue(Object, 'each', function each(obj, fnc) {

	var key;

	for (key in obj) {
		fnc(obj[key], key, obj);
	}
});

/**
 * Map an object
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}     obj
 * @param    {Function}   fnc
 *
 * @return   {Object}
 */
defineValue(Object, 'map', function map(obj, fnc) {

	var mapped = {};

	Object.each(obj, function mapEach(value, key) {
		mapped[key] = fnc(value, key, obj);
	});

	return mapped;
});

/**
 * Create a new date object
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.1.0
 * @version  0.1.0
 */
defineValue(Date, 'create', function create() {
	return new Date();
});

}());<commit_msg>Array.cast converts array-like objects to regular arrays (but not Strings)<commit_after>/**
 * Add the defineProperty method if it doesn't exist yet,
 * this will only support .value setters
 *
 * @author    Jelle De Loecker   <jelle@codedor.be>
 * @since     0.1.0
 * @version   0.1.0
 */
if (!Object.defineProperty || (typeof navigator !== 'undefined' && navigator.appVersion.indexOf('MSIE 8') > -1)) {
	Object.defineProperty = function defineProperty(obj, name, settings) {
		obj[name] = settings.value;
	};
}

/**
 * Define a non-enumerable property
 *
 * @author    Jelle De Loecker   <jelle@codedor.be>
 * @since     0.1.0
 * @version   0.1.0
 *
 * @param     {Object}   target   The object to add the property to
 * @param     {String}   name     The name of the property
 * @param     {Object}   value    The value of the property
 */
Object.defineProperty(Object, 'defineValue', {
	value: function defineValue(target, name, value) {
		Object.defineProperty(target, name, {
			value: value,
			enumerable: false,
			configurable: false,
			writeable: false
		});
	}
});

(function() {

var defineProperty = Object.defineProperty,
    defineValue    = Object.defineValue;

/**
 * Get the shared value between the 2 arrays
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Array}     arr            The array to test agains
 * @param    {Function}  CastFunction   Function to use to cast values
 *
 * @return   {Array}
 */
defineValue(Array.prototype, 'shared', function shared(arr, CastFunction) {

	// Make sure the given value to match against is an array
	if (!Array.isArray(arr)) {
		arr = [arr];
	}

	// Go over every item in the array, and return the ones they have in common
	return this.filter(function(value) {

		var test, i;

		// Cast the value if a cast function is given
		value = CastFunction ? CastFunction(value) : value;

		// Go over every item in the second array
		for (i = 0; i < arr.length; i++) {

			// Also cast that value
			test = CastFunction ? CastFunction(arr[i]) : arr[i];

			// If the values match, add this value to the array
			if (value == test) {
				return true;
			}
		}

		return false;
	});
});

/**
 * Get the values from the first array that are not in the second array,
 * basically: remove all the values in the second array from the first one
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Array}     arr            The array to test agains
 * @param    {Function}  CastFunction   Function to use to cast values
 *
 * @return   {Array}
 */
defineValue(Array.prototype, 'difference', function difference(arr, CastFunction) {

	// Make sure the given value to match against is an array
	if (!Array.isArray(arr)) {
		arr = [arr];
	}

	// Go over every item in the array,
	// and return the ones that are not in the second array
	return this.filter(function(value, index) {

		var test, i;

		// Cast the value if a cast function is given
		value = CastFunction ? CastFunction(value) : value;

		// Go over every item in the second array
		for (i = 0; i < arr.length; i++) {

			// Also cast that value
			test = CastFunction ? CastFunction(arr[i]) : arr[i];

			// If the values match, we should NOT add this
			if (value == test) {
				return false;
			}
		}

		return true;
	});
});

/**
 * Get all the values that are either in the first or in the second array,
 * but not in both
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Array}     arr            The array to test agains
 * @param    {Function}  CastFunction   Function to use to cast values
 *
 * @return   {Array}
 */
defineValue(Array.prototype, 'exclusive', function exclusive(arr, CastFunction) {

	// Get all the shared values
	var shared = this.shared(arr);

	// Return the merged differences between the 2
	return this.difference(shared).concat(arr.difference(shared));
});

/**
 * Hash a (small) string very fast
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @return   {Number}
 */
defineValue(String.prototype, 'numberHash', function hash() {

	var str = this,
	    res = 0,
	    len = str.length,
	    i   = -1;

	while (++i < len) {
		res = res * 31 + str.charCodeAt(i);
	}

	return res;
});

// Generate the crc32 table
var crc32table = (function() {
	var value, pos, i;
	var table = [];

	for (pos = 0; pos < 256; ++pos) {
		value = pos;
		for (i = 0; i < 8; ++i) {
			value = (value & 1) ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
		}
		table[pos] = value >>> 0;
	}

	return table;
})();

/**
 * Generate a checksum (crc32 hash)
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @return   {String}
 */
defineValue(String.prototype, 'checksum', function checksum() {

	var str = this,
	    crc = 0 ^ (-1),
	    i;

	for (i = 0; i < str.length; i++ ) {
		crc = (crc >>> 8) ^ crc32table[(crc ^ str.charCodeAt(i)) & 0xFF];
	}

	return (crc ^ (-1)) >>> 0;
});

/**
 * Get all the placeholders inside a string
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @return   {Array}
 */
defineValue(String.prototype, 'placeholders', function placeholders() {

	var regex  = /:(.*?)(?:\/|$)/g,
	    result = [],
	    match;

	while (match = regex.exec(this)) {
		if (typeof match[1] !== 'undefined') {
			result.push(match[1]);
		}
	}

	return result;
});

/**
 * Replace all the placeholders inside a string
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}   values
 *
 * @return   {String}
 */
defineValue(String.prototype, 'fillPlaceholders', function fillPlaceholders(values) {

	var result = ''+this,
	    params,
	    value,
	    regex,
	    match,
	    repl,
	    ori,
	    i;

	if (values && typeof values == 'object') {
		params = this.placeholders();

		for (i = 0; i < params.length; i++) {

			regex = new RegExp('(:' + params[i] + ')(?:\\/|$)', 'g');
			value = Object.path(values, params[i]);

			if (value || value === 0) {

				while (match = regex.exec(result)) {

					// Get the original value
					ori = match[0];

					// Generate the replacement
					repl = ori.replace(match[1], value);

					// Replace the original with the replacement in the string
					result = result.replace(ori, repl);
				}
			}
		}
	}

	return result;
});

/**
 * Get the value of the given property path
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}   obj
 * @param    {String}   path   The dot notation path
 *
 * @return   {Mixed}
 */
defineValue(Object, 'path', function path(obj, path) {

	var pieces,
	    result,
	    here,
	    key,
	    end,
	    i;

	if (typeof path !== 'string') {
		return;
	}

	pieces = path.split('.');

	here = obj;

	// Go over every piece in the path
	for (i = 0; i < pieces.length; i++) {

		// Get the current key
		key = pieces[i];

		if (here !== null && here !== undefined) {
			here = here[key];

			// Is this the final piece?
			end = ((i+1) == pieces.length);

			if (end) {
				result = here;
			}
		}
	}

	return result;
});

/**
 * See if the given path exists inside an object,
 * even if that value is undefined
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}   obj
 * @param    {String}   path   The dot notation path
 *
 * @return   {Mixed}
 */
defineValue(Object, 'exists', function exists(obj, path) {

	var pieces = path.split('.'),
	    result = false,
	    hereType,
	    here,
	    key,
	    end,
	    i;

	// Set the object as the current position
	here = obj;

	// Go over every piece in the path
	for (i = 0; i < pieces.length; i++) {

		// Get the current key
		key = pieces[i];
		hereType = typeof here;

		if (here === null || here === undefined) {
			return false;
		}

		if (here !== null && here !== undefined) {

			// Is this the final piece?
			end = ((i+1) == pieces.length);

			if (end) {
				if (here[key] || ((hereType == 'object' || hereType == 'function') && key in here)) {
					result = true;
				}
				break;
			}

			here = here[key];
		}
	}

	return result;
});

/**
 * Determine if the object is empty
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}   obj
 * @param    {Boolean}  includePrototype   If true, prototypal properties also count
 *
 * @return   {Boolean}
 */
defineValue(Object, 'isEmpty', function isEmpty(obj, includePrototype) {

	var key;

	if (!obj) {
		return true;
	}

	for(key in obj) {
		if (includePrototype || obj.hasOwnProperty(key)) {
			return false;
		}
	}

	return true;
});

/**
 * Cast a variable to an array.
 * Also turns array-like objects into real arrays, except String objects.
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.1.0
 *
 * @param    {Mixed}   variable
 *
 * @return   {Array}
 */
defineValue(Array, 'cast', function cast(variable) {

	// Return the variable unmodified if it's already an array
	if (Array.isArray(variable)) {
		return variable;
	}

	// Convert array-like objects to regular arrays
	if (variable && typeof variable === 'object') {

		// If the variable has a 'length' property, it could be array-like
		if (variable.length || 'length' in variable) {

			// Skip it if it's a String object (not a string primitive)
			if (variable.constructor.name !== 'String') {
				return Array.prototype.slice.call(variable, 0);
			}
		}
	}

	// Return the variable wrapped in an array otherwise
	return [variable];
});

/**
 * Iterate over an object's properties
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}     obj
 * @param    {Function}   fnc
 */
defineValue(Object, 'each', function each(obj, fnc) {

	var key;

	for (key in obj) {
		fnc(obj[key], key, obj);
	}
});

/**
 * Map an object
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.0.1
 * @version  0.0.1
 *
 * @param    {Object}     obj
 * @param    {Function}   fnc
 *
 * @return   {Object}
 */
defineValue(Object, 'map', function map(obj, fnc) {

	var mapped = {};

	Object.each(obj, function mapEach(value, key) {
		mapped[key] = fnc(value, key, obj);
	});

	return mapped;
});

/**
 * Create a new date object
 *
 * @author   Jelle De Loecker   <jelle@codedor.be>
 * @since    0.1.0
 * @version  0.1.0
 */
defineValue(Date, 'create', function create() {
	return new Date();
});

}());<|endoftext|>


<commit_before>var path = require('path');
module.exports = function jekyllTemplate(answers) {
  return [
    '---',
    'layout: post',
    'title: ' + answers.title,
    'date: ' + answers.date,
    'duration: ' + answers.duration,
    'tags: [' + answers.tags + ']',
    'img: ' + '/assets/image/speakers/' + answers.imagePath,
    'link: ' + answers.link,
    '---',
    ''
  ];
}
<commit_msg>Fix template<commit_after>var path = require('path');
module.exports = function jekyllTemplate(answers) {
  return [
    '---',
    'layout: post',
    'title: ' + answers.title,
    'date: ' + answers.date,
    'duration: ' + answers.duration,
    'tags: [' + answers.tags + ']',
    'img: /assets/image/speakers/' + answers.imagePath,
    'link: ' + answers.link,
    '---',
    ''
  ];
}
<|endoftext|>