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
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
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 Retur...
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 Retur...
[ "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]", ...
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...
[ "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 ``loggin...
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 ``loggin...
[ "def", "debug_object", "(", "obj", ",", "log_level", ":", "int", "=", "logging", ".", "DEBUG", ")", "->", "None", ":", "msgs", "=", "[", "\"For {o!r}:\"", ".", "format", "(", "o", "=", "obj", ")", "]", "for", "attrname", "in", "dir", "(", "obj", ")...
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 anythi...
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 anythi...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "return", "value", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "return", "value", "try", ":", "return", "json_decode", "(", "value", ")", "e...
"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, y...
[ "Called", "during", "deserialization", "and", "during", "the", "clean", "()", "method", "used", "from", "forms", "....", "[", "s", "]", "hould", "deal", "gracefully", "with", "...", "(", "*", ")", "an", "instance", "of", "the", "correct", "type", ";", "(...
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 ...
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 ...
[ "def", "parse", "(", "xml_input", ",", "encoding", "=", "None", ",", "expat", "=", "expat", ",", "process_namespaces", "=", "False", ",", "namespace_separator", "=", "':'", ",", "*", "*", "kwargs", ")", ":", "handler", "=", "_DictSAXHandler", "(", "namespa...
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 ign...
[ "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): ... ...
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): ... ...
[ "def", "cxxRecordDecl", "(", "*", "args", ")", ":", "kinds", "=", "[", "CursorKind", ".", "CLASS_DECL", ",", "CursorKind", ".", "CLASS_TEMPLATE", ",", "]", "inner", "=", "[", "PredMatcher", "(", "is_kind", "(", "k", ")", ")", "for", "k", "in", "kinds",...
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):...
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):...
[ "def", "recordDecl", "(", "*", "args", ")", ":", "kinds", "=", "[", "CursorKind", ".", "STRUCT_DECL", ",", "CursorKind", ".", "UNION_DECL", ",", "CursorKind", ".", "CLASS_DECL", ",", "CursorKind", ".", "CLASS_TEMPLATE", ",", "]", "inner", "=", "[", "PredMa...
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)...
[ "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... ...
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... ...
[ "def", "convert_to_bool", "(", "x", ":", "Any", ",", "default", ":", "bool", "=", "None", ")", "->", "bool", ":", "if", "isinstance", "(", "x", ",", "bool", ")", ":", "return", "x", "if", "not", "x", ":", "# None, zero, blank string...", "return", "def...
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_boo...
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_boo...
[ "def", "convert_attrs_to_bool", "(", "obj", ":", "Any", ",", "attrs", ":", "Iterable", "[", "str", "]", ",", "default", ":", "bool", "=", "None", ")", "->", "None", ":", "for", "a", "in", "attrs", ":", "setattr", "(", "obj", ",", "a", ",", "convert...
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.up...
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.up...
[ "def", "convert_attrs_to_uppercase", "(", "obj", ":", "Any", ",", "attrs", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "for", "a", "in", "attrs", ":", "value", "=", "getattr", "(", "obj", ",", "a", ")", "if", "value", "is", "None", ":...
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.lo...
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.lo...
[ "def", "convert_attrs_to_lowercase", "(", "obj", ":", "Any", ",", "attrs", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "for", "a", "in", "attrs", ":", "value", "=", "getattr", "(", "obj", ",", "a", ")", "if", "value", "is", "None", ":...
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,...
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,...
[ "def", "convert_attrs_to_int", "(", "obj", ":", "Any", ",", "attrs", ":", "Iterable", "[", "str", "]", ",", "default", ":", "int", "=", "None", ")", "->", "None", ":", "for", "a", "in", "attrs", ":", "value", "=", "convert_to_int", "(", "getattr", "(...
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'`` ...
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'`` ...
[ "def", "hex_xformat_decode", "(", "s", ":", "str", ")", "->", "Optional", "[", "bytes", "]", ":", "if", "len", "(", "s", ")", "<", "3", "or", "not", "s", ".", "startswith", "(", "\"X'\"", ")", "or", "not", "s", ".", "endswith", "(", "\"'\"", ")",...
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, s...
[ "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)...
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)...
[ "def", "base64_64format_decode", "(", "s", ":", "str", ")", "->", "Optional", "[", "bytes", "]", ":", "if", "len", "(", "s", ")", "<", "4", "or", "not", "s", ".", "startswith", "(", "\"64'\"", ")", "or", "not", "s", ".", "endswith", "(", "\"'\"", ...
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 - ...
[ "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 ...
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 ...
[ "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...
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 ...
[ "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: ...
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: ...
[ "def", "load", "(", "klass", ")", ":", "config", "=", "klass", "(", ")", "for", "path", "in", "klass", ".", "CONF_PATHS", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "c...
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", "configura...
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 ...
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 ...
[ "def", "configure", "(", "self", ",", "conf", "=", "{", "}", ")", ":", "if", "not", "conf", ":", "return", "if", "isinstance", "(", "conf", ",", "Configuration", ")", ":", "conf", "=", "dict", "(", "conf", ".", "options", "(", ")", ")", "for", "k...
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",...
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 ...
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 ...
[ "def", "options", "(", "self", ")", ":", "keys", "=", "self", ".", "__class__", ".", "__dict__", ".", "copy", "(", ")", "keys", ".", "update", "(", "self", ".", "__dict__", ")", "keys", "=", "sorted", "(", "keys", ".", "keys", "(", ")", ")", "for...
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: ...
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: ...
[ "def", "formatdt", "(", "date", ":", "datetime", ".", "date", ",", "include_time", ":", "bool", "=", "True", ")", "->", "str", ":", "if", "include_time", ":", "return", "date", ".", "strftime", "(", "\"%Y-%m-%dT%H:%M\"", ")", "else", ":", "return", "date...
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`` ...
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`` ...
[ "def", "convert_duration", "(", "duration", ":", "datetime", ".", "timedelta", ",", "units", ":", "str", ")", "->", "Optional", "[", "float", "]", ":", "if", "duration", "is", "None", ":", "return", "None", "s", "=", "duration", ".", "total_seconds", "("...
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! .. c...
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! .. c...
[ "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 ...
[ "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? """ i...
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? """ i...
[ "def", "contains", "(", "self", ",", "time", ":", "datetime", ".", "datetime", ",", "inclusive", ":", "bool", "=", "True", ")", "->", "bool", ":", "if", "inclusive", ":", "return", "self", ".", "start", "<=", "time", "<=", "self", ".", "end", "else",...
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: re...
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: re...
[ "def", "within", "(", "self", ",", "other", ":", "\"Interval\"", ",", "inclusive", ":", "bool", "=", "True", ")", "->", "bool", ":", "if", "not", "other", ":", "return", "False", "if", "inclusive", ":", "return", "self", ".", "start", ">=", "other", ...
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( ...
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( ...
[ "def", "intersection", "(", "self", ",", "other", ":", "\"Interval\"", ")", "->", "Optional", "[", "\"Interval\"", "]", ":", "if", "not", "self", ".", "contiguous", "(", "other", ")", ":", "return", "None", "return", "Interval", "(", "max", "(", "self", ...
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...
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...
[ "def", "cut", "(", "self", ",", "times", ":", "Union", "[", "datetime", ".", "datetime", ",", "List", "[", "datetime", ".", "datetime", "]", "]", ")", "->", "List", "[", "\"Interval\"", "]", ":", "if", "not", "isinstance", "(", "times", ",", "list", ...
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( ...
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( ...
[ "def", "wholeday", "(", "date", ":", "datetime", ".", "date", ")", "->", "\"Interval\"", ":", "start", "=", "datetime", ".", "datetime", ".", "combine", "(", "date", ",", "datetime", ".", "time", "(", ")", ")", "return", "Interval", "(", "start", ",", ...
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. """ ...
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. """ ...
[ "def", "daytime", "(", "date", ":", "datetime", ".", "date", ",", "daybreak", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_START_H", ")", ",", "nightfall", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", ...
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 l...
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 l...
[ "def", "dayspan", "(", "startdate", ":", "datetime", ".", "date", ",", "enddate", ":", "datetime", ".", "date", ",", "include_end", ":", "bool", "=", "True", ")", "->", "Optional", "[", "\"Interval\"", "]", ":", "if", "enddate", "<", "startdate", ":", ...
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", ".", ...
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.ti...
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.ti...
[ "def", "day_night_duration", "(", "self", ",", "daybreak", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_START_H", ")", ",", "nightfall", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_END_H", ")",...
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...
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...
[ "def", "duration_outside_nwh", "(", "self", ",", "starttime", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_START_H", ")", ",", "endtime", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_END_H", ")"...
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 c...
[ "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 =...
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 =...
[ "def", "n_weekends", "(", "self", ")", "->", "int", ":", "startdate", "=", "self", ".", "start", ".", "date", "(", ")", "enddate", "=", "self", ".", "end", ".", "date", "(", ")", "ndays", "=", "(", "enddate", "-", "startdate", ")", ".", "days", "...
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 ...
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 ...
[ "def", "saturdays_of_weekends", "(", "self", ")", "->", "Set", "[", "datetime", ".", "date", "]", ":", "startdate", "=", "self", ".", "start", ".", "date", "(", ")", "enddate", "=", "self", ".", "end", ".", "date", "(", ")", "ndays", "=", "(", "end...
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", "...
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 ...
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 ...
[ "def", "copy", "(", "self", ",", "no_overlap", ":", "bool", "=", "None", ",", "no_contiguous", ":", "bool", "=", "None", ")", "->", "\"IntervalList\"", ":", "if", "no_overlap", "is", "None", ":", "no_overlap", "=", "self", ".", "no_overlap", "if", "no_co...
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 a...
[ "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): ...
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): ...
[ "def", "add", "(", "self", ",", "interval", ":", "Interval", ")", "->", "None", ":", "if", "interval", "is", "None", ":", "return", "if", "not", "isinstance", "(", "interval", ",", "Interval", ")", ":", "raise", "TypeError", "(", "\"Attempt to insert non-I...
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: ...
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: ...
[ "def", "_remove_overlap_sub", "(", "self", ",", "also_remove_contiguous", ":", "bool", ")", "->", "bool", ":", "# Returns", "for", "i", "in", "range", "(", "len", "(", "self", ".", "intervals", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", ...
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 over...
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 over...
[ "def", "remove_overlap", "(", "self", ",", "also_remove_contiguous", ":", "bool", "=", "False", ")", "->", "None", ":", "overlap", "=", "True", "while", "overlap", ":", "overlap", "=", "self", ".", "_remove_overlap_sub", "(", "also_remove_contiguous", ")", "se...
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)...
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)...
[ "def", "_any_overlap_or_contiguous", "(", "self", ",", "test_overlap", ":", "bool", ")", "->", "bool", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "intervals", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", ",", "le...
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_...
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_...
[ "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 += ...
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 += ...
[ "def", "total_duration", "(", "self", ")", "->", "datetime", ".", "timedelta", ":", "total", "=", "datetime", ".", "timedelta", "(", ")", "for", "interval", "in", "self", ".", "intervals", ":", "total", "+=", "interval", ".", "duration", "(", ")", "retur...
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...
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...
[ "def", "get_overlaps", "(", "self", ")", "->", "\"IntervalList\"", ":", "overlaps", "=", "IntervalList", "(", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "intervals", ")", ")", ":", "for", "j", "in", "range", "(", "i", "+", "1", "...
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", "(", ")", "==", "...
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 re...
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 re...
[ "def", "first_interval_starting", "(", "self", ",", "start", ":", "datetime", ".", "datetime", ")", "->", "Optional", "[", "Interval", "]", ":", "for", "i", "in", "self", ".", "intervals", ":", "if", "i", ".", "start", "==", "start", ":", "return", "i"...
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", "ret...
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( ...
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( ...
[ "def", "gaps", "(", "self", ")", "->", "\"IntervalList\"", ":", "if", "len", "(", "self", ".", "intervals", ")", "<", "2", ":", "return", "IntervalList", "(", "None", ")", "gaps", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "self", ...
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. ...
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. ...
[ "def", "subset", "(", "self", ",", "interval", ":", "Interval", ",", "flexibility", ":", "int", "=", "2", ")", "->", "\"IntervalList\"", ":", "if", "flexibility", "not", "in", "[", "0", ",", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "\"sub...
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 i...
[ "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", "parame...
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. ...
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. ...
[ "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(...
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(...
[ "def", "n_weekends", "(", "self", ")", "->", "int", ":", "saturdays", "=", "set", "(", ")", "for", "interval", "in", "self", ".", "intervals", ":", "saturdays", ".", "update", "(", "interval", ".", "saturdays_of_weekends", "(", ")", ")", "return", "len",...
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. eveni...
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. eveni...
[ "def", "duration_outside_nwh", "(", "self", ",", "starttime", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_START_H", ")", ",", "endtime", ":", "datetime", ".", "time", "=", "datetime", ".", "time", "(", "NORMAL_DAY_END_H", ")"...
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 :cl...
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 :cl...
[ "def", "max_consecutive_days", "(", "self", ")", "->", "Optional", "[", "Tuple", "[", "int", ",", "Interval", "]", "]", ":", "if", "len", "(", "self", ".", "intervals", ")", "==", "0", ":", "return", "None", "startdate", "=", "self", ".", "start_date",...
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 -...
[ "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 (sp...
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 (sp...
[ "def", "_sufficient_gaps", "(", "self", ",", "startdate", ":", "datetime", ".", "date", ",", "enddate", ":", "datetime", ".", "date", ",", "requiredgaps", ":", "List", "[", "datetime", ".", "timedelta", "]", ",", "flexibility", ":", "int", ")", "->", "Tu...
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: .. c...
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: .. c...
[ "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 (separ...
[ "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....
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....
[ "def", "cumulative_time_to", "(", "self", ",", "when", ":", "datetime", ".", "datetime", ")", "->", "datetime", ".", "timedelta", ":", "assert", "self", ".", "no_overlap", ",", "self", ".", "_ONLY_FOR_NO_INTERVAL", "cumulative", "=", "datetime", ".", "timedelt...
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 en...
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 en...
[ "def", "time_afterwards_preceding", "(", "self", ",", "when", ":", "datetime", ".", "datetime", ")", "->", "Optional", "[", "datetime", ".", "timedelta", "]", ":", "if", "self", ".", "is_empty", "(", ")", ":", "return", "None", "end_time", "=", "self", "...
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 give...
python
def cumulative_before_during_after(self, start: datetime.datetime, when: datetime.datetime) -> \ Tuple[datetime.timedelta, datetime.timedelta, datetime.timedelta]: """ For a give...
[ "def", "cumulative_before_during_after", "(", "self", ",", "start", ":", "datetime", ".", "datetime", ",", "when", ":", "datetime", ".", "datetime", ")", "->", "Tuple", "[", "datetime", ".", "timedelta", ",", "datetime", ".", "timedelta", ",", "datetime", "....
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 ...
[ "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", "t...
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, ki...
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, ki...
[ "def", "repr_parameter", "(", "param", ":", "inspect", ".", "Parameter", ")", "->", "str", ":", "return", "(", "\"Parameter(name={name}, annotation={annotation}, kind={kind}, \"", "\"default={default}\"", ".", "format", "(", "name", "=", "param", ".", "name", ",", "...
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 ...
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 ...
[ "def", "get_namespace", "(", "fn", ":", "Callable", ",", "namespace", ":", "Optional", "[", "str", "]", ")", "->", "str", ":", "# noqa", "# See hidden attributes with dir(fn)", "# noinspection PyUnresolvedReferences", "return", "\"{module}:{name}{extra}\"", ".", "format...
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, whi...
[ "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 te...
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 te...
[ "def", "fkg_allowing_type_hints", "(", "namespace", ":", "Optional", "[", "str", "]", ",", "fn", ":", "Callable", ",", "to_str", ":", "Callable", "[", "[", "Any", "]", ",", "str", "]", "=", "repr", ")", "->", "Callable", "[", "[", "Any", "]", ",", ...
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 ...
[ "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) t...
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) t...
[ "def", "kw_fkg_allowing_type_hints", "(", "namespace", ":", "Optional", "[", "str", "]", ",", "fn", ":", "Callable", ",", "to_str", ":", "Callable", "[", "[", "Any", "]", ",", "str", "]", "=", "repr", ")", "->", "Callable", "[", "[", "Any", "]", ",",...
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 keyw...
[ "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", "]", "...
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", ...
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_typ...
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_typ...
[ "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'...
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....
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....
[ "def", "actually_flatten", "(", "iterable", ")", ":", "remainder", "=", "iter", "(", "iterable", ")", "while", "True", ":", "first", "=", "next", "(", "remainder", ")", "# pylint: disable=R1708", "# Python 2/3 compat", "is_iter", "=", "isinstance", "(", "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_PASS...
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_PASS...
[ "def", "passphrase_file", "(", "passphrase", "=", "None", ")", ":", "cmd", "=", "[", "]", "pass_file", "=", "None", "if", "not", "passphrase", "and", "'CRYPTORITO_PASSPHRASE_FILE'", "in", "os", ".", "environ", ":", "pass_file", "=", "os", ".", "environ", "...
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", "e...
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: ...
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: ...
[ "def", "gnupg_home", "(", ")", ":", "if", "'GNUPGHOME'", "in", "os", ".", "environ", ":", "gnupghome", "=", "os", ".", "environ", "[", "'GNUPGHOME'", "]", "if", "not", "os", ".", "path", ".", "isdir", "(", "gnupghome", ")", ":", "raise", "CryptoritoErr...
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 = fingerpr...
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 = fingerpr...
[ "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'", "]", "[", "'p...
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: ...
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: ...
[ "def", "key_from_keybase", "(", "username", ",", "fingerprint", "=", "None", ")", ":", "url", "=", "keybase_lookup_url", "(", "username", ")", "resp", "=", "requests", ".", "get", "(", "url", ")", "if", "resp", ".", "status_code", "==", "200", ":", "j_re...
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(...
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(...
[ "def", "has_gpg_key", "(", "fingerprint", ")", ":", "if", "len", "(", "fingerprint", ")", ">", "8", ":", "fingerprint", "=", "fingerprint", "[", "-", "8", ":", "]", "fingerprint", "=", "fingerprint", ".", "upper", "(", ")", "cmd", "=", "flatten", "(", ...
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...
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...
[ "def", "fingerprint_from_var", "(", "var", ")", ":", "vsn", "=", "gpg_version", "(", ")", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "gnupg_home", "(", ")", "]", ")", "if", "vsn", "[", "0", "]", ">=", "2", "and", "vsn", "[", "1"...
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'", ")", ...
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(...
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(...
[ "def", "stderr_handle", "(", ")", ":", "gpg_stderr", "=", "None", "handle", "=", "None", "if", "LOGGER", ".", "getEffectiveLevel", "(", ")", ">", "logging", ".", "DEBUG", ":", "handle", "=", "open", "(", "os", ".", "devnull", ",", "'wb'", ")", "gpg_std...
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(pol...
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(pol...
[ "def", "stderr_output", "(", "cmd", ")", ":", "handle", ",", "gpg_stderr", "=", "stderr_handle", "(", ")", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "gpg_stderr", ")", "# nosec", "if", "handle", ":", "h...
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 ...
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 ...
[ "def", "stderr_with_input", "(", "cmd", ",", "stdin", ")", ":", "handle", ",", "gpg_stderr", "=", "stderr_handle", "(", ")", "LOGGER", ".", "debug", "(", "\"GPG command %s\"", ",", "' '", ".", "join", "(", "cmd", ")", ")", "try", ":", "gpg_proc", "=", ...
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(), gnup...
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(), gnup...
[ "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", "("...
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 ...
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 ...
[ "def", "export_gpg_key", "(", "key", ")", ":", "cmd", "=", "flatten", "(", "[", "gnupg_bin", "(", ")", ",", "gnupg_verbose", "(", ")", ",", "gnupg_home", "(", ")", ",", "\"--export\"", ",", "key", "]", ")", "handle", ",", "gpg_stderr", "=", "stderr_han...
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", "(", ")", ",", "reci...
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", ...
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", ".", "de...
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", ")", "]",...
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: ...
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: ...
[ "def", "decrypt", "(", "source", ",", "dest", "=", "None", ",", "passphrase", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "source", ")", ":", "raise", "CryptoritoError", "(", "\"Encrypted file %s not found\"", "%", "source", ...
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+/]+[=]...
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"...
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 = sampl...
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 = sampl...
[ "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", "=", "(...
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, alr...
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, alr...
[ "def", "download_if_not_exists", "(", "url", ":", "str", ",", "filename", ":", "str", ",", "skip_cert_verify", ":", "bool", "=", "True", ",", "mkdir", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "os", ".", "path", ".", "isfile", "(", "fil...
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: ...
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: ...
[ "def", "git_clone", "(", "prettyname", ":", "str", ",", "url", ":", "str", ",", "directory", ":", "str", ",", "branch", ":", "str", "=", "None", ",", "commit", ":", "str", "=", "None", ",", "clone_options", ":", "List", "[", "str", "]", "=", "None"...
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_fun...
[ "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...
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...
[ "def", "untar_to_directory", "(", "tarfile", ":", "str", ",", "directory", ":", "str", ",", "verbose", ":", "bool", "=", "False", ",", "gzipped", ":", "bool", "=", "False", ",", "skip_if_dir_exists", ":", "bool", "=", "True", ",", "run_func", ":", "Calla...
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 directo...
[ "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(...
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(...
[ "def", "make_copy_paste_env", "(", "env", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "str", ":", "windows", "=", "platform", ".", "system", "(", ")", "==", "\"Windows\"", "cmd", "=", "\"set\"", "if", "windows", "else", "\"export\"", "return", ...
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 ...
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 ...
[ "def", "run", "(", "args", ":", "List", "[", "str", "]", ",", "env", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "capture_stdout", ":", "bool", "=", "False", ",", "echo_stdout", ":", "bool", "=", "True", ",", "capture_stderr", ":", ...
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 ``Non...
[ "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...
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...
[ "def", "fetch", "(", "args", ":", "List", "[", "str", "]", ",", "env", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "encoding", ":", "str", "=", "sys", ".", "getdefaultencoding", "(", ")", ")", "->", "str", ":", "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.stdo...
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.stdo...
[ "def", "dump_connection_info", "(", "engine", ":", "Engine", ",", "fileobj", ":", "TextIO", "=", "sys", ".", "stdout", ")", "->", "None", ":", "meta", "=", "MetaData", "(", "bind", "=", "engine", ")", "writeline_nl", "(", "fileobj", ",", "sql_comment", "...
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