<commit_before>;(function( exports ){

	var publisher = pubsub(),
		data 	  = 'data-component',
		selector  = '['+data+']';

	function jails( name, fn ){
		jails.components[ name ] = fn;
	}

	jails.components = {};
	jails.events 	 = on();
	jails.publish 	 = publisher.publish;
	jails.subscribe	 = publisher.subscribe;

	jails.start = function( ctx ){
		ctx = ctx || document.documentElement;
		each( ctx.querySelectorAll(selector), scan, true );
	};

	jails.destroy = function( node ){
		jails.events.trigger( node, 'destroy' );
	};

	jails.render = function( node, html ){
		var child;
		while( child = node.firstChild ){
			if( child.getAttribute && child.getAttribute(data) )
				jails.destroy( child );
			node.removeChild( child );
		}
		node.innerHTML = html;
		jails.start( node );
	};

	jails.component = function( name, node ){

		var instance = {

			name 		:name,
			publish		:publisher.publish,
			subscribe 	:publisher.subscribe,
			on 			:jails.events.on,

			init :function(){},

			destroy: function(){},

			on :function( ev, selectorOrCallback, callback ){
				return jails.events.on( node, ev, selectorOrCallback, callback );
			},

			off :function( ev, handler ){
				jails.events.off( node, ev, handler );
			},

			get :function( cssSelector ){
				return function( name, args ){
					var args = Array.from( arguments );
					var elements = [].concat( node.matches(cssSelector)? node : [] );
						elements = elements.concat( Array.from( node.querySelectorAll(cssSelector) ) );
					each( elements, call(args.shift(), args) );
				};
			},

			emit :function( ){
				var args = Array.from( arguments );
				jails.events.trigger( node, ':' + args.shift(), { args: args, instance : instance });
			},

			__kill :function(){
				instance.destroy();
				for(var i in this ) delete this[i];
				instance = null;
			}
		};

		jails.events.on( node, 'execute', execute( name, instance, node ) );
		jails.events.on( node, 'destroy', destroy( name, instance, node ) );

		return instance;
	};

	function scan( element, index ){
		var names = element.getAttribute(data);
			names = names.split(/\s/);
		each( names, mount( element ) );
	}

	function mount( node ){

		return function( name, index ){
			var id = 'jails#component#'+name;
			if( node[id] || !(name in jails.components) ) return;
			var comp  = jails.component( name, node );
			Object.assign( comp, jails.components[ name ]( comp, node, getter(name, node) ) || comp );
			comp.init();
			node[id] = true;
		};
	}

	function destroy( name, instance, node ){

		return function(e){
			instance.__kill();
			instance = null;
			clean( node );
			e.stopPropagation();
		};
	}

	function clean( node ){
		for(var e in node._events)
			jails.events.off( node, e, node._events[e].eventHandler );
		node._events = null;
		node['jails#component#'+name] = null;
	}

	function getter( name, node ){
		var props;
		return function( key ){
			if( props ) {
				return key? props[key] : props;
			}
			var anno  = annotations( node )[ name ] || {};
			var attrs = { data:{} };
			each(Array.from( node.attributes ), propset(attrs) );
			props = Object.assign({}, anno, attrs);
			return key? props[key] : props;
		};
	}

	function propset( acc ){

		return function( item ){
			var value, name = item.name.split(/data\-/);
			try{ value = item.value in window? item.value :(new Function('return '+ item.value))();}
			catch(err){ value = item.value; }

			if( name[1] ) acc.data[name.pop().replace(/-([a-z])/g, upper)] = value;
			else acc[item.name] = value;

			return acc;
		};
	}

	function upper( m, string ){
		return string.toUpperCase();
	}

	function annotations( el ){

		var ann = {}, comment, code;

		comment = el.previousSibling;
		comment = comment && comment.nodeType == 8? comment :comment? comment.previousSibling : null;

		if(comment && comment.nodeType == 8){
			code = comment.data
				.replace(/@([a-zA-z0-9-\/]*)(?:\((.*)\))?/g, function( text, component, param ){
					ann[component] = new Function('return '+ param)();
				});
		}

		return ann;
	}

	//Inspired by:
	//http://dev.housetrip.com/2014/09/15/decoupling-javascript-apps-using-pub-sub-pattern/
	function pubsub(){

		var topics = {};
		var _async = {};

		return{

			subscribe :function(){

				var args = Array.from( arguments );
				var key = args[0], method = args[1];
				var _self = this;

				if( key in _async && topics[key] ){
					topics[key].push( method );
					_self.publish.apply(null, [key].concat(_async[key]));
				}else{
					topics[key] = topics[key] || [];
					topics[key].push( method );
				}
				//Unsubscribe
				return function(){
					var newtopics = [];
					var newasync  = [];

					each(topics[key], function( fn){
						if(fn != method)
							newtopics.push(fn);
					});

					topics[key] = newtopics;

					each(_async[key], function( fn){
						if(fn != method)
							newasync.push(fn);
					});
					_async[key] = newasync;
				};
			},

			publish :function(){

				var args = Array.from( arguments );
				var key = args.shift();

				topics[key] = topics[key] || [];

				if(!topics[key].length){
					_async[key] = args;
				}

				else each(topics[key], function( f ) {
					if( f ) f.apply( this, args );
				});
			}
		};
	}

	function delegate( node, cssSelector, callback ){
		return function(e){
			var parent = e.target;
			while ( parent && parent !== node ) {
				if (parent.matches(cssSelector))
					callback.call(e.target, e);
				parent = parent.parentNode;
			}
		};
	}

	function execute( name, instance, node ){
		return function(e){
			if( node != e.target ) return;
			var scope  = e.detail.method.split(/\:/),
				method = scope.length > 1? scope[1] : scope[0];
			if( (method in instance) && (!scope[1]) || (scope[1] && name == scope[0]) )
				instance[ method ].apply( instance, e.detail.args );
			e.stopPropagation();
		};
	}

	function call( name, args ){
		return function( element, index ){
			jails.events.trigger( element, 'execute', { args :args, method :name });
		};
	}

	function each( iterable, callback, reverse ){
		iterable = reverse? Array.from(iterable).reverse() : iterable;
		for( var i = 0, len = iterable.length; i < len; i++ )
			callback( iterable[i], i );
	}

	function on(){

		function Ev(type, params) {
			var e = document.createEvent(type);
			params = params || {};
			e.initEvent(type, params.bubbles || false, params.cancelable || false, params.detail || null);
			return e;
		}

		return {

			on :function( el, ev, selectorOrCallback, callback ){

				var custom, isset, fn;

				el._events 	= el._events || {};
				custom 		= ev.split(/\:/);
				ev 			= custom[1]? ':' + custom[1] : custom[0];
				isset  		= (ev in el._events);
				fn     		= callback? delegate( el, selectorOrCallback, handler ) :handler;

				el._events[ev] = el._events[ev] || [];
				el._events[ev].push( callback || selectorOrCallback );

				if( !isset ){
					el.addEventListener(ev, fn, (ev == 'focus' || ev == 'blur') );
					el._events[ev].eventHandler = fn;
				}

				function handler(e){
					var detail = e.detail || {};
					el._events[ev].map(function( cb ){
						if( !detail.instance || !custom[0] || detail.instance.name == custom[0] )
							cb.apply( el, [e].concat( detail.args ) );
					});
				}

				return function(){
					jails.events.off( el, ev, callback || selectorOrCallback );
				};
			},

			off :function(el, ev, fn){
				el.removeEventListener(ev, fn, false);
				el._events[ev] = (el._events[ev] || []).filter(function(cb){ return cb != fn; });
			},

			trigger :function(el, name, args){
				try{
					el.dispatchEvent( new Ev( name, { bubbles :true, detail :args } ) );
				}catch(e){
					el.dispatchEvent( new CustomEvent( name, { bubbles :true, detail :args } ) );
				}
			}
		};
	}

	// UMD export
	if ( typeof define === 'function' && define.amd ) {
		define(function () { return jails; });
	} else if ( typeof module !== 'undefined' && module.exports ){
		module.exports = jails;
	} else {
		exports.jails = jails;
	}
})( window );
<commit_msg>Fix in .on() interface breaking on multiple assignment<commit_after>;(function( exports ){

	var publisher = pubsub(),
		data 	  = 'data-component',
		selector  = '['+data+']';

	function jails( name, fn ){
		jails.components[ name ] = fn;
	}

	jails.components = {};
	jails.events 	 = on();
	jails.publish 	 = publisher.publish;
	jails.subscribe	 = publisher.subscribe;

	jails.start = function( ctx ){
		ctx = ctx || document.documentElement;
		each( ctx.querySelectorAll(selector), scan, true );
	};

	jails.destroy = function( node ){
		jails.events.trigger( node, 'destroy' );
	};

	jails.render = function( node, html ){
		var child;
		while( child = node.firstChild ){
			if( child.getAttribute && child.getAttribute(data) )
				jails.destroy( child );
			node.removeChild( child );
		}
		node.innerHTML = html;
		jails.start( node );
	};

	jails.component = function( name, node ){

		var instance = {

			name 		:name,
			publish		:publisher.publish,
			subscribe 	:publisher.subscribe,
			on 			:jails.events.on,

			init :function(){},

			destroy: function(){},

			on :function( ev, selectorOrCallback, callback ){
				return jails.events.on( node, ev, selectorOrCallback, callback );
			},

			off :function( ev, handler ){
				jails.events.off( node, ev, handler );
			},

			get :function( cssSelector ){
				return function( name, args ){
					var args = Array.from( arguments );
					var elements = [].concat( node.matches(cssSelector)? node : [] );
						elements = elements.concat( Array.from( node.querySelectorAll(cssSelector) ) );
					each( elements, call(args.shift(), args) );
				};
			},

			emit :function( ){
				var args = Array.from( arguments );
				jails.events.trigger( node, ':' + args.shift(), { args: args, instance : instance });
			},

			__kill :function(){
				instance.destroy();
				for(var i in this ) delete this[i];
				instance = null;
			}
		};

		jails.events.on( node, 'execute', execute( name, instance, node ) );
		jails.events.on( node, 'destroy', destroy( name, instance, node ) );

		return instance;
	};

	function scan( element, index ){
		var names = element.getAttribute(data);
			names = names.split(/\s/);
		each( names, mount( element ) );
	}

	function mount( node ){

		return function( name, index ){
			var id = 'jails#component#'+name;
			if( node[id] || !(name in jails.components) ) return;
			var comp  = jails.component( name, node );
			Object.assign( comp, jails.components[ name ]( comp, node, getter(name, node) ) || comp );
			comp.init();
			node[id] = true;
		};
	}

	function destroy( name, instance, node ){

		return function(e){
			instance.__kill();
			instance = null;
			clean( node );
			e.stopPropagation();
		};
	}

	function clean( node ){
		for(var e in node._events)
			jails.events.off( node, e, node._events[e].eventHandler );
		node._events = null;
		node['jails#component#'+name] = null;
	}

	function getter( name, node ){
		var props;
		return function( key ){
			if( props ) {
				return key? props[key] : props;
			}
			var anno  = annotations( node )[ name ] || {};
			var attrs = { data:{} };
			each(Array.from( node.attributes ), propset(attrs) );
			props = Object.assign({}, anno, attrs);
			return key? props[key] : props;
		};
	}

	function propset( acc ){

		return function( item ){
			var value, name = item.name.split(/data\-/);
			try{ value = item.value in window? item.value :(new Function('return '+ item.value))();}
			catch(err){ value = item.value; }

			if( name[1] ) acc.data[name.pop().replace(/-([a-z])/g, upper)] = value;
			else acc[item.name] = value;

			return acc;
		};
	}

	function upper( m, string ){
		return string.toUpperCase();
	}

	function annotations( el ){

		var ann = {}, comment, code;

		comment = el.previousSibling;
		comment = comment && comment.nodeType == 8? comment :comment? comment.previousSibling : null;

		if(comment && comment.nodeType == 8){
			code = comment.data
				.replace(/@([a-zA-z0-9-\/]*)(?:\((.*)\))?/g, function( text, component, param ){
					ann[component] = new Function('return '+ param)();
				});
		}

		return ann;
	}

	//Inspired by:
	//http://dev.housetrip.com/2014/09/15/decoupling-javascript-apps-using-pub-sub-pattern/
	function pubsub(){

		var topics = {};
		var _async = {};

		return{

			subscribe :function(){

				var args = Array.from( arguments );
				var key = args[0], method = args[1];
				var _self = this;

				if( key in _async && topics[key] ){
					topics[key].push( method );
					_self.publish.apply(null, [key].concat(_async[key]));
				}else{
					topics[key] = topics[key] || [];
					topics[key].push( method );
				}
				//Unsubscribe
				return function(){
					var newtopics = [];
					var newasync  = [];

					each(topics[key], function( fn){
						if(fn != method)
							newtopics.push(fn);
					});

					topics[key] = newtopics;

					each(_async[key], function( fn){
						if(fn != method)
							newasync.push(fn);
					});
					_async[key] = newasync;
				};
			},

			publish :function(){

				var args = Array.from( arguments );
				var key = args.shift();

				topics[key] = topics[key] || [];

				if(!topics[key].length){
					_async[key] = args;
				}

				else each(topics[key], function( f ) {
					if( f ) f.apply( this, args );
				});
			}
		};
	}

	function execute( name, instance, node ){
		return function(e){
			if( node != e.target ) return;
			var scope  = e.detail.method.split(/\:/),
				method = scope.length > 1? scope[1] : scope[0];
			if( (method in instance) && (!scope[1]) || (scope[1] && name == scope[0]) )
				instance[ method ].apply( instance, e.detail.args );
			e.stopPropagation();
		};
	}

	function call( name, args ){
		return function( element, index ){
			jails.events.trigger( element, 'execute', { args :args, method :name });
		};
	}

	function each( iterable, callback, reverse ){
		iterable = reverse? Array.from(iterable).reverse() : iterable;
		for( var i = 0, len = iterable.length; i < len; i++ )
			callback( iterable[i], i );
	}

	function on(){

		function Ev(type, params) {
			var e = document.createEvent(type);
			params = params || {};
			e.initEvent(type, params.bubbles || false, params.cancelable || false, params.detail || null);
			return e;
		}

		function handler(node, ev){
			return function(e){
				var scope = this;
				var detail = e.detail || {};
				node.__events[ev].forEach(function(o){ o.handler.apply(scope, [e].concat(detail.args)); });
			};
		}

		function delegate( node, selector, callback ){
			return function(e){
				var element = this, parent = e.target, detail = e.detail || {};
				while( parent && parent !== node ){
					if( parent.matches(selector) ){
						e.delegateTarget = parent
						callback.apply(element, [e].concat(detail.args));
					}
					parent = parent.parentNode;
				}
			};
		}

		function removeListener( node, ev ){
			if( node.__events[ev] && node.__events[ev].listener ){
				node.removeEventListener(ev, node.__events[ev].listener, false);
				delete node.__events[ev];
			}
		}

		return {

			on :function( node, ev, selectorOrCallback, callback ){

				node.__events 	  = node.__events || {};
				node.__events[ev] = (node.__events[ev] || []);

				if(!node.__events[ev].length){
					var fn = handler(node, ev);
					node.addEventListener(ev, fn, (ev == 'focus' || ev == 'blur'));
					node.__events[ev].eventHandler = fn;
				}

				if( selectorOrCallback.call ){
					node.__events[ev].push({ handler :selectorOrCallback, callback :selectorOrCallback });
				}else{
					node.__events[ev].push({ handler :delegate(node, selectorOrCallback, callback), callback :callback });
				}

				return function(){
					jails.events.off( node, ev, callback || selectorOrCallback );
				};
			},

			off :function(node, ev, fn){
				if( fn && node.__events[ev] && node.__events[ev].length ){
					var old = node.__events[ev];
					node.__events[ev] = node.__events[ev].filter(function(o){ return o.callback != fn; });
					node.__events[ev].listener = old.listener;
					if( !node.__events[ev].length )
						removeListener( node, ev );
				}else{
					removeListener( node, ev );
				}
			},

			trigger :function(el, name, args){
				try{
					el.dispatchEvent( new Ev( name, { bubbles :true, detail :args } ) );
				}catch(e){
					el.dispatchEvent( new CustomEvent( name, { bubbles :true, detail :args } ) );
				}
			}
		};
	}

	// UMD export
	if ( typeof define === 'function' && define.amd ) {
		define(function () { return jails; });
	} else if ( typeof module !== 'undefined' && module.exports ){
		module.exports = jails;
	} else {
		exports.jails = jails;
	}
})( window );
<|endoftext|>


