Wraps a generator or promise-returning callback function
176219
function ko(fn, isParamHandler) {
	// handlers and middlewares may have safeguard properties to be skipped
	if ('$$koified' in fn) {
		return fn;
	}

	let handler = function (req, res, next) {
		let argsLength = arguments.length;
		let args = new Array(argsLength);

		for (let i = 0; i < argsLength; i++) {
			args[i] = arguments[i];
		}

		return ko.ifyHandler(fn, args);
	};

	let errHandler = function (err, req, res, next) {
		let argsLength = arguments.length;
		let args = new Array(argsLength);

		for (let i = 0; i < argsLength; i++) {
			args[i] = arguments[i];
		}

		return ko.ifyHandler(fn, args, true);
	};

	let paramHandler = function (req, res, next, val) {
		let argsLength = arguments.length;
		let args = new Array(argsLength);

		for (let i = 0; i < argsLength; i++) {
			args[i] = arguments[i];
		}

		return ko.ifyHandler(fn, args);
	};

	let wrapper;

	// the way Express distinguishes error handlers from regular ones
	if (fn.length === 4) {
		wrapper = isParamHandler ? paramHandler : errHandler;
	} else {
		wrapper = handler;
	}

	// safeguard
	Object.defineProperty(wrapper, '$$koified', {
		configurable: true,
		writable: true,
		value: true
	});

	return wrapper;
}
840226
function wrapWithDispatch(asyncItems) {
  return asyncItems.map((item) => {
    const { key } = item;
    if (!key) return item;

    return {
      ...item,
      promise: (options) => {
        const { store: { dispatch } } = options;
        const next = item.promise(options);

        // NOTE: possibly refactor this with a breaking change in mind for future versions
        // we can return result of processed promise/thunk if need be
        if (isPromise(next)) {
          dispatch(load(key));
          // add action dispatchers
          next
            .then(data => dispatch(loadSuccess(key, data)))
            .catch(err => dispatch(loadFail(key, err)));
        } else if (next) {
          dispatch(loadSuccess(key, next));
        }

        return next;
      },
    };
  });
}
576
function wrap(fieldName, promise, args) {
  return promise(args).then((result) => ({
    [fieldName]: result,
  }));
}
1357210
function rebuildAsPromise(_thisObject, name, fn) {
    // if is a regular function, that has an async correspondent also make it promiseable
    if (!isFunctionAsync(_thisObject, name, fn)) {
        return function() {
            var that = this,
                args = arguments;

            return blinkts.lang.promiseCode(function() {
                return fn.apply(that, args);
            });
        };
    }

    // if it's an async function, make it promiseable.
    return function() {
		var args = Array.prototype.slice.apply(arguments),
			that = this;

		return new blinkts.lang.Promise(function(fulfill, reject) {
			args.push(function(err, r) {
				if (err) {
					reject(err);
				}

				if (arguments.length > 2) { // if the callback received multiple arguments, put them into an array.
					fulfill(Array.prototype.slice.call(arguments, 1));
				} else {
					fulfill(r);
				}
			});

			try {
				var result = fn.apply(that, args);
			} catch (e) { // if the function failed, so we don't get a chance to get our callback called.
				reject(e);
			}
		});
    };
}
977000
function(){
		var me = this,
			dispatchArguments = arguments,
			promises = []
		;

		this._promises = [];

		// A closure is needed for the callback id
		Object.keys( this._callbacks ).forEach( function( id ){

			// All the promises must be set in me._promises before trying to resolve
			// in order to make waitFor work ok
			me._promises[ id ] = me._Promise.resolve()
				.then( function(){
					return me._callbacks[ id ].apply( me, dispatchArguments );
				})
				.catch( function( err ){
					console.error( err.stack || err );
				})
			;

			promises.push( me._promises[ id ] );
		});

		//
		var dequeue = function(){
			me._dispatchQueue.shift();
			if( !me._dispatchQueue.length )
				me._currentDispatch = false;
		};

		return this._Promise.all( promises )
			.then( dequeue, dequeue )
		;
	}
375843
function wrapFn (gen) {
  if (!is.function(gen)) throw new Error('Middleware must be a function')
  if (!is.generator(gen)) return gen

  // wrap generator with raco
  var fn = raco.wrap(gen)
  return function (ctx, next) {
    fn.call(this, ctx, next)
  }
}
406364
function wrap (func) {
  return () => new Promise((resolve, reject) => {
    func()
      .then(x => resolve(x))
      .catch(err => {
        let status = _get(err, 'response.status')
        let text = _get(err, 'content.text')

        if (status || text) {
          console.warn(`API error: ${text} (${status})`)
          return resolve(null)
        }

        reject(err)
      })
  })
}
592484
def path_wrapper(func):
    

    @functools.wraps(func)
    def wrapped(node, context=None, _func=func, **kwargs):
        """wrapper function handling context"""
        if context is None:
            context = contextmod.InferenceContext()
        if context.push(node):
            return None

        yielded = set()
        generator = _func(node, context, **kwargs)
        try:
            while True:
                res = next(generator)
                # unproxy only true instance, not const, tuple, dict...
                if res.__class__.__name__ == "Instance":
                    ares = res._proxied
                else:
                    ares = res
                if ares not in yielded:
                    yield res
                    yielded.add(ares)
        except StopIteration as error:
            if error.args:
                return error.args[0]
            return None

    return wrapped
