Scheduling block detail resource.
516973
def get(block_id):
    """"""
    try:
        sbi_details = DB.get_block_details([block_id]).__next__()
        sbi_details['processing_blocks'] = []
        pb_ids = sbi_details['processing_block_ids']
        for pb_details in DB.get_block_details(pb_ids):
            sbi_details['processing_blocks'].append(pb_details)
        del sbi_details['processing_block_ids']
        response = sbi_details
        _url = get_root_url()
        response['links'] = {
            'scheduling-blocks': '{}/scheduling-blocks'.format(_url),
            'home': '{}'.format(_url)
        }
        return sbi_details, HTTPStatus.OK

    except IndexError:
        return {'error': 'specified block id not found {}'.format(block_id)}, \
               HTTPStatus.NOT_FOUND
457590
def get():
    """"""
    LOG.debug('GET list of SBIs.')

    # Construct response object.
    _url = get_root_url()
    response = dict(scheduling_blocks=[],
                    links=dict(home='{}'.format(_url)))

    # Get ordered list of SBI ID's.
    block_ids = DB.get_sched_block_instance_ids()

    # Loop over SBIs and add summary of each to the list of SBIs in the
    # response.
    for block in DB.get_block_details(block_ids):
        block_id = block['id']
        LOG.debug('Adding SBI %s to list', block_id)
        LOG.debug(block)

        block['num_processing_blocks'] = len(block['processing_block_ids'])

        temp = ['OK'] * 10 + ['WAITING'] * 4 + ['FAILED'] * 2
        block['status'] = choice(temp)
        try:
            del block['processing_block_ids']
        except KeyError:
            pass
        block['links'] = {
            'detail': '{}/scheduling-block/{}' .format(_url, block_id)
        }
        response['scheduling_blocks'].append(block)
    return response, HTTPStatus.OK
1152599
int computeReplicationWorkForBlocks(List<List<BlockInfo>> blocksToReplicate) {
    int requiredReplication, numEffectiveReplicas, priority;
    List<DatanodeDescriptor> containingNodes;
    DatanodeDescriptor srcNode;
    INodeFile fileINode = null;

    int scheduledWork = 0;
    List<ReplicationWork> work = new LinkedList<ReplicationWork>();

    writeLock();
    try {
      synchronized (neededReplications) {
        for (priority = 0; priority < blocksToReplicate.size(); priority++) {
          for (BlockInfo block : blocksToReplicate.get(priority)) {
            // block should belong to a file
            BlockInfo storedBlock = blocksMap.getBlockInfo(block);
            fileINode = (storedBlock == null) ? null : storedBlock.getINode();
            // abandoned block not belong to a file
            if (fileINode == null) {
              neededReplications.remove(block, priority); // remove from neededReplications
              replIndex[priority]--;
              continue;
            }
            requiredReplication = fileINode.getBlockReplication(storedBlock);

            // get a source data-node
            containingNodes = new ArrayList<DatanodeDescriptor>();
            NumberReplicas numReplicas = new NumberReplicas();
            srcNode = chooseSourceDatanode(block, containingNodes, numReplicas);
            if (srcNode == null) // block can not be replicated from any node
            {
              continue;
            }

            // do not schedule more if enough replicas is already pending
            numEffectiveReplicas = numReplicas.liveReplicas() +
              pendingReplications.getNumReplicas(block);
            if (numEffectiveReplicas >= requiredReplication) {
              neededReplications.remove(block, priority); // remove from neededReplications
              replIndex[priority]--;
              continue;
            }
            work.add(new ReplicationWork(block, fileINode, requiredReplication
                - numEffectiveReplicas, srcNode, containingNodes, priority));
          }
        }
      }
    } finally {
      writeUnlock();
    }

    // choose replication targets: NOT HODING THE GLOBAL LOCK
    for(ReplicationWork rw : work){
      DatanodeDescriptor targets[] = chooseTarget(rw);
      rw.targets = targets;
    }

    writeLock();
    try {
      for(ReplicationWork rw : work){
        DatanodeDescriptor[] targets = rw.targets;
        if(targets == null || targets.length == 0){
          rw.targets = null;
          continue;
        }
        if (targets.length == 1 && 
            !clusterMap.isOnSameRack(rw.srcNode, targets[0])) {
          // in case src & target are not on the same rack
          // see if there is an alternate valid source in the same rack 
          // as the target that we can use instead.
          for (DatanodeDescriptor node : rw.containingNodes) {
            if (node != rw.srcNode && 
                clusterMap.isOnSameRack(node, targets[0]) &&
                isGoodReplica(node, rw.block)) {
              rw.srcNode = node;
              break;
            }
          }
        }
        synchronized (neededReplications) {
          BlockInfo block = rw.block;
          priority = rw.priority;
          // Recheck since global lock was released
          // block should belong to a file
          BlockInfo storedBlock = blocksMap.getBlockInfo(block);
          fileINode = (storedBlock == null) ? null : storedBlock.getINode();
          // abandoned block not belong to a file
          if (fileINode == null ) {
            neededReplications.remove(block, priority); // remove from neededReplications
            rw.targets = null;
            replIndex[priority]--;
            continue;
          }
          requiredReplication = fileINode.getBlockReplication(storedBlock);

          // do not schedule more if enough replicas is already pending
          NumberReplicas numReplicas = countNodes(block);
          numEffectiveReplicas = numReplicas.liveReplicas() +
            pendingReplications.getNumReplicas(block);
          if (numEffectiveReplicas >= requiredReplication) {
            neededReplications.remove(block, priority); // remove from neededReplications
            replIndex[priority]--;
            rw.targets = null;
            continue;
          }

          // Add block to the to be replicated list
          rw.srcNode.addBlockToBeReplicated(block, targets);
          
          scheduledWork++;

          for (DatanodeDescriptor dn : targets) {
            dn.incBlocksScheduled();
          }

          // Move the block-replication into a "pending" state.
          // The reason we use 'pending' is so we can retry
          // replications that fail after an appropriate amount of time.
          pendingReplications.add(block, targets.length);
          if (NameNode.stateChangeLog.isDebugEnabled()) {
            NameNode.stateChangeLog.debug(
              "BLOCK* block " + block
                + " is moved from neededReplications to pendingReplications");
          }

          // remove from neededReplications
          if (numEffectiveReplicas + targets.length >= requiredReplication) {
            neededReplications.remove(block, priority); // remove from neededReplications
            replIndex[priority]--;
          }
        }
      }
    } finally {
      writeUnlock();
    }

    // update metrics
    updateReplicationMetrics(work);
    
    // print debug information
    if(NameNode.stateChangeLog.isInfoEnabled()){
      // log which blocks have been scheduled for replication
      for(ReplicationWork rw : work){
        // report scheduled blocks
        DatanodeDescriptor[] targets = rw.targets;
        if (targets != null && targets.length != 0) {
          StringBuffer targetList = new StringBuffer("datanode(s)");
          for (int k = 0; k < targets.length; k++) {
            targetList.append(' ');
            targetList.append(targets[k].getName());
          }
          NameNode.stateChangeLog.info(
            "BLOCK* ask "
              + rw.srcNode.getName() + " to replicate "
              + rw.block + " to " + targetList);
        }
      }
    }

    // log once per call
    if (NameNode.stateChangeLog.isDebugEnabled()) {
      NameNode.stateChangeLog.debug("BLOCK* neededReplications = "
          + neededReplications.size() + " pendingReplications = "
          + pendingReplications.size());
    }
    return scheduledWork;
  }
