/*
Run an AST through a set of rules and return a report in a callback.
@param {Object} options Doctor options.
@param {AstNode} ast AST.
@param {function} cb Function to call when finished.
177139
function run(options, ast, cb) {
  var report = new Report(options, ast);
  report.run(cb);
}
663336
function (options, callback) {
            /// <summary>Starts the connection</summary>
            /// <param name="options" type="Object">Options map</param>
            /// <param name="callback" type="Function">A callback function to execute when the connection has started</param>
            var connection = this,
                config = {
                    pingInterval: 300000,
                    waitForPageLoad: true,
                    transport: "auto",
                    jsonp: false
                },
                initialize,
                deferred = connection._deferral || $.Deferred(), // Check to see if there is a pre-existing deferral that's being built on, if so we want to keep using it
                parser = window.document.createElement("a");

            connection.lastError = null;

            // Persist the deferral so that if start is called multiple times the same deferral is used.
            connection._deferral = deferred;

            if (!connection.json) {
                // no JSON!
                throw new Error("SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support, e.g. IE<8.");
            }

            if ($.type(options) === "function") {
                // Support calling with single callback parameter
                callback = options;
            } else if ($.type(options) === "object") {
                $.extend(config, options);
                if ($.type(config.callback) === "function") {
                    callback = config.callback;
                }
            }

            config.transport = validateTransport(config.transport, connection);

            // If the transport is invalid throw an error and abort start
            if (!config.transport) {
                throw new Error("SignalR: Invalid transport(s) specified, aborting start.");
            }

            connection._.config = config;

            // Check to see if start is being called prior to page load
            // If waitForPageLoad is true we then want to re-direct function call to the window load event
            if (!_pageLoaded && config.waitForPageLoad === true) {
                connection._.deferredStartHandler = function () {
                    connection.start(options, callback);
                };
                _pageWindow.bind("load", connection._.deferredStartHandler);

                return deferred.promise();
            }

            // If we're already connecting just return the same deferral as the original connection start
            if (connection.state === signalR.connectionState.connecting) {
                return deferred.promise();
            } else if (changeState(connection,
                            signalR.connectionState.disconnected,
                            signalR.connectionState.connecting) === false) {
                // We're not connecting so try and transition into connecting.
                // If we fail to transition then we're either in connected or reconnecting.

                deferred.resolve(connection);
                return deferred.promise();
            }

            configureStopReconnectingTimeout(connection);

            // Resolve the full url
            parser.href = connection.url;
            if (!parser.protocol || parser.protocol === ":") {
                connection.protocol = window.document.location.protocol;
                connection.host = parser.host || window.document.location.host;
            } else {
                connection.protocol = parser.protocol;
                connection.host = parser.host;
            }

            connection.baseUrl = connection.protocol + "//" + connection.host;

            // Set the websocket protocol
            connection.wsProtocol = connection.protocol === "https:" ? "wss://" : "ws://";

            // If jsonp with no/auto transport is specified, then set the transport to long polling
            // since that is the only transport for which jsonp really makes sense.
            // Some developers might actually choose to specify jsonp for same origin requests
            // as demonstrated by Issue #623.
            if (config.transport === "auto" && config.jsonp === true) {
                config.transport = "longPolling";
            }

            // If the url is protocol relative, prepend the current windows protocol to the url. 
            if (connection.url.indexOf("//") === 0) {
                connection.url = window.location.protocol + connection.url;
                connection.log("Protocol relative URL detected, normalizing it to '" + connection.url + "'.");
            }

            if (this.isCrossDomain(connection.url)) {
                connection.log("Auto detected cross domain url.");

                if (config.transport === "auto") {
                    // TODO: Support XDM with foreverFrame
                    config.transport = ["webSockets", "serverSentEvents", "longPolling"];
                }

                if (typeof (config.withCredentials) === "undefined") {
                    config.withCredentials = true;
                }

                // Determine if jsonp is the only choice for negotiation, ajaxSend and ajaxAbort.
                // i.e. if the browser doesn't supports CORS
                // If it is, ignore any preference to the contrary, and switch to jsonp.
                if (!config.jsonp) {
                    config.jsonp = !$.support.cors;

                    if (config.jsonp) {
                        connection.log("Using jsonp because this browser doesn't support CORS.");
                    }
                }

                connection.contentType = signalR._.defaultContentType;
            }

            connection.withCredentials = config.withCredentials;

            connection.ajaxDataType = config.jsonp ? "jsonp" : "text";

            $(connection).bind(events.onStart, function (e, data) {
                if ($.type(callback) === "function") {
                    callback.call(connection);
                }
                deferred.resolve(connection);
            });

            connection._.initHandler = signalR.transports._logic.initHandler(connection);

            initialize = function (transports, index) {
                var noTransportError = signalR._.error(resources.noTransportOnInit);

                index = index || 0;
                if (index >= transports.length) {
                    if (index === 0) {
                        connection.log("No transports supported by the server were selected.");
                    } else if (index === 1) {
                        connection.log("No fallback transports were selected.");
                    } else {
                        connection.log("Fallback transports exhausted.");
                    }

                    // No transport initialized successfully
                    $(connection).triggerHandler(events.onError, [noTransportError]);
                    deferred.reject(noTransportError);
                    // Stop the connection if it has connected and move it into the disconnected state
                    connection.stop();
                    return;
                }

                // The connection was aborted
                if (connection.state === signalR.connectionState.disconnected) {
                    return;
                }

                var transportName = transports[index],
                    transport = signalR.transports[transportName],
                    onFallback = function () {
                        initialize(transports, index + 1);
                    };

                connection.transport = transport;

                try {
                    connection._.initHandler.start(transport, function () { // success
                        // Firefox 11+ doesn't allow sync XHR withCredentials: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#withCredentials
                        var isFirefox11OrGreater = signalR._.firefoxMajorVersion(window.navigator.userAgent) >= 11,
                            asyncAbort = !!connection.withCredentials && isFirefox11OrGreater;

                        connection.log("The start request succeeded. Transitioning to the connected state.");

                        if (supportsKeepAlive(connection)) {
                            signalR.transports._logic.monitorKeepAlive(connection);
                        }

                        signalR.transports._logic.startHeartbeat(connection);

                        // Used to ensure low activity clients maintain their authentication.
                        // Must be configured once a transport has been decided to perform valid ping requests.
                        signalR._.configurePingInterval(connection);

                        if (!changeState(connection,
                                            signalR.connectionState.connecting,
                                            signalR.connectionState.connected)) {
                            connection.log("WARNING! The connection was not in the connecting state.");
                        }

                        // Drain any incoming buffered messages (messages that came in prior to connect)
                        connection._.connectingMessageBuffer.drain();

                        $(connection).triggerHandler(events.onStart);

                        // wire the stop handler for when the user leaves the page
                        _pageWindow.bind("unload", function () {
                            connection.log("Window unloading, stopping the connection.");

                            connection.stop(asyncAbort);
                        });

                        if (isFirefox11OrGreater) {
                            // Firefox does not fire cross-domain XHRs in the normal unload handler on tab close.
                            // #2400
                            _pageWindow.bind("beforeunload", function () {
                                // If connection.stop() runs runs in beforeunload and fails, it will also fail
                                // in unload unless connection.stop() runs after a timeout.
                                window.setTimeout(function () {
                                    connection.stop(asyncAbort);
                                }, 0);
                            });
                        }
                    }, onFallback);
                }
                catch (error) {
                    connection.log(transport.name + " transport threw '" + error.message + "' when attempting to start.");
                    onFallback();
                }
            };

            var url = connection.url + "/negotiate",
                onFailed = function (error, connection) {
                    var err = signalR._.error(resources.errorOnNegotiate, error, connection._.negotiateRequest);

                    $(connection).triggerHandler(events.onError, err);
                    deferred.reject(err);
                    // Stop the connection if negotiate failed
                    connection.stop();
                };

            $(connection).triggerHandler(events.onStarting);

            url = signalR.transports._logic.prepareQueryString(connection, url);

            connection.log("Negotiating with '" + url + "'.");

            // Save the ajax negotiate request object so we can abort it if stop is called while the request is in flight.
            connection._.negotiateRequest = signalR.transports._logic.ajax(connection, {
                url: url,
                error: function (error, statusText) {
                    // We don't want to cause any errors if we're aborting our own negotiate request.
                    if (statusText !== _negotiateAbortText) {
                        onFailed(error, connection);
                    } else {
                        // This rejection will noop if the deferred has already been resolved or rejected.
                        deferred.reject(signalR._.error(resources.stoppedWhileNegotiating, null /* error */, connection._.negotiateRequest));
                    }
                },
                success: function (result) {
                    var res,
                        keepAliveData,
                        protocolError,
                        transports = [],
                        supportedTransports = [];

                    try {
                        res = connection._parseResponse(result);
                    } catch (error) {
                        onFailed(signalR._.error(resources.errorParsingNegotiateResponse, error), connection);
                        return;
                    }

                    keepAliveData = connection._.keepAliveData;
                    connection.appRelativeUrl = res.Url;
                    connection.id = res.ConnectionId;
                    connection.token = res.ConnectionToken;
                    connection.webSocketServerUrl = res.WebSocketServerUrl;

                    // The long poll timeout is the ConnectionTimeout plus 10 seconds
                    connection._.pollTimeout = res.ConnectionTimeout * 1000 + 10000; // in ms

                    // Once the server has labeled the PersistentConnection as Disconnected, we should stop attempting to reconnect
                    // after res.DisconnectTimeout seconds.
                    connection.disconnectTimeout = res.DisconnectTimeout * 1000; // in ms

                    // Add the TransportConnectTimeout from the response to the transportConnectTimeout from the client to calculate the total timeout
                    connection._.totalTransportConnectTimeout = connection.transportConnectTimeout + res.TransportConnectTimeout * 1000;

                    // If we have a keep alive
                    if (res.KeepAliveTimeout) {
                        // Register the keep alive data as activated
                        keepAliveData.activated = true;

                        // Timeout to designate when to force the connection into reconnecting converted to milliseconds
                        keepAliveData.timeout = res.KeepAliveTimeout * 1000;

                        // Timeout to designate when to warn the developer that the connection may be dead or is not responding.
                        keepAliveData.timeoutWarning = keepAliveData.timeout * connection.keepAliveWarnAt;

                        // Instantiate the frequency in which we check the keep alive.  It must be short in order to not miss/pick up any changes
                        connection._.beatInterval = (keepAliveData.timeout - keepAliveData.timeoutWarning) / 3;
                    } else {
                        keepAliveData.activated = false;
                    }

                    connection.reconnectWindow = connection.disconnectTimeout + (keepAliveData.timeout || 0);

                    if (!res.ProtocolVersion || res.ProtocolVersion !== connection.clientProtocol) {
                        protocolError = signalR._.error(signalR._.format(resources.protocolIncompatible, connection.clientProtocol, res.ProtocolVersion));
                        $(connection).triggerHandler(events.onError, [protocolError]);
                        deferred.reject(protocolError);

                        return;
                    }

                    $.each(signalR.transports, function (key) {
                        if ((key.indexOf("_") === 0) || (key === "webSockets" && !res.TryWebSockets)) {
                            return true;
                        }
                        supportedTransports.push(key);
                    });

                    if ($.isArray(config.transport)) {
                        $.each(config.transport, function (_, transport) {
                            if ($.inArray(transport, supportedTransports) >= 0) {
                                transports.push(transport);
                            }
                        });
                    } else if (config.transport === "auto") {
                        transports = supportedTransports;
                    } else if ($.inArray(config.transport, supportedTransports) >= 0) {
                        transports.push(config.transport);
                    }

                    initialize(transports);
                }
            });

            return deferred.promise();
        }