1106558
function wrapMethod(app,fn){
    //Override original express method
    return function(){
        let args = Array.prototype.slice.call(arguments)
        //Check if any middleware argument is a generator function
        for( let i=0; i<args.length; i++ ){
            //Wrap this if necessary
            args[i] = controllerWrapper(args[i])
        }
        
        //Call original method handler
        return fn.apply(app,args)
    }
}
702484
function wrap(value, callback) {
  return Promise.resolve(value).then(
    obj => {
      if (callback) {
        callback(null, obj);
      }
      return obj;
    },
    err => {
      if (callback) {
        callback(err);
      }
      throw err;
    }
  );
}
77630
function wrapFn(fn) {

  var argCount = fn.length;

  if (argCount < 2) {
    // promise style worker
    return async function(context) {
      return await fn(context);
    };
  }

  if (argCount === 2) {
    // callback style worker
    return function(context) {

      return new Promise(function(resolve, reject) {
        try {
          fn(context, function(err, data) {
            if (err) {
              reject(err);
            } else {
              resolve(data);
            }
          });
        } catch (err) {
          reject(err);
        }
      });

    };
  }

  throw new Error('expected Promise or callback style fn');
}
700569
function wrap(fn) {
  // Error handling middleware
  if (fn.length === 4) {
    return async function wrappedErrorHandler(error, req, res, next) {
      next = _once(next);
      try {
        await fn(error, req, res, next);
        res.headersSent ? null : next();
      } catch(err) {
        res.headersSent ? null : next(err);
      }
    };
  }

  return async function wrappedMiddleware(req, res, next) {
    next = _once(next);
    try {
      await fn(req, res, next);
      res.headersSent ? null : next();
    } catch(err) {
      res.headersSent ? null : next(err);
    }
  };
}
205185
function wrapHandler(handler) {
  return function (state, ...args) {
    return _.assign({}, state, handler(state, ...args));
  };
}
354086
function helperWrapper (fn, args) {
    var _this = this
    var options = args[args.length - 1]
    var hash = options.hash

    // "fn" and "inverse" return strings. They must be able to handle promises
    // just as the compiled template and partials
    options.fn = options.fn && wrap(options.fn, prepareAndResolveMarkers)
    options.inverse = options.inverse && wrap(options.inverse, prepareAndResolveMarkers)

    // If there are any promises in the helper args or in the hash,
    // the evaluation of the helper cannot start before these promises are resolved.
    var promisesInArgs = anyApplies(args, isPromiseAlike)
    var promisesInHash = anyApplies(values(hash), isPromiseAlike)

    if (!promisesInArgs && !promisesInHash) {
      // No promises in hash or args. Act a normal as possible.
      var result = fn.apply(_this, args)
      return isPromiseAlike(result) ? markers.asMarker(result) : result
    }

    var promise = deep(args).then(function (resolvedArgs) {
      // We need "markers", because we are in a new event-loop-cycle now.
      return prepareAndResolveMarkers(function () {
        return fn.apply(_this, resolvedArgs)
      })
    })
    return markers.asMarker(promise)
  }
502257
function co(gen) {
  var ctx = this;
  var args = slice.call(arguments, 1)

  // we wrap everything in a promise to avoid promise chaining,
  // which leads to memory leak errors.
  // see https://github.com/tj/co/issues/180
  return new Promise(function(resolve, reject) {
    if (typeof gen === 'function') gen = gen.apply(ctx, args);
    if (!gen || typeof gen.next !== 'function') return resolve(gen);

    onFulfilled();

    /**
     * @param {Mixed} res
     * @return {Promise}
     * @api private
     */

    function onFulfilled(res) {
      var ret;
      try {
        ret = gen.next(res);
      } catch (e) {
        return reject(e);
      }
      next(ret);
    }

    /**
     * @param {Error} err
     * @return {Promise}
     * @api private
     */

    function onRejected(err) {
      var ret;
      try {
        ret = gen.throw(err);
      } catch (e) {
        return reject(e);
      }
      next(ret);
    }

    /**
     * Get the next value in the generator,
     * return a promise.
     *
     * @param {Object} ret
     * @return {Promise}
     * @api private
     */

    function next(ret) {
      if (ret.done) return resolve(ret.value);
      var value = toPromise.call(ctx, ret.value);
      if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
      return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
        + 'but the following object was passed: "' + String(ret.value) + '"'));
    }
  });
}
306154
function (callback) {
        return new Promise((resolve, reject) => {
          this.end(result => {
            try {
              resolve(callback(result))
            } catch (err) {
              reject(err)
            }
          })
        })
      }
695437
def wrap_async(func):
    """"""
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        fut = asyncio.ensure_future(func(*args, **kwargs))
        cur = greenlet.getcurrent()
        def callback(fut):
            try:
                cur.switch(fut.result())
            except BaseException as e:
                cur.throw(e)
        fut.add_done_callback(callback)
        return cur.parent.switch()
    return wrapped