Return a reference to the currently executing Async job object
    or None if not in an Async job.
13326
def get_current_async():
    
    local_context = _local.get_local_context()

    if local_context._executing_async:
        return local_context._executing_async[-1]

    raise errors.NotInContextError('Not in an _ExecutionContext.')
452482
def _pre_job_handling(self, job):
        

        # did we reach the final address?
        if self._final_address is not None and job.addr == self._final_address:
            # our analysis should be termianted here
            l.debug("%s is viewed as a final state. Skip.", job)
            raise AngrSkipJobNotice()

        l.debug("Handling VFGJob %s", job)

        if not self._top_task:
            l.debug("No more tasks available. Skip the job.")
            raise AngrSkipJobNotice()

        assert isinstance(self._top_task, FunctionAnalysis)

        if job not in self._top_task.jobs:
            # it seems that all jobs of the top task has been done. unwind the task stack
            # make sure this job is at least recorded somewhere
            unwind_count = None
            for i, task in enumerate(reversed(self._task_stack)):
                if isinstance(task, FunctionAnalysis):
                    if job in task.jobs:
                        # nice
                        unwind_count = i

            if unwind_count is None:
                l.debug("%s is not recorded. Skip the job.", job)
                raise AngrSkipJobNotice()
            else:
                # unwind the stack till the target, unless we see any pending jobs for each new top task
                for i in range(unwind_count):
                    if isinstance(self._top_task, FunctionAnalysis):
                        # are there any pending job belonging to the current function that we should handle first?
                        pending_job_key = self._get_pending_job(self._top_task.function_address)
                        if pending_job_key is not None:
                            # ah there is
                            # analyze it first
                            self._trace_pending_job(pending_job_key)
                            l.debug("A pending job is found for function %#x. Delay %s.",
                                    self._top_task.function_address, job)
                            raise AngrDelayJobNotice()

                    task = self._task_stack.pop()

                    if not task.done:
                        l.warning("Removing an unfinished task %s. Might be a bug.", task)

                assert job in self._top_task.jobs

        # check if this is considered to be a final state
        if self._final_state_callback is not None and self._final_state_callback(job.state, job.call_stack):
            l.debug("%s.state is considered as a final state. Skip the job.", job)
            self.final_states.append(job.state)
            raise AngrSkipJobNotice()

        # increment the execution counter
        self._execution_counter[job.addr] += 1

        self._top_task.jobs.remove(job)

        # set up some essential variables and parameters
        job.call_stack_suffix = job.get_call_stack_suffix()
        job.jumpkind = 'Ijk_Boring' if job.state.history.jumpkind is None else \
            job.state.history.jumpkind

        src_block_id = job.src_block_id
        src_exit_stmt_idx = job.src_exit_stmt_idx

        addr = job.state.solver.eval(job.state.regs.ip)
        input_state = job.state
        block_id = BlockID.new(addr, job.call_stack_suffix, job.jumpkind)

        if self._tracing_times[block_id] > self._max_iterations:
            l.debug('%s has been traced too many times. Skip', job)
            raise AngrSkipJobNotice()

        self._tracing_times[block_id] += 1

        if block_id not in self._nodes:
            vfg_node = VFGNode(addr, block_id, state=input_state)
            self._nodes[block_id] = vfg_node

        else:
            vfg_node = self._nodes[block_id]

        job.vfg_node = vfg_node
        # log the current state
        vfg_node.state = input_state

        # Execute this basic block with input state, and get a new SimSuccessors instance
        # unused result var is `error_occured`
        job.sim_successors, _, restart_analysis = self._get_simsuccessors(input_state, addr)

        if restart_analysis:
            # We should restart the analysis because of something must be changed in the very initial state
            raise AngrVFGRestartAnalysisNotice()

        if job.sim_successors is None:
            # Ouch, we cannot get the SimSuccessors for some reason
            # Skip this guy
            l.debug('Cannot create SimSuccessors for %s. Skip.', job)
            raise AngrSkipJobNotice()

        self._graph_add_edge(src_block_id,
                             block_id,
                             jumpkind=job.jumpkind,
                             src_exit_stmt_idx=src_exit_stmt_idx
                             )
1058832
def cancel_async(job_name, custom_headers:nil)
      # Send request
      promise = begin_cancel_async(job_name, custom_headers:custom_headers)

      promise = promise.then do |response|
        # Defining deserialization method.
        deserialize_method = lambda do |parsed_response|
          result_mapper = Azure::RecoveryServicesSiteRecovery::Mgmt::V2016_08_10::Models::Job.mapper()
          parsed_response = @client.deserialize(result_mapper, parsed_response)
        end

        # Waiting for response.
        @client.get_long_running_operation_result(response, deserialize_method)
      end

      promise
    end
