repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
RudolfCardinal/pythonlib | cardinal_pythonlib/email/sendmail.py | send_msg | def send_msg(from_addr: str,
to_addrs: Union[str, List[str]],
host: str,
user: str,
password: str,
port: int = None,
use_tls: bool = True,
msg: email.mime.multipart.MIMEMultipart = None,
msg_string: str = None) -> No... | python | def send_msg(from_addr: str,
to_addrs: Union[str, List[str]],
host: str,
user: str,
password: str,
port: int = None,
use_tls: bool = True,
msg: email.mime.multipart.MIMEMultipart = None,
msg_string: str = None) -> No... | [
"def",
"send_msg",
"(",
"from_addr",
":",
"str",
",",
"to_addrs",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
",",
"host",
":",
"str",
",",
"user",
":",
"str",
",",
"password",
":",
"str",
",",
"port",
":",
"int",
"=",
"None",
... | 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... | [
"Sends",
"a",
"pre",
"-",
"built",
"e",
"-",
"mail",
"message",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/email/sendmail.py#L247-L319 |
RudolfCardinal/pythonlib | cardinal_pythonlib/email/sendmail.py | send_email | def send_email(from_addr: str,
host: str,
user: str,
password: str,
port: int = None,
use_tls: bool = True,
date: str = None,
sender: str = "",
reply_to: Union[str, List[str]] = "",
to:... | python | def send_email(from_addr: str,
host: str,
user: str,
password: str,
port: int = None,
use_tls: bool = True,
date: str = None,
sender: str = "",
reply_to: Union[str, List[str]] = "",
to:... | [
"def",
"send_email",
"(",
"from_addr",
":",
"str",
",",
"host",
":",
"str",
",",
"user",
":",
"str",
",",
"password",
":",
"str",
",",
"port",
":",
"int",
"=",
"None",
",",
"use_tls",
":",
"bool",
"=",
"True",
",",
"date",
":",
"str",
"=",
"None"... | 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?
da... | [
"Sends",
"an",
"e",
"-",
"mail",
"in",
"text",
"/",
"html",
"format",
"using",
"SMTP",
"via",
"TLS",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/email/sendmail.py#L326-L466 |
RudolfCardinal/pythonlib | cardinal_pythonlib/email/sendmail.py | main | def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
logging.basicConfig()
log.setLevel(logging.DEBUG)
parser = argparse.ArgumentParser(
description="Send an e-mail from the command line.")
parser.add_argument("sender", action="store",
... | python | def main() -> None:
"""
Command-line processor. See ``--help`` for details.
"""
logging.basicConfig()
log.setLevel(logging.DEBUG)
parser = argparse.ArgumentParser(
description="Send an e-mail from the command line.")
parser.add_argument("sender", action="store",
... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"logging",
".",
"basicConfig",
"(",
")",
"log",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Send an e-mail from the command line.\... | Command-line processor. See ``--help`` for details. | [
"Command",
"-",
"line",
"processor",
".",
"See",
"--",
"help",
"for",
"details",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/email/sendmail.py#L495-L543 |
AndrewWalker/glud | glud/parsing.py | parse_string | def parse_string(contents, name='tmp.cpp', **kwargs):
""" Parse a string of C/C++ code
"""
idx = clang.cindex.Index.create()
tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs)
return _ensure_parse_valid(tu) | python | def parse_string(contents, name='tmp.cpp', **kwargs):
""" Parse a string of C/C++ code
"""
idx = clang.cindex.Index.create()
tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs)
return _ensure_parse_valid(tu) | [
"def",
"parse_string",
"(",
"contents",
",",
"name",
"=",
"'tmp.cpp'",
",",
"*",
"*",
"kwargs",
")",
":",
"idx",
"=",
"clang",
".",
"cindex",
".",
"Index",
".",
"create",
"(",
")",
"tu",
"=",
"idx",
".",
"parse",
"(",
"name",
",",
"unsaved_files",
... | Parse a string of C/C++ code | [
"Parse",
"a",
"string",
"of",
"C",
"/",
"C",
"++",
"code"
] | train | https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/parsing.py#L27-L32 |
AndrewWalker/glud | glud/parsing.py | parse | def parse(name, **kwargs):
""" Parse a C/C++ file
"""
idx = clang.cindex.Index.create()
assert os.path.exists(name)
tu = idx.parse(name, **kwargs)
return _ensure_parse_valid(tu) | python | def parse(name, **kwargs):
""" Parse a C/C++ file
"""
idx = clang.cindex.Index.create()
assert os.path.exists(name)
tu = idx.parse(name, **kwargs)
return _ensure_parse_valid(tu) | [
"def",
"parse",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"idx",
"=",
"clang",
".",
"cindex",
".",
"Index",
".",
"create",
"(",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"name",
")",
"tu",
"=",
"idx",
".",
"parse",
"(",
"name"... | Parse a C/C++ file | [
"Parse",
"a",
"C",
"/",
"C",
"++",
"file"
] | train | https://github.com/AndrewWalker/glud/blob/57de000627fed13d0c383f131163795b09549257/glud/parsing.py#L35-L41 |
RudolfCardinal/pythonlib | cardinal_pythonlib/wsgi/reverse_proxied_mw.py | ip_addresses_from_xff | def ip_addresses_from_xff(value: str) -> List[str]:
"""
Returns a list of IP addresses (as strings), given the value of an HTTP
``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header.
Args:
value:
the value of an HTTP ``X-Forwarded-For`` (or ``WSGI
HTTP_X_FORWARDE... | python | def ip_addresses_from_xff(value: str) -> List[str]:
"""
Returns a list of IP addresses (as strings), given the value of an HTTP
``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header.
Args:
value:
the value of an HTTP ``X-Forwarded-For`` (or ``WSGI
HTTP_X_FORWARDE... | [
"def",
"ip_addresses_from_xff",
"(",
"value",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"if",
"not",
"value",
":",
"return",
"[",
"]",
"return",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"value",
".",
"split",
"(",
"\",\"",
"... | Returns a list of IP addresses (as strings), given the value of an HTTP
``X-Forwarded-For`` (or ``WSGI HTTP_X_FORWARDED_FOR``) header.
Args:
value:
the value of an HTTP ``X-Forwarded-For`` (or ``WSGI
HTTP_X_FORWARDED_FOR``) header
Returns:
a list of IP address as st... | [
"Returns",
"a",
"list",
"of",
"IP",
"addresses",
"(",
"as",
"strings",
")",
"given",
"the",
"value",
"of",
"an",
"HTTP",
"X",
"-",
"Forwarded",
"-",
"For",
"(",
"or",
"WSGI",
"HTTP_X_FORWARDED_FOR",
")",
"header",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/wsgi/reverse_proxied_mw.py#L50-L70 |
RudolfCardinal/pythonlib | cardinal_pythonlib/wsgi/reverse_proxied_mw.py | ReverseProxiedConfig.necessary | def necessary(self) -> bool:
"""
Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config?
"""
return any([
self.trusted_proxy_headers,
self.http_host,
self.remote_addr,
self.script_... | python | def necessary(self) -> bool:
"""
Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config?
"""
return any([
self.trusted_proxy_headers,
self.http_host,
self.remote_addr,
self.script_... | [
"def",
"necessary",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"any",
"(",
"[",
"self",
".",
"trusted_proxy_headers",
",",
"self",
".",
"http_host",
",",
"self",
".",
"remote_addr",
",",
"self",
".",
"script_name",
",",
"self",
".",
"server_name",
",... | Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config? | [
"Is",
"any",
"special",
"handling",
"(",
"e",
".",
"g",
".",
"the",
"addition",
"of",
":",
"class",
":",
"ReverseProxiedMiddleware",
")",
"necessary",
"for",
"thie",
"config?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/wsgi/reverse_proxied_mw.py#L241-L255 |
calston/rhumba | rhumba/client.py | AsyncRhumbaClient.queue | def queue(self, queue, message, params={}, uids=[]):
"""
Queue a job in Rhumba
"""
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid in uids:
... | python | def queue(self, queue, message, params={}, uids=[]):
"""
Queue a job in Rhumba
"""
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid in uids:
... | [
"def",
"queue",
"(",
"self",
",",
"queue",
",",
"message",
",",
"params",
"=",
"{",
"}",
",",
"uids",
"=",
"[",
"]",
")",
":",
"d",
"=",
"{",
"'id'",
":",
"uuid",
".",
"uuid1",
"(",
")",
".",
"get_hex",
"(",
")",
",",
"'version'",
":",
"1",
... | Queue a job in Rhumba | [
"Queue",
"a",
"job",
"in",
"Rhumba"
] | train | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L30-L48 |
calston/rhumba | rhumba/client.py | AsyncRhumbaClient.getResult | def getResult(self, queue, uid, suid=None):
"""
Retrieve the result of a job from its ID
"""
if suid:
r = yield self.client.get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
else:
r = yield self.client.get('rhumba.q.%s.%s' % (queue, uid))
if r:
... | python | def getResult(self, queue, uid, suid=None):
"""
Retrieve the result of a job from its ID
"""
if suid:
r = yield self.client.get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
else:
r = yield self.client.get('rhumba.q.%s.%s' % (queue, uid))
if r:
... | [
"def",
"getResult",
"(",
"self",
",",
"queue",
",",
"uid",
",",
"suid",
"=",
"None",
")",
":",
"if",
"suid",
":",
"r",
"=",
"yield",
"self",
".",
"client",
".",
"get",
"(",
"'rhumba.dq.%s.%s.%s'",
"%",
"(",
"suid",
",",
"queue",
",",
"uid",
")",
... | Retrieve the result of a job from its ID | [
"Retrieve",
"the",
"result",
"of",
"a",
"job",
"from",
"its",
"ID"
] | train | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L51-L64 |
calston/rhumba | rhumba/client.py | AsyncRhumbaClient.clusterStatus | def clusterStatus(self):
"""
Returns a dict of cluster nodes and their status information
"""
servers = yield self.client.keys('rhumba.server.*.heartbeat')
d = {}
now = time.time()
for s in servers:
sname = s.split('.', 2)[-1].rsplit('.', 1)... | python | def clusterStatus(self):
"""
Returns a dict of cluster nodes and their status information
"""
servers = yield self.client.keys('rhumba.server.*.heartbeat')
d = {}
now = time.time()
for s in servers:
sname = s.split('.', 2)[-1].rsplit('.', 1)... | [
"def",
"clusterStatus",
"(",
"self",
")",
":",
"servers",
"=",
"yield",
"self",
".",
"client",
".",
"keys",
"(",
"'rhumba.server.*.heartbeat'",
")",
"d",
"=",
"{",
"}",
"now",
"=",
"time",
".",
"time",
"(",
")",
"for",
"s",
"in",
"servers",
":",
"sna... | Returns a dict of cluster nodes and their status information | [
"Returns",
"a",
"dict",
"of",
"cluster",
"nodes",
"and",
"their",
"status",
"information"
] | train | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L67-L95 |
calston/rhumba | rhumba/client.py | RhumbaClient.queue | def queue(self, queue, message, params={}, uids=[]):
"""
Queue a job in Rhumba
"""
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid in uids:
... | python | def queue(self, queue, message, params={}, uids=[]):
"""
Queue a job in Rhumba
"""
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid in uids:
... | [
"def",
"queue",
"(",
"self",
",",
"queue",
",",
"message",
",",
"params",
"=",
"{",
"}",
",",
"uids",
"=",
"[",
"]",
")",
":",
"d",
"=",
"{",
"'id'",
":",
"uuid",
".",
"uuid1",
"(",
")",
".",
"get_hex",
"(",
")",
",",
"'version'",
":",
"1",
... | Queue a job in Rhumba | [
"Queue",
"a",
"job",
"in",
"Rhumba"
] | train | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L109-L127 |
calston/rhumba | rhumba/client.py | RhumbaClient.getResult | def getResult(self, queue, uid, suid=None):
"""
Retrieve the result of a job from its ID
"""
if suid:
r = self._get_client().get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
else:
r = self._get_client().get('rhumba.q.%s.%s' % (queue, uid))
if r:
... | python | def getResult(self, queue, uid, suid=None):
"""
Retrieve the result of a job from its ID
"""
if suid:
r = self._get_client().get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
else:
r = self._get_client().get('rhumba.q.%s.%s' % (queue, uid))
if r:
... | [
"def",
"getResult",
"(",
"self",
",",
"queue",
",",
"uid",
",",
"suid",
"=",
"None",
")",
":",
"if",
"suid",
":",
"r",
"=",
"self",
".",
"_get_client",
"(",
")",
".",
"get",
"(",
"'rhumba.dq.%s.%s.%s'",
"%",
"(",
"suid",
",",
"queue",
",",
"uid",
... | Retrieve the result of a job from its ID | [
"Retrieve",
"the",
"result",
"of",
"a",
"job",
"from",
"its",
"ID"
] | train | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L129-L141 |
calston/rhumba | rhumba/client.py | RhumbaClient.clusterStatus | def clusterStatus(self):
"""
Returns a dict of cluster nodes and their status information
"""
c = self._get_client()
servers = c.keys('rhumba.server.*.heartbeat')
d = {}
now = time.time()
for s in servers:
sname = s.split('.', 2)[-1]... | python | def clusterStatus(self):
"""
Returns a dict of cluster nodes and their status information
"""
c = self._get_client()
servers = c.keys('rhumba.server.*.heartbeat')
d = {}
now = time.time()
for s in servers:
sname = s.split('.', 2)[-1]... | [
"def",
"clusterStatus",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"_get_client",
"(",
")",
"servers",
"=",
"c",
".",
"keys",
"(",
"'rhumba.server.*.heartbeat'",
")",
"d",
"=",
"{",
"}",
"now",
"=",
"time",
".",
"time",
"(",
")",
"for",
"s",
"in... | Returns a dict of cluster nodes and their status information | [
"Returns",
"a",
"dict",
"of",
"cluster",
"nodes",
"and",
"their",
"status",
"information"
] | train | https://github.com/calston/rhumba/blob/05e3cbf4e531cc51b4777912eb98a4f006893f5e/rhumba/client.py#L143-L168 |
The-Politico/politico-civic-geography | geography/management/commands/bootstrap/_toposimplify.py | Toposimplify.toposimplify | def toposimplify(geojson, p):
"""
Convert geojson and simplify topology.
geojson is a dict representing geojson.
p is a simplification threshold value between 0 and 1.
"""
proc_out = subprocess.run(
['geo2topo'],
input=bytes(
json.... | python | def toposimplify(geojson, p):
"""
Convert geojson and simplify topology.
geojson is a dict representing geojson.
p is a simplification threshold value between 0 and 1.
"""
proc_out = subprocess.run(
['geo2topo'],
input=bytes(
json.... | [
"def",
"toposimplify",
"(",
"geojson",
",",
"p",
")",
":",
"proc_out",
"=",
"subprocess",
".",
"run",
"(",
"[",
"'geo2topo'",
"]",
",",
"input",
"=",
"bytes",
"(",
"json",
".",
"dumps",
"(",
"geojson",
")",
",",
"'utf-8'",
")",
",",
"stdout",
"=",
... | Convert geojson and simplify topology.
geojson is a dict representing geojson.
p is a simplification threshold value between 0 and 1. | [
"Convert",
"geojson",
"and",
"simplify",
"topology",
"."
] | train | https://github.com/The-Politico/politico-civic-geography/blob/032b3ee773b50b65cfe672f230dda772df0f89e0/geography/management/commands/bootstrap/_toposimplify.py#L7-L30 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/engine_func.py | get_sqlserver_product_version | def get_sqlserver_product_version(engine: "Engine") -> Tuple[int]:
"""
Gets SQL Server version information.
Attempted to use ``dialect.server_version_info``:
.. code-block:: python
from sqlalchemy import create_engine
url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME"
engine = cr... | python | def get_sqlserver_product_version(engine: "Engine") -> Tuple[int]:
"""
Gets SQL Server version information.
Attempted to use ``dialect.server_version_info``:
.. code-block:: python
from sqlalchemy import create_engine
url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME"
engine = cr... | [
"def",
"get_sqlserver_product_version",
"(",
"engine",
":",
"\"Engine\"",
")",
"->",
"Tuple",
"[",
"int",
"]",
":",
"assert",
"is_sqlserver",
"(",
"engine",
")",
",",
"(",
"\"Only call get_sqlserver_product_version() for Microsoft SQL Server \"",
"\"instances.\"",
")",
... | Gets SQL Server version information.
Attempted to use ``dialect.server_version_info``:
.. code-block:: python
from sqlalchemy import create_engine
url = "mssql+pyodbc://USER:PASSWORD@ODBC_NAME"
engine = create_engine(url)
dialect = engine.dialect
vi = dialect.server_v... | [
"Gets",
"SQL",
"Server",
"version",
"information",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/engine_func.py#L53-L96 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/engine_func.py | is_sqlserver_2008_or_later | def is_sqlserver_2008_or_later(engine: "Engine") -> bool:
"""
Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server,
version 2008 or later?
"""
if not is_sqlserver(engine):
return False
version_tuple = get_sqlserver_product_version(engine)
return version_tuple >= (SQL... | python | def is_sqlserver_2008_or_later(engine: "Engine") -> bool:
"""
Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server,
version 2008 or later?
"""
if not is_sqlserver(engine):
return False
version_tuple = get_sqlserver_product_version(engine)
return version_tuple >= (SQL... | [
"def",
"is_sqlserver_2008_or_later",
"(",
"engine",
":",
"\"Engine\"",
")",
"->",
"bool",
":",
"if",
"not",
"is_sqlserver",
"(",
"engine",
")",
":",
"return",
"False",
"version_tuple",
"=",
"get_sqlserver_product_version",
"(",
"engine",
")",
"return",
"version_tu... | Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server,
version 2008 or later? | [
"Is",
"the",
"SQLAlchemy",
":",
"class",
":",
"Engine",
"an",
"instance",
"of",
"Microsoft",
"SQL",
"Server",
"version",
"2008",
"or",
"later?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/engine_func.py#L109-L117 |
davenquinn/Attitude | attitude/orientation/linear/regression.py | add_ones | def add_ones(a):
"""Adds a column of 1s at the end of the array"""
arr = N.ones((a.shape[0],a.shape[1]+1))
arr[:,:-1] = a
return arr | python | def add_ones(a):
"""Adds a column of 1s at the end of the array"""
arr = N.ones((a.shape[0],a.shape[1]+1))
arr[:,:-1] = a
return arr | [
"def",
"add_ones",
"(",
"a",
")",
":",
"arr",
"=",
"N",
".",
"ones",
"(",
"(",
"a",
".",
"shape",
"[",
"0",
"]",
",",
"a",
".",
"shape",
"[",
"1",
"]",
"+",
"1",
")",
")",
"arr",
"[",
":",
",",
":",
"-",
"1",
"]",
"=",
"a",
"return",
... | Adds a column of 1s at the end of the array | [
"Adds",
"a",
"column",
"of",
"1s",
"at",
"the",
"end",
"of",
"the",
"array"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/linear/regression.py#L9-L13 |
henzk/featuremonkey | featuremonkey/importhooks.py | ImportHookBase._uninstall | def _uninstall(cls):
"""
uninstall the hook if installed
"""
if cls._hook:
sys.meta_path.remove(cls._hook)
cls._hook = None | python | def _uninstall(cls):
"""
uninstall the hook if installed
"""
if cls._hook:
sys.meta_path.remove(cls._hook)
cls._hook = None | [
"def",
"_uninstall",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_hook",
":",
"sys",
".",
"meta_path",
".",
"remove",
"(",
"cls",
".",
"_hook",
")",
"cls",
".",
"_hook",
"=",
"None"
] | uninstall the hook if installed | [
"uninstall",
"the",
"hook",
"if",
"installed"
] | train | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L34-L40 |
henzk/featuremonkey | featuremonkey/importhooks.py | LazyComposerHook.add | def add(cls, module_name, fsts, composer):
'''
add a couple of fsts to be superimposed on the module given
by module_name as soon as it is imported.
internal - use featuremonkey.compose_later
'''
cls._to_compose.setdefault(module_name, [])
cls._to_compose[module_... | python | def add(cls, module_name, fsts, composer):
'''
add a couple of fsts to be superimposed on the module given
by module_name as soon as it is imported.
internal - use featuremonkey.compose_later
'''
cls._to_compose.setdefault(module_name, [])
cls._to_compose[module_... | [
"def",
"add",
"(",
"cls",
",",
"module_name",
",",
"fsts",
",",
"composer",
")",
":",
"cls",
".",
"_to_compose",
".",
"setdefault",
"(",
"module_name",
",",
"[",
"]",
")",
"cls",
".",
"_to_compose",
"[",
"module_name",
"]",
".",
"append",
"(",
"(",
"... | add a couple of fsts to be superimposed on the module given
by module_name as soon as it is imported.
internal - use featuremonkey.compose_later | [
"add",
"a",
"couple",
"of",
"fsts",
"to",
"be",
"superimposed",
"on",
"the",
"module",
"given",
"by",
"module_name",
"as",
"soon",
"as",
"it",
"is",
"imported",
"."
] | train | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L69-L80 |
henzk/featuremonkey | featuremonkey/importhooks.py | ImportGuardHook.add | def add(cls, module_name, msg=''):
'''
Until the guard is dropped again,
disallow imports of the module given by ``module_name``.
If the module is imported while the guard is in place
an ``ImportGuard`` is raised. An additional message on why
the module cannot be importe... | python | def add(cls, module_name, msg=''):
'''
Until the guard is dropped again,
disallow imports of the module given by ``module_name``.
If the module is imported while the guard is in place
an ``ImportGuard`` is raised. An additional message on why
the module cannot be importe... | [
"def",
"add",
"(",
"cls",
",",
"module_name",
",",
"msg",
"=",
"''",
")",
":",
"if",
"module_name",
"in",
"sys",
".",
"modules",
":",
"raise",
"ImportGuard",
"(",
"'Module to guard has already been imported: '",
"+",
"module_name",
")",
"cls",
".",
"_guards",
... | Until the guard is dropped again,
disallow imports of the module given by ``module_name``.
If the module is imported while the guard is in place
an ``ImportGuard`` is raised. An additional message on why
the module cannot be imported can optionally be specified
using the paramet... | [
"Until",
"the",
"guard",
"is",
"dropped",
"again",
"disallow",
"imports",
"of",
"the",
"module",
"given",
"by",
"module_name",
"."
] | train | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L132-L153 |
henzk/featuremonkey | featuremonkey/importhooks.py | ImportGuardHook.remove | def remove(cls, module_name):
"""
drop a previously created guard on ``module_name``
if the module is not guarded, then this is a no-op.
"""
module_guards = cls._guards.get(module_name, False)
if module_guards:
module_guards.pop()
cls._num_entries ... | python | def remove(cls, module_name):
"""
drop a previously created guard on ``module_name``
if the module is not guarded, then this is a no-op.
"""
module_guards = cls._guards.get(module_name, False)
if module_guards:
module_guards.pop()
cls._num_entries ... | [
"def",
"remove",
"(",
"cls",
",",
"module_name",
")",
":",
"module_guards",
"=",
"cls",
".",
"_guards",
".",
"get",
"(",
"module_name",
",",
"False",
")",
"if",
"module_guards",
":",
"module_guards",
".",
"pop",
"(",
")",
"cls",
".",
"_num_entries",
"-="... | drop a previously created guard on ``module_name``
if the module is not guarded, then this is a no-op. | [
"drop",
"a",
"previously",
"created",
"guard",
"on",
"module_name",
"if",
"the",
"module",
"is",
"not",
"guarded",
"then",
"this",
"is",
"a",
"no",
"-",
"op",
"."
] | train | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/importhooks.py#L156-L170 |
nxdevel/nx_itertools | nx_itertools/recipes.py | random_product | def random_product(*args, repeat=1):
"Random selection from itertools.product(*args, **kwds)"
pools = [tuple(pool) for pool in args] * repeat
return tuple(random.choice(pool) for pool in pools) | python | def random_product(*args, repeat=1):
"Random selection from itertools.product(*args, **kwds)"
pools = [tuple(pool) for pool in args] * repeat
return tuple(random.choice(pool) for pool in pools) | [
"def",
"random_product",
"(",
"*",
"args",
",",
"repeat",
"=",
"1",
")",
":",
"pools",
"=",
"[",
"tuple",
"(",
"pool",
")",
"for",
"pool",
"in",
"args",
"]",
"*",
"repeat",
"return",
"tuple",
"(",
"random",
".",
"choice",
"(",
"pool",
")",
"for",
... | Random selection from itertools.product(*args, **kwds) | [
"Random",
"selection",
"from",
"itertools",
".",
"product",
"(",
"*",
"args",
"**",
"kwds",
")"
] | train | https://github.com/nxdevel/nx_itertools/blob/744da75c616a8a7991b963a549152fe9c434abd9/nx_itertools/recipes.py#L203-L206 |
JohnVinyard/featureflow | featureflow/feature.py | Feature.copy | def copy(
self,
extractor=None,
needs=None,
store=None,
data_writer=None,
persistence=None,
extractor_args=None):
"""
Use self as a template to build a new feature, replacing
values in kwargs
"""
... | python | def copy(
self,
extractor=None,
needs=None,
store=None,
data_writer=None,
persistence=None,
extractor_args=None):
"""
Use self as a template to build a new feature, replacing
values in kwargs
"""
... | [
"def",
"copy",
"(",
"self",
",",
"extractor",
"=",
"None",
",",
"needs",
"=",
"None",
",",
"store",
"=",
"None",
",",
"data_writer",
"=",
"None",
",",
"persistence",
"=",
"None",
",",
"extractor_args",
"=",
"None",
")",
":",
"f",
"=",
"Feature",
"(",... | Use self as a template to build a new feature, replacing
values in kwargs | [
"Use",
"self",
"as",
"a",
"template",
"to",
"build",
"a",
"new",
"feature",
"replacing",
"values",
"in",
"kwargs"
] | train | https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/feature.py#L107-L130 |
JohnVinyard/featureflow | featureflow/feature.py | Feature._can_compute | def _can_compute(self, _id, persistence):
"""
Return true if this feature stored, or is unstored, but can be computed
from stored dependencies
"""
if self.store and self._stored(_id, persistence):
return True
if self.is_root:
return False
... | python | def _can_compute(self, _id, persistence):
"""
Return true if this feature stored, or is unstored, but can be computed
from stored dependencies
"""
if self.store and self._stored(_id, persistence):
return True
if self.is_root:
return False
... | [
"def",
"_can_compute",
"(",
"self",
",",
"_id",
",",
"persistence",
")",
":",
"if",
"self",
".",
"store",
"and",
"self",
".",
"_stored",
"(",
"_id",
",",
"persistence",
")",
":",
"return",
"True",
"if",
"self",
".",
"is_root",
":",
"return",
"False",
... | Return true if this feature stored, or is unstored, but can be computed
from stored dependencies | [
"Return",
"true",
"if",
"this",
"feature",
"stored",
"or",
"is",
"unstored",
"but",
"can",
"be",
"computed",
"from",
"stored",
"dependencies"
] | train | https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/feature.py#L163-L175 |
JohnVinyard/featureflow | featureflow/feature.py | Feature._partial | def _partial(self, _id, features=None, persistence=None):
"""
TODO: _partial is a shit name for this, kind of. I'm building a graph
such that I can only do work necessary to compute self, and no more
"""
root = features is None
stored = self._stored(_id, persistence)
... | python | def _partial(self, _id, features=None, persistence=None):
"""
TODO: _partial is a shit name for this, kind of. I'm building a graph
such that I can only do work necessary to compute self, and no more
"""
root = features is None
stored = self._stored(_id, persistence)
... | [
"def",
"_partial",
"(",
"self",
",",
"_id",
",",
"features",
"=",
"None",
",",
"persistence",
"=",
"None",
")",
":",
"root",
"=",
"features",
"is",
"None",
"stored",
"=",
"self",
".",
"_stored",
"(",
"_id",
",",
"persistence",
")",
"is_cached",
"=",
... | TODO: _partial is a shit name for this, kind of. I'm building a graph
such that I can only do work necessary to compute self, and no more | [
"TODO",
":",
"_partial",
"is",
"a",
"shit",
"name",
"for",
"this",
"kind",
"of",
".",
"I",
"m",
"building",
"a",
"graph",
"such",
"that",
"I",
"can",
"only",
"do",
"work",
"necessary",
"to",
"compute",
"self",
"and",
"no",
"more"
] | train | https://github.com/JohnVinyard/featureflow/blob/7731487b00e38fa4f58c88b7881870fda2d69fdb/featureflow/feature.py#L229-L267 |
RudolfCardinal/pythonlib | cardinal_pythonlib/dbfunc.py | genrows | def genrows(cursor: Cursor, arraysize: int = 1000) \
-> Generator[List[Any], None, None]:
"""
Generate all rows from a cursor.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row
"""
# http://code.activestate.com/r... | python | def genrows(cursor: Cursor, arraysize: int = 1000) \
-> Generator[List[Any], None, None]:
"""
Generate all rows from a cursor.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row
"""
# http://code.activestate.com/r... | [
"def",
"genrows",
"(",
"cursor",
":",
"Cursor",
",",
"arraysize",
":",
"int",
"=",
"1000",
")",
"->",
"Generator",
"[",
"List",
"[",
"Any",
"]",
",",
"None",
",",
"None",
"]",
":",
"# http://code.activestate.com/recipes/137270-use-generators-for-fetching-large-db-... | Generate all rows from a cursor.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row | [
"Generate",
"all",
"rows",
"from",
"a",
"cursor",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L44-L62 |
RudolfCardinal/pythonlib | cardinal_pythonlib/dbfunc.py | genfirstvalues | def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Any, None, None]:
"""
Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
the first value of each row
"""
return... | python | def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Any, None, None]:
"""
Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
the first value of each row
"""
return... | [
"def",
"genfirstvalues",
"(",
"cursor",
":",
"Cursor",
",",
"arraysize",
":",
"int",
"=",
"1000",
")",
"->",
"Generator",
"[",
"Any",
",",
"None",
",",
"None",
"]",
":",
"return",
"(",
"row",
"[",
"0",
"]",
"for",
"row",
"in",
"genrows",
"(",
"curs... | Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
the first value of each row | [
"Generate",
"the",
"first",
"value",
"in",
"each",
"row",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L65-L77 |
RudolfCardinal/pythonlib | cardinal_pythonlib/dbfunc.py | gendicts | def gendicts(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Dict[str, Any], None, None]:
"""
Generate all rows from a cursor as :class:`OrderedDict` objects.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row, as a... | python | def gendicts(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Dict[str, Any], None, None]:
"""
Generate all rows from a cursor as :class:`OrderedDict` objects.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row, as a... | [
"def",
"gendicts",
"(",
"cursor",
":",
"Cursor",
",",
"arraysize",
":",
"int",
"=",
"1000",
")",
"->",
"Generator",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"None",
",",
"None",
"]",
":",
"columns",
"=",
"get_fieldnames_from_cursor",
"(",
"cursor... | Generate all rows from a cursor as :class:`OrderedDict` objects.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
each row, as an :class:`OrderedDict` whose key are column names
and whose values are the row values | [
"Generate",
"all",
"rows",
"from",
"a",
"cursor",
"as",
":",
"class",
":",
"OrderedDict",
"objects",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L87-L104 |
RudolfCardinal/pythonlib | cardinal_pythonlib/dbfunc.py | dictfetchall | def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]:
"""
Return all rows from a cursor as a list of :class:`OrderedDict` objects.
Args:
cursor: the cursor
Returns:
a list (one item per row) of :class:`OrderedDict` objects whose key are
column names and whose values are the... | python | def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]:
"""
Return all rows from a cursor as a list of :class:`OrderedDict` objects.
Args:
cursor: the cursor
Returns:
a list (one item per row) of :class:`OrderedDict` objects whose key are
column names and whose values are the... | [
"def",
"dictfetchall",
"(",
"cursor",
":",
"Cursor",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"columns",
"=",
"get_fieldnames_from_cursor",
"(",
"cursor",
")",
"return",
"[",
"OrderedDict",
"(",
"zip",
"(",
"columns",
",",
... | Return all rows from a cursor as a list of :class:`OrderedDict` objects.
Args:
cursor: the cursor
Returns:
a list (one item per row) of :class:`OrderedDict` objects whose key are
column names and whose values are the row values | [
"Return",
"all",
"rows",
"from",
"a",
"cursor",
"as",
"a",
"list",
"of",
":",
"class",
":",
"OrderedDict",
"objects",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L107-L122 |
RudolfCardinal/pythonlib | cardinal_pythonlib/dbfunc.py | dictfetchone | def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]:
"""
Return the next row from a cursor as an :class:`OrderedDict`, or ``None``.
"""
columns = get_fieldnames_from_cursor(cursor)
row = cursor.fetchone()
if not row:
return None
return OrderedDict(zip(columns, row)) | python | def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]:
"""
Return the next row from a cursor as an :class:`OrderedDict`, or ``None``.
"""
columns = get_fieldnames_from_cursor(cursor)
row = cursor.fetchone()
if not row:
return None
return OrderedDict(zip(columns, row)) | [
"def",
"dictfetchone",
"(",
"cursor",
":",
"Cursor",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"columns",
"=",
"get_fieldnames_from_cursor",
"(",
"cursor",
")",
"row",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"if",
"no... | Return the next row from a cursor as an :class:`OrderedDict`, or ``None``. | [
"Return",
"the",
"next",
"row",
"from",
"a",
"cursor",
"as",
"an",
":",
"class",
":",
"OrderedDict",
"or",
"None",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dbfunc.py#L125-L133 |
RudolfCardinal/pythonlib | cardinal_pythonlib/colander_utils.py | get_values_and_permissible | def get_values_and_permissible(values: Iterable[Tuple[Any, str]],
add_none: bool = False,
none_description: str = "[None]") \
-> Tuple[List[Tuple[Any, str]], List[Any]]:
"""
Used when building Colander nodes.
Args:
values: an ite... | python | def get_values_and_permissible(values: Iterable[Tuple[Any, str]],
add_none: bool = False,
none_description: str = "[None]") \
-> Tuple[List[Tuple[Any, str]], List[Any]]:
"""
Used when building Colander nodes.
Args:
values: an ite... | [
"def",
"get_values_and_permissible",
"(",
"values",
":",
"Iterable",
"[",
"Tuple",
"[",
"Any",
",",
"str",
"]",
"]",
",",
"add_none",
":",
"bool",
"=",
"False",
",",
"none_description",
":",
"str",
"=",
"\"[None]\"",
")",
"->",
"Tuple",
"[",
"List",
"[",... | Used when building Colander nodes.
Args:
values: an iterable of tuples like ``(value, description)`` used in
HTML forms
add_none: add a tuple ``(None, none_description)`` at the start of
``values`` in the result?
none_description: the description used for ``None`` ... | [
"Used",
"when",
"building",
"Colander",
"nodes",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/colander_utils.py#L198-L229 |
RudolfCardinal/pythonlib | cardinal_pythonlib/colander_utils.py | PendulumType.serialize | def serialize(self,
node: SchemaNode,
appstruct: Union[PotentialDatetimeType,
ColanderNullType]) \
-> Union[str, ColanderNullType]:
"""
Serializes Python object to string representation.
"""
if not appstru... | python | def serialize(self,
node: SchemaNode,
appstruct: Union[PotentialDatetimeType,
ColanderNullType]) \
-> Union[str, ColanderNullType]:
"""
Serializes Python object to string representation.
"""
if not appstru... | [
"def",
"serialize",
"(",
"self",
",",
"node",
":",
"SchemaNode",
",",
"appstruct",
":",
"Union",
"[",
"PotentialDatetimeType",
",",
"ColanderNullType",
"]",
")",
"->",
"Union",
"[",
"str",
",",
"ColanderNullType",
"]",
":",
"if",
"not",
"appstruct",
":",
"... | Serializes Python object to string representation. | [
"Serializes",
"Python",
"object",
"to",
"string",
"representation",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/colander_utils.py#L100-L118 |
RudolfCardinal/pythonlib | cardinal_pythonlib/colander_utils.py | PendulumType.deserialize | def deserialize(self,
node: SchemaNode,
cstruct: Union[str, ColanderNullType]) \
-> Optional[Pendulum]:
"""
Deserializes string representation to Python object.
"""
if not cstruct:
return colander.null
try:
... | python | def deserialize(self,
node: SchemaNode,
cstruct: Union[str, ColanderNullType]) \
-> Optional[Pendulum]:
"""
Deserializes string representation to Python object.
"""
if not cstruct:
return colander.null
try:
... | [
"def",
"deserialize",
"(",
"self",
",",
"node",
":",
"SchemaNode",
",",
"cstruct",
":",
"Union",
"[",
"str",
",",
"ColanderNullType",
"]",
")",
"->",
"Optional",
"[",
"Pendulum",
"]",
":",
"if",
"not",
"cstruct",
":",
"return",
"colander",
".",
"null",
... | Deserializes string representation to Python object. | [
"Deserializes",
"string",
"representation",
"to",
"Python",
"object",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/colander_utils.py#L120-L135 |
RudolfCardinal/pythonlib | cardinal_pythonlib/colander_utils.py | AllowNoneType.serialize | def serialize(self, node: SchemaNode,
value: Any) -> Union[str, ColanderNullType]:
"""
Serializes Python object to string representation.
"""
if value is None:
retval = ''
else:
# noinspection PyUnresolvedReferences
retval = s... | python | def serialize(self, node: SchemaNode,
value: Any) -> Union[str, ColanderNullType]:
"""
Serializes Python object to string representation.
"""
if value is None:
retval = ''
else:
# noinspection PyUnresolvedReferences
retval = s... | [
"def",
"serialize",
"(",
"self",
",",
"node",
":",
"SchemaNode",
",",
"value",
":",
"Any",
")",
"->",
"Union",
"[",
"str",
",",
"ColanderNullType",
"]",
":",
"if",
"value",
"is",
"None",
":",
"retval",
"=",
"''",
"else",
":",
"# noinspection PyUnresolved... | Serializes Python object to string representation. | [
"Serializes",
"Python",
"object",
"to",
"string",
"representation",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/colander_utils.py#L167-L178 |
henzk/featuremonkey | featuremonkey/composer.py | get_features_from_equation_file | def get_features_from_equation_file(filename):
"""
returns list of feature names read from equation file given
by ``filename``.
format: one feature per line; comments start with ``#``
Example::
#this is a comment
basefeature
#empty lines are ignored
myfeature
... | python | def get_features_from_equation_file(filename):
"""
returns list of feature names read from equation file given
by ``filename``.
format: one feature per line; comments start with ``#``
Example::
#this is a comment
basefeature
#empty lines are ignored
myfeature
... | [
"def",
"get_features_from_equation_file",
"(",
"filename",
")",
":",
"features",
"=",
"[",
"]",
"for",
"line",
"in",
"open",
"(",
"filename",
")",
":",
"line",
"=",
"line",
".",
"split",
"(",
"'#'",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"if",
... | returns list of feature names read from equation file given
by ``filename``.
format: one feature per line; comments start with ``#``
Example::
#this is a comment
basefeature
#empty lines are ignored
myfeature
anotherfeature
:param filename:
:return: | [
"returns",
"list",
"of",
"feature",
"names",
"read",
"from",
"equation",
"file",
"given",
"by",
"filename",
"."
] | train | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L19-L42 |
henzk/featuremonkey | featuremonkey/composer.py | Composer._create_refinement_wrapper | def _create_refinement_wrapper(transformation, baseattr, base, target_attrname):
"""
applies refinement ``transformation`` to ``baseattr`` attribute of ``base``.
``baseattr`` can be any type of callable (function, method, functor)
this method handles the differences.
docstrings a... | python | def _create_refinement_wrapper(transformation, baseattr, base, target_attrname):
"""
applies refinement ``transformation`` to ``baseattr`` attribute of ``base``.
``baseattr`` can be any type of callable (function, method, functor)
this method handles the differences.
docstrings a... | [
"def",
"_create_refinement_wrapper",
"(",
"transformation",
",",
"baseattr",
",",
"base",
",",
"target_attrname",
")",
":",
"# first step: extract the original",
"special_refinement_type",
"=",
"None",
"instance_refinement",
"=",
"_is_class_instance",
"(",
"base",
")",
"i... | applies refinement ``transformation`` to ``baseattr`` attribute of ``base``.
``baseattr`` can be any type of callable (function, method, functor)
this method handles the differences.
docstrings are also rescued from the original if the refinement
has no docstring set. | [
"applies",
"refinement",
"transformation",
"to",
"baseattr",
"attribute",
"of",
"base",
".",
"baseattr",
"can",
"be",
"any",
"type",
"of",
"callable",
"(",
"function",
"method",
"functor",
")",
"this",
"method",
"handles",
"the",
"differences",
".",
"docstrings"... | train | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L155-L205 |
henzk/featuremonkey | featuremonkey/composer.py | Composer._compose_pair | def _compose_pair(self, role, base):
'''
composes onto base by applying the role
'''
# apply transformations in role to base
for attrname in dir(role):
transformation = getattr(role, attrname)
self._apply_transformation(role, base, transformation, attrname... | python | def _compose_pair(self, role, base):
'''
composes onto base by applying the role
'''
# apply transformations in role to base
for attrname in dir(role):
transformation = getattr(role, attrname)
self._apply_transformation(role, base, transformation, attrname... | [
"def",
"_compose_pair",
"(",
"self",
",",
"role",
",",
"base",
")",
":",
"# apply transformations in role to base",
"for",
"attrname",
"in",
"dir",
"(",
"role",
")",
":",
"transformation",
"=",
"getattr",
"(",
"role",
",",
"attrname",
")",
"self",
".",
"_app... | composes onto base by applying the role | [
"composes",
"onto",
"base",
"by",
"applying",
"the",
"role"
] | train | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L219-L228 |
henzk/featuremonkey | featuremonkey/composer.py | Composer.compose | def compose(self, *things):
'''
compose applies multiple fsts onto a base implementation.
Pass the base implementation as last parameter.
fsts are merged from RIGHT TO LEFT (like function application)
e.g.:
class MyFST(object):
#place introductions and refine... | python | def compose(self, *things):
'''
compose applies multiple fsts onto a base implementation.
Pass the base implementation as last parameter.
fsts are merged from RIGHT TO LEFT (like function application)
e.g.:
class MyFST(object):
#place introductions and refine... | [
"def",
"compose",
"(",
"self",
",",
"*",
"things",
")",
":",
"if",
"not",
"len",
"(",
"things",
")",
":",
"raise",
"CompositionError",
"(",
"'nothing to compose'",
")",
"if",
"len",
"(",
"things",
")",
"==",
"1",
":",
"# composing one element is simple",
"... | compose applies multiple fsts onto a base implementation.
Pass the base implementation as last parameter.
fsts are merged from RIGHT TO LEFT (like function application)
e.g.:
class MyFST(object):
#place introductions and refinements here
introduce_foo = 'bar'
... | [
"compose",
"applies",
"multiple",
"fsts",
"onto",
"a",
"base",
"implementation",
".",
"Pass",
"the",
"base",
"implementation",
"as",
"last",
"parameter",
".",
"fsts",
"are",
"merged",
"from",
"RIGHT",
"TO",
"LEFT",
"(",
"like",
"function",
"application",
")",
... | train | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L230-L254 |
henzk/featuremonkey | featuremonkey/composer.py | Composer.compose_later | def compose_later(self, *things):
"""
register list of things for composition using compose()
compose_later takes a list of fsts.
The last element specifies the base module as string
things are composed directly after the base module
is imported by application code
... | python | def compose_later(self, *things):
"""
register list of things for composition using compose()
compose_later takes a list of fsts.
The last element specifies the base module as string
things are composed directly after the base module
is imported by application code
... | [
"def",
"compose_later",
"(",
"self",
",",
"*",
"things",
")",
":",
"if",
"len",
"(",
"things",
")",
"==",
"1",
":",
"return",
"things",
"[",
"0",
"]",
"module_name",
"=",
"things",
"[",
"-",
"1",
"]",
"if",
"module_name",
"in",
"sys",
".",
"modules... | register list of things for composition using compose()
compose_later takes a list of fsts.
The last element specifies the base module as string
things are composed directly after the base module
is imported by application code | [
"register",
"list",
"of",
"things",
"for",
"composition",
"using",
"compose",
"()"
] | train | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L256-L273 |
henzk/featuremonkey | featuremonkey/composer.py | Composer.select | def select(self, *features):
"""
selects the features given as string
e.g
passing 'hello' and 'world' will result in imports of
'hello' and 'world'. Then, if possible 'hello.feature'
and 'world.feature' are imported and select is called
in each feature module.
... | python | def select(self, *features):
"""
selects the features given as string
e.g
passing 'hello' and 'world' will result in imports of
'hello' and 'world'. Then, if possible 'hello.feature'
and 'world.feature' are imported and select is called
in each feature module.
... | [
"def",
"select",
"(",
"self",
",",
"*",
"features",
")",
":",
"for",
"feature_name",
"in",
"features",
":",
"feature_module",
"=",
"importlib",
".",
"import_module",
"(",
"feature_name",
")",
"# if available, import feature.py and select the feature",
"try",
":",
"f... | selects the features given as string
e.g
passing 'hello' and 'world' will result in imports of
'hello' and 'world'. Then, if possible 'hello.feature'
and 'world.feature' are imported and select is called
in each feature module. | [
"selects",
"the",
"features",
"given",
"as",
"string",
"e",
".",
"g",
"passing",
"hello",
"and",
"world",
"will",
"result",
"in",
"imports",
"of",
"hello",
"and",
"world",
".",
"Then",
"if",
"possible",
"hello",
".",
"feature",
"and",
"world",
".",
"feat... | train | https://github.com/henzk/featuremonkey/blob/e44414fc68427bcd71ad33ec2d816da0dd78eefa/featuremonkey/composer.py#L275-L320 |
davenquinn/Attitude | attitude/display/pca_aligned.py | plot_aligned | def plot_aligned(pca, sparse=True, **kwargs):
""" Plots the residuals of a principal component
analysis of attiude data.
"""
colormap = kwargs.pop('colormap',None)
A = pca.rotated()
# Flip the result if upside down
if pca.normal[2] < 0:
A[:,-1] *= -1
minmax = [(A[:,i].min(),... | python | def plot_aligned(pca, sparse=True, **kwargs):
""" Plots the residuals of a principal component
analysis of attiude data.
"""
colormap = kwargs.pop('colormap',None)
A = pca.rotated()
# Flip the result if upside down
if pca.normal[2] < 0:
A[:,-1] *= -1
minmax = [(A[:,i].min(),... | [
"def",
"plot_aligned",
"(",
"pca",
",",
"sparse",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"colormap",
"=",
"kwargs",
".",
"pop",
"(",
"'colormap'",
",",
"None",
")",
"A",
"=",
"pca",
".",
"rotated",
"(",
")",
"# Flip the result if upside down",
... | Plots the residuals of a principal component
analysis of attiude data. | [
"Plots",
"the",
"residuals",
"of",
"a",
"principal",
"component",
"analysis",
"of",
"attiude",
"data",
"."
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/pca_aligned.py#L18-L141 |
meyersj/geotweet | geotweet/mapreduce/poi_nearby_tweets.py | POINearbyTweetsMRJob.mapper_metro | def mapper_metro(self, _, data):
""" map each osm POI and geotweets based on spatial lookup of metro area """
# OSM POI record
if 'tags' in data:
type_tag = 1
lonlat = data['coordinates']
payload = data['tags']
# Tweet with coordinates from Streaming A... | python | def mapper_metro(self, _, data):
""" map each osm POI and geotweets based on spatial lookup of metro area """
# OSM POI record
if 'tags' in data:
type_tag = 1
lonlat = data['coordinates']
payload = data['tags']
# Tweet with coordinates from Streaming A... | [
"def",
"mapper_metro",
"(",
"self",
",",
"_",
",",
"data",
")",
":",
"# OSM POI record",
"if",
"'tags'",
"in",
"data",
":",
"type_tag",
"=",
"1",
"lonlat",
"=",
"data",
"[",
"'coordinates'",
"]",
"payload",
"=",
"data",
"[",
"'tags'",
"]",
"# Tweet with ... | map each osm POI and geotweets based on spatial lookup of metro area | [
"map",
"each",
"osm",
"POI",
"and",
"geotweets",
"based",
"on",
"spatial",
"lookup",
"of",
"metro",
"area"
] | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L81-L108 |
meyersj/geotweet | geotweet/mapreduce/poi_nearby_tweets.py | POINearbyTweetsMRJob.reducer_metro | def reducer_metro(self, metro, values):
"""
Output tags of POI locations nearby tweet locations
Values will be sorted coming into reducer.
First element in each value tuple will be either 1 (osm POI) or 2 (geotweet).
Build a spatial index with POI records.
For each tweet... | python | def reducer_metro(self, metro, values):
"""
Output tags of POI locations nearby tweet locations
Values will be sorted coming into reducer.
First element in each value tuple will be either 1 (osm POI) or 2 (geotweet).
Build a spatial index with POI records.
For each tweet... | [
"def",
"reducer_metro",
"(",
"self",
",",
"metro",
",",
"values",
")",
":",
"lookup",
"=",
"CachedLookup",
"(",
"precision",
"=",
"POI_GEOHASH_PRECISION",
")",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"values",
")",
":",
"type_tag",
",",
"lonlat",... | Output tags of POI locations nearby tweet locations
Values will be sorted coming into reducer.
First element in each value tuple will be either 1 (osm POI) or 2 (geotweet).
Build a spatial index with POI records.
For each tweet lookup nearby POI, and emit tag values for predefined tags. | [
"Output",
"tags",
"of",
"POI",
"locations",
"nearby",
"tweet",
"locations"
] | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L110-L142 |
meyersj/geotweet | geotweet/mapreduce/poi_nearby_tweets.py | POINearbyTweetsMRJob.reducer_count | def reducer_count(self, key, values):
""" count occurences for each (metro, POI) record """
total = sum(values)
metro, poi = key
# group data by metro areas for final output
yield metro, (total, poi) | python | def reducer_count(self, key, values):
""" count occurences for each (metro, POI) record """
total = sum(values)
metro, poi = key
# group data by metro areas for final output
yield metro, (total, poi) | [
"def",
"reducer_count",
"(",
"self",
",",
"key",
",",
"values",
")",
":",
"total",
"=",
"sum",
"(",
"values",
")",
"metro",
",",
"poi",
"=",
"key",
"# group data by metro areas for final output ",
"yield",
"metro",
",",
"(",
"total",
",",
"poi",
")"
] | count occurences for each (metro, POI) record | [
"count",
"occurences",
"for",
"each",
"(",
"metro",
"POI",
")",
"record"
] | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L144-L149 |
meyersj/geotweet | geotweet/mapreduce/poi_nearby_tweets.py | POINearbyTweetsMRJob.reducer_output | def reducer_output(self, metro, values):
""" store each record in MongoDB and output tab delimited lines """
records = []
# build up list of data for each metro area and submit as one network
# call instead of individually
for value in values:
total, poi = value
... | python | def reducer_output(self, metro, values):
""" store each record in MongoDB and output tab delimited lines """
records = []
# build up list of data for each metro area and submit as one network
# call instead of individually
for value in values:
total, poi = value
... | [
"def",
"reducer_output",
"(",
"self",
",",
"metro",
",",
"values",
")",
":",
"records",
"=",
"[",
"]",
"# build up list of data for each metro area and submit as one network",
"# call instead of individually ",
"for",
"value",
"in",
"values",
":",
"total",
",",
"poi",
... | store each record in MongoDB and output tab delimited lines | [
"store",
"each",
"record",
"in",
"MongoDB",
"and",
"output",
"tab",
"delimited",
"lines"
] | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L159-L175 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/sqlfunc.py | fail_unknown_dialect | def fail_unknown_dialect(compiler: "SQLCompiler", task: str) -> None:
"""
Raise :exc:`NotImplementedError` in relation to a dialect for which a
function hasn't been implemented (with a helpful error message).
"""
raise NotImplementedError(
"Don't know how to {task} on dialect {dialect!r}. "
... | python | def fail_unknown_dialect(compiler: "SQLCompiler", task: str) -> None:
"""
Raise :exc:`NotImplementedError` in relation to a dialect for which a
function hasn't been implemented (with a helpful error message).
"""
raise NotImplementedError(
"Don't know how to {task} on dialect {dialect!r}. "
... | [
"def",
"fail_unknown_dialect",
"(",
"compiler",
":",
"\"SQLCompiler\"",
",",
"task",
":",
"str",
")",
"->",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"Don't know how to {task} on dialect {dialect!r}. \"",
"\"(Check also: if you printed the SQL before it was bound to an ... | Raise :exc:`NotImplementedError` in relation to a dialect for which a
function hasn't been implemented (with a helpful error message). | [
"Raise",
":",
"exc",
":",
"NotImplementedError",
"in",
"relation",
"to",
"a",
"dialect",
"for",
"which",
"a",
"function",
"hasn",
"t",
"been",
"implemented",
"(",
"with",
"a",
"helpful",
"error",
"message",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/sqlfunc.py#L50-L63 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/sqlfunc.py | fetch_processed_single_clause | def fetch_processed_single_clause(element: "ClauseElement",
compiler: "SQLCompiler") -> str:
"""
Takes a clause element that must have a single clause, and converts it
to raw SQL text.
"""
if len(element.clauses) != 1:
raise TypeError("Only one argument supp... | python | def fetch_processed_single_clause(element: "ClauseElement",
compiler: "SQLCompiler") -> str:
"""
Takes a clause element that must have a single clause, and converts it
to raw SQL text.
"""
if len(element.clauses) != 1:
raise TypeError("Only one argument supp... | [
"def",
"fetch_processed_single_clause",
"(",
"element",
":",
"\"ClauseElement\"",
",",
"compiler",
":",
"\"SQLCompiler\"",
")",
"->",
"str",
":",
"if",
"len",
"(",
"element",
".",
"clauses",
")",
"!=",
"1",
":",
"raise",
"TypeError",
"(",
"\"Only one argument su... | Takes a clause element that must have a single clause, and converts it
to raw SQL text. | [
"Takes",
"a",
"clause",
"element",
"that",
"must",
"have",
"a",
"single",
"clause",
"and",
"converts",
"it",
"to",
"raw",
"SQL",
"text",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/sqlfunc.py#L66-L77 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/forms.py | clean_int | def clean_int(x) -> int:
"""
Returns its parameter as an integer, or raises
``django.forms.ValidationError``.
"""
try:
return int(x)
except ValueError:
raise forms.ValidationError(
"Cannot convert to integer: {}".format(repr(x))) | python | def clean_int(x) -> int:
"""
Returns its parameter as an integer, or raises
``django.forms.ValidationError``.
"""
try:
return int(x)
except ValueError:
raise forms.ValidationError(
"Cannot convert to integer: {}".format(repr(x))) | [
"def",
"clean_int",
"(",
"x",
")",
"->",
"int",
":",
"try",
":",
"return",
"int",
"(",
"x",
")",
"except",
"ValueError",
":",
"raise",
"forms",
".",
"ValidationError",
"(",
"\"Cannot convert to integer: {}\"",
".",
"format",
"(",
"repr",
"(",
"x",
")",
"... | Returns its parameter as an integer, or raises
``django.forms.ValidationError``. | [
"Returns",
"its",
"parameter",
"as",
"an",
"integer",
"or",
"raises",
"django",
".",
"forms",
".",
"ValidationError",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/forms.py#L40-L49 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/forms.py | clean_nhs_number | def clean_nhs_number(x) -> int:
"""
Returns its parameter as a valid integer NHS number, or raises
``django.forms.ValidationError``.
"""
try:
x = int(x)
if not is_valid_nhs_number(x):
raise ValueError
return x
except ValueError:
raise forms.ValidationE... | python | def clean_nhs_number(x) -> int:
"""
Returns its parameter as a valid integer NHS number, or raises
``django.forms.ValidationError``.
"""
try:
x = int(x)
if not is_valid_nhs_number(x):
raise ValueError
return x
except ValueError:
raise forms.ValidationE... | [
"def",
"clean_nhs_number",
"(",
"x",
")",
"->",
"int",
":",
"try",
":",
"x",
"=",
"int",
"(",
"x",
")",
"if",
"not",
"is_valid_nhs_number",
"(",
"x",
")",
":",
"raise",
"ValueError",
"return",
"x",
"except",
"ValueError",
":",
"raise",
"forms",
".",
... | Returns its parameter as a valid integer NHS number, or raises
``django.forms.ValidationError``. | [
"Returns",
"its",
"parameter",
"as",
"a",
"valid",
"integer",
"NHS",
"number",
"or",
"raises",
"django",
".",
"forms",
".",
"ValidationError",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/forms.py#L52-L64 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | coltype_as_typeengine | def coltype_as_typeengine(coltype: Union[VisitableType,
TypeEngine]) -> TypeEngine:
"""
Instances of SQLAlchemy column types are subclasses of ``TypeEngine``.
It's possible to specify column types either as such instances, or as the
class type. This function ensu... | python | def coltype_as_typeengine(coltype: Union[VisitableType,
TypeEngine]) -> TypeEngine:
"""
Instances of SQLAlchemy column types are subclasses of ``TypeEngine``.
It's possible to specify column types either as such instances, or as the
class type. This function ensu... | [
"def",
"coltype_as_typeengine",
"(",
"coltype",
":",
"Union",
"[",
"VisitableType",
",",
"TypeEngine",
"]",
")",
"->",
"TypeEngine",
":",
"if",
"isinstance",
"(",
"coltype",
",",
"TypeEngine",
")",
":",
"return",
"coltype",
"return",
"coltype",
"(",
")"
] | Instances of SQLAlchemy column types are subclasses of ``TypeEngine``.
It's possible to specify column types either as such instances, or as the
class type. This function ensures that such classes are converted to
instances.
To explain: you can specify columns like
.. code-block:: python
... | [
"Instances",
"of",
"SQLAlchemy",
"column",
"types",
"are",
"subclasses",
"of",
"TypeEngine",
".",
"It",
"s",
"possible",
"to",
"specify",
"column",
"types",
"either",
"as",
"such",
"instances",
"or",
"as",
"the",
"class",
"type",
".",
"This",
"function",
"en... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L60-L89 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | walk_orm_tree | def walk_orm_tree(obj,
debug: bool = False,
seen: Set = None,
skip_relationships_always: List[str] = None,
skip_relationships_by_tablename: Dict[str, List[str]] = None,
skip_all_relationships_for_tablenames: List[str] = None,
... | python | def walk_orm_tree(obj,
debug: bool = False,
seen: Set = None,
skip_relationships_always: List[str] = None,
skip_relationships_by_tablename: Dict[str, List[str]] = None,
skip_all_relationships_for_tablenames: List[str] = None,
... | [
"def",
"walk_orm_tree",
"(",
"obj",
",",
"debug",
":",
"bool",
"=",
"False",
",",
"seen",
":",
"Set",
"=",
"None",
",",
"skip_relationships_always",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"skip_relationships_by_tablename",
":",
"Dict",
"[",
"str",... | Starting with a SQLAlchemy ORM object, this function walks a
relationship tree, yielding each of the objects once.
To skip attributes by name, put the attribute name(s) in
``skip_attrs_always``. To skip by table name, pass
``skip_attrs_by_tablename`` as e.g.
.. code-block:: python
{'somet... | [
"Starting",
"with",
"a",
"SQLAlchemy",
"ORM",
"object",
"this",
"function",
"walks",
"a",
"relationship",
"tree",
"yielding",
"each",
"of",
"the",
"objects",
"once",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L140-L226 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | copy_sqla_object | def copy_sqla_object(obj: object,
omit_fk: bool = True,
omit_pk: bool = True,
omit_attrs: List[str] = None,
debug: bool = False) -> object:
"""
Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT
MUST SUPP... | python | def copy_sqla_object(obj: object,
omit_fk: bool = True,
omit_pk: bool = True,
omit_attrs: List[str] = None,
debug: bool = False) -> object:
"""
Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT
MUST SUPP... | [
"def",
"copy_sqla_object",
"(",
"obj",
":",
"object",
",",
"omit_fk",
":",
"bool",
"=",
"True",
",",
"omit_pk",
":",
"bool",
"=",
"True",
",",
"omit_attrs",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"debug",
":",
"bool",
"=",
"False",
")",
"-... | Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT
MUST SUPPORT CREATION USING ``__init__()`` WITH NO PARAMETERS), and copies
across all attributes, omitting PKs (by default), FKs (by default), and
relationship attributes (always omitted).
Args:
obj: the object to copy
... | [
"Given",
"an",
"SQLAlchemy",
"object",
"creates",
"a",
"new",
"object",
"(",
"FOR",
"WHICH",
"THE",
"OBJECT",
"MUST",
"SUPPORT",
"CREATION",
"USING",
"__init__",
"()",
"WITH",
"NO",
"PARAMETERS",
")",
"and",
"copies",
"across",
"all",
"attributes",
"omitting",... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L240-L288 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | rewrite_relationships | def rewrite_relationships(oldobj: object,
newobj: object,
objmap: Dict[object, object],
debug: bool = False,
skip_table_names: List[str] = None) -> None:
"""
A utility function only.
Used in copying objec... | python | def rewrite_relationships(oldobj: object,
newobj: object,
objmap: Dict[object, object],
debug: bool = False,
skip_table_names: List[str] = None) -> None:
"""
A utility function only.
Used in copying objec... | [
"def",
"rewrite_relationships",
"(",
"oldobj",
":",
"object",
",",
"newobj",
":",
"object",
",",
"objmap",
":",
"Dict",
"[",
"object",
",",
"object",
"]",
",",
"debug",
":",
"bool",
"=",
"False",
",",
"skip_table_names",
":",
"List",
"[",
"str",
"]",
"... | A utility function only.
Used in copying objects between SQLAlchemy sessions.
Both ``oldobj`` and ``newobj`` are SQLAlchemy instances. The instance
``newobj`` is already a copy of ``oldobj`` but we wish to rewrite its
relationships, according to the map ``objmap``, which maps old to new
objects.
... | [
"A",
"utility",
"function",
"only",
".",
"Used",
"in",
"copying",
"objects",
"between",
"SQLAlchemy",
"sessions",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L291-L382 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | deepcopy_sqla_objects | def deepcopy_sqla_objects(
startobjs: List[object],
session: Session,
flush: bool = True,
debug: bool = False,
debug_walk: bool = True,
debug_rewrite_rel: bool = False,
objmap: Dict[object, object] = None) -> None:
"""
Makes a copy of the specified SQLAlch... | python | def deepcopy_sqla_objects(
startobjs: List[object],
session: Session,
flush: bool = True,
debug: bool = False,
debug_walk: bool = True,
debug_rewrite_rel: bool = False,
objmap: Dict[object, object] = None) -> None:
"""
Makes a copy of the specified SQLAlch... | [
"def",
"deepcopy_sqla_objects",
"(",
"startobjs",
":",
"List",
"[",
"object",
"]",
",",
"session",
":",
"Session",
",",
"flush",
":",
"bool",
"=",
"True",
",",
"debug",
":",
"bool",
"=",
"False",
",",
"debug_walk",
":",
"bool",
"=",
"True",
",",
"debug... | Makes a copy of the specified SQLAlchemy ORM objects, inserting them into a
new session.
This function operates in several passes:
1. Walk the ORM tree through all objects and their relationships, copying
every object thus found (via :func:`copy_sqla_object`, without their
relationships), an... | [
"Makes",
"a",
"copy",
"of",
"the",
"specified",
"SQLAlchemy",
"ORM",
"objects",
"inserting",
"them",
"into",
"a",
"new",
"session",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L385-L468 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | deepcopy_sqla_object | def deepcopy_sqla_object(startobj: object,
session: Session,
flush: bool = True,
debug: bool = False,
debug_walk: bool = False,
debug_rewrite_rel: bool = False,
objmap: D... | python | def deepcopy_sqla_object(startobj: object,
session: Session,
flush: bool = True,
debug: bool = False,
debug_walk: bool = False,
debug_rewrite_rel: bool = False,
objmap: D... | [
"def",
"deepcopy_sqla_object",
"(",
"startobj",
":",
"object",
",",
"session",
":",
"Session",
",",
"flush",
":",
"bool",
"=",
"True",
",",
"debug",
":",
"bool",
"=",
"False",
",",
"debug_walk",
":",
"bool",
"=",
"False",
",",
"debug_rewrite_rel",
":",
"... | Makes a copy of the object, inserting it into ``session``.
Uses :func:`deepcopy_sqla_objects` (q.v.).
A problem is the creation of duplicate dependency objects if you call it
repeatedly.
Optionally, if you pass the objmap in (which maps old to new objects), you
can call this function repeatedly t... | [
"Makes",
"a",
"copy",
"of",
"the",
"object",
"inserting",
"it",
"into",
"session",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L471-L516 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | gen_columns | def gen_columns(obj) -> Generator[Tuple[str, Column], None, None]:
"""
Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?"
Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object
instance. Also works with the corresponding SQLAlchemy ORM class. Examples:
.. code-block:... | python | def gen_columns(obj) -> Generator[Tuple[str, Column], None, None]:
"""
Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?"
Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object
instance. Also works with the corresponding SQLAlchemy ORM class. Examples:
.. code-block:... | [
"def",
"gen_columns",
"(",
"obj",
")",
"->",
"Generator",
"[",
"Tuple",
"[",
"str",
",",
"Column",
"]",
",",
"None",
",",
"None",
"]",
":",
"mapper",
"=",
"obj",
".",
"__mapper__",
"# type: Mapper",
"assert",
"mapper",
",",
"\"gen_columns called on {!r} whic... | Asks a SQLAlchemy ORM object: "what are your SQLAlchemy columns?"
Yields tuples of ``(attr_name, Column)`` from an SQLAlchemy ORM object
instance. Also works with the corresponding SQLAlchemy ORM class. Examples:
.. code-block:: python
from sqlalchemy.ext.declarative import declarative_base
... | [
"Asks",
"a",
"SQLAlchemy",
"ORM",
"object",
":",
"what",
"are",
"your",
"SQLAlchemy",
"columns?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L523-L557 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | get_pk_attrnames | def get_pk_attrnames(obj) -> List[str]:
"""
Asks an SQLAlchemy ORM object: "what are your primary key(s)?"
Args:
obj: SQLAlchemy ORM object
Returns:
list of attribute names of primary-key columns
"""
return [attrname
for attrname, column in gen_columns(obj)
... | python | def get_pk_attrnames(obj) -> List[str]:
"""
Asks an SQLAlchemy ORM object: "what are your primary key(s)?"
Args:
obj: SQLAlchemy ORM object
Returns:
list of attribute names of primary-key columns
"""
return [attrname
for attrname, column in gen_columns(obj)
... | [
"def",
"get_pk_attrnames",
"(",
"obj",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"attrname",
"for",
"attrname",
",",
"column",
"in",
"gen_columns",
"(",
"obj",
")",
"if",
"column",
".",
"primary_key",
"]"
] | Asks an SQLAlchemy ORM object: "what are your primary key(s)?"
Args:
obj: SQLAlchemy ORM object
Returns:
list of attribute names of primary-key columns | [
"Asks",
"an",
"SQLAlchemy",
"ORM",
"object",
":",
"what",
"are",
"your",
"primary",
"key",
"(",
"s",
")",
"?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L566-L579 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | gen_columns_for_uninstrumented_class | def gen_columns_for_uninstrumented_class(cls: Type) \
-> Generator[Tuple[str, Column], None, None]:
"""
Generate ``(attr_name, Column)`` tuples from an UNINSTRUMENTED class, i.e.
one that does not inherit from ``declarative_base()``. Use this for mixins
of that kind.
SUBOPTIMAL. May produce... | python | def gen_columns_for_uninstrumented_class(cls: Type) \
-> Generator[Tuple[str, Column], None, None]:
"""
Generate ``(attr_name, Column)`` tuples from an UNINSTRUMENTED class, i.e.
one that does not inherit from ``declarative_base()``. Use this for mixins
of that kind.
SUBOPTIMAL. May produce... | [
"def",
"gen_columns_for_uninstrumented_class",
"(",
"cls",
":",
"Type",
")",
"->",
"Generator",
"[",
"Tuple",
"[",
"str",
",",
"Column",
"]",
",",
"None",
",",
"None",
"]",
":",
"# noqa",
"for",
"attrname",
"in",
"dir",
"(",
"cls",
")",
":",
"potential_c... | Generate ``(attr_name, Column)`` tuples from an UNINSTRUMENTED class, i.e.
one that does not inherit from ``declarative_base()``. Use this for mixins
of that kind.
SUBOPTIMAL. May produce warnings like:
.. code-block:: none
SAWarning: Unmanaged access of declarative attribute id from ... | [
"Generate",
"(",
"attr_name",
"Column",
")",
"tuples",
"from",
"an",
"UNINSTRUMENTED",
"class",
"i",
".",
"e",
".",
"one",
"that",
"does",
"not",
"inherit",
"from",
"declarative_base",
"()",
".",
"Use",
"this",
"for",
"mixins",
"of",
"that",
"kind",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L582-L600 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | attrname_to_colname_dict | def attrname_to_colname_dict(cls) -> Dict[str, str]:
"""
Asks an SQLAlchemy class how its attribute names correspond to database
column names.
Args:
cls: SQLAlchemy ORM class
Returns:
a dictionary mapping attribute names to database column names
"""
attr_col = {} # type: D... | python | def attrname_to_colname_dict(cls) -> Dict[str, str]:
"""
Asks an SQLAlchemy class how its attribute names correspond to database
column names.
Args:
cls: SQLAlchemy ORM class
Returns:
a dictionary mapping attribute names to database column names
"""
attr_col = {} # type: D... | [
"def",
"attrname_to_colname_dict",
"(",
"cls",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"attr_col",
"=",
"{",
"}",
"# type: Dict[str, str]",
"for",
"attrname",
",",
"column",
"in",
"gen_columns",
"(",
"cls",
")",
":",
"attr_col",
"[",
"attrname... | Asks an SQLAlchemy class how its attribute names correspond to database
column names.
Args:
cls: SQLAlchemy ORM class
Returns:
a dictionary mapping attribute names to database column names | [
"Asks",
"an",
"SQLAlchemy",
"class",
"how",
"its",
"attribute",
"names",
"correspond",
"to",
"database",
"column",
"names",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L603-L617 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | gen_relationships | def gen_relationships(obj) -> Generator[Tuple[str, RelationshipProperty, Type],
None, None]:
"""
Yields tuples of ``(attrname, RelationshipProperty, related_class)``
for all relationships of an ORM object.
The object 'obj' can be EITHER an instance OR a class.
... | python | def gen_relationships(obj) -> Generator[Tuple[str, RelationshipProperty, Type],
None, None]:
"""
Yields tuples of ``(attrname, RelationshipProperty, related_class)``
for all relationships of an ORM object.
The object 'obj' can be EITHER an instance OR a class.
... | [
"def",
"gen_relationships",
"(",
"obj",
")",
"->",
"Generator",
"[",
"Tuple",
"[",
"str",
",",
"RelationshipProperty",
",",
"Type",
"]",
",",
"None",
",",
"None",
"]",
":",
"insp",
"=",
"inspect",
"(",
"obj",
")",
"# type: InstanceState",
"# insp.mapper.rela... | Yields tuples of ``(attrname, RelationshipProperty, related_class)``
for all relationships of an ORM object.
The object 'obj' can be EITHER an instance OR a class. | [
"Yields",
"tuples",
"of",
"(",
"attrname",
"RelationshipProperty",
"related_class",
")",
"for",
"all",
"relationships",
"of",
"an",
"ORM",
"object",
".",
"The",
"object",
"obj",
"can",
"be",
"EITHER",
"an",
"instance",
"OR",
"a",
"class",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L628-L645 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | get_orm_columns | def get_orm_columns(cls: Type) -> List[Column]:
"""
Gets :class:`Column` objects from an SQLAlchemy ORM class.
Does not provide their attribute names.
"""
mapper = inspect(cls) # type: Mapper
# ... returns InstanceState if called with an ORM object
# http://docs.sqlalchemy.org/en/latest... | python | def get_orm_columns(cls: Type) -> List[Column]:
"""
Gets :class:`Column` objects from an SQLAlchemy ORM class.
Does not provide their attribute names.
"""
mapper = inspect(cls) # type: Mapper
# ... returns InstanceState if called with an ORM object
# http://docs.sqlalchemy.org/en/latest... | [
"def",
"get_orm_columns",
"(",
"cls",
":",
"Type",
")",
"->",
"List",
"[",
"Column",
"]",
":",
"mapper",
"=",
"inspect",
"(",
"cls",
")",
"# type: Mapper",
"# ... returns InstanceState if called with an ORM object",
"# http://docs.sqlalchemy.org/en/latest/orm/session_st... | Gets :class:`Column` objects from an SQLAlchemy ORM class.
Does not provide their attribute names. | [
"Gets",
":",
"class",
":",
"Column",
"objects",
"from",
"an",
"SQLAlchemy",
"ORM",
"class",
".",
"Does",
"not",
"provide",
"their",
"attribute",
"names",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L652-L663 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | get_orm_column_names | def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]:
"""
Gets column names (that is, database column names) from an SQLAlchemy
ORM class.
"""
colnames = [col.name for col in get_orm_columns(cls)]
return sorted(colnames) if sort else colnames | python | def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]:
"""
Gets column names (that is, database column names) from an SQLAlchemy
ORM class.
"""
colnames = [col.name for col in get_orm_columns(cls)]
return sorted(colnames) if sort else colnames | [
"def",
"get_orm_column_names",
"(",
"cls",
":",
"Type",
",",
"sort",
":",
"bool",
"=",
"False",
")",
"->",
"List",
"[",
"str",
"]",
":",
"colnames",
"=",
"[",
"col",
".",
"name",
"for",
"col",
"in",
"get_orm_columns",
"(",
"cls",
")",
"]",
"return",
... | Gets column names (that is, database column names) from an SQLAlchemy
ORM class. | [
"Gets",
"column",
"names",
"(",
"that",
"is",
"database",
"column",
"names",
")",
"from",
"an",
"SQLAlchemy",
"ORM",
"class",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L666-L672 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | get_table_names_from_metadata | def get_table_names_from_metadata(metadata: MetaData) -> List[str]:
"""
Returns all database table names found in an SQLAlchemy :class:`MetaData`
object.
"""
return [table.name for table in metadata.tables.values()] | python | def get_table_names_from_metadata(metadata: MetaData) -> List[str]:
"""
Returns all database table names found in an SQLAlchemy :class:`MetaData`
object.
"""
return [table.name for table in metadata.tables.values()] | [
"def",
"get_table_names_from_metadata",
"(",
"metadata",
":",
"MetaData",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"table",
".",
"name",
"for",
"table",
"in",
"metadata",
".",
"tables",
".",
"values",
"(",
")",
"]"
] | Returns all database table names found in an SQLAlchemy :class:`MetaData`
object. | [
"Returns",
"all",
"database",
"table",
"names",
"found",
"in",
"an",
"SQLAlchemy",
":",
"class",
":",
"MetaData",
"object",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L679-L684 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | gen_orm_classes_from_base | def gen_orm_classes_from_base(base: Type) -> Generator[Type, None, None]:
"""
From an SQLAlchemy ORM base class, yield all the subclasses (except those
that are abstract).
If you begin with the proper :class`Base` class, then this should give all
ORM classes in use.
"""
for cls in gen_all_s... | python | def gen_orm_classes_from_base(base: Type) -> Generator[Type, None, None]:
"""
From an SQLAlchemy ORM base class, yield all the subclasses (except those
that are abstract).
If you begin with the proper :class`Base` class, then this should give all
ORM classes in use.
"""
for cls in gen_all_s... | [
"def",
"gen_orm_classes_from_base",
"(",
"base",
":",
"Type",
")",
"->",
"Generator",
"[",
"Type",
",",
"None",
",",
"None",
"]",
":",
"for",
"cls",
"in",
"gen_all_subclasses",
"(",
"base",
")",
":",
"if",
"_get_immediate_cls_attr",
"(",
"cls",
",",
"'__ab... | From an SQLAlchemy ORM base class, yield all the subclasses (except those
that are abstract).
If you begin with the proper :class`Base` class, then this should give all
ORM classes in use. | [
"From",
"an",
"SQLAlchemy",
"ORM",
"base",
"class",
"yield",
"all",
"the",
"subclasses",
"(",
"except",
"those",
"that",
"are",
"abstract",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L697-L710 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | get_orm_classes_by_table_name_from_base | def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]:
"""
Given an SQLAlchemy ORM base class, returns a dictionary whose keys are
table names and whose values are ORM classes.
If you begin with the proper :class`Base` class, then this should give all
tables and ORM classes in ... | python | def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]:
"""
Given an SQLAlchemy ORM base class, returns a dictionary whose keys are
table names and whose values are ORM classes.
If you begin with the proper :class`Base` class, then this should give all
tables and ORM classes in ... | [
"def",
"get_orm_classes_by_table_name_from_base",
"(",
"base",
":",
"Type",
")",
"->",
"Dict",
"[",
"str",
",",
"Type",
"]",
":",
"# noinspection PyUnresolvedReferences",
"return",
"{",
"cls",
".",
"__tablename__",
":",
"cls",
"for",
"cls",
"in",
"gen_orm_classes_... | Given an SQLAlchemy ORM base class, returns a dictionary whose keys are
table names and whose values are ORM classes.
If you begin with the proper :class`Base` class, then this should give all
tables and ORM classes in use. | [
"Given",
"an",
"SQLAlchemy",
"ORM",
"base",
"class",
"returns",
"a",
"dictionary",
"whose",
"keys",
"are",
"table",
"names",
"and",
"whose",
"values",
"are",
"ORM",
"classes",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L713-L722 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | SqlAlchemyAttrDictMixin.get_attrdict | def get_attrdict(self) -> OrderedNamespace:
"""
Returns what looks like a plain object with the values of the
SQLAlchemy ORM object.
"""
# noinspection PyUnresolvedReferences
columns = self.__table__.columns.keys()
values = (getattr(self, x) for x in columns)
... | python | def get_attrdict(self) -> OrderedNamespace:
"""
Returns what looks like a plain object with the values of the
SQLAlchemy ORM object.
"""
# noinspection PyUnresolvedReferences
columns = self.__table__.columns.keys()
values = (getattr(self, x) for x in columns)
... | [
"def",
"get_attrdict",
"(",
"self",
")",
"->",
"OrderedNamespace",
":",
"# noinspection PyUnresolvedReferences",
"columns",
"=",
"self",
".",
"__table__",
".",
"columns",
".",
"keys",
"(",
")",
"values",
"=",
"(",
"getattr",
"(",
"self",
",",
"x",
")",
"for"... | Returns what looks like a plain object with the values of the
SQLAlchemy ORM object. | [
"Returns",
"what",
"looks",
"like",
"a",
"plain",
"object",
"with",
"the",
"values",
"of",
"the",
"SQLAlchemy",
"ORM",
"object",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L108-L117 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_inspect.py | SqlAlchemyAttrDictMixin.from_attrdict | def from_attrdict(cls, attrdict: OrderedNamespace) -> object:
"""
Builds a new instance of the ORM object from values in an attrdict.
"""
dictionary = attrdict.__dict__
# noinspection PyArgumentList
return cls(**dictionary) | python | def from_attrdict(cls, attrdict: OrderedNamespace) -> object:
"""
Builds a new instance of the ORM object from values in an attrdict.
"""
dictionary = attrdict.__dict__
# noinspection PyArgumentList
return cls(**dictionary) | [
"def",
"from_attrdict",
"(",
"cls",
",",
"attrdict",
":",
"OrderedNamespace",
")",
"->",
"object",
":",
"dictionary",
"=",
"attrdict",
".",
"__dict__",
"# noinspection PyArgumentList",
"return",
"cls",
"(",
"*",
"*",
"dictionary",
")"
] | Builds a new instance of the ORM object from values in an attrdict. | [
"Builds",
"a",
"new",
"instance",
"of",
"the",
"ORM",
"object",
"from",
"values",
"in",
"an",
"attrdict",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_inspect.py#L127-L133 |
RudolfCardinal/pythonlib | cardinal_pythonlib/classes.py | derived_class_implements_method | def derived_class_implements_method(derived: Type[T1],
base: Type[T2],
method_name: str) -> bool:
"""
Does a derived class implement a method (and not just inherit a base
class's version)?
Args:
derived: a derived class
... | python | def derived_class_implements_method(derived: Type[T1],
base: Type[T2],
method_name: str) -> bool:
"""
Does a derived class implement a method (and not just inherit a base
class's version)?
Args:
derived: a derived class
... | [
"def",
"derived_class_implements_method",
"(",
"derived",
":",
"Type",
"[",
"T1",
"]",
",",
"base",
":",
"Type",
"[",
"T2",
"]",
",",
"method_name",
":",
"str",
")",
"->",
"bool",
":",
"derived_method",
"=",
"getattr",
"(",
"derived",
",",
"method_name",
... | Does a derived class implement a method (and not just inherit a base
class's version)?
Args:
derived: a derived class
base: a base class
method_name: the name of a method
Returns:
whether the derived class method is (a) present, and (b) different to
the base class's... | [
"Does",
"a",
"derived",
"class",
"implement",
"a",
"method",
"(",
"and",
"not",
"just",
"inherit",
"a",
"base",
"class",
"s",
"version",
")",
"?"
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/classes.py#L73-L102 |
RudolfCardinal/pythonlib | cardinal_pythonlib/classes.py | gen_all_subclasses | def gen_all_subclasses(cls: Type) -> Generator[Type, None, None]:
"""
Generates all subclasses of a class.
Args:
cls: a class
Yields:
all subclasses
"""
for s1 in cls.__subclasses__():
yield s1
for s2 in gen_all_subclasses(s1):
yield s2 | python | def gen_all_subclasses(cls: Type) -> Generator[Type, None, None]:
"""
Generates all subclasses of a class.
Args:
cls: a class
Yields:
all subclasses
"""
for s1 in cls.__subclasses__():
yield s1
for s2 in gen_all_subclasses(s1):
yield s2 | [
"def",
"gen_all_subclasses",
"(",
"cls",
":",
"Type",
")",
"->",
"Generator",
"[",
"Type",
",",
"None",
",",
"None",
"]",
":",
"for",
"s1",
"in",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"yield",
"s1",
"for",
"s2",
"in",
"gen_all_subclasses",
"(",
... | Generates all subclasses of a class.
Args:
cls: a class
Yields:
all subclasses | [
"Generates",
"all",
"subclasses",
"of",
"a",
"class",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/classes.py#L110-L125 |
davenquinn/Attitude | attitude/geom/util.py | augment_tensor | def augment_tensor(matrix, ndim=None):
"""
Increase the dimensionality of a tensor,
splicing it into an identity matrix of a higher
dimension. Useful for generalizing
transformation matrices.
"""
s = matrix.shape
if ndim is None:
ndim = s[0]+1
arr = N.identity(ndim)
arr[:... | python | def augment_tensor(matrix, ndim=None):
"""
Increase the dimensionality of a tensor,
splicing it into an identity matrix of a higher
dimension. Useful for generalizing
transformation matrices.
"""
s = matrix.shape
if ndim is None:
ndim = s[0]+1
arr = N.identity(ndim)
arr[:... | [
"def",
"augment_tensor",
"(",
"matrix",
",",
"ndim",
"=",
"None",
")",
":",
"s",
"=",
"matrix",
".",
"shape",
"if",
"ndim",
"is",
"None",
":",
"ndim",
"=",
"s",
"[",
"0",
"]",
"+",
"1",
"arr",
"=",
"N",
".",
"identity",
"(",
"ndim",
")",
"arr",... | Increase the dimensionality of a tensor,
splicing it into an identity matrix of a higher
dimension. Useful for generalizing
transformation matrices. | [
"Increase",
"the",
"dimensionality",
"of",
"a",
"tensor",
"splicing",
"it",
"into",
"an",
"identity",
"matrix",
"of",
"a",
"higher",
"dimension",
".",
"Useful",
"for",
"generalizing",
"transformation",
"matrices",
"."
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/util.py#L9-L21 |
davenquinn/Attitude | attitude/geom/util.py | angle | def angle(v1,v2, cos=False):
"""
Find the angle between two vectors.
:param cos: If True, the cosine of the
angle will be returned. False by default.
"""
n = (norm(v1)*norm(v2))
_ = dot(v1,v2)/n
return _ if cos else N.arccos(_) | python | def angle(v1,v2, cos=False):
"""
Find the angle between two vectors.
:param cos: If True, the cosine of the
angle will be returned. False by default.
"""
n = (norm(v1)*norm(v2))
_ = dot(v1,v2)/n
return _ if cos else N.arccos(_) | [
"def",
"angle",
"(",
"v1",
",",
"v2",
",",
"cos",
"=",
"False",
")",
":",
"n",
"=",
"(",
"norm",
"(",
"v1",
")",
"*",
"norm",
"(",
"v2",
")",
")",
"_",
"=",
"dot",
"(",
"v1",
",",
"v2",
")",
"/",
"n",
"return",
"_",
"if",
"cos",
"else",
... | Find the angle between two vectors.
:param cos: If True, the cosine of the
angle will be returned. False by default. | [
"Find",
"the",
"angle",
"between",
"two",
"vectors",
"."
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/util.py#L55-L64 |
davenquinn/Attitude | attitude/geom/util.py | perpendicular_vector | def perpendicular_vector(n):
"""
Get a random vector perpendicular
to the given vector
"""
dim = len(n)
if dim == 2:
return n[::-1]
# More complex in 3d
for ix in range(dim):
_ = N.zeros(dim)
# Try to keep axes near the global projection
# by finding vecto... | python | def perpendicular_vector(n):
"""
Get a random vector perpendicular
to the given vector
"""
dim = len(n)
if dim == 2:
return n[::-1]
# More complex in 3d
for ix in range(dim):
_ = N.zeros(dim)
# Try to keep axes near the global projection
# by finding vecto... | [
"def",
"perpendicular_vector",
"(",
"n",
")",
":",
"dim",
"=",
"len",
"(",
"n",
")",
"if",
"dim",
"==",
"2",
":",
"return",
"n",
"[",
":",
":",
"-",
"1",
"]",
"# More complex in 3d",
"for",
"ix",
"in",
"range",
"(",
"dim",
")",
":",
"_",
"=",
"... | Get a random vector perpendicular
to the given vector | [
"Get",
"a",
"random",
"vector",
"perpendicular",
"to",
"the",
"given",
"vector"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/geom/util.py#L91-L110 |
RudolfCardinal/pythonlib | cardinal_pythonlib/signalfunc.py | trap_ctrl_c_ctrl_break | def trap_ctrl_c_ctrl_break() -> None:
"""
Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing
anything.
See
- https://docs.python.org/3/library/signal.html#signal.SIG_IGN
- https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx
- https://msdn.microsoft.com/en-us/libr... | python | def trap_ctrl_c_ctrl_break() -> None:
"""
Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing
anything.
See
- https://docs.python.org/3/library/signal.html#signal.SIG_IGN
- https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx
- https://msdn.microsoft.com/en-us/libr... | [
"def",
"trap_ctrl_c_ctrl_break",
"(",
")",
"->",
"None",
":",
"# noqa",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"ctrl_c_trapper",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"sigterm_trapper",
")",
"if",
"platform",
... | Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing
anything.
See
- https://docs.python.org/3/library/signal.html#signal.SIG_IGN
- https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx
- https://msdn.microsoft.com/en-us/library/windows/desktop/ms682541(v=vs.85).aspx
Un... | [
"Prevent",
"CTRL",
"-",
"C",
"CTRL",
"-",
"BREAK",
"and",
"similar",
"signals",
"from",
"doing",
"anything",
".",
"See",
"-",
"https",
":",
"//",
"docs",
".",
"python",
".",
"org",
"/",
"3",
"/",
"library",
"/",
"signal",
".",
"html#signal",
".",
"SI... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/signalfunc.py#L66-L113 |
RudolfCardinal/pythonlib | cardinal_pythonlib/openxml/find_bad_openxml.py | is_openxml_good | def is_openxml_good(filename: str) -> bool:
"""
Determines whether an OpenXML file appears to be good (not corrupted).
"""
try:
log.debug("Trying: {}", filename)
with ZipFile(filename, 'r') as zip_ref:
namelist = zip_ref.namelist() # type: List[str]
# log.critica... | python | def is_openxml_good(filename: str) -> bool:
"""
Determines whether an OpenXML file appears to be good (not corrupted).
"""
try:
log.debug("Trying: {}", filename)
with ZipFile(filename, 'r') as zip_ref:
namelist = zip_ref.namelist() # type: List[str]
# log.critica... | [
"def",
"is_openxml_good",
"(",
"filename",
":",
"str",
")",
"->",
"bool",
":",
"try",
":",
"log",
".",
"debug",
"(",
"\"Trying: {}\"",
",",
"filename",
")",
"with",
"ZipFile",
"(",
"filename",
",",
"'r'",
")",
"as",
"zip_ref",
":",
"namelist",
"=",
"zi... | Determines whether an OpenXML file appears to be good (not corrupted). | [
"Determines",
"whether",
"an",
"OpenXML",
"file",
"appears",
"to",
"be",
"good",
"(",
"not",
"corrupted",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/find_bad_openxml.py#L80-L139 |
RudolfCardinal/pythonlib | cardinal_pythonlib/openxml/find_bad_openxml.py | process_openxml_file | def process_openxml_file(filename: str,
print_good: bool,
delete_if_bad: bool) -> None:
"""
Prints the filename of, or deletes, an OpenXML file depending on whether
it is corrupt or not.
Args:
filename: filename to check
print_good: if `... | python | def process_openxml_file(filename: str,
print_good: bool,
delete_if_bad: bool) -> None:
"""
Prints the filename of, or deletes, an OpenXML file depending on whether
it is corrupt or not.
Args:
filename: filename to check
print_good: if `... | [
"def",
"process_openxml_file",
"(",
"filename",
":",
"str",
",",
"print_good",
":",
"bool",
",",
"delete_if_bad",
":",
"bool",
")",
"->",
"None",
":",
"print_bad",
"=",
"not",
"print_good",
"try",
":",
"file_good",
"=",
"is_openxml_good",
"(",
"filename",
")... | Prints the filename of, or deletes, an OpenXML file depending on whether
it is corrupt or not.
Args:
filename: filename to check
print_good: if ``True``, then prints the filename if the file
appears good.
delete_if_bad: if ``True``, then deletes the file if the file
... | [
"Prints",
"the",
"filename",
"of",
"or",
"deletes",
"an",
"OpenXML",
"file",
"depending",
"on",
"whether",
"it",
"is",
"corrupt",
"or",
"not",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/find_bad_openxml.py#L142-L170 |
RudolfCardinal/pythonlib | cardinal_pythonlib/openxml/find_bad_openxml.py | main | def main() -> None:
"""
Command-line handler for the ``find_bad_openxml`` tool.
Use the ``--help`` option for help.
"""
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
description="""
Tool to scan rescued Microsoft Office OpenXML files (produced by the
find_reco... | python | def main() -> None:
"""
Command-line handler for the ``find_bad_openxml`` tool.
Use the ``--help`` option for help.
"""
parser = ArgumentParser(
formatter_class=RawDescriptionHelpFormatter,
description="""
Tool to scan rescued Microsoft Office OpenXML files (produced by the
find_reco... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"parser",
"=",
"ArgumentParser",
"(",
"formatter_class",
"=",
"RawDescriptionHelpFormatter",
",",
"description",
"=",
"\"\"\"\nTool to scan rescued Microsoft Office OpenXML files (produced by the\nfind_recovered_openxml.py tool in this ki... | Command-line handler for the ``find_bad_openxml`` tool.
Use the ``--help`` option for help. | [
"Command",
"-",
"line",
"handler",
"for",
"the",
"find_bad_openxml",
"tool",
".",
"Use",
"the",
"--",
"help",
"option",
"for",
"help",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/find_bad_openxml.py#L173-L295 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/mail.py | SmtpEmailBackendTls1.open | def open(self) -> bool:
"""
Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False).
"""
if self.connection:
# Nothing to do if the connection is already open.
return False
connection_... | python | def open(self) -> bool:
"""
Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False).
"""
if self.connection:
# Nothing to do if the connection is already open.
return False
connection_... | [
"def",
"open",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"connection",
":",
"# Nothing to do if the connection is already open.",
"return",
"False",
"connection_params",
"=",
"{",
"'local_hostname'",
":",
"DNS_NAME",
".",
"get_fqdn",
"(",
")",
"}",
... | Ensures we have a connection to the email server. Returns whether or
not a new connection was required (True or False). | [
"Ensures",
"we",
"have",
"a",
"connection",
"to",
"the",
"email",
"server",
".",
"Returns",
"whether",
"or",
"not",
"a",
"new",
"connection",
"was",
"required",
"(",
"True",
"or",
"False",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/mail.py#L93-L126 |
davenquinn/Attitude | attitude/__dustbin/statistical_distances.py | bhattacharyya_distance | def bhattacharyya_distance(pca1,pca2):
"""
A measure of the distance between two probability distributions
"""
u1 = pca1.coefficients
s1 = pca1.covariance_matrix
u2 = pca2.coefficients
s2 = pca2.covariance_matrix
sigma = (s1+s2)/2
assert all(u1 > 0)
assert all(u2 > 0)
asser... | python | def bhattacharyya_distance(pca1,pca2):
"""
A measure of the distance between two probability distributions
"""
u1 = pca1.coefficients
s1 = pca1.covariance_matrix
u2 = pca2.coefficients
s2 = pca2.covariance_matrix
sigma = (s1+s2)/2
assert all(u1 > 0)
assert all(u2 > 0)
asser... | [
"def",
"bhattacharyya_distance",
"(",
"pca1",
",",
"pca2",
")",
":",
"u1",
"=",
"pca1",
".",
"coefficients",
"s1",
"=",
"pca1",
".",
"covariance_matrix",
"u2",
"=",
"pca2",
".",
"coefficients",
"s2",
"=",
"pca2",
".",
"covariance_matrix",
"sigma",
"=",
"("... | A measure of the distance between two probability distributions | [
"A",
"measure",
"of",
"the",
"distance",
"between",
"two",
"probability",
"distributions"
] | train | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/__dustbin/statistical_distances.py#L13-L31 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | produce_csv_output | def produce_csv_output(filehandle: TextIO,
fields: Sequence[str],
values: Iterable[str]) -> None:
"""
Produce CSV output, without using ``csv.writer``, so the log can be used
for lots of things.
- ... eh? What was I talking about?
- POOR; DEPRECATED.
... | python | def produce_csv_output(filehandle: TextIO,
fields: Sequence[str],
values: Iterable[str]) -> None:
"""
Produce CSV output, without using ``csv.writer``, so the log can be used
for lots of things.
- ... eh? What was I talking about?
- POOR; DEPRECATED.
... | [
"def",
"produce_csv_output",
"(",
"filehandle",
":",
"TextIO",
",",
"fields",
":",
"Sequence",
"[",
"str",
"]",
",",
"values",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"output_csv",
"(",
"filehandle",
",",
"fields",
")",
"for",
"row",
... | Produce CSV output, without using ``csv.writer``, so the log can be used
for lots of things.
- ... eh? What was I talking about?
- POOR; DEPRECATED.
Args:
filehandle: file to write to
fields: field names
values: values | [
"Produce",
"CSV",
"output",
"without",
"using",
"csv",
".",
"writer",
"so",
"the",
"log",
"can",
"be",
"used",
"for",
"lots",
"of",
"things",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L39-L56 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | output_csv | def output_csv(filehandle: TextIO, values: Iterable[str]) -> None:
"""
Write a line of CSV. POOR; does not escape things properly. DEPRECATED.
Args:
filehandle: file to write to
values: values
"""
line = ",".join(values)
filehandle.write(line + "\n") | python | def output_csv(filehandle: TextIO, values: Iterable[str]) -> None:
"""
Write a line of CSV. POOR; does not escape things properly. DEPRECATED.
Args:
filehandle: file to write to
values: values
"""
line = ",".join(values)
filehandle.write(line + "\n") | [
"def",
"output_csv",
"(",
"filehandle",
":",
"TextIO",
",",
"values",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"line",
"=",
"\",\"",
".",
"join",
"(",
"values",
")",
"filehandle",
".",
"write",
"(",
"line",
"+",
"\"\\n\"",
")"
] | Write a line of CSV. POOR; does not escape things properly. DEPRECATED.
Args:
filehandle: file to write to
values: values | [
"Write",
"a",
"line",
"of",
"CSV",
".",
"POOR",
";",
"does",
"not",
"escape",
"things",
"properly",
".",
"DEPRECATED",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L59-L68 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_what_follows_raw | def get_what_follows_raw(s: str,
prefix: str,
onlyatstart: bool = True,
stripwhitespace: bool = True) -> Tuple[bool, str]:
"""
Find the part of ``s`` that is after ``prefix``.
Args:
s: string to analyse
prefix: prefi... | python | def get_what_follows_raw(s: str,
prefix: str,
onlyatstart: bool = True,
stripwhitespace: bool = True) -> Tuple[bool, str]:
"""
Find the part of ``s`` that is after ``prefix``.
Args:
s: string to analyse
prefix: prefi... | [
"def",
"get_what_follows_raw",
"(",
"s",
":",
"str",
",",
"prefix",
":",
"str",
",",
"onlyatstart",
":",
"bool",
"=",
"True",
",",
"stripwhitespace",
":",
"bool",
"=",
"True",
")",
"->",
"Tuple",
"[",
"bool",
",",
"str",
"]",
":",
"prefixstart",
"=",
... | Find the part of ``s`` that is after ``prefix``.
Args:
s: string to analyse
prefix: prefix to find
onlyatstart: only accept the prefix if it is right at the start of
``s``
stripwhitespace: remove whitespace from the result
Returns:
tuple: ``(found, result)`` | [
"Find",
"the",
"part",
"of",
"s",
"that",
"is",
"after",
"prefix",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L71-L98 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_what_follows | def get_what_follows(strings: Sequence[str],
prefix: str,
onlyatstart: bool = True,
stripwhitespace: bool = True,
precedingline: str = "") -> str:
"""
Find a string in ``strings`` that begins with ``prefix``; return the part
... | python | def get_what_follows(strings: Sequence[str],
prefix: str,
onlyatstart: bool = True,
stripwhitespace: bool = True,
precedingline: str = "") -> str:
"""
Find a string in ``strings`` that begins with ``prefix``; return the part
... | [
"def",
"get_what_follows",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix",
":",
"str",
",",
"onlyatstart",
":",
"bool",
"=",
"True",
",",
"stripwhitespace",
":",
"bool",
"=",
"True",
",",
"precedingline",
":",
"str",
"=",
"\"\"",
")",
... | Find a string in ``strings`` that begins with ``prefix``; return the part
that's after ``prefix``. Optionally, require that the preceding string
(line) is ``precedingline``.
Args:
strings: strings to analyse
prefix: prefix to find
onlyatstart: only accept the prefix if it is right a... | [
"Find",
"a",
"string",
"in",
"strings",
"that",
"begins",
"with",
"prefix",
";",
"return",
"the",
"part",
"that",
"s",
"after",
"prefix",
".",
"Optionally",
"require",
"that",
"the",
"preceding",
"string",
"(",
"line",
")",
"is",
"precedingline",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L101-L140 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_string | def get_string(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[str]:
"""
Find a string as per :func:`get_what_follows`.
Args:
strings: see :func:`get_what_follows`
prefix: see :func:`get... | python | def get_string(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[str]:
"""
Find a string as per :func:`get_what_follows`.
Args:
strings: see :func:`get_what_follows`
prefix: see :func:`get... | [
"def",
"get_string",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
",",
"precedingline",
":",
"str",
"=",
"\"\"",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"s",
"... | Find a string as per :func:`get_what_follows`.
Args:
strings: see :func:`get_what_follows`
prefix: see :func:`get_what_follows`
ignoreleadingcolon: if ``True``, restrict the result to what comes
after its first colon (and whitespace-strip that)
precedingline: see :func:`... | [
"Find",
"a",
"string",
"as",
"per",
":",
"func",
":",
"get_what_follows",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L143-L168 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_string_relative | def get_string_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False,
stripwhitespace: bool = True) -> Optional[str]:
"""
Finds a line (stri... | python | def get_string_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False,
stripwhitespace: bool = True) -> Optional[str]:
"""
Finds a line (stri... | [
"def",
"get_string_relative",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix1",
":",
"str",
",",
"delta",
":",
"int",
",",
"prefix2",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
",",
"stripwhitespace",
":",
"bool",
"... | Finds a line (string) in ``strings`` beginning with ``prefix1``. Moves
``delta`` lines (strings) further. Returns the end of the line that
begins with ``prefix2``, if found.
Args:
strings: as above
prefix1: as above
delta: as above
prefix2: as above
ignoreleadingcolo... | [
"Finds",
"a",
"line",
"(",
"string",
")",
"in",
"strings",
"beginning",
"with",
"prefix1",
".",
"Moves",
"delta",
"lines",
"(",
"strings",
")",
"further",
".",
"Returns",
"the",
"end",
"of",
"the",
"line",
"that",
"begins",
"with",
"prefix2",
"if",
"foun... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L171-L212 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_int | def get_int(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[int]:
"""
Fetches an integer parameter via :func:`get_string`.
"""
return get_int_raw(get_string(strings, prefix,
... | python | def get_int(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[int]:
"""
Fetches an integer parameter via :func:`get_string`.
"""
return get_int_raw(get_string(strings, prefix,
... | [
"def",
"get_int",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
",",
"precedingline",
":",
"str",
"=",
"\"\"",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"return",
... | Fetches an integer parameter via :func:`get_string`. | [
"Fetches",
"an",
"integer",
"parameter",
"via",
":",
"func",
":",
"get_string",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L215-L224 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_float | def get_float(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[float]:
"""
Fetches a float parameter via :func:`get_string`.
"""
return get_float_raw(get_string(strings, prefix,
... | python | def get_float(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[float]:
"""
Fetches a float parameter via :func:`get_string`.
"""
return get_float_raw(get_string(strings, prefix,
... | [
"def",
"get_float",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
",",
"precedingline",
":",
"str",
"=",
"\"\"",
")",
"->",
"Optional",
"[",
"float",
"]",
":",
"return... | Fetches a float parameter via :func:`get_string`. | [
"Fetches",
"a",
"float",
"parameter",
"via",
":",
"func",
":",
"get_string",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L227-L236 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_bool_raw | def get_bool_raw(s: str) -> Optional[bool]:
"""
Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``.
"""
if s == "Y" or s == "y":
return True
elif s == "N" or s == "n":
return False
return None | python | def get_bool_raw(s: str) -> Optional[bool]:
"""
Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``.
"""
if s == "Y" or s == "y":
return True
elif s == "N" or s == "n":
return False
return None | [
"def",
"get_bool_raw",
"(",
"s",
":",
"str",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"if",
"s",
"==",
"\"Y\"",
"or",
"s",
"==",
"\"y\"",
":",
"return",
"True",
"elif",
"s",
"==",
"\"N\"",
"or",
"s",
"==",
"\"n\"",
":",
"return",
"False",
"r... | Maps ``"Y"``, ``"y"`` to ``True`` and ``"N"``, ``"n"`` to ``False``. | [
"Maps",
"Y",
"y",
"to",
"True",
"and",
"N",
"n",
"to",
"False",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L258-L266 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_bool | def get_bool(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[bool]:
"""
Fetches a boolean parameter via :func:`get_string`.
"""
return get_bool_raw(get_string(strings, prefix,
... | python | def get_bool(strings: Sequence[str],
prefix: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[bool]:
"""
Fetches a boolean parameter via :func:`get_string`.
"""
return get_bool_raw(get_string(strings, prefix,
... | [
"def",
"get_bool",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
",",
"precedingline",
":",
"str",
"=",
"\"\"",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"return",... | Fetches a boolean parameter via :func:`get_string`. | [
"Fetches",
"a",
"boolean",
"parameter",
"via",
":",
"func",
":",
"get_string",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L288-L297 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_bool_relative | def get_bool_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[bool]:
"""
Fetches a boolean parameter via :func:`get_string_relative`.
"""
return g... | python | def get_bool_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[bool]:
"""
Fetches a boolean parameter via :func:`get_string_relative`.
"""
return g... | [
"def",
"get_bool_relative",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix1",
":",
"str",
",",
"delta",
":",
"int",
",",
"prefix2",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
")",
"->",
"Optional",
"[",
"bool",
"]... | Fetches a boolean parameter via :func:`get_string_relative`. | [
"Fetches",
"a",
"boolean",
"parameter",
"via",
":",
"func",
":",
"get_string_relative",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L300-L310 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_float_relative | def get_float_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[float]:
"""
Fetches a float parameter via :func:`get_string_relative`.
"""
retu... | python | def get_float_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[float]:
"""
Fetches a float parameter via :func:`get_string_relative`.
"""
retu... | [
"def",
"get_float_relative",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix1",
":",
"str",
",",
"delta",
":",
"int",
",",
"prefix2",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
")",
"->",
"Optional",
"[",
"float",
... | Fetches a float parameter via :func:`get_string_relative`. | [
"Fetches",
"a",
"float",
"parameter",
"via",
":",
"func",
":",
"get_string_relative",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L313-L323 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_int_relative | def get_int_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[int]:
"""
Fetches an int parameter via :func:`get_string_relative`.
"""
return get_int_ra... | python | def get_int_relative(strings: Sequence[str],
prefix1: str,
delta: int,
prefix2: str,
ignoreleadingcolon: bool = False) -> Optional[int]:
"""
Fetches an int parameter via :func:`get_string_relative`.
"""
return get_int_ra... | [
"def",
"get_int_relative",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix1",
":",
"str",
",",
"delta",
":",
"int",
",",
"prefix2",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
")",
"->",
"Optional",
"[",
"int",
"]",... | Fetches an int parameter via :func:`get_string_relative`. | [
"Fetches",
"an",
"int",
"parameter",
"via",
":",
"func",
":",
"get_string_relative",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L326-L336 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_datetime | def get_datetime(strings: Sequence[str],
prefix: str,
datetime_format_string: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[datetime.datetime]:
"""
Fetches a ``datetime.datetime`` parameter via :func:`get_string`.
... | python | def get_datetime(strings: Sequence[str],
prefix: str,
datetime_format_string: str,
ignoreleadingcolon: bool = False,
precedingline: str = "") -> Optional[datetime.datetime]:
"""
Fetches a ``datetime.datetime`` parameter via :func:`get_string`.
... | [
"def",
"get_datetime",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"prefix",
":",
"str",
",",
"datetime_format_string",
":",
"str",
",",
"ignoreleadingcolon",
":",
"bool",
"=",
"False",
",",
"precedingline",
":",
"str",
"=",
"\"\"",
")",
"->",
... | Fetches a ``datetime.datetime`` parameter via :func:`get_string`. | [
"Fetches",
"a",
"datetime",
".",
"datetime",
"parameter",
"via",
":",
"func",
":",
"get_string",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L339-L355 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | find_line_beginning | def find_line_beginning(strings: Sequence[str],
linestart: Optional[str]) -> int:
"""
Finds the index of the line in ``strings`` that begins with ``linestart``,
or ``-1`` if none is found.
If ``linestart is None``, match an empty line.
"""
if linestart is None: # match ... | python | def find_line_beginning(strings: Sequence[str],
linestart: Optional[str]) -> int:
"""
Finds the index of the line in ``strings`` that begins with ``linestart``,
or ``-1`` if none is found.
If ``linestart is None``, match an empty line.
"""
if linestart is None: # match ... | [
"def",
"find_line_beginning",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"linestart",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"int",
":",
"if",
"linestart",
"is",
"None",
":",
"# match an empty line",
"for",
"i",
"in",
"range",
"(",
"len... | Finds the index of the line in ``strings`` that begins with ``linestart``,
or ``-1`` if none is found.
If ``linestart is None``, match an empty line. | [
"Finds",
"the",
"index",
"of",
"the",
"line",
"in",
"strings",
"that",
"begins",
"with",
"linestart",
"or",
"-",
"1",
"if",
"none",
"is",
"found",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L358-L374 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | find_line_containing | def find_line_containing(strings: Sequence[str], contents: str) -> int:
"""
Finds the index of the line in ``strings`` that contains ``contents``,
or ``-1`` if none is found.
"""
for i in range(len(strings)):
if strings[i].find(contents) != -1:
return i
return -1 | python | def find_line_containing(strings: Sequence[str], contents: str) -> int:
"""
Finds the index of the line in ``strings`` that contains ``contents``,
or ``-1`` if none is found.
"""
for i in range(len(strings)):
if strings[i].find(contents) != -1:
return i
return -1 | [
"def",
"find_line_containing",
"(",
"strings",
":",
"Sequence",
"[",
"str",
"]",
",",
"contents",
":",
"str",
")",
"->",
"int",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"strings",
")",
")",
":",
"if",
"strings",
"[",
"i",
"]",
".",
"find",
... | Finds the index of the line in ``strings`` that contains ``contents``,
or ``-1`` if none is found. | [
"Finds",
"the",
"index",
"of",
"the",
"line",
"in",
"strings",
"that",
"contains",
"contents",
"or",
"-",
"1",
"if",
"none",
"is",
"found",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L377-L385 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | get_lines_from_to | def get_lines_from_to(strings: List[str],
firstlinestart: str,
list_of_lastline_starts: Iterable[Optional[str]]) \
-> List[str]:
"""
Takes a list of ``strings``. Returns a list of strings FROM
``firstlinestart`` (inclusive) TO the first of ``list_of_lastli... | python | def get_lines_from_to(strings: List[str],
firstlinestart: str,
list_of_lastline_starts: Iterable[Optional[str]]) \
-> List[str]:
"""
Takes a list of ``strings``. Returns a list of strings FROM
``firstlinestart`` (inclusive) TO the first of ``list_of_lastli... | [
"def",
"get_lines_from_to",
"(",
"strings",
":",
"List",
"[",
"str",
"]",
",",
"firstlinestart",
":",
"str",
",",
"list_of_lastline_starts",
":",
"Iterable",
"[",
"Optional",
"[",
"str",
"]",
"]",
")",
"->",
"List",
"[",
"str",
"]",
":",
"start_index",
"... | Takes a list of ``strings``. Returns a list of strings FROM
``firstlinestart`` (inclusive) TO the first of ``list_of_lastline_starts``
(exclusive).
To search to the end of the list, use ``list_of_lastline_starts = []``.
To search to a blank line, use ``list_of_lastline_starts = [None]`` | [
"Takes",
"a",
"list",
"of",
"strings",
".",
"Returns",
"a",
"list",
"of",
"strings",
"FROM",
"firstlinestart",
"(",
"inclusive",
")",
"TO",
"the",
"first",
"of",
"list_of_lastline_starts",
"(",
"exclusive",
")",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L388-L415 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | csv_to_list_of_fields | def csv_to_list_of_fields(lines: List[str],
csvheader: str,
quotechar: str = '"') -> List[str]:
"""
Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Used for... | python | def csv_to_list_of_fields(lines: List[str],
csvheader: str,
quotechar: str = '"') -> List[str]:
"""
Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Used for... | [
"def",
"csv_to_list_of_fields",
"(",
"lines",
":",
"List",
"[",
"str",
"]",
",",
"csvheader",
":",
"str",
",",
"quotechar",
":",
"str",
"=",
"'\"'",
")",
"->",
"List",
"[",
"str",
"]",
":",
"# noqa",
"data",
"=",
"[",
"]",
"# type: List[str]",
"# an em... | Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Used for processing e.g. MonkeyCantab rescue text output.
Args:
lines: CSV lines
csvheader: CSV header line
quotechar: ``quotechar`` parame... | [
"Extracts",
"data",
"from",
"a",
"list",
"of",
"CSV",
"lines",
"(",
"starting",
"with",
"a",
"defined",
"header",
"line",
")",
"embedded",
"in",
"a",
"longer",
"text",
"block",
"but",
"ending",
"with",
"a",
"blank",
"line",
".",
"Used",
"for",
"processin... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L425-L470 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | csv_to_list_of_dicts | def csv_to_list_of_dicts(lines: List[str],
csvheader: str,
quotechar: str = '"') -> List[Dict[str, str]]:
"""
Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Args... | python | def csv_to_list_of_dicts(lines: List[str],
csvheader: str,
quotechar: str = '"') -> List[Dict[str, str]]:
"""
Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Args... | [
"def",
"csv_to_list_of_dicts",
"(",
"lines",
":",
"List",
"[",
"str",
"]",
",",
"csvheader",
":",
"str",
",",
"quotechar",
":",
"str",
"=",
"'\"'",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"data",
"=",
"[",
"]",
"# t... | Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Args:
lines: CSV lines
csvheader: CSV header line
quotechar: ``quotechar`` parameter passed to :func:`csv.reader`
Returns:
list of dict... | [
"Extracts",
"data",
"from",
"a",
"list",
"of",
"CSV",
"lines",
"(",
"starting",
"with",
"a",
"defined",
"header",
"line",
")",
"embedded",
"in",
"a",
"longer",
"text",
"block",
"but",
"ending",
"with",
"a",
"blank",
"line",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L473-L500 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | dictlist_convert_to_string | def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a
blank string, convert it to ``None``.
"""
for d in dict_list:
... | python | def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a
blank string, convert it to ``None``.
"""
for d in dict_list:
... | [
"def",
"dictlist_convert_to_string",
"(",
"dict_list",
":",
"Iterable",
"[",
"Dict",
"]",
",",
"key",
":",
"str",
")",
"->",
"None",
":",
"for",
"d",
"in",
"dict_list",
":",
"d",
"[",
"key",
"]",
"=",
"str",
"(",
"d",
"[",
"key",
"]",
")",
"if",
... | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a
blank string, convert it to ``None``. | [
"Process",
"an",
"iterable",
"of",
"dictionaries",
".",
"For",
"each",
"dictionary",
"d",
"convert",
"(",
"in",
"place",
")",
"d",
"[",
"key",
"]",
"to",
"a",
"string",
"form",
"str",
"(",
"d",
"[",
"key",
"]",
")",
".",
"If",
"the",
"result",
"is"... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L503-L512 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | dictlist_convert_to_datetime | def dictlist_convert_to_datetime(dict_list: Iterable[Dict],
key: str,
datetime_format_string: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a ``datetime.datetime`` form, usi... | python | def dictlist_convert_to_datetime(dict_list: Iterable[Dict],
key: str,
datetime_format_string: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a ``datetime.datetime`` form, usi... | [
"def",
"dictlist_convert_to_datetime",
"(",
"dict_list",
":",
"Iterable",
"[",
"Dict",
"]",
",",
"key",
":",
"str",
",",
"datetime_format_string",
":",
"str",
")",
"->",
"None",
":",
"for",
"d",
"in",
"dict_list",
":",
"d",
"[",
"key",
"]",
"=",
"datetim... | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a ``datetime.datetime`` form, using
``datetime_format_string`` as the format parameter to
:func:`datetime.datetime.strptime`. | [
"Process",
"an",
"iterable",
"of",
"dictionaries",
".",
"For",
"each",
"dictionary",
"d",
"convert",
"(",
"in",
"place",
")",
"d",
"[",
"key",
"]",
"to",
"a",
"datetime",
".",
"datetime",
"form",
"using",
"datetime_format_string",
"as",
"the",
"format",
"p... | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L515-L525 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_text.py | dictlist_convert_to_int | def dictlist_convert_to_int(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to an integer. If that fails, convert it to ``None``.
"""
for d in dict_list:
try:
d[key] = int(d[key])
... | python | def dictlist_convert_to_int(dict_list: Iterable[Dict], key: str) -> None:
"""
Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to an integer. If that fails, convert it to ``None``.
"""
for d in dict_list:
try:
d[key] = int(d[key])
... | [
"def",
"dictlist_convert_to_int",
"(",
"dict_list",
":",
"Iterable",
"[",
"Dict",
"]",
",",
"key",
":",
"str",
")",
"->",
"None",
":",
"for",
"d",
"in",
"dict_list",
":",
"try",
":",
"d",
"[",
"key",
"]",
"=",
"int",
"(",
"d",
"[",
"key",
"]",
")... | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to an integer. If that fails, convert it to ``None``. | [
"Process",
"an",
"iterable",
"of",
"dictionaries",
".",
"For",
"each",
"dictionary",
"d",
"convert",
"(",
"in",
"place",
")",
"d",
"[",
"key",
"]",
"to",
"an",
"integer",
".",
"If",
"that",
"fails",
"convert",
"it",
"to",
"None",
"."
] | train | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L528-L537 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.