<commit_before>/*
  This code is
  Main Objective : Comparing 2 Objects(JSON) and find the similarity
  1. Returning the count of similar keys and Count of no similar key's
  2. Returning the JSON(Object) that has the similary keys -> Return the keys corresponding to the values

*/

/*
  Things to DO:
  0.  Compare and Count
  1.  Read   (fs)
  2.  Write  (fs)
  3.  Append
    3.a  Appending to the object with specified key and values (innner Object)
  4.  Search
  5.  Sorting (key/Value/Alphabetical)
  6.  Schema Changing
*/

function compareAndCount(object_1,object_2){
  if(object_1 === undefined || object_2 === undefined){
    try {
      throw new Error('The objects cannot be null or undefined');
    } catch (e) {
      return (e.name + ': ' + e.message);
    }
    return
  }
  if( (typeof object_1 === 'object' && object_1 != null) && (typeof object_2 === 'object' && object_2 != null) ){
    // Sorting the keys of elements to find the similarity in O(nlogn)
    // Returning the keys that are in common of both
    var objectOne         =   Object.keys(object_1).sort()
    var objectTwo         =   Object.keys(object_2).sort()
    // Returns the array of common keys in the json as an array
    var returnJson = {}
    returnJson.compare  = (objectOne.filter(function(element){
      return objectTwo.includes(element)
    }))
    returnJson.count    =  returnJson.compare.length
    return returnJson

  }else{
    try {
      throw new Error('The objects cannot be null or undefined');
    } catch (e) {
      return (e.name + ': ' + e.message);
    }
    return
  }

}

function compare(object_1,object_2){
  if(object_1 === undefined || object_2 === undefined){
    try {
      throw new Error('The objects cannot be null or undefined');
    } catch (e) {
      return (e.name + ': ' + e.message);
    }
    return
  }
  if( (typeof object_1 === 'object' && object_1 != null) && (typeof object_2 === 'object' && object_2 != null) ){
    // Do stuff here

  }else{
    try {
      throw new Error('The objects cannot be null or undefined');
    } catch (e) {
      console.log(e.name + ': ' + e.message);
    }
    return
  }

}

exports.compareAndCount = function(object_1,object_2){
  return compareAndCount(object_1,object_2)
}

exports.compare = function(object_1,object_2){
  return compare(object_1,object_2)
}
<commit_msg>Change<commit_after>/*
  This code is
  Main Objective : Comparing 2 Objects(JSON) and find the similarity
  1. Returning the count of similar keys and Count of no similar key's
  2. Returning the JSON(Object) that has the similary keys -> Return the keys corresponding to the values

*/

/*
  Things to DO:
  0.  Compare and Count
  1.  Read   (fs)
  2.  Write  (fs)
  3.  Append
    3.a  Appending to the object with specified key and values (innner Object)
  4.  Search
  5.  Sorting (key/Value/Alphabetical)
  6.  Schema Changing
  7.  Generating the Routes for the json
*/