1078405
def fetch_and_execute_function_to_run(self, key):
        """"""
        (driver_id, serialized_function,
         run_on_other_drivers) = self.redis_client.hmget(
             key, ["driver_id", "function", "run_on_other_drivers"])

        if (utils.decode(run_on_other_drivers) == "False"
                and self.worker.mode == ray.SCRIPT_MODE
                and driver_id != self.worker.task_driver_id.binary()):
            return

        try:
            # Deserialize the function.
            function = pickle.loads(serialized_function)
            # Run the function.
            function({"worker": self.worker})
        except Exception:
            # If an exception was thrown when the function was run, we record
            # the traceback and notify the scheduler of the failure.
            traceback_str = traceback.format_exc()
            # Log the error message.
            utils.push_error_to_driver(
                self.worker,
                ray_constants.FUNCTION_TO_RUN_PUSH_ERROR,
                traceback_str,
                driver_id=ray.DriverID(driver_id))
449914
def _nextJob(self, job, nextRound=True):
        

        jobInfo = job.info()
        assert jobInfo['state'] == 'FINISHED'

        roundEnd = False
        if jobInfo['type'] == 'INJECT':
            nextCommand = 'GENERATE'
        elif jobInfo['type'] == 'GENERATE':
            nextCommand = 'FETCH'
        elif jobInfo['type'] == 'FETCH':
            nextCommand = 'PARSE'
        elif jobInfo['type'] == 'PARSE':
            nextCommand = 'UPDATEDB'
        elif jobInfo['type'] == 'UPDATEDB':
            nextCommand = 'INVERTLINKS'
        elif jobInfo['type'] == 'INVERTLINKS':
            nextCommand = 'DEDUP'
        elif jobInfo['type'] == 'DEDUP':
            if self.enable_index:
                nextCommand = 'INDEX'
            else:
                roundEnd = True
        elif jobInfo['type'] == 'INDEX':
            roundEnd = True
        else:
            raise NutchException("Unrecognized job type {}".format(jobInfo['type']))

        if roundEnd:
            if nextRound and self.currentRound < self.totalRounds:
                nextCommand = 'GENERATE'
                self.currentRound += 1
            else:
                return None

        return self.jobClient.create(nextCommand)
439342
def first(self, timeout=None):
        
        while True:
            with self._jobfinished:
                if self._results or not self._jobs.unfinished_tasks:
                    break
                self._jobfinished.wait(timeout)
        return self._results[0] if self._results else None
870274
def get(self, *raw_args, **raw_kwargs):
        
        # We pass args and kwargs through a filter to allow them to be
        # converted into values that can be pickled.
        args = self.prepare_args(*raw_args)
        kwargs = self.prepare_kwargs(**raw_kwargs)

        # Build the cache key and attempt to fetch the cached item
        key = self.key(*args, **kwargs)
        item = self.cache.get(key)

        call = Call(args=raw_args, kwargs=raw_kwargs)

        if item is None:
            # Cache MISS - we can either:
            # a) fetch the data immediately, blocking execution until
            #    the fetch has finished, or
            # b) trigger an async refresh and return an empty result
            if self.should_missing_item_be_fetched_synchronously(*args, **kwargs):
                logger.debug(("Job %s with key '%s' - cache MISS - running "
                              "synchronous refresh"),
                             self.class_path, key)
                result = self.refresh(*args, **kwargs)
                return self.process_result(
                    result, call=call, cache_status=self.MISS, sync_fetch=True)

            else:
                logger.debug(("Job %s with key '%s' - cache MISS - triggering "
                              "async refresh and returning empty result"),
                             self.class_path, key)
                # To avoid cache hammering (ie lots of identical tasks
                # to refresh the same cache item), we reset the cache with an
                # empty result which will be returned until the cache is
                # refreshed.
                result = self.empty()
                self.store(key, self.timeout(*args, **kwargs), result)
                self.async_refresh(*args, **kwargs)
                return self.process_result(
                    result, call=call, cache_status=self.MISS,
                    sync_fetch=False)

        expiry, data = item
        delta = time.time() - expiry
        if delta > 0:
            # Cache HIT but STALE expiry - we can either:
            # a) fetch the data immediately, blocking execution until
            #    the fetch has finished, or
            # b) trigger a refresh but allow the stale result to be
            #    returned this time.  This is normally acceptable.
            if self.should_stale_item_be_fetched_synchronously(
                    delta, *args, **kwargs):
                logger.debug(
                    ("Job %s with key '%s' - STALE cache hit - running "
                     "synchronous refresh"),
                    self.class_path, key)
                result = self.refresh(*args, **kwargs)
                return self.process_result(
                    result, call=call, cache_status=self.STALE,
                    sync_fetch=True)

            else:
                logger.debug(
                    ("Job %s with key '%s' - STALE cache hit - triggering "
                     "async refresh and returning stale result"),
                    self.class_path, key)
                # We replace the item in the cache with a 'timeout' expiry - this
                # prevents cache hammering but guards against a 'limbo' situation
                # where the refresh task fails for some reason.
                timeout = self.timeout(*args, **kwargs)
                self.store(key, timeout, data)
                self.async_refresh(*args, **kwargs)
                return self.process_result(
                    data, call=call, cache_status=self.STALE, sync_fetch=False)
        else:
            logger.debug("Job %s with key '%s' - cache HIT", self.class_path, key)
            return self.process_result(data, call=call, cache_status=self.HIT)
