Add a job to an ending reservation that ends at wallTime, splitting
    the reservation if the job doesn't fill the entire timeslice.
429073
def adjustEndingReservationForJob(reservation, jobShape, wallTime):
    
    if jobShape.wallTime - wallTime < reservation.shape.wallTime:
        # This job only partially fills one of the slices. Create a new slice.
        reservation.shape, nS = split(reservation.shape, jobShape, jobShape.wallTime - wallTime)
        nS.nReservation = reservation.nReservation
        reservation.nReservation = nS
    else:
        # This job perfectly fits within the boundaries of the slices.
        reservation.subtract(jobShape)
1276986
def divide(cls, jobs, count):
        ''''''
        jobs = list(zip(*zip_longest(*[iter(jobs)] * count)))
        # If we had no jobs to resume, then we get an empty list
        jobs = jobs or [()] * count
        for index in range(count):
            # Filter out the items in jobs that are Nones
            jobs[index] = [j for j in jobs[index] if j != None]
        return jobs
313812
function requestWork(root, expirationTime) {
    addRootToSchedule(root, expirationTime);

    if (isRendering) {
      // Prevent reentrancy. Remaining work will be scheduled at the end of
      // the currently rendering batch.
      return;
    }

    if (isBatchingUpdates) {
      // Flush work at the end of the batch.
      if (isUnbatchingUpdates) {
        // ...unless we're inside unbatchedUpdates, in which case we should
        // flush it now.
        nextFlushedRoot = root;
        nextFlushedExpirationTime = Sync;
        performWorkOnRoot(root, Sync, false);
      }
      return;
    }

    // TODO: Get rid of Sync and use current time?
    if (expirationTime === Sync) {
      performSyncWork();
    } else {
      scheduleCallbackWithExpiration(expirationTime);
    }
  }
56335
def __solve_overlaps(self, start_time, end_time):
        
        if end_time is None or start_time is None:
            return

        # possible combinations and the OR clauses that catch them
        # (the side of the number marks if it catches the end or start time)
        #             |----------------- NEW -----------------|
        #      |--- old --- 1|   |2 --- old --- 1|   |2 --- old ---|
        # |3 -----------------------  big old   ------------------------ 3|
        query = """
                   SELECT a.*, b.name, c.name as category
                     FROM facts a
                LEFT JOIN activities b on b.id = a.activity_id
                LEFT JOIN categories c on b.category_id = c.id
                    WHERE (end_time > ? and end_time < ?)
                       OR (start_time > ? and start_time < ?)
                       OR (start_time < ? and end_time > ?)
                 ORDER BY start_time
                """
        conflicts = self.fetchall(query, (start_time, end_time,
                                          start_time, end_time,
                                          start_time, end_time))

        for fact in conflicts:
            # won't eliminate as it is better to have overlapping entries than loosing data
            if start_time < fact["start_time"] and end_time > fact["end_time"]:
                continue

            # split - truncate until beginning of new entry and create new activity for end
            if fact["start_time"] < start_time < fact["end_time"] and \
               fact["start_time"] < end_time < fact["end_time"]:

                logger.info("splitting %s" % fact["name"])
                # truncate until beginning of the new entry
                self.execute("""UPDATE facts
                                   SET end_time = ?
                                 WHERE id = ?""", (start_time, fact["id"]))
                fact_name = fact["name"]

                # create new fact for the end
                new_fact = Fact(fact["name"],
                                category = fact["category"],
                                description = fact["description"])
                new_fact_id = self.__add_fact(new_fact.serialized_name(), end_time, fact["end_time"])

                # copy tags
                tag_update = """INSERT INTO fact_tags(fact_id, tag_id)
                                     SELECT ?, tag_id
                                       FROM fact_tags
                                      WHERE fact_id = ?"""
                self.execute(tag_update, (new_fact_id, fact["id"])) #clone tags

            # overlap start
            elif start_time < fact["start_time"] < end_time:
                logger.info("Overlapping start of %s" % fact["name"])
                self.execute("UPDATE facts SET start_time=? WHERE id=?",
                             (end_time, fact["id"]))

            # overlap end
            elif start_time < fact["end_time"] < end_time:
                logger.info("Overlapping end of %s" % fact["name"])
                self.execute("UPDATE facts SET end_time=? WHERE id=?",
                             (start_time, fact["id"]))