1086
function render(options, report, cb) {
  var reportName = options.outputReportName || 'report.json';
  var files = {};
  files[reportName] = report;
  var renderFunctions = u.toArray(options.render || 'default');
  try {
    renderFunctions = u.findFunctions(renderFunctions, 'render');
  } catch (findError) {
    return cb(findError);
  }
  function eachRender(fn, cb) {
    fn(options, files, function (err, renderedFiles) {
      if (err) {
        return cb(err);
      }
      files = renderedFiles;
      cb(null, files);
    });
  }
  async.forEachSeries(renderFunctions, eachRender, function (err) {
    // if (err) {
    //   return cb(err);
    // }
    // Object.keys(files).forEach(function (filename, i) {
    //   var file = files[filename];
    //   if (typeof file !== 'string') {
    //     try {
    //       // if circular references were introduced, this will fail
    //       var fileString = JSON.stringify(file, null, 2);
    //       files[filename] = fileString;
    //     } catch (jsonError) {
    //       return cb(jsonError);
    //     }
    //   }
    // });
    cb(err, files);
  });
}
258156
function(options, callback) {
    // var self = this

    if (typeof options === 'function') {
      callback = options
      options = {}
    }

    if (options.transaction) {
      return callback(options.transaction)
    } else {
      return this.connection
        .transaction(function(transaction) {
          options.transaction = transaction
          return callback(transaction)
        })
        .then(function(result) {
          debug('commit')
          return result
        })
        .catch(function(e) {
          // TODO: do something with e.g. 'afterSave' rollback message!?!
          debug('rollback')
          throw e
        })
    }
  }