function compareAndCount(object_1,object_2){
  if(object_1 === undefined || object_2 === undefined){
    try {
      throw new Error('The objects cannot be null or undefined');
    } catch (e) {
      return (e.name + ': ' + e.message);
    }
    return
  }
  if( (typeof object_1 === 'object' && object_1 != null) && (typeof object_2 === 'object' && object_2 != null) ){
    // Sorting the keys of elements to find the similarity in O(nlogn)
    // Returning the keys that are in common of both
    var objectOne         =   Object.keys(object_1).sort()
    var objectTwo         =   Object.keys(object_2).sort()
    // Returns the array of common keys in the json as an array
    var returnJson = {}
    returnJson.compare  = (objectOne.filter(function(element){
      return objectTwo.includes(element)
    }))
    returnJson.count    =  returnJson.compare.length
    return returnJson

  }else{
    try {
      throw new Error('The objects cannot be null or undefined');
    } catch (e) {
      return (e.name + ': ' + e.message);
    }
    return
  }

}

function compare(object_1,object_2){
  if(object_1 === undefined || object_2 === undefined){
    try {
      throw new Error('The objects cannot be null or undefined');
    } catch (e) {
      return (e.name + ': ' + e.message);
    }
    return
  }
  if( (typeof object_1 === 'object' && object_1 != null) && (typeof object_2 === 'object' && object_2 != null) ){
    // Do stuff here

  }else{
    try {
      throw new Error('The objects cannot be null or undefined');
    } catch (e) {
      console.log(e.name + ': ' + e.message);
    }
    return
  }

}

exports.compareAndCount = function(object_1,object_2){
  return compareAndCount(object_1,object_2)
}

exports.compare = function(object_1,object_2){
  return compare(object_1,object_2)
}
<|endoftext|>


<commit_before>/**
 * Object that represents a linkted list item
 *
 * @param {Number} key
 * @param {LListItem} prev
 * @param {LListItem} next
 * @constructor
 */
var LListItem = function (key, prev, next) {

    this.key = (key) ? key : 0;
    this.prev = (prev) ? prev : null;
    this.next = (next) ? next : null;

};

/**
 * Object that represents a linked list
 *
 * @param {LListItem} firstItem
 * @param {LListItem} lastItem
 * @constructor
 */
var LList = function (firstItem, lastItem) {

    this.firstItem = (firstItem) ? firstItem : null;
    this.lastItem = (lastItem) ? lastItem : null;

};

<commit_msg>function insert for linked list<commit_after>/**
 * Object that represents a linkted list item
 *
 * @param {Number} key
 * @constructor
 */
var LListItem = function (key) {

    this.key = (key) ? key : 0;
    this.prev = null;
    this.next = null;

};

/**
 * Object that represents a linked list
 *
 * @param {string} name
 * @constructor
 */
var LList = function (name) {

    this.name = (name) ? name : '';
    this.firstItem = null;
    this.lastItem = null;

};

/**
 *
 * @param {LList} list
 * @param {LListItem} item
 */
function insert (list, item) {

    if (!(list instanceof LList)) {
        throw new Error('list param is not instance of LList');
    }

    if(!(item instanceof LListItem)){
        throw new Error('item param is not instance of LListItem');
    }

    // empty list
    if (!(list.lastItem)) {
        list.firstItem = item;
        list.lastItem = item;
        return;
    }

    var oldLastItem = list.lastItem;

    // non-empty list
    oldLastItem.next = item;
    item.prev = oldLastItem;
    list.lastItem = item;

}

var listA = new LList('List A');
var keysToInsert = [1,2,3,4,5,6,7];

keysToInsert.forEach(function (key) {
    insert(listA, new LListItem(key));
});

<|endoftext|>


<commit_before>var Client = require('./lib/client');
var Server = require('./lib/server');

module.exports.Client = Client;
module.exports.Server = Server;<commit_msg>added DeviceAuthMessage export<commit_after>var Client = require('./lib/client');
var Server = require('./lib/server');
var DeviceAuthMessage = require('./lib/protocol').DeviceAuthMessage;

module.exports.Client = Client;
module.exports.Server = Server;
module.exports.DeviceAuthMessage = DeviceAuthMessage;
<|endoftext|>


<commit_before>var AWS = require('aws-sdk');
var ffmpeg = require('fluent-ffmpeg');
var q = require('q');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var gm = require('gm')
          .subClass({imageMagick: true})
var mkdirp = require('mkdirp')

var proc = require('child_process');

process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'] + ':/tmp/'

var tmpPrefix;
var pathToBash;
var handleS3Event;

if (!process.env.NODE_ENV || process.env.NODE_ENV != 'testing') {
  //production
  tmpPrefix = '/tmp/';
  pathToBash = '/tmp/gif2mp4';
  handleS3Event = require('handle-s3-event');
} else {
  //local
  tmpPrefix = './';
  pathToBash = './bin/gif2mp4';
  handleS3Event = require('./local_modules/handle-s3-event');
}

var s3 = new AWS.S3();

exports.handler = function(event, context) {
  process.env['FFMPEG_PATH'] = '/tmp/ffmpeg';
  process.env['FFPROBE_PATH'] = '/tmp/ffprobe';

  var promises = [];

  if (!process.env.NODE_ENV || process.env.NODE_ENV != 'testing') {
    promises.push(function() {
      return q.Promise(function(resolve, reject, notify) {

        proc.exec(
          'cp /var/task/ffmpeg /tmp/.; chmod 755 /tmp/ffmpeg; cp /var/task/gif2mp4 /tmp/.; chmod 755 /tmp/gif2mp4',
          function (error, stdout, stderr) {
            if (error) {
              console.log('error setting up bins');
              reject(error)
            } else {
              console.log("updated binaries");
              resolve()
            }
          }
        )
      });

    })
  }

  promises.push(handleS3Event(event))
  promises.push(function(options) {
    return q.Promise(function(resolve, reject) {
      console.log('fetching from s3')
      console.log(options);

      options.gifPath = '/tmp/' + options.srcKey;
      var params = {Bucket: options.srcBucket, Key: options.srcKey};
      var file = require('fs').createWriteStream(options.gifPath);
      var s3Req = s3.getObject(params)

      s3Req.on('httpDone', function() {
        console.log('file writen to ' + options.gifPath);
        resolve(options);
      })
      s3Req.on('error', function(err) {
        reject(err);
      });

      s3Req.createReadStream().pipe(file)
    })
  });

  promises.push(function(options) {
    return q.Promise(function(resolve, reject) {
      console.log('launching my baby-back script');

      var child = proc.spawn(pathToBash, [options.gifPath]);
      child.stdout.on('data', function (data) {
        console.log("stdout:\n" + data);
      });
      child.stderr.on('data', function (data) {
        console.log("stderr:\n" + data);
      });
      child.on('exit', function (code) {
        if (code != 0) {
          reject(new Error('spawn script err'));
        } else {
          resolve(options);
        }
      });
    });
  });

  promises.push(function(options) {
    return q.Promise(function(resolve, reject) {
      console.log('ready to upload');
      context.done();
    });
  });

  promises.reduce(q.when, q())
    .fail(function(err){
      console.log('promise rejected with err');
      console.log(err);
      context.done(err);
    });
};
<commit_msg>moves /tmp/ ahead of lambda root in path<commit_after>var AWS = require('aws-sdk');
var ffmpeg = require('fluent-ffmpeg');
var q = require('q');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var gm = require('gm')
          .subClass({imageMagick: true})
var mkdirp = require('mkdirp')

var proc = require('child_process');

process.env['PATH'] = process.env['PATH'] + ':/tmp/:' + process.env['LAMBDA_TASK_ROOT']

var tmpPrefix;
var pathToBash;
var handleS3Event;

if (!process.env.NODE_ENV || process.env.NODE_ENV != 'testing') {
  //production
  tmpPrefix = '/tmp/';
  pathToBash = '/tmp/gif2mp4';
  handleS3Event = require('handle-s3-event');
} else {
  //local
  tmpPrefix = './';
  pathToBash = './bin/gif2mp4';
  handleS3Event = require('./local_modules/handle-s3-event');
}

var s3 = new AWS.S3();

exports.handler = function(event, context) {
  process.env['FFMPEG_PATH'] = '/tmp/ffmpeg';
  process.env['FFPROBE_PATH'] = '/tmp/ffprobe';

  var promises = [];

  if (!process.env.NODE_ENV || process.env.NODE_ENV != 'testing') {
    promises.push(function() {
      return q.Promise(function(resolve, reject, notify) {

        proc.exec(
          'cp /var/task/ffmpeg /tmp/.; chmod 755 /tmp/ffmpeg; cp /var/task/gif2mp4 /tmp/.; chmod 755 /tmp/gif2mp4',
          function (error, stdout, stderr) {
            if (error) {
              console.log('error setting up bins');
              reject(error)
            } else {
              console.log("updated binaries");
              resolve()
            }
          }
        )
      });

    })
  }

  promises.push(handleS3Event(event))
  promises.push(function(options) {
    return q.Promise(function(resolve, reject) {
      console.log('fetching from s3')
      console.log(options);

      options.gifPath = '/tmp/' + options.srcKey;
      var params = {Bucket: options.srcBucket, Key: options.srcKey};
      var file = require('fs').createWriteStream(options.gifPath);
      var s3Req = s3.getObject(params)

      s3Req.on('httpDone', function() {
        console.log('file writen to ' + options.gifPath);
        resolve(options);
      })
      s3Req.on('error', function(err) {
        reject(err);
      });

      s3Req.createReadStream().pipe(file)
    })
  });

  promises.push(function(options) {
    return q.Promise(function(resolve, reject) {
      console.log('launching my baby-back script');

      var child = proc.spawn(pathToBash, [options.gifPath]);
      child.stdout.on('data', function (data) {
        console.log("stdout:\n" + data);
      });
      child.stderr.on('data', function (data) {
        console.log("stderr:\n" + data);
      });
      child.on('exit', function (code) {
        if (code != 0) {
          reject(new Error('spawn script err'));
        } else {
          resolve(options);
        }
      });
    });
  });

  promises.push(function(options) {
    return q.Promise(function(resolve, reject) {
      console.log('ready to upload');
      context.done();
    });
  });

  promises.reduce(q.when, q())
    .fail(function(err){
      console.log('promise rejected with err');
      console.log(err);
      context.done(err);
    });
};
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var async = require('async');
var util = require('util');
var Etcd = require('etcdjs');