595587
def close(self, end_time=None):
        
        self._check_ended()

        if end_time:
            self.end_time = end_time
        else:
            self.end_time = time.time()
        self.in_progress = False
283918
private void removeScheduledJob(UUID jobId, boolean complete) {
    ScheduledJob sched = jobs.remove(jobId);
    if (sched != null) {
      if (complete) {
        sched.notifyComplete();
        if (logger.isInfoEnabled()) {
          logger.info("Job complete (" + jobId.toString() + ")");
        }
      } else {
        sched.notifyCancelled();
        if (logger.isInfoEnabled()) {
          logger.info("Job cancelled (" + jobId.toString() + ")");
        }
      }
      jobs.remove(jobId);
      scheduler.removeJob(jobId);
      sched.classManager.release();
    }
  }
238097
function tryReservation(schedules, min,max) {
    var reservation = {success: false},
        resources = [], start, end;

    for(var i = 0, len = schedules.length; i < len; i++) {
      var schedule = schedules[i],
          range = schedule.range;

      if(!isInternal(schedule)) {
        resources.push(schedule.id);
      }

      start = !start || range[0] > start ? range[0] : start;
      end = !end || range[1] < end ? range[1] : end;
    }

    var duration = (end - start) / later.MIN;
    if(duration >= min || duration >= max) {
      duration = max && duration > max ? max : duration;
      reservation = createReservation(resources, start, duration);
    }

    return reservation;
  }
1273226
public void addJobToRunLater(Vector<AutoTask> vJobsToRunLater, AutoTask jobToAdd)
    {
        if (jobToAdd.getProperty(NO_DUPLICATE) != null)
        {
            Date timeJobToAdd = (Date)jobToAdd.getProperties().get(TIME_TO_RUN);
            for (int iIndex = 0; iIndex < vJobsToRunLater.size(); iIndex++)
            {
                AutoTask jobAtIndex = vJobsToRunLater.elementAt(iIndex);
                
                if (this.sameJob(jobAtIndex, jobToAdd))
                {
                    Date timeJobAtIndex = (Date)jobAtIndex.getProperties().get(TIME_TO_RUN);
                    if (timeJobAtIndex.getTime() > timeJobToAdd.getTime())
                    {
                        jobAtIndex.free();  // Being careful (this may have been added to application)
                        vJobsToRunLater.setElementAt(jobToAdd, iIndex); // This job is earlier, replace the one in the list
                    }
                    else
                        jobToAdd.free();
                    return;    // Either way, this duplicate has been resolved
                }
            }
        }
        // No match, add this one to the end.
        vJobsToRunLater.add(jobToAdd);
    }
819586
protected void reschedule(long minTimeoutAt) {
		if (minTimeoutAt == Long.MAX_VALUE) {
			for (PendingPromise pending : promises.values()) {
				if (pending.timeoutAt > 0 && pending.timeoutAt < minTimeoutAt) {
					minTimeoutAt = pending.timeoutAt;
				}
			}
			long timeoutAt;
			requestStreamReadLock.lock();
			try {
				for (IncomingStream stream : requestStreams.values()) {
					timeoutAt = stream.getTimeoutAt();
					if (timeoutAt > 0 && timeoutAt < minTimeoutAt) {
						minTimeoutAt = timeoutAt;
					}
				}
			} finally {
				requestStreamReadLock.unlock();
			}
			responseStreamReadLock.lock();
			try {
				for (IncomingStream stream : responseStreams.values()) {
					timeoutAt = stream.getTimeoutAt();
					if (timeoutAt > 0 && timeoutAt < minTimeoutAt) {
						minTimeoutAt = timeoutAt;
					}
				}
			} finally {
				responseStreamReadLock.unlock();
			}
		}
		long now = System.currentTimeMillis();
		if (minTimeoutAt == Long.MAX_VALUE) {
			ScheduledFuture<?> t = callTimeoutTimer.get();
			if (t != null) {
				if (prevTimeoutAt.get() > now) {
					t.cancel(false);
					prevTimeoutAt.set(0);
				} else {
					callTimeoutTimer.set(null);
					prevTimeoutAt.set(0);
				}
			}
		} else {
			minTimeoutAt = (minTimeoutAt / 100 * 100) + 100;
			long prev = prevTimeoutAt.getAndSet(minTimeoutAt);
			if (prev == minTimeoutAt) {

				// Next when not changed
				return;
			}

			// Stop previous timer
			ScheduledFuture<?> t = callTimeoutTimer.get();
			if (t != null) {
				t.cancel(false);
			}

			// Schedule next timeout timer
			long delay = Math.max(10, minTimeoutAt - now);
			callTimeoutTimer.set(scheduler.schedule(this::checkTimeouts, delay, TimeUnit.MILLISECONDS));
		}
	}