485821
function runCommand(name, args, options, cb, stdoutHandler, stderrHandler) {
	//if we dont actually have stdout and stderr, try to get the cb
	//if there was no callback passed, used a default

	options = options || { cwd : cwd, env: env };
	var child = spawn(name, args, options);
	if (cb) {
		var out = null;
		var err = null;
		//we need to wait for process.exit, stdout.end, and stderr.end before
		//we return
		var waiting = 3;
		var returnArgs = [];

		var fire = function(index, arg) {
			if (arg != null) {
				returnArgs[index] = arg;
			}
			if (--waiting === 0) {
				cb.apply(undefined, returnArgs);
			}
		};
		//buffer stdout and stderr to pass to the completion callback
		if (!stdoutHandler) {
			out = '';
			stdoutHandler = function(data) {
				out += data;
			};
		}
		if (!stderrHandler) {
			err = '';
			stderrHandler = function(data) {
				err += data;
			};
		}
		child.stdout.setEncoding('utf8');
		child.stdout.on('data', stdoutHandler); 
		child.stdout.on('end', function() {fire(1, out); });
				
		child.stderr.setEncoding('utf8');
		child.stderr.on('data', stderrHandler);
		child.stderr.on('end', function() {fire(2, err); });

		child.on('exit', function(code) {
			fire(0, code);
		});
	}

	return child;

}
1085921
function findOrCreate(params, cb) {
	/* istanbul ignore next */
	if (typeof cb !== 'function') {
		throw new Error('Callback must be a function');
	}

	db.findOne(params, (err, doc) => {
		/* istanbul ignore next: hard-to-invoke error */
		if (err) {
			cb(err);
			return;
		}

		if (doc) {
			cb(null, doc.token);
		} else {
			params.token = uuid();
			db.insert(params, (err, newDoc) => {
				/* istanbul ignore next: hard-to-invoke error */
				if (err) {
					cb(err);
					return;
				}

				cb(null, newDoc.token);
			});
		}
	});
}
1006578
function(model, id, settings, options, cb) {
      var defaultSelect, query;
      if (settings == null) {
        settings = {};
      }
      if (options == null) {
        options = {};
      }
      if (cb == null) {
        cb = function() {};
      }
      Hoek.assert(model, i18n.assertModuleRequired);
      Hoek.assert(id, i18n.assertIdRequired);
      defaultSelect = settings.defaultSelect || null;
      if (_.isFunction(options)) {
        cb = options;
        options = {};
      }
      options.select || (options.select = defaultSelect);
      query = model.findOne({
        _id: asObjectId(id)
      });
      if (options.select && options.select.length > 0) {
        query = query.select(options.select);
      }
      return query.exec(cb);
    }