function Denver(options, etcd){
	EventEmitter.call(this);
	this._key = options.key || '/denver';

	var host = options.host || '127.0.0.1'
	var port = options.port || 4001
	this._etcd = etcd || Etcd(host + ':' + port)
}

util.inherits(Denver, EventEmitter);

module.exports = Denver;

Denver.prototype.key = function(append){
	return this._key + (append || '');
}

Denver.prototype.env = function(stacks, done){
	var self = this;
	if(typeof(stacks)==='string'){
		stacks = [stacks];
	}

	var flat = {};

	async.forEachSeries(stacks, function(stack, nextstack){
		self._etcd.get(self.key('/' + stack), function(err, packet){
			if(err || !packet){
				return nextstack();
			}
			packet.node.nodes.forEach(function(node){
				var key = node.key.replace(self.key('/' + stack + '/'), '');
				flat[key] = node.value;
			})
			nextstack();
		})
	}, function(err){
		if(err){
			return done(err);
		}
		done(null, flat);
	})
}

Denver.prototype.ls = function(done){
	var self = this;
	this._etcd.get(this.key(), function(err, packet){
		if(err || !packet){
			return done(err);
		}

		var nodes = (packet.node.nodes || []).map(function(node){
			return node.key.replace(self.key() + '/', '');
		})

		done(null, nodes);
	});
}

Denver.prototype.rm = function(stack, done){
	this._etcd.del(this.key('/' + stack), {
		recursive:true
	}, done);
}

Denver.prototype.get = function(stack, key, done){
	this._etcd.get(this.key('/' + stack + '/' + key), function(err, packet){
		if(err || !packet){
			return done(null, '');
		}

		done(null, packet.node.value);
	});
}

Denver.prototype.set = function(stack, key, value, done){
	var self = this;
	this._etcd.set(this.key('/' + stack + '/' + key), value, function(err){
		if(err){
			return done(err);
		}
		self.emit('set', stack, key, value);
		done();
	});
}

Denver.prototype.del = function(stack, key, done){
	var self = this;
	this._etcd.del(this.key('/' + stack + '/' + key), function(err){
		if(err){
			return done(err);
		}
		self.emit('del', stack, key);
		done();
	});
}

module.exports = function denver(options){
	options = options || {};
	return new Denver(options);
}<commit_msg>allow etcd object to be passed<commit_after>var EventEmitter = require('events').EventEmitter;
var async = require('async');
var util = require('util');
var Etcd = require('etcdjs');

function Denver(options, etcd){
	EventEmitter.call(this);
	this._key = options.key || '/denver';

	var host = options.host || '127.0.0.1'
	var port = options.port || 4001
	this._etcd = etcd || Etcd(host + ':' + port)
}

util.inherits(Denver, EventEmitter);

module.exports = Denver;

Denver.prototype.key = function(append){
	return this._key + (append || '');
}

Denver.prototype.env = function(stacks, done){
	var self = this;
	if(typeof(stacks)==='string'){
		stacks = [stacks];
	}

	var flat = {};

	async.forEachSeries(stacks, function(stack, nextstack){
		self._etcd.get(self.key('/' + stack), function(err, packet){
			if(err || !packet){
				return nextstack();
			}
			packet.node.nodes.forEach(function(node){
				var key = node.key.replace(self.key('/' + stack + '/'), '');
				flat[key] = node.value;
			})
			nextstack();
		})
	}, function(err){
		if(err){
			return done(err);
		}
		done(null, flat);
	})
}

Denver.prototype.ls = function(done){
	var self = this;
	this._etcd.get(this.key(), function(err, packet){
		if(err || !packet){
			return done(err);
		}

		var nodes = (packet.node.nodes || []).map(function(node){
			return node.key.replace(self.key() + '/', '');
		})

		done(null, nodes);
	});
}

Denver.prototype.rm = function(stack, done){
	this._etcd.del(this.key('/' + stack), {
		recursive:true
	}, done);
}

Denver.prototype.get = function(stack, key, done){
	this._etcd.get(this.key('/' + stack + '/' + key), function(err, packet){
		if(err || !packet){
			return done(null, '');
		}

		done(null, packet.node.value);
	});
}

Denver.prototype.set = function(stack, key, value, done){
	var self = this;
	this._etcd.set(this.key('/' + stack + '/' + key), value, function(err){
		if(err){
			return done(err);
		}
		self.emit('set', stack, key, value);
		done();
	});
}

Denver.prototype.del = function(stack, key, done){
	var self = this;
	this._etcd.del(this.key('/' + stack + '/' + key), function(err){
		if(err){
			return done(err);
		}
		self.emit('del', stack, key);
		done();
	});
}

module.exports = function denver(options, etcd){
	options = options || {};
	return new Denver(options, etcd);
}<|endoftext|>


<commit_before>/**
 * The UI Element for importing pedigrees from text representation in various formats
 *
 * @class ImportSelector
 */
