Find a state instance, and execute a callback if found.

@param  {Object|Function}    required    the config object, or mutation callback
@param  {Function}           optional    mutation callback
@return {Function}
184852
function findInstanceThen() {
        // this function supports two argument signatures. if the
        // first argument is an object, we will use that as the
        // config, and the second arg as the mutation handler
        var _parseArguments = parseArguments(arguments),
            config = _parseArguments.config,
            callback = _parseArguments.callback;

        return function (state, payload) {
            if (stateAndPayloadAreValid(config, state, payload)) {

                // find our instance based on the current configuration
                var instance = state[config.stateKey].find(function (obj) {
                    return obj[config.instanceKey] === payload[config.instanceKey];
                });

                // if the instance was found, execute our mutation callback
                if (instance) {
                    callback(instance, payload, state);
                }
            }
        };
    }
884074
function patchRequire(require) {
        if (require.patched) {
            return require;
        }
        function fromPackageJson(module, dir) {
            var pkgPath, pkgContents, pkg;
            pkgPath = fs.pathJoin(dir, module, 'package.json');
            if (!fs.exists(pkgPath)) {
                return;
            }
            pkgContents = fs.read(pkgPath);
            if (!pkgContents) {
                return;
            }
            try {
                pkg = JSON.parse(pkgContents);
            } catch (e) {
                return;
            }
            if (typeof pkg === "object" && pkg.main) {
                return fs.absolute(fs.pathJoin(dir, module, pkg.main));
            }
        }
        function resolveFile(path, dir) {
            var extensions = ['js', 'coffee', 'json'];
            var basenames = [path, path + '/index'];
            var paths = [];
            var nodejsScript = fromPackageJson(path, dir);
            if (nodejsScript) {
                return nodejsScript;
            }
            basenames.forEach(function(basename) {
                paths.push(fs.absolute(fs.pathJoin(dir, basename)));
                extensions.forEach(function(extension) {
                    paths.push(fs.absolute(fs.pathJoin(dir, [basename, extension].join('.'))));
                });
            });
            for (var i = 0; i < paths.length; i++) {
                if (fs.isFile(paths[i])) {
                    return paths[i];
                }
            }
            return null;
        }
        function getCurrentScriptRoot() {
            if ((phantom.casperScriptBaseDir || "").indexOf(fs.workingDirectory) === 0) {
                return phantom.casperScriptBaseDir;
            }
            return fs.absolute(fs.pathJoin(fs.workingDirectory, phantom.casperScriptBaseDir));
        }
        function casperBuiltinPath(path) {
            return resolveFile(path, fs.pathJoin(phantom.casperPath, 'modules'));
        }
        function nodeModulePath(path) {
            var resolved, prevBaseDir;
            var baseDir = getCurrentScriptRoot();
            do {
                resolved = resolveFile(path, fs.pathJoin(baseDir, 'node_modules'));
                prevBaseDir = baseDir;
                baseDir = fs.absolute(fs.pathJoin(prevBaseDir, '..'));
            } while (!resolved && baseDir !== '/' && prevBaseDir !== '/' && baseDir !== prevBaseDir);
            return resolved;
        }
        function localModulePath(path) {
            return resolveFile(path, phantom.casperScriptBaseDir || fs.workingDirectory);
        }
        var patchedRequire = function patchedRequire(path) {
            try {
                return require(casperBuiltinPath(path) ||
                               nodeModulePath(path)    ||
                               localModulePath(path)   ||
                               path);
            } catch (e) {
                throw new CasperError("Can't find module " + path);
            }
        };
        patchedRequire.cache = require.cache;
        patchedRequire.extensions = require.extensions;
        patchedRequire.stubs = require.stubs;
        patchedRequire.patched = true;
        return patchedRequire;
    }
661770
function(suppliedConfig) {
    // Handle config and defaults
    try {
      config.parseAndUpdate(suppliedConfig);
    } catch (e) {
      render.triggerError(e);
      return this
    }

    utils.logDebug(['Final config:', getConfig()]);

    try {
      return startRender();
    } catch (e) {
      render.triggerError(e);
      return this
    }
  }
303763
function requireAll(schemaDir, options, callback) {
  debug("loading schemas");
  if (!callback) {
    callback = options;
    options = {};
  }
  const opts = _.assign({
    extensions: ["json"],
  }, options);

  let files;
  try {
    files = fs.readdirSync(schemaDir);
  } catch(errReaddir) {
    return callback(errReaddir);
  }

  let schemas = [];

  for (let index = 0; index < files.length; index++) {
    const file = files[index];
    const ext = path.extname(file).slice(1);

    if (opts.extensions.indexOf(ext) === -1) {
      continue;
    }

    const abspath = path.join(schemaDir, file);
    let schema;

    // try load the schema! If it fails, stop immediately
    try {
      schema = require(abspath);
    } catch (errRequire) {
      return callback(errRequire);
    }

    schema.filepath = abspath;
    schemas.push(schema);
  }

  return callback(null, schemas);
}
897186
function replacer(match, quote, require) {
        var replacement = 'require(' + quote;
        try {
            resolve.sync(require);
        } catch (exc) {
            try {
                // Try to resolve the require statement starting from the root folder
                resolve.sync(require, {paths: ['.']});
                replacement += relativeToRoot + path.sep;
            } catch (exc2) {
            }
        }
        replacement += require + quote + ')';
//        console.log(replacement);
        return replacement;
    }
