text
stringlengths
81
112k
Finds the angle between the nominal vectors def fit_angle(fit1, fit2, degrees=True): """ Finds the angle between the nominal vectors """ return N.degrees(angle(fit1.normal,fit2.normal))
Distance apart for vectors, given in standard deviations def fit_similarity(fit1, fit2): """ Distance apart for vectors, given in standard deviations """ cov1 = aligned_covariance(fit1) cov2 = aligned_covariance(fit2) if fit2.axes[2,2] < 0: cov2 *= -1 v0 = fit1.normal-fit2.n...
Generates three transformation matrices to map three-dimensional data down to slices on the xy, xz and yz planes, respectively. The typical use case for this is to iterate over the results of this method to provide arguments to e.g. the `HyperbolicErrors` function. def axis_aligned_transforms(): ...
Converts a ``pyplot`` figure to an HTML IMG tag with encapsulated PNG. def png_img_html_from_pyplot_figure(fig: "Figure", dpi: int = 100, extra_html_class: str = None) -> str: """ Converts a ``pyplot`` figure to an HTML IMG tag with encaps...
Converts a ``pyplot`` figure to an SVG tag. def svg_html_from_pyplot_figure(fig: "Figure") -> str: """ Converts a ``pyplot`` figure to an SVG tag. """ if fig is None: return "" memfile = io.BytesIO() # StringIO doesn't like mixing str/unicode fig.savefig(memfile, format="svg") retu...
Sets the current font size within the ``matplotlib`` library. **WARNING:** not an appropriate method for multithreaded environments, as it writes (indirectly) to ``matplotlib`` global objects. See CamCOPS for alternative methods. def set_matplotlib_fontsize(matplotlib: ModuleType, ...
Goes through list of GPG/Keybase keys. For the keybase keys it will attempt to look up the GPG key def massage_keys(keys): """Goes through list of GPG/Keybase keys. For the keybase keys it will attempt to look up the GPG key""" m_keys = [] for key in keys: if key.startswith('keybase:'): ...
Encrypt a file with the specific GPG keys and write out to the specified path def encrypt_file(src, dest, csv_keys): """Encrypt a file with the specific GPG keys and write out to the specified path""" keys = massage_keys(csv_keys.split(',')) cryptorito.encrypt(src, dest, keys)
Encrypt what comes in from stdin and return base64 encrypted against the specified keys, returning on stdout def encrypt_var(csv_keys): """Encrypt what comes in from stdin and return base64 encrypted against the specified keys, returning on stdout""" keys = massage_keys(csv_keys.split(',')) data = ...
Decrypt what comes in from stdin (base64'd) and write it out to stdout def decrypt_var(passphrase=None): """Decrypt what comes in from stdin (base64'd) and write it out to stdout""" encrypted = cryptorito.portable_b64decode(sys.stdin.read()) print(cryptorito.decrypt_var(encrypted, passphrase))
Imports a public GPG key from Keybase def import_keybase(useropt): """Imports a public GPG key from Keybase""" public_key = None u_bits = useropt.split(':') username = u_bits[0] if len(u_bits) == 1: public_key = cryptorito.key_from_keybase(username) else: fingerprint = u_bits[1]...
Execute command line cryptorito actions def do_thing(): """Execute command line cryptorito actions""" if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file": encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4]) elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file": decrypt_file(sys.argv...
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...
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...
Applies a preconfigured datetime/colour scheme to a logger. Should ONLY be called from the ``if __name__ == 'main'`` script; see https://docs.python.org/3.4/howto/logging.html#library-config. Args: logger: logger to modify level: log level to set remove_existing: remove existing ha...
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_...
Remove all handlers from a logger. Args: logger: logger to modify def remove_all_logger_handlers(logger: logging.Logger) -> None: """ Remove all handlers from a logger. Args: logger: logger to modify """ while logger.handlers: h = logger.handlers[0] logger.remo...
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...
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: l...
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...
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...
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...
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. def copy_root_log_to_file(filename: str, fmt: str = LOG_FORMAT, date...
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...
Returns information on a log formatter, as a dictionary. For debugging. def get_formatter_report(f: logging.Formatter) -> Optional[Dict[str, str]]: """ Returns information on a log formatter, as a dictionary. For debugging. """ if f is None: return None return { '_fmt': f._f...
Returns information on a log handler, as a dictionary. For debugging. def get_handler_report(h: logging.Handler) -> Dict[str, Any]: """ Returns information on a log handler, as a dictionary. For debugging. """ return { 'get_name()': h.get_name(), 'level': h.level, 'forma...
Returns information on a log, as a dictionary. For debugging. def get_log_report(log: Union[logging.Logger, logging.PlaceHolder]) -> Dict[str, Any]: """ Returns information on a log, as a dictionary. For debugging. """ if isinstance(log, logging.Logger): # suppress...
Use :func:`print` to report information on all logs. def print_report_on_all_logs() -> None: """ Use :func:`print` to report information on all logs. """ d = {} # noinspection PyUnresolvedReferences for name, obj in logging.Logger.manager.loggerDict.items(): d[name] = get_log_report(obj...
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: """ Set a log level for a log and all its handlers. Args: ...
For use by library functions. Returns a log with the specifed name that has a null handler attached, and a :class:`BraceStyleAdapter`. def get_brace_style_log_with_null_handler(name: str) -> BraceStyleAdapter: """ For use by library functions. Returns a log with the specifed name that has a null handle...
Internal function to format the :class:`LogRecord` as HTML. See https://docs.python.org/3.4/library/logging.html#logging.LogRecord def format(self, record: logging.LogRecord) -> str: """ Internal function to format the :class:`LogRecord` as HTML. See https://docs.python.org/3.4/librar...
Internal function to process a :class:`LogRecord`. def emit(self, record: logging.LogRecord) -> None: """ Internal function to process a :class:`LogRecord`. """ # noinspection PyBroadException try: html = self.format(record) self.logfunction(html) ...
Returns a list of database table names from the :class:`Engine`. def get_table_names(engine: Engine) -> List[str]: """ Returns a list of database table names from the :class:`Engine`. """ insp = Inspector.from_engine(engine) return insp.get_table_names()
Returns a list of database view names from the :class:`Engine`. def get_view_names(engine: Engine) -> List[str]: """ Returns a list of database view names from the :class:`Engine`. """ insp = Inspector.from_engine(engine) return insp.get_view_names()
Does the named table/view exist (either as a table or as a view) in the database? def table_or_view_exists(engine: Engine, table_or_view_name: str) -> bool: """ Does the named table/view exist (either as a table or as a view) in the database? """ tables_and_views = get_table_names(engine) + get...
For the specified table, generate column information as :class:`SqlaColumnInspectionInfo` objects. def gen_columns_info(engine: Engine, tablename: str) -> Generator[SqlaColumnInspectionInfo, None, None]: """ For the specified table, gen...
For the specified column in the specified table, get column information as a :class:`SqlaColumnInspectionInfo` object (or ``None`` if such a column can't be found). def get_column_info(engine: Engine, tablename: str, columnname: str) -> Optional[SqlaColumnInspectionInfo]: """ For th...
For the specified column in the specified table, get its type as an instance of an SQLAlchemy column type class (or ``None`` if such a column can't be found). For more on :class:`TypeEngine`, see :func:`cardinal_pythonlib.orm_inspect.coltype_as_typeengine`. def get_column_type(engine: Engine, tablenam...
Get all the database column names for the specified table. def get_column_names(engine: Engine, tablename: str) -> List[str]: """ Get all the database column names for the specified table. """ return [info.name for info in gen_columns_info(engine, tablename)]
If a table has a PK, this will return its database column name(s); otherwise, ``None``. def get_pk_colnames(table_: Table) -> List[str]: """ If a table has a PK, this will return its database column name(s); otherwise, ``None``. """ pk_names = [] # type: List[str] for col in table_.columns...
If a table has a single-field (non-composite) integer PK, this will return its database column name; otherwise, None. Note that it is legitimate for a database table to have both a composite primary key and a separate ``IDENTITY`` (``AUTOINCREMENT``) integer field. This function won't find such columns...
If a table has a single integer ``AUTOINCREMENT`` column, this will return its name; otherwise, ``None``. - It's unlikely that a database has >1 ``AUTOINCREMENT`` field anyway, but we should check. - SQL Server's ``IDENTITY`` keyword is equivalent to MySQL's ``AUTOINCREMENT``. - Verify agai...
Does the specified index exist for the specified table? def index_exists(engine: Engine, tablename: str, indexname: str) -> bool: """ Does the specified index exist for the specified table? """ insp = Inspector.from_engine(engine) return any(i['name'] == indexname for i in insp.get_indexes(tablenam...
For Microsoft SQL Server specifically: fetch the name of the PK index for the specified table (in the specified schema), or ``''`` if none is found. def mssql_get_pk_index_name(engine: Engine, tablename: str, schemaname: str = MSSQL_DEFAULT_SCHEMA) -> str...
For Microsoft SQL Server specifically: fetch the value of the ``TRANCOUNT`` variable (see e.g. https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017). Returns ``None`` if it can't be found (unlikely?). def mssql_transaction_count(engine_or_conn: Union[Connection, ...
Adds an index to a database column (or, in restricted circumstances, several columns). The table name is worked out from the :class:`Column` object. Args: engine: SQLAlchemy :class:`Engine` object sqla_column: single column to index multiple_sqla_columns: multiple columns to index ...
Returns an instance of :class:`Column` representing a :class:`BigInteger` ``AUTOINCREMENT`` column in the specified :class:`Dialect`. def make_bigint_autoincrement_column(column_name: str, dialect: Dialect) -> Column: """ Returns an instance of :class:`Column` represent...
Returns DDL to create a column, using the specified dialect. The column should already be bound to a table (because e.g. the SQL Server dialect requires this for DDL generation). Manual testing: .. code-block:: python from sqlalchemy.schema import Column, CreateColumn, MetaData, Sequence...
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)...
Returns the SQLAlchemy class corresponding to a particular SQL column type in a given dialect. Performs an upper- and lower-case search. For example, the SQLite dialect uses upper case, and the MySQL dialect uses lower case. def _get_sqla_coltype_class_from_str(coltype: str, ...
Used to extract SQL column type parameters. For example, MySQL has column types that look like ``ENUM('a', 'b', 'c', 'd')``. This function takes the ``"'a', 'b', 'c', 'd'"`` and converts it to ``['a', 'b', 'c', 'd']``. def get_list_of_sql_string_literals_from_quoted_csv(x: str) -> List[str]: """ Used t...
Returns an SQLAlchemy column type, given a column type name (a string) and an SQLAlchemy dialect. For example, this might convert the string ``INTEGER(11)`` to an SQLAlchemy ``Integer(length=11)``. Args: dialect: a SQLAlchemy :class:`Dialect` class coltype: a ``str()`` representation, e.g....
Returns a copy of the specific column type with any ``COLLATION`` removed. def remove_collation(coltype: TypeEngine) -> TypeEngine: """ Returns a copy of the specific column type with any ``COLLATION`` removed. """ if not getattr(coltype, 'collation', None): return coltype newcoltype = copy...
Converts an SQLAlchemy column type from one SQL dialect to another. Args: coltype: SQLAlchemy column type in the source dialect dialect: destination :class:`Dialect` strip_collation: remove any ``COLLATION`` information? convert_mssql_timestamp: since you cannot write...
An example is simplest: if you pass in ``Integer()`` (an instance of :class:`TypeEngine`), you'll get ``Integer()`` back. If you pass in ``Integer`` (an instance of :class:`VisitableType`), you'll also get ``Integer()`` back. The function asserts that its return type is an instance of :class:`TypeEngine...
Is the SQLAlchemy column type a binary type? def is_sqlatype_binary(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a binary type? """ # Several binary types inherit internally from _Binary, making that the # easiest to check. coltype = _coltype_to_typeengi...
Is the SQLAlchemy column type a date type? def is_sqlatype_date(coltype: TypeEngine) -> bool: """ Is the SQLAlchemy column type a date type? """ coltype = _coltype_to_typeengine(coltype) # No longer valid in SQLAlchemy 1.2.11: # return isinstance(coltype, sqltypes._DateAffinity) return ( ...
Is the SQLAlchemy column type an integer type? def is_sqlatype_integer(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type an integer type? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.Integer)
Is the SQLAlchemy column type one that inherits from :class:`Numeric`, such as :class:`Float`, :class:`Decimal`? def is_sqlatype_numeric(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type one that inherits from :class:`Numeric`, such as :class:`Float`, :class:`Decimal...
Is the SQLAlchemy column type a string type? def is_sqlatype_string(coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a string type? """ coltype = _coltype_to_typeengine(coltype) return isinstance(coltype, sqltypes.String)
Is the SQLAlchemy column type a string type that's at least the specified length? def is_sqlatype_text_of_length_at_least( coltype: Union[TypeEngine, VisitableType], min_length: int = 1000) -> bool: """ Is the SQLAlchemy column type a string type that's at least the specified length? ...
Is the SQLAlchemy column type a string type that's more than one character long? def is_sqlatype_text_over_one_char( coltype: Union[TypeEngine, VisitableType]) -> bool: """ Is the SQLAlchemy column type a string type that's more than one character long? """ coltype = _coltype_to_typeeng...
Is the SQLAlchemy column type a type that might merit a ``FULLTEXT`` index (meaning a string type of at least ``min_length``)? def does_sqlatype_merit_fulltext_index( coltype: Union[TypeEngine, VisitableType], min_length: int = 1000) -> bool: """ Is the SQLAlchemy column type a type that mi...
Is the SQLAlchemy column type one that requires its indexes to have a length specified? (MySQL, at least, requires index length to be specified for ``BLOB`` and ``TEXT`` columns: http://dev.mysql.com/doc/refman/5.7/en/create-index.html.) def does_sqlatype_require_index_len( coltype: Union[Type...
Checks that two SQLAlchemy column types are equal (by comparing ``str()`` versions of them). See http://stackoverflow.com/questions/34787794/sqlalchemy-column-type-comparison. IMPERFECT. def column_types_equal(a_coltype: TypeEngine, b_coltype: TypeEngine) -> bool: """ Checks that two SQLA...
Are two SQLAlchemy columns are equal? Checks based on: - column ``name`` - column ``type`` (see :func:`column_types_equal`) - ``nullable`` def columns_equal(a: Column, b: Column) -> bool: """ Are two SQLAlchemy columns are equal? Checks based on: - column ``name`` - column ``type`` (see :...
Are all columns in list ``a`` equal to their counterparts in list ``b``, as per :func:`columns_equal`? def column_lists_equal(a: List[Column], b: List[Column]) -> bool: """ Are all columns in list ``a`` equal to their counterparts in list ``b``, as per :func:`columns_equal`? """ n = len(a) ...
Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
Are all indexes in list ``a`` equal to their counterparts in list ``b``, as per :func:`indexes_equal`? def index_lists_equal(a: List[Index], b: List[Index]) -> bool: """ Are all indexes in list ``a`` equal to their counterparts in list ``b``, as per :func:`indexes_equal`? """ n = len(a) if ...
Convert anything to a ``bytearray``. See - http://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3 - http://stackoverflow.com/questions/10459067/how-to-convert-my-bytearrayb-x9e-x18k-x9a-to-something-like-this-x9e-x1 def to_bytes(data: Any) -> bytearray: """...
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: """ Conve...
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: """ Converts an 8-byte sequence to a long i...
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) -...
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, bytearra...
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: """ Implements 128-bit murmur3 hash for x64, as per ``pymmh3``, ...
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: """ Implements 128-bit murmur3 hash for x86, as per ``pymmh3``, ...
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) ...
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], ...
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: """ Ch...
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: """ Ch...
Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: signed 32-bit integer def hash32(data: Any, seed=0) -> int: """ Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: ...
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: """ Non-cryptographic, deterministic, fast hash. Args: data: data to hash seed: seed Returns: ...
Command-line validation checks. def main() -> None: """ Command-line validation checks. """ _ = """ print(twos_comp_to_signed(0, n_bits=32)) # 0 print(twos_comp_to_signed(2 ** 31 - 1, n_bits=32)) # 2147483647 print(twos_comp_to_signed(2 ** 31, n_bits=32)) # -2147483648 == -(2 ** 31) ...
Returns the hex digest of a HMAC-encoded version of the input. def hash(self, raw: Any) -> str: """ Returns the hex digest of a HMAC-encoded version of the input. """ with MultiTimerContext(timer, TIMING_HASH): raw_bytes = str(raw).encode('utf-8') hmac_obj = hmac...
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]: """ Returns the mean of a list of numbers. Args: ...
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""" Return...
Hmpf. Shouldn't need to have to implement this, but... Conventional rounding to integer via the "round half away from zero" method, e.g. .. code-block:: none 1.1 -> 1 1.5 -> 2 1.6 -> 2 2.0 -> 2 -1.6 -> -2 etc. ... or the equivalent for a certain numbe...
Version of :func:`normal_round_float` but guaranteed to return an `int`. def normal_round_int(x: float) -> int: """ Version of :func:`normal_round_float` but guaranteed to return an `int`. """ if not math.isfinite(x): raise ValueError("Input to normal_round_int() is not finite") if x >= 0: ...
Returns command arguments for a ``mysqldump`` call. Args: mysqldump: ``mysqldump`` executable filename username: user name password: password database: database name verbose: verbose output? with_drop_create_database: produce commands to ``DROP`` the database ...
Command-line processor. See ``--help`` for details. def main() -> None: """ Command-line processor. See ``--help`` for details. """ main_only_quicksetup_rootlogger() wdcd_suffix = "_with_drop_create_database" timeformat = "%Y%m%dT%H%M%S" parser = argparse.ArgumentParser( description...
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: """ Finds the SQLAlchemy di...
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: """ Finds the name...
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, ...
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(identifi...
Download the ANTLR v4 tool jar. (Raises :exception:`OSError` if jar is already available, unless ``lazy`` is ``True``.) :param bool force: Force download even if local jar already exists. :param bool lazy: Don't report an error if local jar already exists and don't try to download it either. def i...
Entry point of the install helper tool to ease the download of the right version of the ANTLR v4 tool jar. def execute(): """ Entry point of the install helper tool to ease the download of the right version of the ANTLR v4 tool jar. """ arg_parser = ArgumentParser(description='Install helper t...
Escape data for tab-separated value (TSV) format. def tsv_escape(x: Any) -> str: """ Escape data for tab-separated value (TSV) format. """ if x is None: return "" x = str(x) return x.replace("\t", "\\t").replace("\n", "\\n")
From a list of values, make a TSV line. def make_tsv_row(values: List[Any]) -> str: """ From a list of values, make a TSV line. """ return "\t".join([tsv_escape(x) for x in values]) + "\n"
From a consistent list of dictionaries mapping fieldnames to values, make a TSV file. def dictlist_to_tsv(dictlist: List[Dict[str, Any]]) -> str: """ From a consistent list of dictionaries mapping fieldnames to values, make a TSV file. """ if not dictlist: return "" fieldnames = dic...
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 ...