Call a "global" hook for an output

@param {String} name
@param {Function(Output) -> Mixed} getArgument
@param {Function(Output, result) -> Output} handleResult
@param {Output} output
@return {Promise<Output>}
195862
function callHook(name, getArgument, handleResult, output) {
    getArgument = getArgument || defaultGetArgument;
    handleResult = handleResult || defaultHandleResult;

    var logger = output.getLogger();
    var plugins = output.getPlugins();

    logger.debug.ln('calling hook "' + name + '"');

    // Create the JS context for plugins
    var context = Api.encodeGlobal(output);

    return timing.measure(
        'call.hook.' + name,

        // Get the arguments
        Promise(getArgument(output))

        // Call the hooks in serie
        .then(function(arg) {
            return Promise.reduce(plugins, function(prev, plugin) {
                var hook = plugin.getHook(name);
                if (!hook) {
                    return prev;
                }

                return hook.call(context, prev);
            }, arg);
        })

        // Handle final result
        .then(function(result) {
            output = Api.decodeGlobal(output, context);
            return handleResult(output, result);
        })
    );
}
205482
function createNextAsyncAction (actionFunc, outputs) {
  var resolver = null;
  var promise = new Promise((resolve) => resolver = resolve);
  var fn = createNextFunction(actionFunc, resolver);
  addOutputs(fn, outputs);

  return { fn, promise };
}
1359987
function (caller_args, caller_result) {
            if (!this.enabled())
                return undefined;
            var args = [];
            if (this.async()) {
                args.push(function (value) {
                    if (typeof caller_result === "function")
                        caller_result(value);
                });
            }
            args = _cs.concat(args, this.args(), caller_args);
            return this.func().apply(this.ctx(), args);
        }
1082339
def get_hook(self, name):
        
        assert isinstance(name, (str, unicode)), name
        headers, attributes = self.__requester.requestJsonAndCheck(
            "GET",
            "/hooks/" + name
        )
        return HookDescription.HookDescription(self.__requester, headers, attributes, completed=True)
1201718
function callHandler(fn, req, res, next) {
    let context = new Context(req, res);
    if (utils.isGeneratorFunction(fn)) {
        co(fn).call(context, function (err) {
            if (err || !res.terminated) {
                next(err);
            }
        });
    } else {
        fn.call(context);
        if (!res.terminated) {
            next();
        }
    }
}
867568
def call(self, name: str, *args, **kwargs):
        ''''''
        if self._event_dispatcher is not None:
            self._event_dispatcher.notify(name, *args, **kwargs)

        if self._callbacks[name]:
            return self._callbacks[name](*args, **kwargs)
        else:
            raise HookDisconnected('No callback is connected.')
