Returns the total number of jobs that are scheduled for all queues.
        This function accepts datetime, timedelta instances as well as
        integers representing epoch values.
7810
def count(self, until=None):
        

        until = rationalize_until(until)
        return self.connection.zcount(self.scheduled_jobs_key, 0, until)
1252624
def list(self, request, project):
        
        MAX_JOBS_COUNT = 2000

        # make a mutable copy of these params
        filter_params = request.query_params.copy()

        # various hacks to ensure API backwards compatibility
        for param_key in filter_params.keys():
            # replace `result_set_id` with `push_id`
            if param_key.startswith('result_set_id'):
                new_param_key = param_key.replace('result_set_id', 'push_id')
                filter_params[new_param_key] = filter_params[param_key]
                del filter_params[param_key]
            # convert legacy timestamp parameters to time ones
            elif param_key in ['submit_timestamp', 'start_timestamp',
                               'end_timestamp']:
                new_param_key = param_key.replace('timestamp', 'time')
                filter_params[new_param_key] = datetime.datetime.fromtimestamp(
                    float(filter_params[param_key]))
                del filter_params[param_key]
            # sanity check 'last modified'
            elif param_key.startswith('last_modified'):
                datestr = filter_params[param_key]
                try:
                    parser.parse(datestr)
                except ValueError:
                    return Response(
                        "Invalid date value for `last_modified`: {}".format(datestr),
                        status=HTTP_400_BAD_REQUEST)

        try:
            offset = int(filter_params.get("offset", 0))
            count = int(filter_params.get("count", 10))
        except ValueError:
            return Response(
                "Invalid value for offset or count",
                status=HTTP_400_BAD_REQUEST)
        return_type = filter_params.get("return_type", "dict").lower()

        if count > MAX_JOBS_COUNT:
            msg = "Specified count exceeds API MAX_JOBS_COUNT value: {}".format(MAX_JOBS_COUNT)
            return Response({"detail": msg}, status=HTTP_400_BAD_REQUEST)

        try:
            repository = Repository.objects.get(name=project)
        except Repository.DoesNotExist:
            return Response({
                "detail": "No project with name {}".format(project)
            }, status=HTTP_404_NOT_FOUND)
        jobs = JobFilter({k: v for (k, v) in filter_params.items()},
                         queryset=Job.objects.filter(
                             repository=repository).select_related(
                                 *self._default_select_related)).qs

        response_body = self._get_job_list_response(jobs, offset, count,
                                                    return_type)
        response_body["meta"] = dict(repository=project, offset=offset,
                                     count=count)

        return Response(response_body)
838672
def count(self) -> int:
        ''''''
        counter = 0

        for pool in self._host_pools.values():
            counter += pool.count()

        return counter
85571
public Queue<PoolSchedulable> getPreemptQueue() {
    // TODO: For now, we support only one kind of scheduling.
    // Also note that FAIR is PRIORITY with equal priorities (by default)
    ScheduleComparator sPreempt = null;
    if (preemptQueue == null) {
      ScheduleComparator sc = configManager.getPoolGroupComparator(getName());
      if (sc == ScheduleComparator.PRIORITY) {
        sPreempt = ScheduleComparator.PRIORITY_PREEMPT;
      } else {
        throw new IllegalArgumentException("Unknown/misconfigured poolgroup");
      }
      preemptQueue = createPoolQueue(sPreempt);
    }
    return preemptQueue;
  }
1223745
@VisibleForTesting
    public int getCurrentTaskCount() {
        synchronized (this.queue) {
            int size = this.queue.size() + this.filterQueue.size();
            if (size > 0) {
                // Some tasks may have completed, but we haven't yet been able to clean them up.
                size -= this.queue.values().stream().filter(CompletableFuture::isDone).count();
                size -= this.filterQueue.values().stream().filter(CompletableFuture::isDone).count();
            }

            return size;
        }
    }
940000
def check_running_job_count():
    """"""
    try:
        job_list = current_k8s_batchv1_api_client.\
            list_job_for_all_namespaces()
        if len(job_list.items) > K8S_MAXIMUM_CONCURRENT_JOBS:
            return False
    except ApiException as e:
        log.error('Something went wrong while getting running job list.')
        log.error(e)
        return False
    return True
