<commit_before>/*!
 * jQuery UI @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function( $, undefined ) {

// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
	return;
}

$.extend( $.ui, {
	version: "@VERSION",

	keyCode: {
		ALT: 18,
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		COMMAND: 91,
		COMMAND_LEFT: 91, // COMMAND
		COMMAND_RIGHT: 93,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		MENU: 93, // COMMAND_RIGHT
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38,
		WINDOWS: 91 // COMMAND
	}
});

// plugins
$.fn.extend({
	_focus: $.fn.focus,
	focus: function( delay, fn ) {
		return typeof delay === "number" ?
			this.each(function() {
				var elem = this;
				setTimeout(function() {
					$( elem ).focus();
					if ( fn ) {
						fn.call( elem );
					}
				}, delay );
			}) :
			this._focus.apply( this, arguments );
	},

	scrollParent: function() {
		var scrollParent;
		if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.css(this,'position')) && (/(auto|scroll)/).test($.css(this,'overflow')+$.css(this,'overflow-y')+$.css(this,'overflow-x'));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.css(this,'overflow')+$.css(this,'overflow-y')+$.css(this,'overflow-x'));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					//

					value = parseInt( elem.css( "zIndex" ), 10 );
					if ( !isNaN( value ) && value !== 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	},

	disableSelection: function() {
		return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
			".ui-disableSelection", function( event ) {
				event.preventDefault();
			});
	},

	enableSelection: function() {
		return this.unbind( ".ui-disableSelection" );
	}
});

$.each( [ "Width", "Height" ], function( i, name ) {
	var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
		type = name.toLowerCase(),
		orig = {
			innerWidth: $.fn.innerWidth,
			innerHeight: $.fn.innerHeight,
			outerWidth: $.fn.outerWidth,
			outerHeight: $.fn.outerHeight
		};

	function reduce( elem, size, border, margin ) {
		$.each( side, function() {
			size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
			if ( border ) {
				size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
			}
			if ( margin ) {
				size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
			}
		});
		return size;
	}

	$.fn[ "inner" + name ] = function( size ) {
		if ( size === undefined ) {
			return orig[ "inner" + name ].call( this );
		}

		return this.each(function() {
			$( this ).css( type, reduce( this, size ) + "px" );
		});
	};

	$.fn[ "outer" + name] = function( size, margin ) {
		if ( typeof size !== "number" ) {
			return orig[ "outer" + name ].call( this, size );
		}

		return this.each(function() {
			$( this).css( type, reduce( this, size, true, margin ) + "px" );
		});
	};
});

// selectors
function focusable( element, isTabIndexNotNaN ) {
	var nodeName = element.nodeName.toLowerCase();
	if ( "area" === nodeName ) {
		var map = element.parentNode,
			mapName = map.name,
			img;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap=#" + mapName + "]" )[0];
		return !!img && visible( img );
	}
	return ( /input|select|textarea|button|object/.test( nodeName )
		? !element.disabled
		: "a" == nodeName
			? element.href || isTabIndexNotNaN
			: isTabIndexNotNaN)
		// the element and all of its ancestors must be visible
		&& visible( element );
}

function visible( element ) {
	return !$( element ).parents().andSelf().filter(function() {
		return $.css( this, "visibility" ) === "hidden" ||
			$.expr.filters.hidden( this );
	}).length;
}

$.extend( $.expr[ ":" ], {
	data: function( elem, i, match ) {
		return !!$.data( elem, match[ 3 ] );
	},

	focusable: function( element ) {
		return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			isTabIndexNaN = isNaN( tabIndex );
		return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
	}
});

// support
$(function() {
	var body = document.body,
		div = body.appendChild( div = document.createElement( "div" ) );

	// access offsetHeight before setting the style to prevent a layout bug
	// in IE 9 which causes the elemnt to continue to take up space even
	// after it is removed from the DOM (#8026)
	div.offsetHeight;

	$.extend( div.style, {
		minHeight: "100px",
		height: "auto",
		padding: 0,
		borderWidth: 0
	});

	$.support.minHeight = div.offsetHeight === 100;
	$.support.selectstart = "onselectstart" in div;

	// set display to none to avoid a layout bug in IE
	// http://dev.jquery.com/ticket/4014
	body.removeChild( div ).style.display = "none";
});

// deprecated
$.extend( $.ui, {
	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function( module, option, set ) {
			var proto = $.ui[ module ].prototype;
			for ( var i in set ) {
				proto.plugins[ i ] = proto.plugins[ i ] || [];
				proto.plugins[ i ].push( [ option, set[ i ] ] );
			}
		},
		call: function( instance, name, args ) {
			var set = instance.plugins[ name ];
			if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
				return;
			}

			for ( var i = 0; i < set.length; i++ ) {
				if ( instance.options[ set[ i ][ 0 ] ] ) {
					set[ i ][ 1 ].apply( instance.element, args );
				}
			}
		}
	},

	contains: $.contains,

	// only used by resizable
	hasScroll: function( el, a ) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},

	// these are odd functions, fix the API or move into individual plugins
	isOverAxis: function( x, reference, size ) {
		//Determines when x coordinate is over "b" element axis
		return ( x > reference ) && ( x < ( reference + size ) );
	},
	isOver: function( y, x, top, left, height, width ) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
	}
});

})( jQuery );
<commit_msg>Core: Removed modifier keys from key codes. Fixed #7613 - Incorrect UI keyCodes.<commit_after>/*!
 * jQuery UI @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function( $, undefined ) {

// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
	return;
}

$.extend( $.ui, {
	version: "@VERSION",

	keyCode: {
		BACKSPACE: 8,
		COMMA: 188,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
});

// plugins
$.fn.extend({
	_focus: $.fn.focus,
	focus: function( delay, fn ) {
		return typeof delay === "number" ?
			this.each(function() {
				var elem = this;
				setTimeout(function() {
					$( elem ).focus();
					if ( fn ) {
						fn.call( elem );
					}
				}, delay );
			}) :
			this._focus.apply( this, arguments );
	},

	scrollParent: function() {
		var scrollParent;
		if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.css(this,'position')) && (/(auto|scroll)/).test($.css(this,'overflow')+$.css(this,'overflow-y')+$.css(this,'overflow-x'));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.css(this,'overflow')+$.css(this,'overflow-y')+$.css(this,'overflow-x'));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					//

					value = parseInt( elem.css( "zIndex" ), 10 );
					if ( !isNaN( value ) && value !== 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	},

	disableSelection: function() {
		return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
			".ui-disableSelection", function( event ) {
				event.preventDefault();
			});
	},

	enableSelection: function() {
		return this.unbind( ".ui-disableSelection" );
	}
});

$.each( [ "Width", "Height" ], function( i, name ) {
	var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
		type = name.toLowerCase(),
		orig = {
			innerWidth: $.fn.innerWidth,
			innerHeight: $.fn.innerHeight,
			outerWidth: $.fn.outerWidth,
			outerHeight: $.fn.outerHeight
		};

	function reduce( elem, size, border, margin ) {
		$.each( side, function() {
			size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
			if ( border ) {
				size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
			}
			if ( margin ) {
				size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
			}
		});
		return size;
	}

	$.fn[ "inner" + name ] = function( size ) {
		if ( size === undefined ) {
			return orig[ "inner" + name ].call( this );
		}

		return this.each(function() {
			$( this ).css( type, reduce( this, size ) + "px" );
		});
	};

	$.fn[ "outer" + name] = function( size, margin ) {
		if ( typeof size !== "number" ) {
			return orig[ "outer" + name ].call( this, size );
		}

		return this.each(function() {
			$( this).css( type, reduce( this, size, true, margin ) + "px" );
		});
	};
});

// selectors
function focusable( element, isTabIndexNotNaN ) {
	var nodeName = element.nodeName.toLowerCase();
	if ( "area" === nodeName ) {
		var map = element.parentNode,
			mapName = map.name,
			img;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap=#" + mapName + "]" )[0];
		return !!img && visible( img );
	}
	return ( /input|select|textarea|button|object/.test( nodeName )
		? !element.disabled
		: "a" == nodeName
			? element.href || isTabIndexNotNaN
			: isTabIndexNotNaN)
		// the element and all of its ancestors must be visible
		&& visible( element );
}

function visible( element ) {
	return !$( element ).parents().andSelf().filter(function() {
		return $.css( this, "visibility" ) === "hidden" ||
			$.expr.filters.hidden( this );
	}).length;
}

$.extend( $.expr[ ":" ], {
	data: function( elem, i, match ) {
		return !!$.data( elem, match[ 3 ] );
	},

	focusable: function( element ) {
		return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			isTabIndexNaN = isNaN( tabIndex );
		return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
	}
});

// support
$(function() {
	var body = document.body,
		div = body.appendChild( div = document.createElement( "div" ) );

	// access offsetHeight before setting the style to prevent a layout bug
	// in IE 9 which causes the elemnt to continue to take up space even
	// after it is removed from the DOM (#8026)
	div.offsetHeight;

	$.extend( div.style, {
		minHeight: "100px",
		height: "auto",
		padding: 0,
		borderWidth: 0
	});

	$.support.minHeight = div.offsetHeight === 100;
	$.support.selectstart = "onselectstart" in div;

	// set display to none to avoid a layout bug in IE
	// http://dev.jquery.com/ticket/4014
	body.removeChild( div ).style.display = "none";
});

// deprecated
$.extend( $.ui, {
	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function( module, option, set ) {
			var proto = $.ui[ module ].prototype;
			for ( var i in set ) {
				proto.plugins[ i ] = proto.plugins[ i ] || [];
				proto.plugins[ i ].push( [ option, set[ i ] ] );
			}
		},
		call: function( instance, name, args ) {
			var set = instance.plugins[ name ];
			if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
				return;
			}

			for ( var i = 0; i < set.length; i++ ) {
				if ( instance.options[ set[ i ][ 0 ] ] ) {
					set[ i ][ 1 ].apply( instance.element, args );
				}
			}
		}
	},

	contains: $.contains,

	// only used by resizable
	hasScroll: function( el, a ) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},

	// these are odd functions, fix the API or move into individual plugins
	isOverAxis: function( x, reference, size ) {
		//Determines when x coordinate is over "b" element axis
		return ( x > reference ) && ( x < ( reference + size ) );
	},
	isOver: function( y, x, top, left, height, width ) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
	}
});

})( jQuery );
<|endoftext|>


<commit_before>/**
 * Created by geoffc on 8/13/14.
 */