define([
        "pedigree/view/tabbedSelectorTab"
       ], function(
           TabbedSelectorTab
    ){
    var ImportSelector = Class.create(TabbedSelectorTab, {

        initialize: function() {
            if (editor.isReadOnlyMode()) return;

            var _this = this;

            this.mainDiv = new Element('div', {'class': 'import-selector'});

            var _addTypeOption = function (checked, labelText, value) {
                var optionWrapper = new Element('tr');
                var input = new Element('input', {"type" : "radio", "value": value, "name": "select-type"});
                input.observe('click', _this.disableEnableOptions );
                if (checked) {
                  input.checked = true;
                }
                var label = new Element('label', {'class': 'import-type-label'}).insert(input).insert(labelText);
                optionWrapper.insert(label.wrap('td'));
                return optionWrapper;
              };
            var typeListElement = new Element('table');
            //TODO: typeListElement.insert(_addTypeOption(true,  "Autodetect", "auto"));
            typeListElement.insert(_addTypeOption(true,  "PED or LINKAGE (pre- or post- makeped)", "ped"));
            typeListElement.insert(_addTypeOption(false, "GEDCOM", "gedcom"));
            typeListElement.insert(_addTypeOption(false, "BOADICEA", "BOADICEA"));
            typeListElement.insert(_addTypeOption(false, "Simple JSON", "simpleJSON"));
            //TODO: typeListElement.insert(_addTypeOption(false, "Phenotips Pedigree JSON", "phenotipsJSON"));

            var promptType = new Element('div', {'class': 'import-section'}).update("Data format:");
            var dataSection2 = new Element('div', {'class': 'import-block'});
            dataSection2.insert(promptType).insert(typeListElement);
            this.mainDiv.insert(dataSection2);

            var _addConfigOption = function (checked, labelText, value) {
                var optionWrapper = new Element('tr');
                var input = new Element('input', {"type" : "radio", "value": value, "name": "select-options" });
                if (checked) {
                  input.checked = true;
                }
                var label = new Element('label', {'class': 'import-config-label'}).insert(input).insert(labelText);
                optionWrapper.insert(label.wrap('td'));
                return optionWrapper;
              };
            var configListElement = new Element('table', {id : 'import-type'});
            configListElement.insert(_addConfigOption(true,  "Treat non-standard phenotype values as new disorders", "accept"));
            configListElement.insert(_addConfigOption(false, "Treat non-standard phenotype values as \"no information\"", "dontaccept"));

            var markEvaluated = new Element('input', {"type" : "checkbox", "value": "1", "name": "mark-evaluated"});
            var markLabel1     = new Element('label', {'class': 'import-mark-label1'}).insert(markEvaluated).insert("Mark all patients with known disorder status with 'documented evaluation' mark").wrap('td').wrap('tr');
            configListElement.insert(markLabel1);
            var markExternal = new Element('input', {"type" : "checkbox", "value": "1", "name": "mark-external"});
            markExternal.checked = true;
            var markLabel2   = new Element('label', {'class': 'import-mark-label2'}).insert(markExternal).insert("Save individual IDs as given in the input data as 'external ID'").wrap('td').wrap('tr');
            configListElement.insert(markLabel2);

            var promptConfig = new Element('div', {'class': 'import-section'}).update("Options:");
            var dataSection3 = new Element('div', {'class': 'import-block'});
            dataSection3.insert(promptConfig).insert(configListElement);
            this.mainDiv.insert(dataSection3);

            if (!!window.FileReader && !!window.FileList) {
                // only show the upload link if browser supports FileReader/DOM File API
                // Of the browsers suported by pedigree editor, IE9 and Safari 4 & 5 do not support file API
                var uploadFileSelector = new Element('input', {"type" : "file", "id": 'pedigreeInputFile', "style": 'display:none'});
                uploadFileSelector.observe('change', function(event) {
                    _this.handleFileUpload(this.files);
                    try {
                        this.value = "";  // clear file selector
                    } catch (err) {
                        // some older browsers do not allow setting value of a file input element and may generate a security error
                    }
                })
                var uploadButton = new Element('input', {type: 'button', 'value': ' Select a local file ', 'class' : 'button import-file-button'}).wrap('span', {'class' : 'buttonwrapper import-file-button-wrapper'});
                uploadButton.observe('click', function(event) {
                    var fileElem = document.getElementById("pedigreeInputFile");
                    fileElem.click();
                })
                var promptImportFile = new Element('div', {'class': 'import-file-section', }).update("Paste data in the box below or ");
                this.mainDiv.insert(promptImportFile).insert(uploadFileSelector).insert(uploadButton);
            } else {
                this.mainDiv.insert(new Element('div', {'class': 'box infomessage import-warning-nofileupload'})
                    .update("Your browser does not support file upload.
Please copy-paste import data in the box above."));
            }

            var promptImport = new Element('div', {'class': 'import-section'});
            this.importValue = new Element("textarea", {"id": "import", "value": "", "class": "import-textarea", "placeholder": "Enter pedigree data"});
            this.mainDiv.insert(promptImport).insert(this.importValue);

            //TODO: [x] auto-combine multiple unaffected children when the number of children is greater than [5]

            this.importButton = new Element('input', {type: 'button', name : 'import', 'value': 'Import', 'class' : 'button', 'id': 'import_button'});
            this.importButton.disabled = true;
            this.cancelButton = new Element('input', {type: 'button', name : 'cancel', 'value': 'Cancel', 'class' : 'button secondary'});
            var buttons = new Element('div', {'class' : 'buttons import-block-bottom'});
            buttons.insert(this.importButton.wrap('span', {'class' : 'buttonwrapper'}));
            buttons.insert(this.cancelButton.wrap('span', {'class' : 'buttonwrapper'}));
            this.mainDiv.insert(buttons);

            this.cancelButton.observe('click', function(event) {
                _this.close();
            });
            this.importButton.observe('click', function(event) {
                _this._onImportStarted();
            });

            this.textareaChangeFunction = function() {
                if (_this.importValue.value == "") {
                    _this.importButton.disabled = true;
                } else {
                    _this.importButton.disabled = false;
                }
            };
            // different browsers require different event ofr onchange detection (special cases: IE, paste, backspace)
            var eventList = ["input","propertychange", "mousemove", "keyup"];
            eventList.each(function(item) {
                _this.importValue.observe(item, _this.textareaChangeFunction);
            });
        },

        getContentDiv: function() {
            return this.mainDiv;
        },

        getTitle: function() {
            return "Import";
        },

        /*
         * Populates the text input box with the selected file content (asynchronously)
         */
        handleFileUpload: function(files) {
            for (var i = 0, numFiles = files.length; i < numFiles; i++) {
                var nextFile = files[i];
                console.log("loading file: " + nextFile.name + ", size: " + nextFile.size);

                var _this = this;
                var fr = new FileReader();
                fr.onload = function(e) {
                    _this.importValue.value = e.target.result;  // e.target.result should contain the text
                    _this.textareaChangeFunction();
                };
                fr.readAsText(nextFile);
            }
        },

        /*
         * Disables inapplicable options on input type selection
         */
        disableEnableOptions: function() {
            var importType = $$('input:checked[type=radio][name="select-type"]')[0].value;
            //console.log("Import type: " + importType);
            var pedOnlyOptions = $$('input[type=radio][name="select-options"]');
            for (var i = 0; i < pedOnlyOptions.length; i++) {
                if (importType != "ped") {
                    pedOnlyOptions[i].disabled = true;
                } else {
                    pedOnlyOptions[i].disabled = false;
                }
            }
            var pedAndGedcomOption = $$('input[type=checkbox][name="mark-evaluated"]')[0];
            if (importType != "ped" && importType != "gedcom") {
                pedAndGedcomOption.disabled = true;
            } else {
                pedAndGedcomOption.disabled = false;
            }

            var saveExternalID = $$('input[type=checkbox][name="mark-external"]')[0];
            if (importType == "simpleJSON") {
                saveExternalID.disabled = true;
            } else {
                saveExternalID.disabled = false;
            }
        },

        /**
         * Loads the template once it has been selected
         *
         * @param event
         * @param pictureBox
         * @private
         */
        _onImportStarted: function() {
            var importValue = this.importValue.value;
            console.log("Importing:\n" + importValue);

            this.close();

            if (!importValue || importValue == "") {
                alert("Nothing to import!");
                return;
            }

            var importType = $$('input:checked[type=radio][name="select-type"]')[0].value;
            console.log("Import type: " + importType);

            var importMark = $$('input[type=checkbox][name="mark-evaluated"]')[0].checked;

            var externalIdMark = $$('input[type=checkbox][name="mark-external"]')[0].checked;

            var optionSelected = $$('input:checked[type=radio][name="select-options"]')[0].value;
            var acceptUnknownPhenotypes = (optionSelected == "accept");

            var importOptions = { "markEvaluated": importMark, "externalIdMark": externalIdMark, "acceptUnknownPhenotypes": acceptUnknownPhenotypes };

            editor.getSaveLoadEngine().createGraphFromImportData(importValue, importType, importOptions,
                                                                 false /* add to undo stack */, true /* center around proband */, "import" /* data source */);
        },

        onShow: function(allowCancel) {
            if (allowCancel) {
                this.cancelButton.show();
            } else {
                this.cancelButton.hide();
            }
        },

        onHide: function() {
            this.importValue.value = "";
        }
    });

    return ImportSelector;
});<commit_msg>PT-3431: Update format of stored/serialized pedigrees<commit_after>/**
 * The UI Element for importing pedigrees from text representation in various formats
 *
 * @class ImportSelector
 */
define([
        "pedigree/view/tabbedSelectorTab"
       ], function(
           TabbedSelectorTab
    ){
    var ImportSelector = Class.create(TabbedSelectorTab, {

        initialize: function() {
            if (editor.isReadOnlyMode()) return;

            var _this = this;

            this.mainDiv = new Element('div', {'class': 'import-selector'});

            var _addTypeOption = function (checked, labelText, value) {
                var optionWrapper = new Element('tr');
                var input = new Element('input', {"type" : "radio", "value": value, "name": "select-type"});
                input.observe('click', _this.disableEnableOptions );
                if (checked) {
                  input.checked = true;
                }
                var label = new Element('label', {'class': 'import-type-label'}).insert(input).insert(labelText);
                optionWrapper.insert(label.wrap('td'));
                return optionWrapper;
              };
            var typeListElement = new Element('table');
            //TODO: typeListElement.insert(_addTypeOption(true,  "Autodetect", "auto"));
            typeListElement.insert(_addTypeOption(true,  "PED or LINKAGE (pre- or post- makeped)", "ped"));
            typeListElement.insert(_addTypeOption(false, "GEDCOM", "gedcom"));
            typeListElement.insert(_addTypeOption(false, "BOADICEA", "BOADICEA"));
            typeListElement.insert(_addTypeOption(false, "Simple JSON", "simpleJSON"));
            typeListElement.insert(_addTypeOption(false, "PhenoTips JSON", "phenotipsJSON"));

            var promptType = new Element('div', {'class': 'import-section'}).update("Data format:");
            var dataSection2 = new Element('div', {'class': 'import-block'});
            dataSection2.insert(promptType).insert(typeListElement);
            this.mainDiv.insert(dataSection2);

            var _addConfigOption = function (checked, labelText, value) {
                var optionWrapper = new Element('tr');
                var input = new Element('input', {"type" : "radio", "value": value, "name": "select-options" });
                if (checked) {
                  input.checked = true;
                }
                var label = new Element('label', {'class': 'import-config-label'}).insert(input).insert(labelText);
                optionWrapper.insert(label.wrap('td'));
                return optionWrapper;
              };
            var configListElement = new Element('table', {id : 'import-type'});
            configListElement.insert(_addConfigOption(true,  "Treat non-standard phenotype values as new disorders", "accept"));
            configListElement.insert(_addConfigOption(false, "Treat non-standard phenotype values as \"no information\"", "dontaccept"));

            var markEvaluated = new Element('input', {"type" : "checkbox", "value": "1", "name": "mark-evaluated"});
            var markLabel1     = new Element('label', {'class': 'import-mark-label1'}).insert(markEvaluated).insert("Mark all patients with known disorder status with 'documented evaluation' mark").wrap('td').wrap('tr');
            configListElement.insert(markLabel1);
            var markExternal = new Element('input', {"type" : "checkbox", "value": "1", "name": "mark-external"});
            markExternal.checked = true;
            var markLabel2   = new Element('label', {'class': 'import-mark-label2'}).insert(markExternal).insert("Save individual IDs as given in the input data as 'external ID'").wrap('td').wrap('tr');
            configListElement.insert(markLabel2);

            var promptConfig = new Element('div', {'class': 'import-section'}).update("Options:");
            var dataSection3 = new Element('div', {'class': 'import-block'});
            dataSection3.insert(promptConfig).insert(configListElement);
            this.mainDiv.insert(dataSection3);

            if (!!window.FileReader && !!window.FileList) {
                // only show the upload link if browser supports FileReader/DOM File API
                // Of the browsers suported by pedigree editor, IE9 and Safari 4 & 5 do not support file API
                var uploadFileSelector = new Element('input', {"type" : "file", "id": 'pedigreeInputFile', "style": 'display:none'});
                uploadFileSelector.observe('change', function(event) {
                    _this.handleFileUpload(this.files);
                    try {
                        this.value = "";  // clear file selector
                    } catch (err) {
                        // some older browsers do not allow setting value of a file input element and may generate a security error
                    }
                })
                var uploadButton = new Element('input', {type: 'button', 'value': ' Select a local file ', 'class' : 'button import-file-button'}).wrap('span', {'class' : 'buttonwrapper import-file-button-wrapper'});
                uploadButton.observe('click', function(event) {
                    var fileElem = document.getElementById("pedigreeInputFile");
                    fileElem.click();
                })
                var promptImportFile = new Element('div', {'class': 'import-file-section', }).update("Paste data in the box below or ");
                this.mainDiv.insert(promptImportFile).insert(uploadFileSelector).insert(uploadButton);
            } else {
                this.mainDiv.insert(new Element('div', {'class': 'box infomessage import-warning-nofileupload'})
                    .update("Your browser does not support file upload.
Please copy-paste import data in the box above."));
            }

            var promptImport = new Element('div', {'class': 'import-section'});
            this.importValue = new Element("textarea", {"id": "import", "value": "", "class": "import-textarea", "placeholder": "Enter pedigree data"});
            this.mainDiv.insert(promptImport).insert(this.importValue);

            //TODO: [x] auto-combine multiple unaffected children when the number of children is greater than [5]

            this.importButton = new Element('input', {type: 'button', name : 'import', 'value': 'Import', 'class' : 'button', 'id': 'import_button'});
            this.importButton.disabled = true;
            this.cancelButton = new Element('input', {type: 'button', name : 'cancel', 'value': 'Cancel', 'class' : 'button secondary'});
            var buttons = new Element('div', {'class' : 'buttons import-block-bottom'});
            buttons.insert(this.importButton.wrap('span', {'class' : 'buttonwrapper'}));
            buttons.insert(this.cancelButton.wrap('span', {'class' : 'buttonwrapper'}));
            this.mainDiv.insert(buttons);

            this.cancelButton.observe('click', function(event) {
                _this.close();
            });
            this.importButton.observe('click', function(event) {
                _this._onImportStarted();
            });

            this.textareaChangeFunction = function() {
                if (_this.importValue.value == "") {
                    _this.importButton.disabled = true;
                } else {
                    _this.importButton.disabled = false;
                }
            };
            // different browsers require different event ofr onchange detection (special cases: IE, paste, backspace)
            var eventList = ["input","propertychange", "mousemove", "keyup"];
            eventList.each(function(item) {
                _this.importValue.observe(item, _this.textareaChangeFunction);
            });
        },

        getContentDiv: function() {
            return this.mainDiv;
        },

        getTitle: function() {
            return "Import";
        },

        /**
         * Populates the text input box with the selected file content (asynchronously)
         */
        handleFileUpload: function(files) {
            for (var i = 0, numFiles = files.length; i < numFiles; i++) {
                var nextFile = files[i];
                console.log("loading file: " + nextFile.name + ", size: " + nextFile.size);

                var _this = this;
                var fr = new FileReader();
                fr.onload = function(e) {
                    _this.importValue.value = e.target.result;  // e.target.result should contain the text
                    _this.textareaChangeFunction();
                };
                fr.readAsText(nextFile);
            }
        },

        /**
         * Disables inapplicable options on input type selection
         */
        disableEnableOptions: function() {
            var importType = $$('input:checked[type=radio][name="select-type"]')[0].value;
            //console.log("Import type: " + importType);
            var pedOnlyOptions = $$('input[type=radio][name="select-options"]');
            for (var i = 0; i < pedOnlyOptions.length; i++) {
                if (importType != "ped") {
                    pedOnlyOptions[i].disabled = true;
                } else {
                    pedOnlyOptions[i].disabled = false;
                }
            }
            var pedAndGedcomOption = $$('input[type=checkbox][name="mark-evaluated"]')[0];
            if (importType != "ped" && importType != "gedcom") {
                pedAndGedcomOption.disabled = true;
            } else {
                pedAndGedcomOption.disabled = false;
            }

            var saveExternalID = $$('input[type=checkbox][name="mark-external"]')[0];
            if (importType == "simpleJSON" || importType == "phenotipsJSON") {
                saveExternalID.disabled = true;
            } else {
                saveExternalID.disabled = false;
            }
        },

        /**
         * Loads the template once it has been selected
         *
         * @param event
         * @param pictureBox
         * @private
         */
        _onImportStarted: function() {
            var importValue = this.importValue.value;
            console.log("Importing:\n" + importValue);

            this.close();

            if (!importValue || importValue == "") {
                alert("Nothing to import!");
                return;
            }

            var importType = $$('input:checked[type=radio][name="select-type"]')[0].value;
            console.log("Import type: " + importType);

            var importMark = $$('input[type=checkbox][name="mark-evaluated"]')[0].checked;

            var externalIdMark = $$('input[type=checkbox][name="mark-external"]')[0].checked;

            var optionSelected = $$('input:checked[type=radio][name="select-options"]')[0].value;
            var acceptUnknownPhenotypes = (optionSelected == "accept");

            var importOptions = { "markEvaluated": importMark,
                                  "externalIdMark": externalIdMark,
                                  "acceptUnknownPhenotypes": acceptUnknownPhenotypes,
                                  "doNotLinkPatients": true };

            editor.getSaveLoadEngine().createGraphFromImportData(importValue, importType, importOptions,
                                                                 false /* add to undo stack */, true /* center around proband */, "import" /* data source */);
        },

        onShow: function(allowCancel) {
            if (allowCancel) {
                this.cancelButton.show();
            } else {
                this.cancelButton.hide();
            }
        },

        onHide: function() {
            this.importValue.value = "";
        }
    });

    return ImportSelector;
});<|endoftext|>


<commit_before>#!/usr/bin/env node
var path = require('path');
var Enquirer = require('enquirer');
var enquirer = new Enquirer();

require('shelljs/global');

var version = require('./package.json').version;
var argvs = [].slice.call(process.argv.slice(2));

// utils
var _ = {
  kebabCase: function (name) {
    name = name.replace(/^[A-Z]/, function (match) {
      return match.toLowerCase();
    });
    name = name.replace(/([0-9a-zA-Z])[\b\s]*([0-9A-Z])/g, function (m, g1, g2) {
      return `${g1}-${g2.toLowerCase()}`
    });
    return name;
  },
  pascalCase: function (name) {
    name = this.kebabCase(name);
    name = name.replace(/-([0-9a-zA-Z])/g, function (m, g1) {
      return g1.toUpperCase();
    });
    name = name.replace(/^[a-z]/, function (match) {
      return match.toUpperCase()
    });
    return name;
  }
};

// check conditions
var cmd = function (argvs) {
  var name = argvs[0];

  switch(name) {
    case '--version':
    case '-version':
    case '-v':
      console.log(version);
      break;

    case '--help':
    case '-help':
    case 'help':
    case '--h':
    case '-h':
      console.log('\A vue@2 standalone component generator, with Rollup, PostCSS and CSS Modules.\n\
Usage: vgen <command>\n\
vgen <component name>\n\
vgen --version\n\
vgen --help\n\
');
      break;

    default:
      ask(argvs);
      break;
  }
};

var copy = function (config) {
  let cwd = process.cwd();

  let dirExists = ls(cwd).filter(function (d) {
    return d === config.name;
  }).length;

  let dirName = config.name + (dirExists ? '-1' : '');
  let dir = path.join(cwd, dirName);

  mkdir(dir);
  cp('-R', __dirname + '/template/*', dir);

  ls('-Rl', dir).filter(function (stats) {
    return stats.isFile();
  }).map(function (file) {
    return file.name;
  }).forEach(f => {
    let file = path.join(dir, f);

    sed('-i', /<%name%>/g,        config.name,        file);
    sed('-i', /<%moduleName%>/g,  config.moduleName,  file);
    sed('-i', /<%version%>/g,     config.version,     file);
    sed('-i', /<%description%>/g, config.description, file);
    sed('-i', /<%author%>/g,      config.author,      file);

    let file2 = file.replace(/\{\{#(.+)\}\}/g, function (match, g1) {
      return config[g1] || match;
    });
    mv(file, file2);
  });

  console.log('\nDone. Please check ./' + dirName);
};

var ask = function (args) {
  enquirer.question('name', 'Please enter project name: ');
  enquirer.question('version', 'Please enter version: ');
  enquirer.question('description', 'Please enter description: ');
  enquirer.question('author', 'Please enter author: ');

  var config = {};

  Promise.resolve().then(function () {
    return args[0] ? { name: args[0] } : enquirer.prompt('name');
  }).then(function (answer) {
    var projName = answer.name;
    config.name = _.kebabCase(projName);
    config.moduleName = _.pascalCase(config.name);
    return enquirer.prompt('version');
  }).then(function (answer) {
    config.version = answer.version || '1.0.0';
    return enquirer.prompt('description');
  }).then(function (answer) {
    config.description = answer.description || config.name;
    return enquirer.prompt('author');
  }).then(function (answer) {
    config.author = answer.author;
  }).then(function () {
    copy(config);
  });
};

cmd(argvs);
<commit_msg>add option for compileTemplate<commit_after>#!/usr/bin/env node
var path = require('path');
var Enquirer = require('enquirer');
var enquirer = new Enquirer();

require('shelljs/global');

var version = require('./package.json').version;
var argvs = [].slice.call(process.argv.slice(2));

// utils
var _ = {
  kebabCase: function (name) {
    name = name.replace(/^[A-Z]/, function (match) {
      return match.toLowerCase();
    });
    name = name.replace(/([0-9a-zA-Z])[\b\s]*([0-9A-Z])/g, function (m, g1, g2) {
      return `${g1}-${g2.toLowerCase()}`
    });
    return name;
  },
  pascalCase: function (name) {
    name = this.kebabCase(name);
    name = name.replace(/-([0-9a-zA-Z])/g, function (m, g1) {
      return g1.toUpperCase();
    });
    name = name.replace(/^[a-z]/, function (match) {
      return match.toUpperCase()
    });
    return name;
  }
};

// check conditions
var cmd = function (argvs) {
  var name = argvs[0];

  switch(name) {
    case '--version':
    case '-version':
    case '-v':
      console.log(version);
      break;

    case '--help':
    case '-help':
    case 'help':
    case '--h':
    case '-h':
      console.log('\A vue@2 standalone component generator, with Rollup, PostCSS and CSS Modules.\n\
Usage: vgen <command>\n\
vgen <component name>\n\
vgen --version\n\
vgen --help\n\
');
      break;

    default:
      ask(argvs);
      break;
  }
};

var copy = function (config) {
  let cwd = process.cwd();

  let dirExists = ls(cwd).filter(function (d) {
    return d === config.name;
  }).length;

  let dirName = config.name + (dirExists ? '-1' : '');
  let dir = path.join(cwd, dirName);

  mkdir(dir);
  cp('-R', __dirname + '/template/*', dir);

  ls('-Rl', dir).filter(function (stats) {
    return stats.isFile();
  }).map(function (file) {
    return file.name;
  }).forEach(f => {
    let file = path.join(dir, f);

    sed('-i', /<%name%>/g,        config.name,        file);
    sed('-i', /<%moduleName%>/g,  config.moduleName,  file);
    sed('-i', /<%compile%>/g,     config.compile,     file);
    sed('-i', /<%version%>/g,     config.version,     file);
    sed('-i', /<%description%>/g, config.description, file);
    sed('-i', /<%author%>/g,      config.author,      file);

    let file2 = file.replace(/\{\{#(.+)\}\}/g, function (match, g1) {
      return config[g1] || match;
    });
    mv(file, file2);
  });

  console.log('\nDone. Please check ./' + dirName);
};

var ask = function (args) {
  enquirer.question('name', 'Please enter project name: ');
  enquirer.question('compile', 'Compile templates?(y/n) ');
  enquirer.question('version', 'Please enter version: ');
  enquirer.question('description', 'Please enter description: ');
  enquirer.question('author', 'Please enter author: ');

  var config = {};

  Promise.resolve().then(function () {
    return args[0] ? { name: args[0] } : enquirer.prompt('name');
  }).then(function (answer) {
    var projName = answer.name;
    config.name = _.kebabCase(projName);
    config.moduleName = _.pascalCase(config.name);
    return enquirer.prompt('compile');
  }).then(function (answer) {
    if (answer.compile.toLowerCase() === 'n') {
      config.compile = 'false';
    } else {
      config.compile = 'true';
    }
    return enquirer.prompt('version');
  }).then(function (answer) {
    config.version = answer.version || '1.0.0';
    return enquirer.prompt('description');
  }).then(function (answer) {
    config.description = answer.description || config.name;
    return enquirer.prompt('author');
  }).then(function (answer) {
    config.author = answer.author;
  }).then(function () {
    copy(config);
  });
};

cmd(argvs);
<|endoftext|>


<commit_before>var inherits = require('inherits');
var lsb = require('lsb');
var voxelMesh = require('voxel-mesh');
var voxel = require('voxel');
var Creature = require('voxel-creature').Creature;

function Critter(game, img, opts) {
  this.game = game;
  var data = this.load(img);
  var obj = this.build(data);
  Creature.call(this, game, obj, opts);
}
inherits(Critter, Creature);

module.exports = function(game) {
  return function(img, opts) {
    return new Critter(game, img, opts || {});
  };
};
module.exports.Critter = Critter;
module.exports.convertToVoxels = convertToVoxels
module.exports.load = load

Critter.prototype.build = function(hash) {
  var self = this;

  var converted = convertToVoxels(hash);
  var bounds = converted.bounds;
  var voxelData = converted.voxelData;
  var colors = converted.colors;

  // create voxels
  bounds[0] = bounds[0].map(function(b) { return b - 1; });
  bounds[1] = bounds[1].map(function(b) { return b + 1; });
  var voxels = voxel.generate(bounds[0], bounds[1], function(x, y, z) {
    return voxelData[[x, y, z].join('|')] || 0;
  });

  // create mesh
  var scale = 0.2;
  var mesh = voxelMesh(voxels, this.game.mesher, new this.game.THREE.Vector3(scale, scale, scale), this.game.THREE);
  var mat = new self.game.THREE.MeshBasicMaterial({vertexColors: this.game.THREE.FaceColors});
  mesh.createSurfaceMesh(mat);

  // colorize
  for (var i = 0; i < mesh.surfaceMesh.geometry.faces.length; i++) {
    var face = mesh.surfaceMesh.geometry.faces[i];
    var index = Math.floor(face.color.b*255 + face.color.g*255*255 + face.color.r*255*255*255);
    var color = colors[index] || colors[0];
    face.color.setRGB(color[0], color[1], color[2]);
  }

  // center the geometry
  this.game.THREE.GeometryUtils.center(mesh.surfaceMesh.geometry);
  mesh.setPosition(0, 1.5, 0);

  // create creature
  var critter = new this.game.THREE.Object3D();
  critter.add(mesh.surfaceMesh);
  return critter;
};

function hex2rgb(hex) {
  if (hex[0] === '#') hex = hex.substr(1);
  return [parseInt(hex.substr(0,2), 16)/255, parseInt(hex.substr(2,2), 16)/255, parseInt(hex.substr(4,2), 16)/255];
}

function decode(string) {
  var output = [];
  string.split('').forEach(function(v) {
    output.push("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(v));
  });
  return output;
}

function convertToVoxels(hash) {
  var hashChunks = hash.split(':');
  var chunks = {};
  var colors = [0x000000];

  for (var j = 0; j < hashChunks.length; j++) {
    chunks[hashChunks[j][0]] = hashChunks[j].substr(2);
  }

  if (chunks['C']) {
    // decode colors
    colors = [];
    var hexColors = chunks['C'];
    for(var c = 0, nC = hexColors.length/6; c < nC; c++) {
      var hex = hexColors.substr(c * 6, 6);
      colors[c] = hex2rgb(hex);
    }
  }

  if (chunks['A']) {
    // decode geo
    var current = [0, 0, 0, 0];
    var data = decode(chunks['A']);
    var i = 0, l = data.length;
    var voxelData = Object.create(null);
    var bounds = [[-1, -1, -1], [1, 1, 1]];

    while (i < l) {
      var code = data[i++].toString(2);
      if (code.charAt(1) === '1') current[0] += data[i++] - 32;
      if (code.charAt(2) === '1') current[1] += data[i++] - 32;
      if (code.charAt(3) === '1') current[2] += data[i++] - 32;
      if (code.charAt(4) === '1') current[3] += data[i++] - 32;
      if (code.charAt(0) === '1') {
        if (current[0] < 0 && current[0] < bounds[0][0]) bounds[0][0] = current[0];
        if (current[0] > 0 && current[0] > bounds[1][0]) bounds[1][0] = current[0];
        if (current[1] < 0 && current[1] < bounds[0][1]) bounds[0][1] = current[1];
        if (current[1] > 0 && current[1] > bounds[1][1]) bounds[1][1] = current[1];
        if (current[2] < 0 && current[2] < bounds[0][2]) bounds[0][2] = current[2];
        if (current[2] > 0 && current[2] > bounds[1][2]) bounds[1][2] = current[2];
        voxelData[current.slice(0, 3).join('|')] = current.slice(3)[0];
      }
    }
  }

  return { voxelData: voxelData, colors: colors, bounds: bounds };
}

function load(image) {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  var width = canvas.width = image.width;
  var height = canvas.height = image.height;

  ctx.fillStyle = 'rgb(255,255,255)';
  ctx.fillRect(0, 0, width, height);
  ctx.drawImage(image, 0, 0);

  var imageData = ctx.getImageData(0, 0, width, height);
  var text = lsb.decode(imageData.data, function(idx) {
    return idx + (idx / 3) | 0;
  });

  // ignore images that weren't generated by voxel-painter
  if (text.slice(0, 14) !== 'voxel-painter:') return false;

  return text.slice(15);
};<commit_msg>Fix reference to nonexistant `load` message. Fixes GH-5.<commit_after>var inherits = require('inherits');
var lsb = require('lsb');
var voxelMesh = require('voxel-mesh');
var voxel = require('voxel');
var Creature = require('voxel-creature').Creature;

function Critter(game, img, opts) {
  this.game = game;
  var data = load(img);
  var obj = this.build(data);
  Creature.call(this, game, obj, opts);
}
inherits(Critter, Creature);

module.exports = function(game) {
  return function(img, opts) {
    return new Critter(game, img, opts || {});
  };
};
module.exports.Critter = Critter;
module.exports.convertToVoxels = convertToVoxels
module.exports.load = load

Critter.prototype.build = function(hash) {
  var self = this;

  var converted = convertToVoxels(hash);
  var bounds = converted.bounds;
  var voxelData = converted.voxelData;
  var colors = converted.colors;

  // create voxels
  bounds[0] = bounds[0].map(function(b) { return b - 1; });
  bounds[1] = bounds[1].map(function(b) { return b + 1; });
  var voxels = voxel.generate(bounds[0], bounds[1], function(x, y, z) {
    return voxelData[[x, y, z].join('|')] || 0;
  });

  // create mesh
  var scale = 0.2;
  var mesh = voxelMesh(voxels, this.game.mesher, new this.game.THREE.Vector3(scale, scale, scale), this.game.THREE);
  var mat = new self.game.THREE.MeshBasicMaterial({vertexColors: this.game.THREE.FaceColors});
  mesh.createSurfaceMesh(mat);

  // colorize
  for (var i = 0; i < mesh.surfaceMesh.geometry.faces.length; i++) {
    var face = mesh.surfaceMesh.geometry.faces[i];
    var index = Math.floor(face.color.b*255 + face.color.g*255*255 + face.color.r*255*255*255);
    var color = colors[index] || colors[0];
    face.color.setRGB(color[0], color[1], color[2]);
  }

  // center the geometry
  this.game.THREE.GeometryUtils.center(mesh.surfaceMesh.geometry);
  mesh.setPosition(0, 1.5, 0);

  // create creature
  var critter = new this.game.THREE.Object3D();
  critter.add(mesh.surfaceMesh);
  return critter;
};

function hex2rgb(hex) {
  if (hex[0] === '#') hex = hex.substr(1);
  return [parseInt(hex.substr(0,2), 16)/255, parseInt(hex.substr(2,2), 16)/255, parseInt(hex.substr(4,2), 16)/255];
}

function decode(string) {
  var output = [];
  string.split('').forEach(function(v) {
    output.push("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(v));
  });
  return output;
}

function convertToVoxels(hash) {
  var hashChunks = hash.split(':');
  var chunks = {};
  var colors = [0x000000];

  for (var j = 0; j < hashChunks.length; j++) {
    chunks[hashChunks[j][0]] = hashChunks[j].substr(2);
  }

  if (chunks['C']) {
    // decode colors
    colors = [];
    var hexColors = chunks['C'];
    for(var c = 0, nC = hexColors.length/6; c < nC; c++) {
      var hex = hexColors.substr(c * 6, 6);
      colors[c] = hex2rgb(hex);
    }
  }

  if (chunks['A']) {
    // decode geo
    var current = [0, 0, 0, 0];
    var data = decode(chunks['A']);
    var i = 0, l = data.length;
    var voxelData = Object.create(null);
    var bounds = [[-1, -1, -1], [1, 1, 1]];

    while (i < l) {
      var code = data[i++].toString(2);
      if (code.charAt(1) === '1') current[0] += data[i++] - 32;
      if (code.charAt(2) === '1') current[1] += data[i++] - 32;
      if (code.charAt(3) === '1') current[2] += data[i++] - 32;
      if (code.charAt(4) === '1') current[3] += data[i++] - 32;
      if (code.charAt(0) === '1') {
        if (current[0] < 0 && current[0] < bounds[0][0]) bounds[0][0] = current[0];
        if (current[0] > 0 && current[0] > bounds[1][0]) bounds[1][0] = current[0];
        if (current[1] < 0 && current[1] < bounds[0][1]) bounds[0][1] = current[1];
        if (current[1] > 0 && current[1] > bounds[1][1]) bounds[1][1] = current[1];
        if (current[2] < 0 && current[2] < bounds[0][2]) bounds[0][2] = current[2];
        if (current[2] > 0 && current[2] > bounds[1][2]) bounds[1][2] = current[2];
        voxelData[current.slice(0, 3).join('|')] = current.slice(3)[0];
      }
    }
  }

  return { voxelData: voxelData, colors: colors, bounds: bounds };
}

function load(image) {
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  var width = canvas.width = image.width;
  var height = canvas.height = image.height;

  ctx.fillStyle = 'rgb(255,255,255)';
  ctx.fillRect(0, 0, width, height);
  ctx.drawImage(image, 0, 0);

  var imageData = ctx.getImageData(0, 0, width, height);
  var text = lsb.decode(imageData.data, function(idx) {
    return idx + (idx / 3) | 0;
  });

  // ignore images that weren't generated by voxel-painter
  if (text.slice(0, 14) !== 'voxel-painter:') return false;

  return text.slice(15);
};
<|endoftext|>


<commit_before>var uuid = require('node-uuid')

module.exports = function (options) {

  if (options.constructor && options.constructor.name === 'Logger')
    options = { logger: options }

  if (!options.logger)
    throw new Error('`options.logger` is required')

  var logger = options.logger
    , headerName = options.headerName || 'X-Request-Id'
    , headerNameLower = headerName.toLowerCase()
    , propertyName = options.propertyName || 'reqId'
    , logName = options.logName || 'req_id'

  logger = logger.child({ serializers: logger.constructor.stdSerializers })

  return function (req, res, next) {
    var id = req[propertyName]
          || req.headers[headerNameLower]
          || uuid.v1()

    var prefs = {}
    prefs[logName] = id
    req.log = res.log = logger.child(prefs, true)

    req[propertyName] = res[propertyName] = id
    res.setHeader(headerName, id)

    req.log.info({ req: req }, 'start request')
    res.on('finish', function() {
      res.log.info({ res: res }, 'response finish')
    })

    next()
  }
}
<commit_msg>log request data together with response data<commit_after>var uuid = require('node-uuid')

module.exports = function (options) {

  if (options.constructor && options.constructor.name === 'Logger')
    options = { logger: options }

  if (!options.logger)
    throw new Error('`options.logger` is required')

  var logger = options.logger
    , headerName = options.headerName || 'X-Request-Id'
    , headerNameLower = headerName.toLowerCase()
    , propertyName = options.propertyName || 'reqId'
    , logName = options.logName || 'req_id'

  logger = logger.child({ serializers: logger.constructor.stdSerializers })

  return function (req, res, next) {
    var id = req[propertyName]
          || req.headers[headerNameLower]
          || uuid.v1()

    var prefs = {}
    prefs[logName] = id
    req.log = res.log = logger.child(prefs, true)

    req[propertyName] = res[propertyName] = id
    res.setHeader(headerName, id)

    req.log.info('request start')
    res.on('finish', function() {
      res.log.info(
          { res: res
          , req: req
          }
        , 'request finish'
        )
    })

    next()
  }
}
<|endoftext|>


<commit_before>// knockout.js extensions

// useful tool to invert the value of a function
ko.utils.makeInverse = function (fn) {
   return function () { return !fn(); };
};

// ko.utils.arrayFilter() will also match items with _destroy
// properties, indicating they have been destroyed by self.observableArray.destroy(arrayItem).
// so we add a couple other utilities to isolate alive and destroyed items

// Useful for automatic ignore of items that have been 'destroyed' by setting _destroy = true within them
ko.utils.arrayFilterAlive = function (a, fn) {
    fn = fn || function () { return true; }
    return ko.utils.arrayFilter(a, function (item) {
       return !item._destroy && fn(item);
    })
};

// Just loop through items that have been 'destroyed' but not submitted/removed from server yet.
ko.utils.arrayFilterDestroyed = function (a, fn) {
    return ko.utils.arrayFilter(a, function (item) {
       fn = fn || function () { return true; }
       return item._destroy && fn(item);
    })
};

// knockout.js custom bindings for data-bind
//

if (!window.jQuery) {
    console.warn("jQuery missing, knockout.js binding handler extensions fallback to plain visible/hidden instead of animation.");
    // data-bind= show -- alias for visible when jQuery missing
    ko.bindingHandlers.show = ko.bindingHandlers.visible;

    // data-bind= hidden -- the opposite of visible
    ko.bindingHandlers.hidden = {
        init: function(element, valueAccessor) {
            return ko.bindingHandlers.visible.init(element, ko.utils.makeInverse(valueAccessor));
        },
        update: function(element, valueAccessor) {
            return ko.bindingHandlers.visible.update(element, ko.utils.makeInverse(valueAccessor));
        }
    };
}
else {
    // using jQuery to fade in/out an element
    // custom binding for data-bind="hidden: expression"
    // fades out when condition is true
    ko.bindingHandlers.hidden = {
        init: function(element, valueAccessor) {
            // Start visible/invisible according to initial value
            var shouldHide = valueAccessor();
            $(element).toggle(!shouldHide);
        },
        update: function(element, valueAccessor) {
            // On update, fade in/out
            var shouldHide = valueAccessor();
            shouldHide ? $(element).fadeOut() : $(element).fadeIn();
        }
    };

    // custom binding for data-bind="show: expression"
    // fades in when condition is true
    ko.bindingHandlers.show = {
        init: function(element, valueAccessor) {
            // Start visible/invisible according to initial value
            var shouldDisplay = valueAccessor();
            $(element).toggle(shouldDisplay);
        },
        update: function(element, valueAccessor) {
            // On update, fade in/out
            var shouldDisplay = valueAccessor();
            shouldDisplay ? $(element).fadeIn() : $(element).fadeOut();
        }
    };
}

<commit_msg>jshint satisfied<commit_after>// knockout.js extensions
/*globals ko */

(function(window)
{
    "use strict";

// useful tool to invert the value of a function
ko.utils.makeInverse = function (fn) {
   return function () { return !fn(); };
};

// ko.utils.arrayFilter() will also match items with _destroy
// properties, indicating they have been destroyed by self.observableArray.destroy(arrayItem).
// so we add a couple other utilities to isolate alive and destroyed items

// Useful for automatic ignore of items that have been 'destroyed'
// by setting _destroy = true within them
ko.utils.arrayFilterAlive = function (a, fn) {
    fn = fn || function () { return true; };
    return ko.utils.arrayFilter(a, function (item) {
       return !item._destroy && fn(item);
    });
};

// Just loop through items that have been 'destroyed' but not submitted/removed from server yet.
ko.utils.arrayFilterDestroyed = function (a, fn) {
    return ko.utils.arrayFilter(a, function (item) {
       fn = fn || function () { return true; };
       return item._destroy && fn(item);
    });
};

// knockout.js custom bindings for data-bind
//

if (!window.jQuery) {
    console.warn("jQuery missing, knockout.js binding handler extensions"
        + " fallback to plain visible/hidden instead of animation.");
    // data-bind= show -- alias for visible when jQuery missing
    ko.bindingHandlers.show = ko.bindingHandlers.visible;

    // data-bind= hidden -- the opposite of visible
    ko.bindingHandlers.hidden = {
        init: function(element, valueAccessor) {
            return ko.bindingHandlers.visible.init(element, ko.utils.makeInverse(valueAccessor));
        },
        update: function(element, valueAccessor) {
            return ko.bindingHandlers.visible.update(element, ko.utils.makeInverse(valueAccessor));
        }
    };
}
else {
    var $ = window.jQuery;
    // using jQuery to fade in/out an element
    // custom binding for data-bind="hidden: expression"
    // fades out when condition is true
    ko.bindingHandlers.hidden = {
        init: function(element, valueAccessor) {
            // Start visible/invisible according to initial value
            var shouldHide = valueAccessor();
            $(element).toggle(!shouldHide);
        },
        update: function(element, valueAccessor) {
            // On update, fade in/out
            var shouldHide = valueAccessor();
            return shouldHide ? $(element).fadeOut() : $(element).fadeIn();
        }
    };

    // custom binding for data-bind="show: expression"
    // fades in when condition is true
    ko.bindingHandlers.show = {
        init: function(element, valueAccessor) {
            // Start visible/invisible according to initial value
            var shouldDisplay = valueAccessor();
            $(element).toggle(shouldDisplay);
        },
        update: function(element, valueAccessor) {
            // On update, fade in/out
            var shouldDisplay = valueAccessor();
            return shouldDisplay ? $(element).fadeIn() : $(element).fadeOut();
        }
    };
}

})(this);
<|endoftext|>