298585
function (methodName, argName) {
            var required = this.findParameter(methodName, argName).required;
            //default is false, so if "required" is undefined, return false anyway
            if (required) {
                return true;
            }
            return false;
        }
842986
function tryRequire(name, def, isRoot) {
    function _require() {
        if (!is_1.isNode())
            /* istanbul ignore next */
            return to_1.toDefault(null, def);
        if (isRoot)
            return require.main.require(name);
        return require(name);
    }
    return tryWrap(_require)(def);
}
858372
function require(names, callback, errback, referer) {
      // in amd, first arg can be a config object... we just ignore
      if (typeof names == 'object' && !(names instanceof Array))
        return require.apply(null, Array.prototype.splice.call(arguments, 1, arguments.length - 1));

      // amd require
      if (typeof names == 'string' && typeof callback == 'function')
        names = [names];
      if (names instanceof Array) {
        var dynamicRequires = [];
        for (var i = 0; i < names.length; i++)
          dynamicRequires.push(loader['import'](names[i], referer));
        Promise.all(dynamicRequires).then(function(modules) {
          if (callback)
            callback.apply(null, modules);
        }, errback);
      }

      // commonjs require
      else if (typeof names == 'string') {
        var defaultJSExtension = loader.defaultJSExtensions && names.substr(names.length - 3, 3) != '.js';
        var normalized = loader.decanonicalize(names, referer);
        if (defaultJSExtension && normalized.substr(normalized.length - 3, 3) == '.js')
          normalized = normalized.substr(0, normalized.length - 3);
        var module = loader.get(normalized);
        if (!module)
          throw new Error('Module not already loaded loading "' + names + '" as ' + normalized + (referer ? ' from "' + referer + '".' : '.'));
        return module.__useDefault ? module['default'] : module;
      }

      else
        throw new TypeError('Invalid require');
    }
270783
function requireClass(className) {
		if(!className) {
			return false;
		}

		var theClass;

		try {
			theClass = require(path.join(this.root, '/app/classes/' + className));
		}
		catch(err) {
			theClass = undefined;
			this.log.error(err);
		}

		return theClass;
	}
1060682
function apply(instance, options) {
  var config = new Config(options, StateMachine);
  build(instance, config);
  instance._fsm();
  return instance;
}
197968
function (fn) {
            var requires = [];
            // Remove comments from the callback string,
            // look for require calls, and pull them into the dependencies,
            // but only if there are function args.
            fn.toString()
                .replace(commentRegExp, '')
                .replace(requireRegExp, function (match, _, dep) {
                    requires.push(dep);
                });
            return requires;
        }
857476
function validateConfig(config) {
    // appId and versionId are not validated here since
    // not all operations require these to be present.
    // Validation of specific params are done in the
    // ServiceBase.js
    const {subscriptionKey} = config;
    const messageTail = `is missing from the configuration.\n\nDid you run ${chalk.cyan.bold('qnamaker init')} yet?`;
    assert(typeof subscriptionKey === 'string', `The subscriptionKey ${messageTail}`);
}
852855
function transformRequireCall(path, state) {
    var calleePath = path.get('callee');
    if (
      !t.isIdentifier(calleePath.node, {name: 'require'}) &&
      !(
        t.isMemberExpression(calleePath.node) &&
        t.isIdentifier(calleePath.node.object, {name: 'require'}) &&
        t.isIdentifier(calleePath.node.property, {name: 'requireActual'})
      )
    ) {
      return;
    }

    var args = path.get('arguments');
    if (!args.length) {
      return;
    }
    var moduleArg = args[0];
    if (moduleArg.node.type === 'StringLiteral') {
      var module = mapModule(state, moduleArg.node.value);
      if (module) {
        moduleArg.replaceWith(t.stringLiteral(module));
      }
    }
  }
622768
function requireFunc() {
    if (typeof arguments[0] === 'string') {
      const dep = arguments[0];
      const got = defined(dep);
      if (got) return got.val;
      throw new Error(`commonjs dependency "${dep}" is not prepared.`);
    }

    return requirejs.apply(null, arguments);
  }
792840
function required (val, arg) {
  var isRequired = arg === undefined ? true : arg;
  if (Array.isArray(val)) {
    if (val.length !== 0) {
      var valid = true;
      for (var i = 0, l = val.length; i < l; i++) {
        valid = required(val[i], isRequired);
        if ((isRequired && !valid) || (!isRequired && valid)) {
          break
        }
      }
      return valid
    } else {
      return !isRequired
    }
  } else if (typeof val === 'number' || typeof val === 'function') {
    return isRequired
  } else if (typeof val === 'boolean') {
    return val === isRequired
  } else if (typeof val === 'string') {
    return isRequired ? (val.length > 0) : (val.length <= 0)
  } else if (val !== null && typeof val === 'object') {
    return isRequired ? (Object.keys(val).length > 0) : (Object.keys(val).length <= 0)
  } else if (val === null || val === undefined) {
    return !isRequired
  } else {
    return !isRequired
  }
}
1030567
function (callback) {
		callbacks.fail.push(function () {
			var result = callback.apply(this, arguments);
			if (result) {
				failMessage(result);
			}
		});
		return execute;
	}
87942
function(request, options){
                if(typeof options == "undefined") options = {}; // define options if not yet defined
                options.relative_path_root = relative_path_root; // overwrite user defined rel path root - TODO - make this a private property
                return require_function(request, options);
            }