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>", nargs="<STR_LIT:+>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", default="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", default="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", default="<STR_LIT:root>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", type=str,<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>")<EOL>parser.add_argument(<EOL>"<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>")<EOL>args = parser.parse_args()<EOL>output_dir = args.output_dir or os.getcwd()<EOL>os.chdir(output_dir)<EOL>password = args.password or getpass.getpass(<EOL>prompt="<STR_LIT>".format(args.username))<EOL>output_files = [] <EOL>if args.with_drop_create_database:<EOL><INDENT>log.info("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>suffix = wdcd_suffix<EOL><DEDENT>else:<EOL><INDENT>suffix = "<STR_LIT>"<EOL><DEDENT>for db in args.databases:<EOL><INDENT>now = datetime.datetime.now().strftime(timeformat)<EOL>outfilename = "<STR_LIT>".format(db=db, now=now,<EOL>suffix=suffix)<EOL>display_args = cmdargs(<EOL>mysqldump=args.mysqldump,<EOL>username=args.username,<EOL>password=password,<EOL>database=db,<EOL>verbose=args.verbose,<EOL>with_drop_create_database=args.with_drop_create_database,<EOL>max_allowed_packet=args.max_allowed_packet,<EOL>hide_password=True<EOL>)<EOL>actual_args = cmdargs(<EOL>mysqldump=args.mysqldump,<EOL>username=args.username,<EOL>password=password,<EOL>database=db,<EOL>verbose=args.verbose,<EOL>with_drop_create_database=args.with_drop_create_database,<EOL>max_allowed_packet=args.max_allowed_packet,<EOL>hide_password=False<EOL>)<EOL>log.info("<STR_LIT>" + repr(display_args))<EOL>log.info("<STR_LIT>" + repr(outfilename))<EOL>try:<EOL><INDENT>with open(outfilename, "<STR_LIT:w>") as f:<EOL><INDENT>subprocess.check_call(actual_args, stdout=f)<EOL><DEDENT><DEDENT>except subprocess.CalledProcessError:<EOL><INDENT>os.remove(outfilename)<EOL>log.critical("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>output_files.append(outfilename)<EOL><DEDENT>log.info("<STR_LIT>" + "<STR_LIT:\n>".join("<STR_LIT:U+0020>" + x for x in output_files))<EOL>if args.with_drop_create_database:<EOL><INDENT>log.info("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>log.info("<STR_LIT>")<EOL><DEDENT> | 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><DEDENT><DEDENT>return sorted(list(extensions))<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:\n>".join(repr(x) for x in<EOL>list_file_extensions(args.directory,<EOL>reportevery=args.reportevery)))<EOL> | 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>stdout = completed_process.stdout.decode(encoding)<EOL>stderr = completed_process.stderr.decode(encoding)<EOL>present = OrderedDict()<EOL>for line in stdout.split("<STR_LIT:\n>"):<EOL><INDENT>if line: <EOL><INDENT>words = line.split()<EOL>assert len(words) >= <NUM_LIT:2><EOL>package = words[<NUM_LIT:0>]<EOL>present[package] = "<STR_LIT>" in words[<NUM_LIT:1>:]<EOL><DEDENT><DEDENT>for line in stderr.split("<STR_LIT:\n>"):<EOL><INDENT>if line: <EOL><INDENT>words = line.split()<EOL>assert len(words) >= <NUM_LIT:2><EOL>package = words[-<NUM_LIT:1>]<EOL>present[package] = False<EOL><DEDENT><DEDENT>log.debug("<STR_LIT>", present)<EOL>return present<EOL> | 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(msg)<EOL><DEDENT> | 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><INDENT>'<STR_LIT>'.format(<EOL>nv_cmd=env_cmd, tag=tag)<EOL><DEDENT>nch the process<EOL>nfo("<STR_LIT>", env_cmd)<EOL>ebug("<STR_LIT>", cmd)<EOL>= subprocess.Popen(cmd, stdout=subprocess.PIPE, env=initial_env)<EOL>se the output sent to stdout<EOL>ing = sys.getdefaultencoding()<EOL>en_lines() -> Generator[str, None, None]: <EOL>or line in proc.stdout:<EOL><INDENT>yield line.decode(encoding)<EOL><DEDENT>ine a way to handle each KEY=VALUE line<EOL>andle_line(line: str) -> Tuple[str, str]: <EOL><INDENT>noinspection PyTypeChecker<EOL><DEDENT>arts = line.rstrip().split('<STR_LIT:=>', <NUM_LIT:1>)<EOL><INDENT>split("<STR_LIT:=>", <NUM_LIT:1>) means "<STR_LIT>"<EOL><DEDENT>f len(parts) < <NUM_LIT:2>:<EOL><INDENT>return parts[<NUM_LIT:0>], "<STR_LIT>"<EOL><DEDENT>eturn parts[<NUM_LIT:0>], parts[<NUM_LIT:1>]<EOL><INDENT>= gen_lines() <EOL><DEDENT>sume whatever output occurs until the tag is reached<EOL>me(itertools.takewhile(lambda l: tag not in l, lines))<EOL><INDENT>RNC: note that itertools.takewhile() generates values not matching<EOL>the condition, but then consumes the condition value itself. So the<EOL>tag's already gone. Example:<EOL><DEDENT>ef gen():<EOL><INDENT>mylist = [<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT:5>]<EOL>for x in mylist:<EOL><INDENT>yield x<EOL> | 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 environment
passed to the child process. (Otherwise, this process's ``os.environ()``
will be used by default.)
From https://stackoverflow.com/questions/1214496/how-to-get-environment-from-a-subprocess-in-python,
with decoding bug fixed for Python 3.
PURPOSE: under Windows, ``VCVARSALL.BAT`` sets up a lot of environment
variables to compile for a specific target architecture. We want to be able
to read them, not to replicate its work.
METHOD: create a composite command that executes the specified command,
then echoes an unusual string tag, then prints the environment via ``SET``;
capture the output, work out what came from ``SET``.
Args:
env_cmd: command, or list of command arguments
initial_env: optional dictionary containing initial environment
Returns:
dict: environment created after running the command | 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... command
set RUBBISH="a & b" # OK
... and you get similar knock-on effects, e.g. if you set RUBBISH using the
Control Panel to the literal
.. code-block:: bat
a & dir
and then do
.. code-block:: bat
echo %RUBBISH%
it will (1) print "a" and then (2) print a directory listing as it RUNS
"dir"! That's pretty dreadful.
See also
https://www.thesecurityfactory.be/command-injection-windows.html
Anyway, this is a sanity check for that sort of thing. | 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:<EOL><INDENT>value = "<STR_LIT>"<EOL><DEDENT>elements.append("<STR_LIT>".format(fieldname, value))<EOL><DEDENT>return "<STR_LIT>".format(type(instance).__name__,<EOL>"<STR_LIT:U+002CU+0020>".join(elements))<EOL> | 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>return url<EOL> | 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>current_app = modeladmin.admin_site.name<EOL><DEDENT>url = reverse(viewname, args=[linked_obj.pk], current_app=current_app)<EOL>if use_str:<EOL><INDENT>label = escape(str(linked_obj))<EOL><DEDENT>else:<EOL><INDENT>label = "<STR_LIT>".format(escape(linked_obj._meta.object_name),<EOL>linked_obj.pk)<EOL><DEDENT>return '<STR_LIT>'.format(url, label)<EOL> | 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.lower()<EOL>viewname = "<STR_LIT>".format(app_name, model_name, view_type)<EOL>if current_app is None:<EOL><INDENT>current_app = modeladmin.admin_site.name<EOL><DEDENT>links = []<EOL>for linked_obj in linked_objs:<EOL><INDENT>url = reverse(viewname, args=[linked_obj.pk], current_app=current_app)<EOL>if use_str:<EOL><INDENT>label = escape(str(linked_obj))<EOL><DEDENT>else:<EOL><INDENT>label = "<STR_LIT>".format(escape(linked_obj._meta.object_name),<EOL>linked_obj.pk)<EOL><DEDENT>links.append('<STR_LIT>'.format(url, label))<EOL><DEDENT>return separator.join(links)<EOL> | 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_filefield:<EOL><INDENT>continue<EOL><DEDENT>new_filefield = getattr(instance, fieldname, None)<EOL>if old_filefield != new_filefield:<EOL><INDENT>if os.path.isfile(old_filefield.path):<EOL><INDENT>os.remove(old_filefield.path)<EOL><DEDENT><DEDENT><DEDENT> | 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
millsecond precision. | 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 trailing ``.000`` for zero milliseconds, appends
trailing ``000`` for everything else,
- ... thus matching the output of Python's ``str(x)`` where ``x`` is a
``datetime``.
- ... thus matching the RHS of a Django default ``datetime`` comparison. | 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 value<EOL> | 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:: python
Study.objects.get(pk=1)
Study.objects.get(pk="1") # also works
Choices can be non-string, though, so we compare against a string version
of the choice. | 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`` exception." | 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 to get
a unique string out.
- We shouldn't use ``str()``, because that is often poorly specified; e.g.
is ``'a.b.c'`` a ``TableId``, or is it a ``ColumnId`` with no ``'db'``
field?
- We could use ``repr()``: sometimes that gives us helpful things that
could in principle be passed to ``eval()``, in which case ``repr()`` would
be fine, but sometimes it doesn't, and gives unhelpful things like
``'<__main__.Thing object at 0x7ff3093ebda0>'``.
- However, if something encodes to JSON, that representation should
be reversible and thus contain the right sort of information.
- Note also that bound methods will come with a ``self`` argument, for
which the address may be very relevant...
- Let's go with ``repr()``. Users of the cache decorator should not pass
objects whose ``repr()`` includes the memory address of the object unless
they want those objects to be treated as distinct.
- Ah, no. The cache itself will pickle and unpickle things, and this
will change memory addresses of objects. So we can't store a reference
to an object using ``repr()`` and using ``cache.add()``/``pickle()`` and
hope they'll come out the same.
- Use the JSON after all.
- And do it in ``get_call_signature()``, not here.
- That means that any class we wish to decorate WITHOUT specifying a
cache key manually must support JSON. | 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_cache_key(call_sig)<EOL>check_stored_call_sig = True<EOL><DEDENT>if debug_cache:<EOL><INDENT>log.critical("<STR_LIT>" + _cache_key)<EOL><DEDENT>cache_result_tuple = cache.get(_cache_key) <EOL>if cache_result_tuple is None:<EOL><INDENT>if debug_cache:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if debug_cache:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>cached_call_sig, func_result = cache_result_tuple<EOL>if (not check_stored_call_sig) or cached_call_sig == call_sig:<EOL><INDENT>return func_result<EOL><DEDENT>log.warning(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(<EOL>repr(cached_call_sig), repr(call_sig)))<EOL><DEDENT>func_result = fn(*args, **kwargs)<EOL>cache_result_tuple = (call_sig, func_result)<EOL>cache.set(key=_cache_key, value=cache_result_tuple,<EOL>timeout=timeout) <EOL>return func_result<EOL><DEDENT>return wrapper<EOL><DEDENT>return decorator<EOL> | 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_LIT>'<EOL><DEDENT>else:<EOL><INDENT>prefix = '<STR_LIT>'<EOL><DEDENT>fname = '<STR_LIT>' % smart_str(offered_filename)<EOL>response['<STR_LIT>'] = prefix + fname<EOL>if content_length is not None:<EOL><INDENT>response['<STR_LIT>'] = content_length<EOL><DEDENT> | 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.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
as_inline: attempt to force inline (only if not as_attachment)
content_length: HTTP content length | 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>response = FileResponse(open(path_to_file, mode='<STR_LIT:rb>'))<EOL>content_length = None<EOL><DEDENT>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=content_length)<EOL>return response<EOL> | 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>context = ssl.SSLContext(self._protocol())<EOL>if self.ssl_certfile:<EOL><INDENT>context.load_cert_chain(certfile=self.ssl_certfile,<EOL>keyfile=self.ssl_keyfile)<EOL><DEDENT>self.connection.ehlo()<EOL>self.connection.starttls(context=context)<EOL>self.connection.ehlo()<EOL>if self.username and self.password:<EOL><INDENT>self.connection.login(self.username, self.password)<EOL>log.debug("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>return True<EOL><DEDENT>except smtplib.SMTPException:<EOL><INDENT>log.debug("<STR_LIT>")<EOL>if not self.fail_silently:<EOL><INDENT>raise<EOL><DEDENT><DEDENT> | 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_MENTION, DTYPE_DATE),<EOL>(RCN_DRUG_B_SECOND_MENTION, DTYPE_DATE),<EOL>(RCN_EXPECT_RESPONSE_BY_DATE, DTYPE_DATE),<EOL>(RCN_END_OF_SYMPTOM_PERIOD, DTYPE_DATE),<EOL>]<EOL>))<EOL> | 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_ANTIDEPRESSANT_COURSE_LENGTH_DAYS,<EOL>expect_response_by_days: int = DEFAULT_EXPECT_RESPONSE_BY_DAYS,<EOL>symptom_assessment_time_days: int = DEFAULT_SYMPTOM_ASSESSMENT_TIME_DAYS, <EOL>first_episode_only: bool = True) -> Optional[DataFrame]: | 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_mask = patient_drug_date_df[patient_colname].values == patient_id<EOL>tp = patient_drug_date_df[patient_mask] <EOL>tp = tp.sort_values(by=[date_colname, drug_colname], ascending=True)<EOL>nrows_all = len(tp) <EOL>if nrows_all < <NUM_LIT:4>: <EOL><INDENT>return None<EOL><DEDENT>end_date = tp.iat[nrows_all - <NUM_LIT:1>, sourcecolnum_date] <EOL>for first_b_rownum in range(<NUM_LIT:1>, nrows_all):<EOL><INDENT>antidepressant_b_name = tp.iat[first_b_rownum, sourcecolnum_drug]<EOL>antidepressant_b_first_mention = tp.iat[first_b_rownum,<EOL>sourcecolnum_date]<EOL>earliest_possible_b_second_mention = (<EOL>antidepressant_b_first_mention +<EOL>timedelta_days(course_length_days - <NUM_LIT:1>)<EOL>)<EOL>if earliest_possible_b_second_mention > end_date:<EOL><INDENT>continue <EOL><DEDENT>b_second_mentions = tp[<EOL>(tp[drug_colname] == antidepressant_b_name) & <EOL>(tp[date_colname] >= earliest_possible_b_second_mention)<EOL>]<EOL>if len(b_second_mentions) == <NUM_LIT:0>:<EOL><INDENT>continue <EOL><DEDENT>antidepressant_b_second_mention = b_second_mentions.iat[<EOL><NUM_LIT:0>, sourcecolnum_date]<EOL>preceding_other_antidepressants = tp[<EOL>(tp[drug_colname] != antidepressant_b_name) &<EOL>(tp[date_colname] <= antidepressant_b_first_mention)<EOL>]<EOL>nrows_a = len(preceding_other_antidepressants)<EOL>if nrows_a < <NUM_LIT:2>: <EOL><INDENT>continue <EOL><DEDENT>found_valid_a = False<EOL>antidepressant_a_name = NaN<EOL>antidepressant_a_first_mention = NaN<EOL>antidepressant_a_second_mention = NaN<EOL>for first_a_rownum in range(nrows_a - <NUM_LIT:1>):<EOL><INDENT>antidepressant_a_name = tp.iat[first_a_rownum, sourcecolnum_drug]<EOL>antidepressant_a_first_mention = tp.iat[first_a_rownum,<EOL>sourcecolnum_date]<EOL>earliest_possible_a_second_mention = (<EOL>antidepressant_a_first_mention +<EOL>timedelta_days(course_length_days - <NUM_LIT:1>)<EOL>)<EOL>if (earliest_possible_a_second_mention ><EOL>antidepressant_b_first_mention):<EOL><INDENT>continue <EOL><DEDENT>a_second_mentions = tp[<EOL>(tp[drug_colname] == antidepressant_a_name) &<EOL>(tp[date_colname] >= earliest_possible_a_second_mention)<EOL>]<EOL>if len(a_second_mentions) == <NUM_LIT:0>:<EOL><INDENT>continue <EOL><DEDENT>antidepressant_a_second_mention = a_second_mentions.iat[<EOL><NUM_LIT:0>, sourcecolnum_date]<EOL>mentions_of_b_within_a_range = tp[<EOL>(tp[drug_colname] == antidepressant_b_name) &<EOL>(tp[date_colname] >= antidepressant_a_first_mention) &<EOL>(tp[date_colname] < antidepressant_a_second_mention)<EOL>]<EOL>if len(mentions_of_b_within_a_range) > <NUM_LIT:0>:<EOL><INDENT>continue <EOL><DEDENT>found_valid_a = True<EOL>break<EOL><DEDENT>if not found_valid_a:<EOL><INDENT>continue <EOL><DEDENT>expect_response_by_date = (<EOL>antidepressant_b_first_mention + timedelta_days(<EOL>expect_response_by_days)<EOL>)<EOL>end_of_symptom_period = (<EOL>antidepressant_b_first_mention + timedelta_days(<EOL>expect_response_by_days + symptom_assessment_time_days - <NUM_LIT:1>)<EOL>)<EOL>result = _get_generic_two_antidep_episodes_result((<EOL>patient_id,<EOL>antidepressant_a_name,<EOL>antidepressant_a_first_mention,<EOL>antidepressant_a_second_mention,<EOL>antidepressant_b_name,<EOL>antidepressant_b_first_mention,<EOL>antidepressant_b_second_mention,<EOL>expect_response_by_date,<EOL>end_of_symptom_period<EOL>))<EOL>if first_episode_only:<EOL><INDENT>return result<EOL><DEDENT>else:<EOL><INDENT>all_episodes_for_patient = all_episodes_for_patient.append(result)<EOL><DEDENT><DEDENT>if len(all_episodes_for_patient) == <NUM_LIT:0>:<EOL><INDENT>return None <EOL><DEDENT>return all_episodes_for_patient<EOL> | 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_response_by_days: int = DEFAULT_EXPECT_RESPONSE_BY_DAYS,<EOL>symptom_assessment_time_days: int =<EOL>DEFAULT_SYMPTOM_ASSESSMENT_TIME_DAYS,<EOL>n_threads: int = DEFAULT_N_THREADS,<EOL>first_episode_only: bool = True) -> DataFrame: | <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_antidepressant_episodes_single_patient(<EOL>patient_id=_patient_id,<EOL>patient_drug_date_df=patient_drug_date_df,<EOL>patient_colname=patient_colname,<EOL>drug_colname=drug_colname,<EOL>date_colname=date_colname,<EOL>course_length_days=course_length_days,<EOL>expect_response_by_days=expect_response_by_days,<EOL>symptom_assessment_time_days=symptom_assessment_time_days,<EOL>first_episode_only=first_episode_only,<EOL>)<EOL><DEDENT>combined_result = _get_blank_two_antidep_episodes_result()<EOL>if n_threads > <NUM_LIT:1>:<EOL><INDENT>log.info("<STR_LIT>", n_threads)<EOL>with ThreadPoolExecutor(max_workers=n_threads) as executor:<EOL><INDENT>list_of_results_frames = executor.map(_get_patient_result,<EOL>patient_ids)<EOL><DEDENT>log.debug("<STR_LIT>")<EOL>for patient_result in list_of_results_frames:<EOL><INDENT>if patient_result is not None:<EOL><INDENT>combined_result = combined_result.append(patient_result)<EOL><DEDENT><DEDENT>log.debug("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>log.info("<STR_LIT>")<EOL>for ptnum, patient_id in enumerate(patient_ids, start=<NUM_LIT:1>):<EOL><INDENT>log.debug("<STR_LIT>", ptnum, n_patients)<EOL>patient_result = _get_patient_result(patient_id)<EOL>if patient_result is not None:<EOL><INDENT>combined_result = combined_result.append(patient_result)<EOL><DEDENT><DEDENT><DEDENT>combined_result = combined_result.sort_values(<EOL>by=[RCN_PATIENT_ID], ascending=True)<EOL>combined_result.reset_index(inplace=True, drop=True)<EOL>end = Pendulum.now()<EOL>duration = end - start<EOL>log.info("<STR_LIT>",<EOL>duration.total_seconds(), n_patients)<EOL>flush_stdout_stderr()<EOL>return combined_result<EOL> | 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",
"Priadel", "Haldol")
)
dt_repr <- cpl_rfunc$get_python_repr(dt)
gives this when a duff import is used via
``reticulate::import_from_path()``:
.. code-block:: none
[1] "{'drug': ['citalopram', 'Cipramil', 'Prozac', 'fluoxetine',
'Priadel', 'Haldol'], 'subject': ['Alice', 'Bob', 'Charles', 'Dawn',
'Egbert', 'Flora']}"
but this when a proper import is used via ``reticulate::import()``:
.. code-block:: none
[1] " subject drug\n0 Alice citalopram\n1 Bob
Cipramil\n2 Charles Prozac\n3 Dawn fluoxetine\n4 Egbert
Priadel\n5 Flora Haldol" | 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
[1] "<class 'pandas.core.frame.DataFrame'>"
The same is true of a data.frame(). | 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]<EOL>event_when = drug_events_df.iat[rowidx, sourcecolnum_when]<EOL>interval = Interval(event_when, event_when + event_lasts_for)<EOL>ivlist = timelines[patient_id] <EOL>ivlist.add(interval)<EOL><DEDENT>return timelines<EOL> | 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:`DataFrame` containing the event data
event_lasts_for:
when an event occurs, how long is it assumed to last for? For
example, if a prescription of lithium occurs on 2001-01-01, how
long is the patient presumed to be taking lithium as a consequence
(e.g. 1 day? 28 days? 6 months?)
patient_colname:
name of the column in ``drug_events_df`` containing the patient ID
event_datetime_colname:
name of the column in ``drug_events_df`` containing the date/time
of each event
Returns:
dict: mapping patient ID to a :class:`IntervalList` object indicating
the amalgamated intervals from the events | 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 = DEFAULT_DRUG_EVENT_DATETIME_COLNAME,<EOL>start_colname: str = DEFAULT_START_DATETIME_COLNAME,<EOL>when_colname: str = DEFAULT_QUERY_DATETIME_COLNAME,<EOL>include_timedelta_in_output: bool = False,<EOL>debug: bool = False)-> DataFrame: | 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_df)<EOL>log.critical("<STR_LIT>", event_lasts_for_timedelta)<EOL>log.critical("<STR_LIT>", query_times_df)<EOL><DEDENT>timelines = drug_timelines(<EOL>drug_events_df=drug_events_df,<EOL>event_lasts_for=event_lasts_for_timedelta,<EOL>patient_colname=patient_colname,<EOL>event_datetime_colname=event_datetime_colname,<EOL>)<EOL>query_nrow = len(query_times_df)<EOL>ct_coldefs = [ <EOL>(RCN_PATIENT_ID, DTYPE_STRING),<EOL>(RCN_START, DTYPE_DATETIME),<EOL>(RCN_TIME, DTYPE_DATETIME),<EOL>(RCN_BEFORE_DAYS, DTYPE_FLOAT),<EOL>(RCN_DURING_DAYS, DTYPE_FLOAT),<EOL>(RCN_AFTER_DAYS, DTYPE_FLOAT),<EOL>]<EOL>if include_timedelta_in_output:<EOL><INDENT>ct_coldefs.extend([<EOL>(RCN_BEFORE_TIMEDELTA, DTYPE_TIMEDELTA),<EOL>(RCN_DURING_TIMEDELTA, DTYPE_TIMEDELTA),<EOL>(RCN_AFTER_TIMEDELTA, DTYPE_TIMEDELTA),<EOL>])<EOL><DEDENT>ct_arr = array([None] * query_nrow, dtype=ct_coldefs)<EOL>cumulative_times = DataFrame(ct_arr, index=list(range(query_nrow)))<EOL>sourcecolnum_pt = query_times_df.columns.get_loc(patient_colname)<EOL>sourcecolnum_start = query_times_df.columns.get_loc(start_colname)<EOL>sourcecolnum_when = query_times_df.columns.get_loc(when_colname)<EOL>dest_colnum_pt = cumulative_times.columns.get_loc(RCN_PATIENT_ID)<EOL>dest_colnum_start = cumulative_times.columns.get_loc(RCN_START)<EOL>dest_colnum_t = cumulative_times.columns.get_loc(RCN_TIME)<EOL>dest_colnum_before_days = cumulative_times.columns.get_loc(RCN_BEFORE_DAYS)<EOL>dest_colnum_during_days = cumulative_times.columns.get_loc(RCN_DURING_DAYS)<EOL>dest_colnum_after_days = cumulative_times.columns.get_loc(RCN_AFTER_DAYS)<EOL>if include_timedelta_in_output:<EOL><INDENT>dest_colnum_before_dt = cumulative_times.columns.get_loc(RCN_BEFORE_TIMEDELTA) <EOL>dest_colnum_during_dt = cumulative_times.columns.get_loc(RCN_DURING_TIMEDELTA) <EOL>dest_colnum_after_dt = cumulative_times.columns.get_loc(RCN_AFTER_TIMEDELTA) <EOL><DEDENT>else:<EOL><INDENT>dest_colnum_before_dt = <NUM_LIT:0><EOL>dest_colnum_during_dt = <NUM_LIT:0><EOL>dest_colnum_after_dt = <NUM_LIT:0><EOL><DEDENT>for rowidx in range(query_nrow):<EOL><INDENT>patient_id = query_times_df.iat[rowidx, sourcecolnum_pt]<EOL>start = query_times_df.iat[rowidx, sourcecolnum_start]<EOL>when = query_times_df.iat[rowidx, sourcecolnum_when]<EOL>ivlist = timelines[patient_id]<EOL>before, during, after = ivlist.cumulative_before_during_after(start,<EOL>when)<EOL>cumulative_times.iat[rowidx, dest_colnum_pt] = patient_id<EOL>cumulative_times.iat[rowidx, dest_colnum_start] = start<EOL>cumulative_times.iat[rowidx, dest_colnum_t] = when<EOL>cumulative_times.iat[rowidx, dest_colnum_before_days] = before.days<EOL>cumulative_times.iat[rowidx, dest_colnum_during_days] = during.days<EOL>cumulative_times.iat[rowidx, dest_colnum_after_days] = after.days<EOL>if include_timedelta_in_output:<EOL><INDENT>cumulative_times.iat[rowidx, dest_colnum_before_dt] = before<EOL>cumulative_times.iat[rowidx, dest_colnum_during_dt] = during<EOL>cumulative_times.iat[rowidx, dest_colnum_after_dt] = after<EOL><DEDENT><DEDENT>return cumulative_times<EOL> | 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 lithium occurs on 2001-01-01, how
long is the patient presumed to be taking lithium as a consequence
(e.g. 1 day? 28 days? 6 months?)
event_lasts_for_quantity:
as an alternative to ``event_lasts_for_timedelta``, particularly if
you are calling from R to Python via ``reticulate`` (which doesn't
convert R ``as.difftime()`` to Python ``datetime.timedelta``), you
can specify ``event_lasts_for_quantity``, a number and
``event_lasts_for_units`` (q.v.).
event_lasts_for_units:
specify the units for ``event_lasts_for_quantity`` (q.v.), if used;
e.g. ``"days"``. The string value must be the name of an argument
to the Python ``datetime.timedelta`` constructor.
query_times_df:
times to query for, with columns named according to
``patient_colname``, ``start_colname``, and ``when_colname``
patient_colname:
name of the column in ``drug_events_df`` and ``query_time_df``
containing the patient ID
event_datetime_colname:
name of the column in ``drug_events_df`` containing the date/time
of each event
start_colname:
name of the column in ``query_time_df`` containing the date/time
representing the overall start time for the relevant patient (from
which cumulative times are calculated)
when_colname:
name of the column in ``query_time_df`` containing date/time
values at which to query
include_timedelta_in_output:
include ``datetime.timedelta`` values in the output? The default is
``False`` as this isn't supported by R/``reticulate``.
debug:
print debugging information to the log?
Returns:
:class:`DataFrame` with the requested data | 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_matches(drug_name):<EOL><INDENT>return d<EOL><DEDENT><DEDENT>return None<EOL><DEDENT> | 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`` parameter and storing
results in a ``data.table()`` character column:
.. code-block:: none
------------------------------ ----------------
To Python Back from Python
------------------------------ ----------------
[not passed, so Python None] "NULL"
NULL "NULL"
NA_character_ "NA"
NA TRUE (logical)
------------------------------ ---------------- | 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 ``antidepressant=True``. | 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)<EOL><DEDENT>return matching_drugs<EOL> | 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_ssri_antidep = all_drugs_where(antidepressant=True, ssri=False)
print([d.generic_name for d in non_ssri_antidep])
conventional_antidep = all_drugs_where(conventional_antidepressant=True)
print([d.generic_name for d in conventional_antidep]) | 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 = WILDCARD + p<EOL><DEDENT>if self.add_following_wildcards and not p.endswith(WILDCARD):<EOL><INDENT>p = p + WILDCARD<EOL><DEDENT>possibilities.append(p)<EOL><DEDENT>self._regex_text = "<STR_LIT:|>".join("<STR_LIT>" + x + "<STR_LIT:)>" for x in possibilities)<EOL><DEDENT>return self._regex_text<EOL> | 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 in results])<EOL><DEDENT>results = newresults<EOL><DEDENT>def deduplicate_wildcards(text: str) -> str:<EOL><INDENT>while zero_or_more_wildcard + zero_or_more_wildcard in text:<EOL><INDENT>text = text.replace(<EOL>zero_or_more_wildcard + zero_or_more_wildcard,<EOL>zero_or_more_wildcard)<EOL><DEDENT>return text<EOL><DEDENT>working = regex_text <EOL>results = [zero_or_more_wildcard] <EOL>while working:<EOL><INDENT>if working.startswith("<STR_LIT>"):<EOL><INDENT>append_to_all(zero_or_more_wildcard)<EOL>working = working[<NUM_LIT:2>:]<EOL><DEDENT>elif working.startswith("<STR_LIT:[>"):<EOL><INDENT>close_bracket = working.index("<STR_LIT:]>") <EOL>bracketed = working[<NUM_LIT:1>:close_bracket]<EOL>option_groups = bracketed.split("<STR_LIT:|>")<EOL>options = [c for group in option_groups for c in group]<EOL>split_and_append(options)<EOL>working = working[close_bracket + <NUM_LIT:1>:]<EOL><DEDENT>elif len(working) > <NUM_LIT:1> and working[<NUM_LIT:1>] == "<STR_LIT:?>":<EOL><INDENT>split_and_append(["<STR_LIT>", working[<NUM_LIT:0>]])<EOL>working = working[<NUM_LIT:2>:]<EOL><DEDENT>elif working.startswith("<STR_LIT:.>"):<EOL><INDENT>append_to_all(single_wildcard)<EOL>working = working[<NUM_LIT:1>:]<EOL><DEDENT>else:<EOL><INDENT>append_to_all(working[<NUM_LIT:0>])<EOL>working = working[<NUM_LIT:1>:]<EOL><DEDENT><DEDENT>append_to_all(zero_or_more_wildcard) <EOL>results = [deduplicate_wildcards(r) for r in results]<EOL>return results<EOL> | 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 "zero/one/many" wildcard, probably always
a percent symbol
Returns:
string for an SQL string literal
Raises:
:exc:`ValueError` for some regex text that it doesn't understand
properly | 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_links = [req.static_url(r) for r in js_resources]<EOL>css_links = [req.static_url(r) for r in css_resources]<EOL>js_tags = ['<STR_LIT>' % link<EOL>for link in js_links]<EOL>css_tags = ['<STR_LIT>' % link<EOL>for link in css_links]<EOL>tags = js_tags + css_tags<EOL>head_html = "<STR_LIT:\n>".join(tags)<EOL>return head_html<EOL> | 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 message<EOL> | 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 = "<STR_LIT>",<EOL>content_type: str = CONTENT_TYPE_TEXT,<EOL>charset: str = "<STR_LIT:utf8>",<EOL>attachment_filenames: Sequence[str] = None,<EOL>attachment_binaries: Sequence[bytes] = None,<EOL>attachment_binary_filenames: Sequence[str] = None,<EOL>verbose: bool = False) -> email.mime.multipart.MIMEMultipart: | 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>assert COMMA not in _addr, (<EOL>"<STR_LIT>".format(_addr)<EOL>)<EOL><DEDENT><DEDENT>if not date:<EOL><INDENT>date = email.utils.formatdate(localtime=True)<EOL><DEDENT>assert isinstance(from_addr, str), (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(from_addr)<EOL>)<EOL>_assert_nocomma(from_addr)<EOL>assert isinstance(sender, str), (<EOL>"<STR_LIT>".format(sender)<EOL>)<EOL>_assert_nocomma(sender)<EOL>if isinstance(reply_to, str):<EOL><INDENT>reply_to = [reply_to] if reply_to else [] <EOL><DEDENT>_assert_nocomma(reply_to)<EOL>if isinstance(to, str):<EOL><INDENT>to = _csv_list_to_list(to)<EOL><DEDENT>if isinstance(cc, str):<EOL><INDENT>cc = _csv_list_to_list(cc)<EOL><DEDENT>if isinstance(bcc, str):<EOL><INDENT>bcc = _csv_list_to_list(bcc)<EOL><DEDENT>assert to or cc or bcc, "<STR_LIT>"<EOL>_assert_nocomma(to)<EOL>_assert_nocomma(cc)<EOL>_assert_nocomma(bcc)<EOL>attachment_filenames = attachment_filenames or [] <EOL>assert all(attachment_filenames), (<EOL>"<STR_LIT>".format(attachment_filenames)<EOL>)<EOL>attachment_binaries = attachment_binaries or [] <EOL>attachment_binary_filenames = attachment_binary_filenames or [] <EOL>assert len(attachment_binaries) == len(attachment_binary_filenames), (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>assert all(attachment_binary_filenames), (<EOL>"<STR_LIT>".format(<EOL>attachment_binary_filenames)<EOL>)<EOL>msg = email.mime.multipart.MIMEMultipart()<EOL>msg["<STR_LIT>"] = from_addr<EOL>msg["<STR_LIT>"] = date<EOL>msg["<STR_LIT>"] = subject<EOL>if sender:<EOL><INDENT>msg["<STR_LIT>"] = sender <EOL><DEDENT>if reply_to:<EOL><INDENT>msg["<STR_LIT>"] = COMMASPACE.join(reply_to)<EOL><DEDENT>if to:<EOL><INDENT>msg["<STR_LIT>"] = COMMASPACE.join(to)<EOL><DEDENT>if cc:<EOL><INDENT>msg["<STR_LIT>"] = COMMASPACE.join(cc)<EOL><DEDENT>if bcc:<EOL><INDENT>msg["<STR_LIT>"] = COMMASPACE.join(bcc)<EOL><DEDENT>if content_type == CONTENT_TYPE_TEXT:<EOL><INDENT>msgbody = email.mime.text.MIMEText(body, "<STR_LIT>", charset)<EOL><DEDENT>elif content_type == CONTENT_TYPE_HTML:<EOL><INDENT>msgbody = email.mime.text.MIMEText(body, "<STR_LIT:html>", charset)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>msg.attach(msgbody)<EOL>try:<EOL><INDENT>if attachment_filenames:<EOL><INDENT>if verbose:<EOL><INDENT>log.debug("<STR_LIT>", attachment_filenames)<EOL><DEDENT>for f in attachment_filenames:<EOL><INDENT>part = email.mime.base.MIMEBase("<STR_LIT>", "<STR_LIT>")<EOL>part.set_payload(open(f, "<STR_LIT:rb>").read())<EOL>email.encoders.encode_base64(part)<EOL>part.add_header(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % os.path.basename(f)<EOL>)<EOL>msg.attach(part)<EOL><DEDENT><DEDENT>if attachment_binaries:<EOL><INDENT>if verbose:<EOL><INDENT>log.debug("<STR_LIT>",<EOL>attachment_binary_filenames)<EOL><DEDENT>for i in range(len(attachment_binaries)):<EOL><INDENT>blob = attachment_binaries[i]<EOL>filename = attachment_binary_filenames[i]<EOL>part = email.mime.base.MIMEBase("<STR_LIT>", "<STR_LIT>")<EOL>part.set_payload(blob)<EOL>email.encoders.encode_base64(part)<EOL>part.add_header(<EOL>'<STR_LIT>',<EOL>'<STR_LIT>' % filename)<EOL>msg.attach(part)<EOL><DEDENT><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>raise ValueError("<STR_LIT>".format(e))<EOL><DEDENT>return msg<EOL> | 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 in RFC 2822 format, or ``None`` for "now"
sender: name of the sender for the "Sender:" field
reply_to: name of the sender for the "Reply-To:" field
to: e-mail address(es) of the recipients for "To:" field
cc: e-mail address(es) of the recipients for "Cc:" field
bcc: e-mail address(es) of the recipients for "Bcc:" field
subject: e-mail subject
body: e-mail body
content_type: MIME type for body content, default ``text/plain``
charset: character set for body; default ``utf8``
attachment_filenames: filenames of attachments to add
attachment_binaries: binary objects to add as attachments
attachment_binary_filenames: filenames corresponding to
``attachment_binaries``
verbose: be verbose?
Returns:
a :class:`email.mime.multipart.MIMEMultipart`
Raises:
:exc:`AssertionError`, :exc:`ValueError` | 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:<EOL><INDENT>raise RuntimeError("<STR_LIT>".format(e))<EOL><DEDENT>if use_tls:<EOL><INDENT>try:<EOL><INDENT>session.starttls()<EOL>session.ehlo()<EOL><DEDENT>except smtplib.SMTPException as e:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(e))<EOL><DEDENT><DEDENT>if user:<EOL><INDENT>try:<EOL><INDENT>session.login(user, password)<EOL><DEDENT>except smtplib.SMTPException as e:<EOL><INDENT>raise RuntimeError(<EOL>"<STR_LIT>".format(user, e))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>log.debug("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>session.sendmail(from_addr, to_addrs, msg.as_string())<EOL><DEDENT>except smtplib.SMTPException as e:<EOL><INDENT>raise RuntimeError("<STR_LIT>".format(e))<EOL><DEDENT>session.quit()<EOL> | 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
use_tls: use TLS, rather than plain SMTP?
msg: a :class:`email.mime.multipart.MIMEMultipart`
msg_string: alternative: specify the message as a raw string
Raises:
:exc:`RuntimeError`
See also:
- https://tools.ietf.org/html/rfc3207 | 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>bcc: Union[str, List[str]] = "<STR_LIT>",<EOL>subject: str = "<STR_LIT>",<EOL>body: str = "<STR_LIT>",<EOL>content_type: str = CONTENT_TYPE_TEXT,<EOL>charset: str = "<STR_LIT:utf8>",<EOL>attachment_filenames: Sequence[str] = None,<EOL>attachment_binaries: Sequence[bytes] = None,<EOL>attachment_binary_filenames: Sequence[str] = None,<EOL>verbose: bool = False) -> Tuple[bool, str]: | <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>date=date,<EOL>sender=sender,<EOL>reply_to=reply_to,<EOL>to=to,<EOL>cc=cc,<EOL>bcc=bcc,<EOL>subject=subject,<EOL>body=body,<EOL>content_type=content_type,<EOL>charset=charset,<EOL>attachment_filenames=attachment_filenames,<EOL>attachment_binaries=attachment_binaries,<EOL>attachment_binary_filenames=attachment_binary_filenames,<EOL>verbose=verbose,<EOL>t (AssertionError, ValueError) as e:<EOL>rrmsg = str(e)<EOL>og.error("<STR_LIT:{}>", errmsg)<EOL>eturn False, errmsg<EOL>----------------------------------------------------------------------<EOL>d it<EOL>----------------------------------------------------------------------<EOL>drs = to + cc + bcc<EOL>end_msg(<EOL>msg=msg,<EOL>from_addr=from_addr,<EOL>to_addrs=to_addrs,<EOL>host=host,<EOL>user=user,<EOL>password=password,<EOL>port=port,<EOL>use_tls=use_tls,<EOL>t RuntimeError as e:<EOL>rrmsg = str(e)<EOL>og.error("<STR_LIT:{}>", e)<EOL>eturn False, errmsg<EOL>n True, "<STR_LIT>"<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, or ``None`` for "now"
from_addr: name of the sender for the "From:" field
sender: name of the sender for the "Sender:" field
reply_to: name of the sender for the "Reply-To:" field
to: e-mail address(es) of the recipients for "To:" field
cc: e-mail address(es) of the recipients for "Cc:" field
bcc: e-mail address(es) of the recipients for "Bcc:" field
subject: e-mail subject
body: e-mail body
content_type: MIME type for body content, default ``text/plain``
charset: character set for body; default ``utf8``
attachment_filenames: filenames of attachments to add
attachment_binaries: binary objects to add as attachments
attachment_binary_filenames: filenames corresponding to
``attachment_binaries``
verbose: be verbose?
Returns:
tuple: ``(success, error_or_success_message)``
See
- https://tools.ietf.org/html/rfc2822
- https://tools.ietf.org/html/rfc5322
- http://segfault.in/2010/12/sending-gmail-from-python/
- http://stackoverflow.com/questions/64505
- http://stackoverflow.com/questions/3362600
Re security:
- TLS supersedes SSL:
https://en.wikipedia.org/wiki/Transport_Layer_Security
- https://en.wikipedia.org/wiki/Email_encryption
- SMTP connections on ports 25 and 587 are commonly secured via TLS using
the ``STARTTLS`` command:
https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol
- https://tools.ietf.org/html/rfc8314
- "STARTTLS on port 587" is one common method. Django refers to this as
"explicit TLS" (its ``E_MAIL_USE_TLS`` setting; see
https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-EMAIL_USE_TLS).
- Port 465 is also used for "implicit TLS" (3.3 in
https://tools.ietf.org/html/rfc8314). Django refers to this as "implicit
TLS" too, or SSL; see its ``EMAIL_USE_SSL`` setting at
https://docs.djangoproject.com/en/2.1/ref/settings/#email-use-ssl). We
don't support that here. | 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("<STR_LIT:user>", action="<STR_LIT:store>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT:password>", action="<STR_LIT:store>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT:body>", action="<STR_LIT:store>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", nargs="<STR_LIT:*>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT:store_true>",<EOL>help="<STR_LIT>")<EOL>parser.add_argument("<STR_LIT>", action="<STR_LIT>",<EOL>help="<STR_LIT>")<EOL>args = parser.parse_args()<EOL>(result, msg) = send_email(<EOL>from_addr=args.sender,<EOL>to=args.recipient,<EOL>subject=args.subject,<EOL>body=args.body,<EOL>host=args.host,<EOL>user=args.user,<EOL>password=args.password,<EOL>use_tls=args.tls,<EOL>attachment_filenames=args.attach,<EOL>verbose=args.verbose,<EOL>)<EOL>if result:<EOL><INDENT>log.info("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>log.info("<STR_LIT>")<EOL><DEDENT>sys.exit(<NUM_LIT:0> if result else <NUM_LIT:1>)<EOL> | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.