sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def serialize(obj): """JSON serializer that accepts datetime & date""" from datetime import datetime, date, time if isinstance(obj, date) and not isinstance(obj, datetime): obj = datetime.combine(obj, time.min) if isinstance(obj, datetime): return obj.isoformat()
JSON serializer that accepts datetime & date
entailment
def check(response, expected_status=200, url=None): """ Check whether the status code of the response equals expected_status and raise an APIError otherwise. @param url: The url of the response (for error messages). Defaults to response.url @param json: if True, return r.json(), othe...
Check whether the status code of the response equals expected_status and raise an APIError otherwise. @param url: The url of the response (for error messages). Defaults to response.url @param json: if True, return r.json(), otherwise return r.text
entailment
def _get_auth(self, user=None, password=None): """ Get the authentication info for the current user, from 1) a ~/.amcatauth file, which should be a csv file containing host, username, password entries 2) the AMCAT_USER (or USER) and AMCAT_PASSWORD environment variables ...
Get the authentication info for the current user, from 1) a ~/.amcatauth file, which should be a csv file containing host, username, password entries 2) the AMCAT_USER (or USER) and AMCAT_PASSWORD environment variables
entailment
def request(self, url, method="get", format="json", data=None, expected_status=None, headers=None, use_xpost=True, **options): """ Make an HTTP request to the given relative URL with the host, user, and password information. Returns the deserialized json if successful, an...
Make an HTTP request to the given relative URL with the host, user, and password information. Returns the deserialized json if successful, and raises an exception otherwise
entailment
def get_pages(self, url, page=1, page_size=100, yield_pages=False, **filters): """ Get all pages at url, yielding individual results :param url: the url to fetch :param page: start from this page :param page_size: results per page :param yield_pages: yield whole pages rat...
Get all pages at url, yielding individual results :param url: the url to fetch :param page: start from this page :param page_size: results per page :param yield_pages: yield whole pages rather than individual results :param filters: additional filters :return: a generator...
entailment
def get_scroll(self, url, page_size=100, yield_pages=False, **filters): """ Scroll through the resource at url and yield the individual results :param url: url to scroll through :param page_size: results per page :param yield_pages: yield whole pages rather than individual result...
Scroll through the resource at url and yield the individual results :param url: url to scroll through :param page_size: results per page :param yield_pages: yield whole pages rather than individual results :param filters: Additional filters :return: a generator of objects (dicts)...
entailment
def get_status(self): """Get the AmCAT status page""" url = URL.status.format(**locals()) return self.get_request(url)
Get the AmCAT status page
entailment
def aggregate(self, **filters): """Conduct an aggregate query""" url = URL.aggregate.format(**locals()) return self.get_pages(url, **filters)
Conduct an aggregate query
entailment
def list_sets(self, project, **filters): """List the articlesets in a project""" url = URL.articlesets.format(**locals()) return self.get_pages(url, **filters)
List the articlesets in a project
entailment
def get_set(self, project, articleset, **filters): """List the articlesets in a project""" url = URL.articleset.format(**locals()) return self.request(url, **filters)
List the articlesets in a project
entailment
def list_articles(self, project, articleset, page=1, **filters): """List the articles in a set""" url = URL.article.format(**locals()) return self.get_pages(url, page=page, **filters)
List the articles in a set
entailment
def create_set(self, project, json_data=None, **options): """ Create a new article set. Provide the needed arguments using post_data or with key-value pairs """ url = URL.articlesets.format(**locals()) if json_data is None: # form encoded request r...
Create a new article set. Provide the needed arguments using post_data or with key-value pairs
entailment
def create_articles(self, project, articleset, json_data=None, **options): """ Create one or more articles in the set. Provide the needed arguments using the json_data or with key-value pairs @param json_data: A dictionary or list of dictionaries. Each dict can ...
Create one or more articles in the set. Provide the needed arguments using the json_data or with key-value pairs @param json_data: A dictionary or list of dictionaries. Each dict can contain a 'children' attribute which is another list of dictionaries.
entailment
def sign(self, encoded): """ Return authentication signature of encoded bytes """ signature = self._hmac.copy() signature.update(encoded) return signature.hexdigest().encode('utf-8')
Return authentication signature of encoded bytes
entailment
def split(self, encoded): """ Split into signature and message """ maxlen = len(encoded) - self.sig_size message = encoded[:maxlen] signature = encoded[-self.sig_size:] return message, signature
Split into signature and message
entailment
def auth(self, encoded): """ Validate integrity of encoded bytes """ message, signature = self.split(encoded) computed = self.sign(message) if not hmac.compare_digest(signature, computed): raise AuthenticatorInvalidSignature
Validate integrity of encoded bytes
entailment
def cached_classproperty(fun): """A memorization decorator for class properties. It implements the above `classproperty` decorator, with the difference that the function result is computed and attached to class as direct attribute. (Lazy loading and caching.) """ @functools.wraps(fun) def ...
A memorization decorator for class properties. It implements the above `classproperty` decorator, with the difference that the function result is computed and attached to class as direct attribute. (Lazy loading and caching.)
entailment
def plugin_method(*plugin_names): """Plugin Method decorator. Signs a web handler function with the plugins to be applied as attributes. Args: plugin_names (list): A list of plugin callable names Returns: A wrapped handler callable. Examples: >>> @plugin_method('json', 'bi...
Plugin Method decorator. Signs a web handler function with the plugins to be applied as attributes. Args: plugin_names (list): A list of plugin callable names Returns: A wrapped handler callable. Examples: >>> @plugin_method('json', 'bill') ... def method(): .....
entailment
def route_method(method_name, extra_part=False): """Custom handler routing decorator. Signs a web handler callable with the http method as attribute. Args: method_name (str): HTTP method name (i.e GET, POST) extra_part (bool): Indicates if wrapped callable name should be a part ...
Custom handler routing decorator. Signs a web handler callable with the http method as attribute. Args: method_name (str): HTTP method name (i.e GET, POST) extra_part (bool): Indicates if wrapped callable name should be a part of the actual endpoint. Returns: ...
entailment
def issue_add(lancet, assign, add_to_sprint, summary): """ Create a new issue on the issue tracker. """ summary = " ".join(summary) issue = create_issue( lancet, summary, # project_id=project_id, add_to_active_sprint=add_to_sprint, ) if assign: if assi...
Create a new issue on the issue tracker.
entailment
def _maybe_update(self, user, attribute, new_value): """ DRY helper. If the specified attribute of the user differs from the specified value, it will be updated. """ old_value = getattr(user, attribute) if new_value != old_value: self.stderr.write( ...
DRY helper. If the specified attribute of the user differs from the specified value, it will be updated.
entailment
def _check_email_match(self, user, email): """ DRY helper. Requiring the user to specify both username and email will help catch certain issues, for example if the expected username has already been taken by someone else. """ if user.email != email: #...
DRY helper. Requiring the user to specify both username and email will help catch certain issues, for example if the expected username has already been taken by someone else.
entailment
def credentials_checker(url, username, password): """Check the provided credentials using the Harvest API.""" api = HarvestAPI(url, (username, password)) try: api.whoami() except HarvestError: return False else: return True
Check the provided credentials using the Harvest API.
entailment
def harvest(lancet, config_section): """Construct a new Harvest client.""" url, username, password = lancet.get_credentials( config_section, credentials_checker ) project_id_getter = lancet.get_instance_from_config( "timer", "project_id_getter", lancet ) task_id_getter = lancet....
Construct a new Harvest client.
entailment
def temp_dir(folder=None, delete=True): # type: (Optional[str], bool) -> str """Get a temporary directory optionally with folder appended (and created if it doesn't exist) Args: folder (Optional[str]): Folder to create in temporary folder. Defaults to None. delete (bool): Whether to delete ...
Get a temporary directory optionally with folder appended (and created if it doesn't exist) Args: folder (Optional[str]): Folder to create in temporary folder. Defaults to None. delete (bool): Whether to delete folder on exiting with statement Returns: str: A temporary directory
entailment
def send(self, obj): """Send a push notification""" if not isinstance(obj, NotificationMessage): raise ValueError, u"You can only send NotificationMessage objects." self._send_queue.put(obj)
Send a push notification
entailment
def get_error(self, block = True, timeout = None): """ Gets the next error message. Each error message is a 2-tuple of (status, identifier).""" return self._error_queue.get(block = block, timeout = timeout)
Gets the next error message. Each error message is a 2-tuple of (status, identifier).
entailment
def get_feedback(self, block = True, timeout = None): """ Gets the next feedback message. Each feedback message is a 2-tuple of (timestamp, device_token).""" if self._feedback_greenlet is None: self._feedback_greenlet = gevent.spawn(self._feedback_loop) return self._feedback_queue.get(block = block, timeo...
Gets the next feedback message. Each feedback message is a 2-tuple of (timestamp, device_token).
entailment
def wait_send(self, timeout = None): """Wait until all queued messages are sent.""" self._send_queue_cleared.clear() self._send_queue_cleared.wait(timeout = timeout)
Wait until all queued messages are sent.
entailment
def start(self): """Start the message sending loop.""" if self._send_greenlet is None: self._send_greenlet = gevent.spawn(self._send_loop)
Start the message sending loop.
entailment
def stop(self, timeout = 10.0): """ Send all pending messages, close connection. Returns True if no message left to sent. False if dirty. - timeout: seconds to wait for sending remaining messages. disconnect immedately if None. """ if (self._send_greenlet is not None) and \ (self._send_queue.qsiz...
Send all pending messages, close connection. Returns True if no message left to sent. False if dirty. - timeout: seconds to wait for sending remaining messages. disconnect immedately if None.
entailment
def convert_to_ssml(text, text_format): """ Convert text to SSML based on the text's current format. NOTE: This module is extremely limited at the moment and will be expanded. :param text: The text to convert. :param text_format: The text format of the text. Currently supports 'plai...
Convert text to SSML based on the text's current format. NOTE: This module is extremely limited at the moment and will be expanded. :param text: The text to convert. :param text_format: The text format of the text. Currently supports 'plain', 'html' or None for skipping SSML convers...
entailment
def html_to_ssml(text): """ Replaces specific html tags with probable SSML counterparts. """ ssml_text = reduce(lambda x, y: x.replace(y, html_to_ssml_maps[y]), html_to_ssml_maps, text) return ssml_text
Replaces specific html tags with probable SSML counterparts.
entailment
def multiple_replace(string, replacements): # type: (str, Dict[str,str]) -> str """Simultaneously replace multiple strigns in a string Args: string (str): Input string replacements (Dict[str,str]): Replacements dictionary Returns: str: String with replacements """ patt...
Simultaneously replace multiple strigns in a string Args: string (str): Input string replacements (Dict[str,str]): Replacements dictionary Returns: str: String with replacements
entailment
def get_matching_text_in_strs(a, b, match_min_size=30, ignore='', end_characters=''): # type: (str, str, int, str, str) -> List[str] """Returns a list of matching blocks of text in a and b Args: a (str): First string to match b (str): Second string to match match_min_size (int): Min...
Returns a list of matching blocks of text in a and b Args: a (str): First string to match b (str): Second string to match match_min_size (int): Minimum block size to match on. Defaults to 30. ignore (str): Any characters to ignore in matching. Defaults to ''. end_characters ...
entailment
def get_matching_text(string_list, match_min_size=30, ignore='', end_characters='.!\r\n'): # type: (List[str], int, str, str) -> str """Returns a string containing matching blocks of text in a list of strings followed by non-matching. Args: string_list (List[str]): List of strings to match ...
Returns a string containing matching blocks of text in a list of strings followed by non-matching. Args: string_list (List[str]): List of strings to match match_min_size (int): Minimum block size to match on. Defaults to 30. ignore (str): Any characters to ignore in matching. Defaults to ''...
entailment
def get_matching_then_nonmatching_text(string_list, separator='', match_min_size=30, ignore='', end_characters='.!\r\n'): # type: (List[str], str, int, str, str) -> str """Returns a string containing matching blocks of text in a list of strings followed by non-matching. ...
Returns a string containing matching blocks of text in a list of strings followed by non-matching. Args: string_list (List[str]): List of strings to match separator (str): Separator to add between blocks of text. Defaults to ''. match_min_size (int): Minimum block size to match on. Defaults...
entailment
def iexpand(string, keep_escapes=False): """Expand braces and return an iterator.""" if isinstance(string, bytes): is_bytes = True string = string.decode('latin-1') else: is_bytes = False if is_bytes: return (entry.encode('latin-1') for entry in ExpandBrace(keep_escape...
Expand braces and return an iterator.
entailment
def set_expanding(self): """Set that we are expanding a sequence, and return whether a release is required by the caller.""" status = not self.expanding if status: self.expanding = True return status
Set that we are expanding a sequence, and return whether a release is required by the caller.
entailment
def get_escape(self, c, i): """Get an escape.""" try: escaped = next(i) except StopIteration: escaped = '' return c + escaped if self.keep_escapes else escaped
Get an escape.
entailment
def squash(self, a, b): """ Returns a generator that squashes two iterables into one. ``` ['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that and', 'that or'] ``` """ return ((''.join(x) if isinstance(x, tuple) else x) for x in itertools.product...
Returns a generator that squashes two iterables into one. ``` ['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that and', 'that or'] ```
entailment
def get_literals(self, c, i, depth): """ Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding). """ result = [''] is_dollar = False try: ...
Get a string literal. Gather all the literal chars up to opening curly or closing brace. Also gather chars between braces and commas within a group (is_expanding).
entailment
def combine(self, a, b): """A generator that combines two iterables.""" for l in (a, b): for x in l: yield x
A generator that combines two iterables.
entailment
def get_sequence(self, c, i, depth): """ Get the sequence. Get sequence between `{}`, such as: `{a,b}`, `{1..2[..inc]}`, etc. It will basically crawl to the end or find a valid series. """ result = [] release = self.set_expanding() has_comma = False # U...
Get the sequence. Get sequence between `{}`, such as: `{a,b}`, `{1..2[..inc]}`, etc. It will basically crawl to the end or find a valid series.
entailment
def get_range(self, i): """ Check and retrieve range if value is a valid range. Here we are looking to see if the value is series or range. We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine). """ try: m = i.match(RE_INT_ITER) ...
Check and retrieve range if value is a valid range. Here we are looking to see if the value is series or range. We look for `{1..2[..inc]}` or `{a..z[..inc]}` (negative numbers are fine).
entailment
def format_value(self, value, padding): """Get padding adjusting for negative values.""" # padding = padding - 1 if value < 0 and padding > 0 else padding # prefix = '-' if value < 0 else '' if padding: return "{:0{pad}d}".format(value, pad=padding) else: ...
Get padding adjusting for negative values.
entailment
def get_int_range(self, start, end, increment=None): """Get an integer range between start and end and increments of increment.""" first, last = int(start), int(end) increment = int(increment) if increment is not None else 1 max_length = max(len(start), len(end)) # Zero doesn't...
Get an integer range between start and end and increments of increment.
entailment
def get_char_range(self, start, end, increment=None): """Get a range of alphabetic characters.""" increment = int(increment) if increment else 1 if increment < 0: increment = -increment # Zero doesn't make sense as an incrementer # but like bash, just assume one ...
Get a range of alphabetic characters.
entailment
def expand(self, string): """Expand.""" self.expanding = False empties = [] found_literal = False if string: i = iter(StringIter(string)) for x in self.get_literals(next(i), i, 0): # We don't want to return trailing empty strings. ...
Expand.
entailment
def merge_two_dictionaries(a, b, merge_lists=False): # type: (DictUpperBound, DictUpperBound, bool) -> DictUpperBound """Merges b into a and returns merged result NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen Args: a (DictUpperBound): dictiona...
Merges b into a and returns merged result NOTE: tuples and arbitrary objects are not handled as it is totally ambiguous what should happen Args: a (DictUpperBound): dictionary to merge into b (DictUpperBound): dictionary to merge from merge_lists (bool): Whether to merge lists (True) o...
entailment
def merge_dictionaries(dicts, merge_lists=False): # type: (List[DictUpperBound], bool) -> DictUpperBound """Merges all dictionaries in dicts into a single dictionary and returns result Args: dicts (List[DictUpperBound]): Dictionaries to merge into the first one in the list merge_lists (bool...
Merges all dictionaries in dicts into a single dictionary and returns result Args: dicts (List[DictUpperBound]): Dictionaries to merge into the first one in the list merge_lists (bool): Whether to merge lists (True) or replace lists (False). Default is False. Returns: DictUpperBound: M...
entailment
def dict_diff(d1, d2, no_key='<KEYNOTFOUND>'): # type: (DictUpperBound, DictUpperBound, str) -> Dict """Compares two dictionaries Args: d1 (DictUpperBound): First dictionary to compare d2 (DictUpperBound): Second dictionary to compare no_key (str): What value to use if key is not fo...
Compares two dictionaries Args: d1 (DictUpperBound): First dictionary to compare d2 (DictUpperBound): Second dictionary to compare no_key (str): What value to use if key is not found Defaults to '<KEYNOTFOUND>'. Returns: Dict: Comparison dictionary
entailment
def dict_of_lists_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a list in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to list in dictiona...
Add value to a list in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to list in dictionary Returns: None
entailment
def dict_of_sets_add(dictionary, key, value): # type: (DictUpperBound, Any, Any) -> None """Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary ...
Add value to a set in a dictionary by key Args: dictionary (DictUpperBound): Dictionary to which to add values key (Any): Key within dictionary value (Any): Value to add to set in dictionary Returns: None
entailment
def list_distribute_contents_simple(input_list, function=lambda x: x): # type: (List, Callable[[Any], Any]) -> List """Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 3, 1, 2, 1]. List can contain complex types like dictionaries in which case the function can return the appropriate value ...
Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 3, 1, 2, 1]. List can contain complex types like dictionaries in which case the function can return the appropriate value eg. lambda x: x[KEY] Args: input_list (List): List to distribute values function (Callable[[Any], Any]): ...
entailment
def list_distribute_contents(input_list, function=lambda x: x): # type: (List, Callable[[Any], Any]) -> List """Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 1, 2, 1, 3]. List can contain complex types like dictionaries in which case the function can return the appropriate value eg. la...
Distribute the contents of a list eg. [1, 1, 1, 2, 2, 3] -> [1, 2, 1, 2, 1, 3]. List can contain complex types like dictionaries in which case the function can return the appropriate value eg. lambda x: x[KEY] Args: input_list (List): List to distribute values function (Callable[[Any], Any]): ...
entailment
def extract_list_from_list_of_dict(list_of_dict, key): # type: (List[DictUpperBound], Any) -> List """Extract a list by looking up key in each member of a list of dictionaries Args: list_of_dict (List[DictUpperBound]): List of dictionaries key (Any): Key to find in each dictionary Retu...
Extract a list by looking up key in each member of a list of dictionaries Args: list_of_dict (List[DictUpperBound]): List of dictionaries key (Any): Key to find in each dictionary Returns: List: List containing values returned from each dictionary
entailment
def key_value_convert(dictin, keyfn=lambda x: x, valuefn=lambda x: x, dropfailedkeys=False, dropfailedvalues=False, exception=ValueError): # type: (DictUpperBound, Callable[[Any], Any], Callable[[Any], Any], bool, bool, ExceptionUpperBound) -> Dict """Convert keys and/or values of dictiona...
Convert keys and/or values of dictionary using functions passed in as parameters Args: dictin (DictUpperBound): Input dictionary keyfn (Callable[[Any], Any]): Function to convert keys. Defaults to lambda x: x valuefn (Callable[[Any], Any]): Function to convert values. Defaults to lambda x: ...
entailment
def integer_key_convert(dictin, dropfailedkeys=False): # type: (DictUpperBound, bool) -> Dict """Convert keys of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedkeys (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. ...
Convert keys of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedkeys (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. Returns: Dict: Dictionary with keys converted to integers
entailment
def integer_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to F...
Convert values of dictionary to integers Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. Returns: Dict: Dictionary with values converted to integers
entailment
def float_value_convert(dictin, dropfailedvalues=False): # type: (DictUpperBound, bool) -> Dict """Convert values of dictionary to floats Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False...
Convert values of dictionary to floats Args: dictin (DictUpperBound): Input dictionary dropfailedvalues (bool): Whether to drop dictionary entries where key conversion fails. Defaults to False. Returns: Dict: Dictionary with values converted to floats
entailment
def avg_dicts(dictin1, dictin2, dropmissing=True): # type: (DictUpperBound, DictUpperBound, bool) -> Dict """Create a new dictionary from two dictionaries by averaging values Args: dictin1 (DictUpperBound): First input dictionary dictin2 (DictUpperBound): Second input dictionary dro...
Create a new dictionary from two dictionaries by averaging values Args: dictin1 (DictUpperBound): First input dictionary dictin2 (DictUpperBound): Second input dictionary dropmissing (bool): Whether to drop keys missing in one dictionary. Defaults to True. Returns: Dict: Dictio...
entailment
def read_list_from_csv(filepath, dict_form=False, headers=None, **kwargs): # type: (str, bool, Union[int, List[int], List[str], None], Any) -> List[Union[Dict, List]] """Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of mu...
Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line headers) to be considered as headers (rows start counting at 1), or the actual headers defined a list of strings. If not set, all rows will be treated as c...
entailment
def write_list_to_csv(list_of_rows, filepath, headers=None): # type: (List[Union[DictUpperBound, List]], str, Union[int, List[int], List[str], None]) -> None """Write a list of rows in dict or list form to a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line h...
Write a list of rows in dict or list form to a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line headers) to be considered as headers (rows start counting at 1), or the actual headers defined a list of strings. If not set, all rows will be treated as co...
entailment
def args_to_dict(args): # type: (str) -> DictUpperBound[str,str] """Convert command line arguments in a comma separated string to a dictionary Args: args (str): Command line arguments Returns: DictUpperBound[str,str]: Dictionary of arguments """ arguments = dict() for arg ...
Convert command line arguments in a comma separated string to a dictionary Args: args (str): Command line arguments Returns: DictUpperBound[str,str]: Dictionary of arguments
entailment
def compare_files(path1, path2): # type: (str, str) -> List[str] """Returns the delta between two files using -, ?, + format excluding lines that are the same Args: path1 (str): Path to first file path2 (str): Path to second file Returns: List[str]: Delta between the two fi...
Returns the delta between two files using -, ?, + format excluding lines that are the same Args: path1 (str): Path to first file path2 (str): Path to second file Returns: List[str]: Delta between the two files
entailment
def assert_files_same(path1, path2): # type: (str, str) -> None """Asserts that two files are the same and returns delta using -, ?, + format if not Args: path1 (str): Path to first file path2 (str): Path to second file Returns: None """ difflines = compare_files(p...
Asserts that two files are the same and returns delta using -, ?, + format if not Args: path1 (str): Path to first file path2 (str): Path to second file Returns: None
entailment
def main(): """Entry point when called on the command-line. """ # Locale locale.setlocale(locale.LC_ALL, '') # Encoding for output streams if str == bytes: # PY2 writer = codecs.getwriter(locale.getpreferredencoding()) o_stdout, o_stderr = sys.stdout, sys.stderr sys.std...
Entry point when called on the command-line.
entailment
def apply(self, callback, context): # pragma: no cover """Apply the HTTPError wrapper to the callback. """ def wrapper(*args, **kwargs): try: return callback(*args, **kwargs) except bottle.HTTPError as error: return self.error_wrapper.fro...
Apply the HTTPError wrapper to the callback.
entailment
def add_episode(self, text, text_format, title, author, summary=None, publish_date=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add a new episode to the podcast. :param text: See :meth:`Episode`. :param text_format: S...
Add a new episode to the podcast. :param text: See :meth:`Episode`. :param text_format: See :meth:`Episode`. :param title: See :meth:`Episode`. :param author: See :meth:`Episode`. :param summary: See :meth:`Episode`. ...
entailment
def add_scheduled_job(self, text_source, cron_args, text_format, title, author, summary=None, synthesizer='watson', synth_args=None, sentence_break='. '): """ Add and start a new scheduled job to dynamically generate podcasts. Note: scheduling will end when the process...
Add and start a new scheduled job to dynamically generate podcasts. Note: scheduling will end when the process ends. This works best when run inside an existing application. :param text_source: A function that generates podcast text. Examples: a function that opens a fi...
entailment
def publish(self, titles): """ Publish a set of episodes to the Podcast's RSS feed. :param titles: Either a single episode title or a sequence of episode titles to publish. """ if isinstance(titles, Sequence) and not isinstance(titles, six.string_types): ...
Publish a set of episodes to the Podcast's RSS feed. :param titles: Either a single episode title or a sequence of episode titles to publish.
entailment
def render_audio(self): """ Synthesize audio from the episode's text. """ segment = text_to_speech(self._text, self.synthesizer, self.synth_args, self.sentence_break) milli = len(segment) seconds = '{0:.1f}'.format(float(milli) / 1000 % 60).zfill(2) minutes = '{0...
Synthesize audio from the episode's text.
entailment
def publish(self): """ Mark an episode as published. """ if self.published is False: self.published = True else: raise Warning(self.title + ' is already published.')
Mark an episode as published.
entailment
def unpublish(self): """ Mark an episode as not published. """ if self.published is True: self.published = False else: raise Warning(self.title + ' is already not published.')
Mark an episode as not published.
entailment
def _environment_variables(**kwargs): # type: (Any) -> Any """ Overwrite keyword arguments with environment variables Args: **kwargs: See below user_agent (str): User agent string. Returns: kwargs: Changed keyword arguments """ ...
Overwrite keyword arguments with environment variables Args: **kwargs: See below user_agent (str): User agent string. Returns: kwargs: Changed keyword arguments
entailment
def _construct(configdict, prefix, ua): # type: (Dict, str, str) -> str """ Construct user agent Args: configdict (str): Additional configuration for user agent prefix (str): Text to put at start of user agent ua (str): Custom user agent text ...
Construct user agent Args: configdict (str): Additional configuration for user agent prefix (str): Text to put at start of user agent ua (str): Custom user agent text Returns: str: Full user agent string
entailment
def _load(cls, prefix, user_agent_config_yaml, user_agent_lookup=None): # type: (str, str, Optional[str]) -> str """ Load user agent YAML file Args: prefix (str): Text to put at start of user agent user_agent_config_yaml (str): Path to user agent YAML file ...
Load user agent YAML file Args: prefix (str): Text to put at start of user agent user_agent_config_yaml (str): Path to user agent YAML file user_agent_lookup (Optional[str]): Lookup key for YAML. Ignored if user_agent supplied. Returns: str: user agent
entailment
def _create(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> str """ Get full user agent string Args: user_agent (Optional[str]): User agent string. HDXPythonLi...
Get full user agent string Args: user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml. user_agent_lookup...
entailment
def set_global(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> None """ Set global user agent string Args: user_agent (Optional[str]): User agent string. HD...
Set global user agent string Args: user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml. user_agent_look...
entailment
def get(cls, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> str """ Get full user agent string from parameters if supplied falling back on global user agent if set. Args: user_age...
Get full user agent string from parameters if supplied falling back on global user agent if set. Args: user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent...
entailment
def save_yaml(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to YAML file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to YAML file pretty (bool): Whether to ...
Save dictionary to YAML file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to YAML file pretty (bool): Whether to pretty print. Defaults to False. sortkeys (bool): Whether to sort dictionary keys. Defaults to False. ...
entailment
def save_json(dictionary, path, pretty=False, sortkeys=False): # type: (Dict, str, bool, bool) -> None """Save dictionary to JSON file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to JSON file pretty (bool): Whether to ...
Save dictionary to JSON file preserving order if it is an OrderedDict Args: dictionary (Dict): Python dictionary to save path (str): Path to JSON file pretty (bool): Whether to pretty print. Defaults to False. sortkeys (bool): Whether to sort dictionary keys. Defaults to False. ...
entailment
def load_yaml(path): # type: (str) -> OrderedDict """Load YAML file into an ordered dictionary Args: path (str): Path to YAML file Returns: OrderedDict: Ordered dictionary containing loaded YAML file """ with open(path, 'rt') as f: yamldict = yaml.load(f.read(), Loader=...
Load YAML file into an ordered dictionary Args: path (str): Path to YAML file Returns: OrderedDict: Ordered dictionary containing loaded YAML file
entailment
def load_json(path): # type: (str) -> OrderedDict """Load JSON file into an ordered dictionary Args: path (str): Path to JSON file Returns: OrderedDict: Ordered dictionary containing loaded JSON file """ with open(path, 'rt') as f: jsondict = json.loads(f.read(), object...
Load JSON file into an ordered dictionary Args: path (str): Path to JSON file Returns: OrderedDict: Ordered dictionary containing loaded JSON file
entailment
def load_file_to_str(path): # type: (str) -> str """ Load file into a string removing newlines Args: path (str): Path to file Returns: str: String contents of file """ with open(path, 'rt') as f: string = f.read().replace(linesep, '') if not string: rai...
Load file into a string removing newlines Args: path (str): Path to file Returns: str: String contents of file
entailment
def contributors(lancet, output): """ List all contributors visible in the git history. """ sorting = pygit2.GIT_SORT_TIME | pygit2.GIT_SORT_REVERSE commits = lancet.repo.walk(lancet.repo.head.target, sorting) contributors = ((c.author.name, c.author.email) for c in commits) contributors = O...
List all contributors visible in the git history.
entailment
def text_to_speech(text, synthesizer, synth_args, sentence_break): """ Converts given text to a pydub AudioSegment using a specified speech synthesizer. At the moment, IBM Watson's text-to-speech API is the only available synthesizer. :param text: The text that will be synthesized to audio....
Converts given text to a pydub AudioSegment using a specified speech synthesizer. At the moment, IBM Watson's text-to-speech API is the only available synthesizer. :param text: The text that will be synthesized to audio. :param synthesizer: The text-to-speech synthesizer to use. At the...
entailment
def watson_request(text, synth_args): """ Makes a single request to the IBM Watson text-to-speech API. :param text: The text that will be synthesized to audio. :param synth_args: A dictionary of arguments to add to the request. These should include username and password for auth...
Makes a single request to the IBM Watson text-to-speech API. :param text: The text that will be synthesized to audio. :param synth_args: A dictionary of arguments to add to the request. These should include username and password for authentication.
entailment
def build_rss_feed(podcast): """ Builds a podcast RSS feed and returns an xml file. :param podcast: A Podcast model to build the RSS feed from. """ if not os.path.exists(podcast.output_path): os.makedirs(podcast.output_path) rss = ET.Element('rss', attrib={'xmlns:itunes': 'http...
Builds a podcast RSS feed and returns an xml file. :param podcast: A Podcast model to build the RSS feed from.
entailment
def get(self, uid=None): """Example retrieve API method. """ # Return resource collection if uid is None: return self.response_factory.ok(data=resource_db) # Return resource based on UID. try: record = [r for r in resource_db if r.get('id') == u...
Example retrieve API method.
entailment
def post(self): """Example POST method. """ resource_data = self.request.json record = {'id': str(len(resource_db) + 1), 'name': resource_data.get('name')} resource_db.append(record) return self.response_factory.ok(data=record)
Example POST method.
entailment
def put(self, uid): """Example PUT method. """ resource_data = self.request.json try: record = resource_db[uid] except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) record['name'] = resource_d...
Example PUT method.
entailment
def delete(self, uid): """Example DELETE method. """ try: record = resource_db[uid].copy() except KeyError: return self.response_factory.not_found(errors=['Resource with UID {} does not exist!']) del resource_db[uid] return self.response_factory...
Example DELETE method.
entailment
def get_pages(url): """ Return the 'pages' from the starting url Technically, look for the 'next 50' link, yield and download it, repeat """ while True: yield url doc = html.parse(url).find("body") links = [a for a in doc.findall(".//a") if a.text and a.text.startswith("next...
Return the 'pages' from the starting url Technically, look for the 'next 50' link, yield and download it, repeat
entailment
def get_article_urls(url): """ Return the articles from a page Technically, look for a div with class mw-search-result-heading and get the first link from this div """ doc = html.parse(url).getroot() for div in doc.cssselect("div.mw-search-result-heading"): href = div.cssselect("a")[...
Return the articles from a page Technically, look for a div with class mw-search-result-heading and get the first link from this div
entailment
def get_article(url): """ Return a single article as a 'amcat-ready' dict Uses the 'export' function of wikinews to get an xml article """ a = html.parse(url).getroot() title = a.cssselect(".firstHeading")[0].text_content() date = a.cssselect(".published")[0].text_content() date = dateti...
Return a single article as a 'amcat-ready' dict Uses the 'export' function of wikinews to get an xml article
entailment
def scrape_wikinews(conn, project, articleset, query): """ Scrape wikinews articles from the given query @param conn: The AmcatAPI object @param articleset: The target articleset ID @param category: The wikinews category name """ url = "http://en.wikinews.org/w/index.php?search={}&limit=50"....
Scrape wikinews articles from the given query @param conn: The AmcatAPI object @param articleset: The target articleset ID @param category: The wikinews category name
entailment
def start_service(addr, n): """ Start a service """ s = Service(addr) started = time.time() for _ in range(n): msg = s.socket.recv() s.socket.send(msg) s.socket.close() duration = time.time() - started print('Raw REP service stats:') util.print_stats(n, duration) re...
Start a service
entailment
def bench(client, n): """ Benchmark n requests """ items = list(range(n)) # Time client publish operations # ------------------------------ started = time.time() msg = b'x' for i in items: client.socket.send(msg) res = client.socket.recv() assert msg == res durat...
Benchmark n requests
entailment