repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/dump.py
dump_ddl
def dump_ddl(metadata: MetaData, dialect_name: str, fileobj: TextIO = sys.stdout, checkfirst: bool = True) -> None: """ Sends schema-creating DDL from the metadata to the dump engine. This makes ``CREATE TABLE`` statements. Args: metadata: SQLAlchemy :clas...
python
def dump_ddl(metadata: MetaData, dialect_name: str, fileobj: TextIO = sys.stdout, checkfirst: bool = True) -> None: """ Sends schema-creating DDL from the metadata to the dump engine. This makes ``CREATE TABLE`` statements. Args: metadata: SQLAlchemy :clas...
[ "def", "dump_ddl", "(", "metadata", ":", "MetaData", ",", "dialect_name", ":", "str", ",", "fileobj", ":", "TextIO", "=", "sys", ".", "stdout", ",", "checkfirst", ":", "bool", "=", "True", ")", "->", "None", ":", "# http://docs.sqlalchemy.org/en/rel_0_8/faq.ht...
Sends schema-creating DDL from the metadata to the dump engine. This makes ``CREATE TABLE`` statements. Args: metadata: SQLAlchemy :class:`MetaData` dialect_name: string name of SQL dialect to generate DDL in fileobj: file-like object to send DDL to checkfirst: if ``True``, use ...
[ "Sends", "schema", "-", "creating", "DDL", "from", "the", "metadata", "to", "the", "dump", "engine", ".", "This", "makes", "CREATE", "TABLE", "statements", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L79-L106
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/dump.py
quick_mapper
def quick_mapper(table: Table) -> Type[DeclarativeMeta]: """ Makes a new SQLAlchemy mapper for an existing table. See http://www.tylerlesmann.com/2009/apr/27/copying-databases-across-platforms-sqlalchemy/ Args: table: SQLAlchemy :class:`Table` object Returns: a :class:`Decl...
python
def quick_mapper(table: Table) -> Type[DeclarativeMeta]: """ Makes a new SQLAlchemy mapper for an existing table. See http://www.tylerlesmann.com/2009/apr/27/copying-databases-across-platforms-sqlalchemy/ Args: table: SQLAlchemy :class:`Table` object Returns: a :class:`Decl...
[ "def", "quick_mapper", "(", "table", ":", "Table", ")", "->", "Type", "[", "DeclarativeMeta", "]", ":", "# noqa", "# noinspection PyPep8Naming", "Base", "=", "declarative_base", "(", ")", "class", "GenericMapper", "(", "Base", ")", ":", "__table__", "=", "tabl...
Makes a new SQLAlchemy mapper for an existing table. See http://www.tylerlesmann.com/2009/apr/27/copying-databases-across-platforms-sqlalchemy/ Args: table: SQLAlchemy :class:`Table` object Returns: a :class:`DeclarativeMeta` class
[ "Makes", "a", "new", "SQLAlchemy", "mapper", "for", "an", "existing", "table", ".", "See", "http", ":", "//", "www", ".", "tylerlesmann", ".", "com", "/", "2009", "/", "apr", "/", "27", "/", "copying", "-", "databases", "-", "across", "-", "platforms",...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L113-L133
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/dump.py
get_literal_query
def get_literal_query(statement: Union[Query, Executable], bind: Connectable = None) -> str: """ Takes an SQLAlchemy statement and produces a literal SQL version, with values filled in. As per http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query ...
python
def get_literal_query(statement: Union[Query, Executable], bind: Connectable = None) -> str: """ Takes an SQLAlchemy statement and produces a literal SQL version, with values filled in. As per http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query ...
[ "def", "get_literal_query", "(", "statement", ":", "Union", "[", "Query", ",", "Executable", "]", ",", "bind", ":", "Connectable", "=", "None", ")", "->", "str", ":", "# noqa", "# log.debug(\"statement: {!r}\", statement)", "# log.debug(\"statement.bind: {!r}\", stateme...
Takes an SQLAlchemy statement and produces a literal SQL version, with values filled in. As per http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query Notes: - for debugging purposes *only* - insecure; you should always separate queries from their values - ple...
[ "Takes", "an", "SQLAlchemy", "statement", "and", "produces", "a", "literal", "SQL", "version", "with", "values", "filled", "in", ".", "As", "per", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "5631078", "/", "sqlalchemy", "-", "pr...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L192-L281
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/dump.py
dump_table_as_insert_sql
def dump_table_as_insert_sql(engine: Engine, table_name: str, fileobj: TextIO, wheredict: Dict[str, Any] = None, include_ddl: bool = False, multirow: bool = False) -> None: ...
python
def dump_table_as_insert_sql(engine: Engine, table_name: str, fileobj: TextIO, wheredict: Dict[str, Any] = None, include_ddl: bool = False, multirow: bool = False) -> None: ...
[ "def", "dump_table_as_insert_sql", "(", "engine", ":", "Engine", ",", "table_name", ":", "str", ",", "fileobj", ":", "TextIO", ",", "wheredict", ":", "Dict", "[", "str", ",", "Any", "]", "=", "None", ",", "include_ddl", ":", "bool", "=", "False", ",", ...
Reads a table from the database, and writes SQL to replicate the table's data to the output ``fileobj``. Args: engine: SQLAlchemy :class:`Engine` table_name: name of the table fileobj: file-like object to write to wheredict: optional dictionary of ``{column_name: value}`` to use...
[ "Reads", "a", "table", "from", "the", "database", "and", "writes", "SQL", "to", "replicate", "the", "table", "s", "data", "to", "the", "output", "fileobj", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L284-L373
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/dump.py
dump_database_as_insert_sql
def dump_database_as_insert_sql(engine: Engine, fileobj: TextIO = sys.stdout, include_ddl: bool = False, multirow: bool = False) -> None: """ Reads an entire database and writes SQL to replicate it to the output ...
python
def dump_database_as_insert_sql(engine: Engine, fileobj: TextIO = sys.stdout, include_ddl: bool = False, multirow: bool = False) -> None: """ Reads an entire database and writes SQL to replicate it to the output ...
[ "def", "dump_database_as_insert_sql", "(", "engine", ":", "Engine", ",", "fileobj", ":", "TextIO", "=", "sys", ".", "stdout", ",", "include_ddl", ":", "bool", "=", "False", ",", "multirow", ":", "bool", "=", "False", ")", "->", "None", ":", "for", "table...
Reads an entire database and writes SQL to replicate it to the output file-like object. Args: engine: SQLAlchemy :class:`Engine` fileobj: file-like object to write to include_ddl: if ``True``, include the DDL to create the table as well multirow: write multi-row ``INSERT`` state...
[ "Reads", "an", "entire", "database", "and", "writes", "SQL", "to", "replicate", "it", "to", "the", "output", "file", "-", "like", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L376-L397
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/dump.py
dump_orm_object_as_insert_sql
def dump_orm_object_as_insert_sql(engine: Engine, obj: object, fileobj: TextIO) -> None: """ Takes a SQLAlchemy ORM object, and writes ``INSERT`` SQL to replicate it to the output file-like object. Args: engine: SQLAlchemy :cla...
python
def dump_orm_object_as_insert_sql(engine: Engine, obj: object, fileobj: TextIO) -> None: """ Takes a SQLAlchemy ORM object, and writes ``INSERT`` SQL to replicate it to the output file-like object. Args: engine: SQLAlchemy :cla...
[ "def", "dump_orm_object_as_insert_sql", "(", "engine", ":", "Engine", ",", "obj", ":", "object", ",", "fileobj", ":", "TextIO", ")", "->", "None", ":", "# literal_query = make_literal_query_fn(engine.dialect)", "insp", "=", "inspect", "(", "obj", ")", "# insp: an In...
Takes a SQLAlchemy ORM object, and writes ``INSERT`` SQL to replicate it to the output file-like object. Args: engine: SQLAlchemy :class:`Engine` obj: SQLAlchemy ORM object to write fileobj: file-like object to write to
[ "Takes", "a", "SQLAlchemy", "ORM", "object", "and", "writes", "INSERT", "SQL", "to", "replicate", "it", "to", "the", "output", "file", "-", "like", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L400-L447
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/dump.py
bulk_insert_extras
def bulk_insert_extras(dialect_name: str, fileobj: TextIO, start: bool) -> None: """ Writes bulk ``INSERT`` preamble (start=True) or end (start=False). For MySQL, this temporarily switches off autocommit behaviour and index/FK checks, for speed, then re-ena...
python
def bulk_insert_extras(dialect_name: str, fileobj: TextIO, start: bool) -> None: """ Writes bulk ``INSERT`` preamble (start=True) or end (start=False). For MySQL, this temporarily switches off autocommit behaviour and index/FK checks, for speed, then re-ena...
[ "def", "bulk_insert_extras", "(", "dialect_name", ":", "str", ",", "fileobj", ":", "TextIO", ",", "start", ":", "bool", ")", "->", "None", ":", "lines", "=", "[", "]", "if", "dialect_name", "==", "SqlaDialectName", ".", "MYSQL", ":", "if", "start", ":", ...
Writes bulk ``INSERT`` preamble (start=True) or end (start=False). For MySQL, this temporarily switches off autocommit behaviour and index/FK checks, for speed, then re-enables them at the end and commits. Args: dialect_name: SQLAlchemy dialect name (see :class:`SqlaDialectName`) fileobj: ...
[ "Writes", "bulk", "INSERT", "preamble", "(", "start", "=", "True", ")", "or", "end", "(", "start", "=", "False", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L450-L478
RudolfCardinal/pythonlib
cardinal_pythonlib/sqlalchemy/dump.py
dump_orm_tree_as_insert_sql
def dump_orm_tree_as_insert_sql(engine: Engine, baseobj: object, fileobj: TextIO) -> None: """ Sends an object, and all its relations (discovered via "relationship" links) as ``INSERT`` commands in SQL, to ``fileobj``. Args: engine...
python
def dump_orm_tree_as_insert_sql(engine: Engine, baseobj: object, fileobj: TextIO) -> None: """ Sends an object, and all its relations (discovered via "relationship" links) as ``INSERT`` commands in SQL, to ``fileobj``. Args: engine...
[ "def", "dump_orm_tree_as_insert_sql", "(", "engine", ":", "Engine", ",", "baseobj", ":", "object", ",", "fileobj", ":", "TextIO", ")", "->", "None", ":", "# noqa", "writeline_nl", "(", "fileobj", ",", "sql_comment", "(", "\"Data for all objects related to the first ...
Sends an object, and all its relations (discovered via "relationship" links) as ``INSERT`` commands in SQL, to ``fileobj``. Args: engine: SQLAlchemy :class:`Engine` baseobj: starting SQLAlchemy ORM object fileobj: file-like object to write to Problem: foreign key constraints. ...
[ "Sends", "an", "object", "and", "all", "its", "relations", "(", "discovered", "via", "relationship", "links", ")", "as", "INSERT", "commands", "in", "SQL", "to", "fileobj", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/dump.py#L481-L510
avihad/twistes
twistes/scroller.py
Scroller.next
def next(self): """Fetch next page from scroll API.""" d = None if self._first_results: d = succeed(EsUtils.extract_hits(self._first_results)) self._first_results = None elif self._scroll_id: d = self._scroll_next_results() else: ra...
python
def next(self): """Fetch next page from scroll API.""" d = None if self._first_results: d = succeed(EsUtils.extract_hits(self._first_results)) self._first_results = None elif self._scroll_id: d = self._scroll_next_results() else: ra...
[ "def", "next", "(", "self", ")", ":", "d", "=", "None", "if", "self", ".", "_first_results", ":", "d", "=", "succeed", "(", "EsUtils", ".", "extract_hits", "(", "self", ".", "_first_results", ")", ")", "self", ".", "_first_results", "=", "None", "elif"...
Fetch next page from scroll API.
[ "Fetch", "next", "page", "from", "scroll", "API", "." ]
train
https://github.com/avihad/twistes/blob/9ab8f5aa088b8886aefe3dec85a400e5035e034a/twistes/scroller.py#L31-L41
RudolfCardinal/pythonlib
cardinal_pythonlib/source_reformatting.py
reformat_python_docstrings
def reformat_python_docstrings(top_dirs: List[str], correct_copyright_lines: List[str], show_only: bool = True, rewrite: bool = False, process_only_filenum: int = None) -> None: """ Walk a...
python
def reformat_python_docstrings(top_dirs: List[str], correct_copyright_lines: List[str], show_only: bool = True, rewrite: bool = False, process_only_filenum: int = None) -> None: """ Walk a...
[ "def", "reformat_python_docstrings", "(", "top_dirs", ":", "List", "[", "str", "]", ",", "correct_copyright_lines", ":", "List", "[", "str", "]", ",", "show_only", ":", "bool", "=", "True", ",", "rewrite", ":", "bool", "=", "False", ",", "process_only_filenu...
Walk a directory, finding Python files and rewriting them. Args: top_dirs: list of directories to descend into correct_copyright_lines: list of lines (without newlines) representing the copyright docstring block, including the transition lines of equals symbols ...
[ "Walk", "a", "directory", "finding", "Python", "files", "and", "rewriting", "them", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L310-L352
RudolfCardinal/pythonlib
cardinal_pythonlib/source_reformatting.py
PythonProcessor._read_source
def _read_source(self) -> None: """ Reads the source file. """ with open(self.full_path, "rt") as f: for linenum, line_with_nl in enumerate(f.readlines(), start=1): line_without_newline = ( line_with_nl[:-1] if line_with_nl.endswith(NL) ...
python
def _read_source(self) -> None: """ Reads the source file. """ with open(self.full_path, "rt") as f: for linenum, line_with_nl in enumerate(f.readlines(), start=1): line_without_newline = ( line_with_nl[:-1] if line_with_nl.endswith(NL) ...
[ "def", "_read_source", "(", "self", ")", "->", "None", ":", "with", "open", "(", "self", ".", "full_path", ",", "\"rt\"", ")", "as", "f", ":", "for", "linenum", ",", "line_with_nl", "in", "enumerate", "(", "f", ".", "readlines", "(", ")", ",", "start...
Reads the source file.
[ "Reads", "the", "source", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L95-L110
RudolfCardinal/pythonlib
cardinal_pythonlib/source_reformatting.py
PythonProcessor._create_dest
def _create_dest(self) -> None: """ Creates an internal representation of the destination file. This is where the thinking happens """ in_body = False in_docstring = False in_copyright = False copyright_done = False docstring_done = False ...
python
def _create_dest(self) -> None: """ Creates an internal representation of the destination file. This is where the thinking happens """ in_body = False in_docstring = False in_copyright = False copyright_done = False docstring_done = False ...
[ "def", "_create_dest", "(", "self", ")", "->", "None", ":", "in_body", "=", "False", "in_docstring", "=", "False", "in_copyright", "=", "False", "copyright_done", "=", "False", "docstring_done", "=", "False", "swallow_blanks_and_filename_in_docstring", "=", "False",...
Creates an internal representation of the destination file. This is where the thinking happens
[ "Creates", "an", "internal", "representation", "of", "the", "destination", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L112-L236
RudolfCardinal/pythonlib
cardinal_pythonlib/source_reformatting.py
PythonProcessor._debug_line
def _debug_line(linenum: int, line: str, extramsg: str = "") -> None: """ Writes a debugging report on a line. """ log.critical("{}Line {}: {!r}", extramsg, linenum, line)
python
def _debug_line(linenum: int, line: str, extramsg: str = "") -> None: """ Writes a debugging report on a line. """ log.critical("{}Line {}: {!r}", extramsg, linenum, line)
[ "def", "_debug_line", "(", "linenum", ":", "int", ",", "line", ":", "str", ",", "extramsg", ":", "str", "=", "\"\"", ")", "->", "None", ":", "log", ".", "critical", "(", "\"{}Line {}: {!r}\"", ",", "extramsg", ",", "linenum", ",", "line", ")" ]
Writes a debugging report on a line.
[ "Writes", "a", "debugging", "report", "on", "a", "line", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L239-L243
RudolfCardinal/pythonlib
cardinal_pythonlib/source_reformatting.py
PythonProcessor.rewrite_file
def rewrite_file(self) -> None: """ Rewrites the source file. """ if not self.needs_rewriting: return self._info("Rewriting file") with open(self.full_path, "w") as outfile: self._write(outfile)
python
def rewrite_file(self) -> None: """ Rewrites the source file. """ if not self.needs_rewriting: return self._info("Rewriting file") with open(self.full_path, "w") as outfile: self._write(outfile)
[ "def", "rewrite_file", "(", "self", ")", "->", "None", ":", "if", "not", "self", ".", "needs_rewriting", ":", "return", "self", ".", "_info", "(", "\"Rewriting file\"", ")", "with", "open", "(", "self", ".", "full_path", ",", "\"w\"", ")", "as", "outfile...
Rewrites the source file.
[ "Rewrites", "the", "source", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L288-L296
RudolfCardinal/pythonlib
cardinal_pythonlib/source_reformatting.py
PythonProcessor._write
def _write(self, destination: TextIO) -> None: """ Writes the converted output to a destination. """ for line in self.dest_lines: destination.write(line + NL)
python
def _write(self, destination: TextIO) -> None: """ Writes the converted output to a destination. """ for line in self.dest_lines: destination.write(line + NL)
[ "def", "_write", "(", "self", ",", "destination", ":", "TextIO", ")", "->", "None", ":", "for", "line", "in", "self", ".", "dest_lines", ":", "destination", ".", "write", "(", "line", "+", "NL", ")" ]
Writes the converted output to a destination.
[ "Writes", "the", "converted", "output", "to", "a", "destination", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/source_reformatting.py#L298-L303
RudolfCardinal/pythonlib
cardinal_pythonlib/lists.py
contains_duplicates
def contains_duplicates(values: Iterable[Any]) -> bool: """ Does the iterable contain any duplicate values? """ for v in Counter(values).values(): if v > 1: return True return False
python
def contains_duplicates(values: Iterable[Any]) -> bool: """ Does the iterable contain any duplicate values? """ for v in Counter(values).values(): if v > 1: return True return False
[ "def", "contains_duplicates", "(", "values", ":", "Iterable", "[", "Any", "]", ")", "->", "bool", ":", "for", "v", "in", "Counter", "(", "values", ")", ".", "values", "(", ")", ":", "if", "v", ">", "1", ":", "return", "True", "return", "False" ]
Does the iterable contain any duplicate values?
[ "Does", "the", "iterable", "contain", "any", "duplicate", "values?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L38-L45
RudolfCardinal/pythonlib
cardinal_pythonlib/lists.py
index_list_for_sort_order
def index_list_for_sort_order(x: List[Any], key: Callable[[Any], Any] = None, reverse: bool = False) -> List[int]: """ Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED. Args: x: data key: function to be applied to the data to generate a sort key; ...
python
def index_list_for_sort_order(x: List[Any], key: Callable[[Any], Any] = None, reverse: bool = False) -> List[int]: """ Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED. Args: x: data key: function to be applied to the data to generate a sort key; ...
[ "def", "index_list_for_sort_order", "(", "x", ":", "List", "[", "Any", "]", ",", "key", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", "=", "None", ",", "reverse", ":", "bool", "=", "False", ")", "->", "List", "[", "int", "]", ":", "def"...
Returns a list of indexes of ``x``, IF ``x`` WERE TO BE SORTED. Args: x: data key: function to be applied to the data to generate a sort key; this function is passed as the ``key=`` parameter to :func:`sorted`; the default is ``itemgetter(1)`` reverse: reverse the so...
[ "Returns", "a", "list", "of", "indexes", "of", "x", "IF", "x", "WERE", "TO", "BE", "SORTED", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L48-L84
RudolfCardinal/pythonlib
cardinal_pythonlib/lists.py
sort_list_by_index_list
def sort_list_by_index_list(x: List[Any], indexes: List[int]) -> None: """ Re-orders ``x`` by the list of ``indexes`` of ``x``, in place. Example: .. code-block:: python from cardinal_pythonlib.lists import sort_list_by_index_list z = ["a", "b", "c", "d", "e"] sort_list_by_in...
python
def sort_list_by_index_list(x: List[Any], indexes: List[int]) -> None: """ Re-orders ``x`` by the list of ``indexes`` of ``x``, in place. Example: .. code-block:: python from cardinal_pythonlib.lists import sort_list_by_index_list z = ["a", "b", "c", "d", "e"] sort_list_by_in...
[ "def", "sort_list_by_index_list", "(", "x", ":", "List", "[", "Any", "]", ",", "indexes", ":", "List", "[", "int", "]", ")", "->", "None", ":", "x", "[", ":", "]", "=", "[", "x", "[", "i", "]", "for", "i", "in", "indexes", "]" ]
Re-orders ``x`` by the list of ``indexes`` of ``x``, in place. Example: .. code-block:: python from cardinal_pythonlib.lists import sort_list_by_index_list z = ["a", "b", "c", "d", "e"] sort_list_by_index_list(z, [4, 0, 1, 2, 3]) z # ["e", "a", "b", "c", "d"]
[ "Re", "-", "orders", "x", "by", "the", "list", "of", "indexes", "of", "x", "in", "place", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L87-L101
RudolfCardinal/pythonlib
cardinal_pythonlib/lists.py
flatten_list
def flatten_list(x: List[Any]) -> List[Any]: """ Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ # noqa return [it...
python
def flatten_list(x: List[Any]) -> List[Any]: """ Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python """ # noqa return [it...
[ "def", "flatten_list", "(", "x", ":", "List", "[", "Any", "]", ")", "->", "List", "[", "Any", "]", ":", "# noqa", "return", "[", "item", "for", "sublist", "in", "x", "for", "item", "in", "sublist", "]" ]
Converts a list of lists into a flat list. Args: x: list of lists Returns: flat list As per http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
[ "Converts", "a", "list", "of", "lists", "into", "a", "flat", "list", ".", "Args", ":", "x", ":", "list", "of", "lists" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L104-L118
RudolfCardinal/pythonlib
cardinal_pythonlib/lists.py
unique_list
def unique_list(seq: Iterable[Any]) -> List[Any]: """ Returns a list of all the unique elements in the input list. Args: seq: input list Returns: list of unique elements As per http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserv...
python
def unique_list(seq: Iterable[Any]) -> List[Any]: """ Returns a list of all the unique elements in the input list. Args: seq: input list Returns: list of unique elements As per http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserv...
[ "def", "unique_list", "(", "seq", ":", "Iterable", "[", "Any", "]", ")", "->", "List", "[", "Any", "]", ":", "# noqa", "seen", "=", "set", "(", ")", "seen_add", "=", "seen", ".", "add", "return", "[", "x", "for", "x", "in", "seq", "if", "not", ...
Returns a list of all the unique elements in the input list. Args: seq: input list Returns: list of unique elements As per http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-whilst-preserving-order
[ "Returns", "a", "list", "of", "all", "the", "unique", "elements", "in", "the", "input", "list", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L121-L137
RudolfCardinal/pythonlib
cardinal_pythonlib/lists.py
chunks
def chunks(l: List[Any], n: int) -> Iterable[List[Any]]: """ Yield successive ``n``-sized chunks from ``l``. Args: l: input list n: chunk size Yields: successive chunks of size ``n`` """ for i in range(0, len(l), n): yield l[i:i + n]
python
def chunks(l: List[Any], n: int) -> Iterable[List[Any]]: """ Yield successive ``n``-sized chunks from ``l``. Args: l: input list n: chunk size Yields: successive chunks of size ``n`` """ for i in range(0, len(l), n): yield l[i:i + n]
[ "def", "chunks", "(", "l", ":", "List", "[", "Any", "]", ",", "n", ":", "int", ")", "->", "Iterable", "[", "List", "[", "Any", "]", "]", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "l", ")", ",", "n", ")", ":", "yield", "l"...
Yield successive ``n``-sized chunks from ``l``. Args: l: input list n: chunk size Yields: successive chunks of size ``n``
[ "Yield", "successive", "n", "-", "sized", "chunks", "from", "l", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/lists.py#L140-L153
RudolfCardinal/pythonlib
cardinal_pythonlib/text.py
escape_newlines
def escape_newlines(s: str) -> str: """ Escapes CR, LF, and backslashes. Its counterpart is :func:`unescape_newlines`. ``s.encode("string_escape")`` and ``s.encode("unicode_escape")`` are alternatives, but they mess around with quotes, too (specifically, backslash-escaping single quotes). ...
python
def escape_newlines(s: str) -> str: """ Escapes CR, LF, and backslashes. Its counterpart is :func:`unescape_newlines`. ``s.encode("string_escape")`` and ``s.encode("unicode_escape")`` are alternatives, but they mess around with quotes, too (specifically, backslash-escaping single quotes). ...
[ "def", "escape_newlines", "(", "s", ":", "str", ")", "->", "str", ":", "if", "not", "s", ":", "return", "s", "s", "=", "s", ".", "replace", "(", "\"\\\\\"", ",", "r\"\\\\\"", ")", "# replace \\ with \\\\", "s", "=", "s", ".", "replace", "(", "\"\\n\"...
Escapes CR, LF, and backslashes. Its counterpart is :func:`unescape_newlines`. ``s.encode("string_escape")`` and ``s.encode("unicode_escape")`` are alternatives, but they mess around with quotes, too (specifically, backslash-escaping single quotes).
[ "Escapes", "CR", "LF", "and", "backslashes", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/text.py#L40-L55
RudolfCardinal/pythonlib
cardinal_pythonlib/text.py
unescape_newlines
def unescape_newlines(s: str) -> str: """ Reverses :func:`escape_newlines`. """ # See also http://stackoverflow.com/questions/4020539 if not s: return s d = "" # the destination string in_escape = False for i in range(len(s)): c = s[i] # the character being processed ...
python
def unescape_newlines(s: str) -> str: """ Reverses :func:`escape_newlines`. """ # See also http://stackoverflow.com/questions/4020539 if not s: return s d = "" # the destination string in_escape = False for i in range(len(s)): c = s[i] # the character being processed ...
[ "def", "unescape_newlines", "(", "s", ":", "str", ")", "->", "str", ":", "# See also http://stackoverflow.com/questions/4020539", "if", "not", "s", ":", "return", "s", "d", "=", "\"\"", "# the destination string", "in_escape", "=", "False", "for", "i", "in", "ra...
Reverses :func:`escape_newlines`.
[ "Reverses", ":", "func", ":", "escape_newlines", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/text.py#L58-L82
RudolfCardinal/pythonlib
cardinal_pythonlib/text.py
escape_tabs_newlines
def escape_tabs_newlines(s: str) -> str: """ Escapes CR, LF, tab, and backslashes. Its counterpart is :func:`unescape_tabs_newlines`. """ if not s: return s s = s.replace("\\", r"\\") # replace \ with \\ s = s.replace("\n", r"\n") # escape \n; note ord("\n") == 10 s = s.replac...
python
def escape_tabs_newlines(s: str) -> str: """ Escapes CR, LF, tab, and backslashes. Its counterpart is :func:`unescape_tabs_newlines`. """ if not s: return s s = s.replace("\\", r"\\") # replace \ with \\ s = s.replace("\n", r"\n") # escape \n; note ord("\n") == 10 s = s.replac...
[ "def", "escape_tabs_newlines", "(", "s", ":", "str", ")", "->", "str", ":", "if", "not", "s", ":", "return", "s", "s", "=", "s", ".", "replace", "(", "\"\\\\\"", ",", "r\"\\\\\"", ")", "# replace \\ with \\\\", "s", "=", "s", ".", "replace", "(", "\"...
Escapes CR, LF, tab, and backslashes. Its counterpart is :func:`unescape_tabs_newlines`.
[ "Escapes", "CR", "LF", "tab", "and", "backslashes", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/text.py#L85-L97
RudolfCardinal/pythonlib
cardinal_pythonlib/text.py
_unicode_def_src_to_str
def _unicode_def_src_to_str(srclist: List[Union[str, int]]) -> str: """ Used to create :data:`UNICODE_CATEGORY_STRINGS`. Args: srclist: list of integers or hex range strings like ``"0061-007A"`` Returns: a string with all characters described by ``srclist``: either the characte...
python
def _unicode_def_src_to_str(srclist: List[Union[str, int]]) -> str: """ Used to create :data:`UNICODE_CATEGORY_STRINGS`. Args: srclist: list of integers or hex range strings like ``"0061-007A"`` Returns: a string with all characters described by ``srclist``: either the characte...
[ "def", "_unicode_def_src_to_str", "(", "srclist", ":", "List", "[", "Union", "[", "str", ",", "int", "]", "]", ")", "->", "str", ":", "charlist", "=", "[", "]", "# type: List[str]", "for", "src", "in", "srclist", ":", "if", "isinstance", "(", "src", ",...
Used to create :data:`UNICODE_CATEGORY_STRINGS`. Args: srclist: list of integers or hex range strings like ``"0061-007A"`` Returns: a string with all characters described by ``srclist``: either the character corresponding to the integer Unicode character number, or all characte...
[ "Used", "to", "create", ":", "data", ":", "UNICODE_CATEGORY_STRINGS", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/text.py#L134-L154
davenquinn/Attitude
attitude/__dustbin/__report/__init__.py
report
def report(*arrays, **kwargs): """ Outputs a standalone HTML 'report card' for a measurement (or several grouped measurements), including relevant statistical information. """ name = kwargs.pop("name",None) grouped = len(arrays) > 1 if grouped: arr = N.concatenate(arrays) ...
python
def report(*arrays, **kwargs): """ Outputs a standalone HTML 'report card' for a measurement (or several grouped measurements), including relevant statistical information. """ name = kwargs.pop("name",None) grouped = len(arrays) > 1 if grouped: arr = N.concatenate(arrays) ...
[ "def", "report", "(", "*", "arrays", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "\"name\"", ",", "None", ")", "grouped", "=", "len", "(", "arrays", ")", ">", "1", "if", "grouped", ":", "arr", "=", "N", ".", "conc...
Outputs a standalone HTML 'report card' for a measurement (or several grouped measurements), including relevant statistical information.
[ "Outputs", "a", "standalone", "HTML", "report", "card", "for", "a", "measurement", "(", "or", "several", "grouped", "measurements", ")", "including", "relevant", "statistical", "information", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/__dustbin/__report/__init__.py#L34-L78
meyersj/geotweet
geotweet/twitter/stream_steps.py
GeoFilterStep.validate_geotweet
def validate_geotweet(self, record): """ check that stream record is actual tweet with coordinates """ if record and self._validate('user', record) \ and self._validate('coordinates', record): return True return False
python
def validate_geotweet(self, record): """ check that stream record is actual tweet with coordinates """ if record and self._validate('user', record) \ and self._validate('coordinates', record): return True return False
[ "def", "validate_geotweet", "(", "self", ",", "record", ")", ":", "if", "record", "and", "self", ".", "_validate", "(", "'user'", ",", "record", ")", "and", "self", ".", "_validate", "(", "'coordinates'", ",", "record", ")", ":", "return", "True", "retur...
check that stream record is actual tweet with coordinates
[ "check", "that", "stream", "record", "is", "actual", "tweet", "with", "coordinates" ]
train
https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/twitter/stream_steps.py#L53-L58
davenquinn/Attitude
attitude/geom/conics.py
angle_subtended
def angle_subtended(ell, **kwargs): """ Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to origin """ retu...
python
def angle_subtended(ell, **kwargs): """ Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to origin """ retu...
[ "def", "angle_subtended", "(", "ell", ",", "*", "*", "kwargs", ")", ":", "return_tangent", "=", "kwargs", ".", "pop", "(", "'tangent'", ",", "False", ")", "con", ",", "transform", ",", "offset", "=", "ell", ".", "projection", "(", "*", "*", "kwargs", ...
Compute the half angle subtended (or min and max angles) for an offset elliptical conic from the origin or an arbitrary viewpoint. kwargs: tangent Return tangent instead of angle (default false) viewpoint Defaults to origin
[ "Compute", "the", "half", "angle", "subtended", "(", "or", "min", "and", "max", "angles", ")", "for", "an", "offset", "elliptical", "conic", "from", "the", "origin", "or", "an", "arbitrary", "viewpoint", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L8-L26
davenquinn/Attitude
attitude/geom/conics.py
Conic.from_axes
def from_axes(cls,axes): """ Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic """ ax = list(axes) #ax[-1] *= -1 # Not sure what is going on here... arr = N.diag(ax + [-1]) return arr.view(...
python
def from_axes(cls,axes): """ Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic """ ax = list(axes) #ax[-1] *= -1 # Not sure what is going on here... arr = N.diag(ax + [-1]) return arr.view(...
[ "def", "from_axes", "(", "cls", ",", "axes", ")", ":", "ax", "=", "list", "(", "axes", ")", "#ax[-1] *= -1 # Not sure what is going on here...", "arr", "=", "N", ".", "diag", "(", "ax", "+", "[", "-", "1", "]", ")", "return", "arr", ".", "view", "(", ...
Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic
[ "Get", "axis", "-", "aligned", "elliptical", "conic", "from", "axis", "lenths", "This", "can", "be", "converted", "into", "a", "hyperbola", "by", "getting", "the", "dual", "conic" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L30-L38
davenquinn/Attitude
attitude/geom/conics.py
Conic.from_semiaxes
def from_semiaxes(cls,axes): """ Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic """ ax = list(1/N.array(axes)**2) #ax[-1] *= -1 # Not sure what is going on here... arr = N.diag(ax + [-1]) ...
python
def from_semiaxes(cls,axes): """ Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic """ ax = list(1/N.array(axes)**2) #ax[-1] *= -1 # Not sure what is going on here... arr = N.diag(ax + [-1]) ...
[ "def", "from_semiaxes", "(", "cls", ",", "axes", ")", ":", "ax", "=", "list", "(", "1", "/", "N", ".", "array", "(", "axes", ")", "**", "2", ")", "#ax[-1] *= -1 # Not sure what is going on here...", "arr", "=", "N", ".", "diag", "(", "ax", "+", "[", ...
Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic
[ "Get", "axis", "-", "aligned", "elliptical", "conic", "from", "axis", "lenths", "This", "can", "be", "converted", "into", "a", "hyperbola", "by", "getting", "the", "dual", "conic" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L41-L49
davenquinn/Attitude
attitude/geom/conics.py
Conic.contains
def contains(ell, p, shell_only=False): """ Check to see whether point is inside conic. :param exact: Only solutions exactly on conic are considered (default: False). """ v = augment(p) _ = ell.solve(v) return N.allclose(_,0) if shell_only else ...
python
def contains(ell, p, shell_only=False): """ Check to see whether point is inside conic. :param exact: Only solutions exactly on conic are considered (default: False). """ v = augment(p) _ = ell.solve(v) return N.allclose(_,0) if shell_only else ...
[ "def", "contains", "(", "ell", ",", "p", ",", "shell_only", "=", "False", ")", ":", "v", "=", "augment", "(", "p", ")", "_", "=", "ell", ".", "solve", "(", "v", ")", "return", "N", ".", "allclose", "(", "_", ",", "0", ")", "if", "shell_only", ...
Check to see whether point is inside conic. :param exact: Only solutions exactly on conic are considered (default: False).
[ "Check", "to", "see", "whether", "point", "is", "inside", "conic", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L57-L67
davenquinn/Attitude
attitude/geom/conics.py
Conic.major_axes
def major_axes(ell): """ Gets major axes of ellipsoids """ _ = ell[:-1,:-1] U,s,V = N.linalg.svd(_) scalar = -(ell.sum()-_.sum()) return N.sqrt(s*scalar)*V
python
def major_axes(ell): """ Gets major axes of ellipsoids """ _ = ell[:-1,:-1] U,s,V = N.linalg.svd(_) scalar = -(ell.sum()-_.sum()) return N.sqrt(s*scalar)*V
[ "def", "major_axes", "(", "ell", ")", ":", "_", "=", "ell", "[", ":", "-", "1", ",", ":", "-", "1", "]", "U", ",", "s", ",", "V", "=", "N", ".", "linalg", ".", "svd", "(", "_", ")", "scalar", "=", "-", "(", "ell", ".", "sum", "(", ")", ...
Gets major axes of ellipsoids
[ "Gets", "major", "axes", "of", "ellipsoids" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L80-L87
davenquinn/Attitude
attitude/geom/conics.py
Conic.translate
def translate(conic, vector): """ Translates a conic by a vector """ # Translation matrix T = N.identity(len(conic)) T[:-1,-1] = -vector return conic.transform(T)
python
def translate(conic, vector): """ Translates a conic by a vector """ # Translation matrix T = N.identity(len(conic)) T[:-1,-1] = -vector return conic.transform(T)
[ "def", "translate", "(", "conic", ",", "vector", ")", ":", "# Translation matrix", "T", "=", "N", ".", "identity", "(", "len", "(", "conic", ")", ")", "T", "[", ":", "-", "1", ",", "-", "1", "]", "=", "-", "vector", "return", "conic", ".", "trans...
Translates a conic by a vector
[ "Translates", "a", "conic", "by", "a", "vector" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L120-L127
davenquinn/Attitude
attitude/geom/conics.py
Conic.polar_plane
def polar_plane(conic, vector): """ Calculates the polar plane to a vector (a 'pole') for a given conic section. For poles outside the conic, the polar plane contains all vectors of tangency to the pole. """ pole = augment(vector) return dot(conic,pole).vi...
python
def polar_plane(conic, vector): """ Calculates the polar plane to a vector (a 'pole') for a given conic section. For poles outside the conic, the polar plane contains all vectors of tangency to the pole. """ pole = augment(vector) return dot(conic,pole).vi...
[ "def", "polar_plane", "(", "conic", ",", "vector", ")", ":", "pole", "=", "augment", "(", "vector", ")", "return", "dot", "(", "conic", ",", "pole", ")", ".", "view", "(", "Plane", ")" ]
Calculates the polar plane to a vector (a 'pole') for a given conic section. For poles outside the conic, the polar plane contains all vectors of tangency to the pole.
[ "Calculates", "the", "polar", "plane", "to", "a", "vector", "(", "a", "pole", ")", "for", "a", "given", "conic", "section", ".", "For", "poles", "outside", "the", "conic", "the", "polar", "plane", "contains", "all", "vectors", "of", "tangency", "to", "th...
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L129-L137
davenquinn/Attitude
attitude/geom/conics.py
Conic.pole
def pole(conic, plane): """ Calculates the pole of a polar plane for a given conic section. """ v = dot(N.linalg.inv(conic),plane) return v[:-1]/v[-1]
python
def pole(conic, plane): """ Calculates the pole of a polar plane for a given conic section. """ v = dot(N.linalg.inv(conic),plane) return v[:-1]/v[-1]
[ "def", "pole", "(", "conic", ",", "plane", ")", ":", "v", "=", "dot", "(", "N", ".", "linalg", ".", "inv", "(", "conic", ")", ",", "plane", ")", "return", "v", "[", ":", "-", "1", "]", "/", "v", "[", "-", "1", "]" ]
Calculates the pole of a polar plane for a given conic section.
[ "Calculates", "the", "pole", "of", "a", "polar", "plane", "for", "a", "given", "conic", "section", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L139-L145
davenquinn/Attitude
attitude/geom/conics.py
Conic.projection
def projection(self, **kwargs): """ The elliptical cut of an ellipsoidal conic describing all points of tangency to the conic as viewed from the origin. """ viewpoint = kwargs.pop('viewpoint', None) if viewpoint is None: ndim = self.shape[0]-1 ...
python
def projection(self, **kwargs): """ The elliptical cut of an ellipsoidal conic describing all points of tangency to the conic as viewed from the origin. """ viewpoint = kwargs.pop('viewpoint', None) if viewpoint is None: ndim = self.shape[0]-1 ...
[ "def", "projection", "(", "self", ",", "*", "*", "kwargs", ")", ":", "viewpoint", "=", "kwargs", ".", "pop", "(", "'viewpoint'", ",", "None", ")", "if", "viewpoint", "is", "None", ":", "ndim", "=", "self", ".", "shape", "[", "0", "]", "-", "1", "...
The elliptical cut of an ellipsoidal conic describing all points of tangency to the conic as viewed from the origin.
[ "The", "elliptical", "cut", "of", "an", "ellipsoidal", "conic", "describing", "all", "points", "of", "tangency", "to", "the", "conic", "as", "viewed", "from", "the", "origin", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/conics.py#L181-L192
ivanprjcts/sdklib
sdklib/http/renderers.py
guess_file_name_stream_type_header
def guess_file_name_stream_type_header(args): """ Guess filename, file stream, file type, file header from args. :param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). :return: filena...
python
def guess_file_name_stream_type_header(args): """ Guess filename, file stream, file type, file header from args. :param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). :return: filena...
[ "def", "guess_file_name_stream_type_header", "(", "args", ")", ":", "ftype", "=", "None", "fheader", "=", "None", "if", "isinstance", "(", "args", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "len", "(", "args", ")", "==", "2", ":", "fname", ...
Guess filename, file stream, file type, file header from args. :param args: may be string (filepath), 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tuples (filename, fileobj, contentype, custom_headers). :return: filename, file stream, file type, file header
[ "Guess", "filename", "file", "stream", "file", "type", "file", "header", "from", "args", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/renderers.py#L52-L77
ivanprjcts/sdklib
sdklib/http/renderers.py
MultiPartRenderer.encode_params
def encode_params(self, data=None, files=None, **kwargs): """ Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a di...
python
def encode_params(self, data=None, files=None, **kwargs): """ Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a di...
[ "def", "encode_params", "(", "self", ",", "data", "=", "None", ",", "files", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "data", ",", "basestring", ")", ":", "raise", "ValueError", "(", "\"Data must not be a string.\"", ")", ...
Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be string (filepath), 2-tuples (filename, fileobj),...
[ "Build", "the", "body", "for", "a", "multipart", "/", "form", "-", "data", "request", ".", "Will", "successfully", "encode", "files", "when", "passed", "as", "a", "dict", "or", "a", "list", "of", "tuples", ".", "Order", "is", "retained", "if", "data", ...
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/renderers.py#L86-L137
ivanprjcts/sdklib
sdklib/http/renderers.py
FormRenderer.encode_params
def encode_params(self, data=None, **kwargs): """ Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """...
python
def encode_params(self, data=None, **kwargs): """ Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. """...
[ "def", "encode_params", "(", "self", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "collection_format", "=", "kwargs", ".", "get", "(", "\"collection_format\"", ",", "self", ".", "collection_format", ")", "output_str", "=", "kwargs", ".", "g...
Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict.
[ "Encode", "parameters", "in", "a", "piece", "of", "data", ".", "Will", "successfully", "encode", "parameters", "when", "passed", "as", "a", "dict", "or", "a", "list", "of", "2", "-", "tuples", ".", "Order", "is", "retained", "if", "data", "is", "a", "l...
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/renderers.py#L161-L203
ivanprjcts/sdklib
sdklib/http/renderers.py
PlainTextRenderer.encode_params
def encode_params(self, data=None, **kwargs): """ Build the body for a text/plain request. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. ...
python
def encode_params(self, data=None, **kwargs): """ Build the body for a text/plain request. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict. ...
[ "def", "encode_params", "(", "self", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "charset", "=", "kwargs", ".", "get", "(", "\"charset\"", ",", "self", ".", "charset", ")", "collection_format", "=", "kwargs", ".", "get", "(", "\"collec...
Build the body for a text/plain request. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict.
[ "Build", "the", "body", "for", "a", "text", "/", "plain", "request", ".", "Will", "successfully", "encode", "parameters", "when", "passed", "as", "a", "dict", "or", "a", "list", "of", "2", "-", "tuples", ".", "Order", "is", "retained", "if", "data", "i...
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/renderers.py#L236-L280
ivanprjcts/sdklib
sdklib/http/renderers.py
JSONRenderer.encode_params
def encode_params(self, data=None, **kwargs): """ Build the body for a application/json request. """ if isinstance(data, basestring): raise ValueError("Data must not be a string.") if data is None: return b"", self.content_type fields = to_key_val...
python
def encode_params(self, data=None, **kwargs): """ Build the body for a application/json request. """ if isinstance(data, basestring): raise ValueError("Data must not be a string.") if data is None: return b"", self.content_type fields = to_key_val...
[ "def", "encode_params", "(", "self", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "data", ",", "basestring", ")", ":", "raise", "ValueError", "(", "\"Data must not be a string.\"", ")", "if", "data", "is", "None", ...
Build the body for a application/json request.
[ "Build", "the", "body", "for", "a", "application", "/", "json", "request", "." ]
train
https://github.com/ivanprjcts/sdklib/blob/7ba4273a05c40e2e338f49f2dd564920ed98fcab/sdklib/http/renderers.py#L290-L305
RudolfCardinal/pythonlib
cardinal_pythonlib/cmdline.py
cmdline_split
def cmdline_split(s: str, platform: Union[int, str] = 'this') -> List[str]: """ As per https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex. Multi-platform variant of ``shlex.split()`` for command-line splitting. For use with ``subprocess``, for ``argv`` inje...
python
def cmdline_split(s: str, platform: Union[int, str] = 'this') -> List[str]: """ As per https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex. Multi-platform variant of ``shlex.split()`` for command-line splitting. For use with ``subprocess``, for ``argv`` inje...
[ "def", "cmdline_split", "(", "s", ":", "str", ",", "platform", ":", "Union", "[", "int", ",", "str", "]", "=", "'this'", ")", "->", "List", "[", "str", "]", ":", "# noqa", "if", "platform", "==", "'this'", ":", "platform", "=", "(", "sys", ".", "...
As per https://stackoverflow.com/questions/33560364/python-windows-parsing-command-lines-with-shlex. Multi-platform variant of ``shlex.split()`` for command-line splitting. For use with ``subprocess``, for ``argv`` injection etc. Using fast REGEX. Args: s: string to split ...
[ "As", "per", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "33560364", "/", "python", "-", "windows", "-", "parsing", "-", "command", "-", "lines", "-", "with", "-", "shlex", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/cmdline.py#L36-L90
davenquinn/Attitude
attitude/display/plot/cov_types/misc.py
percentiles
def percentiles(a, pcts, axis=None): """Like scoreatpercentile but can take and return array of percentiles. Parameters ---------- a : array data pcts : sequence of percentile values percentile or percentiles to find score at axis : int or None if not None, computes score...
python
def percentiles(a, pcts, axis=None): """Like scoreatpercentile but can take and return array of percentiles. Parameters ---------- a : array data pcts : sequence of percentile values percentile or percentiles to find score at axis : int or None if not None, computes score...
[ "def", "percentiles", "(", "a", ",", "pcts", ",", "axis", "=", "None", ")", ":", "scores", "=", "[", "]", "try", ":", "n", "=", "len", "(", "pcts", ")", "except", "TypeError", ":", "pcts", "=", "[", "pcts", "]", "n", "=", "0", "for", "i", ","...
Like scoreatpercentile but can take and return array of percentiles. Parameters ---------- a : array data pcts : sequence of percentile values percentile or percentiles to find score at axis : int or None if not None, computes scores over this axis Returns ------- ...
[ "Like", "scoreatpercentile", "but", "can", "take", "and", "return", "array", "of", "percentiles", ".", "Parameters", "----------", "a", ":", "array", "data", "pcts", ":", "sequence", "of", "percentile", "values", "percentile", "or", "percentiles", "to", "find", ...
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/plot/cov_types/misc.py#L6-L37
davenquinn/Attitude
attitude/display/plot/cov_types/misc.py
ci
def ci(a, which=95, axis=None): """Return a percentile range from an array of values.""" p = 50 - which / 2, 50 + which / 2 return percentiles(a, p, axis)
python
def ci(a, which=95, axis=None): """Return a percentile range from an array of values.""" p = 50 - which / 2, 50 + which / 2 return percentiles(a, p, axis)
[ "def", "ci", "(", "a", ",", "which", "=", "95", ",", "axis", "=", "None", ")", ":", "p", "=", "50", "-", "which", "/", "2", ",", "50", "+", "which", "/", "2", "return", "percentiles", "(", "a", ",", "p", ",", "axis", ")" ]
Return a percentile range from an array of values.
[ "Return", "a", "percentile", "range", "from", "an", "array", "of", "values", "." ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/plot/cov_types/misc.py#L40-L43
RudolfCardinal/pythonlib
cardinal_pythonlib/configfiles.py
get_config_string_option
def get_config_string_option(parser: ConfigParser, section: str, option: str, default: str = None) -> str: """ Retrieves a string value from a parser. Args: parser: instance of :class:`ConfigParser` secti...
python
def get_config_string_option(parser: ConfigParser, section: str, option: str, default: str = None) -> str: """ Retrieves a string value from a parser. Args: parser: instance of :class:`ConfigParser` secti...
[ "def", "get_config_string_option", "(", "parser", ":", "ConfigParser", ",", "section", ":", "str", ",", "option", ":", "str", ",", "default", ":", "str", "=", "None", ")", "->", "str", ":", "if", "not", "parser", ".", "has_section", "(", "section", ")", ...
Retrieves a string value from a parser. Args: parser: instance of :class:`ConfigParser` section: section name within config file option: option (variable) name within that section default: value to return if option is absent Returns: string value Raises: Va...
[ "Retrieves", "a", "string", "value", "from", "a", "parser", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L42-L64
RudolfCardinal/pythonlib
cardinal_pythonlib/configfiles.py
read_config_string_options
def read_config_string_options(obj: Any, parser: ConfigParser, section: str, options: Iterable[str], default: str = None) -> None: """ Reads config options and writes them as attributes of...
python
def read_config_string_options(obj: Any, parser: ConfigParser, section: str, options: Iterable[str], default: str = None) -> None: """ Reads config options and writes them as attributes of...
[ "def", "read_config_string_options", "(", "obj", ":", "Any", ",", "parser", ":", "ConfigParser", ",", "section", ":", "str", ",", "options", ":", "Iterable", "[", "str", "]", ",", "default", ":", "str", "=", "None", ")", "->", "None", ":", "# enforce_str...
Reads config options and writes them as attributes of ``obj``, with attribute names as per ``options``. Args: obj: the object to modify parser: instance of :class:`ConfigParser` section: section name within config file options: option (variable) names within that section ...
[ "Reads", "config", "options", "and", "writes", "them", "as", "attributes", "of", "obj", "with", "attribute", "names", "as", "per", "options", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L67-L90
RudolfCardinal/pythonlib
cardinal_pythonlib/configfiles.py
get_config_multiline_option
def get_config_multiline_option(parser: ConfigParser, section: str, option: str, default: List[str] = None) -> List[str]: """ Retrieves a multi-line string value from a parser as a list of strings (one per line, ...
python
def get_config_multiline_option(parser: ConfigParser, section: str, option: str, default: List[str] = None) -> List[str]: """ Retrieves a multi-line string value from a parser as a list of strings (one per line, ...
[ "def", "get_config_multiline_option", "(", "parser", ":", "ConfigParser", ",", "section", ":", "str", ",", "option", ":", "str", ",", "default", ":", "List", "[", "str", "]", "=", "None", ")", "->", "List", "[", "str", "]", ":", "default", "=", "defaul...
Retrieves a multi-line string value from a parser as a list of strings (one per line, ignoring blank lines). Args: parser: instance of :class:`ConfigParser` section: section name within config file option: option (variable) name within that section default: value to return if op...
[ "Retrieves", "a", "multi", "-", "line", "string", "value", "from", "a", "parser", "as", "a", "list", "of", "strings", "(", "one", "per", "line", "ignoring", "blank", "lines", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L93-L123
RudolfCardinal/pythonlib
cardinal_pythonlib/configfiles.py
read_config_multiline_options
def read_config_multiline_options(obj: Any, parser: ConfigParser, section: str, options: Iterable[str]) -> None: """ This is to :func:`read_config_string_options` as :func:`get_config_multiline_option` is t...
python
def read_config_multiline_options(obj: Any, parser: ConfigParser, section: str, options: Iterable[str]) -> None: """ This is to :func:`read_config_string_options` as :func:`get_config_multiline_option` is t...
[ "def", "read_config_multiline_options", "(", "obj", ":", "Any", ",", "parser", ":", "ConfigParser", ",", "section", ":", "str", ",", "options", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "for", "o", "in", "options", ":", "setattr", "(", ...
This is to :func:`read_config_string_options` as :func:`get_config_multiline_option` is to :func:`get_config_string_option`.
[ "This", "is", "to", ":", "func", ":", "read_config_string_options", "as", ":", "func", ":", "get_config_multiline_option", "is", "to", ":", "func", ":", "get_config_string_option", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L126-L135
RudolfCardinal/pythonlib
cardinal_pythonlib/configfiles.py
get_config_bool_option
def get_config_bool_option(parser: ConfigParser, section: str, option: str, default: bool = None) -> bool: """ Retrieves a boolean value from a parser. Args: parser: instance of :class:`ConfigParser` section: s...
python
def get_config_bool_option(parser: ConfigParser, section: str, option: str, default: bool = None) -> bool: """ Retrieves a boolean value from a parser. Args: parser: instance of :class:`ConfigParser` section: s...
[ "def", "get_config_bool_option", "(", "parser", ":", "ConfigParser", ",", "section", ":", "str", ",", "option", ":", "str", ",", "default", ":", "bool", "=", "None", ")", "->", "bool", ":", "if", "not", "parser", ".", "has_section", "(", "section", ")", ...
Retrieves a boolean value from a parser. Args: parser: instance of :class:`ConfigParser` section: section name within config file option: option (variable) name within that section default: value to return if option is absent Returns: string value Raises: V...
[ "Retrieves", "a", "boolean", "value", "from", "a", "parser", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L138-L160
RudolfCardinal/pythonlib
cardinal_pythonlib/configfiles.py
get_config_parameter
def get_config_parameter(config: ConfigParser, section: str, param: str, fn: Callable[[Any], Any], default: Any) -> Any: """ Fetch parameter from ``configparser`` ``.INI`` file. Args: config: :class:...
python
def get_config_parameter(config: ConfigParser, section: str, param: str, fn: Callable[[Any], Any], default: Any) -> Any: """ Fetch parameter from ``configparser`` ``.INI`` file. Args: config: :class:...
[ "def", "get_config_parameter", "(", "config", ":", "ConfigParser", ",", "section", ":", "str", ",", "param", ":", "str", ",", "fn", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", ",", "default", ":", "Any", ")", "->", "Any", ":", "try", ":...
Fetch parameter from ``configparser`` ``.INI`` file. Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section fn: function to apply to string parameter (e.g. ``int``) default: default value Returns: ...
[ "Fetch", "parameter", "from", "configparser", ".", "INI", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L171-L199
RudolfCardinal/pythonlib
cardinal_pythonlib/configfiles.py
get_config_parameter_boolean
def get_config_parameter_boolean(config: ConfigParser, section: str, param: str, default: bool) -> bool: """ Get Boolean parameter from ``configparser`` ``.INI`` file. Args: config: :class:`ConfigPars...
python
def get_config_parameter_boolean(config: ConfigParser, section: str, param: str, default: bool) -> bool: """ Get Boolean parameter from ``configparser`` ``.INI`` file. Args: config: :class:`ConfigPars...
[ "def", "get_config_parameter_boolean", "(", "config", ":", "ConfigParser", ",", "section", ":", "str", ",", "param", ":", "str", ",", "default", ":", "bool", ")", "->", "bool", ":", "try", ":", "value", "=", "config", ".", "getboolean", "(", "section", "...
Get Boolean parameter from ``configparser`` ``.INI`` file. Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section default: default value Returns: parameter value, or default
[ "Get", "Boolean", "parameter", "from", "configparser", ".", "INI", "file", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L202-L224
RudolfCardinal/pythonlib
cardinal_pythonlib/configfiles.py
get_config_parameter_loglevel
def get_config_parameter_loglevel(config: ConfigParser, section: str, param: str, default: int) -> int: """ Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g. mapping ``'debug'`` to ``logg...
python
def get_config_parameter_loglevel(config: ConfigParser, section: str, param: str, default: int) -> int: """ Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g. mapping ``'debug'`` to ``logg...
[ "def", "get_config_parameter_loglevel", "(", "config", ":", "ConfigParser", ",", "section", ":", "str", ",", "param", ":", "str", ",", "default", ":", "int", ")", "->", "int", ":", "try", ":", "value", "=", "config", ".", "get", "(", "section", ",", "p...
Get ``loglevel`` parameter from ``configparser`` ``.INI`` file, e.g. mapping ``'debug'`` to ``logging.DEBUG``. Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section default: default value Returns: ...
[ "Get", "loglevel", "parameter", "from", "configparser", ".", "INI", "file", "e", ".", "g", ".", "mapping", "debug", "to", "logging", ".", "DEBUG", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L227-L261
RudolfCardinal/pythonlib
cardinal_pythonlib/configfiles.py
get_config_parameter_multiline
def get_config_parameter_multiline(config: ConfigParser, section: str, param: str, default: List[str]) -> List[str]: """ Get multi-line string parameter from ``configparser`` ``.INI`` file, as a list of ...
python
def get_config_parameter_multiline(config: ConfigParser, section: str, param: str, default: List[str]) -> List[str]: """ Get multi-line string parameter from ``configparser`` ``.INI`` file, as a list of ...
[ "def", "get_config_parameter_multiline", "(", "config", ":", "ConfigParser", ",", "section", ":", "str", ",", "param", ":", "str", ",", "default", ":", "List", "[", "str", "]", ")", "->", "List", "[", "str", "]", ":", "try", ":", "multiline", "=", "con...
Get multi-line string parameter from ``configparser`` ``.INI`` file, as a list of strings (one per line, ignoring blank lines). Args: config: :class:`ConfigParser` object section: section name within config file param: name of parameter within section default: default value ...
[ "Get", "multi", "-", "line", "string", "parameter", "from", "configparser", ".", "INI", "file", "as", "a", "list", "of", "strings", "(", "one", "per", "line", "ignoring", "blank", "lines", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/configfiles.py#L264-L288
AndrewWalker/glud
glud/predicates.py
is_definition
def is_definition(cursor): """Test if a cursor refers to a definition This occurs when the cursor has a definition, and shares the location of that definiton """ defn = cursor.get_definition() return (defn is not None) and (cursor.location == defn.location)
python
def is_definition(cursor): """Test if a cursor refers to a definition This occurs when the cursor has a definition, and shares the location of that definiton """ defn = cursor.get_definition() return (defn is not None) and (cursor.location == defn.location)
[ "def", "is_definition", "(", "cursor", ")", ":", "defn", "=", "cursor", ".", "get_definition", "(", ")", "return", "(", "defn", "is", "not", "None", ")", "and", "(", "cursor", ".", "location", "==", "defn", ".", "location", ")" ]
Test if a cursor refers to a definition This occurs when the cursor has a definition, and shares the location of that definiton
[ "Test", "if", "a", "cursor", "refers", "to", "a", "definition" ]
train
https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/predicates.py#L38-L44
davenquinn/Attitude
attitude/error/__init__.py
asymptotes
def asymptotes(hyp, n=1000): """ Gets a cone of asymptotes for hyperbola """ assert N.linalg.norm(hyp.center()) == 0 u = N.linspace(0,2*N.pi,n) _ = N.ones(len(u)) angles = N.array([N.cos(u),N.sin(u),_]).T return dot(angles,hyp[:-1,:-1])
python
def asymptotes(hyp, n=1000): """ Gets a cone of asymptotes for hyperbola """ assert N.linalg.norm(hyp.center()) == 0 u = N.linspace(0,2*N.pi,n) _ = N.ones(len(u)) angles = N.array([N.cos(u),N.sin(u),_]).T return dot(angles,hyp[:-1,:-1])
[ "def", "asymptotes", "(", "hyp", ",", "n", "=", "1000", ")", ":", "assert", "N", ".", "linalg", ".", "norm", "(", "hyp", ".", "center", "(", ")", ")", "==", "0", "u", "=", "N", ".", "linspace", "(", "0", ",", "2", "*", "N", ".", "pi", ",", ...
Gets a cone of asymptotes for hyperbola
[ "Gets", "a", "cone", "of", "asymptotes", "for", "hyperbola" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/__init__.py#L12-L21
davenquinn/Attitude
attitude/error/__init__.py
pca_to_mapping
def pca_to_mapping(pca,**extra_props): """ A helper to return a mapping of a PCA result set suitable for reconstructing a planar error surface in other software packages kwargs: method (defaults to sampling axes) """ from .axes import sampling_axes method = extra_props.pop('method',sampling...
python
def pca_to_mapping(pca,**extra_props): """ A helper to return a mapping of a PCA result set suitable for reconstructing a planar error surface in other software packages kwargs: method (defaults to sampling axes) """ from .axes import sampling_axes method = extra_props.pop('method',sampling...
[ "def", "pca_to_mapping", "(", "pca", ",", "*", "*", "extra_props", ")", ":", "from", ".", "axes", "import", "sampling_axes", "method", "=", "extra_props", ".", "pop", "(", "'method'", ",", "sampling_axes", ")", "return", "dict", "(", "axes", "=", "pca", ...
A helper to return a mapping of a PCA result set suitable for reconstructing a planar error surface in other software packages kwargs: method (defaults to sampling axes)
[ "A", "helper", "to", "return", "a", "mapping", "of", "a", "PCA", "result", "set", "suitable", "for", "reconstructing", "a", "planar", "error", "surface", "in", "other", "software", "packages" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/__init__.py#L23-L35
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
generic_service_main
def generic_service_main(cls: Type[WindowsService], name: str) -> None: """ Call this from your command-line entry point to manage a service. - Via inherited functions, enables you to ``install``, ``update``, ``remove``, ``start``, ``stop``, and ``restart`` the service. - Via our additional code,...
python
def generic_service_main(cls: Type[WindowsService], name: str) -> None: """ Call this from your command-line entry point to manage a service. - Via inherited functions, enables you to ``install``, ``update``, ``remove``, ``start``, ``stop``, and ``restart`` the service. - Via our additional code,...
[ "def", "generic_service_main", "(", "cls", ":", "Type", "[", "WindowsService", "]", ",", "name", ":", "str", ")", "->", "None", ":", "argc", "=", "len", "(", "sys", ".", "argv", ")", "if", "argc", "==", "1", ":", "try", ":", "print", "(", "\"Trying...
Call this from your command-line entry point to manage a service. - Via inherited functions, enables you to ``install``, ``update``, ``remove``, ``start``, ``stop``, and ``restart`` the service. - Via our additional code, allows you to run the service function directly from the command line in debu...
[ "Call", "this", "from", "your", "command", "-", "line", "entry", "point", "to", "manage", "a", "service", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L1004-L1042
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager.fullname
def fullname(self) -> str: """ Description of the process. """ fullname = "Process {}/{} ({})".format(self.procnum, self.nprocs, self.details.name) if self.running: fullname += " (PID={})".format(self.process.pid) ...
python
def fullname(self) -> str: """ Description of the process. """ fullname = "Process {}/{} ({})".format(self.procnum, self.nprocs, self.details.name) if self.running: fullname += " (PID={})".format(self.process.pid) ...
[ "def", "fullname", "(", "self", ")", "->", "str", ":", "fullname", "=", "\"Process {}/{} ({})\"", ".", "format", "(", "self", ".", "procnum", ",", "self", ".", "nprocs", ",", "self", ".", "details", ".", "name", ")", "if", "self", ".", "running", ":", ...
Description of the process.
[ "Description", "of", "the", "process", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L375-L383
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager.debug
def debug(self, msg: str) -> None: """ If we are being verbose, write a debug message to the Python disk log. """ if self.debugging: s = "{}: {}".format(self.fullname, msg) log.debug(s)
python
def debug(self, msg: str) -> None: """ If we are being verbose, write a debug message to the Python disk log. """ if self.debugging: s = "{}: {}".format(self.fullname, msg) log.debug(s)
[ "def", "debug", "(", "self", ",", "msg", ":", "str", ")", "->", "None", ":", "if", "self", ".", "debugging", ":", "s", "=", "\"{}: {}\"", ".", "format", "(", "self", ".", "fullname", ",", "msg", ")", "log", ".", "debug", "(", "s", ")" ]
If we are being verbose, write a debug message to the Python disk log.
[ "If", "we", "are", "being", "verbose", "write", "a", "debug", "message", "to", "the", "Python", "disk", "log", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L389-L395
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager.info
def info(self, msg: str) -> None: """ Write an info message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences s = "{}: {}".format(self.fullname, msg) servicemanager.LogInfoMsg(s) if self.debugging: ...
python
def info(self, msg: str) -> None: """ Write an info message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences s = "{}: {}".format(self.fullname, msg) servicemanager.LogInfoMsg(s) if self.debugging: ...
[ "def", "info", "(", "self", ",", "msg", ":", "str", ")", "->", "None", ":", "# noinspection PyUnresolvedReferences", "s", "=", "\"{}: {}\"", ".", "format", "(", "self", ".", "fullname", ",", "msg", ")", "servicemanager", ".", "LogInfoMsg", "(", "s", ")", ...
Write an info message to the Windows Application log (± to the Python disk log).
[ "Write", "an", "info", "message", "to", "the", "Windows", "Application", "log", "(", "±", "to", "the", "Python", "disk", "log", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L397-L406
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager.warning
def warning(self, msg: str) -> None: """ Write a warning message to the Windows Application log (± to the Python disk log). """ # Log messages go to the Windows APPLICATION log. # noinspection PyUnresolvedReferences s = "{}: {}".format(self.fullname, msg) ...
python
def warning(self, msg: str) -> None: """ Write a warning message to the Windows Application log (± to the Python disk log). """ # Log messages go to the Windows APPLICATION log. # noinspection PyUnresolvedReferences s = "{}: {}".format(self.fullname, msg) ...
[ "def", "warning", "(", "self", ",", "msg", ":", "str", ")", "->", "None", ":", "# Log messages go to the Windows APPLICATION log.", "# noinspection PyUnresolvedReferences", "s", "=", "\"{}: {}\"", ".", "format", "(", "self", ".", "fullname", ",", "msg", ")", "serv...
Write a warning message to the Windows Application log (± to the Python disk log).
[ "Write", "a", "warning", "message", "to", "the", "Windows", "Application", "log", "(", "±", "to", "the", "Python", "disk", "log", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L408-L418
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager.error
def error(self, msg: str) -> None: """ Write an error message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences s = "{}: {}".format(self.fullname, msg) servicemanager.LogErrorMsg(s) if self.debugging: ...
python
def error(self, msg: str) -> None: """ Write an error message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences s = "{}: {}".format(self.fullname, msg) servicemanager.LogErrorMsg(s) if self.debugging: ...
[ "def", "error", "(", "self", ",", "msg", ":", "str", ")", "->", "None", ":", "# noinspection PyUnresolvedReferences", "s", "=", "\"{}: {}\"", ".", "format", "(", "self", ".", "fullname", ",", "msg", ")", "servicemanager", ".", "LogErrorMsg", "(", "s", ")",...
Write an error message to the Windows Application log (± to the Python disk log).
[ "Write", "an", "error", "message", "to", "the", "Windows", "Application", "log", "(", "±", "to", "the", "Python", "disk", "log", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L420-L429
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager.open_logs
def open_logs(self) -> None: """ Open Python disk logs. """ if self.details.logfile_out: self.stdout = open(self.details.logfile_out, 'a') else: self.stdout = None if self.details.logfile_err: if self.details.logfile_err == self.details...
python
def open_logs(self) -> None: """ Open Python disk logs. """ if self.details.logfile_out: self.stdout = open(self.details.logfile_out, 'a') else: self.stdout = None if self.details.logfile_err: if self.details.logfile_err == self.details...
[ "def", "open_logs", "(", "self", ")", "->", "None", ":", "if", "self", ".", "details", ".", "logfile_out", ":", "self", ".", "stdout", "=", "open", "(", "self", ".", "details", ".", "logfile_out", ",", "'a'", ")", "else", ":", "self", ".", "stdout", ...
Open Python disk logs.
[ "Open", "Python", "disk", "logs", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L431-L445
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager.close_logs
def close_logs(self) -> None: """ Close Python disk logs. """ if self.stdout is not None: self.stdout.close() self.stdout = None if self.stderr is not None and self.stderr != subprocess.STDOUT: self.stderr.close() self.stderr = None
python
def close_logs(self) -> None: """ Close Python disk logs. """ if self.stdout is not None: self.stdout.close() self.stdout = None if self.stderr is not None and self.stderr != subprocess.STDOUT: self.stderr.close() self.stderr = None
[ "def", "close_logs", "(", "self", ")", "->", "None", ":", "if", "self", ".", "stdout", "is", "not", "None", ":", "self", ".", "stdout", ".", "close", "(", ")", "self", ".", "stdout", "=", "None", "if", "self", ".", "stderr", "is", "not", "None", ...
Close Python disk logs.
[ "Close", "Python", "disk", "logs", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L447-L456
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager.start
def start(self) -> None: """ Starts a subprocess. Optionally routes its output to our disk logs. """ if self.running: return self.info("Starting: {} (with logs stdout={}, stderr={})".format( self.details.procargs, self.details.logfile_out, ...
python
def start(self) -> None: """ Starts a subprocess. Optionally routes its output to our disk logs. """ if self.running: return self.info("Starting: {} (with logs stdout={}, stderr={})".format( self.details.procargs, self.details.logfile_out, ...
[ "def", "start", "(", "self", ")", "->", "None", ":", "if", "self", ".", "running", ":", "return", "self", ".", "info", "(", "\"Starting: {} (with logs stdout={}, stderr={})\"", ".", "format", "(", "self", ".", "details", ".", "procargs", ",", "self", ".", ...
Starts a subprocess. Optionally routes its output to our disk logs.
[ "Starts", "a", "subprocess", ".", "Optionally", "routes", "its", "output", "to", "our", "disk", "logs", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L462-L478
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager.stop
def stop(self) -> None: """ Stops a subprocess. Asks nicely. Waits. Asks less nicely. Repeat until subprocess is dead. .. todo:: cardinal_pythonlib.winservice.ProcessManager._kill: make it reliable under Windows """ if not self.running: ...
python
def stop(self) -> None: """ Stops a subprocess. Asks nicely. Waits. Asks less nicely. Repeat until subprocess is dead. .. todo:: cardinal_pythonlib.winservice.ProcessManager._kill: make it reliable under Windows """ if not self.running: ...
[ "def", "stop", "(", "self", ")", "->", "None", ":", "if", "not", "self", ".", "running", ":", "return", "try", ":", "self", ".", "wait", "(", "timeout_s", "=", "0", ")", "# If we get here: stopped already", "except", "subprocess", ".", "TimeoutExpired", ":...
Stops a subprocess. Asks nicely. Waits. Asks less nicely. Repeat until subprocess is dead. .. todo:: cardinal_pythonlib.winservice.ProcessManager._kill: make it reliable under Windows
[ "Stops", "a", "subprocess", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L480-L506
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager._terminate
def _terminate(self, level: int) -> bool: """ Returns: succeeded in *attempting* a kill? """ if not self.running: return True # Already closed by itself? try: self.wait(0) return True except subprocess.TimeoutExpired: # failed...
python
def _terminate(self, level: int) -> bool: """ Returns: succeeded in *attempting* a kill? """ if not self.running: return True # Already closed by itself? try: self.wait(0) return True except subprocess.TimeoutExpired: # failed...
[ "def", "_terminate", "(", "self", ",", "level", ":", "int", ")", "->", "bool", ":", "if", "not", "self", ".", "running", ":", "return", "True", "# Already closed by itself?", "try", ":", "self", ".", "wait", "(", "0", ")", "return", "True", "except", "...
Returns: succeeded in *attempting* a kill?
[ "Returns", ":", "succeeded", "in", "*", "attempting", "*", "a", "kill?" ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L508-L569
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager._taskkill
def _taskkill(self, force: bool = False) -> int: """ Executes a Windows ``TASKKILL /pid PROCESS_ID /t`` command (``/t`` for "tree kill" = "kill all children"). Args: force: also add ``/f`` (forcefully) Returns: return code from ``TASKKILL`` **Te...
python
def _taskkill(self, force: bool = False) -> int: """ Executes a Windows ``TASKKILL /pid PROCESS_ID /t`` command (``/t`` for "tree kill" = "kill all children"). Args: force: also add ``/f`` (forcefully) Returns: return code from ``TASKKILL`` **Te...
[ "def", "_taskkill", "(", "self", ",", "force", ":", "bool", "=", "False", ")", "->", "int", ":", "# noqa", "args", "=", "[", "\"taskkill\"", ",", "# built in to Windows XP and higher", "\"/pid\"", ",", "str", "(", "self", ".", "process", ".", "pid", ")", ...
Executes a Windows ``TASKKILL /pid PROCESS_ID /t`` command (``/t`` for "tree kill" = "kill all children"). Args: force: also add ``/f`` (forcefully) Returns: return code from ``TASKKILL`` **Test code:** Firstly we need a program that won't let itself b...
[ "Executes", "a", "Windows", "TASKKILL", "/", "pid", "PROCESS_ID", "/", "t", "command", "(", "/", "t", "for", "tree", "kill", "=", "kill", "all", "children", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L571-L675
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager._kill
def _kill(self) -> None: """ Hard kill. - PROBLEM: originally, via ``self.process.kill()``, could leave orphans under Windows. - SOLUTION: see https://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows, which uses ``p...
python
def _kill(self) -> None: """ Hard kill. - PROBLEM: originally, via ``self.process.kill()``, could leave orphans under Windows. - SOLUTION: see https://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows, which uses ``p...
[ "def", "_kill", "(", "self", ")", "->", "None", ":", "# noqa", "self", ".", "warning", "(", "\"Using a recursive hard kill; will assume it worked\"", ")", "pid", "=", "self", ".", "process", ".", "pid", "gone", ",", "still_alive", "=", "kill_proc_tree", "(", "...
Hard kill. - PROBLEM: originally, via ``self.process.kill()``, could leave orphans under Windows. - SOLUTION: see https://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows, which uses ``psutil``.
[ "Hard", "kill", ".", "-", "PROBLEM", ":", "originally", "via", "self", ".", "process", ".", "kill", "()", "could", "leave", "orphans", "under", "Windows", ".", "-", "SOLUTION", ":", "see", "https", ":", "//", "stackoverflow", ".", "com", "/", "questions"...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L677-L693
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
ProcessManager.wait
def wait(self, timeout_s: float = None) -> int: """ Wait for up to ``timeout_s`` for the child process to finish. Args: timeout_s: maximum time to wait or ``None`` to wait forever Returns: process return code; or ``0`` if it wasn't running, or ``1`` if ...
python
def wait(self, timeout_s: float = None) -> int: """ Wait for up to ``timeout_s`` for the child process to finish. Args: timeout_s: maximum time to wait or ``None`` to wait forever Returns: process return code; or ``0`` if it wasn't running, or ``1`` if ...
[ "def", "wait", "(", "self", ",", "timeout_s", ":", "float", "=", "None", ")", "->", "int", ":", "if", "not", "self", ".", "running", ":", "return", "0", "retcode", "=", "self", ".", "process", ".", "wait", "(", "timeout", "=", "timeout_s", ")", "# ...
Wait for up to ``timeout_s`` for the child process to finish. Args: timeout_s: maximum time to wait or ``None`` to wait forever Returns: process return code; or ``0`` if it wasn't running, or ``1`` if it managed to exit without a return code Raises: ...
[ "Wait", "for", "up", "to", "timeout_s", "for", "the", "child", "process", "to", "finish", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L695-L727
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
WindowsService.info
def info(self, msg: str) -> None: """ Write an info message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences servicemanager.LogInfoMsg(str(msg)) if self.debugging: log.info(msg)
python
def info(self, msg: str) -> None: """ Write an info message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences servicemanager.LogInfoMsg(str(msg)) if self.debugging: log.info(msg)
[ "def", "info", "(", "self", ",", "msg", ":", "str", ")", "->", "None", ":", "# noinspection PyUnresolvedReferences", "servicemanager", ".", "LogInfoMsg", "(", "str", "(", "msg", ")", ")", "if", "self", ".", "debugging", ":", "log", ".", "info", "(", "msg...
Write an info message to the Windows Application log (± to the Python disk log).
[ "Write", "an", "info", "message", "to", "the", "Windows", "Application", "log", "(", "±", "to", "the", "Python", "disk", "log", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L787-L795
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
WindowsService.error
def error(self, msg: str) -> None: """ Write an error message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences servicemanager.LogErrorMsg(str(msg)) if self.debugging: log.error(msg)
python
def error(self, msg: str) -> None: """ Write an error message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences servicemanager.LogErrorMsg(str(msg)) if self.debugging: log.error(msg)
[ "def", "error", "(", "self", ",", "msg", ":", "str", ")", "->", "None", ":", "# noinspection PyUnresolvedReferences", "servicemanager", ".", "LogErrorMsg", "(", "str", "(", "msg", ")", ")", "if", "self", ".", "debugging", ":", "log", ".", "error", "(", "...
Write an error message to the Windows Application log (± to the Python disk log).
[ "Write", "an", "error", "message", "to", "the", "Windows", "Application", "log", "(", "±", "to", "the", "Python", "disk", "log", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L797-L805
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
WindowsService.SvcStop
def SvcStop(self) -> None: """ Called when the service is being shut down. """ # tell the SCM we're shutting down # noinspection PyUnresolvedReferences self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # fire the stop event win32event.SetEvent(se...
python
def SvcStop(self) -> None: """ Called when the service is being shut down. """ # tell the SCM we're shutting down # noinspection PyUnresolvedReferences self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # fire the stop event win32event.SetEvent(se...
[ "def", "SvcStop", "(", "self", ")", "->", "None", ":", "# tell the SCM we're shutting down", "# noinspection PyUnresolvedReferences", "self", ".", "ReportServiceStatus", "(", "win32service", ".", "SERVICE_STOP_PENDING", ")", "# fire the stop event", "win32event", ".", "SetE...
Called when the service is being shut down.
[ "Called", "when", "the", "service", "is", "being", "shut", "down", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L812-L820
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
WindowsService.SvcDoRun
def SvcDoRun(self) -> None: """ Called when the service is started. """ # No need to self.ReportServiceStatus(win32service.SERVICE_RUNNING); # that is done by the framework (see win32serviceutil.py). # Similarly, no need to report a SERVICE_STOP_PENDING on exit. #...
python
def SvcDoRun(self) -> None: """ Called when the service is started. """ # No need to self.ReportServiceStatus(win32service.SERVICE_RUNNING); # that is done by the framework (see win32serviceutil.py). # Similarly, no need to report a SERVICE_STOP_PENDING on exit. #...
[ "def", "SvcDoRun", "(", "self", ")", "->", "None", ":", "# No need to self.ReportServiceStatus(win32service.SERVICE_RUNNING);", "# that is done by the framework (see win32serviceutil.py).", "# Similarly, no need to report a SERVICE_STOP_PENDING on exit.", "# noinspection PyUnresolvedReferences...
Called when the service is started.
[ "Called", "when", "the", "service", "is", "started", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L824-L846
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
WindowsService.main
def main(self) -> None: """ Main entry point. Runs :func:`service`. """ # Actual main service code. try: self.service() except Exception as e: self.error("Unexpected exception: {e}\n{t}".format( e=e, t=traceback.format_exc()))
python
def main(self) -> None: """ Main entry point. Runs :func:`service`. """ # Actual main service code. try: self.service() except Exception as e: self.error("Unexpected exception: {e}\n{t}".format( e=e, t=traceback.format_exc()))
[ "def", "main", "(", "self", ")", "->", "None", ":", "# Actual main service code.", "try", ":", "self", ".", "service", "(", ")", "except", "Exception", "as", "e", ":", "self", ".", "error", "(", "\"Unexpected exception: {e}\\n{t}\"", ".", "format", "(", "e",...
Main entry point. Runs :func:`service`.
[ "Main", "entry", "point", ".", "Runs", ":", "func", ":", "service", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L895-L904
RudolfCardinal/pythonlib
cardinal_pythonlib/winservice.py
WindowsService.run_processes
def run_processes(self, procdetails: List[ProcessDetails], subproc_run_timeout_sec: float = 1, stop_event_timeout_ms: int = 1000, kill_timeout_sec: float = 5) -> None: """ Run multiple child processes. Args:...
python
def run_processes(self, procdetails: List[ProcessDetails], subproc_run_timeout_sec: float = 1, stop_event_timeout_ms: int = 1000, kill_timeout_sec: float = 5) -> None: """ Run multiple child processes. Args:...
[ "def", "run_processes", "(", "self", ",", "procdetails", ":", "List", "[", "ProcessDetails", "]", ",", "subproc_run_timeout_sec", ":", "float", "=", "1", ",", "stop_event_timeout_ms", ":", "int", "=", "1000", ",", "kill_timeout_sec", ":", "float", "=", "5", ...
Run multiple child processes. Args: procdetails: list of :class:`ProcessDetails` objects (q.v.) subproc_run_timeout_sec: time (in seconds) to wait for each process when polling child processes to see how they're getting on (default ``1``) sto...
[ "Run", "multiple", "child", "processes", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/winservice.py#L912-L997
RudolfCardinal/pythonlib
cardinal_pythonlib/exceptions.py
add_info_to_exception
def add_info_to_exception(err: Exception, info: Dict) -> None: """ Adds an information dictionary to an exception. See http://stackoverflow.com/questions/9157210/how-do-i-raise-the-same-exception-with-a-custom-message-in-python Args: err: the exception to be modified info: ...
python
def add_info_to_exception(err: Exception, info: Dict) -> None: """ Adds an information dictionary to an exception. See http://stackoverflow.com/questions/9157210/how-do-i-raise-the-same-exception-with-a-custom-message-in-python Args: err: the exception to be modified info: ...
[ "def", "add_info_to_exception", "(", "err", ":", "Exception", ",", "info", ":", "Dict", ")", "->", "None", ":", "# noqa", "if", "not", "err", ".", "args", ":", "err", ".", "args", "=", "(", "''", ",", ")", "err", ".", "args", "+=", "(", "info", "...
Adds an information dictionary to an exception. See http://stackoverflow.com/questions/9157210/how-do-i-raise-the-same-exception-with-a-custom-message-in-python Args: err: the exception to be modified info: the information to add
[ "Adds", "an", "information", "dictionary", "to", "an", "exception", ".", "See", "http", ":", "//", "stackoverflow", ".", "com", "/", "questions", "/", "9157210", "/", "how", "-", "do", "-", "i", "-", "raise", "-", "the", "-", "same", "-", "exception", ...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/exceptions.py#L42-L55
RudolfCardinal/pythonlib
cardinal_pythonlib/exceptions.py
recover_info_from_exception
def recover_info_from_exception(err: Exception) -> Dict: """ Retrives the information added to an exception by :func:`add_info_to_exception`. """ if len(err.args) < 1: return {} info = err.args[-1] if not isinstance(info, dict): return {} return info
python
def recover_info_from_exception(err: Exception) -> Dict: """ Retrives the information added to an exception by :func:`add_info_to_exception`. """ if len(err.args) < 1: return {} info = err.args[-1] if not isinstance(info, dict): return {} return info
[ "def", "recover_info_from_exception", "(", "err", ":", "Exception", ")", "->", "Dict", ":", "if", "len", "(", "err", ".", "args", ")", "<", "1", ":", "return", "{", "}", "info", "=", "err", ".", "args", "[", "-", "1", "]", "if", "not", "isinstance"...
Retrives the information added to an exception by :func:`add_info_to_exception`.
[ "Retrives", "the", "information", "added", "to", "an", "exception", "by", ":", "func", ":", "add_info_to_exception", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/exceptions.py#L58-L68
RudolfCardinal/pythonlib
cardinal_pythonlib/exceptions.py
die
def die(exc: Exception = None, exit_code: int = 1) -> None: """ It is not clear that Python guarantees to exit with a non-zero exit code (errorlevel in DOS/Windows) upon an unhandled exception. So this function produces the usual stack trace then dies with the specified exit code. See http://st...
python
def die(exc: Exception = None, exit_code: int = 1) -> None: """ It is not clear that Python guarantees to exit with a non-zero exit code (errorlevel in DOS/Windows) upon an unhandled exception. So this function produces the usual stack trace then dies with the specified exit code. See http://st...
[ "def", "die", "(", "exc", ":", "Exception", "=", "None", ",", "exit_code", ":", "int", "=", "1", ")", "->", "None", ":", "# noqa", "if", "exc", ":", "lines", "=", "traceback", ".", "format_exception", "(", "None", ",", "# etype: ignored", "exc", ",", ...
It is not clear that Python guarantees to exit with a non-zero exit code (errorlevel in DOS/Windows) upon an unhandled exception. So this function produces the usual stack trace then dies with the specified exit code. See http://stackoverflow.com/questions/9555133/e-printstacktrace-equivalent-in-python...
[ "It", "is", "not", "clear", "that", "Python", "guarantees", "to", "exit", "with", "a", "non", "-", "zero", "exit", "code", "(", "errorlevel", "in", "DOS", "/", "Windows", ")", "upon", "an", "unhandled", "exception", ".", "So", "this", "function", "produc...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/exceptions.py#L71-L120
henzk/featuremonkey
featuremonkey/tracing/serializer.py
_serialize_function
def _serialize_function(obj): """ Still needing this much try-except stuff. We should find a way to get rid of this. :param obj: :return: """ try: obj = inspect.getsource(obj) except (TypeError, IOError): try: obj = marshal.dumps(obj) except ValueError: ...
python
def _serialize_function(obj): """ Still needing this much try-except stuff. We should find a way to get rid of this. :param obj: :return: """ try: obj = inspect.getsource(obj) except (TypeError, IOError): try: obj = marshal.dumps(obj) except ValueError: ...
[ "def", "_serialize_function", "(", "obj", ")", ":", "try", ":", "obj", "=", "inspect", ".", "getsource", "(", "obj", ")", "except", "(", "TypeError", ",", "IOError", ")", ":", "try", ":", "obj", "=", "marshal", ".", "dumps", "(", "obj", ")", "except"...
Still needing this much try-except stuff. We should find a way to get rid of this. :param obj: :return:
[ "Still", "needing", "this", "much", "try", "-", "except", "stuff", ".", "We", "should", "find", "a", "way", "to", "get", "rid", "of", "this", ".", ":", "param", "obj", ":", ":", "return", ":" ]
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/tracing/serializer.py#L52-L66
henzk/featuremonkey
featuremonkey/tracing/serializer.py
_serialize_module
def _serialize_module(obj): """ Tries to serialize a module by its __dict__ attr. Remove the builtins attr as this one is not relevant and extremely large. If its value is a callable, serialize it using serialize_obj, else, use its repr, because in this case we most likely run into max recursion dep...
python
def _serialize_module(obj): """ Tries to serialize a module by its __dict__ attr. Remove the builtins attr as this one is not relevant and extremely large. If its value is a callable, serialize it using serialize_obj, else, use its repr, because in this case we most likely run into max recursion dep...
[ "def", "_serialize_module", "(", "obj", ")", ":", "obj", "=", "dict", "(", "obj", ".", "__dict__", ")", "if", "'__builtins__'", "in", "obj", ".", "keys", "(", ")", ":", "obj", ".", "pop", "(", "'__builtins__'", ")", "for", "k", ",", "v", "in", "obj...
Tries to serialize a module by its __dict__ attr. Remove the builtins attr as this one is not relevant and extremely large. If its value is a callable, serialize it using serialize_obj, else, use its repr, because in this case we most likely run into max recursion depth errors. :param obj: :return:
[ "Tries", "to", "serialize", "a", "module", "by", "its", "__dict__", "attr", ".", "Remove", "the", "builtins", "attr", "as", "this", "one", "is", "not", "relevant", "and", "extremely", "large", ".", "If", "its", "value", "is", "a", "callable", "serialize", ...
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/tracing/serializer.py#L69-L86
henzk/featuremonkey
featuremonkey/tracing/serializer.py
_serialize_iterable
def _serialize_iterable(obj): """ Only for serializing list and tuples and stuff. Dicts and Strings/Unicode is treated differently. String/Unicode normally don't need further serialization and it would cause a max recursion error trying to do so. :param obj: :return: """ if isinstanc...
python
def _serialize_iterable(obj): """ Only for serializing list and tuples and stuff. Dicts and Strings/Unicode is treated differently. String/Unicode normally don't need further serialization and it would cause a max recursion error trying to do so. :param obj: :return: """ if isinstanc...
[ "def", "_serialize_iterable", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "tuple", ",", "set", ")", ")", ":", "# make a tuple assignable by casting it to list", "obj", "=", "list", "(", "obj", ")", "for", "item", "in", "obj", ":", "obj"...
Only for serializing list and tuples and stuff. Dicts and Strings/Unicode is treated differently. String/Unicode normally don't need further serialization and it would cause a max recursion error trying to do so. :param obj: :return:
[ "Only", "for", "serializing", "list", "and", "tuples", "and", "stuff", ".", "Dicts", "and", "Strings", "/", "Unicode", "is", "treated", "differently", ".", "String", "/", "Unicode", "normally", "don", "t", "need", "further", "serialization", "and", "it", "wo...
train
https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/tracing/serializer.py#L117-L131
RudolfCardinal/pythonlib
cardinal_pythonlib/django/admin.py
disable_bool_icon
def disable_bool_icon( fieldname: str, model) -> Callable[[Any], bool]: """ Disable boolean icons for a Django ModelAdmin field. The '_meta' attribute is present on Django model classes and instances. model_class: ``Union[Model, Type[Model]]`` ... only the type checker in Py3.5 is ...
python
def disable_bool_icon( fieldname: str, model) -> Callable[[Any], bool]: """ Disable boolean icons for a Django ModelAdmin field. The '_meta' attribute is present on Django model classes and instances. model_class: ``Union[Model, Type[Model]]`` ... only the type checker in Py3.5 is ...
[ "def", "disable_bool_icon", "(", "fieldname", ":", "str", ",", "model", ")", "->", "Callable", "[", "[", "Any", "]", ",", "bool", "]", ":", "# noinspection PyUnusedLocal", "def", "func", "(", "self", ",", "obj", ")", ":", "return", "getattr", "(", "obj",...
Disable boolean icons for a Django ModelAdmin field. The '_meta' attribute is present on Django model classes and instances. model_class: ``Union[Model, Type[Model]]`` ... only the type checker in Py3.5 is broken; see ``files.py``
[ "Disable", "boolean", "icons", "for", "a", "Django", "ModelAdmin", "field", ".", "The", "_meta", "attribute", "is", "present", "on", "Django", "model", "classes", "and", "instances", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/admin.py#L43-L67
RudolfCardinal/pythonlib
cardinal_pythonlib/django/admin.py
admin_view_url
def admin_view_url(admin_site: AdminSite, obj, view_type: str = "change", current_app: str = None) -> str: """ Get a Django admin site URL for an object. """ app_name = obj._meta.app_label.lower() model_name = obj._meta.object_name.lower() ...
python
def admin_view_url(admin_site: AdminSite, obj, view_type: str = "change", current_app: str = None) -> str: """ Get a Django admin site URL for an object. """ app_name = obj._meta.app_label.lower() model_name = obj._meta.object_name.lower() ...
[ "def", "admin_view_url", "(", "admin_site", ":", "AdminSite", ",", "obj", ",", "view_type", ":", "str", "=", "\"change\"", ",", "current_app", ":", "str", "=", "None", ")", "->", "str", ":", "app_name", "=", "obj", ".", "_meta", ".", "app_label", ".", ...
Get a Django admin site URL for an object.
[ "Get", "a", "Django", "admin", "site", "URL", "for", "an", "object", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/admin.py#L75-L89
RudolfCardinal/pythonlib
cardinal_pythonlib/django/admin.py
admin_view_fk_link
def admin_view_fk_link(modeladmin: ModelAdmin, obj, fkfield: str, missing: str = "(None)", use_str: bool = True, view_type: str = "change", current_app: str = None) -> str: """ ...
python
def admin_view_fk_link(modeladmin: ModelAdmin, obj, fkfield: str, missing: str = "(None)", use_str: bool = True, view_type: str = "change", current_app: str = None) -> str: """ ...
[ "def", "admin_view_fk_link", "(", "modeladmin", ":", "ModelAdmin", ",", "obj", ",", "fkfield", ":", "str", ",", "missing", ":", "str", "=", "\"(None)\"", ",", "use_str", ":", "bool", "=", "True", ",", "view_type", ":", "str", "=", "\"change\"", ",", "cur...
Get a Django admin site URL for an object that's found from a foreign key in our object of interest.
[ "Get", "a", "Django", "admin", "site", "URL", "for", "an", "object", "that", "s", "found", "from", "a", "foreign", "key", "in", "our", "object", "of", "interest", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/admin.py#L93-L120
RudolfCardinal/pythonlib
cardinal_pythonlib/django/admin.py
admin_view_reverse_fk_links
def admin_view_reverse_fk_links(modeladmin: ModelAdmin, obj, reverse_fk_set_field: str, missing: str = "(None)", use_str: bool = True, separator: str = "<br>", ...
python
def admin_view_reverse_fk_links(modeladmin: ModelAdmin, obj, reverse_fk_set_field: str, missing: str = "(None)", use_str: bool = True, separator: str = "<br>", ...
[ "def", "admin_view_reverse_fk_links", "(", "modeladmin", ":", "ModelAdmin", ",", "obj", ",", "reverse_fk_set_field", ":", "str", ",", "missing", ":", "str", "=", "\"(None)\"", ",", "use_str", ":", "bool", "=", "True", ",", "separator", ":", "str", "=", "\"<b...
Get multiple Django admin site URL for multiple objects linked to our object of interest (where the other objects have foreign keys to our object).
[ "Get", "multiple", "Django", "admin", "site", "URL", "for", "multiple", "objects", "linked", "to", "our", "object", "of", "interest", "(", "where", "the", "other", "objects", "have", "foreign", "keys", "to", "our", "object", ")", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/admin.py#L124-L160
RudolfCardinal/pythonlib
cardinal_pythonlib/dsp.py
lowpass_filter
def lowpass_filter(data: FLOATS_TYPE, sampling_freq_hz: float, cutoff_freq_hz: float, numtaps: int) -> FLOATS_TYPE: """ Apply a low-pass filter to the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :mat...
python
def lowpass_filter(data: FLOATS_TYPE, sampling_freq_hz: float, cutoff_freq_hz: float, numtaps: int) -> FLOATS_TYPE: """ Apply a low-pass filter to the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :mat...
[ "def", "lowpass_filter", "(", "data", ":", "FLOATS_TYPE", ",", "sampling_freq_hz", ":", "float", ",", "cutoff_freq_hz", ":", "float", ",", "numtaps", ":", "int", ")", "->", "FLOATS_TYPE", ":", "coeffs", "=", "firwin", "(", "numtaps", "=", "numtaps", ",", "...
Apply a low-pass filter to the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :math:`f_s`, in Hz (or other consistent units) cutoff_freq_hz: filter cutoff frequency in Hz (or other consistent units) numtaps: number of filter ta...
[ "Apply", "a", "low", "-", "pass", "filter", "to", "the", "data", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dsp.py#L71-L97
RudolfCardinal/pythonlib
cardinal_pythonlib/dsp.py
bandpass_filter
def bandpass_filter(data: FLOATS_TYPE, sampling_freq_hz: float, lower_freq_hz: float, upper_freq_hz: float, numtaps: int) -> FLOATS_TYPE: """ Apply a band-pass filter to the data. Args: data: time series of the data ...
python
def bandpass_filter(data: FLOATS_TYPE, sampling_freq_hz: float, lower_freq_hz: float, upper_freq_hz: float, numtaps: int) -> FLOATS_TYPE: """ Apply a band-pass filter to the data. Args: data: time series of the data ...
[ "def", "bandpass_filter", "(", "data", ":", "FLOATS_TYPE", ",", "sampling_freq_hz", ":", "float", ",", "lower_freq_hz", ":", "float", ",", "upper_freq_hz", ":", "float", ",", "numtaps", ":", "int", ")", "->", "FLOATS_TYPE", ":", "f1", "=", "normalized_frequenc...
Apply a band-pass filter to the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :math:`f_s`, in Hz (or other consistent units) lower_freq_hz: filter cutoff lower frequency in Hz (or other consistent units) upper_freq_hz: filter ...
[ "Apply", "a", "band", "-", "pass", "filter", "to", "the", "data", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dsp.py#L129-L160
RudolfCardinal/pythonlib
cardinal_pythonlib/dsp.py
notch_filter
def notch_filter(data: FLOATS_TYPE, sampling_freq_hz: float, notch_freq_hz: float, quality_factor: float) -> FLOATS_TYPE: """ Design and use a notch (band reject) filter to filter the data. Args: data: time series of the data sampling_freq_...
python
def notch_filter(data: FLOATS_TYPE, sampling_freq_hz: float, notch_freq_hz: float, quality_factor: float) -> FLOATS_TYPE: """ Design and use a notch (band reject) filter to filter the data. Args: data: time series of the data sampling_freq_...
[ "def", "notch_filter", "(", "data", ":", "FLOATS_TYPE", ",", "sampling_freq_hz", ":", "float", ",", "notch_freq_hz", ":", "float", ",", "quality_factor", ":", "float", ")", "->", "FLOATS_TYPE", ":", "b", ",", "a", "=", "iirnotch", "(", "w0", "=", "normaliz...
Design and use a notch (band reject) filter to filter the data. Args: data: time series of the data sampling_freq_hz: sampling frequency :math:`f_s`, in Hz (or other consistent units) notch_freq_hz: notch frequency, in Hz (or other consistent units) quality_f...
[ "Design", "and", "use", "a", "notch", "(", "band", "reject", ")", "filter", "to", "filter", "the", "data", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dsp.py#L163-L186
davenquinn/Attitude
attitude/orientation/base.py
rotation
def rotation(angle): """Rotation about the Z axis (in the XY plane)""" return N.array([[N.cos(angle),-N.sin(angle),0], [N.sin(angle), N.cos(angle),0], [0 , 0 ,1]])
python
def rotation(angle): """Rotation about the Z axis (in the XY plane)""" return N.array([[N.cos(angle),-N.sin(angle),0], [N.sin(angle), N.cos(angle),0], [0 , 0 ,1]])
[ "def", "rotation", "(", "angle", ")", ":", "return", "N", ".", "array", "(", "[", "[", "N", ".", "cos", "(", "angle", ")", ",", "-", "N", ".", "sin", "(", "angle", ")", ",", "0", "]", ",", "[", "N", ".", "sin", "(", "angle", ")", ",", "N"...
Rotation about the Z axis (in the XY plane)
[ "Rotation", "about", "the", "Z", "axis", "(", "in", "the", "XY", "plane", ")" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/base.py#L10-L14
davenquinn/Attitude
attitude/orientation/base.py
ellipse
def ellipse(center,covariance_matrix,level=1, n=1000): """Returns error ellipse in slope-azimuth space""" # singular value decomposition U, s, rotation_matrix = N.linalg.svd(covariance_matrix) # semi-axes (largest first) saxes = N.sqrt(s)*level ## If the _area_ of a 2s ellipse is twice that of a 1s...
python
def ellipse(center,covariance_matrix,level=1, n=1000): """Returns error ellipse in slope-azimuth space""" # singular value decomposition U, s, rotation_matrix = N.linalg.svd(covariance_matrix) # semi-axes (largest first) saxes = N.sqrt(s)*level ## If the _area_ of a 2s ellipse is twice that of a 1s...
[ "def", "ellipse", "(", "center", ",", "covariance_matrix", ",", "level", "=", "1", ",", "n", "=", "1000", ")", ":", "# singular value decomposition", "U", ",", "s", ",", "rotation_matrix", "=", "N", ".", "linalg", ".", "svd", "(", "covariance_matrix", ")",...
Returns error ellipse in slope-azimuth space
[ "Returns", "error", "ellipse", "in", "slope", "-", "azimuth", "space" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/base.py#L16-L28
davenquinn/Attitude
attitude/orientation/base.py
BaseOrientation.to_mapping
def to_mapping(self,**values): """ Create a JSON-serializable representation of the plane that is usable with the javascript frontend """ strike, dip, rake = self.strike_dip_rake() min, max = self.angular_errors() try: disabled = self.disabled ...
python
def to_mapping(self,**values): """ Create a JSON-serializable representation of the plane that is usable with the javascript frontend """ strike, dip, rake = self.strike_dip_rake() min, max = self.angular_errors() try: disabled = self.disabled ...
[ "def", "to_mapping", "(", "self", ",", "*", "*", "values", ")", ":", "strike", ",", "dip", ",", "rake", "=", "self", ".", "strike_dip_rake", "(", ")", "min", ",", "max", "=", "self", ".", "angular_errors", "(", ")", "try", ":", "disabled", "=", "se...
Create a JSON-serializable representation of the plane that is usable with the javascript frontend
[ "Create", "a", "JSON", "-", "serializable", "representation", "of", "the", "plane", "that", "is", "usable", "with", "the", "javascript", "frontend" ]
train
https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/base.py#L91-L119
RudolfCardinal/pythonlib
cardinal_pythonlib/subproc.py
kill_child_processes
def kill_child_processes() -> None: """ Kills children of this process that were registered in the :data:`processes` variable. Use with ``@atexit.register``. """ timeout_sec = 5 for p in processes: try: p.wait(timeout_sec) except TimeoutExpired: # fai...
python
def kill_child_processes() -> None: """ Kills children of this process that were registered in the :data:`processes` variable. Use with ``@atexit.register``. """ timeout_sec = 5 for p in processes: try: p.wait(timeout_sec) except TimeoutExpired: # fai...
[ "def", "kill_child_processes", "(", ")", "->", "None", ":", "timeout_sec", "=", "5", "for", "p", "in", "processes", ":", "try", ":", "p", ".", "wait", "(", "timeout_sec", ")", "except", "TimeoutExpired", ":", "# failed to close", "p", ".", "kill", "(", "...
Kills children of this process that were registered in the :data:`processes` variable. Use with ``@atexit.register``.
[ "Kills", "children", "of", "this", "process", "that", "were", "registered", "in", "the", ":", "data", ":", "processes", "variable", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L78-L91
RudolfCardinal/pythonlib
cardinal_pythonlib/subproc.py
start_process
def start_process(args: List[str], stdin: Any = None, stdout: Any = None, stderr: Any = None) -> Popen: """ Launch a child process and record it in our :data:`processes` variable. Args: args: program and its arguments, as a list stdin: t...
python
def start_process(args: List[str], stdin: Any = None, stdout: Any = None, stderr: Any = None) -> Popen: """ Launch a child process and record it in our :data:`processes` variable. Args: args: program and its arguments, as a list stdin: t...
[ "def", "start_process", "(", "args", ":", "List", "[", "str", "]", ",", "stdin", ":", "Any", "=", "None", ",", "stdout", ":", "Any", "=", "None", ",", "stderr", ":", "Any", "=", "None", ")", "->", "Popen", ":", "log", ".", "debug", "(", "\"{!r}\"...
Launch a child process and record it in our :data:`processes` variable. Args: args: program and its arguments, as a list stdin: typically None stdout: use None to perform no routing, which preserves console colour! Otherwise, specify somewhere to route stdout. See subprocess ...
[ "Launch", "a", "child", "process", "and", "record", "it", "in", "our", ":", "data", ":", "processes", "variable", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L117-L146
RudolfCardinal/pythonlib
cardinal_pythonlib/subproc.py
wait_for_processes
def wait_for_processes(die_on_failure: bool = True, timeout_sec: float = 1) -> None: """ Wait for child processes (catalogued in :data:`processes`) to finish. If ``die_on_failure`` is ``True``, then whenever a subprocess returns failure, all are killed. If ``timeout_sec`` is...
python
def wait_for_processes(die_on_failure: bool = True, timeout_sec: float = 1) -> None: """ Wait for child processes (catalogued in :data:`processes`) to finish. If ``die_on_failure`` is ``True``, then whenever a subprocess returns failure, all are killed. If ``timeout_sec`` is...
[ "def", "wait_for_processes", "(", "die_on_failure", ":", "bool", "=", "True", ",", "timeout_sec", ":", "float", "=", "1", ")", "->", "None", ":", "global", "processes", "global", "proc_args_list", "n", "=", "len", "(", "processes", ")", "Pool", "(", "n", ...
Wait for child processes (catalogued in :data:`processes`) to finish. If ``die_on_failure`` is ``True``, then whenever a subprocess returns failure, all are killed. If ``timeout_sec`` is None, the function waits for its first process to complete, then waits for the second, etc. So a subprocess dying d...
[ "Wait", "for", "child", "processes", "(", "catalogued", "in", ":", "data", ":", "processes", ")", "to", "finish", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L149-L191
RudolfCardinal/pythonlib
cardinal_pythonlib/subproc.py
print_lines
def print_lines(process: Popen) -> None: """ Let a subprocess :func:`communicate`, then write both its ``stdout`` and its ``stderr`` to our ``stdout``. """ out, err = process.communicate() if out: for line in out.decode("utf-8").splitlines(): print(line) if err: f...
python
def print_lines(process: Popen) -> None: """ Let a subprocess :func:`communicate`, then write both its ``stdout`` and its ``stderr`` to our ``stdout``. """ out, err = process.communicate() if out: for line in out.decode("utf-8").splitlines(): print(line) if err: f...
[ "def", "print_lines", "(", "process", ":", "Popen", ")", "->", "None", ":", "out", ",", "err", "=", "process", ".", "communicate", "(", ")", "if", "out", ":", "for", "line", "in", "out", ".", "decode", "(", "\"utf-8\"", ")", ".", "splitlines", "(", ...
Let a subprocess :func:`communicate`, then write both its ``stdout`` and its ``stderr`` to our ``stdout``.
[ "Let", "a", "subprocess", ":", "func", ":", "communicate", "then", "write", "both", "its", "stdout", "and", "its", "stderr", "to", "our", "stdout", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L194-L205
RudolfCardinal/pythonlib
cardinal_pythonlib/subproc.py
run_multiple_processes
def run_multiple_processes(args_list: List[List[str]], die_on_failure: bool = True) -> None: """ Fire up multiple processes, and wait for them to finihs. Args: args_list: command arguments for each process die_on_failure: see :func:`wait_for_processes` """ ...
python
def run_multiple_processes(args_list: List[List[str]], die_on_failure: bool = True) -> None: """ Fire up multiple processes, and wait for them to finihs. Args: args_list: command arguments for each process die_on_failure: see :func:`wait_for_processes` """ ...
[ "def", "run_multiple_processes", "(", "args_list", ":", "List", "[", "List", "[", "str", "]", "]", ",", "die_on_failure", ":", "bool", "=", "True", ")", "->", "None", ":", "for", "procargs", "in", "args_list", ":", "start_process", "(", "procargs", ")", ...
Fire up multiple processes, and wait for them to finihs. Args: args_list: command arguments for each process die_on_failure: see :func:`wait_for_processes`
[ "Fire", "up", "multiple", "processes", "and", "wait", "for", "them", "to", "finihs", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L208-L220
RudolfCardinal/pythonlib
cardinal_pythonlib/subproc.py
mimic_user_input
def mimic_user_input( args: List[str], source_challenge_response: List[Tuple[SubprocSource, str, Union[str, SubprocCommand]]], line_terminators: List[str] = None, print_stdout: bool = False, ...
python
def mimic_user_input( args: List[str], source_challenge_response: List[Tuple[SubprocSource, str, Union[str, SubprocCommand]]], line_terminators: List[str] = None, print_stdout: bool = False, ...
[ "def", "mimic_user_input", "(", "args", ":", "List", "[", "str", "]", ",", "source_challenge_response", ":", "List", "[", "Tuple", "[", "SubprocSource", ",", "str", ",", "Union", "[", "str", ",", "SubprocCommand", "]", "]", "]", ",", "line_terminators", ":...
r""" Run an external command. Pretend to be a human by sending text to the subcommand (responses) when the external command sends us triggers (challenges). This is a bit nasty. Args: args: command-line arguments source_challenge_response: list of tuples of the format ``(cha...
[ "r", "Run", "an", "external", "command", ".", "Pretend", "to", "be", "a", "human", "by", "sending", "text", "to", "the", "subcommand", "(", "responses", ")", "when", "the", "external", "command", "sends", "us", "triggers", "(", "challenges", ")", ".", "T...
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L301-L454
RudolfCardinal/pythonlib
cardinal_pythonlib/subproc.py
AsynchronousFileReader.run
def run(self) -> None: """ Read lines and put them on the queue. """ fd = self._fd encoding = self._encoding line_terminators = self._line_terminators queue = self._queue buf = "" while True: try: c = fd.read(1).decode(e...
python
def run(self) -> None: """ Read lines and put them on the queue. """ fd = self._fd encoding = self._encoding line_terminators = self._line_terminators queue = self._queue buf = "" while True: try: c = fd.read(1).decode(e...
[ "def", "run", "(", "self", ")", "->", "None", ":", "fd", "=", "self", ".", "_fd", "encoding", "=", "self", ".", "_encoding", "line_terminators", "=", "self", ".", "_line_terminators", "queue", "=", "self", ".", "_queue", "buf", "=", "\"\"", "while", "T...
Read lines and put them on the queue.
[ "Read", "lines", "and", "put", "them", "on", "the", "queue", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L260-L292
The-Politico/politico-civic-geography
geography/management/commands/bootstrap/fixtures/_nation.py
NationFixtures.create_nation_fixtures
def create_nation_fixtures(self): """ Create national US and State Map """ SHP_SLUG = "cb_{}_us_state_500k".format(self.YEAR) DOWNLOAD_PATH = os.path.join(self.DOWNLOAD_DIRECTORY, SHP_SLUG) shape = shapefile.Reader( os.path.join(DOWNLOAD_PATH, "{}.shp".format...
python
def create_nation_fixtures(self): """ Create national US and State Map """ SHP_SLUG = "cb_{}_us_state_500k".format(self.YEAR) DOWNLOAD_PATH = os.path.join(self.DOWNLOAD_DIRECTORY, SHP_SLUG) shape = shapefile.Reader( os.path.join(DOWNLOAD_PATH, "{}.shp".format...
[ "def", "create_nation_fixtures", "(", "self", ")", ":", "SHP_SLUG", "=", "\"cb_{}_us_state_500k\"", ".", "format", "(", "self", ".", "YEAR", ")", "DOWNLOAD_PATH", "=", "os", ".", "path", ".", "join", "(", "self", ".", "DOWNLOAD_DIRECTORY", ",", "SHP_SLUG", "...
Create national US and State Map
[ "Create", "national", "US", "and", "State", "Map" ]
train
https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/management/commands/bootstrap/fixtures/_nation.py#L12-L71