1003587
function(){
                /*
                 * ruleset
                 *   : selectors_group
                 *     '{' S* declaration? [ ';' S* declaration? ]* '}' S*
                 *   ;
                 */

                var tokenStream = this._tokenStream,
                    tt,
                    selectors;

                var node = this.startNode('Rule', tokenStream.curr().range[0], 'body'); //ORION AST generation
                /*
                 * Error Recovery: If even a single selector fails to parse,
                 * then the entire ruleset should be thrown away.
                 */
                try {
                    selectors = this._selectors_group();
                } catch (ex){
                    if (ex instanceof SyntaxError && !this.options.strict){

                        //fire error event
                        this.fire({
                            type:       "error",
                            error:      ex,
                            message:    ex.message,
                            line:       ex.line,
                            col:        ex.col
                        });

                        //skip over everything until closing brace
                        tt = tokenStream.advance([Tokens.RBRACE]);
                        if (tt === Tokens.RBRACE){
                            //if there's a right brace, the rule is finished so don't do anything
                        } else {
                            //otherwise, rethrow the error because it wasn't handled properly
                            throw ex;
                        }

                    } else {
                        //not a syntax error, rethrow it
                        throw ex;
                    }

                    //trigger parser to continue
                    return true;
                }

                //if it got here, all selectors parsed
                if (selectors){

                    this.fire({
                        type:       "startrule",
                        selectors:  selectors,
                        line:       selectors[0].line,
                        col:        selectors[0].col
                    });

                    this._readDeclarations(true);
                    
                    this.fire({
                        type:       "endrule",
                        selectors:  selectors,
                        line:       selectors[0].line,
                        col:        selectors[0].col
                    });
                    
                    var rbraceRange = this.findLastTokenRange('RBRACE', node.range[0]); // ORION AST Generation select the RBRACE token
                    this.endNode(node, rbraceRange[1]); //ORION AST Generation
                }

				// ORION AST Generation, don't create an empty rule node if no rule selectors found
                if (selectors === null){
                    this.removeNode(node, 'body');
                }
                return selectors;

            }
