INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Ping {url} until it returns a results payload, timing out after {pings} pings and waiting {sleep} seconds between pings.
def await_results(url, pings=45, sleep=2): """ Ping {url} until it returns a results payload, timing out after {pings} pings and waiting {sleep} seconds between pings. """ print("Checking...", end="", flush=True) for _ in range(pings): # Query for check results. res = requests.p...
Copy files/directories from the check directory (:data:`check50.internal.check_dir`), to the current directory :params paths: files/directories to be copied Example usage:: check50.include("foo.txt", "bar.txt") assert os.path.exists("foo.txt") and os.path.exists("bar.txt")
def include(*paths): """ Copy files/directories from the check directory (:data:`check50.internal.check_dir`), to the current directory :params paths: files/directories to be copied Example usage:: check50.include("foo.txt", "bar.txt") assert os.path.exists("foo.txt") and os.path....
Hashes file using SHA-256. :param file: name of file to be hashed :type file: str :rtype: str :raises check50.Failure: if ``file`` does not exist
def hash(file): """ Hashes file using SHA-256. :param file: name of file to be hashed :type file: str :rtype: str :raises check50.Failure: if ``file`` does not exist """ exists(file) log(_("hashing {}...").format(file)) # https://stackoverflow.com/a/22058673 with open(fil...
Assert that all given paths exist. :params paths: files/directories to be checked for existence :raises check50.Failure: if any ``path in paths`` does not exist Example usage:: check50.exists("foo.c", "foo.h")
def exists(*paths): """ Assert that all given paths exist. :params paths: files/directories to be checked for existence :raises check50.Failure: if any ``path in paths`` does not exist Example usage:: check50.exists("foo.c", "foo.h") """ for path in paths: log(_("checking...
Import checks module given relative path. :param path: relative path from which to import checks module :type path: str :returns: the imported module :raises FileNotFoundError: if ``path / .check50.yaml`` does not exist :raises yaml.YAMLError: if ``path / .check50.yaml`` is not a valid YAML file ...
def import_checks(path): """ Import checks module given relative path. :param path: relative path from which to import checks module :type path: str :returns: the imported module :raises FileNotFoundError: if ``path / .check50.yaml`` does not exist :raises yaml.YAMLError: if ``path / .check...
Get raw representation of s, truncating if too long.
def _raw(s): """Get raw representation of s, truncating if too long.""" if isinstance(s, list): s = "\n".join(_raw(item) for item in s) if s == EOF: return "EOF" s = repr(s) # Get raw representation of string s = s[1:-1] # Strip away quotation marks if len(s) > 15: s...
Copy src to dst, copying recursively if src is a directory.
def _copy(src, dst): """Copy src to dst, copying recursively if src is a directory.""" try: shutil.copy(src, dst) except IsADirectoryError: if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) shutil.copytree(src, dst)
Send line to stdin, optionally expect a prompt. :param line: line to be send to stdin :type line: str :param prompt: boolean indicating whether a prompt is expected, if True absorbs \ all of stdout before inserting line into stdin and raises \ :clas...
def stdin(self, line, prompt=True, timeout=3): """ Send line to stdin, optionally expect a prompt. :param line: line to be send to stdin :type line: str :param prompt: boolean indicating whether a prompt is expected, if True absorbs \ all of stdout before ...
Retrieve all output from stdout until timeout (3 sec by default). If ``output`` is None, ``stdout`` returns all of the stdout outputted by the process, else it returns ``self``. :param output: optional output to be expected from stdout, raises \ :class:`check50.Failure` i...
def stdout(self, output=None, str_output=None, regex=True, timeout=3): """ Retrieve all output from stdout until timeout (3 sec by default). If ``output`` is None, ``stdout`` returns all of the stdout outputted by the process, else it returns ``self``. :param output: optional ou...
Check that the process survives for timeout. Useful for checking whether program is waiting on input. :param timeout: number of seconds to wait :type timeout: int / float :raises check50.Failure: if process ends before ``timeout``
def reject(self, timeout=1): """ Check that the process survives for timeout. Useful for checking whether program is waiting on input. :param timeout: number of seconds to wait :type timeout: int / float :raises check50.Failure: if process ends before ``timeout`` """ ...
Wait for process to exit or until timeout (5 sec by default) and asserts that process exits with ``code``. If ``code`` is ``None``, returns the code the process exited with. ..note:: In order to ensure that spawned child processes do not outlive the check that spawned them, it is good practice ...
def exit(self, code=None, timeout=5): """ Wait for process to exit or until timeout (5 sec by default) and asserts that process exits with ``code``. If ``code`` is ``None``, returns the code the process exited with. ..note:: In order to ensure that spawned child processes do not...
Load configuration file from ``check_dir / ".cs50.yaml"``, applying defaults to unspecified values. :param check_dir: directory from which to load config file :type check_dir: str / Path :rtype: dict
def load_config(check_dir): """ Load configuration file from ``check_dir / ".cs50.yaml"``, applying defaults to unspecified values. :param check_dir: directory from which to load config file :type check_dir: str / Path :rtype: dict """ # Defaults for top-level keys options = { ...
Import a file given a raw file path. :param name: Name of module to be imported :type name: str :param path: Path to Python file :type path: str / Path
def import_file(name, path): """ Import a file given a raw file path. :param name: Name of module to be imported :type name: str :param path: Path to Python file :type path: str / Path """ spec = importlib.util.spec_from_file_location(name, path) mod = importlib.util.module_from_spe...
Compile C source files. :param files: filenames to be compiled :param exe_name: name of resulting executable :param cc: compiler to use (:data:`check50.c.CC` by default) :param cflags: additional flags to pass to the compiler :raises check50.Failure: if compilation failed (i.e., if the compiler ret...
def compile(*files, exe_name=None, cc=CC, **cflags): """ Compile C source files. :param files: filenames to be compiled :param exe_name: name of resulting executable :param cc: compiler to use (:data:`check50.c.CC` by default) :param cflags: additional flags to pass to the compiler :raises ...
Run a command with valgrind. :param command: command to be run :type command: str :param env: environment in which to run command :type env: str :raises check50.Failure: if, at the end of the check, valgrind reports any errors This function works exactly like :func:`check50.run`, with the addi...
def valgrind(command, env={}): """Run a command with valgrind. :param command: command to be run :type command: str :param env: environment in which to run command :type env: str :raises check50.Failure: if, at the end of the check, valgrind reports any errors This function works exactly l...
Log and report any errors encountered by valgrind.
def _check_valgrind(xml_file): """Log and report any errors encountered by valgrind.""" log(_("checking for valgrind errors...")) # Load XML file created by valgrind xml = ET.ElementTree(file=xml_file) # Ensure that we don't get duplicate error messages. reported = set() for error in xml.i...
Context manager that runs code block until timeout is reached. Example usage:: try: with _timeout(10): do_stuff() except Timeout: print("do_stuff timed out")
def _timeout(seconds): """Context manager that runs code block until timeout is reached. Example usage:: try: with _timeout(10): do_stuff() except Timeout: print("do_stuff timed out") """ def _handle_timeout(*args): raise Timeout(seconds...
Mark function as a check. :param dependency: the check that this check depends on :type dependency: function :param timeout: maximum number of seconds the check can run :type timeout: int When a check depends on another, the former will only run if the latter passes. Additionally, the dependen...
def check(dependency=None, timeout=60): """Mark function as a check. :param dependency: the check that this check depends on :type dependency: function :param timeout: maximum number of seconds the check can run :type timeout: int When a check depends on another, the former will only run if th...
Run checks concurrently. Returns a list of CheckResults ordered by declaration order of the checks in the imported module
def run(self, files, working_area): """ Run checks concurrently. Returns a list of CheckResults ordered by declaration order of the checks in the imported module """ # Ensure that dictionary is ordered by check declaration order (via self.check_names) # NOTE: Requires CP...
Recursively skip the children of check_name (presumably because check_name did not pass).
def _skip_children(self, check_name, results): """ Recursively skip the children of check_name (presumably because check_name did not pass). """ for name, description in self.child_map[check_name]: if results[name] is None: results[name] = CheckResult(...
Append the contents of one file to another. :param original: name of file that will be appended to :type original: str :param codefile: name of file that will be appende :type codefile: str This function is particularly useful when one wants to replace a function in student code with their own...
def append_code(original, codefile): """Append the contents of one file to another. :param original: name of file that will be appended to :type original: str :param codefile: name of file that will be appende :type codefile: str This function is particularly useful when one wants to replace a...
Import a Python program given a raw file path :param path: path to python file to be imported :type path: str :raises check50.Failure: if ``path`` doesn't exist, or if the Python file at ``path`` throws an exception when imported.
def import_(path): """Import a Python program given a raw file path :param path: path to python file to be imported :type path: str :raises check50.Failure: if ``path`` doesn't exist, or if the Python file at ``path`` throws an exception when imported. """ exists(path) log(_("importing {}.....
Compile a Python program into byte code :param file: file to be compiled :raises check50.Failure: if compilation fails e.g. if there is a SyntaxError
def compile(file): """ Compile a Python program into byte code :param file: file to be compiled :raises check50.Failure: if compilation fails e.g. if there is a SyntaxError """ log(_("compiling {} into byte code...").format(file)) try: py_compile.compile(file, doraise=True) exc...
Set check50 __version__
def _set_version(): """Set check50 __version__""" global __version__ from pkg_resources import get_distribution, DistributionNotFound import os # https://stackoverflow.com/questions/17583443/what-is-the-correct-way-to-share-package-version-with-setup-py-and-the-package try: dist = get_di...
Send GET request to app. :param route: route to send request to :type route: str :param data: form data to include in request :type data: dict :param params: URL parameters to include in request :param follow_redirects: enable redirection (defaults to ``True``) :...
def get(self, route, data=None, params=None, follow_redirects=True): """Send GET request to app. :param route: route to send request to :type route: str :param data: form data to include in request :type data: dict :param params: URL parameters to include in request ...
Send POST request to app. :param route: route to send request to :type route: str :param data: form data to include in request :type data: dict :param params: URL parameters to include in request :param follow_redirects: enable redirection (defaults to ``True``) ...
def post(self, route, data=None, params=None, follow_redirects=True): """Send POST request to app. :param route: route to send request to :type route: str :param data: form data to include in request :type data: dict :param params: URL parameters to include in request ...
Check status code in response returned by application. If ``code`` is not None, assert that ``code`` is returned by application, else simply return the status code. :param code: ``code`` to assert that application returns :type code: int Example usage:: check50.fla...
def status(self, code=None): """Check status code in response returned by application. If ``code`` is not None, assert that ``code`` is returned by application, else simply return the status code. :param code: ``code`` to assert that application returns :type code: int ...
Searches for `output` regex match within content of page, regardless of mimetype.
def raw_content(self, output=None, str_output=None): """Searches for `output` regex match within content of page, regardless of mimetype.""" return self._search_page(output, str_output, self.response.data, lambda regex, content: regex.search(content.decode()))
Searches for `output` regex within HTML page. kwargs are passed to BeautifulSoup's find function to filter for tags.
def content(self, output=None, str_output=None, **kwargs): """Searches for `output` regex within HTML page. kwargs are passed to BeautifulSoup's find function to filter for tags.""" if self.response.mimetype != "text/html": raise Failure(_("expected request to return HTML, but it returned {}...
Send request of type `method` to `route`.
def _send(self, method, route, data, params, **kwargs): """Send request of type `method` to `route`.""" route = self._fmt_route(route, params) log(_("sending {} request to {}").format(method.upper(), route)) try: self.response = getattr(self._client, method.lower())(route, da...
Returns compiled check50 checks from simple YAML checks in path.
def compile(checks): """Returns compiled check50 checks from simple YAML checks in path.""" out = ["import check50"] for name, check in checks.items(): out.append(_compile_check(name, check)) return "\n\n".join(out)
Create an index of days at time ``t``, interpreted in timezone ``tz``. The returned index is localized to UTC. Parameters ---------- days : DatetimeIndex An index of dates (represented as midnight). t : datetime.time The time to apply as an offset to each day in ``days``. tz : ...
def days_at_time(days, t, tz, day_offset=0): """ Create an index of days at time ``t``, interpreted in timezone ``tz``. The returned index is localized to UTC. Parameters ---------- days : DatetimeIndex An index of dates (represented as midnight). t : datetime.time The time...
A vectorized implementation of :func:`pandas.tseries.holiday.sunday_to_monday`. Parameters ---------- dtix : pd.DatetimeIndex The index to shift sundays to mondays. Returns ------- sundays_as_mondays : pd.DatetimeIndex ``dtix`` with all sundays moved to the next monday.
def vectorized_sunday_to_monday(dtix): """A vectorized implementation of :func:`pandas.tseries.holiday.sunday_to_monday`. Parameters ---------- dtix : pd.DatetimeIndex The index to shift sundays to mondays. Returns ------- sundays_as_mondays : pd.DatetimeIndex ``dtix`` ...
If boxing day is saturday then Monday 28th is a holiday If boxing day is sunday then Tuesday 28th is a holiday
def weekend_boxing_day(start_date=None, end_date=None, observance=None): """ If boxing day is saturday then Monday 28th is a holiday If boxing day is sunday then Tuesday 28th is a holiday """ return Holiday( "Weekend Boxing Day", month=12, day=28, days_of_week=(MONDAY...
Given a list of holidays, return whether dt is a holiday or it is on a weekend.
def is_holiday_or_weekend(holidays, dt): """ Given a list of holidays, return whether dt is a holiday or it is on a weekend. """ one_day = timedelta(days=1) for h in holidays: if dt in h.dates(dt - one_day, dt + one_day) or \ dt.weekday() in WEEKENDS: return ...
If a holiday falls on a Sunday, observe it on the next non-holiday weekday. Parameters ---------- holidays : list[pd.tseries.holiday.Holiday] list of holidays dt : pd.Timestamp date of holiday.
def next_non_holiday_weekday(holidays, dt): """ If a holiday falls on a Sunday, observe it on the next non-holiday weekday. Parameters ---------- holidays : list[pd.tseries.holiday.Holiday] list of holidays dt : pd.Timestamp date of holiday. """ day_of_week = dt.weekday(...
Given arrays of opens and closes, both in nanoseconds, return an array of each minute between the opens and closes.
def compute_all_minutes(opens_in_ns, closes_in_ns): """ Given arrays of opens and closes, both in nanoseconds, return an array of each minute between the opens and closes. """ deltas = closes_in_ns - opens_in_ns # + 1 because we want 390 mins per standard day, not 389 daily_sizes = (deltas ...
Retrieves an instance of an TradingCalendar whose name is given. Parameters ---------- name : str The name of the TradingCalendar to be retrieved. Returns ------- calendar : calendars.TradingCalendar The desired calendar.
def get_calendar(self, name): """ Retrieves an instance of an TradingCalendar whose name is given. Parameters ---------- name : str The name of the TradingCalendar to be retrieved. Returns ------- calendar : calendars.TradingCalendar ...
Do we have (or have the ability to make) a calendar with ``name``?
def has_calendar(self, name): """ Do we have (or have the ability to make) a calendar with ``name``? """ return ( name in self._calendars or name in self._calendar_factories or name in self._aliases )
Registers a calendar for retrieval by the get_calendar method. Parameters ---------- name: str The key with which to register this calendar. calendar: TradingCalendar The calendar to be registered for retrieval. force : bool, optional If True,...
def register_calendar(self, name, calendar, force=False): """ Registers a calendar for retrieval by the get_calendar method. Parameters ---------- name: str The key with which to register this calendar. calendar: TradingCalendar The calendar to be...
Registers a calendar by type. This is useful for registering a new calendar to be lazily instantiated at some future point in time. Parameters ---------- name: str The key with which to register this calendar. calendar_type: type The type of the ...
def register_calendar_type(self, name, calendar_type, force=False): """ Registers a calendar by type. This is useful for registering a new calendar to be lazily instantiated at some future point in time. Parameters ---------- name: str The key with w...
Register an alias for a calendar. This is useful when multiple exchanges should share a calendar, or when there are multiple ways to refer to the same exchange. After calling ``register_alias('alias', 'real_name')``, subsequent calls to ``get_calendar('alias')`` will return the same re...
def register_calendar_alias(self, alias, real_name, force=False): """ Register an alias for a calendar. This is useful when multiple exchanges should share a calendar, or when there are multiple ways to refer to the same exchange. After calling ``register_alias('alias', 'real_n...
Resolve a calendar alias for retrieval. Parameters ---------- name : str The name of the requested calendar. Returns ------- canonical_name : str The real name of the calendar to create/return.
def resolve_alias(self, name): """ Resolve a calendar alias for retrieval. Parameters ---------- name : str The name of the requested calendar. Returns ------- canonical_name : str The real name of the calendar to create/return. ...
If a calendar is registered with the given name, it is de-registered. Parameters ---------- cal_name : str The name of the calendar to be deregistered.
def deregister_calendar(self, name): """ If a calendar is registered with the given name, it is de-registered. Parameters ---------- cal_name : str The name of the calendar to be deregistered. """ self._calendars.pop(name, None) self._calendar...
Deregisters all current registered calendars
def clear_calendars(self): """ Deregisters all current registered calendars """ self._calendars.clear() self._calendar_factories.clear() self._aliases.clear()
Returns a Series mapping each holiday (as a UTC midnight Timestamp) in ``calendar`` between ``start`` and ``end`` to that session at ``time`` (as a UTC Timestamp).
def scheduled_special_times(calendar, start, end, time, tz): """ Returns a Series mapping each holiday (as a UTC midnight Timestamp) in ``calendar`` between ``start`` and ``end`` to that session at ``time`` (as a UTC Timestamp). """ days = calendar.holidays(start, end) return pd.Series( ...
Overwrite dates in open_or_closes with corresponding dates in special_opens_or_closes, using midnight_utcs for alignment.
def _overwrite_special_dates(midnight_utcs, opens_or_closes, special_opens_or_closes): """ Overwrite dates in open_or_closes with corresponding dates in special_opens_or_closes, using midnight_utcs for alignment. """ # Short circuit when noth...
Parameters ---------- start_session: pd.Timestamp The first session. end_session: pd.Timestamp The last session. Returns ------- int: The total number of minutes for the contiguous chunk of sessions. between start_session and end_ses...
def minutes_count_for_sessions_in_range(self, start_session, end_session): """ Parameters ---------- start_session: pd.Timestamp The first session. end_session: pd.Timestamp The last session. Returns ------- int: The total number ...
Given a dt, return whether this exchange is open at the given dt. Parameters ---------- dt: pd.Timestamp The dt for which to check if this exchange is open. Returns ------- bool Whether the exchange is open on this dt.
def is_open_on_minute(self, dt): """ Given a dt, return whether this exchange is open at the given dt. Parameters ---------- dt: pd.Timestamp The dt for which to check if this exchange is open. Returns ------- bool Whether the exc...
Given a dt, returns the next open. If the given dt happens to be a session open, the next session's open will be returned. Parameters ---------- dt: pd.Timestamp The dt for which to get the next open. Returns ------- pd.Timestamp ...
def next_open(self, dt): """ Given a dt, returns the next open. If the given dt happens to be a session open, the next session's open will be returned. Parameters ---------- dt: pd.Timestamp The dt for which to get the next open. Returns ...
Given a dt, returns the next close. Parameters ---------- dt: pd.Timestamp The dt for which to get the next close. Returns ------- pd.Timestamp The UTC timestamp of the next close.
def next_close(self, dt): """ Given a dt, returns the next close. Parameters ---------- dt: pd.Timestamp The dt for which to get the next close. Returns ------- pd.Timestamp The UTC timestamp of the next close. """ ...
Given a dt, returns the previous open. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous open. Returns ------- pd.Timestamp The UTC imestamp of the previous open.
def previous_open(self, dt): """ Given a dt, returns the previous open. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous open. Returns ------- pd.Timestamp The UTC imestamp of the previous open. ...
Given a dt, returns the previous close. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous close. Returns ------- pd.Timestamp The UTC timestamp of the previous close.
def previous_close(self, dt): """ Given a dt, returns the previous close. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous close. Returns ------- pd.Timestamp The UTC timestamp of the previous close. ...
Given a dt, return the next exchange minute. If the given dt is not an exchange minute, returns the next exchange open. Parameters ---------- dt: pd.Timestamp The dt for which to get the next exchange minute. Returns ------- pd.Timestamp ...
def next_minute(self, dt): """ Given a dt, return the next exchange minute. If the given dt is not an exchange minute, returns the next exchange open. Parameters ---------- dt: pd.Timestamp The dt for which to get the next exchange minute. Returns ...
Given a dt, return the previous exchange minute. Raises KeyError if the given timestamp is not an exchange minute. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous exchange minute. Returns ------- pd.Timestamp ...
def previous_minute(self, dt): """ Given a dt, return the previous exchange minute. Raises KeyError if the given timestamp is not an exchange minute. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous exchange minute. Return...
Given a session label, returns the label of the next session. Parameters ---------- session_label: pd.Timestamp A session whose next session is desired. Returns ------- pd.Timestamp The next session label (midnight UTC). Notes --...
def next_session_label(self, session_label): """ Given a session label, returns the label of the next session. Parameters ---------- session_label: pd.Timestamp A session whose next session is desired. Returns ------- pd.Timestamp ...
Given a session label, returns the label of the previous session. Parameters ---------- session_label: pd.Timestamp A session whose previous session is desired. Returns ------- pd.Timestamp The previous session label (midnight UTC). Note...
def previous_session_label(self, session_label): """ Given a session label, returns the label of the previous session. Parameters ---------- session_label: pd.Timestamp A session whose previous session is desired. Returns ------- pd.Timestamp...
Given a session label, return the minutes for that session. Parameters ---------- session_label: pd.Timestamp (midnight UTC) A session label whose session's minutes are desired. Returns ------- pd.DateTimeIndex All the minutes for the given sessi...
def minutes_for_session(self, session_label): """ Given a session label, return the minutes for that session. Parameters ---------- session_label: pd.Timestamp (midnight UTC) A session label whose session's minutes are desired. Returns ------- ...
Given a session label, return the execution minutes for that session. Parameters ---------- session_label: pd.Timestamp (midnight UTC) A session label whose session's minutes are desired. Returns ------- pd.DateTimeIndex All the execution minutes...
def execution_minutes_for_session(self, session_label): """ Given a session label, return the execution minutes for that session. Parameters ---------- session_label: pd.Timestamp (midnight UTC) A session label whose session's minutes are desired. Returns ...
Given start and end session labels, return all the sessions in that range, inclusive. Parameters ---------- start_session_label: pd.Timestamp (midnight UTC) The label representing the first session of the desired range. end_session_label: pd.Timestamp (midnight UTC)...
def sessions_in_range(self, start_session_label, end_session_label): """ Given start and end session labels, return all the sessions in that range, inclusive. Parameters ---------- start_session_label: pd.Timestamp (midnight UTC) The label representing the fi...
Given a session label and a window size, returns a list of sessions of size `count` + 1, that either starts with the given session (if `count` is positive) or ends with the given session (if `count` is negative). Parameters ---------- session_label: pd.Timestamp ...
def sessions_window(self, session_label, count): """ Given a session label and a window size, returns a list of sessions of size `count` + 1, that either starts with the given session (if `count` is positive) or ends with the given session (if `count` is negative). Param...
Given a start and end session label, returns the distance between them. For example, for three consecutive sessions Mon., Tues., and Wed, ``session_distance(Mon, Wed)`` returns 3. If ``start_session`` is after ``end_session``, the value will be negated. Parameters ---------- ...
def session_distance(self, start_session_label, end_session_label): """ Given a start and end session label, returns the distance between them. For example, for three consecutive sessions Mon., Tues., and Wed, ``session_distance(Mon, Wed)`` returns 3. If ``start_session`` is after ...
Given start and end minutes, return all the calendar minutes in that range, inclusive. Given minutes don't need to be calendar minutes. Parameters ---------- start_minute: pd.Timestamp The minute representing the start of the desired range. end_minute: pd.T...
def minutes_in_range(self, start_minute, end_minute): """ Given start and end minutes, return all the calendar minutes in that range, inclusive. Given minutes don't need to be calendar minutes. Parameters ---------- start_minute: pd.Timestamp The min...
Returns all the minutes for all the sessions from the given start session label to the given end session label, inclusive. Parameters ---------- start_session_label: pd.Timestamp The label of the first session in the range. end_session_label: pd.Timestamp ...
def minutes_for_sessions_in_range(self, start_session_label, end_session_label): """ Returns all the minutes for all the sessions from the given start session label to the given end session label, inclusive. Par...
Returns a tuple of timestamps of the open and close of the session represented by the given label. Parameters ---------- session_label: pd.Timestamp The session whose open and close are desired. Returns ------- (Timestamp, Timestamp) The ...
def open_and_close_for_session(self, session_label): """ Returns a tuple of timestamps of the open and close of the session represented by the given label. Parameters ---------- session_label: pd.Timestamp The session whose open and close are desired. ...
Returns a DatetimeIndex representing all the minutes in this calendar.
def all_minutes(self): """ Returns a DatetimeIndex representing all the minutes in this calendar. """ opens_in_ns = self._opens.values.astype( 'datetime64[ns]', ).view('int64') closes_in_ns = self._closes.values.astype( 'datetime64[ns]', )...
Given a minute, get the label of its containing session. Parameters ---------- dt : pd.Timestamp or nanosecond offset The dt for which to get the containing session. direction: str "next" (default) means that if the given dt is not part of a session,...
def minute_to_session_label(self, dt, direction="next"): """ Given a minute, get the label of its containing session. Parameters ---------- dt : pd.Timestamp or nanosecond offset The dt for which to get the containing session. direction: str "nex...
Given a sorted DatetimeIndex of market minutes, return a DatetimeIndex of the corresponding session labels. Parameters ---------- index: pd.DatetimeIndex or pd.Series The ordered list of market minutes we want session labels for. Returns ------- pd.D...
def minute_index_to_session_labels(self, index): """ Given a sorted DatetimeIndex of market minutes, return a DatetimeIndex of the corresponding session labels. Parameters ---------- index: pd.DatetimeIndex or pd.Series The ordered list of market minutes we w...
Compute a Series of times associated with special dates. Parameters ---------- holiday_calendars : list[(datetime.time, HolidayCalendar)] Pairs of time and calendar describing when that time occurs. These are used to describe regularly-scheduled late opens or early ...
def _special_dates(self, calendars, ad_hoc_dates, start_date, end_date): """ Compute a Series of times associated with special dates. Parameters ---------- holiday_calendars : list[(datetime.time, HolidayCalendar)] Pairs of time and calendar describing when that time...
Read a text file.
def read(*paths): """Read a text file.""" basedir = os.path.dirname(__file__) fullpath = os.path.join(basedir, *paths) contents = io.open(fullpath, encoding='utf-8').read().strip() return contents
Bootstrap a processing pipeline script. ARG is either a path or a URL for some data to read from, 'hello-world' for a full working code example, or leave empty for an interactive walkthrough.
def init(arg): """Bootstrap a processing pipeline script. ARG is either a path or a URL for some data to read from, 'hello-world' for a full working code example, or leave empty for an interactive walkthrough. """ answers = {'a': 1} if arg == 'interactive': input("""Hi There! DataFlows will...
Returns a Python object decoded from the bytes of this encoding. Raises ------ ~ipfsapi.exceptions.DecodingError Parameters ---------- raw : bytes Data to be parsed Returns ------- object
def parse(self, raw): """Returns a Python object decoded from the bytes of this encoding. Raises ------ ~ipfsapi.exceptions.DecodingError Parameters ---------- raw : bytes Data to be parsed Returns ------- object ...
Incrementally decodes JSON data sets into Python objects. Raises ------ ~ipfsapi.exceptions.DecodingError Returns ------- generator
def parse_partial(self, data): """Incrementally decodes JSON data sets into Python objects. Raises ------ ~ipfsapi.exceptions.DecodingError Returns ------- generator """ try: # Python 3 requires all JSON data to be a text string ...
Raises errors for incomplete buffered data that could not be parsed because the end of the input data has been reached. Raises ------ ~ipfsapi.exceptions.DecodingError Returns ------- tuple : Always empty
def parse_finalize(self): """Raises errors for incomplete buffered data that could not be parsed because the end of the input data has been reached. Raises ------ ~ipfsapi.exceptions.DecodingError Returns ------- tuple : Always empty """ ...
Returns ``obj`` serialized as JSON formatted bytes. Raises ------ ~ipfsapi.exceptions.EncodingError Parameters ---------- obj : str | list | dict | int JSON serializable Python object Returns ------- bytes
def encode(self, obj): """Returns ``obj`` serialized as JSON formatted bytes. Raises ------ ~ipfsapi.exceptions.EncodingError Parameters ---------- obj : str | list | dict | int JSON serializable Python object Returns ------- ...
Parses the buffered data and yields the result. Raises ------ ~ipfsapi.exceptions.DecodingError Returns ------- generator
def parse_finalize(self): """Parses the buffered data and yields the result. Raises ------ ~ipfsapi.exceptions.DecodingError Returns ------- generator """ try: self._buffer.seek(0, 0) yield pickle.load(self._buffer)...
Returns ``obj`` serialized as a pickle binary string. Raises ------ ~ipfsapi.exceptions.EncodingError Parameters ---------- obj : object Serializable Python object Returns ------- bytes
def encode(self, obj): """Returns ``obj`` serialized as a pickle binary string. Raises ------ ~ipfsapi.exceptions.EncodingError Parameters ---------- obj : object Serializable Python object Returns ------- bytes "...
Translate a shell glob PATTERN to a regular expression. This is almost entirely based on `fnmatch.translate` source-code from the python 3.5 standard-library.
def glob_compile(pat): """Translate a shell glob PATTERN to a regular expression. This is almost entirely based on `fnmatch.translate` source-code from the python 3.5 standard-library. """ i, n = 0, len(pat) res = '' while i < n: c = pat[i] i = i + 1 if c == '/' and...
Gets a buffered generator for streaming files. Returns a buffered generator which encodes a file or list of files as :mimetype:`multipart/form-data` with the corresponding headers. Parameters ---------- files : str The file(s) to stream chunk_size : int Maximum size of each str...
def stream_files(files, chunk_size=default_chunk_size): """Gets a buffered generator for streaming files. Returns a buffered generator which encodes a file or list of files as :mimetype:`multipart/form-data` with the corresponding headers. Parameters ---------- files : str The file(s) ...
Gets a buffered generator for streaming directories. Returns a buffered generator which encodes a directory as :mimetype:`multipart/form-data` with the corresponding headers. Parameters ---------- directory : str The filepath of the directory to stream recursive : bool Stream a...
def stream_directory(directory, recursive=False, patterns='**', chunk_size=default_chunk_size): """Gets a buffered generator for streaming directories. Returns a buffered generator which encodes a directory as :mimetype:`multipart/form-data` wi...
Gets a buffered generator for streaming either files or directories. Returns a buffered generator which encodes the file or directory at the given path as :mimetype:`multipart/form-data` with the corresponding headers. Parameters ---------- path : str The filepath of the directory or f...
def stream_filesystem_node(path, recursive=False, patterns='**', chunk_size=default_chunk_size): """Gets a buffered generator for streaming either files or directories. Returns a buffered generator which encodes the file or direct...
Gets a buffered generator for streaming binary data. Returns a buffered generator which encodes binary data as :mimetype:`multipart/form-data` with the corresponding headers. Parameters ---------- data : bytes The data bytes to stream chunk_size : int The maximum size of each s...
def stream_bytes(data, chunk_size=default_chunk_size): """Gets a buffered generator for streaming binary data. Returns a buffered generator which encodes binary data as :mimetype:`multipart/form-data` with the corresponding headers. Parameters ---------- data : bytes The data bytes to ...
Gets a buffered generator for streaming text. Returns a buffered generator which encodes a string as :mimetype:`multipart/form-data` with the corresponding headers. Parameters ---------- text : str The data bytes to stream chunk_size : int The maximum size of each stream chunk ...
def stream_text(text, chunk_size=default_chunk_size): """Gets a buffered generator for streaming text. Returns a buffered generator which encodes a string as :mimetype:`multipart/form-data` with the corresponding headers. Parameters ---------- text : str The data bytes to stream ch...
Yields the HTTP header text for some content. Parameters ---------- headers : dict The headers to yield
def _write_headers(self, headers): """Yields the HTTP header text for some content. Parameters ---------- headers : dict The headers to yield """ if headers: for name in sorted(headers.keys()): yield name.encode("ascii") ...
Yields the opening text of a file section in multipart HTTP. Parameters ---------- fn : str Filename for the file being opened and added to the HTTP body
def file_open(self, fn): """Yields the opening text of a file section in multipart HTTP. Parameters ---------- fn : str Filename for the file being opened and added to the HTTP body """ yield b'--' yield self.boundary.encode() yield CRLF ...
Yields chunks of a file. Parameters ---------- fp : io.RawIOBase The file to break into chunks (must be an open file or have the ``readinto`` method)
def file_chunks(self, fp): """Yields chunks of a file. Parameters ---------- fp : io.RawIOBase The file to break into chunks (must be an open file or have the ``readinto`` method) """ fsize = utils.file_size(fp) offset = 0 if hasat...
Generates byte chunks of a given size. Takes a bytes generator and yields chunks of a maximum of ``chunk_size`` bytes. Parameters ---------- gen : generator The bytes generator that produces the bytes
def gen_chunks(self, gen): """Generates byte chunks of a given size. Takes a bytes generator and yields chunks of a maximum of ``chunk_size`` bytes. Parameters ---------- gen : generator The bytes generator that produces the bytes """ for dat...
Yields the body of the buffered file.
def body(self): """Yields the body of the buffered file.""" for fp, need_close in self.files: try: name = os.path.basename(fp.name) except AttributeError: name = '' for chunk in self.gen_chunks(self.envelope.file_open(name)): ...
Pre-formats the multipart HTTP request to transmit the directory.
def _prepare(self): """Pre-formats the multipart HTTP request to transmit the directory.""" names = [] added_directories = set() def add_directory(short_path): # Do not continue if this directory has already been added if short_path in added_directories: ...
Yields the encoded body.
def body(self): """Yields the encoded body.""" for chunk in self.gen_chunks(self.envelope.file_open(self.name)): yield chunk for chunk in self.gen_chunks(self.data): yield chunk for chunk in self.gen_chunks(self.envelope.file_close()): yield chunk ...
Decorator that returns a function named wrapper. When invoked, wrapper invokes func with default kwargs appended. Parameters ---------- func : callable The function to append the default kwargs to
def pass_defaults(func): """Decorator that returns a function named wrapper. When invoked, wrapper invokes func with default kwargs appended. Parameters ---------- func : callable The function to append the default kwargs to """ @functools.wraps(func) def wrapper(self, *args, *...
Makes an HTTP request to the IPFS daemon. This function returns the contents of the HTTP response from the IPFS daemon. Raises ------ ~ipfsapi.exceptions.ErrorResponse ~ipfsapi.exceptions.ConnectionError ~ipfsapi.exceptions.ProtocolError ~ipfsapi.excepti...
def request(self, path, args=[], files=[], opts={}, stream=False, decoder=None, headers={}, data=None): """Makes an HTTP request to the IPFS daemon. This function returns the contents of the HTTP response from the IPFS daemon. Raises ------ ...
Makes a request to the IPFS daemon to download a file. Downloads a file or files from IPFS into the current working directory, or the directory given by ``filepath``. Raises ------ ~ipfsapi.exceptions.ErrorResponse ~ipfsapi.exceptions.ConnectionError ~ipfsapi.ex...
def download(self, path, args=[], filepath=None, opts={}, compress=True, **kwargs): """Makes a request to the IPFS daemon to download a file. Downloads a file or files from IPFS into the current working directory, or the directory given by ``filepath``. Raises ...
A context manager for this client's session. This function closes the current session when this client goes out of scope.
def session(self): """A context manager for this client's session. This function closes the current session when this client goes out of scope. """ self._session = requests.session() yield self._session.close() self._session = None
Make sure that the given daemon version is supported by this client version. Raises ------ ~ipfsapi.exceptions.VersionMismatch Parameters ---------- version : str The version of an IPFS daemon. minimum : str The minimal IPFS version to allow. maximum : str T...
def assert_version(version, minimum=VERSION_MINIMUM, maximum=VERSION_MAXIMUM): """Make sure that the given daemon version is supported by this client version. Raises ------ ~ipfsapi.exceptions.VersionMismatch Parameters ---------- version : str The version of an IPFS daemon. ...
Create a new :class:`~ipfsapi.Client` instance and connect to the daemon to validate that its version is supported. Raises ------ ~ipfsapi.exceptions.VersionMismatch ~ipfsapi.exceptions.ErrorResponse ~ipfsapi.exceptions.ConnectionError ~ipfsapi.exceptions.ProtocolError ~ipfsapi.exceptio...
def connect(host=DEFAULT_HOST, port=DEFAULT_PORT, base=DEFAULT_BASE, chunk_size=multipart.default_chunk_size, **defaults): """Create a new :class:`~ipfsapi.Client` instance and connect to the daemon to validate that its version is supported. Raises ------ ~ipfsapi.exceptions.VersionMism...
Add a file, or directory of files to IPFS. .. code-block:: python >>> with io.open('nurseryrhyme.txt', 'w', encoding='utf-8') as f: ... numbytes = f.write('Mary had a little lamb') >>> c.add('nurseryrhyme.txt') {'Hash': 'QmZfF6C9j4VtoCsTp4KSrhYH47QMd3DNXVZBK...
def add(self, files, recursive=False, pattern='**', *args, **kwargs): """Add a file, or directory of files to IPFS. .. code-block:: python >>> with io.open('nurseryrhyme.txt', 'w', encoding='utf-8') as f: ... numbytes = f.write('Mary had a little lamb') >>> c.ad...
Downloads a file, or directory of files from IPFS. Files are placed in the current working directory. Parameters ---------- multihash : str The path to the IPFS object(s) to be outputted
def get(self, multihash, **kwargs): """Downloads a file, or directory of files from IPFS. Files are placed in the current working directory. Parameters ---------- multihash : str The path to the IPFS object(s) to be outputted """ args = (multihash,) ...
r"""Retrieves the contents of a file identified by hash. .. code-block:: python >>> c.cat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D') Traceback (most recent call last): ... ipfsapi.exceptions.Error: this dag node is a directory >>> c.cat('Qme...
def cat(self, multihash, offset=0, length=-1, **kwargs): r"""Retrieves the contents of a file identified by hash. .. code-block:: python >>> c.cat('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D') Traceback (most recent call last): ... ipfsapi.exceptio...
Returns a list of objects linked to by the given hash. .. code-block:: python >>> c.ls('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D') {'Objects': [ {'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D', 'Links': [ {'Hash': 'Qmd2xkBfEw...
def ls(self, multihash, **kwargs): """Returns a list of objects linked to by the given hash. .. code-block:: python >>> c.ls('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D') {'Objects': [ {'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D', '...