<commit_before>/* %Z% %W% %I% %E% %U% */
/*
 * <copyright
 * notice="lm-source-program"
 * pids="5755-P60"
 * years="2013,2014"
 * crc="3568777996" >
 * Licensed Materials - Property of IBM
 *
 * 5755-P60
 *
 * (C) Copyright IBM Corp. 2013, 2014
 *
 * US Government Users Restricted Rights - Use, duplication or
 * disclosure restricted by GSA ADP Schedule Contract with
 * IBM Corp.
 * </copyright>
 */

var os = require('os');
var _system = os.platform() + '-' + process.arch;
try {
  var proton = require('./lib/' + _system + '/proton');
} catch(_) {
  if ('MODULE_NOT_FOUND' === _.code) {
    throw new Error('mqlight.js is not currently supported on ' + _system);
  }
  throw _;
}
var EventEmitter = require('events').EventEmitter;
var util = require('util');

try {
  var uuid = require('node-uuid');
} catch(_) {
  var uuid = require(require.resolve('npm') + '/../../node_modules/request/node_modules/node-uuid');
}

var validClientIdChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%/._';
/** @constant {number} */
exports.QOS_AT_MOST_ONCE = 0;
/** @constant {number} */
exports.QOS_AT_LEAST_ONCE = 1;
/** @constant {number} */
exports.QOS_EXACTLY_ONCE = 2;

/**
 * Creates an MQ Light client instance.
 *
 * Options:
 *  - **host**, (String, default: localhost), the remote hostname to which we will connect.
 *  - **port**, (Number, default: 5672), the remote tcp port to connect to.
 *  - **clientId (String, default: AUTO_[0-9a-f]{7}), a unique identifier for this client.
 *
 * @param {Object} [options] (optional) map of options for the client.
 */
exports.createClient = function(options) {
  var opt = (typeof options == 'object') ? options : {};
  var client = new Client(opt.host, opt.port, opt.clientId, opt.userName, opt.password);
  // FIXME: make this actually check driver/engine connection state
  process.nextTick(function() {
    client.emit('connected', true);
  });
  process.setMaxListeners(0);
  process.once('exit', function() {
    if (client) {
      client.send();
      client.close();
    }
  });
  return client;
};

/**
 * Represents an MQ Light client instance.
 *
 * @param {string} host - (optional) the remote host to which we will connect.
 * @param {number} [port] - (optional) the remote tcp port to connect to.
 * @param {string} [clientId] - (optional) unique identifier for this client.
 * @constructor
 */
var Client = function(host, port, clientId, userName, password) {
  EventEmitter.call(this);
  if (!host) host = "localhost";
  if (!port) port = 5672;
  if (!clientId) clientId = "AUTO_" + uuid.v4().substring(0, 7);
  if (!password) password = "";
  if (clientId.length > 48) {
    var msg = "Client identifier '" + clientId + "' is longer than the " +
        "maximum ID length of 48.";
    throw new Error(msg);
  }
  /* currently client ids are restricted to a fixed char set, reject those not in it*/
  var i;
  for (i in clientId) {
    if (validClientIdChars.indexOf(clientId[i]) == -1) {
      var err = "Client Identifier '" + clientId + "' contains invalid char: " +
        clientId[i];
      throw new Error(err);
    }
  }

  this.brokerUrl = "amqp://" + host + ':' + port;
  this.clientId = clientId;
  if (userName){
    this.messenger = new proton.ProtonMessenger(clientId, userName, password);
  } else {
    this.messenger = new proton.ProtonMessenger(clientId);
  }
  this.messenger.start();
};
util.inherits(Client, EventEmitter);

/**
 * @callback sendCallback
 * @param {string} err - an error message if a problem occurred.
 * @param {ProtonMessage} message - the message that was sent.
 */

/**
 * Sends the given MQ Light message object to its address.
 *
 * @param {string} topic - the topic to which the message will be sent.
 * @param {Object} message - the message body to be sent.
 * @param {Object} [options] (optional) map of additional options for the send.
 * @param {sendCallback} cb - (optional) callback to be notified of
 *                                       errors and completion.
 */
Client.prototype.send = function(topic, message, options, cb) {
  var messenger = this.messenger;
  var callback = (typeof options === 'function') ? options : cb;
  try {
    if (message) {
      var protonMsg = new proton.ProtonMessage();
      protonMsg.address = this.brokerUrl;
      if (topic) protonMsg.address += '/' + topic;
      if (typeof message === 'string') {
        protonMsg.body = message;
        protonMsg.contentType = 'text/plain';
      } else if (message instanceof Buffer) {
        protonMsg.body = message;
        protonMsg.contentType = 'application/octet-stream';
      } else {
        protonMsg.body = JSON.stringify(message);
        protonMsg.contentType = 'application/json';
      }
      messenger.put(protonMsg);

      // setup a timer to trigger the callback once the msg has been sent
      var untilSendComplete = function(protonMsg, callback) {
        messenger.send();
        if (messenger.hasSent(protonMsg)) {
          messenger.send();
          process.nextTick(function() {
            callback(undefined, protonMsg);
          });
          return;
        }
        // if msg not yet sent and still running, check again in a second or so
        if (!messenger.stopped) {
          setImmediate(untilSendComplete, protonMsg, callback);
        }
      };
      // if a callback is set, start the timer to trigger it
      if (callback) {
        setImmediate(untilSendComplete, protonMsg, callback);
      }
    }
  } catch (e) {
    var client = this;
    var err = new Error(e.message);
    process.nextTick(function() {
      if (callback) {
        callback(err, protonMsg);
      }
      if (err) client.emit('error', err);
    });
  }
};

/**
 * Disconnects this Client from the messaging server and frees the system
 * resources that it uses. Calling this method also implicitly closes any
 * Destination objects that have been created using the client's
 * {@linkClient#createDestination} method.
 */
Client.prototype.close = function() {
  this.messenger.stop();
};

/**
 * @callback destCallback
 * @param {string} err - an error message if a problem occurred.
 * @param {string} address - the address that was subscribed to.
 */

/**
 * Create a {@link Destination} and associates it with a pattern.
 *
 * The pattern is matched against the address
 * attribute of messages sent to the IBM MQ Light messaging service to
 * determine whether a particular message will be delivered to a particular
 * Destination.
 *
 * @param pattern used to match against the address attribute of
 * messages to determine if a copy of the message should be delivered to the
 * Destination.
 * @param {Object} [options] (optional) map of additional options for the
 *        destination.
 * @param {destCallback} cb - (optional) callback to be notified of errors
 * @return a {@link Destination} which will emit 'message' events on arrival.
 */
Client.prototype.createDestination = function(pattern, options, cb) {
    var messenger = this.messenger;
    var address = this.brokerUrl + '/' + pattern;
    var emitter = new EventEmitter();
    var callback = (typeof options === 'function') ? options : cb;

    try {
      messenger.subscribe(address);
    } catch (e) {
      var err = new Error(e.message);
    }

    setImmediate(function() {
      if (callback) {
        callback(err, address);
      }
      if (err) emitter.emit('error', err);
    });

    if (!err) {
      var check_for_messages = function() {
        var messages = messenger.receive(50);
        if (messages.length > 0) {
          for (var i=0, tot=messages.length; i < tot; i++) {
            var protonMsg = messages[i];
            var message = { address: protonMsg.address,
                            contentType: protonMsg.contentType,
                            body: protonMsg.body
                          };

            // if body is a JSON'ified object, try to parse it back to a js obj
            if (message.contentType === 'application/json') {
              try {
                var obj = JSON.parse(message.body);
                message.body = obj;
              } catch(_) {console.log(_);}
            }
            emitter.emit('message', message);
          }
        }
        if (!messenger.stopped) {
          setImmediate(check_for_messages);
        }
      };
      process.nextTick(function() {
        if (!messenger.stopped) {
          check_for_messages();
        }
      });
    }

    return emitter;
};

/* ------------------------------------------------------------------------- */
<commit_msg>Check if send() has been called on undefined or a function and throw an exception<commit_after>/* %Z% %W% %I% %E% %U% */
/*
 * <copyright
 * notice="lm-source-program"
 * pids="5755-P60"
 * years="2013,2014"
 * crc="3568777996" >
 * Licensed Materials - Property of IBM
 *
 * 5755-P60
 *
 * (C) Copyright IBM Corp. 2013, 2014
 *
 * US Government Users Restricted Rights - Use, duplication or
 * disclosure restricted by GSA ADP Schedule Contract with
 * IBM Corp.
 * </copyright>
 */

var os = require('os');
var _system = os.platform() + '-' + process.arch;
try {
  var proton = require('./lib/' + _system + '/proton');
} catch(_) {
  if ('MODULE_NOT_FOUND' === _.code) {
    throw new Error('mqlight.js is not currently supported on ' + _system);
  }
  throw _;
}
var EventEmitter = require('events').EventEmitter;
var util = require('util');

try {
  var uuid = require('node-uuid');
} catch(_) {
  var uuid = require(require.resolve('npm') + '/../../node_modules/request/node_modules/node-uuid');
}

var validClientIdChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%/._';
/** @constant {number} */
exports.QOS_AT_MOST_ONCE = 0;
/** @constant {number} */
exports.QOS_AT_LEAST_ONCE = 1;
/** @constant {number} */
exports.QOS_EXACTLY_ONCE = 2;

