repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
sequencelengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
sequencelengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/remove_duplicate_files.py
deduplicate
def deduplicate(directories: List[str], recursive: bool, dummy_run: bool) -> None: """ De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subdirectories (recursively)? dummy_run: say what it'll do, but don't do it """ # ------------------------------------------------------------------------- # Catalogue files by their size # ------------------------------------------------------------------------- files_by_size = {} # type: Dict[int, List[str]] # maps size to list of filenames # noqa num_considered = 0 for filename in gen_filenames(directories, recursive=recursive): if not os.path.isfile(filename): continue size = os.stat(filename)[stat.ST_SIZE] a = files_by_size.setdefault(size, []) a.append(filename) num_considered += 1 log.debug("files_by_size =\n{}", pformat(files_by_size)) # ------------------------------------------------------------------------- # By size, look for duplicates using a hash of the first part only # ------------------------------------------------------------------------- log.info("Finding potential duplicates...") potential_duplicate_sets = [] potential_count = 0 sizes = list(files_by_size.keys()) sizes.sort() for k in sizes: files_of_this_size = files_by_size[k] out_files = [] # type: List[str] # ... list of all files having >1 file per hash, for this size hashes = {} # type: Dict[str, Union[bool, str]] # ... key is a hash; value is either True or a filename if len(files_of_this_size) == 1: continue log.info("Testing {} files of size {}...", len(files_of_this_size), k) for filename in files_of_this_size: if not os.path.isfile(filename): continue log.debug("Quick-scanning file: {}", filename) with open(filename, 'rb') as fd: hasher = md5() hasher.update(fd.read(INITIAL_HASH_SIZE)) hash_value = hasher.digest() if hash_value in hashes: # We have discovered the SECOND OR SUBSEQUENT hash match. first_file_or_true = hashes[hash_value] if first_file_or_true is not True: # We have discovered the SECOND file; # first_file_or_true contains the name of the FIRST. out_files.append(first_file_or_true) hashes[hash_value] = True out_files.append(filename) else: # We have discovered the FIRST file with this hash. hashes[hash_value] = filename if out_files: potential_duplicate_sets.append(out_files) potential_count = potential_count + len(out_files) del files_by_size log.info("Found {} sets of potential duplicates, based on hashing the " "first {} bytes of each...", potential_count, INITIAL_HASH_SIZE) log.debug("potential_duplicate_sets =\n{}", pformat(potential_duplicate_sets)) # ------------------------------------------------------------------------- # Within each set, check for duplicates using a hash of the entire file # ------------------------------------------------------------------------- log.info("Scanning for real duplicates...") num_scanned = 0 num_to_scan = sum(len(one_set) for one_set in potential_duplicate_sets) duplicate_sets = [] # type: List[List[str]] for one_set in potential_duplicate_sets: out_files = [] # type: List[str] hashes = {} for filename in one_set: num_scanned += 1 log.info("Scanning file [{}/{}]: {}", num_scanned, num_to_scan, filename) with open(filename, 'rb') as fd: hasher = md5() while True: r = fd.read(MAIN_READ_CHUNK_SIZE) if len(r) == 0: break hasher.update(r) hash_value = hasher.digest() if hash_value in hashes: if not out_files: out_files.append(hashes[hash_value]) out_files.append(filename) else: hashes[hash_value] = filename if len(out_files): duplicate_sets.append(out_files) log.debug("duplicate_sets = \n{}", pformat(duplicate_sets)) num_originals = 0 num_deleted = 0 for d in duplicate_sets: print("Original is: {}".format(d[0])) num_originals += 1 for f in d[1:]: if dummy_run: print("Would delete: {}".format(f)) else: print("Deleting: {}".format(f)) os.remove(f) num_deleted += 1 print() num_unique = num_considered - (num_originals + num_deleted) print( "{action} {d} duplicates, leaving {o} originals (and {u} unique files " "not touched; {c} files considered in total)".format( action="Would delete" if dummy_run else "Deleted", d=num_deleted, o=num_originals, u=num_unique, c=num_considered ) )
python
def deduplicate(directories: List[str], recursive: bool, dummy_run: bool) -> None: """ De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subdirectories (recursively)? dummy_run: say what it'll do, but don't do it """ # ------------------------------------------------------------------------- # Catalogue files by their size # ------------------------------------------------------------------------- files_by_size = {} # type: Dict[int, List[str]] # maps size to list of filenames # noqa num_considered = 0 for filename in gen_filenames(directories, recursive=recursive): if not os.path.isfile(filename): continue size = os.stat(filename)[stat.ST_SIZE] a = files_by_size.setdefault(size, []) a.append(filename) num_considered += 1 log.debug("files_by_size =\n{}", pformat(files_by_size)) # ------------------------------------------------------------------------- # By size, look for duplicates using a hash of the first part only # ------------------------------------------------------------------------- log.info("Finding potential duplicates...") potential_duplicate_sets = [] potential_count = 0 sizes = list(files_by_size.keys()) sizes.sort() for k in sizes: files_of_this_size = files_by_size[k] out_files = [] # type: List[str] # ... list of all files having >1 file per hash, for this size hashes = {} # type: Dict[str, Union[bool, str]] # ... key is a hash; value is either True or a filename if len(files_of_this_size) == 1: continue log.info("Testing {} files of size {}...", len(files_of_this_size), k) for filename in files_of_this_size: if not os.path.isfile(filename): continue log.debug("Quick-scanning file: {}", filename) with open(filename, 'rb') as fd: hasher = md5() hasher.update(fd.read(INITIAL_HASH_SIZE)) hash_value = hasher.digest() if hash_value in hashes: # We have discovered the SECOND OR SUBSEQUENT hash match. first_file_or_true = hashes[hash_value] if first_file_or_true is not True: # We have discovered the SECOND file; # first_file_or_true contains the name of the FIRST. out_files.append(first_file_or_true) hashes[hash_value] = True out_files.append(filename) else: # We have discovered the FIRST file with this hash. hashes[hash_value] = filename if out_files: potential_duplicate_sets.append(out_files) potential_count = potential_count + len(out_files) del files_by_size log.info("Found {} sets of potential duplicates, based on hashing the " "first {} bytes of each...", potential_count, INITIAL_HASH_SIZE) log.debug("potential_duplicate_sets =\n{}", pformat(potential_duplicate_sets)) # ------------------------------------------------------------------------- # Within each set, check for duplicates using a hash of the entire file # ------------------------------------------------------------------------- log.info("Scanning for real duplicates...") num_scanned = 0 num_to_scan = sum(len(one_set) for one_set in potential_duplicate_sets) duplicate_sets = [] # type: List[List[str]] for one_set in potential_duplicate_sets: out_files = [] # type: List[str] hashes = {} for filename in one_set: num_scanned += 1 log.info("Scanning file [{}/{}]: {}", num_scanned, num_to_scan, filename) with open(filename, 'rb') as fd: hasher = md5() while True: r = fd.read(MAIN_READ_CHUNK_SIZE) if len(r) == 0: break hasher.update(r) hash_value = hasher.digest() if hash_value in hashes: if not out_files: out_files.append(hashes[hash_value]) out_files.append(filename) else: hashes[hash_value] = filename if len(out_files): duplicate_sets.append(out_files) log.debug("duplicate_sets = \n{}", pformat(duplicate_sets)) num_originals = 0 num_deleted = 0 for d in duplicate_sets: print("Original is: {}".format(d[0])) num_originals += 1 for f in d[1:]: if dummy_run: print("Would delete: {}".format(f)) else: print("Deleting: {}".format(f)) os.remove(f) num_deleted += 1 print() num_unique = num_considered - (num_originals + num_deleted) print( "{action} {d} duplicates, leaving {o} originals (and {u} unique files " "not touched; {c} files considered in total)".format( action="Would delete" if dummy_run else "Deleted", d=num_deleted, o=num_originals, u=num_unique, c=num_considered ) )
[ "def", "deduplicate", "(", "directories", ":", "List", "[", "str", "]", ",", "recursive", ":", "bool", ",", "dummy_run", ":", "bool", ")", "->", "None", ":", "# -------------------------------------------------------------------------", "# Catalogue files by their size", "# -------------------------------------------------------------------------", "files_by_size", "=", "{", "}", "# type: Dict[int, List[str]] # maps size to list of filenames # noqa", "num_considered", "=", "0", "for", "filename", "in", "gen_filenames", "(", "directories", ",", "recursive", "=", "recursive", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "continue", "size", "=", "os", ".", "stat", "(", "filename", ")", "[", "stat", ".", "ST_SIZE", "]", "a", "=", "files_by_size", ".", "setdefault", "(", "size", ",", "[", "]", ")", "a", ".", "append", "(", "filename", ")", "num_considered", "+=", "1", "log", ".", "debug", "(", "\"files_by_size =\\n{}\"", ",", "pformat", "(", "files_by_size", ")", ")", "# -------------------------------------------------------------------------", "# By size, look for duplicates using a hash of the first part only", "# -------------------------------------------------------------------------", "log", ".", "info", "(", "\"Finding potential duplicates...\"", ")", "potential_duplicate_sets", "=", "[", "]", "potential_count", "=", "0", "sizes", "=", "list", "(", "files_by_size", ".", "keys", "(", ")", ")", "sizes", ".", "sort", "(", ")", "for", "k", "in", "sizes", ":", "files_of_this_size", "=", "files_by_size", "[", "k", "]", "out_files", "=", "[", "]", "# type: List[str]", "# ... list of all files having >1 file per hash, for this size", "hashes", "=", "{", "}", "# type: Dict[str, Union[bool, str]]", "# ... key is a hash; value is either True or a filename", "if", "len", "(", "files_of_this_size", ")", "==", "1", ":", "continue", "log", ".", "info", "(", "\"Testing {} files of size {}...\"", ",", "len", "(", "files_of_this_size", ")", ",", "k", ")", "for", "filename", "in", "files_of_this_size", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "continue", "log", ".", "debug", "(", "\"Quick-scanning file: {}\"", ",", "filename", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fd", ":", "hasher", "=", "md5", "(", ")", "hasher", ".", "update", "(", "fd", ".", "read", "(", "INITIAL_HASH_SIZE", ")", ")", "hash_value", "=", "hasher", ".", "digest", "(", ")", "if", "hash_value", "in", "hashes", ":", "# We have discovered the SECOND OR SUBSEQUENT hash match.", "first_file_or_true", "=", "hashes", "[", "hash_value", "]", "if", "first_file_or_true", "is", "not", "True", ":", "# We have discovered the SECOND file;", "# first_file_or_true contains the name of the FIRST.", "out_files", ".", "append", "(", "first_file_or_true", ")", "hashes", "[", "hash_value", "]", "=", "True", "out_files", ".", "append", "(", "filename", ")", "else", ":", "# We have discovered the FIRST file with this hash.", "hashes", "[", "hash_value", "]", "=", "filename", "if", "out_files", ":", "potential_duplicate_sets", ".", "append", "(", "out_files", ")", "potential_count", "=", "potential_count", "+", "len", "(", "out_files", ")", "del", "files_by_size", "log", ".", "info", "(", "\"Found {} sets of potential duplicates, based on hashing the \"", "\"first {} bytes of each...\"", ",", "potential_count", ",", "INITIAL_HASH_SIZE", ")", "log", ".", "debug", "(", "\"potential_duplicate_sets =\\n{}\"", ",", "pformat", "(", "potential_duplicate_sets", ")", ")", "# -------------------------------------------------------------------------", "# Within each set, check for duplicates using a hash of the entire file", "# -------------------------------------------------------------------------", "log", ".", "info", "(", "\"Scanning for real duplicates...\"", ")", "num_scanned", "=", "0", "num_to_scan", "=", "sum", "(", "len", "(", "one_set", ")", "for", "one_set", "in", "potential_duplicate_sets", ")", "duplicate_sets", "=", "[", "]", "# type: List[List[str]]", "for", "one_set", "in", "potential_duplicate_sets", ":", "out_files", "=", "[", "]", "# type: List[str]", "hashes", "=", "{", "}", "for", "filename", "in", "one_set", ":", "num_scanned", "+=", "1", "log", ".", "info", "(", "\"Scanning file [{}/{}]: {}\"", ",", "num_scanned", ",", "num_to_scan", ",", "filename", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fd", ":", "hasher", "=", "md5", "(", ")", "while", "True", ":", "r", "=", "fd", ".", "read", "(", "MAIN_READ_CHUNK_SIZE", ")", "if", "len", "(", "r", ")", "==", "0", ":", "break", "hasher", ".", "update", "(", "r", ")", "hash_value", "=", "hasher", ".", "digest", "(", ")", "if", "hash_value", "in", "hashes", ":", "if", "not", "out_files", ":", "out_files", ".", "append", "(", "hashes", "[", "hash_value", "]", ")", "out_files", ".", "append", "(", "filename", ")", "else", ":", "hashes", "[", "hash_value", "]", "=", "filename", "if", "len", "(", "out_files", ")", ":", "duplicate_sets", ".", "append", "(", "out_files", ")", "log", ".", "debug", "(", "\"duplicate_sets = \\n{}\"", ",", "pformat", "(", "duplicate_sets", ")", ")", "num_originals", "=", "0", "num_deleted", "=", "0", "for", "d", "in", "duplicate_sets", ":", "print", "(", "\"Original is: {}\"", ".", "format", "(", "d", "[", "0", "]", ")", ")", "num_originals", "+=", "1", "for", "f", "in", "d", "[", "1", ":", "]", ":", "if", "dummy_run", ":", "print", "(", "\"Would delete: {}\"", ".", "format", "(", "f", ")", ")", "else", ":", "print", "(", "\"Deleting: {}\"", ".", "format", "(", "f", ")", ")", "os", ".", "remove", "(", "f", ")", "num_deleted", "+=", "1", "print", "(", ")", "num_unique", "=", "num_considered", "-", "(", "num_originals", "+", "num_deleted", ")", "print", "(", "\"{action} {d} duplicates, leaving {o} originals (and {u} unique files \"", "\"not touched; {c} files considered in total)\"", ".", "format", "(", "action", "=", "\"Would delete\"", "if", "dummy_run", "else", "\"Deleted\"", ",", "d", "=", "num_deleted", ",", "o", "=", "num_originals", ",", "u", "=", "num_unique", ",", "c", "=", "num_considered", ")", ")" ]
De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subdirectories (recursively)? dummy_run: say what it'll do, but don't do it
[ "De", "-", "duplicate", "files", "within", "one", "or", "more", "directories", ".", "Remove", "files", "that", "are", "identical", "to", "ones", "already", "considered", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/remove_duplicate_files.py#L53-L186
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/remove_duplicate_files.py
main
def main() -> None: """ Command-line processor. See ``--help`` for details. """ parser = ArgumentParser( description="Remove duplicate files" ) parser.add_argument( "directory", nargs="+", help="Files and/or directories to check and remove duplicates from." ) parser.add_argument( "--recursive", action="store_true", help="Recurse through any directories found" ) parser.add_argument( "--dummy_run", action="store_true", help="Dummy run only; don't actually delete anything" ) parser.add_argument( "--run_repeatedly", type=int, help="Run the tool repeatedly with a pause of <run_repeatedly> " "seconds between runs. (For this to work well," "you should specify one or more DIRECTORIES in " "the 'filename' arguments, not files, and you will need the " "--recursive option.)" ) parser.add_argument( "--verbose", action="store_true", help="Verbose output" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO) while True: deduplicate(args.directory, recursive=args.recursive, dummy_run=args.dummy_run) if args.run_repeatedly is None: break log.info("Sleeping for {} s...", args.run_repeatedly) sleep(args.run_repeatedly)
python
def main() -> None: """ Command-line processor. See ``--help`` for details. """ parser = ArgumentParser( description="Remove duplicate files" ) parser.add_argument( "directory", nargs="+", help="Files and/or directories to check and remove duplicates from." ) parser.add_argument( "--recursive", action="store_true", help="Recurse through any directories found" ) parser.add_argument( "--dummy_run", action="store_true", help="Dummy run only; don't actually delete anything" ) parser.add_argument( "--run_repeatedly", type=int, help="Run the tool repeatedly with a pause of <run_repeatedly> " "seconds between runs. (For this to work well," "you should specify one or more DIRECTORIES in " "the 'filename' arguments, not files, and you will need the " "--recursive option.)" ) parser.add_argument( "--verbose", action="store_true", help="Verbose output" ) args = parser.parse_args() main_only_quicksetup_rootlogger( level=logging.DEBUG if args.verbose else logging.INFO) while True: deduplicate(args.directory, recursive=args.recursive, dummy_run=args.dummy_run) if args.run_repeatedly is None: break log.info("Sleeping for {} s...", args.run_repeatedly) sleep(args.run_repeatedly)
[ "def", "main", "(", ")", "->", "None", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "\"Remove duplicate files\"", ")", "parser", ".", "add_argument", "(", "\"directory\"", ",", "nargs", "=", "\"+\"", ",", "help", "=", "\"Files and/or directories to check and remove duplicates from.\"", ")", "parser", ".", "add_argument", "(", "\"--recursive\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Recurse through any directories found\"", ")", "parser", ".", "add_argument", "(", "\"--dummy_run\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Dummy run only; don't actually delete anything\"", ")", "parser", ".", "add_argument", "(", "\"--run_repeatedly\"", ",", "type", "=", "int", ",", "help", "=", "\"Run the tool repeatedly with a pause of <run_repeatedly> \"", "\"seconds between runs. (For this to work well,\"", "\"you should specify one or more DIRECTORIES in \"", "\"the 'filename' arguments, not files, and you will need the \"", "\"--recursive option.)\"", ")", "parser", ".", "add_argument", "(", "\"--verbose\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Verbose output\"", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "main_only_quicksetup_rootlogger", "(", "level", "=", "logging", ".", "DEBUG", "if", "args", ".", "verbose", "else", "logging", ".", "INFO", ")", "while", "True", ":", "deduplicate", "(", "args", ".", "directory", ",", "recursive", "=", "args", ".", "recursive", ",", "dummy_run", "=", "args", ".", "dummy_run", ")", "if", "args", ".", "run_repeatedly", "is", "None", ":", "break", "log", ".", "info", "(", "\"Sleeping for {} s...\"", ",", "args", ".", "run_repeatedly", ")", "sleep", "(", "args", ".", "run_repeatedly", ")" ]
Command-line processor. See ``--help`` for details.
[ "Command", "-", "line", "processor", ".", "See", "--", "help", "for", "details", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/remove_duplicate_files.py#L189-L231
RudolfCardinal/pythonlib
cardinal_pythonlib/django/fields/helpers.py
valid_choice
def valid_choice(strvalue: str, choices: Iterable[Tuple[str, str]]) -> bool: """ Checks that value is one of the valid option in choices, where choices is a list/tuple of 2-tuples (option, description). Note that parameters sent by URLconf are always strings (https://docs.djangoproject.com/en/1.8/topics/http/urls/) but Python is happy with a string-to-integer-PK lookup, e.g. .. code-block:: python Study.objects.get(pk=1) Study.objects.get(pk="1") # also works Choices can be non-string, though, so we compare against a string version of the choice. """ return strvalue in [str(x[0]) for x in choices]
python
def valid_choice(strvalue: str, choices: Iterable[Tuple[str, str]]) -> bool: """ Checks that value is one of the valid option in choices, where choices is a list/tuple of 2-tuples (option, description). Note that parameters sent by URLconf are always strings (https://docs.djangoproject.com/en/1.8/topics/http/urls/) but Python is happy with a string-to-integer-PK lookup, e.g. .. code-block:: python Study.objects.get(pk=1) Study.objects.get(pk="1") # also works Choices can be non-string, though, so we compare against a string version of the choice. """ return strvalue in [str(x[0]) for x in choices]
[ "def", "valid_choice", "(", "strvalue", ":", "str", ",", "choices", ":", "Iterable", "[", "Tuple", "[", "str", ",", "str", "]", "]", ")", "->", "bool", ":", "return", "strvalue", "in", "[", "str", "(", "x", "[", "0", "]", ")", "for", "x", "in", "choices", "]" ]
Checks that value is one of the valid option in choices, where choices is a list/tuple of 2-tuples (option, description). Note that parameters sent by URLconf are always strings (https://docs.djangoproject.com/en/1.8/topics/http/urls/) but Python is happy with a string-to-integer-PK lookup, e.g. .. code-block:: python Study.objects.get(pk=1) Study.objects.get(pk="1") # also works Choices can be non-string, though, so we compare against a string version of the choice.
[ "Checks", "that", "value", "is", "one", "of", "the", "valid", "option", "in", "choices", "where", "choices", "is", "a", "list", "/", "tuple", "of", "2", "-", "tuples", "(", "option", "description", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/helpers.py#L36-L53
RudolfCardinal/pythonlib
cardinal_pythonlib/django/fields/helpers.py
choice_explanation
def choice_explanation(value: str, choices: Iterable[Tuple[str, str]]) -> str: """ Returns the explanation associated with a Django choice tuple-list. """ for k, v in choices: if k == value: return v return ''
python
def choice_explanation(value: str, choices: Iterable[Tuple[str, str]]) -> str: """ Returns the explanation associated with a Django choice tuple-list. """ for k, v in choices: if k == value: return v return ''
[ "def", "choice_explanation", "(", "value", ":", "str", ",", "choices", ":", "Iterable", "[", "Tuple", "[", "str", ",", "str", "]", "]", ")", "->", "str", ":", "for", "k", ",", "v", "in", "choices", ":", "if", "k", "==", "value", ":", "return", "v", "return", "''" ]
Returns the explanation associated with a Django choice tuple-list.
[ "Returns", "the", "explanation", "associated", "with", "a", "Django", "choice", "tuple", "-", "list", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/helpers.py#L56-L63
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
tee
def tee(infile: IO, *files: IO) -> Thread: r""" Print the file-like object ``infile`` to the file-like object(s) ``files`` in a separate thread. Starts and returns that thread. The type (text, binary) must MATCH across all files. From https://stackoverflow.com/questions/4984428/python-subprocess-get-childrens-output-to-file-and-terminal A note on text versus binary IO: TEXT files include: - files opened in text mode (``"r"``, ``"rt"``, ``"w"``, ``"wt"``) - ``sys.stdin``, ``sys.stdout`` - ``io.StringIO()``; see https://docs.python.org/3/glossary.html#term-text-file BINARY files include: - files opened in binary mode (``"rb"``, ``"wb"``, ``"rb+"``...) - ``sys.stdin.buffer``, ``sys.stdout.buffer`` - ``io.BytesIO()`` - ``gzip.GzipFile()``; see https://docs.python.org/3/glossary.html#term-binary-file .. code-block:: bash $ python3 # don't get confused and use Python 2 by mistake! .. code-block:: python t = open("/tmp/text.txt", "r+t") # text mode is default b = open("/tmp/bin.bin", "r+b") t.write("hello\n") # OK # b.write("hello\n") # raises TypeError # t.write(b"world\n") # raises TypeError b.write(b"world\n") # OK t.flush() b.flush() t.seek(0) b.seek(0) x = t.readline() # "hello\n" y = b.readline() # b"world\n" """ # noqa def fanout(_infile: IO, *_files: IO): for line in iter(_infile.readline, ''): for f in _files: f.write(line) infile.close() t = Thread(target=fanout, args=(infile,) + files) t.daemon = True t.start() return t
python
def tee(infile: IO, *files: IO) -> Thread: r""" Print the file-like object ``infile`` to the file-like object(s) ``files`` in a separate thread. Starts and returns that thread. The type (text, binary) must MATCH across all files. From https://stackoverflow.com/questions/4984428/python-subprocess-get-childrens-output-to-file-and-terminal A note on text versus binary IO: TEXT files include: - files opened in text mode (``"r"``, ``"rt"``, ``"w"``, ``"wt"``) - ``sys.stdin``, ``sys.stdout`` - ``io.StringIO()``; see https://docs.python.org/3/glossary.html#term-text-file BINARY files include: - files opened in binary mode (``"rb"``, ``"wb"``, ``"rb+"``...) - ``sys.stdin.buffer``, ``sys.stdout.buffer`` - ``io.BytesIO()`` - ``gzip.GzipFile()``; see https://docs.python.org/3/glossary.html#term-binary-file .. code-block:: bash $ python3 # don't get confused and use Python 2 by mistake! .. code-block:: python t = open("/tmp/text.txt", "r+t") # text mode is default b = open("/tmp/bin.bin", "r+b") t.write("hello\n") # OK # b.write("hello\n") # raises TypeError # t.write(b"world\n") # raises TypeError b.write(b"world\n") # OK t.flush() b.flush() t.seek(0) b.seek(0) x = t.readline() # "hello\n" y = b.readline() # b"world\n" """ # noqa def fanout(_infile: IO, *_files: IO): for line in iter(_infile.readline, ''): for f in _files: f.write(line) infile.close() t = Thread(target=fanout, args=(infile,) + files) t.daemon = True t.start() return t
[ "def", "tee", "(", "infile", ":", "IO", ",", "*", "files", ":", "IO", ")", "->", "Thread", ":", "# noqa", "def", "fanout", "(", "_infile", ":", "IO", ",", "*", "_files", ":", "IO", ")", ":", "for", "line", "in", "iter", "(", "_infile", ".", "readline", ",", "''", ")", ":", "for", "f", "in", "_files", ":", "f", ".", "write", "(", "line", ")", "infile", ".", "close", "(", ")", "t", "=", "Thread", "(", "target", "=", "fanout", ",", "args", "=", "(", "infile", ",", ")", "+", "files", ")", "t", ".", "daemon", "=", "True", "t", ".", "start", "(", ")", "return", "t" ]
r""" Print the file-like object ``infile`` to the file-like object(s) ``files`` in a separate thread. Starts and returns that thread. The type (text, binary) must MATCH across all files. From https://stackoverflow.com/questions/4984428/python-subprocess-get-childrens-output-to-file-and-terminal A note on text versus binary IO: TEXT files include: - files opened in text mode (``"r"``, ``"rt"``, ``"w"``, ``"wt"``) - ``sys.stdin``, ``sys.stdout`` - ``io.StringIO()``; see https://docs.python.org/3/glossary.html#term-text-file BINARY files include: - files opened in binary mode (``"rb"``, ``"wb"``, ``"rb+"``...) - ``sys.stdin.buffer``, ``sys.stdout.buffer`` - ``io.BytesIO()`` - ``gzip.GzipFile()``; see https://docs.python.org/3/glossary.html#term-binary-file .. code-block:: bash $ python3 # don't get confused and use Python 2 by mistake! .. code-block:: python t = open("/tmp/text.txt", "r+t") # text mode is default b = open("/tmp/bin.bin", "r+b") t.write("hello\n") # OK # b.write("hello\n") # raises TypeError # t.write(b"world\n") # raises TypeError b.write(b"world\n") # OK t.flush() b.flush() t.seek(0) b.seek(0) x = t.readline() # "hello\n" y = b.readline() # b"world\n"
[ "r", "Print", "the", "file", "-", "like", "object", "infile", "to", "the", "file", "-", "like", "object", "(", "s", ")", "files", "in", "a", "separate", "thread", ".", "Starts", "and", "returns", "that", "thread", ".", "The", "type", "(", "text", "binary", ")", "must", "MATCH", "across", "all", "files", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L82-L145
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
teed_call
def teed_call(cmd_args, stdout_targets: List[TextIO] = None, stderr_targets: List[TextIO] = None, encoding: str = sys.getdefaultencoding(), **kwargs): """ Runs a command and captures its output via :func:`tee` to one or more destinations. The output is always captured (otherwise we would lose control of the output and ability to ``tee`` it); if no destination is specified, we add a null handler. We insist on ``TextIO`` output files to match ``sys.stdout`` (etc.). A variation on: https://stackoverflow.com/questions/4984428/python-subprocess-get-childrens-output-to-file-and-terminal Args: cmd_args: arguments for the command to run stdout_targets: file-like objects to write ``stdout`` to stderr_targets: file-like objects to write ``stderr`` to encoding: encoding to apply to ``stdout`` and ``stderr`` kwargs: additional arguments for :class:`subprocess.Popen` """ # noqa # Make a copy so we can append without damaging the original: stdout_targets = stdout_targets.copy() if stdout_targets else [] # type: List[TextIO] # noqa stderr_targets = stderr_targets.copy() if stderr_targets else [] # type: List[TextIO] # noqa p = Popen(cmd_args, stdout=PIPE, stderr=PIPE, **kwargs) threads = [] # type: List[Thread] with open(os.devnull, "w") as null: # type: TextIO if not stdout_targets: stdout_targets.append(null) if not stderr_targets: stderr_targets.append(null) # Now, by default, because we're not using "universal_newlines", both # p.stdout and p.stderr are binary. stdout_txt = TextIOWrapper(p.stdout, encoding=encoding) # type: TextIO # noqa stderr_txt = TextIOWrapper(p.stderr, encoding=encoding) # type: TextIO # noqa threads.append(tee(stdout_txt, *stdout_targets)) threads.append(tee(stderr_txt, *stderr_targets)) for t in threads: t.join() # wait for IO completion return p.wait()
python
def teed_call(cmd_args, stdout_targets: List[TextIO] = None, stderr_targets: List[TextIO] = None, encoding: str = sys.getdefaultencoding(), **kwargs): """ Runs a command and captures its output via :func:`tee` to one or more destinations. The output is always captured (otherwise we would lose control of the output and ability to ``tee`` it); if no destination is specified, we add a null handler. We insist on ``TextIO`` output files to match ``sys.stdout`` (etc.). A variation on: https://stackoverflow.com/questions/4984428/python-subprocess-get-childrens-output-to-file-and-terminal Args: cmd_args: arguments for the command to run stdout_targets: file-like objects to write ``stdout`` to stderr_targets: file-like objects to write ``stderr`` to encoding: encoding to apply to ``stdout`` and ``stderr`` kwargs: additional arguments for :class:`subprocess.Popen` """ # noqa # Make a copy so we can append without damaging the original: stdout_targets = stdout_targets.copy() if stdout_targets else [] # type: List[TextIO] # noqa stderr_targets = stderr_targets.copy() if stderr_targets else [] # type: List[TextIO] # noqa p = Popen(cmd_args, stdout=PIPE, stderr=PIPE, **kwargs) threads = [] # type: List[Thread] with open(os.devnull, "w") as null: # type: TextIO if not stdout_targets: stdout_targets.append(null) if not stderr_targets: stderr_targets.append(null) # Now, by default, because we're not using "universal_newlines", both # p.stdout and p.stderr are binary. stdout_txt = TextIOWrapper(p.stdout, encoding=encoding) # type: TextIO # noqa stderr_txt = TextIOWrapper(p.stderr, encoding=encoding) # type: TextIO # noqa threads.append(tee(stdout_txt, *stdout_targets)) threads.append(tee(stderr_txt, *stderr_targets)) for t in threads: t.join() # wait for IO completion return p.wait()
[ "def", "teed_call", "(", "cmd_args", ",", "stdout_targets", ":", "List", "[", "TextIO", "]", "=", "None", ",", "stderr_targets", ":", "List", "[", "TextIO", "]", "=", "None", ",", "encoding", ":", "str", "=", "sys", ".", "getdefaultencoding", "(", ")", ",", "*", "*", "kwargs", ")", ":", "# noqa", "# Make a copy so we can append without damaging the original:", "stdout_targets", "=", "stdout_targets", ".", "copy", "(", ")", "if", "stdout_targets", "else", "[", "]", "# type: List[TextIO] # noqa", "stderr_targets", "=", "stderr_targets", ".", "copy", "(", ")", "if", "stderr_targets", "else", "[", "]", "# type: List[TextIO] # noqa", "p", "=", "Popen", "(", "cmd_args", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "*", "*", "kwargs", ")", "threads", "=", "[", "]", "# type: List[Thread]", "with", "open", "(", "os", ".", "devnull", ",", "\"w\"", ")", "as", "null", ":", "# type: TextIO", "if", "not", "stdout_targets", ":", "stdout_targets", ".", "append", "(", "null", ")", "if", "not", "stderr_targets", ":", "stderr_targets", ".", "append", "(", "null", ")", "# Now, by default, because we're not using \"universal_newlines\", both", "# p.stdout and p.stderr are binary.", "stdout_txt", "=", "TextIOWrapper", "(", "p", ".", "stdout", ",", "encoding", "=", "encoding", ")", "# type: TextIO # noqa", "stderr_txt", "=", "TextIOWrapper", "(", "p", ".", "stderr", ",", "encoding", "=", "encoding", ")", "# type: TextIO # noqa", "threads", ".", "append", "(", "tee", "(", "stdout_txt", ",", "*", "stdout_targets", ")", ")", "threads", ".", "append", "(", "tee", "(", "stderr_txt", ",", "*", "stderr_targets", ")", ")", "for", "t", "in", "threads", ":", "t", ".", "join", "(", ")", "# wait for IO completion", "return", "p", ".", "wait", "(", ")" ]
Runs a command and captures its output via :func:`tee` to one or more destinations. The output is always captured (otherwise we would lose control of the output and ability to ``tee`` it); if no destination is specified, we add a null handler. We insist on ``TextIO`` output files to match ``sys.stdout`` (etc.). A variation on: https://stackoverflow.com/questions/4984428/python-subprocess-get-childrens-output-to-file-and-terminal Args: cmd_args: arguments for the command to run stdout_targets: file-like objects to write ``stdout`` to stderr_targets: file-like objects to write ``stderr`` to encoding: encoding to apply to ``stdout`` and ``stderr`` kwargs: additional arguments for :class:`subprocess.Popen`
[ "Runs", "a", "command", "and", "captures", "its", "output", "via", ":", "func", ":", "tee", "to", "one", "or", "more", "destinations", ".", "The", "output", "is", "always", "captured", "(", "otherwise", "we", "would", "lose", "control", "of", "the", "output", "and", "ability", "to", "tee", "it", ")", ";", "if", "no", "destination", "is", "specified", "we", "add", "a", "null", "handler", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L148-L190
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
tee_log
def tee_log(tee_file: TextIO, loglevel: int) -> None: """ Context manager to add a file output stream to our logging system. Args: tee_file: file-like object to write to loglevel: log level (e.g. ``logging.DEBUG``) to use for this stream """ handler = get_monochrome_handler(stream=tee_file) handler.setLevel(loglevel) rootlogger = logging.getLogger() rootlogger.addHandler(handler) # Tee the main stdout/stderr as required. with TeeContextManager(tee_file, capture_stdout=True): with TeeContextManager(tee_file, capture_stderr=True): try: yield except Exception: # We catch this so that the exception also goes to # the log. exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) log.critical("\n" + "".join(lines)) raise
python
def tee_log(tee_file: TextIO, loglevel: int) -> None: """ Context manager to add a file output stream to our logging system. Args: tee_file: file-like object to write to loglevel: log level (e.g. ``logging.DEBUG``) to use for this stream """ handler = get_monochrome_handler(stream=tee_file) handler.setLevel(loglevel) rootlogger = logging.getLogger() rootlogger.addHandler(handler) # Tee the main stdout/stderr as required. with TeeContextManager(tee_file, capture_stdout=True): with TeeContextManager(tee_file, capture_stderr=True): try: yield except Exception: # We catch this so that the exception also goes to # the log. exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) log.critical("\n" + "".join(lines)) raise
[ "def", "tee_log", "(", "tee_file", ":", "TextIO", ",", "loglevel", ":", "int", ")", "->", "None", ":", "handler", "=", "get_monochrome_handler", "(", "stream", "=", "tee_file", ")", "handler", ".", "setLevel", "(", "loglevel", ")", "rootlogger", "=", "logging", ".", "getLogger", "(", ")", "rootlogger", ".", "addHandler", "(", "handler", ")", "# Tee the main stdout/stderr as required.", "with", "TeeContextManager", "(", "tee_file", ",", "capture_stdout", "=", "True", ")", ":", "with", "TeeContextManager", "(", "tee_file", ",", "capture_stderr", "=", "True", ")", ":", "try", ":", "yield", "except", "Exception", ":", "# We catch this so that the exception also goes to", "# the log.", "exc_type", ",", "exc_value", ",", "exc_traceback", "=", "sys", ".", "exc_info", "(", ")", "lines", "=", "traceback", ".", "format_exception", "(", "exc_type", ",", "exc_value", ",", "exc_traceback", ")", "log", ".", "critical", "(", "\"\\n\"", "+", "\"\"", ".", "join", "(", "lines", ")", ")", "raise" ]
Context manager to add a file output stream to our logging system. Args: tee_file: file-like object to write to loglevel: log level (e.g. ``logging.DEBUG``) to use for this stream
[ "Context", "manager", "to", "add", "a", "file", "output", "stream", "to", "our", "logging", "system", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L290-L315
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
TeeContextManager.write
def write(self, message: str) -> None: """ To act as a file. """ self.underlying_stream.write(message) self.file.write(message)
python
def write(self, message: str) -> None: """ To act as a file. """ self.underlying_stream.write(message) self.file.write(message)
[ "def", "write", "(", "self", ",", "message", ":", "str", ")", "->", "None", ":", "self", ".", "underlying_stream", ".", "write", "(", "message", ")", "self", ".", "file", ".", "write", "(", "message", ")" ]
To act as a file.
[ "To", "act", "as", "a", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L257-L262
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
TeeContextManager.flush
def flush(self) -> None: """ To act as a file. """ self.underlying_stream.flush() self.file.flush() os.fsync(self.file.fileno())
python
def flush(self) -> None: """ To act as a file. """ self.underlying_stream.flush() self.file.flush() os.fsync(self.file.fileno())
[ "def", "flush", "(", "self", ")", "->", "None", ":", "self", ".", "underlying_stream", ".", "flush", "(", ")", "self", ".", "file", ".", "flush", "(", ")", "os", ".", "fsync", "(", "self", ".", "file", ".", "fileno", "(", ")", ")" ]
To act as a file.
[ "To", "act", "as", "a", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L264-L270
RudolfCardinal/pythonlib
cardinal_pythonlib/tee.py
TeeContextManager.close
def close(self) -> None: """ To act as a file. """ if self.underlying_stream: if self.using_stdout: sys.stdout = self.underlying_stream else: sys.stderr = self.underlying_stream self.underlying_stream = None if self.file: # Do NOT close the file; we don't own it. self.file = None log.debug("Finished copying {} to {}", self.output_description, self.filename)
python
def close(self) -> None: """ To act as a file. """ if self.underlying_stream: if self.using_stdout: sys.stdout = self.underlying_stream else: sys.stderr = self.underlying_stream self.underlying_stream = None if self.file: # Do NOT close the file; we don't own it. self.file = None log.debug("Finished copying {} to {}", self.output_description, self.filename)
[ "def", "close", "(", "self", ")", "->", "None", ":", "if", "self", ".", "underlying_stream", ":", "if", "self", ".", "using_stdout", ":", "sys", ".", "stdout", "=", "self", ".", "underlying_stream", "else", ":", "sys", ".", "stderr", "=", "self", ".", "underlying_stream", "self", ".", "underlying_stream", "=", "None", "if", "self", ".", "file", ":", "# Do NOT close the file; we don't own it.", "self", ".", "file", "=", "None", "log", ".", "debug", "(", "\"Finished copying {} to {}\"", ",", "self", ".", "output_description", ",", "self", ".", "filename", ")" ]
To act as a file.
[ "To", "act", "as", "a", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tee.py#L272-L286
davenquinn/Attitude
attitude/error/bootstrap.py
bootstrap
def bootstrap(array): """ Provides a bootstrap resampling of an array. Provides another statistical method to estimate the variance of a dataset. For a `PCA` object in this library, it should be applied to `Orientation.array` method. """ reg_func = lambda a: N.linalg.svd(a,full_matrices=False)[2][2] beta_boots = bootstrap(array, func=reg_func) return yhat, yhat_boots
python
def bootstrap(array): """ Provides a bootstrap resampling of an array. Provides another statistical method to estimate the variance of a dataset. For a `PCA` object in this library, it should be applied to `Orientation.array` method. """ reg_func = lambda a: N.linalg.svd(a,full_matrices=False)[2][2] beta_boots = bootstrap(array, func=reg_func) return yhat, yhat_boots
[ "def", "bootstrap", "(", "array", ")", ":", "reg_func", "=", "lambda", "a", ":", "N", ".", "linalg", ".", "svd", "(", "a", ",", "full_matrices", "=", "False", ")", "[", "2", "]", "[", "2", "]", "beta_boots", "=", "bootstrap", "(", "array", ",", "func", "=", "reg_func", ")", "return", "yhat", ",", "yhat_boots" ]
Provides a bootstrap resampling of an array. Provides another statistical method to estimate the variance of a dataset. For a `PCA` object in this library, it should be applied to `Orientation.array` method.
[ "Provides", "a", "bootstrap", "resampling", "of", "an", "array", ".", "Provides", "another", "statistical", "method", "to", "estimate", "the", "variance", "of", "a", "dataset", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/bootstrap.py#L6-L16
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/literals.py
sql_string_literal
def sql_string_literal(text: str) -> str: """ Transforms text into its ANSI SQL-quoted version, e.g. (in Python ``repr()`` format): .. code-block:: none "some string" -> "'some string'" "Jack's dog" -> "'Jack''s dog'" """ # ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt # <character string literal> return SQUOTE + text.replace(SQUOTE, DOUBLE_SQUOTE) + SQUOTE
python
def sql_string_literal(text: str) -> str: """ Transforms text into its ANSI SQL-quoted version, e.g. (in Python ``repr()`` format): .. code-block:: none "some string" -> "'some string'" "Jack's dog" -> "'Jack''s dog'" """ # ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt # <character string literal> return SQUOTE + text.replace(SQUOTE, DOUBLE_SQUOTE) + SQUOTE
[ "def", "sql_string_literal", "(", "text", ":", "str", ")", "->", "str", ":", "# ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt", "# <character string literal>", "return", "SQUOTE", "+", "text", ".", "replace", "(", "SQUOTE", ",", "DOUBLE_SQUOTE", ")", "+", "SQUOTE" ]
Transforms text into its ANSI SQL-quoted version, e.g. (in Python ``repr()`` format): .. code-block:: none "some string" -> "'some string'" "Jack's dog" -> "'Jack''s dog'"
[ "Transforms", "text", "into", "its", "ANSI", "SQL", "-", "quoted", "version", "e", ".", "g", ".", "(", "in", "Python", "repr", "()", "format", ")", ":" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L42-L54
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/literals.py
sql_datetime_literal
def sql_datetime_literal(dt: DateTimeLikeType, subsecond: bool = False) -> str: """ Transforms a Python object that is of duck type ``datetime.datetime`` into an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if ``subsecond=True``, into the (non-ANSI) format ``'2000-12-31 23:59:59.123456'`` or similar. """ # ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt # <timestamp string> # ... the subsecond part is non-ANSI fmt = "'%Y-%m-%d %H:%M:%S{}'".format(".%f" if subsecond else "") return dt.strftime(fmt)
python
def sql_datetime_literal(dt: DateTimeLikeType, subsecond: bool = False) -> str: """ Transforms a Python object that is of duck type ``datetime.datetime`` into an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if ``subsecond=True``, into the (non-ANSI) format ``'2000-12-31 23:59:59.123456'`` or similar. """ # ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt # <timestamp string> # ... the subsecond part is non-ANSI fmt = "'%Y-%m-%d %H:%M:%S{}'".format(".%f" if subsecond else "") return dt.strftime(fmt)
[ "def", "sql_datetime_literal", "(", "dt", ":", "DateTimeLikeType", ",", "subsecond", ":", "bool", "=", "False", ")", "->", "str", ":", "# ANSI SQL: http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt", "# <timestamp string>", "# ... the subsecond part is non-ANSI", "fmt", "=", "\"'%Y-%m-%d %H:%M:%S{}'\"", ".", "format", "(", "\".%f\"", "if", "subsecond", "else", "\"\"", ")", "return", "dt", ".", "strftime", "(", "fmt", ")" ]
Transforms a Python object that is of duck type ``datetime.datetime`` into an ANSI SQL literal string, like ``'2000-12-31 23:59:59'``, or if ``subsecond=True``, into the (non-ANSI) format ``'2000-12-31 23:59:59.123456'`` or similar.
[ "Transforms", "a", "Python", "object", "that", "is", "of", "duck", "type", "datetime", ".", "datetime", "into", "an", "ANSI", "SQL", "literal", "string", "like", "2000", "-", "12", "-", "31", "23", ":", "59", ":", "59", "or", "if", "subsecond", "=", "True", "into", "the", "(", "non", "-", "ANSI", ")", "format", "2000", "-", "12", "-", "31", "23", ":", "59", ":", "59", ".", "123456", "or", "similar", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L70-L82
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/literals.py
sql_comment
def sql_comment(comment: str) -> str: """ Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``. """ """Using -- as a comment marker is ANSI SQL.""" if not comment: return "" return "\n".join("-- {}".format(x) for x in comment.splitlines())
python
def sql_comment(comment: str) -> str: """ Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``. """ """Using -- as a comment marker is ANSI SQL.""" if not comment: return "" return "\n".join("-- {}".format(x) for x in comment.splitlines())
[ "def", "sql_comment", "(", "comment", ":", "str", ")", "->", "str", ":", "\"\"\"Using -- as a comment marker is ANSI SQL.\"\"\"", "if", "not", "comment", ":", "return", "\"\"", "return", "\"\\n\"", ".", "join", "(", "\"-- {}\"", ".", "format", "(", "x", ")", "for", "x", "in", "comment", ".", "splitlines", "(", ")", ")" ]
Transforms a single- or multi-line string into an ANSI SQL comment, prefixed by ``--``.
[ "Transforms", "a", "single", "-", "or", "multi", "-", "line", "string", "into", "an", "ANSI", "SQL", "comment", "prefixed", "by", "--", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L85-L93
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/literals.py
sql_dequote_string
def sql_dequote_string(s: str) -> str: """ Reverses :func:`sql_quote_string`. """ if len(s) < 2 or s[0] != SQUOTE or s[-1] != SQUOTE: raise ValueError("Not an SQL string literal") s = s[1:-1] # strip off the surrounding quotes return s.replace(DOUBLE_SQUOTE, SQUOTE)
python
def sql_dequote_string(s: str) -> str: """ Reverses :func:`sql_quote_string`. """ if len(s) < 2 or s[0] != SQUOTE or s[-1] != SQUOTE: raise ValueError("Not an SQL string literal") s = s[1:-1] # strip off the surrounding quotes return s.replace(DOUBLE_SQUOTE, SQUOTE)
[ "def", "sql_dequote_string", "(", "s", ":", "str", ")", "->", "str", ":", "if", "len", "(", "s", ")", "<", "2", "or", "s", "[", "0", "]", "!=", "SQUOTE", "or", "s", "[", "-", "1", "]", "!=", "SQUOTE", ":", "raise", "ValueError", "(", "\"Not an SQL string literal\"", ")", "s", "=", "s", "[", "1", ":", "-", "1", "]", "# strip off the surrounding quotes", "return", "s", ".", "replace", "(", "DOUBLE_SQUOTE", ",", "SQUOTE", ")" ]
Reverses :func:`sql_quote_string`.
[ "Reverses", ":", "func", ":", "sql_quote_string", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L100-L107
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/literals.py
gen_items_from_sql_csv
def gen_items_from_sql_csv(s: str) -> Generator[str, None, None]: """ Splits a comma-separated list of quoted SQL values, with ``'`` as the quote character. Allows escaping of the quote character by doubling it. Returns the quotes (and escaped quotes) as part of the result. Allows newlines etc. within the string passed. """ # csv.reader will not both process the quotes and return the quotes; # we need them to distinguish e.g. NULL from 'NULL'. # log.warning('gen_items_from_sql_csv: s = {0!r}', s) if not s: return n = len(s) startpos = 0 pos = 0 in_quotes = False while pos < n: if not in_quotes: if s[pos] == COMMA: # end of chunk chunk = s[startpos:pos] # does not include s[pos] result = chunk.strip() # log.warning('yielding: {0!r}', result) yield result startpos = pos + 1 elif s[pos] == SQUOTE: # start of quote in_quotes = True else: if pos < n - 1 and s[pos] == SQUOTE and s[pos + 1] == SQUOTE: # double quote, '', is an escaped quote, not end of quote pos += 1 # skip one more than we otherwise would elif s[pos] == SQUOTE: # end of quote in_quotes = False pos += 1 # Last chunk result = s[startpos:].strip() # log.warning('yielding last: {0!r}', result) yield result
python
def gen_items_from_sql_csv(s: str) -> Generator[str, None, None]: """ Splits a comma-separated list of quoted SQL values, with ``'`` as the quote character. Allows escaping of the quote character by doubling it. Returns the quotes (and escaped quotes) as part of the result. Allows newlines etc. within the string passed. """ # csv.reader will not both process the quotes and return the quotes; # we need them to distinguish e.g. NULL from 'NULL'. # log.warning('gen_items_from_sql_csv: s = {0!r}', s) if not s: return n = len(s) startpos = 0 pos = 0 in_quotes = False while pos < n: if not in_quotes: if s[pos] == COMMA: # end of chunk chunk = s[startpos:pos] # does not include s[pos] result = chunk.strip() # log.warning('yielding: {0!r}', result) yield result startpos = pos + 1 elif s[pos] == SQUOTE: # start of quote in_quotes = True else: if pos < n - 1 and s[pos] == SQUOTE and s[pos + 1] == SQUOTE: # double quote, '', is an escaped quote, not end of quote pos += 1 # skip one more than we otherwise would elif s[pos] == SQUOTE: # end of quote in_quotes = False pos += 1 # Last chunk result = s[startpos:].strip() # log.warning('yielding last: {0!r}', result) yield result
[ "def", "gen_items_from_sql_csv", "(", "s", ":", "str", ")", "->", "Generator", "[", "str", ",", "None", ",", "None", "]", ":", "# csv.reader will not both process the quotes and return the quotes;", "# we need them to distinguish e.g. NULL from 'NULL'.", "# log.warning('gen_items_from_sql_csv: s = {0!r}', s)", "if", "not", "s", ":", "return", "n", "=", "len", "(", "s", ")", "startpos", "=", "0", "pos", "=", "0", "in_quotes", "=", "False", "while", "pos", "<", "n", ":", "if", "not", "in_quotes", ":", "if", "s", "[", "pos", "]", "==", "COMMA", ":", "# end of chunk", "chunk", "=", "s", "[", "startpos", ":", "pos", "]", "# does not include s[pos]", "result", "=", "chunk", ".", "strip", "(", ")", "# log.warning('yielding: {0!r}', result)", "yield", "result", "startpos", "=", "pos", "+", "1", "elif", "s", "[", "pos", "]", "==", "SQUOTE", ":", "# start of quote", "in_quotes", "=", "True", "else", ":", "if", "pos", "<", "n", "-", "1", "and", "s", "[", "pos", "]", "==", "SQUOTE", "and", "s", "[", "pos", "+", "1", "]", "==", "SQUOTE", ":", "# double quote, '', is an escaped quote, not end of quote", "pos", "+=", "1", "# skip one more than we otherwise would", "elif", "s", "[", "pos", "]", "==", "SQUOTE", ":", "# end of quote", "in_quotes", "=", "False", "pos", "+=", "1", "# Last chunk", "result", "=", "s", "[", "startpos", ":", "]", ".", "strip", "(", ")", "# log.warning('yielding last: {0!r}', result)", "yield", "result" ]
Splits a comma-separated list of quoted SQL values, with ``'`` as the quote character. Allows escaping of the quote character by doubling it. Returns the quotes (and escaped quotes) as part of the result. Allows newlines etc. within the string passed.
[ "Splits", "a", "comma", "-", "separated", "list", "of", "quoted", "SQL", "values", "with", "as", "the", "quote", "character", ".", "Allows", "escaping", "of", "the", "quote", "character", "by", "doubling", "it", ".", "Returns", "the", "quotes", "(", "and", "escaped", "quotes", ")", "as", "part", "of", "the", "result", ".", "Allows", "newlines", "etc", ".", "within", "the", "string", "passed", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/literals.py#L114-L153
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
get_case_insensitive_dict_key
def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]: """ Within the dictionary ``d``, find a key that matches (in case-insensitive fashion) the key ``k``, and return it (or ``None`` if there isn't one). """ for key in d.keys(): if k.lower() == key.lower(): return key return None
python
def get_case_insensitive_dict_key(d: Dict, k: str) -> Optional[str]: """ Within the dictionary ``d``, find a key that matches (in case-insensitive fashion) the key ``k``, and return it (or ``None`` if there isn't one). """ for key in d.keys(): if k.lower() == key.lower(): return key return None
[ "def", "get_case_insensitive_dict_key", "(", "d", ":", "Dict", ",", "k", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "for", "key", "in", "d", ".", "keys", "(", ")", ":", "if", "k", ".", "lower", "(", ")", "==", "key", ".", "lower", "(", ")", ":", "return", "key", "return", "None" ]
Within the dictionary ``d``, find a key that matches (in case-insensitive fashion) the key ``k``, and return it (or ``None`` if there isn't one).
[ "Within", "the", "dictionary", "d", "find", "a", "key", "that", "matches", "(", "in", "case", "-", "insensitive", "fashion", ")", "the", "key", "k", "and", "return", "it", "(", "or", "None", "if", "there", "isn", "t", "one", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L36-L44
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
merge_two_dicts
def merge_two_dicts(x: Dict, y: Dict) -> Dict: """ Given two dicts, merge them into a new dict as a shallow copy, e.g. .. code-block:: python z = merge_two_dicts(x, y) If you can guarantee Python 3.5, then a simpler syntax is: .. code-block:: python z = {**x, **y} See http://stackoverflow.com/questions/38987. """ z = x.copy() z.update(y) return z
python
def merge_two_dicts(x: Dict, y: Dict) -> Dict: """ Given two dicts, merge them into a new dict as a shallow copy, e.g. .. code-block:: python z = merge_two_dicts(x, y) If you can guarantee Python 3.5, then a simpler syntax is: .. code-block:: python z = {**x, **y} See http://stackoverflow.com/questions/38987. """ z = x.copy() z.update(y) return z
[ "def", "merge_two_dicts", "(", "x", ":", "Dict", ",", "y", ":", "Dict", ")", "->", "Dict", ":", "z", "=", "x", ".", "copy", "(", ")", "z", ".", "update", "(", "y", ")", "return", "z" ]
Given two dicts, merge them into a new dict as a shallow copy, e.g. .. code-block:: python z = merge_two_dicts(x, y) If you can guarantee Python 3.5, then a simpler syntax is: .. code-block:: python z = {**x, **y} See http://stackoverflow.com/questions/38987.
[ "Given", "two", "dicts", "merge", "them", "into", "a", "new", "dict", "as", "a", "shallow", "copy", "e", ".", "g", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L60-L78
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
rename_key
def rename_key(d: Dict[str, Any], old: str, new: str) -> None: """ Rename a key in dictionary ``d`` from ``old`` to ``new``, in place. """ d[new] = d.pop(old)
python
def rename_key(d: Dict[str, Any], old: str, new: str) -> None: """ Rename a key in dictionary ``d`` from ``old`` to ``new``, in place. """ d[new] = d.pop(old)
[ "def", "rename_key", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "old", ":", "str", ",", "new", ":", "str", ")", "->", "None", ":", "d", "[", "new", "]", "=", "d", ".", "pop", "(", "old", ")" ]
Rename a key in dictionary ``d`` from ``old`` to ``new``, in place.
[ "Rename", "a", "key", "in", "dictionary", "d", "from", "old", "to", "new", "in", "place", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L81-L85
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
rename_keys
def rename_keys(d: Dict[str, Any], mapping: Dict[str, str]) -> Dict[str, Any]: """ Returns a copy of the dictionary ``d`` with its keys renamed according to ``mapping``. Args: d: the starting dictionary mapping: a dictionary of the format ``{old_key_name: new_key_name}`` Returns: a new dictionary Keys that are not in ``mapping`` are left unchanged. The input parameters are not modified. """ result = {} # type: Dict[str, Any] for k, v in d.items(): if k in mapping: k = mapping[k] result[k] = v return result
python
def rename_keys(d: Dict[str, Any], mapping: Dict[str, str]) -> Dict[str, Any]: """ Returns a copy of the dictionary ``d`` with its keys renamed according to ``mapping``. Args: d: the starting dictionary mapping: a dictionary of the format ``{old_key_name: new_key_name}`` Returns: a new dictionary Keys that are not in ``mapping`` are left unchanged. The input parameters are not modified. """ result = {} # type: Dict[str, Any] for k, v in d.items(): if k in mapping: k = mapping[k] result[k] = v return result
[ "def", "rename_keys", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "mapping", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "result", "=", "{", "}", "# type: Dict[str, Any]", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "k", "in", "mapping", ":", "k", "=", "mapping", "[", "k", "]", "result", "[", "k", "]", "=", "v", "return", "result" ]
Returns a copy of the dictionary ``d`` with its keys renamed according to ``mapping``. Args: d: the starting dictionary mapping: a dictionary of the format ``{old_key_name: new_key_name}`` Returns: a new dictionary Keys that are not in ``mapping`` are left unchanged. The input parameters are not modified.
[ "Returns", "a", "copy", "of", "the", "dictionary", "d", "with", "its", "keys", "renamed", "according", "to", "mapping", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L88-L108
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
rename_keys_in_dict
def rename_keys_in_dict(d: Dict[str, Any], renames: Dict[str, str]) -> None: """ Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary. """ # noqa for old_key, new_key in renames.items(): if new_key == old_key: continue if old_key in d: if new_key in d: raise ValueError( "rename_keys_in_dict: renaming {} -> {} but new key " "already exists".format(repr(old_key), repr(new_key))) d[new_key] = d.pop(old_key)
python
def rename_keys_in_dict(d: Dict[str, Any], renames: Dict[str, str]) -> None: """ Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary. """ # noqa for old_key, new_key in renames.items(): if new_key == old_key: continue if old_key in d: if new_key in d: raise ValueError( "rename_keys_in_dict: renaming {} -> {} but new key " "already exists".format(repr(old_key), repr(new_key))) d[new_key] = d.pop(old_key)
[ "def", "rename_keys_in_dict", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "renames", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "None", ":", "# noqa", "for", "old_key", ",", "new_key", "in", "renames", ".", "items", "(", ")", ":", "if", "new_key", "==", "old_key", ":", "continue", "if", "old_key", "in", "d", ":", "if", "new_key", "in", "d", ":", "raise", "ValueError", "(", "\"rename_keys_in_dict: renaming {} -> {} but new key \"", "\"already exists\"", ".", "format", "(", "repr", "(", "old_key", ")", ",", "repr", "(", "new_key", ")", ")", ")", "d", "[", "new_key", "]", "=", "d", ".", "pop", "(", "old_key", ")" ]
Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary.
[ "Renames", "IN", "PLACE", "the", "keys", "in", "d", "according", "to", "the", "mapping", "in", "renames", ".", "Args", ":", "d", ":", "a", "dictionary", "to", "modify", "renames", ":", "a", "dictionary", "of", "the", "format", "{", "old_key_name", ":", "new_key_name", "}", "See", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "4406501", "/", "change", "-", "the", "-", "name", "-", "of", "-", "a", "-", "key", "-", "in", "-", "dictionary", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L111-L131
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
prefix_dict_keys
def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]: """ Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys. """ result = {} # type: Dict[str, Any] for k, v in d.items(): result[prefix + k] = v return result
python
def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]: """ Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys. """ result = {} # type: Dict[str, Any] for k, v in d.items(): result[prefix + k] = v return result
[ "def", "prefix_dict_keys", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "prefix", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "result", "=", "{", "}", "# type: Dict[str, Any]", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "result", "[", "prefix", "+", "k", "]", "=", "v", "return", "result" ]
Returns a dictionary that's a copy of as ``d`` but with ``prefix`` prepended to its keys.
[ "Returns", "a", "dictionary", "that", "s", "a", "copy", "of", "as", "d", "but", "with", "prefix", "prepended", "to", "its", "keys", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L134-L142
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
reversedict
def reversedict(d: Dict[Any, Any]) -> Dict[Any, Any]: """ Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping. """ return {v: k for k, v in d.items()}
python
def reversedict(d: Dict[Any, Any]) -> Dict[Any, Any]: """ Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping. """ return {v: k for k, v in d.items()}
[ "def", "reversedict", "(", "d", ":", "Dict", "[", "Any", ",", "Any", "]", ")", "->", "Dict", "[", "Any", ",", "Any", "]", ":", "return", "{", "v", ":", "k", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", "}" ]
Takes a ``k -> v`` mapping and returns a ``v -> k`` mapping.
[ "Takes", "a", "k", "-", ">", "v", "mapping", "and", "returns", "a", "v", "-", ">", "k", "mapping", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L145-L149
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
set_null_values_in_dict
def set_null_values_in_dict(d: Dict[str, Any], null_literals: List[Any]) -> None: """ Within ``d`` (in place), replace any values found in ``null_literals`` with ``None``. """ if not null_literals: return # DO NOT add/delete values to/from a dictionary during iteration, but it # is OK to modify existing keys: # https://stackoverflow.com/questions/6777485 # https://stackoverflow.com/questions/2315520 # https://docs.python.org/3/library/stdtypes.html#dict-views for k, v in d.items(): if v in null_literals: d[k] = None
python
def set_null_values_in_dict(d: Dict[str, Any], null_literals: List[Any]) -> None: """ Within ``d`` (in place), replace any values found in ``null_literals`` with ``None``. """ if not null_literals: return # DO NOT add/delete values to/from a dictionary during iteration, but it # is OK to modify existing keys: # https://stackoverflow.com/questions/6777485 # https://stackoverflow.com/questions/2315520 # https://docs.python.org/3/library/stdtypes.html#dict-views for k, v in d.items(): if v in null_literals: d[k] = None
[ "def", "set_null_values_in_dict", "(", "d", ":", "Dict", "[", "str", ",", "Any", "]", ",", "null_literals", ":", "List", "[", "Any", "]", ")", "->", "None", ":", "if", "not", "null_literals", ":", "return", "# DO NOT add/delete values to/from a dictionary during iteration, but it", "# is OK to modify existing keys:", "# https://stackoverflow.com/questions/6777485", "# https://stackoverflow.com/questions/2315520", "# https://docs.python.org/3/library/stdtypes.html#dict-views", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "v", "in", "null_literals", ":", "d", "[", "k", "]", "=", "None" ]
Within ``d`` (in place), replace any values found in ``null_literals`` with ``None``.
[ "Within", "d", "(", "in", "place", ")", "replace", "any", "values", "found", "in", "null_literals", "with", "None", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L152-L167
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
map_keys_to_values
def map_keys_to_values(l: List[Any], d: Dict[Any, Any], default: Any = None, raise_if_missing: bool = False, omit_if_missing: bool = False) -> List[Any]: """ The ``d`` dictionary contains a ``key -> value`` mapping. We start with a list of potential keys in ``l``, and return a list of corresponding values -- substituting ``default`` if any are missing, or raising :exc:`KeyError` if ``raise_if_missing`` is true, or omitting the entry if ``omit_if_missing`` is true. """ result = [] for k in l: if raise_if_missing and k not in d: raise ValueError("Missing key: " + repr(k)) if omit_if_missing and k not in d: continue result.append(d.get(k, default)) return result
python
def map_keys_to_values(l: List[Any], d: Dict[Any, Any], default: Any = None, raise_if_missing: bool = False, omit_if_missing: bool = False) -> List[Any]: """ The ``d`` dictionary contains a ``key -> value`` mapping. We start with a list of potential keys in ``l``, and return a list of corresponding values -- substituting ``default`` if any are missing, or raising :exc:`KeyError` if ``raise_if_missing`` is true, or omitting the entry if ``omit_if_missing`` is true. """ result = [] for k in l: if raise_if_missing and k not in d: raise ValueError("Missing key: " + repr(k)) if omit_if_missing and k not in d: continue result.append(d.get(k, default)) return result
[ "def", "map_keys_to_values", "(", "l", ":", "List", "[", "Any", "]", ",", "d", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "default", ":", "Any", "=", "None", ",", "raise_if_missing", ":", "bool", "=", "False", ",", "omit_if_missing", ":", "bool", "=", "False", ")", "->", "List", "[", "Any", "]", ":", "result", "=", "[", "]", "for", "k", "in", "l", ":", "if", "raise_if_missing", "and", "k", "not", "in", "d", ":", "raise", "ValueError", "(", "\"Missing key: \"", "+", "repr", "(", "k", ")", ")", "if", "omit_if_missing", "and", "k", "not", "in", "d", ":", "continue", "result", ".", "append", "(", "d", ".", "get", "(", "k", ",", "default", ")", ")", "return", "result" ]
The ``d`` dictionary contains a ``key -> value`` mapping. We start with a list of potential keys in ``l``, and return a list of corresponding values -- substituting ``default`` if any are missing, or raising :exc:`KeyError` if ``raise_if_missing`` is true, or omitting the entry if ``omit_if_missing`` is true.
[ "The", "d", "dictionary", "contains", "a", "key", "-", ">", "value", "mapping", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L170-L188
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
dict_diff
def dict_diff(d1: Dict[Any, Any], d2: Dict[Any, Any], deleted_value: Any = None) -> Dict[Any, Any]: """ Returns a representation of the changes that need to be made to ``d1`` to create ``d2``. Args: d1: a dictionary d2: another dictionary deleted_value: value to use for deleted keys; see below Returns: dict: a dictionary of the format ``{k: v}`` where the ``k``/``v`` pairs are key/value pairs that are absent from ``d1`` and present in ``d2``, or present in both but with different values (in which case the ``d2`` value is shown). If a key ``k`` is present in ``d1`` but absent in ``d2``, the result dictionary has the entry ``{k: deleted_value}``. """ changes = {k: v for k, v in d2.items() if k not in d1 or d2[k] != d1[k]} for k in d1.keys(): if k not in d2: changes[k] = deleted_value return changes
python
def dict_diff(d1: Dict[Any, Any], d2: Dict[Any, Any], deleted_value: Any = None) -> Dict[Any, Any]: """ Returns a representation of the changes that need to be made to ``d1`` to create ``d2``. Args: d1: a dictionary d2: another dictionary deleted_value: value to use for deleted keys; see below Returns: dict: a dictionary of the format ``{k: v}`` where the ``k``/``v`` pairs are key/value pairs that are absent from ``d1`` and present in ``d2``, or present in both but with different values (in which case the ``d2`` value is shown). If a key ``k`` is present in ``d1`` but absent in ``d2``, the result dictionary has the entry ``{k: deleted_value}``. """ changes = {k: v for k, v in d2.items() if k not in d1 or d2[k] != d1[k]} for k in d1.keys(): if k not in d2: changes[k] = deleted_value return changes
[ "def", "dict_diff", "(", "d1", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "d2", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "deleted_value", ":", "Any", "=", "None", ")", "->", "Dict", "[", "Any", ",", "Any", "]", ":", "changes", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "d2", ".", "items", "(", ")", "if", "k", "not", "in", "d1", "or", "d2", "[", "k", "]", "!=", "d1", "[", "k", "]", "}", "for", "k", "in", "d1", ".", "keys", "(", ")", ":", "if", "k", "not", "in", "d2", ":", "changes", "[", "k", "]", "=", "deleted_value", "return", "changes" ]
Returns a representation of the changes that need to be made to ``d1`` to create ``d2``. Args: d1: a dictionary d2: another dictionary deleted_value: value to use for deleted keys; see below Returns: dict: a dictionary of the format ``{k: v}`` where the ``k``/``v`` pairs are key/value pairs that are absent from ``d1`` and present in ``d2``, or present in both but with different values (in which case the ``d2`` value is shown). If a key ``k`` is present in ``d1`` but absent in ``d2``, the result dictionary has the entry ``{k: deleted_value}``.
[ "Returns", "a", "representation", "of", "the", "changes", "that", "need", "to", "be", "made", "to", "d1", "to", "create", "d2", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L191-L215
RudolfCardinal/pythonlib
cardinal_pythonlib/dicts.py
delete_keys
def delete_keys(d: Dict[Any, Any], keys_to_delete: List[Any], keys_to_keep: List[Any]) -> None: """ Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are deleted... keys_to_keep: ... unless they are present in this list. """ for k in keys_to_delete: if k in d and k not in keys_to_keep: del d[k]
python
def delete_keys(d: Dict[Any, Any], keys_to_delete: List[Any], keys_to_keep: List[Any]) -> None: """ Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are deleted... keys_to_keep: ... unless they are present in this list. """ for k in keys_to_delete: if k in d and k not in keys_to_keep: del d[k]
[ "def", "delete_keys", "(", "d", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "keys_to_delete", ":", "List", "[", "Any", "]", ",", "keys_to_keep", ":", "List", "[", "Any", "]", ")", "->", "None", ":", "for", "k", "in", "keys_to_delete", ":", "if", "k", "in", "d", "and", "k", "not", "in", "keys_to_keep", ":", "del", "d", "[", "k", "]" ]
Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are deleted... keys_to_keep: ... unless they are present in this list.
[ "Deletes", "keys", "from", "a", "dictionary", "in", "place", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dicts.py#L218-L234
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/list_types.py
StringListType.process_bind_param
def process_bind_param(self, value: Optional[List[str]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._strlist_to_dbstr(value) return retval
python
def process_bind_param(self, value: Optional[List[str]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._strlist_to_dbstr(value) return retval
[ "def", "process_bind_param", "(", "self", ",", "value", ":", "Optional", "[", "List", "[", "str", "]", "]", ",", "dialect", ":", "Dialect", ")", "->", "str", ":", "retval", "=", "self", ".", "_strlist_to_dbstr", "(", "value", ")", "return", "retval" ]
Convert things on the way from Python to the database.
[ "Convert", "things", "on", "the", "way", "from", "Python", "to", "the", "database", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L208-L212
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/list_types.py
StringListType.process_result_value
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[str]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_strlist(value) return retval
python
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[str]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_strlist(value) return retval
[ "def", "process_result_value", "(", "self", ",", "value", ":", "Optional", "[", "str", "]", ",", "dialect", ":", "Dialect", ")", "->", "List", "[", "str", "]", ":", "retval", "=", "self", ".", "_dbstr_to_strlist", "(", "value", ")", "return", "retval" ]
Convert things on the way from the database to Python.
[ "Convert", "things", "on", "the", "way", "from", "the", "database", "to", "Python", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L223-L227
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/list_types.py
IntListType.process_literal_param
def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._intlist_to_dbstr(value) return retval
python
def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._intlist_to_dbstr(value) return retval
[ "def", "process_literal_param", "(", "self", ",", "value", ":", "Optional", "[", "List", "[", "int", "]", "]", ",", "dialect", ":", "Dialect", ")", "->", "str", ":", "retval", "=", "self", ".", "_intlist_to_dbstr", "(", "value", ")", "return", "retval" ]
Convert things on the way from Python to the database.
[ "Convert", "things", "on", "the", "way", "from", "Python", "to", "the", "database", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L271-L275
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/list_types.py
IntListType.process_result_value
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[int]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_intlist(value) return retval
python
def process_result_value(self, value: Optional[str], dialect: Dialect) -> List[int]: """Convert things on the way from the database to Python.""" retval = self._dbstr_to_intlist(value) return retval
[ "def", "process_result_value", "(", "self", ",", "value", ":", "Optional", "[", "str", "]", ",", "dialect", ":", "Dialect", ")", "->", "List", "[", "int", "]", ":", "retval", "=", "self", ".", "_dbstr_to_intlist", "(", "value", ")", "return", "retval" ]
Convert things on the way from the database to Python.
[ "Convert", "things", "on", "the", "way", "from", "the", "database", "to", "Python", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/list_types.py#L277-L281
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
MultiTimer.reset
def reset(self) -> None: """ Reset the timers. """ self._overallstart = get_now_utc_pendulum() self._starttimes.clear() self._totaldurations.clear() self._count.clear() self._stack.clear()
python
def reset(self) -> None: """ Reset the timers. """ self._overallstart = get_now_utc_pendulum() self._starttimes.clear() self._totaldurations.clear() self._count.clear() self._stack.clear()
[ "def", "reset", "(", "self", ")", "->", "None", ":", "self", ".", "_overallstart", "=", "get_now_utc_pendulum", "(", ")", "self", ".", "_starttimes", ".", "clear", "(", ")", "self", ".", "_totaldurations", ".", "clear", "(", ")", "self", ".", "_count", ".", "clear", "(", ")", "self", ".", "_stack", ".", "clear", "(", ")" ]
Reset the timers.
[ "Reset", "the", "timers", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L58-L66
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
MultiTimer.set_timing
def set_timing(self, timing: bool, reset: bool = False) -> None: """ Manually set the ``timing`` parameter, and optionally reset the timers. Args: timing: should we be timing? reset: reset the timers? """ self._timing = timing if reset: self.reset()
python
def set_timing(self, timing: bool, reset: bool = False) -> None: """ Manually set the ``timing`` parameter, and optionally reset the timers. Args: timing: should we be timing? reset: reset the timers? """ self._timing = timing if reset: self.reset()
[ "def", "set_timing", "(", "self", ",", "timing", ":", "bool", ",", "reset", ":", "bool", "=", "False", ")", "->", "None", ":", "self", ".", "_timing", "=", "timing", "if", "reset", ":", "self", ".", "reset", "(", ")" ]
Manually set the ``timing`` parameter, and optionally reset the timers. Args: timing: should we be timing? reset: reset the timers?
[ "Manually", "set", "the", "timing", "parameter", "and", "optionally", "reset", "the", "timers", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L68-L79
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
MultiTimer.start
def start(self, name: str, increment_count: bool = True) -> None: """ Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer """ if not self._timing: return now = get_now_utc_pendulum() # If we were already timing something else, pause that. if self._stack: last = self._stack[-1] self._totaldurations[last] += now - self._starttimes[last] # Start timing our new thing if name not in self._starttimes: self._totaldurations[name] = datetime.timedelta() self._count[name] = 0 self._starttimes[name] = now if increment_count: self._count[name] += 1 self._stack.append(name)
python
def start(self, name: str, increment_count: bool = True) -> None: """ Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer """ if not self._timing: return now = get_now_utc_pendulum() # If we were already timing something else, pause that. if self._stack: last = self._stack[-1] self._totaldurations[last] += now - self._starttimes[last] # Start timing our new thing if name not in self._starttimes: self._totaldurations[name] = datetime.timedelta() self._count[name] = 0 self._starttimes[name] = now if increment_count: self._count[name] += 1 self._stack.append(name)
[ "def", "start", "(", "self", ",", "name", ":", "str", ",", "increment_count", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "not", "self", ".", "_timing", ":", "return", "now", "=", "get_now_utc_pendulum", "(", ")", "# If we were already timing something else, pause that.", "if", "self", ".", "_stack", ":", "last", "=", "self", ".", "_stack", "[", "-", "1", "]", "self", ".", "_totaldurations", "[", "last", "]", "+=", "now", "-", "self", ".", "_starttimes", "[", "last", "]", "# Start timing our new thing", "if", "name", "not", "in", "self", ".", "_starttimes", ":", "self", ".", "_totaldurations", "[", "name", "]", "=", "datetime", ".", "timedelta", "(", ")", "self", ".", "_count", "[", "name", "]", "=", "0", "self", ".", "_starttimes", "[", "name", "]", "=", "now", "if", "increment_count", ":", "self", ".", "_count", "[", "name", "]", "+=", "1", "self", ".", "_stack", ".", "append", "(", "name", ")" ]
Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer
[ "Start", "a", "named", "timer", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L81-L106
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
MultiTimer.stop
def stop(self, name: str) -> None: """ Stop a named timer. Args: name: timer to stop """ if not self._timing: return now = get_now_utc_pendulum() # Validity check if not self._stack: raise AssertionError("MultiTimer.stop() when nothing running") if self._stack[-1] != name: raise AssertionError( "MultiTimer.stop({}) when {} is running".format( repr(name), repr(self._stack[-1]))) # Finish what we were asked to self._totaldurations[name] += now - self._starttimes[name] self._stack.pop() # Now, if we were timing something else before we started "name", # resume... if self._stack: last = self._stack[-1] self._starttimes[last] = now
python
def stop(self, name: str) -> None: """ Stop a named timer. Args: name: timer to stop """ if not self._timing: return now = get_now_utc_pendulum() # Validity check if not self._stack: raise AssertionError("MultiTimer.stop() when nothing running") if self._stack[-1] != name: raise AssertionError( "MultiTimer.stop({}) when {} is running".format( repr(name), repr(self._stack[-1]))) # Finish what we were asked to self._totaldurations[name] += now - self._starttimes[name] self._stack.pop() # Now, if we were timing something else before we started "name", # resume... if self._stack: last = self._stack[-1] self._starttimes[last] = now
[ "def", "stop", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "if", "not", "self", ".", "_timing", ":", "return", "now", "=", "get_now_utc_pendulum", "(", ")", "# Validity check", "if", "not", "self", ".", "_stack", ":", "raise", "AssertionError", "(", "\"MultiTimer.stop() when nothing running\"", ")", "if", "self", ".", "_stack", "[", "-", "1", "]", "!=", "name", ":", "raise", "AssertionError", "(", "\"MultiTimer.stop({}) when {} is running\"", ".", "format", "(", "repr", "(", "name", ")", ",", "repr", "(", "self", ".", "_stack", "[", "-", "1", "]", ")", ")", ")", "# Finish what we were asked to", "self", ".", "_totaldurations", "[", "name", "]", "+=", "now", "-", "self", ".", "_starttimes", "[", "name", "]", "self", ".", "_stack", ".", "pop", "(", ")", "# Now, if we were timing something else before we started \"name\",", "# resume...", "if", "self", ".", "_stack", ":", "last", "=", "self", ".", "_stack", "[", "-", "1", "]", "self", ".", "_starttimes", "[", "last", "]", "=", "now" ]
Stop a named timer. Args: name: timer to stop
[ "Stop", "a", "named", "timer", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L108-L135
RudolfCardinal/pythonlib
cardinal_pythonlib/timing.py
MultiTimer.report
def report(self) -> None: """ Finish and report to the log. """ while self._stack: self.stop(self._stack[-1]) now = get_now_utc_pendulum() grand_total = datetime.timedelta() overall_duration = now - self._overallstart for name, duration in self._totaldurations.items(): grand_total += duration log.info("Timing summary:") summaries = [] for name, duration in self._totaldurations.items(): n = self._count[name] total_sec = duration.total_seconds() mean = total_sec / n if n > 0 else None summaries.append({ 'total': total_sec, 'description': ( "- {}: {:.3f} s ({:.2f}%, n={}, mean={:.3f}s)".format( name, total_sec, (100 * total_sec / grand_total.total_seconds()), n, mean)), }) summaries.sort(key=lambda x: x['total'], reverse=True) for s in summaries: # noinspection PyTypeChecker log.info(s["description"]) if not self._totaldurations: log.info("<no timings recorded>") unmetered = overall_duration - grand_total log.info( "Unmetered time: {:.3f} s ({:.2f}%)", unmetered.total_seconds(), 100 * unmetered.total_seconds() / overall_duration.total_seconds() ) log.info("Total time: {:.3f} s", grand_total.total_seconds())
python
def report(self) -> None: """ Finish and report to the log. """ while self._stack: self.stop(self._stack[-1]) now = get_now_utc_pendulum() grand_total = datetime.timedelta() overall_duration = now - self._overallstart for name, duration in self._totaldurations.items(): grand_total += duration log.info("Timing summary:") summaries = [] for name, duration in self._totaldurations.items(): n = self._count[name] total_sec = duration.total_seconds() mean = total_sec / n if n > 0 else None summaries.append({ 'total': total_sec, 'description': ( "- {}: {:.3f} s ({:.2f}%, n={}, mean={:.3f}s)".format( name, total_sec, (100 * total_sec / grand_total.total_seconds()), n, mean)), }) summaries.sort(key=lambda x: x['total'], reverse=True) for s in summaries: # noinspection PyTypeChecker log.info(s["description"]) if not self._totaldurations: log.info("<no timings recorded>") unmetered = overall_duration - grand_total log.info( "Unmetered time: {:.3f} s ({:.2f}%)", unmetered.total_seconds(), 100 * unmetered.total_seconds() / overall_duration.total_seconds() ) log.info("Total time: {:.3f} s", grand_total.total_seconds())
[ "def", "report", "(", "self", ")", "->", "None", ":", "while", "self", ".", "_stack", ":", "self", ".", "stop", "(", "self", ".", "_stack", "[", "-", "1", "]", ")", "now", "=", "get_now_utc_pendulum", "(", ")", "grand_total", "=", "datetime", ".", "timedelta", "(", ")", "overall_duration", "=", "now", "-", "self", ".", "_overallstart", "for", "name", ",", "duration", "in", "self", ".", "_totaldurations", ".", "items", "(", ")", ":", "grand_total", "+=", "duration", "log", ".", "info", "(", "\"Timing summary:\"", ")", "summaries", "=", "[", "]", "for", "name", ",", "duration", "in", "self", ".", "_totaldurations", ".", "items", "(", ")", ":", "n", "=", "self", ".", "_count", "[", "name", "]", "total_sec", "=", "duration", ".", "total_seconds", "(", ")", "mean", "=", "total_sec", "/", "n", "if", "n", ">", "0", "else", "None", "summaries", ".", "append", "(", "{", "'total'", ":", "total_sec", ",", "'description'", ":", "(", "\"- {}: {:.3f} s ({:.2f}%, n={}, mean={:.3f}s)\"", ".", "format", "(", "name", ",", "total_sec", ",", "(", "100", "*", "total_sec", "/", "grand_total", ".", "total_seconds", "(", ")", ")", ",", "n", ",", "mean", ")", ")", ",", "}", ")", "summaries", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "'total'", "]", ",", "reverse", "=", "True", ")", "for", "s", "in", "summaries", ":", "# noinspection PyTypeChecker", "log", ".", "info", "(", "s", "[", "\"description\"", "]", ")", "if", "not", "self", ".", "_totaldurations", ":", "log", ".", "info", "(", "\"<no timings recorded>\"", ")", "unmetered", "=", "overall_duration", "-", "grand_total", "log", ".", "info", "(", "\"Unmetered time: {:.3f} s ({:.2f}%)\"", ",", "unmetered", ".", "total_seconds", "(", ")", ",", "100", "*", "unmetered", ".", "total_seconds", "(", ")", "/", "overall_duration", ".", "total_seconds", "(", ")", ")", "log", ".", "info", "(", "\"Total time: {:.3f} s\"", ",", "grand_total", ".", "total_seconds", "(", ")", ")" ]
Finish and report to the log.
[ "Finish", "and", "report", "to", "the", "log", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/timing.py#L137-L179
davenquinn/Attitude
attitude/display/stereonet.py
girdle_error
def girdle_error(ax, fit, **kwargs): """ Plot an attitude measurement on an `mplstereonet` axes object. """ vertices = [] codes = [] for sheet in ('upper','lower'): err = plane_errors(fit.axes, fit.covariance_matrix, sheet=sheet) lonlat = N.array(err) lonlat *= -1 n = len(lonlat) if sheet == 'lower': lonlat = lonlat[::-1] vertices += list(lonlat) codes.append(Path.MOVETO) codes += [Path.LINETO]*(n-1) plot_patch(ax, vertices, codes, **kwargs)
python
def girdle_error(ax, fit, **kwargs): """ Plot an attitude measurement on an `mplstereonet` axes object. """ vertices = [] codes = [] for sheet in ('upper','lower'): err = plane_errors(fit.axes, fit.covariance_matrix, sheet=sheet) lonlat = N.array(err) lonlat *= -1 n = len(lonlat) if sheet == 'lower': lonlat = lonlat[::-1] vertices += list(lonlat) codes.append(Path.MOVETO) codes += [Path.LINETO]*(n-1) plot_patch(ax, vertices, codes, **kwargs)
[ "def", "girdle_error", "(", "ax", ",", "fit", ",", "*", "*", "kwargs", ")", ":", "vertices", "=", "[", "]", "codes", "=", "[", "]", "for", "sheet", "in", "(", "'upper'", ",", "'lower'", ")", ":", "err", "=", "plane_errors", "(", "fit", ".", "axes", ",", "fit", ".", "covariance_matrix", ",", "sheet", "=", "sheet", ")", "lonlat", "=", "N", ".", "array", "(", "err", ")", "lonlat", "*=", "-", "1", "n", "=", "len", "(", "lonlat", ")", "if", "sheet", "==", "'lower'", ":", "lonlat", "=", "lonlat", "[", ":", ":", "-", "1", "]", "vertices", "+=", "list", "(", "lonlat", ")", "codes", ".", "append", "(", "Path", ".", "MOVETO", ")", "codes", "+=", "[", "Path", ".", "LINETO", "]", "*", "(", "n", "-", "1", ")", "plot_patch", "(", "ax", ",", "vertices", ",", "codes", ",", "*", "*", "kwargs", ")" ]
Plot an attitude measurement on an `mplstereonet` axes object.
[ "Plot", "an", "attitude", "measurement", "on", "an", "mplstereonet", "axes", "object", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/stereonet.py#L21-L39
davenquinn/Attitude
attitude/display/stereonet.py
pole_error
def pole_error(ax, fit, **kwargs): """ Plot the error to the pole to a plane on a `mplstereonet` axis object. """ ell = normal_errors(fit.axes, fit.covariance_matrix) lonlat = -N.array(ell) n = len(lonlat) codes = [Path.MOVETO] codes += [Path.LINETO]*(n-1) vertices = list(lonlat) plot_patch(ax, vertices, codes, **kwargs)
python
def pole_error(ax, fit, **kwargs): """ Plot the error to the pole to a plane on a `mplstereonet` axis object. """ ell = normal_errors(fit.axes, fit.covariance_matrix) lonlat = -N.array(ell) n = len(lonlat) codes = [Path.MOVETO] codes += [Path.LINETO]*(n-1) vertices = list(lonlat) plot_patch(ax, vertices, codes, **kwargs)
[ "def", "pole_error", "(", "ax", ",", "fit", ",", "*", "*", "kwargs", ")", ":", "ell", "=", "normal_errors", "(", "fit", ".", "axes", ",", "fit", ".", "covariance_matrix", ")", "lonlat", "=", "-", "N", ".", "array", "(", "ell", ")", "n", "=", "len", "(", "lonlat", ")", "codes", "=", "[", "Path", ".", "MOVETO", "]", "codes", "+=", "[", "Path", ".", "LINETO", "]", "*", "(", "n", "-", "1", ")", "vertices", "=", "list", "(", "lonlat", ")", "plot_patch", "(", "ax", ",", "vertices", ",", "codes", ",", "*", "*", "kwargs", ")" ]
Plot the error to the pole to a plane on a `mplstereonet` axis object.
[ "Plot", "the", "error", "to", "the", "pole", "to", "a", "plane", "on", "a", "mplstereonet", "axis", "object", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/stereonet.py#L41-L53
RudolfCardinal/pythonlib
cardinal_pythonlib/network.py
ping
def ping(hostname: str, timeout_s: int = 5) -> bool: """ Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful? """ if sys.platform == "win32": timeout_ms = timeout_s * 1000 args = [ "ping", hostname, "-n", "1", # ping count "-w", str(timeout_ms), # timeout ] elif sys.platform.startswith('linux'): args = [ "ping", hostname, "-c", "1", # ping count "-w", str(timeout_s), # timeout ] else: raise AssertionError("Don't know how to ping on this operating system") proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.communicate() retcode = proc.returncode return retcode == 0
python
def ping(hostname: str, timeout_s: int = 5) -> bool: """ Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful? """ if sys.platform == "win32": timeout_ms = timeout_s * 1000 args = [ "ping", hostname, "-n", "1", # ping count "-w", str(timeout_ms), # timeout ] elif sys.platform.startswith('linux'): args = [ "ping", hostname, "-c", "1", # ping count "-w", str(timeout_s), # timeout ] else: raise AssertionError("Don't know how to ping on this operating system") proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) proc.communicate() retcode = proc.returncode return retcode == 0
[ "def", "ping", "(", "hostname", ":", "str", ",", "timeout_s", ":", "int", "=", "5", ")", "->", "bool", ":", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "timeout_ms", "=", "timeout_s", "*", "1000", "args", "=", "[", "\"ping\"", ",", "hostname", ",", "\"-n\"", ",", "\"1\"", ",", "# ping count", "\"-w\"", ",", "str", "(", "timeout_ms", ")", ",", "# timeout", "]", "elif", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "args", "=", "[", "\"ping\"", ",", "hostname", ",", "\"-c\"", ",", "\"1\"", ",", "# ping count", "\"-w\"", ",", "str", "(", "timeout_s", ")", ",", "# timeout", "]", "else", ":", "raise", "AssertionError", "(", "\"Don't know how to ping on this operating system\"", ")", "proc", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "proc", ".", "communicate", "(", ")", "retcode", "=", "proc", ".", "returncode", "return", "retcode", "==", "0" ]
Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful?
[ "Pings", "a", "host", "using", "OS", "tools", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/network.py#L59-L92
RudolfCardinal/pythonlib
cardinal_pythonlib/network.py
download
def download(url: str, filename: str, skip_cert_verify: bool = True) -> None: """ Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check? """ log.info("Downloading from {} to {}", url, filename) # urllib.request.urlretrieve(url, filename) # ... sometimes fails (e.g. downloading # https://www.openssl.org/source/openssl-1.1.0g.tar.gz under Windows) with: # ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) # noqa # ... due to this certificate root problem (probably because OpenSSL # [used by Python] doesn't play entirely by the same rules as others?): # https://stackoverflow.com/questions/27804710 # So: ctx = ssl.create_default_context() # type: ssl.SSLContext if skip_cert_verify: log.debug("Skipping SSL certificate check for " + url) ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE with urllib.request.urlopen(url, context=ctx) as u, open(filename, 'wb') as f: # noqa f.write(u.read())
python
def download(url: str, filename: str, skip_cert_verify: bool = True) -> None: """ Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check? """ log.info("Downloading from {} to {}", url, filename) # urllib.request.urlretrieve(url, filename) # ... sometimes fails (e.g. downloading # https://www.openssl.org/source/openssl-1.1.0g.tar.gz under Windows) with: # ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) # noqa # ... due to this certificate root problem (probably because OpenSSL # [used by Python] doesn't play entirely by the same rules as others?): # https://stackoverflow.com/questions/27804710 # So: ctx = ssl.create_default_context() # type: ssl.SSLContext if skip_cert_verify: log.debug("Skipping SSL certificate check for " + url) ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE with urllib.request.urlopen(url, context=ctx) as u, open(filename, 'wb') as f: # noqa f.write(u.read())
[ "def", "download", "(", "url", ":", "str", ",", "filename", ":", "str", ",", "skip_cert_verify", ":", "bool", "=", "True", ")", "->", "None", ":", "log", ".", "info", "(", "\"Downloading from {} to {}\"", ",", "url", ",", "filename", ")", "# urllib.request.urlretrieve(url, filename)", "# ... sometimes fails (e.g. downloading", "# https://www.openssl.org/source/openssl-1.1.0g.tar.gz under Windows) with:", "# ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) # noqa", "# ... due to this certificate root problem (probably because OpenSSL", "# [used by Python] doesn't play entirely by the same rules as others?):", "# https://stackoverflow.com/questions/27804710", "# So:", "ctx", "=", "ssl", ".", "create_default_context", "(", ")", "# type: ssl.SSLContext", "if", "skip_cert_verify", ":", "log", ".", "debug", "(", "\"Skipping SSL certificate check for \"", "+", "url", ")", "ctx", ".", "check_hostname", "=", "False", "ctx", ".", "verify_mode", "=", "ssl", ".", "CERT_NONE", "with", "urllib", ".", "request", ".", "urlopen", "(", "url", ",", "context", "=", "ctx", ")", "as", "u", ",", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "# noqa", "f", ".", "write", "(", "u", ".", "read", "(", ")", ")" ]
Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check?
[ "Downloads", "a", "URL", "to", "a", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/network.py#L99-L127
RudolfCardinal/pythonlib
cardinal_pythonlib/network.py
gen_binary_files_from_urls
def gen_binary_files_from_urls( urls: Iterable[str], on_disk: bool = False, show_info: bool = True) -> Generator[BinaryIO, None, None]: """ Generate binary files from a series of URLs (one per URL). Args: urls: iterable of URLs on_disk: if ``True``, yields files that are on disk (permitting random access); if ``False``, yields in-memory files (which will not permit random access) show_info: show progress to the log? Yields: files, each of type :class:`BinaryIO` """ for url in urls: if on_disk: # Necessary for e.g. zip processing (random access) with tempfile.TemporaryDirectory() as tmpdir: filename = os.path.join(tmpdir, "tempfile") download(url=url, filename=filename) with open(filename, 'rb') as f: yield f else: if show_info: log.info("Reading from URL: {}", url) with urllib.request.urlopen(url) as f: yield f if show_info: log.info("... finished reading from URL: {}", url)
python
def gen_binary_files_from_urls( urls: Iterable[str], on_disk: bool = False, show_info: bool = True) -> Generator[BinaryIO, None, None]: """ Generate binary files from a series of URLs (one per URL). Args: urls: iterable of URLs on_disk: if ``True``, yields files that are on disk (permitting random access); if ``False``, yields in-memory files (which will not permit random access) show_info: show progress to the log? Yields: files, each of type :class:`BinaryIO` """ for url in urls: if on_disk: # Necessary for e.g. zip processing (random access) with tempfile.TemporaryDirectory() as tmpdir: filename = os.path.join(tmpdir, "tempfile") download(url=url, filename=filename) with open(filename, 'rb') as f: yield f else: if show_info: log.info("Reading from URL: {}", url) with urllib.request.urlopen(url) as f: yield f if show_info: log.info("... finished reading from URL: {}", url)
[ "def", "gen_binary_files_from_urls", "(", "urls", ":", "Iterable", "[", "str", "]", ",", "on_disk", ":", "bool", "=", "False", ",", "show_info", ":", "bool", "=", "True", ")", "->", "Generator", "[", "BinaryIO", ",", "None", ",", "None", "]", ":", "for", "url", "in", "urls", ":", "if", "on_disk", ":", "# Necessary for e.g. zip processing (random access)", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmpdir", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "\"tempfile\"", ")", "download", "(", "url", "=", "url", ",", "filename", "=", "filename", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "yield", "f", "else", ":", "if", "show_info", ":", "log", ".", "info", "(", "\"Reading from URL: {}\"", ",", "url", ")", "with", "urllib", ".", "request", ".", "urlopen", "(", "url", ")", "as", "f", ":", "yield", "f", "if", "show_info", ":", "log", ".", "info", "(", "\"... finished reading from URL: {}\"", ",", "url", ")" ]
Generate binary files from a series of URLs (one per URL). Args: urls: iterable of URLs on_disk: if ``True``, yields files that are on disk (permitting random access); if ``False``, yields in-memory files (which will not permit random access) show_info: show progress to the log? Yields: files, each of type :class:`BinaryIO`
[ "Generate", "binary", "files", "from", "a", "series", "of", "URLs", "(", "one", "per", "URL", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/network.py#L134-L166
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
find_nth
def find_nth(s: str, x: str, n: int = 0, overlap: bool = False) -> int: """ Finds the position of *n*\ th occurrence of ``x`` in ``s``, or ``-1`` if there isn't one. - The ``n`` parameter is zero-based (i.e. 0 for the first, 1 for the second...). - If ``overlap`` is true, allows fragments to overlap. If not, they must be distinct. As per https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string """ # noqa length_of_fragment = 1 if overlap else len(x) i = -length_of_fragment for _ in range(n + 1): i = s.find(x, i + length_of_fragment) if i < 0: break return i
python
def find_nth(s: str, x: str, n: int = 0, overlap: bool = False) -> int: """ Finds the position of *n*\ th occurrence of ``x`` in ``s``, or ``-1`` if there isn't one. - The ``n`` parameter is zero-based (i.e. 0 for the first, 1 for the second...). - If ``overlap`` is true, allows fragments to overlap. If not, they must be distinct. As per https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string """ # noqa length_of_fragment = 1 if overlap else len(x) i = -length_of_fragment for _ in range(n + 1): i = s.find(x, i + length_of_fragment) if i < 0: break return i
[ "def", "find_nth", "(", "s", ":", "str", ",", "x", ":", "str", ",", "n", ":", "int", "=", "0", ",", "overlap", ":", "bool", "=", "False", ")", "->", "int", ":", "# noqa", "length_of_fragment", "=", "1", "if", "overlap", "else", "len", "(", "x", ")", "i", "=", "-", "length_of_fragment", "for", "_", "in", "range", "(", "n", "+", "1", ")", ":", "i", "=", "s", ".", "find", "(", "x", ",", "i", "+", "length_of_fragment", ")", "if", "i", "<", "0", ":", "break", "return", "i" ]
Finds the position of *n*\ th occurrence of ``x`` in ``s``, or ``-1`` if there isn't one. - The ``n`` parameter is zero-based (i.e. 0 for the first, 1 for the second...). - If ``overlap`` is true, allows fragments to overlap. If not, they must be distinct. As per https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string
[ "Finds", "the", "position", "of", "*", "n", "*", "\\", "th", "occurrence", "of", "x", "in", "s", "or", "-", "1", "if", "there", "isn", "t", "one", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L35-L54
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
split_string
def split_string(x: str, n: int) -> List[str]: """ Split string into chunks of length n """ # https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa return [x[i:i+n] for i in range(0, len(x), n)]
python
def split_string(x: str, n: int) -> List[str]: """ Split string into chunks of length n """ # https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa return [x[i:i+n] for i in range(0, len(x), n)]
[ "def", "split_string", "(", "x", ":", "str", ",", "n", ":", "int", ")", "->", "List", "[", "str", "]", ":", "# https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa", "return", "[", "x", "[", "i", ":", "i", "+", "n", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "x", ")", ",", "n", ")", "]" ]
Split string into chunks of length n
[ "Split", "string", "into", "chunks", "of", "length", "n" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L61-L66
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
multiple_replace
def multiple_replace(text: str, rep: Dict[str, str]) -> str: """ Returns a version of ``text`` in which the keys of ``rep`` (a dict) have been replaced by their values. As per http://stackoverflow.com/questions/6116978/python-replace-multiple-strings. """ rep = dict((re.escape(k), v) for k, v in rep.items()) pattern = re.compile("|".join(rep.keys())) return pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
python
def multiple_replace(text: str, rep: Dict[str, str]) -> str: """ Returns a version of ``text`` in which the keys of ``rep`` (a dict) have been replaced by their values. As per http://stackoverflow.com/questions/6116978/python-replace-multiple-strings. """ rep = dict((re.escape(k), v) for k, v in rep.items()) pattern = re.compile("|".join(rep.keys())) return pattern.sub(lambda m: rep[re.escape(m.group(0))], text)
[ "def", "multiple_replace", "(", "text", ":", "str", ",", "rep", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "str", ":", "rep", "=", "dict", "(", "(", "re", ".", "escape", "(", "k", ")", ",", "v", ")", "for", "k", ",", "v", "in", "rep", ".", "items", "(", ")", ")", "pattern", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "rep", ".", "keys", "(", ")", ")", ")", "return", "pattern", ".", "sub", "(", "lambda", "m", ":", "rep", "[", "re", ".", "escape", "(", "m", ".", "group", "(", "0", ")", ")", "]", ",", "text", ")" ]
Returns a version of ``text`` in which the keys of ``rep`` (a dict) have been replaced by their values. As per http://stackoverflow.com/questions/6116978/python-replace-multiple-strings.
[ "Returns", "a", "version", "of", "text", "in", "which", "the", "keys", "of", "rep", "(", "a", "dict", ")", "have", "been", "replaced", "by", "their", "values", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L73-L83
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
replace_in_list
def replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) -> List[str]: """ Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "original" to "replacement" strings Returns: list of final strings """ newlist = [] for fromstring in stringlist: newlist.append(multiple_replace(fromstring, replacedict)) return newlist
python
def replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) -> List[str]: """ Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "original" to "replacement" strings Returns: list of final strings """ newlist = [] for fromstring in stringlist: newlist.append(multiple_replace(fromstring, replacedict)) return newlist
[ "def", "replace_in_list", "(", "stringlist", ":", "Iterable", "[", "str", "]", ",", "replacedict", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "List", "[", "str", "]", ":", "newlist", "=", "[", "]", "for", "fromstring", "in", "stringlist", ":", "newlist", ".", "append", "(", "multiple_replace", "(", "fromstring", ",", "replacedict", ")", ")", "return", "newlist" ]
Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "original" to "replacement" strings Returns: list of final strings
[ "Returns", "a", "list", "produced", "by", "applying", ":", "func", ":", "multiple_replace", "to", "every", "string", "in", "stringlist", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L86-L103
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
mangle_unicode_to_ascii
def mangle_unicode_to_ascii(s: Any) -> str: """ Mangle unicode to ASCII, losing accents etc. in the process. """ # http://stackoverflow.com/questions/1207457 if s is None: return "" if not isinstance(s, str): s = str(s) return ( unicodedata.normalize('NFKD', s) .encode('ascii', 'ignore') # gets rid of accents .decode('ascii') # back to a string )
python
def mangle_unicode_to_ascii(s: Any) -> str: """ Mangle unicode to ASCII, losing accents etc. in the process. """ # http://stackoverflow.com/questions/1207457 if s is None: return "" if not isinstance(s, str): s = str(s) return ( unicodedata.normalize('NFKD', s) .encode('ascii', 'ignore') # gets rid of accents .decode('ascii') # back to a string )
[ "def", "mangle_unicode_to_ascii", "(", "s", ":", "Any", ")", "->", "str", ":", "# http://stackoverflow.com/questions/1207457", "if", "s", "is", "None", ":", "return", "\"\"", "if", "not", "isinstance", "(", "s", ",", "str", ")", ":", "s", "=", "str", "(", "s", ")", "return", "(", "unicodedata", ".", "normalize", "(", "'NFKD'", ",", "s", ")", ".", "encode", "(", "'ascii'", ",", "'ignore'", ")", "# gets rid of accents", ".", "decode", "(", "'ascii'", ")", "# back to a string", ")" ]
Mangle unicode to ASCII, losing accents etc. in the process.
[ "Mangle", "unicode", "to", "ASCII", "losing", "accents", "etc", ".", "in", "the", "process", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L110-L123
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
strnum
def strnum(prefix: str, num: int, suffix: str = "") -> str: """ Makes a string of the format ``<prefix><number><suffix>``. """ return "{}{}{}".format(prefix, num, suffix)
python
def strnum(prefix: str, num: int, suffix: str = "") -> str: """ Makes a string of the format ``<prefix><number><suffix>``. """ return "{}{}{}".format(prefix, num, suffix)
[ "def", "strnum", "(", "prefix", ":", "str", ",", "num", ":", "int", ",", "suffix", ":", "str", "=", "\"\"", ")", "->", "str", ":", "return", "\"{}{}{}\"", ".", "format", "(", "prefix", ",", "num", ",", "suffix", ")" ]
Makes a string of the format ``<prefix><number><suffix>``.
[ "Makes", "a", "string", "of", "the", "format", "<prefix", ">", "<number", ">", "<suffix", ">", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L130-L134
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
strnumlist
def strnumlist(prefix: str, numbers: List[int], suffix: str = "") -> List[str]: """ Makes a string of the format ``<prefix><number><suffix>`` for every number in ``numbers``, and returns them as a list. """ return ["{}{}{}".format(prefix, num, suffix) for num in numbers]
python
def strnumlist(prefix: str, numbers: List[int], suffix: str = "") -> List[str]: """ Makes a string of the format ``<prefix><number><suffix>`` for every number in ``numbers``, and returns them as a list. """ return ["{}{}{}".format(prefix, num, suffix) for num in numbers]
[ "def", "strnumlist", "(", "prefix", ":", "str", ",", "numbers", ":", "List", "[", "int", "]", ",", "suffix", ":", "str", "=", "\"\"", ")", "->", "List", "[", "str", "]", ":", "return", "[", "\"{}{}{}\"", ".", "format", "(", "prefix", ",", "num", ",", "suffix", ")", "for", "num", "in", "numbers", "]" ]
Makes a string of the format ``<prefix><number><suffix>`` for every number in ``numbers``, and returns them as a list.
[ "Makes", "a", "string", "of", "the", "format", "<prefix", ">", "<number", ">", "<suffix", ">", "for", "every", "number", "in", "numbers", "and", "returns", "them", "as", "a", "list", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L137-L142
RudolfCardinal/pythonlib
cardinal_pythonlib/stringfunc.py
strseq
def strseq(prefix: str, first: int, last: int, suffix: str = "") -> List[str]: """ Makes a string of the format ``<prefix><number><suffix>`` for every number from ``first`` to ``last`` inclusive, and returns them as a list. """ return [strnum(prefix, n, suffix) for n in range(first, last + 1)]
python
def strseq(prefix: str, first: int, last: int, suffix: str = "") -> List[str]: """ Makes a string of the format ``<prefix><number><suffix>`` for every number from ``first`` to ``last`` inclusive, and returns them as a list. """ return [strnum(prefix, n, suffix) for n in range(first, last + 1)]
[ "def", "strseq", "(", "prefix", ":", "str", ",", "first", ":", "int", ",", "last", ":", "int", ",", "suffix", ":", "str", "=", "\"\"", ")", "->", "List", "[", "str", "]", ":", "return", "[", "strnum", "(", "prefix", ",", "n", ",", "suffix", ")", "for", "n", "in", "range", "(", "first", ",", "last", "+", "1", ")", "]" ]
Makes a string of the format ``<prefix><number><suffix>`` for every number from ``first`` to ``last`` inclusive, and returns them as a list.
[ "Makes", "a", "string", "of", "the", "format", "<prefix", ">", "<number", ">", "<suffix", ">", "for", "every", "number", "from", "first", "to", "last", "inclusive", "and", "returns", "them", "as", "a", "list", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/stringfunc.py#L145-L150
davenquinn/Attitude
attitude/display/plot/misc.py
aligned_residuals
def aligned_residuals(pca): """ Plots error components along with bootstrap resampled error surface. Provides another statistical method to estimate the variance of a dataset. """ A = pca.rotated() fig, axes = P.subplots(2,1, sharex=True, frameon=False) fig.subplots_adjust(hspace=0, wspace=0.1) kw = dict(c="#555555", s=40, alpha=0.5) #lengths = attitude.pca.singular_values[::-1] lengths = (A[:,i].max()-A[:,i].min() for i in range(3)) titles = ( "Long cross-section (axis 3 vs. axis 1)", "Short cross-section (axis 3 vs. axis 2)") for title,ax,(a,b) in zip(titles,axes, [(0,2),(1,2)]): seaborn.regplot(A[:,a], A[:,b], ax=ax) ax.text(0,1,title, verticalalignment='top', transform=ax.transAxes) ax.autoscale(tight=True) for spine in ax.spines.itervalues(): spine.set_visible(False) ax.set_xlabel("Meters") return fig
python
def aligned_residuals(pca): """ Plots error components along with bootstrap resampled error surface. Provides another statistical method to estimate the variance of a dataset. """ A = pca.rotated() fig, axes = P.subplots(2,1, sharex=True, frameon=False) fig.subplots_adjust(hspace=0, wspace=0.1) kw = dict(c="#555555", s=40, alpha=0.5) #lengths = attitude.pca.singular_values[::-1] lengths = (A[:,i].max()-A[:,i].min() for i in range(3)) titles = ( "Long cross-section (axis 3 vs. axis 1)", "Short cross-section (axis 3 vs. axis 2)") for title,ax,(a,b) in zip(titles,axes, [(0,2),(1,2)]): seaborn.regplot(A[:,a], A[:,b], ax=ax) ax.text(0,1,title, verticalalignment='top', transform=ax.transAxes) ax.autoscale(tight=True) for spine in ax.spines.itervalues(): spine.set_visible(False) ax.set_xlabel("Meters") return fig
[ "def", "aligned_residuals", "(", "pca", ")", ":", "A", "=", "pca", ".", "rotated", "(", ")", "fig", ",", "axes", "=", "P", ".", "subplots", "(", "2", ",", "1", ",", "sharex", "=", "True", ",", "frameon", "=", "False", ")", "fig", ".", "subplots_adjust", "(", "hspace", "=", "0", ",", "wspace", "=", "0.1", ")", "kw", "=", "dict", "(", "c", "=", "\"#555555\"", ",", "s", "=", "40", ",", "alpha", "=", "0.5", ")", "#lengths = attitude.pca.singular_values[::-1]", "lengths", "=", "(", "A", "[", ":", ",", "i", "]", ".", "max", "(", ")", "-", "A", "[", ":", ",", "i", "]", ".", "min", "(", ")", "for", "i", "in", "range", "(", "3", ")", ")", "titles", "=", "(", "\"Long cross-section (axis 3 vs. axis 1)\"", ",", "\"Short cross-section (axis 3 vs. axis 2)\"", ")", "for", "title", ",", "ax", ",", "(", "a", ",", "b", ")", "in", "zip", "(", "titles", ",", "axes", ",", "[", "(", "0", ",", "2", ")", ",", "(", "1", ",", "2", ")", "]", ")", ":", "seaborn", ".", "regplot", "(", "A", "[", ":", ",", "a", "]", ",", "A", "[", ":", ",", "b", "]", ",", "ax", "=", "ax", ")", "ax", ".", "text", "(", "0", ",", "1", ",", "title", ",", "verticalalignment", "=", "'top'", ",", "transform", "=", "ax", ".", "transAxes", ")", "ax", ".", "autoscale", "(", "tight", "=", "True", ")", "for", "spine", "in", "ax", ".", "spines", ".", "itervalues", "(", ")", ":", "spine", ".", "set_visible", "(", "False", ")", "ax", ".", "set_xlabel", "(", "\"Meters\"", ")", "return", "fig" ]
Plots error components along with bootstrap resampled error surface. Provides another statistical method to estimate the variance of a dataset.
[ "Plots", "error", "components", "along", "with", "bootstrap", "resampled", "error", "surface", ".", "Provides", "another", "statistical", "method", "to", "estimate", "the", "variance", "of", "a", "dataset", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/plot/misc.py#L6-L37
ivanprjcts/sdklib
sdklib/util/design_pattern.py
Singleton.get_instance
def get_instance(self): """ Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned. """ try: return self._instance except AttributeError: self._instance = self._decorated() return self._instance
python
def get_instance(self): """ Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned. """ try: return self._instance except AttributeError: self._instance = self._decorated() return self._instance
[ "def", "get_instance", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_instance", "except", "AttributeError", ":", "self", ".", "_instance", "=", "self", ".", "_decorated", "(", ")", "return", "self", ".", "_instance" ]
Returns the singleton instance. Upon its first call, it creates a new instance of the decorated class and calls its `__init__` method. On all subsequent calls, the already created instance is returned.
[ "Returns", "the", "singleton", "instance", ".", "Upon", "its", "first", "call", "it", "creates", "a", "new", "instance", "of", "the", "decorated", "class", "and", "calls", "its", "__init__", "method", ".", "On", "all", "subsequent", "calls", "the", "already", "created", "instance", "is", "returned", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/design_pattern.py#L25-L35
meyersj/geotweet
geotweet/mapreduce/metro_wordcount.py
MRMetroMongoWordCount.mapper_init
def mapper_init(self): """ build local spatial index of US metro areas """ self.lookup = CachedMetroLookup(precision=GEOHASH_PRECISION) self.extractor = WordExtractor()
python
def mapper_init(self): """ build local spatial index of US metro areas """ self.lookup = CachedMetroLookup(precision=GEOHASH_PRECISION) self.extractor = WordExtractor()
[ "def", "mapper_init", "(", "self", ")", ":", "self", ".", "lookup", "=", "CachedMetroLookup", "(", "precision", "=", "GEOHASH_PRECISION", ")", "self", ".", "extractor", "=", "WordExtractor", "(", ")" ]
build local spatial index of US metro areas
[ "build", "local", "spatial", "index", "of", "US", "metro", "areas" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/metro_wordcount.py#L96-L99
meyersj/geotweet
geotweet/mapreduce/metro_wordcount.py
MRMetroMongoWordCount.reducer_init_output
def reducer_init_output(self): """ establish connection to MongoDB """ try: self.mongo = MongoGeo(db=DB, collection=COLLECTION, timeout=MONGO_TIMEOUT) except ServerSelectionTimeoutError: # failed to connect to running MongoDB instance self.mongo = None
python
def reducer_init_output(self): """ establish connection to MongoDB """ try: self.mongo = MongoGeo(db=DB, collection=COLLECTION, timeout=MONGO_TIMEOUT) except ServerSelectionTimeoutError: # failed to connect to running MongoDB instance self.mongo = None
[ "def", "reducer_init_output", "(", "self", ")", ":", "try", ":", "self", ".", "mongo", "=", "MongoGeo", "(", "db", "=", "DB", ",", "collection", "=", "COLLECTION", ",", "timeout", "=", "MONGO_TIMEOUT", ")", "except", "ServerSelectionTimeoutError", ":", "# failed to connect to running MongoDB instance", "self", ".", "mongo", "=", "None" ]
establish connection to MongoDB
[ "establish", "connection", "to", "MongoDB" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/metro_wordcount.py#L124-L130
The-Politico/politico-civic-geography
geography/models/division.py
Division.save
def save(self, *args, **kwargs): """ **uid**: :code:`division:{parentuid}_{levelcode}-{code}` """ slug = "{}:{}".format(self.level.uid, self.code) if self.parent: self.uid = "{}_{}".format(self.parent.uid, slug) else: self.uid = slug self.slug = uuslug( self.name, instance=self, max_length=100, separator="-", start_no=2 ) super(Division, self).save(*args, **kwargs)
python
def save(self, *args, **kwargs): """ **uid**: :code:`division:{parentuid}_{levelcode}-{code}` """ slug = "{}:{}".format(self.level.uid, self.code) if self.parent: self.uid = "{}_{}".format(self.parent.uid, slug) else: self.uid = slug self.slug = uuslug( self.name, instance=self, max_length=100, separator="-", start_no=2 ) super(Division, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "slug", "=", "\"{}:{}\"", ".", "format", "(", "self", ".", "level", ".", "uid", ",", "self", ".", "code", ")", "if", "self", ".", "parent", ":", "self", ".", "uid", "=", "\"{}_{}\"", ".", "format", "(", "self", ".", "parent", ".", "uid", ",", "slug", ")", "else", ":", "self", ".", "uid", "=", "slug", "self", ".", "slug", "=", "uuslug", "(", "self", ".", "name", ",", "instance", "=", "self", ",", "max_length", "=", "100", ",", "separator", "=", "\"-\"", ",", "start_no", "=", "2", ")", "super", "(", "Division", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
**uid**: :code:`division:{parentuid}_{levelcode}-{code}`
[ "**", "uid", "**", ":", ":", "code", ":", "division", ":", "{", "parentuid", "}", "_", "{", "levelcode", "}", "-", "{", "code", "}" ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L70-L82
The-Politico/politico-civic-geography
geography/models/division.py
Division.add_intersecting
def add_intersecting(self, division, intersection=None, symm=True): """ Adds paired relationships between intersecting divisions. Optional intersection represents the portion of the area of the related division intersecting this division. You can only specify an intersection on one side of the relationship when adding a peer. """ relationship, created = IntersectRelationship.objects.update_or_create( from_division=self, to_division=division, defaults={"intersection": intersection}, ) if symm: division.add_intersecting(self, None, False) return relationship
python
def add_intersecting(self, division, intersection=None, symm=True): """ Adds paired relationships between intersecting divisions. Optional intersection represents the portion of the area of the related division intersecting this division. You can only specify an intersection on one side of the relationship when adding a peer. """ relationship, created = IntersectRelationship.objects.update_or_create( from_division=self, to_division=division, defaults={"intersection": intersection}, ) if symm: division.add_intersecting(self, None, False) return relationship
[ "def", "add_intersecting", "(", "self", ",", "division", ",", "intersection", "=", "None", ",", "symm", "=", "True", ")", ":", "relationship", ",", "created", "=", "IntersectRelationship", ".", "objects", ".", "update_or_create", "(", "from_division", "=", "self", ",", "to_division", "=", "division", ",", "defaults", "=", "{", "\"intersection\"", ":", "intersection", "}", ",", ")", "if", "symm", ":", "division", ".", "add_intersecting", "(", "self", ",", "None", ",", "False", ")", "return", "relationship" ]
Adds paired relationships between intersecting divisions. Optional intersection represents the portion of the area of the related division intersecting this division. You can only specify an intersection on one side of the relationship when adding a peer.
[ "Adds", "paired", "relationships", "between", "intersecting", "divisions", "." ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L84-L99
The-Politico/politico-civic-geography
geography/models/division.py
Division.remove_intersecting
def remove_intersecting(self, division, symm=True): """Removes paired relationships between intersecting divisions""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).delete() if symm: division.remove_intersecting(self, False)
python
def remove_intersecting(self, division, symm=True): """Removes paired relationships between intersecting divisions""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).delete() if symm: division.remove_intersecting(self, False)
[ "def", "remove_intersecting", "(", "self", ",", "division", ",", "symm", "=", "True", ")", ":", "IntersectRelationship", ".", "objects", ".", "filter", "(", "from_division", "=", "self", ",", "to_division", "=", "division", ")", ".", "delete", "(", ")", "if", "symm", ":", "division", ".", "remove_intersecting", "(", "self", ",", "False", ")" ]
Removes paired relationships between intersecting divisions
[ "Removes", "paired", "relationships", "between", "intersecting", "divisions" ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L101-L107
The-Politico/politico-civic-geography
geography/models/division.py
Division.set_intersection
def set_intersection(self, division, intersection): """Set intersection percentage of intersecting divisions.""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).update(intersection=intersection)
python
def set_intersection(self, division, intersection): """Set intersection percentage of intersecting divisions.""" IntersectRelationship.objects.filter( from_division=self, to_division=division ).update(intersection=intersection)
[ "def", "set_intersection", "(", "self", ",", "division", ",", "intersection", ")", ":", "IntersectRelationship", ".", "objects", ".", "filter", "(", "from_division", "=", "self", ",", "to_division", "=", "division", ")", ".", "update", "(", "intersection", "=", "intersection", ")" ]
Set intersection percentage of intersecting divisions.
[ "Set", "intersection", "percentage", "of", "intersecting", "divisions", "." ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L109-L113
The-Politico/politico-civic-geography
geography/models/division.py
Division.get_intersection
def get_intersection(self, division): """Get intersection percentage of intersecting divisions.""" try: return IntersectRelationship.objects.get( from_division=self, to_division=division ).intersection except ObjectDoesNotExist: raise Exception("No intersecting relationship with that division.")
python
def get_intersection(self, division): """Get intersection percentage of intersecting divisions.""" try: return IntersectRelationship.objects.get( from_division=self, to_division=division ).intersection except ObjectDoesNotExist: raise Exception("No intersecting relationship with that division.")
[ "def", "get_intersection", "(", "self", ",", "division", ")", ":", "try", ":", "return", "IntersectRelationship", ".", "objects", ".", "get", "(", "from_division", "=", "self", ",", "to_division", "=", "division", ")", ".", "intersection", "except", "ObjectDoesNotExist", ":", "raise", "Exception", "(", "\"No intersecting relationship with that division.\"", ")" ]
Get intersection percentage of intersecting divisions.
[ "Get", "intersection", "percentage", "of", "intersecting", "divisions", "." ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/division.py#L115-L122
RudolfCardinal/pythonlib
cardinal_pythonlib/slurm.py
launch_slurm
def launch_slurm(jobname: str, cmd: str, memory_mb: int, project: str, qos: str, email: str, duration: timedelta, tasks_per_node: int, cpus_per_task: int, partition: str = "", modules: List[str] = None, directory: str = os.getcwd(), encoding: str = "ascii") -> None: """ Launch a job into the SLURM environment. Args: jobname: name of the job cmd: command to be executed memory_mb: maximum memory requirement per process (Mb) project: project name qos: quality-of-service name email: user's e-mail address duration: maximum duration per job tasks_per_node: tasks per (cluster) node cpus_per_task: CPUs per task partition: cluster partition name modules: SLURM modules to load directory: directory to change to encoding: encoding to apply to launch script as sent to ``sbatch`` """ if partition: partition_cmd = "#SBATCH -p {}".format(partition) else: partition_cmd = "" if modules is None: modules = ["default-wbic"] log.info("Launching SLURM job: {}", jobname) script = """#!/bin/bash #! Name of the job: #SBATCH -J {jobname} #! Which project should jobs run under: #SBATCH -A {project} #! What QoS [Quality of Service] should the job run in? #SBATCH --qos={qos} #! How much resource should be allocated? #SBATCH --tasks-per-node={tasks_per_node} #SBATCH --cpus-per-task={cpus_per_task} #! Memory requirements #SBATCH --mem={memory_mb} #! How much wall-clock time will be required? #SBATCH --time={duration} #! What e-mail address to use for notifications? #SBATCH --mail-user={email} #! What types of email messages do you wish to receive? #SBATCH --mail-type=ALL #! Uncomment this to prevent the job from being requeued (e.g. if #! interrupted by node failure or system downtime): #! SBATCH --no-requeue #! Partition {partition_cmd} #! sbatch directives end here (put any additional directives above this line) #! ############################################################ #! Modify the settings below to specify the application's environment, location #! and launch method: #! Optionally modify the environment seen by the application #! (note that SLURM reproduces the environment at submission irrespective of ~/.bashrc): . /etc/profile.d/modules.sh # Leave this line (enables the module command) module purge # Removes all modules still loaded module load {modules} # Basic one, e.g. default-wbic, is REQUIRED - loads the basic environment #! Insert additional module load commands after this line if needed: #! Full path to your application executable: application="hostname" #! Run options for the application: options="" #! Work directory (i.e. where the job will run): workdir="$SLURM_SUBMIT_DIR" # The value of SLURM_SUBMIT_DIR sets workdir to the directory # in which sbatch is run. #! Are you using OpenMP (NB this is **unrelated to OpenMPI**)? If so increase this #! safe value to no more than 24: export OMP_NUM_THREADS=24 # Command line to be submited by SLURM: CMD="{cmd}" ############################################################### ### You should not have to change anything below this line #### ############################################################### cd $workdir echo -e "Changed directory to `pwd`.\n" JOBID=$SLURM_JOB_ID echo -e "JobID: $JOBID\n======" echo "Time: `date`" echo "Running on master node: `hostname`" echo "Current directory: `pwd`" if [ "$SLURM_JOB_NODELIST" ]; then #! Create a machine file: export NODEFILE=`/usr/bin/generate_pbs_nodefile` cat $NODEFILE | uniq > machine.file.$JOBID echo -e "\nNodes allocated:\n================" echo `cat machine.file.$JOBID | sed -e 's/\..*$//g'` fi echo -e "\nExecuting command:\n==================\n$CMD\n" eval $CMD """.format( # noqa cmd=cmd, cpus_per_task=cpus_per_task, duration=strfdelta(duration, SLURM_TIMEDELTA_FMT), email=email, jobname=jobname, memory_mb=memory_mb, modules=" ".join(modules), partition_cmd=partition_cmd, project=project, qos=qos, tasks_per_node=tasks_per_node, ) cmdargs = ["sbatch"] with pushd(directory): p = Popen(cmdargs, stdin=PIPE) p.communicate(input=script.encode(encoding))
python
def launch_slurm(jobname: str, cmd: str, memory_mb: int, project: str, qos: str, email: str, duration: timedelta, tasks_per_node: int, cpus_per_task: int, partition: str = "", modules: List[str] = None, directory: str = os.getcwd(), encoding: str = "ascii") -> None: """ Launch a job into the SLURM environment. Args: jobname: name of the job cmd: command to be executed memory_mb: maximum memory requirement per process (Mb) project: project name qos: quality-of-service name email: user's e-mail address duration: maximum duration per job tasks_per_node: tasks per (cluster) node cpus_per_task: CPUs per task partition: cluster partition name modules: SLURM modules to load directory: directory to change to encoding: encoding to apply to launch script as sent to ``sbatch`` """ if partition: partition_cmd = "#SBATCH -p {}".format(partition) else: partition_cmd = "" if modules is None: modules = ["default-wbic"] log.info("Launching SLURM job: {}", jobname) script = """#!/bin/bash #! Name of the job: #SBATCH -J {jobname} #! Which project should jobs run under: #SBATCH -A {project} #! What QoS [Quality of Service] should the job run in? #SBATCH --qos={qos} #! How much resource should be allocated? #SBATCH --tasks-per-node={tasks_per_node} #SBATCH --cpus-per-task={cpus_per_task} #! Memory requirements #SBATCH --mem={memory_mb} #! How much wall-clock time will be required? #SBATCH --time={duration} #! What e-mail address to use for notifications? #SBATCH --mail-user={email} #! What types of email messages do you wish to receive? #SBATCH --mail-type=ALL #! Uncomment this to prevent the job from being requeued (e.g. if #! interrupted by node failure or system downtime): #! SBATCH --no-requeue #! Partition {partition_cmd} #! sbatch directives end here (put any additional directives above this line) #! ############################################################ #! Modify the settings below to specify the application's environment, location #! and launch method: #! Optionally modify the environment seen by the application #! (note that SLURM reproduces the environment at submission irrespective of ~/.bashrc): . /etc/profile.d/modules.sh # Leave this line (enables the module command) module purge # Removes all modules still loaded module load {modules} # Basic one, e.g. default-wbic, is REQUIRED - loads the basic environment #! Insert additional module load commands after this line if needed: #! Full path to your application executable: application="hostname" #! Run options for the application: options="" #! Work directory (i.e. where the job will run): workdir="$SLURM_SUBMIT_DIR" # The value of SLURM_SUBMIT_DIR sets workdir to the directory # in which sbatch is run. #! Are you using OpenMP (NB this is **unrelated to OpenMPI**)? If so increase this #! safe value to no more than 24: export OMP_NUM_THREADS=24 # Command line to be submited by SLURM: CMD="{cmd}" ############################################################### ### You should not have to change anything below this line #### ############################################################### cd $workdir echo -e "Changed directory to `pwd`.\n" JOBID=$SLURM_JOB_ID echo -e "JobID: $JOBID\n======" echo "Time: `date`" echo "Running on master node: `hostname`" echo "Current directory: `pwd`" if [ "$SLURM_JOB_NODELIST" ]; then #! Create a machine file: export NODEFILE=`/usr/bin/generate_pbs_nodefile` cat $NODEFILE | uniq > machine.file.$JOBID echo -e "\nNodes allocated:\n================" echo `cat machine.file.$JOBID | sed -e 's/\..*$//g'` fi echo -e "\nExecuting command:\n==================\n$CMD\n" eval $CMD """.format( # noqa cmd=cmd, cpus_per_task=cpus_per_task, duration=strfdelta(duration, SLURM_TIMEDELTA_FMT), email=email, jobname=jobname, memory_mb=memory_mb, modules=" ".join(modules), partition_cmd=partition_cmd, project=project, qos=qos, tasks_per_node=tasks_per_node, ) cmdargs = ["sbatch"] with pushd(directory): p = Popen(cmdargs, stdin=PIPE) p.communicate(input=script.encode(encoding))
[ "def", "launch_slurm", "(", "jobname", ":", "str", ",", "cmd", ":", "str", ",", "memory_mb", ":", "int", ",", "project", ":", "str", ",", "qos", ":", "str", ",", "email", ":", "str", ",", "duration", ":", "timedelta", ",", "tasks_per_node", ":", "int", ",", "cpus_per_task", ":", "int", ",", "partition", ":", "str", "=", "\"\"", ",", "modules", ":", "List", "[", "str", "]", "=", "None", ",", "directory", ":", "str", "=", "os", ".", "getcwd", "(", ")", ",", "encoding", ":", "str", "=", "\"ascii\"", ")", "->", "None", ":", "if", "partition", ":", "partition_cmd", "=", "\"#SBATCH -p {}\"", ".", "format", "(", "partition", ")", "else", ":", "partition_cmd", "=", "\"\"", "if", "modules", "is", "None", ":", "modules", "=", "[", "\"default-wbic\"", "]", "log", ".", "info", "(", "\"Launching SLURM job: {}\"", ",", "jobname", ")", "script", "=", "\"\"\"#!/bin/bash\n\n#! Name of the job:\n#SBATCH -J {jobname}\n\n#! Which project should jobs run under:\n#SBATCH -A {project}\n\n#! What QoS [Quality of Service] should the job run in?\n#SBATCH --qos={qos}\n\n#! How much resource should be allocated?\n#SBATCH --tasks-per-node={tasks_per_node}\n#SBATCH --cpus-per-task={cpus_per_task}\n\n#! Memory requirements\n#SBATCH --mem={memory_mb}\n\n#! How much wall-clock time will be required?\n#SBATCH --time={duration}\n\n#! What e-mail address to use for notifications?\n#SBATCH --mail-user={email}\n\n#! What types of email messages do you wish to receive?\n#SBATCH --mail-type=ALL\n\n#! Uncomment this to prevent the job from being requeued (e.g. if\n#! interrupted by node failure or system downtime):\n#! SBATCH --no-requeue\n\n#! Partition\n{partition_cmd}\n\n#! sbatch directives end here (put any additional directives above this line)\n\n#! ############################################################\n#! Modify the settings below to specify the application's environment, location\n#! and launch method:\n\n#! Optionally modify the environment seen by the application\n#! (note that SLURM reproduces the environment at submission irrespective of ~/.bashrc):\n. /etc/profile.d/modules.sh # Leave this line (enables the module command)\nmodule purge # Removes all modules still loaded\nmodule load {modules} # Basic one, e.g. default-wbic, is REQUIRED - loads the basic environment\n\n#! Insert additional module load commands after this line if needed:\n\n#! Full path to your application executable:\napplication=\"hostname\"\n\n#! Run options for the application:\noptions=\"\"\n\n#! Work directory (i.e. where the job will run):\nworkdir=\"$SLURM_SUBMIT_DIR\" # The value of SLURM_SUBMIT_DIR sets workdir to the directory\n # in which sbatch is run.\n\n#! Are you using OpenMP (NB this is **unrelated to OpenMPI**)? If so increase this\n#! safe value to no more than 24:\nexport OMP_NUM_THREADS=24\n\n# Command line to be submited by SLURM:\nCMD=\"{cmd}\"\n\n###############################################################\n### You should not have to change anything below this line ####\n###############################################################\n\ncd $workdir\necho -e \"Changed directory to `pwd`.\\n\"\n\nJOBID=$SLURM_JOB_ID\n\necho -e \"JobID: $JOBID\\n======\"\necho \"Time: `date`\"\necho \"Running on master node: `hostname`\"\necho \"Current directory: `pwd`\"\n\nif [ \"$SLURM_JOB_NODELIST\" ]; then\n #! Create a machine file:\n export NODEFILE=`/usr/bin/generate_pbs_nodefile`\n cat $NODEFILE | uniq > machine.file.$JOBID\n echo -e \"\\nNodes allocated:\\n================\"\n echo `cat machine.file.$JOBID | sed -e 's/\\..*$//g'`\nfi\n\necho -e \"\\nExecuting command:\\n==================\\n$CMD\\n\"\n\neval $CMD\n \"\"\"", ".", "format", "(", "# noqa", "cmd", "=", "cmd", ",", "cpus_per_task", "=", "cpus_per_task", ",", "duration", "=", "strfdelta", "(", "duration", ",", "SLURM_TIMEDELTA_FMT", ")", ",", "email", "=", "email", ",", "jobname", "=", "jobname", ",", "memory_mb", "=", "memory_mb", ",", "modules", "=", "\" \"", ".", "join", "(", "modules", ")", ",", "partition_cmd", "=", "partition_cmd", ",", "project", "=", "project", ",", "qos", "=", "qos", ",", "tasks_per_node", "=", "tasks_per_node", ",", ")", "cmdargs", "=", "[", "\"sbatch\"", "]", "with", "pushd", "(", "directory", ")", ":", "p", "=", "Popen", "(", "cmdargs", ",", "stdin", "=", "PIPE", ")", "p", ".", "communicate", "(", "input", "=", "script", ".", "encode", "(", "encoding", ")", ")" ]
Launch a job into the SLURM environment. Args: jobname: name of the job cmd: command to be executed memory_mb: maximum memory requirement per process (Mb) project: project name qos: quality-of-service name email: user's e-mail address duration: maximum duration per job tasks_per_node: tasks per (cluster) node cpus_per_task: CPUs per task partition: cluster partition name modules: SLURM modules to load directory: directory to change to encoding: encoding to apply to launch script as sent to ``sbatch``
[ "Launch", "a", "job", "into", "the", "SLURM", "environment", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/slurm.py#L66-L211
RudolfCardinal/pythonlib
cardinal_pythonlib/slurm.py
launch_cambridge_hphi
def launch_cambridge_hphi( jobname: str, cmd: str, memory_mb: int, qos: str, email: str, duration: timedelta, cpus_per_task: int, project: str = "hphi", tasks_per_node: int = 1, partition: str = "wbic-cs", # 2018-02: was "wbic", now "wbic-cs" modules: List[str] = None, directory: str = os.getcwd(), encoding: str = "ascii") -> None: """ Specialization of :func:`launch_slurm` (q.v.) with defaults for the University of Cambridge WBIC HPHI. """ if modules is None: modules = ["default-wbic"] launch_slurm( cmd=cmd, cpus_per_task=cpus_per_task, directory=directory, duration=duration, email=email, encoding=encoding, jobname=jobname, memory_mb=memory_mb, modules=modules, partition=partition, project=project, qos=qos, tasks_per_node=tasks_per_node, )
python
def launch_cambridge_hphi( jobname: str, cmd: str, memory_mb: int, qos: str, email: str, duration: timedelta, cpus_per_task: int, project: str = "hphi", tasks_per_node: int = 1, partition: str = "wbic-cs", # 2018-02: was "wbic", now "wbic-cs" modules: List[str] = None, directory: str = os.getcwd(), encoding: str = "ascii") -> None: """ Specialization of :func:`launch_slurm` (q.v.) with defaults for the University of Cambridge WBIC HPHI. """ if modules is None: modules = ["default-wbic"] launch_slurm( cmd=cmd, cpus_per_task=cpus_per_task, directory=directory, duration=duration, email=email, encoding=encoding, jobname=jobname, memory_mb=memory_mb, modules=modules, partition=partition, project=project, qos=qos, tasks_per_node=tasks_per_node, )
[ "def", "launch_cambridge_hphi", "(", "jobname", ":", "str", ",", "cmd", ":", "str", ",", "memory_mb", ":", "int", ",", "qos", ":", "str", ",", "email", ":", "str", ",", "duration", ":", "timedelta", ",", "cpus_per_task", ":", "int", ",", "project", ":", "str", "=", "\"hphi\"", ",", "tasks_per_node", ":", "int", "=", "1", ",", "partition", ":", "str", "=", "\"wbic-cs\"", ",", "# 2018-02: was \"wbic\", now \"wbic-cs\"", "modules", ":", "List", "[", "str", "]", "=", "None", ",", "directory", ":", "str", "=", "os", ".", "getcwd", "(", ")", ",", "encoding", ":", "str", "=", "\"ascii\"", ")", "->", "None", ":", "if", "modules", "is", "None", ":", "modules", "=", "[", "\"default-wbic\"", "]", "launch_slurm", "(", "cmd", "=", "cmd", ",", "cpus_per_task", "=", "cpus_per_task", ",", "directory", "=", "directory", ",", "duration", "=", "duration", ",", "email", "=", "email", ",", "encoding", "=", "encoding", ",", "jobname", "=", "jobname", ",", "memory_mb", "=", "memory_mb", ",", "modules", "=", "modules", ",", "partition", "=", "partition", ",", "project", "=", "project", ",", "qos", "=", "qos", ",", "tasks_per_node", "=", "tasks_per_node", ",", ")" ]
Specialization of :func:`launch_slurm` (q.v.) with defaults for the University of Cambridge WBIC HPHI.
[ "Specialization", "of", ":", "func", ":", "launch_slurm", "(", "q", ".", "v", ".", ")", "with", "defaults", "for", "the", "University", "of", "Cambridge", "WBIC", "HPHI", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/slurm.py#L214-L248
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
get_drug
def get_drug(drug_name: str, name_is_generic: bool = False, include_categories: bool = False) -> Optional[Drug]: """ Converts a drug name to a :class:`.Drug` class. If you already have the generic name, you can get the Drug more efficiently by setting ``name_is_generic=True``. Set ``include_categories=True`` to include drug categories (such as tricyclics) as well as individual drugs. """ drug_name = drug_name.strip().lower() if name_is_generic: drug = DRUGS_BY_GENERIC_NAME.get(drug_name) # type: Optional[Drug] if drug is not None and drug.category_not_drug and not include_categories: # noqa return None return drug else: for d in DRUGS: if d.name_matches(drug_name): return d return None
python
def get_drug(drug_name: str, name_is_generic: bool = False, include_categories: bool = False) -> Optional[Drug]: """ Converts a drug name to a :class:`.Drug` class. If you already have the generic name, you can get the Drug more efficiently by setting ``name_is_generic=True``. Set ``include_categories=True`` to include drug categories (such as tricyclics) as well as individual drugs. """ drug_name = drug_name.strip().lower() if name_is_generic: drug = DRUGS_BY_GENERIC_NAME.get(drug_name) # type: Optional[Drug] if drug is not None and drug.category_not_drug and not include_categories: # noqa return None return drug else: for d in DRUGS: if d.name_matches(drug_name): return d return None
[ "def", "get_drug", "(", "drug_name", ":", "str", ",", "name_is_generic", ":", "bool", "=", "False", ",", "include_categories", ":", "bool", "=", "False", ")", "->", "Optional", "[", "Drug", "]", ":", "drug_name", "=", "drug_name", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "name_is_generic", ":", "drug", "=", "DRUGS_BY_GENERIC_NAME", ".", "get", "(", "drug_name", ")", "# type: Optional[Drug]", "if", "drug", "is", "not", "None", "and", "drug", ".", "category_not_drug", "and", "not", "include_categories", ":", "# noqa", "return", "None", "return", "drug", "else", ":", "for", "d", "in", "DRUGS", ":", "if", "d", ".", "name_matches", "(", "drug_name", ")", ":", "return", "d", "return", "None" ]
Converts a drug name to a :class:`.Drug` class. If you already have the generic name, you can get the Drug more efficiently by setting ``name_is_generic=True``. Set ``include_categories=True`` to include drug categories (such as tricyclics) as well as individual drugs.
[ "Converts", "a", "drug", "name", "to", "a", ":", "class", ":", ".", "Drug", "class", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1295-L1317
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
drug_name_to_generic
def drug_name_to_generic(drug_name: str, unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> str: """ Converts a drug name to the name of its generic equivalent. """ drug = get_drug(drug_name, include_categories=include_categories) if drug is not None: return drug.generic_name return default if unknown_to_default else drug_name
python
def drug_name_to_generic(drug_name: str, unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> str: """ Converts a drug name to the name of its generic equivalent. """ drug = get_drug(drug_name, include_categories=include_categories) if drug is not None: return drug.generic_name return default if unknown_to_default else drug_name
[ "def", "drug_name_to_generic", "(", "drug_name", ":", "str", ",", "unknown_to_default", ":", "bool", "=", "False", ",", "default", ":", "str", "=", "None", ",", "include_categories", ":", "bool", "=", "False", ")", "->", "str", ":", "drug", "=", "get_drug", "(", "drug_name", ",", "include_categories", "=", "include_categories", ")", "if", "drug", "is", "not", "None", ":", "return", "drug", ".", "generic_name", "return", "default", "if", "unknown_to_default", "else", "drug_name" ]
Converts a drug name to the name of its generic equivalent.
[ "Converts", "a", "drug", "name", "to", "the", "name", "of", "its", "generic", "equivalent", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1324-L1334
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
drug_names_to_generic
def drug_names_to_generic(drugs: List[str], unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> List[str]: """ Converts a list of drug names to their generic equivalents. The arguments are as for :func:`drug_name_to_generic` but this function handles a list of drug names rather than a single one. Note in passing the following conversion of blank-type representations from R via ``reticulate``, when using e.g. the ``default`` parameter and storing results in a ``data.table()`` character column: .. code-block:: none ------------------------------ ---------------- To Python Back from Python ------------------------------ ---------------- [not passed, so Python None] "NULL" NULL "NULL" NA_character_ "NA" NA TRUE (logical) ------------------------------ ---------------- """ return [ drug_name_to_generic(drug, unknown_to_default=unknown_to_default, default=default, include_categories=include_categories) for drug in drugs ]
python
def drug_names_to_generic(drugs: List[str], unknown_to_default: bool = False, default: str = None, include_categories: bool = False) -> List[str]: """ Converts a list of drug names to their generic equivalents. The arguments are as for :func:`drug_name_to_generic` but this function handles a list of drug names rather than a single one. Note in passing the following conversion of blank-type representations from R via ``reticulate``, when using e.g. the ``default`` parameter and storing results in a ``data.table()`` character column: .. code-block:: none ------------------------------ ---------------- To Python Back from Python ------------------------------ ---------------- [not passed, so Python None] "NULL" NULL "NULL" NA_character_ "NA" NA TRUE (logical) ------------------------------ ---------------- """ return [ drug_name_to_generic(drug, unknown_to_default=unknown_to_default, default=default, include_categories=include_categories) for drug in drugs ]
[ "def", "drug_names_to_generic", "(", "drugs", ":", "List", "[", "str", "]", ",", "unknown_to_default", ":", "bool", "=", "False", ",", "default", ":", "str", "=", "None", ",", "include_categories", ":", "bool", "=", "False", ")", "->", "List", "[", "str", "]", ":", "return", "[", "drug_name_to_generic", "(", "drug", ",", "unknown_to_default", "=", "unknown_to_default", ",", "default", "=", "default", ",", "include_categories", "=", "include_categories", ")", "for", "drug", "in", "drugs", "]" ]
Converts a list of drug names to their generic equivalents. The arguments are as for :func:`drug_name_to_generic` but this function handles a list of drug names rather than a single one. Note in passing the following conversion of blank-type representations from R via ``reticulate``, when using e.g. the ``default`` parameter and storing results in a ``data.table()`` character column: .. code-block:: none ------------------------------ ---------------- To Python Back from Python ------------------------------ ---------------- [not passed, so Python None] "NULL" NULL "NULL" NA_character_ "NA" NA TRUE (logical) ------------------------------ ----------------
[ "Converts", "a", "list", "of", "drug", "names", "to", "their", "generic", "equivalents", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1337-L1369
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
drug_matches_criteria
def drug_matches_criteria(drug: Drug, **criteria: Dict[str, bool]) -> bool: """ Determines whether a drug, passed as an instance of :class:`.Drug`, matches the specified criteria. Args: drug: a :class:`.Drug` instance criteria: ``name=value`` pairs to match against the attributes of the :class:`Drug` class. For example, you can include keyword arguments like ``antidepressant=True``. """ for attribute, value in criteria.items(): if getattr(drug, attribute) != value: return False return True
python
def drug_matches_criteria(drug: Drug, **criteria: Dict[str, bool]) -> bool: """ Determines whether a drug, passed as an instance of :class:`.Drug`, matches the specified criteria. Args: drug: a :class:`.Drug` instance criteria: ``name=value`` pairs to match against the attributes of the :class:`Drug` class. For example, you can include keyword arguments like ``antidepressant=True``. """ for attribute, value in criteria.items(): if getattr(drug, attribute) != value: return False return True
[ "def", "drug_matches_criteria", "(", "drug", ":", "Drug", ",", "*", "*", "criteria", ":", "Dict", "[", "str", ",", "bool", "]", ")", "->", "bool", ":", "for", "attribute", ",", "value", "in", "criteria", ".", "items", "(", ")", ":", "if", "getattr", "(", "drug", ",", "attribute", ")", "!=", "value", ":", "return", "False", "return", "True" ]
Determines whether a drug, passed as an instance of :class:`.Drug`, matches the specified criteria. Args: drug: a :class:`.Drug` instance criteria: ``name=value`` pairs to match against the attributes of the :class:`Drug` class. For example, you can include keyword arguments like ``antidepressant=True``.
[ "Determines", "whether", "a", "drug", "passed", "as", "an", "instance", "of", ":", "class", ":", ".", "Drug", "matches", "the", "specified", "criteria", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1376-L1390
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
all_drugs_where
def all_drugs_where(sort=True, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[Drug]: """ Find all drugs matching the specified criteria (see :func:`drug_matches_criteria`). If ``include_categories`` is true, then drug categories (like "tricyclics") are included as well as individual drugs. Pass keyword arguments such as .. code-block:: python from cardinal_pythonlib.psychiatry.drugs import * non_ssri_antidep = all_drugs_where(antidepressant=True, ssri=False) print([d.generic_name for d in non_ssri_antidep]) conventional_antidep = all_drugs_where(conventional_antidepressant=True) print([d.generic_name for d in conventional_antidep]) """ matching_drugs = [] # type: List[Drug] for drug in DRUGS: if drug.category_not_drug and not include_categories: continue if drug_matches_criteria(drug, **criteria): matching_drugs.append(drug) if sort: matching_drugs.sort(key=lambda d: d.generic_name) return matching_drugs
python
def all_drugs_where(sort=True, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[Drug]: """ Find all drugs matching the specified criteria (see :func:`drug_matches_criteria`). If ``include_categories`` is true, then drug categories (like "tricyclics") are included as well as individual drugs. Pass keyword arguments such as .. code-block:: python from cardinal_pythonlib.psychiatry.drugs import * non_ssri_antidep = all_drugs_where(antidepressant=True, ssri=False) print([d.generic_name for d in non_ssri_antidep]) conventional_antidep = all_drugs_where(conventional_antidepressant=True) print([d.generic_name for d in conventional_antidep]) """ matching_drugs = [] # type: List[Drug] for drug in DRUGS: if drug.category_not_drug and not include_categories: continue if drug_matches_criteria(drug, **criteria): matching_drugs.append(drug) if sort: matching_drugs.sort(key=lambda d: d.generic_name) return matching_drugs
[ "def", "all_drugs_where", "(", "sort", "=", "True", ",", "include_categories", ":", "bool", "=", "False", ",", "*", "*", "criteria", ":", "Dict", "[", "str", ",", "bool", "]", ")", "->", "List", "[", "Drug", "]", ":", "matching_drugs", "=", "[", "]", "# type: List[Drug]", "for", "drug", "in", "DRUGS", ":", "if", "drug", ".", "category_not_drug", "and", "not", "include_categories", ":", "continue", "if", "drug_matches_criteria", "(", "drug", ",", "*", "*", "criteria", ")", ":", "matching_drugs", ".", "append", "(", "drug", ")", "if", "sort", ":", "matching_drugs", ".", "sort", "(", "key", "=", "lambda", "d", ":", "d", ".", "generic_name", ")", "return", "matching_drugs" ]
Find all drugs matching the specified criteria (see :func:`drug_matches_criteria`). If ``include_categories`` is true, then drug categories (like "tricyclics") are included as well as individual drugs. Pass keyword arguments such as .. code-block:: python from cardinal_pythonlib.psychiatry.drugs import * non_ssri_antidep = all_drugs_where(antidepressant=True, ssri=False) print([d.generic_name for d in non_ssri_antidep]) conventional_antidep = all_drugs_where(conventional_antidepressant=True) print([d.generic_name for d in conventional_antidep])
[ "Find", "all", "drugs", "matching", "the", "specified", "criteria", "(", "see", ":", "func", ":", "drug_matches_criteria", ")", ".", "If", "include_categories", "is", "true", "then", "drug", "categories", "(", "like", "tricyclics", ")", "are", "included", "as", "well", "as", "individual", "drugs", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1393-L1420
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
drug_name_matches_criteria
def drug_name_matches_criteria(drug_name: str, name_is_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> bool: """ Establish whether a single drug, passed by name, matches the specified criteria. See :func:`drug_matches_criteria`. """ drug = get_drug(drug_name, name_is_generic) if drug is None: return False if drug.category_not_drug and not include_categories: return False return drug_matches_criteria(drug, **criteria)
python
def drug_name_matches_criteria(drug_name: str, name_is_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> bool: """ Establish whether a single drug, passed by name, matches the specified criteria. See :func:`drug_matches_criteria`. """ drug = get_drug(drug_name, name_is_generic) if drug is None: return False if drug.category_not_drug and not include_categories: return False return drug_matches_criteria(drug, **criteria)
[ "def", "drug_name_matches_criteria", "(", "drug_name", ":", "str", ",", "name_is_generic", ":", "bool", "=", "False", ",", "include_categories", ":", "bool", "=", "False", ",", "*", "*", "criteria", ":", "Dict", "[", "str", ",", "bool", "]", ")", "->", "bool", ":", "drug", "=", "get_drug", "(", "drug_name", ",", "name_is_generic", ")", "if", "drug", "is", "None", ":", "return", "False", "if", "drug", ".", "category_not_drug", "and", "not", "include_categories", ":", "return", "False", "return", "drug_matches_criteria", "(", "drug", ",", "*", "*", "criteria", ")" ]
Establish whether a single drug, passed by name, matches the specified criteria. See :func:`drug_matches_criteria`.
[ "Establish", "whether", "a", "single", "drug", "passed", "by", "name", "matches", "the", "specified", "criteria", ".", "See", ":", "func", ":", "drug_matches_criteria", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1423-L1436
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
drug_names_match_criteria
def drug_names_match_criteria(drug_names: List[str], names_are_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[bool]: """ Establish whether multiple drugs, passed as a list of drug names, each matches the specified criteria. See :func:`drug_matches_criteria`. """ return [ drug_name_matches_criteria( dn, name_is_generic=names_are_generic, include_categories=include_categories, **criteria) for dn in drug_names ]
python
def drug_names_match_criteria(drug_names: List[str], names_are_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[bool]: """ Establish whether multiple drugs, passed as a list of drug names, each matches the specified criteria. See :func:`drug_matches_criteria`. """ return [ drug_name_matches_criteria( dn, name_is_generic=names_are_generic, include_categories=include_categories, **criteria) for dn in drug_names ]
[ "def", "drug_names_match_criteria", "(", "drug_names", ":", "List", "[", "str", "]", ",", "names_are_generic", ":", "bool", "=", "False", ",", "include_categories", ":", "bool", "=", "False", ",", "*", "*", "criteria", ":", "Dict", "[", "str", ",", "bool", "]", ")", "->", "List", "[", "bool", "]", ":", "return", "[", "drug_name_matches_criteria", "(", "dn", ",", "name_is_generic", "=", "names_are_generic", ",", "include_categories", "=", "include_categories", ",", "*", "*", "criteria", ")", "for", "dn", "in", "drug_names", "]" ]
Establish whether multiple drugs, passed as a list of drug names, each matches the specified criteria. See :func:`drug_matches_criteria`.
[ "Establish", "whether", "multiple", "drugs", "passed", "as", "a", "list", "of", "drug", "names", "each", "matches", "the", "specified", "criteria", ".", "See", ":", "func", ":", "drug_matches_criteria", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L1439-L1454
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.regex_text
def regex_text(self) -> str: """ Return regex text (yet to be compiled) for this drug. """ if self._regex_text is None: possibilities = [] # type: List[str] for p in list(set(self.all_generics + self.alternatives)): if self.add_preceding_word_boundary and not p.startswith(WB): p = WB + p if self.add_preceding_wildcards and not p.startswith(WILDCARD): p = WILDCARD + p if self.add_following_wildcards and not p.endswith(WILDCARD): p = p + WILDCARD possibilities.append(p) self._regex_text = "|".join("(?:" + x + ")" for x in possibilities) return self._regex_text
python
def regex_text(self) -> str: """ Return regex text (yet to be compiled) for this drug. """ if self._regex_text is None: possibilities = [] # type: List[str] for p in list(set(self.all_generics + self.alternatives)): if self.add_preceding_word_boundary and not p.startswith(WB): p = WB + p if self.add_preceding_wildcards and not p.startswith(WILDCARD): p = WILDCARD + p if self.add_following_wildcards and not p.endswith(WILDCARD): p = p + WILDCARD possibilities.append(p) self._regex_text = "|".join("(?:" + x + ")" for x in possibilities) return self._regex_text
[ "def", "regex_text", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_regex_text", "is", "None", ":", "possibilities", "=", "[", "]", "# type: List[str]", "for", "p", "in", "list", "(", "set", "(", "self", ".", "all_generics", "+", "self", ".", "alternatives", ")", ")", ":", "if", "self", ".", "add_preceding_word_boundary", "and", "not", "p", ".", "startswith", "(", "WB", ")", ":", "p", "=", "WB", "+", "p", "if", "self", ".", "add_preceding_wildcards", "and", "not", "p", ".", "startswith", "(", "WILDCARD", ")", ":", "p", "=", "WILDCARD", "+", "p", "if", "self", ".", "add_following_wildcards", "and", "not", "p", ".", "endswith", "(", "WILDCARD", ")", ":", "p", "=", "p", "+", "WILDCARD", "possibilities", ".", "append", "(", "p", ")", "self", ".", "_regex_text", "=", "\"|\"", ".", "join", "(", "\"(?:\"", "+", "x", "+", "\")\"", "for", "x", "in", "possibilities", ")", "return", "self", ".", "_regex_text" ]
Return regex text (yet to be compiled) for this drug.
[ "Return", "regex", "text", "(", "yet", "to", "be", "compiled", ")", "for", "this", "drug", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L501-L516
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.regex
def regex(self) -> Pattern: """ Returns a compiled regex for this drug. """ if self._regex is None: self._regex = re.compile(self.regex_text, re.IGNORECASE | re.DOTALL) return self._regex
python
def regex(self) -> Pattern: """ Returns a compiled regex for this drug. """ if self._regex is None: self._regex = re.compile(self.regex_text, re.IGNORECASE | re.DOTALL) return self._regex
[ "def", "regex", "(", "self", ")", "->", "Pattern", ":", "if", "self", ".", "_regex", "is", "None", ":", "self", ".", "_regex", "=", "re", ".", "compile", "(", "self", ".", "regex_text", ",", "re", ".", "IGNORECASE", "|", "re", ".", "DOTALL", ")", "return", "self", ".", "_regex" ]
Returns a compiled regex for this drug.
[ "Returns", "a", "compiled", "regex", "for", "this", "drug", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L519-L526
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.regex_to_sql_like
def regex_to_sql_like(regex_text: str, single_wildcard: str = "_", zero_or_more_wildcard: str = "%") -> List[str]: """ Converts regular expression text to a reasonably close fragment for the SQL ``LIKE`` operator. NOT PERFECT, but works for current built-in regular expressions. Args: regex_text: regular expression text to work with single_wildcard: SQL single wildcard, typically an underscore zero_or_more_wildcard: SQL "zero/one/many" wildcard, probably always a percent symbol Returns: string for an SQL string literal Raises: :exc:`ValueError` for some regex text that it doesn't understand properly """ def append_to_all(new_content: str) -> None: nonlocal results results = [r + new_content for r in results] def split_and_append(new_options: List[str]) -> None: nonlocal results newresults = [] # type: List[str] for option in new_options: newresults.extend([r + option for r in results]) results = newresults def deduplicate_wildcards(text: str) -> str: while zero_or_more_wildcard + zero_or_more_wildcard in text: text = text.replace( zero_or_more_wildcard + zero_or_more_wildcard, zero_or_more_wildcard) return text # Basic processing working = regex_text # strings are immutable results = [zero_or_more_wildcard] # start with a wildcard while working: if working.startswith(".*"): # e.g. ".*ozapi" append_to_all(zero_or_more_wildcard) working = working[2:] elif working.startswith("["): # e.g. "[io]peridol" close_bracket = working.index("]") # may raise bracketed = working[1:close_bracket] option_groups = bracketed.split("|") options = [c for group in option_groups for c in group] split_and_append(options) working = working[close_bracket + 1:] elif len(working) > 1 and working[1] == "?": # e.g. "r?azole" split_and_append(["", working[0]]) # ... regex "optional character" # ... SQL: some results with a single wildcard, some without working = working[2:] elif working.startswith("."): # single character wildcard append_to_all(single_wildcard) working = working[1:] else: append_to_all(working[0]) working = working[1:] append_to_all(zero_or_more_wildcard) # end with a wildcard # Remove any duplicate (consecutive) % wildcards: results = [deduplicate_wildcards(r) for r in results] # Done return results
python
def regex_to_sql_like(regex_text: str, single_wildcard: str = "_", zero_or_more_wildcard: str = "%") -> List[str]: """ Converts regular expression text to a reasonably close fragment for the SQL ``LIKE`` operator. NOT PERFECT, but works for current built-in regular expressions. Args: regex_text: regular expression text to work with single_wildcard: SQL single wildcard, typically an underscore zero_or_more_wildcard: SQL "zero/one/many" wildcard, probably always a percent symbol Returns: string for an SQL string literal Raises: :exc:`ValueError` for some regex text that it doesn't understand properly """ def append_to_all(new_content: str) -> None: nonlocal results results = [r + new_content for r in results] def split_and_append(new_options: List[str]) -> None: nonlocal results newresults = [] # type: List[str] for option in new_options: newresults.extend([r + option for r in results]) results = newresults def deduplicate_wildcards(text: str) -> str: while zero_or_more_wildcard + zero_or_more_wildcard in text: text = text.replace( zero_or_more_wildcard + zero_or_more_wildcard, zero_or_more_wildcard) return text # Basic processing working = regex_text # strings are immutable results = [zero_or_more_wildcard] # start with a wildcard while working: if working.startswith(".*"): # e.g. ".*ozapi" append_to_all(zero_or_more_wildcard) working = working[2:] elif working.startswith("["): # e.g. "[io]peridol" close_bracket = working.index("]") # may raise bracketed = working[1:close_bracket] option_groups = bracketed.split("|") options = [c for group in option_groups for c in group] split_and_append(options) working = working[close_bracket + 1:] elif len(working) > 1 and working[1] == "?": # e.g. "r?azole" split_and_append(["", working[0]]) # ... regex "optional character" # ... SQL: some results with a single wildcard, some without working = working[2:] elif working.startswith("."): # single character wildcard append_to_all(single_wildcard) working = working[1:] else: append_to_all(working[0]) working = working[1:] append_to_all(zero_or_more_wildcard) # end with a wildcard # Remove any duplicate (consecutive) % wildcards: results = [deduplicate_wildcards(r) for r in results] # Done return results
[ "def", "regex_to_sql_like", "(", "regex_text", ":", "str", ",", "single_wildcard", ":", "str", "=", "\"_\"", ",", "zero_or_more_wildcard", ":", "str", "=", "\"%\"", ")", "->", "List", "[", "str", "]", ":", "def", "append_to_all", "(", "new_content", ":", "str", ")", "->", "None", ":", "nonlocal", "results", "results", "=", "[", "r", "+", "new_content", "for", "r", "in", "results", "]", "def", "split_and_append", "(", "new_options", ":", "List", "[", "str", "]", ")", "->", "None", ":", "nonlocal", "results", "newresults", "=", "[", "]", "# type: List[str]", "for", "option", "in", "new_options", ":", "newresults", ".", "extend", "(", "[", "r", "+", "option", "for", "r", "in", "results", "]", ")", "results", "=", "newresults", "def", "deduplicate_wildcards", "(", "text", ":", "str", ")", "->", "str", ":", "while", "zero_or_more_wildcard", "+", "zero_or_more_wildcard", "in", "text", ":", "text", "=", "text", ".", "replace", "(", "zero_or_more_wildcard", "+", "zero_or_more_wildcard", ",", "zero_or_more_wildcard", ")", "return", "text", "# Basic processing", "working", "=", "regex_text", "# strings are immutable", "results", "=", "[", "zero_or_more_wildcard", "]", "# start with a wildcard", "while", "working", ":", "if", "working", ".", "startswith", "(", "\".*\"", ")", ":", "# e.g. \".*ozapi\"", "append_to_all", "(", "zero_or_more_wildcard", ")", "working", "=", "working", "[", "2", ":", "]", "elif", "working", ".", "startswith", "(", "\"[\"", ")", ":", "# e.g. \"[io]peridol\"", "close_bracket", "=", "working", ".", "index", "(", "\"]\"", ")", "# may raise", "bracketed", "=", "working", "[", "1", ":", "close_bracket", "]", "option_groups", "=", "bracketed", ".", "split", "(", "\"|\"", ")", "options", "=", "[", "c", "for", "group", "in", "option_groups", "for", "c", "in", "group", "]", "split_and_append", "(", "options", ")", "working", "=", "working", "[", "close_bracket", "+", "1", ":", "]", "elif", "len", "(", "working", ")", ">", "1", "and", "working", "[", "1", "]", "==", "\"?\"", ":", "# e.g. \"r?azole\"", "split_and_append", "(", "[", "\"\"", ",", "working", "[", "0", "]", "]", ")", "# ... regex \"optional character\"", "# ... SQL: some results with a single wildcard, some without", "working", "=", "working", "[", "2", ":", "]", "elif", "working", ".", "startswith", "(", "\".\"", ")", ":", "# single character wildcard", "append_to_all", "(", "single_wildcard", ")", "working", "=", "working", "[", "1", ":", "]", "else", ":", "append_to_all", "(", "working", "[", "0", "]", ")", "working", "=", "working", "[", "1", ":", "]", "append_to_all", "(", "zero_or_more_wildcard", ")", "# end with a wildcard", "# Remove any duplicate (consecutive) % wildcards:", "results", "=", "[", "deduplicate_wildcards", "(", "r", ")", "for", "r", "in", "results", "]", "# Done", "return", "results" ]
Converts regular expression text to a reasonably close fragment for the SQL ``LIKE`` operator. NOT PERFECT, but works for current built-in regular expressions. Args: regex_text: regular expression text to work with single_wildcard: SQL single wildcard, typically an underscore zero_or_more_wildcard: SQL "zero/one/many" wildcard, probably always a percent symbol Returns: string for an SQL string literal Raises: :exc:`ValueError` for some regex text that it doesn't understand properly
[ "Converts", "regular", "expression", "text", "to", "a", "reasonably", "close", "fragment", "for", "the", "SQL", "LIKE", "operator", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L529-L605
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.sql_like_fragments
def sql_like_fragments(self) -> List[str]: """ Returns all the string literals to which a database column should be compared using the SQL ``LIKE`` operator, to match this drug. This isn't as accurate as the regex, but ``LIKE`` can do less. ``LIKE`` uses the wildcards ``?`` and ``%``. """ if self._sql_like_fragments is None: self._sql_like_fragments = [] for p in list(set(self.all_generics + self.alternatives)): self._sql_like_fragments.extend(self.regex_to_sql_like(p)) return self._sql_like_fragments
python
def sql_like_fragments(self) -> List[str]: """ Returns all the string literals to which a database column should be compared using the SQL ``LIKE`` operator, to match this drug. This isn't as accurate as the regex, but ``LIKE`` can do less. ``LIKE`` uses the wildcards ``?`` and ``%``. """ if self._sql_like_fragments is None: self._sql_like_fragments = [] for p in list(set(self.all_generics + self.alternatives)): self._sql_like_fragments.extend(self.regex_to_sql_like(p)) return self._sql_like_fragments
[ "def", "sql_like_fragments", "(", "self", ")", "->", "List", "[", "str", "]", ":", "if", "self", ".", "_sql_like_fragments", "is", "None", ":", "self", ".", "_sql_like_fragments", "=", "[", "]", "for", "p", "in", "list", "(", "set", "(", "self", ".", "all_generics", "+", "self", ".", "alternatives", ")", ")", ":", "self", ".", "_sql_like_fragments", ".", "extend", "(", "self", ".", "regex_to_sql_like", "(", "p", ")", ")", "return", "self", ".", "_sql_like_fragments" ]
Returns all the string literals to which a database column should be compared using the SQL ``LIKE`` operator, to match this drug. This isn't as accurate as the regex, but ``LIKE`` can do less. ``LIKE`` uses the wildcards ``?`` and ``%``.
[ "Returns", "all", "the", "string", "literals", "to", "which", "a", "database", "column", "should", "be", "compared", "using", "the", "SQL", "LIKE", "operator", "to", "match", "this", "drug", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L608-L621
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.name_matches
def name_matches(self, name: str) -> bool: """ Detects whether the name that's passed matches our knowledge of any of things that this drug might be called: generic name, brand name(s), common misspellings. The parameter should be pre-stripped of edge whitespace. """ return bool(self.regex.match(name))
python
def name_matches(self, name: str) -> bool: """ Detects whether the name that's passed matches our knowledge of any of things that this drug might be called: generic name, brand name(s), common misspellings. The parameter should be pre-stripped of edge whitespace. """ return bool(self.regex.match(name))
[ "def", "name_matches", "(", "self", ",", "name", ":", "str", ")", "->", "bool", ":", "return", "bool", "(", "self", ".", "regex", ".", "match", "(", "name", ")", ")" ]
Detects whether the name that's passed matches our knowledge of any of things that this drug might be called: generic name, brand name(s), common misspellings. The parameter should be pre-stripped of edge whitespace.
[ "Detects", "whether", "the", "name", "that", "s", "passed", "matches", "our", "knowledge", "of", "any", "of", "things", "that", "this", "drug", "might", "be", "called", ":", "generic", "name", "brand", "name", "(", "s", ")", "common", "misspellings", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L623-L631
RudolfCardinal/pythonlib
cardinal_pythonlib/psychiatry/drugs.py
Drug.sql_column_like_drug
def sql_column_like_drug(self, column_name: str) -> str: """ Returns SQL like .. code-block:: sql (column_name LIKE '%drugname1%' OR column_name LIKE '%drugname2%') for the drug names that this Drug object knows about. Args: column_name: column name, pre-escaped if necessary Returns: SQL fragment as above """ clauses = [ "{col} LIKE {fragment}".format( col=column_name, fragment=sql_string_literal(f)) for f in self.sql_like_fragments ] return "({})".format(" OR ".join(clauses))
python
def sql_column_like_drug(self, column_name: str) -> str: """ Returns SQL like .. code-block:: sql (column_name LIKE '%drugname1%' OR column_name LIKE '%drugname2%') for the drug names that this Drug object knows about. Args: column_name: column name, pre-escaped if necessary Returns: SQL fragment as above """ clauses = [ "{col} LIKE {fragment}".format( col=column_name, fragment=sql_string_literal(f)) for f in self.sql_like_fragments ] return "({})".format(" OR ".join(clauses))
[ "def", "sql_column_like_drug", "(", "self", ",", "column_name", ":", "str", ")", "->", "str", ":", "clauses", "=", "[", "\"{col} LIKE {fragment}\"", ".", "format", "(", "col", "=", "column_name", ",", "fragment", "=", "sql_string_literal", "(", "f", ")", ")", "for", "f", "in", "self", ".", "sql_like_fragments", "]", "return", "\"({})\"", ".", "format", "(", "\" OR \"", ".", "join", "(", "clauses", ")", ")" ]
Returns SQL like .. code-block:: sql (column_name LIKE '%drugname1%' OR column_name LIKE '%drugname2%') for the drug names that this Drug object knows about. Args: column_name: column name, pre-escaped if necessary Returns: SQL fragment as above
[ "Returns", "SQL", "like" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/drugs.py#L633-L657
davenquinn/Attitude
attitude/stereonet.py
quaternion
def quaternion(vector, angle): """ Unit quaternion for a vector and an angle """ return N.cos(angle/2)+vector*N.sin(angle/2)
python
def quaternion(vector, angle): """ Unit quaternion for a vector and an angle """ return N.cos(angle/2)+vector*N.sin(angle/2)
[ "def", "quaternion", "(", "vector", ",", "angle", ")", ":", "return", "N", ".", "cos", "(", "angle", "/", "2", ")", "+", "vector", "*", "N", ".", "sin", "(", "angle", "/", "2", ")" ]
Unit quaternion for a vector and an angle
[ "Unit", "quaternion", "for", "a", "vector", "and", "an", "angle" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L7-L11
davenquinn/Attitude
attitude/stereonet.py
ellipse
def ellipse(n=1000, adaptive=False): """ Get a parameterized set of vectors defining ellipse for a major and minor axis length. Resulting vector bundle has major axes along axes given. """ u = N.linspace(0,2*N.pi,n) # Get a bundle of vectors defining # a full rotation around the unit circle return N.array([N.cos(u),N.sin(u)]).T
python
def ellipse(n=1000, adaptive=False): """ Get a parameterized set of vectors defining ellipse for a major and minor axis length. Resulting vector bundle has major axes along axes given. """ u = N.linspace(0,2*N.pi,n) # Get a bundle of vectors defining # a full rotation around the unit circle return N.array([N.cos(u),N.sin(u)]).T
[ "def", "ellipse", "(", "n", "=", "1000", ",", "adaptive", "=", "False", ")", ":", "u", "=", "N", ".", "linspace", "(", "0", ",", "2", "*", "N", ".", "pi", ",", "n", ")", "# Get a bundle of vectors defining", "# a full rotation around the unit circle", "return", "N", ".", "array", "(", "[", "N", ".", "cos", "(", "u", ")", ",", "N", ".", "sin", "(", "u", ")", "]", ")", ".", "T" ]
Get a parameterized set of vectors defining ellipse for a major and minor axis length. Resulting vector bundle has major axes along axes given.
[ "Get", "a", "parameterized", "set", "of", "vectors", "defining", "ellipse", "for", "a", "major", "and", "minor", "axis", "length", ".", "Resulting", "vector", "bundle", "has", "major", "axes", "along", "axes", "given", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L13-L23
davenquinn/Attitude
attitude/stereonet.py
scale_errors
def scale_errors(cov_axes, confidence_level=0.95): """ Returns major axes of error ellipse or hyperbola, rescaled using chi2 test statistic """ dof = len(cov_axes) x2t = chi2.ppf(confidence_level,dof) return N.sqrt(x2t*cov_axes)
python
def scale_errors(cov_axes, confidence_level=0.95): """ Returns major axes of error ellipse or hyperbola, rescaled using chi2 test statistic """ dof = len(cov_axes) x2t = chi2.ppf(confidence_level,dof) return N.sqrt(x2t*cov_axes)
[ "def", "scale_errors", "(", "cov_axes", ",", "confidence_level", "=", "0.95", ")", ":", "dof", "=", "len", "(", "cov_axes", ")", "x2t", "=", "chi2", ".", "ppf", "(", "confidence_level", ",", "dof", ")", "return", "N", ".", "sqrt", "(", "x2t", "*", "cov_axes", ")" ]
Returns major axes of error ellipse or hyperbola, rescaled using chi2 test statistic
[ "Returns", "major", "axes", "of", "error", "ellipse", "or", "hyperbola", "rescaled", "using", "chi2", "test", "statistic" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L33-L40
davenquinn/Attitude
attitude/stereonet.py
normal_errors
def normal_errors(axes, covariance_matrix, **kwargs): """ Currently assumes upper hemisphere of stereonet """ level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.diagonal(covariance_matrix) ell = ellipse(**kwargs) if axes[2,2] < 0: axes *= -1 # Not sure where this factor comes from but it # seems to make things work better c1 = 2 axis_lengths = d[:2] f = N.linalg.norm( ell*axis_lengths,axis=1) e0 = -ell.T*d[2]*c1 e = N.vstack((e0,f)) _ = dot(e.T,axes).T if traditional_layout: lon,lat = stereonet_math.cart2sph(_[2],_[0],-_[1]) else: lon,lat = stereonet_math.cart2sph(-_[1],_[0],_[2]) return list(zip(lon,lat))
python
def normal_errors(axes, covariance_matrix, **kwargs): """ Currently assumes upper hemisphere of stereonet """ level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.diagonal(covariance_matrix) ell = ellipse(**kwargs) if axes[2,2] < 0: axes *= -1 # Not sure where this factor comes from but it # seems to make things work better c1 = 2 axis_lengths = d[:2] f = N.linalg.norm( ell*axis_lengths,axis=1) e0 = -ell.T*d[2]*c1 e = N.vstack((e0,f)) _ = dot(e.T,axes).T if traditional_layout: lon,lat = stereonet_math.cart2sph(_[2],_[0],-_[1]) else: lon,lat = stereonet_math.cart2sph(-_[1],_[0],_[2]) return list(zip(lon,lat))
[ "def", "normal_errors", "(", "axes", ",", "covariance_matrix", ",", "*", "*", "kwargs", ")", ":", "level", "=", "kwargs", ".", "pop", "(", "'level'", ",", "1", ")", "traditional_layout", "=", "kwargs", ".", "pop", "(", "'traditional_layout'", ",", "True", ")", "d", "=", "N", ".", "diagonal", "(", "covariance_matrix", ")", "ell", "=", "ellipse", "(", "*", "*", "kwargs", ")", "if", "axes", "[", "2", ",", "2", "]", "<", "0", ":", "axes", "*=", "-", "1", "# Not sure where this factor comes from but it", "# seems to make things work better", "c1", "=", "2", "axis_lengths", "=", "d", "[", ":", "2", "]", "f", "=", "N", ".", "linalg", ".", "norm", "(", "ell", "*", "axis_lengths", ",", "axis", "=", "1", ")", "e0", "=", "-", "ell", ".", "T", "*", "d", "[", "2", "]", "*", "c1", "e", "=", "N", ".", "vstack", "(", "(", "e0", ",", "f", ")", ")", "_", "=", "dot", "(", "e", ".", "T", ",", "axes", ")", ".", "T", "if", "traditional_layout", ":", "lon", ",", "lat", "=", "stereonet_math", ".", "cart2sph", "(", "_", "[", "2", "]", ",", "_", "[", "0", "]", ",", "-", "_", "[", "1", "]", ")", "else", ":", "lon", ",", "lat", "=", "stereonet_math", ".", "cart2sph", "(", "-", "_", "[", "1", "]", ",", "_", "[", "0", "]", ",", "_", "[", "2", "]", ")", "return", "list", "(", "zip", "(", "lon", ",", "lat", ")", ")" ]
Currently assumes upper hemisphere of stereonet
[ "Currently", "assumes", "upper", "hemisphere", "of", "stereonet" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L42-L70
davenquinn/Attitude
attitude/stereonet.py
plane_errors
def plane_errors(axes, covariance_matrix, sheet='upper',**kwargs): """ kwargs: traditional_layout boolean [True] Lay the stereonet out traditionally, with north at the pole of the diagram. The default is a more natural and intuitive visualization with vertical at the pole and the compass points of strike around the equator. Thus, longitude at the equator represents strike and latitude represents apparent dip at that azimuth. """ level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.sqrt(covariance_matrix) ell = ellipse(**kwargs) bundle = dot(ell, d[:2]) res = d[2]*level # Switch hemispheres if PCA is upside-down # Normal vector is always correctly fit #if traditional_layout: #if axes[2,2] > 0: if axes[2,2] > 0: res *= -1 if sheet == 'upper': bundle += res elif sheet == 'lower': bundle -= res _ = dot(bundle,axes).T if traditional_layout: lon,lat = stereonet_math.cart2sph(_[2],_[0],_[1]) else: lon,lat = stereonet_math.cart2sph(-_[1],_[0],_[2]) return list(zip(lon,lat))
python
def plane_errors(axes, covariance_matrix, sheet='upper',**kwargs): """ kwargs: traditional_layout boolean [True] Lay the stereonet out traditionally, with north at the pole of the diagram. The default is a more natural and intuitive visualization with vertical at the pole and the compass points of strike around the equator. Thus, longitude at the equator represents strike and latitude represents apparent dip at that azimuth. """ level = kwargs.pop('level',1) traditional_layout = kwargs.pop('traditional_layout',True) d = N.sqrt(covariance_matrix) ell = ellipse(**kwargs) bundle = dot(ell, d[:2]) res = d[2]*level # Switch hemispheres if PCA is upside-down # Normal vector is always correctly fit #if traditional_layout: #if axes[2,2] > 0: if axes[2,2] > 0: res *= -1 if sheet == 'upper': bundle += res elif sheet == 'lower': bundle -= res _ = dot(bundle,axes).T if traditional_layout: lon,lat = stereonet_math.cart2sph(_[2],_[0],_[1]) else: lon,lat = stereonet_math.cart2sph(-_[1],_[0],_[2]) return list(zip(lon,lat))
[ "def", "plane_errors", "(", "axes", ",", "covariance_matrix", ",", "sheet", "=", "'upper'", ",", "*", "*", "kwargs", ")", ":", "level", "=", "kwargs", ".", "pop", "(", "'level'", ",", "1", ")", "traditional_layout", "=", "kwargs", ".", "pop", "(", "'traditional_layout'", ",", "True", ")", "d", "=", "N", ".", "sqrt", "(", "covariance_matrix", ")", "ell", "=", "ellipse", "(", "*", "*", "kwargs", ")", "bundle", "=", "dot", "(", "ell", ",", "d", "[", ":", "2", "]", ")", "res", "=", "d", "[", "2", "]", "*", "level", "# Switch hemispheres if PCA is upside-down", "# Normal vector is always correctly fit", "#if traditional_layout:", "#if axes[2,2] > 0:", "if", "axes", "[", "2", ",", "2", "]", ">", "0", ":", "res", "*=", "-", "1", "if", "sheet", "==", "'upper'", ":", "bundle", "+=", "res", "elif", "sheet", "==", "'lower'", ":", "bundle", "-=", "res", "_", "=", "dot", "(", "bundle", ",", "axes", ")", ".", "T", "if", "traditional_layout", ":", "lon", ",", "lat", "=", "stereonet_math", ".", "cart2sph", "(", "_", "[", "2", "]", ",", "_", "[", "0", "]", ",", "_", "[", "1", "]", ")", "else", ":", "lon", ",", "lat", "=", "stereonet_math", ".", "cart2sph", "(", "-", "_", "[", "1", "]", ",", "_", "[", "0", "]", ",", "_", "[", "2", "]", ")", "return", "list", "(", "zip", "(", "lon", ",", "lat", ")", ")" ]
kwargs: traditional_layout boolean [True] Lay the stereonet out traditionally, with north at the pole of the diagram. The default is a more natural and intuitive visualization with vertical at the pole and the compass points of strike around the equator. Thus, longitude at the equator represents strike and latitude represents apparent dip at that azimuth.
[ "kwargs", ":", "traditional_layout", "boolean", "[", "True", "]", "Lay", "the", "stereonet", "out", "traditionally", "with", "north", "at", "the", "pole", "of", "the", "diagram", ".", "The", "default", "is", "a", "more", "natural", "and", "intuitive", "visualization", "with", "vertical", "at", "the", "pole", "and", "the", "compass", "points", "of", "strike", "around", "the", "equator", ".", "Thus", "longitude", "at", "the", "equator", "represents", "strike", "and", "latitude", "represents", "apparent", "dip", "at", "that", "azimuth", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L114-L154
davenquinn/Attitude
attitude/stereonet.py
iterative_plane_errors
def iterative_plane_errors(axes,covariance_matrix, **kwargs): """ An iterative version of `pca.plane_errors`, which computes an error surface for a plane. """ sheet = kwargs.pop('sheet','upper') level = kwargs.pop('level',1) n = kwargs.pop('n',100) cov = N.sqrt(N.diagonal(covariance_matrix)) u = N.linspace(0, 2*N.pi, n) scales = dict(upper=1,lower=-1,nominal=0) c1 = scales[sheet] c1 *= -1 # We assume upper hemisphere if axes[2,2] < 0: c1 *= -1 def sdot(a,b): return sum([i*j for i,j in zip(a,b)]) def step_func(a): e = [ N.cos(a)*cov[0], N.sin(a)*cov[1], c1*cov[2]] d = [sdot(e,i) for i in axes.T] x,y,z = d[2],d[0],d[1] r = N.sqrt(x**2 + y**2 + z**2) lat = N.arcsin(z/r) lon = N.arctan2(y, x) return lon,lat # Get a bundle of vectors defining # a full rotation around the unit circle return N.array([step_func(i) for i in u])
python
def iterative_plane_errors(axes,covariance_matrix, **kwargs): """ An iterative version of `pca.plane_errors`, which computes an error surface for a plane. """ sheet = kwargs.pop('sheet','upper') level = kwargs.pop('level',1) n = kwargs.pop('n',100) cov = N.sqrt(N.diagonal(covariance_matrix)) u = N.linspace(0, 2*N.pi, n) scales = dict(upper=1,lower=-1,nominal=0) c1 = scales[sheet] c1 *= -1 # We assume upper hemisphere if axes[2,2] < 0: c1 *= -1 def sdot(a,b): return sum([i*j for i,j in zip(a,b)]) def step_func(a): e = [ N.cos(a)*cov[0], N.sin(a)*cov[1], c1*cov[2]] d = [sdot(e,i) for i in axes.T] x,y,z = d[2],d[0],d[1] r = N.sqrt(x**2 + y**2 + z**2) lat = N.arcsin(z/r) lon = N.arctan2(y, x) return lon,lat # Get a bundle of vectors defining # a full rotation around the unit circle return N.array([step_func(i) for i in u])
[ "def", "iterative_plane_errors", "(", "axes", ",", "covariance_matrix", ",", "*", "*", "kwargs", ")", ":", "sheet", "=", "kwargs", ".", "pop", "(", "'sheet'", ",", "'upper'", ")", "level", "=", "kwargs", ".", "pop", "(", "'level'", ",", "1", ")", "n", "=", "kwargs", ".", "pop", "(", "'n'", ",", "100", ")", "cov", "=", "N", ".", "sqrt", "(", "N", ".", "diagonal", "(", "covariance_matrix", ")", ")", "u", "=", "N", ".", "linspace", "(", "0", ",", "2", "*", "N", ".", "pi", ",", "n", ")", "scales", "=", "dict", "(", "upper", "=", "1", ",", "lower", "=", "-", "1", ",", "nominal", "=", "0", ")", "c1", "=", "scales", "[", "sheet", "]", "c1", "*=", "-", "1", "# We assume upper hemisphere", "if", "axes", "[", "2", ",", "2", "]", "<", "0", ":", "c1", "*=", "-", "1", "def", "sdot", "(", "a", ",", "b", ")", ":", "return", "sum", "(", "[", "i", "*", "j", "for", "i", ",", "j", "in", "zip", "(", "a", ",", "b", ")", "]", ")", "def", "step_func", "(", "a", ")", ":", "e", "=", "[", "N", ".", "cos", "(", "a", ")", "*", "cov", "[", "0", "]", ",", "N", ".", "sin", "(", "a", ")", "*", "cov", "[", "1", "]", ",", "c1", "*", "cov", "[", "2", "]", "]", "d", "=", "[", "sdot", "(", "e", ",", "i", ")", "for", "i", "in", "axes", ".", "T", "]", "x", ",", "y", ",", "z", "=", "d", "[", "2", "]", ",", "d", "[", "0", "]", ",", "d", "[", "1", "]", "r", "=", "N", ".", "sqrt", "(", "x", "**", "2", "+", "y", "**", "2", "+", "z", "**", "2", ")", "lat", "=", "N", ".", "arcsin", "(", "z", "/", "r", ")", "lon", "=", "N", ".", "arctan2", "(", "y", ",", "x", ")", "return", "lon", ",", "lat", "# Get a bundle of vectors defining", "# a full rotation around the unit circle", "return", "N", ".", "array", "(", "[", "step_func", "(", "i", ")", "for", "i", "in", "u", "]", ")" ]
An iterative version of `pca.plane_errors`, which computes an error surface for a plane.
[ "An", "iterative", "version", "of", "pca", ".", "plane_errors", "which", "computes", "an", "error", "surface", "for", "a", "plane", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/stereonet.py#L156-L193
RudolfCardinal/pythonlib
cardinal_pythonlib/sql/sql_grammar.py
SqlGrammar.quote_identifier_if_required
def quote_identifier_if_required(cls, identifier: str, debug_force_quote: bool = False) -> str: """ Transforms a SQL identifier (such as a column name) into a version that is quoted if required (or, with ``debug_force_quote=True``, is quoted regardless). """ if debug_force_quote: return cls.quote_identifier(identifier) if cls.is_quoted(identifier): return identifier if cls.requires_quoting(identifier): return cls.quote_identifier(identifier) return identifier
python
def quote_identifier_if_required(cls, identifier: str, debug_force_quote: bool = False) -> str: """ Transforms a SQL identifier (such as a column name) into a version that is quoted if required (or, with ``debug_force_quote=True``, is quoted regardless). """ if debug_force_quote: return cls.quote_identifier(identifier) if cls.is_quoted(identifier): return identifier if cls.requires_quoting(identifier): return cls.quote_identifier(identifier) return identifier
[ "def", "quote_identifier_if_required", "(", "cls", ",", "identifier", ":", "str", ",", "debug_force_quote", ":", "bool", "=", "False", ")", "->", "str", ":", "if", "debug_force_quote", ":", "return", "cls", ".", "quote_identifier", "(", "identifier", ")", "if", "cls", ".", "is_quoted", "(", "identifier", ")", ":", "return", "identifier", "if", "cls", ".", "requires_quoting", "(", "identifier", ")", ":", "return", "cls", ".", "quote_identifier", "(", "identifier", ")", "return", "identifier" ]
Transforms a SQL identifier (such as a column name) into a version that is quoted if required (or, with ``debug_force_quote=True``, is quoted regardless).
[ "Transforms", "a", "SQL", "identifier", "(", "such", "as", "a", "column", "name", ")", "into", "a", "version", "that", "is", "quoted", "if", "required", "(", "or", "with", "debug_force_quote", "=", "True", "is", "quoted", "regardless", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sql/sql_grammar.py#L640-L653
The-Politico/politico-civic-geography
geography/models/geometry.py
Geometry.to_topojson
def to_topojson(self): """Adds points and converts to topojson string.""" topojson = self.topojson topojson["objects"]["points"] = { "type": "GeometryCollection", "geometries": [point.to_topojson() for point in self.points.all()], } return json.dumps(topojson)
python
def to_topojson(self): """Adds points and converts to topojson string.""" topojson = self.topojson topojson["objects"]["points"] = { "type": "GeometryCollection", "geometries": [point.to_topojson() for point in self.points.all()], } return json.dumps(topojson)
[ "def", "to_topojson", "(", "self", ")", ":", "topojson", "=", "self", ".", "topojson", "topojson", "[", "\"objects\"", "]", "[", "\"points\"", "]", "=", "{", "\"type\"", ":", "\"GeometryCollection\"", ",", "\"geometries\"", ":", "[", "point", ".", "to_topojson", "(", ")", "for", "point", "in", "self", ".", "points", ".", "all", "(", ")", "]", ",", "}", "return", "json", ".", "dumps", "(", "topojson", ")" ]
Adds points and converts to topojson string.
[ "Adds", "points", "and", "converts", "to", "topojson", "string", "." ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/models/geometry.py#L124-L131
Netuitive/netuitive-client-python
netuitive/client.py
Client.post
def post(self, element): """ :param element: Element to post to Netuitive :type element: object """ try: if self.disabled is True: element.clear_samples() logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) if element.id is None: raise Exception('element id is not set') element.merge_metrics() payload = json.dumps( [element], default=lambda o: o.__dict__, sort_keys=True) logging.debug(payload) headers = {'Content-Type': 'application/json', 'User-Agent': self.agent} request = urllib2.Request( self.dataurl, data=payload, headers=headers) resp = urllib2.urlopen(request) logging.debug("Response code: %d", resp.getcode()) resp.close() self.post_error_count = 0 return(True) except urllib2.HTTPError as e: logging.debug("Response code: %d", e.code) if e.code in self.kill_codes: self.disabled = True logging.exception('Posting has been disabled.' 'See previous errors for details.') else: self.post_error_count += 1 if self.post_error_count > self.max_post_errors: element.clear_samples() logging.exception( 'error posting payload to api ingest endpoint (%s): %s', self.dataurl, e) except Exception as e: self.post_error_count += 1 if self.post_error_count > self.max_post_errors: element.clear_samples() # pragma: no cover logging.exception( 'error posting payload to api ingest endpoint (%s): %s', self.dataurl, e)
python
def post(self, element): """ :param element: Element to post to Netuitive :type element: object """ try: if self.disabled is True: element.clear_samples() logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) if element.id is None: raise Exception('element id is not set') element.merge_metrics() payload = json.dumps( [element], default=lambda o: o.__dict__, sort_keys=True) logging.debug(payload) headers = {'Content-Type': 'application/json', 'User-Agent': self.agent} request = urllib2.Request( self.dataurl, data=payload, headers=headers) resp = urllib2.urlopen(request) logging.debug("Response code: %d", resp.getcode()) resp.close() self.post_error_count = 0 return(True) except urllib2.HTTPError as e: logging.debug("Response code: %d", e.code) if e.code in self.kill_codes: self.disabled = True logging.exception('Posting has been disabled.' 'See previous errors for details.') else: self.post_error_count += 1 if self.post_error_count > self.max_post_errors: element.clear_samples() logging.exception( 'error posting payload to api ingest endpoint (%s): %s', self.dataurl, e) except Exception as e: self.post_error_count += 1 if self.post_error_count > self.max_post_errors: element.clear_samples() # pragma: no cover logging.exception( 'error posting payload to api ingest endpoint (%s): %s', self.dataurl, e)
[ "def", "post", "(", "self", ",", "element", ")", ":", "try", ":", "if", "self", ".", "disabled", "is", "True", ":", "element", ".", "clear_samples", "(", ")", "logging", ".", "error", "(", "'Posting has been disabled. '", "'See previous errors for details.'", ")", "return", "(", "False", ")", "if", "element", ".", "id", "is", "None", ":", "raise", "Exception", "(", "'element id is not set'", ")", "element", ".", "merge_metrics", "(", ")", "payload", "=", "json", ".", "dumps", "(", "[", "element", "]", ",", "default", "=", "lambda", "o", ":", "o", ".", "__dict__", ",", "sort_keys", "=", "True", ")", "logging", ".", "debug", "(", "payload", ")", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'User-Agent'", ":", "self", ".", "agent", "}", "request", "=", "urllib2", ".", "Request", "(", "self", ".", "dataurl", ",", "data", "=", "payload", ",", "headers", "=", "headers", ")", "resp", "=", "urllib2", ".", "urlopen", "(", "request", ")", "logging", ".", "debug", "(", "\"Response code: %d\"", ",", "resp", ".", "getcode", "(", ")", ")", "resp", ".", "close", "(", ")", "self", ".", "post_error_count", "=", "0", "return", "(", "True", ")", "except", "urllib2", ".", "HTTPError", "as", "e", ":", "logging", ".", "debug", "(", "\"Response code: %d\"", ",", "e", ".", "code", ")", "if", "e", ".", "code", "in", "self", ".", "kill_codes", ":", "self", ".", "disabled", "=", "True", "logging", ".", "exception", "(", "'Posting has been disabled.'", "'See previous errors for details.'", ")", "else", ":", "self", ".", "post_error_count", "+=", "1", "if", "self", ".", "post_error_count", ">", "self", ".", "max_post_errors", ":", "element", ".", "clear_samples", "(", ")", "logging", ".", "exception", "(", "'error posting payload to api ingest endpoint (%s): %s'", ",", "self", ".", "dataurl", ",", "e", ")", "except", "Exception", "as", "e", ":", "self", ".", "post_error_count", "+=", "1", "if", "self", ".", "post_error_count", ">", "self", ".", "max_post_errors", ":", "element", ".", "clear_samples", "(", ")", "# pragma: no cover", "logging", ".", "exception", "(", "'error posting payload to api ingest endpoint (%s): %s'", ",", "self", ".", "dataurl", ",", "e", ")" ]
:param element: Element to post to Netuitive :type element: object
[ ":", "param", "element", ":", "Element", "to", "post", "to", "Netuitive", ":", "type", "element", ":", "object" ]
train
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/client.py#L56-L115
Netuitive/netuitive-client-python
netuitive/client.py
Client.post_event
def post_event(self, event): """ :param event: Event to post to Netuitive :type event: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) payload = json.dumps( [event], default=lambda o: o.__dict__, sort_keys=True) logging.debug(payload) try: headers = {'Content-Type': 'application/json', 'User-Agent': self.agent} request = urllib2.Request( self.eventurl, data=payload, headers=headers) resp = urllib2.urlopen(request) logging.debug("Response code: %d", resp.getcode()) resp.close() return(True) except urllib2.HTTPError as e: logging.debug("Response code: %d", e.code) if e.code in self.kill_codes: self.disabled = True logging.exception('Posting has been disabled.' 'See previous errors for details.') else: logging.exception( 'error posting payload to api ingest endpoint (%s): %s', self.eventurl, e) except Exception as e: logging.exception( 'error posting payload to api ingest endpoint (%s): %s', self.eventurl, e)
python
def post_event(self, event): """ :param event: Event to post to Netuitive :type event: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) payload = json.dumps( [event], default=lambda o: o.__dict__, sort_keys=True) logging.debug(payload) try: headers = {'Content-Type': 'application/json', 'User-Agent': self.agent} request = urllib2.Request( self.eventurl, data=payload, headers=headers) resp = urllib2.urlopen(request) logging.debug("Response code: %d", resp.getcode()) resp.close() return(True) except urllib2.HTTPError as e: logging.debug("Response code: %d", e.code) if e.code in self.kill_codes: self.disabled = True logging.exception('Posting has been disabled.' 'See previous errors for details.') else: logging.exception( 'error posting payload to api ingest endpoint (%s): %s', self.eventurl, e) except Exception as e: logging.exception( 'error posting payload to api ingest endpoint (%s): %s', self.eventurl, e)
[ "def", "post_event", "(", "self", ",", "event", ")", ":", "if", "self", ".", "disabled", "is", "True", ":", "logging", ".", "error", "(", "'Posting has been disabled. '", "'See previous errors for details.'", ")", "return", "(", "False", ")", "payload", "=", "json", ".", "dumps", "(", "[", "event", "]", ",", "default", "=", "lambda", "o", ":", "o", ".", "__dict__", ",", "sort_keys", "=", "True", ")", "logging", ".", "debug", "(", "payload", ")", "try", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'User-Agent'", ":", "self", ".", "agent", "}", "request", "=", "urllib2", ".", "Request", "(", "self", ".", "eventurl", ",", "data", "=", "payload", ",", "headers", "=", "headers", ")", "resp", "=", "urllib2", ".", "urlopen", "(", "request", ")", "logging", ".", "debug", "(", "\"Response code: %d\"", ",", "resp", ".", "getcode", "(", ")", ")", "resp", ".", "close", "(", ")", "return", "(", "True", ")", "except", "urllib2", ".", "HTTPError", "as", "e", ":", "logging", ".", "debug", "(", "\"Response code: %d\"", ",", "e", ".", "code", ")", "if", "e", ".", "code", "in", "self", ".", "kill_codes", ":", "self", ".", "disabled", "=", "True", "logging", ".", "exception", "(", "'Posting has been disabled.'", "'See previous errors for details.'", ")", "else", ":", "logging", ".", "exception", "(", "'error posting payload to api ingest endpoint (%s): %s'", ",", "self", ".", "eventurl", ",", "e", ")", "except", "Exception", "as", "e", ":", "logging", ".", "exception", "(", "'error posting payload to api ingest endpoint (%s): %s'", ",", "self", ".", "eventurl", ",", "e", ")" ]
:param event: Event to post to Netuitive :type event: object
[ ":", "param", "event", ":", "Event", "to", "post", "to", "Netuitive", ":", "type", "event", ":", "object" ]
train
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/client.py#L117-L157
Netuitive/netuitive-client-python
netuitive/client.py
Client.post_check
def post_check(self, check): """ :param check: Check to post to Metricly :type check: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) url = self.checkurl + '/' \ + check.name + '/' \ + check.elementId + '/' \ + str(check.ttl) headers = {'User-Agent': self.agent} try: request = urllib2.Request( url, data='', headers=headers) resp = self._repeat_request(request, self.connection_timeout) logging.debug("Response code: %d", resp.getcode()) resp.close() return(True) except urllib2.HTTPError as e: logging.debug("Response code: %d", e.code) if e.code in self.kill_codes: self.disabled = True logging.exception('Posting has been disabled.' 'See previous errors for details.') else: logging.exception( 'HTTPError posting payload to api ingest endpoint' + ' (%s): %s', url, e)
python
def post_check(self, check): """ :param check: Check to post to Metricly :type check: object """ if self.disabled is True: logging.error('Posting has been disabled. ' 'See previous errors for details.') return(False) url = self.checkurl + '/' \ + check.name + '/' \ + check.elementId + '/' \ + str(check.ttl) headers = {'User-Agent': self.agent} try: request = urllib2.Request( url, data='', headers=headers) resp = self._repeat_request(request, self.connection_timeout) logging.debug("Response code: %d", resp.getcode()) resp.close() return(True) except urllib2.HTTPError as e: logging.debug("Response code: %d", e.code) if e.code in self.kill_codes: self.disabled = True logging.exception('Posting has been disabled.' 'See previous errors for details.') else: logging.exception( 'HTTPError posting payload to api ingest endpoint' + ' (%s): %s', url, e)
[ "def", "post_check", "(", "self", ",", "check", ")", ":", "if", "self", ".", "disabled", "is", "True", ":", "logging", ".", "error", "(", "'Posting has been disabled. '", "'See previous errors for details.'", ")", "return", "(", "False", ")", "url", "=", "self", ".", "checkurl", "+", "'/'", "+", "check", ".", "name", "+", "'/'", "+", "check", ".", "elementId", "+", "'/'", "+", "str", "(", "check", ".", "ttl", ")", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "agent", "}", "try", ":", "request", "=", "urllib2", ".", "Request", "(", "url", ",", "data", "=", "''", ",", "headers", "=", "headers", ")", "resp", "=", "self", ".", "_repeat_request", "(", "request", ",", "self", ".", "connection_timeout", ")", "logging", ".", "debug", "(", "\"Response code: %d\"", ",", "resp", ".", "getcode", "(", ")", ")", "resp", ".", "close", "(", ")", "return", "(", "True", ")", "except", "urllib2", ".", "HTTPError", "as", "e", ":", "logging", ".", "debug", "(", "\"Response code: %d\"", ",", "e", ".", "code", ")", "if", "e", ".", "code", "in", "self", ".", "kill_codes", ":", "self", ".", "disabled", "=", "True", "logging", ".", "exception", "(", "'Posting has been disabled.'", "'See previous errors for details.'", ")", "else", ":", "logging", ".", "exception", "(", "'HTTPError posting payload to api ingest endpoint'", "+", "' (%s): %s'", ",", "url", ",", "e", ")" ]
:param check: Check to post to Metricly :type check: object
[ ":", "param", "check", ":", "Check", "to", "post", "to", "Metricly", ":", "type", "check", ":", "object" ]
train
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/client.py#L159-L195
ivanprjcts/sdklib
sdklib/util/urls.py
urlsplit
def urlsplit(url): """ Split url into scheme, host, port, path, query :param str url: :return: scheme, host, port, path, query """ p = '((?P<scheme>.*)?.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*' m = re.search(p, url) scheme = m.group('scheme') host = m.group('host') port = m.group('port') _scheme, _netloc, path, query, _fragment = tuple(py_urlsplit(url)) return scheme, host, port, path, query
python
def urlsplit(url): """ Split url into scheme, host, port, path, query :param str url: :return: scheme, host, port, path, query """ p = '((?P<scheme>.*)?.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*' m = re.search(p, url) scheme = m.group('scheme') host = m.group('host') port = m.group('port') _scheme, _netloc, path, query, _fragment = tuple(py_urlsplit(url)) return scheme, host, port, path, query
[ "def", "urlsplit", "(", "url", ")", ":", "p", "=", "'((?P<scheme>.*)?.*://)?(?P<host>[^:/ ]+).?(?P<port>[0-9]*).*'", "m", "=", "re", ".", "search", "(", "p", ",", "url", ")", "scheme", "=", "m", ".", "group", "(", "'scheme'", ")", "host", "=", "m", ".", "group", "(", "'host'", ")", "port", "=", "m", ".", "group", "(", "'port'", ")", "_scheme", ",", "_netloc", ",", "path", ",", "query", ",", "_fragment", "=", "tuple", "(", "py_urlsplit", "(", "url", ")", ")", "return", "scheme", ",", "host", ",", "port", ",", "path", ",", "query" ]
Split url into scheme, host, port, path, query :param str url: :return: scheme, host, port, path, query
[ "Split", "url", "into", "scheme", "host", "port", "path", "query" ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/urls.py#L6-L21
ivanprjcts/sdklib
sdklib/util/urls.py
generate_url
def generate_url(scheme=None, host=None, port=None, path=None, query=None): """ Generate URI from parameters. :param str scheme: :param str host: :param int port: :param str path: :param dict query: :return: """ url = "" if scheme is not None: url += "%s://" % scheme if host is not None: url += host if port is not None: url += ":%s" % str(port) if path is not None: url += ensure_url_path_starts_with_slash(path) if query is not None: url += "?%s" % (urlencode(query)) return url
python
def generate_url(scheme=None, host=None, port=None, path=None, query=None): """ Generate URI from parameters. :param str scheme: :param str host: :param int port: :param str path: :param dict query: :return: """ url = "" if scheme is not None: url += "%s://" % scheme if host is not None: url += host if port is not None: url += ":%s" % str(port) if path is not None: url += ensure_url_path_starts_with_slash(path) if query is not None: url += "?%s" % (urlencode(query)) return url
[ "def", "generate_url", "(", "scheme", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "path", "=", "None", ",", "query", "=", "None", ")", ":", "url", "=", "\"\"", "if", "scheme", "is", "not", "None", ":", "url", "+=", "\"%s://\"", "%", "scheme", "if", "host", "is", "not", "None", ":", "url", "+=", "host", "if", "port", "is", "not", "None", ":", "url", "+=", "\":%s\"", "%", "str", "(", "port", ")", "if", "path", "is", "not", "None", ":", "url", "+=", "ensure_url_path_starts_with_slash", "(", "path", ")", "if", "query", "is", "not", "None", ":", "url", "+=", "\"?%s\"", "%", "(", "urlencode", "(", "query", ")", ")", "return", "url" ]
Generate URI from parameters. :param str scheme: :param str host: :param int port: :param str path: :param dict query: :return:
[ "Generate", "URI", "from", "parameters", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/util/urls.py#L60-L82
meyersj/geotweet
geotweet/osm.py
OSMRunner.run
def run(self): """ For each state in states file build url and download file """ states = open(self.states, 'r').read().splitlines() for state in states: url = self.build_url(state) log = "Downloading State < {0} > from < {1} >" logging.info(log.format(state, url)) tmp = self.download(self.output, url, self.overwrite) self.s3.store(self.extract(tmp, self.tmp2poi(tmp)))
python
def run(self): """ For each state in states file build url and download file """ states = open(self.states, 'r').read().splitlines() for state in states: url = self.build_url(state) log = "Downloading State < {0} > from < {1} >" logging.info(log.format(state, url)) tmp = self.download(self.output, url, self.overwrite) self.s3.store(self.extract(tmp, self.tmp2poi(tmp)))
[ "def", "run", "(", "self", ")", ":", "states", "=", "open", "(", "self", ".", "states", ",", "'r'", ")", ".", "read", "(", ")", ".", "splitlines", "(", ")", "for", "state", "in", "states", ":", "url", "=", "self", ".", "build_url", "(", "state", ")", "log", "=", "\"Downloading State < {0} > from < {1} >\"", "logging", ".", "info", "(", "log", ".", "format", "(", "state", ",", "url", ")", ")", "tmp", "=", "self", ".", "download", "(", "self", ".", "output", ",", "url", ",", "self", ".", "overwrite", ")", "self", ".", "s3", ".", "store", "(", "self", ".", "extract", "(", "tmp", ",", "self", ".", "tmp2poi", "(", "tmp", ")", ")", ")" ]
For each state in states file build url and download file
[ "For", "each", "state", "in", "states", "file", "build", "url", "and", "download", "file" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L37-L45
meyersj/geotweet
geotweet/osm.py
OSMRunner.download
def download(self, output_dir, url, overwrite): """ Dowload file to /tmp """ tmp = self.url2tmp(output_dir, url) if os.path.isfile(tmp) and not overwrite: logging.info("File {0} already exists. Skipping download.".format(tmp)) return tmp f = open(tmp, 'wb') logging.info("Downloading {0}".format(url)) res = requests.get(url, stream=True) if res.status_code != 200: # failed to download, cleanup and raise exception f.close() os.remove(tmp) error = "{0}\n\nFailed to download < {0} >".format(res.content, url) raise IOError(error) for block in res.iter_content(1024): f.write(block) f.close() return tmp
python
def download(self, output_dir, url, overwrite): """ Dowload file to /tmp """ tmp = self.url2tmp(output_dir, url) if os.path.isfile(tmp) and not overwrite: logging.info("File {0} already exists. Skipping download.".format(tmp)) return tmp f = open(tmp, 'wb') logging.info("Downloading {0}".format(url)) res = requests.get(url, stream=True) if res.status_code != 200: # failed to download, cleanup and raise exception f.close() os.remove(tmp) error = "{0}\n\nFailed to download < {0} >".format(res.content, url) raise IOError(error) for block in res.iter_content(1024): f.write(block) f.close() return tmp
[ "def", "download", "(", "self", ",", "output_dir", ",", "url", ",", "overwrite", ")", ":", "tmp", "=", "self", ".", "url2tmp", "(", "output_dir", ",", "url", ")", "if", "os", ".", "path", ".", "isfile", "(", "tmp", ")", "and", "not", "overwrite", ":", "logging", ".", "info", "(", "\"File {0} already exists. Skipping download.\"", ".", "format", "(", "tmp", ")", ")", "return", "tmp", "f", "=", "open", "(", "tmp", ",", "'wb'", ")", "logging", ".", "info", "(", "\"Downloading {0}\"", ".", "format", "(", "url", ")", ")", "res", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "if", "res", ".", "status_code", "!=", "200", ":", "# failed to download, cleanup and raise exception", "f", ".", "close", "(", ")", "os", ".", "remove", "(", "tmp", ")", "error", "=", "\"{0}\\n\\nFailed to download < {0} >\"", ".", "format", "(", "res", ".", "content", ",", "url", ")", "raise", "IOError", "(", "error", ")", "for", "block", "in", "res", ".", "iter_content", "(", "1024", ")", ":", "f", ".", "write", "(", "block", ")", "f", ".", "close", "(", ")", "return", "tmp" ]
Dowload file to /tmp
[ "Dowload", "file", "to", "/", "tmp" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L47-L65
meyersj/geotweet
geotweet/osm.py
OSMRunner.extract
def extract(self, pbf, output): """ extract POI nodes from osm pbf extract """ logging.info("Extracting POI nodes from {0} to {1}".format(pbf, output)) with open(output, 'w') as f: # define callback for each node that is processed def nodes_callback(nodes): for node in nodes: node_id, tags, coordinates = node # if any tags have a matching key then write record if any([t in tags for t in POI_TAGS]): f.write(json.dumps(dict(tags=tags, coordinates=coordinates))) f.write('\n') parser = OSMParser(concurrency=4, nodes_callback=nodes_callback) parser.parse(pbf) return output
python
def extract(self, pbf, output): """ extract POI nodes from osm pbf extract """ logging.info("Extracting POI nodes from {0} to {1}".format(pbf, output)) with open(output, 'w') as f: # define callback for each node that is processed def nodes_callback(nodes): for node in nodes: node_id, tags, coordinates = node # if any tags have a matching key then write record if any([t in tags for t in POI_TAGS]): f.write(json.dumps(dict(tags=tags, coordinates=coordinates))) f.write('\n') parser = OSMParser(concurrency=4, nodes_callback=nodes_callback) parser.parse(pbf) return output
[ "def", "extract", "(", "self", ",", "pbf", ",", "output", ")", ":", "logging", ".", "info", "(", "\"Extracting POI nodes from {0} to {1}\"", ".", "format", "(", "pbf", ",", "output", ")", ")", "with", "open", "(", "output", ",", "'w'", ")", "as", "f", ":", "# define callback for each node that is processed", "def", "nodes_callback", "(", "nodes", ")", ":", "for", "node", "in", "nodes", ":", "node_id", ",", "tags", ",", "coordinates", "=", "node", "# if any tags have a matching key then write record", "if", "any", "(", "[", "t", "in", "tags", "for", "t", "in", "POI_TAGS", "]", ")", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "dict", "(", "tags", "=", "tags", ",", "coordinates", "=", "coordinates", ")", ")", ")", "f", ".", "write", "(", "'\\n'", ")", "parser", "=", "OSMParser", "(", "concurrency", "=", "4", ",", "nodes_callback", "=", "nodes_callback", ")", "parser", ".", "parse", "(", "pbf", ")", "return", "output" ]
extract POI nodes from osm pbf extract
[ "extract", "POI", "nodes", "from", "osm", "pbf", "extract" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L67-L81
meyersj/geotweet
geotweet/osm.py
OSMRunner.url2tmp
def url2tmp(self, root, url): """ convert url path to filename """ filename = url.rsplit('/', 1)[-1] return os.path.join(root, filename)
python
def url2tmp(self, root, url): """ convert url path to filename """ filename = url.rsplit('/', 1)[-1] return os.path.join(root, filename)
[ "def", "url2tmp", "(", "self", ",", "root", ",", "url", ")", ":", "filename", "=", "url", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "-", "1", "]", "return", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")" ]
convert url path to filename
[ "convert", "url", "path", "to", "filename" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L86-L89
RudolfCardinal/pythonlib
cardinal_pythonlib/ui.py
ask_user
def ask_user(prompt: str, default: str = None) -> Optional[str]: """ Prompts the user, with a default. Returns user input from ``stdin``. """ if default is None: prompt += ": " else: prompt += " [" + default + "]: " result = input(prompt) return result if len(result) > 0 else default
python
def ask_user(prompt: str, default: str = None) -> Optional[str]: """ Prompts the user, with a default. Returns user input from ``stdin``. """ if default is None: prompt += ": " else: prompt += " [" + default + "]: " result = input(prompt) return result if len(result) > 0 else default
[ "def", "ask_user", "(", "prompt", ":", "str", ",", "default", ":", "str", "=", "None", ")", "->", "Optional", "[", "str", "]", ":", "if", "default", "is", "None", ":", "prompt", "+=", "\": \"", "else", ":", "prompt", "+=", "\" [\"", "+", "default", "+", "\"]: \"", "result", "=", "input", "(", "prompt", ")", "return", "result", "if", "len", "(", "result", ")", ">", "0", "else", "default" ]
Prompts the user, with a default. Returns user input from ``stdin``.
[ "Prompts", "the", "user", "with", "a", "default", ".", "Returns", "user", "input", "from", "stdin", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/ui.py#L44-L53
RudolfCardinal/pythonlib
cardinal_pythonlib/ui.py
get_save_as_filename
def get_save_as_filename(defaultfilename: str, defaultextension: str, title: str = "Save As") -> str: """ Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the filename. """ root = tkinter.Tk() # create and get Tk topmost window # (don't do this too early; the command prompt loses focus) root.withdraw() # won't need this; this gets rid of a blank Tk window root.attributes('-topmost', True) # makes the tk window topmost filename = filedialog.asksaveasfilename( initialfile=defaultfilename, defaultextension=defaultextension, parent=root, title=title ) root.attributes('-topmost', False) # stop the tk window being topmost return filename
python
def get_save_as_filename(defaultfilename: str, defaultextension: str, title: str = "Save As") -> str: """ Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the filename. """ root = tkinter.Tk() # create and get Tk topmost window # (don't do this too early; the command prompt loses focus) root.withdraw() # won't need this; this gets rid of a blank Tk window root.attributes('-topmost', True) # makes the tk window topmost filename = filedialog.asksaveasfilename( initialfile=defaultfilename, defaultextension=defaultextension, parent=root, title=title ) root.attributes('-topmost', False) # stop the tk window being topmost return filename
[ "def", "get_save_as_filename", "(", "defaultfilename", ":", "str", ",", "defaultextension", ":", "str", ",", "title", ":", "str", "=", "\"Save As\"", ")", "->", "str", ":", "root", "=", "tkinter", ".", "Tk", "(", ")", "# create and get Tk topmost window", "# (don't do this too early; the command prompt loses focus)", "root", ".", "withdraw", "(", ")", "# won't need this; this gets rid of a blank Tk window", "root", ".", "attributes", "(", "'-topmost'", ",", "True", ")", "# makes the tk window topmost", "filename", "=", "filedialog", ".", "asksaveasfilename", "(", "initialfile", "=", "defaultfilename", ",", "defaultextension", "=", "defaultextension", ",", "parent", "=", "root", ",", "title", "=", "title", ")", "root", ".", "attributes", "(", "'-topmost'", ",", "False", ")", "# stop the tk window being topmost", "return", "filename" ]
Provides a GUI "Save As" dialogue (via ``tkinter``) and returns the filename.
[ "Provides", "a", "GUI", "Save", "As", "dialogue", "(", "via", "tkinter", ")", "and", "returns", "the", "filename", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/ui.py#L63-L81
RudolfCardinal/pythonlib
cardinal_pythonlib/ui.py
get_open_filename
def get_open_filename(defaultfilename: str, defaultextension: str, title: str = "Open") -> str: """ Provides a GUI "Open" dialogue (via ``tkinter``) and returns the filename. """ root = tkinter.Tk() # create and get Tk topmost window # (don't do this too early; the command prompt loses focus) root.withdraw() # won't need this; this gets rid of a blank Tk window root.attributes('-topmost', True) # makes the tk window topmost filename = filedialog.askopenfilename( initialfile=defaultfilename, defaultextension=defaultextension, parent=root, title=title ) root.attributes('-topmost', False) # stop the tk window being topmost return filename
python
def get_open_filename(defaultfilename: str, defaultextension: str, title: str = "Open") -> str: """ Provides a GUI "Open" dialogue (via ``tkinter``) and returns the filename. """ root = tkinter.Tk() # create and get Tk topmost window # (don't do this too early; the command prompt loses focus) root.withdraw() # won't need this; this gets rid of a blank Tk window root.attributes('-topmost', True) # makes the tk window topmost filename = filedialog.askopenfilename( initialfile=defaultfilename, defaultextension=defaultextension, parent=root, title=title ) root.attributes('-topmost', False) # stop the tk window being topmost return filename
[ "def", "get_open_filename", "(", "defaultfilename", ":", "str", ",", "defaultextension", ":", "str", ",", "title", ":", "str", "=", "\"Open\"", ")", "->", "str", ":", "root", "=", "tkinter", ".", "Tk", "(", ")", "# create and get Tk topmost window", "# (don't do this too early; the command prompt loses focus)", "root", ".", "withdraw", "(", ")", "# won't need this; this gets rid of a blank Tk window", "root", ".", "attributes", "(", "'-topmost'", ",", "True", ")", "# makes the tk window topmost", "filename", "=", "filedialog", ".", "askopenfilename", "(", "initialfile", "=", "defaultfilename", ",", "defaultextension", "=", "defaultextension", ",", "parent", "=", "root", ",", "title", "=", "title", ")", "root", ".", "attributes", "(", "'-topmost'", ",", "False", ")", "# stop the tk window being topmost", "return", "filename" ]
Provides a GUI "Open" dialogue (via ``tkinter``) and returns the filename.
[ "Provides", "a", "GUI", "Open", "dialogue", "(", "via", "tkinter", ")", "and", "returns", "the", "filename", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/ui.py#L84-L101
RudolfCardinal/pythonlib
cardinal_pythonlib/argparse_func.py
str2bool
def str2bool(v: str) -> bool: """ ``argparse`` type that maps strings in case-insensitive fashion like this: .. code-block:: none argument strings value ------------------------------- ----- 'yes', 'true', 't', 'y', '1' True 'no', 'false', 'f', 'n', '0' False From https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse Specimen usage: .. code-block:: python parser.add_argument( "--nice", type=str2bool, nargs='?', const=True, # if --nice is present with no parameter default=NICE, # if the argument is entirely absent help="Activate nice mode.") """ # noqa lv = v.lower() if lv in ('yes', 'true', 't', 'y', '1'): return True elif lv in ('no', 'false', 'f', 'n', '0'): return False else: raise ArgumentTypeError('Boolean value expected.')
python
def str2bool(v: str) -> bool: """ ``argparse`` type that maps strings in case-insensitive fashion like this: .. code-block:: none argument strings value ------------------------------- ----- 'yes', 'true', 't', 'y', '1' True 'no', 'false', 'f', 'n', '0' False From https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse Specimen usage: .. code-block:: python parser.add_argument( "--nice", type=str2bool, nargs='?', const=True, # if --nice is present with no parameter default=NICE, # if the argument is entirely absent help="Activate nice mode.") """ # noqa lv = v.lower() if lv in ('yes', 'true', 't', 'y', '1'): return True elif lv in ('no', 'false', 'f', 'n', '0'): return False else: raise ArgumentTypeError('Boolean value expected.')
[ "def", "str2bool", "(", "v", ":", "str", ")", "->", "bool", ":", "# noqa", "lv", "=", "v", ".", "lower", "(", ")", "if", "lv", "in", "(", "'yes'", ",", "'true'", ",", "'t'", ",", "'y'", ",", "'1'", ")", ":", "return", "True", "elif", "lv", "in", "(", "'no'", ",", "'false'", ",", "'f'", ",", "'n'", ",", "'0'", ")", ":", "return", "False", "else", ":", "raise", "ArgumentTypeError", "(", "'Boolean value expected.'", ")" ]
``argparse`` type that maps strings in case-insensitive fashion like this: .. code-block:: none argument strings value ------------------------------- ----- 'yes', 'true', 't', 'y', '1' True 'no', 'false', 'f', 'n', '0' False From https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse Specimen usage: .. code-block:: python parser.add_argument( "--nice", type=str2bool, nargs='?', const=True, # if --nice is present with no parameter default=NICE, # if the argument is entirely absent help="Activate nice mode.")
[ "argparse", "type", "that", "maps", "strings", "in", "case", "-", "insensitive", "fashion", "like", "this", ":", "..", "code", "-", "block", "::", "none", "argument", "strings", "value", "-------------------------------", "-----", "yes", "true", "t", "y", "1", "True", "no", "false", "f", "n", "0", "False", "From", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "15008758", "/", "parsing", "-", "boolean", "-", "values", "-", "with", "-", "argparse" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/argparse_func.py#L101-L132
RudolfCardinal/pythonlib
cardinal_pythonlib/argparse_func.py
positive_int
def positive_int(value: str) -> int: """ ``argparse`` argument type that checks that its value is a positive integer. """ try: ivalue = int(value) assert ivalue > 0 except (AssertionError, TypeError, ValueError): raise ArgumentTypeError( "{!r} is an invalid positive int".format(value)) return ivalue
python
def positive_int(value: str) -> int: """ ``argparse`` argument type that checks that its value is a positive integer. """ try: ivalue = int(value) assert ivalue > 0 except (AssertionError, TypeError, ValueError): raise ArgumentTypeError( "{!r} is an invalid positive int".format(value)) return ivalue
[ "def", "positive_int", "(", "value", ":", "str", ")", "->", "int", ":", "try", ":", "ivalue", "=", "int", "(", "value", ")", "assert", "ivalue", ">", "0", "except", "(", "AssertionError", ",", "TypeError", ",", "ValueError", ")", ":", "raise", "ArgumentTypeError", "(", "\"{!r} is an invalid positive int\"", ".", "format", "(", "value", ")", ")", "return", "ivalue" ]
``argparse`` argument type that checks that its value is a positive integer.
[ "argparse", "argument", "type", "that", "checks", "that", "its", "value", "is", "a", "positive", "integer", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/argparse_func.py#L135-L146
RudolfCardinal/pythonlib
cardinal_pythonlib/argparse_func.py
percentage
def percentage(value: str) -> float: """ ``argparse`` argument type that checks that its value is a percentage (in the sense of a float in the range [0, 100]). """ try: fvalue = float(value) assert 0 <= fvalue <= 100 except (AssertionError, TypeError, ValueError): raise ArgumentTypeError( "{!r} is an invalid percentage value".format(value)) return fvalue
python
def percentage(value: str) -> float: """ ``argparse`` argument type that checks that its value is a percentage (in the sense of a float in the range [0, 100]). """ try: fvalue = float(value) assert 0 <= fvalue <= 100 except (AssertionError, TypeError, ValueError): raise ArgumentTypeError( "{!r} is an invalid percentage value".format(value)) return fvalue
[ "def", "percentage", "(", "value", ":", "str", ")", "->", "float", ":", "try", ":", "fvalue", "=", "float", "(", "value", ")", "assert", "0", "<=", "fvalue", "<=", "100", "except", "(", "AssertionError", ",", "TypeError", ",", "ValueError", ")", ":", "raise", "ArgumentTypeError", "(", "\"{!r} is an invalid percentage value\"", ".", "format", "(", "value", ")", ")", "return", "fvalue" ]
``argparse`` argument type that checks that its value is a percentage (in the sense of a float in the range [0, 100]).
[ "argparse", "argument", "type", "that", "checks", "that", "its", "value", "is", "a", "percentage", "(", "in", "the", "sense", "of", "a", "float", "in", "the", "range", "[", "0", "100", "]", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/argparse_func.py#L163-L174
calston/rhumba
rhumba/http_client.py
HTTPRequest.abort_request
def abort_request(self, request): """Called to abort request on timeout""" self.timedout = True try: request.cancel() except error.AlreadyCancelled: return
python
def abort_request(self, request): """Called to abort request on timeout""" self.timedout = True try: request.cancel() except error.AlreadyCancelled: return
[ "def", "abort_request", "(", "self", ",", "request", ")", ":", "self", ".", "timedout", "=", "True", "try", ":", "request", ".", "cancel", "(", ")", "except", "error", ".", "AlreadyCancelled", ":", "return" ]
Called to abort request on timeout
[ "Called", "to", "abort", "request", "on", "timeout" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/http_client.py#L69-L75
calston/rhumba
rhumba/http_client.py
HTTPRequest.getBody
def getBody(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Make an HTTP request and return the body """ if not 'User-Agent' in headers: headers['User-Agent'] = ['Tensor HTTP checker'] return cls().request(url, method, headers, data, socket, timeout)
python
def getBody(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Make an HTTP request and return the body """ if not 'User-Agent' in headers: headers['User-Agent'] = ['Tensor HTTP checker'] return cls().request(url, method, headers, data, socket, timeout)
[ "def", "getBody", "(", "cls", ",", "url", ",", "method", "=", "'GET'", ",", "headers", "=", "{", "}", ",", "data", "=", "None", ",", "socket", "=", "None", ",", "timeout", "=", "120", ")", ":", "if", "not", "'User-Agent'", "in", "headers", ":", "headers", "[", "'User-Agent'", "]", "=", "[", "'Tensor HTTP checker'", "]", "return", "cls", "(", ")", ".", "request", "(", "url", ",", "method", ",", "headers", ",", "data", ",", "socket", ",", "timeout", ")" ]
Make an HTTP request and return the body
[ "Make", "an", "HTTP", "request", "and", "return", "the", "body" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/http_client.py#L131-L137
calston/rhumba
rhumba/http_client.py
HTTPRequest.getJson
def getJson(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Fetch a JSON result via HTTP """ if not 'Content-Type' in headers: headers['Content-Type'] = ['application/json'] body = yield cls().getBody(url, method, headers, data, socket, timeout) defer.returnValue(json.loads(body))
python
def getJson(cls, url, method='GET', headers={}, data=None, socket=None, timeout=120): """Fetch a JSON result via HTTP """ if not 'Content-Type' in headers: headers['Content-Type'] = ['application/json'] body = yield cls().getBody(url, method, headers, data, socket, timeout) defer.returnValue(json.loads(body))
[ "def", "getJson", "(", "cls", ",", "url", ",", "method", "=", "'GET'", ",", "headers", "=", "{", "}", ",", "data", "=", "None", ",", "socket", "=", "None", ",", "timeout", "=", "120", ")", ":", "if", "not", "'Content-Type'", "in", "headers", ":", "headers", "[", "'Content-Type'", "]", "=", "[", "'application/json'", "]", "body", "=", "yield", "cls", "(", ")", ".", "getBody", "(", "url", ",", "method", ",", "headers", ",", "data", ",", "socket", ",", "timeout", ")", "defer", ".", "returnValue", "(", "json", ".", "loads", "(", "body", ")", ")" ]
Fetch a JSON result via HTTP
[ "Fetch", "a", "JSON", "result", "via", "HTTP" ]
train
https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/http_client.py#L141-L149
davenquinn/Attitude
attitude/geom/__init__.py
aligned_covariance
def aligned_covariance(fit, type='noise'): """ Covariance rescaled so that eigenvectors sum to 1 and rotated into data coordinates from PCA space """ cov = fit._covariance_matrix(type) # Rescale eigenvectors to sum to 1 cov /= N.linalg.norm(cov) return dot(fit.axes,cov)
python
def aligned_covariance(fit, type='noise'): """ Covariance rescaled so that eigenvectors sum to 1 and rotated into data coordinates from PCA space """ cov = fit._covariance_matrix(type) # Rescale eigenvectors to sum to 1 cov /= N.linalg.norm(cov) return dot(fit.axes,cov)
[ "def", "aligned_covariance", "(", "fit", ",", "type", "=", "'noise'", ")", ":", "cov", "=", "fit", ".", "_covariance_matrix", "(", "type", ")", "# Rescale eigenvectors to sum to 1", "cov", "/=", "N", ".", "linalg", ".", "norm", "(", "cov", ")", "return", "dot", "(", "fit", ".", "axes", ",", "cov", ")" ]
Covariance rescaled so that eigenvectors sum to 1 and rotated into data coordinates from PCA space
[ "Covariance", "rescaled", "so", "that", "eigenvectors", "sum", "to", "1", "and", "rotated", "into", "data", "coordinates", "from", "PCA", "space" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/__init__.py#L7-L15