436212
function run (command, args, cb) {
    if (typeof cb !== 'function') {
      var cb = cbmain
    }
    my.args = args
    my.command = command
    if (my.state) {
      parseState( function (err) {
        if (err) return cb(err)
        switchboard(cb)
      })
    }
    else {
      readState(function (err, state) {
        if (err) return cb(err)
        setState(state)
        parseState( function (err) {
          if (err) return cb(err)
          switchboard(cb)
        }) //end parseState
      }) // end readState
    }

    function switchboard(cb) {
      switch (my.command) {
      case 'init':
        init(cb);
        break
      case 'add':
        add(cb)
        break
      case 'remove':
        remove(cb);
        break
      case 'bin':
        bin(cb);
        break
      case 'checkout':
        checkout(cb);
        break
      case 'status':
        status(cb);
        break
      case 'push':
        push(cb);
        break
      default:
        cb( erf( (command === undefined) ? '' :
                 'Unknown command: ' + command , usage) )
      }
    } // end SWITCHBOARD
  }
595089
function (str, options, cb) {
    var tmpl = this.cache(options) || this.cache(options, this.engine.compile(str, options));
    tmpl.eval(options, function(str){
      cb(null, str);
    });
  }
777133
function(server, port, options, cb) {
    return this.client.connect.call(this.client, server, port, options, cb);
  }