585912
def process(job = nil, &block)
      return unless job ||= reserve

      job.worker = self
      working_on job
      perform(job, &block)
    ensure
      done_working
    end
153579
def go(self):
        
        DEBUG and self._name and Log.note("GO! {{name|quote}}", name=self.name)

        if self._go:
            return

        with self.lock:
            if self._go:
                return
            self._go = True

        DEBUG and self._name and Log.note("internal GO! {{name|quote}}", name=self.name)
        jobs, self.job_queue = self.job_queue, None
        threads, self.waiting_threads = self.waiting_threads, None

        if threads:
            DEBUG and self._name and Log.note("Release {{num}} threads", num=len(threads))
            for t in threads:
                t.release()

        if jobs:
            for j in jobs:
                try:
                    j()
                except Exception as e:
                    Log.warning("Trigger on Signal.go() failed!", cause=e)
1285115
def _get_async_status(self, response):
        
        if self._is_empty(response):
            return None
        body = response.json()
        return body.get('status')
144187
def enqueue(self, job):
    
    if job.queue_name():
      raise EnqueueError("job %s already queued!" % job.job_id)
    new_len = self.redis.lpush(self.queue_name, job.serialize())
    job.notify_queued(self)
    return new_len
447134
def execution_context_from_async(async):
    
    local_context = _local.get_local_context()

    if local_context._executing_async_context:
        raise errors.ContextExistsError

    execution_context = _ExecutionContext(async)
    local_context._executing_async_context = execution_context
    return execution_context
786761
async def info(self) -> Optional[JobDef]:
        
        info = await self.result_info()
        if not info:
            v = await self._redis.get(job_key_prefix + self.job_id, encoding=None)
            if v:
                info = unpickle_job(v)
        if info:
            info.score = await self._redis.zscore(queue_name, self.job_id)
        return info
882960
function getNextJob(){
  let job = null;

  while(!job && queue.size() > 0){
    let id = queue.pop().id;
    job = map[id];
  }

  return (!!job)?job:null;
}
147482
function(asyncRes, callback) {
			var jobId = asyncRes.jobID

			if (!jobId) return callback(null, asyncRes)
			else if (IODOpts.getResults) {
				IOD.result({
					jobId: jobId,
					majorVersion: IODOpts.majorVersion,
					retries: 3
				}, callback)
			}
			else {
				callback(null, asyncRes)
				pollUntilDone(jobId)
			}

		}
408851
def _get_tasks_by_queue(self):
        """"""
        task_map = {}
        _checker = None

        # Ask the persistence engine for an Async to use for checking if the
        # context is complete.
        if self._persistence_engine:
            _checker = self._persistence_engine.context_completion_checker

        for async in self._tasks:
            queue = async.get_queue()
            if _checker:
                async.update_options(_context_checker=_checker)

            task = async.to_task()
            task_map.setdefault(queue, []).append(task)

        return task_map
1112136
def queue_exc(*arg, **kw):
    """"""
    _self = arg[0]
    if not isinstance(_self, AnsibleUndefinedVariable):
        # Run for AnsibleUndefinedVariable instance
        return
    _rslt_q = None
    for stack_trace in inspect.stack():
        # Check if method to be skipped
        if stack_trace[3] in SKIP_METHODS:
            continue
        _frame = stack_trace[0]
        _locals = inspect.getargvalues(_frame).locals
        if 'self' not in _locals:
            continue
        # Check if current frame instance of worker
        if isinstance(_locals['self'], WorkerProcess):
            # Get queue to add exception
            _rslt_q = getattr(_locals['self'], '_rslt_q')
    if not _rslt_q:
        raise ValueError("No Queue found.")
    # Add interceptor exception
    _rslt_q.put(arg[3].message, interceptor=True)