/**
 * Creates an MQ Light client instance.
 *
 * Options:
 *  - **host**, (String, default: localhost), the remote hostname to which we will connect.
 *  - **port**, (Number, default: 5672), the remote tcp port to connect to.
 *  - **clientId (String, default: AUTO_[0-9a-f]{7}), a unique identifier for this client.
 *
 * @param {Object} [options] (optional) map of options for the client.
 */
exports.createClient = function(options) {
  var opt = (typeof options == 'object') ? options : {};
  var client = new Client(opt.host, opt.port, opt.clientId, opt.userName, opt.password);
  // FIXME: make this actually check driver/engine connection state
  process.nextTick(function() {
    client.emit('connected', true);
  });
  process.setMaxListeners(0);
  process.once('exit', function() {
    if (client) {
      client.send();
      client.close();
    }
  });
  return client;
};

/**
 * Represents an MQ Light client instance.
 *
 * @param {string} host - (optional) the remote host to which we will connect.
 * @param {number} [port] - (optional) the remote tcp port to connect to.
 * @param {string} [clientId] - (optional) unique identifier for this client.
 * @constructor
 */
var Client = function(host, port, clientId, userName, password) {
  EventEmitter.call(this);
  if (!host) host = "localhost";
  if (!port) port = 5672;
  if (!clientId) clientId = "AUTO_" + uuid.v4().substring(0, 7);
  if (!password) password = "";
  if (clientId.length > 48) {
    var msg = "Client identifier '" + clientId + "' is longer than the " +
        "maximum ID length of 48.";
    throw new Error(msg);
  }
  /* currently client ids are restricted to a fixed char set, reject those not in it*/
  var i;
  for (i in clientId) {
    if (validClientIdChars.indexOf(clientId[i]) == -1) {
      var err = "Client Identifier '" + clientId + "' contains invalid char: " +
        clientId[i];
      throw new Error(err);
    }
  }

  this.brokerUrl = "amqp://" + host + ':' + port;
  this.clientId = clientId;
  if (userName){
    this.messenger = new proton.ProtonMessenger(clientId, userName, password);
  } else {
    this.messenger = new proton.ProtonMessenger(clientId);
  }
  this.messenger.start();
};
util.inherits(Client, EventEmitter);

/**
 * @callback sendCallback
 * @param {string} err - an error message if a problem occurred.
 * @param {ProtonMessage} message - the message that was sent.
 */

/**
 * Sends the given MQ Light message object to its address.
 *
 * @param {string} topic - the topic to which the message will be sent.
 * @param {Object} message - the message body to be sent.
 * @param {Object} [options] (optional) map of additional options for the send.
 * @param {sendCallback} cb - (optional) callback to be notified of
 *                                       errors and completion.
 */
Client.prototype.send = function(topic, message, options, cb) {
  var messenger = this.messenger;
  var callback = (typeof options === 'function') ? options : cb;
  try {
    if (!message) {
      throw new Error('Cannot send undefined');
    } else if (message instanceof Function) {
      throw new Error('Cannot send a function');
    } else {
      var protonMsg = new proton.ProtonMessage();
      protonMsg.address = this.brokerUrl;
      if (topic) protonMsg.address += '/' + topic;
      if (typeof message === 'string') {
        protonMsg.body = message;
        protonMsg.contentType = 'text/plain';
      } else if (message instanceof Buffer) {
        protonMsg.body = message;
        protonMsg.contentType = 'application/octet-stream';
      } else {
        protonMsg.body = JSON.stringify(message);
        protonMsg.contentType = 'application/json';
      }
      messenger.put(protonMsg);

      // setup a timer to trigger the callback once the msg has been sent
      var untilSendComplete = function(protonMsg, callback) {
        messenger.send();
        if (messenger.hasSent(protonMsg)) {
          messenger.send();
          process.nextTick(function() {
            callback(undefined, protonMsg);
          });
          return;
        }
        // if msg not yet sent and still running, check again in a second or so
        if (!messenger.stopped) {
          setImmediate(untilSendComplete, protonMsg, callback);
        }
      };
      // if a callback is set, start the timer to trigger it
      if (callback) {
        setImmediate(untilSendComplete, protonMsg, callback);
      }
    }
  } catch (e) {
    var client = this;
    var err = new Error(e.message);
    process.nextTick(function() {
      if (callback) {
        callback(err, protonMsg);
      }
      if (err) client.emit('error', err);
    });
  }
};

/**
 * Disconnects this Client from the messaging server and frees the system
 * resources that it uses. Calling this method also implicitly closes any
 * Destination objects that have been created using the client's
 * {@linkClient#createDestination} method.
 */
Client.prototype.close = function() {
  this.messenger.stop();
};

/**
 * @callback destCallback
 * @param {string} err - an error message if a problem occurred.
 * @param {string} address - the address that was subscribed to.
 */

/**
 * Create a {@link Destination} and associates it with a pattern.
 *
 * The pattern is matched against the address
 * attribute of messages sent to the IBM MQ Light messaging service to
 * determine whether a particular message will be delivered to a particular
 * Destination.
 *
 * @param pattern used to match against the address attribute of
 * messages to determine if a copy of the message should be delivered to the
 * Destination.
 * @param {Object} [options] (optional) map of additional options for the
 *        destination.
 * @param {destCallback} cb - (optional) callback to be notified of errors
 * @return a {@link Destination} which will emit 'message' events on arrival.
 */
Client.prototype.createDestination = function(pattern, options, cb) {
    var messenger = this.messenger;
    var address = this.brokerUrl + '/' + pattern;
    var emitter = new EventEmitter();
    var callback = (typeof options === 'function') ? options : cb;

    try {
      messenger.subscribe(address);
    } catch (e) {
      var err = new Error(e.message);
    }

    setImmediate(function() {
      if (callback) {
        callback(err, address);
      }
      if (err) emitter.emit('error', err);
    });

    if (!err) {
      var check_for_messages = function() {
        var messages = messenger.receive(50);
        if (messages.length > 0) {
          for (var i=0, tot=messages.length; i < tot; i++) {
            var protonMsg = messages[i];
            var message = { address: protonMsg.address,
                            contentType: protonMsg.contentType,
                            body: protonMsg.body
                          };

            // if body is a JSON'ified object, try to parse it back to a js obj
            if (message.contentType === 'application/json') {
              try {
                var obj = JSON.parse(message.body);
                message.body = obj;
              } catch(_) {console.log(_);}
            }
            emitter.emit('message', message);
          }
        }
        if (!messenger.stopped) {
          setImmediate(check_for_messages);
        }
      };
      process.nextTick(function() {
        if (!messenger.stopped) {
          check_for_messages();
        }
      });
    }

    return emitter;
};

/* ------------------------------------------------------------------------- */
<|endoftext|>


<commit_before><commit_msg>Update testsA.js<commit_after><|endoftext|>


<commit_before>/* ===========================================================================

	trace.js

	Copyright 2012 John Dunning.
	fw@johndunning.com
	http://johndunning.com/fireworks

	trace.js is released under the MIT license.  See the LICENSE file
	for details.

   ======================================================================== */

/*
	First, install the Fireworks Console extension from here:
	http://johndunning.com/fireworks/about/FWConsole

	Then restart Fireworks and open the console panel.  Add `return trace(this);`
	to the functions whose execution you want to trace:

		function myBuggyFunc(count)
		{
			return trace(this);

			var dom = fw.getDocumentDOM();
			dom.selectAll();
			dom.deleteSelection();

			for (var i = 0; i < count; i++) {
				dom.clipPaste();
				dom.moveSelectionTo({ x: i * 10, y: i * 10 });
			}
		}

		myBuggyFunc();

	See the readme for more information about the parameters that can be
	passed to trace().
*/

