repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
renatahodovan/antlerinator
antlerinator/install.py
execute
def execute(): """ Entry point of the install helper tool to ease the download of the right version of the ANTLR v4 tool jar. """ arg_parser = ArgumentParser(description='Install helper tool to download the right version of the ANTLR v4 tool jar.') arg_parser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=__version__)) mode_group = arg_parser.add_mutually_exclusive_group() mode_group.add_argument('-f', '--force', action='store_true', default=False, help='force download even if local antlr4.jar already exists') mode_group.add_argument('-l', '--lazy', action='store_true', default=False, help='don\'t report an error if local antlr4.jar already exists and don\'t try to download it either') args = arg_parser.parse_args() install(force=args.force, lazy=args.lazy)
python
def execute(): """ Entry point of the install helper tool to ease the download of the right version of the ANTLR v4 tool jar. """ arg_parser = ArgumentParser(description='Install helper tool to download the right version of the ANTLR v4 tool jar.') arg_parser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=__version__)) mode_group = arg_parser.add_mutually_exclusive_group() mode_group.add_argument('-f', '--force', action='store_true', default=False, help='force download even if local antlr4.jar already exists') mode_group.add_argument('-l', '--lazy', action='store_true', default=False, help='don\'t report an error if local antlr4.jar already exists and don\'t try to download it either') args = arg_parser.parse_args() install(force=args.force, lazy=args.lazy)
[ "def", "execute", "(", ")", ":", "arg_parser", "=", "ArgumentParser", "(", "description", "=", "'Install helper tool to download the right version of the ANTLR v4 tool jar.'", ")", "arg_parser", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'version'", ","...
Entry point of the install helper tool to ease the download of the right version of the ANTLR v4 tool jar.
[ "Entry", "point", "of", "the", "install", "helper", "tool", "to", "ease", "the", "download", "of", "the", "right", "version", "of", "the", "ANTLR", "v4", "tool", "jar", "." ]
02b165d758014bc064991e5dbc05f4b39f2bb5c9
https://github.com/renatahodovan/antlerinator/blob/02b165d758014bc064991e5dbc05f4b39f2bb5c9/antlerinator/install.py#L57-L75
train
53,100
RudolfCardinal/pythonlib
cardinal_pythonlib/tsv.py
make_tsv_row
def make_tsv_row(values: List[Any]) -> str: """ From a list of values, make a TSV line. """ return "\t".join([tsv_escape(x) for x in values]) + "\n"
python
def make_tsv_row(values: List[Any]) -> str: """ From a list of values, make a TSV line. """ return "\t".join([tsv_escape(x) for x in values]) + "\n"
[ "def", "make_tsv_row", "(", "values", ":", "List", "[", "Any", "]", ")", "->", "str", ":", "return", "\"\\t\"", ".", "join", "(", "[", "tsv_escape", "(", "x", ")", "for", "x", "in", "values", "]", ")", "+", "\"\\n\"" ]
From a list of values, make a TSV line.
[ "From", "a", "list", "of", "values", "make", "a", "TSV", "line", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tsv.py#L48-L52
train
53,101
RudolfCardinal/pythonlib
cardinal_pythonlib/tsv.py
dictlist_to_tsv
def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str: """ From a consistent list of dictionaries mapping fieldnames to values, make a TSV file. """ if not dictlist: return "" fieldnames = dictlist[0].keys() tsv = "\t".join([tsv_escape(f) for f in fieldnames]) + "\n" for d in dictlist: tsv += "\t".join([tsv_escape(v) for v in d.values()]) + "\n" return tsv
python
def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str: """ From a consistent list of dictionaries mapping fieldnames to values, make a TSV file. """ if not dictlist: return "" fieldnames = dictlist[0].keys() tsv = "\t".join([tsv_escape(f) for f in fieldnames]) + "\n" for d in dictlist: tsv += "\t".join([tsv_escape(v) for v in d.values()]) + "\n" return tsv
[ "def", "dictlist_to_tsv", "(", "dictlist", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "str", ":", "if", "not", "dictlist", ":", "return", "\"\"", "fieldnames", "=", "dictlist", "[", "0", "]", ".", "keys", "(", ")", "tsv"...
From a consistent list of dictionaries mapping fieldnames to values, make a TSV file.
[ "From", "a", "consistent", "list", "of", "dictionaries", "mapping", "fieldnames", "to", "values", "make", "a", "TSV", "file", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tsv.py#L55-L66
train
53,102
RudolfCardinal/pythonlib
cardinal_pythonlib/modules.py
import_submodules
def import_submodules(package: Union[str, ModuleType], base_package_for_relative_import: str = None, recursive: bool = True) -> Dict[str, ModuleType]: """ Import all submodules of a module, recursively, including subpackages. Args: package: package (name or actual module) base_package_for_relative_import: path to prepend? recursive: import submodules too? Returns: dict: mapping from full module name to module """ # http://stackoverflow.com/questions/3365740/how-to-import-all-submodules if isinstance(package, str): package = importlib.import_module(package, base_package_for_relative_import) results = {} for loader, name, is_pkg in pkgutil.walk_packages(package.__path__): full_name = package.__name__ + '.' + name log.debug("importing: {}", full_name) results[full_name] = importlib.import_module(full_name) if recursive and is_pkg: results.update(import_submodules(full_name)) return results
python
def import_submodules(package: Union[str, ModuleType], base_package_for_relative_import: str = None, recursive: bool = True) -> Dict[str, ModuleType]: """ Import all submodules of a module, recursively, including subpackages. Args: package: package (name or actual module) base_package_for_relative_import: path to prepend? recursive: import submodules too? Returns: dict: mapping from full module name to module """ # http://stackoverflow.com/questions/3365740/how-to-import-all-submodules if isinstance(package, str): package = importlib.import_module(package, base_package_for_relative_import) results = {} for loader, name, is_pkg in pkgutil.walk_packages(package.__path__): full_name = package.__name__ + '.' + name log.debug("importing: {}", full_name) results[full_name] = importlib.import_module(full_name) if recursive and is_pkg: results.update(import_submodules(full_name)) return results
[ "def", "import_submodules", "(", "package", ":", "Union", "[", "str", ",", "ModuleType", "]", ",", "base_package_for_relative_import", ":", "str", "=", "None", ",", "recursive", ":", "bool", "=", "True", ")", "->", "Dict", "[", "str", ",", "ModuleType", "]...
Import all submodules of a module, recursively, including subpackages. Args: package: package (name or actual module) base_package_for_relative_import: path to prepend? recursive: import submodules too? Returns: dict: mapping from full module name to module
[ "Import", "all", "submodules", "of", "a", "module", "recursively", "including", "subpackages", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/modules.py#L48-L74
train
53,103
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
preserve_cwd
def preserve_cwd(func: Callable) -> Callable: """ Decorator to preserve the current working directory in calls to the decorated function. Example: .. code-block:: python @preserve_cwd def myfunc(): os.chdir("/faraway") os.chdir("/home") myfunc() assert os.getcwd() == "/home" """ # http://stackoverflow.com/questions/169070/python-how-do-i-write-a-decorator-that-restores-the-cwd # noqa def decorator(*args_, **kwargs) -> Any: cwd = os.getcwd() result = func(*args_, **kwargs) os.chdir(cwd) return result return decorator
python
def preserve_cwd(func: Callable) -> Callable: """ Decorator to preserve the current working directory in calls to the decorated function. Example: .. code-block:: python @preserve_cwd def myfunc(): os.chdir("/faraway") os.chdir("/home") myfunc() assert os.getcwd() == "/home" """ # http://stackoverflow.com/questions/169070/python-how-do-i-write-a-decorator-that-restores-the-cwd # noqa def decorator(*args_, **kwargs) -> Any: cwd = os.getcwd() result = func(*args_, **kwargs) os.chdir(cwd) return result return decorator
[ "def", "preserve_cwd", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "# http://stackoverflow.com/questions/169070/python-how-do-i-write-a-decorator-that-restores-the-cwd # noqa", "def", "decorator", "(", "*", "args_", ",", "*", "*", "kwargs", ")", "->", "Any"...
Decorator to preserve the current working directory in calls to the decorated function. Example: .. code-block:: python @preserve_cwd def myfunc(): os.chdir("/faraway") os.chdir("/home") myfunc() assert os.getcwd() == "/home"
[ "Decorator", "to", "preserve", "the", "current", "working", "directory", "in", "calls", "to", "the", "decorated", "function", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L117-L140
train
53,104
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
copyglob
def copyglob(src: str, dest: str, allow_nothing: bool = False, allow_nonfiles: bool = False) -> None: """ Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_nothing is True. Args: src: source glob (e.g. ``/somewhere/*.txt``) dest: destination directory allow_nothing: don't raise an exception if no files are found allow_nonfiles: copy things that are not files too (as judged by :func:`os.path.isfile`). Raises: ValueError: if no files are found and ``allow_nothing`` is not set """ something = False for filename in glob.glob(src): if allow_nonfiles or os.path.isfile(filename): shutil.copy(filename, dest) something = True if something or allow_nothing: return raise ValueError("No files found matching: {}".format(src))
python
def copyglob(src: str, dest: str, allow_nothing: bool = False, allow_nonfiles: bool = False) -> None: """ Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_nothing is True. Args: src: source glob (e.g. ``/somewhere/*.txt``) dest: destination directory allow_nothing: don't raise an exception if no files are found allow_nonfiles: copy things that are not files too (as judged by :func:`os.path.isfile`). Raises: ValueError: if no files are found and ``allow_nothing`` is not set """ something = False for filename in glob.glob(src): if allow_nonfiles or os.path.isfile(filename): shutil.copy(filename, dest) something = True if something or allow_nothing: return raise ValueError("No files found matching: {}".format(src))
[ "def", "copyglob", "(", "src", ":", "str", ",", "dest", ":", "str", ",", "allow_nothing", ":", "bool", "=", "False", ",", "allow_nonfiles", ":", "bool", "=", "False", ")", "->", "None", ":", "something", "=", "False", "for", "filename", "in", "glob", ...
Copies files whose filenames match the glob src" into the directory "dest". Raises an error if no files are copied, unless allow_nothing is True. Args: src: source glob (e.g. ``/somewhere/*.txt``) dest: destination directory allow_nothing: don't raise an exception if no files are found allow_nonfiles: copy things that are not files too (as judged by :func:`os.path.isfile`). Raises: ValueError: if no files are found and ``allow_nothing`` is not set
[ "Copies", "files", "whose", "filenames", "match", "the", "glob", "src", "into", "the", "directory", "dest", ".", "Raises", "an", "error", "if", "no", "files", "are", "copied", "unless", "allow_nothing", "is", "True", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L155-L179
train
53,105
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
rmtree
def rmtree(directory: str) -> None: """ Deletes a directory tree. """ log.debug("Deleting directory {!r}", directory) shutil.rmtree(directory, onerror=shutil_rmtree_onerror)
python
def rmtree(directory: str) -> None: """ Deletes a directory tree. """ log.debug("Deleting directory {!r}", directory) shutil.rmtree(directory, onerror=shutil_rmtree_onerror)
[ "def", "rmtree", "(", "directory", ":", "str", ")", "->", "None", ":", "log", ".", "debug", "(", "\"Deleting directory {!r}\"", ",", "directory", ")", "shutil", ".", "rmtree", "(", "directory", ",", "onerror", "=", "shutil_rmtree_onerror", ")" ]
Deletes a directory tree.
[ "Deletes", "a", "directory", "tree", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L335-L340
train
53,106
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
chown_r
def chown_r(path: str, user: str, group: str) -> None: """ Performs a recursive ``chown``. Args: path: path to walk down user: user name or ID group: group name or ID As per http://stackoverflow.com/questions/2853723 """ for root, dirs, files in os.walk(path): for x in dirs: shutil.chown(os.path.join(root, x), user, group) for x in files: shutil.chown(os.path.join(root, x), user, group)
python
def chown_r(path: str, user: str, group: str) -> None: """ Performs a recursive ``chown``. Args: path: path to walk down user: user name or ID group: group name or ID As per http://stackoverflow.com/questions/2853723 """ for root, dirs, files in os.walk(path): for x in dirs: shutil.chown(os.path.join(root, x), user, group) for x in files: shutil.chown(os.path.join(root, x), user, group)
[ "def", "chown_r", "(", "path", ":", "str", ",", "user", ":", "str", ",", "group", ":", "str", ")", "->", "None", ":", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "x", "in", "dirs", ":", "sh...
Performs a recursive ``chown``. Args: path: path to walk down user: user name or ID group: group name or ID As per http://stackoverflow.com/questions/2853723
[ "Performs", "a", "recursive", "chown", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L347-L362
train
53,107
RudolfCardinal/pythonlib
cardinal_pythonlib/fileops.py
chmod_r
def chmod_r(root: str, permission: int) -> None: """ Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR`` """ os.chmod(root, permission) for dirpath, dirnames, filenames in os.walk(root): for d in dirnames: os.chmod(os.path.join(dirpath, d), permission) for f in filenames: os.chmod(os.path.join(dirpath, f), permission)
python
def chmod_r(root: str, permission: int) -> None: """ Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR`` """ os.chmod(root, permission) for dirpath, dirnames, filenames in os.walk(root): for d in dirnames: os.chmod(os.path.join(dirpath, d), permission) for f in filenames: os.chmod(os.path.join(dirpath, f), permission)
[ "def", "chmod_r", "(", "root", ":", "str", ",", "permission", ":", "int", ")", "->", "None", ":", "os", ".", "chmod", "(", "root", ",", "permission", ")", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "root", ")...
Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR``
[ "Recursive", "chmod", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/fileops.py#L365-L378
train
53,108
smtp2go-oss/smtp2go-python
smtp2go/core.py
Smtp2goResponse._get_errors
def _get_errors(self): """ Gets errors from HTTP response """ errors = self.json.get('data').get('failures') if errors: logger.error(errors) return errors
python
def _get_errors(self): """ Gets errors from HTTP response """ errors = self.json.get('data').get('failures') if errors: logger.error(errors) return errors
[ "def", "_get_errors", "(", "self", ")", ":", "errors", "=", "self", ".", "json", ".", "get", "(", "'data'", ")", ".", "get", "(", "'failures'", ")", "if", "errors", ":", "logger", ".", "error", "(", "errors", ")", "return", "errors" ]
Gets errors from HTTP response
[ "Gets", "errors", "from", "HTTP", "response" ]
581cc33b1c6f4ca2882535a51a787c33e5cfcce7
https://github.com/smtp2go-oss/smtp2go-python/blob/581cc33b1c6f4ca2882535a51a787c33e5cfcce7/smtp2go/core.py#L120-L127
train
53,109
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
page_sequence
def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: """ Generates the final page sequence from the starting number of sheets. """ n_pages = calc_n_virtual_pages(n_sheets) assert n_pages % 4 == 0 half_n_pages = n_pages // 2 firsthalf = list(range(half_n_pages)) secondhalf = list(reversed(range(half_n_pages, n_pages))) # Seen from the top of an UNFOLDED booklet (e.g. a stack of paper that's # come out of your printer), "firsthalf" are on the right (from top to # bottom: recto facing up, then verso facing down, then recto, then verso) # and "secondhalf" are on the left (from top to bottom: verso facing up, # then recto facing down, etc.). sequence = [] # type: List[int] top = True for left, right in zip(secondhalf, firsthalf): if not top: left, right = right, left sequence += [left, right] top = not top if one_based: sequence = [x + 1 for x in sequence] log.debug("{} sheets => page sequence {!r}", n_sheets, sequence) return sequence
python
def page_sequence(n_sheets: int, one_based: bool = True) -> List[int]: """ Generates the final page sequence from the starting number of sheets. """ n_pages = calc_n_virtual_pages(n_sheets) assert n_pages % 4 == 0 half_n_pages = n_pages // 2 firsthalf = list(range(half_n_pages)) secondhalf = list(reversed(range(half_n_pages, n_pages))) # Seen from the top of an UNFOLDED booklet (e.g. a stack of paper that's # come out of your printer), "firsthalf" are on the right (from top to # bottom: recto facing up, then verso facing down, then recto, then verso) # and "secondhalf" are on the left (from top to bottom: verso facing up, # then recto facing down, etc.). sequence = [] # type: List[int] top = True for left, right in zip(secondhalf, firsthalf): if not top: left, right = right, left sequence += [left, right] top = not top if one_based: sequence = [x + 1 for x in sequence] log.debug("{} sheets => page sequence {!r}", n_sheets, sequence) return sequence
[ "def", "page_sequence", "(", "n_sheets", ":", "int", ",", "one_based", ":", "bool", "=", "True", ")", "->", "List", "[", "int", "]", ":", "n_pages", "=", "calc_n_virtual_pages", "(", "n_sheets", ")", "assert", "n_pages", "%", "4", "==", "0", "half_n_page...
Generates the final page sequence from the starting number of sheets.
[ "Generates", "the", "final", "page", "sequence", "from", "the", "starting", "number", "of", "sheets", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L161-L185
train
53,110
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
require
def require(executable: str, explanation: str = "") -> None: """ Ensures that the external tool is available. Asserts upon failure. """ assert shutil.which(executable), "Need {!r} on the PATH.{}".format( executable, "\n" + explanation if explanation else "")
python
def require(executable: str, explanation: str = "") -> None: """ Ensures that the external tool is available. Asserts upon failure. """ assert shutil.which(executable), "Need {!r} on the PATH.{}".format( executable, "\n" + explanation if explanation else "")
[ "def", "require", "(", "executable", ":", "str", ",", "explanation", ":", "str", "=", "\"\"", ")", "->", "None", ":", "assert", "shutil", ".", "which", "(", "executable", ")", ",", "\"Need {!r} on the PATH.{}\"", ".", "format", "(", "executable", ",", "\"\...
Ensures that the external tool is available. Asserts upon failure.
[ "Ensures", "that", "the", "external", "tool", "is", "available", ".", "Asserts", "upon", "failure", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L192-L198
train
53,111
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
get_page_count
def get_page_count(filename: str) -> int: """ How many pages are in a PDF? """ log.debug("Getting page count for {!r}", filename) require(PDFTK, HELP_MISSING_PDFTK) stdout, _ = run([PDFTK, filename, "dump_data"], get_output=True) regex = re.compile(r"^NumberOfPages: (\d+)$", re.MULTILINE) m = regex.search(stdout) if m: return int(m.group(1)) raise ValueError("Can't get PDF page count for: {!r}".format(filename))
python
def get_page_count(filename: str) -> int: """ How many pages are in a PDF? """ log.debug("Getting page count for {!r}", filename) require(PDFTK, HELP_MISSING_PDFTK) stdout, _ = run([PDFTK, filename, "dump_data"], get_output=True) regex = re.compile(r"^NumberOfPages: (\d+)$", re.MULTILINE) m = regex.search(stdout) if m: return int(m.group(1)) raise ValueError("Can't get PDF page count for: {!r}".format(filename))
[ "def", "get_page_count", "(", "filename", ":", "str", ")", "->", "int", ":", "log", ".", "debug", "(", "\"Getting page count for {!r}\"", ",", "filename", ")", "require", "(", "PDFTK", ",", "HELP_MISSING_PDFTK", ")", "stdout", ",", "_", "=", "run", "(", "[...
How many pages are in a PDF?
[ "How", "many", "pages", "are", "in", "a", "PDF?" ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L221-L232
train
53,112
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
make_blank_pdf
def make_blank_pdf(filename: str, paper: str = "A4") -> None: """ NOT USED. Makes a blank single-page PDF, using ImageMagick's ``convert``. """ # https://unix.stackexchange.com/questions/277892/how-do-i-create-a-blank-pdf-from-the-command-line # noqa require(CONVERT, HELP_MISSING_IMAGEMAGICK) run([CONVERT, "xc:none", "-page", paper, filename])
python
def make_blank_pdf(filename: str, paper: str = "A4") -> None: """ NOT USED. Makes a blank single-page PDF, using ImageMagick's ``convert``. """ # https://unix.stackexchange.com/questions/277892/how-do-i-create-a-blank-pdf-from-the-command-line # noqa require(CONVERT, HELP_MISSING_IMAGEMAGICK) run([CONVERT, "xc:none", "-page", paper, filename])
[ "def", "make_blank_pdf", "(", "filename", ":", "str", ",", "paper", ":", "str", "=", "\"A4\"", ")", "->", "None", ":", "# https://unix.stackexchange.com/questions/277892/how-do-i-create-a-blank-pdf-from-the-command-line # noqa", "require", "(", "CONVERT", ",", "HELP_MISSIN...
NOT USED. Makes a blank single-page PDF, using ImageMagick's ``convert``.
[ "NOT", "USED", ".", "Makes", "a", "blank", "single", "-", "page", "PDF", "using", "ImageMagick", "s", "convert", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L235-L242
train
53,113
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
slice_pdf
def slice_pdf(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int) -> str: """ Slice each page of the original, to convert to "one real page per PDF page". Return the output filename. """ if slice_horiz == 1 and slice_vert == 1: log.debug("No slicing required") return input_filename # nothing to do log.info("Slicing each source page mv into {} horizontally x {} vertically", slice_horiz, slice_vert) log.debug("... from {!r} to {!r}", input_filename, output_filename) require(MUTOOL, HELP_MISSING_MUTOOL) run([ MUTOOL, "poster", "-x", str(slice_horiz), "-y", str(slice_vert), input_filename, output_filename ]) return output_filename
python
def slice_pdf(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int) -> str: """ Slice each page of the original, to convert to "one real page per PDF page". Return the output filename. """ if slice_horiz == 1 and slice_vert == 1: log.debug("No slicing required") return input_filename # nothing to do log.info("Slicing each source page mv into {} horizontally x {} vertically", slice_horiz, slice_vert) log.debug("... from {!r} to {!r}", input_filename, output_filename) require(MUTOOL, HELP_MISSING_MUTOOL) run([ MUTOOL, "poster", "-x", str(slice_horiz), "-y", str(slice_vert), input_filename, output_filename ]) return output_filename
[ "def", "slice_pdf", "(", "input_filename", ":", "str", ",", "output_filename", ":", "str", ",", "slice_horiz", ":", "int", ",", "slice_vert", ":", "int", ")", "->", "str", ":", "if", "slice_horiz", "==", "1", "and", "slice_vert", "==", "1", ":", "log", ...
Slice each page of the original, to convert to "one real page per PDF page". Return the output filename.
[ "Slice", "each", "page", "of", "the", "original", "to", "convert", "to", "one", "real", "page", "per", "PDF", "page", ".", "Return", "the", "output", "filename", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L245-L266
train
53,114
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
rotate_even_pages_180
def rotate_even_pages_180(input_filename: str, output_filename: str) -> str: """ Rotates even-numbered pages 180 degrees. Returns the output filename. """ log.info("Rotating even-numbered pages 180 degrees for long-edge " "duplex printing") log.debug("... {!r} -> {!r}", input_filename, output_filename) require(PDFTK, HELP_MISSING_PDFTK) args = [ PDFTK, "A=" + input_filename, # give it handle 'A' # handles are one or more UPPER CASE letters "shuffle", "Aoddnorth", # for 'A', keep odd pages as they are "Aevensouth", # for 'A', rotate even pages 180 degrees "output", output_filename, ] run(args) return output_filename
python
def rotate_even_pages_180(input_filename: str, output_filename: str) -> str: """ Rotates even-numbered pages 180 degrees. Returns the output filename. """ log.info("Rotating even-numbered pages 180 degrees for long-edge " "duplex printing") log.debug("... {!r} -> {!r}", input_filename, output_filename) require(PDFTK, HELP_MISSING_PDFTK) args = [ PDFTK, "A=" + input_filename, # give it handle 'A' # handles are one or more UPPER CASE letters "shuffle", "Aoddnorth", # for 'A', keep odd pages as they are "Aevensouth", # for 'A', rotate even pages 180 degrees "output", output_filename, ] run(args) return output_filename
[ "def", "rotate_even_pages_180", "(", "input_filename", ":", "str", ",", "output_filename", ":", "str", ")", "->", "str", ":", "log", ".", "info", "(", "\"Rotating even-numbered pages 180 degrees for long-edge \"", "\"duplex printing\"", ")", "log", ".", "debug", "(", ...
Rotates even-numbered pages 180 degrees. Returns the output filename.
[ "Rotates", "even", "-", "numbered", "pages", "180", "degrees", ".", "Returns", "the", "output", "filename", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L304-L323
train
53,115
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/pdf_to_booklet.py
convert_to_foldable
def convert_to_foldable(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int, overwrite: bool = False, longedge: bool = False, latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> bool: """ Runs a chain of tasks to convert a PDF to a useful booklet PDF. """ if not os.path.isfile(input_filename): log.warning("Input file does not exist or is not a file") return False if not overwrite and os.path.isfile(output_filename): log.error("Output file exists; not authorized to overwrite (use " "--overwrite if you are sure)") return False log.info("Processing {!r}", input_filename) with tempfile.TemporaryDirectory() as tmpdir: log.debug("Using temporary directory {!r}", tmpdir) intermediate_num = 0 def make_intermediate() -> str: nonlocal intermediate_num intermediate_num += 1 return os.path.join(tmpdir, "intermediate_{}.pdf".format(intermediate_num)) # Run this as a chain, rewriting input_filename at each step: # Slice, if necessary. input_filename = slice_pdf( input_filename=input_filename, output_filename=make_intermediate(), slice_horiz=slice_horiz, slice_vert=slice_vert ) # Make the final n-up input_filename = booklet_nup_pdf( input_filename=input_filename, output_filename=make_intermediate(), latex_paper_size=latex_paper_size ) # Rotate? if longedge: input_filename = rotate_even_pages_180( input_filename=input_filename, output_filename=make_intermediate(), ) # Done. log.info("Writing to {!r}", output_filename) shutil.move(input_filename, output_filename) return True
python
def convert_to_foldable(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int, overwrite: bool = False, longedge: bool = False, latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> bool: """ Runs a chain of tasks to convert a PDF to a useful booklet PDF. """ if not os.path.isfile(input_filename): log.warning("Input file does not exist or is not a file") return False if not overwrite and os.path.isfile(output_filename): log.error("Output file exists; not authorized to overwrite (use " "--overwrite if you are sure)") return False log.info("Processing {!r}", input_filename) with tempfile.TemporaryDirectory() as tmpdir: log.debug("Using temporary directory {!r}", tmpdir) intermediate_num = 0 def make_intermediate() -> str: nonlocal intermediate_num intermediate_num += 1 return os.path.join(tmpdir, "intermediate_{}.pdf".format(intermediate_num)) # Run this as a chain, rewriting input_filename at each step: # Slice, if necessary. input_filename = slice_pdf( input_filename=input_filename, output_filename=make_intermediate(), slice_horiz=slice_horiz, slice_vert=slice_vert ) # Make the final n-up input_filename = booklet_nup_pdf( input_filename=input_filename, output_filename=make_intermediate(), latex_paper_size=latex_paper_size ) # Rotate? if longedge: input_filename = rotate_even_pages_180( input_filename=input_filename, output_filename=make_intermediate(), ) # Done. log.info("Writing to {!r}", output_filename) shutil.move(input_filename, output_filename) return True
[ "def", "convert_to_foldable", "(", "input_filename", ":", "str", ",", "output_filename", ":", "str", ",", "slice_horiz", ":", "int", ",", "slice_vert", ":", "int", ",", "overwrite", ":", "bool", "=", "False", ",", "longedge", ":", "bool", "=", "False", ","...
Runs a chain of tasks to convert a PDF to a useful booklet PDF.
[ "Runs", "a", "chain", "of", "tasks", "to", "convert", "a", "PDF", "to", "a", "useful", "booklet", "PDF", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/pdf_to_booklet.py#L326-L377
train
53,116
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/estimate_mysql_memory_usage.py
get_mysql_vars
def get_mysql_vars(mysql: str, host: str, port: int, user: str) -> Dict[str, str]: """ Asks MySQL for its variables and status. Args: mysql: ``mysql`` executable filename host: host name port: TCP/IP port number user: username Returns: dictionary of MySQL variables/values """ cmdargs = [ mysql, "-h", host, "-P", str(port), "-e", "SHOW VARIABLES; SHOW STATUS", "-u", user, "-p" # prompt for password ] log.info("Connecting to MySQL with user: {}", user) log.debug(cmdargs) process = subprocess.Popen(cmdargs, stdout=subprocess.PIPE) out, err = process.communicate() lines = out.decode("utf8").splitlines() mysqlvars = {} for line in lines: var, val = line.split("\t") mysqlvars[var] = val return mysqlvars
python
def get_mysql_vars(mysql: str, host: str, port: int, user: str) -> Dict[str, str]: """ Asks MySQL for its variables and status. Args: mysql: ``mysql`` executable filename host: host name port: TCP/IP port number user: username Returns: dictionary of MySQL variables/values """ cmdargs = [ mysql, "-h", host, "-P", str(port), "-e", "SHOW VARIABLES; SHOW STATUS", "-u", user, "-p" # prompt for password ] log.info("Connecting to MySQL with user: {}", user) log.debug(cmdargs) process = subprocess.Popen(cmdargs, stdout=subprocess.PIPE) out, err = process.communicate() lines = out.decode("utf8").splitlines() mysqlvars = {} for line in lines: var, val = line.split("\t") mysqlvars[var] = val return mysqlvars
[ "def", "get_mysql_vars", "(", "mysql", ":", "str", ",", "host", ":", "str", ",", "port", ":", "int", ",", "user", ":", "str", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "cmdargs", "=", "[", "mysql", ",", "\"-h\"", ",", "host", ",", "\...
Asks MySQL for its variables and status. Args: mysql: ``mysql`` executable filename host: host name port: TCP/IP port number user: username Returns: dictionary of MySQL variables/values
[ "Asks", "MySQL", "for", "its", "variables", "and", "status", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/estimate_mysql_memory_usage.py#L54-L88
train
53,117
RudolfCardinal/pythonlib
cardinal_pythonlib/tools/estimate_mysql_memory_usage.py
add_var_mb
def add_var_mb(table: PrettyTable, vardict: Dict[str, str], varname: str) -> None: """ Adds a row to ``table`` for ``varname``, in megabytes. """ valstr = vardict.get(varname, None) table.add_row([varname, val_mb(valstr), UNITS_MB])
python
def add_var_mb(table: PrettyTable, vardict: Dict[str, str], varname: str) -> None: """ Adds a row to ``table`` for ``varname``, in megabytes. """ valstr = vardict.get(varname, None) table.add_row([varname, val_mb(valstr), UNITS_MB])
[ "def", "add_var_mb", "(", "table", ":", "PrettyTable", ",", "vardict", ":", "Dict", "[", "str", ",", "str", "]", ",", "varname", ":", "str", ")", "->", "None", ":", "valstr", "=", "vardict", ".", "get", "(", "varname", ",", "None", ")", "table", "....
Adds a row to ``table`` for ``varname``, in megabytes.
[ "Adds", "a", "row", "to", "table", "for", "varname", "in", "megabytes", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/estimate_mysql_memory_usage.py#L108-L115
train
53,118
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/grep_in_openxml.py
report_line
def report_line(zipfilename: str, contentsfilename: str, line: str, show_inner_file: bool) -> None: """ Prints a line from a file, with the ``.zip`` filename and optionally also the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filename of the inner file line: the line from the inner file show_inner_file: if ``True``, show both filenames; if ``False``, show just the ``.zip`` filename """ if show_inner_file: print("{} [{}]: {}".format(zipfilename, contentsfilename, line)) else: print("{}: {}".format(zipfilename, line))
python
def report_line(zipfilename: str, contentsfilename: str, line: str, show_inner_file: bool) -> None: """ Prints a line from a file, with the ``.zip`` filename and optionally also the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filename of the inner file line: the line from the inner file show_inner_file: if ``True``, show both filenames; if ``False``, show just the ``.zip`` filename """ if show_inner_file: print("{} [{}]: {}".format(zipfilename, contentsfilename, line)) else: print("{}: {}".format(zipfilename, line))
[ "def", "report_line", "(", "zipfilename", ":", "str", ",", "contentsfilename", ":", "str", ",", "line", ":", "str", ",", "show_inner_file", ":", "bool", ")", "->", "None", ":", "if", "show_inner_file", ":", "print", "(", "\"{} [{}]: {}\"", ".", "format", "...
Prints a line from a file, with the ``.zip`` filename and optionally also the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filename of the inner file line: the line from the inner file show_inner_file: if ``True``, show both filenames; if ``False``, show just the ``.zip`` filename
[ "Prints", "a", "line", "from", "a", "file", "with", "the", ".", "zip", "filename", "and", "optionally", "also", "the", "inner", "filename", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/grep_in_openxml.py#L85-L101
train
53,119
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/grep_in_openxml.py
parse_zip
def parse_zip(zipfilename: str, regex: Pattern, invert_match: bool, files_with_matches: bool, files_without_match: bool, grep_inner_file_name: bool, show_inner_file: bool) -> None: """ Implement a "grep within an OpenXML file" for a single OpenXML file, which is by definition a ``.zip`` file. Args: zipfilename: name of the OpenXML (zip) file regex: regular expression to match invert_match: find files that do NOT match, instead of ones that do? files_with_matches: show filenames of files with a match? files_without_match: show filenames of files with no match? grep_inner_file_name: search the names of "inner" files, rather than their contents? show_inner_file: show the names of the "inner" files, not just the "outer" (OpenXML) file? """ assert not (files_without_match and files_with_matches) report_lines = (not files_without_match) and (not files_with_matches) report_hit_lines = report_lines and not invert_match report_miss_lines = report_lines and invert_match log.debug("Checking ZIP: " + zipfilename) found_in_zip = False try: with ZipFile(zipfilename, 'r') as zf: for contentsfilename in zf.namelist(): log.debug("... checking file: " + contentsfilename) if grep_inner_file_name: found_in_filename = bool(regex.search(contentsfilename)) found_in_zip = found_in_zip or found_in_filename if files_with_matches and found_in_zip: report_hit_filename(zipfilename, contentsfilename, show_inner_file) return if ((report_hit_lines and found_in_filename) or (report_miss_lines and not found_in_filename)): report_line(zipfilename, contentsfilename, contentsfilename, show_inner_file) else: try: with zf.open(contentsfilename, 'r') as file: try: for line in file.readlines(): # log.debug("line: {!r}", line) found_in_line = bool(regex.search(line)) found_in_zip = found_in_zip or found_in_line if files_with_matches and found_in_zip: report_hit_filename(zipfilename, contentsfilename, show_inner_file) return if ((report_hit_lines and found_in_line) or (report_miss_lines and not found_in_line)): report_line(zipfilename, contentsfilename, line, show_inner_file) except EOFError: pass except RuntimeError as e: log.warning( "RuntimeError whilst processing {} [{}]: probably " "encrypted contents; error was {!r}", zipfilename, contentsfilename, e) except (zlib.error, BadZipFile) as e: log.debug("Invalid zip: {}; error was {!r}", zipfilename, e) if files_without_match and not found_in_zip: report_miss_filename(zipfilename)
python
def parse_zip(zipfilename: str, regex: Pattern, invert_match: bool, files_with_matches: bool, files_without_match: bool, grep_inner_file_name: bool, show_inner_file: bool) -> None: """ Implement a "grep within an OpenXML file" for a single OpenXML file, which is by definition a ``.zip`` file. Args: zipfilename: name of the OpenXML (zip) file regex: regular expression to match invert_match: find files that do NOT match, instead of ones that do? files_with_matches: show filenames of files with a match? files_without_match: show filenames of files with no match? grep_inner_file_name: search the names of "inner" files, rather than their contents? show_inner_file: show the names of the "inner" files, not just the "outer" (OpenXML) file? """ assert not (files_without_match and files_with_matches) report_lines = (not files_without_match) and (not files_with_matches) report_hit_lines = report_lines and not invert_match report_miss_lines = report_lines and invert_match log.debug("Checking ZIP: " + zipfilename) found_in_zip = False try: with ZipFile(zipfilename, 'r') as zf: for contentsfilename in zf.namelist(): log.debug("... checking file: " + contentsfilename) if grep_inner_file_name: found_in_filename = bool(regex.search(contentsfilename)) found_in_zip = found_in_zip or found_in_filename if files_with_matches and found_in_zip: report_hit_filename(zipfilename, contentsfilename, show_inner_file) return if ((report_hit_lines and found_in_filename) or (report_miss_lines and not found_in_filename)): report_line(zipfilename, contentsfilename, contentsfilename, show_inner_file) else: try: with zf.open(contentsfilename, 'r') as file: try: for line in file.readlines(): # log.debug("line: {!r}", line) found_in_line = bool(regex.search(line)) found_in_zip = found_in_zip or found_in_line if files_with_matches and found_in_zip: report_hit_filename(zipfilename, contentsfilename, show_inner_file) return if ((report_hit_lines and found_in_line) or (report_miss_lines and not found_in_line)): report_line(zipfilename, contentsfilename, line, show_inner_file) except EOFError: pass except RuntimeError as e: log.warning( "RuntimeError whilst processing {} [{}]: probably " "encrypted contents; error was {!r}", zipfilename, contentsfilename, e) except (zlib.error, BadZipFile) as e: log.debug("Invalid zip: {}; error was {!r}", zipfilename, e) if files_without_match and not found_in_zip: report_miss_filename(zipfilename)
[ "def", "parse_zip", "(", "zipfilename", ":", "str", ",", "regex", ":", "Pattern", ",", "invert_match", ":", "bool", ",", "files_with_matches", ":", "bool", ",", "files_without_match", ":", "bool", ",", "grep_inner_file_name", ":", "bool", ",", "show_inner_file",...
Implement a "grep within an OpenXML file" for a single OpenXML file, which is by definition a ``.zip`` file. Args: zipfilename: name of the OpenXML (zip) file regex: regular expression to match invert_match: find files that do NOT match, instead of ones that do? files_with_matches: show filenames of files with a match? files_without_match: show filenames of files with no match? grep_inner_file_name: search the names of "inner" files, rather than their contents? show_inner_file: show the names of the "inner" files, not just the "outer" (OpenXML) file?
[ "Implement", "a", "grep", "within", "an", "OpenXML", "file", "for", "a", "single", "OpenXML", "file", "which", "is", "by", "definition", "a", ".", "zip", "file", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/grep_in_openxml.py#L104-L176
train
53,120
Netuitive/netuitive-client-python
netuitive/element.py
Element.merge_metrics
def merge_metrics(self): """ Merge metrics in the internal _metrics dict to metrics list and delete the internal _metrics """ self.metrics.extend(self._metrics.values()) del self._metrics
python
def merge_metrics(self): """ Merge metrics in the internal _metrics dict to metrics list and delete the internal _metrics """ self.metrics.extend(self._metrics.values()) del self._metrics
[ "def", "merge_metrics", "(", "self", ")", ":", "self", ".", "metrics", ".", "extend", "(", "self", ".", "_metrics", ".", "values", "(", ")", ")", "del", "self", ".", "_metrics" ]
Merge metrics in the internal _metrics dict to metrics list and delete the internal _metrics
[ "Merge", "metrics", "in", "the", "internal", "_metrics", "dict", "to", "metrics", "list", "and", "delete", "the", "internal", "_metrics" ]
16426ade6a5dc0888ce978c97b02663a9713fc16
https://github.com/Netuitive/netuitive-client-python/blob/16426ade6a5dc0888ce978c97b02663a9713fc16/netuitive/element.py#L43-L50
train
53,121
nxdevel/nx_itertools
nx_itertools/extra.py
pairwise
def pairwise(iterable): """Pair each element with its neighbors. Arguments --------- iterable : iterable Returns ------- The generator produces a tuple containing a pairing of each element with its neighbor. """ iterable = iter(iterable) left = next(iterable) for right in iterable: yield left, right left = right
python
def pairwise(iterable): """Pair each element with its neighbors. Arguments --------- iterable : iterable Returns ------- The generator produces a tuple containing a pairing of each element with its neighbor. """ iterable = iter(iterable) left = next(iterable) for right in iterable: yield left, right left = right
[ "def", "pairwise", "(", "iterable", ")", ":", "iterable", "=", "iter", "(", "iterable", ")", "left", "=", "next", "(", "iterable", ")", "for", "right", "in", "iterable", ":", "yield", "left", ",", "right", "left", "=", "right" ]
Pair each element with its neighbors. Arguments --------- iterable : iterable Returns ------- The generator produces a tuple containing a pairing of each element with its neighbor.
[ "Pair", "each", "element", "with", "its", "neighbors", "." ]
744da75c616a8a7991b963a549152fe9c434abd9
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L21-L37
train
53,122
nxdevel/nx_itertools
nx_itertools/extra.py
partition
def partition(pred, iterable): """Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple of lists with the first list containing the elements on which the predicate indicated False and the second list containing the elements on which the predicate indicated True. Note that, unlike the recipe which returns generators, this version returns lists. """ pos, neg = [], [] pos_append, neg_append = pos.append, neg.append for elem in iterable: if pred(elem): pos_append(elem) else: neg_append(elem) return neg, pos
python
def partition(pred, iterable): """Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple of lists with the first list containing the elements on which the predicate indicated False and the second list containing the elements on which the predicate indicated True. Note that, unlike the recipe which returns generators, this version returns lists. """ pos, neg = [], [] pos_append, neg_append = pos.append, neg.append for elem in iterable: if pred(elem): pos_append(elem) else: neg_append(elem) return neg, pos
[ "def", "partition", "(", "pred", ",", "iterable", ")", ":", "pos", ",", "neg", "=", "[", "]", ",", "[", "]", "pos_append", ",", "neg_append", "=", "pos", ".", "append", ",", "neg", ".", "append", "for", "elem", "in", "iterable", ":", "if", "pred", ...
Partition an iterable. Arguments --------- pred : function A function that takes an element of the iterable and returns a boolen indicating to which partition it belongs iterable : iterable Returns ------- A two-tuple of lists with the first list containing the elements on which the predicate indicated False and the second list containing the elements on which the predicate indicated True. Note that, unlike the recipe which returns generators, this version returns lists.
[ "Partition", "an", "iterable", "." ]
744da75c616a8a7991b963a549152fe9c434abd9
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L40-L66
train
53,123
nxdevel/nx_itertools
nx_itertools/extra.py
powerset
def powerset(iterable, *, reverse=False): """Return the powerset. Arguments --------- iterable : iterable reverse : boolean Indicates whether the powerset should be returned descending by size Returns ------- A generator producing each element of the powerset. """ lst = list(iterable) if reverse: rng = range(len(lst), -1, -1) else: rng = range(len(lst) + 1) return chain.from_iterable(combinations(lst, r) for r in rng)
python
def powerset(iterable, *, reverse=False): """Return the powerset. Arguments --------- iterable : iterable reverse : boolean Indicates whether the powerset should be returned descending by size Returns ------- A generator producing each element of the powerset. """ lst = list(iterable) if reverse: rng = range(len(lst), -1, -1) else: rng = range(len(lst) + 1) return chain.from_iterable(combinations(lst, r) for r in rng)
[ "def", "powerset", "(", "iterable", ",", "*", ",", "reverse", "=", "False", ")", ":", "lst", "=", "list", "(", "iterable", ")", "if", "reverse", ":", "rng", "=", "range", "(", "len", "(", "lst", ")", ",", "-", "1", ",", "-", "1", ")", "else", ...
Return the powerset. Arguments --------- iterable : iterable reverse : boolean Indicates whether the powerset should be returned descending by size Returns ------- A generator producing each element of the powerset.
[ "Return", "the", "powerset", "." ]
744da75c616a8a7991b963a549152fe9c434abd9
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L69-L88
train
53,124
nxdevel/nx_itertools
nx_itertools/extra.py
multi_map
def multi_map(key, iterable, *, default_dict=False): """Collect data into a multi-map. Arguments ---------- key : function A function that accepts an element retrieved from the iterable and returns the key to be used in the multi-map iterable : iterable default_dict : boolean Indicates whether or not the returned multi-map is an instance of defaultdict(list) Returns ------- A dictionary of lists where the dictionary is either an instance of dict() or defaultdict(list) based on the *default_dict* boolean and each list contains the elements that are associated with the key in the order in which they occur in the iterable. """ result = collections.defaultdict(list) for rec in iterable: result[key(rec)].append(rec) return result if default_dict else dict(result)
python
def multi_map(key, iterable, *, default_dict=False): """Collect data into a multi-map. Arguments ---------- key : function A function that accepts an element retrieved from the iterable and returns the key to be used in the multi-map iterable : iterable default_dict : boolean Indicates whether or not the returned multi-map is an instance of defaultdict(list) Returns ------- A dictionary of lists where the dictionary is either an instance of dict() or defaultdict(list) based on the *default_dict* boolean and each list contains the elements that are associated with the key in the order in which they occur in the iterable. """ result = collections.defaultdict(list) for rec in iterable: result[key(rec)].append(rec) return result if default_dict else dict(result)
[ "def", "multi_map", "(", "key", ",", "iterable", ",", "*", ",", "default_dict", "=", "False", ")", ":", "result", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "rec", "in", "iterable", ":", "result", "[", "key", "(", "rec", ")", "]...
Collect data into a multi-map. Arguments ---------- key : function A function that accepts an element retrieved from the iterable and returns the key to be used in the multi-map iterable : iterable default_dict : boolean Indicates whether or not the returned multi-map is an instance of defaultdict(list) Returns ------- A dictionary of lists where the dictionary is either an instance of dict() or defaultdict(list) based on the *default_dict* boolean and each list contains the elements that are associated with the key in the order in which they occur in the iterable.
[ "Collect", "data", "into", "a", "multi", "-", "map", "." ]
744da75c616a8a7991b963a549152fe9c434abd9
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L91-L114
train
53,125
nxdevel/nx_itertools
nx_itertools/extra.py
split
def split(pred, iterable, *, trailing=True): """Split the iterable. Arguments ---------- pred : function A function that accepts an element retrieved from the iterable and returns a boolean indicating if it is the element on which to split iterable : iterable trailing : boolean Indicates whether the split should occur on the leading edge of the match on the split or on the trailing edge of the match on the split Returns ------- The generator produces a list for each split. If *trailing* is True then the element that was identified by the predicate will be returned at the end of each split. If *trailing* is False then the element that was identified by the predicate will be returned at the beginning of the following split. No guarantee is made regarding the state of the iterable during operation. """ result = [] result_append = result.append if trailing: for elem in iterable: result_append(elem) if pred(elem): yield result result = [] result_append = result.append else: for elem in iterable: if pred(elem): if result: yield result result = [] result_append = result.append result_append(elem) if result: yield result
python
def split(pred, iterable, *, trailing=True): """Split the iterable. Arguments ---------- pred : function A function that accepts an element retrieved from the iterable and returns a boolean indicating if it is the element on which to split iterable : iterable trailing : boolean Indicates whether the split should occur on the leading edge of the match on the split or on the trailing edge of the match on the split Returns ------- The generator produces a list for each split. If *trailing* is True then the element that was identified by the predicate will be returned at the end of each split. If *trailing* is False then the element that was identified by the predicate will be returned at the beginning of the following split. No guarantee is made regarding the state of the iterable during operation. """ result = [] result_append = result.append if trailing: for elem in iterable: result_append(elem) if pred(elem): yield result result = [] result_append = result.append else: for elem in iterable: if pred(elem): if result: yield result result = [] result_append = result.append result_append(elem) if result: yield result
[ "def", "split", "(", "pred", ",", "iterable", ",", "*", ",", "trailing", "=", "True", ")", ":", "result", "=", "[", "]", "result_append", "=", "result", ".", "append", "if", "trailing", ":", "for", "elem", "in", "iterable", ":", "result_append", "(", ...
Split the iterable. Arguments ---------- pred : function A function that accepts an element retrieved from the iterable and returns a boolean indicating if it is the element on which to split iterable : iterable trailing : boolean Indicates whether the split should occur on the leading edge of the match on the split or on the trailing edge of the match on the split Returns ------- The generator produces a list for each split. If *trailing* is True then the element that was identified by the predicate will be returned at the end of each split. If *trailing* is False then the element that was identified by the predicate will be returned at the beginning of the following split. No guarantee is made regarding the state of the iterable during operation.
[ "Split", "the", "iterable", "." ]
744da75c616a8a7991b963a549152fe9c434abd9
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L117-L161
train
53,126
nxdevel/nx_itertools
nx_itertools/extra.py
chunk
def chunk(iterable, length): """Collect data into chunks. Arguments --------- iterable : iterable length : integer Maximum size of each chunk to return Returns ------- The generator produces a tuple of elements whose size is at least one but no more than *length*. If the number of elements in the iterable is not a multiple of *length* then the final tuple will be less than *length*. This function is meant to be a variant of the recipe's function grouper() that does not pad the last tuple with a fill-value if the number elements in the iterable is not a multiple of the specified length. """ if length < 0: return () iterable = iter(iterable) result = tuple(islice(iterable, length)) while result: yield result result = tuple(islice(iterable, length))
python
def chunk(iterable, length): """Collect data into chunks. Arguments --------- iterable : iterable length : integer Maximum size of each chunk to return Returns ------- The generator produces a tuple of elements whose size is at least one but no more than *length*. If the number of elements in the iterable is not a multiple of *length* then the final tuple will be less than *length*. This function is meant to be a variant of the recipe's function grouper() that does not pad the last tuple with a fill-value if the number elements in the iterable is not a multiple of the specified length. """ if length < 0: return () iterable = iter(iterable) result = tuple(islice(iterable, length)) while result: yield result result = tuple(islice(iterable, length))
[ "def", "chunk", "(", "iterable", ",", "length", ")", ":", "if", "length", "<", "0", ":", "return", "(", ")", "iterable", "=", "iter", "(", "iterable", ")", "result", "=", "tuple", "(", "islice", "(", "iterable", ",", "length", ")", ")", "while", "r...
Collect data into chunks. Arguments --------- iterable : iterable length : integer Maximum size of each chunk to return Returns ------- The generator produces a tuple of elements whose size is at least one but no more than *length*. If the number of elements in the iterable is not a multiple of *length* then the final tuple will be less than *length*. This function is meant to be a variant of the recipe's function grouper() that does not pad the last tuple with a fill-value if the number elements in the iterable is not a multiple of the specified length.
[ "Collect", "data", "into", "chunks", "." ]
744da75c616a8a7991b963a549152fe9c434abd9
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L164-L191
train
53,127
nxdevel/nx_itertools
nx_itertools/extra.py
divide
def divide(iterable, n): # pylint: disable=invalid-name """Evenly divide elements. Arguments --------- iterable : iterable n : integer The number of buckets in which to divide the elements Returns ------- The generator produces *n* tuples, each containing a number of elements where the number is calculated to be evenly distributed across all of the returned tuples. The number of tuples returned is always *n* and, thus, may return an empty tuple if there is not enough data to distribute. In order to determine the number of elements to put in each tuple, the iterable is converted into a list. Consider using divide_sizes() and manually slicing the iterator if this is not desirable. """ if n <= 0: return [] data = list(iterable) base, rem = divmod(len(data), n) iterable = iter(data) for i in range(n): yield tuple(islice(iterable, base + 1 if i < rem else base))
python
def divide(iterable, n): # pylint: disable=invalid-name """Evenly divide elements. Arguments --------- iterable : iterable n : integer The number of buckets in which to divide the elements Returns ------- The generator produces *n* tuples, each containing a number of elements where the number is calculated to be evenly distributed across all of the returned tuples. The number of tuples returned is always *n* and, thus, may return an empty tuple if there is not enough data to distribute. In order to determine the number of elements to put in each tuple, the iterable is converted into a list. Consider using divide_sizes() and manually slicing the iterator if this is not desirable. """ if n <= 0: return [] data = list(iterable) base, rem = divmod(len(data), n) iterable = iter(data) for i in range(n): yield tuple(islice(iterable, base + 1 if i < rem else base))
[ "def", "divide", "(", "iterable", ",", "n", ")", ":", "# pylint: disable=invalid-name", "if", "n", "<=", "0", ":", "return", "[", "]", "data", "=", "list", "(", "iterable", ")", "base", ",", "rem", "=", "divmod", "(", "len", "(", "data", ")", ",", ...
Evenly divide elements. Arguments --------- iterable : iterable n : integer The number of buckets in which to divide the elements Returns ------- The generator produces *n* tuples, each containing a number of elements where the number is calculated to be evenly distributed across all of the returned tuples. The number of tuples returned is always *n* and, thus, may return an empty tuple if there is not enough data to distribute. In order to determine the number of elements to put in each tuple, the iterable is converted into a list. Consider using divide_sizes() and manually slicing the iterator if this is not desirable.
[ "Evenly", "divide", "elements", "." ]
744da75c616a8a7991b963a549152fe9c434abd9
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L194-L222
train
53,128
nxdevel/nx_itertools
nx_itertools/extra.py
divide_sizes
def divide_sizes(count, n): # pylint: disable=invalid-name """Evenly divide a count. Arguments --------- count : integer The number to be evenly divided n : integer The number of buckets in which to divide the number Returns ------- A list of integers indicating what size each bucket should be for an even distribution of *count*. The number of integers returned is always *n* and, thus, may be 0. Useful for calculating slices for generators that might be too large to convert into a list as happens in divide(). """ if n <= 0: return [] if count < 0: return [0] * n base, rem = divmod(count, n) return [base + 1 if i < rem else base for i in range(n)]
python
def divide_sizes(count, n): # pylint: disable=invalid-name """Evenly divide a count. Arguments --------- count : integer The number to be evenly divided n : integer The number of buckets in which to divide the number Returns ------- A list of integers indicating what size each bucket should be for an even distribution of *count*. The number of integers returned is always *n* and, thus, may be 0. Useful for calculating slices for generators that might be too large to convert into a list as happens in divide(). """ if n <= 0: return [] if count < 0: return [0] * n base, rem = divmod(count, n) return [base + 1 if i < rem else base for i in range(n)]
[ "def", "divide_sizes", "(", "count", ",", "n", ")", ":", "# pylint: disable=invalid-name", "if", "n", "<=", "0", ":", "return", "[", "]", "if", "count", "<", "0", ":", "return", "[", "0", "]", "*", "n", "base", ",", "rem", "=", "divmod", "(", "coun...
Evenly divide a count. Arguments --------- count : integer The number to be evenly divided n : integer The number of buckets in which to divide the number Returns ------- A list of integers indicating what size each bucket should be for an even distribution of *count*. The number of integers returned is always *n* and, thus, may be 0. Useful for calculating slices for generators that might be too large to convert into a list as happens in divide().
[ "Evenly", "divide", "a", "count", "." ]
744da75c616a8a7991b963a549152fe9c434abd9
https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/extra.py#L225-L250
train
53,129
AndrewWalker/glud
glud/display.py
dump
def dump(cursor): """ Display the AST represented by the cursor """ def node_children(node): return list(node.get_children()) def print_node(node): text = node.spelling or node.displayname kind = str(node.kind).split('.')[1] return '{} {}'.format(kind, text) return draw_tree(cursor, node_children, print_node)
python
def dump(cursor): """ Display the AST represented by the cursor """ def node_children(node): return list(node.get_children()) def print_node(node): text = node.spelling or node.displayname kind = str(node.kind).split('.')[1] return '{} {}'.format(kind, text) return draw_tree(cursor, node_children, print_node)
[ "def", "dump", "(", "cursor", ")", ":", "def", "node_children", "(", "node", ")", ":", "return", "list", "(", "node", ".", "get_children", "(", ")", ")", "def", "print_node", "(", "node", ")", ":", "text", "=", "node", ".", "spelling", "or", "node", ...
Display the AST represented by the cursor
[ "Display", "the", "AST", "represented", "by", "the", "cursor" ]
57de000627fed13d0c383f131163795b09549257
https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/display.py#L4-L16
train
53,130
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
pendulum_to_datetime
def pendulum_to_datetime(x: DateTime) -> datetime.datetime: """ Used, for example, where a database backend insists on datetime.datetime. Compare code in :meth:`pendulum.datetime.DateTime.int_timestamp`. """ return datetime.datetime( x.year, x.month, x.day, x.hour, x.minute, x.second, x.microsecond, tzinfo=x.tzinfo )
python
def pendulum_to_datetime(x: DateTime) -> datetime.datetime: """ Used, for example, where a database backend insists on datetime.datetime. Compare code in :meth:`pendulum.datetime.DateTime.int_timestamp`. """ return datetime.datetime( x.year, x.month, x.day, x.hour, x.minute, x.second, x.microsecond, tzinfo=x.tzinfo )
[ "def", "pendulum_to_datetime", "(", "x", ":", "DateTime", ")", "->", "datetime", ".", "datetime", ":", "return", "datetime", ".", "datetime", "(", "x", ".", "year", ",", "x", ".", "month", ",", "x", ".", "day", ",", "x", ".", "hour", ",", "x", ".",...
Used, for example, where a database backend insists on datetime.datetime. Compare code in :meth:`pendulum.datetime.DateTime.int_timestamp`.
[ "Used", "for", "example", "where", "a", "database", "backend", "insists", "on", "datetime", ".", "datetime", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L118-L128
train
53,131
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
format_datetime
def format_datetime(d: PotentialDatetimeType, fmt: str, default: str = None) -> Optional[str]: """ Format a datetime with a ``strftime`` format specification string, or return ``default`` if the input is ``None``. """ d = coerce_to_pendulum(d) if d is None: return default return d.strftime(fmt)
python
def format_datetime(d: PotentialDatetimeType, fmt: str, default: str = None) -> Optional[str]: """ Format a datetime with a ``strftime`` format specification string, or return ``default`` if the input is ``None``. """ d = coerce_to_pendulum(d) if d is None: return default return d.strftime(fmt)
[ "def", "format_datetime", "(", "d", ":", "PotentialDatetimeType", ",", "fmt", ":", "str", ",", "default", ":", "str", "=", "None", ")", "->", "Optional", "[", "str", "]", ":", "d", "=", "coerce_to_pendulum", "(", "d", ")", "if", "d", "is", "None", ":...
Format a datetime with a ``strftime`` format specification string, or return ``default`` if the input is ``None``.
[ "Format", "a", "datetime", "with", "a", "strftime", "format", "specification", "string", "or", "return", "default", "if", "the", "input", "is", "None", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L191-L201
train
53,132
RudolfCardinal/pythonlib
cardinal_pythonlib/datetimefunc.py
truncate_date_to_first_of_month
def truncate_date_to_first_of_month( dt: Optional[DateLikeType]) -> Optional[DateLikeType]: """ Change the day to the first of the month. """ if dt is None: return None return dt.replace(day=1)
python
def truncate_date_to_first_of_month( dt: Optional[DateLikeType]) -> Optional[DateLikeType]: """ Change the day to the first of the month. """ if dt is None: return None return dt.replace(day=1)
[ "def", "truncate_date_to_first_of_month", "(", "dt", ":", "Optional", "[", "DateLikeType", "]", ")", "->", "Optional", "[", "DateLikeType", "]", ":", "if", "dt", "is", "None", ":", "return", "None", "return", "dt", ".", "replace", "(", "day", "=", "1", "...
Change the day to the first of the month.
[ "Change", "the", "day", "to", "the", "first", "of", "the", "month", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/datetimefunc.py#L408-L415
train
53,133
ivanprjcts/sdklib
sdklib/http/base.py
request_from_context
def request_from_context(context): """ Do http requests from context. :param context: request context. """ new_context = copy.deepcopy(context) assert new_context.method in ALLOWED_METHODS new_context.url_path = generate_url_path( new_context.url_path, prefix=new_context.prefix_url_path, format_suffix=new_context.url_path_format, **new_context.url_path_params ) if new_context.body_params or new_context.files: body, content_type = new_context.renderer.encode_params(new_context.body_params, files=new_context.files) if new_context.update_content_type and HttpSdk.CONTENT_TYPE_HEADER_NAME not in new_context.headers: new_context.headers[HttpSdk.CONTENT_TYPE_HEADER_NAME] = content_type else: body = None authentication_instances = new_context.authentication_instances for auth_obj in authentication_instances: new_context = auth_obj.apply_authentication(new_context) if HttpSdk.COOKIE_HEADER_NAME not in new_context.headers and not new_context.cookie.is_empty(): new_context.headers[HttpSdk.COOKIE_HEADER_NAME] = new_context.cookie.as_cookie_header_value() url = "%s%s" % (new_context.host, new_context.url_path) if new_context.query_params: url += "?%s" % (urlencode(new_context.query_params)) log_print_request(new_context.method, url, new_context.query_params, new_context.headers, body) # ensure method and url are native str r = HttpSdk.get_pool_manager(new_context.proxy).request( convert_unicode_to_native_str(new_context.method), convert_unicode_to_native_str(url), body=body, headers=HttpSdk.convert_headers_to_native_str(new_context.headers), redirect=new_context.redirect, timeout=new_context.timeout ) log_print_response(r.status, r.data, r.headers) r = new_context.response_class(r) return r
python
def request_from_context(context): """ Do http requests from context. :param context: request context. """ new_context = copy.deepcopy(context) assert new_context.method in ALLOWED_METHODS new_context.url_path = generate_url_path( new_context.url_path, prefix=new_context.prefix_url_path, format_suffix=new_context.url_path_format, **new_context.url_path_params ) if new_context.body_params or new_context.files: body, content_type = new_context.renderer.encode_params(new_context.body_params, files=new_context.files) if new_context.update_content_type and HttpSdk.CONTENT_TYPE_HEADER_NAME not in new_context.headers: new_context.headers[HttpSdk.CONTENT_TYPE_HEADER_NAME] = content_type else: body = None authentication_instances = new_context.authentication_instances for auth_obj in authentication_instances: new_context = auth_obj.apply_authentication(new_context) if HttpSdk.COOKIE_HEADER_NAME not in new_context.headers and not new_context.cookie.is_empty(): new_context.headers[HttpSdk.COOKIE_HEADER_NAME] = new_context.cookie.as_cookie_header_value() url = "%s%s" % (new_context.host, new_context.url_path) if new_context.query_params: url += "?%s" % (urlencode(new_context.query_params)) log_print_request(new_context.method, url, new_context.query_params, new_context.headers, body) # ensure method and url are native str r = HttpSdk.get_pool_manager(new_context.proxy).request( convert_unicode_to_native_str(new_context.method), convert_unicode_to_native_str(url), body=body, headers=HttpSdk.convert_headers_to_native_str(new_context.headers), redirect=new_context.redirect, timeout=new_context.timeout ) log_print_response(r.status, r.data, r.headers) r = new_context.response_class(r) return r
[ "def", "request_from_context", "(", "context", ")", ":", "new_context", "=", "copy", ".", "deepcopy", "(", "context", ")", "assert", "new_context", ".", "method", "in", "ALLOWED_METHODS", "new_context", ".", "url_path", "=", "generate_url_path", "(", "new_context"...
Do http requests from context. :param context: request context.
[ "Do", "http", "requests", "from", "context", "." ]
7ba4273a05c40e2e338f49f2dd564920ed98fcab
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L33-L79
train
53,134
ivanprjcts/sdklib
sdklib/http/base.py
HttpSdk.host
def host(self, value): """ A string that will be automatically included at the beginning of the url generated for doing each http request. :param value: The host to be connected with, e.g. (http://hostname) or (https://X.X.X.X:port) """ scheme, host, port = get_hostname_parameters_from_url(value) self._host = "%s://%s:%s" % (scheme, host, port)
python
def host(self, value): """ A string that will be automatically included at the beginning of the url generated for doing each http request. :param value: The host to be connected with, e.g. (http://hostname) or (https://X.X.X.X:port) """ scheme, host, port = get_hostname_parameters_from_url(value) self._host = "%s://%s:%s" % (scheme, host, port)
[ "def", "host", "(", "self", ",", "value", ")", ":", "scheme", ",", "host", ",", "port", "=", "get_hostname_parameters_from_url", "(", "value", ")", "self", ".", "_host", "=", "\"%s://%s:%s\"", "%", "(", "scheme", ",", "host", ",", "port", ")" ]
A string that will be automatically included at the beginning of the url generated for doing each http request. :param value: The host to be connected with, e.g. (http://hostname) or (https://X.X.X.X:port)
[ "A", "string", "that", "will", "be", "automatically", "included", "at", "the", "beginning", "of", "the", "url", "generated", "for", "doing", "each", "http", "request", "." ]
7ba4273a05c40e2e338f49f2dd564920ed98fcab
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L281-L288
train
53,135
ivanprjcts/sdklib
sdklib/http/base.py
HttpSdk._http_request
def _http_request(self, method, url_path, headers=None, query_params=None, body_params=None, files=None, **kwargs): """ Method to do http requests. :param method: :param url_path: :param headers: :param body_params: :param query_params: :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. ``file-tuple`` can be a 1-tuple ``('filepath')``, 2-tuple ``('filepath', 'content_type')`` or a 3-tuple ``('filepath', 'content_type', custom_headers)``, where ``'content-type'`` is a string defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers to add for the file. :param update_content_type: (bool) Update headers before performig the request, adding the Content-Type value according to the rendered body. By default: True. :return: """ host = kwargs.get('host', self.host) proxy = kwargs.get('proxy', self.proxy) renderer = kwargs.get('renderer', MultiPartRenderer() if files else self.default_renderer) prefix_url_path = kwargs.get('prefix_url_path', self.prefix_url_path) authentication_instances = kwargs.get('authentication_instances', self.authentication_instances) url_path_format = kwargs.get('url_path_format', self.url_path_format) update_content_type = kwargs.get('update_content_type', True) redirect = kwargs.get('redirect', False) if headers is None: headers = self.default_headers() context = HttpRequestContext( host=host, proxy=proxy, method=method, prefix_url_path=prefix_url_path, url_path=url_path, url_path_params=self.url_path_params, url_path_format=url_path_format, headers=headers, query_params=query_params, body_params=body_params, files=files, renderer=renderer, response_class=self.response_class, authentication_instances=authentication_instances, update_content_type=update_content_type, redirect=redirect ) res = self.http_request_from_context(context) self.cookie.update(res.cookie) return res
python
def _http_request(self, method, url_path, headers=None, query_params=None, body_params=None, files=None, **kwargs): """ Method to do http requests. :param method: :param url_path: :param headers: :param body_params: :param query_params: :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. ``file-tuple`` can be a 1-tuple ``('filepath')``, 2-tuple ``('filepath', 'content_type')`` or a 3-tuple ``('filepath', 'content_type', custom_headers)``, where ``'content-type'`` is a string defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers to add for the file. :param update_content_type: (bool) Update headers before performig the request, adding the Content-Type value according to the rendered body. By default: True. :return: """ host = kwargs.get('host', self.host) proxy = kwargs.get('proxy', self.proxy) renderer = kwargs.get('renderer', MultiPartRenderer() if files else self.default_renderer) prefix_url_path = kwargs.get('prefix_url_path', self.prefix_url_path) authentication_instances = kwargs.get('authentication_instances', self.authentication_instances) url_path_format = kwargs.get('url_path_format', self.url_path_format) update_content_type = kwargs.get('update_content_type', True) redirect = kwargs.get('redirect', False) if headers is None: headers = self.default_headers() context = HttpRequestContext( host=host, proxy=proxy, method=method, prefix_url_path=prefix_url_path, url_path=url_path, url_path_params=self.url_path_params, url_path_format=url_path_format, headers=headers, query_params=query_params, body_params=body_params, files=files, renderer=renderer, response_class=self.response_class, authentication_instances=authentication_instances, update_content_type=update_content_type, redirect=redirect ) res = self.http_request_from_context(context) self.cookie.update(res.cookie) return res
[ "def", "_http_request", "(", "self", ",", "method", ",", "url_path", ",", "headers", "=", "None", ",", "query_params", "=", "None", ",", "body_params", "=", "None", ",", "files", "=", "None", ",", "*", "*", "kwargs", ")", ":", "host", "=", "kwargs", ...
Method to do http requests. :param method: :param url_path: :param headers: :param body_params: :param query_params: :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload. ``file-tuple`` can be a 1-tuple ``('filepath')``, 2-tuple ``('filepath', 'content_type')`` or a 3-tuple ``('filepath', 'content_type', custom_headers)``, where ``'content-type'`` is a string defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers to add for the file. :param update_content_type: (bool) Update headers before performig the request, adding the Content-Type value according to the rendered body. By default: True. :return:
[ "Method", "to", "do", "http", "requests", "." ]
7ba4273a05c40e2e338f49f2dd564920ed98fcab
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L394-L443
train
53,136
ivanprjcts/sdklib
sdklib/http/base.py
HttpSdk.login
def login(self, **kwargs): """ Login abstract method with default implementation. :param kwargs: parameters :return: SdkResponse """ assert self.LOGIN_URL_PATH is not None render_name = kwargs.pop("render", "json") render = get_renderer(render_name) params = parse_args(**kwargs) return self.post(self.LOGIN_URL_PATH, body_params=params, render=render)
python
def login(self, **kwargs): """ Login abstract method with default implementation. :param kwargs: parameters :return: SdkResponse """ assert self.LOGIN_URL_PATH is not None render_name = kwargs.pop("render", "json") render = get_renderer(render_name) params = parse_args(**kwargs) return self.post(self.LOGIN_URL_PATH, body_params=params, render=render)
[ "def", "login", "(", "self", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "LOGIN_URL_PATH", "is", "not", "None", "render_name", "=", "kwargs", ".", "pop", "(", "\"render\"", ",", "\"json\"", ")", "render", "=", "get_renderer", "(", "render_n...
Login abstract method with default implementation. :param kwargs: parameters :return: SdkResponse
[ "Login", "abstract", "method", "with", "default", "implementation", "." ]
7ba4273a05c40e2e338f49f2dd564920ed98fcab
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/base.py#L463-L475
train
53,137
RudolfCardinal/pythonlib
cardinal_pythonlib/nhs.py
nhs_check_digit
def nhs_check_digit(ninedigits: Union[str, List[Union[str, int]]]) -> int: """ Calculates an NHS number check digit. Args: ninedigits: string or list Returns: check digit Method: 1. Multiply each of the first nine digits by the corresponding digit weighting (see :const:`NHS_DIGIT_WEIGHTINGS`). 2. Sum the results. 3. Take remainder after division by 11. 4. Subtract the remainder from 11 5. If this is 11, use 0 instead If it's 10, the number is invalid If it doesn't match the actual check digit, the number is invalid """ if len(ninedigits) != 9 or not all(str(x).isdigit() for x in ninedigits): raise ValueError("bad string to nhs_check_digit") check_digit = 11 - (sum([ int(d) * f for (d, f) in zip(ninedigits, NHS_DIGIT_WEIGHTINGS) ]) % 11) # ... % 11 yields something in the range 0-10 # ... 11 - that yields something in the range 1-11 if check_digit == 11: check_digit = 0 return check_digit
python
def nhs_check_digit(ninedigits: Union[str, List[Union[str, int]]]) -> int: """ Calculates an NHS number check digit. Args: ninedigits: string or list Returns: check digit Method: 1. Multiply each of the first nine digits by the corresponding digit weighting (see :const:`NHS_DIGIT_WEIGHTINGS`). 2. Sum the results. 3. Take remainder after division by 11. 4. Subtract the remainder from 11 5. If this is 11, use 0 instead If it's 10, the number is invalid If it doesn't match the actual check digit, the number is invalid """ if len(ninedigits) != 9 or not all(str(x).isdigit() for x in ninedigits): raise ValueError("bad string to nhs_check_digit") check_digit = 11 - (sum([ int(d) * f for (d, f) in zip(ninedigits, NHS_DIGIT_WEIGHTINGS) ]) % 11) # ... % 11 yields something in the range 0-10 # ... 11 - that yields something in the range 1-11 if check_digit == 11: check_digit = 0 return check_digit
[ "def", "nhs_check_digit", "(", "ninedigits", ":", "Union", "[", "str", ",", "List", "[", "Union", "[", "str", ",", "int", "]", "]", "]", ")", "->", "int", ":", "if", "len", "(", "ninedigits", ")", "!=", "9", "or", "not", "all", "(", "str", "(", ...
Calculates an NHS number check digit. Args: ninedigits: string or list Returns: check digit Method: 1. Multiply each of the first nine digits by the corresponding digit weighting (see :const:`NHS_DIGIT_WEIGHTINGS`). 2. Sum the results. 3. Take remainder after division by 11. 4. Subtract the remainder from 11 5. If this is 11, use 0 instead If it's 10, the number is invalid If it doesn't match the actual check digit, the number is invalid
[ "Calculates", "an", "NHS", "number", "check", "digit", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/nhs.py#L45-L77
train
53,138
RudolfCardinal/pythonlib
cardinal_pythonlib/nhs.py
generate_random_nhs_number
def generate_random_nhs_number() -> int: """ Returns a random valid NHS number, as an ``int``. """ check_digit = 10 # NHS numbers with this check digit are all invalid while check_digit == 10: digits = [random.randint(1, 9)] # don't start with a zero digits.extend([random.randint(0, 9) for _ in range(8)]) # ... length now 9 check_digit = nhs_check_digit(digits) # noinspection PyUnboundLocalVariable digits.append(check_digit) return int("".join([str(d) for d in digits]))
python
def generate_random_nhs_number() -> int: """ Returns a random valid NHS number, as an ``int``. """ check_digit = 10 # NHS numbers with this check digit are all invalid while check_digit == 10: digits = [random.randint(1, 9)] # don't start with a zero digits.extend([random.randint(0, 9) for _ in range(8)]) # ... length now 9 check_digit = nhs_check_digit(digits) # noinspection PyUnboundLocalVariable digits.append(check_digit) return int("".join([str(d) for d in digits]))
[ "def", "generate_random_nhs_number", "(", ")", "->", "int", ":", "check_digit", "=", "10", "# NHS numbers with this check digit are all invalid", "while", "check_digit", "==", "10", ":", "digits", "=", "[", "random", ".", "randint", "(", "1", ",", "9", ")", "]",...
Returns a random valid NHS number, as an ``int``.
[ "Returns", "a", "random", "valid", "NHS", "number", "as", "an", "int", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/nhs.py#L116-L128
train
53,139
RudolfCardinal/pythonlib
cardinal_pythonlib/email/sendmail.py
send_msg
def send_msg(from_addr: str, to_addrs: Union[str, List[str]], host: str, user: str, password: str, port: int = None, use_tls: bool = True, msg: email.mime.multipart.MIMEMultipart = None, msg_string: str = None) -> None: """ Sends a pre-built e-mail message. Args: from_addr: e-mail address for 'From:' field to_addrs: address or list of addresses to transmit to host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default use_tls: use TLS, rather than plain SMTP? msg: a :class:`email.mime.multipart.MIMEMultipart` msg_string: alternative: specify the message as a raw string Raises: :exc:`RuntimeError` See also: - https://tools.ietf.org/html/rfc3207 """ assert bool(msg) != bool(msg_string), "Specify either msg or msg_string" # Connect try: session = smtplib.SMTP(host, port) except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to connect to host {}, port {}: {}".format( host, port, e)) try: session.ehlo() except smtplib.SMTPException as e: raise RuntimeError("send_msg: Failed to issue EHLO: {}".format(e)) if use_tls: try: session.starttls() session.ehlo() except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to initiate TLS: {}".format(e)) # Log in if user: try: session.login(user, password) except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to login as user {}: {}".format(user, e)) else: log.debug("Not using SMTP AUTH; no user specified") # For systems with... lax... security requirements # Send try: session.sendmail(from_addr, to_addrs, msg.as_string()) except smtplib.SMTPException as e: raise RuntimeError("send_msg: Failed to send e-mail: {}".format(e)) # Log out session.quit()
python
def send_msg(from_addr: str, to_addrs: Union[str, List[str]], host: str, user: str, password: str, port: int = None, use_tls: bool = True, msg: email.mime.multipart.MIMEMultipart = None, msg_string: str = None) -> None: """ Sends a pre-built e-mail message. Args: from_addr: e-mail address for 'From:' field to_addrs: address or list of addresses to transmit to host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default use_tls: use TLS, rather than plain SMTP? msg: a :class:`email.mime.multipart.MIMEMultipart` msg_string: alternative: specify the message as a raw string Raises: :exc:`RuntimeError` See also: - https://tools.ietf.org/html/rfc3207 """ assert bool(msg) != bool(msg_string), "Specify either msg or msg_string" # Connect try: session = smtplib.SMTP(host, port) except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to connect to host {}, port {}: {}".format( host, port, e)) try: session.ehlo() except smtplib.SMTPException as e: raise RuntimeError("send_msg: Failed to issue EHLO: {}".format(e)) if use_tls: try: session.starttls() session.ehlo() except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to initiate TLS: {}".format(e)) # Log in if user: try: session.login(user, password) except smtplib.SMTPException as e: raise RuntimeError( "send_msg: Failed to login as user {}: {}".format(user, e)) else: log.debug("Not using SMTP AUTH; no user specified") # For systems with... lax... security requirements # Send try: session.sendmail(from_addr, to_addrs, msg.as_string()) except smtplib.SMTPException as e: raise RuntimeError("send_msg: Failed to send e-mail: {}".format(e)) # Log out session.quit()
[ "def", "send_msg", "(", "from_addr", ":", "str", ",", "to_addrs", ":", "Union", "[", "str", ",", "List", "[", "str", "]", "]", ",", "host", ":", "str", ",", "user", ":", "str", ",", "password", ":", "str", ",", "port", ":", "int", "=", "None", ...
Sends a pre-built e-mail message. Args: from_addr: e-mail address for 'From:' field to_addrs: address or list of addresses to transmit to host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default use_tls: use TLS, rather than plain SMTP? msg: a :class:`email.mime.multipart.MIMEMultipart` msg_string: alternative: specify the message as a raw string Raises: :exc:`RuntimeError` See also: - https://tools.ietf.org/html/rfc3207
[ "Sends", "a", "pre", "-", "built", "e", "-", "mail", "message", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/email/sendmail.py#L247-L319
train
53,140
The-Politico/politico-civic-geography
geography/management/commands/bootstrap/_toposimplify.py
Toposimplify.toposimplify
def toposimplify(geojson, p): """ Convert geojson and simplify topology. geojson is a dict representing geojson. p is a simplification threshold value between 0 and 1. """ proc_out = subprocess.run( ['geo2topo'], input=bytes( json.dumps(geojson), 'utf-8'), stdout=subprocess.PIPE ) proc_out = subprocess.run( ['toposimplify', '-P', p], input=proc_out.stdout, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL ) topojson = json.loads(proc_out.stdout) # Standardize object name topojson['objects']['divisions'] = topojson['objects'].pop('-') return topojson
python
def toposimplify(geojson, p): """ Convert geojson and simplify topology. geojson is a dict representing geojson. p is a simplification threshold value between 0 and 1. """ proc_out = subprocess.run( ['geo2topo'], input=bytes( json.dumps(geojson), 'utf-8'), stdout=subprocess.PIPE ) proc_out = subprocess.run( ['toposimplify', '-P', p], input=proc_out.stdout, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL ) topojson = json.loads(proc_out.stdout) # Standardize object name topojson['objects']['divisions'] = topojson['objects'].pop('-') return topojson
[ "def", "toposimplify", "(", "geojson", ",", "p", ")", ":", "proc_out", "=", "subprocess", ".", "run", "(", "[", "'geo2topo'", "]", ",", "input", "=", "bytes", "(", "json", ".", "dumps", "(", "geojson", ")", ",", "'utf-8'", ")", ",", "stdout", "=", ...
Convert geojson and simplify topology. geojson is a dict representing geojson. p is a simplification threshold value between 0 and 1.
[ "Convert", "geojson", "and", "simplify", "topology", "." ]
032b3ee773b50b65cfe672f230dda772df0f89e0
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/management/commands/bootstrap/_toposimplify.py#L7-L30
train
53,141
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/engine_func.py
get_sqlserver_product_version
def get_sqlserver_product_version(engine: "Engine") -> Tuple[int]: """ Gets SQL Server version information. Attempted to use ``dialect.server_version_info``: .. code-block:: python from sqlalchemy import create_engine url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME" engine = create_engine(url) dialect = engine.dialect vi = dialect.server_version_info Unfortunately, ``vi == ()`` for an SQL Server 2014 instance via ``mssql+pyodbc``. It's also ``None`` for a ``mysql+pymysql`` connection. So this seems ``server_version_info`` is a badly supported feature. So the only other way is to ask the database directly. The problem is that this requires an :class:`Engine` or similar. (The initial hope was to be able to use this from within SQL compilation hooks, to vary the SQL based on the engine version. Still, this isn't so bad.) We could use either .. code-block:: sql SELECT @@version; -- returns a human-readable string SELECT SERVERPROPERTY('ProductVersion'); -- better The ``pyodbc`` interface will fall over with ``ODBC SQL type -150 is not yet supported`` with that last call, though, meaning that a ``VARIANT`` is coming back, so we ``CAST`` as per the source below. """ assert is_sqlserver(engine), ( "Only call get_sqlserver_product_version() for Microsoft SQL Server " "instances." ) sql = "SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)" rp = engine.execute(sql) # type: ResultProxy row = rp.fetchone() dotted_version = row[0] # type: str # e.g. '12.0.5203.0' return tuple(int(x) for x in dotted_version.split("."))
python
def get_sqlserver_product_version(engine: "Engine") -> Tuple[int]: """ Gets SQL Server version information. Attempted to use ``dialect.server_version_info``: .. code-block:: python from sqlalchemy import create_engine url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME" engine = create_engine(url) dialect = engine.dialect vi = dialect.server_version_info Unfortunately, ``vi == ()`` for an SQL Server 2014 instance via ``mssql+pyodbc``. It's also ``None`` for a ``mysql+pymysql`` connection. So this seems ``server_version_info`` is a badly supported feature. So the only other way is to ask the database directly. The problem is that this requires an :class:`Engine` or similar. (The initial hope was to be able to use this from within SQL compilation hooks, to vary the SQL based on the engine version. Still, this isn't so bad.) We could use either .. code-block:: sql SELECT @@version; -- returns a human-readable string SELECT SERVERPROPERTY('ProductVersion'); -- better The ``pyodbc`` interface will fall over with ``ODBC SQL type -150 is not yet supported`` with that last call, though, meaning that a ``VARIANT`` is coming back, so we ``CAST`` as per the source below. """ assert is_sqlserver(engine), ( "Only call get_sqlserver_product_version() for Microsoft SQL Server " "instances." ) sql = "SELECT CAST(SERVERPROPERTY('ProductVersion') AS VARCHAR)" rp = engine.execute(sql) # type: ResultProxy row = rp.fetchone() dotted_version = row[0] # type: str # e.g. '12.0.5203.0' return tuple(int(x) for x in dotted_version.split("."))
[ "def", "get_sqlserver_product_version", "(", "engine", ":", "\"Engine\"", ")", "->", "Tuple", "[", "int", "]", ":", "assert", "is_sqlserver", "(", "engine", ")", ",", "(", "\"Only call get_sqlserver_product_version() for Microsoft SQL Server \"", "\"instances.\"", ")", ...
Gets SQL Server version information. Attempted to use ``dialect.server_version_info``: .. code-block:: python from sqlalchemy import create_engine url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME" engine = create_engine(url) dialect = engine.dialect vi = dialect.server_version_info Unfortunately, ``vi == ()`` for an SQL Server 2014 instance via ``mssql+pyodbc``. It's also ``None`` for a ``mysql+pymysql`` connection. So this seems ``server_version_info`` is a badly supported feature. So the only other way is to ask the database directly. The problem is that this requires an :class:`Engine` or similar. (The initial hope was to be able to use this from within SQL compilation hooks, to vary the SQL based on the engine version. Still, this isn't so bad.) We could use either .. code-block:: sql SELECT @@version; -- returns a human-readable string SELECT SERVERPROPERTY('ProductVersion'); -- better The ``pyodbc`` interface will fall over with ``ODBC SQL type -150 is not yet supported`` with that last call, though, meaning that a ``VARIANT`` is coming back, so we ``CAST`` as per the source below.
[ "Gets", "SQL", "Server", "version", "information", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/engine_func.py#L53-L96
train
53,142
davenquinn/Attitude
attitude/orientation/linear/regression.py
add_ones
def add_ones(a): """Adds a column of 1s at the end of the array""" arr = N.ones((a.shape[0],a.shape[1]+1)) arr[:,:-1] = a return arr
python
def add_ones(a): """Adds a column of 1s at the end of the array""" arr = N.ones((a.shape[0],a.shape[1]+1)) arr[:,:-1] = a return arr
[ "def", "add_ones", "(", "a", ")", ":", "arr", "=", "N", ".", "ones", "(", "(", "a", ".", "shape", "[", "0", "]", ",", "a", ".", "shape", "[", "1", "]", "+", "1", ")", ")", "arr", "[", ":", ",", ":", "-", "1", "]", "=", "a", "return", ...
Adds a column of 1s at the end of the array
[ "Adds", "a", "column", "of", "1s", "at", "the", "end", "of", "the", "array" ]
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/linear/regression.py#L9-L13
train
53,143
henzk/featuremonkey
featuremonkey/importhooks.py
ImportHookBase._uninstall
def _uninstall(cls): """ uninstall the hook if installed """ if cls._hook: sys.meta_path.remove(cls._hook) cls._hook = None
python
def _uninstall(cls): """ uninstall the hook if installed """ if cls._hook: sys.meta_path.remove(cls._hook) cls._hook = None
[ "def", "_uninstall", "(", "cls", ")", ":", "if", "cls", ".", "_hook", ":", "sys", ".", "meta_path", ".", "remove", "(", "cls", ".", "_hook", ")", "cls", ".", "_hook", "=", "None" ]
uninstall the hook if installed
[ "uninstall", "the", "hook", "if", "installed" ]
e44414fc68427bcd71ad33ec2d816da0dd78eefa
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L34-L40
train
53,144
henzk/featuremonkey
featuremonkey/importhooks.py
LazyComposerHook.add
def add(cls, module_name, fsts, composer): ''' add a couple of fsts to be superimposed on the module given by module_name as soon as it is imported. internal - use featuremonkey.compose_later ''' cls._to_compose.setdefault(module_name, []) cls._to_compose[module_name].append( (list(fsts), composer) ) cls._install()
python
def add(cls, module_name, fsts, composer): ''' add a couple of fsts to be superimposed on the module given by module_name as soon as it is imported. internal - use featuremonkey.compose_later ''' cls._to_compose.setdefault(module_name, []) cls._to_compose[module_name].append( (list(fsts), composer) ) cls._install()
[ "def", "add", "(", "cls", ",", "module_name", ",", "fsts", ",", "composer", ")", ":", "cls", ".", "_to_compose", ".", "setdefault", "(", "module_name", ",", "[", "]", ")", "cls", ".", "_to_compose", "[", "module_name", "]", ".", "append", "(", "(", "...
add a couple of fsts to be superimposed on the module given by module_name as soon as it is imported. internal - use featuremonkey.compose_later
[ "add", "a", "couple", "of", "fsts", "to", "be", "superimposed", "on", "the", "module", "given", "by", "module_name", "as", "soon", "as", "it", "is", "imported", "." ]
e44414fc68427bcd71ad33ec2d816da0dd78eefa
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L69-L80
train
53,145
henzk/featuremonkey
featuremonkey/importhooks.py
ImportGuardHook.add
def add(cls, module_name, msg=''): ''' Until the guard is dropped again, disallow imports of the module given by ``module_name``. If the module is imported while the guard is in place an ``ImportGuard`` is raised. An additional message on why the module cannot be imported can optionally be specified using the parameter ``msg``. If multiple guards are placed on the same module, all these guards have to be dropped before the module can be imported again. ''' if module_name in sys.modules: raise ImportGuard( 'Module to guard has already been imported: ' + module_name ) cls._guards.setdefault(module_name, []) cls._guards[module_name].append(msg) cls._num_entries += 1 cls._install()
python
def add(cls, module_name, msg=''): ''' Until the guard is dropped again, disallow imports of the module given by ``module_name``. If the module is imported while the guard is in place an ``ImportGuard`` is raised. An additional message on why the module cannot be imported can optionally be specified using the parameter ``msg``. If multiple guards are placed on the same module, all these guards have to be dropped before the module can be imported again. ''' if module_name in sys.modules: raise ImportGuard( 'Module to guard has already been imported: ' + module_name ) cls._guards.setdefault(module_name, []) cls._guards[module_name].append(msg) cls._num_entries += 1 cls._install()
[ "def", "add", "(", "cls", ",", "module_name", ",", "msg", "=", "''", ")", ":", "if", "module_name", "in", "sys", ".", "modules", ":", "raise", "ImportGuard", "(", "'Module to guard has already been imported: '", "+", "module_name", ")", "cls", ".", "_guards", ...
Until the guard is dropped again, disallow imports of the module given by ``module_name``. If the module is imported while the guard is in place an ``ImportGuard`` is raised. An additional message on why the module cannot be imported can optionally be specified using the parameter ``msg``. If multiple guards are placed on the same module, all these guards have to be dropped before the module can be imported again.
[ "Until", "the", "guard", "is", "dropped", "again", "disallow", "imports", "of", "the", "module", "given", "by", "module_name", "." ]
e44414fc68427bcd71ad33ec2d816da0dd78eefa
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L132-L153
train
53,146
henzk/featuremonkey
featuremonkey/importhooks.py
ImportGuardHook.remove
def remove(cls, module_name): """ drop a previously created guard on ``module_name`` if the module is not guarded, then this is a no-op. """ module_guards = cls._guards.get(module_name, False) if module_guards: module_guards.pop() cls._num_entries -= 1 if cls._num_entries < 1: if cls._num_entries < 0: raise Exception( 'Bug: ImportGuardHook._num_entries became negative!' ) cls._uninstall()
python
def remove(cls, module_name): """ drop a previously created guard on ``module_name`` if the module is not guarded, then this is a no-op. """ module_guards = cls._guards.get(module_name, False) if module_guards: module_guards.pop() cls._num_entries -= 1 if cls._num_entries < 1: if cls._num_entries < 0: raise Exception( 'Bug: ImportGuardHook._num_entries became negative!' ) cls._uninstall()
[ "def", "remove", "(", "cls", ",", "module_name", ")", ":", "module_guards", "=", "cls", ".", "_guards", ".", "get", "(", "module_name", ",", "False", ")", "if", "module_guards", ":", "module_guards", ".", "pop", "(", ")", "cls", ".", "_num_entries", "-="...
drop a previously created guard on ``module_name`` if the module is not guarded, then this is a no-op.
[ "drop", "a", "previously", "created", "guard", "on", "module_name", "if", "the", "module", "is", "not", "guarded", "then", "this", "is", "a", "no", "-", "op", "." ]
e44414fc68427bcd71ad33ec2d816da0dd78eefa
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L156-L170
train
53,147
JohnVinyard/featureflow
featureflow/feature.py
Feature.copy
def copy( self, extractor=None, needs=None, store=None, data_writer=None, persistence=None, extractor_args=None): """ Use self as a template to build a new feature, replacing values in kwargs """ f = Feature( extractor or self.extractor, needs=needs, store=self.store if store is None else store, encoder=self.encoder, decoder=self.decoder, key=self.key, data_writer=data_writer, persistence=persistence, **(extractor_args or self.extractor_args)) f._fixup_needs() return f
python
def copy( self, extractor=None, needs=None, store=None, data_writer=None, persistence=None, extractor_args=None): """ Use self as a template to build a new feature, replacing values in kwargs """ f = Feature( extractor or self.extractor, needs=needs, store=self.store if store is None else store, encoder=self.encoder, decoder=self.decoder, key=self.key, data_writer=data_writer, persistence=persistence, **(extractor_args or self.extractor_args)) f._fixup_needs() return f
[ "def", "copy", "(", "self", ",", "extractor", "=", "None", ",", "needs", "=", "None", ",", "store", "=", "None", ",", "data_writer", "=", "None", ",", "persistence", "=", "None", ",", "extractor_args", "=", "None", ")", ":", "f", "=", "Feature", "(",...
Use self as a template to build a new feature, replacing values in kwargs
[ "Use", "self", "as", "a", "template", "to", "build", "a", "new", "feature", "replacing", "values", "in", "kwargs" ]
7731487b00e38fa4f58c88b7881870fda2d69fdb
https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/feature.py#L107-L130
train
53,148
JohnVinyard/featureflow
featureflow/feature.py
Feature._can_compute
def _can_compute(self, _id, persistence): """ Return true if this feature stored, or is unstored, but can be computed from stored dependencies """ if self.store and self._stored(_id, persistence): return True if self.is_root: return False return all( [n._can_compute(_id, persistence) for n in self.dependencies])
python
def _can_compute(self, _id, persistence): """ Return true if this feature stored, or is unstored, but can be computed from stored dependencies """ if self.store and self._stored(_id, persistence): return True if self.is_root: return False return all( [n._can_compute(_id, persistence) for n in self.dependencies])
[ "def", "_can_compute", "(", "self", ",", "_id", ",", "persistence", ")", ":", "if", "self", ".", "store", "and", "self", ".", "_stored", "(", "_id", ",", "persistence", ")", ":", "return", "True", "if", "self", ".", "is_root", ":", "return", "False", ...
Return true if this feature stored, or is unstored, but can be computed from stored dependencies
[ "Return", "true", "if", "this", "feature", "stored", "or", "is", "unstored", "but", "can", "be", "computed", "from", "stored", "dependencies" ]
7731487b00e38fa4f58c88b7881870fda2d69fdb
https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/feature.py#L163-L175
train
53,149
RudolfCardinal/pythonlib
cardinal_pythonlib/dbfunc.py
genrows
def genrows(cursor: Cursor, arraysize: int = 1000) \ -> Generator[List[Any], None, None]: """ Generate all rows from a cursor. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row """ # http://code.activestate.com/recipes/137270-use-generators-for-fetching-large-db-record-sets/ # noqa while True: results = cursor.fetchmany(arraysize) if not results: break for result in results: yield result
python
def genrows(cursor: Cursor, arraysize: int = 1000) \ -> Generator[List[Any], None, None]: """ Generate all rows from a cursor. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row """ # http://code.activestate.com/recipes/137270-use-generators-for-fetching-large-db-record-sets/ # noqa while True: results = cursor.fetchmany(arraysize) if not results: break for result in results: yield result
[ "def", "genrows", "(", "cursor", ":", "Cursor", ",", "arraysize", ":", "int", "=", "1000", ")", "->", "Generator", "[", "List", "[", "Any", "]", ",", "None", ",", "None", "]", ":", "# http://code.activestate.com/recipes/137270-use-generators-for-fetching-large-db-...
Generate all rows from a cursor. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row
[ "Generate", "all", "rows", "from", "a", "cursor", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L44-L62
train
53,150
RudolfCardinal/pythonlib
cardinal_pythonlib/dbfunc.py
genfirstvalues
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \ -> Generator[Any, None, None]: """ Generate the first value in each row. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: the first value of each row """ return (row[0] for row in genrows(cursor, arraysize))
python
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \ -> Generator[Any, None, None]: """ Generate the first value in each row. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: the first value of each row """ return (row[0] for row in genrows(cursor, arraysize))
[ "def", "genfirstvalues", "(", "cursor", ":", "Cursor", ",", "arraysize", ":", "int", "=", "1000", ")", "->", "Generator", "[", "Any", ",", "None", ",", "None", "]", ":", "return", "(", "row", "[", "0", "]", "for", "row", "in", "genrows", "(", "curs...
Generate the first value in each row. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: the first value of each row
[ "Generate", "the", "first", "value", "in", "each", "row", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L65-L77
train
53,151
RudolfCardinal/pythonlib
cardinal_pythonlib/colander_utils.py
get_values_and_permissible
def get_values_and_permissible(values: Iterable[Tuple[Any, str]], add_none: bool = False, none_description: str = "[None]") \ -> Tuple[List[Tuple[Any, str]], List[Any]]: """ Used when building Colander nodes. Args: values: an iterable of tuples like ``(value, description)`` used in HTML forms add_none: add a tuple ``(None, none_description)`` at the start of ``values`` in the result? none_description: the description used for ``None`` if ``add_none`` is set Returns: a tuple ``(values, permissible_values)``, where - ``values`` is what was passed in (perhaps with the addition of the "None" tuple at the start) - ``permissible_values`` is a list of all the ``value`` elements of the original ``values`` """ permissible_values = list(x[0] for x in values) # ... does not include the None value; those do not go to the validator if add_none: none_tuple = (SERIALIZED_NONE, none_description) values = [none_tuple] + list(values) return values, permissible_values
python
def get_values_and_permissible(values: Iterable[Tuple[Any, str]], add_none: bool = False, none_description: str = "[None]") \ -> Tuple[List[Tuple[Any, str]], List[Any]]: """ Used when building Colander nodes. Args: values: an iterable of tuples like ``(value, description)`` used in HTML forms add_none: add a tuple ``(None, none_description)`` at the start of ``values`` in the result? none_description: the description used for ``None`` if ``add_none`` is set Returns: a tuple ``(values, permissible_values)``, where - ``values`` is what was passed in (perhaps with the addition of the "None" tuple at the start) - ``permissible_values`` is a list of all the ``value`` elements of the original ``values`` """ permissible_values = list(x[0] for x in values) # ... does not include the None value; those do not go to the validator if add_none: none_tuple = (SERIALIZED_NONE, none_description) values = [none_tuple] + list(values) return values, permissible_values
[ "def", "get_values_and_permissible", "(", "values", ":", "Iterable", "[", "Tuple", "[", "Any", ",", "str", "]", "]", ",", "add_none", ":", "bool", "=", "False", ",", "none_description", ":", "str", "=", "\"[None]\"", ")", "->", "Tuple", "[", "List", "[",...
Used when building Colander nodes. Args: values: an iterable of tuples like ``(value, description)`` used in HTML forms add_none: add a tuple ``(None, none_description)`` at the start of ``values`` in the result? none_description: the description used for ``None`` if ``add_none`` is set Returns: a tuple ``(values, permissible_values)``, where - ``values`` is what was passed in (perhaps with the addition of the "None" tuple at the start) - ``permissible_values`` is a list of all the ``value`` elements of the original ``values``
[ "Used", "when", "building", "Colander", "nodes", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/colander_utils.py#L198-L229
train
53,152
RudolfCardinal/pythonlib
cardinal_pythonlib/colander_utils.py
PendulumType.deserialize
def deserialize(self, node: SchemaNode, cstruct: Union[str, ColanderNullType]) \ -> Optional[Pendulum]: """ Deserializes string representation to Python object. """ if not cstruct: return colander.null try: result = coerce_to_pendulum(cstruct, assume_local=self.use_local_tz) except (ValueError, ParserError) as e: raise Invalid(node, "Invalid date/time: value={!r}, error=" "{!r}".format(cstruct, e)) return result
python
def deserialize(self, node: SchemaNode, cstruct: Union[str, ColanderNullType]) \ -> Optional[Pendulum]: """ Deserializes string representation to Python object. """ if not cstruct: return colander.null try: result = coerce_to_pendulum(cstruct, assume_local=self.use_local_tz) except (ValueError, ParserError) as e: raise Invalid(node, "Invalid date/time: value={!r}, error=" "{!r}".format(cstruct, e)) return result
[ "def", "deserialize", "(", "self", ",", "node", ":", "SchemaNode", ",", "cstruct", ":", "Union", "[", "str", ",", "ColanderNullType", "]", ")", "->", "Optional", "[", "Pendulum", "]", ":", "if", "not", "cstruct", ":", "return", "colander", ".", "null", ...
Deserializes string representation to Python object.
[ "Deserializes", "string", "representation", "to", "Python", "object", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/colander_utils.py#L120-L135
train
53,153
henzk/featuremonkey
featuremonkey/composer.py
get_features_from_equation_file
def get_features_from_equation_file(filename): """ returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature anotherfeature :param filename: :return: """ features = [] for line in open(filename): line = line.split('#')[0].strip() if line: features.append(line) return features
python
def get_features_from_equation_file(filename): """ returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature anotherfeature :param filename: :return: """ features = [] for line in open(filename): line = line.split('#')[0].strip() if line: features.append(line) return features
[ "def", "get_features_from_equation_file", "(", "filename", ")", ":", "features", "=", "[", "]", "for", "line", "in", "open", "(", "filename", ")", ":", "line", "=", "line", ".", "split", "(", "'#'", ")", "[", "0", "]", ".", "strip", "(", ")", "if", ...
returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature anotherfeature :param filename: :return:
[ "returns", "list", "of", "feature", "names", "read", "from", "equation", "file", "given", "by", "filename", "." ]
e44414fc68427bcd71ad33ec2d816da0dd78eefa
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L19-L42
train
53,154
henzk/featuremonkey
featuremonkey/composer.py
Composer._compose_pair
def _compose_pair(self, role, base): ''' composes onto base by applying the role ''' # apply transformations in role to base for attrname in dir(role): transformation = getattr(role, attrname) self._apply_transformation(role, base, transformation, attrname) return base
python
def _compose_pair(self, role, base): ''' composes onto base by applying the role ''' # apply transformations in role to base for attrname in dir(role): transformation = getattr(role, attrname) self._apply_transformation(role, base, transformation, attrname) return base
[ "def", "_compose_pair", "(", "self", ",", "role", ",", "base", ")", ":", "# apply transformations in role to base", "for", "attrname", "in", "dir", "(", "role", ")", ":", "transformation", "=", "getattr", "(", "role", ",", "attrname", ")", "self", ".", "_app...
composes onto base by applying the role
[ "composes", "onto", "base", "by", "applying", "the", "role" ]
e44414fc68427bcd71ad33ec2d816da0dd78eefa
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L219-L228
train
53,155
meyersj/geotweet
geotweet/mapreduce/poi_nearby_tweets.py
POINearbyTweetsMRJob.mapper_metro
def mapper_metro(self, _, data): """ map each osm POI and geotweets based on spatial lookup of metro area """ # OSM POI record if 'tags' in data: type_tag = 1 lonlat = data['coordinates'] payload = data['tags'] # Tweet with coordinates from Streaming API elif 'user_id' in data: type_tag = 2 # only allow tweets from the listed domains to try and filter out # noise such as HR tweets, Weather reports and news updates accept = [ "twitter\.com", "foursquare\.com", "instagram\.com", "untappd\.com" ] expr = "|".join(accept) if not re.findall(expr, data['source']): return lonlat = data['lonlat'] payload = None # spatial lookup using Rtree with cached results metro = self.lookup.get(lonlat, METRO_DISTANCE) if not metro: return yield metro, (type_tag, lonlat, payload)
python
def mapper_metro(self, _, data): """ map each osm POI and geotweets based on spatial lookup of metro area """ # OSM POI record if 'tags' in data: type_tag = 1 lonlat = data['coordinates'] payload = data['tags'] # Tweet with coordinates from Streaming API elif 'user_id' in data: type_tag = 2 # only allow tweets from the listed domains to try and filter out # noise such as HR tweets, Weather reports and news updates accept = [ "twitter\.com", "foursquare\.com", "instagram\.com", "untappd\.com" ] expr = "|".join(accept) if not re.findall(expr, data['source']): return lonlat = data['lonlat'] payload = None # spatial lookup using Rtree with cached results metro = self.lookup.get(lonlat, METRO_DISTANCE) if not metro: return yield metro, (type_tag, lonlat, payload)
[ "def", "mapper_metro", "(", "self", ",", "_", ",", "data", ")", ":", "# OSM POI record", "if", "'tags'", "in", "data", ":", "type_tag", "=", "1", "lonlat", "=", "data", "[", "'coordinates'", "]", "payload", "=", "data", "[", "'tags'", "]", "# Tweet with ...
map each osm POI and geotweets based on spatial lookup of metro area
[ "map", "each", "osm", "POI", "and", "geotweets", "based", "on", "spatial", "lookup", "of", "metro", "area" ]
1a6b55f98adf34d1b91f172d9187d599616412d9
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L81-L108
train
53,156
meyersj/geotweet
geotweet/mapreduce/poi_nearby_tweets.py
POINearbyTweetsMRJob.reducer_metro
def reducer_metro(self, metro, values): """ Output tags of POI locations nearby tweet locations Values will be sorted coming into reducer. First element in each value tuple will be either 1 (osm POI) or 2 (geotweet). Build a spatial index with POI records. For each tweet lookup nearby POI, and emit tag values for predefined tags. """ lookup = CachedLookup(precision=POI_GEOHASH_PRECISION) for i, value in enumerate(values): type_tag, lonlat, data = value if type_tag == 1: # OSM POI node, construct geojson and add to Rtree index lookup.insert(i, dict( geometry=dict(type='Point', coordinates=project(lonlat)), properties=dict(tags=data) )) else: # geotweet, lookup nearest POI from index if not lookup.data_store: return poi_names = [] kwargs = dict(buffer_size=POI_DISTANCE, multiple=True) # lookup nearby POI from Rtree index (caching results) # for any tags we care about emit the tags value and 1 for poi in lookup.get(lonlat, **kwargs): has_tag = [ tag in poi['tags'] for tag in POI_TAGS ] if any(has_tag) and 'name' in poi['tags']: poi_names.append(poi['tags']['name']) for poi in set(poi_names): yield (metro, poi), 1
python
def reducer_metro(self, metro, values): """ Output tags of POI locations nearby tweet locations Values will be sorted coming into reducer. First element in each value tuple will be either 1 (osm POI) or 2 (geotweet). Build a spatial index with POI records. For each tweet lookup nearby POI, and emit tag values for predefined tags. """ lookup = CachedLookup(precision=POI_GEOHASH_PRECISION) for i, value in enumerate(values): type_tag, lonlat, data = value if type_tag == 1: # OSM POI node, construct geojson and add to Rtree index lookup.insert(i, dict( geometry=dict(type='Point', coordinates=project(lonlat)), properties=dict(tags=data) )) else: # geotweet, lookup nearest POI from index if not lookup.data_store: return poi_names = [] kwargs = dict(buffer_size=POI_DISTANCE, multiple=True) # lookup nearby POI from Rtree index (caching results) # for any tags we care about emit the tags value and 1 for poi in lookup.get(lonlat, **kwargs): has_tag = [ tag in poi['tags'] for tag in POI_TAGS ] if any(has_tag) and 'name' in poi['tags']: poi_names.append(poi['tags']['name']) for poi in set(poi_names): yield (metro, poi), 1
[ "def", "reducer_metro", "(", "self", ",", "metro", ",", "values", ")", ":", "lookup", "=", "CachedLookup", "(", "precision", "=", "POI_GEOHASH_PRECISION", ")", "for", "i", ",", "value", "in", "enumerate", "(", "values", ")", ":", "type_tag", ",", "lonlat",...
Output tags of POI locations nearby tweet locations Values will be sorted coming into reducer. First element in each value tuple will be either 1 (osm POI) or 2 (geotweet). Build a spatial index with POI records. For each tweet lookup nearby POI, and emit tag values for predefined tags.
[ "Output", "tags", "of", "POI", "locations", "nearby", "tweet", "locations" ]
1a6b55f98adf34d1b91f172d9187d599616412d9
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L110-L142
train
53,157
meyersj/geotweet
geotweet/mapreduce/poi_nearby_tweets.py
POINearbyTweetsMRJob.reducer_output
def reducer_output(self, metro, values): """ store each record in MongoDB and output tab delimited lines """ records = [] # build up list of data for each metro area and submit as one network # call instead of individually for value in values: total, poi = value records.append(dict( metro_area=metro, poi=poi, count=total )) output = "{0}\t{1}\t{2}" output = output.format(metro.encode('utf-8'), total, poi.encode('utf-8')) yield None, output if self.mongo: self.mongo.insert_many(records)
python
def reducer_output(self, metro, values): """ store each record in MongoDB and output tab delimited lines """ records = [] # build up list of data for each metro area and submit as one network # call instead of individually for value in values: total, poi = value records.append(dict( metro_area=metro, poi=poi, count=total )) output = "{0}\t{1}\t{2}" output = output.format(metro.encode('utf-8'), total, poi.encode('utf-8')) yield None, output if self.mongo: self.mongo.insert_many(records)
[ "def", "reducer_output", "(", "self", ",", "metro", ",", "values", ")", ":", "records", "=", "[", "]", "# build up list of data for each metro area and submit as one network", "# call instead of individually ", "for", "value", "in", "values", ":", "total", ",", "poi", ...
store each record in MongoDB and output tab delimited lines
[ "store", "each", "record", "in", "MongoDB", "and", "output", "tab", "delimited", "lines" ]
1a6b55f98adf34d1b91f172d9187d599616412d9
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L159-L175
train
53,158
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/sqlfunc.py
fetch_processed_single_clause
def fetch_processed_single_clause(element: "ClauseElement", compiler: "SQLCompiler") -> str: """ Takes a clause element that must have a single clause, and converts it to raw SQL text. """ if len(element.clauses) != 1: raise TypeError("Only one argument supported; {} were passed".format( len(element.clauses))) clauselist = element.clauses # type: ClauseList first = clauselist.get_children()[0] return compiler.process(first)
python
def fetch_processed_single_clause(element: "ClauseElement", compiler: "SQLCompiler") -> str: """ Takes a clause element that must have a single clause, and converts it to raw SQL text. """ if len(element.clauses) != 1: raise TypeError("Only one argument supported; {} were passed".format( len(element.clauses))) clauselist = element.clauses # type: ClauseList first = clauselist.get_children()[0] return compiler.process(first)
[ "def", "fetch_processed_single_clause", "(", "element", ":", "\"ClauseElement\"", ",", "compiler", ":", "\"SQLCompiler\"", ")", "->", "str", ":", "if", "len", "(", "element", ".", "clauses", ")", "!=", "1", ":", "raise", "TypeError", "(", "\"Only one argument su...
Takes a clause element that must have a single clause, and converts it to raw SQL text.
[ "Takes", "a", "clause", "element", "that", "must", "have", "a", "single", "clause", "and", "converts", "it", "to", "raw", "SQL", "text", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/sqlfunc.py#L66-L77
train
53,159
RudolfCardinal/pythonlib
cardinal_pythonlib/django/forms.py
clean_int
def clean_int(x) -> int: """ Returns its parameter as an integer, or raises ``django.forms.ValidationError``. """ try: return int(x) except ValueError: raise forms.ValidationError( "Cannot convert to integer: {}".format(repr(x)))
python
def clean_int(x) -> int: """ Returns its parameter as an integer, or raises ``django.forms.ValidationError``. """ try: return int(x) except ValueError: raise forms.ValidationError( "Cannot convert to integer: {}".format(repr(x)))
[ "def", "clean_int", "(", "x", ")", "->", "int", ":", "try", ":", "return", "int", "(", "x", ")", "except", "ValueError", ":", "raise", "forms", ".", "ValidationError", "(", "\"Cannot convert to integer: {}\"", ".", "format", "(", "repr", "(", "x", ")", "...
Returns its parameter as an integer, or raises ``django.forms.ValidationError``.
[ "Returns", "its", "parameter", "as", "an", "integer", "or", "raises", "django", ".", "forms", ".", "ValidationError", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/forms.py#L40-L49
train
53,160
RudolfCardinal/pythonlib
cardinal_pythonlib/django/forms.py
clean_nhs_number
def clean_nhs_number(x) -> int: """ Returns its parameter as a valid integer NHS number, or raises ``django.forms.ValidationError``. """ try: x = int(x) if not is_valid_nhs_number(x): raise ValueError return x except ValueError: raise forms.ValidationError( "Not a valid NHS number: {}".format(repr(x)))
python
def clean_nhs_number(x) -> int: """ Returns its parameter as a valid integer NHS number, or raises ``django.forms.ValidationError``. """ try: x = int(x) if not is_valid_nhs_number(x): raise ValueError return x except ValueError: raise forms.ValidationError( "Not a valid NHS number: {}".format(repr(x)))
[ "def", "clean_nhs_number", "(", "x", ")", "->", "int", ":", "try", ":", "x", "=", "int", "(", "x", ")", "if", "not", "is_valid_nhs_number", "(", "x", ")", ":", "raise", "ValueError", "return", "x", "except", "ValueError", ":", "raise", "forms", ".", ...
Returns its parameter as a valid integer NHS number, or raises ``django.forms.ValidationError``.
[ "Returns", "its", "parameter", "as", "a", "valid", "integer", "NHS", "number", "or", "raises", "django", ".", "forms", ".", "ValidationError", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/forms.py#L52-L64
train
53,161
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
coltype_as_typeengine
def coltype_as_typeengine(coltype: Union[VisitableType, TypeEngine]) -> TypeEngine: """ Instances of SQLAlchemy column types are subclasses of ``TypeEngine``. It's possible to specify column types either as such instances, or as the class type. This function ensures that such classes are converted to instances. To explain: you can specify columns like .. code-block:: python a = Column("a", Integer) b = Column("b", Integer()) c = Column("c", String(length=50)) isinstance(Integer, TypeEngine) # False isinstance(Integer(), TypeEngine) # True isinstance(String(length=50), TypeEngine) # True type(Integer) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(Integer()) # <class 'sqlalchemy.sql.sqltypes.Integer'> type(String) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(String(length=50)) # <class 'sqlalchemy.sql.sqltypes.String'> This function coerces things to a :class:`TypeEngine`. """ if isinstance(coltype, TypeEngine): return coltype return coltype()
python
def coltype_as_typeengine(coltype: Union[VisitableType, TypeEngine]) -> TypeEngine: """ Instances of SQLAlchemy column types are subclasses of ``TypeEngine``. It's possible to specify column types either as such instances, or as the class type. This function ensures that such classes are converted to instances. To explain: you can specify columns like .. code-block:: python a = Column("a", Integer) b = Column("b", Integer()) c = Column("c", String(length=50)) isinstance(Integer, TypeEngine) # False isinstance(Integer(), TypeEngine) # True isinstance(String(length=50), TypeEngine) # True type(Integer) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(Integer()) # <class 'sqlalchemy.sql.sqltypes.Integer'> type(String) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(String(length=50)) # <class 'sqlalchemy.sql.sqltypes.String'> This function coerces things to a :class:`TypeEngine`. """ if isinstance(coltype, TypeEngine): return coltype return coltype()
[ "def", "coltype_as_typeengine", "(", "coltype", ":", "Union", "[", "VisitableType", ",", "TypeEngine", "]", ")", "->", "TypeEngine", ":", "if", "isinstance", "(", "coltype", ",", "TypeEngine", ")", ":", "return", "coltype", "return", "coltype", "(", ")" ]
Instances of SQLAlchemy column types are subclasses of ``TypeEngine``. It's possible to specify column types either as such instances, or as the class type. This function ensures that such classes are converted to instances. To explain: you can specify columns like .. code-block:: python a = Column("a", Integer) b = Column("b", Integer()) c = Column("c", String(length=50)) isinstance(Integer, TypeEngine) # False isinstance(Integer(), TypeEngine) # True isinstance(String(length=50), TypeEngine) # True type(Integer) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(Integer()) # <class 'sqlalchemy.sql.sqltypes.Integer'> type(String) # <class 'sqlalchemy.sql.visitors.VisitableType'> type(String(length=50)) # <class 'sqlalchemy.sql.sqltypes.String'> This function coerces things to a :class:`TypeEngine`.
[ "Instances", "of", "SQLAlchemy", "column", "types", "are", "subclasses", "of", "TypeEngine", ".", "It", "s", "possible", "to", "specify", "column", "types", "either", "as", "such", "instances", "or", "as", "the", "class", "type", ".", "This", "function", "en...
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L60-L89
train
53,162
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
walk_orm_tree
def walk_orm_tree(obj, debug: bool = False, seen: Set = None, skip_relationships_always: List[str] = None, skip_relationships_by_tablename: Dict[str, List[str]] = None, skip_all_relationships_for_tablenames: List[str] = None, skip_all_objects_for_tablenames: List[str] = None) \ -> Generator[object, None, None]: """ Starting with a SQLAlchemy ORM object, this function walks a relationship tree, yielding each of the objects once. To skip attributes by name, put the attribute name(s) in ``skip_attrs_always``. To skip by table name, pass ``skip_attrs_by_tablename`` as e.g. .. code-block:: python {'sometable': ['attr1_to_skip', 'attr2_to_skip']} Args: obj: the SQLAlchemy ORM object to walk debug: be verbose seen: usually ``None``, but can be a set of objects marked as "already seen"; if an object is in this set, it is skipped skip_relationships_always: relationships are skipped if the relationship has a name in this (optional) list skip_relationships_by_tablename: optional dictionary mapping table names (keys) to relationship attribute names (values); if the "related table"/"relationship attribute" pair are in this dictionary, the relationship is skipped skip_all_relationships_for_tablenames: relationships are skipped if the the related table has a name in this (optional) list skip_all_objects_for_tablenames: if the object belongs to a table whose name is in this (optional) list, the object is skipped Yields: SQLAlchemy ORM objects (including the starting object) """ # http://docs.sqlalchemy.org/en/latest/faq/sessions.html#faq-walk-objects skip_relationships_always = skip_relationships_always or [] # type: List[str] # noqa skip_relationships_by_tablename = skip_relationships_by_tablename or {} # type: Dict[str, List[str]] # noqa skip_all_relationships_for_tablenames = skip_all_relationships_for_tablenames or [] # type: List[str] # noqa skip_all_objects_for_tablenames = skip_all_objects_for_tablenames or [] # type: List[str] # noqa stack = [obj] if seen is None: seen = set() while stack: obj = stack.pop(0) if obj in seen: continue tablename = obj.__tablename__ if tablename in skip_all_objects_for_tablenames: continue seen.add(obj) if debug: log.debug("walk: yielding {!r}", obj) yield obj insp = inspect(obj) # type: InstanceState for relationship in insp.mapper.relationships: # type: RelationshipProperty # noqa attrname = relationship.key # Skip? if attrname in skip_relationships_always: continue if tablename in skip_all_relationships_for_tablenames: continue if (tablename in skip_relationships_by_tablename and attrname in skip_relationships_by_tablename[tablename]): continue # Process relationship if debug: log.debug("walk: following relationship {}", relationship) related = getattr(obj, attrname) if debug and related: log.debug("walk: queueing {!r}", related) if relationship.uselist: stack.extend(related) elif related is not None: stack.append(related)
python
def walk_orm_tree(obj, debug: bool = False, seen: Set = None, skip_relationships_always: List[str] = None, skip_relationships_by_tablename: Dict[str, List[str]] = None, skip_all_relationships_for_tablenames: List[str] = None, skip_all_objects_for_tablenames: List[str] = None) \ -> Generator[object, None, None]: """ Starting with a SQLAlchemy ORM object, this function walks a relationship tree, yielding each of the objects once. To skip attributes by name, put the attribute name(s) in ``skip_attrs_always``. To skip by table name, pass ``skip_attrs_by_tablename`` as e.g. .. code-block:: python {'sometable': ['attr1_to_skip', 'attr2_to_skip']} Args: obj: the SQLAlchemy ORM object to walk debug: be verbose seen: usually ``None``, but can be a set of objects marked as "already seen"; if an object is in this set, it is skipped skip_relationships_always: relationships are skipped if the relationship has a name in this (optional) list skip_relationships_by_tablename: optional dictionary mapping table names (keys) to relationship attribute names (values); if the "related table"/"relationship attribute" pair are in this dictionary, the relationship is skipped skip_all_relationships_for_tablenames: relationships are skipped if the the related table has a name in this (optional) list skip_all_objects_for_tablenames: if the object belongs to a table whose name is in this (optional) list, the object is skipped Yields: SQLAlchemy ORM objects (including the starting object) """ # http://docs.sqlalchemy.org/en/latest/faq/sessions.html#faq-walk-objects skip_relationships_always = skip_relationships_always or [] # type: List[str] # noqa skip_relationships_by_tablename = skip_relationships_by_tablename or {} # type: Dict[str, List[str]] # noqa skip_all_relationships_for_tablenames = skip_all_relationships_for_tablenames or [] # type: List[str] # noqa skip_all_objects_for_tablenames = skip_all_objects_for_tablenames or [] # type: List[str] # noqa stack = [obj] if seen is None: seen = set() while stack: obj = stack.pop(0) if obj in seen: continue tablename = obj.__tablename__ if tablename in skip_all_objects_for_tablenames: continue seen.add(obj) if debug: log.debug("walk: yielding {!r}", obj) yield obj insp = inspect(obj) # type: InstanceState for relationship in insp.mapper.relationships: # type: RelationshipProperty # noqa attrname = relationship.key # Skip? if attrname in skip_relationships_always: continue if tablename in skip_all_relationships_for_tablenames: continue if (tablename in skip_relationships_by_tablename and attrname in skip_relationships_by_tablename[tablename]): continue # Process relationship if debug: log.debug("walk: following relationship {}", relationship) related = getattr(obj, attrname) if debug and related: log.debug("walk: queueing {!r}", related) if relationship.uselist: stack.extend(related) elif related is not None: stack.append(related)
[ "def", "walk_orm_tree", "(", "obj", ",", "debug", ":", "bool", "=", "False", ",", "seen", ":", "Set", "=", "None", ",", "skip_relationships_always", ":", "List", "[", "str", "]", "=", "None", ",", "skip_relationships_by_tablename", ":", "Dict", "[", "str",...
Starting with a SQLAlchemy ORM object, this function walks a relationship tree, yielding each of the objects once. To skip attributes by name, put the attribute name(s) in ``skip_attrs_always``. To skip by table name, pass ``skip_attrs_by_tablename`` as e.g. .. code-block:: python {'sometable': ['attr1_to_skip', 'attr2_to_skip']} Args: obj: the SQLAlchemy ORM object to walk debug: be verbose seen: usually ``None``, but can be a set of objects marked as "already seen"; if an object is in this set, it is skipped skip_relationships_always: relationships are skipped if the relationship has a name in this (optional) list skip_relationships_by_tablename: optional dictionary mapping table names (keys) to relationship attribute names (values); if the "related table"/"relationship attribute" pair are in this dictionary, the relationship is skipped skip_all_relationships_for_tablenames: relationships are skipped if the the related table has a name in this (optional) list skip_all_objects_for_tablenames: if the object belongs to a table whose name is in this (optional) list, the object is skipped Yields: SQLAlchemy ORM objects (including the starting object)
[ "Starting", "with", "a", "SQLAlchemy", "ORM", "object", "this", "function", "walks", "a", "relationship", "tree", "yielding", "each", "of", "the", "objects", "once", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L140-L226
train
53,163
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
rewrite_relationships
def rewrite_relationships(oldobj: object, newobj: object, objmap: Dict[object, object], debug: bool = False, skip_table_names: List[str] = None) -> None: """ A utility function only. Used in copying objects between SQLAlchemy sessions. Both ``oldobj`` and ``newobj`` are SQLAlchemy instances. The instance ``newobj`` is already a copy of ``oldobj`` but we wish to rewrite its relationships, according to the map ``objmap``, which maps old to new objects. For example: - Suppose a source session has a Customer record and a Sale record containing ``sale.customer_id``, a foreign key to Customer. - We may have corresponding Python SQLAlchemy ORM objects ``customer_1_src`` and ``sale_1_src``. - We copy them into a destination database, where their Python ORM objects are ``customer_1_dest`` and ``sale_1_dest``. - In the process we set up an object map looking like: .. code-block:: none Old session New session ------------------------------- customer_1_src customer_1_dest sale_1_src sale_1_dest - Now, we wish to make ``sale_1_dest`` have a relationship to ``customer_1_dest``, in the same way that ``sale_1_src`` has a relationship to ``customer_1_src``. This function will modify ``sale_1_dest`` accordingly, given this object map. It will observe that ``sale_1_src`` (here ``oldobj``) has a relationship to ``customer_1_src``; it will note that ``objmap`` maps ``customer_1_src`` to ``customer_1_dest``; it will create the relationship from ``sale_1_dest`` (here ``newobj``) to ``customer_1_dest``. Args: oldobj: SQLAlchemy ORM object to read from newobj: SQLAlchemy ORM object to write to objmap: dictionary mapping "source" objects to their corresponding "destination" object. debug: be verbose skip_table_names: if a related table's name is in this (optional) list, that relationship is skipped """ skip_table_names = skip_table_names or [] # type: List[str] insp = inspect(oldobj) # type: InstanceState # insp.mapper.relationships is of type # sqlalchemy.utils._collections.ImmutableProperties, which is basically # a sort of AttrDict. for attrname_rel in insp.mapper.relationships.items(): # type: Tuple[str, RelationshipProperty] # noqa attrname = attrname_rel[0] rel_prop = attrname_rel[1] if rel_prop.viewonly: if debug: log.debug("Skipping viewonly relationship") continue # don't attempt to write viewonly relationships # noqa related_class = rel_prop.mapper.class_ related_table_name = related_class.__tablename__ # type: str if related_table_name in skip_table_names: if debug: log.debug("Skipping relationship for related table {!r}", related_table_name) continue # The relationship is an abstract object (so getting the # relationship from the old object and from the new, with e.g. # newrel = newinsp.mapper.relationships[oldrel.key], # yield the same object. All we need from it is the key name. # rel_key = rel.key # type: str # ... but also available from the mapper as attrname, above related_old = getattr(oldobj, attrname) if rel_prop.uselist: related_new = [objmap[r] for r in related_old] elif related_old is not None: related_new = objmap[related_old] else: related_new = None if debug: log.debug("rewrite_relationships: relationship {} -> {}", attrname, related_new) setattr(newobj, attrname, related_new)
python
def rewrite_relationships(oldobj: object, newobj: object, objmap: Dict[object, object], debug: bool = False, skip_table_names: List[str] = None) -> None: """ A utility function only. Used in copying objects between SQLAlchemy sessions. Both ``oldobj`` and ``newobj`` are SQLAlchemy instances. The instance ``newobj`` is already a copy of ``oldobj`` but we wish to rewrite its relationships, according to the map ``objmap``, which maps old to new objects. For example: - Suppose a source session has a Customer record and a Sale record containing ``sale.customer_id``, a foreign key to Customer. - We may have corresponding Python SQLAlchemy ORM objects ``customer_1_src`` and ``sale_1_src``. - We copy them into a destination database, where their Python ORM objects are ``customer_1_dest`` and ``sale_1_dest``. - In the process we set up an object map looking like: .. code-block:: none Old session New session ------------------------------- customer_1_src customer_1_dest sale_1_src sale_1_dest - Now, we wish to make ``sale_1_dest`` have a relationship to ``customer_1_dest``, in the same way that ``sale_1_src`` has a relationship to ``customer_1_src``. This function will modify ``sale_1_dest`` accordingly, given this object map. It will observe that ``sale_1_src`` (here ``oldobj``) has a relationship to ``customer_1_src``; it will note that ``objmap`` maps ``customer_1_src`` to ``customer_1_dest``; it will create the relationship from ``sale_1_dest`` (here ``newobj``) to ``customer_1_dest``. Args: oldobj: SQLAlchemy ORM object to read from newobj: SQLAlchemy ORM object to write to objmap: dictionary mapping "source" objects to their corresponding "destination" object. debug: be verbose skip_table_names: if a related table's name is in this (optional) list, that relationship is skipped """ skip_table_names = skip_table_names or [] # type: List[str] insp = inspect(oldobj) # type: InstanceState # insp.mapper.relationships is of type # sqlalchemy.utils._collections.ImmutableProperties, which is basically # a sort of AttrDict. for attrname_rel in insp.mapper.relationships.items(): # type: Tuple[str, RelationshipProperty] # noqa attrname = attrname_rel[0] rel_prop = attrname_rel[1] if rel_prop.viewonly: if debug: log.debug("Skipping viewonly relationship") continue # don't attempt to write viewonly relationships # noqa related_class = rel_prop.mapper.class_ related_table_name = related_class.__tablename__ # type: str if related_table_name in skip_table_names: if debug: log.debug("Skipping relationship for related table {!r}", related_table_name) continue # The relationship is an abstract object (so getting the # relationship from the old object and from the new, with e.g. # newrel = newinsp.mapper.relationships[oldrel.key], # yield the same object. All we need from it is the key name. # rel_key = rel.key # type: str # ... but also available from the mapper as attrname, above related_old = getattr(oldobj, attrname) if rel_prop.uselist: related_new = [objmap[r] for r in related_old] elif related_old is not None: related_new = objmap[related_old] else: related_new = None if debug: log.debug("rewrite_relationships: relationship {} -> {}", attrname, related_new) setattr(newobj, attrname, related_new)
[ "def", "rewrite_relationships", "(", "oldobj", ":", "object", ",", "newobj", ":", "object", ",", "objmap", ":", "Dict", "[", "object", ",", "object", "]", ",", "debug", ":", "bool", "=", "False", ",", "skip_table_names", ":", "List", "[", "str", "]", "...
A utility function only. Used in copying objects between SQLAlchemy sessions. Both ``oldobj`` and ``newobj`` are SQLAlchemy instances. The instance ``newobj`` is already a copy of ``oldobj`` but we wish to rewrite its relationships, according to the map ``objmap``, which maps old to new objects. For example: - Suppose a source session has a Customer record and a Sale record containing ``sale.customer_id``, a foreign key to Customer. - We may have corresponding Python SQLAlchemy ORM objects ``customer_1_src`` and ``sale_1_src``. - We copy them into a destination database, where their Python ORM objects are ``customer_1_dest`` and ``sale_1_dest``. - In the process we set up an object map looking like: .. code-block:: none Old session New session ------------------------------- customer_1_src customer_1_dest sale_1_src sale_1_dest - Now, we wish to make ``sale_1_dest`` have a relationship to ``customer_1_dest``, in the same way that ``sale_1_src`` has a relationship to ``customer_1_src``. This function will modify ``sale_1_dest`` accordingly, given this object map. It will observe that ``sale_1_src`` (here ``oldobj``) has a relationship to ``customer_1_src``; it will note that ``objmap`` maps ``customer_1_src`` to ``customer_1_dest``; it will create the relationship from ``sale_1_dest`` (here ``newobj``) to ``customer_1_dest``. Args: oldobj: SQLAlchemy ORM object to read from newobj: SQLAlchemy ORM object to write to objmap: dictionary mapping "source" objects to their corresponding "destination" object. debug: be verbose skip_table_names: if a related table's name is in this (optional) list, that relationship is skipped
[ "A", "utility", "function", "only", ".", "Used", "in", "copying", "objects", "between", "SQLAlchemy", "sessions", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L291-L382
train
53,164
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
deepcopy_sqla_objects
def deepcopy_sqla_objects( startobjs: List[object], session: Session, flush: bool = True, debug: bool = False, debug_walk: bool = True, debug_rewrite_rel: bool = False, objmap: Dict[object, object] = None) -> None: """ Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a new session. This function operates in several passes: 1. Walk the ORM tree through all objects and their relationships, copying every object thus found (via :func:`copy_sqla_object`, without their relationships), and building a map from each source-session object to its equivalent destination-session object. 2. Work through all the destination objects, rewriting their relationships (via :func:`rewrite_relationships`) so they relate to each other (rather than their source-session brethren). 3. Insert all the destination-session objects into the destination session. For this to succeed, every object must take an ``__init__`` call with no arguments (see :func:`copy_sqla_object`). (We can't specify the required ``args``/``kwargs``, since we are copying a tree of arbitrary objects.) Args: startobjs: SQLAlchemy ORM objects to copy session: destination SQLAlchemy :class:`Session` into which to insert the copies flush: flush the session when we've finished? debug: be verbose? debug_walk: be extra verbose when walking the ORM tree? debug_rewrite_rel: be extra verbose when rewriting relationships? objmap: starting object map from source-session to destination-session objects (see :func:`rewrite_relationships` for more detail); usually ``None`` to begin with. """ if objmap is None: objmap = {} # keys = old objects, values = new objects if debug: log.debug("deepcopy_sqla_objects: pass 1: create new objects") # Pass 1: iterate through all objects. (Can't guarantee to get # relationships correct until we've done this, since we don't know whether # or where the "root" of the PK tree is.) seen = set() for startobj in startobjs: for oldobj in walk_orm_tree(startobj, seen=seen, debug=debug_walk): if debug: log.debug("deepcopy_sqla_objects: copying {}", oldobj) newobj = copy_sqla_object(oldobj, omit_pk=True, omit_fk=True) # Don't insert the new object into the session here; it may trigger # an autoflush as the relationships are queried, and the new # objects are not ready for insertion yet (as their relationships # aren't set). # Note also the session.no_autoflush option: # "sqlalchemy.exc.OperationalError: (raised as a result of Query- # invoked autoflush; consider using a session.no_autoflush block if # this flush is occurring prematurely)..." objmap[oldobj] = newobj # Pass 2: set all relationship properties. if debug: log.debug("deepcopy_sqla_objects: pass 2: set relationships") for oldobj, newobj in objmap.items(): if debug: log.debug("deepcopy_sqla_objects: newobj: {}", newobj) rewrite_relationships(oldobj, newobj, objmap, debug=debug_rewrite_rel) # Now we can do session insert. if debug: log.debug("deepcopy_sqla_objects: pass 3: insert into session") for newobj in objmap.values(): session.add(newobj) # Done if debug: log.debug("deepcopy_sqla_objects: done") if flush: session.flush()
python
def deepcopy_sqla_objects( startobjs: List[object], session: Session, flush: bool = True, debug: bool = False, debug_walk: bool = True, debug_rewrite_rel: bool = False, objmap: Dict[object, object] = None) -> None: """ Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a new session. This function operates in several passes: 1. Walk the ORM tree through all objects and their relationships, copying every object thus found (via :func:`copy_sqla_object`, without their relationships), and building a map from each source-session object to its equivalent destination-session object. 2. Work through all the destination objects, rewriting their relationships (via :func:`rewrite_relationships`) so they relate to each other (rather than their source-session brethren). 3. Insert all the destination-session objects into the destination session. For this to succeed, every object must take an ``__init__`` call with no arguments (see :func:`copy_sqla_object`). (We can't specify the required ``args``/``kwargs``, since we are copying a tree of arbitrary objects.) Args: startobjs: SQLAlchemy ORM objects to copy session: destination SQLAlchemy :class:`Session` into which to insert the copies flush: flush the session when we've finished? debug: be verbose? debug_walk: be extra verbose when walking the ORM tree? debug_rewrite_rel: be extra verbose when rewriting relationships? objmap: starting object map from source-session to destination-session objects (see :func:`rewrite_relationships` for more detail); usually ``None`` to begin with. """ if objmap is None: objmap = {} # keys = old objects, values = new objects if debug: log.debug("deepcopy_sqla_objects: pass 1: create new objects") # Pass 1: iterate through all objects. (Can't guarantee to get # relationships correct until we've done this, since we don't know whether # or where the "root" of the PK tree is.) seen = set() for startobj in startobjs: for oldobj in walk_orm_tree(startobj, seen=seen, debug=debug_walk): if debug: log.debug("deepcopy_sqla_objects: copying {}", oldobj) newobj = copy_sqla_object(oldobj, omit_pk=True, omit_fk=True) # Don't insert the new object into the session here; it may trigger # an autoflush as the relationships are queried, and the new # objects are not ready for insertion yet (as their relationships # aren't set). # Note also the session.no_autoflush option: # "sqlalchemy.exc.OperationalError: (raised as a result of Query- # invoked autoflush; consider using a session.no_autoflush block if # this flush is occurring prematurely)..." objmap[oldobj] = newobj # Pass 2: set all relationship properties. if debug: log.debug("deepcopy_sqla_objects: pass 2: set relationships") for oldobj, newobj in objmap.items(): if debug: log.debug("deepcopy_sqla_objects: newobj: {}", newobj) rewrite_relationships(oldobj, newobj, objmap, debug=debug_rewrite_rel) # Now we can do session insert. if debug: log.debug("deepcopy_sqla_objects: pass 3: insert into session") for newobj in objmap.values(): session.add(newobj) # Done if debug: log.debug("deepcopy_sqla_objects: done") if flush: session.flush()
[ "def", "deepcopy_sqla_objects", "(", "startobjs", ":", "List", "[", "object", "]", ",", "session", ":", "Session", ",", "flush", ":", "bool", "=", "True", ",", "debug", ":", "bool", "=", "False", ",", "debug_walk", ":", "bool", "=", "True", ",", "debug...
Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a new session. This function operates in several passes: 1. Walk the ORM tree through all objects and their relationships, copying every object thus found (via :func:`copy_sqla_object`, without their relationships), and building a map from each source-session object to its equivalent destination-session object. 2. Work through all the destination objects, rewriting their relationships (via :func:`rewrite_relationships`) so they relate to each other (rather than their source-session brethren). 3. Insert all the destination-session objects into the destination session. For this to succeed, every object must take an ``__init__`` call with no arguments (see :func:`copy_sqla_object`). (We can't specify the required ``args``/``kwargs``, since we are copying a tree of arbitrary objects.) Args: startobjs: SQLAlchemy ORM objects to copy session: destination SQLAlchemy :class:`Session` into which to insert the copies flush: flush the session when we've finished? debug: be verbose? debug_walk: be extra verbose when walking the ORM tree? debug_rewrite_rel: be extra verbose when rewriting relationships? objmap: starting object map from source-session to destination-session objects (see :func:`rewrite_relationships` for more detail); usually ``None`` to begin with.
[ "Makes", "a", "copy", "of", "the", "specified", "SQLAlchemy", "ORM", "objects", "inserting", "them", "into", "a", "new", "session", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L385-L468
train
53,165
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
deepcopy_sqla_object
def deepcopy_sqla_object(startobj: object, session: Session, flush: bool = True, debug: bool = False, debug_walk: bool = False, debug_rewrite_rel: bool = False, objmap: Dict[object, object] = None) -> object: """ Makes a copy of the object, inserting it into ``session``. Uses :func:`deepcopy_sqla_objects` (q.v.). A problem is the creation of duplicate dependency objects if you call it repeatedly. Optionally, if you pass the objmap in (which maps old to new objects), you can call this function repeatedly to clone a related set of objects... ... no, that doesn't really work, as it doesn't visit parents before children. The :func:`cardinal_pythonlib.sqlalchemy.merge_db.merge_db` function does that properly. Args: startobj: SQLAlchemy ORM object to deep-copy session: see :func:`deepcopy_sqla_objects` flush: see :func:`deepcopy_sqla_objects` debug: see :func:`deepcopy_sqla_objects` debug_walk: see :func:`deepcopy_sqla_objects` debug_rewrite_rel: see :func:`deepcopy_sqla_objects` objmap: see :func:`deepcopy_sqla_objects` Returns: the copied object matching ``startobj`` """ if objmap is None: objmap = {} # keys = old objects, values = new objects deepcopy_sqla_objects( startobjs=[startobj], session=session, flush=flush, debug=debug, debug_walk=debug_walk, debug_rewrite_rel=debug_rewrite_rel, objmap=objmap ) return objmap[startobj]
python
def deepcopy_sqla_object(startobj: object, session: Session, flush: bool = True, debug: bool = False, debug_walk: bool = False, debug_rewrite_rel: bool = False, objmap: Dict[object, object] = None) -> object: """ Makes a copy of the object, inserting it into ``session``. Uses :func:`deepcopy_sqla_objects` (q.v.). A problem is the creation of duplicate dependency objects if you call it repeatedly. Optionally, if you pass the objmap in (which maps old to new objects), you can call this function repeatedly to clone a related set of objects... ... no, that doesn't really work, as it doesn't visit parents before children. The :func:`cardinal_pythonlib.sqlalchemy.merge_db.merge_db` function does that properly. Args: startobj: SQLAlchemy ORM object to deep-copy session: see :func:`deepcopy_sqla_objects` flush: see :func:`deepcopy_sqla_objects` debug: see :func:`deepcopy_sqla_objects` debug_walk: see :func:`deepcopy_sqla_objects` debug_rewrite_rel: see :func:`deepcopy_sqla_objects` objmap: see :func:`deepcopy_sqla_objects` Returns: the copied object matching ``startobj`` """ if objmap is None: objmap = {} # keys = old objects, values = new objects deepcopy_sqla_objects( startobjs=[startobj], session=session, flush=flush, debug=debug, debug_walk=debug_walk, debug_rewrite_rel=debug_rewrite_rel, objmap=objmap ) return objmap[startobj]
[ "def", "deepcopy_sqla_object", "(", "startobj", ":", "object", ",", "session", ":", "Session", ",", "flush", ":", "bool", "=", "True", ",", "debug", ":", "bool", "=", "False", ",", "debug_walk", ":", "bool", "=", "False", ",", "debug_rewrite_rel", ":", "...
Makes a copy of the object, inserting it into ``session``. Uses :func:`deepcopy_sqla_objects` (q.v.). A problem is the creation of duplicate dependency objects if you call it repeatedly. Optionally, if you pass the objmap in (which maps old to new objects), you can call this function repeatedly to clone a related set of objects... ... no, that doesn't really work, as it doesn't visit parents before children. The :func:`cardinal_pythonlib.sqlalchemy.merge_db.merge_db` function does that properly. Args: startobj: SQLAlchemy ORM object to deep-copy session: see :func:`deepcopy_sqla_objects` flush: see :func:`deepcopy_sqla_objects` debug: see :func:`deepcopy_sqla_objects` debug_walk: see :func:`deepcopy_sqla_objects` debug_rewrite_rel: see :func:`deepcopy_sqla_objects` objmap: see :func:`deepcopy_sqla_objects` Returns: the copied object matching ``startobj``
[ "Makes", "a", "copy", "of", "the", "object", "inserting", "it", "into", "session", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L471-L516
train
53,166
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
attrname_to_colname_dict
def attrname_to_colname_dict(cls) -> Dict[str, str]: """ Asks an SQLAlchemy class how its attribute names correspond to database column names. Args: cls: SQLAlchemy ORM class Returns: a dictionary mapping attribute names to database column names """ attr_col = {} # type: Dict[str, str] for attrname, column in gen_columns(cls): attr_col[attrname] = column.name return attr_col
python
def attrname_to_colname_dict(cls) -> Dict[str, str]: """ Asks an SQLAlchemy class how its attribute names correspond to database column names. Args: cls: SQLAlchemy ORM class Returns: a dictionary mapping attribute names to database column names """ attr_col = {} # type: Dict[str, str] for attrname, column in gen_columns(cls): attr_col[attrname] = column.name return attr_col
[ "def", "attrname_to_colname_dict", "(", "cls", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "attr_col", "=", "{", "}", "# type: Dict[str, str]", "for", "attrname", ",", "column", "in", "gen_columns", "(", "cls", ")", ":", "attr_col", "[", "attrname...
Asks an SQLAlchemy class how its attribute names correspond to database column names. Args: cls: SQLAlchemy ORM class Returns: a dictionary mapping attribute names to database column names
[ "Asks", "an", "SQLAlchemy", "class", "how", "its", "attribute", "names", "correspond", "to", "database", "column", "names", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L603-L617
train
53,167
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
get_orm_classes_by_table_name_from_base
def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]: """ Given an SQLAlchemy ORM base class, returns a dictionary whose keys are table names and whose values are ORM classes. If you begin with the proper :class`Base` class, then this should give all tables and ORM classes in use. """ # noinspection PyUnresolvedReferences return {cls.__tablename__: cls for cls in gen_orm_classes_from_base(base)}
python
def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]: """ Given an SQLAlchemy ORM base class, returns a dictionary whose keys are table names and whose values are ORM classes. If you begin with the proper :class`Base` class, then this should give all tables and ORM classes in use. """ # noinspection PyUnresolvedReferences return {cls.__tablename__: cls for cls in gen_orm_classes_from_base(base)}
[ "def", "get_orm_classes_by_table_name_from_base", "(", "base", ":", "Type", ")", "->", "Dict", "[", "str", ",", "Type", "]", ":", "# noinspection PyUnresolvedReferences", "return", "{", "cls", ".", "__tablename__", ":", "cls", "for", "cls", "in", "gen_orm_classes_...
Given an SQLAlchemy ORM base class, returns a dictionary whose keys are table names and whose values are ORM classes. If you begin with the proper :class`Base` class, then this should give all tables and ORM classes in use.
[ "Given", "an", "SQLAlchemy", "ORM", "base", "class", "returns", "a", "dictionary", "whose", "keys", "are", "table", "names", "and", "whose", "values", "are", "ORM", "classes", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L713-L722
train
53,168
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
SqlAlchemyAttrDictMixin.get_attrdict
def get_attrdict(self) -> OrderedNamespace: """ Returns what looks like a plain object with the values of the SQLAlchemy ORM object. """ # noinspection PyUnresolvedReferences columns = self.__table__.columns.keys() values = (getattr(self, x) for x in columns) zipped = zip(columns, values) return OrderedNamespace(zipped)
python
def get_attrdict(self) -> OrderedNamespace: """ Returns what looks like a plain object with the values of the SQLAlchemy ORM object. """ # noinspection PyUnresolvedReferences columns = self.__table__.columns.keys() values = (getattr(self, x) for x in columns) zipped = zip(columns, values) return OrderedNamespace(zipped)
[ "def", "get_attrdict", "(", "self", ")", "->", "OrderedNamespace", ":", "# noinspection PyUnresolvedReferences", "columns", "=", "self", ".", "__table__", ".", "columns", ".", "keys", "(", ")", "values", "=", "(", "getattr", "(", "self", ",", "x", ")", "for"...
Returns what looks like a plain object with the values of the SQLAlchemy ORM object.
[ "Returns", "what", "looks", "like", "a", "plain", "object", "with", "the", "values", "of", "the", "SQLAlchemy", "ORM", "object", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L108-L117
train
53,169
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/orm_inspect.py
SqlAlchemyAttrDictMixin.from_attrdict
def from_attrdict(cls, attrdict: OrderedNamespace) -> object: """ Builds a new instance of the ORM object from values in an attrdict. """ dictionary = attrdict.__dict__ # noinspection PyArgumentList return cls(**dictionary)
python
def from_attrdict(cls, attrdict: OrderedNamespace) -> object: """ Builds a new instance of the ORM object from values in an attrdict. """ dictionary = attrdict.__dict__ # noinspection PyArgumentList return cls(**dictionary)
[ "def", "from_attrdict", "(", "cls", ",", "attrdict", ":", "OrderedNamespace", ")", "->", "object", ":", "dictionary", "=", "attrdict", ".", "__dict__", "# noinspection PyArgumentList", "return", "cls", "(", "*", "*", "dictionary", ")" ]
Builds a new instance of the ORM object from values in an attrdict.
[ "Builds", "a", "new", "instance", "of", "the", "ORM", "object", "from", "values", "in", "an", "attrdict", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L127-L133
train
53,170
RudolfCardinal/pythonlib
cardinal_pythonlib/classes.py
gen_all_subclasses
def gen_all_subclasses(cls: Type) -> Generator[Type, None, None]: """ Generates all subclasses of a class. Args: cls: a class Yields: all subclasses """ for s1 in cls.__subclasses__(): yield s1 for s2 in gen_all_subclasses(s1): yield s2
python
def gen_all_subclasses(cls: Type) -> Generator[Type, None, None]: """ Generates all subclasses of a class. Args: cls: a class Yields: all subclasses """ for s1 in cls.__subclasses__(): yield s1 for s2 in gen_all_subclasses(s1): yield s2
[ "def", "gen_all_subclasses", "(", "cls", ":", "Type", ")", "->", "Generator", "[", "Type", ",", "None", ",", "None", "]", ":", "for", "s1", "in", "cls", ".", "__subclasses__", "(", ")", ":", "yield", "s1", "for", "s2", "in", "gen_all_subclasses", "(", ...
Generates all subclasses of a class. Args: cls: a class Yields: all subclasses
[ "Generates", "all", "subclasses", "of", "a", "class", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/classes.py#L110-L125
train
53,171
davenquinn/Attitude
attitude/geom/util.py
augment_tensor
def augment_tensor(matrix, ndim=None): """ Increase the dimensionality of a tensor, splicing it into an identity matrix of a higher dimension. Useful for generalizing transformation matrices. """ s = matrix.shape if ndim is None: ndim = s[0]+1 arr = N.identity(ndim) arr[:s[0],:s[1]] = matrix return arr
python
def augment_tensor(matrix, ndim=None): """ Increase the dimensionality of a tensor, splicing it into an identity matrix of a higher dimension. Useful for generalizing transformation matrices. """ s = matrix.shape if ndim is None: ndim = s[0]+1 arr = N.identity(ndim) arr[:s[0],:s[1]] = matrix return arr
[ "def", "augment_tensor", "(", "matrix", ",", "ndim", "=", "None", ")", ":", "s", "=", "matrix", ".", "shape", "if", "ndim", "is", "None", ":", "ndim", "=", "s", "[", "0", "]", "+", "1", "arr", "=", "N", ".", "identity", "(", "ndim", ")", "arr",...
Increase the dimensionality of a tensor, splicing it into an identity matrix of a higher dimension. Useful for generalizing transformation matrices.
[ "Increase", "the", "dimensionality", "of", "a", "tensor", "splicing", "it", "into", "an", "identity", "matrix", "of", "a", "higher", "dimension", ".", "Useful", "for", "generalizing", "transformation", "matrices", "." ]
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/util.py#L9-L21
train
53,172
davenquinn/Attitude
attitude/geom/util.py
angle
def angle(v1,v2, cos=False): """ Find the angle between two vectors. :param cos: If True, the cosine of the angle will be returned. False by default. """ n = (norm(v1)*norm(v2)) _ = dot(v1,v2)/n return _ if cos else N.arccos(_)
python
def angle(v1,v2, cos=False): """ Find the angle between two vectors. :param cos: If True, the cosine of the angle will be returned. False by default. """ n = (norm(v1)*norm(v2)) _ = dot(v1,v2)/n return _ if cos else N.arccos(_)
[ "def", "angle", "(", "v1", ",", "v2", ",", "cos", "=", "False", ")", ":", "n", "=", "(", "norm", "(", "v1", ")", "*", "norm", "(", "v2", ")", ")", "_", "=", "dot", "(", "v1", ",", "v2", ")", "/", "n", "return", "_", "if", "cos", "else", ...
Find the angle between two vectors. :param cos: If True, the cosine of the angle will be returned. False by default.
[ "Find", "the", "angle", "between", "two", "vectors", "." ]
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/util.py#L55-L64
train
53,173
davenquinn/Attitude
attitude/geom/util.py
perpendicular_vector
def perpendicular_vector(n): """ Get a random vector perpendicular to the given vector """ dim = len(n) if dim == 2: return n[::-1] # More complex in 3d for ix in range(dim): _ = N.zeros(dim) # Try to keep axes near the global projection # by finding vectors perpendicular to higher- # index axes first. This may or may not be worth # doing. _[dim-ix-1] = 1 v1 = N.cross(n,_) if N.linalg.norm(v1) != 0: return v1 raise ValueError("Cannot find perpendicular vector")
python
def perpendicular_vector(n): """ Get a random vector perpendicular to the given vector """ dim = len(n) if dim == 2: return n[::-1] # More complex in 3d for ix in range(dim): _ = N.zeros(dim) # Try to keep axes near the global projection # by finding vectors perpendicular to higher- # index axes first. This may or may not be worth # doing. _[dim-ix-1] = 1 v1 = N.cross(n,_) if N.linalg.norm(v1) != 0: return v1 raise ValueError("Cannot find perpendicular vector")
[ "def", "perpendicular_vector", "(", "n", ")", ":", "dim", "=", "len", "(", "n", ")", "if", "dim", "==", "2", ":", "return", "n", "[", ":", ":", "-", "1", "]", "# More complex in 3d", "for", "ix", "in", "range", "(", "dim", ")", ":", "_", "=", "...
Get a random vector perpendicular to the given vector
[ "Get", "a", "random", "vector", "perpendicular", "to", "the", "given", "vector" ]
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/util.py#L91-L110
train
53,174
RudolfCardinal/pythonlib
cardinal_pythonlib/openxml/find_bad_openxml.py
process_openxml_file
def process_openxml_file(filename: str, print_good: bool, delete_if_bad: bool) -> None: """ Prints the filename of, or deletes, an OpenXML file depending on whether it is corrupt or not. Args: filename: filename to check print_good: if ``True``, then prints the filename if the file appears good. delete_if_bad: if ``True``, then deletes the file if the file appears corrupt. """ print_bad = not print_good try: file_good = is_openxml_good(filename) file_bad = not file_good if (print_good and file_good) or (print_bad and file_bad): print(filename) if delete_if_bad and file_bad: log.warning("Deleting: {}", filename) os.remove(filename) except Exception as e: # Must explicitly catch and report errors, since otherwise they vanish # into the ether. log.critical("Uncaught error in subprocess: {!r}\n{}", e, traceback.format_exc()) raise
python
def process_openxml_file(filename: str, print_good: bool, delete_if_bad: bool) -> None: """ Prints the filename of, or deletes, an OpenXML file depending on whether it is corrupt or not. Args: filename: filename to check print_good: if ``True``, then prints the filename if the file appears good. delete_if_bad: if ``True``, then deletes the file if the file appears corrupt. """ print_bad = not print_good try: file_good = is_openxml_good(filename) file_bad = not file_good if (print_good and file_good) or (print_bad and file_bad): print(filename) if delete_if_bad and file_bad: log.warning("Deleting: {}", filename) os.remove(filename) except Exception as e: # Must explicitly catch and report errors, since otherwise they vanish # into the ether. log.critical("Uncaught error in subprocess: {!r}\n{}", e, traceback.format_exc()) raise
[ "def", "process_openxml_file", "(", "filename", ":", "str", ",", "print_good", ":", "bool", ",", "delete_if_bad", ":", "bool", ")", "->", "None", ":", "print_bad", "=", "not", "print_good", "try", ":", "file_good", "=", "is_openxml_good", "(", "filename", ")...
Prints the filename of, or deletes, an OpenXML file depending on whether it is corrupt or not. Args: filename: filename to check print_good: if ``True``, then prints the filename if the file appears good. delete_if_bad: if ``True``, then deletes the file if the file appears corrupt.
[ "Prints", "the", "filename", "of", "or", "deletes", "an", "OpenXML", "file", "depending", "on", "whether", "it", "is", "corrupt", "or", "not", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/find_bad_openxml.py#L142-L170
train
53,175
davenquinn/Attitude
attitude/__dustbin/statistical_distances.py
bhattacharyya_distance
def bhattacharyya_distance(pca1,pca2): """ A measure of the distance between two probability distributions """ u1 = pca1.coefficients s1 = pca1.covariance_matrix u2 = pca2.coefficients s2 = pca2.covariance_matrix sigma = (s1+s2)/2 assert all(u1 > 0) assert all(u2 > 0) assert all(s1.sum(axis=1) > 0) assert all(s2.sum(axis=1) > 0) _ = 1/8*dot((u1-u2).T, N.linalg.inv(sigma),u1-u2) _ += 1/2*N.log(N.linalg.det(sigma)/(N.linalg.det(s1)*N.linalg.det(s2))) return _
python
def bhattacharyya_distance(pca1,pca2): """ A measure of the distance between two probability distributions """ u1 = pca1.coefficients s1 = pca1.covariance_matrix u2 = pca2.coefficients s2 = pca2.covariance_matrix sigma = (s1+s2)/2 assert all(u1 > 0) assert all(u2 > 0) assert all(s1.sum(axis=1) > 0) assert all(s2.sum(axis=1) > 0) _ = 1/8*dot((u1-u2).T, N.linalg.inv(sigma),u1-u2) _ += 1/2*N.log(N.linalg.det(sigma)/(N.linalg.det(s1)*N.linalg.det(s2))) return _
[ "def", "bhattacharyya_distance", "(", "pca1", ",", "pca2", ")", ":", "u1", "=", "pca1", ".", "coefficients", "s1", "=", "pca1", ".", "covariance_matrix", "u2", "=", "pca2", ".", "coefficients", "s2", "=", "pca2", ".", "covariance_matrix", "sigma", "=", "("...
A measure of the distance between two probability distributions
[ "A", "measure", "of", "the", "distance", "between", "two", "probability", "distributions" ]
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/__dustbin/statistical_distances.py#L13-L31
train
53,176
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
produce_csv_output
def produce_csv_output(filehandle: TextIO, fields: Sequence[str], values: Iterable[str]) -> None: """ Produce CSV output, without using ``csv.writer``, so the log can be used for lots of things. - ... eh? What was I talking about? - POOR; DEPRECATED. Args: filehandle: file to write to fields: field names values: values """ output_csv(filehandle, fields) for row in values: output_csv(filehandle, row)
python
def produce_csv_output(filehandle: TextIO, fields: Sequence[str], values: Iterable[str]) -> None: """ Produce CSV output, without using ``csv.writer``, so the log can be used for lots of things. - ... eh? What was I talking about? - POOR; DEPRECATED. Args: filehandle: file to write to fields: field names values: values """ output_csv(filehandle, fields) for row in values: output_csv(filehandle, row)
[ "def", "produce_csv_output", "(", "filehandle", ":", "TextIO", ",", "fields", ":", "Sequence", "[", "str", "]", ",", "values", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "output_csv", "(", "filehandle", ",", "fields", ")", "for", "row", ...
Produce CSV output, without using ``csv.writer``, so the log can be used for lots of things. - ... eh? What was I talking about? - POOR; DEPRECATED. Args: filehandle: file to write to fields: field names values: values
[ "Produce", "CSV", "output", "without", "using", "csv", ".", "writer", "so", "the", "log", "can", "be", "used", "for", "lots", "of", "things", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L39-L56
train
53,177
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
output_csv
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None: """ Write a line of CSV. POOR; does not escape things properly. DEPRECATED. Args: filehandle: file to write to values: values """ line = ",".join(values) filehandle.write(line + "\n")
python
def output_csv(filehandle: TextIO, values: Iterable[str]) -> None: """ Write a line of CSV. POOR; does not escape things properly. DEPRECATED. Args: filehandle: file to write to values: values """ line = ",".join(values) filehandle.write(line + "\n")
[ "def", "output_csv", "(", "filehandle", ":", "TextIO", ",", "values", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "line", "=", "\",\"", ".", "join", "(", "values", ")", "filehandle", ".", "write", "(", "line", "+", "\"\\n\"", ")" ]
Write a line of CSV. POOR; does not escape things properly. DEPRECATED. Args: filehandle: file to write to values: values
[ "Write", "a", "line", "of", "CSV", ".", "POOR", ";", "does", "not", "escape", "things", "properly", ".", "DEPRECATED", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L59-L68
train
53,178
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_what_follows_raw
def get_what_follows_raw(s: str, prefix: str, onlyatstart: bool = True, stripwhitespace: bool = True) -> Tuple[bool, str]: """ Find the part of ``s`` that is after ``prefix``. Args: s: string to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result Returns: tuple: ``(found, result)`` """ prefixstart = s.find(prefix) if ((prefixstart == 0 and onlyatstart) or (prefixstart != -1 and not onlyatstart)): # substring found resultstart = prefixstart + len(prefix) result = s[resultstart:] if stripwhitespace: result = result.strip() return True, result return False, ""
python
def get_what_follows_raw(s: str, prefix: str, onlyatstart: bool = True, stripwhitespace: bool = True) -> Tuple[bool, str]: """ Find the part of ``s`` that is after ``prefix``. Args: s: string to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result Returns: tuple: ``(found, result)`` """ prefixstart = s.find(prefix) if ((prefixstart == 0 and onlyatstart) or (prefixstart != -1 and not onlyatstart)): # substring found resultstart = prefixstart + len(prefix) result = s[resultstart:] if stripwhitespace: result = result.strip() return True, result return False, ""
[ "def", "get_what_follows_raw", "(", "s", ":", "str", ",", "prefix", ":", "str", ",", "onlyatstart", ":", "bool", "=", "True", ",", "stripwhitespace", ":", "bool", "=", "True", ")", "->", "Tuple", "[", "bool", ",", "str", "]", ":", "prefixstart", "=", ...
Find the part of ``s`` that is after ``prefix``. Args: s: string to analyse prefix: prefix to find onlyatstart: only accept the prefix if it is right at the start of ``s`` stripwhitespace: remove whitespace from the result Returns: tuple: ``(found, result)``
[ "Find", "the", "part", "of", "s", "that", "is", "after", "prefix", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L71-L98
train
53,179
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
get_bool_raw
def get_bool_raw(s: str) -> Optional[bool]: """ Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``. """ if s == "Y" or s == "y": return True elif s == "N" or s == "n": return False return None
python
def get_bool_raw(s: str) -> Optional[bool]: """ Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``. """ if s == "Y" or s == "y": return True elif s == "N" or s == "n": return False return None
[ "def", "get_bool_raw", "(", "s", ":", "str", ")", "->", "Optional", "[", "bool", "]", ":", "if", "s", "==", "\"Y\"", "or", "s", "==", "\"y\"", ":", "return", "True", "elif", "s", "==", "\"N\"", "or", "s", "==", "\"n\"", ":", "return", "False", "r...
Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``.
[ "Maps", "Y", "y", "to", "True", "and", "N", "n", "to", "False", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L258-L266
train
53,180
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
find_line_beginning
def find_line_beginning(strings: Sequence[str], linestart: Optional[str]) -> int: """ Finds the index of the line in ``strings`` that begins with ``linestart``, or ``-1`` if none is found. If ``linestart is None``, match an empty line. """ if linestart is None: # match an empty line for i in range(len(strings)): if is_empty_string(strings[i]): return i return -1 for i in range(len(strings)): if strings[i].find(linestart) == 0: return i return -1
python
def find_line_beginning(strings: Sequence[str], linestart: Optional[str]) -> int: """ Finds the index of the line in ``strings`` that begins with ``linestart``, or ``-1`` if none is found. If ``linestart is None``, match an empty line. """ if linestart is None: # match an empty line for i in range(len(strings)): if is_empty_string(strings[i]): return i return -1 for i in range(len(strings)): if strings[i].find(linestart) == 0: return i return -1
[ "def", "find_line_beginning", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "linestart", ":", "Optional", "[", "str", "]", ")", "->", "int", ":", "if", "linestart", "is", "None", ":", "# match an empty line", "for", "i", "in", "range", "(", "len...
Finds the index of the line in ``strings`` that begins with ``linestart``, or ``-1`` if none is found. If ``linestart is None``, match an empty line.
[ "Finds", "the", "index", "of", "the", "line", "in", "strings", "that", "begins", "with", "linestart", "or", "-", "1", "if", "none", "is", "found", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L358-L374
train
53,181
RudolfCardinal/pythonlib
cardinal_pythonlib/rnc_text.py
find_line_containing
def find_line_containing(strings: Sequence[str], contents: str) -> int: """ Finds the index of the line in ``strings`` that contains ``contents``, or ``-1`` if none is found. """ for i in range(len(strings)): if strings[i].find(contents) != -1: return i return -1
python
def find_line_containing(strings: Sequence[str], contents: str) -> int: """ Finds the index of the line in ``strings`` that contains ``contents``, or ``-1`` if none is found. """ for i in range(len(strings)): if strings[i].find(contents) != -1: return i return -1
[ "def", "find_line_containing", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "contents", ":", "str", ")", "->", "int", ":", "for", "i", "in", "range", "(", "len", "(", "strings", ")", ")", ":", "if", "strings", "[", "i", "]", ".", "find", ...
Finds the index of the line in ``strings`` that contains ``contents``, or ``-1`` if none is found.
[ "Finds", "the", "index", "of", "the", "line", "in", "strings", "that", "contains", "contents", "or", "-", "1", "if", "none", "is", "found", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L377-L385
train
53,182
RudolfCardinal/pythonlib
cardinal_pythonlib/django/function_cache.py
django_cache_function
def django_cache_function(timeout: int = 5 * 60, cache_key: str = '', debug_cache: bool = False): """ Decorator to add caching to a function in Django. Uses the Django default cache. Args: timeout: timeout in seconds; use None for "never expire", as 0 means "do not cache". cache_key: optional cache key to use (if falsy, we'll invent one) debug_cache: show hits/misses? """ cache_key = cache_key or None def decorator(fn): def wrapper(*args, **kwargs): # - NOTE that Django returns None from cache.get() for "not in # cache", so can't cache a None value; # https://docs.djangoproject.com/en/1.10/topics/cache/#basic-usage # noqa # - We need to store a bit more than just the function result # anyway, to detect hash collisions when the user doesn't specify # the cache_key, so we may as well use that format even if the # user does specify the cache_key, and then we can store a None # result properly as well. if cache_key: # User specified a cache key. This is easy. call_sig = '' _cache_key = cache_key check_stored_call_sig = False else: # User didn't specify a cache key, so we'll do one # automatically. Since we do this via a hash, there is a small # but non-zero chance of a hash collision. call_sig = get_call_signature(fn, args, kwargs) _cache_key = make_cache_key(call_sig) check_stored_call_sig = True if debug_cache: log.critical("Checking cache for key: " + _cache_key) cache_result_tuple = cache.get(_cache_key) # TALKS TO CACHE HERE if cache_result_tuple is None: if debug_cache: log.debug("Cache miss") else: if debug_cache: log.debug("Cache hit") cached_call_sig, func_result = cache_result_tuple if (not check_stored_call_sig) or cached_call_sig == call_sig: return func_result log.warning( "... Cache hit was due to hash collision; cached_call_sig " "{} != call_sig {}".format( repr(cached_call_sig), repr(call_sig))) # If we get here, either it wasn't in the cache, or something # was in the cache that matched by cache_key but was actually a # hash collision. Either way, we must do the real work. func_result = fn(*args, **kwargs) cache_result_tuple = (call_sig, func_result) cache.set(key=_cache_key, value=cache_result_tuple, timeout=timeout) # TALKS TO CACHE HERE return func_result return wrapper return decorator
python
def django_cache_function(timeout: int = 5 * 60, cache_key: str = '', debug_cache: bool = False): """ Decorator to add caching to a function in Django. Uses the Django default cache. Args: timeout: timeout in seconds; use None for "never expire", as 0 means "do not cache". cache_key: optional cache key to use (if falsy, we'll invent one) debug_cache: show hits/misses? """ cache_key = cache_key or None def decorator(fn): def wrapper(*args, **kwargs): # - NOTE that Django returns None from cache.get() for "not in # cache", so can't cache a None value; # https://docs.djangoproject.com/en/1.10/topics/cache/#basic-usage # noqa # - We need to store a bit more than just the function result # anyway, to detect hash collisions when the user doesn't specify # the cache_key, so we may as well use that format even if the # user does specify the cache_key, and then we can store a None # result properly as well. if cache_key: # User specified a cache key. This is easy. call_sig = '' _cache_key = cache_key check_stored_call_sig = False else: # User didn't specify a cache key, so we'll do one # automatically. Since we do this via a hash, there is a small # but non-zero chance of a hash collision. call_sig = get_call_signature(fn, args, kwargs) _cache_key = make_cache_key(call_sig) check_stored_call_sig = True if debug_cache: log.critical("Checking cache for key: " + _cache_key) cache_result_tuple = cache.get(_cache_key) # TALKS TO CACHE HERE if cache_result_tuple is None: if debug_cache: log.debug("Cache miss") else: if debug_cache: log.debug("Cache hit") cached_call_sig, func_result = cache_result_tuple if (not check_stored_call_sig) or cached_call_sig == call_sig: return func_result log.warning( "... Cache hit was due to hash collision; cached_call_sig " "{} != call_sig {}".format( repr(cached_call_sig), repr(call_sig))) # If we get here, either it wasn't in the cache, or something # was in the cache that matched by cache_key but was actually a # hash collision. Either way, we must do the real work. func_result = fn(*args, **kwargs) cache_result_tuple = (call_sig, func_result) cache.set(key=_cache_key, value=cache_result_tuple, timeout=timeout) # TALKS TO CACHE HERE return func_result return wrapper return decorator
[ "def", "django_cache_function", "(", "timeout", ":", "int", "=", "5", "*", "60", ",", "cache_key", ":", "str", "=", "''", ",", "debug_cache", ":", "bool", "=", "False", ")", ":", "cache_key", "=", "cache_key", "or", "None", "def", "decorator", "(", "fn...
Decorator to add caching to a function in Django. Uses the Django default cache. Args: timeout: timeout in seconds; use None for "never expire", as 0 means "do not cache". cache_key: optional cache key to use (if falsy, we'll invent one) debug_cache: show hits/misses?
[ "Decorator", "to", "add", "caching", "to", "a", "function", "in", "Django", ".", "Uses", "the", "Django", "default", "cache", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/function_cache.py#L113-L179
train
53,183
davenquinn/Attitude
attitude/coordinates/rotations.py
transform
def transform(v1, v2): """ Create an affine transformation matrix that maps vector 1 onto vector 2 https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another """ theta = angle(v1,v2) x = N.cross(v1,v2) x = x / N.linalg.norm(x) A = N.array([ [0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]]) R = N.exp(A*theta) return R
python
def transform(v1, v2): """ Create an affine transformation matrix that maps vector 1 onto vector 2 https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another """ theta = angle(v1,v2) x = N.cross(v1,v2) x = x / N.linalg.norm(x) A = N.array([ [0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]]) R = N.exp(A*theta) return R
[ "def", "transform", "(", "v1", ",", "v2", ")", ":", "theta", "=", "angle", "(", "v1", ",", "v2", ")", "x", "=", "N", ".", "cross", "(", "v1", ",", "v2", ")", "x", "=", "x", "/", "N", ".", "linalg", ".", "norm", "(", "x", ")", "A", "=", ...
Create an affine transformation matrix that maps vector 1 onto vector 2 https://math.stackexchange.com/questions/293116/rotating-one-3d-vector-to-another
[ "Create", "an", "affine", "transformation", "matrix", "that", "maps", "vector", "1", "onto", "vector", "2" ]
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/coordinates/rotations.py#L11-L28
train
53,184
ivanprjcts/sdklib
sdklib/http/authorization.py
x_11paths_authorization
def x_11paths_authorization(app_id, secret, context, utc=None): """ Calculate the authentication headers to be sent with a request to the API. :param app_id: :param secret: :param context :param utc: :return: array a map with the Authorization and Date headers needed to sign a Latch API request """ utc = utc or context.headers[X_11PATHS_DATE_HEADER_NAME] url_path = ensure_url_path_starts_with_slash(context.url_path) url_path_query = url_path if context.query_params: url_path_query += "?%s" % (url_encode(context.query_params, sort=True)) string_to_sign = (context.method.upper().strip() + "\n" + utc + "\n" + _get_11paths_serialized_headers(context.headers) + "\n" + url_path_query.strip()) if context.body_params and isinstance(context.renderer, FormRenderer): string_to_sign = string_to_sign + "\n" + url_encode(context.body_params, sort=True).replace("&", "") authorization_header_value = (AUTHORIZATION_METHOD + AUTHORIZATION_HEADER_FIELD_SEPARATOR + app_id + AUTHORIZATION_HEADER_FIELD_SEPARATOR + _sign_data(secret, string_to_sign)) return authorization_header_value
python
def x_11paths_authorization(app_id, secret, context, utc=None): """ Calculate the authentication headers to be sent with a request to the API. :param app_id: :param secret: :param context :param utc: :return: array a map with the Authorization and Date headers needed to sign a Latch API request """ utc = utc or context.headers[X_11PATHS_DATE_HEADER_NAME] url_path = ensure_url_path_starts_with_slash(context.url_path) url_path_query = url_path if context.query_params: url_path_query += "?%s" % (url_encode(context.query_params, sort=True)) string_to_sign = (context.method.upper().strip() + "\n" + utc + "\n" + _get_11paths_serialized_headers(context.headers) + "\n" + url_path_query.strip()) if context.body_params and isinstance(context.renderer, FormRenderer): string_to_sign = string_to_sign + "\n" + url_encode(context.body_params, sort=True).replace("&", "") authorization_header_value = (AUTHORIZATION_METHOD + AUTHORIZATION_HEADER_FIELD_SEPARATOR + app_id + AUTHORIZATION_HEADER_FIELD_SEPARATOR + _sign_data(secret, string_to_sign)) return authorization_header_value
[ "def", "x_11paths_authorization", "(", "app_id", ",", "secret", ",", "context", ",", "utc", "=", "None", ")", ":", "utc", "=", "utc", "or", "context", ".", "headers", "[", "X_11PATHS_DATE_HEADER_NAME", "]", "url_path", "=", "ensure_url_path_starts_with_slash", "...
Calculate the authentication headers to be sent with a request to the API. :param app_id: :param secret: :param context :param utc: :return: array a map with the Authorization and Date headers needed to sign a Latch API request
[ "Calculate", "the", "authentication", "headers", "to", "be", "sent", "with", "a", "request", "to", "the", "API", "." ]
7ba4273a05c40e2e338f49f2dd564920ed98fcab
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/authorization.py#L35-L63
train
53,185
ivanprjcts/sdklib
sdklib/http/authorization.py
_sign_data
def _sign_data(secret, data): """ Sign data. :param data: the string to sign :return: string base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key. """ sha1_hash = hmac.new(secret.encode(), data.encode(), sha1) return binascii.b2a_base64(sha1_hash.digest())[:-1].decode('utf8')
python
def _sign_data(secret, data): """ Sign data. :param data: the string to sign :return: string base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key. """ sha1_hash = hmac.new(secret.encode(), data.encode(), sha1) return binascii.b2a_base64(sha1_hash.digest())[:-1].decode('utf8')
[ "def", "_sign_data", "(", "secret", ",", "data", ")", ":", "sha1_hash", "=", "hmac", ".", "new", "(", "secret", ".", "encode", "(", ")", ",", "data", ".", "encode", "(", ")", ",", "sha1", ")", "return", "binascii", ".", "b2a_base64", "(", "sha1_hash"...
Sign data. :param data: the string to sign :return: string base64 encoding of the HMAC-SHA1 hash of the data parameter using {@code secretKey} as cipher key.
[ "Sign", "data", "." ]
7ba4273a05c40e2e338f49f2dd564920ed98fcab
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/authorization.py#L66-L74
train
53,186
ivanprjcts/sdklib
sdklib/http/authorization.py
_get_11paths_serialized_headers
def _get_11paths_serialized_headers(x_headers): """ Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received. :param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered. :return: string The serialized headers, an empty string if no headers are passed, or None if there's a problem such as non 11paths specific headers """ if x_headers: headers = to_key_val_list(x_headers, sort=True, insensitive=True) serialized_headers = "" for key, value in headers: if key.lower().startswith(X_11PATHS_HEADER_PREFIX.lower()) and \ key.lower() != X_11PATHS_DATE_HEADER_NAME.lower(): serialized_headers += key.lower() + X_11PATHS_HEADER_SEPARATOR + value.replace("\n", " ") + " " return serialized_headers.strip() else: return ""
python
def _get_11paths_serialized_headers(x_headers): """ Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received. :param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered. :return: string The serialized headers, an empty string if no headers are passed, or None if there's a problem such as non 11paths specific headers """ if x_headers: headers = to_key_val_list(x_headers, sort=True, insensitive=True) serialized_headers = "" for key, value in headers: if key.lower().startswith(X_11PATHS_HEADER_PREFIX.lower()) and \ key.lower() != X_11PATHS_DATE_HEADER_NAME.lower(): serialized_headers += key.lower() + X_11PATHS_HEADER_SEPARATOR + value.replace("\n", " ") + " " return serialized_headers.strip() else: return ""
[ "def", "_get_11paths_serialized_headers", "(", "x_headers", ")", ":", "if", "x_headers", ":", "headers", "=", "to_key_val_list", "(", "x_headers", ",", "sort", "=", "True", ",", "insensitive", "=", "True", ")", "serialized_headers", "=", "\"\"", "for", "key", ...
Prepares and returns a string ready to be signed from the 11-paths specific HTTP headers received. :param x_headers: a non necessarily ordered map (array without duplicates) of the HTTP headers to be ordered. :return: string The serialized headers, an empty string if no headers are passed, or None if there's a problem such as non 11paths specific headers
[ "Prepares", "and", "returns", "a", "string", "ready", "to", "be", "signed", "from", "the", "11", "-", "paths", "specific", "HTTP", "headers", "received", "." ]
7ba4273a05c40e2e338f49f2dd564920ed98fcab
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/authorization.py#L96-L113
train
53,187
davenquinn/Attitude
attitude/geom/transform.py
rotate_2D
def rotate_2D(angle): """ Returns a 2x2 transformation matrix to rotate by an angle in two dimensions """ return N.array([[N.cos(angle),-N.sin(angle)], [N.sin(angle),N.cos(angle)]])
python
def rotate_2D(angle): """ Returns a 2x2 transformation matrix to rotate by an angle in two dimensions """ return N.array([[N.cos(angle),-N.sin(angle)], [N.sin(angle),N.cos(angle)]])
[ "def", "rotate_2D", "(", "angle", ")", ":", "return", "N", ".", "array", "(", "[", "[", "N", ".", "cos", "(", "angle", ")", ",", "-", "N", ".", "sin", "(", "angle", ")", "]", ",", "[", "N", ".", "sin", "(", "angle", ")", ",", "N", ".", "c...
Returns a 2x2 transformation matrix to rotate by an angle in two dimensions
[ "Returns", "a", "2x2", "transformation", "matrix", "to", "rotate", "by", "an", "angle", "in", "two", "dimensions" ]
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/transform.py#L3-L9
train
53,188
davenquinn/Attitude
attitude/display/hyperbola.py
apparent_dip_correction
def apparent_dip_correction(axes): """ Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip """ a1 = axes[0].copy() a1[-1] = 0 cosa = angle(axes[0],a1,cos=True) _ = 1-cosa**2 if _ > 1e-12: sina = N.sqrt(_) if cosa < 0: sina *= -1 # Construct rotation matrix R= N.array([[cosa,sina],[-sina,cosa]]) else: # Small angle, don't bother # (small angles can lead to spurious results) R = N.identity(2) #if axes[0,0] < 0: # return R.T #else: return R
python
def apparent_dip_correction(axes): """ Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip """ a1 = axes[0].copy() a1[-1] = 0 cosa = angle(axes[0],a1,cos=True) _ = 1-cosa**2 if _ > 1e-12: sina = N.sqrt(_) if cosa < 0: sina *= -1 # Construct rotation matrix R= N.array([[cosa,sina],[-sina,cosa]]) else: # Small angle, don't bother # (small angles can lead to spurious results) R = N.identity(2) #if axes[0,0] < 0: # return R.T #else: return R
[ "def", "apparent_dip_correction", "(", "axes", ")", ":", "a1", "=", "axes", "[", "0", "]", ".", "copy", "(", ")", "a1", "[", "-", "1", "]", "=", "0", "cosa", "=", "angle", "(", "axes", "[", "0", "]", ",", "a1", ",", "cos", "=", "True", ")", ...
Produces a two-dimensional rotation matrix that rotates a projected dataset to correct for apparent dip
[ "Produces", "a", "two", "-", "dimensional", "rotation", "matrix", "that", "rotates", "a", "projected", "dataset", "to", "correct", "for", "apparent", "dip" ]
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/hyperbola.py#L9-L31
train
53,189
davenquinn/Attitude
attitude/display/hyperbola.py
hyperbolic_errors
def hyperbolic_errors(hyp_axes, xvals, transformation=None, axes=None, means=None, correct_apparent_dip=True, reverse=False): """ Returns a function that can be used to create a view of the hyperbolic error ellipse from a specific direction. This creates a hyperbolic quadric and slices it to form a conic on a 2d cartesian plane aligned with the requested direction. A function is returned that takes x values (distance along nominal line) and returns y values (width of error hyperbola) kwargs: transformation rotation to apply to quadric prior to slicing (e.g. transformation into 'world' coordinates axes axes on which to slice the data """ if means is None: means = N.array([0,0]) arr = augment_tensor(N.diag(hyp_axes)) # Transform ellipsoid to dual hyperboloid hyp = conic(arr).dual() if len(hyp_axes) == 3: # Three_dimensional case if transformation is None: transformation = N.identity(3) if axes is None: axes = N.array([[0,1,0],[0,0,1]]) hyp = hyp.transform(augment_tensor(transformation)) n_ = N.cross(axes[0],axes[1]) # Create a plane containing the two axes specified # in the function call p = plane(n_) # no offset (goes through origin) h1 = hyp.slice(p, axes=axes)[0] else: # We have a 2d geometry h1 = hyp # Major axes of the conic sliced in the requested viewing # geometry A = N.sqrt(h1.semiaxes()) yvals = A[1]*N.cosh(N.arcsinh(xvals/A[0])) vals = N.array([xvals,yvals]).transpose() nom = N.array([xvals,N.zeros(xvals.shape)]).transpose() # Rotate the whole result if the PCA axes aren't aligned to the # major axes of the view coordinate system ax1 = apparent_dip_correction(axes) # This is a dirty hack to flip things left to right if reverse: ax1 = ax1.T # Top t = dot(vals,ax1).T+means[:,N.newaxis] # Btm vals[:,-1] *= -1 b = dot(vals,ax1).T+means[:,N.newaxis] nom = dot(nom,ax1).T+means[:,N.newaxis] return nom, b, t[:,::-1]
python
def hyperbolic_errors(hyp_axes, xvals, transformation=None, axes=None, means=None, correct_apparent_dip=True, reverse=False): """ Returns a function that can be used to create a view of the hyperbolic error ellipse from a specific direction. This creates a hyperbolic quadric and slices it to form a conic on a 2d cartesian plane aligned with the requested direction. A function is returned that takes x values (distance along nominal line) and returns y values (width of error hyperbola) kwargs: transformation rotation to apply to quadric prior to slicing (e.g. transformation into 'world' coordinates axes axes on which to slice the data """ if means is None: means = N.array([0,0]) arr = augment_tensor(N.diag(hyp_axes)) # Transform ellipsoid to dual hyperboloid hyp = conic(arr).dual() if len(hyp_axes) == 3: # Three_dimensional case if transformation is None: transformation = N.identity(3) if axes is None: axes = N.array([[0,1,0],[0,0,1]]) hyp = hyp.transform(augment_tensor(transformation)) n_ = N.cross(axes[0],axes[1]) # Create a plane containing the two axes specified # in the function call p = plane(n_) # no offset (goes through origin) h1 = hyp.slice(p, axes=axes)[0] else: # We have a 2d geometry h1 = hyp # Major axes of the conic sliced in the requested viewing # geometry A = N.sqrt(h1.semiaxes()) yvals = A[1]*N.cosh(N.arcsinh(xvals/A[0])) vals = N.array([xvals,yvals]).transpose() nom = N.array([xvals,N.zeros(xvals.shape)]).transpose() # Rotate the whole result if the PCA axes aren't aligned to the # major axes of the view coordinate system ax1 = apparent_dip_correction(axes) # This is a dirty hack to flip things left to right if reverse: ax1 = ax1.T # Top t = dot(vals,ax1).T+means[:,N.newaxis] # Btm vals[:,-1] *= -1 b = dot(vals,ax1).T+means[:,N.newaxis] nom = dot(nom,ax1).T+means[:,N.newaxis] return nom, b, t[:,::-1]
[ "def", "hyperbolic_errors", "(", "hyp_axes", ",", "xvals", ",", "transformation", "=", "None", ",", "axes", "=", "None", ",", "means", "=", "None", ",", "correct_apparent_dip", "=", "True", ",", "reverse", "=", "False", ")", ":", "if", "means", "is", "No...
Returns a function that can be used to create a view of the hyperbolic error ellipse from a specific direction. This creates a hyperbolic quadric and slices it to form a conic on a 2d cartesian plane aligned with the requested direction. A function is returned that takes x values (distance along nominal line) and returns y values (width of error hyperbola) kwargs: transformation rotation to apply to quadric prior to slicing (e.g. transformation into 'world' coordinates axes axes on which to slice the data
[ "Returns", "a", "function", "that", "can", "be", "used", "to", "create", "a", "view", "of", "the", "hyperbolic", "error", "ellipse", "from", "a", "specific", "direction", "." ]
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/hyperbola.py#L33-L103
train
53,190
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/merge_db.py
TableDependency.set_metadata
def set_metadata(self, metadata: MetaData) -> None: """ Sets the metadata for the parent and child tables. """ self._parent.set_metadata(metadata) self._child.set_metadata(metadata)
python
def set_metadata(self, metadata: MetaData) -> None: """ Sets the metadata for the parent and child tables. """ self._parent.set_metadata(metadata) self._child.set_metadata(metadata)
[ "def", "set_metadata", "(", "self", ",", "metadata", ":", "MetaData", ")", "->", "None", ":", "self", ".", "_parent", ".", "set_metadata", "(", "metadata", ")", "self", ".", "_child", ".", "set_metadata", "(", "metadata", ")" ]
Sets the metadata for the parent and child tables.
[ "Sets", "the", "metadata", "for", "the", "parent", "and", "child", "tables", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/merge_db.py#L156-L161
train
53,191
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/merge_db.py
TableDependency.set_metadata_if_none
def set_metadata_if_none(self, metadata: MetaData) -> None: """ Sets the metadata for the parent and child tables, unless they were set already. """ self._parent.set_metadata_if_none(metadata) self._child.set_metadata_if_none(metadata)
python
def set_metadata_if_none(self, metadata: MetaData) -> None: """ Sets the metadata for the parent and child tables, unless they were set already. """ self._parent.set_metadata_if_none(metadata) self._child.set_metadata_if_none(metadata)
[ "def", "set_metadata_if_none", "(", "self", ",", "metadata", ":", "MetaData", ")", "->", "None", ":", "self", ".", "_parent", ".", "set_metadata_if_none", "(", "metadata", ")", "self", ".", "_child", ".", "set_metadata_if_none", "(", "metadata", ")" ]
Sets the metadata for the parent and child tables, unless they were set already.
[ "Sets", "the", "metadata", "for", "the", "parent", "and", "child", "tables", "unless", "they", "were", "set", "already", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/merge_db.py#L163-L169
train
53,192
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/merge_db.py
TableDependencyClassification.description
def description(self) -> str: """ Short description. """ if self.is_parent and self.is_child: desc = "parent+child" elif self.is_parent: desc = "parent" elif self.is_child: desc = "child" else: desc = "standalone" if self.circular: desc += "+CIRCULAR({})".format(self.circular_description) return desc
python
def description(self) -> str: """ Short description. """ if self.is_parent and self.is_child: desc = "parent+child" elif self.is_parent: desc = "parent" elif self.is_child: desc = "child" else: desc = "standalone" if self.circular: desc += "+CIRCULAR({})".format(self.circular_description) return desc
[ "def", "description", "(", "self", ")", "->", "str", ":", "if", "self", ".", "is_parent", "and", "self", ".", "is_child", ":", "desc", "=", "\"parent+child\"", "elif", "self", ".", "is_parent", ":", "desc", "=", "\"parent\"", "elif", "self", ".", "is_chi...
Short description.
[ "Short", "description", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/merge_db.py#L345-L359
train
53,193
davenquinn/Attitude
attitude/coordinates/__init__.py
spherical
def spherical(coordinates): """No error is propagated""" c = coordinates r = N.linalg.norm(c,axis=0) theta = N.arccos(c[2]/r) phi = N.arctan2(c[1],c[0]) return N.column_stack((r,theta,phi))
python
def spherical(coordinates): """No error is propagated""" c = coordinates r = N.linalg.norm(c,axis=0) theta = N.arccos(c[2]/r) phi = N.arctan2(c[1],c[0]) return N.column_stack((r,theta,phi))
[ "def", "spherical", "(", "coordinates", ")", ":", "c", "=", "coordinates", "r", "=", "N", ".", "linalg", ".", "norm", "(", "c", ",", "axis", "=", "0", ")", "theta", "=", "N", ".", "arccos", "(", "c", "[", "2", "]", "/", "r", ")", "phi", "=", ...
No error is propagated
[ "No", "error", "is", "propagated" ]
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/coordinates/__init__.py#L3-L9
train
53,194
davenquinn/Attitude
attitude/coordinates/__init__.py
centered
def centered(coordinates): """ Centers coordinate distribution with respect to its mean on all three axes. This is used as the input to the regression model, so it can be converted easily into radial coordinates. """ coordinates = N.array(coordinates) means = N.mean(coordinates,axis=0) return coordinates - means
python
def centered(coordinates): """ Centers coordinate distribution with respect to its mean on all three axes. This is used as the input to the regression model, so it can be converted easily into radial coordinates. """ coordinates = N.array(coordinates) means = N.mean(coordinates,axis=0) return coordinates - means
[ "def", "centered", "(", "coordinates", ")", ":", "coordinates", "=", "N", ".", "array", "(", "coordinates", ")", "means", "=", "N", ".", "mean", "(", "coordinates", ",", "axis", "=", "0", ")", "return", "coordinates", "-", "means" ]
Centers coordinate distribution with respect to its mean on all three axes. This is used as the input to the regression model, so it can be converted easily into radial coordinates.
[ "Centers", "coordinate", "distribution", "with", "respect", "to", "its", "mean", "on", "all", "three", "axes", ".", "This", "is", "used", "as", "the", "input", "to", "the", "regression", "model", "so", "it", "can", "be", "converted", "easily", "into", "rad...
2ce97b9aba0aa5deedc6617c2315e07e6396d240
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/coordinates/__init__.py#L19-L28
train
53,195
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
add_http_headers_for_attachment
def add_http_headers_for_attachment(response: HttpResponse, offered_filename: str = None, content_type: str = None, as_attachment: bool = False, as_inline: bool = False, content_length: int = None) -> None: """ Add HTTP headers to a Django response class object. Args: response: ``HttpResponse`` instance offered_filename: filename that the client browser will suggest content_type: HTTP content type as_attachment: if True, browsers will generally save to disk. If False, they may display it inline. http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html as_inline: attempt to force inline (only if not as_attachment) content_length: HTTP content length """ if offered_filename is None: offered_filename = '' if content_type is None: content_type = 'application/force-download' response['Content-Type'] = content_type if as_attachment: prefix = 'attachment; ' elif as_inline: prefix = 'inline; ' else: prefix = '' fname = 'filename=%s' % smart_str(offered_filename) response['Content-Disposition'] = prefix + fname if content_length is not None: response['Content-Length'] = content_length
python
def add_http_headers_for_attachment(response: HttpResponse, offered_filename: str = None, content_type: str = None, as_attachment: bool = False, as_inline: bool = False, content_length: int = None) -> None: """ Add HTTP headers to a Django response class object. Args: response: ``HttpResponse`` instance offered_filename: filename that the client browser will suggest content_type: HTTP content type as_attachment: if True, browsers will generally save to disk. If False, they may display it inline. http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html as_inline: attempt to force inline (only if not as_attachment) content_length: HTTP content length """ if offered_filename is None: offered_filename = '' if content_type is None: content_type = 'application/force-download' response['Content-Type'] = content_type if as_attachment: prefix = 'attachment; ' elif as_inline: prefix = 'inline; ' else: prefix = '' fname = 'filename=%s' % smart_str(offered_filename) response['Content-Disposition'] = prefix + fname if content_length is not None: response['Content-Length'] = content_length
[ "def", "add_http_headers_for_attachment", "(", "response", ":", "HttpResponse", ",", "offered_filename", ":", "str", "=", "None", ",", "content_type", ":", "str", "=", "None", ",", "as_attachment", ":", "bool", "=", "False", ",", "as_inline", ":", "bool", "=",...
Add HTTP headers to a Django response class object. Args: response: ``HttpResponse`` instance offered_filename: filename that the client browser will suggest content_type: HTTP content type as_attachment: if True, browsers will generally save to disk. If False, they may display it inline. http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html as_inline: attempt to force inline (only if not as_attachment) content_length: HTTP content length
[ "Add", "HTTP", "headers", "to", "a", "Django", "response", "class", "object", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L58-L93
train
53,196
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
add_download_filename
def add_download_filename(response: HttpResponse, filename: str) -> None: """ Adds a ``Content-Disposition`` header to the HTTP response to say that there is an attachment with the specified filename. """ # https://docs.djangoproject.com/en/1.9/howto/outputting-csv/ add_http_headers_for_attachment(response) response['Content-Disposition'] = 'attachment; filename="{}"'.format( filename)
python
def add_download_filename(response: HttpResponse, filename: str) -> None: """ Adds a ``Content-Disposition`` header to the HTTP response to say that there is an attachment with the specified filename. """ # https://docs.djangoproject.com/en/1.9/howto/outputting-csv/ add_http_headers_for_attachment(response) response['Content-Disposition'] = 'attachment; filename="{}"'.format( filename)
[ "def", "add_download_filename", "(", "response", ":", "HttpResponse", ",", "filename", ":", "str", ")", "->", "None", ":", "# https://docs.djangoproject.com/en/1.9/howto/outputting-csv/", "add_http_headers_for_attachment", "(", "response", ")", "response", "[", "'Content-Di...
Adds a ``Content-Disposition`` header to the HTTP response to say that there is an attachment with the specified filename.
[ "Adds", "a", "Content", "-", "Disposition", "header", "to", "the", "HTTP", "response", "to", "say", "that", "there", "is", "an", "attachment", "with", "the", "specified", "filename", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L155-L163
train
53,197
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
file_response
def file_response(data: Union[bytes, str], # HttpResponse encodes str if req'd content_type: str, filename: str) -> HttpResponse: """ Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment. """ response = HttpResponse(data, content_type=content_type) add_download_filename(response, filename) return response
python
def file_response(data: Union[bytes, str], # HttpResponse encodes str if req'd content_type: str, filename: str) -> HttpResponse: """ Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment. """ response = HttpResponse(data, content_type=content_type) add_download_filename(response, filename) return response
[ "def", "file_response", "(", "data", ":", "Union", "[", "bytes", ",", "str", "]", ",", "# HttpResponse encodes str if req'd", "content_type", ":", "str", ",", "filename", ":", "str", ")", "->", "HttpResponse", ":", "response", "=", "HttpResponse", "(", "data",...
Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment.
[ "Returns", "an", "HttpResponse", "with", "an", "attachment", "containing", "the", "specified", "data", "with", "the", "specified", "filename", "as", "an", "attachment", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L166-L175
train
53,198
RudolfCardinal/pythonlib
cardinal_pythonlib/django/serve.py
serve_concatenated_pdf_from_disk
def serve_concatenated_pdf_from_disk( filenames: Iterable[str], offered_filename: str = "crate_download.pdf", **kwargs) -> HttpResponse: """ Concatenates PDFs from disk and serves them. """ pdf = get_concatenated_pdf_from_disk(filenames, **kwargs) return serve_buffer(pdf, offered_filename=offered_filename, content_type=MimeType.PDF, as_attachment=False, as_inline=True)
python
def serve_concatenated_pdf_from_disk( filenames: Iterable[str], offered_filename: str = "crate_download.pdf", **kwargs) -> HttpResponse: """ Concatenates PDFs from disk and serves them. """ pdf = get_concatenated_pdf_from_disk(filenames, **kwargs) return serve_buffer(pdf, offered_filename=offered_filename, content_type=MimeType.PDF, as_attachment=False, as_inline=True)
[ "def", "serve_concatenated_pdf_from_disk", "(", "filenames", ":", "Iterable", "[", "str", "]", ",", "offered_filename", ":", "str", "=", "\"crate_download.pdf\"", ",", "*", "*", "kwargs", ")", "->", "HttpResponse", ":", "pdf", "=", "get_concatenated_pdf_from_disk", ...
Concatenates PDFs from disk and serves them.
[ "Concatenates", "PDFs", "from", "disk", "and", "serves", "them", "." ]
0b84cb35f38bd7d8723958dae51b480a829b7227
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/serve.py#L182-L194
train
53,199