Universal functional to retrieve availability through either findtime or group booking slots
546216
function() {

    showLoadingScreen();

    calendarTarget.fullCalendar('removeEventSources');

    if (getConfig().booking.graph === 'group_customer' || getConfig().booking.graph === 'group_customer_payment') {
      // If in group bookings mode, fetch slots
      timekitGetBookingSlots();
    } else {
      // If in normal single-participant mode, call findtime
      timekitFetchAvailability();
    }

  }
1023222
def on_destination(self, *args):
        """"""
        if self.destination is None:
            Clock.schedule_once(self.on_destination, 0)
            return
        self.destination.bind(
            pos=self._trigger_repoint,
            size=self._trigger_repoint
        )
255165
function getReservation(resources, start, min, max) {
    var reservation, schedules = [], delays = {},
        maxTries = 50;

    initRanges(resources, start, schedules, delays);
    while(!(reservation = tryReservation(schedules, min, max)).success && --maxTries) {
      updateRanges(schedules, nextValidStart(schedules), delays);
    }

    reservation.delays = delays;
    return reservation;
  }
18804
def wait_for_available(self, locator):
        
        for i in range(timeout_seconds):
            try:
                if self.is_element_available(locator):
                    break
            except:
                pass
            time.sleep(1)
        else:
            raise ElementVisiblityTimeout("%s availability timed out" % locator)
        return True
255516
def availability(self):
        
        if not hasattr(self, '_availability'):
            self._availability = conf.lib.clang_getCursorAvailability(self)

        return AvailabilityKind.from_id(self._availability)
1156785
function() {

    utils.doCallback('GetBookingSlotsStarted');

    var requestData = {
      url: '/bookings/groups',
      method: 'get',
      headers: {
        'Timekit-Timezone': customerTimezone
      }
    }

    // scope group booking slots by widget ID if possible
    if (getConfig().project_id) requestData.params = {
      search: 'project.id:' + getConfig().project_id
    }

    sdk
    .makeRequest(requestData)
    .then(function(response){

      var slots = response.data.map(function(item) {
        return {
          title: item.attributes.event_info.what,
          start: item.attributes.event_info.start,
          end: item.attributes.event_info.end,
          booking: item
        }
      })

      // Make sure to sort the slots chronologically,
      // otherwise FullCalendar might skip rendering some of them
      slots.sort(function(a, b) {
        return moment(a.start) - moment(b.start);
      })

      utils.doCallback('getBookingSlotsSuccessful', response);
      hideLoadingScreen();

      // Render available timeslots in FullCalendar
      if(slots.length > 0) renderCalendarEvents(slots);

      // Render test ribbon if enabled
      if (response.headers['timekit-testmode']) renderTestModeRibbon();

    }).catch(function(response){
      utils.doCallback('getBookingSlotsFailed', response);
      hideLoadingScreen();
      triggerError(['An error with Timekit Get Booking Slots occured', response]);
    });

  }
1045963
def avail_locations(call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_locations function must be called with '
            '-f or --function, or with the --list-locations option'
        )

    ret = {}
    conn = get_conn(service='SoftLayer_Product_Package')

    locations = conn.getLocations(id=50)
    for location in locations:
        ret[location['id']] = {
            'id': location['id'],
            'name': location['name'],
            'location': location['longName'],
        }

    available = conn.getAvailableLocations(id=50)
    for location in available:
        if location.get('isAvailable', 0) is 0:
            continue
        ret[location['locationId']]['available'] = True

    return ret
853242
def get_scheduler_info():
    """"""

    scheduler = current_app.apscheduler

    d = OrderedDict([
        ('current_host', scheduler.host_name),
        ('allowed_hosts', scheduler.allowed_hosts),
        ('running', scheduler.running)
    ])

    return jsonify(d)
426681
def get_actual(cls, trip_list, time):
        
        for trip in trip_list:
            if simple_time(trip.departure_time_planned) == time:
                return trip
        return None
827116
def await_reservations(self, sc, status={}, timeout=600):
    """"""
    timespent = 0
    while not self.reservations.done():
      logging.info("waiting for {0} reservations".format(self.reservations.remaining()))
      # check status flags for any errors
      if 'error' in status:
        sc.cancelAllJobs()
        sc.stop()
        sys.exit(1)
      time.sleep(1)
      timespent += 1
      if (timespent > timeout):
        raise Exception("timed out waiting for reservations to complete")
    logging.info("all reservations completed")
    return self.reservations.get()
158321
def avail_locations(conn=None, call=None):
    '''
    
    '''
    if call == 'action':
        raise SaltCloudSystemExit(
            'The avail_locations function must be called with '
            '-f or --function, or with the --list-locations option'
        )

    if not conn:
        conn = get_conn()

    ret = {}
    locations = conn.list_locations()
    for location in locations:
        ret[location.name] = {
            'name': location.name,
            'display_name': location.display_name,
            'available_services': location.available_services,
        }
    return ret
