itertools.imap for deferred callables
482826
def asyncImap(asyncCallable, *iterables):
    
    deferreds = imap(asyncCallable, *iterables)
    return gatherResults(deferreds, consumeErrors=True)
1311356
def call_sync(func):
    """"""

    @wraps(func)
    def wrapper(self, *args, **kw):
        """Wraps instance method to be called on loop thread"""

        # Just return when already on the event thread
        if self.thread.ident == get_ident():
            return func(self, *args, **kw)

        barrier = Barrier(2)
        result = None
        ex = None

        def call():
            """Calls function on loop thread"""
            nonlocal result, ex
            try:
                result = func(self, *args, **kw)
            except Exception as exc:
                ex = exc
            finally:
                barrier.wait()

        self.loop.call_soon_threadsafe(call)
        barrier.wait()
        if ex:
            raise ex or Exception("Unknown error")
        return result

    return wrapper
1278256
def defer(callable, trans_event, *data)
      async_call = AsyncCall.new(machine, callable, trans_event, *data)
      callback_queue.start unless callback_queue.running?
      callback_queue << async_call
    end
565598
def defer_callback(callback, *args, **kwargs):
    """"""
    start()
    global_server.ioloop.add_callback(lambda: callback(*args, **kwargs))
957938
def defer(callable):
    '''
    '''
    t = threading.Thread(target=callable)
    t.start()
    return t.join
361525
def delay_or_eager(self, *args, **kwargs):
        
        return self.async_or_eager(args=args, kwargs=kwargs)
243773
def partial_imap_1to1(func, si_func):
    
    @functools.wraps(si_func)
    def wrapper(input_):
        if not util_iter.isiterable(input_):
            return func(si_func(input_))
        else:
            return list(map(func, si_func(input_)))
    set_funcname(wrapper, util_str.get_callable_name(func) + '_mapper_' + get_funcname(si_func))
    return wrapper
489665
public static Object callIterator(Object obj, Context cx, Scriptable scope)
    {
        final Callable getIterator =
                ScriptRuntime.getElemFunctionAndThis(obj, SymbolKey.ITERATOR, cx, scope);
        final Scriptable iterable = ScriptRuntime.lastStoredScriptable(cx);
        return getIterator.call(cx, scope, iterable, ScriptRuntime.emptyArgs);
    }
957229
def _async_callable(func):
    """"""
    if isinstance(func, types.CoroutineType):

        return func

    @functools.wraps(func)
    async def _async_def_wrapper(*args, **kwargs):
        """Wrap a a sync callable in an async def."""
        return func(*args, **kwargs)

    return _async_def_wrapper
732874
def subpool_imap(pool_size, func, iterable, flatten=False, unordered=False, buffer_size=None):
  

  from .context import get_current_job, set_current_job, log

  if not pool_size:
    for args in iterable:
      yield func(*args)

  counter = itertools_count()

  current_job = get_current_job()

  def inner_func(*args):
    """ As each call to 'func' will be done in a random greenlet of the subpool, we need to
        register their IDs with set_current_job() to make get_current_job() calls work properly
        inside 'func'.
    """
    next(counter)
    if current_job:
      set_current_job(current_job)

    try:
      ret = func(*args)
    except Exception as exc:
      trace = traceback.format_exc()
      exc.subpool_traceback = trace
      raise

    if current_job:
      set_current_job(None)
    return ret

  def inner_iterable():
    """ This will be called inside the pool's main greenlet, which ID also needs to be registered """
    if current_job:
      set_current_job(current_job)

    for x in iterable:
      yield x

    if current_job:
      set_current_job(None)

  start_time = time.time()
  pool = gevent.pool.Pool(size=pool_size)

  if unordered:
    iterator = pool.imap_unordered(inner_func, inner_iterable(), maxsize=buffer_size or pool_size)
  else:
    iterator = pool.imap(inner_func, inner_iterable())

  for x in iterator:
    if flatten:
      for y in x:
        yield y
    else:
      yield x

  pool.join(raise_error=True)
  total_time = time.time() - start_time

  log.debug("SubPool ran %s greenlets in %0.6fs" % (counter, total_time))
608611
def iscallable(self, objtxt):
        """"""
        obj, valid = self._eval(objtxt)
        if valid:
            return callable(obj)
