Reserve a time slot.

        Reserves a particular time slot and return the new reservation
172016
def reserve_time_slot(self, id, cancel_existing=None, comments=None, participant_id=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - id
        """ID"""
        path["id"] = id

        # OPTIONAL - participant_id
        """User or group id for whom you are making the reservation (depends on the
        participant type). Defaults to the current user (or user's candidate group)."""
        if participant_id is not None:
            data["participant_id"] = participant_id

        # OPTIONAL - comments
        """Comments to associate with this reservation"""
        if comments is not None:
            data["comments"] = comments

        # OPTIONAL - cancel_existing
        """Defaults to false. If true, cancel any previous reservation(s) for this
        participant and appointment group."""
        if cancel_existing is not None:
            data["cancel_existing"] = cancel_existing

        self.logger.debug("POST /api/v1/calendar_events/{id}/reservations with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("POST", "/api/v1/calendar_events/{id}/reservations".format(**path), data=data, params=params, no_data=True)
825535
def schedule(self, seconds: float):
        
        def wrap(func: Callable):
            self._schedules.append(Scheduler(self.app, seconds, func))
        return wrap
40109
def find_slots(self, wanted, slots=None):
        
        if slots is None:
            slots = self.inv_slots_preferred + self.window.window_slots
        wanted = make_slot_check(wanted)

        for slot in slots:
            if wanted(slot):
                yield slot
988725
def reserve(
        self,
        session: Session,
        saving_classes: List[Type],
        item_counts: Optional[Dict[str, int]] = None,
        use_lock: bool = False,
    ) -> "PrimaryKeyGenerator":
        
        query_classes = {cls for cls in saving_classes if cls in self.QUERY_CLASSES}
        for cls in query_classes:
            if item_counts and cls.__name__ in item_counts:
                count = item_counts[cls.__name__]
            else:
                count = 1
            self._reserve_id_range(session, cls, count, use_lock)

        return self
807216
def reserve(self, timeout=None):
        """"""
        if timeout is not None:
            command = 'reserve-with-timeout %d\r\n' % timeout
        else:
            command = 'reserve\r\n'
        try:
            return self._interact_job(command,
                                      ['RESERVED'],
                                      ['DEADLINE_SOON', 'TIMED_OUT'])
        except CommandFailed:
            exc = sys.exc_info()[1]
            _, status, results = exc.args
            if status == 'TIMED_OUT':
                return None
            elif status == 'DEADLINE_SOON':
                raise DeadlineSoon(results)
1131812
public ListenableFuture<?> reserve(QueryId queryId, String allocationTag, long bytes)
    {
        checkArgument(bytes >= 0, "bytes is negative");

        ListenableFuture<?> result;
        synchronized (this) {
            if (bytes != 0) {
                queryMemoryReservations.merge(queryId, bytes, Long::sum);
                updateTaggedMemoryAllocations(queryId, allocationTag, bytes);
            }
            reservedBytes += bytes;
            if (getFreeBytes() <= 0) {
                if (future == null) {
                    future = NonCancellableMemoryFuture.create();
                }
                checkState(!future.isDone(), "future is already completed");
                result = future;
            }
            else {
                result = NOT_BLOCKED;
            }
        }

        onMemoryReserved();
        return result;
    }
144629
def reserve(self, force=False):
        

        if not force:
            try:
                self.api.call_rc('ixPortTakeOwnership {}'.format(self.uri))
            except Exception as _:
                raise TgnError('Failed to take ownership for port {} current owner is {}'.format(self, self.owner))
        else:
            self.api.call_rc('ixPortTakeOwnership {} force'.format(self.uri))
470788
def select(cls, symbol, start_date, end_date):
        """"""
        instance = cls(symbol, start_date, end_date)

        return instance.data
274846
def reserve(queue_name)
      resp = sqs.receive_message(queue_url: url_for_queue(queue_name), max_number_of_messages: 1)
      return nil unless resp.messages.any?
      Message.new queue_client: self, queue: queue_name, sqs_message: resp.messages.first
    end
145434
def reserve_job
      @log.info "Trying to reserve job for queues: #{@queues.join(', ')}"
      job = job_message_klass.reserve(@queues, reservation_details)
      @log.debug "Job: #{job.inspect}"
      raise InvalidJobReservationError.new("Invalid Job Reserved") if ! (job.nil? || job.valid?)
      job
    end
1271165
def get_reservations(self, sessionid, timeout=None):
        """"""
        url = "{}{}".format(BASE_URL, "/reservations/")
        cookies = dict(sessionid=sessionid)

        try:
            resp = requests.get(url, timeout=timeout, cookies=cookies)
        except resp.exceptions.HTTPError as error:
            raise APIError("Server Error: {}".format(error))
        except requests.exceptions.ConnectTimeout:
            raise APIError("Timeout Error")

        html = resp.content.decode("utf8")

        if "https://weblogin.pennkey.upenn.edu" in html:
            raise APIError("Wharton Auth Failed. Session ID is not valid.")

        soup = BeautifulSoup(html, "html5lib")
        reservations = []
        media = soup.find_all("div", {'class': "Media-body"})
        for res in media:
            times = res.find_all("span", {'class': "list-view-item__end-time"})
            reservation = {
                "date": res.find("span", {'class': "list-view-item__start-time u-display-block"}).get_text(),
                "startTime": times[0].get_text(),
                "endTime": times[1].get_text(),
                "location": res.find("span", {'class': "list-view-item-building"}).get_text(),
                "booking_id": int(res.find("a")['href'].split("delete/")[1][:-1])
            }
            reservations.append(reservation)
        return reservations
892595
def get(self, max=None, timeout=None, wait=None):
        
        response = self.reserve(max, timeout, wait)
        return response
628377
public function reserve($timeout = null)
    {
        if (isset($timeout)) {
            $this->_write(sprintf('reserve-with-timeout %d', $timeout));
        } else {
            $this->_write('reserve');
        }
        $status = strtok($this->_read(), ' ');

        switch ($status) {
            case 'RESERVED':
                return [
                    'id' => (integer) strtok(' '),
                    'body' => $this->_read((integer) strtok(' ')),
                ];
            case 'TIMED_OUT':
                return false;
            case 'DEADLINE_SOON':
                throw new DeadlineSoonException('Reserve failed: '.$status);
            default:
                throw new ServerException('Reserve failed: '.$status);
        }
    }
529966
def update_schedule_items(*args, **kw):
    """"""
    slot = kw.pop('instance', None)
    if not slot:
        return
    for item in slot.scheduleitem_set.all():
        item.save(update_fields=['last_updated'])
    # We also need to update the next slot, in case we changed it's
    # times as well
    next_slot = slot.slot_set.all()
    if next_slot.count():
        # From the way we structure the slot tree, we know that
        # there's only 1 next slot that could have changed.
        for item in next_slot[0].scheduleitem_set.all():
            item.save(update_fields=['last_updated'])
838767
function buildOptions(slot, appointmentType, date, bookingMap) {
    const dayStrings = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    if (slot === 'AppointmentType') {
        return [
            { text: 'cleaning (30 min)', value: 'cleaning' },
            { text: 'root canal (60 min)', value: 'root canal' },
            { text: 'whitening (30 min)', value: 'whitening' },
        ];
    } else if (slot === 'Date') {
        // Return the next five weekdays.
        const options = [];
        const potentialDate = new Date();
        while (options.length < 5) {
            potentialDate.setDate(potentialDate.getDate() + 1);
            if (potentialDate.getDay() > 0 && potentialDate.getDay() < 6) {
                options.push({ text: `${potentialDate.getMonth() + 1}-${potentialDate.getDate()} (${dayStrings[potentialDate.getDay()]})`,
                    value: potentialDate.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) });
            }
        }
        return options;
    } else if (slot === 'Time') {
        // Return the availabilities on the given date.
        if (!appointmentType || !date) {
            return null;
        }
        let availabilities = bookingMap[`${date}`];
        if (!availabilities) {
            return null;
        }
        availabilities = getAvailabilitiesForDuration(getDuration(appointmentType), availabilities);
        if (availabilities.length === 0) {
            return null;
        }
        const options = [];
        for (let i = 0; i < Math.min(availabilities.length, 5); i++) {
            options.push({ text: buildTimeOutputString(availabilities[i]), value: buildTimeOutputString(availabilities[i]) });
        }
        return options;
    }
}
789483
protected function reserve( $job ) {
		$data = array(
			'reserved_at' => $this->datetime(),
		);

		$this->database->update( $this->jobs_table, $data, array(
			'id' => $job->id(),
		) );
	}
58363
def expire(self, current_time=None):
        
        if not self._queue:
            return

        if current_time is None:
            current_time = time()

        while self._queue:
            # Get top most item
            top = self._queue[0]

            # Early exit if item was not promoted and its expiration time
            # is greater than now.
            if top.promoted is None and top.expiry_date > current_time:
                break

            # Pop item from the stack
            top = heappop(self._queue)

            need_reschedule = (top.promoted is not None
                               and top.promoted > current_time)

            # Give chance to reschedule
            if not need_reschedule:
                top.promoted = None
                top.on_delete(False)

                need_reschedule = (top.promoted is not None
                                   and top.promoted > current_time)

            # If item is promoted and expiration time somewhere in future
            # just reschedule it
            if need_reschedule:
                top.expiry_date = top.promoted
                top.promoted = None
                heappush(self._queue, top)
            else:
                del self._items[top.session_id]