280822
function handleArguments(args) {
  return new Promise(function(resolve, reject) {
    var requires = [];
    var promises = [];

    // check for Promises in args
    if (args && args instanceof Array) {
      args.some(function (arg, i) {
        if ((arg.value === null || typeof(arg.value) == 'undefined') && arg.optional) {
          return true;
        }

        if (arg.value && Array.isArray(arg.value) && arg.optional && arg.value.length == 0) {
          return true;
        }

        if (arg.type == 'string') {
          var s = '"' + arg.value.replace(/"/g, '\\\"') + '"';
          promises.push(Promise.resolve(s));
        } else if (arg.type == 'lambda') {
          promises.push(serializeLambda(arg.value));
        } else if (arg.type == 'lambdaArgs') {
          promises.push(new Promise(function(resolve, reject) {
            handleArrayArgument(arg.value).then(function (result) {
              resolve(result);
            }).catch(reject);
          }));
        } else if (arg.type == 'map') {
          promises.push(Promise.resolve(JSON.stringify(arg.value)));
        } else if (arg.type == 'promise') {
          promises.push(new Promise(function(resolve, reject) {
            arg.value.then(function(val) {
              if (typeof(val) == 'string') {
                if (isNaN(val)) {
                  // a string
                  var s = '"' + val.replace(/"/g, '\\\"') + '"';
                  resolve(s);
                } else {
                  resolve(parseFloat(val));
                }
              } else {
                resolve(val);
              }
            });
          }));
        } else if (arg.value.refIdP) {
          promises.push(arg.value.refIdP);
        } else if (arg.type == 'List') {
          promises.push(Promise.resolve(arg.value.toString()));
        } else if (arg.type == 'array') {
          // simple array argument
          promises.push(handleArrayArgument(arg.value));
        } else if (arg.type == '_eclairSerialize') {
          if (arg.value._eclairSerialize == 'staticProperty') {
            var val = arg.value.ref.name + '.' + arg.value.value;
            promises.push(Promise.resolve(val));
            requires.push({name: arg.value.ref.name, moduleLocation: arg.value.ref.moduleLocation});
          }
        } else if (Array.isArray(arg.value)) {
          // TODO: should we try to wrap the array if it isn't?
          promises.push(new Promise(function (resolve, reject) {
            handleArguments(arg.value).then(function (result) {
              if (result.requires.length > 0) {
                result.requires.forEach(function (r) {
                  requires.push(r)
                });
              }

              resolve('[' + result.args + ']');
            }).catch(reject);
          }));
        } else if (arg.type == '_eclairForceFloat') {
          var val = arg.value.value;
          if (val.toString().indexOf('.') === -1) {
            val = val.toFixed(1);
          }
          promises.push(Promise.resolve(val));
        } else if (arg.type == '_eclairLocal') {
          promises.push(Promise.resolve(arg.value._generateRemote().refIdP));
        } else if (arg.type == 'sparkclassref') {
          // we have a spark class reference, so return its name
          promises.push(Promise.resolve(arg.value.name));
          // add the class to the requires list
          requires.push({name: arg.value.name, moduleLocation: arg.value.moduleLocation});
        } else {
          promises.push(Promise.resolve(arg.value));
        }

        return false;
      });
    }

    Promise.all(promises).then(function(finalArgs) {
      resolve({args: finalArgs, requires: requires});
      //resolve(finalArgs);
    }).catch(function(e) {
      console.log(e);
      reject(e)
    });
  });
}
361519
@SuppressWarnings("unchecked")
    public <T> T getArgument(String name) {
        return (T) arguments.get(name);
    }
76879
function genWeexHandler (params, handlerCode) {
  var innerHandlerCode = handlerCode;
  var exps = params.filter(function (exp) { return simplePathRE.test(exp) && exp !== '$event'; });
  var bindings = exps.map(function (exp) { return ({ '@binding': exp }); });
  var args = exps.map(function (exp, i) {
    var key = "$_" + (i + 1);
    innerHandlerCode = innerHandlerCode.replace(exp, key);
    return key
  });
  args.push('$event');
  return '{\n' +
    "handler:function(" + (args.join(',')) + "){" + innerHandlerCode + "},\n" +
    "params:" + (JSON.stringify(bindings)) + "\n" +
    '}'
}
193680
public function applyChain($name, $hookArg = null)
    {
        $hooks = $this->app->getHooks();

        if (!isset($hooks[$name])) {
            $hooks[$name] = array(array());
        }
        if (!empty($hooks[$name])) {
            // Sort by priority, low to high, if there's more than one priority
            if (count($hooks[$name]) > 1) {
                ksort($hooks[$name]);
            }
            foreach ($hooks[$name] as $priority) {
                if (!empty($priority)) {
                    foreach ($priority as $callable) {
                        $value = call_user_func($callable, $hookArg);
                        if ($value !== null) {
                            return $value;
                        }
                    }
                }
            }
        }
    }
269715
function(name){
      var config = this._wreqrHandlers[name];

      if (!config){
        throw new Error("Handler not found for '" + name + "'");
      }

      return function(){
        var args = Array.prototype.slice.apply(arguments);
        return config.callback.apply(config.context, args);
      };
    }
555159
function Promise(callback, handler) {
			// The `handler` variable points to the function that will
			// 1) handle a .then(resolved, rejected) call
			// 2) handle a resolve or reject call (if the first argument === `is`)
			// Before 2), `handler` holds a queue of callbacks.
			// After 2), `handler` is a finalized .then handler.
			handler = function pendingHandler(resolved, rejected, value, queue, then, i) {
				queue = pendingHandler.q;

				// Case 1) handle a .then(resolved, rejected) call
				if (resolved != is) {
					return Promise(function (resolve, reject) {
						queue.push({ p: this, r: resolve, j: reject, 1: resolved, 0: rejected });
					});
				}

				// Case 2) handle a resolve or reject call
				// (`resolved` === `is` acts as a sentinel)
				// The actual function signature is
				// .re[ject|solve](<is>, success, value)

				// Check if the value is a promise and try to obtain its `then` method
				if (value && (is(func, value) | is(obj, value))) {
					try { then = value.then; }
					catch (reason) { rejected = 0; value = reason; }
				}
				// If the value is a promise, take over its state
				if (is(func, then)) {
					function valueHandler(resolved) {
						return function (value) { then && (then = 0, pendingHandler(is, resolved, value)); };
					}
					try { then.call(value, valueHandler(1), rejected = valueHandler(0)); }
					catch (reason) { rejected(reason); }
				}
				// The value is not a promise; handle resolve/reject
				else {
					// Replace this handler with a finalized resolved/rejected handler
					handler = function (Resolved, Rejected) {
						// If the Resolved or Rejected parameter is not a function,
						// return the original promise (now stored in the `callback` variable)
						if (!is(func, (Resolved = rejected ? Resolved : Rejected)))
							return callback;
						// Otherwise, return a finalized promise, transforming the value with the function
						return Promise(function (resolve, reject) { finalize(this, resolve, reject, value, Resolved); });
					};
					// Resolve/reject pending callbacks
					i = 0;
					while (i < queue.length) {
						then = queue[i++];
						// If no callback, just resolve/reject the promise
						if (!is(func, resolved = then[rejected]))
							(rejected ? then.r : then.j)(value);
						// Otherwise, resolve/reject the promise with the result of the callback
						else
							finalize(then.p, then.r, then.j, value, resolved);
					}
				}
			};
			// The queue of pending callbacks; garbage-collected when handler is resolved/rejected
			handler.q = [];

			// Create and return the promise (reusing the callback variable)
			callback.call(callback = { then:    function (resolved, rejected) { return handler(resolved, rejected); },
					"catch": function (rejected)           { return handler(0,        rejected); } },
				function (value)  { handler(is, 1,  value); },
				function (reason) { handler(is, 0, reason); });
			return callback;
		}
356647
function(name, args){
      name = arguments[0];
      args = Array.prototype.slice.call(arguments, 1);

      if (this.hasHandler(name)){
        this.getHandler(name).apply(this, args);
      } else {
        this.storage.addCommand(name, args);
      }

    }
598819
function (args) {
            args = argsToArray(arguments);
            if (this.__fired) {
                throw new Error("Already fired!");
            }
            this.__results = args;
            this.__resolve();
            return this.promise();
        }
134088
function(dbg, raFn, subName, g, name, argv_, context, outerCallback, callback) {

  var argv = _.extend({}, argv_);

  g[name] = {};

  return raFn(argv, context, function(err, result_) {
    if (err) { return sg.die(err, outerCallback, 'fetching '+name); }

    var result = subName ? result_[subName] : result_;
    if (_.isArray(result)) {
      g[name] = [];
      _.each(result, function(value) {
        g[name].push(value);
      });
    } else {
      _.each(result, function(value, key) {
        g[name][key] = value;
      });
    }

    // Get from prod
    var argv2      = _.extend({}, argv_, jsaws.getAcct('pub', process.env.JSAWS_AWS_ACCT_EXTRA_CREDS), {session:'prod'});

    return raFn(argv2, context, function(err, result_) {
      if (err) { return sg.die(err, outerCallback, 'fetching '+name); }

      var result = subName ? result_[subName] : result_;
      if (_.isArray(result)) {
        _.each(result, function(value) {
          g[name].push(value);
        });
      } else {
        _.each(result, function(value, key) {
          g[name][key] = value;
        });
      }

      return callback.apply(this, arguments);
    });
  });
}
115393
function invokeFunctionHandler(handler, args, checkArity, req, res, done) {
  // check if number of arguments provided matches the handler function arity
  if (checkArity && args.length < handler.length) { // < due to possible optionals
    done(new ModofunError(400, 'InvalidInput',
      `This operation requires ${handler.length} parameters. Received ${args.length}.`));
    return;
  }
  // set this in function call to the remaining relevant request data
  // could consider pushing the whole request object instead?
  // for now prefer to keep it to minimum to allow maximum flexibility
  const thisArg = {
    method: req.method,
    headers: req.headers,
    body: req.body,
    query: req.query,
    user: req.user
  };
  // call handler function with
  let result = handler.apply(thisArg, args);
  // handle results that are not a trusted Promise with Promise.resolve()
  // which also supports other then-ables
  if (result instanceof Promise === false) {
    result = Promise.resolve(result);
  }
  return result
    .then(value => {
      if (value === null) {
        done(new ModofunError(404, 'NullResponse', `${req.path} resource was not found`));
        return;
      }
      if (value === undefined || value === '') {
        res.status(204).end();
      } else {
        res.status(200).json(value);
      }
      done();
    })
    .catch(done);
}
954667
def output_hook(output)
      idx = output.index(COMMAND_PREFIX)
      return yield output.gsub(@prompt, '') if idx.nil?

      yield output.slice!(0, idx)
      cmd, args = output.slice(COMMAND_PREFIX.size..-1).split(' ', 2)
      # only support ruby and pry now.
      return yield output unless %w[ruby pry rsource].include?(cmd)

      args = case cmd
             when 'pry' then '__send__(:invoke_pry)'
             when 'rsource' then File.read(File.expand_path(args.strip))
             else args
             end
      args = '__send__(:invoke_pry)' if cmd == 'pry'
      # gdb by default set tty
      # hack it
      `stty opost onlcr`
      begin
        eval_context.instance_eval(args)
      rescue StandardError, ScriptError => e
        $stdout.puts("#{e.class}: #{e}")
      end
      @tube.puts('END')
      @tube.readuntil(@prompt)
      nil
    end