docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
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 ...
def get_config_parameter_multiline(config: ConfigParser, section: str, param: str, default: List[str]) -> List[str]: try: multiline = config.get(section, param) lines = [x.strip() for x in m...
729,899
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: ...
def wait(self, timeout_s: float = None) -> int: if not self.running: return 0 retcode = self.process.wait(timeout=timeout_s) # We won't get further unless the process has stopped. if retcode is None: self.error("Subprocess finished, but return code was No...
729,919
A test service. Writes to a file occasionally, so you can see it's running. Args: filename: file to write data to periodically period_ms: period, in milliseconds
def test_service(self, filename: str = TEST_FILENAME, period_ms: int = TEST_PERIOD_MS) -> None: # A test service. This works! (As long as you can write to the file.) def write(msg): f.write('{}: {}\n'.format(arrow.now(), msg)) f....
729,925
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
def add_info_to_exception(err: Exception, info: Dict) -> None: # noqa if not err.args: err.args = ('', ) err.args += (info, )
729,933
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...
def lowpass_filter(data: FLOATS_TYPE, sampling_freq_hz: float, cutoff_freq_hz: float, numtaps: int) -> FLOATS_TYPE: coeffs = firwin( numtaps=numtaps, cutoff=normalized_frequency(cutoff_freq_hz, sampling_freq_hz), pass_zero=True ...
729,952
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...
def notch_filter(data: FLOATS_TYPE, sampling_freq_hz: float, notch_freq_hz: float, quality_factor: float) -> FLOATS_TYPE: b, a = iirnotch( w0=normalized_frequency(notch_freq_hz, sampling_freq_hz), Q=quality_factor ) filtered_data = lfil...
729,954
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) # Wait for them all to finish wait_for_processes(die_on_failure=die_on_failure)
729,969
Command to produce an :class:`InsertOnDuplicate` object. Args: tablename: name of the table values: values to ``INSERT`` inline: as per http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.insert kwargs: additional parameters Returns: ...
def insert_on_duplicate(tablename: str, values: Any = None, inline: bool = False, **kwargs): # noqa return InsertOnDuplicate(tablename, values, inline=inline, **kwargs)
729,982
Amalgamate multiple CSV/TSV/similar files into one. Args: filenames: list of filenames to process outfile: file-like object to write output to input_dialect: dialect of input files, as passed to ``csv.reader`` output_dialect: dialect to write, as passed to ``csv.writer`` deb...
def merge_csv(filenames: List[str], outfile: TextIO = sys.stdout, input_dialect: str = 'excel', output_dialect: str = 'excel', debug: bool = False, headers: bool = True) -> None: writer = csv.writer(outfile, dialect=output_dialect) writt...
730,004
r""" Standard logistic function. .. math:: y = \frac {1} {1 + e^{-k (x - \theta)}} Args: x: :math:`x` k: :math:`k` theta: :math:`\theta` Returns: :math:`y`
def logistic(x: Union[float, np.ndarray], k: float, theta: float) -> Optional[float]: r # https://www.sharelatex.com/learn/List_of_Greek_letters_and_math_symbols if x is None or k is None or theta is None: return None # noinspection PyUnresolvedReferences return 1 /...
730,017
r""" Inverse standard logistic function: .. math:: x = ( log( \frac {1} {y} - 1) / -k ) + \theta Args: y: :math:`y` k: :math:`k` theta: :math:`\theta` Returns: :math:`x`
def inv_logistic(y: Union[float, np.ndarray], k: float, theta: float) -> Optional[float]: r if y is None or k is None or theta is None: return None # noinspection PyUnresolvedReferences return (np.log((1 / y) - 1) / -k) + theta
730,018
Convert nose-style test reports to UnitTH-style test reports by splitting modules into separate XML files Args: in_file_nose (:obj:`str`): path to nose-style test report out_file_unitth (:obj:`str`): path to save UnitTH-style test reports
def run(in_file_nose, out_dir_unitth): suites = Converter.read_nose(in_file_nose) Converter.write_unitth(suites, out_dir_unitth)
730,031
Parse nose-style test reports into a `dict` Args: in_file (:obj:`str`): path to nose-style test report Returns: :obj:`dict`: dictionary of test suites
def read_nose(in_file): suites = {} doc_xml = minidom.parse(in_file) suite_xml = doc_xml.getElementsByTagName("testsuite")[0] for case_xml in suite_xml.getElementsByTagName('testcase'): classname = case_xml.getAttribute('classname') if classname not in su...
730,032
Write UnitTH-style test reports Args: suites (:obj:`dict`): dictionary of test suites out_dir (:obj:`str`): path to save UnitTH-style test reports
def write_unitth(suites, out_dir): if not os.path.isdir(out_dir): os.mkdir(out_dir) for classname, cases in suites.items(): doc_xml = minidom.Document() suite_xml = doc_xml.createElement('testsuite') suite_xml.setAttribute('name', classname) ...
730,033
Returns results and column names from a query. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object sql: raw SQL to execure Returns: ``(rows, fieldnames)`` where ``rows`` is the usual set of results and ``fieldnames`` are the na...
def get_rows_fieldnames_from_raw_sql( session: Union[Session, Engine, Connection], sql: str) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]: result = session.execute(sql) # type: ResultProxy fieldnames = result.keys() rows = result.fetchall() return rows, fieldnames
730,042
Returns the result of ``COUNT(*)`` from the specified table (with additional ``WHERE`` criteria if desired). Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object tablename: name of the table criteria: optional SQLAlchemy "where" criteria...
def count_star(session: Union[Session, Engine, Connection], tablename: str, *criteria: Any) -> int: # works if you pass a connection or a session or an engine; all have # the execute() method query = select([func.count()]).select_from(table(tablename)) for criterion in...
730,043
Returns a list of the first values in each row returned by a ``SELECT`` query. A Core version of this sort of thing: http://xion.io/post/code/sqlalchemy-query-values.html Args: session: SQLAlchemy :class:`Session` object select_statement: SQLAlchemy :class:`Select` object Returns:...
def fetch_all_first_values(session: Session, select_statement: Select) -> List[Any]: rows = session.execute(select_statement) # type: ResultProxy try: return [row[0] for row in rows] except ValueError as e: raise MultipleResultsFound(str(e))
730,047
If we're running under SQL Server, disable constraint checking for the specified table while the resource is held. Args: session: SQLAlchemy :class:`Session` tablename: table name See https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger
def if_sqlserver_disable_constraints(session: SqlASession, tablename: str) -> None: # noqa engine = get_engine_from_session(session) if is_sqlserver(engine): quoted_tablename = quote_identifier(tablename, engine) session.execute( "ALTER TABL...
730,056
If we're running under SQL Server, disable triggers AND constraints for the specified table while the resource is held. Args: session: SQLAlchemy :class:`Session` tablename: table name
def if_sqlserver_disable_constraints_triggers(session: SqlASession, tablename: str) -> None: with if_sqlserver_disable_constraints(session, tablename): with if_sqlserver_disable_triggers(session, tablename): yield
730,057
Ask Alembic what its head revision is (i.e. where the Python code would like the database to be at). Arguments: alembic_config_filename: config filename alembic_base_dir: directory to start in, so relative paths in the config file work. version_table: table name for Alembic ...
def get_head_revision_from_alembic( alembic_config_filename: str, alembic_base_dir: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str: if alembic_base_dir is None: alembic_base_dir = os.path.dirname(alembic_config_filename) os.chdir(alembic_base_dir) # ...
730,069
Ask the database what its current revision is. Arguments: database_url: SQLAlchemy URL for the database version_table: table name for Alembic versions
def get_current_revision( database_url: str, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> str: engine = create_engine(database_url) conn = engine.connect() opts = {'version_table': version_table} mig_context = MigrationContext.configure(conn, opts=opts) return mig_cont...
730,070
Returns a tuple of ``(current_revision, head_revision)``; see :func:`get_current_revision` and :func:`get_head_revision_from_alembic`. Arguments: database_url: SQLAlchemy URL for the database alembic_config_filename: config filename alembic_base_dir: directory to start in, so relative p...
def get_current_and_head_revision( database_url: str, alembic_config_filename: str, alembic_base_dir: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> Tuple[str, str]: # Where we are head_revision = get_head_revision_from_alembic( alembic_config_fil...
730,071
Takes a command-line command, executes it, and returns its ``stdout`` output. Args: command: command string Returns: output from the command as ``bytes``
def get_external_command_output(command: str) -> bytes: args = shlex.split(command) ret = subprocess.check_output(args) # this needs Python 2.7 or higher return ret
730,105
Get the output from a piped series of commands. Args: commands: sequence of command strings stdinput: optional ``stdin`` data to feed into the start of the pipe Returns: ``stdout`` from the end of the pipe
def get_pipe_series_output(commands: Sequence[str], stdinput: BinaryIO = None) -> bytes: # Python arrays indexes are zero-based, i.e. an array is indexed from # 0 to len(array)-1. # The range/xrange commands, by default, start at 0 and go to one less # than the maximum sp...
730,106
Launches a file using the operating system's standard launcher. Args: filename: file to launch raise_if_fails: raise any exceptions from ``subprocess.call(["xdg-open", filename])`` (Linux) or ``os.startfile(filename)`` (otherwise)? If not, exceptions are suppress...
def launch_external_file(filename: str, raise_if_fails: bool = False) -> None: log.info("Launching external file: {!r}", filename) try: if sys.platform.startswith('linux'): cmdargs = ["xdg-open", filename] # log.debug("... command: {!r}", cmdargs) subprocess.call...
730,107
Kills a tree of processes, starting with the parent. Slightly modified from https://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows. Args: pid: process ID of the parent including_parent: kill the parent too? timeout_s: timeout to wait for processes...
def kill_proc_tree(pid: int, including_parent: bool = True, timeout_s: float = 5) \ -> Tuple[Set[psutil.Process], Set[psutil.Process]]: # noqa parent = psutil.Process(pid) to_kill = parent.children(recursive=True) # type: List[psutil.Process] if including...
730,108
Generates file-like objects from a list of filenames. Args: filenames: iterable of filenames Yields: each file as a :class:`TextIO` object
def gen_textfiles_from_filenames( filenames: Iterable[str]) -> Generator[TextIO, None, None]: for filename in filenames: with open(filename) as f: yield f
730,153
Generates lines from file-like objects. Args: files: iterable of :class:`TextIO` objects Yields: each line of all the files
def gen_lines_from_textfiles( files: Iterable[TextIO]) -> Generator[str, None, None]: for file in files: for line in file: yield line
730,154
Generates lines from binary files. Strips out newlines. Args: files: iterable of :class:`BinaryIO` file-like objects encoding: encoding to use Yields: each line of all the files
def gen_lines_from_binary_files( files: Iterable[BinaryIO], encoding: str = UTF8) -> Generator[str, None, None]: for file in files: for byteline in file: line = byteline.decode(encoding).strip() yield line
730,156
Splits lines with ``splitter`` and yields a specified part by index. Args: lines: iterable of strings part_index: index of part to yield splitter: string to split the lines on Yields: the specified part for each line
def gen_part_from_line(lines: Iterable[str], part_index: int, splitter: str = None) -> Generator[str, None, None]: for line in lines: parts = line.split(splitter) yield parts[part_index]
730,158
r""" Yields the *n*\ th part of each thing in ``iterables``. Args: iterables: iterable of anything part_index: part index Yields: ``item[part_index] for item in iterable``
def gen_part_from_iterables(iterables: Iterable[Any], part_index: int) -> Generator[Any, None, None]: r # RST: make part of word bold/italic: # https://stackoverflow.com/questions/12771480/part-of-a-word-bold-in-restructuredtext # noqa for iterable in iterables: yiel...
730,159
Iterate through binary file-like objects that are CSV files in a specified encoding. Yield each row. Args: csv_files: iterable of :class:`BinaryIO` objects encoding: encoding to use skip_header: skip the header (first) row of each file? csv_reader_kwargs: arguments to pass to :f...
def gen_rows_from_csv_binfiles( csv_files: Iterable[BinaryIO], encoding: str = UTF8, skip_header: bool = False, **csv_reader_kwargs) -> Generator[Iterable[str], None, None]: dialect = csv_reader_kwargs.pop('dialect', None) for csv_file_bin in csv_files: # noinspectio...
730,160
Replaces text in a file. Args: filename: filename to process (modifying it in place) text_from: original text to replace text_to: replacement text
def replace_in_file(filename: str, text_from: str, text_to: str) -> None: log.info("Amending {}: {} -> {}", filename, repr(text_from), repr(text_to)) with open(filename) as infile: contents = infile.read() contents = contents.replace(text_from, text_to) with open(filename, 'w')...
730,163
Replaces multiple from/to string pairs within a single file. Args: filename: filename to process (modifying it in place) replacements: list of ``(from_text, to_text)`` tuples
def replace_multiple_in_file(filename: str, replacements: List[Tuple[str, str]]) -> None: with open(filename) as infile: contents = infile.read() for text_from, text_to in replacements: log.info("Amending {}: {} -> {}", filename, repr(text_from)...
730,164
Converts a file (in place) from UNIX to Windows line endings, or the reverse. Args: filename: filename to modify (in place) to_unix: convert Windows (CR LF) to UNIX (LF) to_windows: convert UNIX (LF) to Windows (CR LF)
def convert_line_endings(filename: str, to_unix: bool = False, to_windows: bool = False) -> None: assert to_unix != to_windows with open(filename, "rb") as f: contents = f.read() windows_eol = b"\r\n" # CR LF unix_eol = b"\n" # LF if to_unix: log.info(...
730,165
Detects whether a line is present within a file. Args: filename: file to check line: line to search for (as an exact match)
def is_line_in_file(filename: str, line: str) -> bool: assert "\n" not in line with open(filename, "r") as file: for fileline in file: if fileline == line: return True return False
730,166
Adds a line (at the end) if it's not already in the file somewhere. Args: filename: filename to modify (in place) line: line to append (which must not have a newline in)
def add_line_if_absent(filename: str, line: str) -> None: assert "\n" not in line if not is_line_in_file(filename, line): log.info("Appending line {!r} to file {!r}", line, filename) with open(filename, "a") as file: file.writelines([line])
730,167
De-duplicate files within one or more directories. Remove files that are identical to ones already considered. Args: directories: list of directories to process recursive: process subdirectories (recursively)? dummy_run: say what it'll do, but don't do it
def deduplicate(directories: List[str], recursive: bool, dummy_run: bool) -> None: # ------------------------------------------------------------------------- # Catalogue files by their size # ------------------------------------------------------------------------- files_by_size = ...
730,177
Context manager to add a file output stream to our logging system. Args: tee_file: file-like object to write to loglevel: log level (e.g. ``logging.DEBUG``) to use for this stream
def tee_log(tee_file: TextIO, loglevel: int) -> None: handler = get_monochrome_handler(stream=tee_file) handler.setLevel(loglevel) rootlogger = logging.getLogger() rootlogger.addHandler(handler) # Tee the main stdout/stderr as required. with TeeContextManager(tee_file, capture_stdout=True):...
730,183
Returns a copy of the dictionary ``d`` with its keys renamed according to ``mapping``. Args: d: the starting dictionary mapping: a dictionary of the format ``{old_key_name: new_key_name}`` Returns: a new dictionary Keys that are not in ``mapping`` are left unchanged. The i...
def rename_keys(d: Dict[str, Any], mapping: Dict[str, str]) -> Dict[str, Any]: result = {} # type: Dict[str, Any] for k, v in d.items(): if k in mapping: k = mapping[k] result[k] = v return result
730,204
Renames, IN PLACE, the keys in ``d`` according to the mapping in ``renames``. Args: d: a dictionary to modify renames: a dictionary of the format ``{old_key_name: new_key_name}`` See https://stackoverflow.com/questions/4406501/change-the-name-of-a-key-in-dictionary.
def rename_keys_in_dict(d: Dict[str, Any], renames: Dict[str, str]) -> None: # noqa for old_key, new_key in renames.items(): if new_key == old_key: continue if old_key in d: if new_key in d: raise ValueError( "rename_keys_in_dict: ren...
730,205
Deletes keys from a dictionary, in place. Args: d: dictonary to modify keys_to_delete: if any keys are present in this list, they are deleted... keys_to_keep: ... unless they are present in this list.
def delete_keys(d: Dict[Any, Any], keys_to_delete: List[Any], keys_to_keep: List[Any]) -> None: for k in keys_to_delete: if k in d and k not in keys_to_keep: del d[k]
730,211
Manually set the ``timing`` parameter, and optionally reset the timers. Args: timing: should we be timing? reset: reset the timers?
def set_timing(self, timing: bool, reset: bool = False) -> None: self._timing = timing if reset: self.reset()
730,227
Start a named timer. Args: name: name of the timer increment_count: increment the start count for this timer
def start(self, name: str, increment_count: bool = True) -> None: if not self._timing: return now = get_now_utc_pendulum() # If we were already timing something else, pause that. if self._stack: last = self._stack[-1] self._totaldurations[las...
730,228
Stop a named timer. Args: name: timer to stop
def stop(self, name: str) -> None: if not self._timing: return now = get_now_utc_pendulum() # Validity check if not self._stack: raise AssertionError("MultiTimer.stop() when nothing running") if self._stack[-1] != name: raise Assertio...
730,229
Pings a host, using OS tools. Args: hostname: host name or IP address timeout_s: timeout in seconds Returns: was the ping successful?
def ping(hostname: str, timeout_s: int = 5) -> bool: if sys.platform == "win32": timeout_ms = timeout_s * 1000 args = [ "ping", hostname, "-n", "1", # ping count "-w", str(timeout_ms), # timeout ] elif sys.platform.startswith('linux'...
730,255
Downloads a URL to a file. Args: url: URL to download from filename: file to save to skip_cert_verify: skip SSL certificate check?
def download(url: str, filename: str, skip_cert_verify: bool = True) -> None: log.info("Downloading from {} to {}", url, filename) # urllib.request.urlretrieve(url, filename) # ... sometimes fails (e.g. downloading # https://www.openssl.org/source/openssl-1.1.0g.tar.gz under Windows) ...
730,256
Generate binary files from a series of URLs (one per URL). Args: urls: iterable of URLs on_disk: if ``True``, yields files that are on disk (permitting random access); if ``False``, yields in-memory files (which will not permit random access) show_info: show progress...
def gen_binary_files_from_urls( urls: Iterable[str], on_disk: bool = False, show_info: bool = True) -> Generator[BinaryIO, None, None]: for url in urls: if on_disk: # Necessary for e.g. zip processing (random access) with tempfile.TemporaryDirectory() as ...
730,257
Returns a list produced by applying :func:`multiple_replace` to every string in ``stringlist``. Args: stringlist: list of source strings replacedict: dictionary mapping "original" to "replacement" strings Returns: list of final strings
def replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) -> List[str]: newlist = [] for fromstring in stringlist: newlist.append(multiple_replace(fromstring, replacedict)) return newlist
730,261
Determines whether a drug, passed as an instance of :class:`.Drug`, matches the specified criteria. Args: drug: a :class:`.Drug` instance criteria: ``name=value`` pairs to match against the attributes of the :class:`Drug` class. For example, you can include keyword argum...
def drug_matches_criteria(drug: Drug, **criteria: Dict[str, bool]) -> bool: for attribute, value in criteria.items(): if getattr(drug, attribute) != value: return False return True
730,305
Returns SQL like .. code-block:: sql (column_name LIKE '%drugname1%' OR column_name LIKE '%drugname2%') for the drug names that this Drug object knows about. Args: column_name: column name, pre-escaped if necessary Returns: SQL fragme...
def sql_column_like_drug(self, column_name: str) -> str: clauses = [ "{col} LIKE {fragment}".format( col=column_name, fragment=sql_string_literal(f)) for f in self.sql_like_fragments ] return "({})".format(" OR ".join(clauses))
730,315
Runs self-tests. Args: test_expr: include tests of expressions (which can be slow).
def test(cls, test_expr: bool = True) -> None: cls.test_dialect_specific_1() cls.test_identifiers() if test_expr: cls.test_expr() cls.test_sql_core() cls.test_dialect_specific_2()
730,346
Gets a monochrome log handler using a standard format. Args: extranames: additional names to append to the logger's name with_process_id: include the process ID in the logger's name? with_thread_id: include the thread ID in the logger's name? stream: ``TextIO`` stream to send log ou...
def get_monochrome_handler( extranames: List[str] = None, with_process_id: bool = False, with_thread_id: bool = False, stream: TextIO = None) -> logging.StreamHandler: fmt = "%(asctime)s.%(msecs)03d" if with_process_id or with_thread_id: procinfo = [] # type: List[s...
730,426
Gets a colour log handler using a standard format. Args: extranames: additional names to append to the logger's name with_process_id: include the process ID in the logger's name? with_thread_id: include the thread ID in the logger's name? stream: ``TextIO`` stream to send log output...
def get_colour_handler(extranames: List[str] = None, with_process_id: bool = False, with_thread_id: bool = False, stream: TextIO = None) -> logging.StreamHandler: fmt = "%(white)s%(asctime)s.%(msecs)03d" # this is dim white = grey if wit...
730,427
Quick function to set up the root logger for colour. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Args: level: log level to set with_process_id: include the process ID in the logger's name? with_...
def main_only_quicksetup_rootlogger(level: int = logging.DEBUG, with_process_id: bool = False, with_thread_id: bool = False) -> None: # Nasty. Only call from "if __name__ == '__main__'" clauses! rootlogger = logging.getLogger() con...
730,429
Remove all handlers from a logger. Args: logger: logger to modify
def remove_all_logger_handlers(logger: logging.Logger) -> None: while logger.handlers: h = logger.handlers[0] logger.removeHandler(h)
730,430
Create a new formatter and apply it to the logger. :func:`logging.basicConfig` won't reset the formatter if another module has called it, so always set the formatter like this. Args: logger: logger to modify fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter` datefmt...
def reset_logformat(logger: logging.Logger, fmt: str, datefmt: str = '%Y-%m-%d %H:%M:%S') -> None: handler = logging.StreamHandler() formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) handler.setFormatter(formatter) remove_all_logger_handlers(logger) ...
730,431
Apply a simple time-stamped log format to an existing logger, and set its loglevel to either ``logging.DEBUG`` or ``logging.INFO``. Args: logger: logger to modify extraname: additional name to append to the logger's name level: log level to set
def reset_logformat_timestamped(logger: logging.Logger, extraname: str = "", level: int = logging.INFO) -> None: namebit = extraname + ":" if extraname else "" fmt = ("%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:" + namebit + "%(...
730,432
Applies a preconfigured datetime/colour scheme to ALL logger. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Generally MORE SENSIBLE just to apply a handler to the root logger. Args: remove_existing: remove e...
def configure_all_loggers_for_colour(remove_existing: bool = True) -> None: handler = get_colour_handler() apply_handler_to_all_logs(handler, remove_existing=remove_existing)
730,433
Applies a handler to all logs, optionally removing existing handlers. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Generally MORE SENSIBLE just to apply a handler to the root logger. Args: handler: the hand...
def apply_handler_to_root_log(handler: logging.Handler, remove_existing: bool = False) -> None: rootlog = logging.getLogger() if remove_existing: rootlog.handlers = [] rootlog.addHandler(handler)
730,434
Applies a handler to all logs, optionally removing existing handlers. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Generally MORE SENSIBLE just to apply a handler to the root logger. Args: handler: the hand...
def apply_handler_to_all_logs(handler: logging.Handler, remove_existing: bool = False) -> None: # noinspection PyUnresolvedReferences for name, obj in logging.Logger.manager.loggerDict.items(): if remove_existing: obj.handlers = [] # http://stackoverflow.c...
730,435
Copy all currently configured logs to the specified file. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Args: filename: file to send log output to fmt: passed to the ``fmt=`` argument of :class:`logging.F...
def copy_all_logs_to_file(filename: str, fmt: str = LOG_FORMAT, datefmt: str = LOG_DATEFMT) -> None: fh = logging.FileHandler(filename) # default file mode is 'a' for append formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) fh.setFormatter(f...
730,437
Set a log level for a log and all its handlers. Args: log: log to modify level: log level to set
def set_level_for_logger_and_its_handlers(log: logging.Logger, level: int) -> None: log.setLevel(level) for h in log.handlers: # type: logging.Handler h.setLevel(level)
730,442
r""" Args: append_br: append ``<br>`` to each line? replace_nl_with_br: replace ``\n`` with ``<br>`` in messages? See https://hg.python.org/cpython/file/3.5/Lib/logging/__init__.py
def __init__(self, append_br: bool = False, replace_nl_with_br: bool = True) -> None: r super().__init__( fmt='%(message)s', datefmt='%Y-%m-%d %H:%M:%S', style='%' ) self.append_br = append_br self.replace_nl_with_br = replace_...
730,444
Returns the SQL column type used to make very large text columns for a given dialect. Args: dialect: a SQLAlchemy :class:`Dialect` Returns: the SQL data type of "giant text", typically 'LONGTEXT' for MySQL and 'NVARCHAR(MAX)' for SQL Server.
def giant_text_sqltype(dialect: Dialect) -> str: if dialect.name == SqlaDialectName.SQLSERVER: return 'NVARCHAR(MAX)' elif dialect.name == SqlaDialectName.MYSQL: return 'LONGTEXT' else: raise ValueError("Unknown dialect: {}".format(dialect.name))
730,469
Convert a signed integer to its "two's complement" representation. Args: val: signed integer n_bits: number of bits (which must reflect a whole number of bytes) Returns: unsigned integer: two's complement version
def signed_to_twos_comp(val: int, n_bits: int) -> int: assert n_bits % 8 == 0, "Must specify a whole number of bytes" n_bytes = n_bits // 8 b = val.to_bytes(n_bytes, byteorder=sys.byteorder, signed=True) return int.from_bytes(b, byteorder=sys.byteorder, signed=False)
730,507
Converts an 8-byte sequence to a long integer. Args: bytesdata: 8 consecutive bytes, as a ``bytes`` object, in little-endian format (least significant byte [LSB] first) Returns: integer
def bytes_to_long(bytesdata: bytes) -> int: assert len(bytesdata) == 8 return sum((b << (k * 8) for k, b in enumerate(bytesdata)))
730,508
Pure 32-bit Python implementation of MurmurHash3; see http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash. Args: data: data to hash seed: seed Returns: integer hash
def murmur3_x86_32(data: Union[bytes, bytearray], seed: int = 0) -> int: # noqa c1 = 0xcc9e2d51 c2 = 0x1b873593 length = len(data) h1 = seed rounded_end = (length & 0xfffffffc) # round down to 4 byte block for i in range(0, rounded_end, 4): # little endian load order # RN...
730,509
Pure 64-bit Python implementation of MurmurHash3; see http://stackoverflow.com/questions/13305290/is-there-a-pure-python-implementation-of-murmurhash (plus RNC bugfixes). Args: data: data to hash seed: seed Returns: integer hash
def murmur3_64(data: Union[bytes, bytearray], seed: int = 19820125) -> int: # noqa m = 0xc6a4a7935bd1e995 r = 47 mask = 2 ** 64 - 1 length = len(data) h = seed ^ ((m * length) & mask) offset = (length // 8) * 8 # RNC: was /, but for Python 3 that gives float; brackets added for cla...
730,510
Implements 128-bit murmur3 hash for x64, as per ``pymmh3``, with some bugfixes. Args: key: data to hash seed: seed Returns: integer hash
def pymmh3_hash128_x64(key: Union[bytes, bytearray], seed: int) -> int: def fmix(k): k ^= k >> 33 k = (k * 0xff51afd7ed558ccd) & 0xFFFFFFFFFFFFFFFF k ^= k >> 33 k = (k * 0xc4ceb9fe1a85ec53) & 0xFFFFFFFFFFFFFFFF k ^= k >> 33 return k length = len(key) nb...
730,511
Implements 128-bit murmur3 hash for x86, as per ``pymmh3``, with some bugfixes. Args: key: data to hash seed: seed Returns: integer hash
def pymmh3_hash128_x86(key: Union[bytes, bytearray], seed: int) -> int: def fmix(h): h ^= h >> 16 h = (h * 0x85ebca6b) & 0xFFFFFFFF h ^= h >> 13 h = (h * 0xc2b2ae35) & 0xFFFFFFFF h ^= h >> 16 return h length = len(key) nblocks = int(length / 16) h1...
730,512
Implements 128bit murmur3 hash, as per ``pymmh3``. Args: key: data to hash seed: seed x64arch: is a 64-bit architecture available? Returns: integer hash
def pymmh3_hash128(key: Union[bytes, bytearray], seed: int = 0, x64arch: bool = True) -> int: if x64arch: return pymmh3_hash128_x64(key, seed) else: return pymmh3_hash128_x86(key, seed)
730,513
Implements 64bit murmur3 hash, as per ``pymmh3``. Returns a tuple. Args: key: data to hash seed: seed x64arch: is a 64-bit architecture available? Returns: tuple: tuple of integers, ``(signed_val1, signed_val2)``
def pymmh3_hash64(key: Union[bytes, bytearray], seed: int = 0, x64arch: bool = True) -> Tuple[int, int]: hash_128 = pymmh3_hash128(key, seed, x64arch) unsigned_val1 = hash_128 & 0xFFFFFFFFFFFFFFFF # low half if unsigned_val1 & 0x8000000000000000 == 0: sign...
730,514
Checks the pure Python implementation of 32-bit murmur3 against the ``mmh3`` C-based module. Args: data: data to hash seed: seed Raises: AssertionError: if the two calculations don't match
def compare_python_to_reference_murmur3_32(data: Any, seed: int = 0) -> None: assert mmh3, "Need mmh3 module" c_data = to_str(data) c_signed = mmh3.hash(c_data, seed=seed) # 32 bit py_data = to_bytes(c_data) py_unsigned = murmur3_x86_32(py_data, seed=seed) py_signed = twos_comp_to_signed(p...
730,515
Checks the pure Python implementation of 64-bit murmur3 against the ``mmh3`` C-based module. Args: data: data to hash seed: seed Raises: AssertionError: if the two calculations don't match
def compare_python_to_reference_murmur3_64(data: Any, seed: int = 0) -> None: assert mmh3, "Need mmh3 module" c_data = to_str(data) c_signed_low, c_signed_high = mmh3.hash64(c_data, seed=seed, x64arch=IS_64_BIT) py_data = to_bytes(c_data) py_signed_...
730,516
Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 32-bit integer
def hash32(data: Any, seed=0) -> int: with MultiTimerContext(timer, TIMING_HASH): c_data = to_str(data) if mmh3: return mmh3.hash(c_data, seed=seed) py_data = to_bytes(c_data) py_unsigned = murmur3_x86_32(py_data, seed=seed) return twos_comp_to_signed(py_unsi...
730,517
Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 64-bit integer
def hash64(data: Any, seed: int = 0) -> int: # ------------------------------------------------------------------------- # MurmurHash3 # ------------------------------------------------------------------------- c_data = to_str(data) if mmh3: c_signed_low, _ = mmh3.hash64(data, seed=seed...
730,518
Returns the mean of a list of numbers. Args: values: values to mean, ignoring any values that are ``None`` Returns: the mean, or ``None`` if :math:`n = 0`
def mean(values: Sequence[Union[int, float, None]]) -> Optional[float]: total = 0.0 # starting with "0.0" causes automatic conversion to float n = 0 for x in values: if x is not None: total += x n += 1 return total / n if n > 0 else None
730,527
r""" Returns the logit (log odds) of its input probability .. math:: \alpha = logit(p) = log(x / (1 - x)) Args: p: :math:`p` Returns: :math:`\alpha`, or ``None`` if ``x`` is not in the range [0, 1].
def safe_logit(p: Union[float, int]) -> Optional[float]: r if p > 1 or p < 0: return None # can't take log of negative number if p == 1: return float("inf") if p == 0: return float("-inf") return math.log(p / (1 - p))
730,528
Finds the SQLAlchemy dialect in use. Args: mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or :class:`Dialect` object Returns: the SQLAlchemy :class:`Dialect` being used
def get_dialect(mixed: Union[SQLCompiler, Engine, Dialect]) -> Dialect: if isinstance(mixed, Dialect): return mixed elif isinstance(mixed, Engine): return mixed.dialect elif isinstance(mixed, SQLCompiler): return mixed.dialect else: raise ValueError("get_dialect: 'mi...
730,541
Finds the name of the SQLAlchemy dialect in use. Args: mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or :class:`Dialect` object Returns: the SQLAlchemy dialect name being used
def get_dialect_name(mixed: Union[SQLCompiler, Engine, Dialect]) -> str: dialect = get_dialect(mixed) # noinspection PyUnresolvedReferences return dialect.name
730,542
Returns the SQLAlchemy :class:`IdentifierPreparer` in use for the dialect being used. Args: mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or :class:`Dialect` object Returns: an :class:`IdentifierPreparer`
def get_preparer(mixed: Union[SQLCompiler, Engine, Dialect]) -> IdentifierPreparer: dialect = get_dialect(mixed) # noinspection PyUnresolvedReferences return dialect.preparer(dialect)
730,543
Converts an SQL identifier to a quoted version, via the SQL dialect in use. Args: identifier: the identifier to be quoted mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or :class:`Dialect` object Returns: the quoted identifier
def quote_identifier(identifier: str, mixed: Union[SQLCompiler, Engine, Dialect]) -> str: # See also http://sqlalchemy-utils.readthedocs.io/en/latest/_modules/sqlalchemy_utils/functions/orm.html # noqa return get_preparer(mixed).quote(identifier)
730,544
r""" Converts a TSV line into sequential key/value pairs as a dictionary. For example, .. code-block:: none field1\tvalue1\tfield2\tvalue2 becomes .. code-block:: none {"field1": "value1", "field2": "value2"} Args: line: the line key_lower: should the keys ...
def tsv_pairs_to_dict(line: str, key_lower: bool = True) -> Dict[str, str]: r items = line.split("\t") d = {} # type: Dict[str, str] for chunk in chunks(items, 2): if len(chunk) < 2: log.warning("Bad chunk, not of length 2: {!r}", chunk) continue key = chunk[0] ...
730,555
Import all submodules of a module, recursively, including subpackages. Args: package: package (name or actual module) base_package_for_relative_import: path to prepend? recursive: import submodules too? Returns: dict: mapping from full module name to module
def import_submodules(package: Union[str, ModuleType], base_package_for_relative_import: str = None, recursive: bool = True) -> Dict[str, ModuleType]: # http://stackoverflow.com/questions/3365740/how-to-import-all-submodules if isinstance(package, str): p...
730,556
Performs a :func:`shutil.which` command using the PATH from the specified environment. Reason: when you use ``run([executable, ...], env)`` and therefore ``subprocess.run([executable, ...], env=env)``, the PATH that's searched for ``executable`` is the parent's, not the new child's -- so you have to ...
def which_with_envpath(executable: str, env: Dict[str, str]) -> str: oldpath = os.environ.get("PATH", "") os.environ["PATH"] = env.get("PATH") which = shutil.which(executable) os.environ["PATH"] = oldpath return which
730,560
Performs a recursive ``chown``. Args: path: path to walk down user: user name or ID group: group name or ID As per http://stackoverflow.com/questions/2853723
def chown_r(path: str, user: str, group: str) -> None: for root, dirs, files in os.walk(path): for x in dirs: shutil.chown(os.path.join(root, x), user, group) for x in files: shutil.chown(os.path.join(root, x), user, group)
730,573
Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR``
def chmod_r(root: str, permission: int) -> None: os.chmod(root, permission) for dirpath, dirnames, filenames in os.walk(root): for d in dirnames: os.chmod(os.path.join(dirpath, d), permission) for f in filenames: os.chmod(os.path.join(dirpath, f), permission)
730,574
From a starting list of files and/or directories, generates filenames of all files in the list, and (if ``recursive`` is set) all files within directories in the list. Args: starting_filenames: files and/or directories recursive: walk down any directories in the starting list, recursively? ...
def gen_filenames(starting_filenames: List[str], recursive: bool) -> Generator[str, None, None]: for base_filename in starting_filenames: if os.path.isfile(base_filename): yield os.path.abspath(base_filename) elif os.path.isdir(base_filename) and recursive: ...
730,577
Checks if a file is locked by opening it in append mode. (If no exception is thrown in that situation, then the file is not locked.) Args: filepath: file to check Returns: tuple: ``(exists, locked)`` See https://www.calazan.com/how-to-check-if-a-file-is-locked-in-python/.
def exists_locked(filepath: str) -> Tuple[bool, bool]: exists = False locked = None file_object = None if os.path.exists(filepath): exists = True locked = True try: buffer_size = 8 # Opening file in append mode and read the first 8 characters. ...
730,578
Asks MySQL for its variables and status. Args: mysql: ``mysql`` executable filename host: host name port: TCP/IP port number user: username Returns: dictionary of MySQL variables/values
def get_mysql_vars(mysql: str, host: str, port: int, user: str) -> Dict[str, str]: cmdargs = [ mysql, "-h", host, "-P", str(port), "-e", "SHOW VARIABLES; SHOW STATUS", "-u", user, "-p" # prompt for passwor...
730,597
For "hits": prints either the ``.zip`` filename, or the ``.zip`` filename and the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filename of the inner file show_inner_file: if ``True``, show both; if ``False``, show just the ``.zip`` filen...
def report_hit_filename(zipfilename: str, contentsfilename: str, show_inner_file: bool) -> None: if show_inner_file: print("{} [{}]".format(zipfilename, contentsfilename)) else: print(zipfilename)
730,601
Prints a line from a file, with the ``.zip`` filename and optionally also the inner filename. Args: zipfilename: filename of the ``.zip`` file contentsfilename: filename of the inner file line: the line from the inner file show_inner_file: if ``True``, show both filenames; if ``...
def report_line(zipfilename: str, contentsfilename: str, line: str, show_inner_file: bool) -> None: if show_inner_file: print("{} [{}]: {}".format(zipfilename, contentsfilename, line)) else: print("{}: {}".format(zipfilename, line))
730,602
Validates the form. Args: controls: an iterable of ``(key, value)`` tuples subcontrol: Returns: a Colander ``appstruct`` Raises: ValidationFailure: on failure
def validate(self, controls: Iterable[Tuple[str, str]], subcontrol: str = None) -> Any: try: return super().validate(controls, subcontrol) except ValidationFailure as e: if DEBUG_FORM_VALIDATION: log.warning("Validation f...
730,680
Converts something to a :class:`pendulum.DateTime`. Args: x: something that may be coercible to a datetime assume_local: if ``True``, assume local timezone; if ``False``, assume UTC Returns: a :class:`pendulum.DateTime`, or ``None``. Raises: pendulum.parsing.ex...
def coerce_to_pendulum(x: PotentialDatetimeType, assume_local: bool = False) -> Optional[DateTime]: if not x: # None and blank string return None if isinstance(x, DateTime): return x tz = get_tz_local() if assume_local else get_tz_utc() if isinstance(x, datet...
730,729
Converts something to a :class:`pendulum.Date`. Args: x: something that may be coercible to a date assume_local: if ``True``, assume local timezone; if ``False``, assume UTC Returns: a :class:`pendulum.Date`, or ``None``. Raises: pendulum.parsing.exceptions.Par...
def coerce_to_pendulum_date(x: PotentialDatetimeType, assume_local: bool = False) -> Optional[Date]: p = coerce_to_pendulum(x, assume_local=assume_local) return None if p is None else p.date()
730,730
Calculate the time between two dates/times expressed as strings. Args: start: start date/time end: end date/time default: string value to return in case either of the inputs is ``None`` Returns: a string that is one of .. code-block: 'hh:mm' ...
def get_duration_h_m(start: Union[str, DateTime], end: Union[str, DateTime], default: str = "N/A") -> str: start = coerce_to_pendulum(start) end = coerce_to_pendulum(end) if start is None or end is None: return default duration = end - start min...
730,739
Age (in whole years) at a particular date, or ``default``. Args: dob: date of birth when: date/time at which to calculate age default: value to return if either input is ``None`` Returns: age in whole years (rounded down), or ``default``
def get_age(dob: PotentialDatetimeType, when: PotentialDatetimeType, default: str = "") -> Union[int, str]: dob = coerce_to_pendulum_date(dob) when = coerce_to_pendulum_date(when) if dob is None or when is None: return default return (when - dob).years
730,740
Validates an integer as an NHS number. Args: n: NHS number Returns: valid? Checksum details are at http://www.datadictionary.nhs.uk/version2/data_dictionary/data_field_notes/n/nhs_number_de.asp
def is_valid_nhs_number(n: int) -> bool: # noqa if not isinstance(n, int): log.debug("is_valid_nhs_number: parameter was not of integer type") return False s = str(n) # Not 10 digits long? if len(s) != 10: log.debug("is_valid_nhs_number: not 10 digits") return Fals...
730,776
Generate all rows from a cursor. Args: cursor: the cursor arraysize: split fetches into chunks of this many records Yields: each row
def genrows(cursor: Cursor, arraysize: int = 1000) \ -> Generator[List[Any], None, None]: # http://code.activestate.com/recipes/137270-use-generators-for-fetching-large-db-record-sets/ # noqa while True: results = cursor.fetchmany(arraysize) if not results: break ...
730,893