488273
function transform(options, ast, cb) {

  var transformObj = {
    options: options
  };

  function queueNodeWalk(node, cb) {
    if (options._walkQueue) {
      options._walkQueue.push(node);
    }
  }

  function eachNodeRule(node, rule) {
    if (rule.transform) {
      if (typeof rule.transform === 'function') {
        node._walk = queueNodeWalk;
        rule.transform(node, transformObj);
        delete node._walk;
      }
    }
  }

  var rules = u.toArray(options.transform || 'default');

  nast.walkWithRules(options, rules, 'transform', ast, eachNodeRule, cb);
}
1323563
function updateRules(rulesToUpdate, cb) {
    function updateRule(ruleDetails, cb1) {
      var id = ruleDetails._id;

      rulesModel.findOne({_id: id}, function(err, ruleToUpdate) {
        if (err) {
          return cb1(err);
        }

        if (ruleToUpdate === null && !options.createIfNotFound) {
          return cb1(new Error("No " + ruleType + " rule matches id " + id));
        } else if (ruleToUpdate === null && options.createIfNotFound) {
          ruleToUpdate = new rulesModel(ruleDetails);
        }

        for (var saveKey in ruleDetails) { // eslint-disable-line guard-for-in
          ruleToUpdate[saveKey] = ruleDetails[saveKey];
        }

        ruleToUpdate.save(cb1);
      });
    }

    async.map(rulesToUpdate, updateRule, cb);
  }
942240
async function createConfig(optionsArgs) {
  const options = {
    ...DEFAULT_OPTIONS,
    ...optionsArgs,
  };
  const { rules, base } = options;

  const config = {
    ...base,
    rules: base.rules || {},
  };

  return Object.keys(config)
    .reduce(async (collection, key) => {
      const previous = await collection;

      if (key === 'rules') {
        const combinedRules = await combineRules(rules);

        return {
          ...previous,
          rules: {
            ...combinedRules,
            ...config.rules,
          },
        };
      }

      return {
        ...previous,
        [key]: config[key],
      };
    }, Promise.resolve({}));
}
221586
def _do_cb(self, cb, error_cb, *args, **kw):
        
        try:
            res = self.work(*args, **kw)
        except Exception as e:
            if error_cb is None:
                show_err()
            elif error_cb:
                error_cb(e)
        else:
            # Success, let's call away!
            cb(res)
1203305
function createRules(rulesToCreate, cb) {

    function addRule(ruleToCreate, addRuleCallback) {
      var fr = new rulesModel(ruleToCreate);

      fr.save(function(err, frdoc) {
        if (err) {
          return addRuleCallback(err);
        }
        return addRuleCallback(null, frdoc);
      });
    }

    async.map(rulesToCreate, addRule, cb);
  }
224912
function(opts) {
  opts = opts || {};

  this.options = {
    debug: opts.debug || false,
    board: opts.board || 'uno',
    port: opts.port || '',
    manualReset: opts.manualReset || false
  };

  // this here checks for 3 conditions:
  // if debug option is simply true, we want to fall back to default debug function
  // if a custom debug function is passed in, we want to assign debug to be that
  // if debug option is false, then run debug as a no-op
  if (this.options.debug === true) {
    this.debug = console.log.bind(console);
  } else if (typeof this.options.debug === 'function') {
    this.debug = this.options.debug;
  } else {
    this.debug = function() {};
  }

  if (typeof this.options.board === 'string') {
    this.options.board = boards[this.options.board];
  } else if (typeof this.options.board === 'object') {
    this.options.board = this.options.board;
  }

  if (this.options.board && !this.options.board.manualReset) {
    this.options.board.manualReset = this.options.manualReset;
  }

  this.connection = new Connection(this.options);

  if (this.options.board) {
    var Protocol = protocols[this.options.board.protocol] || function() {};

    this.protocol = new Protocol({
      board: this.options.board,
      connection: this.connection,
      debug: this.debug
    });
  }
}