276448
def add_job(self, data, persist=True):
        '''
        
        '''

        # we don't do any checking here besides making sure its a dict.
        # eval() already does for us and raises errors accordingly
        if not isinstance(data, dict):
            raise ValueError('Scheduled jobs have to be of type dict.')
        if not len(data) == 1:
            raise ValueError('You can only schedule one new job at a time.')

        # if enabled is not included in the job,
        # assume job is enabled.
        for job in data:
            if 'enabled' not in data[job]:
                data[job]['enabled'] = True

        new_job = next(six.iterkeys(data))

        if new_job in self._get_schedule(include_opts=False):
            log.warning("Cannot update job %s, it's in the pillar!", new_job)

        elif new_job in self.opts['schedule']:
            log.info('Updating job settings for scheduled job: %s', new_job)
            self.opts['schedule'].update(data)

        else:
            log.info('Added new job %s to scheduler', new_job)
            self.opts['schedule'].update(data)

        # Fire the complete event back along with updated list of schedule
        evt = salt.utils.event.get_event('minion', opts=self.opts, listen=False)
        evt.fire_event({'complete': True,
                        'schedule': self._get_schedule()},
                       tag='/salt/minion/minion_schedule_add_complete')

        if persist:
            self.persist()
198620
def setup(job, input_file_id, n, down_checkpoints):
    
    # Write the input file to the file store
    job.fileStore.logToMaster("Starting the merge sort")
    return job.addChildJobFn(down,
                             input_file_id, n,
                             down_checkpoints=down_checkpoints,
                             memory='600M').rv()
749108
def _maybe_finish_job(self, job_id):
        """"""
        job = brozzler.Job.load(self.rr, job_id)
        if not job:
            return False
        if job.status.startswith("FINISH"):
            self.logger.warn("%s is already %s", job, job.status)
            return True

        results = self.rr.table("sites").get_all(job_id, index="job_id").run()
        n = 0
        for result in results:
            site = brozzler.Site(self.rr, result)
            if not site.status.startswith("FINISH"):
                results.close()
                return False
            n += 1

        self.logger.info(
                "all %s sites finished, job %s is FINISHED!", n, job.id)
        job.finish()
        job.save()
        return True
