text
stringlengths
81
112k
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 ...
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 def quick_mapper(table: Table) -> Type[Declarativ...
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...
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 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...
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 def dump_orm_object_as_insert_sql(engine: Engine, ...
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: ...
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. ...
Fetch next page from scroll API. 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_resu...
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 ...
Reads the source file. 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_...
Creates an internal representation of the destination file. This is where the thinking happens def _create_dest(self) -> None: """ Creates an internal representation of the destination file. This is where the thinking happens """ in_body = False in_docstring = ...
Writes a debugging report on a 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)
Rewrites the source 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)
Writes the converted output to a destination. def _write(self, destination: TextIO) -> None: """ Writes the converted output to a destination. """ for line in self.dest_lines: destination.write(line + NL)
Does the iterable contain any duplicate values? 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
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...
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"] def sort_list_...
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 def flatten_list(x: List[Any]) -> List[Any]: """ Converts a list of lists into ...
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 def unique_list(seq: Iterable[Any]) -> List[Any]: ...
Yield successive ``n``-sized chunks from ``l``. Args: l: input list n: chunk size Yields: successive chunks of size ``n`` def chunks(l: List[Any], n: int) -> Iterable[List[Any]]: """ Yield successive ``n``-sized chunks from ``l``. Args: l: input list n: ch...
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: """ Esc...
Reverses :func:`escape_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] ...
Escapes CR, LF, tab, and backslashes. Its counterpart is :func:`unescape_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"\\") # repla...
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...
Outputs a standalone HTML 'report card' for a measurement (or several grouped measurements), including relevant statistical information. def report(*arrays, **kwargs): """ Outputs a standalone HTML 'report card' for a measurement (or several grouped measurements), including relevant statistical...
check that stream record is actual tweet with coordinates 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 ret...
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 def angle_subtended(ell, **kwargs): """ Compute the hal...
Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic 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 = l...
Get axis-aligned elliptical conic from axis lenths This can be converted into a hyperbola by getting the dual conic 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...
Check to see whether point is inside conic. :param exact: Only solutions exactly on conic are considered (default: False). def contains(ell, p, shell_only=False): """ Check to see whether point is inside conic. :param exact: Only solutions exactly on conic ...
Gets major axes of ellipsoids 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
Translates a conic by a vector 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)
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. def polar_plane(conic, vector): """ Calculates the polar plane to a vector (a 'pole') for a given conic...
Calculates the pole of a polar plane for a given conic section. 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]
The elliptical cut of an ellipsoidal conic describing all points of tangency to the conic as viewed from the origin. def projection(self, **kwargs): """ The elliptical cut of an ellipsoidal conic describing all points of tangency to the conic as viewed from the origin. ...
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 def guess_file_na...
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),...
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): """ Encode par...
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): """ Build t...
Build the body for a application/json request. 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""...
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 ...
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 ------- ...
Return a percentile range from an array of values. 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)
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...
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 ...
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...
This is to :func:`read_config_string_options` as :func:`get_config_multiline_option` is to :func:`get_config_string_option`. def read_config_multiline_options(obj: Any, parser: ConfigParser, section: str, options:...
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...
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: ...
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 def get_config_parameter_bo...
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 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 ...
Test if a cursor refers to a definition This occurs when the cursor has a definition, and shares the location of that definiton 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 = ...
Gets a cone of asymptotes for hyperbola 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])
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) def pca_to_mapping(pca,**extra_props): """ A helper to return a mapping of a PCA result set suitable for reconstructing a planar...
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...
Description of the process. def fullname(self) -> str: """ Description of the process. """ fullname = "Process {}/{} ({})".format(self.procnum, self.nprocs, self.details.name) if self.running: fullname += " (PID={})".for...
If we are being verbose, write a debug message to the Python disk log. 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)
Write an info message to the Windows Application log (± to the Python disk log). def info(self, msg: str) -> None: """ Write an info message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences s = "{}: {}".format(s...
Write a warning message to the Windows Application log (± to the Python disk log). 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. # ...
Write an error message to the Windows Application log (± to the Python disk log). def error(self, msg: str) -> None: """ Write an error message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences s = "{}: {}".forma...
Open Python disk 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.log...
Close Python disk 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() ...
Starts a subprocess. Optionally routes its output to our disk logs. 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( ...
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 def stop(self) -> None: """ Stops a subprocess. Asks nicely. Waits. ...
Returns: succeeded in *attempting* a kill? 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 ...
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...
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``. def _kill(self) -> None: ""...
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: ...
Write an info message to the Windows Application log (± to the Python disk log). def info(self, msg: str) -> None: """ Write an info message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences servicemanager.LogInf...
Write an error message to the Windows Application log (± to the Python disk log). def error(self, msg: str) -> None: """ Write an error message to the Windows Application log (± to the Python disk log). """ # noinspection PyUnresolvedReferences servicemanager.Log...
Called when the service is being shut down. 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 ...
Called when the service is started. 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 SE...
Main entry point. Runs :func:`service`. 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( ...
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...
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: Dic...
Retrives the information added to an exception by :func:`add_info_to_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] ...
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...
Still needing this much try-except stuff. We should find a way to get rid of this. :param obj: :return: 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)...
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: ...
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: def _serialize_iterable(obj): """ Only for serializing li...
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`` def disable_bool_icon( fieldname: str, model) -> Callable[...
Get a Django admin site URL for an object. 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() mo...
Get a Django admin site URL for an object that's found from a foreign key in our object of interest. def admin_view_fk_link(modeladmin: ModelAdmin, obj, fkfield: str, missing: str = "(None)", use_str: bool = True, ...
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). def admin_view_reverse_fk_links(modeladmin: ModelAdmin, obj, reverse_fk_set_field: str, ...
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 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 ...
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...
Rotation about the Z axis (in the XY plane) 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]])
Returns error ellipse in slope-azimuth space 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 th...
Create a JSON-serializable representation of the plane that is usable with the javascript frontend 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_di...
Kills children of this process that were registered in the :data:`processes` variable. Use with ``@atexit.register``. def kill_child_processes() -> None: """ Kills children of this process that were registered in the :data:`processes` variable. Use with ``@atexit.register``. """ timeo...
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 ...
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...
Let a subprocess :func:`communicate`, then write both its ``stdout`` and its ``stderr`` to our ``stdout``. 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()...
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: """ Fire up mu...
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...
Read lines and put them on the queue. 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: ...
Create national US and State Map 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.j...