var hackFilters = angular.module('hackFilters', []);

hackFilters.filter('joinTags', function () {
    return function (input, delimiter) {
        input = input.map(function (x) {
            return x.text
        });
        return (input || []).join(delimiter || ',');
    };
});<commit_msg>joinTags filter handles undefined values.<commit_after>/**
 * Created by geoffc on 8/13/14.
 */
var hackFilters = angular.module('hackFilters', []);

hackFilters.filter('joinTags', function () {
    return function (input, delimiter) {
        if (input === undefined) {
            return '';
        }
        input = input.map(function (x) {
            return x.text
        });
        return (input || []).join(delimiter || ',');
    };
});<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs-extra');
var utils= require('./utils');

address=process.argv[process.argv.length - 4];
port=process.argv[process.argv.length - 3];
sharedDir=process.argv[process.argv.length -2];
destDir=process.argv[process.argv.length - 1];

var copyFile = function(file, sha1) {
  var src = sharedDir + '/' + file;
  utils.calcHash(src, function(err, calcHash) {
    if (err) {
      console.log('[-] Unable to calculate checksum ' + JSON.stringify(err));
      return;
    }
    if (sha1 != calcHash) {
      console.log('[-] File Version Missmatch');
    }
    var dst = destDir + '/' + file;
    console.log('[.] Coping File ' + src + ' to ' + dst);
    fs.copy(src, dst, function(err) {
      if (err) {
        console.log('[-] ' + err);
      } else {
        console.log('[+] File ' + src + ' copied to ' + dst);
      }
    });
  });
}

var mkDir = function(dir) {
  var dst = destDir + '/' + dir;
  fs.mkdirs(dst, function(err) {
    if (err) {
      console.log('[-] Unable to create ' + dst + ' directory');
    } else {
      console.log('[+] Directory ' + dst + ' created');
    }
  });
}

var eventDispatch = {
  'add': function(event, file, sha1) {
    console.log('[.] add event received for ' + sharedDir + '/' + file );
    copyFile(file, sha1);
  },
  'unlink': function(event, file, sha1) {
    console.log("Unlinked file " + file);
  },
  'change': function(event, file, sha1) {
    console.log('[.] change event received for ' + sharedDir + '/' + file);
    copyFile(file, sha1);
  },
  'addDir': function(event, dir, sha1) {
    console.log('addDir event received for  ' + sharedDir + '/' + dir);
    mkDir(dir);
  },
  'unlinkDir': function(event, dir, sha1) {
    console.log("Unlinked directory " + dir);
  },
  'default': function(event, file, sha1) {
    console.log('Unknown event occurred ' + event + ' on ' + file);
  },
};

//Clean destDirecotry first
fs.remove(destDir, function(err) {
  if (err) {
    console.log(err);
    return 1;
  }
  fs.copy(sharedDir, destDir, function(err) {
    if (err) {
      console.log(err);
      return 1;
    }
    http.createServer(function(request,response){
      var req = "";

      request.on('data', function(chunk) {
        req+=chunk
      });

      request.on('end', function() {
        var reqObj = JSON.parse(req);
        var dispatchKey = reqObj["event"];

        if (!(dispatchKey in eventDispatch)) {
          dispatchKey = 'default';
        }

        eventDispatch[dispatchKey](reqObj['event'], reqObj['file'], reqObj['checkSum']);
      });

      response.writeHead(200, {'Content-Type': 'application/json'});
      response.write(JSON.stringify({code: 200, message: 'Hello'}));
      response.end();
    }).listen(port, address);

    console.log("Server is listening to http://" + address + ":" + port);
  });
})
<commit_msg>fixed default event handler<commit_after>var http = require('http');
var fs = require('fs-extra');
var utils= require('./utils');

address=process.argv[process.argv.length - 4];
port=process.argv[process.argv.length - 3];
sharedDir=process.argv[process.argv.length -2];
destDir=process.argv[process.argv.length - 1];

var copyFile = function(file, sha1) {
  var src = sharedDir + '/' + file;
  utils.calcHash(src, function(err, calcHash) {
    if (err) {
      console.log('[-] Unable to calculate checksum ' + JSON.stringify(err));
      return;
    }
    if (sha1 != calcHash) {
      console.log('[-] File Version Missmatch');
    }
    var dst = destDir + '/' + file;
    console.log('[.] Coping File ' + src + ' to ' + dst);
    fs.copy(src, dst, function(err) {
      if (err) {
        console.log('[-] ' + err);
      } else {
        console.log('[+] File ' + src + ' copied to ' + dst);
      }
    });
  });
}

var mkDir = function(dir) {
  var dst = destDir + '/' + dir;
  fs.mkdirs(dst, function(err) {
    if (err) {
      console.log('[-] Unable to create ' + dst + ' directory');
    } else {
      console.log('[+] Directory ' + dst + ' created');
    }
  });
}

var eventDispatch = {
  'add': function(event, file, sha1) {
    console.log('[.] add event received for ' + sharedDir + '/' + file );
    copyFile(file, sha1);
  },
  'unlink': function(event, file, sha1) {
    console.log("Unlinked file " + file);
  },
  'change': function(event, file, sha1) {
    console.log('[.] change event received for ' + sharedDir + '/' + file);
    copyFile(file, sha1);
  },
  'addDir': function(event, dir, sha1) {
    console.log('addDir event received for  ' + sharedDir + '/' + dir);
    mkDir(dir);
  },
  'unlinkDir': function(event, dir, sha1) {
    console.log("Unlinked directory " + dir);
  },
  'default': function(event, file, sha1) {
    console.log('[-] unknown event received ' + event + ' on ' + file);
  },
};

//Clean destDirecotry first
fs.remove(destDir, function(err) {
  if (err) {
    console.log(err);
    return 1;
  }
  fs.copy(sharedDir, destDir, function(err) {
    if (err) {
      console.log(err);
      return 1;
    }
    http.createServer(function(request,response){
      var req = "";

      request.on('data', function(chunk) {
        req+=chunk
      });

      request.on('end', function() {
        var reqObj = JSON.parse(req);
        var dispatchKey = reqObj["event"];

        if (!(dispatchKey in eventDispatch)) {
          dispatchKey = 'default';
        }

        eventDispatch[dispatchKey](reqObj['event'], reqObj['file'], reqObj['checkSum']);
      });

      response.writeHead(200, {'Content-Type': 'application/json'});
      response.write(JSON.stringify({code: 200, message: 'Hello'}));
      response.end();
    }).listen(port, address);

    console.log("Server is listening to http://" + address + ":" + port);
  });
})
<|endoftext|>


<commit_before>// Run JSHint and Plato over the specified files

var fs = require('fs');
var path = require('path');
var async = require('async');
var chalk = require('chalk');
var plato = require('plato');
var Getopt = require('node-getopt');
var buildJSHint = require('build-jshint');

var filesets = require('./lib/filesets.js');
var reporter = require('./lib/reporter.js');

// By default reports are output to `./reports` and given the title of `Plato
// Report`.

var outputDir = 'reports';

var options = {};
var jsHintOptions = {};
var platoOptions = {
    title: 'Plato Report',
    recurse: true,
    quiet: true
};

// Check the path provided by the user, prefixing it with `./` if it's not an
// explicitly provided as an absolute or relative path. Valid paths are passed
// to the provided callback.