771767
private void mergeSameDay(ProjectCalendar calendar, LinkedList<TimephasedWork> list)
   {
      LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();

      TimephasedWork previousAssignment = null;
      for (TimephasedWork assignment : list)
      {
         if (previousAssignment == null)
         {
            assignment.setAmountPerDay(assignment.getTotalAmount());
            result.add(assignment);
         }
         else
         {
            Date previousAssignmentStart = previousAssignment.getStart();
            Date previousAssignmentStartDay = DateHelper.getDayStartDate(previousAssignmentStart);
            Date assignmentStart = assignment.getStart();
            Date assignmentStartDay = DateHelper.getDayStartDate(assignmentStart);

            if (previousAssignmentStartDay.getTime() == assignmentStartDay.getTime())
            {
               Duration previousAssignmentWork = previousAssignment.getTotalAmount();
               Duration assignmentWork = assignment.getTotalAmount();

               if (previousAssignmentWork.getDuration() != 0 && assignmentWork.getDuration() == 0)
               {
                  continue;
               }

               result.removeLast();

               if (previousAssignmentWork.getDuration() != 0 && assignmentWork.getDuration() != 0)
               {
                  double work = previousAssignment.getTotalAmount().getDuration();
                  work += assignment.getTotalAmount().getDuration();
                  Duration totalWork = Duration.getInstance(work, TimeUnit.MINUTES);

                  TimephasedWork merged = new TimephasedWork();
                  merged.setStart(previousAssignment.getStart());
                  merged.setFinish(assignment.getFinish());
                  merged.setTotalAmount(totalWork);
                  assignment = merged;
               }
               else
               {
                  if (assignmentWork.getDuration() == 0)
                  {
                     assignment = previousAssignment;
                  }
               }
            }

            assignment.setAmountPerDay(assignment.getTotalAmount());
            result.add(assignment);
         }

         Duration calendarWork = calendar.getWork(assignment.getStart(), assignment.getFinish(), TimeUnit.MINUTES);
         Duration assignmentWork = assignment.getTotalAmount();
         if (calendarWork.getDuration() == 0 && assignmentWork.getDuration() == 0)
         {
            result.removeLast();
         }
         else
         {
            previousAssignment = assignment;
         }
      }

      list.clear();
      list.addAll(result);
   }
259925
public void timeSlotPruning(long curTime) {
        // if a bucket has not been accessed in a while, and it only has
        // dead entries then get rid of it
        TimeSlot slotEntry = this.firstSlot;
        TimeSlot nextSlot = null;
        int endIndex = 0;
        int i;

        while (slotEntry != null) {
            nextSlot = slotEntry.nextEntry;

            if (curTime - slotEntry.mostRecentlyAccessedTime > TIMESLOT_PRUNING_THRESHOLD) {
                endIndex = slotEntry.lastEntryIndex;

                // entries added last are more likely to be active, so
                // go from last to first
                for (i = endIndex; i >= 0; i--) {
                    if (slotEntry.entries[i].state == TimerWorkItem.ENTRY_ACTIVE) {
                        break;
                    }
                }

                if (i < 0) {
                    // no entries are active
                    removeSlot(slotEntry);
                }
            }

            slotEntry = nextSlot;
        }
    }
310593
private void addInternal(int i, Composite start, Composite end, long markedAt, int delTime)
    {
        assert i >= 0;

        if (size == capacity())
            growToFree(i);
        else if (i < size)
            moveElements(i);

        setInternal(i, start, end, markedAt, delTime);
        size++;
    }
340919
def reschedule(event)
            # Check promise is not resolved
            return if event.resolved?

            @critical.synchronize {
                # Remove the event from the scheduled list and ensure it is in the schedules set
                if @schedules.include?(event)
                    remove(event)
                else
                    @schedules << event
                end

                # optimal algorithm for inserting into an already sorted list
                Bisect.insort(@scheduled, event)

                # Update the timer
                check_timer
            }
        end
1266147
public void reserveSlots(TaskType taskType, JobInProgress job, int numSlots) {
    JobID jobId = job.getJobID();
    if (taskType == TaskType.MAP) {
      if (jobForFallowMapSlot != null && 
          !jobForFallowMapSlot.getJobID().equals(jobId)) {
        throw new RuntimeException(trackerName + " already has " + 
                                   "slots reserved for " + 
                                   jobForFallowMapSlot + "; being"  +
                                   " asked to reserve " + numSlots + " for " + 
                                   jobId);
      }

      jobForFallowMapSlot = job;
    } else if (taskType == TaskType.REDUCE){
      if (jobForFallowReduceSlot != null && 
          !jobForFallowReduceSlot.getJobID().equals(jobId)) {
        throw new RuntimeException(trackerName + " already has " + 
                                   "slots reserved for " + 
                                   jobForFallowReduceSlot + "; being"  +
                                   " asked to reserve " + numSlots + " for " + 
                                   jobId);
      }

      jobForFallowReduceSlot = job;
    }
    
    job.reserveTaskTracker(this, taskType, numSlots);
    LOG.info(trackerName + ": Reserved " + numSlots + " " + taskType + 
             " slots for " + jobId);
  }