1190752
def get_choices(timezones, grouped=False):
    """"""

    # Created a namedtuple to store the "key" for the choices_dict
    TZOffset = namedtuple('TZOffset', 'value offset_string')

    choices_dict = defaultdict(list)

    # Iterate through the timezones and populate the timezone choices
    for tz in iter(timezones):
        # Retrieve a datetime object in this time zone
        now = datetime.now(pytz.timezone(tz))

        # Retrieve the timezone offset ("-0500" / "+0500")
        offset = now.strftime("%z")

        # Retrieve the offset string ("GMT-12:00" / "GMT+12:00")
        timezone_offset_string = 'GMT{plus_minus}{hours}:{minutes}'.format(
            **TIMEZONE_OFFSET_REGEX.match(offset).groupdict()
        )

        if not grouped:
            # Format the timezone display string
            display_string = '({timezone_offset_string}) {tz}'.format(
                timezone_offset_string=timezone_offset_string,
                tz=tz,
            )
        else:
            display_string = tz

        choices_dict[
            TZOffset(value=int(offset), offset_string=timezone_offset_string)
        ].append(
            (tz, display_string)
        )

    choices = []

    for tz_offset in sorted(choices_dict, key=attrgetter('value')):
        if not grouped:
            choices.extend(
                tuple(choices_dict[tz_offset])
            )
        else:
            choices.append(
                (
                    tz_offset.offset_string,
                    tuple(choices_dict[tz_offset])
                )
            )

    # Cast the timezone choices to a tuple and return
    return tuple(choices)
939873
def query(cls, resources, time_range, query, resource_type, sampler):
        """"""
        if not isinstance(resources, (list, tuple)):
            resources = [resources]

        now = time.time()
        start_utc = datetime.utcfromtimestamp(now - time_range)
        end_utc = datetime.utcfromtimestamp(now)
        date_format = '%Y-%m-%d %H:%M:%S'
        start = start_utc.strftime(date_format)
        end = end_utc.strftime(date_format)
        query = {'start': start,
                 'end': end,
                 'query': query,
                 'resource_id': resources,
                 'resource_type': resource_type,
                 'sampler': sampler}
        return cls.call('hosting.metric.query', query)
203353
private function checkAvailability() {
		// Get the boldgrid_available transient.
		$available = get_site_transient( 'boldgrid_available' );

		// No transient was found.
		$wp_http = new WP_Http();
		$url = $this->getUrl();

		// Check that calling server is not blocked locally.
		if ( $wp_http->block_request( $url ) === false ) {
			$available = 1;
		}

		// Update the boldgrid_available transient.
		set_site_transient( 'boldgrid_available', ( int ) $available, 2 * MINUTE_IN_SECONDS );

		return $available;
	}
1226737
def book_reservation(self, sessionid, roomid, start, end):
        
        duration = int((end - start).seconds / 60)
        format = "%Y-%m-%dT%H:%M:%S-{}".format(self.get_dst_gmt_timezone())
        booking_url = "{}/reserve/{}/{}/?d={}".format(BASE_URL, roomid, start.strftime(format), duration)
        resp = requests.get(booking_url, cookies={"sessionid": sessionid})

        if resp.status_code == 403:
            return {"success": False, "error": "Your account does not have permission to book Wharton GSRs!"}

        resp.raise_for_status()

        csrfheader = re.search(r"csrftoken=(.*?);", resp.headers["Set-Cookie"]).group(1)
        csrftoken = re.search(r"<input name=\"csrfmiddlewaretoken\" type=\"hidden\" value=\"(.*?)\"/>", resp.content.decode("utf8")).group(1)

        start_string = start.strftime("%I:%M %p")
        if start_string[0] == "0":
            start_string = start_string[1:]

        resp = requests.post(
            booking_url,
            cookies={"sessionid": sessionid, "csrftoken": csrfheader},
            headers={"Referer": booking_url},
            data={
                "csrfmiddlewaretoken": csrftoken,
                "room": roomid,
                "start_time": start_string,
                "end_time": end.strftime("%a %b %d %H:%M:%S %Y"),
                "date": start.strftime("%B %d, %Y")
            }
        )
        resp.raise_for_status()
        content = resp.content.decode("utf8")
        if "errorlist" in content:
            error_msg = re.search(r"class=\"errorlist\"><li>(.*?)</li>", content).group(1)
            return {"success": False, "error": error_msg}

        return {"success": True}
617051
private void readAvailabilityTable(Resource resource, AvailabilityPeriods periods)
   {
      if (periods != null)
      {
         AvailabilityTable table = resource.getAvailability();
         List<AvailabilityPeriod> list = periods.getAvailabilityPeriod();
         for (AvailabilityPeriod period : list)
         {
            Date start = period.getAvailableFrom();
            Date end = period.getAvailableTo();
            Number units = DatatypeConverter.parseUnits(period.getAvailableUnits());
            Availability availability = new Availability(start, end, units);
            table.add(availability);
         }
         Collections.sort(table);
      }
   }
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