1189746
def get_cameras_schedule(self):
        """"""
        resource = "schedule"
        schedule_event = self.publish_and_get_event(resource)
        if schedule_event:
            return schedule_event.get('properties')

        return None
1271016
def schedule_from_proto_dicts(
        device: 'xmon_device.XmonDevice',
        ops: Iterable[Dict],
) -> Schedule:
    """"""
    scheduled_ops = []
    last_time_picos = 0
    for op in ops:
        delay_picos = 0
        if 'incremental_delay_picoseconds' in op:
            delay_picos = op['incremental_delay_picoseconds']
        time_picos = last_time_picos + delay_picos
        last_time_picos = time_picos
        xmon_op = xmon_op_from_proto_dict(op)
        scheduled_ops.append(ScheduledOperation.op_at_on(
            operation=xmon_op,
            time=Timestamp(picos=time_picos),
            device=device,
        ))
    return Schedule(device, scheduled_ops)
1213134
def set_block(fd):
    """"""
    flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
831524
def make_schedule_row(schedule_day, slot, seen_items):
    """"""
    row = ScheduleRow(schedule_day, slot)
    skip = {}
    expanding = {}
    all_items = list(slot.scheduleitem_set
                     .select_related('talk', 'page', 'venue')
                     .all())

    for item in all_items:
        if item in seen_items:
            # Inc rowspan
            seen_items[item]['rowspan'] += 1
            # Note that we need to skip this during colspan checks
            skip[item.venue] = seen_items[item]
            continue
        scheditem = {'item': item, 'rowspan': 1, 'colspan': 1}
        row.items[item.venue] = scheditem
        seen_items[item] = scheditem
        if item.expand:
            expanding[item.venue] = []

    empty = []
    expanding_right = None
    skipping = 0
    skip_item = None
    for venue in schedule_day.venues:
        if venue in skip:
            # We need to skip all the venues this item spans over
            skipping = 1
            skip_item = skip[venue]
            continue
        if venue in expanding:
            item = row.items[venue]
            for empty_venue in empty:
                row.items.pop(empty_venue)
                item['colspan'] += 1
            empty = []
            expanding_right = item
        elif venue in row.items:
            empty = []
            expanding_right = None
        elif expanding_right:
            expanding_right['colspan'] += 1
        elif skipping > 0 and skipping < skip_item['colspan']:
            skipping += 1
        else:
            skipping = 0
            empty.append(venue)
            row.items[venue] = {'item': None, 'rowspan': 1, 'colspan': 1}

    return row
1279191
def get_scheduling_block_event():
    """"""
    event = DB.rpoplpush('scheduling_block_events',
                         'scheduling_block_event_history')
    if event:
        event = json.loads(event.decode('utf-8'))
    return event