function checkPath(string, callback, done) {
    var path = string;
    if (!(/^\.|\//).test(string)) {
        path = './' + string;
    }

    fs.stat(path, function(err) {
        if (err) {
            console.log(chalk.red('Error, cannot open: %s'), string);
            process.exit(1);
        } else {
            callback(path, done);
        }
    });
}

// Plato uses the `jshintrc` as is, whereas JSHint-Build needs the options
// inserted into its own options.

function setJSHint(path, done) {
    var opts = JSON.parse(fs.readFileSync(path, 'utf8'));

    jsHintOptions.config = opts;
    done();
}

// The default `jshintrc` from the linter package can be overridden with the
// `jshint` option. The provided file is checked to ensure it exists before it's
// used.

function checkJSHint(done) {
    if(!options.jshint) {
        options.jshint = path.join(__dirname, '.jshintrc');
    }

    checkPath(options.jshint, setJSHint, done);
}

// Set the filesets from those defined in the provided configuration file. If
// a given fileset isn't defined then a warning will be output. The `lintOnly`
// fileset is an optional fileset that will be excluded from the Plato fileset.

function setFilesets(path, done) {
    var config = JSON.parse(fs.readFileSync(path, 'utf8'));

    /* jshint sub: true */
    var includeFiles = config['includeFiles'];
    var excludeFiles = config['excludeFiles'];
    var filterFiles = config['lintOnly'];
    /* jshint sub: false */

    if (filterFiles && !Array.isArray(filterFiles)) {
        filterFiles = [];
        console.log(chalk.yellow('invalid `lintOnly` set; ignoring'));
    }

    if (includeFiles && Array.isArray(includeFiles)) {
        filesets.include(includeFiles, filterFiles);
    } else {
        console.log(chalk.yellow('valid `includeFiles` not found in %s'), path);
    }

    if (excludeFiles && Array.isArray(includeFiles)) {
        filesets.exclude(excludeFiles);
    } else {
        console.log(chalk.yellow('valid `excludeFiles` not found in %s'), path);
    }

    done();
}

// The default filesets that are used can be overridden from the command line by
// providing a configuration file with the new filesets defined. The existence
// of the configuration file is checked before the new filesets are defined.

function checkFilesets(done) {
    /* jshint sub: true */
    if (options['filesets']) {
        checkPath(options['filesets'], setFilesets, done);
    } else {
        done();
    }
    /* jshint sub: false */
}

// Run the actual reports. The plato reports are run first, then the JSHint
// report. The output is annotated with headers and details on where the reports
// are stored.

function runReports(err) {
    if (err) { console.log(chalk.red('Error running reports: %s'), err); }

    var excludes = filesets.platoExcludes();

    if (excludes) {
        platoOptions.exclude = excludes;
    }

    jsHintOptions.ignore = filesets.jshintExcludes();
    jsHintOptions.reporter = reporter.reporter;

    console.log(chalk.blue('Building plato reports...'));
    console.log(chalk.gray('(Ignore any output about being unable to parse ' +
        'JSON files)'));

    plato.inspect(filesets.platoIncludes(), outputDir, platoOptions,
        function() {
            console.log(chalk.blue('\nPlato reports have been built to: ') +
                chalk.magenta(outputDir));
            console.log(chalk.blue('\nJSHint Report\n=============\n'));
            buildJSHint(filesets.jshintIncludes(), jsHintOptions,
                reporter.callback);
        }
    );
}

// Provide options to override all the defaults from the command line

getopt = new Getopt([
    ['t', 'title=TITLE', 'The title of the report.'],
    ['o', 'output=PATH', 'The directory to output the reports to'],
    ['l', 'jshint=PATH', 'Path to a jshintrc file for JSHint linting.'],
    ['f', 'filesets=PATH',
     'Path to a file containing the filesets to report on.'],
    ['h', 'help', 'display this help text.']
]);

getopt.setHelp("Usage: node report.js [options]\n[[OPTIONS]]");
getopt.bindHelp();

// Override defaults with any options from the command line, then run the
// reports.

options = getopt.parseSystem().options;

if (options.title) {
    platoOptions.title = options.title;
}

if (options.output) {
    outputDir = options.output;
}

async.parallel([checkJSHint, checkFilesets], runReports);

// ## License
//
// Copyright (c) 2014, RainBird Technologies <follow@rainbird.ai>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.<commit_msg>Adds a --version flag<commit_after>// Run JSHint and Plato over the specified files

var fs = require('fs');
var path = require('path');
var async = require('async');
var chalk = require('chalk');
var plato = require('plato');
var Getopt = require('node-getopt');
var buildJSHint = require('build-jshint');

var filesets = require('./lib/filesets.js');
var reporter = require('./lib/reporter.js');

// By default reports are output to `./reports` and given the title of `Plato
// Report`.

var outputDir = 'reports';

var options = {};
var jsHintOptions = {};
var platoOptions = {
    title: 'Plato Report',
    recurse: true,
    quiet: true
};

// Check the path provided by the user, prefixing it with `./` if it's not an
// explicitly provided as an absolute or relative path. Valid paths are passed
// to the provided callback.

function checkPath(string, callback, done) {
    var path = string;
    if (!(/^\.|\//).test(string)) {
        path = './' + string;
    }

    fs.stat(path, function(err) {
        if (err) {
            console.log(chalk.red('Error, cannot open: %s'), string);
            process.exit(1);
        } else {
            callback(path, done);
        }
    });
}

// Plato uses the `jshintrc` as is, whereas JSHint-Build needs the options
// inserted into its own options.

function setJSHint(path, done) {
    var opts = JSON.parse(fs.readFileSync(path, 'utf8'));

    jsHintOptions.config = opts;
    done();
}

// The default `jshintrc` from the linter package can be overridden with the
// `jshint` option. The provided file is checked to ensure it exists before it's
// used.

function checkJSHint(done) {
    if(!options.jshint) {
        options.jshint = path.join(__dirname, '.jshintrc');
    }

    checkPath(options.jshint, setJSHint, done);
}

// Set the filesets from those defined in the provided configuration file. If
// a given fileset isn't defined then a warning will be output. The `lintOnly`
// fileset is an optional fileset that will be excluded from the Plato fileset.

function setFilesets(path, done) {
    var config = JSON.parse(fs.readFileSync(path, 'utf8'));

    /* jshint sub: true */
    var includeFiles = config['includeFiles'];
    var excludeFiles = config['excludeFiles'];
    var filterFiles = config['lintOnly'];
    /* jshint sub: false */

    if (filterFiles && !Array.isArray(filterFiles)) {
        filterFiles = [];
        console.log(chalk.yellow('invalid `lintOnly` set; ignoring'));
    }

    if (includeFiles && Array.isArray(includeFiles)) {
        filesets.include(includeFiles, filterFiles);
    } else {
        console.log(chalk.yellow('valid `includeFiles` not found in %s'), path);
    }

    if (excludeFiles && Array.isArray(includeFiles)) {
        filesets.exclude(excludeFiles);
    } else {
        console.log(chalk.yellow('valid `excludeFiles` not found in %s'), path);
    }

    done();
}

// The default filesets that are used can be overridden from the command line by
// providing a configuration file with the new filesets defined. The existence
// of the configuration file is checked before the new filesets are defined.

function checkFilesets(done) {
    /* jshint sub: true */
    if (options['filesets']) {
        checkPath(options['filesets'], setFilesets, done);
    } else {
        done();
    }
    /* jshint sub: false */
}

// Run the actual reports. The plato reports are run first, then the JSHint
// report. The output is annotated with headers and details on where the reports
// are stored.

function runReports(err) {
    if (err) { console.log(chalk.red('Error running reports: %s'), err); }

    var excludes = filesets.platoExcludes();

    if (excludes) {
        platoOptions.exclude = excludes;
    }

    jsHintOptions.ignore = filesets.jshintExcludes();
    jsHintOptions.reporter = reporter.reporter;

    console.log(chalk.blue('Building plato reports...'));
    console.log(chalk.gray('(Ignore any output about being unable to parse ' +
        'JSON files)'));

    plato.inspect(filesets.platoIncludes(), outputDir, platoOptions,
        function() {
            console.log(chalk.blue('\nPlato reports have been built to: ') +
                chalk.magenta(outputDir));
            console.log(chalk.blue('\nJSHint Report\n=============\n'));
            buildJSHint(filesets.jshintIncludes(), jsHintOptions,
                reporter.callback);
        }
    );
}

// Provide options to override all the defaults from the command line

getopt = new Getopt([
    ['t', 'title=TITLE', 'The title of the report.'],
    ['o', 'output=PATH', 'The directory to output the reports to'],
    ['l', 'jshint=PATH', 'Path to a jshintrc file for JSHint linting.'],
    ['f', 'filesets=PATH',
     'Path to a file containing the filesets to report on.'],
    ['v', 'version', 'Display the installed version'],
    ['h', 'help', 'display this help text.']
]);

getopt.setHelp("Usage: node report.js [options]\n[[OPTIONS]]");
getopt.bindHelp();

// Override defaults with any options from the command line, then run the
// reports.

options = getopt.parseSystem().options;

if (options.title) {
    platoOptions.title = options.title;
}

if (options.output) {
    outputDir = options.output;
}

if (options.version) {
    var path = path.join(__dirname, 'package.json');
    var pkg = JSON.parse(fs.readFileSync(path, 'utf8'));
    console.log(pkg.version);
    process.exit(0);
}

async.parallel([checkJSHint, checkFilesets], runReports);

// ## License
//
// Copyright (c) 2014, RainBird Technologies <follow@rainbird.ai>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.<|endoftext|>


<commit_before>//==========
//===EH LEE LA DOCUMENTACIÓN ACA=====
//==http://expressjs.com/guide/routing.html===
//==Para más detalles de la API MIRA ACA===
//==http://expressjs.com/4x/api.html
var express = require('express');
var http = require('http');
var app = express();

var options = {
  hostname: 'localhost',
  port: 3000,
  path: '/alumnoSeConecta',
  method: 'GET'
}

app.get('/', function (req, res) {
  res.send('Hello World!');
});

var server = app.listen(5000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

connect();

var interval = setInterval(produce(), 1000);
clearInterval(interval);

function connect() {
  console.log('me conecto');
  http.get('http://localhost:3000/alumnoSeConecta?port=5000', function(res){
    console.log('me conecte');
  });
}

function produce() {
  console.log('envio una consulta');
  http.get('http://localhost:3000/alumnoEscribe?port=5000&consulta=unaconsulta', function(res){
    console.log('la consulta fue enviada');
  });
}

<commit_msg>alumno nueva cons<commit_after>//==========
//===EH LEE LA DOCUMENTACIÓN ACA=====
//==http://expressjs.com/guide/routing.html===
//==Para más detalles de la API MIRA ACA===
//==http://expressjs.com/4x/api.html
var express = require('express');
var http = require('http');
var app = express();

var options = {
  hostname: 'localhost',
  port: 3000,
  path: '/alumnoSeConecta',
  method: 'GET'
}

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.get('/nuevaConsulta', function (req, res) {
  console.log('nueva consulta: ', req.query.consulta);
});

var server = app.listen(5000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

connect();

var interval = setInterval(produce(), 1000);
clearInterval(interval);

function connect() {
  console.log('me conecto');
  http.get('http://localhost:3000/alumnoSeConecta?port=5000', function(res){
    console.log('me conecte');
  });
}

function produce() {
  console.log('envio una consulta');
  http.get('http://localhost:3000/alumnoEscribe?port=5000&consulta=unaconsulta', function(res){
    console.log('la consulta fue enviada');
  });
}

<|endoftext|>


<commit_before>var monk = require('monk');

var winston = require('winston')

const conn = monk('localhost:27017/partstracker');
const users = conn.get('users');
const inventory = conn.get('inventory');
const reservations = conn.get('reservations');
const activities = conn.get('activities');
const requests = conn.get('requests');
const assemblies = conn.get('assemblies');
const assembly_links = conn.get('assembly_links');

reservations.ensureIndex( {part: 1} );

var DatabaseItem = function(database, id) {
    this.db = database;
    if(id === undefined) {
        this._id = monk.id();
    } else {
        this._id = id;
    }
}

/* Returns this item's ObjectID. */
DatabaseItem.prototype.id = function () {
    return monk.id(this._id);
};

/* Get or set a property. */
DatabaseItem.prototype.prop = function (k, v) {
    if(k === 'updated' || k === 'created') {
        v = undefined;
    }

    if(v === undefined) {
        /* Get name */
        if(this['_'+k] === undefined) {
            return this.db.findOne({_id: this.id()}).then(
                (doc) => {
                    if(doc === null) {
                        return null;
                    } else {
                        this['_'+k] = doc[k];
                        return doc[k];
                    }
                }
            );
        } else {
            return Promise.resolve(this['_'+k]);
        }
    } else {
        /* Set name */
        this['_'+k] = v;
    }
};

DatabaseItem.prototype.updated = function () { return this.prop('updated'); };
DatabaseItem.prototype.created = function () { return this.prop('created'); };

/* Check to see if this item exists in the database. */
DatabaseItem.prototype.exists = function () {
    return this.db.count({_id: this.id()}).then(
        (count) => {
            return (count > 0);
        }
    );
};

/* Update the DatabaseItem with information from the database. */
DatabaseItem.prototype.fetch = function () {
    return this.db.findOne({_id: this.id()}).then(
        (doc) => {
            if(doc === null) {
                return this; // no updates
            } else {
                for(var prop in doc) {
                    if(doc.hasOwnProperty(prop) && prop !== '_id') {
                        this['_'+prop] = doc[prop];
                    }
                }

                return this;
            }
        }
    );
};

/* Update the database with information from this object. */
DatabaseItem.prototype.save = function () {
    return this.db.count({_id: this.id()}).then(
        (n) => {
            spec = { _id: this.id() };
            for(var prop in this) {
                if(this.hasOwnProperty(prop) &&
                    prop !== '_id' &&
                    prop !== '_updated' &&
                    prop !== '_created' &&
                    prop.charAt(0) === '_') {
                    spec[prop.substr(1)] = this[prop];
                }
            }

            /* Set last updated time */
            spec.updated = new Date();

            if(n == 0) {
                /* Insert this as a new document: */
                spec.created = new Date();
                winston.log('info', 'Added new object %s to %s collection.',
                    this.id().toString(), this.db.name,
                    {
                        id: this.id().toString(),
                        collection: this.db.name,
                        object: JSON.stringify(spec)
                    }
                );

                return this.db.insert(spec);
            } else {
                /* Update the existing document: */
                winston.log('info', 'Updated object %s in %s collection.',
                    this.id().toString(), this.db.name,
                    {
                        id: this.id().toString(),
                        collection: this.db.name,
                        spec: JSON.stringify(spec)
                    }
                );

                return this.db.update(
                    { _id: this.id() },
                    { $set: spec }
                );
            }
        }
    ).then( () => { return this; } );
};

DatabaseItem.prototype.delete = async function () {
    winston.log('info', 'Deleted object %s from %s collection.',
        this.id().toString(), this.db.name,
        {
            id: this.id().toString(),
            collection: this.db.name
        }
    );
    return this.db.remove({_id: this.id()});
};

module.exports = {
    conn: conn,
    users: users,
    inventory: inventory,
    reservations: reservations,
    activities: activities,
    requests: requests,
    assemblies: assemblies,
    assembly_links: assembly_links,
    DatabaseItem: DatabaseItem
};
<commit_msg>Add ability to change database connection and collection objects<commit_after>var monk = require('monk');
var winston = require('winston');
var args = require('minimist')(process.argv.slice(2));

const dbLocation = `${args.db_host || 'localhost'}:${args.db_port || 27017}/partstracker`;

/* Database collections are also exported under the appropriate names. */
module.exports = {
    DatabaseItem: DatabaseItem
};

/* This function is mostly intended for testing purposes.
 * It should not be called when DatabaseItem (subclass) objects are in use
 * (i.e. don't call this from middleware)
 */
async function reset_database_connection(newLocation) {
    /* Close the old connection, if necessary */
    if(module.exports.conn) {
        await module.exports.conn.close();
    }

    const conn = monk(newLocation);

    module.exports.conn = conn;
    module.exports.users = conn.get('users');
    module.exports.inventory = conn.get('inventory');
    module.exports.reservations = conn.get('reservations');
    module.exports.activities = conn.get('activities');
    module.exports.requests = conn.get('requests');

    module.exports.reservations.ensureIndex( {part: 1} );
}

/* Open the initial connection. */
reset_database_connection(dbLocation);

function DatabaseItem(database, id) {
    this.db = database;
    if(id === undefined) {
        this._id = monk.id();
    } else {
        this._id = id;
    }
}

/* Returns this item's ObjectID. */
DatabaseItem.prototype.id = function () {
    return monk.id(this._id);
};

/* Get or set a property. */
DatabaseItem.prototype.prop = function (k, v) {
    if(k === 'updated' || k === 'created') {
        v = undefined;
    }

    if(v === undefined) {
        /* Get name */
        if(this['_'+k] === undefined) {
            return this.db.findOne({_id: this.id()}).then(
                (doc) => {
                    if(doc === null) {
                        return null;
                    } else {
                        this['_'+k] = doc[k];
                        return doc[k];
                    }
                }
            );
        } else {
            return Promise.resolve(this['_'+k]);
        }
    } else {
        /* Set name */
        this['_'+k] = v;
    }
};

DatabaseItem.prototype.updated = function () { return this.prop('updated'); };
DatabaseItem.prototype.created = function () { return this.prop('created'); };

/* Check to see if this item exists in the database. */
DatabaseItem.prototype.exists = function () {
    return this.db.count({_id: this.id()}).then(
        (count) => {
            return (count > 0);
        }
    );
};

/* Update the DatabaseItem with information from the database. */
DatabaseItem.prototype.fetch = function () {
    return this.db.findOne({_id: this.id()}).then(
        (doc) => {
            if(doc === null) {
                return this; // no updates
            } else {
                for(var prop in doc) {
                    if(doc.hasOwnProperty(prop) && prop !== '_id') {
                        this['_'+prop] = doc[prop];
                    }
                }

                return this;
            }
        }
    );
};

/* Update the database with information from this object. */
DatabaseItem.prototype.save = function () {
    return this.db.count({_id: this.id()}).then(
        (n) => {
            spec = { _id: this.id() };
            for(var prop in this) {
                if(this.hasOwnProperty(prop) &&
                    prop !== '_id' &&
                    prop !== '_updated' &&
                    prop !== '_created' &&
                    prop.charAt(0) === '_') {
                    spec[prop.substr(1)] = this[prop];
                }
            }

            /* Set last updated time */
            spec.updated = new Date();

            if(n == 0) {
                /* Insert this as a new document: */
                spec.created = new Date();
                winston.log('info', 'Added new object %s to %s collection.',
                    this.id().toString(), this.db.name,
                    {
                        id: this.id().toString(),
                        collection: this.db.name,
                        object: JSON.stringify(spec)
                    }
                );

                return this.db.insert(spec);
            } else {
                /* Update the existing document: */
                winston.log('info', 'Updated object %s in %s collection.',
                    this.id().toString(), this.db.name,
                    {
                        id: this.id().toString(),
                        collection: this.db.name,
                        spec: JSON.stringify(spec)
                    }
                );

                return this.db.update(
                    { _id: this.id() },
                    { $set: spec }
                );
            }
        }
    ).then( () => { return this; } );
};

DatabaseItem.prototype.delete = async function () {
    winston.log('info', 'Deleted object %s from %s collection.',
        this.id().toString(), this.db.name,
        {
            id: this.id().toString(),
            collection: this.db.name
        }
    );
    return this.db.remove({_id: this.id()});
};
<|endoftext|>


<commit_before>var mysql = require('mysql');
const config = require('./config');
var log = config.log();

var pool = mysql.createPool(config.mysql);
//mysql example: https://www.npmjs.com/package/mysql
//function done(error, account)
function getAccount(username, done) {
    var sql =  'SELECT * FROM Account WHERE uname=?;';
    sql = mysql.format(sql, username);
    log.debug(sql);
    pool.query(sql, function(error, rows, fields){
	//log.debug("query account for " + username);
	if(error){
	    log.error('query error');
	    return done(error, null);
	}else if(rows[0]){
	    log.debug(rows);
	    //log.debug('uname= ' + rows[0].uname);
	    log.debug('password = ' + rows[0].password);
	    return done(null, rows[0]);
	}
	return done(null, null);
    });
}

//function don(error, success)
function putAccount(username, password, done){
    var sql = mysql.format('INSERT INTO Account VALUES (?,?);', [username, password]);
    pool.query(sql, function(error, rows, fields){
	if(error){
	    return done(error, false);
	}else{
	    return done(null, true);
	}
    });
}

/*project-updates*/
function getReleatedProject(username){
    var sql = "SELECT pname FROM User_project WHERE uname = ?";
    sql += "UNION SELECT pname FROM Project WHERE uname = ?";
    sql += "UNION SELECT pname FROM Pledge WHERE uname = ?";
    return mysql.format(sql, [username, username, username]);
}

function getReleatedUpdate(username){
    var sql_pname = getReleatedProject(username);
    sql = "SELECT * FROM Project_update WHERE pname IN (" + sql_pname + ");";
    return sql;
}

function getUpdate(projectname){
    return mysql.format("SELECT * FROM Project_update WHERE pname = ?", [projectname]);
}

/*Users'comment, pledge, like and fellow*/
const fellowedUser = 'SELECT fellowed_uname FROM Fellow_user WHERE fellower_uname = ?';

//TODO: rename methods from get to query
function getUserPledge(username, done){
    var sql = 'SELECT pname, time, amount FROM Pledge WHERE uname IN ('+ fellowedUser +');';
    sql = mysql.format(sql, username);
    return pool.query(sql, done);
}

function getUserComment(username, done){
    sql = 'SELECT pname, time, comment FROM Comment_project WHERE uname IN ('+ fellowedUser +');';
    sql = mysql.format(sql, [username]);
    log.debug(sql);
    return pool.query(sql, done);
}

function getFellowedProject(username, done){
    var sql = mysql.format('SELECT pname, time, relation FROM User_project WHERE uname IN ('+ fellowedUser +');', [username]);
    return pool.query(sql, done);
}

function getUser(username){
    return "SELECT * FROM `Users` WHERE `uname`=" + pool.escape(username) + ";";
}

function putUser(username, address, credict_card){
    address = address || null;
    credict_card = credict_card || null;
    return mysql.format('INSERT INTO Users VALUES (?,?,?);', [username, address, credict_card]);
}

function updateUser(username, address, credict_card, picture, done){
    address = address || null;
    credict_card = credict_card || null;
    const tmp ='UPDATE Users SET address = ?, credict_card = ?, picture = ? WHERE uname = ?;';
    var sql = mysql.format(tmp, [address, credict_card, picture, username]);
    log.debug(sql);
    pool.query(sql, function(error, rows, fields){
	if(error){
	    log.debug(error);
	    return done(false);
	}else{
	    return done(true);
	}
    });
}

function where(fields){
    if(!fields || fields.length == 0){
	return '';
    }
    var sql = 'WHERE ' + mysql.format(fields[0][0], fields[0][1]);
    for(i = 1; i < fields.length; i++){
	sql =sql + ' AND ' + mysql.format(fields[i][0], fields[i][1]);
    }
    return sql;
}

function select(fields){
    if(!fields || fields == '*' || fields.length == 0|| fields[0] == '*'){
	return 'SELECT * ';
    }
    var sql = 'SELECT ' + fields[0];
    for(i = 1; i < fields.length; i++){
	sql =sql + ' , ' + fields[i];
    }
    return sql;
}

/*Projects Releated. */
function getProjects(num, fields, done){
    var sql = mysql.format('SELECT * FROM Project '+ where(fields) +' ORDER BY start_time DESC LIMIT ? ;', num);
    log.debug(sql);
    pool.query(sql, done);
}

/*Projects updates.
 *fields include pname, type(`text`| `video`| `picture`), keyword serach in content
 * */
function getUpdates(num, fields, done){
    var sql = mysql.format('SELECT * FROM Project_update '+ where(fields) +' ORDER BY time DESC LIMIT ? ;', num);
    log.debug(sql);
    pool.query(sql, done);
}

function getSelected(fields, table, conditions, done){
    var sql = select(fields) + ' FROM ' + table + ' ' + where(conditions) + ';';
    log.debug(sql);
    pool.query(sql, done);
}

function insert(table, values, done){
    if(values && values.length != 0){
	var tmp = ' ? ';
	for(i=0; i < values.length - 1; i++){
	    tmp = tmp + ', ? ';
	}
	var sql = 'INSERT INTO ' + table + ' VALUES (' + tmp + ' );'
	log.debug(sql);
	sql = mysql.format(sql, values);
	log.debug(sql);
	pool.query(sql, function(error, rows, fields){
	    if(error){
		return done(false);
	    }else{
		return done(true);
	    }
	});
    }else{
	throw new error('undefined values for insert qury.');
    }
}

function remove(table, conditions, done){
    log.debug(conditions);
    if(conditions && conditions.length != 0){
	var tmp = ' ? ';
	for(i=0; i < conditions.length - 1; i++){
	    tmp = tmp + ', ? ';
	}
	var sql = 'DELETE FROM ' + table +' '+ where(conditions) + ';';
	sql = mysql.format(sql, conditions);
	log.debug(sql);
	pool.query(sql, function(error, rows, fields){
	    if(error){
		return done(false);
	    }else{
		return done(true);
	    }
	});
    }else{
	return done(false);
    }
}

module.exports.sql ={
    'getUser': getUser,
    'putUser': putUser,
    'getReleatedUpdate': getReleatedUpdate,
    'select': getSelected,
    'insert': insert,
    'remove': remove
};

module.exports.user = {
    'getAccount': getAccount,
    'putAccount': putAccount,
    'updateProfile': updateUser,
    'getPledge': getUserPledge,
    'getComment': getUserComment,
    'getFellowedProject':getFellowedProject
};

module.exports.project = {
    'get':getProjects,
    'getUpdates':getUpdates
};

module.exports.pool = pool;
<commit_msg>add uname, picture in newsfeed/activities<commit_after>var mysql = require('mysql');
const config = require('./config');
var log = config.log();

var pool = mysql.createPool(config.mysql);
//mysql example: https://www.npmjs.com/package/mysql
//function done(error, account)
function getAccount(username, done) {
    var sql =  'SELECT * FROM Account WHERE uname=?;';
    sql = mysql.format(sql, username);
    log.debug(sql);
    pool.query(sql, function(error, rows, fields){
	//log.debug("query account for " + username);
	if(error){
	    log.error('query error');
	    return done(error, null);
	}else if(rows[0]){
	    log.debug(rows);
	    //log.debug('uname= ' + rows[0].uname);
	    log.debug('password = ' + rows[0].password);
	    return done(null, rows[0]);
	}
	return done(null, null);
    });
}

//function don(error, success)
function putAccount(username, password, done){
    var sql = mysql.format('INSERT INTO Account VALUES (?,?);', [username, password]);
    pool.query(sql, function(error, rows, fields){
	if(error){
	    return done(error, false);
	}else{
	    return done(null, true);
	}
    });
}

/*project-updates*/
function getReleatedProject(username){
    var sql = "SELECT pname FROM User_project WHERE uname = ?";
    sql += "UNION SELECT pname FROM Project WHERE uname = ?";
    sql += "UNION SELECT pname FROM Pledge WHERE uname = ?";
    return mysql.format(sql, [username, username, username]);
}

function getReleatedUpdate(username){
    var sql_pname = getReleatedProject(username);
    sql = "SELECT * FROM Project_update WHERE pname IN (" + sql_pname + ");";
    return sql;
}

function getUpdate(projectname){
    return mysql.format("SELECT * FROM Project_update WHERE pname = ?", [projectname]);
}

/*Users'comment, pledge, like and fellow*/
const fellowedUser = 'SELECT fellowed_uname FROM Fellow_user WHERE fellower_uname = ?';

//TODO: rename methods from get to query
function getUserPledge(username, done){
    var sql = 'SELECT pname, uname, picture, time, amount FROM Pledge NATURAL JOIN Users WHERE uname IN ('+ fellowedUser +');';
    sql = mysql.format(sql, username);
    return pool.query(sql, done);
}

function getUserComment(username, done){
    sql = 'SELECT uname, picture, pname, time, comment FROM Comment_project NATURAL JOIN Users WHERE uname IN ('+ fellowedUser +');';
    sql = mysql.format(sql, [username]);
    log.debug(sql);
    return pool.query(sql, done);
}

function getFellowedProject(username, done){
    var sql = mysql.format('SELECT pname, uname, picture, time, relation FROM User_project NATURAL JOIN Users WHERE uname IN ('+ fellowedUser +');', [username]);
    return pool.query(sql, done);
}

function getUser(username){
    return "SELECT * FROM `Users` WHERE `uname`=" + pool.escape(username) + ";";
}

function putUser(username, address, credict_card){
    address = address || null;
    credict_card = credict_card || null;
    return mysql.format('INSERT INTO Users VALUES (?,?,?);', [username, address, credict_card]);
}

function updateUser(username, address, credict_card, picture, done){
    address = address || null;
    credict_card = credict_card || null;
    const tmp ='UPDATE Users SET address = ?, credict_card = ?, picture = ? WHERE uname = ?;';
    var sql = mysql.format(tmp, [address, credict_card, picture, username]);
    log.debug(sql);
    pool.query(sql, function(error, rows, fields){
	if(error){
	    log.debug(error);
	    return done(false);
	}else{
	    return done(true);
	}
    });
}

function where(fields){
    if(!fields || fields.length == 0){
	return '';
    }
    var sql = 'WHERE ' + mysql.format(fields[0][0], fields[0][1]);
    for(i = 1; i < fields.length; i++){
	sql =sql + ' AND ' + mysql.format(fields[i][0], fields[i][1]);
    }
    return sql;
}

function select(fields){
    if(!fields || fields == '*' || fields.length == 0|| fields[0] == '*'){
	return 'SELECT * ';
    }
    var sql = 'SELECT ' + fields[0];
    for(i = 1; i < fields.length; i++){
	sql =sql + ' , ' + fields[i];
    }
    return sql;
}

/*Projects Releated. */
function getProjects(num, fields, done){
    var sql = mysql.format('SELECT * FROM Project '+ where(fields) +' ORDER BY start_time DESC LIMIT ? ;', num);
    log.debug(sql);
    pool.query(sql, done);
}

/*Projects updates.
 *fields include pname, type(`text`| `video`| `picture`), keyword serach in content
 * */
function getUpdates(num, fields, done){
    var sql = mysql.format('SELECT * FROM Project_update '+ where(fields) +' ORDER BY time DESC LIMIT ? ;', num);
    log.debug(sql);
    pool.query(sql, done);
}

function getSelected(fields, table, conditions, done){
    var sql = select(fields) + ' FROM ' + table + ' ' + where(conditions) + ';';
    log.debug(sql);
    pool.query(sql, done);
}

function insert(table, values, done){
    if(values && values.length != 0){
	var tmp = ' ? ';
	for(i=0; i < values.length - 1; i++){
	    tmp = tmp + ', ? ';
	}
	var sql = 'INSERT INTO ' + table + ' VALUES (' + tmp + ' );'
	log.debug(sql);
	sql = mysql.format(sql, values);
	log.debug(sql);
	pool.query(sql, function(error, rows, fields){
	    if(error){
		return done(false);
	    }else{
		return done(true);
	    }
	});
    }else{
	throw new error('undefined values for insert qury.');
    }
}

function remove(table, conditions, done){
    log.debug(conditions);
    if(conditions && conditions.length != 0){
	var tmp = ' ? ';
	for(i=0; i < conditions.length - 1; i++){
	    tmp = tmp + ', ? ';
	}
	var sql = 'DELETE FROM ' + table +' '+ where(conditions) + ';';
	sql = mysql.format(sql, conditions);
	log.debug(sql);
	pool.query(sql, function(error, rows, fields){
	    if(error){
		return done(false);
	    }else{
		return done(true);
	    }
	});
    }else{
	return done(false);
    }
}

module.exports.sql ={
    'getUser': getUser,
    'putUser': putUser,
    'getReleatedUpdate': getReleatedUpdate,
    'select': getSelected,
    'insert': insert,
    'remove': remove
};

module.exports.user = {
    'getAccount': getAccount,
    'putAccount': putAccount,
    'updateProfile': updateUser,
    'getPledge': getUserPledge,
    'getComment': getUserComment,
    'getFellowedProject':getFellowedProject
};

module.exports.project = {
    'get':getProjects,
    'getUpdates':getUpdates
};

module.exports.pool = pool;
<|endoftext|>


<commit_before>"use strict";

var Applet = null;

(function () { // === scope ==============================

  Applet = function () {
    var i = this; // === this instance

    i.stack = [];
    i.id_counter = -1;
    i.stack      = _.clone(Applet.core);

    i.configs    = {}; // === used by callbacks to store info.
    i.func_ids   = {}; // give each callback an id to be used in .configs

    i.run('constructor');
    i.run('dom');
    i.run('form');
  }; // === Applet constructor ===========================

  Applet._id = -1;

  // =====================================================
  // === HELPERS
  // =====================================================

  var bool = function (o, key) {
    if (!_.has(o, key))
      throw new Error('Key not found: ' + key);

    return !!o[key];
  };

  var log = Applet.log = function (str) {
    if (window.console)
      return console.log.apply(console, arguments);
    return this;
  };

  // Get id or (create id, return it)
  var id = Applet.id = function (raw, prefix) {
    var o = $(raw);
    var old = o.attr('id');

    if (old && !_.isEmpty(old))
      return old;

    Applet._id = Applet._id + 1;
    var new_id = (prefix || 'id_for_applet') + '_' + Applet._id.toString();
    o.attr('id', new_id);
    return new_id;
  }; // === id

  var insert_after = Applet.insert_after = function (script) {
    $($(script).contents()).insertAfter($(script));
  }; // === insert_after

  var insert_before = Applet.insert_before = function (script) {
    $($(script).contents()).insertBefore($(script));
  }; // === insert_before

  var meta_key = Applet.meta_key = function (str) {
    var dots  = str.split('.');
    var bangs = '';

    if (dots[0]) {
      var temp = /(\!+)?(.+)/.exec(dots[0]);
      if (temp) {
        bangs = temp[1] || '';
        dots[0] = temp[2];
      }
    }

    return { bangs: bangs, keys: dots};
  }; // === func

  var is_true = Applet.is_true = function (data, key) {
    var meta = meta_key(key);
    var current = data;
    var ans  = false;

    if (!_.has(data, meta.keys[0])) {
      return undefined;
    }

    _.detect(meta.keys, function (key) {
      if (_.has(current, key)) {
        current = data[key];
        ans = !!current;
      } else {
        ans = false;
      }

      return !ans;
    });

    if (meta.bangs) {
      _.times(meta.bangs.length, function (n) {
        ans = !ans;
      });
    }

    return ans;
  }; // === func

  var attrs = Applet.attrs = function (dom) {
    return _.reduce(
      dom.attributes,
      function (kv, o) {
        kv[o.name] = o.value;
        return kv;
      },
      {}
    );
  }; // === attrs

  Applet.standard_name = function (str) {
    return _.trim(str).replace(/\ +/g, ' ').toLowerCase();
  };

  Applet.remove_attr = function (node, name) {
    var val = $(node).attr(name);
    $(node).removeAttr(name);
    return val;
  };

  var node_array = Applet.node_array = function (unknown) {
    var arr = [];
    _.each($(unknown), function (dom) {
      if (dom.nodeType !== 1)
        return arr.push(dom);

      arr.push({
        tag    : dom.nodeName,
        attrs  : attrs(dom),
        custom : {},
        childs : node_array($(dom).contents())
      });
    });

    return arr;
  };

  var raw_scripts = Applet.raw_scripts = function () {
    return $('script[type="text/applet"]:not(script.compiled)');
  }; // === func

  var each_raw_script = Applet.each_raw_script = function (func) {

    var scripts, i, contents, script;

    while ((scripts = raw_scripts()).length > 0) {

      i = 0;

      while (scripts[i]) {
        script   = $(scripts[i]);
        contents = $(script.html());
        script.empty();
        script.append(contents);
        script.addClass('compiled');
        ++i;
      }

      i = 0;
      while (scripts[i]) {
        if (func)
          func(scripts[i], scripts);
        ++i;
      }
    }

    return true;
  }; // === func: each_raw_script

  Applet.top_descendents = function (dom, selector) {
    var arr = [];
    _.each($(dom), function (node) {
      var o = $(node);
      if (o.is(selector))
        return arr.push(o);
      arr = arr.concat(Applet.top_descendents(o.children(), selector));
    }); // === func

    return arr;
  }; // === func

  // =====================================================
  // === PROTOTYPE
  // =====================================================

  Applet.prototype.config_id = function (f) {
    var i = this;
    var id = _.findKey(i.func_ids, function (v) { return v === f; } );

    if (!id) {
      i.id_counter   = i.id_counter + 1;
      id             = 'config_id_' + i.id_counter;
      i.configs[id]  = {};
      i.func_ids[id] = f;
    }

    return id;
  }; // === config_id

  // === Examples:
  //
  // .run('str')               => {name: 'str'}
  // .run('str', {...})        => {name: 'str', data: {...}}
  // .run({name: 'str', ... }) => {name: 'str', ... }
  //
  Applet.prototype.run = function (msg, data) {

    var o = null;
    var instance = this;

    if (_.isPlainObject(msg)) {
      o = msg;
    } else { // === is String
      o = {
        name : Applet.standard_name(msg),
        data : data
      };
    }

    o.applet = instance;

    _.each(
      [
        'before before ' + o.name,
        'before ' + o.name,
        o.name,
        'after ' + o.name,
        'after after ' + o.name
      ],
      function (name) {
        o.name = Applet.standard_name(name);
        var i = 0, f;

        while (instance.stack[i]) {
          f             = instance.stack[i];
          o.this_config = instance.configs[instance.config_id(f)];
          o.this_func   = f;

          f(o);
          ++i;
        }
      }
    ); // === _.each name

    return instance;
  }; // === func

  Applet.prototype.unshift = function (func) {
    this.stack.unshift(func);
    return this;
  };

  Applet.prototype.push = function (func) {
    this.stack.push(func);
    return this;
  };

  // =================== CORE =================
  Applet.core = [];

  var raw_scripts = function () {
    return $('script[type="text/applet"]:not(script.compiled)');
  }; // === func

  // === dom ==================================
  Applet.core.push(function (o) {
    if (o.name === 'before dom') {
      if (!o.dom) {
        o.dom = raw_scripts();
        _.each(o.dom, function (raw) {
          var script   = $(raw);
          var contents = $(script.html());
          script.empty();
          script.append(contents);
          script.addClass('compiled');
        });
      }
    }

    if (o.name === 'after dom') {
      _.each(
        o.dom.filter('script'),
        function (e) {
          var s = $(e);
          (s.contents()).insertBefore(s);
        }
      );
    }

    if (o.name === 'after after dom') {
      if (raw_scripts().length > 0)
        o.applet.run('dom');
    }
  }); // === core: dom

  // === template ====================
  Applet.core.push(function (o) {
    var this_config = o.this_config;
    var applet     = o.applet;

    if (o.name === 'constructor') {
      o.this_config.templates = [];
      return;
    }

    if (o.name !== 'dom')
      return;

    var selector  = '*[template]';
    this_config.templates = this_config.templates.concat(
      _.map(
        Applet.top_descendents(o.dom, selector),
        function (t) {
          var placeholder = $('<script type="text/applet_placeholder"></script>');
          var placeholder_id = Applet.id(placeholder);
          var attr = _.trim(Applet.remove_attr(t, 'template')).split(/\ +/);
          var name = attr.shift();
          var pos  = (attr.length > 0) ? attr.pop() : 'replace';

          var meta = {
            name      : name,
            html      : t.prop('outerHTML'),
            mustache  : Hogan.compile(t.prop('outerHTML')),
            placeholder_id : placeholder_id,
            elements  : null,
            pos       : pos
          };

          applet.push(function (o) {
            if (o.name !== 'data' || !_.isPlainObject(o.data[meta.name]))
              return;

            // === Remove old nodes:
            if (meta.elements && meta.pos === 'replace') {
              meta.elements.remove();
            }

            var html = $(meta.mustache.render(o.data));
            if (meta.pos === 'replace' || meta.pos === 'bottom')
              html.insertBefore($('#' + meta.placeholder_id));
            else
              html.insertAfter($('#' + meta.placeholder_id));

            meta.elements = html;
            applet.run({
              name: 'dom',
              dom:  html
            });
          });

          t.replaceWith(placeholder);
          return meta;
        }
    ) // === each
    );
  }); // ==== core: template ==========

  // === show_if ====================
  Applet.core.push(function (o) {
    var this_config = o.this_config;

    if (o.name === 'constructor') {
      this_config.show_if_data_cache = {};
      return;
    }

    if (o.name === 'data') {
      _.extend(this_config.show_if_data_cache, o.data);
      return;
    }

    if (o.name !== 'dom')
      return;

    var selector = '*[show_if]';
    _.each(
      $(o.dom).find(selector).addBack(selector),
      function (raw) {
        var node = $(raw);
        var id   = Applet.id(node);
        var val  = Applet.remove_attr(node, 'show_if');

        if (!Applet.is_true(this_config.show_if_data_cache, val))
          node.hide();

        o.applet.push(
          function (o) {
            if (o.name !== 'data')
              return;

            var data = o.data;
            var ans = Applet.is_true(data, val);
            if (ans === undefined)
              return;

            if ( ans )
              $('#' + id).show();
            else
              $('#' + id).hide();
          }
        ); // === push
      } // === function raw
    ); // === _.each
  }); // === core: show_if ========

  Applet.core.push(
    function (o) {
      if (o.name !== 'before form')
        return;
      if (o.name === 'form') {
        if (!o['submit?'])
          return;
        o.send_ajax(o.data);
      }
      _.each(
        $('form:not(form.compiled) button.submit'),
        function (raw) {
          $(raw).on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            o.applet.run({
              name: 'form submit',
              'submit?' : true,
              form: $(this).parent('form').attr('id'),
              data: $(this).parent('form').serializeJSON()
            });
          });
        }
      ); // === each
    }
  ); // === push

})(); // === end scope =================================

<commit_msg>Various: fixes, typos, etc<commit_after>"use strict";
/* jshint undef: true, unused: true */
/* global Hogan  */

var Applet = function (optional_func) {
    var i = this; // === this instance

    i.stack = _.clone(Applet.core);

    i.run('constructor');

    if (optional_func)
      optional_func(i);

    i.run('dom');
    i.run('form');
  }; // === Applet constructor ===========================

(function () { // === scope ==============================

  // =====================================================
  // === HELPERS
  // =====================================================

  var bool, log, id,
  insert_after, insert_before, is_true, each_raw_script, raw_scripts;

  bool = function (o, key) {
    if (!_.has(o, key))
      throw new Error('Key not found: ' + key);

    return !!o[key];
  };

  log = Applet.log = function () {
    if (window.console)
      return console.log.apply(console, arguments);
    return this;
  };

  // Get id or (create id, return it)
  id = Applet.id = function (raw, prefix) {
    var o = $(raw);
    var old = o.attr('id');

    if (old && !_.isEmpty(old))
      return old;

    var new_id = Applet.new_id(prefix || 'id_for_applet_') ;
    o.attr('id', new_id);
    return new_id;
  }; // === id

  insert_after = Applet.insert_after = function (script) {
    $($(script).contents()).insertAfter($(script));
  }; // === insert_after

  insert_before = Applet.insert_before = function (script) {
    $($(script).contents()).insertBefore($(script));
  }; // === insert_before

  var meta_key = Applet.meta_key = function (str) {
    var dots  = str.split('.');
    var bangs = '';

    if (dots[0]) {
      var temp = /(\!+)?(.+)/.exec(dots[0]);
      if (temp) {
        bangs = temp[1] || '';
        dots[0] = temp[2];
      }
    }

    return { bangs: bangs, keys: dots};
  }; // === func

  is_true = Applet.is_true = function (data, key) {
    var meta = meta_key(key);
    var current = data;
    var ans  = false;

    if (!_.has(data, meta.keys[0])) {
      return undefined;
    }

    _.detect(meta.keys, function (key) {
      if (_.has(current, key)) {
        current = data[key];
        ans = !!current;
      } else {
        ans = false;
      }

      return !ans;
    });

    if (meta.bangs) {
      _.times(meta.bangs.length, function () {
        ans = !ans;
      });
    }

    return ans;
  }; // === func

  var attrs = Applet.attrs = function (dom) {
    return _.reduce(
      dom.attributes,
      function (kv, o) {
        kv[o.name] = o.value;
        return kv;
      },
      {}
    );
  }; // === attrs

  Applet.standard_name = function (str) {
    return _.trim(str).replace(/\ +/g, ' ').toLowerCase();
  };

  Applet.remove_attr = function (node, name) {
    var val = $(node).attr(name);
    $(node).removeAttr(name);
    return val;
  };

  var node_array = Applet.node_array = function (unknown) {
    var arr = [];
    _.each($(unknown), function (dom) {
      if (dom.nodeType !== 1)
        return arr.push(dom);

      arr.push({
        tag    : dom.nodeName,
        attrs  : attrs(dom),
        custom : {},
        childs : node_array($(dom).contents())
      });
    });

    return arr;
  };

  raw_scripts = Applet.raw_scripts = function () {
    return $('script[type="text/applet"]:not(script.compiled)');
  }; // === func

  each_raw_script = Applet.each_raw_script = function (func) {

    var scripts, i, contents, script;

    while ((scripts = raw_scripts()).length > 0) {

      i = 0;

      while (scripts[i]) {
        script   = $(scripts[i]);
        contents = $(script.html());
        script.empty();
        script.append(contents);
        script.addClass('compiled');
        ++i;
      }

      i = 0;
      while (scripts[i]) {
        if (func)
          func(scripts[i], scripts);
        ++i;
      }
    }

    return true;
  }; // === func: each_raw_script

  Applet.top_descendents = function (dom, selector) {
    var arr = [];
    _.each($(dom), function (node) {
      var o = $(node);
      if (o.is(selector))
        return arr.push(o);
      arr = arr.concat(Applet.top_descendents(o.children(), selector));
    }); // === func

    return arr;
  }; // === func

  Applet.raw_scripts = function () {
    return $('script[type="text/applet"]:not(script.compiled)');
  }; // === func

  // =====================================================
  // === PROTOTYPE
  // =====================================================

  Applet.prototype.config_for_func = function (f) {
    var i = this;

    if (!i.func_ids) {
      i.func_id_to_config = {}; // === used by callbacks to store info.
      i.func_ids          = {}; // give each callback an id to be used in .configs
    }

    var id = _.findKey(i.func_ids, function (v) { return v === f; } );

    if (!id) {
      id             = Applet.new_id('config_id_');
      i.configs[id]  = {};
      i.func_ids[id] = f;
    }

    return i.func_id_to_config[id];
  }; // === config_id

  // === Examples:
  //
  // .run('str')               => {name: 'str'}
  // .run('str', {...})        => {name: 'str', data: {...}}
  // .run({name: 'str', ... }) => {name: 'str', ... }
  //
  Applet.prototype.run = function (msg, data) {

    var o = null;
    var instance = this;

    if (_.isPlainObject(msg)) {
      o = msg;
    } else { // === is String
      o = {
        name : Applet.standard_name(msg),
        data : data
      };
    }

    o.applet = instance;

    _.each(
      [
        'before before ' + o.name,
        'before ' + o.name,
        o.name,
        'after ' + o.name,
        'after after ' + o.name
      ],
      function (name) {
        o.name = Applet.standard_name(name);
        var i = 0, f;

        while (instance.stack[i]) {
          f             = instance.stack[i];
          o.this_config = instance.config_for_func(f);
          o.this_func   = f;

          f(o);
          ++i;
        }
      }
    ); // === _.each name

    return instance;
  }; // === func

  Applet.prototype.new_func = Applet.new_func = function (func) {
    var i   = this;
    var msg = {name : 'this position'};
    var stack;

    if (i === Applet) {
      msg.Applet = i;
      if (!Applet.core)
        Applet.core = [];
      stack = Applet.core;
    } else {
      msg.applet = i;
      stack = i.stack;
    }

    if (func(msg) === 'top')
      i.stack.unshift(func);
    else
      i.stack.push(func);

    return this;
  };

  Applet.new_id = function (prefix) {
    if (!Applet.hasOwnProperty('_id'))
      Applet._id = -1;
    Applet._id = Applet._id + 1;
    return (prefix || '') + Applet._id;
  }; // === func

  // === dom ==================================
  Applet.func(function (o) {
    if (o.name === 'before dom') {
      if (!o.dom) {
        o.dom = raw_scripts();
        _.each(o.dom, function (raw) {
          var script   = $(raw);
          var contents = $(script.html());
          script.empty();
          script.append(contents);
          script.addClass('compiled');
        });
      }
    }

    if (o.name === 'after dom') {
      _.each(
        o.dom.filter('script'),
        function (e) {
          var s = $(e);
          (s.contents()).insertBefore(s);
        }
      );
    }

    if (o.name === 'after after dom') {
      if (raw_scripts().length > 0)
        o.applet.run('dom');
    }
  }); // === core: dom

  // === template ====================
  Applet.func(function (o) {
    var this_config = o.this_config;
    var applet      = o.applet;

    if (o.name === 'this position')
      return 'top';

    if (o.name === 'constructor') {
      o.this_config.templates = [];
      return;
    }

    if (o.name !== 'dom')
      return;

    var selector  = '*[template]';
    this_config.templates = this_config.templates.concat(
      _.map(
        Applet.top_descendents(o.dom, selector),
        function (t) {
          var placeholder = $('<script type="text/applet_placeholder"></script>');
          var placeholder_id = Applet.id(placeholder);
          var attr = _.trim(Applet.remove_attr(t, 'template')).split(/\ +/);
          var name = attr.shift();
          var pos  = (attr.length > 0) ? attr.pop() : 'replace';

          var meta = {
            name      : name,
            html      : t.prop('outerHTML'),
            mustache  : Hogan.compile(t.prop('outerHTML')),
            placeholder_id : placeholder_id,
            elements  : null,
            pos       : pos
          };

          applet.push(function (o) {
            if (o.name !== 'data' || !_.isPlainObject(o.data[meta.name]))
              return;

            // === Remove old nodes:
            if (meta.elements && meta.pos === 'replace') {
              meta.elements.remove();
            }

            var html = $(meta.mustache.render(o.data));
            if (meta.pos === 'replace' || meta.pos === 'bottom')
              html.insertBefore($('#' + meta.placeholder_id));
            else
              html.insertAfter($('#' + meta.placeholder_id));

            meta.elements = html;
            applet.run({
              name: 'dom',
              dom:  html
            });
          });

          t.replaceWith(placeholder);
          return meta;
        }
    ) // === each
    );
  }); // ==== core: template ==========

  // === show_if ====================
  Applet.func(function (o) {
    var this_config = o.this_config;

    if (o.name === 'constructor') {
      this_config.show_if_data_cache = {};
      return;
    }

    if (o.name === 'data') {
      _.extend(this_config.show_if_data_cache, o.data);
      return;
    }

    if (o.name !== 'dom')
      return;

    var selector = '*[show_if]';
    _.each(
      $(o.dom).find(selector).addBack(selector),
      function (raw) {
        var node = $(raw);
        var id   = Applet.id(node);
        var val  = Applet.remove_attr(node, 'show_if');

        if (!Applet.is_true(this_config.show_if_data_cache, val))
          node.hide();

        o.applet.push(
          function (o) {
            if (o.name !== 'data')
              return;

            var data = o.data;
            var ans = Applet.is_true(data, val);
            if (ans === undefined)
              return;

            if ( ans )
              $('#' + id).show();
            else
              $('#' + id).hide();
          }
        ); // === push
      } // === function raw
    ); // === _.each
  }); // === core: show_if ========

  Applet.new_func(
    function (o) {
      if (o.name !== 'before form')
        return;
      if (o.name === 'form') {
        if (!o['submit?'])
          return;
        o.send_ajax(o.data);
      }
      _.each(
        $('form:not(form.compiled) button.submit'),
        function (raw) {
          $(raw).on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            o.applet.run({
              name: 'form submit',
              'submit?' : true,
              form: $(this).parent('form').attr('id'),
              data: $(this).parent('form').serializeJSON()
            });
          });
        }
      ); // === each
    }
  ); // === push

})(); // === end scope =================================