87962
def getQueueStats(self):
        
        if not self.hasQueue():
            return None
        info_dict = {}
        if self.checkVersion('1.4'):
            cmd = "queue show"
        else:
            cmd = "show queues"
        cmdresp = self.executeCommand(cmd)
        
        queue = None
        ctxt = None
        member_states = ("unknown", "not in use", "in use", "busy", "invalid", 
                         "unavailable", "ringing", "ring+inuse", "on hold", 
                         "total")
        member_state_dict = dict([(k.lower().replace(' ', '_'),0) 
                                  for k in member_states]) 
        for line in cmdresp.splitlines():
            mobj = re.match(r"([\w\-]+)\s+has\s+(\d+)\s+calls\s+"
                            r"\(max (\d+|unlimited)\)\s+in\s+'(\w+)'\s+strategy\s+"
                            r"\((.+)\),\s+W:(\d+),\s+C:(\d+),\s+A:(\d+),\s+"
                            r"SL:([\d\.]+)%\s+within\s+(\d+)s", line)
            if mobj:
                ctxt = None
                queue = mobj.group(1)
                info_dict[queue] = {}
                info_dict[queue]['queue_len'] = int(mobj.group(2))
                try:
                    info_dict[queue]['queue_maxlen'] = int(mobj.group(3))
                except ValueError:
                    info_dict[queue]['queue_maxlen'] = None
                info_dict[queue]['strategy'] = mobj.group(4)
                for tkn in mobj.group(5).split(','):
                    mobjx = re.match(r"\s*(\d+)s\s+(\w+)\s*", tkn)
                    if mobjx:
                        info_dict[queue]['avg_' + mobjx.group(2)] = int(mobjx.group(1))
                info_dict[queue]['queue_weight'] = int(mobj.group(6))
                info_dict[queue]['calls_completed'] = int(mobj.group(7))
                info_dict[queue]['calls_abandoned'] = int(mobj.group(8))
                info_dict[queue]['sla_pcent'] = float(mobj.group(9))
                info_dict[queue]['sla_cutoff'] = int(mobj.group(10))
                info_dict[queue]['members'] = member_state_dict.copy() 
                continue
            mobj = re.match('\s+(Members|Callers):\s*$', line)
            if mobj:
                ctxt = mobj.group(1).lower()
                continue
            if ctxt == 'members':
                mobj = re.match(r"\s+\S.*\s\((.*)\)\s+has\s+taken.*calls", line)
                if mobj:
                    info_dict[queue]['members']['total'] += 1
                    state = mobj.group(1).lower().replace(' ', '_')
                    if info_dict[queue]['members'].has_key(state):
                        info_dict[queue]['members'][state] += 1
                    else:
                        raise AttributeError("Undefined queue member state %s"
                                             % state)
                    continue
        return info_dict
158785
def queue_raw_jobs(queue, params_list, **kwargs):
    

    from .queue import Queue
    queue_obj = Queue(queue)
    queue_obj.enqueue_raw_jobs(params_list, **kwargs)
1030385
private int countTasksShouldPreempt() {
    int tasksToPreempt = 0;
    long now = ClusterManager.clock.getTime();
    for (PoolGroupSchedulable poolGroup : poolGroupManager.getPoolGroups()) {
      for (PoolSchedulable pool : poolGroup.getPools()) {
        if (pool.isStarving(now)) {
          tasksToPreempt +=
            Math.min(pool.getPending(), pool.getShare() - pool.getGranted());
        }
      }
    }
    return tasksToPreempt;
  }
402481
@Override
    public int getNumberOfJobs() throws JobPersistenceException {
        return  doWithLock(new LockCallback<Integer>() {
            @Override
            public Integer doWithLock(JedisCommands jedis) throws JobPersistenceException {
                return storage.getNumberOfJobs(jedis);
            }
        }, "Could not get number of jobs.");
    }
1033315
int getTotalCount() {
    int ret = 0; 
    for (RaidMissingBlocksPerCodec queue : queues.values()) {
      ret += queue.getTotalCount();
    }
    return ret;
  }
1074281
def count(self):
        
        self.log.info("Running 'count'")
        retvals = {}

        # Numbers of 'tasks'
        num_tasks = self._count_tasks()
        retvals['num_tasks'] = num_tasks

        # Numbers of 'files'
        num_files = self._count_repo_files()
        retvals['num_files'] = num_files

        return retvals
962923
def n_weekends(self) -> int:
        
        startdate = self.start.date()
        enddate = self.end.date()
        ndays = (enddate - startdate).days + 1
        in_weekend = False
        n_weekends = 0
        for i in range(ndays):
            date = startdate + datetime.timedelta(days=i)
            if not in_weekend and is_weekend(date):
                in_weekend = True
                n_weekends += 1
            elif in_weekend and not is_weekend(date):
                in_weekend = False
        return n_weekends
1145609
async def all_job_results(self) -> List[JobResult]:
        
        keys = await self.keys(result_key_prefix + '*')
        results = await asyncio.gather(*[self._get_job_result(k) for k in keys])
        return sorted(results, key=attrgetter('enqueue_time'))
456062
def len(self, queue_name):
        
        try:
            stats = self.conn.stats_tube(queue_name)
        except beanstalkc.CommandFailed as err:
            if err[1] == 'NOT_FOUND':
                return 0

            raise

        return stats.get('current-jobs-ready', 0)
635629
def inspect_periodic_tasks(self) -> List[Tuple[int, str]]:
        
        return [(int(e[0]), e[3][0].name) for e in self._scheduler.queue]
827501
def jobs(self):
        
        if self._job_manager is None:
            self._job_manager = JobManager(session=self._session)
        return self._job_manager