signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def main() -> None:
main_only_quicksetup_rootlogger()<EOL>wdcd_suffix = "<STR_LIT>"<EOL>timeformat = "<STR_LIT>"<EOL>parser = argparse.ArgumentParser(<EOL>description="""<STR_LIT>""".format(timeformat=timeformat, suffix=wdcd_suffix),<EOL>formatter_class=argparse.ArgumentDefaultsHelpFormatter)<EOL>parser.add_argument(<EOL>"<STR_LIT>", narg...
Command-line processor. See ``--help`` for details.
f14577:m1
def list_file_extensions(path: str, reportevery: int = <NUM_LIT:1>) -> List[str]:
extensions = set()<EOL>count = <NUM_LIT:0><EOL>for root, dirs, files in os.walk(path):<EOL><INDENT>count += <NUM_LIT:1><EOL>if count % reportevery == <NUM_LIT:0>:<EOL><INDENT>log.debug("<STR_LIT>", count, root)<EOL><DEDENT>for file in files:<EOL><INDENT>filename, ext = os.path.splitext(file)<EOL>extensions.add(ext)<EOL...
Returns a sorted list of every file extension found in a directory and its subdirectories. Args: path: path to scan reportevery: report directory progress after every *n* steps Returns: sorted list of every file extension found
f14578:m0
def main() -> None:
main_only_quicksetup_rootlogger(level=logging.DEBUG)<EOL>parser = argparse.ArgumentParser()<EOL>parser.add_argument("<STR_LIT>", nargs="<STR_LIT:?>", default=os.getcwd())<EOL>parser.add_argument("<STR_LIT>", default=<NUM_LIT>)<EOL>args = parser.parse_args()<EOL>log.info("<STR_LIT>", args.directory)<EOL>print("<STR_LIT:...
Command-line processor. See ``--help`` for details.
f14578:m1
def are_debian_packages_installed(packages: List[str]) -> Dict[str, bool]:
assert len(packages) >= <NUM_LIT:1><EOL>require_executable(DPKG_QUERY)<EOL>args = [<EOL>DPKG_QUERY,<EOL>"<STR_LIT>", <EOL>"<STR_LIT>", <EOL>] + packages<EOL>completed_process = subprocess.run(args,<EOL>stdout=subprocess.PIPE,<EOL>stderr=subprocess.PIPE,<EOL>check=False)<EOL>encoding = sys.getdefaultencoding()<EOL>std...
Check which of a list of Debian packages are installed, via ``dpkg-query``. Args: packages: list of Debian package names Returns: dict: mapping from package name to boolean ("present?")
f14579:m2
def require_debian_packages(packages: List[str]) -> None:
present = are_debian_packages_installed(packages)<EOL>missing_packages = [k for k, v in present.items() if not v]<EOL>if missing_packages:<EOL><INDENT>missing_packages.sort()<EOL>msg = (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format("<STR_LIT:U+0020>".join(missing_packages))<EOL>)<EOL>log.critical(msg)<EOL>raise ValueError(ms...
Ensure specific packages are installed under Debian. Args: packages: list of packages Raises: ValueError: if any are missing
f14579:m3
def validate_pair(ob: Any) -> bool:
try:<EOL><INDENT>if len(ob) != <NUM_LIT:2>:<EOL><INDENT>log.warning("<STR_LIT>", ob)<EOL>raise ValueError()<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>return False<EOL><DEDENT>return True<EOL>
Does the object have length 2?
f14579:m4
def consume(iterator: Iterator[Any]) -> None:
try:<EOL><INDENT>while True:<EOL><INDENT>next(iterator)<EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>pass<EOL><DEDENT>
Consume all remaining values of an iterator. A reminder: iterable versus iterator: https://anandology.com/python-practice-book/iterators.html.
f14579:m5
def windows_get_environment_from_batch_command(<EOL>env_cmd: Union[str, List[str]],<EOL>initial_env: Dict[str, str] = None) -> Dict[str, str]:
<EOL>t isinstance(env_cmd, (list, tuple)):<EOL>nv_cmd = [env_cmd]<EOL>struct the command that will alter the environment<EOL>md = subprocess.list2cmdline(env_cmd)<EOL>ate a tag so we can tell in the output when the proc is done<EOL><INDENT>'<STR_LIT>' <EOL><DEDENT>struct a cmd.exe command to do accomplish this<EOL><IN...
Take a command (either a single command or list of arguments) and return the environment created after running that command. Note that the command must be a batch (``.bat``) file or ``.cmd`` file, or the changes to the environment will not be captured. If ``initial_env`` is supplied, it is used as the initial environm...
f14579:m6
def contains_unquoted_target(x: str,<EOL>quote: str = '<STR_LIT:">', target: str = '<STR_LIT:&>') -> bool:
in_quote = False<EOL>for c in x:<EOL><INDENT>if c == quote:<EOL><INDENT>in_quote = not in_quote<EOL><DEDENT>elif c == target:<EOL><INDENT>if not in_quote:<EOL><INDENT>return True<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>
Checks if ``target`` exists in ``x`` outside quotes (as defined by ``quote``). Principal use: from :func:`contains_unquoted_ampersand_dangerous_to_windows`.
f14579:m7
def contains_unquoted_ampersand_dangerous_to_windows(x: str) -> bool:
return contains_unquoted_target(x, quote='<STR_LIT:">', target='<STR_LIT:&>')<EOL>
Under Windows, if an ampersand is in a path and is not quoted, it'll break lots of things. See https://stackoverflow.com/questions/34124636. Simple example: .. code-block:: bat set RUBBISH=a & b # 'b' is not recognizable as a... command set RUBBISH='a & b' # 'b'' is not recognizable as a... ...
f14579:m8
def modelrepr(instance) -> str:
elements = []<EOL>for f in instance._meta.get_fields():<EOL><INDENT>if f.auto_created:<EOL><INDENT>continue<EOL><DEDENT>if f.is_relation and f.related_model is None:<EOL><INDENT>continue<EOL><DEDENT>fieldname = f.name<EOL>try:<EOL><INDENT>value = repr(getattr(instance, fieldname))<EOL><DEDENT>except ObjectDoesNotExist:...
Default ``repr`` version of a Django model object, for debugging.
f14580:m0
def disable_bool_icon(<EOL>fieldname: str,<EOL>model) -> Callable[[Any], bool]:
<EOL>def func(self, obj):<EOL><INDENT>return getattr(obj, fieldname)<EOL><DEDENT>func.boolean = False<EOL>func.admin_order_field = fieldname<EOL>func.short_description =model._meta.get_field(fieldname).verbose_name<EOL>return func<EOL>
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``
f14581:m0
def admin_view_url(admin_site: AdminSite,<EOL>obj,<EOL>view_type: str = "<STR_LIT>",<EOL>current_app: str = None) -> str:
app_name = obj._meta.app_label.lower()<EOL>model_name = obj._meta.object_name.lower()<EOL>pk = obj.pk<EOL>viewname = "<STR_LIT>".format(app_name, model_name, view_type)<EOL>if current_app is None:<EOL><INDENT>current_app = admin_site.name<EOL><DEDENT>url = reverse(viewname, args=[pk], current_app=current_app)<EOL>retur...
Get a Django admin site URL for an object.
f14581:m1
def admin_view_fk_link(modeladmin: ModelAdmin,<EOL>obj,<EOL>fkfield: str,<EOL>missing: str = "<STR_LIT>",<EOL>use_str: bool = True,<EOL>view_type: str = "<STR_LIT>",<EOL>current_app: str = None) -> str:
if not hasattr(obj, fkfield):<EOL><INDENT>return missing<EOL><DEDENT>linked_obj = getattr(obj, fkfield)<EOL>app_name = linked_obj._meta.app_label.lower()<EOL>model_name = linked_obj._meta.object_name.lower()<EOL>viewname = "<STR_LIT>".format(app_name, model_name, view_type)<EOL>if current_app is None:<EOL><INDENT>curre...
Get a Django admin site URL for an object that's found from a foreign key in our object of interest.
f14581:m2
def admin_view_reverse_fk_links(modeladmin: ModelAdmin,<EOL>obj,<EOL>reverse_fk_set_field: str,<EOL>missing: str = "<STR_LIT>",<EOL>use_str: bool = True,<EOL>separator: str = "<STR_LIT>",<EOL>view_type: str = "<STR_LIT>",<EOL>current_app: str = None) -> str:
if not hasattr(obj, reverse_fk_set_field):<EOL><INDENT>return missing<EOL><DEDENT>linked_objs = getattr(obj, reverse_fk_set_field).all()<EOL>if not linked_objs:<EOL><INDENT>return missing<EOL><DEDENT>first = linked_objs[<NUM_LIT:0>]<EOL>app_name = first._meta.app_label.lower()<EOL>model_name = first._meta.object_name.l...
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).
f14581:m3
def main() -> None:
chars = '<STR_LIT>' <EOL>key = get_random_string(<NUM_LIT:50>, chars)<EOL>print(key)<EOL>
Generates a new Django secret key and prints it to stdout.
f14582:m0
def auto_delete_files_on_instance_delete(instance: Any,<EOL>fieldnames: Iterable[str]) -> None:
for fieldname in fieldnames:<EOL><INDENT>filefield = getattr(instance, fieldname, None)<EOL>if filefield:<EOL><INDENT>if os.path.isfile(filefield.path):<EOL><INDENT>os.remove(filefield.path)<EOL><DEDENT><DEDENT><DEDENT>
Deletes files from filesystem when object is deleted.
f14584:m0
def auto_delete_files_on_instance_change(<EOL>instance: Any,<EOL>fieldnames: Iterable[str],<EOL>model_class) -> None:
if not instance.pk:<EOL><INDENT>return <EOL><DEDENT>try:<EOL><INDENT>old_instance = model_class.objects.get(pk=instance.pk)<EOL><DEDENT>except model_class.DoesNotExist:<EOL><INDENT>return <EOL><DEDENT>for fieldname in fieldnames:<EOL><INDENT>old_filefield = getattr(old_instance, fieldname, None)<EOL>if not old_filefi...
Deletes files from filesystem when object is changed. model_class: ``Type[Model]`` ... only the type checker in Py3.5 is broken; v.s.
f14584:m1
def iso_string_to_python_datetime(<EOL>isostring: str) -> Optional[datetime.datetime]:
if not isostring:<EOL><INDENT>return None <EOL><DEDENT>return dateutil.parser.parse(isostring)<EOL>
Takes an ISO-8601 string and returns a ``datetime``.
f14587:m0
def python_utc_datetime_to_sqlite_strftime_string(<EOL>value: datetime.datetime) -> str:
millisec_str = str(round(value.microsecond / <NUM_LIT:1000>)).zfill(<NUM_LIT:3>)<EOL>return value.strftime("<STR_LIT>") + "<STR_LIT:.>" + millisec_str<EOL>
Converts a Python datetime to a string literal compatible with SQLite, including the millisecond field.
f14587:m1
def python_localized_datetime_to_human_iso(value: datetime.datetime) -> str:
s = value.strftime("<STR_LIT>")<EOL>return s[:<NUM_LIT>] + "<STR_LIT::>" + s[<NUM_LIT>:]<EOL>
Converts a Python ``datetime`` that has a timezone to an ISO-8601 string with ``:`` between the hours and minutes of the timezone. Example: >>> import datetime >>> import pytz >>> x = datetime.datetime.now(pytz.utc) >>> python_localized_datetime_to_human_iso(x) '2017-08-21T20:47:18.952971+00:00'
f14587:m2
def iso_string_to_sql_utcdatetime_mysql(x: str) -> str:
return (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>" <EOL>"<STR_LIT>" <EOL>).format(x=x)<EOL>
Provides MySQL SQL to convert an ISO-8601-format string (with punctuation) to a ``DATETIME`` in UTC. The argument ``x`` is the SQL expression to be converted (such as a column name).
f14587:m3
def iso_string_to_sql_utcdate_mysql(x: str) -> str:
return (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>).format(x=x)<EOL>
Provides MySQL SQL to convert an ISO-8601-format string (with punctuation) to a ``DATE`` in UTC. The argument ``x`` is the SQL expression to be converted (such as a column name).
f14587:m4
def iso_string_to_sql_date_mysql(x: str) -> str:
return "<STR_LIT>".format(x=x)<EOL>
Provides MySQL SQL to convert an ISO-8601-format string (with punctuation) to a ``DATE``, just by taking the date fields (without any timezone conversion). The argument ``x`` is the SQL expression to be converted (such as a column name).
f14587:m5
def iso_string_to_sql_utcdatetime_sqlite(x: str) -> str:
return "<STR_LIT>".format(x=x)<EOL>
Provides SQLite SQL to convert a column to a ``DATETIME`` in UTC. The argument ``x`` is the SQL expression to be converted (such as a column name). Output like: .. code-block:: none 2015-11-14 18:52:47.000 2015-11-14 18:52:47.247 Internally, we don't use ``DATETIME()``; using ``STRFTIME()`` allows millsecon...
f14587:m6
def iso_string_to_sql_utcdatetime_pythonformat_sqlite(x: str) -> str:
return """<STR_LIT>""".format(x=x)<EOL>
Provides SQLite SQL to convert a column to a ``DATETIME`` in UTC, in a string format that matches a common Python format. The argument ``x`` is the SQL expression to be converted (such as a column name). Output like .. code-block:: none 2015-11-14 18:52:47 2015-11-14 18:52:47.247000 i.e. - gets rid of trai...
f14587:m7
def iso_string_to_sql_utcdate_sqlite(x: str) -> str:
return "<STR_LIT>".format(x=x)<EOL>
Provides SQLite SQL to convert a column to a ``DATE`` in UTC. The argument ``x`` is the SQL expression to be converted (such as a column name).
f14587:m8
def iso_string_to_sql_date_sqlite(x: str) -> str:
return "<STR_LIT>".format(x=x)<EOL>
Provides SQLite SQL to convert a column to a ``DATE``, just by taking the date fields (without any timezone conversion). The argument ``x`` is the SQL expression to be converted (such as a column name).
f14587:m9
def isodt_lookup_mysql(lookup, compiler, connection,<EOL>operator) -> Tuple[str, Any]:
lhs, lhs_params = compiler.compile(lookup.lhs)<EOL>rhs, rhs_params = lookup.process_rhs(compiler, connection)<EOL>params = lhs_params + rhs_params<EOL>return '<STR_LIT>'.format(<EOL>lhs=iso_string_to_sql_utcdatetime_mysql(lhs),<EOL>op=operator,<EOL>rhs=rhs,<EOL>), params<EOL>
For a comparison "LHS *op* RHS", transforms the LHS from a column containing an ISO-8601 date/time into an SQL ``DATETIME``, for MySQL.
f14587:m10
def isodt_lookup_sqlite(lookup, compiler, connection,<EOL>operator) -> Tuple[str, Any]:
lhs, lhs_params = compiler.compile(lookup.lhs)<EOL>rhs, rhs_params = lookup.process_rhs(compiler, connection)<EOL>params = lhs_params + rhs_params<EOL>return '<STR_LIT>'.format(<EOL>lhs=iso_string_to_sql_utcdatetime_sqlite(lhs),<EOL>op=operator,<EOL>rhs=rhs,<EOL>), params<EOL>
For a comparison "LHS *op* RHS", transforms the LHS from a column containing an ISO-8601 date/time into an SQL ``DATETIME``, for SQLite.
f14587:m11
def __init__(self, *args, **kwargs) -> None:
<EOL>kwargs['<STR_LIT:max_length>'] = <NUM_LIT:32><EOL>super().__init__(*args, **kwargs)<EOL>
Declare that we're a ``VARCHAR(32)`` on the database side.
f14587:c0:m0
def deconstruct(self) -> Tuple[str, str, List[Any], Dict[str, Any]]:
name, path, args, kwargs = super().deconstruct()<EOL>del kwargs['<STR_LIT:max_length>']<EOL>return name, path, args, kwargs<EOL>
Takes an instance and calculates the arguments to pass to ``__init__`` to reconstruct it.
f14587:c0:m1
def from_db_value(self, value, expression, connection, context):
<EOL>if value is None:<EOL><INDENT>return value<EOL><DEDENT>if value == '<STR_LIT>':<EOL><INDENT>return None<EOL><DEDENT>return iso_string_to_python_datetime(value)<EOL>
Convert database value to Python value. Called when data is loaded from the database.
f14587:c0:m2
def to_python(self, value: Optional[str]) -> Optional[Any]:
<EOL>if isinstance(value, datetime.datetime):<EOL><INDENT>return value<EOL><DEDENT>if value is None:<EOL><INDENT>return value<EOL><DEDENT>if value == '<STR_LIT>':<EOL><INDENT>return None<EOL><DEDENT>return iso_string_to_python_datetime(value)<EOL>
Called during deserialization and during form ``clean()`` calls. Must deal with an instance of the correct type; a string; or ``None`` (if the field allows ``null=True``). Should raise ``ValidationError`` if problems.
f14587:c0:m3
def get_prep_value(self, value):
log.debug("<STR_LIT>", value, type(value))<EOL>if not value:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return value.astimezone(timezone.utc)<EOL>
Convert Python value to database value for QUERYING. We query with UTC, so this function converts datetime values to UTC. Calls to this function are followed by calls to ``get_db_prep_value()``, which is for backend-specific conversions.
f14587:c0:m4
def get_db_prep_value(self, value, connection, prepared=False):
log.debug("<STR_LIT>", value, type(value))<EOL>value = super().get_db_prep_value(value, connection, prepared)<EOL>if value is None:<EOL><INDENT>return value<EOL><DEDENT>if connection.settings_dict['<STR_LIT>'] == '<STR_LIT>':<EOL><INDENT>return python_utc_datetime_to_sqlite_strftime_string(value)<EOL><DEDENT>return val...
Further conversion of Python value to database value for QUERYING. This follows ``get_prep_value()``, and is for backend-specific stuff. See notes above.
f14587:c0:m5
def get_db_prep_save(self, value, connection, prepared=False):
log.debug("<STR_LIT>", value, type(value))<EOL>if not value:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return python_localized_datetime_to_human_iso(value)<EOL>
Convert Python value to database value for SAVING. We save with full timezone information.
f14587:c0:m6
def valid_choice(strvalue: str, choices: Iterable[Tuple[str, str]]) -> bool:
return strvalue in [str(x[<NUM_LIT:0>]) for x in choices]<EOL>
Checks that value is one of the valid option in choices, where choices is a list/tuple of 2-tuples (option, description). Note that parameters sent by URLconf are always strings (https://docs.djangoproject.com/en/1.8/topics/http/urls/) but Python is happy with a string-to-integer-PK lookup, e.g. .. code-block:: pytho...
f14589:m0
def choice_explanation(value: str, choices: Iterable[Tuple[str, str]]) -> str:
for k, v in choices:<EOL><INDENT>if k == value:<EOL><INDENT>return v<EOL><DEDENT><DEDENT>return '<STR_LIT>'<EOL>
Returns the explanation associated with a Django choice tuple-list.
f14589:m1
def from_db_value(self, value, expression, connection, context):
if value is None:<EOL><INDENT>return value<EOL><DEDENT>return json_decode(value)<EOL>
"Called in all circumstances when the data is loaded from the database, including in aggregates and values() calls."
f14590:c0:m0
def to_python(self, value):
if value is None:<EOL><INDENT>return value<EOL><DEDENT>if not isinstance(value, str):<EOL><INDENT>return value<EOL><DEDENT>try:<EOL><INDENT>return json_decode(value)<EOL><DEDENT>except Exception as err:<EOL><INDENT>raise ValidationError(repr(err))<EOL><DEDENT>
"Called during deserialization and during the clean() method used from forms.... [s]hould deal gracefully with... (*) an instance of the correct type; (*) a string; (*) None (if the field allows null=True)." "For ``to_python()``, if anything goes wrong during value conversion, you should raise a ``ValidationError`` ex...
f14590:c0:m1
def get_prep_value(self, value):
return json_encode(value)<EOL>
Converse of ``to_python()``. Converts Python objects back to query values.
f14590:c0:m2
def clean_int(x) -> int:
try:<EOL><INDENT>return int(x)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise forms.ValidationError(<EOL>"<STR_LIT>".format(repr(x)))<EOL><DEDENT>
Returns its parameter as an integer, or raises ``django.forms.ValidationError``.
f14591:m0
def clean_nhs_number(x) -> int:
try:<EOL><INDENT>x = int(x)<EOL>if not is_valid_nhs_number(x):<EOL><INDENT>raise ValueError<EOL><DEDENT>return x<EOL><DEDENT>except ValueError:<EOL><INDENT>raise forms.ValidationError(<EOL>"<STR_LIT>".format(repr(x)))<EOL><DEDENT>
Returns its parameter as a valid integer NHS number, or raises ``django.forms.ValidationError``.
f14591:m1
def get_request_cache():
assert _installed_middleware, '<STR_LIT>'<EOL>return _request_cache[currentThread()]<EOL>
Returns the Django request cache for the current thread. Requires that ``RequestCacheMiddleware`` is loaded.
f14593:m0
def get_call_signature(fn: FunctionType,<EOL>args: ArgsType,<EOL>kwargs: KwargsType,<EOL>debug_cache: bool = False) -> str:
<EOL>try:<EOL><INDENT>call_sig = json_encode((fn.__qualname__, args, kwargs))<EOL><DEDENT>except TypeError:<EOL><INDENT>log.critical(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise<EOL><DEDENT>if debug_cache:<EOL><INDENT>log.debug("<STR_LIT>", call_sig)<EOL><DEDENT>return call_sig<EOL>
Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use indirectly as a cache key. The string is a JSON representation. See ``make_cache_key`` for a more suitable actual cache key.
f14595:m0
def make_cache_key(call_signature: str,<EOL>debug_cache: bool = False) -> str:
key = hashlib.md5(call_signature.encode("<STR_LIT:utf-8>")).hexdigest()<EOL>if debug_cache:<EOL><INDENT>log.debug("<STR_LIT>",<EOL>key, call_signature)<EOL><DEDENT>return key<EOL>
Takes a function and its args/kwargs, and produces a string description of the function call (the call signature) suitable for use as a cache key. The string is an MD5 hash of the JSON-encoded call signature. The logic behind these decisions is as follows: - We have a bunch of components of arbitrary type, and we need...
f14595:m1
def django_cache_function(timeout: int = <NUM_LIT:5> * <NUM_LIT>,<EOL>cache_key: str = '<STR_LIT>',<EOL>debug_cache: bool = False):
cache_key = cache_key or None<EOL>def decorator(fn):<EOL><INDENT>def wrapper(*args, **kwargs):<EOL><INDENT>if cache_key:<EOL><INDENT>call_sig = '<STR_LIT>'<EOL>_cache_key = cache_key<EOL>check_stored_call_sig = False<EOL><DEDENT>else:<EOL><INDENT>call_sig = get_call_signature(fn, args, kwargs)<EOL>_cache_key = make_cac...
Decorator to add caching to a function in Django. Uses the Django default cache. Args: timeout: timeout in seconds; use None for "never expire", as 0 means "do not cache". cache_key: optional cache key to use (if falsy, we'll invent one) debug_cache: show hits/misses?
f14595:m2
def add_http_headers_for_attachment(response: HttpResponse,<EOL>offered_filename: str = None,<EOL>content_type: str = None,<EOL>as_attachment: bool = False,<EOL>as_inline: bool = False,<EOL>content_length: int = None) -> None:
if offered_filename is None:<EOL><INDENT>offered_filename = '<STR_LIT>'<EOL><DEDENT>if content_type is None:<EOL><INDENT>content_type = '<STR_LIT>'<EOL><DEDENT>response['<STR_LIT:Content-Type>'] = content_type<EOL>if as_attachment:<EOL><INDENT>prefix = '<STR_LIT>'<EOL><DEDENT>elif as_inline:<EOL><INDENT>prefix = '<STR_...
Add HTTP headers to a Django response class object. Args: response: ``HttpResponse`` instance offered_filename: filename that the client browser will suggest content_type: HTTP content type as_attachment: if True, browsers will generally save to disk. If False, they may display it inline. ...
f14596:m0
def serve_file(path_to_file: str,<EOL>offered_filename: str = None,<EOL>content_type: str = None,<EOL>as_attachment: bool = False,<EOL>as_inline: bool = False) -> HttpResponseBase:
<EOL>if offered_filename is None:<EOL><INDENT>offered_filename = os.path.basename(path_to_file) or '<STR_LIT>'<EOL><DEDENT>if settings.XSENDFILE:<EOL><INDENT>response = HttpResponse()<EOL>response['<STR_LIT>'] = smart_str(path_to_file)<EOL>content_length = os.path.getsize(path_to_file)<EOL><DEDENT>else:<EOL><INDENT>res...
Serve up a file from disk. Two methods (chosen by ``settings.XSENDFILE``): (a) serve directly (b) serve by asking the web server to do so via the X-SendFile directive.
f14596:m1
def serve_buffer(data: bytes,<EOL>offered_filename: str = None,<EOL>content_type: str = None,<EOL>as_attachment: bool = True,<EOL>as_inline: bool = False) -> HttpResponse:
response = HttpResponse(data)<EOL>add_http_headers_for_attachment(response,<EOL>offered_filename=offered_filename,<EOL>content_type=content_type,<EOL>as_attachment=as_attachment,<EOL>as_inline=as_inline,<EOL>content_length=len(data))<EOL>return response<EOL>
Serve up binary data from a buffer. Options as for ``serve_file()``.
f14596:m2
def add_download_filename(response: HttpResponse, filename: str) -> None:
<EOL>add_http_headers_for_attachment(response)<EOL>response['<STR_LIT>'] = '<STR_LIT>'.format(<EOL>filename)<EOL>
Adds a ``Content-Disposition`` header to the HTTP response to say that there is an attachment with the specified filename.
f14596:m3
def file_response(data: Union[bytes, str], <EOL>content_type: str,<EOL>filename: str) -> HttpResponse:
response = HttpResponse(data, content_type=content_type)<EOL>add_download_filename(response, filename)<EOL>return response<EOL>
Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment.
f14596:m4
def serve_concatenated_pdf_from_disk(<EOL>filenames: Iterable[str],<EOL>offered_filename: str = "<STR_LIT>",<EOL>**kwargs) -> HttpResponse:
pdf = get_concatenated_pdf_from_disk(filenames, **kwargs)<EOL>return serve_buffer(pdf,<EOL>offered_filename=offered_filename,<EOL>content_type=MimeType.PDF,<EOL>as_attachment=False,<EOL>as_inline=True)<EOL>
Concatenates PDFs from disk and serves them.
f14596:m5
def serve_concatenated_pdf_from_memory(<EOL>pdf_plans: Iterable[PdfPlan],<EOL>start_recto: bool = True,<EOL>offered_filename: str = "<STR_LIT>") -> HttpResponse:
pdf = get_concatenated_pdf_in_memory(pdf_plans, start_recto=start_recto)<EOL>return serve_buffer(pdf,<EOL>offered_filename=offered_filename,<EOL>content_type=MimeType.PDF,<EOL>as_attachment=False,<EOL>as_inline=True)<EOL>
Concatenates PDFs into memory and serves it. WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish.
f14596:m7
def open(self) -> bool:
if self.connection:<EOL><INDENT>return False<EOL><DEDENT>connection_params = {'<STR_LIT>': DNS_NAME.get_fqdn()}<EOL>if self.timeout is not None:<EOL><INDENT>connection_params['<STR_LIT>'] = self.timeout<EOL><DEDENT>try:<EOL><INDENT>self.connection = smtplib.SMTP(self.host, self.port,<EOL>**connection_params)<EOL>contex...
Ensures we have a connection to the email server. Returns whether or not a new connection was required (True or False).
f14597:c0:m2
def timedelta_days(days: int) -> timedelta64:
int_days = int(days)<EOL>if int_days != days:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(days))<EOL><DEDENT>try:<EOL><INDENT>return timedelta64(int_days, '<STR_LIT:D>')<EOL><DEDENT>except ValueError as e:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(days, e))<EOL><DEDENT>
Convert a duration in days to a NumPy ``timedelta64`` object.
f14598:m0
def _get_generic_two_antidep_episodes_result(<EOL>rowdata: Tuple[Any, ...] = None) -> DataFrame:
<EOL>data = [rowdata] if rowdata else []<EOL>return DataFrame(array(<EOL>data, <EOL>dtype=[ <EOL>(RCN_PATIENT_ID, DTYPE_STRING),<EOL>(RCN_DRUG_A_NAME, DTYPE_STRING),<EOL>(RCN_DRUG_A_FIRST_MENTION, DTYPE_DATE),<EOL>(RCN_DRUG_A_SECOND_MENTION, DTYPE_DATE),<EOL>(RCN_DRUG_B_NAME, DTYPE_STRING),<EOL>(RCN_DRUG_B_FIRST_MENT...
Create a results row for this application.
f14598:m1
def _get_blank_two_antidep_episodes_result() -> DataFrame:
return _get_generic_two_antidep_episodes_result()<EOL>
Returns a blank results row.
f14598:m2
def two_antidepressant_episodes_single_patient(<EOL>patient_id: str,<EOL>patient_drug_date_df: DataFrame,<EOL>patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME,<EOL>drug_colname: str = DEFAULT_SOURCE_DRUG_COLNAME,<EOL>date_colname: str = DEFAULT_SOURCE_DATE_COLNAME,<EOL>course_length_days: int = DEFAULT_ANTIDEPRESS...
log.debug("<STR_LIT>"<EOL>"<STR_LIT>".format(patient_id))<EOL>all_episodes_for_patient = _get_blank_two_antidep_episodes_result()<EOL>flush_stdout_stderr()<EOL>sourcecolnum_drug = patient_drug_date_df.columns.get_loc(drug_colname)<EOL>sourcecolnum_date = patient_drug_date_df.columns.get_loc(date_colname)<EOL>patient_ma...
Processes a single patient for ``two_antidepressant_episodes()`` (q.v.). Implements the key algorithm.
f14598:m3
def two_antidepressant_episodes(<EOL>patient_drug_date_df: DataFrame,<EOL>patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME,<EOL>drug_colname: str = DEFAULT_SOURCE_DRUG_COLNAME,<EOL>date_colname: str = DEFAULT_SOURCE_DATE_COLNAME,<EOL>course_length_days: int = DEFAULT_ANTIDEPRESSANT_COURSE_LENGTH_DAYS,<EOL>expect_r...
<EOL>log.info("<STR_LIT>")<EOL>start = Pendulum.now()<EOL>patient_ids = sorted(list(set(patient_drug_date_df[patient_colname])))<EOL>n_patients = len(patient_ids)<EOL>log.info("<STR_LIT>", n_patients)<EOL>flush_stdout_stderr()<EOL>def _get_patient_result(_patient_id: str) -> Optional[DataFrame]:<EOL><INDENT>return two_...
Takes a *pandas* ``DataFrame``, ``patient_drug_date_df`` (or, via ``reticulate``, an R ``data.frame`` or ``data.table``). This should contain dated present-tense references to antidepressant drugs (only). Returns a set of result rows as a ``DataFrame``.
f14598:m4
def get_python_repr(x: Any) -> str:
return repr(x)<EOL>
r""" A few notes: **data.table()** Data tables are converted to a Python dictionary: .. code-block:: r dt <- data.table( subject = c("Alice", "Bob", "Charles", "Dawn", "Egbert", "Flora"), drug = c("citalopram", "Cipramil", "Prozac", "fluoxetine", ...
f14599:m0
def get_python_repr_of_type(x: Any) -> str:
return repr(type(x))<EOL>
See ``get_python_repr``. .. code-block:: r dt_type_repr <- cpl_rfunc$get_python_repr_of_type(dt) gives this when a duff import is used via ``reticulate::import_from_path()``: .. code-block:: none [1] "<class 'dict'>" but this when a proper import is used via ``reticulate::import()``: .. code-block:: none...
f14599:m1
def flush_stdout_stderr() -> None:
sys.stdout.flush()<EOL>sys.stderr.flush()<EOL>
R code won't see much unless we flush stdout/stderr manually. See also https://github.com/rstudio/reticulate/issues/284
f14599:m3
def drug_timelines(<EOL>drug_events_df: DataFrame,<EOL>event_lasts_for: datetime.timedelta,<EOL>patient_colname: str = DEFAULT_PATIENT_COLNAME,<EOL>event_datetime_colname: str = DEFAULT_DRUG_EVENT_DATETIME_COLNAME)-> Dict[Any, IntervalList]:
sourcecolnum_pt = drug_events_df.columns.get_loc(patient_colname)<EOL>sourcecolnum_when = drug_events_df.columns.get_loc(event_datetime_colname)<EOL>timelines = defaultdict(IntervalList)<EOL>nrows = len(drug_events_df)<EOL>for rowidx in range(nrows):<EOL><INDENT>patient_id = drug_events_df.iat[rowidx, sourcecolnum_pt]<...
Takes a set of drug event start times (one or more per patient), plus a fixed time that each event is presumed to last for, and returns an :class:`IntervalList` for each patient representing the set of events (which may overlap, in which case they will be amalgamated). Args: drug_events_df: pandas :class:`...
f14600:m0
def cumulative_time_on_drug(<EOL>drug_events_df: DataFrame,<EOL>query_times_df: DataFrame,<EOL>event_lasts_for_timedelta: datetime.timedelta = None,<EOL>event_lasts_for_quantity: float = None,<EOL>event_lasts_for_units: str = None,<EOL>patient_colname: str = DEFAULT_PATIENT_COLNAME,<EOL>event_datetime_colname: str = DE...
if event_lasts_for_timedelta is None:<EOL><INDENT>assert event_lasts_for_quantity and event_lasts_for_units<EOL>timedelta_dict = {event_lasts_for_units: event_lasts_for_quantity}<EOL>event_lasts_for_timedelta = datetime.timedelta(**timedelta_dict)<EOL><DEDENT>if debug:<EOL><INDENT>log.critical("<STR_LIT>", drug_events_...
Args: drug_events_df: pandas :class:`DataFrame` containing the event data, with columns named according to ``patient_colname``, ``event_datetime_colname`` event_lasts_for_timedelta: when an event occurs, how long is it assumed to last for? For example, if a prescription of lithiu...
f14600:m1
def get_drug(drug_name: str,<EOL>name_is_generic: bool = False,<EOL>include_categories: bool = False) -> Optional[Drug]:
drug_name = drug_name.strip().lower()<EOL>if name_is_generic:<EOL><INDENT>drug = DRUGS_BY_GENERIC_NAME.get(drug_name) <EOL>if drug is not None and drug.category_not_drug and not include_categories: <EOL><INDENT>return None<EOL><DEDENT>return drug<EOL><DEDENT>else:<EOL><INDENT>for d in DRUGS:<EOL><INDENT>if d.name_mat...
Converts a drug name to a :class:`.Drug` class. If you already have the generic name, you can get the Drug more efficiently by setting ``name_is_generic=True``. Set ``include_categories=True`` to include drug categories (such as tricyclics) as well as individual drugs.
f14602:m0
def drug_name_to_generic(drug_name: str,<EOL>unknown_to_default: bool = False,<EOL>default: str = None,<EOL>include_categories: bool = False) -> str:
drug = get_drug(drug_name, include_categories=include_categories)<EOL>if drug is not None:<EOL><INDENT>return drug.generic_name<EOL><DEDENT>return default if unknown_to_default else drug_name<EOL>
Converts a drug name to the name of its generic equivalent.
f14602:m1
def drug_names_to_generic(drugs: List[str],<EOL>unknown_to_default: bool = False,<EOL>default: str = None,<EOL>include_categories: bool = False) -> List[str]:
return [<EOL>drug_name_to_generic(drug,<EOL>unknown_to_default=unknown_to_default,<EOL>default=default,<EOL>include_categories=include_categories)<EOL>for drug in drugs<EOL>]<EOL>
Converts a list of drug names to their generic equivalents. The arguments are as for :func:`drug_name_to_generic` but this function handles a list of drug names rather than a single one. Note in passing the following conversion of blank-type representations from R via ``reticulate``, when using e.g. the ``default`` p...
f14602:m2
def drug_matches_criteria(drug: Drug, **criteria: Dict[str, bool]) -> bool:
for attribute, value in criteria.items():<EOL><INDENT>if getattr(drug, attribute) != value:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
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 arguments like ``antidepressa...
f14602:m3
def all_drugs_where(sort=True,<EOL>include_categories: bool = False,<EOL>**criteria: Dict[str, bool]) -> List[Drug]:
matching_drugs = [] <EOL>for drug in DRUGS:<EOL><INDENT>if drug.category_not_drug and not include_categories:<EOL><INDENT>continue<EOL><DEDENT>if drug_matches_criteria(drug, **criteria):<EOL><INDENT>matching_drugs.append(drug)<EOL><DEDENT><DEDENT>if sort:<EOL><INDENT>matching_drugs.sort(key=lambda d: d.generic_name)<E...
Find all drugs matching the specified criteria (see :func:`drug_matches_criteria`). If ``include_categories`` is true, then drug categories (like "tricyclics") are included as well as individual drugs. Pass keyword arguments such as .. code-block:: python from cardinal_pythonlib.psychiatry.drugs import * non...
f14602:m4
def drug_name_matches_criteria(drug_name: str,<EOL>name_is_generic: bool = False,<EOL>include_categories: bool = False,<EOL>**criteria: Dict[str, bool]) -> bool:
drug = get_drug(drug_name, name_is_generic)<EOL>if drug is None:<EOL><INDENT>return False<EOL><DEDENT>if drug.category_not_drug and not include_categories:<EOL><INDENT>return False<EOL><DEDENT>return drug_matches_criteria(drug, **criteria)<EOL>
Establish whether a single drug, passed by name, matches the specified criteria. See :func:`drug_matches_criteria`.
f14602:m5
def drug_names_match_criteria(drug_names: List[str],<EOL>names_are_generic: bool = False,<EOL>include_categories: bool = False,<EOL>**criteria: Dict[str, bool]) -> List[bool]:
return [<EOL>drug_name_matches_criteria(<EOL>dn,<EOL>name_is_generic=names_are_generic,<EOL>include_categories=include_categories,<EOL>**criteria)<EOL>for dn in drug_names<EOL>]<EOL>
Establish whether multiple drugs, passed as a list of drug names, each matches the specified criteria. See :func:`drug_matches_criteria`.
f14602:m6
@property<EOL><INDENT>def regex_text(self) -> str:<DEDENT>
if self._regex_text is None:<EOL><INDENT>possibilities = [] <EOL>for p in list(set(self.all_generics + self.alternatives)):<EOL><INDENT>if self.add_preceding_word_boundary and not p.startswith(WB):<EOL><INDENT>p = WB + p<EOL><DEDENT>if self.add_preceding_wildcards and not p.startswith(WILDCARD):<EOL><INDENT>p = WILDCA...
Return regex text (yet to be compiled) for this drug.
f14602:c0:m1
@property<EOL><INDENT>def regex(self) -> Pattern:<DEDENT>
if self._regex is None:<EOL><INDENT>self._regex = re.compile(self.regex_text,<EOL>re.IGNORECASE | re.DOTALL)<EOL><DEDENT>return self._regex<EOL>
Returns a compiled regex for this drug.
f14602:c0:m2
@staticmethod<EOL><INDENT>def regex_to_sql_like(regex_text: str,<EOL>single_wildcard: str = "<STR_LIT:_>",<EOL>zero_or_more_wildcard: str = "<STR_LIT:%>") -> List[str]:<DEDENT>
def append_to_all(new_content: str) -> None:<EOL><INDENT>nonlocal results<EOL>results = [r + new_content for r in results]<EOL><DEDENT>def split_and_append(new_options: List[str]) -> None:<EOL><INDENT>nonlocal results<EOL>newresults = [] <EOL>for option in new_options:<EOL><INDENT>newresults.extend([r + option for r i...
Converts regular expression text to a reasonably close fragment for the SQL ``LIKE`` operator. NOT PERFECT, but works for current built-in regular expressions. Args: regex_text: regular expression text to work with single_wildcard: SQL single wildcard, typically an underscore zero_or_more_wildcard: SQL "z...
f14602:c0:m3
@property<EOL><INDENT>def sql_like_fragments(self) -> List[str]:<DEDENT>
if self._sql_like_fragments is None:<EOL><INDENT>self._sql_like_fragments = []<EOL>for p in list(set(self.all_generics + self.alternatives)):<EOL><INDENT>self._sql_like_fragments.extend(self.regex_to_sql_like(p))<EOL><DEDENT><DEDENT>return self._sql_like_fragments<EOL>
Returns all the string literals to which a database column should be compared using the SQL ``LIKE`` operator, to match this drug. This isn't as accurate as the regex, but ``LIKE`` can do less. ``LIKE`` uses the wildcards ``?`` and ``%``.
f14602:c0:m4
def name_matches(self, name: str) -> bool:
return bool(self.regex.match(name))<EOL>
Detects whether the name that's passed matches our knowledge of any of things that this drug might be called: generic name, brand name(s), common misspellings. The parameter should be pre-stripped of edge whitespace.
f14602:c0:m5
def sql_column_like_drug(self, column_name: str) -> str:
clauses = [<EOL>"<STR_LIT>".format(<EOL>col=column_name,<EOL>fragment=sql_string_literal(f))<EOL>for f in self.sql_like_fragments<EOL>]<EOL>return "<STR_LIT>".format("<STR_LIT>".join(clauses))<EOL>
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 fragment as above
f14602:c0:m6
def get_head_form_html(req: "<STR_LIT>", forms: List[Form]) -> str:
<EOL>js_resources = [] <EOL>css_resources = [] <EOL>for form in forms:<EOL><INDENT>resources = form.get_widget_resources() <EOL>js_resources.extend(x for x in resources['<STR_LIT>']<EOL>if x not in js_resources)<EOL>css_resources.extend(x for x in resources['<STR_LIT>']<EOL>if x not in css_resources)<EOL><DEDENT>js_...
Returns the extra HTML that needs to be injected into the ``<head>`` section for a Deform form to work properly.
f14603:m0
def debug_validator(validator: ValidatorType) -> ValidatorType:
def _validate(node: SchemaNode, value: Any) -> None:<EOL><INDENT>log.debug("<STR_LIT>", value)<EOL>try:<EOL><INDENT>validator(node, value)<EOL>log.debug("<STR_LIT>")<EOL><DEDENT>except Invalid:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>raise<EOL><DEDENT><DEDENT>return _validate<EOL>
Use as a wrapper around a validator, e.g. .. code-block:: python self.validator = debug_validator(OneOf(["some", "values"])) If you do this, the log will show the thinking of the validator (what it's trying to validate, and whether it accepted or rejected the value).
f14603:m1
def gen_fields(field: Field) -> Generator[Field, None, None]:
yield field<EOL>for c in field.children:<EOL><INDENT>for f in gen_fields(c):<EOL><INDENT>yield f<EOL><DEDENT><DEDENT>
Starting with a Deform :class:`Field`, yield the field itself and any children.
f14603:m2
def __init__(self, msg: str, *children: "<STR_LIT>") -> None:
self._msg = msg<EOL>self.children = children<EOL>
Args: msg: error message children: further, child errors (e.g. from subfields with problems)
f14603:c0:m0
def validate(self,<EOL>controls: Iterable[Tuple[str, str]],<EOL>subcontrol: str = None) -> Any:
try:<EOL><INDENT>return super().validate(controls, subcontrol)<EOL><DEDENT>except ValidationFailure as e:<EOL><INDENT>if DEBUG_FORM_VALIDATION:<EOL><INDENT>log.warning("<STR_LIT>",<EOL>e, self._get_form_errors())<EOL><DEDENT>self._show_hidden_widgets_for_fields_with_errors(self)<EOL>raise<EOL><DEDENT>
Validates the form. Args: controls: an iterable of ``(key, value)`` tuples subcontrol: Returns: a Colander ``appstruct`` Raises: ValidationFailure: on failure
f14603:c1:m0
def __init__(self,<EOL>*args,<EOL>dynamic_descriptions: bool = True,<EOL>dynamic_titles: bool = False,<EOL>**kwargs) -> None:
self.dynamic_descriptions = dynamic_descriptions<EOL>self.dynamic_titles = dynamic_titles<EOL>super().__init__(*args, **kwargs)<EOL>
Args: args: other positional arguments to :class:`InformativeForm` dynamic_descriptions: use dynamic descriptions? dynamic_titles: use dynamic titles? kwargs: other keyword arguments to :class:`InformativeForm`
f14603:c2:m0
def gut_message(message: Message) -> Message:
wrapper = Message()<EOL>wrapper.add_header('<STR_LIT:Content-Type>', '<STR_LIT>',<EOL>access_type='<STR_LIT>',<EOL>expiration=time.strftime("<STR_LIT>"),<EOL>size=str(len(message.get_payload())))<EOL>message.set_payload('<STR_LIT>')<EOL>wrapper.set_payload([message])<EOL>return wrapper<EOL>
Remove body from a message, and wrap in a message/external-body.
f14604:m0
def message_is_binary(message: Message) -> bool:
return message.get_content_maintype() not in ('<STR_LIT:text>', '<STR_LIT:message>')<EOL>
Determine if a non-multipart message is of binary type.
f14604:m1
def clean_message(message: Message, topmost: bool = False) -> Message:
if message.is_multipart():<EOL><INDENT>if message.get_content_type() != '<STR_LIT>':<EOL><INDENT>parts = message.get_payload()<EOL>parts[:] = map(clean_message, parts)<EOL><DEDENT><DEDENT>elif message_is_binary(message):<EOL><INDENT>if not topmost:<EOL><INDENT>message = gut_message(message)<EOL><DEDENT><DEDENT>return m...
Clean a message of all its binary parts. This guts all binary attachments, and returns the message itself for convenience.
f14604:m2
def make_email(from_addr: str,<EOL>date: str = None,<EOL>sender: str = "<STR_LIT>",<EOL>reply_to: Union[str, List[str]] = "<STR_LIT>",<EOL>to: Union[str, List[str]] = "<STR_LIT>",<EOL>cc: Union[str, List[str]] = "<STR_LIT>",<EOL>bcc: Union[str, List[str]] = "<STR_LIT>",<EOL>subject: str = "<STR_LIT>",<EOL>body: str = "...
def _csv_list_to_list(x: str) -> List[str]:<EOL><INDENT>stripped = [item.strip() for item in x.split(COMMA)]<EOL>return [item for item in stripped if item]<EOL><DEDENT>def _assert_nocomma(x: Union[str, List[str]]) -> None:<EOL><INDENT>if isinstance(x, str):<EOL><INDENT>x = [x]<EOL><DEDENT>for _addr in x:<EOL><INDENT>as...
Makes an e-mail message. Arguments that can be multiple e-mail addresses are (a) a single e-mail address as a string, or (b) a list of strings (each a single e-mail address), or (c) a comma-separated list of multiple e-mail addresses. Args: from_addr: name of the sender for the "From:" field date: e-mail date...
f14605:m0
def send_msg(from_addr: str,<EOL>to_addrs: Union[str, List[str]],<EOL>host: str,<EOL>user: str,<EOL>password: str,<EOL>port: int = None,<EOL>use_tls: bool = True,<EOL>msg: email.mime.multipart.MIMEMultipart = None,<EOL>msg_string: str = None) -> None:
assert bool(msg) != bool(msg_string), "<STR_LIT>"<EOL>try:<EOL><INDENT>session = smtplib.SMTP(host, port)<EOL><DEDENT>except smtplib.SMTPException as e:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(<EOL>host, port, e))<EOL><DEDENT>try:<EOL><INDENT>session.ehlo()<EOL><DEDENT>except smtplib.SMTPException as e:<...
Sends a pre-built e-mail message. Args: from_addr: e-mail address for 'From:' field to_addrs: address or list of addresses to transmit to host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default ...
f14605:m1
def send_email(from_addr: str,<EOL>host: str,<EOL>user: str,<EOL>password: str,<EOL>port: int = None,<EOL>use_tls: bool = True,<EOL>date: str = None,<EOL>sender: str = "<STR_LIT>",<EOL>reply_to: Union[str, List[str]] = "<STR_LIT>",<EOL>to: Union[str, List[str]] = "<STR_LIT>",<EOL>cc: Union[str, List[str]] = "<STR_LIT>"...
<EOL>instance(to, str):<EOL>o = [to]<EOL>instance(cc, str):<EOL>c = [cc]<EOL>instance(bcc, str):<EOL>cc = [bcc]<EOL>----------------------------------------------------------------------<EOL>e it<EOL>----------------------------------------------------------------------<EOL>sg = make_email(<EOL>from_addr=from_addr,<EOL...
Sends an e-mail in text/html format using SMTP via TLS. Args: host: mail server host user: username on mail server password: password for username on mail server port: port to use, or ``None`` for protocol default use_tls: use TLS, rather than plain SMTP? date: e-mail date in RFC 2822 format, ...
f14605:m2
def is_email_valid(email_: str) -> bool:
<EOL>return _SIMPLE_EMAIL_REGEX.match(email_) is not None<EOL>
Performs a very basic check that a string appears to be an e-mail address.
f14605:m3
def get_email_domain(email_: str) -> str:
return email_.split("<STR_LIT:@>")[<NUM_LIT:1>]<EOL>
Returns the domain part of an e-mail address.
f14605:m4
def main() -> None:
logging.basicConfig()<EOL>log.setLevel(logging.DEBUG)<EOL>parser = argparse.ArgumentParser(<EOL>description="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT:host>", action="<STR_LIT:store>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(...
Command-line processor. See ``--help`` for details.
f14605:m5
def png_img_html_from_pyplot_figure(fig: "<STR_LIT>",<EOL>dpi: int = <NUM_LIT:100>,<EOL>extra_html_class: str = None) -> str:
if fig is None:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>memfile = io.BytesIO()<EOL>fig.savefig(memfile, format="<STR_LIT>", dpi=dpi)<EOL>memfile.seek(<NUM_LIT:0>)<EOL>pngblob = memoryview(memfile.read())<EOL>return rnc_web.get_png_img_html(pngblob, extra_html_class)<EOL>
Converts a ``pyplot`` figure to an HTML IMG tag with encapsulated PNG.
f14607:m0
def svg_html_from_pyplot_figure(fig: "<STR_LIT>") -> str:
if fig is None:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>memfile = io.BytesIO() <EOL>fig.savefig(memfile, format="<STR_LIT>")<EOL>return memfile.getvalue().decode("<STR_LIT:utf-8>")<EOL>
Converts a ``pyplot`` figure to an SVG tag.
f14607:m1
def set_matplotlib_fontsize(matplotlib: ModuleType,<EOL>fontsize: Union[int, float] = <NUM_LIT:12>) -> None:
font = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>', <EOL>'<STR_LIT>': '<STR_LIT>', <EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:size>': fontsize <EOL>}<EOL>matplotlib.rc('<STR_LIT>', **font)<EOL>legend = {<EOL>'<STR_LIT>': fontsize<EOL>}<EOL>matplotlib.rc('<STR_LIT>', **legend)<EOL>
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.
f14607:m2
def create_sys_dsn(driver: str, **kw) -> bool:
attributes = [] <EOL>for attr in kw.keys():<EOL><INDENT>attributes.append("<STR_LIT>" % (attr, kw[attr]))<EOL><DEDENT>return bool(<EOL>ctypes.windll.ODBCCP32.SQLConfigDataSource(<NUM_LIT:0>, ODBC_ADD_SYS_DSN,<EOL>driver,<EOL>nul.join(attributes))<EOL>)<EOL>
(Windows only.) Create a system ODBC data source name (DSN). Args: driver: ODBC driver name kw: Driver attributes Returns: bool: was the DSN created?
f14608:m0
def create_user_dsn(driver: str, **kw) -> bool:
attributes = [] <EOL>for attr in kw.keys():<EOL><INDENT>attributes.append("<STR_LIT>" % (attr, kw[attr]))<EOL><DEDENT>return bool(<EOL>ctypes.windll.ODBCCP32.SQLConfigDataSource(<NUM_LIT:0>, ODBC_ADD_DSN, driver,<EOL>nul.join(attributes))<EOL>)<EOL>
(Windows only.) Create a user ODBC data source name (DSN). Args: driver: ODBC driver name kw: Driver attributes Returns: bool: was the DSN created?
f14608:m1
def register_access_db(fullfilename: str, dsn: str, description: str) -> bool:
directory = os.path.dirname(fullfilename)<EOL>return create_sys_dsn(<EOL>access_driver,<EOL>SERVER="<STR_LIT>",<EOL>DESCRIPTION=description,<EOL>DSN=dsn,<EOL>DBQ=fullfilename,<EOL>DefaultDir=directory<EOL>)<EOL>
(Windows only.) Registers a Microsoft Access database with ODBC. Args: fullfilename: filename of the existing database dsn: ODBC data source name to create description: description of the database Returns: bool: was the DSN created?
f14608:m2