<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

// Node server which gets OpenNI data from clients and combines it
// using socket.io as a transport
exports.init = function () {
    var ClientSkeletonManager = require("./lib/server-helpers/ClientSkeletonManager");

    // Logger
    var winston = require("winston");

    if (process.env.loggly_inputToken) {
        winston.add(require("winston-loggly").Loggly, {
            subdomain: process.env.loggly_subdomain,
            inputToken: process.env.loggly_inputToken,
            json: true
        });

        winston.info("switching to SaaS logger");
    }

    // Uses the socket.io server component (debug output suppressed)
    var io = require("socket.io").listen(
        process.env.port || 3000,
        { log: false }
    );

    // One manager per app
    var manager = new ClientSkeletonManager();

    io.sockets.on("connection", function (socket) {
        winston.info("client connected", {
            "clientId": socket.id
        });

        // We need some way to uniquely identify each client
        // (don't know what the skeleton ID is at this time
        // so leave it blank)
        var syncedClient;

        // Client leaving or disconnecting
        var onexit = function () {
            winston.info("Client leaving", {
                clientId: socket.id
            });

            if (syncedClient) {
                syncedClient.terminate();
            }
        };

        // Received calibration data from client
        socket.on("calibrate", function (data) {
            winston.info("Client calibrating", {
                "clientId": socket.id
            });

            if (syncedClient) {
                syncedClient.calibrate(data);
            }
        });

        // Received 'real' data from a client
        socket.on("request", function (data) {
            if (syncedClient) {
                syncedClient.pushRealData(data);
            } else {
                // If not connected to any skeleton
                // just reflect the data
                socket.emit("response", data);
            }
        });

        // Client setting its 'sharing code' to team up with others
        socket.on("subscribe", function (skeletonId) {
            winston.info("Client joining a session", {
                "clientId": socket.id,
                "sessionId": skeletonId
            });

            syncedClient = manager.joinSkeleton(socket.id, skeletonId);

            // Only now there is a syncedClient
            // do we bind the windowFinishCallback
            syncedClient.vent.finishWindow.add(function (reconstructed) {
                socket.emit("response", reconstructed);
            });
        });

        socket.on("unsubscribe", onexit);

        socket.on("disconnect", onexit);
    });
};<commit_msg>tweak logger comment<commit_after>/*jslint node: true */
"use strict";