956404
def visit_Call(self, node):
        """"""
        if node in self.potential_iterator:
            matched_path = self.find_matching_builtin(node)
            if matched_path is None:
                return self.generic_visit(node)

            # Special handling for map which can't be turn to imap with None as
            # a parameter as map(None, [1, 2]) == [1, 2] while
            # list(imap(None, [1, 2])) == [(1,), (2,)]
            if (matched_path[1] == "map" and
                    MODULES["__builtin__"]["None"] in
                    self.aliases[node.args[0]]):
                return self.generic_visit(node)

            # if a dtype conversion is implied
            if matched_path[1] in ('array', 'asarray') and len(node.args) != 1:
                return self.generic_visit(node)

            path = EQUIVALENT_ITERATORS[matched_path]
            if path:
                node.func = path_to_attr(path)
                self.use_itertools |= path[0] == 'itertools'
            else:
                node = node.args[0]

            self.update = True
        return self.generic_visit(node)
66281
function IPromise(executor) {
  const self = this;
  if (!Shared.isObject(self)) {
    throw new TypeError('IPromise must be a object');
  }
  if (!Shared.isFunction(executor)) {
    throw new TypeError('executor must be a function');
  }
  this.currentState = Shared.PENDING; // default
  this.valOrErr = null; // if fulfilled result to it else rejected error to it
  this.onFulfilledCallback = []; // if current state PENDING push the func wait onFulfilled to exec
  this.onRejectedCallback = []; // if current state PENDING push the func wait onRejected to exec

  // safely executor when executor not a empty function
  if (Shared.noop !== executor) {
    safelyToExecutor(self, executor);
  }
}
500345
function deferred(mediaObject, params, prevRpc, callback) {
  var promises = [];

  if (mediaObject != undefined)
    promises.push(mediaObject);

  for (var key in params) {
    var param = params[key];
    if (param !== undefined)
      promises.push(param);
  };

  if (prevRpc != undefined)
    promises.push(prevRpc);

  return promiseCallback(Promise.all(promises), callback);
}
27802
def as_completed(objects, count=None, timeout=None):
    
    for obj in objects:
        if not hasattr(obj, 'add_done_callback'):
            raise TypeError('Expecting sequence of waitable objects')
    if count is None:
        count = len(objects)
    if count < 0 or count > len(objects):
        raise ValueError('count must be between 0 and len(objects)')
    if count == 0:
        return
    pending = list(objects)
    for obj in _wait(pending, timeout):
        yield obj
        count -= 1
        if count == 0:
            break
1031553
function iterate(iterator, callback) {
	        var self = this;

	        var promise = self.ready().then(function () {
	            var dbInfo = self._dbInfo;
	            var keyPrefix = dbInfo.keyPrefix;
	            var keyPrefixLength = keyPrefix.length;
	            var length = localStorage.length;

	            // We use a dedicated iterator instead of the `i` variable below
	            // so other keys we fetch in localStorage aren't counted in
	            // the `iterationNumber` argument passed to the `iterate()`
	            // callback.
	            //
	            // See: github.com/mozilla/localForage/pull/435#discussion_r38061530
	            var iterationNumber = 1;

	            for (var i = 0; i < length; i++) {
	                var key = localStorage.key(i);
	                if (key.indexOf(keyPrefix) !== 0) {
	                    continue;
	                }
	                var value = localStorage.getItem(key);

	                // If a result was found, parse it from the serialized
	                // string into a JS object. If result isn't truthy, the
	                // key is likely undefined and we'll pass it straight
	                // to the iterator.
	                if (value) {
	                    value = dbInfo.serializer.deserialize(value);
	                }

	                value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);

	                if (value !== void 0) {
	                    return value;
	                }
	            }
	        });

	        executeCallback(promise, callback);
	        return promise;
	    }
454730
def _raise_deferred_exc(self):
    """"""
    if self._deferred_exception:
      try:
        exc_type, exc_value, exc_traceback = self._deferred_exception
        raise_with_traceback(exc_value, exc_traceback)
      except TypeError:
        # If `_deferred_exception` isn't a 3-item tuple (raising a TypeError on the above
        # destructuring), treat it like a bare exception.
        raise self._deferred_exception