321741
def delete_scheduling_block(block_id):
    """"""
    DB.delete('scheduling_block/{}'.format(block_id))

    # Add a event to the scheduling block event list to notify
    # of a deleting a scheduling block from the db
    DB.rpush('scheduling_block_events',
             json.dumps(dict(type="deleted", id=block_id)))
272759
def gen_schedule(user, num_blocks=6, surrounding_blocks=None):
    
    no_signup_today = None
    schedule = []

    if surrounding_blocks is None:
        surrounding_blocks = EighthBlock.objects.get_upcoming_blocks(num_blocks)

    if len(surrounding_blocks) == 0:
        return None, False

    # Use select_related to reduce query count
    signups = (EighthSignup.objects.filter(user=user, scheduled_activity__block__in=surrounding_blocks).select_related(
        "scheduled_activity", "scheduled_activity__block", "scheduled_activity__activity"))
    block_signup_map = {s.scheduled_activity.block.id: s.scheduled_activity for s in signups}

    for b in surrounding_blocks:
        current_sched_act = block_signup_map.get(b.id, None)
        if current_sched_act:
            current_signup = current_sched_act.title_with_flags
            current_signup_cancelled = current_sched_act.cancelled
            current_signup_sticky = current_sched_act.activity.sticky
            rooms = current_sched_act.get_scheduled_rooms()
        else:
            current_signup = None
            current_signup_cancelled = False
            current_signup_sticky = False
            rooms = None

        # warning flag (red block text and signup link) if no signup today
        # cancelled flag (red activity text) if cancelled
        flags = "locked" if b.locked else "open"
        blk_today = b.is_today()
        if blk_today and not current_signup:
            flags += " warning"
        if current_signup_cancelled:
            flags += " cancelled warning"

        if current_signup_cancelled:
            # don't duplicate this info; already caught
            current_signup = current_signup.replace(" (Cancelled)", "")

        info = {
            "id": b.id,
            "block": b,
            "block_letter": b.block_letter,
            "current_signup": current_signup,
            "current_signup_cancelled": current_signup_cancelled,
            "current_signup_sticky": current_signup_sticky,
            "locked": b.locked,
            "date": b.date,
            "flags": flags,
            "is_today": blk_today,
            "signup_time": b.signup_time,
            "signup_time_future": b.signup_time_future,
            "rooms": rooms
        }
        schedule.append(info)

        if blk_today and not current_signup:
            no_signup_today = True

    return schedule, no_signup_today
16719
def manage_schedule(self, tag, data):
        '''
        
        '''
        func = data.get('func', None)
        name = data.get('name', None)
        schedule = data.get('schedule', None)
        where = data.get('where', None)
        persist = data.get('persist', None)

        funcs = {'delete': ('delete_job', (name, persist)),
                 'add': ('add_job', (schedule, persist)),
                 'modify': ('modify_job',
                            (name, schedule, persist)),
                 'enable': ('enable_schedule', ()),
                 'disable': ('disable_schedule', ()),
                 'enable_job': ('enable_job', (name, persist)),
                 'disable_job': ('disable_job', (name, persist)),
                 'postpone_job': ('postpone_job', (name, data)),
                 'skip_job': ('skip_job', (name, data)),
                 'reload': ('reload', (schedule,)),
                 'list': ('list', (where,)),
                 'save_schedule': ('save_schedule', ()),
                 'get_next_fire_time': ('get_next_fire_time',
                                        (name,))}

        # Call the appropriate schedule function
        try:
            alias, params = funcs.get(func)
            getattr(self.schedule, alias)(*params)
        except TypeError:
            log.error('Function "%s" is unavailable in salt.utils.scheduler',
                      func)
1333330
private void scheduleRetry() {
        Context appContext = getApplicationContext();
        long nextRetry = System.currentTimeMillis() + RetryPolicy.incrementAndGetTime(appContext);
        scheduleWingsService(appContext, nextRetry);
    }
627151
public void schedule(@NonNull Node<K, V> node) {
    Node<K, V> sentinel = findBucket(node.getVariableTime());
    link(sentinel, node);
  }
189232
def create(sub_array_id):
    """"""
    config = request.data
    config['sub_array_id'] = 'subarray-{:02d}'.format(sub_array_id)
    return add_scheduling_block(config)
860658
def processing_blocks(self):
        """"""
        pb_list = ProcessingBlockList()
        # TODO(BMo) realtime, offline etc.
        return json.dumps(dict(active=pb_list.active,
                               completed=pb_list.completed,
                               aborted=pb_list.aborted))
1231632
private void rollBlocksScheduled(long now) {
    if ((now - lastBlocksScheduledRollTime) > 
        BLOCKS_SCHEDULED_ROLL_INTERVAL) {
      prevApproxBlocksScheduled = currApproxBlocksScheduled;
      currApproxBlocksScheduled = 0;
      lastBlocksScheduledRollTime = now;
    }
  }
264293
def set_schedule(self, data):
        
        value = Schedule.build(data)
        self._conn.make_request(PROP_WRITE_HANDLE, value)