// Node server which gets OpenNI data from clients and combines it
// using socket.io as a transport
exports.init = function () {
    var ClientSkeletonManager = require("./lib/server-helpers/ClientSkeletonManager");

    // Logger
    var winston = require("winston");

    if (process.env.loggly_inputToken) {
        winston.info("adding SaaS logger");

        winston.add(require("winston-loggly").Loggly, {
            subdomain: process.env.loggly_subdomain,
            inputToken: process.env.loggly_inputToken,
            json: true
        });
    }

    // Uses the socket.io server component (debug output suppressed)
    var io = require("socket.io").listen(
        process.env.port || 3000,
        { log: false }
    );

    // One manager per app
    var manager = new ClientSkeletonManager();

    io.sockets.on("connection", function (socket) {
        winston.info("client connected", {
            "clientId": socket.id
        });

        // We need some way to uniquely identify each client
        // (don't know what the skeleton ID is at this time
        // so leave it blank)
        var syncedClient;

        // Client leaving or disconnecting
        var onexit = function () {
            winston.info("Client leaving", {
                clientId: socket.id
            });

            if (syncedClient) {
                syncedClient.terminate();
            }
        };

        // Received calibration data from client
        socket.on("calibrate", function (data) {
            winston.info("Client calibrating", {
                "clientId": socket.id
            });

            if (syncedClient) {
                syncedClient.calibrate(data);
            }
        });

        // Received 'real' data from a client
        socket.on("request", function (data) {
            if (syncedClient) {
                syncedClient.pushRealData(data);
            } else {
                // If not connected to any skeleton
                // just reflect the data
                socket.emit("response", data);
            }
        });

        // Client setting its 'sharing code' to team up with others
        socket.on("subscribe", function (skeletonId) {
            winston.info("Client joining a session", {
                "clientId": socket.id,
                "sessionId": skeletonId
            });

            syncedClient = manager.joinSkeleton(socket.id, skeletonId);

            // Only now there is a syncedClient
            // do we bind the windowFinishCallback
            syncedClient.vent.finishWindow.add(function (reconstructed) {
                socket.emit("response", reconstructed);
            });
        });

        socket.on("unsubscribe", onexit);

        socket.on("disconnect", onexit);
    });
};<|endoftext|>