Wrap the apply_async function of multiprocessing.pools. Get the function
    that will be called and wrap it then add the opencensus context.
5212
def wrap_submit(submit_func):
    """"""

    def call(self, func, *args, **kwargs):
        wrapped_func = wrap_task_func(func)
        _tracer = execution_context.get_opencensus_tracer()
        propagator = binary_format.BinaryFormatPropagator()

        wrapped_kwargs = {}
        wrapped_kwargs["span_context_binary"] = propagator.to_header(
            _tracer.span_context
        )
        wrapped_kwargs["kwds"] = kwargs
        wrapped_kwargs["sampler"] = _tracer.sampler
        wrapped_kwargs["exporter"] = _tracer.exporter
        wrapped_kwargs["propagator"] = _tracer.propagator

        return submit_func(self, wrapped_func, *args, **wrapped_kwargs)

    return call
697202
def build_sink_async(coro=None, *, mode=None, unpack: bool = False):
    
    _mode = mode

    def _build_sink_async(coro):
        @wraps(coro)
        def _wrapper(*args, mode=None, **kwargs) -> SinkAsync:
            if 'unpack' in kwargs:
                raise TypeError('"unpack" has to be defined by decorator')
            if mode is None:
                mode = MODE.CONCURRENT if _mode is None else _mode
            return SinkAsync(coro, *args, mode=mode, unpack=unpack, **kwargs)
        return _wrapper

    if coro:
        return _build_sink_async(coro)

    return _build_sink_async
1212181
def _wrapper(self, q, start):
        
        try:
            func_name = self.fnc.__name__
        except AttributeError:
            func_name = str(self.fnc)
        logger.debug("Running \"%s\" with parameters: \"%s\":\t%s/%s"
                     % (func_name, str(self.kwargs), round(time.time() - start), self.timeout))
        try:
            result = self.fnc(**self.kwargs)
            # let's log only first 50 characters of the response
            logger.debug("callback result = %s", str(result)[:50])
            q.put(result)
        except self.expected_exceptions as ex:
            logger.debug("expected exception was caught: %s", ex)
            q.put(False)
        except Exception as ex:
            logger.debug("adding exception %s to queue", ex)
            q.put(ex)
1353517
def wrap_create_channel(create_channel_func, tracer=None):
    """"""
    def call(*args, **kwargs):
        channel = create_channel_func(*args, **kwargs)

        try:
            target = kwargs.get('target')
            tracer_interceptor = OpenCensusClientInterceptor(tracer, target)
            intercepted_channel = grpc.intercept_channel(
                channel, tracer_interceptor)
            return intercepted_channel  # pragma: NO COVER
        except Exception:
            log.warning(
                'Failed to wrap create_channel, '
                'clientlibs grpc calls not traced.')
            return channel
    return call
937801
def async_atomic(on_exception=None, raise_exception=True, **kwargs):
    '''
    
    '''
    if not raise_exception and not on_exception:
        async def default_on_exception(exc):
            resp_dict = {}
            resp_dict['status'] = type(exc)
            resp_dict['message'] = str(exc)
            return resp_dict

        on_exception = default_on_exception
    elif raise_exception and not on_exception:
        async def raise_exception(exp_args):
            raise exp_args

        on_exception = raise_exception

    _db_adapter = get_db_adapter()

    def decorator(func):
        @functools.wraps(func)
        async def wrapped(self, *args, **kwargs):
            conn = None
            for i in itertools.chain(args, kwargs.values()):
                if type(i) is Connection:
                    conn = i
                    break
            if not conn:
                pool = await _db_adapter.get_pool()
                async with pool.acquire() as conn:
                    try:
                        async with conn.transaction():
                            kwargs['conn'] = conn
                            return await func(self, *args, **kwargs)
                    except Exception as e:
                        return await on_exception(e)
            else:
                try:
                    async with conn.transaction():
                        kwargs['conn'] = conn
                        return await func(self, *args, **kwargs)
                except Exception as e:
                    return await on_exception(e)

        return wrapped

    return decorator
987016
def threadpooled(
    func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]],
    *,
    loop_getter: None = None,
    loop_getter_need_context: bool = False,
) -> typing.Callable[..., "concurrent.futures.Future[typing.Any]"]:
    """"""
171403
def ensure_async(function_original):
    

    def wrapper(*args, **kwargs):
        try:
            result = function_original(*args, **kwargs)
            if isinstance(result, Deferred):
                return result
            d = Deferred()
            d.callback(result)
            return d
        except:
            return fail()

    return wrapper