// ===========================================================================
try { (function() {
	if (typeof log != "function") {
		alert("Before trace() can be called, the Fireworks Console extension must be installed and the panel must be open.  The extension can be downloaded from here:\n\n" +
			"http://johndunning.com/fireworks/about/FWConsole");
		return;
	}

	// =======================================================================
	function forEach(obj, iterator, context) {
		if (obj == null) { return; }
		if (obj.length === +obj.length) {
			for (var i = 0, l = obj.length; i < l; i++) {
					// i in obj seems to be false when it's an array extracted
					// from customData
				if (iterator.call(context, obj[i], i, obj) === false) { return; }
			}
		} else {
			for (var key in obj) {
				if (iterator.call(context, obj[key], key, obj) === false) { return; }
			}
		}
	}

	// =======================================================================
	function map(obj, iterator, context) {
		var	results	= [];
		if (obj	== null) { return results; }

		forEach(obj, function(value, index, list) {
			results[results.length] = iterator.call(context, value, index, list);
		});

		return results;
	}

	// =======================================================================
	function logWatched(
		inExpression,
		inFunctionName)
	{
		inFunctionName = inFunctionName.slice(0, -1);

		var test = inExpression,
			prefix = " ";

		if (/[<>=]+/.test(test)) {
			return '((' + test + ') ? "" : log("' + inFunctionName + prefix +
				'ASSERTION FAILED:", ' + test.quote() + '));';
		} else {
			return 'log("' + inFunctionName + prefix + test + ':", ' + test + ');';
		}
	}

	// =======================================================================
	function getScopeFacade(
		inCaller)
	{
		function Facade()
		{
			// this is an empty class that we use just to check whether a scope
			// we encounter is actually a Facade
		}

		function createGetter(
			inName,
			inScope)
		{
				// get the value from the scope that contains this variable
			return function() { return inScope[inName]; }
		}

		function createSetter(
			inName,
			inScope)
		{
				// set the value on the scope that contains this variable
			return function(inValue) { inScope[inName] = inValue; }
		}

		function addScope(
			inScope,
			inFacade)
		{
				// add a getter and setter for every variable in this scope.
				// these functions will get/set the values from/in the scope
				// the var is originally from, rather than the inFacade object.
			for (var name in inScope) {
				inFacade.__defineGetter__(name, createGetter(name, inScope));
				inFacade.__defineSetter__(name, createSetter(name, inScope));

					// this crazy syntax is valid in the FW JS engine, though it
					// was removed from later versions of the Mozilla engine.
					// it seems to be the only way to make the g/setters
					// enumerable, which is sometimes useful for debugging.  but
					// since this looks like a syntax error to NetBeans, leave
					// it commented out when not needed.
//				inFacade[name] getter = createGetter(name, inScope);
//				inFacade[name] setter = createSetter(name, inScope);
			}
		}

		function walkScopeChain(
			inScope,
			inFacade)
		{
			if (inScope instanceof Facade) {
					// we've hit a scope that was created by an earlier call to
					// trace().  if we tried to add that scope to our facade,
					// we'd get in an endless loop, so flee!
				return inFacade;
			} else if (inScope.__parent__ && inScope.__parent__.__parent__) {
					// add the variables from the scope's parent scope first,
					// in case the scope shadows some vars that are also defined
					// in the parent scope, but only if the parent isn't the
					// global scope.  that should always be accessible and so
					// doesn't need to be on the facade.
				inFacade = arguments.callee(inScope.__parent__, inFacade);
			}

				// add this scope to the facade
			addScope(inScope, inFacade);

			return inFacade;
		}

			// we use an empty Facade object to store the scope values so that
			// we can tell we created it, using instanceof.  that way, if the
			// function we're tracing calls another function that is also
			// traced, we won't get into an infinite loop.
		var facade = new Facade();

			// first add all the parent scopes from the caller's scope chain
		walkScopeChain(inCaller.__parent__, facade);

			// then add the local variables from the caller, so that they can
			// shadow ones in the parent scopes, if needed
		addScope(inCaller.__call__, facade);

		return facade;
	}

	// =======================================================================
	trace = function(
		__CALLER_THIS__,
		inWatched,
		inFunctionName)
	{
			// this function is local to trace just so it can access the name
			// of the function being traced
		function logStatement(
			inWholeLine,
			inWhitespace,
			inStatement)
		{
				// convert tabs to 2 spaces and get rid of newlines
			inWhitespace = (inWhitespace || "").replace(/\n/g, "").replace(/\t/g, "  ");

				// display the function name and statement in the console
			var logCall = 'log(' + (functionName + inWhitespace + inStatement).quote() + ');',
				code;

			if (/^(return|continue|break)[\s;]/.test(inStatement)) {
					// since putting a log call after return, continue or break
					// is pointless, put it before the statement.  we don't need
					// to match the whole statement, just verify that it's a
					// token followed by a space or ;.  toString always puts a
					// space after a return, even if the source looks like
					// return(foo);
				code = [logCall, watchedVars, inWholeLine];
			} else if (/^(for|while|if)\s*\(/.test(inStatement) || /^(\}\s+else|do)\s+\{/.test(inStatement)) {
					// we want to put the log call and watched vars after the
					// looping statement so that we see them each time through
					// the loop
				code = [inWholeLine, logCall, watchedVars];
			} else {
					// put the log call before the statement, so that we can see a
					// function call before the code steps into the function.  doing
					// this would normally break a block of var definitions separated
					// by commas and a new line, since the regexp would match the
					// last line in the block and stick the log call before it, which
					// breaks the syntax.  but toString on a function puts all var
					// definitions on a single line, as well as a mutli-line object
					// definitions, like var foo = { bar: 42 }.  we want to add the
					// watchedVars after the statement, so that it shows the value
					// of the watched vars after the statement is executed.
				code = [logCall, inWholeLine, watchedVars];
			}

			return code.join("\n");
		}

			// adjust the optional parameters
		if (typeof inWatched == "string") {
			inFunctionName = inWatched;
			inWatched = [];
		}

				// we can't call this "caller", because that creates a property
				// called "caller" on our function object, which then overwrites
				// the arguments.callee.caller property.  ffs.
		var callerFunc = arguments.callee.caller,
			__CALLER_ARGS__ = callerFunc.arguments,
			callerSource = arguments.callee.caller.toString(),
				// ignore the calling function's name if one was passed in
			functionName = inFunctionName || callerFunc.name,
				// pull out the body and params of the function
			codeMatch = callerSource.match(/function\s+([^(]+)?\(([^)]*)\)\s*\{([\s\S]*)\}/),
			params = codeMatch[2] ? codeMatch[2].split(/\s*,\s*/) : [],
			body = codeMatch[3],
			paramLog,
			watchedVars = "",
			traceMatch;

			// add a colon after the function name, if there is one
		functionName = functionName ? functionName + ": " : "";

		if (inWatched) {
			watchedVars = map(inWatched, function(watched) {
					// argh, there's some global native function called "watch"?
					// and we can't shadow it with a local var?  wtf?  ah, it's
					// actually an incredibly useful watch() function to get
					// callbacks when a property changes.  booyah.
				return logWatched(watched, functionName);
			});
			watchedVars = watchedVars.join("\n");
		}

			// create a log statement to display the function's parameters.
			// include the function name as the first string in the log call.
		paramLog = [(functionName + "(").quote()].concat(map(params, function(param) {
			return [(param + ":").quote(), param];
		}));

		paramLog.push(")".quote());
		paramLog = 'log(' + paramLog.join(", ") + ');\n';

		traceMatch = body.match(/return\s+trace\s*\([^)]*\)\s*;/);

		if (!traceMatch) {
				// the caller must have set a var to trace and then called us
				// through that var.  but we can't trace if we can't find the
				// trace call and strip it out.
			alert('A "return trace();" statement could not be found in the calling function. The trace function must be called directly, not through a reference.');
			return;
		}

			// start tracing from the statement after the trace() call, and
			// remove any other calls to trace that happen to be in the function.
			// also, the array returned by match() doesn't have a lastIndex
			// property on it.  ffs.
		body = body.slice(traceMatch.index + traceMatch[0].length);
		body = body.replace(/return\s+trace\s*\([^)]*\)\s*;/g, "");

			// this monster regex will:
			//
			// - add a log call after the opening brace of an if/else/for/while block.
			// but do so only if there's a space in front of the if, to avoid
			// sticking log calls in the middle of another log call, which can
			// happen with a nested function definition.  FW returns the body of
			// the nested function all on one line when doing toString, so the
			// replace call above will log the whole line.  but then this `if`
			// replace will see if statements inside the log string and replace
			// them, breaking the code.  requiring a space before the keyword
			// won't match in the nested function case, since FW removes all
			// the whitespace from the function body.
			//
			// - add a log call before each ;\n to display the statement
			//
			// - add a log call after each do statement
		body = body.replace(/^(\s*)((?:(?:if|for|while)\s+\([^{]+\)\s*\{)|(?:[^\n]+;)|(?:do\s+\{)|(?:\}\s+else\s+\{))\s*$/mg,
			logStatement);

			// override the arguments var with the caller's arguments so that
			// things like arguments.callee correctly point to the caller.  we
			// do this at the very beginning of the function, but after all the
			// statements have been logged, so that this doesn't get logged, too.
		body = 'arguments = __CALLER_ARGS__;\n' + body;

			// wrap the body in an anonymous function so our caller can execute
			// it in the caller's scope, and apply it to the caller's this value
			// and arguments.  we have to pass the caller's this and arguments
			// into the function so that if code in the caller does something
			// like `arguments.length`, it'll have the appropriate value.  then
			// capture that function's return value, log it, and return it from
			// another anonymous function.  we use slightly obscure var names for
			// this and args so that hopefully, the caller doesn't have anything
			// with the same names in its scope.
		body = '(function(){ var returnValue = (function(){' +
			paramLog + body + '}).apply(__CALLER_THIS__, __CALLER_ARGS__); log("' +
			functionName + 'returns:", returnValue); return returnValue; })();';

			// create a facade object that maps all of the identifiers in the
			// our caller's scope chain to the owning scope, and then eval the
			// caller's code within that fake scope.  this is where all the
			// magic happens.
		with (getScopeFacade(callerFunc)) {
			try {
				return eval(body);
			} catch (exception) {
				if (exception.lineNumber) {
					alert([exception, exception.lineNumber, exception.fileName].join("\n"));
				} else {
						// this is an internal error with a useless error number,
						// so throw it to let FW handle it and show a better message
					throw exception;
				}
			}
		}
	}
})(); } catch (exception) {
	if (exception.lineNumber) {
		alert([exception, exception.lineNumber, exception.fileName].join("\n"));
	} else {
		throw exception;
	}
}
<commit_msg>Cleaned up whitespace.<commit_after>/* ===========================================================================

	trace.js

	Copyright 2012 John Dunning.
	fw@johndunning.com
	http://johndunning.com/fireworks

	trace.js is released under the MIT license.  See the LICENSE file
	for details.

   ======================================================================== */

/*
	First, install the Fireworks Console extension from here:
	http://johndunning.com/fireworks/about/FWConsole

	Then restart Fireworks and open the console panel.  Add `return trace(this);`
	to the functions whose execution you want to trace:

		function myBuggyFunc(count)
		{
			return trace(this);

			var dom = fw.getDocumentDOM();
			dom.selectAll();
			dom.deleteSelection();

			for (var i = 0; i < count; i++) {
				dom.clipPaste();
				dom.moveSelectionTo({ x: i * 10, y: i * 10 });
			}
		}

		myBuggyFunc();

	See the readme for more information about the parameters that can be
	passed to trace().
*/

// ===========================================================================
try { (function() {
	if (typeof log != "function") {
		alert("Before trace() can be called, the Fireworks Console extension must be installed and the panel must be open.  The extension can be downloaded from here:\n\n" +
			"http://johndunning.com/fireworks/about/FWConsole");
		return;
	}

	// =======================================================================
	function forEach(obj, iterator, context) {
		if (obj == null) { return; }
		if (obj.length === +obj.length) {
			for (var i = 0, l = obj.length; i < l; i++) {
					// i in obj seems to be false when it's an array extracted
					// from customData
				if (iterator.call(context, obj[i], i, obj) === false) { return; }
			}
		} else {
			for (var key in obj) {
				if (iterator.call(context, obj[key], key, obj) === false) { return; }
			}
		}
	}

	// =======================================================================
	function map(obj, iterator, context) {
		var results = [];
		if (obj == null) { return results; }

		forEach(obj, function(value, index, list) {
			results[results.length] = iterator.call(context, value, index, list);
		});

		return results;
	}

	// =======================================================================
	function logWatched(
		inExpression,
		inFunctionName)
	{
		inFunctionName = inFunctionName.slice(0, -1);

		var test = inExpression,
			prefix = " ";

		if (/[<>=]+/.test(test)) {
			return '((' + test + ') ? "" : log("' + inFunctionName + prefix +
				'ASSERTION FAILED:", ' + test.quote() + '));';
		} else {
			return 'log("' + inFunctionName + prefix + test + ':", ' + test + ');';
		}
	}

	// =======================================================================
	function getScopeFacade(
		inCaller)
	{
		function Facade()
		{
			// this is an empty class that we use just to check whether a scope
			// we encounter is actually a Facade
		}

		function createGetter(
			inName,
			inScope)
		{
				// get the value from the scope that contains this variable
			return function() { return inScope[inName]; }
		}

		function createSetter(
			inName,
			inScope)
		{
				// set the value on the scope that contains this variable
			return function(inValue) { inScope[inName] = inValue; }
		}

		function addScope(
			inScope,
			inFacade)
		{
				// add a getter and setter for every variable in this scope.
				// these functions will get/set the values from/in the scope
				// the var is originally from, rather than the inFacade object.
			for (var name in inScope) {
				inFacade.__defineGetter__(name, createGetter(name, inScope));
				inFacade.__defineSetter__(name, createSetter(name, inScope));

					// this crazy syntax is valid in the FW JS engine, though it
					// was removed from later versions of the Mozilla engine.
					// it seems to be the only way to make the g/setters
					// enumerable, which is sometimes useful for debugging.  but
					// since this looks like a syntax error to NetBeans, leave
					// it commented out when not needed.
//				inFacade[name] getter = createGetter(name, inScope);
//				inFacade[name] setter = createSetter(name, inScope);
			}
		}

		function walkScopeChain(
			inScope,
			inFacade)
		{
			if (inScope instanceof Facade) {
					// we've hit a scope that was created by an earlier call to
					// trace().  if we tried to add that scope to our facade,
					// we'd get in an endless loop, so flee!
				return inFacade;
			} else if (inScope.__parent__ && inScope.__parent__.__parent__) {
					// add the variables from the scope's parent scope first,
					// in case the scope shadows some vars that are also defined
					// in the parent scope, but only if the parent isn't the
					// global scope.  that should always be accessible and so
					// doesn't need to be on the facade.
				inFacade = arguments.callee(inScope.__parent__, inFacade);
			}

				// add this scope to the facade
			addScope(inScope, inFacade);

			return inFacade;
		}

			// we use an empty Facade object to store the scope values so that
			// we can tell we created it, using instanceof.  that way, if the
			// function we're tracing calls another function that is also
			// traced, we won't get into an infinite loop.
		var facade = new Facade();

			// first add all the parent scopes from the caller's scope chain
		walkScopeChain(inCaller.__parent__, facade);

			// then add the local variables from the caller, so that they can
			// shadow ones in the parent scopes, if needed
		addScope(inCaller.__call__, facade);

		return facade;
	}

	// =======================================================================
	trace = function(
		__CALLER_THIS__,
		inWatched,
		inFunctionName)
	{
			// this function is local to trace just so it can access the name
			// of the function being traced
		function logStatement(
			inWholeLine,
			inWhitespace,
			inStatement)
		{
				// convert tabs to 2 spaces and get rid of newlines
			inWhitespace = (inWhitespace || "").replace(/\n/g, "").replace(/\t/g, "  ");

				// display the function name and statement in the console
			var logCall = 'log(' + (functionName + inWhitespace + inStatement).quote() + ');',
				code;

			if (/^(return|continue|break)[\s;]/.test(inStatement)) {
					// since putting a log call after return, continue or break
					// is pointless, put it before the statement.  we don't need
					// to match the whole statement, just verify that it's a
					// token followed by a space or ;.  toString always puts a
					// space after a return, even if the source looks like
					// return(foo);
				code = [logCall, watchedVars, inWholeLine];
			} else if (/^(for|while|if)\s*\(/.test(inStatement) || /^(\}\s+else|do)\s+\{/.test(inStatement)) {
					// we want to put the log call and watched vars after the
					// looping statement so that we see them each time through
					// the loop
				code = [inWholeLine, logCall, watchedVars];
			} else {
					// put the log call before the statement, so that we can see a
					// function call before the code steps into the function.  doing
					// this would normally break a block of var definitions separated
					// by commas and a new line, since the regexp would match the
					// last line in the block and stick the log call before it, which
					// breaks the syntax.  but toString on a function puts all var
					// definitions on a single line, as well as a mutli-line object
					// definitions, like var foo = { bar: 42 }.  we want to add the
					// watchedVars after the statement, so that it shows the value
					// of the watched vars after the statement is executed.
				code = [logCall, inWholeLine, watchedVars];
			}

			return code.join("\n");
		}

			// adjust the optional parameters
		if (typeof inWatched == "string") {
			inFunctionName = inWatched;
			inWatched = [];
		}

				// we can't call this "caller", because that creates a property
				// called "caller" on our function object, which then overwrites
				// the arguments.callee.caller property.  ffs.
		var callerFunc = arguments.callee.caller,
			__CALLER_ARGS__ = callerFunc.arguments,
			callerSource = arguments.callee.caller.toString(),
				// ignore the calling function's name if one was passed in
			functionName = inFunctionName || callerFunc.name,
				// pull out the body and params of the function
			codeMatch = callerSource.match(/function\s+([^(]+)?\(([^)]*)\)\s*\{([\s\S]*)\}/),
			params = codeMatch[2] ? codeMatch[2].split(/\s*,\s*/) : [],
			body = codeMatch[3],
			paramLog,
			watchedVars = "",
			traceMatch;

			// add a colon after the function name, if there is one
		functionName = functionName ? functionName + ": " : "";

		if (inWatched) {
			watchedVars = map(inWatched, function(watched) {
					// argh, there's some global native function called "watch"?
					// and we can't shadow it with a local var?  wtf?  ah, it's
					// actually an incredibly useful watch() function to get
					// callbacks when a property changes.  booyah.
				return logWatched(watched, functionName);
			});
			watchedVars = watchedVars.join("\n");
		}

			// create a log statement to display the function's parameters.
			// include the function name as the first string in the log call.
		paramLog = [(functionName + "(").quote()].concat(map(params, function(param) {
			return [(param + ":").quote(), param];
		}));

		paramLog.push(")".quote());
		paramLog = 'log(' + paramLog.join(", ") + ');\n';

		traceMatch = body.match(/return\s+trace\s*\([^)]*\)\s*;/);

		if (!traceMatch) {
				// the caller must have set a var to trace and then called us
				// through that var.  but we can't trace if we can't find the
				// trace call and strip it out.
			alert('A "return trace();" statement could not be found in the calling function. The trace function must be called directly, not through a reference.');
			return;
		}

			// start tracing from the statement after the trace() call, and
			// remove any other calls to trace that happen to be in the function.
			// also, the array returned by match() doesn't have a lastIndex
			// property on it.  ffs.
		body = body.slice(traceMatch.index + traceMatch[0].length);
		body = body.replace(/return\s+trace\s*\([^)]*\)\s*;/g, "");

			// this monster regex will:
			//
			// - add a log call after the opening brace of an if/else/for/while block.
			// but do so only if there's a space in front of the if, to avoid
			// sticking log calls in the middle of another log call, which can
			// happen with a nested function definition.  FW returns the body of
			// the nested function all on one line when doing toString, so the
			// replace call above will log the whole line.  but then this `if`
			// replace will see if statements inside the log string and replace
			// them, breaking the code.  requiring a space before the keyword
			// won't match in the nested function case, since FW removes all
			// the whitespace from the function body.
			//
			// - add a log call before each ;\n to display the statement
			//
			// - add a log call after each do statement
		body = body.replace(/^(\s*)((?:(?:if|for|while)\s+\([^{]+\)\s*\{)|(?:[^\n]+;)|(?:do\s+\{)|(?:\}\s+else\s+\{))\s*$/mg,
			logStatement);

			// override the arguments var with the caller's arguments so that
			// things like arguments.callee correctly point to the caller.  we
			// do this at the very beginning of the function, but after all the
			// statements have been logged, so that this doesn't get logged, too.
		body = 'arguments = __CALLER_ARGS__;\n' + body;

			// wrap the body in an anonymous function so our caller can execute
			// it in the caller's scope, and apply it to the caller's this value
			// and arguments.  we have to pass the caller's this and arguments
			// into the function so that if code in the caller does something
			// like `arguments.length`, it'll have the appropriate value.  then
			// capture that function's return value, log it, and return it from
			// another anonymous function.  we use slightly obscure var names for
			// this and args so that hopefully, the caller doesn't have anything
			// with the same names in its scope.
		body = '(function(){ var returnValue = (function(){' +
			paramLog + body + '}).apply(__CALLER_THIS__, __CALLER_ARGS__); log("' +
			functionName + 'returns:", returnValue); return returnValue; })();';

			// create a facade object that maps all of the identifiers in the
			// our caller's scope chain to the owning scope, and then eval the
			// caller's code within that fake scope.  this is where all the
			// magic happens.
		with (getScopeFacade(callerFunc)) {
			try {
				return eval(body);
			} catch (exception) {
				if (exception.lineNumber) {
					alert([exception, exception.lineNumber, exception.fileName].join("\n"));
				} else {
						// this is an internal error with a useless error number,
						// so throw it to let FW handle it and show a better message
					throw exception;
				}
			}
		}
	}
})(); } catch (exception) {
	if (exception.lineNumber) {
		alert([exception, exception.lineNumber, exception.fileName].join("\n"));
	} else {
		throw exception;
	}
}
<|endoftext|>


<commit_before>var tools = require(__dirname + '/../tools.js');

function detect(ip, device, options, callback) {
    // options.newInstances
    // options.existingInstances
    // device - additional info about device
    // options.log - logger
    // options.enums - {
    //      enum.rooms: {
    //          enum.rooms.ROOM1: {
    //              common: name
    //          }
    //      },
    //      enum.functions: {}
    // }

    var http = require('http');

    // print error function
    function printError(error){
        //options.log.debug(error.message);
        callback(null, false, ip);
    }

    function isEnergymanager(){
        var request = http.get('http://' + ip + '/rest/kiwigrid/wizard/devices', function(response){

            var body = "";

            response.on("data", function(chunk){
                body += chunk;
            });

            response.on("end", function(){
                if(response.statusCode === 200){
                try{
                if (body && body.indexOf('solarwatt') !== -1) {
                //var managerData = JSON.parse(body);
                //if (managerData.hasOwnProperty("result")){
                    var instance = tools.findInstance(options, 'energymanager', function (obj) {
                        return (obj.native.managerAddress === ip);
                    });
                    if (!instance) {
                        instance = {
                            _id: tools.getNextInstanceID('energymanager', options),
                            common: {
                                name: 'energymanager',
                                title: 'energymanager (' + ip + (device._name ? (' - ' + device._name) : '') + ')'
                            },
                            native: {
                                managerAddress: ip
                            },
                            comment: {
                                add: ['energymanager (' + ip + ')']
                            }
                        };
                        options.newInstances.push(instance);
                        callback(null, true, ip);
                    } else {
                        callback(null, false, ip);
                    }
                } else {
                    printError(error);
                }
            }
            catch(error){
                printError(error);
            }
        }
        else{
            printError;
        }
            });
        });

        // Connection Error
        request.on("error", printError);
    }

    isEnergymanager();
}

exports.detect = detect;
exports.type = ['ip'];// make type=serial for USB sticks
<commit_msg>changed solarwatt pattern to kiwigrid<commit_after>var tools = require(__dirname + '/../tools.js');

function detect(ip, device, options, callback) {
    // options.newInstances
    // options.existingInstances
    // device - additional info about device
    // options.log - logger
    // options.enums - {
    //      enum.rooms: {
    //          enum.rooms.ROOM1: {
    //              common: name
    //          }
    //      },
    //      enum.functions: {}
    // }

    var http = require('http');

    // print error function
    function printError(error){
        //options.log.debug(error.message);
        callback(null, false, ip);
    }

    function isEnergymanager(){
        var request = http.get('http://' + ip + '/rest/kiwigrid/wizard/devices', function(response){

            var body = "";

            response.on("data", function(chunk){
                body += chunk;
            });

            response.on("end", function(){
                if(response.statusCode === 200){
                try{
                if (body && body.indexOf('kiwigrid') !== -1) {
                //var managerData = JSON.parse(body);
                //if (managerData.hasOwnProperty("result")){
                    var instance = tools.findInstance(options, 'energymanager', function (obj) {
                        return (obj.native.managerAddress === ip);
                    });
                    if (!instance) {
                        instance = {
                            _id: tools.getNextInstanceID('energymanager', options),
                            common: {
                                name: 'energymanager',
                                title: 'energymanager (' + ip + (device._name ? (' - ' + device._name) : '') + ')'
                            },
                            native: {
                                managerAddress: ip
                            },
                            comment: {
                                add: ['energymanager (' + ip + ')']
                            }
                        };
                        options.newInstances.push(instance);
                        callback(null, true, ip);
                    } else {
                        callback(null, false, ip);
                    }
                } else {
                    printError(error);
                }
            }
            catch(error){
                printError(error);
            }
        }
        else{
            printError;
        }
            });
        });

        // Connection Error
        request.on("error", printError);
    }

    isEnergymanager();
}

exports.detect = detect;
exports.type = ['ip'];// make type=serial for USB sticks
<|endoftext|>


<commit_before><commit_msg>added places autocomplete<commit_after><|endoftext|>


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

function getConnection(){
	var connection = mysql.createConnection({
		facebook_api_key      :     "420507768127451",
  		facebook_api_secret   :     "cb799a25b790181819c231af9307ccdc",
   	    callback_url         :     "http://localhost:4302/auth/facebook/callback",

	    host: 'localhost',
	    user: 'root',
	    password : '',
	    port : 3306,
	    database:'ecommerce1'
	});
	return connection;
}
exports.getConnection = getConnection;<commit_msg>changed key<commit_after>var mysql = require('mysql');

function getConnection(){
	var connection = mysql.createConnection({
		facebook_api_key      :     "",
  		facebook_api_secret   :     "",
   	    callback_url         :     "http://localhost:4302/auth/facebook/callback",

	    host: 'localhost',
	    user: 'root',
	    password : '',
	    port : 3306,
	    database:'ecommerce1'
	});
	return connection;
}
exports.getConnection = getConnection;
<|endoftext|>


<commit_before>var runSeries = require('run-series');
var prependFile = require('prepend-file');

var constants = require('./util/constants');
var common = require('./util/common');
var _bundle = require('./util/browserify_wrapper');

var header = constants.licenseDist + '\n';
var pathToPlotlyDist = constants.pathToPlotlyDist;
var pathToPlotlyIndex = constants.pathToPlotlyIndex;
var pathToPlotlyDistMin = constants.pathToPlotlyDistMin;
var pathToPlotlyDistWithMeta = constants.pathToPlotlyDistWithMeta;

var pathToPlotlyStrict = constants.pathToPlotlyStrict;
var pathToPlotlyStrictDist = constants.pathToPlotlyStrictDist;
var pathToPlotlyStrictDistMin = constants.pathToPlotlyStrictDistMin;

var pathToPlotlyGeoAssetsSrc = constants.pathToPlotlyGeoAssetsSrc;
var pathToPlotlyGeoAssetsDist = constants.pathToPlotlyGeoAssetsDist;

// Check if style build file is there
var doesFileExist = common.doesFileExist;
if(!doesFileExist(constants.pathToCSSBuild)) {
    throw new Error([
        'build/plotcss.js is missing',
        'Please run `npm run preprocess` first'
    ].join('\n'));
}

// list of tasks to pass to run-series to not blow up
// memory consumption.
var tasks = [];

// Browserify plotly.js
tasks.push(function(done) {
    _bundle(pathToPlotlyIndex, pathToPlotlyDist, {
        standalone: 'Plotly',
        pathToMinBundle: pathToPlotlyDistMin
    }, function() {
        prependFile.sync(pathToPlotlyDist, header, common.throwOnError);
        prependFile.sync(pathToPlotlyDistMin, header, common.throwOnError);

        done();
    });
});

// Browserify plotly.js-strict
tasks.push(function(done) {
    _bundle(pathToPlotlyStrict, pathToPlotlyStrictDist, {
        standalone: 'Plotly',
        pathToMinBundle: pathToPlotlyStrictDistMin
    }, function() {
        prependFile.sync(pathToPlotlyStrictDist, header, common.throwOnError);
        prependFile.sync(pathToPlotlyStrictDistMin, header, common.throwOnError);

        done();
    });
});

// Browserify the geo assets
tasks.push(function(done) {
    _bundle(pathToPlotlyGeoAssetsSrc, pathToPlotlyGeoAssetsDist, {
        standalone: 'PlotlyGeoAssets'
    }, function() {
        prependFile.sync(pathToPlotlyGeoAssetsDist, header, common.throwOnError);

        done();
    });
});

// Browserify plotly.js with meta
tasks.push(function(done) {
    _bundle(pathToPlotlyIndex, pathToPlotlyDistWithMeta, {
        standalone: 'Plotly',
        noCompress: true
    }, function() {
        prependFile.sync(pathToPlotlyDistWithMeta, header, common.throwOnError);

        done();
    });
});

runSeries(tasks, function(err) {
    if(err) throw err;
});
<commit_msg>adjust strict bundle headers<commit_after>var runSeries = require('run-series');
var prependFile = require('prepend-file');

var constants = require('./util/constants');
var common = require('./util/common');
var _bundle = require('./util/browserify_wrapper');

var header = constants.licenseDist + '\n';
var pathToPlotlyDist = constants.pathToPlotlyDist;
var pathToPlotlyIndex = constants.pathToPlotlyIndex;
var pathToPlotlyDistMin = constants.pathToPlotlyDistMin;
var pathToPlotlyDistWithMeta = constants.pathToPlotlyDistWithMeta;

var pathToPlotlyStrict = constants.pathToPlotlyStrict;
var pathToPlotlyStrictDist = constants.pathToPlotlyStrictDist;
var pathToPlotlyStrictDistMin = constants.pathToPlotlyStrictDistMin;

var pathToPlotlyGeoAssetsSrc = constants.pathToPlotlyGeoAssetsSrc;
var pathToPlotlyGeoAssetsDist = constants.pathToPlotlyGeoAssetsDist;

// Check if style build file is there
var doesFileExist = common.doesFileExist;
if(!doesFileExist(constants.pathToCSSBuild)) {
    throw new Error([
        'build/plotcss.js is missing',
        'Please run `npm run preprocess` first'
    ].join('\n'));
}

// list of tasks to pass to run-series to not blow up
// memory consumption.
var tasks = [];

// Browserify plotly.js
tasks.push(function(done) {
    _bundle(pathToPlotlyIndex, pathToPlotlyDist, {
        standalone: 'Plotly',
        pathToMinBundle: pathToPlotlyDistMin
    }, function() {
        prependFile.sync(pathToPlotlyDist, header, common.throwOnError);
        prependFile.sync(pathToPlotlyDistMin, header, common.throwOnError);

        done();
    });
});

// Browserify plotly.js-strict
tasks.push(function(done) {
    _bundle(pathToPlotlyStrict, pathToPlotlyStrictDist, {
        standalone: 'Plotly',
        pathToMinBundle: pathToPlotlyStrictDistMin
    }, function() {
        prependFile.sync(pathToPlotlyStrictDist, header.replace('plotly.js', 'plotly.js (strict)'), common.throwOnError);
        prependFile.sync(pathToPlotlyStrictDistMin, header.replace('plotly.js', 'plotly.js (strict - minified)'), common.throwOnError);

        done();
    });
});

// Browserify the geo assets
tasks.push(function(done) {
    _bundle(pathToPlotlyGeoAssetsSrc, pathToPlotlyGeoAssetsDist, {
        standalone: 'PlotlyGeoAssets'
    }, function() {
        prependFile.sync(pathToPlotlyGeoAssetsDist, header, common.throwOnError);

        done();
    });
});

// Browserify plotly.js with meta
tasks.push(function(done) {
    _bundle(pathToPlotlyIndex, pathToPlotlyDistWithMeta, {
        standalone: 'Plotly',
        noCompress: true
    }, function() {
        prependFile.sync(pathToPlotlyDistWithMeta, header, common.throwOnError);

        done();
    });
});

runSeries(tasks, function(err) {
    if(err) throw err;
});
<|endoftext|>


<commit_before>/*
 * grunt-contrib-coffee
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Eric Woroshow, contributors
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  var path = require('path');
  var _ = grunt.util._;

  grunt.registerMultiTask('coffee', 'Compile CoffeeScript files into JavaScript', function() {

    var options = this.options({
      bare: false,
      join: false,
      sourceMap: false,
      separator: grunt.util.linefeed
    });

    grunt.verbose.writeflags(options, 'Options');

    this.files.forEach(function (f) {
      var validFiles = removeInvalidFiles(f);

      if (options.sourceMap === true) {
        var paths = createOutputPaths(f.dest);
        writeFileAndMap(paths, compileWithMaps(validFiles, options, paths));
      } else if (options.join === true) {
        writeFile(f.dest, concatInput(validFiles, options));
      } else {
        writeFile(f.dest, concatOutput(validFiles, options));
      }
    });
  });

  var isLiterate = function (ext) {
    return (ext === ".litcoffee" || ext === ".md");
  };

  var removeInvalidFiles = function(files) {
    return files.src.filter(function(filepath) {
      if (!grunt.file.exists(filepath)) {
        grunt.log.warn('Source file "' + filepath + '" not found.');
        return false;
      } else {
        return true;
      }
    });
  };

  var createOutputPaths = function (destination) {
    var fileName = path.basename(destination, path.extname(destination));
    return {
      dest: destination,
      destName: fileName,
      destDir: appendTrailingSlash(path.dirname(destination)),
      mapFileName: fileName + '.js.map'
    };
  };

  var appendTrailingSlash = function (path) {
    if (path.length > 0) {
      return path + '/';
    } else {
      return path;
    }
  };

  var compileWithMaps = function (files, options, paths) {
    if (!hasUniformExtensions(files)) {
      return;
    }

    var mapOptions, filepath;

    if (files.length > 1) {
      mapOptions = createOptionsForJoin(files, paths, options.separator);
    } else {
      mapOptions = createOptionsForFile(files[0], paths);
      filepath = files[0];
    }

    options = _.extend({
        generatedFile: path.basename(paths.dest),
        sourceRoot: mapOptions.sourceRoot,
        sourceFiles: mapOptions.sourceFiles
      }, options);

    var output = compileCoffee(mapOptions.code, options, filepath);
    appendFooter(output, paths);
    return output;
  };

  var hasUniformExtensions = function(files) {
    // get all extensions for input files
    var ext = files.map(function (f) {
      return path.extname(f);
    });

    if(_.uniq(ext).length > 1) {
      grunt.fail.warn('Join and sourceMap options require input files share the same extension (found '+_.uniq(ext).join(', ')+').');
      return false;
    } else {
      return true;
    }
  };

  var createOptionsForJoin = function (files, paths, separator) {
    var code = concatFiles(files, separator);
    var targetFileName = paths.destName + '.src.coffee';
    grunt.file.write(paths.destDir + targetFileName, code);

    return {
      code: code,
      sourceFiles: [targetFileName],
      sourceRoot: ''
    };
  };

  var concatFiles = function (files, separator) {
    return files.map(function (filePath) {
      return grunt.file.read(filePath);
    }).join(grunt.util.normalizelf(separator));
  };

  var createOptionsForFile = function (file, paths) {
    return {
      code: grunt.file.read(file),
      sourceFiles: [path.basename(file)],
      sourceRoot: appendTrailingSlash(path.relative(paths.destDir, path.dirname(file)))
    };
  };

  var appendFooter = function (output, paths) {
    // Add sourceMappingURL to file footer
    output.js = output.js + '\n/*\n//@ sourceMappingURL=' + paths.mapFileName + '\n*/';
  };

  var concatInput = function (files, options) {
    if (!hasUniformExtensions(files)) {
      return;
    }

    var code = concatFiles(files, options.separator);
    return compileCoffee(code, options);
  };

  var concatOutput = function(files, options) {
    return files.map(function(filepath) {
      var code = grunt.file.read(filepath);
      return compileCoffee(code, options, filepath);
    }).join(grunt.util.normalizelf(options.separator));
  };

  var compileCoffee = function(code, options, filepath) {
    options = _.clone(options);
    if(filepath) {
      options.filename = filepath;
      options.literate = isLiterate(path.extname(filepath));
    }

    try {
      return require('coffee-script').compile(code, options);
    } catch (e) {
      if (e.location == null ||
          e.location.first_column == null ||
          e.location.first_line == null) {
        grunt.log.error('Got an unexpected exception ' +
                        'from the coffee-script compiler. ' +
                        'The original exception was: ' +
                        e);
        grunt.log.error('(The coffee-script compiler should not raise *unexpected* exceptions. ' +
                        'You can file this error as an issue of the coffee-script compiler: ' +
                        'https://github.com/jashkenas/coffee-script/issues)');
      } else {
        var firstColumn = e.location.first_column;
        var firstLine = e.location.first_line;
        var codeLine = code.split('\n')[firstLine];
        var errorArrows = '\x1B[31m>>\x1B[39m ';
        var offendingCharacter;

        if (firstColumn < codeLine.length) {
          offendingCharacter = '\x1B[31m' + codeLine[firstColumn] + '\x1B[39m';
        } else {
          offendingCharacter = '';
        }

        grunt.log.error(e);
        grunt.log.error('In file: ' + filepath);
        grunt.log.error('On line: ' + firstLine);
        // Log erroneous line and highlight offending character
        // grunt.log.error trims whitespace so we have to use grunt.log.writeln
        grunt.log.writeln(errorArrows + codeLine.substring(0, firstColumn) +
                          offendingCharacter + codeLine.substring(firstColumn + 1));
        grunt.log.writeln(errorArrows + grunt.util.repeat(firstColumn, ' ') +
                          '\x1B[31m^\x1B[39m ');
      }
      grunt.fail.warn('CoffeeScript failed to compile.');
    }
  };

  var writeFileAndMap = function(paths, output) {
    if (!output || output.js.length === 0) {
      warnOnEmptyFile(paths.dest);
      return;
    }

    writeFile(paths.dest, output.js);
    writeFile(paths.destDir + paths.mapFileName, output.v3SourceMap);
  };

  var warnOnEmptyFile = function (path) {
    grunt.log.warn('Destination (' + path + ') not written because compiled files were empty.');
  };

  var writeFile = function (path, output) {
    if (output.length < 1) {
      warnOnEmptyFile(path);
    } else {
      grunt.file.write(path, output);
      grunt.log.writeln('File ' + path + ' created.');
    }
  };
};
<commit_msg>Colorize created path as cyan<commit_after>/*
 * grunt-contrib-coffee
 * http://gruntjs.com/
 *
 * Copyright (c) 2012 Eric Woroshow, contributors
 * Licensed under the MIT license.
 */

module.exports = function(grunt) {
  'use strict';

  var path = require('path');
  var _ = grunt.util._;

  grunt.registerMultiTask('coffee', 'Compile CoffeeScript files into JavaScript', function() {

    var options = this.options({
      bare: false,
      join: false,
      sourceMap: false,
      separator: grunt.util.linefeed
    });

    grunt.verbose.writeflags(options, 'Options');

    this.files.forEach(function (f) {
      var validFiles = removeInvalidFiles(f);

      if (options.sourceMap === true) {
        var paths = createOutputPaths(f.dest);
        writeFileAndMap(paths, compileWithMaps(validFiles, options, paths));
      } else if (options.join === true) {
        writeFile(f.dest, concatInput(validFiles, options));
      } else {
        writeFile(f.dest, concatOutput(validFiles, options));
      }
    });
  });

  var isLiterate = function (ext) {
    return (ext === ".litcoffee" || ext === ".md");
  };

  var removeInvalidFiles = function(files) {
    return files.src.filter(function(filepath) {
      if (!grunt.file.exists(filepath)) {
        grunt.log.warn('Source file "' + filepath + '" not found.');
        return false;
      } else {
        return true;
      }
    });
  };

  var createOutputPaths = function (destination) {
    var fileName = path.basename(destination, path.extname(destination));
    return {
      dest: destination,
      destName: fileName,
      destDir: appendTrailingSlash(path.dirname(destination)),
      mapFileName: fileName + '.js.map'
    };
  };

  var appendTrailingSlash = function (path) {
    if (path.length > 0) {
      return path + '/';
    } else {
      return path;
    }
  };

  var compileWithMaps = function (files, options, paths) {
    if (!hasUniformExtensions(files)) {
      return;
    }

    var mapOptions, filepath;

    if (files.length > 1) {
      mapOptions = createOptionsForJoin(files, paths, options.separator);
    } else {
      mapOptions = createOptionsForFile(files[0], paths);
      filepath = files[0];
    }

    options = _.extend({
        generatedFile: path.basename(paths.dest),
        sourceRoot: mapOptions.sourceRoot,
        sourceFiles: mapOptions.sourceFiles
      }, options);

    var output = compileCoffee(mapOptions.code, options, filepath);
    appendFooter(output, paths);
    return output;
  };

  var hasUniformExtensions = function(files) {
    // get all extensions for input files
    var ext = files.map(function (f) {
      return path.extname(f);
    });

    if(_.uniq(ext).length > 1) {
      grunt.fail.warn('Join and sourceMap options require input files share the same extension (found '+_.uniq(ext).join(', ')+').');
      return false;
    } else {
      return true;
    }
  };

  var createOptionsForJoin = function (files, paths, separator) {
    var code = concatFiles(files, separator);
    var targetFileName = paths.destName + '.src.coffee';
    grunt.file.write(paths.destDir + targetFileName, code);

    return {
      code: code,
      sourceFiles: [targetFileName],
      sourceRoot: ''
    };
  };

  var concatFiles = function (files, separator) {
    return files.map(function (filePath) {
      return grunt.file.read(filePath);
    }).join(grunt.util.normalizelf(separator));
  };

  var createOptionsForFile = function (file, paths) {
    return {
      code: grunt.file.read(file),
      sourceFiles: [path.basename(file)],
      sourceRoot: appendTrailingSlash(path.relative(paths.destDir, path.dirname(file)))
    };
  };

  var appendFooter = function (output, paths) {
    // Add sourceMappingURL to file footer
    output.js = output.js + '\n/*\n//@ sourceMappingURL=' + paths.mapFileName + '\n*/';
  };

  var concatInput = function (files, options) {
    if (!hasUniformExtensions(files)) {
      return;
    }

    var code = concatFiles(files, options.separator);
    return compileCoffee(code, options);
  };

  var concatOutput = function(files, options) {
    return files.map(function(filepath) {
      var code = grunt.file.read(filepath);
      return compileCoffee(code, options, filepath);
    }).join(grunt.util.normalizelf(options.separator));
  };

  var compileCoffee = function(code, options, filepath) {
    options = _.clone(options);
    if(filepath) {
      options.filename = filepath;
      options.literate = isLiterate(path.extname(filepath));
    }

    try {
      return require('coffee-script').compile(code, options);
    } catch (e) {
      if (e.location == null ||
          e.location.first_column == null ||
          e.location.first_line == null) {
        grunt.log.error('Got an unexpected exception ' +
                        'from the coffee-script compiler. ' +
                        'The original exception was: ' +
                        e);
        grunt.log.error('(The coffee-script compiler should not raise *unexpected* exceptions. ' +
                        'You can file this error as an issue of the coffee-script compiler: ' +
                        'https://github.com/jashkenas/coffee-script/issues)');
      } else {
        var firstColumn = e.location.first_column;
        var firstLine = e.location.first_line;
        var codeLine = code.split('\n')[firstLine];
        var errorArrows = '\x1B[31m>>\x1B[39m ';
        var offendingCharacter;

        if (firstColumn < codeLine.length) {
          offendingCharacter = '\x1B[31m' + codeLine[firstColumn] + '\x1B[39m';
        } else {
          offendingCharacter = '';
        }

        grunt.log.error(e);
        grunt.log.error('In file: ' + filepath);
        grunt.log.error('On line: ' + firstLine);
        // Log erroneous line and highlight offending character
        // grunt.log.error trims whitespace so we have to use grunt.log.writeln
        grunt.log.writeln(errorArrows + codeLine.substring(0, firstColumn) +
                          offendingCharacter + codeLine.substring(firstColumn + 1));
        grunt.log.writeln(errorArrows + grunt.util.repeat(firstColumn, ' ') +
                          '\x1B[31m^\x1B[39m ');
      }
      grunt.fail.warn('CoffeeScript failed to compile.');
    }
  };

  var writeFileAndMap = function(paths, output) {
    if (!output || output.js.length === 0) {
      warnOnEmptyFile(paths.dest);
      return;
    }

    writeFile(paths.dest, output.js);
    writeFile(paths.destDir + paths.mapFileName, output.v3SourceMap);
  };

  var warnOnEmptyFile = function (path) {
    grunt.log.warn('Destination (' + path + ') not written because compiled files were empty.');
  };

  var writeFile = function (path, output) {
    if (output.length < 1) {
      warnOnEmptyFile(path);
    } else {
      grunt.file.write(path, output);
      grunt.log.writeln('File ' + path.cyan + ' created.');
    }
  };
};
<|endoftext|>


<commit_before>var docker = require('../lib/docker')(),
    path = require('path'),
    Promise = require('promise'),
    spawn = require('child_process').spawn;

var detectOrder = function(containers, pocket) {
    'use strict';

    pocket = pocket || [];

    var retval = [];

    containers.forEach(function(name) {
        if (pocket.indexOf(name) >= 0) {
            return;
        }

        pocket.push(name);

        var container = docker.manifest.containers[name];

        if (container.volumesFrom) {
            detectOrder(container.volumesFrom, pocket).forEach(function(result) {
                retval.push(result);
            });
        }

        retval.push(name);
    });

    return retval;
};

var createTask = module.exports = function() {
    'use strict';

    var task = this.require('task');

    return task({_:['docker:build']})
        .then(function() {
            return task({_:['docker:remove']});
        })
        .then(function() {
            var packageName = docker.packageManifest.name;
            this.report('message', '[%s] pulling required images', packageName);

            var promises = [];
            Object.keys(docker.manifest.containers).forEach(function(name) {
                var image = docker.manifest.containers[name].image;

                if (image) {
                    var img = docker.getImage(image);
                    var promise = Promise.denodeify(img.inspect).bind(img)()
                        .then(null, function(a) {
                            this.report('message', '    | %s: pulling %s', name, image);

                            return new Promise(function(resolve, reject) {
                                var pull = spawn('docker', ['pull', image]);
                                pull.stdout.on('data', function(data) {
                                    this.report('message', '    | %s: %s', name, data.toString().trim());
                                }.bind(this));

                                pull.stderr.on('data', function(data) {
                                    this.report('message', '   e| %s: %s', name, data.toString().trim());
                                }.bind(this));

                                pull.on('close', function(code) {
                                    if (code) {
                                        reject(new Error('Error on pulling with code: ' + code));
                                    } else {
                                        resolve();
                                    }
                                });
                            }.bind(this));
                        }.bind(this));
                    promises.push(promise);
                }
            }.bind(this));

            return Promise.all(promises);
        }.bind(this))
        .then(function() {
            var packageName = docker.packageManifest.name;

            var orders = detectOrder(Object.keys(docker.manifest.containers));

            this.report('message', '[%s] creating containers (%s)', packageName, orders);

            var promise = Promise.resolve();

            orders.forEach(function(name) {

                var containerConf = docker.manifest.containers[name];

                var opts = {
                    Image: containerConf.imageName,
                    Volumes: {},
                    HostConfig: {
                        VolumesFrom: [],
                        Binds: []
                    }
                };

                if (containerConf.command) {
                    opts.Cmd = containerConf.command;
                }

                if (containerConf.volumesFrom) {
                    var volumesFrom = opts.HostConfig.VolumesFrom = opts.HostConfig.VolumesFrom || [];

                    containerConf.volumesFrom.forEach(function(c) {
                        var splitted = c.split(':');
                        var containerName = splitted[0];
                        var suffix = splitted[1] ? ':' + splitted[1] : '';
                        volumesFrom.push(docker.manifest.containers[containerName].prefixName + '0' + suffix);
                    });
                }

                // console.log(opts);

                if (containerConf.volumes) {

                    var binds = opts.HostConfig.Binds = opts.HostConfig.Binds || [];

                    containerConf.volumes.forEach(function(v) {
                        var splitted = v.split(':');
                        var origin = path.resolve(splitted[0]);
                        var destination = splitted.slice(1).join(':');

                        opts.Volumes[destination] = {};

                        binds.push(origin + ':' + destination);
                    });
                }

                promise = promise.then(function() {
                    var promises = [];

                    for(var i = 0; i < containerConf.scale; i++) {
                        opts.name = containerConf.prefixName + i;
                        this.report('message', '    | %s: creating %s', containerConf.name, opts.name);
                        promises.push(Promise.denodeify(docker.createContainer).bind(docker)(opts));
                    }

                    return Promise.all(promises);
                }.bind(this));
            }.bind(this));

            return promise;
        }.bind(this));
};

createTask.description = 'Create package containers';<commit_msg>added pas home as vol<commit_after>var docker = require('../lib/docker')(),
    path = require('path'),
    Promise = require('promise'),
    spawn = require('child_process').spawn;

var detectOrder = function(containers, pocket) {
    'use strict';

    pocket = pocket || [];

    var retval = [];

    containers.forEach(function(name) {
        if (pocket.indexOf(name) >= 0) {
            return;
        }

        pocket.push(name);

        var container = docker.manifest.containers[name];

        if (container.volumesFrom) {
            detectOrder(container.volumesFrom, pocket).forEach(function(result) {
                retval.push(result);
            });
        }

        retval.push(name);
    });

    return retval;
};

var createTask = module.exports = function() {
    'use strict';

    var task = this.require('task');
    var config = this.require('config')();

    return task({_:['docker:build']})
        .then(function() {
            return task({_:['docker:remove']});
        })
        .then(function() {
            var packageName = docker.packageManifest.name;
            this.report('message', '[%s] pulling required images', packageName);

            var promises = [];
            Object.keys(docker.manifest.containers).forEach(function(name) {
                var image = docker.manifest.containers[name].image;

                if (image) {
                    var img = docker.getImage(image);
                    var promise = Promise.denodeify(img.inspect).bind(img)()
                        .then(null, function(a) {
                            this.report('message', '    | %s: pulling %s', name, image);

                            return new Promise(function(resolve, reject) {
                                var pull = spawn('docker', ['pull', image]);
                                pull.stdout.on('data', function(data) {
                                    this.report('message', '    | %s: %s', name, data.toString().trim());
                                }.bind(this));

                                pull.stderr.on('data', function(data) {
                                    this.report('message', '   e| %s: %s', name, data.toString().trim());
                                }.bind(this));

                                pull.on('close', function(code) {
                                    if (code) {
                                        reject(new Error('Error on pulling with code: ' + code));
                                    } else {
                                        resolve();
                                    }
                                });
                            }.bind(this));
                        }.bind(this));
                    promises.push(promise);
                }
            }.bind(this));

            return Promise.all(promises);
        }.bind(this))
        .then(function() {
            var packageName = docker.packageManifest.name;

            var orders = detectOrder(Object.keys(docker.manifest.containers));

            this.report('message', '[%s] creating containers (%s)', packageName, orders);

            var promise = Promise.resolve();

            orders.forEach(function(name) {

                var containerConf = docker.manifest.containers[name];

                var opts = {
                    Image: containerConf.imageName,
                    Volumes: {},
                    HostConfig: {
                        VolumesFrom: [],
                        Binds: []
                    }
                };

                if (containerConf.command) {
                    opts.Cmd = containerConf.command;
                }

                if (containerConf.volumesFrom) {
                    var volumesFrom = opts.HostConfig.VolumesFrom = opts.HostConfig.VolumesFrom || [];
                    containerConf.volumesFrom.forEach(function(c) {
                        var splitted = c.split(':');
                        var containerName = splitted[0];
                        var suffix = splitted[1] ? ':' + splitted[1] : '';
                        volumesFrom.push(docker.manifest.containers[containerName].prefixName + '0' + suffix);
                    });
                }

                // console.log(opts);

                if (containerConf.volumes) {

                    var binds = opts.HostConfig.Binds = opts.HostConfig.Binds || [];

                    containerConf.volumes.forEach(function(v) {
                        var splitted = v.split(':');
                        var origin = path.resolve(splitted[0]);
                        var destination = splitted.slice(1).join(':');

                        opts.Volumes[destination] = {};

                        binds.push(origin + ':' + destination);
                    });

                    // FIXME this is ugly hack to include pas home here
                    binds.push(config.home + ':' + config.home);
                }

                promise = promise.then(function() {
                    var promises = [];

                    for(var i = 0; i < containerConf.scale; i++) {
                        opts.name = containerConf.prefixName + i;
                        this.report('message', '    | %s: creating %s', containerConf.name, opts.name);
                        promises.push(Promise.denodeify(docker.createContainer).bind(docker)(opts));
                    }

                    return Promise.all(promises);
                }.bind(this));
            }.bind(this));

            return promise;
        }.bind(this));
};

createTask.description = 'Create package containers';<|endoftext|>


<commit_before>'use strict';

module.exports = function(grunt) {

  var spawn = require('child_process').spawn,
      dancer = require('../lib/dancer');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('dancer', 'Control your dancer server via Grunt', function(command) {

    command = command || 'start';

    var args = [];
    var opts = this.options();
    opts.pidFile = opts.pidFile || "/tmp/dancerServer.pid";

    switch(command) {
      case 'serve':
        dancer.serve(args, opts);
        break;
      case 'start':
        dancer.start(args, opts);
        break;
      case 'restart':
        if(_currentProcess) {

          _currentProcess.on('close', function() {
            _currentProcess = spawn(args, {
              stdio: 'inherit'
            });
          });

          _currentProcess.kill('SIGQUIT');
        } else {
          if(grunt.file.exists(_pidFile)) {
            var killArgs = ['-s', 'QUIT', grunt.file.read(_pidFile)];
            var killTask = spawn('kill', killArgs, {
              stdio: 'ignore'
            });

            // args.unshift('server');
            _currentProcess = spawn(args, {
              stdio: ['ignore', process.stdout, 'ignore']
            });
          }
        }
        break;
      case 'kill':
        dancer.kill(args, opts);
        break;
    }

  });

};
<commit_msg>fixes<commit_after>'use strict';

module.exports = function(grunt) {

  var spawn = require('child_process').spawn,
      dancer = require('../lib/dancer');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerTask('dancer', 'Control your dancer server via Grunt', function(command) {

    command = command || 'start';

    var args = [];
    var opts = this.options();
    opts.pidFile = opts.pidFile || "/tmp/dancerServer.pid";

    switch(command) {
      case 'serve':
        dancer.serve(args, opts);
        break;
      case 'start':
        dancer.start(args, opts);
        break;
      case 'restart':
        if(typeof(_currentProcess) !== 'undefined') {

          _currentProcess.on('close', function() {
            _currentProcess = spawn(args, {
              stdio: 'inherit'
            });
          });

          _currentProcess.kill('SIGQUIT');
        } else {
          if(grunt.file.exists(opts.pidFile)) {
            var killArgs = ['-s', 'QUIT', grunt.file.read(opts.pidFile)];
            var killTask = spawn('kill', killArgs, {
//              stdio: 'ignore'
            });

          }
          dancer.start(args, opts);
        }
        break;
      case 'kill':
        dancer.kill(args, opts);
        break;
    }

  });

};
<|endoftext|>


<commit_before><commit_msg>reset bug fix<commit_after><|endoftext|>