repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
RudolfCardinal/pythonlib
cardinal_pythonlib/debugging.py
get_caller_stack_info
def get_caller_stack_info(start_back: int = 1) -> List[str]: r""" Retrieves a textual representation of the call stack. Args: start_back: number of calls back in the frame stack (starting from the frame stack as seen by :func:`get_caller_stack_info`) to begin with Returns: list of descriptions Example: .. code-block:: python from cardinal_pythonlib.debugging import get_caller_stack_info def who_am_i(): return get_caller_name() class MyClass(object): def classfunc(self): print("Stack info:\n" + "\n".join(get_caller_stack_info())) def f2(): x = MyClass() x.classfunc() def f1(): f2() f1() if called from the Python prompt will produce: .. code-block:: none Stack info: <module>() ... defined at <stdin>:1 ... line 1 calls next in stack; code is: f1() ... defined at <stdin>:1 ... line 2 calls next in stack; code is: f2() ... defined at <stdin>:1 ... line 3 calls next in stack; code is: classfunc(self=<__main__.MyClass object at 0x7f86a009c6d8>) ... defined at <stdin>:2 ... line 3 calls next in stack; code is: and if called from a Python file will produce: .. code-block:: none Stack info: <module>() ... defined at /home/rudolf/tmp/stack.py:1 ... line 17 calls next in stack; code is: f1() f1() ... defined at /home/rudolf/tmp/stack.py:14 ... line 15 calls next in stack; code is: f2() f2() ... defined at /home/rudolf/tmp/stack.py:10 ... line 12 calls next in stack; code is: x.classfunc() classfunc(self=<__main__.MyClass object at 0x7fd7a731f358>) ... defined at /home/rudolf/tmp/stack.py:7 ... line 8 calls next in stack; code is: print("Stack info:\n" + "\n".join(get_caller_stack_info())) """ # "0 back" is debug_callers, so "1 back" its caller # https://docs.python.org/3/library/inspect.html callers = [] # type: List[str] frameinfolist = inspect.stack() # type: List[FrameInfo] # noqa frameinfolist = frameinfolist[start_back:] for frameinfo in frameinfolist: frame = frameinfo.frame function_defined_at = "... defined at {filename}:{line}".format( filename=frame.f_code.co_filename, line=frame.f_code.co_firstlineno, ) argvalues = inspect.getargvalues(frame) formatted_argvalues = inspect.formatargvalues(*argvalues) function_call = "{funcname}{argvals}".format( funcname=frame.f_code.co_name, argvals=formatted_argvalues, ) code_context = frameinfo.code_context code = "".join(code_context) if code_context else "" onwards = "... line {line} calls next in stack; code is:\n{c}".format( line=frame.f_lineno, c=code, ) description = "\n".join([function_call, function_defined_at, onwards]) callers.append(description) return list(reversed(callers))
python
def get_caller_stack_info(start_back: int = 1) -> List[str]: r""" Retrieves a textual representation of the call stack. Args: start_back: number of calls back in the frame stack (starting from the frame stack as seen by :func:`get_caller_stack_info`) to begin with Returns: list of descriptions Example: .. code-block:: python from cardinal_pythonlib.debugging import get_caller_stack_info def who_am_i(): return get_caller_name() class MyClass(object): def classfunc(self): print("Stack info:\n" + "\n".join(get_caller_stack_info())) def f2(): x = MyClass() x.classfunc() def f1(): f2() f1() if called from the Python prompt will produce: .. code-block:: none Stack info: <module>() ... defined at <stdin>:1 ... line 1 calls next in stack; code is: f1() ... defined at <stdin>:1 ... line 2 calls next in stack; code is: f2() ... defined at <stdin>:1 ... line 3 calls next in stack; code is: classfunc(self=<__main__.MyClass object at 0x7f86a009c6d8>) ... defined at <stdin>:2 ... line 3 calls next in stack; code is: and if called from a Python file will produce: .. code-block:: none Stack info: <module>() ... defined at /home/rudolf/tmp/stack.py:1 ... line 17 calls next in stack; code is: f1() f1() ... defined at /home/rudolf/tmp/stack.py:14 ... line 15 calls next in stack; code is: f2() f2() ... defined at /home/rudolf/tmp/stack.py:10 ... line 12 calls next in stack; code is: x.classfunc() classfunc(self=<__main__.MyClass object at 0x7fd7a731f358>) ... defined at /home/rudolf/tmp/stack.py:7 ... line 8 calls next in stack; code is: print("Stack info:\n" + "\n".join(get_caller_stack_info())) """ # "0 back" is debug_callers, so "1 back" its caller # https://docs.python.org/3/library/inspect.html callers = [] # type: List[str] frameinfolist = inspect.stack() # type: List[FrameInfo] # noqa frameinfolist = frameinfolist[start_back:] for frameinfo in frameinfolist: frame = frameinfo.frame function_defined_at = "... defined at {filename}:{line}".format( filename=frame.f_code.co_filename, line=frame.f_code.co_firstlineno, ) argvalues = inspect.getargvalues(frame) formatted_argvalues = inspect.formatargvalues(*argvalues) function_call = "{funcname}{argvals}".format( funcname=frame.f_code.co_name, argvals=formatted_argvalues, ) code_context = frameinfo.code_context code = "".join(code_context) if code_context else "" onwards = "... line {line} calls next in stack; code is:\n{c}".format( line=frame.f_lineno, c=code, ) description = "\n".join([function_call, function_defined_at, onwards]) callers.append(description) return list(reversed(callers))
[ "def", "get_caller_stack_info", "(", "start_back", ":", "int", "=", "1", ")", "->", "List", "[", "str", "]", ":", "# \"0 back\" is debug_callers, so \"1 back\" its caller", "# https://docs.python.org/3/library/inspect.html", "callers", "=", "[", "]", "# type: List[str]", "frameinfolist", "=", "inspect", ".", "stack", "(", ")", "# type: List[FrameInfo] # noqa", "frameinfolist", "=", "frameinfolist", "[", "start_back", ":", "]", "for", "frameinfo", "in", "frameinfolist", ":", "frame", "=", "frameinfo", ".", "frame", "function_defined_at", "=", "\"... defined at {filename}:{line}\"", ".", "format", "(", "filename", "=", "frame", ".", "f_code", ".", "co_filename", ",", "line", "=", "frame", ".", "f_code", ".", "co_firstlineno", ",", ")", "argvalues", "=", "inspect", ".", "getargvalues", "(", "frame", ")", "formatted_argvalues", "=", "inspect", ".", "formatargvalues", "(", "*", "argvalues", ")", "function_call", "=", "\"{funcname}{argvals}\"", ".", "format", "(", "funcname", "=", "frame", ".", "f_code", ".", "co_name", ",", "argvals", "=", "formatted_argvalues", ",", ")", "code_context", "=", "frameinfo", ".", "code_context", "code", "=", "\"\"", ".", "join", "(", "code_context", ")", "if", "code_context", "else", "\"\"", "onwards", "=", "\"... line {line} calls next in stack; code is:\\n{c}\"", ".", "format", "(", "line", "=", "frame", ".", "f_lineno", ",", "c", "=", "code", ",", ")", "description", "=", "\"\\n\"", ".", "join", "(", "[", "function_call", ",", "function_defined_at", ",", "onwards", "]", ")", "callers", ".", "append", "(", "description", ")", "return", "list", "(", "reversed", "(", "callers", ")", ")" ]
r""" Retrieves a textual representation of the call stack. Args: start_back: number of calls back in the frame stack (starting from the frame stack as seen by :func:`get_caller_stack_info`) to begin with Returns: list of descriptions Example: .. code-block:: python from cardinal_pythonlib.debugging import get_caller_stack_info def who_am_i(): return get_caller_name() class MyClass(object): def classfunc(self): print("Stack info:\n" + "\n".join(get_caller_stack_info())) def f2(): x = MyClass() x.classfunc() def f1(): f2() f1() if called from the Python prompt will produce: .. code-block:: none Stack info: <module>() ... defined at <stdin>:1 ... line 1 calls next in stack; code is: f1() ... defined at <stdin>:1 ... line 2 calls next in stack; code is: f2() ... defined at <stdin>:1 ... line 3 calls next in stack; code is: classfunc(self=<__main__.MyClass object at 0x7f86a009c6d8>) ... defined at <stdin>:2 ... line 3 calls next in stack; code is: and if called from a Python file will produce: .. code-block:: none Stack info: <module>() ... defined at /home/rudolf/tmp/stack.py:1 ... line 17 calls next in stack; code is: f1() f1() ... defined at /home/rudolf/tmp/stack.py:14 ... line 15 calls next in stack; code is: f2() f2() ... defined at /home/rudolf/tmp/stack.py:10 ... line 12 calls next in stack; code is: x.classfunc() classfunc(self=<__main__.MyClass object at 0x7fd7a731f358>) ... defined at /home/rudolf/tmp/stack.py:7 ... line 8 calls next in stack; code is: print("Stack info:\n" + "\n".join(get_caller_stack_info()))
[ "r", "Retrieves", "a", "textual", "representation", "of", "the", "call", "stack", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L158-L264
RudolfCardinal/pythonlib
cardinal_pythonlib/debugging.py
debug_object
def debug_object(obj, log_level: int = logging.DEBUG) -> None: """ Sends details about a Python to the log, specifically its ``repr()`` representation, and all of its attributes with their name, value, and type. Args: obj: object to debug log_level: log level to use; default is ``logging.DEBUG`` """ msgs = ["For {o!r}:".format(o=obj)] for attrname in dir(obj): attribute = getattr(obj, attrname) msgs.append("- {an!r}: {at!r}, of type {t!r}".format( an=attrname, at=attribute, t=type(attribute))) log.log(log_level, "{}", "\n".join(msgs))
python
def debug_object(obj, log_level: int = logging.DEBUG) -> None: """ Sends details about a Python to the log, specifically its ``repr()`` representation, and all of its attributes with their name, value, and type. Args: obj: object to debug log_level: log level to use; default is ``logging.DEBUG`` """ msgs = ["For {o!r}:".format(o=obj)] for attrname in dir(obj): attribute = getattr(obj, attrname) msgs.append("- {an!r}: {at!r}, of type {t!r}".format( an=attrname, at=attribute, t=type(attribute))) log.log(log_level, "{}", "\n".join(msgs))
[ "def", "debug_object", "(", "obj", ",", "log_level", ":", "int", "=", "logging", ".", "DEBUG", ")", "->", "None", ":", "msgs", "=", "[", "\"For {o!r}:\"", ".", "format", "(", "o", "=", "obj", ")", "]", "for", "attrname", "in", "dir", "(", "obj", ")", ":", "attribute", "=", "getattr", "(", "obj", ",", "attrname", ")", "msgs", ".", "append", "(", "\"- {an!r}: {at!r}, of type {t!r}\"", ".", "format", "(", "an", "=", "attrname", ",", "at", "=", "attribute", ",", "t", "=", "type", "(", "attribute", ")", ")", ")", "log", ".", "log", "(", "log_level", ",", "\"{}\"", ",", "\"\\n\"", ".", "join", "(", "msgs", ")", ")" ]
Sends details about a Python to the log, specifically its ``repr()`` representation, and all of its attributes with their name, value, and type. Args: obj: object to debug log_level: log level to use; default is ``logging.DEBUG``
[ "Sends", "details", "about", "a", "Python", "to", "the", "log", "specifically", "its", "repr", "()", "representation", "and", "all", "of", "its", "attributes", "with", "their", "name", "value", "and", "type", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L271-L285
RudolfCardinal/pythonlib
cardinal_pythonlib/django/fields/jsonclassfield.py
JsonClassField.from_db_value
def from_db_value(self, value, expression, connection, context): """ "Called in all circumstances when the data is loaded from the database, including in aggregates and values() calls." """ if value is None: return value return json_decode(value)
python
def from_db_value(self, value, expression, connection, context): """ "Called in all circumstances when the data is loaded from the database, including in aggregates and values() calls." """ if value is None: return value return json_decode(value)
[ "def", "from_db_value", "(", "self", ",", "value", ",", "expression", ",", "connection", ",", "context", ")", ":", "if", "value", "is", "None", ":", "return", "value", "return", "json_decode", "(", "value", ")" ]
"Called in all circumstances when the data is loaded from the database, including in aggregates and values() calls."
[ "Called", "in", "all", "circumstances", "when", "the", "data", "is", "loaded", "from", "the", "database", "including", "in", "aggregates", "and", "values", "()", "calls", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/jsonclassfield.py#L152-L159
RudolfCardinal/pythonlib
cardinal_pythonlib/django/fields/jsonclassfield.py
JsonClassField.to_python
def to_python(self, value): """ "Called during deserialization and during the clean() method used from forms.... [s]hould deal gracefully with... (*) an instance of the correct type; (*) a string; (*) None (if the field allows null=True)." "For ``to_python()``, if anything goes wrong during value conversion, you should raise a ``ValidationError`` exception." """ if value is None: return value if not isinstance(value, str): return value try: return json_decode(value) except Exception as err: raise ValidationError(repr(err))
python
def to_python(self, value): """ "Called during deserialization and during the clean() method used from forms.... [s]hould deal gracefully with... (*) an instance of the correct type; (*) a string; (*) None (if the field allows null=True)." "For ``to_python()``, if anything goes wrong during value conversion, you should raise a ``ValidationError`` exception." """ if value is None: return value if not isinstance(value, str): return value try: return json_decode(value) except Exception as err: raise ValidationError(repr(err))
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "value", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "return", "value", "try", ":", "return", "json_decode", "(", "value", ")", "except", "Exception", "as", "err", ":", "raise", "ValidationError", "(", "repr", "(", "err", ")", ")" ]
"Called during deserialization and during the clean() method used from forms.... [s]hould deal gracefully with... (*) an instance of the correct type; (*) a string; (*) None (if the field allows null=True)." "For ``to_python()``, if anything goes wrong during value conversion, you should raise a ``ValidationError`` exception."
[ "Called", "during", "deserialization", "and", "during", "the", "clean", "()", "method", "used", "from", "forms", "....", "[", "s", "]", "hould", "deal", "gracefully", "with", "...", "(", "*", ")", "an", "instance", "of", "the", "correct", "type", ";", "(", "*", ")", "a", "string", ";", "(", "*", ")", "None", "(", "if", "the", "field", "allows", "null", "=", "True", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/jsonclassfield.py#L161-L178
ivanprjcts/sdklib
sdklib/util/xmltodict.py
parse
def parse(xml_input, encoding=None, expat=expat, process_namespaces=False, namespace_separator=':', **kwargs): """Parse the given XML input and convert it into a dictionary. `xml_input` can either be a `string` or a file-like object. If `xml_attribs` is `True`, element attributes are put in the dictionary among regular child elements, using `@` as a prefix to avoid collisions. If set to `False`, they are just ignored. Simple example:: >>> import xmltodict >>> doc = xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a> ... \"\"\") >>> doc['a']['@prop'] u'x' >>> doc['a']['b'] [u'1', u'2'] If `item_depth` is `0`, the function returns a dictionary for the root element (default behavior). Otherwise, it calls `item_callback` every time an item at the specified depth is found and returns `None` in the end (streaming mode). The callback function receives two parameters: the `path` from the document root to the item (name-attribs pairs), and the `item` (dict). If the callback's return value is false-ish, parsing will be stopped with the :class:`ParsingInterrupted` exception. Streaming example:: >>> def handle(path, item): ... print 'path:%s item:%s' % (path, item) ... return True ... >>> xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a>\"\"\", item_depth=2, item_callback=handle) path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1 path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2 The optional argument `postprocessor` is a function that takes `path`, `key` and `value` as positional arguments and returns a new `(key, value)` pair where both `key` and `value` may have changed. Usage example:: >>> def postprocessor(path, key, value): ... try: ... return key + ':int', int(value) ... except (ValueError, TypeError): ... return key, value >>> xmltodict.parse('<a><b>1</b><b>2</b><b>x</b></a>', ... postprocessor=postprocessor) OrderedDict([(u'a', OrderedDict([(u'b:int', [1, 2]), (u'b', u'x')]))]) You can pass an alternate version of `expat` (such as `defusedexpat`) by using the `expat` parameter. E.g: >>> import defusedexpat >>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat) OrderedDict([(u'a', u'hello')]) You can use the force_list argument to force lists to be created even when there is only a single child of a given level of hierarchy. The force_list argument is a tuple of keys. If the key for a given level of hierarchy is in the force_list argument, that level of hierarchy will have a list as a child (even if there is only one sub-element). The index_keys operation takes precendence over this. This is applied after any user-supplied postprocessor has already run. For example, given this input: <servers> <server> <name>host1</name> <os>Linux</os> <interfaces> <interface> <name>em0</name> <ip_address>10.0.0.1</ip_address> </interface> </interfaces> </server> </servers> If called with force_list=('interface',), it will produce this dictionary: {'servers': {'server': {'name': 'host1', 'os': 'Linux'}, 'interfaces': {'interface': [ {'name': 'em0', 'ip_address': '10.0.0.1' } ] } } } `force_list` can also be a callable that receives `path`, `key` and `value`. This is helpful in cases where the logic that decides whether a list should be forced is more complex. """ handler = _DictSAXHandler(namespace_separator=namespace_separator, **kwargs) if isinstance(xml_input, _unicode): if not encoding: encoding = 'utf-8' xml_input = xml_input.encode(encoding) if not process_namespaces: namespace_separator = None parser = expat.ParserCreate( encoding, namespace_separator ) try: parser.ordered_attributes = True except AttributeError: # Jython's expat does not support ordered_attributes pass parser.StartElementHandler = handler.startElement parser.EndElementHandler = handler.endElement parser.CharacterDataHandler = handler.characters parser.buffer_text = True try: parser.ParseFile(xml_input) except (TypeError, AttributeError): parser.Parse(xml_input, True) return handler.item
python
def parse(xml_input, encoding=None, expat=expat, process_namespaces=False, namespace_separator=':', **kwargs): """Parse the given XML input and convert it into a dictionary. `xml_input` can either be a `string` or a file-like object. If `xml_attribs` is `True`, element attributes are put in the dictionary among regular child elements, using `@` as a prefix to avoid collisions. If set to `False`, they are just ignored. Simple example:: >>> import xmltodict >>> doc = xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a> ... \"\"\") >>> doc['a']['@prop'] u'x' >>> doc['a']['b'] [u'1', u'2'] If `item_depth` is `0`, the function returns a dictionary for the root element (default behavior). Otherwise, it calls `item_callback` every time an item at the specified depth is found and returns `None` in the end (streaming mode). The callback function receives two parameters: the `path` from the document root to the item (name-attribs pairs), and the `item` (dict). If the callback's return value is false-ish, parsing will be stopped with the :class:`ParsingInterrupted` exception. Streaming example:: >>> def handle(path, item): ... print 'path:%s item:%s' % (path, item) ... return True ... >>> xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a>\"\"\", item_depth=2, item_callback=handle) path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1 path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2 The optional argument `postprocessor` is a function that takes `path`, `key` and `value` as positional arguments and returns a new `(key, value)` pair where both `key` and `value` may have changed. Usage example:: >>> def postprocessor(path, key, value): ... try: ... return key + ':int', int(value) ... except (ValueError, TypeError): ... return key, value >>> xmltodict.parse('<a><b>1</b><b>2</b><b>x</b></a>', ... postprocessor=postprocessor) OrderedDict([(u'a', OrderedDict([(u'b:int', [1, 2]), (u'b', u'x')]))]) You can pass an alternate version of `expat` (such as `defusedexpat`) by using the `expat` parameter. E.g: >>> import defusedexpat >>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat) OrderedDict([(u'a', u'hello')]) You can use the force_list argument to force lists to be created even when there is only a single child of a given level of hierarchy. The force_list argument is a tuple of keys. If the key for a given level of hierarchy is in the force_list argument, that level of hierarchy will have a list as a child (even if there is only one sub-element). The index_keys operation takes precendence over this. This is applied after any user-supplied postprocessor has already run. For example, given this input: <servers> <server> <name>host1</name> <os>Linux</os> <interfaces> <interface> <name>em0</name> <ip_address>10.0.0.1</ip_address> </interface> </interfaces> </server> </servers> If called with force_list=('interface',), it will produce this dictionary: {'servers': {'server': {'name': 'host1', 'os': 'Linux'}, 'interfaces': {'interface': [ {'name': 'em0', 'ip_address': '10.0.0.1' } ] } } } `force_list` can also be a callable that receives `path`, `key` and `value`. This is helpful in cases where the logic that decides whether a list should be forced is more complex. """ handler = _DictSAXHandler(namespace_separator=namespace_separator, **kwargs) if isinstance(xml_input, _unicode): if not encoding: encoding = 'utf-8' xml_input = xml_input.encode(encoding) if not process_namespaces: namespace_separator = None parser = expat.ParserCreate( encoding, namespace_separator ) try: parser.ordered_attributes = True except AttributeError: # Jython's expat does not support ordered_attributes pass parser.StartElementHandler = handler.startElement parser.EndElementHandler = handler.endElement parser.CharacterDataHandler = handler.characters parser.buffer_text = True try: parser.ParseFile(xml_input) except (TypeError, AttributeError): parser.Parse(xml_input, True) return handler.item
[ "def", "parse", "(", "xml_input", ",", "encoding", "=", "None", ",", "expat", "=", "expat", ",", "process_namespaces", "=", "False", ",", "namespace_separator", "=", "':'", ",", "*", "*", "kwargs", ")", ":", "handler", "=", "_DictSAXHandler", "(", "namespace_separator", "=", "namespace_separator", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "xml_input", ",", "_unicode", ")", ":", "if", "not", "encoding", ":", "encoding", "=", "'utf-8'", "xml_input", "=", "xml_input", ".", "encode", "(", "encoding", ")", "if", "not", "process_namespaces", ":", "namespace_separator", "=", "None", "parser", "=", "expat", ".", "ParserCreate", "(", "encoding", ",", "namespace_separator", ")", "try", ":", "parser", ".", "ordered_attributes", "=", "True", "except", "AttributeError", ":", "# Jython's expat does not support ordered_attributes", "pass", "parser", ".", "StartElementHandler", "=", "handler", ".", "startElement", "parser", ".", "EndElementHandler", "=", "handler", ".", "endElement", "parser", ".", "CharacterDataHandler", "=", "handler", ".", "characters", "parser", ".", "buffer_text", "=", "True", "try", ":", "parser", ".", "ParseFile", "(", "xml_input", ")", "except", "(", "TypeError", ",", "AttributeError", ")", ":", "parser", ".", "Parse", "(", "xml_input", ",", "True", ")", "return", "handler", ".", "item" ]
Parse the given XML input and convert it into a dictionary. `xml_input` can either be a `string` or a file-like object. If `xml_attribs` is `True`, element attributes are put in the dictionary among regular child elements, using `@` as a prefix to avoid collisions. If set to `False`, they are just ignored. Simple example:: >>> import xmltodict >>> doc = xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a> ... \"\"\") >>> doc['a']['@prop'] u'x' >>> doc['a']['b'] [u'1', u'2'] If `item_depth` is `0`, the function returns a dictionary for the root element (default behavior). Otherwise, it calls `item_callback` every time an item at the specified depth is found and returns `None` in the end (streaming mode). The callback function receives two parameters: the `path` from the document root to the item (name-attribs pairs), and the `item` (dict). If the callback's return value is false-ish, parsing will be stopped with the :class:`ParsingInterrupted` exception. Streaming example:: >>> def handle(path, item): ... print 'path:%s item:%s' % (path, item) ... return True ... >>> xmltodict.parse(\"\"\" ... <a prop="x"> ... <b>1</b> ... <b>2</b> ... </a>\"\"\", item_depth=2, item_callback=handle) path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:1 path:[(u'a', {u'prop': u'x'}), (u'b', None)] item:2 The optional argument `postprocessor` is a function that takes `path`, `key` and `value` as positional arguments and returns a new `(key, value)` pair where both `key` and `value` may have changed. Usage example:: >>> def postprocessor(path, key, value): ... try: ... return key + ':int', int(value) ... except (ValueError, TypeError): ... return key, value >>> xmltodict.parse('<a><b>1</b><b>2</b><b>x</b></a>', ... postprocessor=postprocessor) OrderedDict([(u'a', OrderedDict([(u'b:int', [1, 2]), (u'b', u'x')]))]) You can pass an alternate version of `expat` (such as `defusedexpat`) by using the `expat` parameter. E.g: >>> import defusedexpat >>> xmltodict.parse('<a>hello</a>', expat=defusedexpat.pyexpat) OrderedDict([(u'a', u'hello')]) You can use the force_list argument to force lists to be created even when there is only a single child of a given level of hierarchy. The force_list argument is a tuple of keys. If the key for a given level of hierarchy is in the force_list argument, that level of hierarchy will have a list as a child (even if there is only one sub-element). The index_keys operation takes precendence over this. This is applied after any user-supplied postprocessor has already run. For example, given this input: <servers> <server> <name>host1</name> <os>Linux</os> <interfaces> <interface> <name>em0</name> <ip_address>10.0.0.1</ip_address> </interface> </interfaces> </server> </servers> If called with force_list=('interface',), it will produce this dictionary: {'servers': {'server': {'name': 'host1', 'os': 'Linux'}, 'interfaces': {'interface': [ {'name': 'em0', 'ip_address': '10.0.0.1' } ] } } } `force_list` can also be a callable that receives `path`, `key` and `value`. This is helpful in cases where the logic that decides whether a list should be forced is more complex.
[ "Parse", "the", "given", "XML", "input", "and", "convert", "it", "into", "a", "dictionary", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/xmltodict.py#L183-L312
AndrewWalker/glud
glud/matchers.py
cxxRecordDecl
def cxxRecordDecl(*args): """Matches C++ class declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = cxxRecordDecl() >>> for c in walk(m, parse_string(config).cursor): ... print(c.spelling) W X """ kinds = [ CursorKind.CLASS_DECL, CursorKind.CLASS_TEMPLATE, ] inner = [ PredMatcher(is_kind(k)) for k in kinds ] return allOf(anyOf(*inner), *args)
python
def cxxRecordDecl(*args): """Matches C++ class declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = cxxRecordDecl() >>> for c in walk(m, parse_string(config).cursor): ... print(c.spelling) W X """ kinds = [ CursorKind.CLASS_DECL, CursorKind.CLASS_TEMPLATE, ] inner = [ PredMatcher(is_kind(k)) for k in kinds ] return allOf(anyOf(*inner), *args)
[ "def", "cxxRecordDecl", "(", "*", "args", ")", ":", "kinds", "=", "[", "CursorKind", ".", "CLASS_DECL", ",", "CursorKind", ".", "CLASS_TEMPLATE", ",", "]", "inner", "=", "[", "PredMatcher", "(", "is_kind", "(", "k", ")", ")", "for", "k", "in", "kinds", "]", "return", "allOf", "(", "anyOf", "(", "*", "inner", ")", ",", "*", "args", ")" ]
Matches C++ class declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = cxxRecordDecl() >>> for c in walk(m, parse_string(config).cursor): ... print(c.spelling) W X
[ "Matches", "C", "++", "class", "declarations", "." ]
train
https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/matchers.py#L167-L188
AndrewWalker/glud
glud/matchers.py
recordDecl
def recordDecl(*args): """Matches class, struct, and union declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = recordDecl() >>> for c in walk(m, parse_string(config).cursor): ... print(c.spelling) W X Y Z """ kinds = [ CursorKind.STRUCT_DECL, CursorKind.UNION_DECL, CursorKind.CLASS_DECL, CursorKind.CLASS_TEMPLATE, ] inner = [ PredMatcher(is_kind(k)) for k in kinds ] return allOf(anyOf(*inner), *args)
python
def recordDecl(*args): """Matches class, struct, and union declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = recordDecl() >>> for c in walk(m, parse_string(config).cursor): ... print(c.spelling) W X Y Z """ kinds = [ CursorKind.STRUCT_DECL, CursorKind.UNION_DECL, CursorKind.CLASS_DECL, CursorKind.CLASS_TEMPLATE, ] inner = [ PredMatcher(is_kind(k)) for k in kinds ] return allOf(anyOf(*inner), *args)
[ "def", "recordDecl", "(", "*", "args", ")", ":", "kinds", "=", "[", "CursorKind", ".", "STRUCT_DECL", ",", "CursorKind", ".", "UNION_DECL", ",", "CursorKind", ".", "CLASS_DECL", ",", "CursorKind", ".", "CLASS_TEMPLATE", ",", "]", "inner", "=", "[", "PredMatcher", "(", "is_kind", "(", "k", ")", ")", "for", "k", "in", "kinds", "]", "return", "allOf", "(", "anyOf", "(", "*", "inner", ")", ",", "*", "args", ")" ]
Matches class, struct, and union declarations. >>> from glud import * >>> config = ''' ... class W; ... template<typename T> class X {}; ... struct Y {}; ... union Z {}; ... ''' >>> m = recordDecl() >>> for c in walk(m, parse_string(config).cursor): ... print(c.spelling) W X Y Z
[ "Matches", "class", "struct", "and", "union", "declarations", "." ]
train
https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/matchers.py#L679-L704
RudolfCardinal/pythonlib
cardinal_pythonlib/convert.py
convert_to_bool
def convert_to_bool(x: Any, default: bool = None) -> bool: """ Transforms its input to a ``bool`` (or returns ``default`` if ``x`` is falsy but not itself a boolean). Accepts various common string versions. """ if isinstance(x, bool): return x if not x: # None, zero, blank string... return default try: return int(x) != 0 except (TypeError, ValueError): pass try: return float(x) != 0 except (TypeError, ValueError): pass if not isinstance(x, str): raise Exception("Unknown thing being converted to bool: {!r}".format(x)) x = x.upper() if x in ["Y", "YES", "T", "TRUE"]: return True if x in ["N", "NO", "F", "FALSE"]: return False raise Exception("Unknown thing being converted to bool: {!r}".format(x))
python
def convert_to_bool(x: Any, default: bool = None) -> bool: """ Transforms its input to a ``bool`` (or returns ``default`` if ``x`` is falsy but not itself a boolean). Accepts various common string versions. """ if isinstance(x, bool): return x if not x: # None, zero, blank string... return default try: return int(x) != 0 except (TypeError, ValueError): pass try: return float(x) != 0 except (TypeError, ValueError): pass if not isinstance(x, str): raise Exception("Unknown thing being converted to bool: {!r}".format(x)) x = x.upper() if x in ["Y", "YES", "T", "TRUE"]: return True if x in ["N", "NO", "F", "FALSE"]: return False raise Exception("Unknown thing being converted to bool: {!r}".format(x))
[ "def", "convert_to_bool", "(", "x", ":", "Any", ",", "default", ":", "bool", "=", "None", ")", "->", "bool", ":", "if", "isinstance", "(", "x", ",", "bool", ")", ":", "return", "x", "if", "not", "x", ":", "# None, zero, blank string...", "return", "default", "try", ":", "return", "int", "(", "x", ")", "!=", "0", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "try", ":", "return", "float", "(", "x", ")", "!=", "0", "except", "(", "TypeError", ",", "ValueError", ")", ":", "pass", "if", "not", "isinstance", "(", "x", ",", "str", ")", ":", "raise", "Exception", "(", "\"Unknown thing being converted to bool: {!r}\"", ".", "format", "(", "x", ")", ")", "x", "=", "x", ".", "upper", "(", ")", "if", "x", "in", "[", "\"Y\"", ",", "\"YES\"", ",", "\"T\"", ",", "\"TRUE\"", "]", ":", "return", "True", "if", "x", "in", "[", "\"N\"", ",", "\"NO\"", ",", "\"F\"", ",", "\"FALSE\"", "]", ":", "return", "False", "raise", "Exception", "(", "\"Unknown thing being converted to bool: {!r}\"", ".", "format", "(", "x", ")", ")" ]
Transforms its input to a ``bool`` (or returns ``default`` if ``x`` is falsy but not itself a boolean). Accepts various common string versions.
[ "Transforms", "its", "input", "to", "a", "bool", "(", "or", "returns", "default", "if", "x", "is", "falsy", "but", "not", "itself", "a", "boolean", ")", ".", "Accepts", "various", "common", "string", "versions", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L43-L73
RudolfCardinal/pythonlib
cardinal_pythonlib/convert.py
convert_to_int
def convert_to_int(x: Any, default: int = None) -> int: """ Transforms its input into an integer, or returns ``default``. """ try: return int(x) except (TypeError, ValueError): return default
python
def convert_to_int(x: Any, default: int = None) -> int: """ Transforms its input into an integer, or returns ``default``. """ try: return int(x) except (TypeError, ValueError): return default
[ "def", "convert_to_int", "(", "x", ":", "Any", ",", "default", ":", "int", "=", "None", ")", "->", "int", ":", "try", ":", "return", "int", "(", "x", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "return", "default" ]
Transforms its input into an integer, or returns ``default``.
[ "Transforms", "its", "input", "into", "an", "integer", "or", "returns", "default", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L76-L83
RudolfCardinal/pythonlib
cardinal_pythonlib/convert.py
convert_attrs_to_bool
def convert_attrs_to_bool(obj: Any, attrs: Iterable[str], default: bool = None) -> None: """ Applies :func:`convert_to_bool` to the specified attributes of an object, modifying it in place. """ for a in attrs: setattr(obj, a, convert_to_bool(getattr(obj, a), default=default))
python
def convert_attrs_to_bool(obj: Any, attrs: Iterable[str], default: bool = None) -> None: """ Applies :func:`convert_to_bool` to the specified attributes of an object, modifying it in place. """ for a in attrs: setattr(obj, a, convert_to_bool(getattr(obj, a), default=default))
[ "def", "convert_attrs_to_bool", "(", "obj", ":", "Any", ",", "attrs", ":", "Iterable", "[", "str", "]", ",", "default", ":", "bool", "=", "None", ")", "->", "None", ":", "for", "a", "in", "attrs", ":", "setattr", "(", "obj", ",", "a", ",", "convert_to_bool", "(", "getattr", "(", "obj", ",", "a", ")", ",", "default", "=", "default", ")", ")" ]
Applies :func:`convert_to_bool` to the specified attributes of an object, modifying it in place.
[ "Applies", ":", "func", ":", "convert_to_bool", "to", "the", "specified", "attributes", "of", "an", "object", "modifying", "it", "in", "place", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L90-L98
RudolfCardinal/pythonlib
cardinal_pythonlib/convert.py
convert_attrs_to_uppercase
def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None: """ Converts the specified attributes of an object to upper case, modifying the object in place. """ for a in attrs: value = getattr(obj, a) if value is None: continue setattr(obj, a, value.upper())
python
def convert_attrs_to_uppercase(obj: Any, attrs: Iterable[str]) -> None: """ Converts the specified attributes of an object to upper case, modifying the object in place. """ for a in attrs: value = getattr(obj, a) if value is None: continue setattr(obj, a, value.upper())
[ "def", "convert_attrs_to_uppercase", "(", "obj", ":", "Any", ",", "attrs", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "for", "a", "in", "attrs", ":", "value", "=", "getattr", "(", "obj", ",", "a", ")", "if", "value", "is", "None", ":", "continue", "setattr", "(", "obj", ",", "a", ",", "value", ".", "upper", "(", ")", ")" ]
Converts the specified attributes of an object to upper case, modifying the object in place.
[ "Converts", "the", "specified", "attributes", "of", "an", "object", "to", "upper", "case", "modifying", "the", "object", "in", "place", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L101-L110
RudolfCardinal/pythonlib
cardinal_pythonlib/convert.py
convert_attrs_to_lowercase
def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None: """ Converts the specified attributes of an object to lower case, modifying the object in place. """ for a in attrs: value = getattr(obj, a) if value is None: continue setattr(obj, a, value.lower())
python
def convert_attrs_to_lowercase(obj: Any, attrs: Iterable[str]) -> None: """ Converts the specified attributes of an object to lower case, modifying the object in place. """ for a in attrs: value = getattr(obj, a) if value is None: continue setattr(obj, a, value.lower())
[ "def", "convert_attrs_to_lowercase", "(", "obj", ":", "Any", ",", "attrs", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "for", "a", "in", "attrs", ":", "value", "=", "getattr", "(", "obj", ",", "a", ")", "if", "value", "is", "None", ":", "continue", "setattr", "(", "obj", ",", "a", ",", "value", ".", "lower", "(", ")", ")" ]
Converts the specified attributes of an object to lower case, modifying the object in place.
[ "Converts", "the", "specified", "attributes", "of", "an", "object", "to", "lower", "case", "modifying", "the", "object", "in", "place", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L113-L122
RudolfCardinal/pythonlib
cardinal_pythonlib/convert.py
convert_attrs_to_int
def convert_attrs_to_int(obj: Any, attrs: Iterable[str], default: int = None) -> None: """ Applies :func:`convert_to_int` to the specified attributes of an object, modifying it in place. """ for a in attrs: value = convert_to_int(getattr(obj, a), default=default) setattr(obj, a, value)
python
def convert_attrs_to_int(obj: Any, attrs: Iterable[str], default: int = None) -> None: """ Applies :func:`convert_to_int` to the specified attributes of an object, modifying it in place. """ for a in attrs: value = convert_to_int(getattr(obj, a), default=default) setattr(obj, a, value)
[ "def", "convert_attrs_to_int", "(", "obj", ":", "Any", ",", "attrs", ":", "Iterable", "[", "str", "]", ",", "default", ":", "int", "=", "None", ")", "->", "None", ":", "for", "a", "in", "attrs", ":", "value", "=", "convert_to_int", "(", "getattr", "(", "obj", ",", "a", ")", ",", "default", "=", "default", ")", "setattr", "(", "obj", ",", "a", ",", "value", ")" ]
Applies :func:`convert_to_int` to the specified attributes of an object, modifying it in place.
[ "Applies", ":", "func", ":", "convert_to_int", "to", "the", "specified", "attributes", "of", "an", "object", "modifying", "it", "in", "place", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L125-L134
RudolfCardinal/pythonlib
cardinal_pythonlib/convert.py
hex_xformat_decode
def hex_xformat_decode(s: str) -> Optional[bytes]: """ Reverse :func:`hex_xformat_encode`. The parameter is a hex-encoded BLOB like .. code-block:: none "X'CDE7A24B1A9DBA3148BCB7A0B9DA5BB6A424486C'" Original purpose and notes: - SPECIAL HANDLING for BLOBs: a string like ``X'01FF'`` means a hex-encoded BLOB. Titanium is rubbish at BLOBs, so we encode them as special string literals. - SQLite uses this notation: https://sqlite.org/lang_expr.html - Strip off the start and end and convert it to a byte array: http://stackoverflow.com/questions/5649407 """ if len(s) < 3 or not s.startswith("X'") or not s.endswith("'"): return None return binascii.unhexlify(s[2:-1])
python
def hex_xformat_decode(s: str) -> Optional[bytes]: """ Reverse :func:`hex_xformat_encode`. The parameter is a hex-encoded BLOB like .. code-block:: none "X'CDE7A24B1A9DBA3148BCB7A0B9DA5BB6A424486C'" Original purpose and notes: - SPECIAL HANDLING for BLOBs: a string like ``X'01FF'`` means a hex-encoded BLOB. Titanium is rubbish at BLOBs, so we encode them as special string literals. - SQLite uses this notation: https://sqlite.org/lang_expr.html - Strip off the start and end and convert it to a byte array: http://stackoverflow.com/questions/5649407 """ if len(s) < 3 or not s.startswith("X'") or not s.endswith("'"): return None return binascii.unhexlify(s[2:-1])
[ "def", "hex_xformat_decode", "(", "s", ":", "str", ")", "->", "Optional", "[", "bytes", "]", ":", "if", "len", "(", "s", ")", "<", "3", "or", "not", "s", ".", "startswith", "(", "\"X'\"", ")", "or", "not", "s", ".", "endswith", "(", "\"'\"", ")", ":", "return", "None", "return", "binascii", ".", "unhexlify", "(", "s", "[", "2", ":", "-", "1", "]", ")" ]
Reverse :func:`hex_xformat_encode`. The parameter is a hex-encoded BLOB like .. code-block:: none "X'CDE7A24B1A9DBA3148BCB7A0B9DA5BB6A424486C'" Original purpose and notes: - SPECIAL HANDLING for BLOBs: a string like ``X'01FF'`` means a hex-encoded BLOB. Titanium is rubbish at BLOBs, so we encode them as special string literals. - SQLite uses this notation: https://sqlite.org/lang_expr.html - Strip off the start and end and convert it to a byte array: http://stackoverflow.com/questions/5649407
[ "Reverse", ":", "func", ":", "hex_xformat_encode", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L171-L192
RudolfCardinal/pythonlib
cardinal_pythonlib/convert.py
base64_64format_decode
def base64_64format_decode(s: str) -> Optional[bytes]: """ Reverse :func:`base64_64format_encode`. Original purpose and notes: - THIS IS ANOTHER WAY OF DOING BLOBS: base64 encoding, e.g. a string like ``64'cGxlYXN1cmUu'`` is a base-64-encoded BLOB (the ``64'...'`` bit is my representation). - regex from http://stackoverflow.com/questions/475074 - better one from http://www.perlmonks.org/?node_id=775820 """ if len(s) < 4 or not s.startswith("64'") or not s.endswith("'"): return None return base64.b64decode(s[3:-1])
python
def base64_64format_decode(s: str) -> Optional[bytes]: """ Reverse :func:`base64_64format_encode`. Original purpose and notes: - THIS IS ANOTHER WAY OF DOING BLOBS: base64 encoding, e.g. a string like ``64'cGxlYXN1cmUu'`` is a base-64-encoded BLOB (the ``64'...'`` bit is my representation). - regex from http://stackoverflow.com/questions/475074 - better one from http://www.perlmonks.org/?node_id=775820 """ if len(s) < 4 or not s.startswith("64'") or not s.endswith("'"): return None return base64.b64decode(s[3:-1])
[ "def", "base64_64format_decode", "(", "s", ":", "str", ")", "->", "Optional", "[", "bytes", "]", ":", "if", "len", "(", "s", ")", "<", "4", "or", "not", "s", ".", "startswith", "(", "\"64'\"", ")", "or", "not", "s", ".", "endswith", "(", "\"'\"", ")", ":", "return", "None", "return", "base64", ".", "b64decode", "(", "s", "[", "3", ":", "-", "1", "]", ")" ]
Reverse :func:`base64_64format_encode`. Original purpose and notes: - THIS IS ANOTHER WAY OF DOING BLOBS: base64 encoding, e.g. a string like ``64'cGxlYXN1cmUu'`` is a base-64-encoded BLOB (the ``64'...'`` bit is my representation). - regex from http://stackoverflow.com/questions/475074 - better one from http://www.perlmonks.org/?node_id=775820
[ "Reverse", ":", "func", ":", "base64_64format_encode", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/convert.py#L212-L227
bbengfort/confire
confire/config.py
environ_setting
def environ_setting(name, default=None, required=True): """ Fetch setting from the environment. The bahavior of the setting if it is not in environment is as follows: 1. If it is required and the default is None, raise Exception 2. If it is requried and a default exists, return default 3. If it is not required and default is None, return None 4. If it is not required and default exists, return default """ if name not in os.environ and default is None: message = "The {0} ENVVAR is not set.".format(name) if required: raise ImproperlyConfigured(message) else: warnings.warn(ConfigurationMissing(message)) return os.environ.get(name, default)
python
def environ_setting(name, default=None, required=True): """ Fetch setting from the environment. The bahavior of the setting if it is not in environment is as follows: 1. If it is required and the default is None, raise Exception 2. If it is requried and a default exists, return default 3. If it is not required and default is None, return None 4. If it is not required and default exists, return default """ if name not in os.environ and default is None: message = "The {0} ENVVAR is not set.".format(name) if required: raise ImproperlyConfigured(message) else: warnings.warn(ConfigurationMissing(message)) return os.environ.get(name, default)
[ "def", "environ_setting", "(", "name", ",", "default", "=", "None", ",", "required", "=", "True", ")", ":", "if", "name", "not", "in", "os", ".", "environ", "and", "default", "is", "None", ":", "message", "=", "\"The {0} ENVVAR is not set.\"", ".", "format", "(", "name", ")", "if", "required", ":", "raise", "ImproperlyConfigured", "(", "message", ")", "else", ":", "warnings", ".", "warn", "(", "ConfigurationMissing", "(", "message", ")", ")", "return", "os", ".", "environ", ".", "get", "(", "name", ",", "default", ")" ]
Fetch setting from the environment. The bahavior of the setting if it is not in environment is as follows: 1. If it is required and the default is None, raise Exception 2. If it is requried and a default exists, return default 3. If it is not required and default is None, return None 4. If it is not required and default exists, return default
[ "Fetch", "setting", "from", "the", "environment", ".", "The", "bahavior", "of", "the", "setting", "if", "it", "is", "not", "in", "environment", "is", "as", "follows", ":" ]
train
https://github.com/bbengfort/confire/blob/0879aea2516b39a438e202dcc0c6882ca64eb613/confire/config.py#L55-L72
bbengfort/confire
confire/config.py
Configuration.load
def load(klass): """ Insantiates the configuration by attempting to load the configuration from YAML files specified by the CONF_PATH module variable. This should be the main entry point for configuration. """ config = klass() for path in klass.CONF_PATHS: if os.path.exists(path): with open(path, 'r') as conf: config.configure(yaml.safe_load(conf)) return config
python
def load(klass): """ Insantiates the configuration by attempting to load the configuration from YAML files specified by the CONF_PATH module variable. This should be the main entry point for configuration. """ config = klass() for path in klass.CONF_PATHS: if os.path.exists(path): with open(path, 'r') as conf: config.configure(yaml.safe_load(conf)) return config
[ "def", "load", "(", "klass", ")", ":", "config", "=", "klass", "(", ")", "for", "path", "in", "klass", ".", "CONF_PATHS", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "conf", ":", "config", ".", "configure", "(", "yaml", ".", "safe_load", "(", "conf", ")", ")", "return", "config" ]
Insantiates the configuration by attempting to load the configuration from YAML files specified by the CONF_PATH module variable. This should be the main entry point for configuration.
[ "Insantiates", "the", "configuration", "by", "attempting", "to", "load", "the", "configuration", "from", "YAML", "files", "specified", "by", "the", "CONF_PATH", "module", "variable", ".", "This", "should", "be", "the", "main", "entry", "point", "for", "configuration", "." ]
train
https://github.com/bbengfort/confire/blob/0879aea2516b39a438e202dcc0c6882ca64eb613/confire/config.py#L136-L147
bbengfort/confire
confire/config.py
Configuration.configure
def configure(self, conf={}): """ Allows updating of the configuration via a dictionary of configuration terms or a configuration object. Generally speaking, this method is utilized to configure the object from a JSON or YAML parsing. """ if not conf: return if isinstance(conf, Configuration): conf = dict(conf.options()) for key, value in conf.items(): opt = self.get(key, None) if isinstance(opt, Configuration): opt.configure(value) else: setattr(self, key, value)
python
def configure(self, conf={}): """ Allows updating of the configuration via a dictionary of configuration terms or a configuration object. Generally speaking, this method is utilized to configure the object from a JSON or YAML parsing. """ if not conf: return if isinstance(conf, Configuration): conf = dict(conf.options()) for key, value in conf.items(): opt = self.get(key, None) if isinstance(opt, Configuration): opt.configure(value) else: setattr(self, key, value)
[ "def", "configure", "(", "self", ",", "conf", "=", "{", "}", ")", ":", "if", "not", "conf", ":", "return", "if", "isinstance", "(", "conf", ",", "Configuration", ")", ":", "conf", "=", "dict", "(", "conf", ".", "options", "(", ")", ")", "for", "key", ",", "value", "in", "conf", ".", "items", "(", ")", ":", "opt", "=", "self", ".", "get", "(", "key", ",", "None", ")", "if", "isinstance", "(", "opt", ",", "Configuration", ")", ":", "opt", ".", "configure", "(", "value", ")", "else", ":", "setattr", "(", "self", ",", "key", ",", "value", ")" ]
Allows updating of the configuration via a dictionary of configuration terms or a configuration object. Generally speaking, this method is utilized to configure the object from a JSON or YAML parsing.
[ "Allows", "updating", "of", "the", "configuration", "via", "a", "dictionary", "of", "configuration", "terms", "or", "a", "configuration", "object", ".", "Generally", "speaking", "this", "method", "is", "utilized", "to", "configure", "the", "object", "from", "a", "JSON", "or", "YAML", "parsing", "." ]
train
https://github.com/bbengfort/confire/blob/0879aea2516b39a438e202dcc0c6882ca64eb613/confire/config.py#L149-L164
bbengfort/confire
confire/config.py
Configuration.options
def options(self): """ Returns an iterable of sorted option names in order to loop through all the configuration directives specified in the class. """ keys = self.__class__.__dict__.copy() keys.update(self.__dict__) keys = sorted(keys.keys()) for opt in keys: val = self.get(opt) if val is not None: yield opt, val
python
def options(self): """ Returns an iterable of sorted option names in order to loop through all the configuration directives specified in the class. """ keys = self.__class__.__dict__.copy() keys.update(self.__dict__) keys = sorted(keys.keys()) for opt in keys: val = self.get(opt) if val is not None: yield opt, val
[ "def", "options", "(", "self", ")", ":", "keys", "=", "self", ".", "__class__", ".", "__dict__", ".", "copy", "(", ")", "keys", ".", "update", "(", "self", ".", "__dict__", ")", "keys", "=", "sorted", "(", "keys", ".", "keys", "(", ")", ")", "for", "opt", "in", "keys", ":", "val", "=", "self", ".", "get", "(", "opt", ")", "if", "val", "is", "not", "None", ":", "yield", "opt", ",", "val" ]
Returns an iterable of sorted option names in order to loop through all the configuration directives specified in the class.
[ "Returns", "an", "iterable", "of", "sorted", "option", "names", "in", "order", "to", "loop", "through", "all", "the", "configuration", "directives", "specified", "in", "the", "class", "." ]
train
https://github.com/bbengfort/confire/blob/0879aea2516b39a438e202dcc0c6882ca64eb613/confire/config.py#L166-L178
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
formatdt
def formatdt(date: datetime.date, include_time: bool = True) -> str: """ Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy with no timezone (or, if ``include_time`` is ``False``, omit the time). """ if include_time: return date.strftime("%Y-%m-%dT%H:%M") else: return date.strftime("%Y-%m-%d")
python
def formatdt(date: datetime.date, include_time: bool = True) -> str: """ Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy with no timezone (or, if ``include_time`` is ``False``, omit the time). """ if include_time: return date.strftime("%Y-%m-%dT%H:%M") else: return date.strftime("%Y-%m-%d")
[ "def", "formatdt", "(", "date", ":", "datetime", ".", "date", ",", "include_time", ":", "bool", "=", "True", ")", "->", "str", ":", "if", "include_time", ":", "return", "date", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M\"", ")", "else", ":", "return", "date", ".", "strftime", "(", "\"%Y-%m-%d\"", ")" ]
Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy with no timezone (or, if ``include_time`` is ``False``, omit the time).
[ "Formats", "a", "datetime", ".", "date", "to", "ISO", "-", "8601", "basic", "format", "to", "minute", "accuracy", "with", "no", "timezone", "(", "or", "if", "include_time", "is", "False", "omit", "the", "time", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L130-L138
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
convert_duration
def convert_duration(duration: datetime.timedelta, units: str) -> Optional[float]: """ Convert a ``datetime.timedelta`` object -- a duration -- into other units. Possible units: ``s``, ``sec``, ``seconds`` ``m``, ``min``, ``minutes`` ``h``, ``hr``, ``hours`` ``d``, ``days`` ``w``, ``weeks`` ``y``, ``years`` """ if duration is None: return None s = duration.total_seconds() if units in ['s', 'sec', 'seconds']: return s if units in ['m', 'min', 'minutes']: return s / SECONDS_PER_MINUTE if units in ['h', 'hr', 'hours']: return s / SECONDS_PER_HOUR if units in ['d', 'days']: return s / SECONDS_PER_DAY if units in ['w', 'weeks']: return s / SECONDS_PER_WEEK if units in ['y', 'years']: return s / SECONDS_PER_YEAR raise ValueError("Unknown units: {}".format(units))
python
def convert_duration(duration: datetime.timedelta, units: str) -> Optional[float]: """ Convert a ``datetime.timedelta`` object -- a duration -- into other units. Possible units: ``s``, ``sec``, ``seconds`` ``m``, ``min``, ``minutes`` ``h``, ``hr``, ``hours`` ``d``, ``days`` ``w``, ``weeks`` ``y``, ``years`` """ if duration is None: return None s = duration.total_seconds() if units in ['s', 'sec', 'seconds']: return s if units in ['m', 'min', 'minutes']: return s / SECONDS_PER_MINUTE if units in ['h', 'hr', 'hours']: return s / SECONDS_PER_HOUR if units in ['d', 'days']: return s / SECONDS_PER_DAY if units in ['w', 'weeks']: return s / SECONDS_PER_WEEK if units in ['y', 'years']: return s / SECONDS_PER_YEAR raise ValueError("Unknown units: {}".format(units))
[ "def", "convert_duration", "(", "duration", ":", "datetime", ".", "timedelta", ",", "units", ":", "str", ")", "->", "Optional", "[", "float", "]", ":", "if", "duration", "is", "None", ":", "return", "None", "s", "=", "duration", ".", "total_seconds", "(", ")", "if", "units", "in", "[", "'s'", ",", "'sec'", ",", "'seconds'", "]", ":", "return", "s", "if", "units", "in", "[", "'m'", ",", "'min'", ",", "'minutes'", "]", ":", "return", "s", "/", "SECONDS_PER_MINUTE", "if", "units", "in", "[", "'h'", ",", "'hr'", ",", "'hours'", "]", ":", "return", "s", "/", "SECONDS_PER_HOUR", "if", "units", "in", "[", "'d'", ",", "'days'", "]", ":", "return", "s", "/", "SECONDS_PER_DAY", "if", "units", "in", "[", "'w'", ",", "'weeks'", "]", ":", "return", "s", "/", "SECONDS_PER_WEEK", "if", "units", "in", "[", "'y'", ",", "'years'", "]", ":", "return", "s", "/", "SECONDS_PER_YEAR", "raise", "ValueError", "(", "\"Unknown units: {}\"", ".", "format", "(", "units", ")", ")" ]
Convert a ``datetime.timedelta`` object -- a duration -- into other units. Possible units: ``s``, ``sec``, ``seconds`` ``m``, ``min``, ``minutes`` ``h``, ``hr``, ``hours`` ``d``, ``days`` ``w``, ``weeks`` ``y``, ``years``
[ "Convert", "a", "datetime", ".", "timedelta", "object", "--", "a", "duration", "--", "into", "other", "units", ".", "Possible", "units", ":" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L141-L169
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.overlaps
def overlaps(self, other: "Interval") -> bool: """ Does this interval overlap the other? Overlap: .. code-block:: none S--------S S---S S---S O---O O---O O---O Simpler method of testing is for non-overlap! .. code-block:: none S---S S---S O---O O---O """ return not(self.end <= other.start or self.start >= other.end)
python
def overlaps(self, other: "Interval") -> bool: """ Does this interval overlap the other? Overlap: .. code-block:: none S--------S S---S S---S O---O O---O O---O Simpler method of testing is for non-overlap! .. code-block:: none S---S S---S O---O O---O """ return not(self.end <= other.start or self.start >= other.end)
[ "def", "overlaps", "(", "self", ",", "other", ":", "\"Interval\"", ")", "->", "bool", ":", "return", "not", "(", "self", ".", "end", "<=", "other", ".", "start", "or", "self", ".", "start", ">=", "other", ".", "end", ")" ]
Does this interval overlap the other? Overlap: .. code-block:: none S--------S S---S S---S O---O O---O O---O Simpler method of testing is for non-overlap! .. code-block:: none S---S S---S O---O O---O
[ "Does", "this", "interval", "overlap", "the", "other?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L270-L288
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.contiguous
def contiguous(self, other: "Interval") -> bool: """ Does this interval overlap or touch the other? """ return not(self.end < other.start or self.start > other.end)
python
def contiguous(self, other: "Interval") -> bool: """ Does this interval overlap or touch the other? """ return not(self.end < other.start or self.start > other.end)
[ "def", "contiguous", "(", "self", ",", "other", ":", "\"Interval\"", ")", "->", "bool", ":", "return", "not", "(", "self", ".", "end", "<", "other", ".", "start", "or", "self", ".", "start", ">", "other", ".", "end", ")" ]
Does this interval overlap or touch the other?
[ "Does", "this", "interval", "overlap", "or", "touch", "the", "other?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L290-L294
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.contains
def contains(self, time: datetime.datetime, inclusive: bool = True) -> bool: """ Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks? """ if inclusive: return self.start <= time <= self.end else: return self.start < time < self.end
python
def contains(self, time: datetime.datetime, inclusive: bool = True) -> bool: """ Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks? """ if inclusive: return self.start <= time <= self.end else: return self.start < time < self.end
[ "def", "contains", "(", "self", ",", "time", ":", "datetime", ".", "datetime", ",", "inclusive", ":", "bool", "=", "True", ")", "->", "bool", ":", "if", "inclusive", ":", "return", "self", ".", "start", "<=", "time", "<=", "self", ".", "end", "else", ":", "return", "self", ".", "start", "<", "time", "<", "self", ".", "end" ]
Does the interval contain a momentary time? Args: time: the ``datetime.datetime`` to check inclusive: use inclusive rather than exclusive range checks?
[ "Does", "the", "interval", "contain", "a", "momentary", "time?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L296-L308
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.within
def within(self, other: "Interval", inclusive: bool = True) -> bool: """ Is this interval contained within the other? Args: other: the :class:`Interval` to check inclusive: use inclusive rather than exclusive range checks? """ if not other: return False if inclusive: return self.start >= other.start and self.end <= other.end else: return self.start > other.start and self.end < other.end
python
def within(self, other: "Interval", inclusive: bool = True) -> bool: """ Is this interval contained within the other? Args: other: the :class:`Interval` to check inclusive: use inclusive rather than exclusive range checks? """ if not other: return False if inclusive: return self.start >= other.start and self.end <= other.end else: return self.start > other.start and self.end < other.end
[ "def", "within", "(", "self", ",", "other", ":", "\"Interval\"", ",", "inclusive", ":", "bool", "=", "True", ")", "->", "bool", ":", "if", "not", "other", ":", "return", "False", "if", "inclusive", ":", "return", "self", ".", "start", ">=", "other", ".", "start", "and", "self", ".", "end", "<=", "other", ".", "end", "else", ":", "return", "self", ".", "start", ">", "other", ".", "start", "and", "self", ".", "end", "<", "other", ".", "end" ]
Is this interval contained within the other? Args: other: the :class:`Interval` to check inclusive: use inclusive rather than exclusive range checks?
[ "Is", "this", "interval", "contained", "within", "the", "other?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L310-L323
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.intersection
def intersection(self, other: "Interval") -> Optional["Interval"]: """ Returns an :class:`Interval` representing the intersection of this and the ``other``, or ``None`` if they don't overlap. """ if not self.contiguous(other): return None return Interval( max(self.start, other.start), min(self.end, other.end) )
python
def intersection(self, other: "Interval") -> Optional["Interval"]: """ Returns an :class:`Interval` representing the intersection of this and the ``other``, or ``None`` if they don't overlap. """ if not self.contiguous(other): return None return Interval( max(self.start, other.start), min(self.end, other.end) )
[ "def", "intersection", "(", "self", ",", "other", ":", "\"Interval\"", ")", "->", "Optional", "[", "\"Interval\"", "]", ":", "if", "not", "self", ".", "contiguous", "(", "other", ")", ":", "return", "None", "return", "Interval", "(", "max", "(", "self", ".", "start", ",", "other", ".", "start", ")", ",", "min", "(", "self", ".", "end", ",", "other", ".", "end", ")", ")" ]
Returns an :class:`Interval` representing the intersection of this and the ``other``, or ``None`` if they don't overlap.
[ "Returns", "an", ":", "class", ":", "Interval", "representing", "the", "intersection", "of", "this", "and", "the", "other", "or", "None", "if", "they", "don", "t", "overlap", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L334-L344
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.cut
def cut(self, times: Union[datetime.datetime, List[datetime.datetime]]) -> List["Interval"]: """ Returns a list of intervals produced by using times (a list of ``datetime.datetime`` objects, or a single such object) as a set of knives to slice this interval. """ if not isinstance(times, list): # Single time time = times if not self.contains(time): return [] return [ Interval(self.start, time), Interval(time, self.end) ] else: # Multiple times times = [t for t in times if self.contains(t)] # discard others times.sort() times = [self.start] + times + [self.end] intervals = [] for i in range(len(times) - 1): intervals.append(Interval(times[i], times[i + 1])) return intervals
python
def cut(self, times: Union[datetime.datetime, List[datetime.datetime]]) -> List["Interval"]: """ Returns a list of intervals produced by using times (a list of ``datetime.datetime`` objects, or a single such object) as a set of knives to slice this interval. """ if not isinstance(times, list): # Single time time = times if not self.contains(time): return [] return [ Interval(self.start, time), Interval(time, self.end) ] else: # Multiple times times = [t for t in times if self.contains(t)] # discard others times.sort() times = [self.start] + times + [self.end] intervals = [] for i in range(len(times) - 1): intervals.append(Interval(times[i], times[i + 1])) return intervals
[ "def", "cut", "(", "self", ",", "times", ":", "Union", "[", "datetime", ".", "datetime", ",", "List", "[", "datetime", ".", "datetime", "]", "]", ")", "->", "List", "[", "\"Interval\"", "]", ":", "if", "not", "isinstance", "(", "times", ",", "list", ")", ":", "# Single time", "time", "=", "times", "if", "not", "self", ".", "contains", "(", "time", ")", ":", "return", "[", "]", "return", "[", "Interval", "(", "self", ".", "start", ",", "time", ")", ",", "Interval", "(", "time", ",", "self", ".", "end", ")", "]", "else", ":", "# Multiple times", "times", "=", "[", "t", "for", "t", "in", "times", "if", "self", ".", "contains", "(", "t", ")", "]", "# discard others", "times", ".", "sort", "(", ")", "times", "=", "[", "self", ".", "start", "]", "+", "times", "+", "[", "self", ".", "end", "]", "intervals", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "times", ")", "-", "1", ")", ":", "intervals", ".", "append", "(", "Interval", "(", "times", "[", "i", "]", ",", "times", "[", "i", "+", "1", "]", ")", ")", "return", "intervals" ]
Returns a list of intervals produced by using times (a list of ``datetime.datetime`` objects, or a single such object) as a set of knives to slice this interval.
[ "Returns", "a", "list", "of", "intervals", "produced", "by", "using", "times", "(", "a", "list", "of", "datetime", ".", "datetime", "objects", "or", "a", "single", "such", "object", ")", "as", "a", "set", "of", "knives", "to", "slice", "this", "interval", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L346-L370
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.wholeday
def wholeday(date: datetime.date) -> "Interval": """ Returns an :class:`Interval` covering the date given (midnight at the start of that day to midnight at the start of the next day). """ start = datetime.datetime.combine(date, datetime.time()) return Interval( start, start + datetime.timedelta(days=1) )
python
def wholeday(date: datetime.date) -> "Interval": """ Returns an :class:`Interval` covering the date given (midnight at the start of that day to midnight at the start of the next day). """ start = datetime.datetime.combine(date, datetime.time()) return Interval( start, start + datetime.timedelta(days=1) )
[ "def", "wholeday", "(", "date", ":", "datetime", ".", "date", ")", "->", "\"Interval\"", ":", "start", "=", "datetime", ".", "datetime", ".", "combine", "(", "date", ",", "datetime", ".", "time", "(", ")", ")", "return", "Interval", "(", "start", ",", "start", "+", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", ")" ]
Returns an :class:`Interval` covering the date given (midnight at the start of that day to midnight at the start of the next day).
[ "Returns", "an", ":", "class", ":", "Interval", "covering", "the", "date", "given", "(", "midnight", "at", "the", "start", "of", "that", "day", "to", "midnight", "at", "the", "start", "of", "the", "next", "day", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L387-L396
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.daytime
def daytime(date: datetime.date, daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H), nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \ -> "Interval": """ Returns an :class:`Interval` representing daytime on the date given. """ return Interval( datetime.datetime.combine(date, daybreak), datetime.datetime.combine(date, nightfall), )
python
def daytime(date: datetime.date, daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H), nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \ -> "Interval": """ Returns an :class:`Interval` representing daytime on the date given. """ return Interval( datetime.datetime.combine(date, daybreak), datetime.datetime.combine(date, nightfall), )
[ "def", "daytime", "(", "date", ":", "datetime", ".", "date", ",", "daybreak", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_START_H", ")", ",", "nightfall", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_END_H", ")", ")", "->", "\"Interval\"", ":", "return", "Interval", "(", "datetime", ".", "datetime", ".", "combine", "(", "date", ",", "daybreak", ")", ",", "datetime", ".", "datetime", ".", "combine", "(", "date", ",", "nightfall", ")", ",", ")" ]
Returns an :class:`Interval` representing daytime on the date given.
[ "Returns", "an", ":", "class", ":", "Interval", "representing", "daytime", "on", "the", "date", "given", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L399-L409
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.dayspan
def dayspan(startdate: datetime.date, enddate: datetime.date, include_end: bool = True) -> Optional["Interval"]: """ Returns an :class:`Interval` representing the date range given, from midnight at the start of the first day to midnight at the end of the last (i.e. at the start of the next day after the last), or if include_end is False, 24h before that. If the parameters are invalid, returns ``None``. """ if enddate < startdate: return None if enddate == startdate and include_end: return None start_dt = datetime.datetime.combine(startdate, datetime.time()) end_dt = datetime.datetime.combine(enddate, datetime.time()) if include_end: end_dt += datetime.timedelta(days=1) return Interval(start_dt, end_dt)
python
def dayspan(startdate: datetime.date, enddate: datetime.date, include_end: bool = True) -> Optional["Interval"]: """ Returns an :class:`Interval` representing the date range given, from midnight at the start of the first day to midnight at the end of the last (i.e. at the start of the next day after the last), or if include_end is False, 24h before that. If the parameters are invalid, returns ``None``. """ if enddate < startdate: return None if enddate == startdate and include_end: return None start_dt = datetime.datetime.combine(startdate, datetime.time()) end_dt = datetime.datetime.combine(enddate, datetime.time()) if include_end: end_dt += datetime.timedelta(days=1) return Interval(start_dt, end_dt)
[ "def", "dayspan", "(", "startdate", ":", "datetime", ".", "date", ",", "enddate", ":", "datetime", ".", "date", ",", "include_end", ":", "bool", "=", "True", ")", "->", "Optional", "[", "\"Interval\"", "]", ":", "if", "enddate", "<", "startdate", ":", "return", "None", "if", "enddate", "==", "startdate", "and", "include_end", ":", "return", "None", "start_dt", "=", "datetime", ".", "datetime", ".", "combine", "(", "startdate", ",", "datetime", ".", "time", "(", ")", ")", "end_dt", "=", "datetime", ".", "datetime", ".", "combine", "(", "enddate", ",", "datetime", ".", "time", "(", ")", ")", "if", "include_end", ":", "end_dt", "+=", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", "return", "Interval", "(", "start_dt", ",", "end_dt", ")" ]
Returns an :class:`Interval` representing the date range given, from midnight at the start of the first day to midnight at the end of the last (i.e. at the start of the next day after the last), or if include_end is False, 24h before that. If the parameters are invalid, returns ``None``.
[ "Returns", "an", ":", "class", ":", "Interval", "representing", "the", "date", "range", "given", "from", "midnight", "at", "the", "start", "of", "the", "first", "day", "to", "midnight", "at", "the", "end", "of", "the", "last", "(", "i", ".", "e", ".", "at", "the", "start", "of", "the", "next", "day", "after", "the", "last", ")", "or", "if", "include_end", "is", "False", "24h", "before", "that", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L412-L431
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.component_on_date
def component_on_date(self, date: datetime.date) -> Optional["Interval"]: """ Returns the part of this interval that falls on the date given, or ``None`` if the interval doesn't have any part during that date. """ return self.intersection(Interval.wholeday(date))
python
def component_on_date(self, date: datetime.date) -> Optional["Interval"]: """ Returns the part of this interval that falls on the date given, or ``None`` if the interval doesn't have any part during that date. """ return self.intersection(Interval.wholeday(date))
[ "def", "component_on_date", "(", "self", ",", "date", ":", "datetime", ".", "date", ")", "->", "Optional", "[", "\"Interval\"", "]", ":", "return", "self", ".", "intersection", "(", "Interval", ".", "wholeday", "(", "date", ")", ")" ]
Returns the part of this interval that falls on the date given, or ``None`` if the interval doesn't have any part during that date.
[ "Returns", "the", "part", "of", "this", "interval", "that", "falls", "on", "the", "date", "given", "or", "None", "if", "the", "interval", "doesn", "t", "have", "any", "part", "during", "that", "date", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L433-L438
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.day_night_duration
def day_night_duration( self, daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H), nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \ -> Tuple[datetime.timedelta, datetime.timedelta]: """ Returns a ``(day, night)`` tuple of ``datetime.timedelta`` objects giving the duration of this interval that falls into day and night respectively. """ daytotal = datetime.timedelta() nighttotal = datetime.timedelta() startdate = self.start.date() enddate = self.end.date() ndays = (enddate - startdate).days + 1 for i in range(ndays): date = startdate + datetime.timedelta(days=i) component = self.component_on_date(date) # ... an interval on a single day day = Interval.daytime(date, daybreak, nightfall) daypart = component.intersection(day) if daypart is not None: daytotal += daypart.duration() nighttotal += component.duration() - daypart.duration() else: nighttotal += component.duration() return daytotal, nighttotal
python
def day_night_duration( self, daybreak: datetime.time = datetime.time(NORMAL_DAY_START_H), nightfall: datetime.time = datetime.time(NORMAL_DAY_END_H)) \ -> Tuple[datetime.timedelta, datetime.timedelta]: """ Returns a ``(day, night)`` tuple of ``datetime.timedelta`` objects giving the duration of this interval that falls into day and night respectively. """ daytotal = datetime.timedelta() nighttotal = datetime.timedelta() startdate = self.start.date() enddate = self.end.date() ndays = (enddate - startdate).days + 1 for i in range(ndays): date = startdate + datetime.timedelta(days=i) component = self.component_on_date(date) # ... an interval on a single day day = Interval.daytime(date, daybreak, nightfall) daypart = component.intersection(day) if daypart is not None: daytotal += daypart.duration() nighttotal += component.duration() - daypart.duration() else: nighttotal += component.duration() return daytotal, nighttotal
[ "def", "day_night_duration", "(", "self", ",", "daybreak", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_START_H", ")", ",", "nightfall", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_END_H", ")", ")", "->", "Tuple", "[", "datetime", ".", "timedelta", ",", "datetime", ".", "timedelta", "]", ":", "daytotal", "=", "datetime", ".", "timedelta", "(", ")", "nighttotal", "=", "datetime", ".", "timedelta", "(", ")", "startdate", "=", "self", ".", "start", ".", "date", "(", ")", "enddate", "=", "self", ".", "end", ".", "date", "(", ")", "ndays", "=", "(", "enddate", "-", "startdate", ")", ".", "days", "+", "1", "for", "i", "in", "range", "(", "ndays", ")", ":", "date", "=", "startdate", "+", "datetime", ".", "timedelta", "(", "days", "=", "i", ")", "component", "=", "self", ".", "component_on_date", "(", "date", ")", "# ... an interval on a single day", "day", "=", "Interval", ".", "daytime", "(", "date", ",", "daybreak", ",", "nightfall", ")", "daypart", "=", "component", ".", "intersection", "(", "day", ")", "if", "daypart", "is", "not", "None", ":", "daytotal", "+=", "daypart", ".", "duration", "(", ")", "nighttotal", "+=", "component", ".", "duration", "(", ")", "-", "daypart", ".", "duration", "(", ")", "else", ":", "nighttotal", "+=", "component", ".", "duration", "(", ")", "return", "daytotal", ",", "nighttotal" ]
Returns a ``(day, night)`` tuple of ``datetime.timedelta`` objects giving the duration of this interval that falls into day and night respectively.
[ "Returns", "a", "(", "day", "night", ")", "tuple", "of", "datetime", ".", "timedelta", "objects", "giving", "the", "duration", "of", "this", "interval", "that", "falls", "into", "day", "and", "night", "respectively", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L440-L466
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.duration_outside_nwh
def duration_outside_nwh( self, starttime: datetime.time = datetime.time(NORMAL_DAY_START_H), endtime: datetime.time = datetime.time(NORMAL_DAY_END_H), weekdays_only: bool = False, weekends_only: bool = False) -> datetime.timedelta: """ Returns a duration (a ``datetime.timedelta`` object) representing the number of hours outside normal working hours. This is not simply a subset of :meth:`day_night_duration`, because weekends are treated differently (they are always out of hours). The options allow the calculation of components on weekdays or weekends only. """ if weekdays_only and weekends_only: raise ValueError("Can't have weekdays_only and weekends_only") ooh = datetime.timedelta() # ooh = out of (normal) hours startdate = self.start.date() enddate = self.end.date() ndays = (enddate - startdate).days + 1 for i in range(ndays): date = startdate + datetime.timedelta(days=i) component = self.component_on_date(date) # ... an interval on a single day if not is_normal_working_day(date): if weekdays_only: continue ooh += component.duration() # all is out-of-normal-hours else: if weekends_only: continue normalday = Interval.daytime(date, starttime, endtime) normalpart = component.intersection(normalday) if normalpart is not None: ooh += component.duration() - normalpart.duration() else: ooh += component.duration() return ooh
python
def duration_outside_nwh( self, starttime: datetime.time = datetime.time(NORMAL_DAY_START_H), endtime: datetime.time = datetime.time(NORMAL_DAY_END_H), weekdays_only: bool = False, weekends_only: bool = False) -> datetime.timedelta: """ Returns a duration (a ``datetime.timedelta`` object) representing the number of hours outside normal working hours. This is not simply a subset of :meth:`day_night_duration`, because weekends are treated differently (they are always out of hours). The options allow the calculation of components on weekdays or weekends only. """ if weekdays_only and weekends_only: raise ValueError("Can't have weekdays_only and weekends_only") ooh = datetime.timedelta() # ooh = out of (normal) hours startdate = self.start.date() enddate = self.end.date() ndays = (enddate - startdate).days + 1 for i in range(ndays): date = startdate + datetime.timedelta(days=i) component = self.component_on_date(date) # ... an interval on a single day if not is_normal_working_day(date): if weekdays_only: continue ooh += component.duration() # all is out-of-normal-hours else: if weekends_only: continue normalday = Interval.daytime(date, starttime, endtime) normalpart = component.intersection(normalday) if normalpart is not None: ooh += component.duration() - normalpart.duration() else: ooh += component.duration() return ooh
[ "def", "duration_outside_nwh", "(", "self", ",", "starttime", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_START_H", ")", ",", "endtime", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_END_H", ")", ",", "weekdays_only", ":", "bool", "=", "False", ",", "weekends_only", ":", "bool", "=", "False", ")", "->", "datetime", ".", "timedelta", ":", "if", "weekdays_only", "and", "weekends_only", ":", "raise", "ValueError", "(", "\"Can't have weekdays_only and weekends_only\"", ")", "ooh", "=", "datetime", ".", "timedelta", "(", ")", "# ooh = out of (normal) hours", "startdate", "=", "self", ".", "start", ".", "date", "(", ")", "enddate", "=", "self", ".", "end", ".", "date", "(", ")", "ndays", "=", "(", "enddate", "-", "startdate", ")", ".", "days", "+", "1", "for", "i", "in", "range", "(", "ndays", ")", ":", "date", "=", "startdate", "+", "datetime", ".", "timedelta", "(", "days", "=", "i", ")", "component", "=", "self", ".", "component_on_date", "(", "date", ")", "# ... an interval on a single day", "if", "not", "is_normal_working_day", "(", "date", ")", ":", "if", "weekdays_only", ":", "continue", "ooh", "+=", "component", ".", "duration", "(", ")", "# all is out-of-normal-hours", "else", ":", "if", "weekends_only", ":", "continue", "normalday", "=", "Interval", ".", "daytime", "(", "date", ",", "starttime", ",", "endtime", ")", "normalpart", "=", "component", ".", "intersection", "(", "normalday", ")", "if", "normalpart", "is", "not", "None", ":", "ooh", "+=", "component", ".", "duration", "(", ")", "-", "normalpart", ".", "duration", "(", ")", "else", ":", "ooh", "+=", "component", ".", "duration", "(", ")", "return", "ooh" ]
Returns a duration (a ``datetime.timedelta`` object) representing the number of hours outside normal working hours. This is not simply a subset of :meth:`day_night_duration`, because weekends are treated differently (they are always out of hours). The options allow the calculation of components on weekdays or weekends only.
[ "Returns", "a", "duration", "(", "a", "datetime", ".", "timedelta", "object", ")", "representing", "the", "number", "of", "hours", "outside", "normal", "working", "hours", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L468-L507
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.n_weekends
def n_weekends(self) -> int: """ Returns the number of weekends that this interval covers. Includes partial weekends. """ startdate = self.start.date() enddate = self.end.date() ndays = (enddate - startdate).days + 1 in_weekend = False n_weekends = 0 for i in range(ndays): date = startdate + datetime.timedelta(days=i) if not in_weekend and is_weekend(date): in_weekend = True n_weekends += 1 elif in_weekend and not is_weekend(date): in_weekend = False return n_weekends
python
def n_weekends(self) -> int: """ Returns the number of weekends that this interval covers. Includes partial weekends. """ startdate = self.start.date() enddate = self.end.date() ndays = (enddate - startdate).days + 1 in_weekend = False n_weekends = 0 for i in range(ndays): date = startdate + datetime.timedelta(days=i) if not in_weekend and is_weekend(date): in_weekend = True n_weekends += 1 elif in_weekend and not is_weekend(date): in_weekend = False return n_weekends
[ "def", "n_weekends", "(", "self", ")", "->", "int", ":", "startdate", "=", "self", ".", "start", ".", "date", "(", ")", "enddate", "=", "self", ".", "end", ".", "date", "(", ")", "ndays", "=", "(", "enddate", "-", "startdate", ")", ".", "days", "+", "1", "in_weekend", "=", "False", "n_weekends", "=", "0", "for", "i", "in", "range", "(", "ndays", ")", ":", "date", "=", "startdate", "+", "datetime", ".", "timedelta", "(", "days", "=", "i", ")", "if", "not", "in_weekend", "and", "is_weekend", "(", "date", ")", ":", "in_weekend", "=", "True", "n_weekends", "+=", "1", "elif", "in_weekend", "and", "not", "is_weekend", "(", "date", ")", ":", "in_weekend", "=", "False", "return", "n_weekends" ]
Returns the number of weekends that this interval covers. Includes partial weekends.
[ "Returns", "the", "number", "of", "weekends", "that", "this", "interval", "covers", ".", "Includes", "partial", "weekends", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L509-L526
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
Interval.saturdays_of_weekends
def saturdays_of_weekends(self) -> Set[datetime.date]: """ Returns the dates of all Saturdays that are part of weekends that this interval covers (each Saturday representing a unique identifier for that weekend). The Saturday itself isn't necessarily the part of the weekend that the interval covers! """ startdate = self.start.date() enddate = self.end.date() ndays = (enddate - startdate).days + 1 saturdays = set() for i in range(ndays): date = startdate + datetime.timedelta(days=i) if is_saturday(date): saturdays.add(date) elif is_sunday(date): saturdays.add(date - datetime.timedelta(days=1)) return saturdays
python
def saturdays_of_weekends(self) -> Set[datetime.date]: """ Returns the dates of all Saturdays that are part of weekends that this interval covers (each Saturday representing a unique identifier for that weekend). The Saturday itself isn't necessarily the part of the weekend that the interval covers! """ startdate = self.start.date() enddate = self.end.date() ndays = (enddate - startdate).days + 1 saturdays = set() for i in range(ndays): date = startdate + datetime.timedelta(days=i) if is_saturday(date): saturdays.add(date) elif is_sunday(date): saturdays.add(date - datetime.timedelta(days=1)) return saturdays
[ "def", "saturdays_of_weekends", "(", "self", ")", "->", "Set", "[", "datetime", ".", "date", "]", ":", "startdate", "=", "self", ".", "start", ".", "date", "(", ")", "enddate", "=", "self", ".", "end", ".", "date", "(", ")", "ndays", "=", "(", "enddate", "-", "startdate", ")", ".", "days", "+", "1", "saturdays", "=", "set", "(", ")", "for", "i", "in", "range", "(", "ndays", ")", ":", "date", "=", "startdate", "+", "datetime", ".", "timedelta", "(", "days", "=", "i", ")", "if", "is_saturday", "(", "date", ")", ":", "saturdays", ".", "add", "(", "date", ")", "elif", "is_sunday", "(", "date", ")", ":", "saturdays", ".", "add", "(", "date", "-", "datetime", ".", "timedelta", "(", "days", "=", "1", ")", ")", "return", "saturdays" ]
Returns the dates of all Saturdays that are part of weekends that this interval covers (each Saturday representing a unique identifier for that weekend). The Saturday itself isn't necessarily the part of the weekend that the interval covers!
[ "Returns", "the", "dates", "of", "all", "Saturdays", "that", "are", "part", "of", "weekends", "that", "this", "interval", "covers", "(", "each", "Saturday", "representing", "a", "unique", "identifier", "for", "that", "weekend", ")", ".", "The", "Saturday", "itself", "isn", "t", "necessarily", "the", "part", "of", "the", "weekend", "that", "the", "interval", "covers!" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L528-L545
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.copy
def copy(self, no_overlap: bool = None, no_contiguous: bool = None) -> "IntervalList": """ Makes and returns a copy of the :class:`IntervalList`. The ``no_overlap``/``no_contiguous`` parameters can be changed. Args: no_overlap: merge intervals that overlap (now and on subsequent addition)? no_contiguous: if ``no_overlap`` is set, merge intervals that are contiguous too? """ if no_overlap is None: no_overlap = self.no_overlap if no_contiguous is None: no_contiguous = self.no_contiguous return IntervalList(self.intervals, no_overlap=no_overlap, no_contiguous=no_contiguous)
python
def copy(self, no_overlap: bool = None, no_contiguous: bool = None) -> "IntervalList": """ Makes and returns a copy of the :class:`IntervalList`. The ``no_overlap``/``no_contiguous`` parameters can be changed. Args: no_overlap: merge intervals that overlap (now and on subsequent addition)? no_contiguous: if ``no_overlap`` is set, merge intervals that are contiguous too? """ if no_overlap is None: no_overlap = self.no_overlap if no_contiguous is None: no_contiguous = self.no_contiguous return IntervalList(self.intervals, no_overlap=no_overlap, no_contiguous=no_contiguous)
[ "def", "copy", "(", "self", ",", "no_overlap", ":", "bool", "=", "None", ",", "no_contiguous", ":", "bool", "=", "None", ")", "->", "\"IntervalList\"", ":", "if", "no_overlap", "is", "None", ":", "no_overlap", "=", "self", ".", "no_overlap", "if", "no_contiguous", "is", "None", ":", "no_contiguous", "=", "self", ".", "no_contiguous", "return", "IntervalList", "(", "self", ".", "intervals", ",", "no_overlap", "=", "no_overlap", ",", "no_contiguous", "=", "no_contiguous", ")" ]
Makes and returns a copy of the :class:`IntervalList`. The ``no_overlap``/``no_contiguous`` parameters can be changed. Args: no_overlap: merge intervals that overlap (now and on subsequent addition)? no_contiguous: if ``no_overlap`` is set, merge intervals that are contiguous too?
[ "Makes", "and", "returns", "a", "copy", "of", "the", ":", "class", ":", "IntervalList", ".", "The", "no_overlap", "/", "no_contiguous", "parameters", "can", "be", "changed", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L605-L622
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.add
def add(self, interval: Interval) -> None: """ Adds an interval to the list. If ``self.no_overlap`` is True, as is the default, it will merge any overlapping intervals thus created. """ if interval is None: return if not isinstance(interval, Interval): raise TypeError( "Attempt to insert non-Interval into IntervalList") self.intervals.append(interval) self._tidy()
python
def add(self, interval: Interval) -> None: """ Adds an interval to the list. If ``self.no_overlap`` is True, as is the default, it will merge any overlapping intervals thus created. """ if interval is None: return if not isinstance(interval, Interval): raise TypeError( "Attempt to insert non-Interval into IntervalList") self.intervals.append(interval) self._tidy()
[ "def", "add", "(", "self", ",", "interval", ":", "Interval", ")", "->", "None", ":", "if", "interval", "is", "None", ":", "return", "if", "not", "isinstance", "(", "interval", ",", "Interval", ")", ":", "raise", "TypeError", "(", "\"Attempt to insert non-Interval into IntervalList\"", ")", "self", ".", "intervals", ".", "append", "(", "interval", ")", "self", ".", "_tidy", "(", ")" ]
Adds an interval to the list. If ``self.no_overlap`` is True, as is the default, it will merge any overlapping intervals thus created.
[ "Adds", "an", "interval", "to", "the", "list", ".", "If", "self", ".", "no_overlap", "is", "True", "as", "is", "the", "default", "it", "will", "merge", "any", "overlapping", "intervals", "thus", "created", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L634-L645
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList._tidy
def _tidy(self) -> None: """ Removes overlaps, etc., and sorts. """ if self.no_overlap: self.remove_overlap(self.no_contiguous) # will sort else: self._sort()
python
def _tidy(self) -> None: """ Removes overlaps, etc., and sorts. """ if self.no_overlap: self.remove_overlap(self.no_contiguous) # will sort else: self._sort()
[ "def", "_tidy", "(", "self", ")", "->", "None", ":", "if", "self", ".", "no_overlap", ":", "self", ".", "remove_overlap", "(", "self", ".", "no_contiguous", ")", "# will sort", "else", ":", "self", ".", "_sort", "(", ")" ]
Removes overlaps, etc., and sorts.
[ "Removes", "overlaps", "etc", ".", "and", "sorts", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L651-L658
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList._remove_overlap_sub
def _remove_overlap_sub(self, also_remove_contiguous: bool) -> bool: """ Called by :meth:`remove_overlap`. Removes the first overlap found. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging? Returns: bool: ``True`` if an overlap was removed; ``False`` otherwise """ # Returns for i in range(len(self.intervals)): for j in range(i + 1, len(self.intervals)): first = self.intervals[i] second = self.intervals[j] if also_remove_contiguous: test = first.contiguous(second) else: test = first.overlaps(second) if test: newint = first.union(second) self.intervals.pop(j) self.intervals.pop(i) # note that i must be less than j self.intervals.append(newint) return True return False
python
def _remove_overlap_sub(self, also_remove_contiguous: bool) -> bool: """ Called by :meth:`remove_overlap`. Removes the first overlap found. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging? Returns: bool: ``True`` if an overlap was removed; ``False`` otherwise """ # Returns for i in range(len(self.intervals)): for j in range(i + 1, len(self.intervals)): first = self.intervals[i] second = self.intervals[j] if also_remove_contiguous: test = first.contiguous(second) else: test = first.overlaps(second) if test: newint = first.union(second) self.intervals.pop(j) self.intervals.pop(i) # note that i must be less than j self.intervals.append(newint) return True return False
[ "def", "_remove_overlap_sub", "(", "self", ",", "also_remove_contiguous", ":", "bool", ")", "->", "bool", ":", "# Returns", "for", "i", "in", "range", "(", "len", "(", "self", ".", "intervals", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "len", "(", "self", ".", "intervals", ")", ")", ":", "first", "=", "self", ".", "intervals", "[", "i", "]", "second", "=", "self", ".", "intervals", "[", "j", "]", "if", "also_remove_contiguous", ":", "test", "=", "first", ".", "contiguous", "(", "second", ")", "else", ":", "test", "=", "first", ".", "overlaps", "(", "second", ")", "if", "test", ":", "newint", "=", "first", ".", "union", "(", "second", ")", "self", ".", "intervals", ".", "pop", "(", "j", ")", "self", ".", "intervals", ".", "pop", "(", "i", ")", "# note that i must be less than j", "self", ".", "intervals", ".", "append", "(", "newint", ")", "return", "True", "return", "False" ]
Called by :meth:`remove_overlap`. Removes the first overlap found. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging? Returns: bool: ``True`` if an overlap was removed; ``False`` otherwise
[ "Called", "by", ":", "meth", ":", "remove_overlap", ".", "Removes", "the", "first", "overlap", "found", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L666-L693
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.remove_overlap
def remove_overlap(self, also_remove_contiguous: bool = False) -> None: """ Merges any overlapping intervals. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging? """ overlap = True while overlap: overlap = self._remove_overlap_sub(also_remove_contiguous) self._sort()
python
def remove_overlap(self, also_remove_contiguous: bool = False) -> None: """ Merges any overlapping intervals. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging? """ overlap = True while overlap: overlap = self._remove_overlap_sub(also_remove_contiguous) self._sort()
[ "def", "remove_overlap", "(", "self", ",", "also_remove_contiguous", ":", "bool", "=", "False", ")", "->", "None", ":", "overlap", "=", "True", "while", "overlap", ":", "overlap", "=", "self", ".", "_remove_overlap_sub", "(", "also_remove_contiguous", ")", "self", ".", "_sort", "(", ")" ]
Merges any overlapping intervals. Args: also_remove_contiguous: treat contiguous (as well as overlapping) intervals as worthy of merging?
[ "Merges", "any", "overlapping", "intervals", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L695-L706
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList._any_overlap_or_contiguous
def _any_overlap_or_contiguous(self, test_overlap: bool) -> bool: """ Do any of the intervals overlap? Args: test_overlap: if ``True``, test for overlapping intervals; if ``False``, test for contiguous intervals. """ for i in range(len(self.intervals)): for j in range(i + 1, len(self.intervals)): first = self.intervals[i] second = self.intervals[j] if test_overlap: test = first.overlaps(second) else: test = first.contiguous(second) if test: return True return False
python
def _any_overlap_or_contiguous(self, test_overlap: bool) -> bool: """ Do any of the intervals overlap? Args: test_overlap: if ``True``, test for overlapping intervals; if ``False``, test for contiguous intervals. """ for i in range(len(self.intervals)): for j in range(i + 1, len(self.intervals)): first = self.intervals[i] second = self.intervals[j] if test_overlap: test = first.overlaps(second) else: test = first.contiguous(second) if test: return True return False
[ "def", "_any_overlap_or_contiguous", "(", "self", ",", "test_overlap", ":", "bool", ")", "->", "bool", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "intervals", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "len", "(", "self", ".", "intervals", ")", ")", ":", "first", "=", "self", ".", "intervals", "[", "i", "]", "second", "=", "self", ".", "intervals", "[", "j", "]", "if", "test_overlap", ":", "test", "=", "first", ".", "overlaps", "(", "second", ")", "else", ":", "test", "=", "first", ".", "contiguous", "(", "second", ")", "if", "test", ":", "return", "True", "return", "False" ]
Do any of the intervals overlap? Args: test_overlap: if ``True``, test for overlapping intervals; if ``False``, test for contiguous intervals.
[ "Do", "any", "of", "the", "intervals", "overlap?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L708-L726
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.start_datetime
def start_datetime(self) -> Optional[datetime.datetime]: """ Returns the start date of the set of intervals, or ``None`` if empty. """ if not self.intervals: return None return self.intervals[0].start
python
def start_datetime(self) -> Optional[datetime.datetime]: """ Returns the start date of the set of intervals, or ``None`` if empty. """ if not self.intervals: return None return self.intervals[0].start
[ "def", "start_datetime", "(", "self", ")", "->", "Optional", "[", "datetime", ".", "datetime", "]", ":", "if", "not", "self", ".", "intervals", ":", "return", "None", "return", "self", ".", "intervals", "[", "0", "]", ".", "start" ]
Returns the start date of the set of intervals, or ``None`` if empty.
[ "Returns", "the", "start", "date", "of", "the", "set", "of", "intervals", "or", "None", "if", "empty", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L754-L760
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.end_datetime
def end_datetime(self) -> Optional[datetime.datetime]: """ Returns the end date of the set of intervals, or ``None`` if empty. """ if not self.intervals: return None return max([x.end for x in self.intervals])
python
def end_datetime(self) -> Optional[datetime.datetime]: """ Returns the end date of the set of intervals, or ``None`` if empty. """ if not self.intervals: return None return max([x.end for x in self.intervals])
[ "def", "end_datetime", "(", "self", ")", "->", "Optional", "[", "datetime", ".", "datetime", "]", ":", "if", "not", "self", ".", "intervals", ":", "return", "None", "return", "max", "(", "[", "x", ".", "end", "for", "x", "in", "self", ".", "intervals", "]", ")" ]
Returns the end date of the set of intervals, or ``None`` if empty.
[ "Returns", "the", "end", "date", "of", "the", "set", "of", "intervals", "or", "None", "if", "empty", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L763-L769
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.start_date
def start_date(self) -> Optional[datetime.date]: """ Returns the start date of the set of intervals, or ``None`` if empty. """ if not self.intervals: return None return self.start_datetime().date()
python
def start_date(self) -> Optional[datetime.date]: """ Returns the start date of the set of intervals, or ``None`` if empty. """ if not self.intervals: return None return self.start_datetime().date()
[ "def", "start_date", "(", "self", ")", "->", "Optional", "[", "datetime", ".", "date", "]", ":", "if", "not", "self", ".", "intervals", ":", "return", "None", "return", "self", ".", "start_datetime", "(", ")", ".", "date", "(", ")" ]
Returns the start date of the set of intervals, or ``None`` if empty.
[ "Returns", "the", "start", "date", "of", "the", "set", "of", "intervals", "or", "None", "if", "empty", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L771-L777
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.end_date
def end_date(self) -> Optional[datetime.date]: """ Returns the end date of the set of intervals, or ``None`` if empty. """ if not self.intervals: return None return self.end_datetime().date()
python
def end_date(self) -> Optional[datetime.date]: """ Returns the end date of the set of intervals, or ``None`` if empty. """ if not self.intervals: return None return self.end_datetime().date()
[ "def", "end_date", "(", "self", ")", "->", "Optional", "[", "datetime", ".", "date", "]", ":", "if", "not", "self", ".", "intervals", ":", "return", "None", "return", "self", ".", "end_datetime", "(", ")", ".", "date", "(", ")" ]
Returns the end date of the set of intervals, or ``None`` if empty.
[ "Returns", "the", "end", "date", "of", "the", "set", "of", "intervals", "or", "None", "if", "empty", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L779-L785
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.extent
def extent(self) -> Optional[Interval]: """ Returns an :class:`Interval` running from the earliest start of an interval in this list to the latest end. Returns ``None`` if we are empty. """ if not self.intervals: return None return Interval(self.start_datetime(), self.end_datetime())
python
def extent(self) -> Optional[Interval]: """ Returns an :class:`Interval` running from the earliest start of an interval in this list to the latest end. Returns ``None`` if we are empty. """ if not self.intervals: return None return Interval(self.start_datetime(), self.end_datetime())
[ "def", "extent", "(", "self", ")", "->", "Optional", "[", "Interval", "]", ":", "if", "not", "self", ".", "intervals", ":", "return", "None", "return", "Interval", "(", "self", ".", "start_datetime", "(", ")", ",", "self", ".", "end_datetime", "(", ")", ")" ]
Returns an :class:`Interval` running from the earliest start of an interval in this list to the latest end. Returns ``None`` if we are empty.
[ "Returns", "an", ":", "class", ":", "Interval", "running", "from", "the", "earliest", "start", "of", "an", "interval", "in", "this", "list", "to", "the", "latest", "end", ".", "Returns", "None", "if", "we", "are", "empty", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L787-L795
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.total_duration
def total_duration(self) -> datetime.timedelta: """ Returns a ``datetime.timedelta`` object with the total sum of durations. If there is overlap, time will be double-counted, so beware! """ total = datetime.timedelta() for interval in self.intervals: total += interval.duration() return total
python
def total_duration(self) -> datetime.timedelta: """ Returns a ``datetime.timedelta`` object with the total sum of durations. If there is overlap, time will be double-counted, so beware! """ total = datetime.timedelta() for interval in self.intervals: total += interval.duration() return total
[ "def", "total_duration", "(", "self", ")", "->", "datetime", ".", "timedelta", ":", "total", "=", "datetime", ".", "timedelta", "(", ")", "for", "interval", "in", "self", ".", "intervals", ":", "total", "+=", "interval", ".", "duration", "(", ")", "return", "total" ]
Returns a ``datetime.timedelta`` object with the total sum of durations. If there is overlap, time will be double-counted, so beware!
[ "Returns", "a", "datetime", ".", "timedelta", "object", "with", "the", "total", "sum", "of", "durations", ".", "If", "there", "is", "overlap", "time", "will", "be", "double", "-", "counted", "so", "beware!" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L797-L805
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.get_overlaps
def get_overlaps(self) -> "IntervalList": """ Returns an :class:`IntervalList` containing intervals representing periods of overlap between intervals in this one. """ overlaps = IntervalList() for i in range(len(self.intervals)): for j in range(i + 1, len(self.intervals)): first = self.intervals[i] second = self.intervals[j] ol = first.intersection(second) if ol is not None: overlaps.add(ol) return overlaps
python
def get_overlaps(self) -> "IntervalList": """ Returns an :class:`IntervalList` containing intervals representing periods of overlap between intervals in this one. """ overlaps = IntervalList() for i in range(len(self.intervals)): for j in range(i + 1, len(self.intervals)): first = self.intervals[i] second = self.intervals[j] ol = first.intersection(second) if ol is not None: overlaps.add(ol) return overlaps
[ "def", "get_overlaps", "(", "self", ")", "->", "\"IntervalList\"", ":", "overlaps", "=", "IntervalList", "(", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "intervals", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "len", "(", "self", ".", "intervals", ")", ")", ":", "first", "=", "self", ".", "intervals", "[", "i", "]", "second", "=", "self", ".", "intervals", "[", "j", "]", "ol", "=", "first", ".", "intersection", "(", "second", ")", "if", "ol", "is", "not", "None", ":", "overlaps", ".", "add", "(", "ol", ")", "return", "overlaps" ]
Returns an :class:`IntervalList` containing intervals representing periods of overlap between intervals in this one.
[ "Returns", "an", ":", "class", ":", "IntervalList", "containing", "intervals", "representing", "periods", "of", "overlap", "between", "intervals", "in", "this", "one", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L811-L824
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.durations
def durations(self) -> List[datetime.timedelta]: """ Returns a list of ``datetime.timedelta`` objects representing the durations of each interval in our list. """ return [x.duration() for x in self.intervals]
python
def durations(self) -> List[datetime.timedelta]: """ Returns a list of ``datetime.timedelta`` objects representing the durations of each interval in our list. """ return [x.duration() for x in self.intervals]
[ "def", "durations", "(", "self", ")", "->", "List", "[", "datetime", ".", "timedelta", "]", ":", "return", "[", "x", ".", "duration", "(", ")", "for", "x", "in", "self", ".", "intervals", "]" ]
Returns a list of ``datetime.timedelta`` objects representing the durations of each interval in our list.
[ "Returns", "a", "list", "of", "datetime", ".", "timedelta", "objects", "representing", "the", "durations", "of", "each", "interval", "in", "our", "list", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L826-L831
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.longest_duration
def longest_duration(self) -> Optional[datetime.timedelta]: """ Returns the duration of the longest interval, or None if none. """ if not self.intervals: return None return max(self.durations())
python
def longest_duration(self) -> Optional[datetime.timedelta]: """ Returns the duration of the longest interval, or None if none. """ if not self.intervals: return None return max(self.durations())
[ "def", "longest_duration", "(", "self", ")", "->", "Optional", "[", "datetime", ".", "timedelta", "]", ":", "if", "not", "self", ".", "intervals", ":", "return", "None", "return", "max", "(", "self", ".", "durations", "(", ")", ")" ]
Returns the duration of the longest interval, or None if none.
[ "Returns", "the", "duration", "of", "the", "longest", "interval", "or", "None", "if", "none", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L833-L839
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.longest_interval
def longest_interval(self) -> Optional[Interval]: """ Returns the longest interval, or ``None`` if none. """ longest_duration = self.longest_duration() for i in self.intervals: if i.duration() == longest_duration: return i return None
python
def longest_interval(self) -> Optional[Interval]: """ Returns the longest interval, or ``None`` if none. """ longest_duration = self.longest_duration() for i in self.intervals: if i.duration() == longest_duration: return i return None
[ "def", "longest_interval", "(", "self", ")", "->", "Optional", "[", "Interval", "]", ":", "longest_duration", "=", "self", ".", "longest_duration", "(", ")", "for", "i", "in", "self", ".", "intervals", ":", "if", "i", ".", "duration", "(", ")", "==", "longest_duration", ":", "return", "i", "return", "None" ]
Returns the longest interval, or ``None`` if none.
[ "Returns", "the", "longest", "interval", "or", "None", "if", "none", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L841-L849
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.first_interval_starting
def first_interval_starting(self, start: datetime.datetime) -> \ Optional[Interval]: """ Returns our first interval that starts with the ``start`` parameter, or ``None``. """ for i in self.intervals: if i.start == start: return i return None
python
def first_interval_starting(self, start: datetime.datetime) -> \ Optional[Interval]: """ Returns our first interval that starts with the ``start`` parameter, or ``None``. """ for i in self.intervals: if i.start == start: return i return None
[ "def", "first_interval_starting", "(", "self", ",", "start", ":", "datetime", ".", "datetime", ")", "->", "Optional", "[", "Interval", "]", ":", "for", "i", "in", "self", ".", "intervals", ":", "if", "i", ".", "start", "==", "start", ":", "return", "i", "return", "None" ]
Returns our first interval that starts with the ``start`` parameter, or ``None``.
[ "Returns", "our", "first", "interval", "that", "starts", "with", "the", "start", "parameter", "or", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L869-L878
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.first_interval_ending
def first_interval_ending(self, end: datetime.datetime) \ -> Optional[Interval]: """ Returns our first interval that ends with the ``end`` parameter, or ``None``. """ for i in self.intervals: if i.end == end: return i return None
python
def first_interval_ending(self, end: datetime.datetime) \ -> Optional[Interval]: """ Returns our first interval that ends with the ``end`` parameter, or ``None``. """ for i in self.intervals: if i.end == end: return i return None
[ "def", "first_interval_ending", "(", "self", ",", "end", ":", "datetime", ".", "datetime", ")", "->", "Optional", "[", "Interval", "]", ":", "for", "i", "in", "self", ".", "intervals", ":", "if", "i", ".", "end", "==", "end", ":", "return", "i", "return", "None" ]
Returns our first interval that ends with the ``end`` parameter, or ``None``.
[ "Returns", "our", "first", "interval", "that", "ends", "with", "the", "end", "parameter", "or", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L880-L889
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.gaps
def gaps(self) -> "IntervalList": """ Returns all the gaps between intervals, as an :class:`IntervalList`. """ if len(self.intervals) < 2: return IntervalList(None) gaps = [] for i in range(len(self.intervals) - 1): gap = Interval( self.intervals[i].end, self.intervals[i + 1].start ) gaps.append(gap) return IntervalList(gaps)
python
def gaps(self) -> "IntervalList": """ Returns all the gaps between intervals, as an :class:`IntervalList`. """ if len(self.intervals) < 2: return IntervalList(None) gaps = [] for i in range(len(self.intervals) - 1): gap = Interval( self.intervals[i].end, self.intervals[i + 1].start ) gaps.append(gap) return IntervalList(gaps)
[ "def", "gaps", "(", "self", ")", "->", "\"IntervalList\"", ":", "if", "len", "(", "self", ".", "intervals", ")", "<", "2", ":", "return", "IntervalList", "(", "None", ")", "gaps", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "intervals", ")", "-", "1", ")", ":", "gap", "=", "Interval", "(", "self", ".", "intervals", "[", "i", "]", ".", "end", ",", "self", ".", "intervals", "[", "i", "+", "1", "]", ".", "start", ")", "gaps", ".", "append", "(", "gap", ")", "return", "IntervalList", "(", "gaps", ")" ]
Returns all the gaps between intervals, as an :class:`IntervalList`.
[ "Returns", "all", "the", "gaps", "between", "intervals", "as", "an", ":", "class", ":", "IntervalList", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L895-L908
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.subset
def subset(self, interval: Interval, flexibility: int = 2) -> "IntervalList": """ Returns an IntervalList that's a subset of this one, only containing intervals that meet the "interval" parameter criterion. What "meet" means is defined by the ``flexibility`` parameter. ``flexibility == 0``: permits only wholly contained intervals: .. code-block:: none interval: I----------------I intervals in self that will/won't be returned: N---N N---N Y---Y N---N N---N N---N N---N ``flexibility == 1``: permits overlapping intervals as well: .. code-block:: none I----------------I N---N Y---Y Y---Y Y---Y N---N N---N N---N ``flexibility == 2``: permits adjoining intervals as well: .. code-block:: none I----------------I N---N Y---Y Y---Y Y---Y N---N Y---Y Y---Y """ if flexibility not in [0, 1, 2]: raise ValueError("subset: bad flexibility value") permitted = [] for i in self.intervals: if flexibility == 0: ok = i.start > interval.start and i.end < interval.end elif flexibility == 1: ok = i.end > interval.start and i.start < interval.end else: ok = i.end >= interval.start and i.start <= interval.end if ok: permitted.append(i) return IntervalList(permitted)
python
def subset(self, interval: Interval, flexibility: int = 2) -> "IntervalList": """ Returns an IntervalList that's a subset of this one, only containing intervals that meet the "interval" parameter criterion. What "meet" means is defined by the ``flexibility`` parameter. ``flexibility == 0``: permits only wholly contained intervals: .. code-block:: none interval: I----------------I intervals in self that will/won't be returned: N---N N---N Y---Y N---N N---N N---N N---N ``flexibility == 1``: permits overlapping intervals as well: .. code-block:: none I----------------I N---N Y---Y Y---Y Y---Y N---N N---N N---N ``flexibility == 2``: permits adjoining intervals as well: .. code-block:: none I----------------I N---N Y---Y Y---Y Y---Y N---N Y---Y Y---Y """ if flexibility not in [0, 1, 2]: raise ValueError("subset: bad flexibility value") permitted = [] for i in self.intervals: if flexibility == 0: ok = i.start > interval.start and i.end < interval.end elif flexibility == 1: ok = i.end > interval.start and i.start < interval.end else: ok = i.end >= interval.start and i.start <= interval.end if ok: permitted.append(i) return IntervalList(permitted)
[ "def", "subset", "(", "self", ",", "interval", ":", "Interval", ",", "flexibility", ":", "int", "=", "2", ")", "->", "\"IntervalList\"", ":", "if", "flexibility", "not", "in", "[", "0", ",", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "\"subset: bad flexibility value\"", ")", "permitted", "=", "[", "]", "for", "i", "in", "self", ".", "intervals", ":", "if", "flexibility", "==", "0", ":", "ok", "=", "i", ".", "start", ">", "interval", ".", "start", "and", "i", ".", "end", "<", "interval", ".", "end", "elif", "flexibility", "==", "1", ":", "ok", "=", "i", ".", "end", ">", "interval", ".", "start", "and", "i", ".", "start", "<", "interval", ".", "end", "else", ":", "ok", "=", "i", ".", "end", ">=", "interval", ".", "start", "and", "i", ".", "start", "<=", "interval", ".", "end", "if", "ok", ":", "permitted", ".", "append", "(", "i", ")", "return", "IntervalList", "(", "permitted", ")" ]
Returns an IntervalList that's a subset of this one, only containing intervals that meet the "interval" parameter criterion. What "meet" means is defined by the ``flexibility`` parameter. ``flexibility == 0``: permits only wholly contained intervals: .. code-block:: none interval: I----------------I intervals in self that will/won't be returned: N---N N---N Y---Y N---N N---N N---N N---N ``flexibility == 1``: permits overlapping intervals as well: .. code-block:: none I----------------I N---N Y---Y Y---Y Y---Y N---N N---N N---N ``flexibility == 2``: permits adjoining intervals as well: .. code-block:: none I----------------I N---N Y---Y Y---Y Y---Y N---N Y---Y Y---Y
[ "Returns", "an", "IntervalList", "that", "s", "a", "subset", "of", "this", "one", "only", "containing", "intervals", "that", "meet", "the", "interval", "parameter", "criterion", ".", "What", "meet", "means", "is", "defined", "by", "the", "flexibility", "parameter", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L925-L974
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.gap_subset
def gap_subset(self, interval: Interval, flexibility: int = 2) -> "IntervalList": """ Returns an IntervalList that's a subset of this one, only containing *gaps* between intervals that meet the interval criterion. See :meth:`subset` for the meaning of parameters. """ return self.gaps().subset(interval, flexibility)
python
def gap_subset(self, interval: Interval, flexibility: int = 2) -> "IntervalList": """ Returns an IntervalList that's a subset of this one, only containing *gaps* between intervals that meet the interval criterion. See :meth:`subset` for the meaning of parameters. """ return self.gaps().subset(interval, flexibility)
[ "def", "gap_subset", "(", "self", ",", "interval", ":", "Interval", ",", "flexibility", ":", "int", "=", "2", ")", "->", "\"IntervalList\"", ":", "return", "self", ".", "gaps", "(", ")", ".", "subset", "(", "interval", ",", "flexibility", ")" ]
Returns an IntervalList that's a subset of this one, only containing *gaps* between intervals that meet the interval criterion. See :meth:`subset` for the meaning of parameters.
[ "Returns", "an", "IntervalList", "that", "s", "a", "subset", "of", "this", "one", "only", "containing", "*", "gaps", "*", "between", "intervals", "that", "meet", "the", "interval", "criterion", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L976-L984
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.n_weekends
def n_weekends(self) -> int: """ Returns the number of weekends that the intervals collectively touch (where "touching a weekend" means "including time on a Saturday or a Sunday"). """ saturdays = set() for interval in self.intervals: saturdays.update(interval.saturdays_of_weekends()) return len(saturdays)
python
def n_weekends(self) -> int: """ Returns the number of weekends that the intervals collectively touch (where "touching a weekend" means "including time on a Saturday or a Sunday"). """ saturdays = set() for interval in self.intervals: saturdays.update(interval.saturdays_of_weekends()) return len(saturdays)
[ "def", "n_weekends", "(", "self", ")", "->", "int", ":", "saturdays", "=", "set", "(", ")", "for", "interval", "in", "self", ".", "intervals", ":", "saturdays", ".", "update", "(", "interval", ".", "saturdays_of_weekends", "(", ")", ")", "return", "len", "(", "saturdays", ")" ]
Returns the number of weekends that the intervals collectively touch (where "touching a weekend" means "including time on a Saturday or a Sunday").
[ "Returns", "the", "number", "of", "weekends", "that", "the", "intervals", "collectively", "touch", "(", "where", "touching", "a", "weekend", "means", "including", "time", "on", "a", "Saturday", "or", "a", "Sunday", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L990-L999
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.duration_outside_nwh
def duration_outside_nwh( self, starttime: datetime.time = datetime.time(NORMAL_DAY_START_H), endtime: datetime.time = datetime.time(NORMAL_DAY_END_H)) \ -> datetime.timedelta: """ Returns the total duration outside normal working hours, i.e. evenings/nights, weekends (and Bank Holidays). """ total = datetime.timedelta() for interval in self.intervals: total += interval.duration_outside_nwh(starttime, endtime) return total
python
def duration_outside_nwh( self, starttime: datetime.time = datetime.time(NORMAL_DAY_START_H), endtime: datetime.time = datetime.time(NORMAL_DAY_END_H)) \ -> datetime.timedelta: """ Returns the total duration outside normal working hours, i.e. evenings/nights, weekends (and Bank Holidays). """ total = datetime.timedelta() for interval in self.intervals: total += interval.duration_outside_nwh(starttime, endtime) return total
[ "def", "duration_outside_nwh", "(", "self", ",", "starttime", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_START_H", ")", ",", "endtime", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_END_H", ")", ")", "->", "datetime", ".", "timedelta", ":", "total", "=", "datetime", ".", "timedelta", "(", ")", "for", "interval", "in", "self", ".", "intervals", ":", "total", "+=", "interval", ".", "duration_outside_nwh", "(", "starttime", ",", "endtime", ")", "return", "total" ]
Returns the total duration outside normal working hours, i.e. evenings/nights, weekends (and Bank Holidays).
[ "Returns", "the", "total", "duration", "outside", "normal", "working", "hours", "i", ".", "e", ".", "evenings", "/", "nights", "weekends", "(", "and", "Bank", "Holidays", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1001-L1013
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.max_consecutive_days
def max_consecutive_days(self) -> Optional[Tuple[int, Interval]]: """ The length of the longest sequence of days in which all days include an interval. Returns: tuple: ``(longest_length, longest_interval)`` where ``longest_interval`` is a :class:`Interval` containing the start and end date of the longest span -- or ``None`` if we contain no intervals. """ if len(self.intervals) == 0: return None startdate = self.start_date() enddate = self.end_date() seq = '' ndays = (enddate - startdate).days + 1 for i in range(ndays): date = startdate + datetime.timedelta(days=i) wholeday = Interval.wholeday(date) if any([x.overlaps(wholeday) for x in self.intervals]): seq += '+' else: seq += ' ' # noinspection PyTypeChecker longest = max(seq.split(), key=len) longest_len = len(longest) longest_idx = seq.index(longest) longest_interval = Interval.dayspan( startdate + datetime.timedelta(days=longest_idx), startdate + datetime.timedelta(days=longest_idx + longest_len) ) return longest_len, longest_interval
python
def max_consecutive_days(self) -> Optional[Tuple[int, Interval]]: """ The length of the longest sequence of days in which all days include an interval. Returns: tuple: ``(longest_length, longest_interval)`` where ``longest_interval`` is a :class:`Interval` containing the start and end date of the longest span -- or ``None`` if we contain no intervals. """ if len(self.intervals) == 0: return None startdate = self.start_date() enddate = self.end_date() seq = '' ndays = (enddate - startdate).days + 1 for i in range(ndays): date = startdate + datetime.timedelta(days=i) wholeday = Interval.wholeday(date) if any([x.overlaps(wholeday) for x in self.intervals]): seq += '+' else: seq += ' ' # noinspection PyTypeChecker longest = max(seq.split(), key=len) longest_len = len(longest) longest_idx = seq.index(longest) longest_interval = Interval.dayspan( startdate + datetime.timedelta(days=longest_idx), startdate + datetime.timedelta(days=longest_idx + longest_len) ) return longest_len, longest_interval
[ "def", "max_consecutive_days", "(", "self", ")", "->", "Optional", "[", "Tuple", "[", "int", ",", "Interval", "]", "]", ":", "if", "len", "(", "self", ".", "intervals", ")", "==", "0", ":", "return", "None", "startdate", "=", "self", ".", "start_date", "(", ")", "enddate", "=", "self", ".", "end_date", "(", ")", "seq", "=", "''", "ndays", "=", "(", "enddate", "-", "startdate", ")", ".", "days", "+", "1", "for", "i", "in", "range", "(", "ndays", ")", ":", "date", "=", "startdate", "+", "datetime", ".", "timedelta", "(", "days", "=", "i", ")", "wholeday", "=", "Interval", ".", "wholeday", "(", "date", ")", "if", "any", "(", "[", "x", ".", "overlaps", "(", "wholeday", ")", "for", "x", "in", "self", ".", "intervals", "]", ")", ":", "seq", "+=", "'+'", "else", ":", "seq", "+=", "' '", "# noinspection PyTypeChecker", "longest", "=", "max", "(", "seq", ".", "split", "(", ")", ",", "key", "=", "len", ")", "longest_len", "=", "len", "(", "longest", ")", "longest_idx", "=", "seq", ".", "index", "(", "longest", ")", "longest_interval", "=", "Interval", ".", "dayspan", "(", "startdate", "+", "datetime", ".", "timedelta", "(", "days", "=", "longest_idx", ")", ",", "startdate", "+", "datetime", ".", "timedelta", "(", "days", "=", "longest_idx", "+", "longest_len", ")", ")", "return", "longest_len", ",", "longest_interval" ]
The length of the longest sequence of days in which all days include an interval. Returns: tuple: ``(longest_length, longest_interval)`` where ``longest_interval`` is a :class:`Interval` containing the start and end date of the longest span -- or ``None`` if we contain no intervals.
[ "The", "length", "of", "the", "longest", "sequence", "of", "days", "in", "which", "all", "days", "include", "an", "interval", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1015-L1048
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList._sufficient_gaps
def _sufficient_gaps(self, startdate: datetime.date, enddate: datetime.date, requiredgaps: List[datetime.timedelta], flexibility: int) -> Tuple[bool, Optional[Interval]]: """ Are there sufficient gaps (specified by ``requiredgaps``) in the date range specified? This is a worker function for :meth:`sufficient_gaps`. """ requiredgaps = list(requiredgaps) # make a copy interval = Interval.dayspan(startdate, enddate, include_end=True) # log.debug(">>> _sufficient_gaps") gaps = self.gap_subset(interval, flexibility) gapdurations = gaps.durations() gaplist = gaps.list() gapdurations.sort(reverse=True) # longest gap first requiredgaps.sort(reverse=True) # longest gap first # log.debug("... gaps = {}".format(gaps)) # log.debug("... gapdurations = {}".format(gapdurations)) # log.debug("... requiredgaps = {}".format(requiredgaps)) while requiredgaps: # log.debug("... processing gap") if not gapdurations: # log.debug("<<< no gaps left") return False, None if gapdurations[0] < requiredgaps[0]: # log.debug("<<< longest gap is too short") return False, self.first_interval_ending(gaplist[0].start) gapdurations.pop(0) requiredgaps.pop(0) gaplist.pop(0) # ... keeps gaplist and gapdurations mapped to each other # log.debug("<<< success") return True, None
python
def _sufficient_gaps(self, startdate: datetime.date, enddate: datetime.date, requiredgaps: List[datetime.timedelta], flexibility: int) -> Tuple[bool, Optional[Interval]]: """ Are there sufficient gaps (specified by ``requiredgaps``) in the date range specified? This is a worker function for :meth:`sufficient_gaps`. """ requiredgaps = list(requiredgaps) # make a copy interval = Interval.dayspan(startdate, enddate, include_end=True) # log.debug(">>> _sufficient_gaps") gaps = self.gap_subset(interval, flexibility) gapdurations = gaps.durations() gaplist = gaps.list() gapdurations.sort(reverse=True) # longest gap first requiredgaps.sort(reverse=True) # longest gap first # log.debug("... gaps = {}".format(gaps)) # log.debug("... gapdurations = {}".format(gapdurations)) # log.debug("... requiredgaps = {}".format(requiredgaps)) while requiredgaps: # log.debug("... processing gap") if not gapdurations: # log.debug("<<< no gaps left") return False, None if gapdurations[0] < requiredgaps[0]: # log.debug("<<< longest gap is too short") return False, self.first_interval_ending(gaplist[0].start) gapdurations.pop(0) requiredgaps.pop(0) gaplist.pop(0) # ... keeps gaplist and gapdurations mapped to each other # log.debug("<<< success") return True, None
[ "def", "_sufficient_gaps", "(", "self", ",", "startdate", ":", "datetime", ".", "date", ",", "enddate", ":", "datetime", ".", "date", ",", "requiredgaps", ":", "List", "[", "datetime", ".", "timedelta", "]", ",", "flexibility", ":", "int", ")", "->", "Tuple", "[", "bool", ",", "Optional", "[", "Interval", "]", "]", ":", "requiredgaps", "=", "list", "(", "requiredgaps", ")", "# make a copy", "interval", "=", "Interval", ".", "dayspan", "(", "startdate", ",", "enddate", ",", "include_end", "=", "True", ")", "# log.debug(\">>> _sufficient_gaps\")", "gaps", "=", "self", ".", "gap_subset", "(", "interval", ",", "flexibility", ")", "gapdurations", "=", "gaps", ".", "durations", "(", ")", "gaplist", "=", "gaps", ".", "list", "(", ")", "gapdurations", ".", "sort", "(", "reverse", "=", "True", ")", "# longest gap first", "requiredgaps", ".", "sort", "(", "reverse", "=", "True", ")", "# longest gap first", "# log.debug(\"... gaps = {}\".format(gaps))", "# log.debug(\"... gapdurations = {}\".format(gapdurations))", "# log.debug(\"... requiredgaps = {}\".format(requiredgaps))", "while", "requiredgaps", ":", "# log.debug(\"... processing gap\")", "if", "not", "gapdurations", ":", "# log.debug(\"<<< no gaps left\")", "return", "False", ",", "None", "if", "gapdurations", "[", "0", "]", "<", "requiredgaps", "[", "0", "]", ":", "# log.debug(\"<<< longest gap is too short\")", "return", "False", ",", "self", ".", "first_interval_ending", "(", "gaplist", "[", "0", "]", ".", "start", ")", "gapdurations", ".", "pop", "(", "0", ")", "requiredgaps", ".", "pop", "(", "0", ")", "gaplist", ".", "pop", "(", "0", ")", "# ... keeps gaplist and gapdurations mapped to each other", "# log.debug(\"<<< success\")", "return", "True", ",", "None" ]
Are there sufficient gaps (specified by ``requiredgaps``) in the date range specified? This is a worker function for :meth:`sufficient_gaps`.
[ "Are", "there", "sufficient", "gaps", "(", "specified", "by", "requiredgaps", ")", "in", "the", "date", "range", "specified?", "This", "is", "a", "worker", "function", "for", ":", "meth", ":", "sufficient_gaps", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1050-L1083
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.sufficient_gaps
def sufficient_gaps(self, every_n_days: int, requiredgaps: List[datetime.timedelta], flexibility: int = 2) \ -> Tuple[bool, Optional[Interval]]: """ Are gaps present sufficiently often? For example: .. code-block:: python every_n_days=21 requiredgaps=[ datetime.timedelta(hours=62), datetime.timedelta(hours=48), ] ... means "is there at least one 62-hour gap and one (separate) 48-hour gap in every possible 21-day sequence within the IntervalList? - If ``flexibility == 0``: gaps must be WHOLLY WITHIN the interval. - If ``flexibility == 1``: gaps may OVERLAP the edges of the interval. - If ``flexibility == 2``: gaps may ABUT the edges of the interval. Returns ``(True, None)`` or ``(False, first_failure_interval)``. """ if len(self.intervals) < 2: return False, None startdate = self.start_date() enddate = self.end_date() ndays = (enddate - startdate).days + 1 if ndays <= every_n_days: # Our interval is too short, or just right return self._sufficient_gaps(startdate, enddate, requiredgaps, flexibility) for i in range(ndays - every_n_days): j = i + every_n_days a = startdate + datetime.timedelta(days=i) b = startdate + datetime.timedelta(days=j) sufficient, ffi = self._sufficient_gaps(a, b, requiredgaps, flexibility) if not sufficient: return False, ffi return True, None
python
def sufficient_gaps(self, every_n_days: int, requiredgaps: List[datetime.timedelta], flexibility: int = 2) \ -> Tuple[bool, Optional[Interval]]: """ Are gaps present sufficiently often? For example: .. code-block:: python every_n_days=21 requiredgaps=[ datetime.timedelta(hours=62), datetime.timedelta(hours=48), ] ... means "is there at least one 62-hour gap and one (separate) 48-hour gap in every possible 21-day sequence within the IntervalList? - If ``flexibility == 0``: gaps must be WHOLLY WITHIN the interval. - If ``flexibility == 1``: gaps may OVERLAP the edges of the interval. - If ``flexibility == 2``: gaps may ABUT the edges of the interval. Returns ``(True, None)`` or ``(False, first_failure_interval)``. """ if len(self.intervals) < 2: return False, None startdate = self.start_date() enddate = self.end_date() ndays = (enddate - startdate).days + 1 if ndays <= every_n_days: # Our interval is too short, or just right return self._sufficient_gaps(startdate, enddate, requiredgaps, flexibility) for i in range(ndays - every_n_days): j = i + every_n_days a = startdate + datetime.timedelta(days=i) b = startdate + datetime.timedelta(days=j) sufficient, ffi = self._sufficient_gaps(a, b, requiredgaps, flexibility) if not sufficient: return False, ffi return True, None
[ "def", "sufficient_gaps", "(", "self", ",", "every_n_days", ":", "int", ",", "requiredgaps", ":", "List", "[", "datetime", ".", "timedelta", "]", ",", "flexibility", ":", "int", "=", "2", ")", "->", "Tuple", "[", "bool", ",", "Optional", "[", "Interval", "]", "]", ":", "if", "len", "(", "self", ".", "intervals", ")", "<", "2", ":", "return", "False", ",", "None", "startdate", "=", "self", ".", "start_date", "(", ")", "enddate", "=", "self", ".", "end_date", "(", ")", "ndays", "=", "(", "enddate", "-", "startdate", ")", ".", "days", "+", "1", "if", "ndays", "<=", "every_n_days", ":", "# Our interval is too short, or just right", "return", "self", ".", "_sufficient_gaps", "(", "startdate", ",", "enddate", ",", "requiredgaps", ",", "flexibility", ")", "for", "i", "in", "range", "(", "ndays", "-", "every_n_days", ")", ":", "j", "=", "i", "+", "every_n_days", "a", "=", "startdate", "+", "datetime", ".", "timedelta", "(", "days", "=", "i", ")", "b", "=", "startdate", "+", "datetime", ".", "timedelta", "(", "days", "=", "j", ")", "sufficient", ",", "ffi", "=", "self", ".", "_sufficient_gaps", "(", "a", ",", "b", ",", "requiredgaps", ",", "flexibility", ")", "if", "not", "sufficient", ":", "return", "False", ",", "ffi", "return", "True", ",", "None" ]
Are gaps present sufficiently often? For example: .. code-block:: python every_n_days=21 requiredgaps=[ datetime.timedelta(hours=62), datetime.timedelta(hours=48), ] ... means "is there at least one 62-hour gap and one (separate) 48-hour gap in every possible 21-day sequence within the IntervalList? - If ``flexibility == 0``: gaps must be WHOLLY WITHIN the interval. - If ``flexibility == 1``: gaps may OVERLAP the edges of the interval. - If ``flexibility == 2``: gaps may ABUT the edges of the interval. Returns ``(True, None)`` or ``(False, first_failure_interval)``.
[ "Are", "gaps", "present", "sufficiently", "often?", "For", "example", ":" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1085-L1130
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.cumulative_time_to
def cumulative_time_to(self, when: datetime.datetime) -> datetime.timedelta: """ Returns the cumulative time contained in our intervals up to the specified time point. """ assert self.no_overlap, self._ONLY_FOR_NO_INTERVAL cumulative = datetime.timedelta() for interval in self.intervals: if interval.start >= when: break elif interval.end <= when: # complete interval precedes "when" cumulative += interval.duration() else: # start < when < end cumulative += when - interval.start return cumulative
python
def cumulative_time_to(self, when: datetime.datetime) -> datetime.timedelta: """ Returns the cumulative time contained in our intervals up to the specified time point. """ assert self.no_overlap, self._ONLY_FOR_NO_INTERVAL cumulative = datetime.timedelta() for interval in self.intervals: if interval.start >= when: break elif interval.end <= when: # complete interval precedes "when" cumulative += interval.duration() else: # start < when < end cumulative += when - interval.start return cumulative
[ "def", "cumulative_time_to", "(", "self", ",", "when", ":", "datetime", ".", "datetime", ")", "->", "datetime", ".", "timedelta", ":", "assert", "self", ".", "no_overlap", ",", "self", ".", "_ONLY_FOR_NO_INTERVAL", "cumulative", "=", "datetime", ".", "timedelta", "(", ")", "for", "interval", "in", "self", ".", "intervals", ":", "if", "interval", ".", "start", ">=", "when", ":", "break", "elif", "interval", ".", "end", "<=", "when", ":", "# complete interval precedes \"when\"", "cumulative", "+=", "interval", ".", "duration", "(", ")", "else", ":", "# start < when < end", "cumulative", "+=", "when", "-", "interval", ".", "start", "return", "cumulative" ]
Returns the cumulative time contained in our intervals up to the specified time point.
[ "Returns", "the", "cumulative", "time", "contained", "in", "our", "intervals", "up", "to", "the", "specified", "time", "point", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1136-L1152
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.cumulative_gaps_to
def cumulative_gaps_to(self, when: datetime.datetime) -> datetime.timedelta: """ Return the cumulative time within our gaps, up to ``when``. """ gaps = self.gaps() return gaps.cumulative_time_to(when)
python
def cumulative_gaps_to(self, when: datetime.datetime) -> datetime.timedelta: """ Return the cumulative time within our gaps, up to ``when``. """ gaps = self.gaps() return gaps.cumulative_time_to(when)
[ "def", "cumulative_gaps_to", "(", "self", ",", "when", ":", "datetime", ".", "datetime", ")", "->", "datetime", ".", "timedelta", ":", "gaps", "=", "self", ".", "gaps", "(", ")", "return", "gaps", ".", "cumulative_time_to", "(", "when", ")" ]
Return the cumulative time within our gaps, up to ``when``.
[ "Return", "the", "cumulative", "time", "within", "our", "gaps", "up", "to", "when", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1154-L1160
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.time_afterwards_preceding
def time_afterwards_preceding( self, when: datetime.datetime) -> Optional[datetime.timedelta]: """ Returns the time after our last interval, but before ``when``. If ``self`` is an empty list, returns ``None``. """ if self.is_empty(): return None end_time = self.end_datetime() if when <= end_time: return datetime.timedelta() else: return when - end_time
python
def time_afterwards_preceding( self, when: datetime.datetime) -> Optional[datetime.timedelta]: """ Returns the time after our last interval, but before ``when``. If ``self`` is an empty list, returns ``None``. """ if self.is_empty(): return None end_time = self.end_datetime() if when <= end_time: return datetime.timedelta() else: return when - end_time
[ "def", "time_afterwards_preceding", "(", "self", ",", "when", ":", "datetime", ".", "datetime", ")", "->", "Optional", "[", "datetime", ".", "timedelta", "]", ":", "if", "self", ".", "is_empty", "(", ")", ":", "return", "None", "end_time", "=", "self", ".", "end_datetime", "(", ")", "if", "when", "<=", "end_time", ":", "return", "datetime", ".", "timedelta", "(", ")", "else", ":", "return", "when", "-", "end_time" ]
Returns the time after our last interval, but before ``when``. If ``self`` is an empty list, returns ``None``.
[ "Returns", "the", "time", "after", "our", "last", "interval", "but", "before", "when", ".", "If", "self", "is", "an", "empty", "list", "returns", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1162-L1174
RudolfCardinal/pythonlib
cardinal_pythonlib/interval.py
IntervalList.cumulative_before_during_after
def cumulative_before_during_after(self, start: datetime.datetime, when: datetime.datetime) -> \ Tuple[datetime.timedelta, datetime.timedelta, datetime.timedelta]: """ For a given time, ``when``, returns the cumulative time - after ``start`` but before ``self`` begins, prior to ``when``; - after ``start`` and during intervals represented by ``self``, prior to ``when``; - after ``start`` and after at least one interval represented by ``self`` has finished, and not within any intervals represented by ``self``, and prior to ``when``. Args: start: the start time of interest (e.g. before ``self`` begins) when: the time of interest Returns: tuple: ``before, during, after`` Illustration .. code-block:: none start: S self: X---X X---X X---X X---X when: W before: ---- during: ----- ----- ----- after: ------- ------- ---- """ assert self.no_overlap, ( "Only implemented for IntervalList objects with no_overlap == True" ) no_time = datetime.timedelta() earliest_interval_start = self.start_datetime() # Easy special cases if when <= start: return no_time, no_time, no_time if self.is_empty() or when <= earliest_interval_start: return when - start, no_time, no_time # Now we can guarantee: # - "self" is a non-empty list # - start < when # - earliest_interval_start < when # Before if earliest_interval_start < start: before = no_time else: before = earliest_interval_start - start # During during = self.cumulative_time_to(when) after = ( self.cumulative_gaps_to(when) + self.time_afterwards_preceding(when) ) return before, during, after
python
def cumulative_before_during_after(self, start: datetime.datetime, when: datetime.datetime) -> \ Tuple[datetime.timedelta, datetime.timedelta, datetime.timedelta]: """ For a given time, ``when``, returns the cumulative time - after ``start`` but before ``self`` begins, prior to ``when``; - after ``start`` and during intervals represented by ``self``, prior to ``when``; - after ``start`` and after at least one interval represented by ``self`` has finished, and not within any intervals represented by ``self``, and prior to ``when``. Args: start: the start time of interest (e.g. before ``self`` begins) when: the time of interest Returns: tuple: ``before, during, after`` Illustration .. code-block:: none start: S self: X---X X---X X---X X---X when: W before: ---- during: ----- ----- ----- after: ------- ------- ---- """ assert self.no_overlap, ( "Only implemented for IntervalList objects with no_overlap == True" ) no_time = datetime.timedelta() earliest_interval_start = self.start_datetime() # Easy special cases if when <= start: return no_time, no_time, no_time if self.is_empty() or when <= earliest_interval_start: return when - start, no_time, no_time # Now we can guarantee: # - "self" is a non-empty list # - start < when # - earliest_interval_start < when # Before if earliest_interval_start < start: before = no_time else: before = earliest_interval_start - start # During during = self.cumulative_time_to(when) after = ( self.cumulative_gaps_to(when) + self.time_afterwards_preceding(when) ) return before, during, after
[ "def", "cumulative_before_during_after", "(", "self", ",", "start", ":", "datetime", ".", "datetime", ",", "when", ":", "datetime", ".", "datetime", ")", "->", "Tuple", "[", "datetime", ".", "timedelta", ",", "datetime", ".", "timedelta", ",", "datetime", ".", "timedelta", "]", ":", "assert", "self", ".", "no_overlap", ",", "(", "\"Only implemented for IntervalList objects with no_overlap == True\"", ")", "no_time", "=", "datetime", ".", "timedelta", "(", ")", "earliest_interval_start", "=", "self", ".", "start_datetime", "(", ")", "# Easy special cases", "if", "when", "<=", "start", ":", "return", "no_time", ",", "no_time", ",", "no_time", "if", "self", ".", "is_empty", "(", ")", "or", "when", "<=", "earliest_interval_start", ":", "return", "when", "-", "start", ",", "no_time", ",", "no_time", "# Now we can guarantee:", "# - \"self\" is a non-empty list", "# - start < when", "# - earliest_interval_start < when", "# Before", "if", "earliest_interval_start", "<", "start", ":", "before", "=", "no_time", "else", ":", "before", "=", "earliest_interval_start", "-", "start", "# During", "during", "=", "self", ".", "cumulative_time_to", "(", "when", ")", "after", "=", "(", "self", ".", "cumulative_gaps_to", "(", "when", ")", "+", "self", ".", "time_afterwards_preceding", "(", "when", ")", ")", "return", "before", ",", "during", ",", "after" ]
For a given time, ``when``, returns the cumulative time - after ``start`` but before ``self`` begins, prior to ``when``; - after ``start`` and during intervals represented by ``self``, prior to ``when``; - after ``start`` and after at least one interval represented by ``self`` has finished, and not within any intervals represented by ``self``, and prior to ``when``. Args: start: the start time of interest (e.g. before ``self`` begins) when: the time of interest Returns: tuple: ``before, during, after`` Illustration .. code-block:: none start: S self: X---X X---X X---X X---X when: W before: ---- during: ----- ----- ----- after: ------- ------- ----
[ "For", "a", "given", "time", "when", "returns", "the", "cumulative", "time", "-", "after", "start", "but", "before", "self", "begins", "prior", "to", "when", ";", "-", "after", "start", "and", "during", "intervals", "represented", "by", "self", "prior", "to", "when", ";", "-", "after", "start", "and", "after", "at", "least", "one", "interval", "represented", "by", "self", "has", "finished", "and", "not", "within", "any", "intervals", "represented", "by", "self", "and", "prior", "to", "when", ".", "Args", ":", "start", ":", "the", "start", "time", "of", "interest", "(", "e", ".", "g", ".", "before", "self", "begins", ")", "when", ":", "the", "time", "of", "interest", "Returns", ":", "tuple", ":", "before", "during", "after" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L1176-L1245
RudolfCardinal/pythonlib
cardinal_pythonlib/dogpile_cache.py
repr_parameter
def repr_parameter(param: inspect.Parameter) -> str: """ Provides a ``repr``-style representation of a function parameter. """ return ( "Parameter(name={name}, annotation={annotation}, kind={kind}, " "default={default}".format( name=param.name, annotation=param.annotation, kind=param.kind, default=param.default) )
python
def repr_parameter(param: inspect.Parameter) -> str: """ Provides a ``repr``-style representation of a function parameter. """ return ( "Parameter(name={name}, annotation={annotation}, kind={kind}, " "default={default}".format( name=param.name, annotation=param.annotation, kind=param.kind, default=param.default) )
[ "def", "repr_parameter", "(", "param", ":", "inspect", ".", "Parameter", ")", "->", "str", ":", "return", "(", "\"Parameter(name={name}, annotation={annotation}, kind={kind}, \"", "\"default={default}\"", ".", "format", "(", "name", "=", "param", ".", "name", ",", "annotation", "=", "param", ".", "annotation", ",", "kind", "=", "param", ".", "kind", ",", "default", "=", "param", ".", "default", ")", ")" ]
Provides a ``repr``-style representation of a function parameter.
[ "Provides", "a", "repr", "-", "style", "representation", "of", "a", "function", "parameter", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dogpile_cache.py#L109-L118
RudolfCardinal/pythonlib
cardinal_pythonlib/dogpile_cache.py
get_namespace
def get_namespace(fn: Callable, namespace: Optional[str]) -> str: """ Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace Args: fn: a function namespace: an optional namespace, which can be of any type but is normally a ``str``; if not ``None``, ``str(namespace)`` will be added to the result. See https://dogpilecache.readthedocs.io/en/latest/api.html#dogpile.cache.region.CacheRegion.cache_on_arguments """ # noqa # See hidden attributes with dir(fn) # noinspection PyUnresolvedReferences return "{module}:{name}{extra}".format( module=fn.__module__, name=fn.__qualname__, # __qualname__ includes class name, if present extra="|{}".format(namespace) if namespace is not None else "", )
python
def get_namespace(fn: Callable, namespace: Optional[str]) -> str: """ Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace Args: fn: a function namespace: an optional namespace, which can be of any type but is normally a ``str``; if not ``None``, ``str(namespace)`` will be added to the result. See https://dogpilecache.readthedocs.io/en/latest/api.html#dogpile.cache.region.CacheRegion.cache_on_arguments """ # noqa # See hidden attributes with dir(fn) # noinspection PyUnresolvedReferences return "{module}:{name}{extra}".format( module=fn.__module__, name=fn.__qualname__, # __qualname__ includes class name, if present extra="|{}".format(namespace) if namespace is not None else "", )
[ "def", "get_namespace", "(", "fn", ":", "Callable", ",", "namespace", ":", "Optional", "[", "str", "]", ")", "->", "str", ":", "# noqa", "# See hidden attributes with dir(fn)", "# noinspection PyUnresolvedReferences", "return", "\"{module}:{name}{extra}\"", ".", "format", "(", "module", "=", "fn", ".", "__module__", ",", "name", "=", "fn", ".", "__qualname__", ",", "# __qualname__ includes class name, if present", "extra", "=", "\"|{}\"", ".", "format", "(", "namespace", ")", "if", "namespace", "is", "not", "None", "else", "\"\"", ",", ")" ]
Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace Args: fn: a function namespace: an optional namespace, which can be of any type but is normally a ``str``; if not ``None``, ``str(namespace)`` will be added to the result. See https://dogpilecache.readthedocs.io/en/latest/api.html#dogpile.cache.region.CacheRegion.cache_on_arguments
[ "Returns", "a", "representation", "of", "a", "function", "s", "name", "(", "perhaps", "within", "a", "namespace", ")", "like" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dogpile_cache.py#L121-L144
RudolfCardinal/pythonlib
cardinal_pythonlib/dogpile_cache.py
fkg_allowing_type_hints
def fkg_allowing_type_hints( namespace: Optional[str], fn: Callable, to_str: Callable[[Any], str] = repr) -> Callable[[Any], str]: """ Replacement for :func:`dogpile.cache.util.function_key_generator` that handles type-hinted functions like .. code-block:: python def testfunc(param: str) -> str: return param + "hello" ... at which :func:`inspect.getargspec` balks; plus :func:`inspect.getargspec` is deprecated in Python 3. Used as an argument to e.g. ``@cache_region_static.cache_on_arguments()``. Also modified to make the cached function unique per INSTANCE for normal methods of a class. Args: namespace: optional namespace, as per :func:`get_namespace` fn: function to generate a key for (usually the function being decorated) to_str: function to apply to map arguments to a string (to make a unique key for a particular call to the function); by default it is :func:`repr` Returns: a function that generates a string key, based on a given function as well as arguments to the returned function itself. """ namespace = get_namespace(fn, namespace) sig = inspect.signature(fn) argnames = [p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD] has_self = bool(argnames and argnames[0] in ('self', 'cls')) def generate_key(*args: Any, **kw: Any) -> str: """ Makes the actual key for a specific call to the decorated function, with particular ``args``/``kwargs``. """ if kw: raise ValueError("This dogpile.cache key function generator, " "fkg_allowing_type_hints, " "does not accept keyword arguments.") if has_self: # Unlike dogpile's default, make it instance- (or class-) specific # by including a representation of the "self" or "cls" argument: args = [hex(id(args[0]))] + list(args[1:]) key = namespace + "|" + " ".join(map(to_str, args)) if DEBUG_INTERNALS: log.debug("fkg_allowing_type_hints.generate_key() -> {!r}", key) return key return generate_key
python
def fkg_allowing_type_hints( namespace: Optional[str], fn: Callable, to_str: Callable[[Any], str] = repr) -> Callable[[Any], str]: """ Replacement for :func:`dogpile.cache.util.function_key_generator` that handles type-hinted functions like .. code-block:: python def testfunc(param: str) -> str: return param + "hello" ... at which :func:`inspect.getargspec` balks; plus :func:`inspect.getargspec` is deprecated in Python 3. Used as an argument to e.g. ``@cache_region_static.cache_on_arguments()``. Also modified to make the cached function unique per INSTANCE for normal methods of a class. Args: namespace: optional namespace, as per :func:`get_namespace` fn: function to generate a key for (usually the function being decorated) to_str: function to apply to map arguments to a string (to make a unique key for a particular call to the function); by default it is :func:`repr` Returns: a function that generates a string key, based on a given function as well as arguments to the returned function itself. """ namespace = get_namespace(fn, namespace) sig = inspect.signature(fn) argnames = [p.name for p in sig.parameters.values() if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD] has_self = bool(argnames and argnames[0] in ('self', 'cls')) def generate_key(*args: Any, **kw: Any) -> str: """ Makes the actual key for a specific call to the decorated function, with particular ``args``/``kwargs``. """ if kw: raise ValueError("This dogpile.cache key function generator, " "fkg_allowing_type_hints, " "does not accept keyword arguments.") if has_self: # Unlike dogpile's default, make it instance- (or class-) specific # by including a representation of the "self" or "cls" argument: args = [hex(id(args[0]))] + list(args[1:]) key = namespace + "|" + " ".join(map(to_str, args)) if DEBUG_INTERNALS: log.debug("fkg_allowing_type_hints.generate_key() -> {!r}", key) return key return generate_key
[ "def", "fkg_allowing_type_hints", "(", "namespace", ":", "Optional", "[", "str", "]", ",", "fn", ":", "Callable", ",", "to_str", ":", "Callable", "[", "[", "Any", "]", ",", "str", "]", "=", "repr", ")", "->", "Callable", "[", "[", "Any", "]", ",", "str", "]", ":", "namespace", "=", "get_namespace", "(", "fn", ",", "namespace", ")", "sig", "=", "inspect", ".", "signature", "(", "fn", ")", "argnames", "=", "[", "p", ".", "name", "for", "p", "in", "sig", ".", "parameters", ".", "values", "(", ")", "if", "p", ".", "kind", "==", "inspect", ".", "Parameter", ".", "POSITIONAL_OR_KEYWORD", "]", "has_self", "=", "bool", "(", "argnames", "and", "argnames", "[", "0", "]", "in", "(", "'self'", ",", "'cls'", ")", ")", "def", "generate_key", "(", "*", "args", ":", "Any", ",", "*", "*", "kw", ":", "Any", ")", "->", "str", ":", "\"\"\"\n Makes the actual key for a specific call to the decorated function,\n with particular ``args``/``kwargs``.\n \"\"\"", "if", "kw", ":", "raise", "ValueError", "(", "\"This dogpile.cache key function generator, \"", "\"fkg_allowing_type_hints, \"", "\"does not accept keyword arguments.\"", ")", "if", "has_self", ":", "# Unlike dogpile's default, make it instance- (or class-) specific", "# by including a representation of the \"self\" or \"cls\" argument:", "args", "=", "[", "hex", "(", "id", "(", "args", "[", "0", "]", ")", ")", "]", "+", "list", "(", "args", "[", "1", ":", "]", ")", "key", "=", "namespace", "+", "\"|\"", "+", "\" \"", ".", "join", "(", "map", "(", "to_str", ",", "args", ")", ")", "if", "DEBUG_INTERNALS", ":", "log", ".", "debug", "(", "\"fkg_allowing_type_hints.generate_key() -> {!r}\"", ",", "key", ")", "return", "key", "return", "generate_key" ]
Replacement for :func:`dogpile.cache.util.function_key_generator` that handles type-hinted functions like .. code-block:: python def testfunc(param: str) -> str: return param + "hello" ... at which :func:`inspect.getargspec` balks; plus :func:`inspect.getargspec` is deprecated in Python 3. Used as an argument to e.g. ``@cache_region_static.cache_on_arguments()``. Also modified to make the cached function unique per INSTANCE for normal methods of a class. Args: namespace: optional namespace, as per :func:`get_namespace` fn: function to generate a key for (usually the function being decorated) to_str: function to apply to map arguments to a string (to make a unique key for a particular call to the function); by default it is :func:`repr` Returns: a function that generates a string key, based on a given function as well as arguments to the returned function itself.
[ "Replacement", "for", ":", "func", ":", "dogpile", ".", "cache", ".", "util", ".", "function_key_generator", "that", "handles", "type", "-", "hinted", "functions", "like" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dogpile_cache.py#L151-L210
RudolfCardinal/pythonlib
cardinal_pythonlib/dogpile_cache.py
kw_fkg_allowing_type_hints
def kw_fkg_allowing_type_hints( namespace: Optional[str], fn: Callable, to_str: Callable[[Any], str] = repr) -> Callable[[Any], str]: """ As for :func:`fkg_allowing_type_hints`, but allowing keyword arguments. For ``kwargs`` passed in, we will build a ``dict`` of all argname (key) to argvalue (values) pairs, including default args from the argspec, and then alphabetize the list before generating the key. NOTE ALSO that once we have keyword arguments, we should be using :func:`repr`, because we need to distinguish .. code-block:: python kwargs = {'p': 'another', 'q': 'thing'} # ... which compat.string_type will make into # p=another q=thing # ... from kwargs = {'p': 'another q=thing'} Also modified to make the cached function unique per INSTANCE for normal methods of a class. """ namespace = get_namespace(fn, namespace) sig = inspect.signature(fn) parameters = list(sig.parameters.values()) # convert from odict_values argnames = [p.name for p in parameters if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD] has_self = bool(argnames and argnames[0] in ('self', 'cls')) if DEBUG_INTERNALS: log.debug( "At start of kw_fkg_allowing_type_hints: namespace={namespace}," "parameters=[{parameters}], argnames={argnames}, " "has_self={has_self}, fn={fn}", namespace=namespace, parameters=", ".join(repr_parameter(p) for p in parameters), argnames=repr(argnames), has_self=has_self, fn=repr(fn), ) def generate_key(*args: Any, **kwargs: Any) -> str: as_kwargs = {} # type: Dict[str, Any] loose_args = [] # type: List[Any] # those captured by *args # 1. args: get the name as well. for idx, arg in enumerate(args): if idx >= len(argnames): # positional argument to be scooped up with *args loose_args.append(arg) else: # normal plain positional argument if has_self and idx == 0: # "self" or "cls" initial argument argvalue = hex(id(arg)) else: argvalue = arg as_kwargs[argnames[idx]] = argvalue # 1b. args with no name if loose_args: as_kwargs['*args'] = loose_args # '*args' is guaranteed not to be a parameter name in its own right # 2. kwargs as_kwargs.update(kwargs) # 3. default values for param in parameters: if param.default != inspect.Parameter.empty: if param.name not in as_kwargs: as_kwargs[param.name] = param.default # 4. sorted by name # ... but also incorporating the name of the argument, because once # we allow the arbitrary **kwargs format, order is no longer # sufficient to discriminate # fn(p="another", q="thing") # from # fn(r="another", s="thing") argument_values = ["{k}={v}".format(k=key, v=to_str(as_kwargs[key])) for key in sorted(as_kwargs.keys())] key = namespace + '|' + " ".join(argument_values) if DEBUG_INTERNALS: log.debug("kw_fkg_allowing_type_hints.generate_key() -> {!r}", key) return key return generate_key
python
def kw_fkg_allowing_type_hints( namespace: Optional[str], fn: Callable, to_str: Callable[[Any], str] = repr) -> Callable[[Any], str]: """ As for :func:`fkg_allowing_type_hints`, but allowing keyword arguments. For ``kwargs`` passed in, we will build a ``dict`` of all argname (key) to argvalue (values) pairs, including default args from the argspec, and then alphabetize the list before generating the key. NOTE ALSO that once we have keyword arguments, we should be using :func:`repr`, because we need to distinguish .. code-block:: python kwargs = {'p': 'another', 'q': 'thing'} # ... which compat.string_type will make into # p=another q=thing # ... from kwargs = {'p': 'another q=thing'} Also modified to make the cached function unique per INSTANCE for normal methods of a class. """ namespace = get_namespace(fn, namespace) sig = inspect.signature(fn) parameters = list(sig.parameters.values()) # convert from odict_values argnames = [p.name for p in parameters if p.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD] has_self = bool(argnames and argnames[0] in ('self', 'cls')) if DEBUG_INTERNALS: log.debug( "At start of kw_fkg_allowing_type_hints: namespace={namespace}," "parameters=[{parameters}], argnames={argnames}, " "has_self={has_self}, fn={fn}", namespace=namespace, parameters=", ".join(repr_parameter(p) for p in parameters), argnames=repr(argnames), has_self=has_self, fn=repr(fn), ) def generate_key(*args: Any, **kwargs: Any) -> str: as_kwargs = {} # type: Dict[str, Any] loose_args = [] # type: List[Any] # those captured by *args # 1. args: get the name as well. for idx, arg in enumerate(args): if idx >= len(argnames): # positional argument to be scooped up with *args loose_args.append(arg) else: # normal plain positional argument if has_self and idx == 0: # "self" or "cls" initial argument argvalue = hex(id(arg)) else: argvalue = arg as_kwargs[argnames[idx]] = argvalue # 1b. args with no name if loose_args: as_kwargs['*args'] = loose_args # '*args' is guaranteed not to be a parameter name in its own right # 2. kwargs as_kwargs.update(kwargs) # 3. default values for param in parameters: if param.default != inspect.Parameter.empty: if param.name not in as_kwargs: as_kwargs[param.name] = param.default # 4. sorted by name # ... but also incorporating the name of the argument, because once # we allow the arbitrary **kwargs format, order is no longer # sufficient to discriminate # fn(p="another", q="thing") # from # fn(r="another", s="thing") argument_values = ["{k}={v}".format(k=key, v=to_str(as_kwargs[key])) for key in sorted(as_kwargs.keys())] key = namespace + '|' + " ".join(argument_values) if DEBUG_INTERNALS: log.debug("kw_fkg_allowing_type_hints.generate_key() -> {!r}", key) return key return generate_key
[ "def", "kw_fkg_allowing_type_hints", "(", "namespace", ":", "Optional", "[", "str", "]", ",", "fn", ":", "Callable", ",", "to_str", ":", "Callable", "[", "[", "Any", "]", ",", "str", "]", "=", "repr", ")", "->", "Callable", "[", "[", "Any", "]", ",", "str", "]", ":", "namespace", "=", "get_namespace", "(", "fn", ",", "namespace", ")", "sig", "=", "inspect", ".", "signature", "(", "fn", ")", "parameters", "=", "list", "(", "sig", ".", "parameters", ".", "values", "(", ")", ")", "# convert from odict_values", "argnames", "=", "[", "p", ".", "name", "for", "p", "in", "parameters", "if", "p", ".", "kind", "==", "inspect", ".", "Parameter", ".", "POSITIONAL_OR_KEYWORD", "]", "has_self", "=", "bool", "(", "argnames", "and", "argnames", "[", "0", "]", "in", "(", "'self'", ",", "'cls'", ")", ")", "if", "DEBUG_INTERNALS", ":", "log", ".", "debug", "(", "\"At start of kw_fkg_allowing_type_hints: namespace={namespace},\"", "\"parameters=[{parameters}], argnames={argnames}, \"", "\"has_self={has_self}, fn={fn}\"", ",", "namespace", "=", "namespace", ",", "parameters", "=", "\", \"", ".", "join", "(", "repr_parameter", "(", "p", ")", "for", "p", "in", "parameters", ")", ",", "argnames", "=", "repr", "(", "argnames", ")", ",", "has_self", "=", "has_self", ",", "fn", "=", "repr", "(", "fn", ")", ",", ")", "def", "generate_key", "(", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "str", ":", "as_kwargs", "=", "{", "}", "# type: Dict[str, Any]", "loose_args", "=", "[", "]", "# type: List[Any] # those captured by *args", "# 1. args: get the name as well.", "for", "idx", ",", "arg", "in", "enumerate", "(", "args", ")", ":", "if", "idx", ">=", "len", "(", "argnames", ")", ":", "# positional argument to be scooped up with *args", "loose_args", ".", "append", "(", "arg", ")", "else", ":", "# normal plain positional argument", "if", "has_self", "and", "idx", "==", "0", ":", "# \"self\" or \"cls\" initial argument", "argvalue", "=", "hex", "(", "id", "(", "arg", ")", ")", "else", ":", "argvalue", "=", "arg", "as_kwargs", "[", "argnames", "[", "idx", "]", "]", "=", "argvalue", "# 1b. args with no name", "if", "loose_args", ":", "as_kwargs", "[", "'*args'", "]", "=", "loose_args", "# '*args' is guaranteed not to be a parameter name in its own right", "# 2. kwargs", "as_kwargs", ".", "update", "(", "kwargs", ")", "# 3. default values", "for", "param", "in", "parameters", ":", "if", "param", ".", "default", "!=", "inspect", ".", "Parameter", ".", "empty", ":", "if", "param", ".", "name", "not", "in", "as_kwargs", ":", "as_kwargs", "[", "param", ".", "name", "]", "=", "param", ".", "default", "# 4. sorted by name", "# ... but also incorporating the name of the argument, because once", "# we allow the arbitrary **kwargs format, order is no longer", "# sufficient to discriminate", "# fn(p=\"another\", q=\"thing\")", "# from", "# fn(r=\"another\", s=\"thing\")", "argument_values", "=", "[", "\"{k}={v}\"", ".", "format", "(", "k", "=", "key", ",", "v", "=", "to_str", "(", "as_kwargs", "[", "key", "]", ")", ")", "for", "key", "in", "sorted", "(", "as_kwargs", ".", "keys", "(", ")", ")", "]", "key", "=", "namespace", "+", "'|'", "+", "\" \"", ".", "join", "(", "argument_values", ")", "if", "DEBUG_INTERNALS", ":", "log", ".", "debug", "(", "\"kw_fkg_allowing_type_hints.generate_key() -> {!r}\"", ",", "key", ")", "return", "key", "return", "generate_key" ]
As for :func:`fkg_allowing_type_hints`, but allowing keyword arguments. For ``kwargs`` passed in, we will build a ``dict`` of all argname (key) to argvalue (values) pairs, including default args from the argspec, and then alphabetize the list before generating the key. NOTE ALSO that once we have keyword arguments, we should be using :func:`repr`, because we need to distinguish .. code-block:: python kwargs = {'p': 'another', 'q': 'thing'} # ... which compat.string_type will make into # p=another q=thing # ... from kwargs = {'p': 'another q=thing'} Also modified to make the cached function unique per INSTANCE for normal methods of a class.
[ "As", "for", ":", "func", ":", "fkg_allowing_type_hints", "but", "allowing", "keyword", "arguments", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dogpile_cache.py#L251-L337
Autodesk/cryptorito
cryptorito/__init__.py
gpg_version
def gpg_version(): """Returns the GPG version""" cmd = flatten([gnupg_bin(), "--version"]) output = stderr_output(cmd) output = output \ .split('\n')[0] \ .split(" ")[2] \ .split('.') return tuple([int(x) for x in output])
python
def gpg_version(): """Returns the GPG version""" cmd = flatten([gnupg_bin(), "--version"]) output = stderr_output(cmd) output = output \ .split('\n')[0] \ .split(" ")[2] \ .split('.') return tuple([int(x) for x in output])
[ "def", "gpg_version", "(", ")", ":", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "\"--version\"", "]", ")", "output", "=", "stderr_output", "(", "cmd", ")", "output", "=", "output", ".", "split", "(", "'\\n'", ")", "[", "0", "]", ".", "split", "(", "\" \"", ")", "[", "2", "]", ".", "split", "(", "'.'", ")", "return", "tuple", "(", "[", "int", "(", "x", ")", "for", "x", "in", "output", "]", ")" ]
Returns the GPG version
[ "Returns", "the", "GPG", "version" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L51-L59
Autodesk/cryptorito
cryptorito/__init__.py
polite_string
def polite_string(a_string): """Returns a "proper" string that should work in both Py3/Py2""" if is_py3() and hasattr(a_string, 'decode'): try: return a_string.decode('utf-8') except UnicodeDecodeError: return a_string return a_string
python
def polite_string(a_string): """Returns a "proper" string that should work in both Py3/Py2""" if is_py3() and hasattr(a_string, 'decode'): try: return a_string.decode('utf-8') except UnicodeDecodeError: return a_string return a_string
[ "def", "polite_string", "(", "a_string", ")", ":", "if", "is_py3", "(", ")", "and", "hasattr", "(", "a_string", ",", "'decode'", ")", ":", "try", ":", "return", "a_string", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeDecodeError", ":", "return", "a_string", "return", "a_string" ]
Returns a "proper" string that should work in both Py3/Py2
[ "Returns", "a", "proper", "string", "that", "should", "work", "in", "both", "Py3", "/", "Py2" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L68-L76
Autodesk/cryptorito
cryptorito/__init__.py
not_a_string
def not_a_string(obj): """It's probably not a string, in the sense that Python2/3 get confused about these things""" my_type = str(type(obj)) if is_py3(): is_str = my_type.find('bytes') < 0 and my_type.find('str') < 0 return is_str return my_type.find('str') < 0 and \ my_type.find('unicode') < 0
python
def not_a_string(obj): """It's probably not a string, in the sense that Python2/3 get confused about these things""" my_type = str(type(obj)) if is_py3(): is_str = my_type.find('bytes') < 0 and my_type.find('str') < 0 return is_str return my_type.find('str') < 0 and \ my_type.find('unicode') < 0
[ "def", "not_a_string", "(", "obj", ")", ":", "my_type", "=", "str", "(", "type", "(", "obj", ")", ")", "if", "is_py3", "(", ")", ":", "is_str", "=", "my_type", ".", "find", "(", "'bytes'", ")", "<", "0", "and", "my_type", ".", "find", "(", "'str'", ")", "<", "0", "return", "is_str", "return", "my_type", ".", "find", "(", "'str'", ")", "<", "0", "and", "my_type", ".", "find", "(", "'unicode'", ")", "<", "0" ]
It's probably not a string, in the sense that Python2/3 get confused about these things
[ "It", "s", "probably", "not", "a", "string", "in", "the", "sense", "that", "Python2", "/", "3", "get", "confused", "about", "these", "things" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L91-L100
Autodesk/cryptorito
cryptorito/__init__.py
actually_flatten
def actually_flatten(iterable): """Flatten iterables This is super ugly. There must be a cleaner py2/3 way of handling this.""" remainder = iter(iterable) while True: first = next(remainder) # pylint: disable=R1708 # Python 2/3 compat is_iter = isinstance(first, collections.Iterable) try: basestring except NameError: basestring = str # pylint: disable=W0622 if is_py3() and is_iter and not_a_string(first): remainder = IT.chain(first, remainder) elif (not is_py3()) and is_iter and not isinstance(first, basestring): remainder = IT.chain(first, remainder) else: yield polite_string(first)
python
def actually_flatten(iterable): """Flatten iterables This is super ugly. There must be a cleaner py2/3 way of handling this.""" remainder = iter(iterable) while True: first = next(remainder) # pylint: disable=R1708 # Python 2/3 compat is_iter = isinstance(first, collections.Iterable) try: basestring except NameError: basestring = str # pylint: disable=W0622 if is_py3() and is_iter and not_a_string(first): remainder = IT.chain(first, remainder) elif (not is_py3()) and is_iter and not isinstance(first, basestring): remainder = IT.chain(first, remainder) else: yield polite_string(first)
[ "def", "actually_flatten", "(", "iterable", ")", ":", "remainder", "=", "iter", "(", "iterable", ")", "while", "True", ":", "first", "=", "next", "(", "remainder", ")", "# pylint: disable=R1708", "# Python 2/3 compat", "is_iter", "=", "isinstance", "(", "first", ",", "collections", ".", "Iterable", ")", "try", ":", "basestring", "except", "NameError", ":", "basestring", "=", "str", "# pylint: disable=W0622", "if", "is_py3", "(", ")", "and", "is_iter", "and", "not_a_string", "(", "first", ")", ":", "remainder", "=", "IT", ".", "chain", "(", "first", ",", "remainder", ")", "elif", "(", "not", "is_py3", "(", ")", ")", "and", "is_iter", "and", "not", "isinstance", "(", "first", ",", "basestring", ")", ":", "remainder", "=", "IT", ".", "chain", "(", "first", ",", "remainder", ")", "else", ":", "yield", "polite_string", "(", "first", ")" ]
Flatten iterables This is super ugly. There must be a cleaner py2/3 way of handling this.
[ "Flatten", "iterables", "This", "is", "super", "ugly", ".", "There", "must", "be", "a", "cleaner", "py2", "/", "3", "way", "of", "handling", "this", "." ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L103-L122
Autodesk/cryptorito
cryptorito/__init__.py
passphrase_file
def passphrase_file(passphrase=None): """Read passphrase from a file. This should only ever be used by our built in integration tests. At this time, during normal operation, only pinentry is supported for entry of passwords.""" cmd = [] pass_file = None if not passphrase and 'CRYPTORITO_PASSPHRASE_FILE' in os.environ: pass_file = os.environ['CRYPTORITO_PASSPHRASE_FILE'] if not os.path.isfile(pass_file): raise CryptoritoError('CRYPTORITO_PASSPHRASE_FILE is invalid') elif passphrase: tmpdir = ensure_tmpdir() pass_file = "%s/p_pass" % tmpdir p_handle = open(pass_file, 'w') p_handle.write(passphrase) p_handle.close() if pass_file: cmd = cmd + ["--batch", "--passphrase-file", pass_file] vsn = gpg_version() if vsn[0] >= 2 and vsn[1] >= 1: cmd = cmd + ["--pinentry-mode", "loopback"] return cmd
python
def passphrase_file(passphrase=None): """Read passphrase from a file. This should only ever be used by our built in integration tests. At this time, during normal operation, only pinentry is supported for entry of passwords.""" cmd = [] pass_file = None if not passphrase and 'CRYPTORITO_PASSPHRASE_FILE' in os.environ: pass_file = os.environ['CRYPTORITO_PASSPHRASE_FILE'] if not os.path.isfile(pass_file): raise CryptoritoError('CRYPTORITO_PASSPHRASE_FILE is invalid') elif passphrase: tmpdir = ensure_tmpdir() pass_file = "%s/p_pass" % tmpdir p_handle = open(pass_file, 'w') p_handle.write(passphrase) p_handle.close() if pass_file: cmd = cmd + ["--batch", "--passphrase-file", pass_file] vsn = gpg_version() if vsn[0] >= 2 and vsn[1] >= 1: cmd = cmd + ["--pinentry-mode", "loopback"] return cmd
[ "def", "passphrase_file", "(", "passphrase", "=", "None", ")", ":", "cmd", "=", "[", "]", "pass_file", "=", "None", "if", "not", "passphrase", "and", "'CRYPTORITO_PASSPHRASE_FILE'", "in", "os", ".", "environ", ":", "pass_file", "=", "os", ".", "environ", "[", "'CRYPTORITO_PASSPHRASE_FILE'", "]", "if", "not", "os", ".", "path", ".", "isfile", "(", "pass_file", ")", ":", "raise", "CryptoritoError", "(", "'CRYPTORITO_PASSPHRASE_FILE is invalid'", ")", "elif", "passphrase", ":", "tmpdir", "=", "ensure_tmpdir", "(", ")", "pass_file", "=", "\"%s/p_pass\"", "%", "tmpdir", "p_handle", "=", "open", "(", "pass_file", ",", "'w'", ")", "p_handle", ".", "write", "(", "passphrase", ")", "p_handle", ".", "close", "(", ")", "if", "pass_file", ":", "cmd", "=", "cmd", "+", "[", "\"--batch\"", ",", "\"--passphrase-file\"", ",", "pass_file", "]", "vsn", "=", "gpg_version", "(", ")", "if", "vsn", "[", "0", "]", ">=", "2", "and", "vsn", "[", "1", "]", ">=", "1", ":", "cmd", "=", "cmd", "+", "[", "\"--pinentry-mode\"", ",", "\"loopback\"", "]", "return", "cmd" ]
Read passphrase from a file. This should only ever be used by our built in integration tests. At this time, during normal operation, only pinentry is supported for entry of passwords.
[ "Read", "passphrase", "from", "a", "file", ".", "This", "should", "only", "ever", "be", "used", "by", "our", "built", "in", "integration", "tests", ".", "At", "this", "time", "during", "normal", "operation", "only", "pinentry", "is", "supported", "for", "entry", "of", "passwords", "." ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L131-L156
Autodesk/cryptorito
cryptorito/__init__.py
gnupg_home
def gnupg_home(): """Returns appropriate arguments if GNUPGHOME is set""" if 'GNUPGHOME' in os.environ: gnupghome = os.environ['GNUPGHOME'] if not os.path.isdir(gnupghome): raise CryptoritoError("Invalid GNUPGHOME directory") return ["--homedir", gnupghome] else: return []
python
def gnupg_home(): """Returns appropriate arguments if GNUPGHOME is set""" if 'GNUPGHOME' in os.environ: gnupghome = os.environ['GNUPGHOME'] if not os.path.isdir(gnupghome): raise CryptoritoError("Invalid GNUPGHOME directory") return ["--homedir", gnupghome] else: return []
[ "def", "gnupg_home", "(", ")", ":", "if", "'GNUPGHOME'", "in", "os", ".", "environ", ":", "gnupghome", "=", "os", ".", "environ", "[", "'GNUPGHOME'", "]", "if", "not", "os", ".", "path", ".", "isdir", "(", "gnupghome", ")", ":", "raise", "CryptoritoError", "(", "\"Invalid GNUPGHOME directory\"", ")", "return", "[", "\"--homedir\"", ",", "gnupghome", "]", "else", ":", "return", "[", "]" ]
Returns appropriate arguments if GNUPGHOME is set
[ "Returns", "appropriate", "arguments", "if", "GNUPGHOME", "is", "set" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L159-L168
Autodesk/cryptorito
cryptorito/__init__.py
fingerprint_from_keybase
def fingerprint_from_keybase(fingerprint, kb_obj): """Extracts a key matching a specific fingerprint from a Keybase API response""" if 'public_keys' in kb_obj and \ 'pgp_public_keys' in kb_obj['public_keys']: for key in kb_obj['public_keys']['pgp_public_keys']: keyprint = fingerprint_from_var(key).lower() fingerprint = fingerprint.lower() if fingerprint == keyprint or \ keyprint.startswith(fingerprint) or \ keyprint.endswith(fingerprint): return { 'fingerprint': keyprint, 'bundle': key } return None
python
def fingerprint_from_keybase(fingerprint, kb_obj): """Extracts a key matching a specific fingerprint from a Keybase API response""" if 'public_keys' in kb_obj and \ 'pgp_public_keys' in kb_obj['public_keys']: for key in kb_obj['public_keys']['pgp_public_keys']: keyprint = fingerprint_from_var(key).lower() fingerprint = fingerprint.lower() if fingerprint == keyprint or \ keyprint.startswith(fingerprint) or \ keyprint.endswith(fingerprint): return { 'fingerprint': keyprint, 'bundle': key } return None
[ "def", "fingerprint_from_keybase", "(", "fingerprint", ",", "kb_obj", ")", ":", "if", "'public_keys'", "in", "kb_obj", "and", "'pgp_public_keys'", "in", "kb_obj", "[", "'public_keys'", "]", ":", "for", "key", "in", "kb_obj", "[", "'public_keys'", "]", "[", "'pgp_public_keys'", "]", ":", "keyprint", "=", "fingerprint_from_var", "(", "key", ")", ".", "lower", "(", ")", "fingerprint", "=", "fingerprint", ".", "lower", "(", ")", "if", "fingerprint", "==", "keyprint", "or", "keyprint", ".", "startswith", "(", "fingerprint", ")", "or", "keyprint", ".", "endswith", "(", "fingerprint", ")", ":", "return", "{", "'fingerprint'", ":", "keyprint", ",", "'bundle'", ":", "key", "}", "return", "None" ]
Extracts a key matching a specific fingerprint from a Keybase API response
[ "Extracts", "a", "key", "matching", "a", "specific", "fingerprint", "from", "a", "Keybase", "API", "response" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L214-L230
Autodesk/cryptorito
cryptorito/__init__.py
key_from_keybase
def key_from_keybase(username, fingerprint=None): """Look up a public key from a username""" url = keybase_lookup_url(username) resp = requests.get(url) if resp.status_code == 200: j_resp = json.loads(polite_string(resp.content)) if 'them' in j_resp and len(j_resp['them']) == 1: kb_obj = j_resp['them'][0] if fingerprint: return fingerprint_from_keybase(fingerprint, kb_obj) else: if 'public_keys' in kb_obj \ and 'pgp_public_keys' in kb_obj['public_keys']: key = kb_obj['public_keys']['primary'] return massage_key(key) return None
python
def key_from_keybase(username, fingerprint=None): """Look up a public key from a username""" url = keybase_lookup_url(username) resp = requests.get(url) if resp.status_code == 200: j_resp = json.loads(polite_string(resp.content)) if 'them' in j_resp and len(j_resp['them']) == 1: kb_obj = j_resp['them'][0] if fingerprint: return fingerprint_from_keybase(fingerprint, kb_obj) else: if 'public_keys' in kb_obj \ and 'pgp_public_keys' in kb_obj['public_keys']: key = kb_obj['public_keys']['primary'] return massage_key(key) return None
[ "def", "key_from_keybase", "(", "username", ",", "fingerprint", "=", "None", ")", ":", "url", "=", "keybase_lookup_url", "(", "username", ")", "resp", "=", "requests", ".", "get", "(", "url", ")", "if", "resp", ".", "status_code", "==", "200", ":", "j_resp", "=", "json", ".", "loads", "(", "polite_string", "(", "resp", ".", "content", ")", ")", "if", "'them'", "in", "j_resp", "and", "len", "(", "j_resp", "[", "'them'", "]", ")", "==", "1", ":", "kb_obj", "=", "j_resp", "[", "'them'", "]", "[", "0", "]", "if", "fingerprint", ":", "return", "fingerprint_from_keybase", "(", "fingerprint", ",", "kb_obj", ")", "else", ":", "if", "'public_keys'", "in", "kb_obj", "and", "'pgp_public_keys'", "in", "kb_obj", "[", "'public_keys'", "]", ":", "key", "=", "kb_obj", "[", "'public_keys'", "]", "[", "'primary'", "]", "return", "massage_key", "(", "key", ")", "return", "None" ]
Look up a public key from a username
[ "Look", "up", "a", "public", "key", "from", "a", "username" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L233-L249
Autodesk/cryptorito
cryptorito/__init__.py
has_gpg_key
def has_gpg_key(fingerprint): """Checks to see if we have this gpg fingerprint""" if len(fingerprint) > 8: fingerprint = fingerprint[-8:] fingerprint = fingerprint.upper() cmd = flatten([gnupg_bin(), gnupg_home(), "--list-public-keys"]) lines = stderr_output(cmd).split('\n') return len([key for key in lines if key.find(fingerprint) > -1]) == 1
python
def has_gpg_key(fingerprint): """Checks to see if we have this gpg fingerprint""" if len(fingerprint) > 8: fingerprint = fingerprint[-8:] fingerprint = fingerprint.upper() cmd = flatten([gnupg_bin(), gnupg_home(), "--list-public-keys"]) lines = stderr_output(cmd).split('\n') return len([key for key in lines if key.find(fingerprint) > -1]) == 1
[ "def", "has_gpg_key", "(", "fingerprint", ")", ":", "if", "len", "(", "fingerprint", ")", ">", "8", ":", "fingerprint", "=", "fingerprint", "[", "-", "8", ":", "]", "fingerprint", "=", "fingerprint", ".", "upper", "(", ")", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "gnupg_home", "(", ")", ",", "\"--list-public-keys\"", "]", ")", "lines", "=", "stderr_output", "(", "cmd", ")", ".", "split", "(", "'\\n'", ")", "return", "len", "(", "[", "key", "for", "key", "in", "lines", "if", "key", ".", "find", "(", "fingerprint", ")", ">", "-", "1", "]", ")", "==", "1" ]
Checks to see if we have this gpg fingerprint
[ "Checks", "to", "see", "if", "we", "have", "this", "gpg", "fingerprint" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L252-L260
Autodesk/cryptorito
cryptorito/__init__.py
fingerprint_from_var
def fingerprint_from_var(var): """Extract a fingerprint from a GPG public key""" vsn = gpg_version() cmd = flatten([gnupg_bin(), gnupg_home()]) if vsn[0] >= 2 and vsn[1] < 1: cmd.append("--with-fingerprint") output = polite_string(stderr_with_input(cmd, var)).split('\n') if not output[0].startswith('pub'): raise CryptoritoError('probably an invalid gpg key') if vsn[0] >= 2 and vsn[1] < 1: return output[1] \ .split('=')[1] \ .replace(' ', '') return output[1].strip()
python
def fingerprint_from_var(var): """Extract a fingerprint from a GPG public key""" vsn = gpg_version() cmd = flatten([gnupg_bin(), gnupg_home()]) if vsn[0] >= 2 and vsn[1] < 1: cmd.append("--with-fingerprint") output = polite_string(stderr_with_input(cmd, var)).split('\n') if not output[0].startswith('pub'): raise CryptoritoError('probably an invalid gpg key') if vsn[0] >= 2 and vsn[1] < 1: return output[1] \ .split('=')[1] \ .replace(' ', '') return output[1].strip()
[ "def", "fingerprint_from_var", "(", "var", ")", ":", "vsn", "=", "gpg_version", "(", ")", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "gnupg_home", "(", ")", "]", ")", "if", "vsn", "[", "0", "]", ">=", "2", "and", "vsn", "[", "1", "]", "<", "1", ":", "cmd", ".", "append", "(", "\"--with-fingerprint\"", ")", "output", "=", "polite_string", "(", "stderr_with_input", "(", "cmd", ",", "var", ")", ")", ".", "split", "(", "'\\n'", ")", "if", "not", "output", "[", "0", "]", ".", "startswith", "(", "'pub'", ")", ":", "raise", "CryptoritoError", "(", "'probably an invalid gpg key'", ")", "if", "vsn", "[", "0", "]", ">=", "2", "and", "vsn", "[", "1", "]", "<", "1", ":", "return", "output", "[", "1", "]", ".", "split", "(", "'='", ")", "[", "1", "]", ".", "replace", "(", "' '", ",", "''", ")", "return", "output", "[", "1", "]", ".", "strip", "(", ")" ]
Extract a fingerprint from a GPG public key
[ "Extract", "a", "fingerprint", "from", "a", "GPG", "public", "key" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L263-L279
Autodesk/cryptorito
cryptorito/__init__.py
fingerprint_from_file
def fingerprint_from_file(filename): """Extract a fingerprint from a GPG public key file""" cmd = flatten([gnupg_bin(), gnupg_home(), filename]) outp = stderr_output(cmd).split('\n') if not outp[0].startswith('pub'): raise CryptoritoError('probably an invalid gpg key') return outp[1].strip()
python
def fingerprint_from_file(filename): """Extract a fingerprint from a GPG public key file""" cmd = flatten([gnupg_bin(), gnupg_home(), filename]) outp = stderr_output(cmd).split('\n') if not outp[0].startswith('pub'): raise CryptoritoError('probably an invalid gpg key') return outp[1].strip()
[ "def", "fingerprint_from_file", "(", "filename", ")", ":", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "gnupg_home", "(", ")", ",", "filename", "]", ")", "outp", "=", "stderr_output", "(", "cmd", ")", ".", "split", "(", "'\\n'", ")", "if", "not", "outp", "[", "0", "]", ".", "startswith", "(", "'pub'", ")", ":", "raise", "CryptoritoError", "(", "'probably an invalid gpg key'", ")", "return", "outp", "[", "1", "]", ".", "strip", "(", ")" ]
Extract a fingerprint from a GPG public key file
[ "Extract", "a", "fingerprint", "from", "a", "GPG", "public", "key", "file" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L282-L289
Autodesk/cryptorito
cryptorito/__init__.py
stderr_handle
def stderr_handle(): """Generate debug-level appropriate stderr context for executing things through subprocess. Normally stderr gets sent to dev/null but when debugging it is sent to stdout.""" gpg_stderr = None handle = None if LOGGER.getEffectiveLevel() > logging.DEBUG: handle = open(os.devnull, 'wb') gpg_stderr = handle return handle, gpg_stderr
python
def stderr_handle(): """Generate debug-level appropriate stderr context for executing things through subprocess. Normally stderr gets sent to dev/null but when debugging it is sent to stdout.""" gpg_stderr = None handle = None if LOGGER.getEffectiveLevel() > logging.DEBUG: handle = open(os.devnull, 'wb') gpg_stderr = handle return handle, gpg_stderr
[ "def", "stderr_handle", "(", ")", ":", "gpg_stderr", "=", "None", "handle", "=", "None", "if", "LOGGER", ".", "getEffectiveLevel", "(", ")", ">", "logging", ".", "DEBUG", ":", "handle", "=", "open", "(", "os", ".", "devnull", ",", "'wb'", ")", "gpg_stderr", "=", "handle", "return", "handle", ",", "gpg_stderr" ]
Generate debug-level appropriate stderr context for executing things through subprocess. Normally stderr gets sent to dev/null but when debugging it is sent to stdout.
[ "Generate", "debug", "-", "level", "appropriate", "stderr", "context", "for", "executing", "things", "through", "subprocess", ".", "Normally", "stderr", "gets", "sent", "to", "dev", "/", "null", "but", "when", "debugging", "it", "is", "sent", "to", "stdout", "." ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L292-L302
Autodesk/cryptorito
cryptorito/__init__.py
stderr_output
def stderr_output(cmd): """Wraps the execution of check_output in a way that ignores stderr when not in debug mode""" handle, gpg_stderr = stderr_handle() try: output = subprocess.check_output(cmd, stderr=gpg_stderr) # nosec if handle: handle.close() return str(polite_string(output)) except subprocess.CalledProcessError as exception: LOGGER.debug("GPG Command %s", ' '.join(exception.cmd)) LOGGER.debug("GPG Output %s", exception.output) raise CryptoritoError('GPG Execution')
python
def stderr_output(cmd): """Wraps the execution of check_output in a way that ignores stderr when not in debug mode""" handle, gpg_stderr = stderr_handle() try: output = subprocess.check_output(cmd, stderr=gpg_stderr) # nosec if handle: handle.close() return str(polite_string(output)) except subprocess.CalledProcessError as exception: LOGGER.debug("GPG Command %s", ' '.join(exception.cmd)) LOGGER.debug("GPG Output %s", exception.output) raise CryptoritoError('GPG Execution')
[ "def", "stderr_output", "(", "cmd", ")", ":", "handle", ",", "gpg_stderr", "=", "stderr_handle", "(", ")", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "gpg_stderr", ")", "# nosec", "if", "handle", ":", "handle", ".", "close", "(", ")", "return", "str", "(", "polite_string", "(", "output", ")", ")", "except", "subprocess", ".", "CalledProcessError", "as", "exception", ":", "LOGGER", ".", "debug", "(", "\"GPG Command %s\"", ",", "' '", ".", "join", "(", "exception", ".", "cmd", ")", ")", "LOGGER", ".", "debug", "(", "\"GPG Output %s\"", ",", "exception", ".", "output", ")", "raise", "CryptoritoError", "(", "'GPG Execution'", ")" ]
Wraps the execution of check_output in a way that ignores stderr when not in debug mode
[ "Wraps", "the", "execution", "of", "check_output", "in", "a", "way", "that", "ignores", "stderr", "when", "not", "in", "debug", "mode" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L305-L319
Autodesk/cryptorito
cryptorito/__init__.py
stderr_with_input
def stderr_with_input(cmd, stdin): """Runs a command, passing something in stdin, and returning whatever came out from stdout""" handle, gpg_stderr = stderr_handle() LOGGER.debug("GPG command %s", ' '.join(cmd)) try: gpg_proc = subprocess.Popen(cmd, # nosec stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=gpg_stderr) output, _err = gpg_proc.communicate(polite_bytes(stdin)) if handle: handle.close() return output except subprocess.CalledProcessError as exception: return gpg_error(exception, 'GPG variable encryption error') except OSError as exception: raise CryptoritoError("File %s not found" % exception.filename)
python
def stderr_with_input(cmd, stdin): """Runs a command, passing something in stdin, and returning whatever came out from stdout""" handle, gpg_stderr = stderr_handle() LOGGER.debug("GPG command %s", ' '.join(cmd)) try: gpg_proc = subprocess.Popen(cmd, # nosec stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=gpg_stderr) output, _err = gpg_proc.communicate(polite_bytes(stdin)) if handle: handle.close() return output except subprocess.CalledProcessError as exception: return gpg_error(exception, 'GPG variable encryption error') except OSError as exception: raise CryptoritoError("File %s not found" % exception.filename)
[ "def", "stderr_with_input", "(", "cmd", ",", "stdin", ")", ":", "handle", ",", "gpg_stderr", "=", "stderr_handle", "(", ")", "LOGGER", ".", "debug", "(", "\"GPG command %s\"", ",", "' '", ".", "join", "(", "cmd", ")", ")", "try", ":", "gpg_proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "# nosec", "stdout", "=", "subprocess", ".", "PIPE", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "gpg_stderr", ")", "output", ",", "_err", "=", "gpg_proc", ".", "communicate", "(", "polite_bytes", "(", "stdin", ")", ")", "if", "handle", ":", "handle", ".", "close", "(", ")", "return", "output", "except", "subprocess", ".", "CalledProcessError", "as", "exception", ":", "return", "gpg_error", "(", "exception", ",", "'GPG variable encryption error'", ")", "except", "OSError", "as", "exception", ":", "raise", "CryptoritoError", "(", "\"File %s not found\"", "%", "exception", ".", "filename", ")" ]
Runs a command, passing something in stdin, and returning whatever came out from stdout
[ "Runs", "a", "command", "passing", "something", "in", "stdin", "and", "returning", "whatever", "came", "out", "from", "stdout" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L322-L342
Autodesk/cryptorito
cryptorito/__init__.py
import_gpg_key
def import_gpg_key(key): """Imports a GPG key""" if not key: raise CryptoritoError('Invalid GPG Key') key_fd, key_filename = mkstemp("cryptorito-gpg-import") key_handle = os.fdopen(key_fd, 'w') key_handle.write(polite_string(key)) key_handle.close() cmd = flatten([gnupg_bin(), gnupg_home(), "--import", key_filename]) output = stderr_output(cmd) msg = 'gpg: Total number processed: 1' output_bits = polite_string(output).split('\n') return len([line for line in output_bits if line == msg]) == 1
python
def import_gpg_key(key): """Imports a GPG key""" if not key: raise CryptoritoError('Invalid GPG Key') key_fd, key_filename = mkstemp("cryptorito-gpg-import") key_handle = os.fdopen(key_fd, 'w') key_handle.write(polite_string(key)) key_handle.close() cmd = flatten([gnupg_bin(), gnupg_home(), "--import", key_filename]) output = stderr_output(cmd) msg = 'gpg: Total number processed: 1' output_bits = polite_string(output).split('\n') return len([line for line in output_bits if line == msg]) == 1
[ "def", "import_gpg_key", "(", "key", ")", ":", "if", "not", "key", ":", "raise", "CryptoritoError", "(", "'Invalid GPG Key'", ")", "key_fd", ",", "key_filename", "=", "mkstemp", "(", "\"cryptorito-gpg-import\"", ")", "key_handle", "=", "os", ".", "fdopen", "(", "key_fd", ",", "'w'", ")", "key_handle", ".", "write", "(", "polite_string", "(", "key", ")", ")", "key_handle", ".", "close", "(", ")", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "gnupg_home", "(", ")", ",", "\"--import\"", ",", "key_filename", "]", ")", "output", "=", "stderr_output", "(", "cmd", ")", "msg", "=", "'gpg: Total number processed: 1'", "output_bits", "=", "polite_string", "(", "output", ")", ".", "split", "(", "'\\n'", ")", "return", "len", "(", "[", "line", "for", "line", "in", "output_bits", "if", "line", "==", "msg", "]", ")", "==", "1" ]
Imports a GPG key
[ "Imports", "a", "GPG", "key" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L345-L359
Autodesk/cryptorito
cryptorito/__init__.py
export_gpg_key
def export_gpg_key(key): """Exports a GPG key and returns it""" cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(), "--export", key]) handle, gpg_stderr = stderr_handle() try: gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, # nosec stderr=gpg_stderr) output, _err = gpg_proc.communicate() if handle: handle.close() return portable_b64encode(output) except subprocess.CalledProcessError as exception: LOGGER.debug("GPG Command %s", ' '.join(exception.cmd)) LOGGER.debug("GPG Output %s", exception.output) raise CryptoritoError('GPG encryption error')
python
def export_gpg_key(key): """Exports a GPG key and returns it""" cmd = flatten([gnupg_bin(), gnupg_verbose(), gnupg_home(), "--export", key]) handle, gpg_stderr = stderr_handle() try: gpg_proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, # nosec stderr=gpg_stderr) output, _err = gpg_proc.communicate() if handle: handle.close() return portable_b64encode(output) except subprocess.CalledProcessError as exception: LOGGER.debug("GPG Command %s", ' '.join(exception.cmd)) LOGGER.debug("GPG Output %s", exception.output) raise CryptoritoError('GPG encryption error')
[ "def", "export_gpg_key", "(", "key", ")", ":", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "gnupg_verbose", "(", ")", ",", "gnupg_home", "(", ")", ",", "\"--export\"", ",", "key", "]", ")", "handle", ",", "gpg_stderr", "=", "stderr_handle", "(", ")", "try", ":", "gpg_proc", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "# nosec", "stderr", "=", "gpg_stderr", ")", "output", ",", "_err", "=", "gpg_proc", ".", "communicate", "(", ")", "if", "handle", ":", "handle", ".", "close", "(", ")", "return", "portable_b64encode", "(", "output", ")", "except", "subprocess", ".", "CalledProcessError", "as", "exception", ":", "LOGGER", ".", "debug", "(", "\"GPG Command %s\"", ",", "' '", ".", "join", "(", "exception", ".", "cmd", ")", ")", "LOGGER", ".", "debug", "(", "\"GPG Output %s\"", ",", "exception", ".", "output", ")", "raise", "CryptoritoError", "(", "'GPG encryption error'", ")" ]
Exports a GPG key and returns it
[ "Exports", "a", "GPG", "key", "and", "returns", "it" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L362-L378
Autodesk/cryptorito
cryptorito/__init__.py
encrypt
def encrypt(source, dest, keys): """Encrypts a file using the given keys""" cmd = flatten([gnupg_bin(), "--armor", "--output", dest, gnupg_verbose(), gnupg_home(), recipients_args(keys), "--encrypt", source]) stderr_output(cmd) return True
python
def encrypt(source, dest, keys): """Encrypts a file using the given keys""" cmd = flatten([gnupg_bin(), "--armor", "--output", dest, gnupg_verbose(), gnupg_home(), recipients_args(keys), "--encrypt", source]) stderr_output(cmd) return True
[ "def", "encrypt", "(", "source", ",", "dest", ",", "keys", ")", ":", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "\"--armor\"", ",", "\"--output\"", ",", "dest", ",", "gnupg_verbose", "(", ")", ",", "gnupg_home", "(", ")", ",", "recipients_args", "(", "keys", ")", ",", "\"--encrypt\"", ",", "source", "]", ")", "stderr_output", "(", "cmd", ")", "return", "True" ]
Encrypts a file using the given keys
[ "Encrypts", "a", "file", "using", "the", "given", "keys" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L387-L394
Autodesk/cryptorito
cryptorito/__init__.py
encrypt_var
def encrypt_var(source, keys): """Attempts to encrypt a variable""" cmd = flatten([gnupg_bin(), "--armor", "--encrypt", gnupg_verbose(), recipients_args(keys)]) output = stderr_with_input(cmd, source) return output
python
def encrypt_var(source, keys): """Attempts to encrypt a variable""" cmd = flatten([gnupg_bin(), "--armor", "--encrypt", gnupg_verbose(), recipients_args(keys)]) output = stderr_with_input(cmd, source) return output
[ "def", "encrypt_var", "(", "source", ",", "keys", ")", ":", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "\"--armor\"", ",", "\"--encrypt\"", ",", "gnupg_verbose", "(", ")", ",", "recipients_args", "(", "keys", ")", "]", ")", "output", "=", "stderr_with_input", "(", "cmd", ",", "source", ")", "return", "output" ]
Attempts to encrypt a variable
[ "Attempts", "to", "encrypt", "a", "variable" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L397-L402
Autodesk/cryptorito
cryptorito/__init__.py
gpg_error
def gpg_error(exception, message): """Handles the output of subprocess errors in a way that is compatible with the log level""" LOGGER.debug("GPG Command %s", ' '.join([str(x) for x in exception.cmd])) LOGGER.debug("GPG Output %s", exception.output) raise CryptoritoError(message)
python
def gpg_error(exception, message): """Handles the output of subprocess errors in a way that is compatible with the log level""" LOGGER.debug("GPG Command %s", ' '.join([str(x) for x in exception.cmd])) LOGGER.debug("GPG Output %s", exception.output) raise CryptoritoError(message)
[ "def", "gpg_error", "(", "exception", ",", "message", ")", ":", "LOGGER", ".", "debug", "(", "\"GPG Command %s\"", ",", "' '", ".", "join", "(", "[", "str", "(", "x", ")", "for", "x", "in", "exception", ".", "cmd", "]", ")", ")", "LOGGER", ".", "debug", "(", "\"GPG Output %s\"", ",", "exception", ".", "output", ")", "raise", "CryptoritoError", "(", "message", ")" ]
Handles the output of subprocess errors in a way that is compatible with the log level
[ "Handles", "the", "output", "of", "subprocess", "errors", "in", "a", "way", "that", "is", "compatible", "with", "the", "log", "level" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L405-L410
Autodesk/cryptorito
cryptorito/__init__.py
decrypt_var
def decrypt_var(source, passphrase=None): """Attempts to decrypt a variable""" cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(), passphrase_file(passphrase)] return stderr_with_input(flatten(cmd), source)
python
def decrypt_var(source, passphrase=None): """Attempts to decrypt a variable""" cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(), passphrase_file(passphrase)] return stderr_with_input(flatten(cmd), source)
[ "def", "decrypt_var", "(", "source", ",", "passphrase", "=", "None", ")", ":", "cmd", "=", "[", "gnupg_bin", "(", ")", ",", "\"--decrypt\"", ",", "gnupg_home", "(", ")", ",", "gnupg_verbose", "(", ")", ",", "passphrase_file", "(", "passphrase", ")", "]", "return", "stderr_with_input", "(", "flatten", "(", "cmd", ")", ",", "source", ")" ]
Attempts to decrypt a variable
[ "Attempts", "to", "decrypt", "a", "variable" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L413-L418
Autodesk/cryptorito
cryptorito/__init__.py
decrypt
def decrypt(source, dest=None, passphrase=None): """Attempts to decrypt a file""" if not os.path.exists(source): raise CryptoritoError("Encrypted file %s not found" % source) cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(), passphrase_file(passphrase)] if dest: cmd.append(["--output", dest]) cmd.append([source]) stderr_output(flatten(cmd)) return True
python
def decrypt(source, dest=None, passphrase=None): """Attempts to decrypt a file""" if not os.path.exists(source): raise CryptoritoError("Encrypted file %s not found" % source) cmd = [gnupg_bin(), gnupg_verbose(), "--decrypt", gnupg_home(), passphrase_file(passphrase)] if dest: cmd.append(["--output", dest]) cmd.append([source]) stderr_output(flatten(cmd)) return True
[ "def", "decrypt", "(", "source", ",", "dest", "=", "None", ",", "passphrase", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "source", ")", ":", "raise", "CryptoritoError", "(", "\"Encrypted file %s not found\"", "%", "source", ")", "cmd", "=", "[", "gnupg_bin", "(", ")", ",", "gnupg_verbose", "(", ")", ",", "\"--decrypt\"", ",", "gnupg_home", "(", ")", ",", "passphrase_file", "(", "passphrase", ")", "]", "if", "dest", ":", "cmd", ".", "append", "(", "[", "\"--output\"", ",", "dest", "]", ")", "cmd", ".", "append", "(", "[", "source", "]", ")", "stderr_output", "(", "flatten", "(", "cmd", ")", ")", "return", "True" ]
Attempts to decrypt a file
[ "Attempts", "to", "decrypt", "a", "file" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L421-L434
Autodesk/cryptorito
cryptorito/__init__.py
is_base64
def is_base64(string): """Determines whether or not a string is likely to be base64 encoded binary nonsense""" return (not re.match('^[0-9]+$', string)) and \ (len(string) % 4 == 0) and \ re.match('^[A-Za-z0-9+/]+[=]{0,2}$', string)
python
def is_base64(string): """Determines whether or not a string is likely to be base64 encoded binary nonsense""" return (not re.match('^[0-9]+$', string)) and \ (len(string) % 4 == 0) and \ re.match('^[A-Za-z0-9+/]+[=]{0,2}$', string)
[ "def", "is_base64", "(", "string", ")", ":", "return", "(", "not", "re", ".", "match", "(", "'^[0-9]+$'", ",", "string", ")", ")", "and", "(", "len", "(", "string", ")", "%", "4", "==", "0", ")", "and", "re", ".", "match", "(", "'^[A-Za-z0-9+/]+[=]{0,2}$'", ",", "string", ")" ]
Determines whether or not a string is likely to be base64 encoded binary nonsense
[ "Determines", "whether", "or", "not", "a", "string", "is", "likely", "to", "be", "base64", "encoded", "binary", "nonsense" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L437-L442
Autodesk/cryptorito
cryptorito/__init__.py
portable_b64encode
def portable_b64encode(thing): """Wrap b64encode for Python 2 & 3""" if is_py3(): try: some_bits = bytes(thing, 'utf-8') except TypeError: some_bits = thing return polite_string(b64encode(some_bits).decode('utf-8')) return polite_string(b64encode(thing))
python
def portable_b64encode(thing): """Wrap b64encode for Python 2 & 3""" if is_py3(): try: some_bits = bytes(thing, 'utf-8') except TypeError: some_bits = thing return polite_string(b64encode(some_bits).decode('utf-8')) return polite_string(b64encode(thing))
[ "def", "portable_b64encode", "(", "thing", ")", ":", "if", "is_py3", "(", ")", ":", "try", ":", "some_bits", "=", "bytes", "(", "thing", ",", "'utf-8'", ")", "except", "TypeError", ":", "some_bits", "=", "thing", "return", "polite_string", "(", "b64encode", "(", "some_bits", ")", ".", "decode", "(", "'utf-8'", ")", ")", "return", "polite_string", "(", "b64encode", "(", "thing", ")", ")" ]
Wrap b64encode for Python 2 & 3
[ "Wrap", "b64encode", "for", "Python", "2", "&", "3" ]
train
https://github.com/Autodesk/cryptorito/blob/277fc7cc42c31c5bc37e26d8bf5a2ac746a6ea85/cryptorito/__init__.py#L445-L455
davenquinn/Attitude
attitude/bingham.py
bingham_pdf
def bingham_pdf(fit): """ From the *Encyclopedia of Paleomagnetism* From Onstott, 1980: Vector resultant: R is analogous to eigenvectors of T. Eigenvalues are analogous to |R|/N. """ # Uses eigenvectors of the covariance matrix e = fit.hyperbolic_axes #singular_values #e = sampling_covariance(fit) # not sure e = e[2]**2/e kappa = (e-e[2])[:-1] kappa /= kappa[-1] F = N.sqrt(N.pi)*confluent_hypergeometric_function(*kappa) ax = fit.axes Z = 1/e M = ax F = 1/hyp1f1(*1/Z) def pdf(coords): lon,lat = coords I = lat D = lon# + N.pi/2 #D,I = _rotate(N.degrees(D),N.degrees(I),90) # Bingham is given in spherical coordinates of inclination # and declination in radians # From USGS bingham statistics reference xhat = N.array(sph2cart(lon,lat)).T #return F*expm(dot(xhat.T, M, N.diag(Z), M.T, xhat)) return 1/(F*N.exp(dot(xhat.T, M, N.diag(Z), M.T, xhat))) return pdf
python
def bingham_pdf(fit): """ From the *Encyclopedia of Paleomagnetism* From Onstott, 1980: Vector resultant: R is analogous to eigenvectors of T. Eigenvalues are analogous to |R|/N. """ # Uses eigenvectors of the covariance matrix e = fit.hyperbolic_axes #singular_values #e = sampling_covariance(fit) # not sure e = e[2]**2/e kappa = (e-e[2])[:-1] kappa /= kappa[-1] F = N.sqrt(N.pi)*confluent_hypergeometric_function(*kappa) ax = fit.axes Z = 1/e M = ax F = 1/hyp1f1(*1/Z) def pdf(coords): lon,lat = coords I = lat D = lon# + N.pi/2 #D,I = _rotate(N.degrees(D),N.degrees(I),90) # Bingham is given in spherical coordinates of inclination # and declination in radians # From USGS bingham statistics reference xhat = N.array(sph2cart(lon,lat)).T #return F*expm(dot(xhat.T, M, N.diag(Z), M.T, xhat)) return 1/(F*N.exp(dot(xhat.T, M, N.diag(Z), M.T, xhat))) return pdf
[ "def", "bingham_pdf", "(", "fit", ")", ":", "# Uses eigenvectors of the covariance matrix", "e", "=", "fit", ".", "hyperbolic_axes", "#singular_values", "#e = sampling_covariance(fit) # not sure", "e", "=", "e", "[", "2", "]", "**", "2", "/", "e", "kappa", "=", "(", "e", "-", "e", "[", "2", "]", ")", "[", ":", "-", "1", "]", "kappa", "/=", "kappa", "[", "-", "1", "]", "F", "=", "N", ".", "sqrt", "(", "N", ".", "pi", ")", "*", "confluent_hypergeometric_function", "(", "*", "kappa", ")", "ax", "=", "fit", ".", "axes", "Z", "=", "1", "/", "e", "M", "=", "ax", "F", "=", "1", "/", "hyp1f1", "(", "*", "1", "/", "Z", ")", "def", "pdf", "(", "coords", ")", ":", "lon", ",", "lat", "=", "coords", "I", "=", "lat", "D", "=", "lon", "# + N.pi/2", "#D,I = _rotate(N.degrees(D),N.degrees(I),90)", "# Bingham is given in spherical coordinates of inclination", "# and declination in radians", "# From USGS bingham statistics reference", "xhat", "=", "N", ".", "array", "(", "sph2cart", "(", "lon", ",", "lat", ")", ")", ".", "T", "#return F*expm(dot(xhat.T, M, N.diag(Z), M.T, xhat))", "return", "1", "/", "(", "F", "*", "N", ".", "exp", "(", "dot", "(", "xhat", ".", "T", ",", "M", ",", "N", ".", "diag", "(", "Z", ")", ",", "M", ".", "T", ",", "xhat", ")", ")", ")", "return", "pdf" ]
From the *Encyclopedia of Paleomagnetism* From Onstott, 1980: Vector resultant: R is analogous to eigenvectors of T. Eigenvalues are analogous to |R|/N.
[ "From", "the", "*", "Encyclopedia", "of", "Paleomagnetism", "*" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/bingham.py#L23-L66
RudolfCardinal/pythonlib
cardinal_pythonlib/buildfunc.py
download_if_not_exists
def download_if_not_exists(url: str, filename: str, skip_cert_verify: bool = True, mkdir: bool = True) -> None: """ Downloads a URL to a file, unless the file already exists. """ if os.path.isfile(filename): log.info("No need to download, already have: {}", filename) return if mkdir: directory, basename = os.path.split(os.path.abspath(filename)) mkdir_p(directory) download(url=url, filename=filename, skip_cert_verify=skip_cert_verify)
python
def download_if_not_exists(url: str, filename: str, skip_cert_verify: bool = True, mkdir: bool = True) -> None: """ Downloads a URL to a file, unless the file already exists. """ if os.path.isfile(filename): log.info("No need to download, already have: {}", filename) return if mkdir: directory, basename = os.path.split(os.path.abspath(filename)) mkdir_p(directory) download(url=url, filename=filename, skip_cert_verify=skip_cert_verify)
[ "def", "download_if_not_exists", "(", "url", ":", "str", ",", "filename", ":", "str", ",", "skip_cert_verify", ":", "bool", "=", "True", ",", "mkdir", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "log", ".", "info", "(", "\"No need to download, already have: {}\"", ",", "filename", ")", "return", "if", "mkdir", ":", "directory", ",", "basename", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "abspath", "(", "filename", ")", ")", "mkdir_p", "(", "directory", ")", "download", "(", "url", "=", "url", ",", "filename", "=", "filename", ",", "skip_cert_verify", "=", "skip_cert_verify", ")" ]
Downloads a URL to a file, unless the file already exists.
[ "Downloads", "a", "URL", "to", "a", "file", "unless", "the", "file", "already", "exists", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L56-L70
RudolfCardinal/pythonlib
cardinal_pythonlib/buildfunc.py
git_clone
def git_clone(prettyname: str, url: str, directory: str, branch: str = None, commit: str = None, clone_options: List[str] = None, run_func: Callable[[List[str]], Any] = None) -> bool: """ Fetches a Git repository, unless we have it already. Args: prettyname: name to display to user url: URL directory: destination directory branch: repository branch commit: repository commit tag clone_options: additional options to pass to ``git clone`` run_func: function to use to call an external command Returns: did we need to do anything? """ run_func = run_func or subprocess.check_call clone_options = clone_options or [] # type: List[str] if os.path.isdir(directory): log.info("Not re-cloning {} Git repository: using existing source " "in {}".format(prettyname, directory)) return False log.info("Fetching {} source from {} into {}", prettyname, url, directory) require_executable(GIT) gitargs = [GIT, "clone"] + clone_options if branch: gitargs += ["--branch", branch] gitargs += [url, directory] run_func(gitargs) if commit: log.info("Resetting {} local Git repository to commit {}", prettyname, commit) run_func([GIT, "-C", directory, "reset", "--hard", commit]) # Using a Git repository that's not in the working directory: # https://stackoverflow.com/questions/1386291/git-git-dir-not-working-as-expected # noqa return True
python
def git_clone(prettyname: str, url: str, directory: str, branch: str = None, commit: str = None, clone_options: List[str] = None, run_func: Callable[[List[str]], Any] = None) -> bool: """ Fetches a Git repository, unless we have it already. Args: prettyname: name to display to user url: URL directory: destination directory branch: repository branch commit: repository commit tag clone_options: additional options to pass to ``git clone`` run_func: function to use to call an external command Returns: did we need to do anything? """ run_func = run_func or subprocess.check_call clone_options = clone_options or [] # type: List[str] if os.path.isdir(directory): log.info("Not re-cloning {} Git repository: using existing source " "in {}".format(prettyname, directory)) return False log.info("Fetching {} source from {} into {}", prettyname, url, directory) require_executable(GIT) gitargs = [GIT, "clone"] + clone_options if branch: gitargs += ["--branch", branch] gitargs += [url, directory] run_func(gitargs) if commit: log.info("Resetting {} local Git repository to commit {}", prettyname, commit) run_func([GIT, "-C", directory, "reset", "--hard", commit]) # Using a Git repository that's not in the working directory: # https://stackoverflow.com/questions/1386291/git-git-dir-not-working-as-expected # noqa return True
[ "def", "git_clone", "(", "prettyname", ":", "str", ",", "url", ":", "str", ",", "directory", ":", "str", ",", "branch", ":", "str", "=", "None", ",", "commit", ":", "str", "=", "None", ",", "clone_options", ":", "List", "[", "str", "]", "=", "None", ",", "run_func", ":", "Callable", "[", "[", "List", "[", "str", "]", "]", ",", "Any", "]", "=", "None", ")", "->", "bool", ":", "run_func", "=", "run_func", "or", "subprocess", ".", "check_call", "clone_options", "=", "clone_options", "or", "[", "]", "# type: List[str]", "if", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "log", ".", "info", "(", "\"Not re-cloning {} Git repository: using existing source \"", "\"in {}\"", ".", "format", "(", "prettyname", ",", "directory", ")", ")", "return", "False", "log", ".", "info", "(", "\"Fetching {} source from {} into {}\"", ",", "prettyname", ",", "url", ",", "directory", ")", "require_executable", "(", "GIT", ")", "gitargs", "=", "[", "GIT", ",", "\"clone\"", "]", "+", "clone_options", "if", "branch", ":", "gitargs", "+=", "[", "\"--branch\"", ",", "branch", "]", "gitargs", "+=", "[", "url", ",", "directory", "]", "run_func", "(", "gitargs", ")", "if", "commit", ":", "log", ".", "info", "(", "\"Resetting {} local Git repository to commit {}\"", ",", "prettyname", ",", "commit", ")", "run_func", "(", "[", "GIT", ",", "\"-C\"", ",", "directory", ",", "\"reset\"", ",", "\"--hard\"", ",", "commit", "]", ")", "# Using a Git repository that's not in the working directory:", "# https://stackoverflow.com/questions/1386291/git-git-dir-not-working-as-expected # noqa", "return", "True" ]
Fetches a Git repository, unless we have it already. Args: prettyname: name to display to user url: URL directory: destination directory branch: repository branch commit: repository commit tag clone_options: additional options to pass to ``git clone`` run_func: function to use to call an external command Returns: did we need to do anything?
[ "Fetches", "a", "Git", "repository", "unless", "we", "have", "it", "already", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L77-L119
RudolfCardinal/pythonlib
cardinal_pythonlib/buildfunc.py
untar_to_directory
def untar_to_directory(tarfile: str, directory: str, verbose: bool = False, gzipped: bool = False, skip_if_dir_exists: bool = True, run_func: Callable[[List[str]], Any] = None, chdir_via_python: bool = True) -> None: """ Unpacks a TAR file into a specified directory. Args: tarfile: filename of the ``.tar`` file directory: destination directory verbose: be verbose? gzipped: is the ``.tar`` also gzipped, e.g. a ``.tar.gz`` file? skip_if_dir_exists: don't do anything if the destrination directory exists? run_func: function to use to call an external command chdir_via_python: change directory via Python, not via ``tar``. Consider using this via Windows, because Cygwin ``tar`` v1.29 falls over when given a Windows path for its ``-C`` (or ``--directory``) option. """ if skip_if_dir_exists and os.path.isdir(directory): log.info("Skipping extraction of {} as directory {} exists", tarfile, directory) return log.info("Extracting {} -> {}", tarfile, directory) require_executable(TAR) mkdir_p(directory) args = [TAR, "-x"] # -x: extract if verbose: args.append("-v") # -v: verbose if gzipped: args.append("-z") # -z: decompress using gzip if platform.system() != "Darwin": # OS/X tar doesn't support --force-local args.append("--force-local") # allows filenames with colons in (Windows!) # noqa args.extend(["-f", tarfile]) # -f: filename follows if chdir_via_python: with pushd(directory): run_func(args) else: # chdir via tar args.extend(["-C", directory]) # -C: change to directory run_func(args)
python
def untar_to_directory(tarfile: str, directory: str, verbose: bool = False, gzipped: bool = False, skip_if_dir_exists: bool = True, run_func: Callable[[List[str]], Any] = None, chdir_via_python: bool = True) -> None: """ Unpacks a TAR file into a specified directory. Args: tarfile: filename of the ``.tar`` file directory: destination directory verbose: be verbose? gzipped: is the ``.tar`` also gzipped, e.g. a ``.tar.gz`` file? skip_if_dir_exists: don't do anything if the destrination directory exists? run_func: function to use to call an external command chdir_via_python: change directory via Python, not via ``tar``. Consider using this via Windows, because Cygwin ``tar`` v1.29 falls over when given a Windows path for its ``-C`` (or ``--directory``) option. """ if skip_if_dir_exists and os.path.isdir(directory): log.info("Skipping extraction of {} as directory {} exists", tarfile, directory) return log.info("Extracting {} -> {}", tarfile, directory) require_executable(TAR) mkdir_p(directory) args = [TAR, "-x"] # -x: extract if verbose: args.append("-v") # -v: verbose if gzipped: args.append("-z") # -z: decompress using gzip if platform.system() != "Darwin": # OS/X tar doesn't support --force-local args.append("--force-local") # allows filenames with colons in (Windows!) # noqa args.extend(["-f", tarfile]) # -f: filename follows if chdir_via_python: with pushd(directory): run_func(args) else: # chdir via tar args.extend(["-C", directory]) # -C: change to directory run_func(args)
[ "def", "untar_to_directory", "(", "tarfile", ":", "str", ",", "directory", ":", "str", ",", "verbose", ":", "bool", "=", "False", ",", "gzipped", ":", "bool", "=", "False", ",", "skip_if_dir_exists", ":", "bool", "=", "True", ",", "run_func", ":", "Callable", "[", "[", "List", "[", "str", "]", "]", ",", "Any", "]", "=", "None", ",", "chdir_via_python", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "skip_if_dir_exists", "and", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "log", ".", "info", "(", "\"Skipping extraction of {} as directory {} exists\"", ",", "tarfile", ",", "directory", ")", "return", "log", ".", "info", "(", "\"Extracting {} -> {}\"", ",", "tarfile", ",", "directory", ")", "require_executable", "(", "TAR", ")", "mkdir_p", "(", "directory", ")", "args", "=", "[", "TAR", ",", "\"-x\"", "]", "# -x: extract", "if", "verbose", ":", "args", ".", "append", "(", "\"-v\"", ")", "# -v: verbose", "if", "gzipped", ":", "args", ".", "append", "(", "\"-z\"", ")", "# -z: decompress using gzip", "if", "platform", ".", "system", "(", ")", "!=", "\"Darwin\"", ":", "# OS/X tar doesn't support --force-local", "args", ".", "append", "(", "\"--force-local\"", ")", "# allows filenames with colons in (Windows!) # noqa", "args", ".", "extend", "(", "[", "\"-f\"", ",", "tarfile", "]", ")", "# -f: filename follows", "if", "chdir_via_python", ":", "with", "pushd", "(", "directory", ")", ":", "run_func", "(", "args", ")", "else", ":", "# chdir via tar", "args", ".", "extend", "(", "[", "\"-C\"", ",", "directory", "]", ")", "# -C: change to directory", "run_func", "(", "args", ")" ]
Unpacks a TAR file into a specified directory. Args: tarfile: filename of the ``.tar`` file directory: destination directory verbose: be verbose? gzipped: is the ``.tar`` also gzipped, e.g. a ``.tar.gz`` file? skip_if_dir_exists: don't do anything if the destrination directory exists? run_func: function to use to call an external command chdir_via_python: change directory via Python, not via ``tar``. Consider using this via Windows, because Cygwin ``tar`` v1.29 falls over when given a Windows path for its ``-C`` (or ``--directory``) option.
[ "Unpacks", "a", "TAR", "file", "into", "a", "specified", "directory", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L136-L180
RudolfCardinal/pythonlib
cardinal_pythonlib/buildfunc.py
make_copy_paste_env
def make_copy_paste_env(env: Dict[str, str]) -> str: """ Convert an environment into a set of commands that can be copied/pasted, on the build platform, to recreate that environment. """ windows = platform.system() == "Windows" cmd = "set" if windows else "export" return ( "\n".join( "{cmd} {k}={v}".format( cmd=cmd, k=k, v=env[k] if windows else subprocess.list2cmdline([env[k]]) ) for k in sorted(env.keys()) ) )
python
def make_copy_paste_env(env: Dict[str, str]) -> str: """ Convert an environment into a set of commands that can be copied/pasted, on the build platform, to recreate that environment. """ windows = platform.system() == "Windows" cmd = "set" if windows else "export" return ( "\n".join( "{cmd} {k}={v}".format( cmd=cmd, k=k, v=env[k] if windows else subprocess.list2cmdline([env[k]]) ) for k in sorted(env.keys()) ) )
[ "def", "make_copy_paste_env", "(", "env", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "str", ":", "windows", "=", "platform", ".", "system", "(", ")", "==", "\"Windows\"", "cmd", "=", "\"set\"", "if", "windows", "else", "\"export\"", "return", "(", "\"\\n\"", ".", "join", "(", "\"{cmd} {k}={v}\"", ".", "format", "(", "cmd", "=", "cmd", ",", "k", "=", "k", ",", "v", "=", "env", "[", "k", "]", "if", "windows", "else", "subprocess", ".", "list2cmdline", "(", "[", "env", "[", "k", "]", "]", ")", ")", "for", "k", "in", "sorted", "(", "env", ".", "keys", "(", ")", ")", ")", ")" ]
Convert an environment into a set of commands that can be copied/pasted, on the build platform, to recreate that environment.
[ "Convert", "an", "environment", "into", "a", "set", "of", "commands", "that", "can", "be", "copied", "/", "pasted", "on", "the", "build", "platform", "to", "recreate", "that", "environment", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L187-L202
RudolfCardinal/pythonlib
cardinal_pythonlib/buildfunc.py
run
def run(args: List[str], env: Dict[str, str] = None, capture_stdout: bool = False, echo_stdout: bool = True, capture_stderr: bool = False, echo_stderr: bool = True, debug_show_env: bool = True, encoding: str = sys.getdefaultencoding(), allow_failure: bool = False, **kwargs) -> Tuple[str, str]: """ Runs an external process, announcing it. Optionally, retrieves its ``stdout`` and/or ``stderr`` output (if not retrieved, the output will be visible to the user). Args: args: list of command-line arguments (the first being the executable) env: operating system environment to use (if ``None``, the current OS environment will be used) capture_stdout: capture the command's ``stdout``? echo_stdout: allow the command's ``stdout`` to go to ``sys.stdout``? capture_stderr: capture the command's ``stderr``? echo_stderr: allow the command's ``stderr`` to go to ``sys.stderr``? debug_show_env: be verbose and show the environment used before calling encoding: encoding to use to translate the command's output allow_failure: if ``True``, continues if the command returns a non-zero (failure) exit code; if ``False``, raises an error if that happens kwargs: additional arguments to :func:`teed_call` Returns: a tuple: ``(stdout, stderr)``. If the output wasn't captured, an empty string will take its place in this tuple. """ cwd = os.getcwd() # log.debug("External command Python form: {}", args) copy_paste_cmd = subprocess.list2cmdline(args) csep = "=" * 79 esep = "-" * 79 effective_env = env or os.environ if debug_show_env: log.debug( "Environment for the command that follows:\n" "{esep}\n" "{env}\n" "{esep}".format(esep=esep, env=make_copy_paste_env(effective_env)) ) log.info( "Launching external command:\n" "{csep}\n" "WORKING DIRECTORY: {cwd}\n" "PYTHON ARGS: {args!r}\n" "COMMAND: {cmd}\n" "{csep}".format(csep=csep, cwd=cwd, cmd=copy_paste_cmd, args=args) ) try: with io.StringIO() as out, io.StringIO() as err: stdout_targets = [] # type: List[TextIO] stderr_targets = [] # type: List[TextIO] if capture_stdout: stdout_targets.append(out) if echo_stdout: stdout_targets.append(sys.stdout) if capture_stderr: stderr_targets.append(err) if echo_stderr: stderr_targets.append(sys.stderr) retcode = teed_call(args, stdout_targets=stdout_targets, stderr_targets=stderr_targets, encoding=encoding, env=env, **kwargs) stdout = out.getvalue() stderr = err.getvalue() if retcode != 0 and not allow_failure: # subprocess.check_call() and check_output() raise # CalledProcessError if the called process returns a non-zero # return code. raise subprocess.CalledProcessError(returncode=retcode, cmd=args, output=stdout, stderr=stderr) log.debug("\n{csep}\nFINISHED SUCCESSFULLY: {cmd}\n{csep}", cmd=copy_paste_cmd, csep=csep) return stdout, stderr except FileNotFoundError: require_executable(args[0]) # which is missing, so we'll see some help raise except subprocess.CalledProcessError: log.critical( "Command that failed:\n" "[ENVIRONMENT]\n" "{env}\n" "\n" "[DIRECTORY] {cwd}\n" "[PYTHON ARGS] {args}\n" "[COMMAND] {cmd}".format( cwd=cwd, env=make_copy_paste_env(effective_env), cmd=copy_paste_cmd, args=args ) ) raise
python
def run(args: List[str], env: Dict[str, str] = None, capture_stdout: bool = False, echo_stdout: bool = True, capture_stderr: bool = False, echo_stderr: bool = True, debug_show_env: bool = True, encoding: str = sys.getdefaultencoding(), allow_failure: bool = False, **kwargs) -> Tuple[str, str]: """ Runs an external process, announcing it. Optionally, retrieves its ``stdout`` and/or ``stderr`` output (if not retrieved, the output will be visible to the user). Args: args: list of command-line arguments (the first being the executable) env: operating system environment to use (if ``None``, the current OS environment will be used) capture_stdout: capture the command's ``stdout``? echo_stdout: allow the command's ``stdout`` to go to ``sys.stdout``? capture_stderr: capture the command's ``stderr``? echo_stderr: allow the command's ``stderr`` to go to ``sys.stderr``? debug_show_env: be verbose and show the environment used before calling encoding: encoding to use to translate the command's output allow_failure: if ``True``, continues if the command returns a non-zero (failure) exit code; if ``False``, raises an error if that happens kwargs: additional arguments to :func:`teed_call` Returns: a tuple: ``(stdout, stderr)``. If the output wasn't captured, an empty string will take its place in this tuple. """ cwd = os.getcwd() # log.debug("External command Python form: {}", args) copy_paste_cmd = subprocess.list2cmdline(args) csep = "=" * 79 esep = "-" * 79 effective_env = env or os.environ if debug_show_env: log.debug( "Environment for the command that follows:\n" "{esep}\n" "{env}\n" "{esep}".format(esep=esep, env=make_copy_paste_env(effective_env)) ) log.info( "Launching external command:\n" "{csep}\n" "WORKING DIRECTORY: {cwd}\n" "PYTHON ARGS: {args!r}\n" "COMMAND: {cmd}\n" "{csep}".format(csep=csep, cwd=cwd, cmd=copy_paste_cmd, args=args) ) try: with io.StringIO() as out, io.StringIO() as err: stdout_targets = [] # type: List[TextIO] stderr_targets = [] # type: List[TextIO] if capture_stdout: stdout_targets.append(out) if echo_stdout: stdout_targets.append(sys.stdout) if capture_stderr: stderr_targets.append(err) if echo_stderr: stderr_targets.append(sys.stderr) retcode = teed_call(args, stdout_targets=stdout_targets, stderr_targets=stderr_targets, encoding=encoding, env=env, **kwargs) stdout = out.getvalue() stderr = err.getvalue() if retcode != 0 and not allow_failure: # subprocess.check_call() and check_output() raise # CalledProcessError if the called process returns a non-zero # return code. raise subprocess.CalledProcessError(returncode=retcode, cmd=args, output=stdout, stderr=stderr) log.debug("\n{csep}\nFINISHED SUCCESSFULLY: {cmd}\n{csep}", cmd=copy_paste_cmd, csep=csep) return stdout, stderr except FileNotFoundError: require_executable(args[0]) # which is missing, so we'll see some help raise except subprocess.CalledProcessError: log.critical( "Command that failed:\n" "[ENVIRONMENT]\n" "{env}\n" "\n" "[DIRECTORY] {cwd}\n" "[PYTHON ARGS] {args}\n" "[COMMAND] {cmd}".format( cwd=cwd, env=make_copy_paste_env(effective_env), cmd=copy_paste_cmd, args=args ) ) raise
[ "def", "run", "(", "args", ":", "List", "[", "str", "]", ",", "env", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "capture_stdout", ":", "bool", "=", "False", ",", "echo_stdout", ":", "bool", "=", "True", ",", "capture_stderr", ":", "bool", "=", "False", ",", "echo_stderr", ":", "bool", "=", "True", ",", "debug_show_env", ":", "bool", "=", "True", ",", "encoding", ":", "str", "=", "sys", ".", "getdefaultencoding", "(", ")", ",", "allow_failure", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "cwd", "=", "os", ".", "getcwd", "(", ")", "# log.debug(\"External command Python form: {}\", args)", "copy_paste_cmd", "=", "subprocess", ".", "list2cmdline", "(", "args", ")", "csep", "=", "\"=\"", "*", "79", "esep", "=", "\"-\"", "*", "79", "effective_env", "=", "env", "or", "os", ".", "environ", "if", "debug_show_env", ":", "log", ".", "debug", "(", "\"Environment for the command that follows:\\n\"", "\"{esep}\\n\"", "\"{env}\\n\"", "\"{esep}\"", ".", "format", "(", "esep", "=", "esep", ",", "env", "=", "make_copy_paste_env", "(", "effective_env", ")", ")", ")", "log", ".", "info", "(", "\"Launching external command:\\n\"", "\"{csep}\\n\"", "\"WORKING DIRECTORY: {cwd}\\n\"", "\"PYTHON ARGS: {args!r}\\n\"", "\"COMMAND: {cmd}\\n\"", "\"{csep}\"", ".", "format", "(", "csep", "=", "csep", ",", "cwd", "=", "cwd", ",", "cmd", "=", "copy_paste_cmd", ",", "args", "=", "args", ")", ")", "try", ":", "with", "io", ".", "StringIO", "(", ")", "as", "out", ",", "io", ".", "StringIO", "(", ")", "as", "err", ":", "stdout_targets", "=", "[", "]", "# type: List[TextIO]", "stderr_targets", "=", "[", "]", "# type: List[TextIO]", "if", "capture_stdout", ":", "stdout_targets", ".", "append", "(", "out", ")", "if", "echo_stdout", ":", "stdout_targets", ".", "append", "(", "sys", ".", "stdout", ")", "if", "capture_stderr", ":", "stderr_targets", ".", "append", "(", "err", ")", "if", "echo_stderr", ":", "stderr_targets", ".", "append", "(", "sys", ".", "stderr", ")", "retcode", "=", "teed_call", "(", "args", ",", "stdout_targets", "=", "stdout_targets", ",", "stderr_targets", "=", "stderr_targets", ",", "encoding", "=", "encoding", ",", "env", "=", "env", ",", "*", "*", "kwargs", ")", "stdout", "=", "out", ".", "getvalue", "(", ")", "stderr", "=", "err", ".", "getvalue", "(", ")", "if", "retcode", "!=", "0", "and", "not", "allow_failure", ":", "# subprocess.check_call() and check_output() raise", "# CalledProcessError if the called process returns a non-zero", "# return code.", "raise", "subprocess", ".", "CalledProcessError", "(", "returncode", "=", "retcode", ",", "cmd", "=", "args", ",", "output", "=", "stdout", ",", "stderr", "=", "stderr", ")", "log", ".", "debug", "(", "\"\\n{csep}\\nFINISHED SUCCESSFULLY: {cmd}\\n{csep}\"", ",", "cmd", "=", "copy_paste_cmd", ",", "csep", "=", "csep", ")", "return", "stdout", ",", "stderr", "except", "FileNotFoundError", ":", "require_executable", "(", "args", "[", "0", "]", ")", "# which is missing, so we'll see some help", "raise", "except", "subprocess", ".", "CalledProcessError", ":", "log", ".", "critical", "(", "\"Command that failed:\\n\"", "\"[ENVIRONMENT]\\n\"", "\"{env}\\n\"", "\"\\n\"", "\"[DIRECTORY] {cwd}\\n\"", "\"[PYTHON ARGS] {args}\\n\"", "\"[COMMAND] {cmd}\"", ".", "format", "(", "cwd", "=", "cwd", ",", "env", "=", "make_copy_paste_env", "(", "effective_env", ")", ",", "cmd", "=", "copy_paste_cmd", ",", "args", "=", "args", ")", ")", "raise" ]
Runs an external process, announcing it. Optionally, retrieves its ``stdout`` and/or ``stderr`` output (if not retrieved, the output will be visible to the user). Args: args: list of command-line arguments (the first being the executable) env: operating system environment to use (if ``None``, the current OS environment will be used) capture_stdout: capture the command's ``stdout``? echo_stdout: allow the command's ``stdout`` to go to ``sys.stdout``? capture_stderr: capture the command's ``stderr``? echo_stderr: allow the command's ``stderr`` to go to ``sys.stderr``? debug_show_env: be verbose and show the environment used before calling encoding: encoding to use to translate the command's output allow_failure: if ``True``, continues if the command returns a non-zero (failure) exit code; if ``False``, raises an error if that happens kwargs: additional arguments to :func:`teed_call` Returns: a tuple: ``(stdout, stderr)``. If the output wasn't captured, an empty string will take its place in this tuple.
[ "Runs", "an", "external", "process", "announcing", "it", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L213-L328
RudolfCardinal/pythonlib
cardinal_pythonlib/buildfunc.py
fetch
def fetch(args: List[str], env: Dict[str, str] = None, encoding: str = sys.getdefaultencoding()) -> str: """ Run a command and returns its stdout. Args: args: the command-line arguments env: the operating system environment to use encoding: the encoding to use for ``stdout`` Returns: the command's ``stdout`` output """ stdout, _ = run(args, env=env, capture_stdout=True, echo_stdout=False, encoding=encoding) log.debug(stdout) return stdout
python
def fetch(args: List[str], env: Dict[str, str] = None, encoding: str = sys.getdefaultencoding()) -> str: """ Run a command and returns its stdout. Args: args: the command-line arguments env: the operating system environment to use encoding: the encoding to use for ``stdout`` Returns: the command's ``stdout`` output """ stdout, _ = run(args, env=env, capture_stdout=True, echo_stdout=False, encoding=encoding) log.debug(stdout) return stdout
[ "def", "fetch", "(", "args", ":", "List", "[", "str", "]", ",", "env", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "encoding", ":", "str", "=", "sys", ".", "getdefaultencoding", "(", ")", ")", "->", "str", ":", "stdout", ",", "_", "=", "run", "(", "args", ",", "env", "=", "env", ",", "capture_stdout", "=", "True", ",", "echo_stdout", "=", "False", ",", "encoding", "=", "encoding", ")", "log", ".", "debug", "(", "stdout", ")", "return", "stdout" ]
Run a command and returns its stdout. Args: args: the command-line arguments env: the operating system environment to use encoding: the encoding to use for ``stdout`` Returns: the command's ``stdout`` output
[ "Run", "a", "command", "and", "returns", "its", "stdout", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/buildfunc.py#L331-L348
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/dump.py
dump_connection_info
def dump_connection_info(engine: Engine, fileobj: TextIO = sys.stdout) -> None: """ Dumps some connection info, as an SQL comment. Obscures passwords. Args: engine: the SQLAlchemy :class:`Engine` to dump metadata information from fileobj: the file-like object (default ``sys.stdout``) to write information to """ meta = MetaData(bind=engine) writeline_nl(fileobj, sql_comment('Database info: {}'.format(meta)))
python
def dump_connection_info(engine: Engine, fileobj: TextIO = sys.stdout) -> None: """ Dumps some connection info, as an SQL comment. Obscures passwords. Args: engine: the SQLAlchemy :class:`Engine` to dump metadata information from fileobj: the file-like object (default ``sys.stdout``) to write information to """ meta = MetaData(bind=engine) writeline_nl(fileobj, sql_comment('Database info: {}'.format(meta)))
[ "def", "dump_connection_info", "(", "engine", ":", "Engine", ",", "fileobj", ":", "TextIO", "=", "sys", ".", "stdout", ")", "->", "None", ":", "meta", "=", "MetaData", "(", "bind", "=", "engine", ")", "writeline_nl", "(", "fileobj", ",", "sql_comment", "(", "'Database info: {}'", ".", "format", "(", "meta", ")", ")", ")" ]
Dumps some connection info, as an SQL comment. Obscures passwords. Args: engine: the SQLAlchemy :class:`Engine` to dump metadata information from fileobj: the file-like object (default ``sys.stdout``) to write information to
[ "Dumps", "some", "connection", "info", "as", "an", "SQL", "comment", ".", "Obscures", "passwords", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L65-L76