632899
async def open_async(self):
        
        self.set_pump_status("Opening")
        self.partition_context = PartitionContext(self.host, self.lease.partition_id,
                                                  self.host.eh_config.client_address,
                                                  self.host.eh_config.consumer_group,
                                                  self.loop)
        self.partition_context.lease = self.lease
        self.partition_context.event_processor_context = self.lease.event_processor_context
        self.processor = self.host.event_processor(self.host.event_processor_params)
        try:
            await self.processor.open_async(self.partition_context)
        except Exception as err:  # pylint: disable=broad-except
            # If the processor won't create or open, only thing we can do here is pass the buck.
            # Null it out so we don't try to operate on it further.
            await self.process_error_async(err)
            self.processor = None
            self.set_pump_status("OpenFailed")

        # If Open Async Didn't Fail call OnOpenAsync
        if self.pump_status == "Opening":
            await self.on_open_async()
433249
def decorate_callable(self, func):
        
        def wrapper(*args, **kwargs):
            try:
                with self:
                    result = func(*args, **kwargs)
                return result
            except DBMutexError as e:
                if self.suppress_acquisition_exceptions:
                    LOG.error(e)
                else:
                    raise e
        functools.update_wrapper(wrapper, func)
        return wrapper
108722
def add(self, task, multiprocess=False, processes=0):
        
        if self._first_task is None and hasattr(task, 'task_id'):
            self._first_task = task.task_id
        self.add_succeeded = True
        if multiprocess:
            queue = multiprocessing.Manager().Queue()
            pool = multiprocessing.Pool(processes=processes if processes > 0 else None)
        else:
            queue = DequeQueue()
            pool = SingleProcessPool()
        self._validate_task(task)
        pool.apply_async(check_complete, [task, queue])

        # we track queue size ourselves because len(queue) won't work for multiprocessing
        queue_size = 1
        try:
            seen = {task.task_id}
            while queue_size:
                current = queue.get()
                queue_size -= 1
                item, is_complete = current
                for next in self._add(item, is_complete):
                    if next.task_id not in seen:
                        self._validate_task(next)
                        seen.add(next.task_id)
                        pool.apply_async(check_complete, [next, queue])
                        queue_size += 1
        except (KeyboardInterrupt, TaskException):
            raise
        except Exception as ex:
            self.add_succeeded = False
            formatted_traceback = traceback.format_exc()
            self._log_unexpected_error(task)
            task.trigger_event(Event.BROKEN_TASK, task, ex)
            self._email_unexpected_error(task, formatted_traceback)
            raise
        finally:
            pool.close()
            pool.join()
        return self.add_succeeded
623341
def add_done_callback(self, fn):  # pylint: disable=invalid-name
        
        if self._operation.done:
            _try_callback(self, fn)
        else:
            self._queue.put(dill.dumps(fn))
            if self._process is None:
                self._process = mp.Process(target=self._execute_tasks)
                self._process.start()
408498
function applied(fn, scope) {
    if (fn.wrappedInApply) {
      return fn;
    }
    var wrapped = function() {
      var args = arguments;
      var phase = scope.$root.$$phase;
      if (phase === "$apply" || phase === "$digest") {
        return fn.apply(null, args);
      } else {
        return scope.$apply(function() {
          return fn.apply( null, args );
        });
      }
    };
    wrapped.wrappedInApply = true;
    return wrapped;
  }
1052085
def synctasklet(func):
  
  taskletfunc = tasklet(func)  # wrap at declaration time.

  @utils.wrapping(func)
  def synctasklet_wrapper(*args, **kwds):
    # pylint: disable=invalid-name
    __ndb_debug__ = utils.func_info(func)
    return taskletfunc(*args, **kwds).get_result()
  return synctasklet_wrapper
597983
def coerce_to_synchronous(func):
    '''
    
    '''
    if inspect.iscoroutinefunction(func):
        @functools.wraps(func)
        def sync_wrapper(*args, **kwargs):
            loop = asyncio.get_event_loop()
            try:
                loop.run_until_complete(func(*args, **kwargs))
            finally:
                loop.close()
        return sync_wrapper
    return func
95264
def run_in_process_pool(self, pool_size=None, func=None, *args):
        """"""
        executor = ProcessPool(pool_size)
        return self.loop.run_in_executor(executor, func, *args)
418728
def wrap_context(func):
    
    @functools.wraps(func)
    def wrapper(self, request, context):
        return func(self, request, LogFieldsContext(context))

    return wrapper
273233
def _multiprocessing_to_asyncio(in_queue, out_queue, loop):
    

    while True:
        value = in_queue.get()
        loop.call_soon_threadsafe(out_queue.put_nowait, value)