repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
RudolfCardinal/pythonlib | cardinal_pythonlib/django/files.py | auto_delete_files_on_instance_delete | def auto_delete_files_on_instance_delete(instance: Any,
fieldnames: Iterable[str]) -> None:
"""
Deletes files from filesystem when object is deleted.
"""
for fieldname in fieldnames:
filefield = getattr(instance, fieldname, None)
if filefield:
if os.path.isfile(filefield.path):
os.remove(filefield.path) | python | def auto_delete_files_on_instance_delete(instance: Any,
fieldnames: Iterable[str]) -> None:
"""
Deletes files from filesystem when object is deleted.
"""
for fieldname in fieldnames:
filefield = getattr(instance, fieldname, None)
if filefield:
if os.path.isfile(filefield.path):
os.remove(filefield.path) | [
"def",
"auto_delete_files_on_instance_delete",
"(",
"instance",
":",
"Any",
",",
"fieldnames",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"fieldname",
"in",
"fieldnames",
":",
"filefield",
"=",
"getattr",
"(",
"instance",
",",
"fieldname"... | Deletes files from filesystem when object is deleted. | [
"Deletes",
"files",
"from",
"filesystem",
"when",
"object",
"is",
"deleted",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/files.py#L43-L52 | train | 53,200 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/files.py | auto_delete_files_on_instance_change | def auto_delete_files_on_instance_change(
instance: Any,
fieldnames: Iterable[str],
model_class) -> None:
"""
Deletes files from filesystem when object is changed.
model_class: ``Type[Model]``
... only the type checker in Py3.5 is broken; v.s.
"""
if not instance.pk:
return # instance not yet saved in database
# noinspection PyUnresolvedReferences
try:
# noinspection PyUnresolvedReferences
old_instance = model_class.objects.get(pk=instance.pk)
except model_class.DoesNotExist:
return # old version gone from database entirely
for fieldname in fieldnames:
old_filefield = getattr(old_instance, fieldname, None)
if not old_filefield:
continue
new_filefield = getattr(instance, fieldname, None)
if old_filefield != new_filefield:
if os.path.isfile(old_filefield.path):
os.remove(old_filefield.path) | python | def auto_delete_files_on_instance_change(
instance: Any,
fieldnames: Iterable[str],
model_class) -> None:
"""
Deletes files from filesystem when object is changed.
model_class: ``Type[Model]``
... only the type checker in Py3.5 is broken; v.s.
"""
if not instance.pk:
return # instance not yet saved in database
# noinspection PyUnresolvedReferences
try:
# noinspection PyUnresolvedReferences
old_instance = model_class.objects.get(pk=instance.pk)
except model_class.DoesNotExist:
return # old version gone from database entirely
for fieldname in fieldnames:
old_filefield = getattr(old_instance, fieldname, None)
if not old_filefield:
continue
new_filefield = getattr(instance, fieldname, None)
if old_filefield != new_filefield:
if os.path.isfile(old_filefield.path):
os.remove(old_filefield.path) | [
"def",
"auto_delete_files_on_instance_change",
"(",
"instance",
":",
"Any",
",",
"fieldnames",
":",
"Iterable",
"[",
"str",
"]",
",",
"model_class",
")",
"->",
"None",
":",
"if",
"not",
"instance",
".",
"pk",
":",
"return",
"# instance not yet saved in database",
... | Deletes files from filesystem when object is changed.
model_class: ``Type[Model]``
... only the type checker in Py3.5 is broken; v.s. | [
"Deletes",
"files",
"from",
"filesystem",
"when",
"object",
"is",
"changed",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/files.py#L73-L100 | train | 53,201 |
davenquinn/Attitude | attitude/orientation/pca.py | axis_transform | def axis_transform(pca_axes):
"""
Creates an affine transformation matrix to
rotate data in PCA axes into Cartesian plane
"""
from_ = N.identity(3)
to_ = pca_axes
# Find inverse transform for forward transform
# y = M x -> M = y (x)^(-1)
# We don't need to do least-squares since
# there is a simple transformation
trans_matrix = N.linalg.lstsq(from_,to_)[0]
return trans_matrix | python | def axis_transform(pca_axes):
"""
Creates an affine transformation matrix to
rotate data in PCA axes into Cartesian plane
"""
from_ = N.identity(3)
to_ = pca_axes
# Find inverse transform for forward transform
# y = M x -> M = y (x)^(-1)
# We don't need to do least-squares since
# there is a simple transformation
trans_matrix = N.linalg.lstsq(from_,to_)[0]
return trans_matrix | [
"def",
"axis_transform",
"(",
"pca_axes",
")",
":",
"from_",
"=",
"N",
".",
"identity",
"(",
"3",
")",
"to_",
"=",
"pca_axes",
"# Find inverse transform for forward transform",
"# y = M x -> M = y (x)^(-1)",
"# We don't need to do least-squares since",
"# there is a simple tr... | Creates an affine transformation matrix to
rotate data in PCA axes into Cartesian plane | [
"Creates",
"an",
"affine",
"transformation",
"matrix",
"to",
"rotate",
"data",
"in",
"PCA",
"axes",
"into",
"Cartesian",
"plane"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L57-L70 | train | 53,202 |
davenquinn/Attitude | attitude/orientation/pca.py | covariance_matrix | def covariance_matrix(self):
"""
Constructs the covariance matrix of
input data from
the singular value decomposition. Note
that this is different than a covariance
matrix of residuals, which is what we want
for calculating fit errors.
Using SVD output to compute covariance matrix
X=UΣV⊤
XX⊤XX⊤=(UΣV⊤)(UΣV⊤)⊤=(UΣV⊤)(VΣU⊤)
V is an orthogonal matrix (V⊤V=I),
covariance matrix of input data: XX⊤=UΣ2U⊤
Because the axes represent identity in the
PCA coordinate system, the PCA major axes
themselves represent an affine transformation
matrix from PCA to Cartesian space
"""
a = N.dot(self.U,self.sigma)
cv = N.dot(a,a.T)
# This yields the covariance matrix in Cartesian
# coordinates
return cv | python | def covariance_matrix(self):
"""
Constructs the covariance matrix of
input data from
the singular value decomposition. Note
that this is different than a covariance
matrix of residuals, which is what we want
for calculating fit errors.
Using SVD output to compute covariance matrix
X=UΣV⊤
XX⊤XX⊤=(UΣV⊤)(UΣV⊤)⊤=(UΣV⊤)(VΣU⊤)
V is an orthogonal matrix (V⊤V=I),
covariance matrix of input data: XX⊤=UΣ2U⊤
Because the axes represent identity in the
PCA coordinate system, the PCA major axes
themselves represent an affine transformation
matrix from PCA to Cartesian space
"""
a = N.dot(self.U,self.sigma)
cv = N.dot(a,a.T)
# This yields the covariance matrix in Cartesian
# coordinates
return cv | [
"def",
"covariance_matrix",
"(",
"self",
")",
":",
"a",
"=",
"N",
".",
"dot",
"(",
"self",
".",
"U",
",",
"self",
".",
"sigma",
")",
"cv",
"=",
"N",
".",
"dot",
"(",
"a",
",",
"a",
".",
"T",
")",
"# This yields the covariance matrix in Cartesian",
"#... | Constructs the covariance matrix of
input data from
the singular value decomposition. Note
that this is different than a covariance
matrix of residuals, which is what we want
for calculating fit errors.
Using SVD output to compute covariance matrix
X=UΣV⊤
XX⊤XX⊤=(UΣV⊤)(UΣV⊤)⊤=(UΣV⊤)(VΣU⊤)
V is an orthogonal matrix (V⊤V=I),
covariance matrix of input data: XX⊤=UΣ2U⊤
Because the axes represent identity in the
PCA coordinate system, the PCA major axes
themselves represent an affine transformation
matrix from PCA to Cartesian space | [
"Constructs",
"the",
"covariance",
"matrix",
"of",
"input",
"data",
"from",
"the",
"singular",
"value",
"decomposition",
".",
"Note",
"that",
"this",
"is",
"different",
"than",
"a",
"covariance",
"matrix",
"of",
"residuals",
"which",
"is",
"what",
"we",
"want"... | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L83-L108 | train | 53,203 |
davenquinn/Attitude | attitude/orientation/pca.py | PCAOrientation.U | def U(self):
"""
Property to support lazy evaluation of residuals
"""
if self._U is None:
sinv = N.diag(1/self.singular_values)
self._U = dot(self.arr,self.V.T,sinv)
return self._U | python | def U(self):
"""
Property to support lazy evaluation of residuals
"""
if self._U is None:
sinv = N.diag(1/self.singular_values)
self._U = dot(self.arr,self.V.T,sinv)
return self._U | [
"def",
"U",
"(",
"self",
")",
":",
"if",
"self",
".",
"_U",
"is",
"None",
":",
"sinv",
"=",
"N",
".",
"diag",
"(",
"1",
"/",
"self",
".",
"singular_values",
")",
"self",
".",
"_U",
"=",
"dot",
"(",
"self",
".",
"arr",
",",
"self",
".",
"V",
... | Property to support lazy evaluation of residuals | [
"Property",
"to",
"support",
"lazy",
"evaluation",
"of",
"residuals"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L240-L247 | train | 53,204 |
davenquinn/Attitude | attitude/orientation/pca.py | PCAOrientation._covariance_matrix | def _covariance_matrix(self, type='noise'):
"""
Constructs the covariance matrix from PCA
residuals
"""
if type == 'sampling':
return self.sigma**2/(self.n-1)
elif type == 'noise':
return 4*self.sigma*N.var(self.rotated(), axis=0) | python | def _covariance_matrix(self, type='noise'):
"""
Constructs the covariance matrix from PCA
residuals
"""
if type == 'sampling':
return self.sigma**2/(self.n-1)
elif type == 'noise':
return 4*self.sigma*N.var(self.rotated(), axis=0) | [
"def",
"_covariance_matrix",
"(",
"self",
",",
"type",
"=",
"'noise'",
")",
":",
"if",
"type",
"==",
"'sampling'",
":",
"return",
"self",
".",
"sigma",
"**",
"2",
"/",
"(",
"self",
".",
"n",
"-",
"1",
")",
"elif",
"type",
"==",
"'noise'",
":",
"ret... | Constructs the covariance matrix from PCA
residuals | [
"Constructs",
"the",
"covariance",
"matrix",
"from",
"PCA",
"residuals"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L309-L317 | train | 53,205 |
davenquinn/Attitude | attitude/orientation/pca.py | PCAOrientation.as_hyperbola | def as_hyperbola(self, rotated=False):
"""
Hyperbolic error area
"""
idx = N.diag_indices(3)
_ = 1/self.covariance_matrix[idx]
d = list(_)
d[-1] *= -1
arr = N.identity(4)*-1
arr[idx] = d
hyp = conic(arr)
if rotated:
R = augment(self.axes)
hyp = hyp.transform(R)
return hyp | python | def as_hyperbola(self, rotated=False):
"""
Hyperbolic error area
"""
idx = N.diag_indices(3)
_ = 1/self.covariance_matrix[idx]
d = list(_)
d[-1] *= -1
arr = N.identity(4)*-1
arr[idx] = d
hyp = conic(arr)
if rotated:
R = augment(self.axes)
hyp = hyp.transform(R)
return hyp | [
"def",
"as_hyperbola",
"(",
"self",
",",
"rotated",
"=",
"False",
")",
":",
"idx",
"=",
"N",
".",
"diag_indices",
"(",
"3",
")",
"_",
"=",
"1",
"/",
"self",
".",
"covariance_matrix",
"[",
"idx",
"]",
"d",
"=",
"list",
"(",
"_",
")",
"d",
"[",
"... | Hyperbolic error area | [
"Hyperbolic",
"error",
"area"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/orientation/pca.py#L422-L437 | train | 53,206 |
meyersj/geotweet | geotweet/mapreduce/utils/words.py | WordExtractor.run | def run(self, line):
"""
Extract words from tweet
1. Remove non-ascii characters
2. Split line into individual words
3. Clean up puncuation characters
"""
words = []
for word in self.clean_unicode(line.lower()).split():
if word.startswith('http'):
continue
cleaned = self.clean_punctuation(word)
if len(cleaned) > 1 and cleaned not in self.stopwords:
words.append(cleaned)
return words | python | def run(self, line):
"""
Extract words from tweet
1. Remove non-ascii characters
2. Split line into individual words
3. Clean up puncuation characters
"""
words = []
for word in self.clean_unicode(line.lower()).split():
if word.startswith('http'):
continue
cleaned = self.clean_punctuation(word)
if len(cleaned) > 1 and cleaned not in self.stopwords:
words.append(cleaned)
return words | [
"def",
"run",
"(",
"self",
",",
"line",
")",
":",
"words",
"=",
"[",
"]",
"for",
"word",
"in",
"self",
".",
"clean_unicode",
"(",
"line",
".",
"lower",
"(",
")",
")",
".",
"split",
"(",
")",
":",
"if",
"word",
".",
"startswith",
"(",
"'http'",
... | Extract words from tweet
1. Remove non-ascii characters
2. Split line into individual words
3. Clean up puncuation characters | [
"Extract",
"words",
"from",
"tweet"
] | 1a6b55f98adf34d1b91f172d9187d599616412d9 | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/words.py#L47-L63 | train | 53,207 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_query.py | bool_from_exists_clause | def bool_from_exists_clause(session: Session,
exists_clause: Exists) -> bool:
"""
Database dialects are not consistent in how ``EXISTS`` clauses can be
converted to a boolean answer. This function manages the inconsistencies.
See:
- https://bitbucket.org/zzzeek/sqlalchemy/issues/3212/misleading-documentation-for-queryexists
- http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.exists
Specifically, we want this:
*SQL Server*
.. code-block:: sql
SELECT 1 WHERE EXISTS (SELECT 1 FROM table WHERE ...)
-- ... giving 1 or None (no rows)
-- ... fine for SQL Server, but invalid for MySQL (no FROM clause)
*Others, including MySQL*
.. code-block:: sql
SELECT EXISTS (SELECT 1 FROM table WHERE ...)
-- ... giving 1 or 0
-- ... fine for MySQL, but invalid syntax for SQL Server
""" # noqa
if session.get_bind().dialect.name == SqlaDialectName.MSSQL:
# SQL Server
result = session.query(literal(True)).filter(exists_clause).scalar()
else:
# MySQL, etc.
result = session.query(exists_clause).scalar()
return bool(result) | python | def bool_from_exists_clause(session: Session,
exists_clause: Exists) -> bool:
"""
Database dialects are not consistent in how ``EXISTS`` clauses can be
converted to a boolean answer. This function manages the inconsistencies.
See:
- https://bitbucket.org/zzzeek/sqlalchemy/issues/3212/misleading-documentation-for-queryexists
- http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.exists
Specifically, we want this:
*SQL Server*
.. code-block:: sql
SELECT 1 WHERE EXISTS (SELECT 1 FROM table WHERE ...)
-- ... giving 1 or None (no rows)
-- ... fine for SQL Server, but invalid for MySQL (no FROM clause)
*Others, including MySQL*
.. code-block:: sql
SELECT EXISTS (SELECT 1 FROM table WHERE ...)
-- ... giving 1 or 0
-- ... fine for MySQL, but invalid syntax for SQL Server
""" # noqa
if session.get_bind().dialect.name == SqlaDialectName.MSSQL:
# SQL Server
result = session.query(literal(True)).filter(exists_clause).scalar()
else:
# MySQL, etc.
result = session.query(exists_clause).scalar()
return bool(result) | [
"def",
"bool_from_exists_clause",
"(",
"session",
":",
"Session",
",",
"exists_clause",
":",
"Exists",
")",
"->",
"bool",
":",
"# noqa",
"if",
"session",
".",
"get_bind",
"(",
")",
".",
"dialect",
".",
"name",
"==",
"SqlaDialectName",
".",
"MSSQL",
":",
"#... | Database dialects are not consistent in how ``EXISTS`` clauses can be
converted to a boolean answer. This function manages the inconsistencies.
See:
- https://bitbucket.org/zzzeek/sqlalchemy/issues/3212/misleading-documentation-for-queryexists
- http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.exists
Specifically, we want this:
*SQL Server*
.. code-block:: sql
SELECT 1 WHERE EXISTS (SELECT 1 FROM table WHERE ...)
-- ... giving 1 or None (no rows)
-- ... fine for SQL Server, but invalid for MySQL (no FROM clause)
*Others, including MySQL*
.. code-block:: sql
SELECT EXISTS (SELECT 1 FROM table WHERE ...)
-- ... giving 1 or 0
-- ... fine for MySQL, but invalid syntax for SQL Server | [
"Database",
"dialects",
"are",
"not",
"consistent",
"in",
"how",
"EXISTS",
"clauses",
"can",
"be",
"converted",
"to",
"a",
"boolean",
"answer",
".",
"This",
"function",
"manages",
"the",
"inconsistencies",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_query.py#L81-L117 | train | 53,208 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_query.py | exists_orm | def exists_orm(session: Session,
ormclass: DeclarativeMeta,
*criteria: Any) -> bool:
"""
Detects whether a database record exists for the specified ``ormclass``
and ``criteria``.
Example usage:
.. code-block:: python
bool_exists = exists_orm(session, MyClass, MyClass.myfield == value)
"""
# http://docs.sqlalchemy.org/en/latest/orm/query.html
q = session.query(ormclass)
for criterion in criteria:
q = q.filter(criterion)
exists_clause = q.exists()
return bool_from_exists_clause(session=session,
exists_clause=exists_clause) | python | def exists_orm(session: Session,
ormclass: DeclarativeMeta,
*criteria: Any) -> bool:
"""
Detects whether a database record exists for the specified ``ormclass``
and ``criteria``.
Example usage:
.. code-block:: python
bool_exists = exists_orm(session, MyClass, MyClass.myfield == value)
"""
# http://docs.sqlalchemy.org/en/latest/orm/query.html
q = session.query(ormclass)
for criterion in criteria:
q = q.filter(criterion)
exists_clause = q.exists()
return bool_from_exists_clause(session=session,
exists_clause=exists_clause) | [
"def",
"exists_orm",
"(",
"session",
":",
"Session",
",",
"ormclass",
":",
"DeclarativeMeta",
",",
"*",
"criteria",
":",
"Any",
")",
"->",
"bool",
":",
"# http://docs.sqlalchemy.org/en/latest/orm/query.html",
"q",
"=",
"session",
".",
"query",
"(",
"ormclass",
"... | Detects whether a database record exists for the specified ``ormclass``
and ``criteria``.
Example usage:
.. code-block:: python
bool_exists = exists_orm(session, MyClass, MyClass.myfield == value) | [
"Detects",
"whether",
"a",
"database",
"record",
"exists",
"for",
"the",
"specified",
"ormclass",
"and",
"criteria",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_query.py#L120-L139 | train | 53,209 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/orm_query.py | get_or_create | def get_or_create(session: Session,
model: DeclarativeMeta,
defaults: Dict[str, Any] = None,
**kwargs: Any) -> Tuple[Any, bool]:
"""
Fetches an ORM object from the database, or creates one if none existed.
Args:
session: an SQLAlchemy :class:`Session`
model: an SQLAlchemy ORM class
defaults: default initialization arguments (in addition to relevant
filter criteria) if we have to create a new instance
kwargs: optional filter criteria
Returns:
a tuple ``(instance, newly_created)``
See http://stackoverflow.com/questions/2546207 (this function is a
composite of several suggestions).
"""
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance, False
else:
params = dict((k, v) for k, v in kwargs.items()
if not isinstance(v, ClauseElement))
params.update(defaults or {})
instance = model(**params)
session.add(instance)
return instance, True | python | def get_or_create(session: Session,
model: DeclarativeMeta,
defaults: Dict[str, Any] = None,
**kwargs: Any) -> Tuple[Any, bool]:
"""
Fetches an ORM object from the database, or creates one if none existed.
Args:
session: an SQLAlchemy :class:`Session`
model: an SQLAlchemy ORM class
defaults: default initialization arguments (in addition to relevant
filter criteria) if we have to create a new instance
kwargs: optional filter criteria
Returns:
a tuple ``(instance, newly_created)``
See http://stackoverflow.com/questions/2546207 (this function is a
composite of several suggestions).
"""
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance, False
else:
params = dict((k, v) for k, v in kwargs.items()
if not isinstance(v, ClauseElement))
params.update(defaults or {})
instance = model(**params)
session.add(instance)
return instance, True | [
"def",
"get_or_create",
"(",
"session",
":",
"Session",
",",
"model",
":",
"DeclarativeMeta",
",",
"defaults",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Tuple",
"[",
"Any",
",",
"bool",
... | Fetches an ORM object from the database, or creates one if none existed.
Args:
session: an SQLAlchemy :class:`Session`
model: an SQLAlchemy ORM class
defaults: default initialization arguments (in addition to relevant
filter criteria) if we have to create a new instance
kwargs: optional filter criteria
Returns:
a tuple ``(instance, newly_created)``
See http://stackoverflow.com/questions/2546207 (this function is a
composite of several suggestions). | [
"Fetches",
"an",
"ORM",
"object",
"from",
"the",
"database",
"or",
"creates",
"one",
"if",
"none",
"existed",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/orm_query.py#L146-L175 | train | 53,210 |
RudolfCardinal/pythonlib | cardinal_pythonlib/randomness.py | create_base64encoded_randomness | def create_base64encoded_randomness(num_bytes: int) -> str:
"""
Create and return ``num_bytes`` of random data.
The result is encoded in a string with URL-safe ``base64`` encoding.
Used (for example) to generate session tokens.
Which generator to use? See
https://cryptography.io/en/latest/random-numbers/.
Do NOT use these methods:
.. code-block:: python
randbytes = M2Crypto.m2.rand_bytes(num_bytes) # NO!
randbytes = Crypto.Random.get_random_bytes(num_bytes) # NO!
Instead, do this:
.. code-block:: python
randbytes = os.urandom(num_bytes) # YES
"""
randbytes = os.urandom(num_bytes) # YES
return base64.urlsafe_b64encode(randbytes).decode('ascii') | python | def create_base64encoded_randomness(num_bytes: int) -> str:
"""
Create and return ``num_bytes`` of random data.
The result is encoded in a string with URL-safe ``base64`` encoding.
Used (for example) to generate session tokens.
Which generator to use? See
https://cryptography.io/en/latest/random-numbers/.
Do NOT use these methods:
.. code-block:: python
randbytes = M2Crypto.m2.rand_bytes(num_bytes) # NO!
randbytes = Crypto.Random.get_random_bytes(num_bytes) # NO!
Instead, do this:
.. code-block:: python
randbytes = os.urandom(num_bytes) # YES
"""
randbytes = os.urandom(num_bytes) # YES
return base64.urlsafe_b64encode(randbytes).decode('ascii') | [
"def",
"create_base64encoded_randomness",
"(",
"num_bytes",
":",
"int",
")",
"->",
"str",
":",
"randbytes",
"=",
"os",
".",
"urandom",
"(",
"num_bytes",
")",
"# YES",
"return",
"base64",
".",
"urlsafe_b64encode",
"(",
"randbytes",
")",
".",
"decode",
"(",
"'... | Create and return ``num_bytes`` of random data.
The result is encoded in a string with URL-safe ``base64`` encoding.
Used (for example) to generate session tokens.
Which generator to use? See
https://cryptography.io/en/latest/random-numbers/.
Do NOT use these methods:
.. code-block:: python
randbytes = M2Crypto.m2.rand_bytes(num_bytes) # NO!
randbytes = Crypto.Random.get_random_bytes(num_bytes) # NO!
Instead, do this:
.. code-block:: python
randbytes = os.urandom(num_bytes) # YES | [
"Create",
"and",
"return",
"num_bytes",
"of",
"random",
"data",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/randomness.py#L33-L58 | train | 53,211 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/table_identity.py | TableIdentity.tablename | def tablename(self) -> str:
"""
Returns the string name of the table.
"""
if self._tablename:
return self._tablename
return self.table.name | python | def tablename(self) -> str:
"""
Returns the string name of the table.
"""
if self._tablename:
return self._tablename
return self.table.name | [
"def",
"tablename",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"_tablename",
":",
"return",
"self",
".",
"_tablename",
"return",
"self",
".",
"table",
".",
"name"
] | Returns the string name of the table. | [
"Returns",
"the",
"string",
"name",
"of",
"the",
"table",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/table_identity.py#L96-L102 | train | 53,212 |
RudolfCardinal/pythonlib | cardinal_pythonlib/openxml/pause_process_by_disk_space.py | is_running | def is_running(process_id: int) -> bool:
"""
Uses the Unix ``ps`` program to see if a process is running.
"""
pstr = str(process_id)
encoding = sys.getdefaultencoding()
s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE)
for line in s.stdout:
strline = line.decode(encoding)
if pstr in strline:
return True
return False | python | def is_running(process_id: int) -> bool:
"""
Uses the Unix ``ps`` program to see if a process is running.
"""
pstr = str(process_id)
encoding = sys.getdefaultencoding()
s = subprocess.Popen(["ps", "-p", pstr], stdout=subprocess.PIPE)
for line in s.stdout:
strline = line.decode(encoding)
if pstr in strline:
return True
return False | [
"def",
"is_running",
"(",
"process_id",
":",
"int",
")",
"->",
"bool",
":",
"pstr",
"=",
"str",
"(",
"process_id",
")",
"encoding",
"=",
"sys",
".",
"getdefaultencoding",
"(",
")",
"s",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"ps\"",
",",
"\"-p\""... | Uses the Unix ``ps`` program to see if a process is running. | [
"Uses",
"the",
"Unix",
"ps",
"program",
"to",
"see",
"if",
"a",
"process",
"is",
"running",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/openxml/pause_process_by_disk_space.py#L45-L56 | train | 53,213 |
davenquinn/Attitude | attitude/display/plot/cov_types/regressions.py | bootstrap_noise | def bootstrap_noise(data, func, n=10000, std=1, symmetric=True):
"""
Bootstrap by adding noise
"""
boot_dist = []
arr = N.zeros(data.shape)
for i in range(n):
if symmetric:
# Noise on all three axes
arr = N.random.randn(*data.shape)*std
else:
# Only z-coordinate noise
arr[:,-1] = N.random.randn(data.shape[0])*std
boot_dist.append(func(data+arr))
return N.array(boot_dist) | python | def bootstrap_noise(data, func, n=10000, std=1, symmetric=True):
"""
Bootstrap by adding noise
"""
boot_dist = []
arr = N.zeros(data.shape)
for i in range(n):
if symmetric:
# Noise on all three axes
arr = N.random.randn(*data.shape)*std
else:
# Only z-coordinate noise
arr[:,-1] = N.random.randn(data.shape[0])*std
boot_dist.append(func(data+arr))
return N.array(boot_dist) | [
"def",
"bootstrap_noise",
"(",
"data",
",",
"func",
",",
"n",
"=",
"10000",
",",
"std",
"=",
"1",
",",
"symmetric",
"=",
"True",
")",
":",
"boot_dist",
"=",
"[",
"]",
"arr",
"=",
"N",
".",
"zeros",
"(",
"data",
".",
"shape",
")",
"for",
"i",
"i... | Bootstrap by adding noise | [
"Bootstrap",
"by",
"adding",
"noise"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/display/plot/cov_types/regressions.py#L43-L57 | train | 53,214 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/reprfunc.py | modelrepr | def modelrepr(instance) -> str:
"""
Default ``repr`` version of a Django model object, for debugging.
"""
elements = []
# noinspection PyProtectedMember
for f in instance._meta.get_fields():
# https://docs.djangoproject.com/en/2.0/ref/models/meta/
if f.auto_created:
continue
if f.is_relation and f.related_model is None:
continue
fieldname = f.name
try:
value = repr(getattr(instance, fieldname))
except ObjectDoesNotExist:
value = "<RelatedObjectDoesNotExist>"
elements.append("{}={}".format(fieldname, value))
return "<{} <{}>>".format(type(instance).__name__,
", ".join(elements)) | python | def modelrepr(instance) -> str:
"""
Default ``repr`` version of a Django model object, for debugging.
"""
elements = []
# noinspection PyProtectedMember
for f in instance._meta.get_fields():
# https://docs.djangoproject.com/en/2.0/ref/models/meta/
if f.auto_created:
continue
if f.is_relation and f.related_model is None:
continue
fieldname = f.name
try:
value = repr(getattr(instance, fieldname))
except ObjectDoesNotExist:
value = "<RelatedObjectDoesNotExist>"
elements.append("{}={}".format(fieldname, value))
return "<{} <{}>>".format(type(instance).__name__,
", ".join(elements)) | [
"def",
"modelrepr",
"(",
"instance",
")",
"->",
"str",
":",
"elements",
"=",
"[",
"]",
"# noinspection PyProtectedMember",
"for",
"f",
"in",
"instance",
".",
"_meta",
".",
"get_fields",
"(",
")",
":",
"# https://docs.djangoproject.com/en/2.0/ref/models/meta/",
"if",... | Default ``repr`` version of a Django model object, for debugging. | [
"Default",
"repr",
"version",
"of",
"a",
"Django",
"model",
"object",
"for",
"debugging",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/reprfunc.py#L32-L51 | train | 53,215 |
RudolfCardinal/pythonlib | cardinal_pythonlib/pdf.py | assert_processor_available | def assert_processor_available(processor: str) -> None:
"""
Assert that a specific PDF processor is available.
Args:
processor: a PDF processor type from :class:`Processors`
Raises:
AssertionError: if bad ``processor``
RuntimeError: if requested processor is unavailable
"""
if processor not in [Processors.XHTML2PDF,
Processors.WEASYPRINT,
Processors.PDFKIT]:
raise AssertionError("rnc_pdf.set_pdf_processor: invalid PDF processor"
" specified")
if processor == Processors.WEASYPRINT and not weasyprint:
raise RuntimeError("rnc_pdf: Weasyprint requested, but not available")
if processor == Processors.XHTML2PDF and not xhtml2pdf:
raise RuntimeError("rnc_pdf: xhtml2pdf requested, but not available")
if processor == Processors.PDFKIT and not pdfkit:
raise RuntimeError("rnc_pdf: pdfkit requested, but not available") | python | def assert_processor_available(processor: str) -> None:
"""
Assert that a specific PDF processor is available.
Args:
processor: a PDF processor type from :class:`Processors`
Raises:
AssertionError: if bad ``processor``
RuntimeError: if requested processor is unavailable
"""
if processor not in [Processors.XHTML2PDF,
Processors.WEASYPRINT,
Processors.PDFKIT]:
raise AssertionError("rnc_pdf.set_pdf_processor: invalid PDF processor"
" specified")
if processor == Processors.WEASYPRINT and not weasyprint:
raise RuntimeError("rnc_pdf: Weasyprint requested, but not available")
if processor == Processors.XHTML2PDF and not xhtml2pdf:
raise RuntimeError("rnc_pdf: xhtml2pdf requested, but not available")
if processor == Processors.PDFKIT and not pdfkit:
raise RuntimeError("rnc_pdf: pdfkit requested, but not available") | [
"def",
"assert_processor_available",
"(",
"processor",
":",
"str",
")",
"->",
"None",
":",
"if",
"processor",
"not",
"in",
"[",
"Processors",
".",
"XHTML2PDF",
",",
"Processors",
".",
"WEASYPRINT",
",",
"Processors",
".",
"PDFKIT",
"]",
":",
"raise",
"Assert... | Assert that a specific PDF processor is available.
Args:
processor: a PDF processor type from :class:`Processors`
Raises:
AssertionError: if bad ``processor``
RuntimeError: if requested processor is unavailable | [
"Assert",
"that",
"a",
"specific",
"PDF",
"processor",
"is",
"available",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L193-L214 | train | 53,216 |
RudolfCardinal/pythonlib | cardinal_pythonlib/pdf.py | get_pdf_from_html | def get_pdf_from_html(html: str,
header_html: str = None,
footer_html: str = None,
wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME,
wkhtmltopdf_options: Dict[str, Any] = None,
file_encoding: str = "utf-8",
debug_options: bool = False,
debug_content: bool = False,
debug_wkhtmltopdf_args: bool = True,
fix_pdfkit_encoding_bug: bool = None,
processor: str = _DEFAULT_PROCESSOR) -> bytes:
"""
Takes HTML and returns a PDF.
See the arguments to :func:`make_pdf_from_html` (except ``on_disk``).
Returns:
the PDF binary as a ``bytes`` object
"""
result = make_pdf_from_html(
on_disk=False,
html=html,
header_html=header_html,
footer_html=footer_html,
wkhtmltopdf_filename=wkhtmltopdf_filename,
wkhtmltopdf_options=wkhtmltopdf_options,
file_encoding=file_encoding,
debug_options=debug_options,
debug_content=debug_content,
debug_wkhtmltopdf_args=debug_wkhtmltopdf_args,
fix_pdfkit_encoding_bug=fix_pdfkit_encoding_bug,
processor=processor,
) # type: bytes
return result | python | def get_pdf_from_html(html: str,
header_html: str = None,
footer_html: str = None,
wkhtmltopdf_filename: str = _WKHTMLTOPDF_FILENAME,
wkhtmltopdf_options: Dict[str, Any] = None,
file_encoding: str = "utf-8",
debug_options: bool = False,
debug_content: bool = False,
debug_wkhtmltopdf_args: bool = True,
fix_pdfkit_encoding_bug: bool = None,
processor: str = _DEFAULT_PROCESSOR) -> bytes:
"""
Takes HTML and returns a PDF.
See the arguments to :func:`make_pdf_from_html` (except ``on_disk``).
Returns:
the PDF binary as a ``bytes`` object
"""
result = make_pdf_from_html(
on_disk=False,
html=html,
header_html=header_html,
footer_html=footer_html,
wkhtmltopdf_filename=wkhtmltopdf_filename,
wkhtmltopdf_options=wkhtmltopdf_options,
file_encoding=file_encoding,
debug_options=debug_options,
debug_content=debug_content,
debug_wkhtmltopdf_args=debug_wkhtmltopdf_args,
fix_pdfkit_encoding_bug=fix_pdfkit_encoding_bug,
processor=processor,
) # type: bytes
return result | [
"def",
"get_pdf_from_html",
"(",
"html",
":",
"str",
",",
"header_html",
":",
"str",
"=",
"None",
",",
"footer_html",
":",
"str",
"=",
"None",
",",
"wkhtmltopdf_filename",
":",
"str",
"=",
"_WKHTMLTOPDF_FILENAME",
",",
"wkhtmltopdf_options",
":",
"Dict",
"[",
... | Takes HTML and returns a PDF.
See the arguments to :func:`make_pdf_from_html` (except ``on_disk``).
Returns:
the PDF binary as a ``bytes`` object | [
"Takes",
"HTML",
"and",
"returns",
"a",
"PDF",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L405-L438 | train | 53,217 |
RudolfCardinal/pythonlib | cardinal_pythonlib/pdf.py | append_pdf | def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):
"""
Appends a PDF to a pyPDF writer. Legacy interface.
"""
append_memory_pdf_to_writer(input_pdf=input_pdf,
writer=output_writer) | python | def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter):
"""
Appends a PDF to a pyPDF writer. Legacy interface.
"""
append_memory_pdf_to_writer(input_pdf=input_pdf,
writer=output_writer) | [
"def",
"append_pdf",
"(",
"input_pdf",
":",
"bytes",
",",
"output_writer",
":",
"PdfFileWriter",
")",
":",
"append_memory_pdf_to_writer",
"(",
"input_pdf",
"=",
"input_pdf",
",",
"writer",
"=",
"output_writer",
")"
] | Appends a PDF to a pyPDF writer. Legacy interface. | [
"Appends",
"a",
"PDF",
"to",
"a",
"pyPDF",
"writer",
".",
"Legacy",
"interface",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L563-L568 | train | 53,218 |
RudolfCardinal/pythonlib | cardinal_pythonlib/pdf.py | get_concatenated_pdf_from_disk | def get_concatenated_pdf_from_disk(filenames: Iterable[str],
start_recto: bool = True) -> bytes:
"""
Concatenates PDFs from disk and returns them as an in-memory binary PDF.
Args:
filenames: iterable of filenames of PDFs to concatenate
start_recto: start a new right-hand page for each new PDF?
Returns:
concatenated PDF, as ``bytes``
"""
# http://stackoverflow.com/questions/17104926/pypdf-merging-multiple-pdf-files-into-one-pdf # noqa
# https://en.wikipedia.org/wiki/Recto_and_verso
if start_recto:
writer = PdfFileWriter()
for filename in filenames:
if filename:
if writer.getNumPages() % 2 != 0:
writer.addBlankPage()
writer.appendPagesFromReader(
PdfFileReader(open(filename, 'rb')))
return pdf_from_writer(writer)
else:
merger = PdfFileMerger()
for filename in filenames:
if filename:
merger.append(open(filename, 'rb'))
return pdf_from_writer(merger) | python | def get_concatenated_pdf_from_disk(filenames: Iterable[str],
start_recto: bool = True) -> bytes:
"""
Concatenates PDFs from disk and returns them as an in-memory binary PDF.
Args:
filenames: iterable of filenames of PDFs to concatenate
start_recto: start a new right-hand page for each new PDF?
Returns:
concatenated PDF, as ``bytes``
"""
# http://stackoverflow.com/questions/17104926/pypdf-merging-multiple-pdf-files-into-one-pdf # noqa
# https://en.wikipedia.org/wiki/Recto_and_verso
if start_recto:
writer = PdfFileWriter()
for filename in filenames:
if filename:
if writer.getNumPages() % 2 != 0:
writer.addBlankPage()
writer.appendPagesFromReader(
PdfFileReader(open(filename, 'rb')))
return pdf_from_writer(writer)
else:
merger = PdfFileMerger()
for filename in filenames:
if filename:
merger.append(open(filename, 'rb'))
return pdf_from_writer(merger) | [
"def",
"get_concatenated_pdf_from_disk",
"(",
"filenames",
":",
"Iterable",
"[",
"str",
"]",
",",
"start_recto",
":",
"bool",
"=",
"True",
")",
"->",
"bytes",
":",
"# http://stackoverflow.com/questions/17104926/pypdf-merging-multiple-pdf-files-into-one-pdf # noqa",
"# https:... | Concatenates PDFs from disk and returns them as an in-memory binary PDF.
Args:
filenames: iterable of filenames of PDFs to concatenate
start_recto: start a new right-hand page for each new PDF?
Returns:
concatenated PDF, as ``bytes`` | [
"Concatenates",
"PDFs",
"from",
"disk",
"and",
"returns",
"them",
"as",
"an",
"in",
"-",
"memory",
"binary",
"PDF",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L597-L626 | train | 53,219 |
RudolfCardinal/pythonlib | cardinal_pythonlib/pdf.py | get_concatenated_pdf_in_memory | def get_concatenated_pdf_in_memory(
pdf_plans: Iterable[PdfPlan],
start_recto: bool = True) -> bytes:
"""
Concatenates PDFs and returns them as an in-memory binary PDF.
Args:
pdf_plans: iterable of :class:`PdfPlan` objects
start_recto: start a new right-hand page for each new PDF?
Returns:
concatenated PDF, as ``bytes``
"""
writer = PdfFileWriter()
for pdfplan in pdf_plans:
pdfplan.add_to_writer(writer, start_recto=start_recto)
return pdf_from_writer(writer) | python | def get_concatenated_pdf_in_memory(
pdf_plans: Iterable[PdfPlan],
start_recto: bool = True) -> bytes:
"""
Concatenates PDFs and returns them as an in-memory binary PDF.
Args:
pdf_plans: iterable of :class:`PdfPlan` objects
start_recto: start a new right-hand page for each new PDF?
Returns:
concatenated PDF, as ``bytes``
"""
writer = PdfFileWriter()
for pdfplan in pdf_plans:
pdfplan.add_to_writer(writer, start_recto=start_recto)
return pdf_from_writer(writer) | [
"def",
"get_concatenated_pdf_in_memory",
"(",
"pdf_plans",
":",
"Iterable",
"[",
"PdfPlan",
"]",
",",
"start_recto",
":",
"bool",
"=",
"True",
")",
"->",
"bytes",
":",
"writer",
"=",
"PdfFileWriter",
"(",
")",
"for",
"pdfplan",
"in",
"pdf_plans",
":",
"pdfpl... | Concatenates PDFs and returns them as an in-memory binary PDF.
Args:
pdf_plans: iterable of :class:`PdfPlan` objects
start_recto: start a new right-hand page for each new PDF?
Returns:
concatenated PDF, as ``bytes`` | [
"Concatenates",
"PDFs",
"and",
"returns",
"them",
"as",
"an",
"in",
"-",
"memory",
"binary",
"PDF",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L629-L646 | train | 53,220 |
RudolfCardinal/pythonlib | cardinal_pythonlib/pdf.py | PdfPlan.add_to_writer | def add_to_writer(self,
writer: PdfFileWriter,
start_recto: bool = True) -> None:
"""
Add the PDF described by this class to a PDF writer.
Args:
writer: a :class:`PyPDF2.PdfFileWriter`
start_recto: start a new right-hand page?
"""
if self.is_html:
pdf = get_pdf_from_html(
html=self.html,
header_html=self.header_html,
footer_html=self.footer_html,
wkhtmltopdf_filename=self.wkhtmltopdf_filename,
wkhtmltopdf_options=self.wkhtmltopdf_options)
append_memory_pdf_to_writer(pdf, writer, start_recto=start_recto)
elif self.is_filename:
if start_recto and writer.getNumPages() % 2 != 0:
writer.addBlankPage()
writer.appendPagesFromReader(PdfFileReader(
open(self.filename, 'rb')))
else:
raise AssertionError("PdfPlan: shouldn't get here!") | python | def add_to_writer(self,
writer: PdfFileWriter,
start_recto: bool = True) -> None:
"""
Add the PDF described by this class to a PDF writer.
Args:
writer: a :class:`PyPDF2.PdfFileWriter`
start_recto: start a new right-hand page?
"""
if self.is_html:
pdf = get_pdf_from_html(
html=self.html,
header_html=self.header_html,
footer_html=self.footer_html,
wkhtmltopdf_filename=self.wkhtmltopdf_filename,
wkhtmltopdf_options=self.wkhtmltopdf_options)
append_memory_pdf_to_writer(pdf, writer, start_recto=start_recto)
elif self.is_filename:
if start_recto and writer.getNumPages() % 2 != 0:
writer.addBlankPage()
writer.appendPagesFromReader(PdfFileReader(
open(self.filename, 'rb')))
else:
raise AssertionError("PdfPlan: shouldn't get here!") | [
"def",
"add_to_writer",
"(",
"self",
",",
"writer",
":",
"PdfFileWriter",
",",
"start_recto",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"if",
"self",
".",
"is_html",
":",
"pdf",
"=",
"get_pdf_from_html",
"(",
"html",
"=",
"self",
".",
"html",
"... | Add the PDF described by this class to a PDF writer.
Args:
writer: a :class:`PyPDF2.PdfFileWriter`
start_recto: start a new right-hand page? | [
"Add",
"the",
"PDF",
"described",
"by",
"this",
"class",
"to",
"a",
"PDF",
"writer",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/pdf.py#L161-L186 | train | 53,221 |
RudolfCardinal/pythonlib | cardinal_pythonlib/formatting.py | trunc_if_integer | def trunc_if_integer(n: Any) -> Any:
"""
Truncates floats that are integers to their integer representation.
That is, converts ``1.0`` to ``1``, etc.
Otherwise, returns the starting value.
Will raise an exception if the input cannot be converted to ``int``.
"""
if n == int(n):
return int(n)
return n | python | def trunc_if_integer(n: Any) -> Any:
"""
Truncates floats that are integers to their integer representation.
That is, converts ``1.0`` to ``1``, etc.
Otherwise, returns the starting value.
Will raise an exception if the input cannot be converted to ``int``.
"""
if n == int(n):
return int(n)
return n | [
"def",
"trunc_if_integer",
"(",
"n",
":",
"Any",
")",
"->",
"Any",
":",
"if",
"n",
"==",
"int",
"(",
"n",
")",
":",
"return",
"int",
"(",
"n",
")",
"return",
"n"
] | Truncates floats that are integers to their integer representation.
That is, converts ``1.0`` to ``1``, etc.
Otherwise, returns the starting value.
Will raise an exception if the input cannot be converted to ``int``. | [
"Truncates",
"floats",
"that",
"are",
"integers",
"to",
"their",
"integer",
"representation",
".",
"That",
"is",
"converts",
"1",
".",
"0",
"to",
"1",
"etc",
".",
"Otherwise",
"returns",
"the",
"starting",
"value",
".",
"Will",
"raise",
"an",
"exception",
... | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/formatting.py#L36-L45 | train | 53,222 |
RudolfCardinal/pythonlib | cardinal_pythonlib/psychiatry/treatment_resistant_depression.py | timedelta_days | def timedelta_days(days: int) -> timedelta64:
"""
Convert a duration in days to a NumPy ``timedelta64`` object.
"""
int_days = int(days)
if int_days != days:
raise ValueError("Fractional days passed to timedelta_days: "
"{!r}".format(days))
try:
# Do not pass e.g. 27.0; that will raise a ValueError.
# Must be an actual int:
return timedelta64(int_days, 'D')
except ValueError as e:
raise ValueError("Failure in timedelta_days; value was {!r}; original "
"error was: {}".format(days, e)) | python | def timedelta_days(days: int) -> timedelta64:
"""
Convert a duration in days to a NumPy ``timedelta64`` object.
"""
int_days = int(days)
if int_days != days:
raise ValueError("Fractional days passed to timedelta_days: "
"{!r}".format(days))
try:
# Do not pass e.g. 27.0; that will raise a ValueError.
# Must be an actual int:
return timedelta64(int_days, 'D')
except ValueError as e:
raise ValueError("Failure in timedelta_days; value was {!r}; original "
"error was: {}".format(days, e)) | [
"def",
"timedelta_days",
"(",
"days",
":",
"int",
")",
"->",
"timedelta64",
":",
"int_days",
"=",
"int",
"(",
"days",
")",
"if",
"int_days",
"!=",
"days",
":",
"raise",
"ValueError",
"(",
"\"Fractional days passed to timedelta_days: \"",
"\"{!r}\"",
".",
"format... | Convert a duration in days to a NumPy ``timedelta64`` object. | [
"Convert",
"a",
"duration",
"in",
"days",
"to",
"a",
"NumPy",
"timedelta64",
"object",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/treatment_resistant_depression.py#L121-L135 | train | 53,223 |
RudolfCardinal/pythonlib | cardinal_pythonlib/psychiatry/treatment_resistant_depression.py | _get_generic_two_antidep_episodes_result | def _get_generic_two_antidep_episodes_result(
rowdata: Tuple[Any, ...] = None) -> DataFrame:
"""
Create a results row for this application.
"""
# Valid data types... see:
# - pandas.core.dtypes.common.pandas_dtype
# - https://pandas.pydata.org/pandas-docs/stable/timeseries.html
# - https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.datetime.html
data = [rowdata] if rowdata else []
return DataFrame(array(
data, # data
dtype=[ # column definitions:
(RCN_PATIENT_ID, DTYPE_STRING),
(RCN_DRUG_A_NAME, DTYPE_STRING),
(RCN_DRUG_A_FIRST_MENTION, DTYPE_DATE),
(RCN_DRUG_A_SECOND_MENTION, DTYPE_DATE),
(RCN_DRUG_B_NAME, DTYPE_STRING),
(RCN_DRUG_B_FIRST_MENTION, DTYPE_DATE),
(RCN_DRUG_B_SECOND_MENTION, DTYPE_DATE),
(RCN_EXPECT_RESPONSE_BY_DATE, DTYPE_DATE),
(RCN_END_OF_SYMPTOM_PERIOD, DTYPE_DATE),
]
)) | python | def _get_generic_two_antidep_episodes_result(
rowdata: Tuple[Any, ...] = None) -> DataFrame:
"""
Create a results row for this application.
"""
# Valid data types... see:
# - pandas.core.dtypes.common.pandas_dtype
# - https://pandas.pydata.org/pandas-docs/stable/timeseries.html
# - https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.datetime.html
data = [rowdata] if rowdata else []
return DataFrame(array(
data, # data
dtype=[ # column definitions:
(RCN_PATIENT_ID, DTYPE_STRING),
(RCN_DRUG_A_NAME, DTYPE_STRING),
(RCN_DRUG_A_FIRST_MENTION, DTYPE_DATE),
(RCN_DRUG_A_SECOND_MENTION, DTYPE_DATE),
(RCN_DRUG_B_NAME, DTYPE_STRING),
(RCN_DRUG_B_FIRST_MENTION, DTYPE_DATE),
(RCN_DRUG_B_SECOND_MENTION, DTYPE_DATE),
(RCN_EXPECT_RESPONSE_BY_DATE, DTYPE_DATE),
(RCN_END_OF_SYMPTOM_PERIOD, DTYPE_DATE),
]
)) | [
"def",
"_get_generic_two_antidep_episodes_result",
"(",
"rowdata",
":",
"Tuple",
"[",
"Any",
",",
"...",
"]",
"=",
"None",
")",
"->",
"DataFrame",
":",
"# Valid data types... see:",
"# - pandas.core.dtypes.common.pandas_dtype",
"# - https://pandas.pydata.org/pandas-docs/stable/... | Create a results row for this application. | [
"Create",
"a",
"results",
"row",
"for",
"this",
"application",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/psychiatry/treatment_resistant_depression.py#L138-L161 | train | 53,224 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | get_filelikeobject | def get_filelikeobject(filename: str = None,
blob: bytes = None) -> BinaryIO:
"""
Open a file-like object.
Guard the use of this function with ``with``.
Args:
filename: for specifying via a filename
blob: for specifying via an in-memory ``bytes`` object
Returns:
a :class:`BinaryIO` object
"""
if not filename and not blob:
raise ValueError("no filename and no blob")
if filename and blob:
raise ValueError("specify either filename or blob")
if filename:
return open(filename, 'rb')
else:
return io.BytesIO(blob) | python | def get_filelikeobject(filename: str = None,
blob: bytes = None) -> BinaryIO:
"""
Open a file-like object.
Guard the use of this function with ``with``.
Args:
filename: for specifying via a filename
blob: for specifying via an in-memory ``bytes`` object
Returns:
a :class:`BinaryIO` object
"""
if not filename and not blob:
raise ValueError("no filename and no blob")
if filename and blob:
raise ValueError("specify either filename or blob")
if filename:
return open(filename, 'rb')
else:
return io.BytesIO(blob) | [
"def",
"get_filelikeobject",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
")",
"->",
"BinaryIO",
":",
"if",
"not",
"filename",
"and",
"not",
"blob",
":",
"raise",
"ValueError",
"(",
"\"no filename and no blob\"",
")",
"... | Open a file-like object.
Guard the use of this function with ``with``.
Args:
filename: for specifying via a filename
blob: for specifying via an in-memory ``bytes`` object
Returns:
a :class:`BinaryIO` object | [
"Open",
"a",
"file",
"-",
"like",
"object",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L272-L293 | train | 53,225 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | get_file_contents | def get_file_contents(filename: str = None, blob: bytes = None) -> bytes:
"""
Returns the binary contents of a file, or of a BLOB.
"""
if not filename and not blob:
raise ValueError("no filename and no blob")
if filename and blob:
raise ValueError("specify either filename or blob")
if blob:
return blob
with open(filename, 'rb') as f:
return f.read() | python | def get_file_contents(filename: str = None, blob: bytes = None) -> bytes:
"""
Returns the binary contents of a file, or of a BLOB.
"""
if not filename and not blob:
raise ValueError("no filename and no blob")
if filename and blob:
raise ValueError("specify either filename or blob")
if blob:
return blob
with open(filename, 'rb') as f:
return f.read() | [
"def",
"get_file_contents",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
")",
"->",
"bytes",
":",
"if",
"not",
"filename",
"and",
"not",
"blob",
":",
"raise",
"ValueError",
"(",
"\"no filename and no blob\"",
")",
"if",... | Returns the binary contents of a file, or of a BLOB. | [
"Returns",
"the",
"binary",
"contents",
"of",
"a",
"file",
"or",
"of",
"a",
"BLOB",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L297-L308 | train | 53,226 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | get_chardet_encoding | def get_chardet_encoding(binary_contents: bytes) -> Optional[str]:
"""
Guess the character set encoding of the specified ``binary_contents``.
"""
if not binary_contents:
return None
if chardet is None or UniversalDetector is None:
log.warning("chardet not installed; limits detection of encodings")
return None
# METHOD 1
# http://chardet.readthedocs.io/en/latest/
#
# guess = chardet.detect(binary_contents)
#
# METHOD 2: faster with large files
# http://chardet.readthedocs.io/en/latest/
# http://stackoverflow.com/questions/13857856/split-byte-string-into-lines
# noinspection PyCallingNonCallable
detector = UniversalDetector()
for byte_line in binary_contents.split(b"\n"):
detector.feed(byte_line)
if detector.done:
break
guess = detector.result
# Handle result
if 'encoding' not in guess:
log.warning("Something went wrong within chardet; no encoding")
return None
return guess['encoding'] | python | def get_chardet_encoding(binary_contents: bytes) -> Optional[str]:
"""
Guess the character set encoding of the specified ``binary_contents``.
"""
if not binary_contents:
return None
if chardet is None or UniversalDetector is None:
log.warning("chardet not installed; limits detection of encodings")
return None
# METHOD 1
# http://chardet.readthedocs.io/en/latest/
#
# guess = chardet.detect(binary_contents)
#
# METHOD 2: faster with large files
# http://chardet.readthedocs.io/en/latest/
# http://stackoverflow.com/questions/13857856/split-byte-string-into-lines
# noinspection PyCallingNonCallable
detector = UniversalDetector()
for byte_line in binary_contents.split(b"\n"):
detector.feed(byte_line)
if detector.done:
break
guess = detector.result
# Handle result
if 'encoding' not in guess:
log.warning("Something went wrong within chardet; no encoding")
return None
return guess['encoding'] | [
"def",
"get_chardet_encoding",
"(",
"binary_contents",
":",
"bytes",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"not",
"binary_contents",
":",
"return",
"None",
"if",
"chardet",
"is",
"None",
"or",
"UniversalDetector",
"is",
"None",
":",
"log",
".",
... | Guess the character set encoding of the specified ``binary_contents``. | [
"Guess",
"the",
"character",
"set",
"encoding",
"of",
"the",
"specified",
"binary_contents",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L311-L340 | train | 53,227 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | get_file_contents_text | def get_file_contents_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Returns the string contents of a file, or of a BLOB.
"""
binary_contents = get_file_contents(filename=filename, blob=blob)
# 1. Try the encoding the user specified
if config.encoding:
try:
return binary_contents.decode(config.encoding)
except ValueError: # of which UnicodeDecodeError is more specific
# ... https://docs.python.org/3/library/codecs.html
pass
# 2. Try the system encoding
sysdef = sys.getdefaultencoding()
if sysdef != config.encoding:
try:
return binary_contents.decode(sysdef)
except ValueError:
pass
# 3. Try the best guess from chardet
# http://chardet.readthedocs.io/en/latest/usage.html
if chardet:
guess = chardet.detect(binary_contents)
if guess['encoding']:
return binary_contents.decode(guess['encoding'])
raise ValueError("Unknown encoding ({})".format(
"filename={}".format(repr(filename)) if filename else "blob")) | python | def get_file_contents_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Returns the string contents of a file, or of a BLOB.
"""
binary_contents = get_file_contents(filename=filename, blob=blob)
# 1. Try the encoding the user specified
if config.encoding:
try:
return binary_contents.decode(config.encoding)
except ValueError: # of which UnicodeDecodeError is more specific
# ... https://docs.python.org/3/library/codecs.html
pass
# 2. Try the system encoding
sysdef = sys.getdefaultencoding()
if sysdef != config.encoding:
try:
return binary_contents.decode(sysdef)
except ValueError:
pass
# 3. Try the best guess from chardet
# http://chardet.readthedocs.io/en/latest/usage.html
if chardet:
guess = chardet.detect(binary_contents)
if guess['encoding']:
return binary_contents.decode(guess['encoding'])
raise ValueError("Unknown encoding ({})".format(
"filename={}".format(repr(filename)) if filename else "blob")) | [
"def",
"get_file_contents_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"binary_contents",
"=",
"get_file_contents",
"(",
"fil... | Returns the string contents of a file, or of a BLOB. | [
"Returns",
"the",
"string",
"contents",
"of",
"a",
"file",
"or",
"of",
"a",
"BLOB",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L343-L371 | train | 53,228 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | get_cmd_output | def get_cmd_output(*args, encoding: str = SYS_ENCODING) -> str:
"""
Returns text output of a command.
"""
log.debug("get_cmd_output(): args = {!r}", args)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.decode(encoding, errors='ignore') | python | def get_cmd_output(*args, encoding: str = SYS_ENCODING) -> str:
"""
Returns text output of a command.
"""
log.debug("get_cmd_output(): args = {!r}", args)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.decode(encoding, errors='ignore') | [
"def",
"get_cmd_output",
"(",
"*",
"args",
",",
"encoding",
":",
"str",
"=",
"SYS_ENCODING",
")",
"->",
"str",
":",
"log",
".",
"debug",
"(",
"\"get_cmd_output(): args = {!r}\"",
",",
"args",
")",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"... | Returns text output of a command. | [
"Returns",
"text",
"output",
"of",
"a",
"command",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L374-L381 | train | 53,229 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | get_cmd_output_from_stdin | def get_cmd_output_from_stdin(stdint_content_binary: bytes,
*args, encoding: str = SYS_ENCODING) -> str:
"""
Returns text output of a command, passing binary data in via stdin.
"""
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate(input=stdint_content_binary)
return stdout.decode(encoding, errors='ignore') | python | def get_cmd_output_from_stdin(stdint_content_binary: bytes,
*args, encoding: str = SYS_ENCODING) -> str:
"""
Returns text output of a command, passing binary data in via stdin.
"""
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout, stderr = p.communicate(input=stdint_content_binary)
return stdout.decode(encoding, errors='ignore') | [
"def",
"get_cmd_output_from_stdin",
"(",
"stdint_content_binary",
":",
"bytes",
",",
"*",
"args",
",",
"encoding",
":",
"str",
"=",
"SYS_ENCODING",
")",
"->",
"str",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdin",
"=",
"subprocess",
"... | Returns text output of a command, passing binary data in via stdin. | [
"Returns",
"text",
"output",
"of",
"a",
"command",
"passing",
"binary",
"data",
"in",
"via",
"stdin",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L384-L391 | train | 53,230 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_pdf_to_txt | def convert_pdf_to_txt(filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a PDF file to text.
Pass either a filename or a binary object.
"""
pdftotext = tools['pdftotext']
if pdftotext: # External command method
if filename:
return get_cmd_output(pdftotext, filename, '-')
else:
return get_cmd_output_from_stdin(blob, pdftotext, '-', '-')
elif pdfminer: # Memory-hogging method
with get_filelikeobject(filename, blob) as fp:
rsrcmgr = pdfminer.pdfinterp.PDFResourceManager()
retstr = StringIO()
codec = ENCODING
laparams = pdfminer.layout.LAParams()
device = pdfminer.converter.TextConverter(
rsrcmgr, retstr, codec=codec, laparams=laparams)
interpreter = pdfminer.pdfinterp.PDFPageInterpreter(rsrcmgr,
device)
password = ""
maxpages = 0
caching = True
pagenos = set()
for page in pdfminer.pdfpage.PDFPage.get_pages(
fp, pagenos, maxpages=maxpages, password=password,
caching=caching, check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue().decode(ENCODING)
return text
else:
raise AssertionError("No PDF-reading tool available") | python | def convert_pdf_to_txt(filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a PDF file to text.
Pass either a filename or a binary object.
"""
pdftotext = tools['pdftotext']
if pdftotext: # External command method
if filename:
return get_cmd_output(pdftotext, filename, '-')
else:
return get_cmd_output_from_stdin(blob, pdftotext, '-', '-')
elif pdfminer: # Memory-hogging method
with get_filelikeobject(filename, blob) as fp:
rsrcmgr = pdfminer.pdfinterp.PDFResourceManager()
retstr = StringIO()
codec = ENCODING
laparams = pdfminer.layout.LAParams()
device = pdfminer.converter.TextConverter(
rsrcmgr, retstr, codec=codec, laparams=laparams)
interpreter = pdfminer.pdfinterp.PDFPageInterpreter(rsrcmgr,
device)
password = ""
maxpages = 0
caching = True
pagenos = set()
for page in pdfminer.pdfpage.PDFPage.get_pages(
fp, pagenos, maxpages=maxpages, password=password,
caching=caching, check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue().decode(ENCODING)
return text
else:
raise AssertionError("No PDF-reading tool available") | [
"def",
"convert_pdf_to_txt",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"pdftotext",
"=",
"tools",
"[",
"'pdftotext'",
"]",
"i... | Converts a PDF file to text.
Pass either a filename or a binary object. | [
"Converts",
"a",
"PDF",
"file",
"to",
"text",
".",
"Pass",
"either",
"a",
"filename",
"or",
"a",
"binary",
"object",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L399-L432 | train | 53,231 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | availability_pdf | def availability_pdf() -> bool:
"""
Is a PDF-to-text tool available?
"""
pdftotext = tools['pdftotext']
if pdftotext:
return True
elif pdfminer:
log.warning("PDF conversion: pdftotext missing; "
"using pdfminer (less efficient)")
return True
else:
return False | python | def availability_pdf() -> bool:
"""
Is a PDF-to-text tool available?
"""
pdftotext = tools['pdftotext']
if pdftotext:
return True
elif pdfminer:
log.warning("PDF conversion: pdftotext missing; "
"using pdfminer (less efficient)")
return True
else:
return False | [
"def",
"availability_pdf",
"(",
")",
"->",
"bool",
":",
"pdftotext",
"=",
"tools",
"[",
"'pdftotext'",
"]",
"if",
"pdftotext",
":",
"return",
"True",
"elif",
"pdfminer",
":",
"log",
".",
"warning",
"(",
"\"PDF conversion: pdftotext missing; \"",
"\"using pdfminer ... | Is a PDF-to-text tool available? | [
"Is",
"a",
"PDF",
"-",
"to",
"-",
"text",
"tool",
"available?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L435-L447 | train | 53,232 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | docx_text_from_xml | def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str:
"""
Converts an XML tree of a DOCX file to string contents.
Args:
xml: raw XML text
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
"""
root = ElementTree.fromstring(xml)
return docx_text_from_xml_node(root, 0, config) | python | def docx_text_from_xml(xml: str, config: TextProcessingConfig) -> str:
"""
Converts an XML tree of a DOCX file to string contents.
Args:
xml: raw XML text
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
"""
root = ElementTree.fromstring(xml)
return docx_text_from_xml_node(root, 0, config) | [
"def",
"docx_text_from_xml",
"(",
"xml",
":",
"str",
",",
"config",
":",
"TextProcessingConfig",
")",
"->",
"str",
":",
"root",
"=",
"ElementTree",
".",
"fromstring",
"(",
"xml",
")",
"return",
"docx_text_from_xml_node",
"(",
"root",
",",
"0",
",",
"config",... | Converts an XML tree of a DOCX file to string contents.
Args:
xml: raw XML text
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string | [
"Converts",
"an",
"XML",
"tree",
"of",
"a",
"DOCX",
"file",
"to",
"string",
"contents",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L508-L520 | train | 53,233 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | docx_text_from_xml_node | def docx_text_from_xml_node(node: ElementTree.Element,
level: int,
config: TextProcessingConfig) -> str:
"""
Returns text from an XML node within a DOCX file.
Args:
node: an XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
"""
text = ''
# log.debug("Level {}, tag {}", level, node.tag)
if node.tag == DOCX_TEXT:
text += node.text or ''
elif node.tag == DOCX_TAB:
text += '\t'
elif node.tag in DOCX_NEWLINES:
text += '\n'
elif node.tag == DOCX_NEWPARA:
text += '\n\n'
if node.tag == DOCX_TABLE:
text += '\n\n' + docx_table_from_xml_node(node, level, config)
else:
for child in node:
text += docx_text_from_xml_node(child, level + 1, config)
return text | python | def docx_text_from_xml_node(node: ElementTree.Element,
level: int,
config: TextProcessingConfig) -> str:
"""
Returns text from an XML node within a DOCX file.
Args:
node: an XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string
"""
text = ''
# log.debug("Level {}, tag {}", level, node.tag)
if node.tag == DOCX_TEXT:
text += node.text or ''
elif node.tag == DOCX_TAB:
text += '\t'
elif node.tag in DOCX_NEWLINES:
text += '\n'
elif node.tag == DOCX_NEWPARA:
text += '\n\n'
if node.tag == DOCX_TABLE:
text += '\n\n' + docx_table_from_xml_node(node, level, config)
else:
for child in node:
text += docx_text_from_xml_node(child, level + 1, config)
return text | [
"def",
"docx_text_from_xml_node",
"(",
"node",
":",
"ElementTree",
".",
"Element",
",",
"level",
":",
"int",
",",
"config",
":",
"TextProcessingConfig",
")",
"->",
"str",
":",
"text",
"=",
"''",
"# log.debug(\"Level {}, tag {}\", level, node.tag)",
"if",
"node",
"... | Returns text from an XML node within a DOCX file.
Args:
node: an XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
contents as a string | [
"Returns",
"text",
"from",
"an",
"XML",
"node",
"within",
"a",
"DOCX",
"file",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L523-L555 | train | 53,234 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | docx_table_from_xml_node | def docx_table_from_xml_node(table_node: ElementTree.Element,
level: int,
config: TextProcessingConfig) -> str:
"""
Converts an XML node representing a DOCX table into a textual
representation.
Args:
table_node: XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
string representation
"""
table = CustomDocxTable()
for row_node in table_node:
if row_node.tag != DOCX_TABLE_ROW:
continue
table.new_row()
for cell_node in row_node:
if cell_node.tag != DOCX_TABLE_CELL:
continue
table.new_cell()
for para_node in cell_node:
text = docx_text_from_xml_node(para_node, level, config)
if text:
table.add_paragraph(text)
return docx_process_table(table, config) | python | def docx_table_from_xml_node(table_node: ElementTree.Element,
level: int,
config: TextProcessingConfig) -> str:
"""
Converts an XML node representing a DOCX table into a textual
representation.
Args:
table_node: XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
string representation
"""
table = CustomDocxTable()
for row_node in table_node:
if row_node.tag != DOCX_TABLE_ROW:
continue
table.new_row()
for cell_node in row_node:
if cell_node.tag != DOCX_TABLE_CELL:
continue
table.new_cell()
for para_node in cell_node:
text = docx_text_from_xml_node(para_node, level, config)
if text:
table.add_paragraph(text)
return docx_process_table(table, config) | [
"def",
"docx_table_from_xml_node",
"(",
"table_node",
":",
"ElementTree",
".",
"Element",
",",
"level",
":",
"int",
",",
"config",
":",
"TextProcessingConfig",
")",
"->",
"str",
":",
"table",
"=",
"CustomDocxTable",
"(",
")",
"for",
"row_node",
"in",
"table_no... | Converts an XML node representing a DOCX table into a textual
representation.
Args:
table_node: XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
string representation | [
"Converts",
"an",
"XML",
"node",
"representing",
"a",
"DOCX",
"table",
"into",
"a",
"textual",
"representation",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L630-L660 | train | 53,235 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | docx_process_simple_text | def docx_process_simple_text(text: str, width: int) -> str:
"""
Word-wraps text.
Args:
text: text to process
width: width to word-wrap to (or 0 to skip word wrapping)
Returns:
wrapped text
"""
if width:
return '\n'.join(textwrap.wrap(text, width=width))
else:
return text | python | def docx_process_simple_text(text: str, width: int) -> str:
"""
Word-wraps text.
Args:
text: text to process
width: width to word-wrap to (or 0 to skip word wrapping)
Returns:
wrapped text
"""
if width:
return '\n'.join(textwrap.wrap(text, width=width))
else:
return text | [
"def",
"docx_process_simple_text",
"(",
"text",
":",
"str",
",",
"width",
":",
"int",
")",
"->",
"str",
":",
"if",
"width",
":",
"return",
"'\\n'",
".",
"join",
"(",
"textwrap",
".",
"wrap",
"(",
"text",
",",
"width",
"=",
"width",
")",
")",
"else",
... | Word-wraps text.
Args:
text: text to process
width: width to word-wrap to (or 0 to skip word wrapping)
Returns:
wrapped text | [
"Word",
"-",
"wraps",
"text",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L667-L681 | train | 53,236 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | docx_process_table | def docx_process_table(table: DOCX_TABLE_TYPE,
config: TextProcessingConfig) -> str:
"""
Converts a DOCX table to text.
Structure representing a DOCX table:
.. code-block:: none
table
.rows[]
.cells[]
.paragraphs[]
.text
That's the structure of a :class:`docx.table.Table` object, but also of our
homebrew creation, :class:`CustomDocxTable`.
The ``plain`` option optimizes for natural language processing, by:
- removing vertical lines:
.. code-block:: none
+-------------+-------------+
| AAA AAA | BBB BBB |
| AAA AAA | BBB BBB |
+-------------+-------------+
becomes
.. code-block:: none
-----------------------------
AAA AAA BBB BBB
AAA AAA BBB BBB
-----------------------------
- and offsetting cells:
.. code-block:: none
AAA AAA BBB BBB CCC CCC
AAA AAA BBB BBB CCC CCC
becomes
.. code-block:: none
AAA AAA
AAA AAA
BBB BBB
BBB BBB
CCC CCC
CCC CCC
- Note also that the grids in DOCX files can have varying number of cells
per row, e.g.
.. code-block:: none
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 1 | 2 |
+---+---+
"""
def get_cell_text(cell_) -> str:
cellparagraphs = [paragraph.text.strip()
for paragraph in cell_.paragraphs]
cellparagraphs = [x for x in cellparagraphs if x]
return '\n\n'.join(cellparagraphs)
ncols = 1
# noinspection PyTypeChecker
for row in table.rows:
ncols = max(ncols, len(row.cells))
pt = prettytable.PrettyTable(
field_names=list(range(ncols)),
encoding=ENCODING,
header=False,
border=True,
hrules=prettytable.ALL,
vrules=prettytable.NONE if config.plain else prettytable.ALL,
)
pt.align = 'l'
pt.valign = 't'
pt.max_width = max(config.width // ncols, config.min_col_width)
if config.plain:
# noinspection PyTypeChecker
for row in table.rows:
for i, cell in enumerate(row.cells):
n_before = i
n_after = ncols - i - 1
# ... use ncols, not len(row.cells), since "cells per row" is
# not constant, but prettytable wants a fixed number.
# (changed in v0.2.8)
ptrow = (
[''] * n_before +
[get_cell_text(cell)] +
[''] * n_after
)
assert(len(ptrow) == ncols)
pt.add_row(ptrow)
else:
# noinspection PyTypeChecker
for row in table.rows:
ptrow = [] # type: List[str]
# noinspection PyTypeChecker
for cell in row.cells:
ptrow.append(get_cell_text(cell))
ptrow += [''] * (ncols - len(ptrow)) # added in v0.2.8
assert (len(ptrow) == ncols)
pt.add_row(ptrow)
return pt.get_string() | python | def docx_process_table(table: DOCX_TABLE_TYPE,
config: TextProcessingConfig) -> str:
"""
Converts a DOCX table to text.
Structure representing a DOCX table:
.. code-block:: none
table
.rows[]
.cells[]
.paragraphs[]
.text
That's the structure of a :class:`docx.table.Table` object, but also of our
homebrew creation, :class:`CustomDocxTable`.
The ``plain`` option optimizes for natural language processing, by:
- removing vertical lines:
.. code-block:: none
+-------------+-------------+
| AAA AAA | BBB BBB |
| AAA AAA | BBB BBB |
+-------------+-------------+
becomes
.. code-block:: none
-----------------------------
AAA AAA BBB BBB
AAA AAA BBB BBB
-----------------------------
- and offsetting cells:
.. code-block:: none
AAA AAA BBB BBB CCC CCC
AAA AAA BBB BBB CCC CCC
becomes
.. code-block:: none
AAA AAA
AAA AAA
BBB BBB
BBB BBB
CCC CCC
CCC CCC
- Note also that the grids in DOCX files can have varying number of cells
per row, e.g.
.. code-block:: none
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 1 | 2 |
+---+---+
"""
def get_cell_text(cell_) -> str:
cellparagraphs = [paragraph.text.strip()
for paragraph in cell_.paragraphs]
cellparagraphs = [x for x in cellparagraphs if x]
return '\n\n'.join(cellparagraphs)
ncols = 1
# noinspection PyTypeChecker
for row in table.rows:
ncols = max(ncols, len(row.cells))
pt = prettytable.PrettyTable(
field_names=list(range(ncols)),
encoding=ENCODING,
header=False,
border=True,
hrules=prettytable.ALL,
vrules=prettytable.NONE if config.plain else prettytable.ALL,
)
pt.align = 'l'
pt.valign = 't'
pt.max_width = max(config.width // ncols, config.min_col_width)
if config.plain:
# noinspection PyTypeChecker
for row in table.rows:
for i, cell in enumerate(row.cells):
n_before = i
n_after = ncols - i - 1
# ... use ncols, not len(row.cells), since "cells per row" is
# not constant, but prettytable wants a fixed number.
# (changed in v0.2.8)
ptrow = (
[''] * n_before +
[get_cell_text(cell)] +
[''] * n_after
)
assert(len(ptrow) == ncols)
pt.add_row(ptrow)
else:
# noinspection PyTypeChecker
for row in table.rows:
ptrow = [] # type: List[str]
# noinspection PyTypeChecker
for cell in row.cells:
ptrow.append(get_cell_text(cell))
ptrow += [''] * (ncols - len(ptrow)) # added in v0.2.8
assert (len(ptrow) == ncols)
pt.add_row(ptrow)
return pt.get_string() | [
"def",
"docx_process_table",
"(",
"table",
":",
"DOCX_TABLE_TYPE",
",",
"config",
":",
"TextProcessingConfig",
")",
"->",
"str",
":",
"def",
"get_cell_text",
"(",
"cell_",
")",
"->",
"str",
":",
"cellparagraphs",
"=",
"[",
"paragraph",
".",
"text",
".",
"str... | Converts a DOCX table to text.
Structure representing a DOCX table:
.. code-block:: none
table
.rows[]
.cells[]
.paragraphs[]
.text
That's the structure of a :class:`docx.table.Table` object, but also of our
homebrew creation, :class:`CustomDocxTable`.
The ``plain`` option optimizes for natural language processing, by:
- removing vertical lines:
.. code-block:: none
+-------------+-------------+
| AAA AAA | BBB BBB |
| AAA AAA | BBB BBB |
+-------------+-------------+
becomes
.. code-block:: none
-----------------------------
AAA AAA BBB BBB
AAA AAA BBB BBB
-----------------------------
- and offsetting cells:
.. code-block:: none
AAA AAA BBB BBB CCC CCC
AAA AAA BBB BBB CCC CCC
becomes
.. code-block:: none
AAA AAA
AAA AAA
BBB BBB
BBB BBB
CCC CCC
CCC CCC
- Note also that the grids in DOCX files can have varying number of cells
per row, e.g.
.. code-block:: none
+---+---+---+
| 1 | 2 | 3 |
+---+---+---+
| 1 | 2 |
+---+---+ | [
"Converts",
"a",
"DOCX",
"table",
"to",
"text",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L684-L800 | train | 53,237 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | docx_docx_iter_block_items | def docx_docx_iter_block_items(parent: DOCX_CONTAINER_TYPE) \
-> Iterator[DOCX_BLOCK_ITEM_TYPE]:
# only called if docx loaded
"""
Iterate through items of a DOCX file.
See https://github.com/python-openxml/python-docx/issues/40.
Yield each paragraph and table child within ``parent``, in document order.
Each returned value is an instance of either :class:`Table` or
:class:`Paragraph`. ``parent`` would most commonly be a reference to a main
:class:`Document` object, but also works for a :class:`_Cell` object, which
itself can contain paragraphs and tables.
NOTE: uses internals of the ``python-docx`` (``docx``) library; subject to
change; this version works with ``docx==0.8.5``.
"""
if isinstance(parent, docx.document.Document):
parent_elm = parent.element.body
elif isinstance(parent, docx.table._Cell):
parent_elm = parent._tc
else:
raise ValueError("something's not right")
for child in parent_elm.iterchildren():
if isinstance(child, docx.oxml.text.paragraph.CT_P):
yield docx.text.paragraph.Paragraph(child, parent)
elif isinstance(child, docx.oxml.table.CT_Tbl):
yield docx.table.Table(child, parent) | python | def docx_docx_iter_block_items(parent: DOCX_CONTAINER_TYPE) \
-> Iterator[DOCX_BLOCK_ITEM_TYPE]:
# only called if docx loaded
"""
Iterate through items of a DOCX file.
See https://github.com/python-openxml/python-docx/issues/40.
Yield each paragraph and table child within ``parent``, in document order.
Each returned value is an instance of either :class:`Table` or
:class:`Paragraph`. ``parent`` would most commonly be a reference to a main
:class:`Document` object, but also works for a :class:`_Cell` object, which
itself can contain paragraphs and tables.
NOTE: uses internals of the ``python-docx`` (``docx``) library; subject to
change; this version works with ``docx==0.8.5``.
"""
if isinstance(parent, docx.document.Document):
parent_elm = parent.element.body
elif isinstance(parent, docx.table._Cell):
parent_elm = parent._tc
else:
raise ValueError("something's not right")
for child in parent_elm.iterchildren():
if isinstance(child, docx.oxml.text.paragraph.CT_P):
yield docx.text.paragraph.Paragraph(child, parent)
elif isinstance(child, docx.oxml.table.CT_Tbl):
yield docx.table.Table(child, parent) | [
"def",
"docx_docx_iter_block_items",
"(",
"parent",
":",
"DOCX_CONTAINER_TYPE",
")",
"->",
"Iterator",
"[",
"DOCX_BLOCK_ITEM_TYPE",
"]",
":",
"# only called if docx loaded",
"if",
"isinstance",
"(",
"parent",
",",
"docx",
".",
"document",
".",
"Document",
")",
":",
... | Iterate through items of a DOCX file.
See https://github.com/python-openxml/python-docx/issues/40.
Yield each paragraph and table child within ``parent``, in document order.
Each returned value is an instance of either :class:`Table` or
:class:`Paragraph`. ``parent`` would most commonly be a reference to a main
:class:`Document` object, but also works for a :class:`_Cell` object, which
itself can contain paragraphs and tables.
NOTE: uses internals of the ``python-docx`` (``docx``) library; subject to
change; this version works with ``docx==0.8.5``. | [
"Iterate",
"through",
"items",
"of",
"a",
"DOCX",
"file",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L808-L836 | train | 53,238 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | docx_docx_gen_text | def docx_docx_gen_text(doc: DOCX_DOCUMENT_TYPE,
config: TextProcessingConfig) -> Iterator[str]:
# only called if docx loaded
"""
Iterate through a DOCX file and yield text.
Args:
doc: DOCX document to process
config: :class:`TextProcessingConfig` control object
Yields:
pieces of text (paragraphs)
"""
if in_order:
for thing in docx_docx_iter_block_items(doc):
if isinstance(thing, docx.text.paragraph.Paragraph):
yield docx_process_simple_text(thing.text, config.width)
elif isinstance(thing, docx.table.Table):
yield docx_process_table(thing, config)
else:
for paragraph in doc.paragraphs:
yield docx_process_simple_text(paragraph.text, config.width)
for table in doc.tables:
yield docx_process_table(table, config) | python | def docx_docx_gen_text(doc: DOCX_DOCUMENT_TYPE,
config: TextProcessingConfig) -> Iterator[str]:
# only called if docx loaded
"""
Iterate through a DOCX file and yield text.
Args:
doc: DOCX document to process
config: :class:`TextProcessingConfig` control object
Yields:
pieces of text (paragraphs)
"""
if in_order:
for thing in docx_docx_iter_block_items(doc):
if isinstance(thing, docx.text.paragraph.Paragraph):
yield docx_process_simple_text(thing.text, config.width)
elif isinstance(thing, docx.table.Table):
yield docx_process_table(thing, config)
else:
for paragraph in doc.paragraphs:
yield docx_process_simple_text(paragraph.text, config.width)
for table in doc.tables:
yield docx_process_table(table, config) | [
"def",
"docx_docx_gen_text",
"(",
"doc",
":",
"DOCX_DOCUMENT_TYPE",
",",
"config",
":",
"TextProcessingConfig",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"# only called if docx loaded",
"if",
"in_order",
":",
"for",
"thing",
"in",
"docx_docx_iter_block_items",
"(... | Iterate through a DOCX file and yield text.
Args:
doc: DOCX document to process
config: :class:`TextProcessingConfig` control object
Yields:
pieces of text (paragraphs) | [
"Iterate",
"through",
"a",
"DOCX",
"file",
"and",
"yield",
"text",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L840-L864 | train | 53,239 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_docx_to_text | def convert_docx_to_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to process
config: :class:`TextProcessingConfig` control object
Returns:
text contents
Notes:
- Old ``docx`` (https://pypi.python.org/pypi/python-docx) has been
superseded (see https://github.com/mikemaccana/python-docx).
- ``docx.opendocx(file)`` uses :class:`zipfile.ZipFile`, which can take
either a filename or a file-like object
(https://docs.python.org/2/library/zipfile.html).
- Method was:
.. code-block:: python
with get_filelikeobject(filename, blob) as fp:
document = docx.opendocx(fp)
paratextlist = docx.getdocumenttext(document)
return '\n\n'.join(paratextlist)
- Newer ``docx`` is python-docx
- https://pypi.python.org/pypi/python-docx
- https://python-docx.readthedocs.org/en/latest/
- http://stackoverflow.com/questions/25228106
However, it uses ``lxml``, which has C dependencies, so it doesn't always
install properly on e.g. bare Windows machines.
PERFORMANCE of my method:
- nice table formatting
- but tables grouped at end, not in sensible places
- can iterate via ``doc.paragraphs`` and ``doc.tables`` but not in
true document order, it seems
- others have noted this too:
- https://github.com/python-openxml/python-docx/issues/40
- https://github.com/deanmalmgren/textract/pull/92
- ``docx2txt`` is at https://pypi.python.org/pypi/docx2txt/0.6; this is
pure Python. Its command-line function appears to be for Python 2 only
(2016-04-21: crashes under Python 3; is due to an encoding bug). However,
it seems fine as a library. It doesn't handle in-memory blobs properly,
though, so we need to extend it.
PERFORMANCE OF ITS ``process()`` function:
- all text comes out
- table text is in a sensible place
- table formatting is lost.
- Other manual methods (not yet implemented):
http://etienned.github.io/posts/extract-text-from-word-docx-simply/.
Looks like it won't deal with header stuff (etc.) that ``docx2txt``
handles.
- Upshot: we need a DIY version.
- See also this "compile lots of techniques" libraries, which has C
dependencies: http://textract.readthedocs.org/en/latest/
"""
if True:
text = ''
with get_filelikeobject(filename, blob) as fp:
for xml in gen_xml_files_from_docx(fp):
text += docx_text_from_xml(xml, config)
return text | python | def convert_docx_to_text(
filename: str = None, blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to process
config: :class:`TextProcessingConfig` control object
Returns:
text contents
Notes:
- Old ``docx`` (https://pypi.python.org/pypi/python-docx) has been
superseded (see https://github.com/mikemaccana/python-docx).
- ``docx.opendocx(file)`` uses :class:`zipfile.ZipFile`, which can take
either a filename or a file-like object
(https://docs.python.org/2/library/zipfile.html).
- Method was:
.. code-block:: python
with get_filelikeobject(filename, blob) as fp:
document = docx.opendocx(fp)
paratextlist = docx.getdocumenttext(document)
return '\n\n'.join(paratextlist)
- Newer ``docx`` is python-docx
- https://pypi.python.org/pypi/python-docx
- https://python-docx.readthedocs.org/en/latest/
- http://stackoverflow.com/questions/25228106
However, it uses ``lxml``, which has C dependencies, so it doesn't always
install properly on e.g. bare Windows machines.
PERFORMANCE of my method:
- nice table formatting
- but tables grouped at end, not in sensible places
- can iterate via ``doc.paragraphs`` and ``doc.tables`` but not in
true document order, it seems
- others have noted this too:
- https://github.com/python-openxml/python-docx/issues/40
- https://github.com/deanmalmgren/textract/pull/92
- ``docx2txt`` is at https://pypi.python.org/pypi/docx2txt/0.6; this is
pure Python. Its command-line function appears to be for Python 2 only
(2016-04-21: crashes under Python 3; is due to an encoding bug). However,
it seems fine as a library. It doesn't handle in-memory blobs properly,
though, so we need to extend it.
PERFORMANCE OF ITS ``process()`` function:
- all text comes out
- table text is in a sensible place
- table formatting is lost.
- Other manual methods (not yet implemented):
http://etienned.github.io/posts/extract-text-from-word-docx-simply/.
Looks like it won't deal with header stuff (etc.) that ``docx2txt``
handles.
- Upshot: we need a DIY version.
- See also this "compile lots of techniques" libraries, which has C
dependencies: http://textract.readthedocs.org/en/latest/
"""
if True:
text = ''
with get_filelikeobject(filename, blob) as fp:
for xml in gen_xml_files_from_docx(fp):
text += docx_text_from_xml(xml, config)
return text | [
"def",
"convert_docx_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"if",
"True",
":",
"text",
"=",
"''",
"with",
"get... | Converts a DOCX file to text.
Pass either a filename or a binary object.
Args:
filename: filename to process
blob: binary ``bytes`` object to process
config: :class:`TextProcessingConfig` control object
Returns:
text contents
Notes:
- Old ``docx`` (https://pypi.python.org/pypi/python-docx) has been
superseded (see https://github.com/mikemaccana/python-docx).
- ``docx.opendocx(file)`` uses :class:`zipfile.ZipFile`, which can take
either a filename or a file-like object
(https://docs.python.org/2/library/zipfile.html).
- Method was:
.. code-block:: python
with get_filelikeobject(filename, blob) as fp:
document = docx.opendocx(fp)
paratextlist = docx.getdocumenttext(document)
return '\n\n'.join(paratextlist)
- Newer ``docx`` is python-docx
- https://pypi.python.org/pypi/python-docx
- https://python-docx.readthedocs.org/en/latest/
- http://stackoverflow.com/questions/25228106
However, it uses ``lxml``, which has C dependencies, so it doesn't always
install properly on e.g. bare Windows machines.
PERFORMANCE of my method:
- nice table formatting
- but tables grouped at end, not in sensible places
- can iterate via ``doc.paragraphs`` and ``doc.tables`` but not in
true document order, it seems
- others have noted this too:
- https://github.com/python-openxml/python-docx/issues/40
- https://github.com/deanmalmgren/textract/pull/92
- ``docx2txt`` is at https://pypi.python.org/pypi/docx2txt/0.6; this is
pure Python. Its command-line function appears to be for Python 2 only
(2016-04-21: crashes under Python 3; is due to an encoding bug). However,
it seems fine as a library. It doesn't handle in-memory blobs properly,
though, so we need to extend it.
PERFORMANCE OF ITS ``process()`` function:
- all text comes out
- table text is in a sensible place
- table formatting is lost.
- Other manual methods (not yet implemented):
http://etienned.github.io/posts/extract-text-from-word-docx-simply/.
Looks like it won't deal with header stuff (etc.) that ``docx2txt``
handles.
- Upshot: we need a DIY version.
- See also this "compile lots of techniques" libraries, which has C
dependencies: http://textract.readthedocs.org/en/latest/ | [
"Converts",
"a",
"DOCX",
"file",
"to",
"text",
".",
"Pass",
"either",
"a",
"filename",
"or",
"a",
"binary",
"object",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L868-L951 | train | 53,240 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_odt_to_text | def convert_odt_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts an OpenOffice ODT file to text.
Pass either a filename or a binary object.
"""
# We can't use exactly the same method as for DOCX files, using docx:
# sometimes that works, but sometimes it falls over with:
# KeyError: "There is no item named 'word/document.xml' in the archive"
with get_filelikeobject(filename, blob) as fp:
z = zipfile.ZipFile(fp)
tree = ElementTree.fromstring(z.read('content.xml'))
# ... may raise zipfile.BadZipfile
textlist = [] # type: List[str]
for element in tree.iter():
if element.text:
textlist.append(element.text.strip())
return '\n\n'.join(textlist) | python | def convert_odt_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts an OpenOffice ODT file to text.
Pass either a filename or a binary object.
"""
# We can't use exactly the same method as for DOCX files, using docx:
# sometimes that works, but sometimes it falls over with:
# KeyError: "There is no item named 'word/document.xml' in the archive"
with get_filelikeobject(filename, blob) as fp:
z = zipfile.ZipFile(fp)
tree = ElementTree.fromstring(z.read('content.xml'))
# ... may raise zipfile.BadZipfile
textlist = [] # type: List[str]
for element in tree.iter():
if element.text:
textlist.append(element.text.strip())
return '\n\n'.join(textlist) | [
"def",
"convert_odt_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"# We can't use exactly the same method as for DOCX files, using ... | Converts an OpenOffice ODT file to text.
Pass either a filename or a binary object. | [
"Converts",
"an",
"OpenOffice",
"ODT",
"file",
"to",
"text",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L972-L991 | train | 53,241 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_html_to_text | def convert_html_to_text(
filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts HTML to text.
"""
with get_filelikeobject(filename, blob) as fp:
soup = bs4.BeautifulSoup(fp)
return soup.get_text() | python | def convert_html_to_text(
filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts HTML to text.
"""
with get_filelikeobject(filename, blob) as fp:
soup = bs4.BeautifulSoup(fp)
return soup.get_text() | [
"def",
"convert_html_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"with",
"get_filelikeobject",
"(",
"filename",
",",
"b... | Converts HTML to text. | [
"Converts",
"HTML",
"to",
"text",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L999-L1008 | train | 53,242 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_xml_to_text | def convert_xml_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts XML to text.
"""
with get_filelikeobject(filename, blob) as fp:
soup = bs4.BeautifulStoneSoup(fp)
return soup.get_text() | python | def convert_xml_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts XML to text.
"""
with get_filelikeobject(filename, blob) as fp:
soup = bs4.BeautifulStoneSoup(fp)
return soup.get_text() | [
"def",
"convert_xml_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"with",
"get_filelikeobject",
"(",
"filename",
",",
"bl... | Converts XML to text. | [
"Converts",
"XML",
"to",
"text",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1016-L1024 | train | 53,243 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_rtf_to_text | def convert_rtf_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts RTF to text.
"""
unrtf = tools['unrtf']
if unrtf: # Best
args = [unrtf, '--text', '--nopict']
if UNRTF_SUPPORTS_QUIET:
args.append('--quiet')
if filename:
args.append(filename)
return get_cmd_output(*args)
else:
return get_cmd_output_from_stdin(blob, *args)
elif pyth: # Very memory-consuming:
# https://github.com/brendonh/pyth/blob/master/pyth/plugins/rtf15/reader.py # noqa
with get_filelikeobject(filename, blob) as fp:
doc = pyth.plugins.rtf15.reader.Rtf15Reader.read(fp)
return (
pyth.plugins.plaintext.writer.PlaintextWriter.write(doc).getvalue()
)
else:
raise AssertionError("No RTF-reading tool available") | python | def convert_rtf_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts RTF to text.
"""
unrtf = tools['unrtf']
if unrtf: # Best
args = [unrtf, '--text', '--nopict']
if UNRTF_SUPPORTS_QUIET:
args.append('--quiet')
if filename:
args.append(filename)
return get_cmd_output(*args)
else:
return get_cmd_output_from_stdin(blob, *args)
elif pyth: # Very memory-consuming:
# https://github.com/brendonh/pyth/blob/master/pyth/plugins/rtf15/reader.py # noqa
with get_filelikeobject(filename, blob) as fp:
doc = pyth.plugins.rtf15.reader.Rtf15Reader.read(fp)
return (
pyth.plugins.plaintext.writer.PlaintextWriter.write(doc).getvalue()
)
else:
raise AssertionError("No RTF-reading tool available") | [
"def",
"convert_rtf_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"unrtf",
"=",
"tools",
"[",
"'unrtf'",
"]",
"if",
"... | Converts RTF to text. | [
"Converts",
"RTF",
"to",
"text",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1032-L1056 | train | 53,244 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | availability_rtf | def availability_rtf() -> bool:
"""
Is an RTF processor available?
"""
unrtf = tools['unrtf']
if unrtf:
return True
elif pyth:
log.warning("RTF conversion: unrtf missing; "
"using pyth (less efficient)")
return True
else:
return False | python | def availability_rtf() -> bool:
"""
Is an RTF processor available?
"""
unrtf = tools['unrtf']
if unrtf:
return True
elif pyth:
log.warning("RTF conversion: unrtf missing; "
"using pyth (less efficient)")
return True
else:
return False | [
"def",
"availability_rtf",
"(",
")",
"->",
"bool",
":",
"unrtf",
"=",
"tools",
"[",
"'unrtf'",
"]",
"if",
"unrtf",
":",
"return",
"True",
"elif",
"pyth",
":",
"log",
".",
"warning",
"(",
"\"RTF conversion: unrtf missing; \"",
"\"using pyth (less efficient)\"",
"... | Is an RTF processor available? | [
"Is",
"an",
"RTF",
"processor",
"available?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1059-L1071 | train | 53,245 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | convert_doc_to_text | def convert_doc_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts Microsoft Word DOC files to text.
"""
antiword = tools['antiword']
if antiword:
if filename:
return get_cmd_output(antiword, '-w', str(config.width), filename)
else:
return get_cmd_output_from_stdin(blob, antiword, '-w',
str(config.width), '-')
else:
raise AssertionError("No DOC-reading tool available") | python | def convert_doc_to_text(filename: str = None,
blob: bytes = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts Microsoft Word DOC files to text.
"""
antiword = tools['antiword']
if antiword:
if filename:
return get_cmd_output(antiword, '-w', str(config.width), filename)
else:
return get_cmd_output_from_stdin(blob, antiword, '-w',
str(config.width), '-')
else:
raise AssertionError("No DOC-reading tool available") | [
"def",
"convert_doc_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"antiword",
"=",
"tools",
"[",
"'antiword'",
"]",
"if... | Converts Microsoft Word DOC files to text. | [
"Converts",
"Microsoft",
"Word",
"DOC",
"files",
"to",
"text",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1079-L1093 | train | 53,246 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | document_to_text | def document_to_text(filename: str = None,
blob: bytes = None,
extension: str = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a document to text.
This function selects a processor based on the file extension (either from
the filename, or, in the case of a BLOB, the extension specified manually
via the ``extension`` parameter).
Pass either a filename or a binary object.
- Raises an exception for malformed arguments, missing files, bad
filetypes, etc.
- Returns a string if the file was processed (potentially an empty string).
"""
if not filename and not blob:
raise ValueError("document_to_text: no filename and no blob")
if filename and blob:
raise ValueError("document_to_text: specify either filename or blob")
if blob and not extension:
raise ValueError("document_to_text: need extension hint for blob")
if filename:
stub, extension = os.path.splitext(filename)
else:
if extension[0] != ".":
extension = "." + extension
extension = extension.lower()
# Ensure blob is an appropriate type
log.debug(
"filename: {}, blob type: {}, blob length: {}, extension: {}".format(
filename,
type(blob),
len(blob) if blob is not None else None,
extension))
# If we were given a filename and the file doesn't exist, don't bother.
if filename and not os.path.isfile(filename):
raise ValueError("document_to_text: no such file: {!r}".format(
filename))
# Choose method
info = ext_map.get(extension)
if info is None:
log.warning("Unknown filetype: {}; using generic tool", extension)
info = ext_map[None]
func = info[CONVERTER]
return func(filename, blob, config) | python | def document_to_text(filename: str = None,
blob: bytes = None,
extension: str = None,
config: TextProcessingConfig = _DEFAULT_CONFIG) -> str:
"""
Converts a document to text.
This function selects a processor based on the file extension (either from
the filename, or, in the case of a BLOB, the extension specified manually
via the ``extension`` parameter).
Pass either a filename or a binary object.
- Raises an exception for malformed arguments, missing files, bad
filetypes, etc.
- Returns a string if the file was processed (potentially an empty string).
"""
if not filename and not blob:
raise ValueError("document_to_text: no filename and no blob")
if filename and blob:
raise ValueError("document_to_text: specify either filename or blob")
if blob and not extension:
raise ValueError("document_to_text: need extension hint for blob")
if filename:
stub, extension = os.path.splitext(filename)
else:
if extension[0] != ".":
extension = "." + extension
extension = extension.lower()
# Ensure blob is an appropriate type
log.debug(
"filename: {}, blob type: {}, blob length: {}, extension: {}".format(
filename,
type(blob),
len(blob) if blob is not None else None,
extension))
# If we were given a filename and the file doesn't exist, don't bother.
if filename and not os.path.isfile(filename):
raise ValueError("document_to_text: no such file: {!r}".format(
filename))
# Choose method
info = ext_map.get(extension)
if info is None:
log.warning("Unknown filetype: {}; using generic tool", extension)
info = ext_map[None]
func = info[CONVERTER]
return func(filename, blob, config) | [
"def",
"document_to_text",
"(",
"filename",
":",
"str",
"=",
"None",
",",
"blob",
":",
"bytes",
"=",
"None",
",",
"extension",
":",
"str",
"=",
"None",
",",
"config",
":",
"TextProcessingConfig",
"=",
"_DEFAULT_CONFIG",
")",
"->",
"str",
":",
"if",
"not"... | Converts a document to text.
This function selects a processor based on the file extension (either from
the filename, or, in the case of a BLOB, the extension specified manually
via the ``extension`` parameter).
Pass either a filename or a binary object.
- Raises an exception for malformed arguments, missing files, bad
filetypes, etc.
- Returns a string if the file was processed (potentially an empty string). | [
"Converts",
"a",
"document",
"to",
"text",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1211-L1261 | train | 53,247 |
RudolfCardinal/pythonlib | cardinal_pythonlib/extract_text.py | is_text_extractor_available | def is_text_extractor_available(extension: str) -> bool:
"""
Is a text extractor available for the specified extension?
"""
if extension is not None:
extension = extension.lower()
info = ext_map.get(extension)
if info is None:
return False
availability = info[AVAILABILITY]
if type(availability) == bool:
return availability
elif callable(availability):
return availability()
else:
raise ValueError(
"Bad information object for extension: {}".format(extension)) | python | def is_text_extractor_available(extension: str) -> bool:
"""
Is a text extractor available for the specified extension?
"""
if extension is not None:
extension = extension.lower()
info = ext_map.get(extension)
if info is None:
return False
availability = info[AVAILABILITY]
if type(availability) == bool:
return availability
elif callable(availability):
return availability()
else:
raise ValueError(
"Bad information object for extension: {}".format(extension)) | [
"def",
"is_text_extractor_available",
"(",
"extension",
":",
"str",
")",
"->",
"bool",
":",
"if",
"extension",
"is",
"not",
"None",
":",
"extension",
"=",
"extension",
".",
"lower",
"(",
")",
"info",
"=",
"ext_map",
".",
"get",
"(",
"extension",
")",
"if... | Is a text extractor available for the specified extension? | [
"Is",
"a",
"text",
"extractor",
"available",
"for",
"the",
"specified",
"extension?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/extract_text.py#L1264-L1280 | train | 53,248 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | set_verbose_logging | def set_verbose_logging(verbose: bool) -> None:
"""Chooses basic or verbose logging."""
if verbose:
set_loglevel(logging.DEBUG)
else:
set_loglevel(logging.INFO) | python | def set_verbose_logging(verbose: bool) -> None:
"""Chooses basic or verbose logging."""
if verbose:
set_loglevel(logging.DEBUG)
else:
set_loglevel(logging.INFO) | [
"def",
"set_verbose_logging",
"(",
"verbose",
":",
"bool",
")",
"->",
"None",
":",
"if",
"verbose",
":",
"set_loglevel",
"(",
"logging",
".",
"DEBUG",
")",
"else",
":",
"set_loglevel",
"(",
"logging",
".",
"INFO",
")"
] | Chooses basic or verbose logging. | [
"Chooses",
"basic",
"or",
"verbose",
"logging",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L863-L868 | train | 53,249 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | debug_sql | def debug_sql(sql: str, *args: Any) -> None:
"""Writes SQL and arguments to the log."""
log.debug("SQL: %s" % sql)
if args:
log.debug("Args: %r" % args) | python | def debug_sql(sql: str, *args: Any) -> None:
"""Writes SQL and arguments to the log."""
log.debug("SQL: %s" % sql)
if args:
log.debug("Args: %r" % args) | [
"def",
"debug_sql",
"(",
"sql",
":",
"str",
",",
"*",
"args",
":",
"Any",
")",
"->",
"None",
":",
"log",
".",
"debug",
"(",
"\"SQL: %s\"",
"%",
"sql",
")",
"if",
"args",
":",
"log",
".",
"debug",
"(",
"\"Args: %r\"",
"%",
"args",
")"
] | Writes SQL and arguments to the log. | [
"Writes",
"SQL",
"and",
"arguments",
"to",
"the",
"log",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L875-L879 | train | 53,250 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | get_sql_insert | def get_sql_insert(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT statement."""
return (
"INSERT INTO " + delimit(table, delims) +
" (" +
",".join([delimit(x, delims) for x in fieldlist]) +
") VALUES (" +
",".join(["?"] * len(fieldlist)) +
")"
) | python | def get_sql_insert(table: str,
fieldlist: Sequence[str],
delims: Tuple[str, str] = ("", "")) -> str:
"""Returns ?-marked SQL for an INSERT statement."""
return (
"INSERT INTO " + delimit(table, delims) +
" (" +
",".join([delimit(x, delims) for x in fieldlist]) +
") VALUES (" +
",".join(["?"] * len(fieldlist)) +
")"
) | [
"def",
"get_sql_insert",
"(",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"delims",
":",
"Tuple",
"[",
"str",
",",
"str",
"]",
"=",
"(",
"\"\"",
",",
"\"\"",
")",
")",
"->",
"str",
":",
"return",
"(",
"\"INSERT INT... | Returns ?-marked SQL for an INSERT statement. | [
"Returns",
"?",
"-",
"marked",
"SQL",
"for",
"an",
"INSERT",
"statement",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L923-L934 | train | 53,251 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | sql_dequote_string | def sql_dequote_string(s: str) -> str:
"""Reverses sql_quote_string."""
if len(s) < 2:
# Something wrong.
return s
s = s[1:-1] # strip off the surrounding quotes
return s.replace("''", "'") | python | def sql_dequote_string(s: str) -> str:
"""Reverses sql_quote_string."""
if len(s) < 2:
# Something wrong.
return s
s = s[1:-1] # strip off the surrounding quotes
return s.replace("''", "'") | [
"def",
"sql_dequote_string",
"(",
"s",
":",
"str",
")",
"->",
"str",
":",
"if",
"len",
"(",
"s",
")",
"<",
"2",
":",
"# Something wrong.",
"return",
"s",
"s",
"=",
"s",
"[",
"1",
":",
"-",
"1",
"]",
"# strip off the surrounding quotes",
"return",
"s",
... | Reverses sql_quote_string. | [
"Reverses",
"sql_quote_string",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L985-L991 | train | 53,252 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | datetime2literal_rnc | def datetime2literal_rnc(d: datetime.datetime, c: Optional[Dict]) -> str:
"""Format a DateTime object as something MySQL will actually accept."""
# dt = d.strftime("%Y-%m-%d %H:%M:%S")
# ... can fail with e.g.
# ValueError: year=1850 is before 1900; the datetime strftime() methods
# require year >= 1900
# http://stackoverflow.com/questions/10263956
dt = d.isoformat(" ")
# noinspection PyArgumentList
return _mysql.string_literal(dt, c) | python | def datetime2literal_rnc(d: datetime.datetime, c: Optional[Dict]) -> str:
"""Format a DateTime object as something MySQL will actually accept."""
# dt = d.strftime("%Y-%m-%d %H:%M:%S")
# ... can fail with e.g.
# ValueError: year=1850 is before 1900; the datetime strftime() methods
# require year >= 1900
# http://stackoverflow.com/questions/10263956
dt = d.isoformat(" ")
# noinspection PyArgumentList
return _mysql.string_literal(dt, c) | [
"def",
"datetime2literal_rnc",
"(",
"d",
":",
"datetime",
".",
"datetime",
",",
"c",
":",
"Optional",
"[",
"Dict",
"]",
")",
"->",
"str",
":",
"# dt = d.strftime(\"%Y-%m-%d %H:%M:%S\")",
"# ... can fail with e.g.",
"# ValueError: year=1850 is before 1900; the datetime str... | Format a DateTime object as something MySQL will actually accept. | [
"Format",
"a",
"DateTime",
"object",
"as",
"something",
"MySQL",
"will",
"actually",
"accept",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L994-L1003 | train | 53,253 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | assign_from_list | def assign_from_list(obj: T,
fieldlist: Sequence[str],
valuelist: Sequence[any]) -> None:
"""Within "obj", assigns the values from the value list to the fields in
the fieldlist."""
if len(fieldlist) != len(valuelist):
raise AssertionError("assign_from_list: fieldlist and valuelist of "
"different length")
for i in range(len(valuelist)):
setattr(obj, fieldlist[i], valuelist[i]) | python | def assign_from_list(obj: T,
fieldlist: Sequence[str],
valuelist: Sequence[any]) -> None:
"""Within "obj", assigns the values from the value list to the fields in
the fieldlist."""
if len(fieldlist) != len(valuelist):
raise AssertionError("assign_from_list: fieldlist and valuelist of "
"different length")
for i in range(len(valuelist)):
setattr(obj, fieldlist[i], valuelist[i]) | [
"def",
"assign_from_list",
"(",
"obj",
":",
"T",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"valuelist",
":",
"Sequence",
"[",
"any",
"]",
")",
"->",
"None",
":",
"if",
"len",
"(",
"fieldlist",
")",
"!=",
"len",
"(",
"valuelist",
")",
... | Within "obj", assigns the values from the value list to the fields in
the fieldlist. | [
"Within",
"obj",
"assigns",
"the",
"values",
"from",
"the",
"value",
"list",
"to",
"the",
"fields",
"in",
"the",
"fieldlist",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1042-L1051 | train | 53,254 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | blank_object | def blank_object(obj: T, fieldlist: Sequence[str]) -> None:
"""Within "obj", sets all fields in the fieldlist to None."""
for f in fieldlist:
setattr(obj, f, None) | python | def blank_object(obj: T, fieldlist: Sequence[str]) -> None:
"""Within "obj", sets all fields in the fieldlist to None."""
for f in fieldlist:
setattr(obj, f, None) | [
"def",
"blank_object",
"(",
"obj",
":",
"T",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"None",
":",
"for",
"f",
"in",
"fieldlist",
":",
"setattr",
"(",
"obj",
",",
"f",
",",
"None",
")"
] | Within "obj", sets all fields in the fieldlist to None. | [
"Within",
"obj",
"sets",
"all",
"fields",
"in",
"the",
"fieldlist",
"to",
"None",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1087-L1090 | train | 53,255 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | debug_query_result | def debug_query_result(rows: Sequence[Any]) -> None:
"""Writes a query result to the log."""
log.info("Retrieved {} rows", len(rows))
for i in range(len(rows)):
log.info("Row {}: {}", i, rows[i]) | python | def debug_query_result(rows: Sequence[Any]) -> None:
"""Writes a query result to the log."""
log.info("Retrieved {} rows", len(rows))
for i in range(len(rows)):
log.info("Row {}: {}", i, rows[i]) | [
"def",
"debug_query_result",
"(",
"rows",
":",
"Sequence",
"[",
"Any",
"]",
")",
"->",
"None",
":",
"log",
".",
"info",
"(",
"\"Retrieved {} rows\"",
",",
"len",
"(",
"rows",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"rows",
")",
")",
"... | Writes a query result to the log. | [
"Writes",
"a",
"query",
"result",
"to",
"the",
"log",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1093-L1097 | train | 53,256 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | MySQL.is_read_only | def is_read_only(cls,
db: DATABASE_SUPPORTER_FWD_REF,
logger: logging.Logger = None) -> bool:
"""Do we have read-only access?"""
def convert_enums(row_):
# All these columns are of type enum('N', 'Y');
# https://dev.mysql.com/doc/refman/5.0/en/enum.html
return [True if x == 'Y' else (False if x == 'N' else None)
for x in row_]
# 1. Check per-database privileges.
# We don't check SELECT privileges. We're just trying to ensure
# nothing dangerous is present - for ANY database.
# If we get an exception
try:
sql = """
SELECT db,
/* must not have: */
Insert_priv, Update_priv, Delete_priv,
Create_priv, Drop_priv, Index_priv, Alter_priv,
Lock_tables_priv, Create_view_priv,
Create_routine_priv, Alter_routine_priv,
Execute_priv, Event_priv, Trigger_priv
FROM mysql.db
WHERE
CONCAT(user, '@', host) = CURRENT_USER()
"""
rows = db.fetchall(sql)
for row in rows:
dbname = row[0]
prohibited = convert_enums(row[1:])
if any(prohibited):
if logger:
logger.debug(
"MySQL.is_read_only(): FAIL: database privileges "
"wrong: dbname={}, prohibited={}".format(
dbname, prohibited
)
)
return False
except mysql.OperationalError:
# Probably: error 1142, "SELECT command denied to user 'xxx'@'yyy'
# for table 'db'". This would be OK.
pass
# 2. Global privileges, e.g. as held by root
try:
sql = """
SELECT /* must not have: */
Insert_priv, Update_priv, Delete_priv,
Create_priv, Drop_priv,
Reload_priv, Shutdown_priv,
Process_priv, File_priv, Grant_priv,
Index_priv, Alter_priv,
Show_db_priv, Super_priv,
Lock_tables_priv, Execute_priv,
Repl_slave_priv, Repl_client_priv,
Create_view_priv,
Create_routine_priv, Alter_routine_priv,
Create_user_priv,
Event_priv, Trigger_priv,
Create_tablespace_priv
FROM mysql.user
WHERE
CONCAT(user, '@', host) = CURRENT_USER()
"""
rows = db.fetchall(sql)
if not rows or len(rows) > 1:
return False
prohibited = convert_enums(rows[0])
if any(prohibited):
if logger:
logger.debug(
"MySQL.is_read_only(): FAIL: GLOBAL privileges "
"wrong: prohibited={}".format(prohibited))
return False
except mysql.OperationalError:
# Probably: error 1142, "SELECT command denied to user 'xxx'@'yyy'
# for table 'user'". This would be OK.
pass
return True | python | def is_read_only(cls,
db: DATABASE_SUPPORTER_FWD_REF,
logger: logging.Logger = None) -> bool:
"""Do we have read-only access?"""
def convert_enums(row_):
# All these columns are of type enum('N', 'Y');
# https://dev.mysql.com/doc/refman/5.0/en/enum.html
return [True if x == 'Y' else (False if x == 'N' else None)
for x in row_]
# 1. Check per-database privileges.
# We don't check SELECT privileges. We're just trying to ensure
# nothing dangerous is present - for ANY database.
# If we get an exception
try:
sql = """
SELECT db,
/* must not have: */
Insert_priv, Update_priv, Delete_priv,
Create_priv, Drop_priv, Index_priv, Alter_priv,
Lock_tables_priv, Create_view_priv,
Create_routine_priv, Alter_routine_priv,
Execute_priv, Event_priv, Trigger_priv
FROM mysql.db
WHERE
CONCAT(user, '@', host) = CURRENT_USER()
"""
rows = db.fetchall(sql)
for row in rows:
dbname = row[0]
prohibited = convert_enums(row[1:])
if any(prohibited):
if logger:
logger.debug(
"MySQL.is_read_only(): FAIL: database privileges "
"wrong: dbname={}, prohibited={}".format(
dbname, prohibited
)
)
return False
except mysql.OperationalError:
# Probably: error 1142, "SELECT command denied to user 'xxx'@'yyy'
# for table 'db'". This would be OK.
pass
# 2. Global privileges, e.g. as held by root
try:
sql = """
SELECT /* must not have: */
Insert_priv, Update_priv, Delete_priv,
Create_priv, Drop_priv,
Reload_priv, Shutdown_priv,
Process_priv, File_priv, Grant_priv,
Index_priv, Alter_priv,
Show_db_priv, Super_priv,
Lock_tables_priv, Execute_priv,
Repl_slave_priv, Repl_client_priv,
Create_view_priv,
Create_routine_priv, Alter_routine_priv,
Create_user_priv,
Event_priv, Trigger_priv,
Create_tablespace_priv
FROM mysql.user
WHERE
CONCAT(user, '@', host) = CURRENT_USER()
"""
rows = db.fetchall(sql)
if not rows or len(rows) > 1:
return False
prohibited = convert_enums(rows[0])
if any(prohibited):
if logger:
logger.debug(
"MySQL.is_read_only(): FAIL: GLOBAL privileges "
"wrong: prohibited={}".format(prohibited))
return False
except mysql.OperationalError:
# Probably: error 1142, "SELECT command denied to user 'xxx'@'yyy'
# for table 'user'". This would be OK.
pass
return True | [
"def",
"is_read_only",
"(",
"cls",
",",
"db",
":",
"DATABASE_SUPPORTER_FWD_REF",
",",
"logger",
":",
"logging",
".",
"Logger",
"=",
"None",
")",
"->",
"bool",
":",
"def",
"convert_enums",
"(",
"row_",
")",
":",
"# All these columns are of type enum('N', 'Y');",
... | Do we have read-only access? | [
"Do",
"we",
"have",
"read",
"-",
"only",
"access?"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L652-L734 | train | 53,257 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.ping | def ping(self) -> None:
"""Pings a database connection, reconnecting if necessary."""
if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB,
PYTHONLIB_PYMYSQL]:
return
try:
self.db.ping(True) # test connection; reconnect upon failure
# ... should auto-reconnect; however, it seems to fail the first
# time, then work the next time.
# Exception (the first time) is:
# <class '_mysql_exceptions.OperationalError'>:
# (2006, 'MySQL server has gone away')
# http://mail.python.org/pipermail/python-list/2008-February/
# 474598.html
except mysql.OperationalError: # loss of connection
self.db = None
self.connect_to_database_mysql(
self._database, self._user, self._password, self._server,
self._port, self._charset, self._use_unicode) | python | def ping(self) -> None:
"""Pings a database connection, reconnecting if necessary."""
if self.db is None or self.db_pythonlib not in [PYTHONLIB_MYSQLDB,
PYTHONLIB_PYMYSQL]:
return
try:
self.db.ping(True) # test connection; reconnect upon failure
# ... should auto-reconnect; however, it seems to fail the first
# time, then work the next time.
# Exception (the first time) is:
# <class '_mysql_exceptions.OperationalError'>:
# (2006, 'MySQL server has gone away')
# http://mail.python.org/pipermail/python-list/2008-February/
# 474598.html
except mysql.OperationalError: # loss of connection
self.db = None
self.connect_to_database_mysql(
self._database, self._user, self._password, self._server,
self._port, self._charset, self._use_unicode) | [
"def",
"ping",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"db",
"is",
"None",
"or",
"self",
".",
"db_pythonlib",
"not",
"in",
"[",
"PYTHONLIB_MYSQLDB",
",",
"PYTHONLIB_PYMYSQL",
"]",
":",
"return",
"try",
":",
"self",
".",
"db",
".",
"pi... | Pings a database connection, reconnecting if necessary. | [
"Pings",
"a",
"database",
"connection",
"reconnecting",
"if",
"necessary",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1931-L1949 | train | 53,258 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.connect_to_database_odbc_mysql | def connect_to_database_odbc_mysql(self,
database: str,
user: str,
password: str,
server: str = "localhost",
port: int = 3306,
driver: str = "{MySQL ODBC 5.1 Driver}",
autocommit: bool = True) -> None:
"""Connects to a MySQL database via ODBC."""
self.connect(engine=ENGINE_MYSQL, interface=INTERFACE_ODBC,
database=database, user=user, password=password,
host=server, port=port, driver=driver,
autocommit=autocommit) | python | def connect_to_database_odbc_mysql(self,
database: str,
user: str,
password: str,
server: str = "localhost",
port: int = 3306,
driver: str = "{MySQL ODBC 5.1 Driver}",
autocommit: bool = True) -> None:
"""Connects to a MySQL database via ODBC."""
self.connect(engine=ENGINE_MYSQL, interface=INTERFACE_ODBC,
database=database, user=user, password=password,
host=server, port=port, driver=driver,
autocommit=autocommit) | [
"def",
"connect_to_database_odbc_mysql",
"(",
"self",
",",
"database",
":",
"str",
",",
"user",
":",
"str",
",",
"password",
":",
"str",
",",
"server",
":",
"str",
"=",
"\"localhost\"",
",",
"port",
":",
"int",
"=",
"3306",
",",
"driver",
":",
"str",
"... | Connects to a MySQL database via ODBC. | [
"Connects",
"to",
"a",
"MySQL",
"database",
"via",
"ODBC",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1969-L1981 | train | 53,259 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.connect_to_database_odbc_sqlserver | def connect_to_database_odbc_sqlserver(self,
odbc_connection_string: str = None,
dsn: str = None,
database: str = None,
user: str = None,
password: str = None,
server: str = "localhost",
driver: str = "{SQL Server}",
autocommit: bool = True) -> None:
"""Connects to an SQL Server database via ODBC."""
self.connect(engine=ENGINE_SQLSERVER, interface=INTERFACE_ODBC,
odbc_connection_string=odbc_connection_string,
dsn=dsn,
database=database, user=user, password=password,
host=server, driver=driver,
autocommit=autocommit) | python | def connect_to_database_odbc_sqlserver(self,
odbc_connection_string: str = None,
dsn: str = None,
database: str = None,
user: str = None,
password: str = None,
server: str = "localhost",
driver: str = "{SQL Server}",
autocommit: bool = True) -> None:
"""Connects to an SQL Server database via ODBC."""
self.connect(engine=ENGINE_SQLSERVER, interface=INTERFACE_ODBC,
odbc_connection_string=odbc_connection_string,
dsn=dsn,
database=database, user=user, password=password,
host=server, driver=driver,
autocommit=autocommit) | [
"def",
"connect_to_database_odbc_sqlserver",
"(",
"self",
",",
"odbc_connection_string",
":",
"str",
"=",
"None",
",",
"dsn",
":",
"str",
"=",
"None",
",",
"database",
":",
"str",
"=",
"None",
",",
"user",
":",
"str",
"=",
"None",
",",
"password",
":",
"... | Connects to an SQL Server database via ODBC. | [
"Connects",
"to",
"an",
"SQL",
"Server",
"database",
"via",
"ODBC",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L1983-L1998 | train | 53,260 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.connect_to_database_odbc_access | def connect_to_database_odbc_access(self,
dsn: str,
autocommit: bool = True) -> None:
"""Connects to an Access database via ODBC, with the DSN
prespecified."""
self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,
dsn=dsn, autocommit=autocommit) | python | def connect_to_database_odbc_access(self,
dsn: str,
autocommit: bool = True) -> None:
"""Connects to an Access database via ODBC, with the DSN
prespecified."""
self.connect(engine=ENGINE_ACCESS, interface=INTERFACE_ODBC,
dsn=dsn, autocommit=autocommit) | [
"def",
"connect_to_database_odbc_access",
"(",
"self",
",",
"dsn",
":",
"str",
",",
"autocommit",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"self",
".",
"connect",
"(",
"engine",
"=",
"ENGINE_ACCESS",
",",
"interface",
"=",
"INTERFACE_ODBC",
",",
"... | Connects to an Access database via ODBC, with the DSN
prespecified. | [
"Connects",
"to",
"an",
"Access",
"database",
"via",
"ODBC",
"with",
"the",
"DSN",
"prespecified",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2000-L2006 | train | 53,261 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.localize_sql | def localize_sql(self, sql: str) -> str:
"""Translates ?-placeholder SQL to appropriate dialect.
For example, MySQLdb uses %s rather than ?.
"""
# pyodbc seems happy with ? now (pyodbc.paramstyle is 'qmark');
# using ? is much simpler, because we may want to use % with LIKE
# fields or (in my case) with date formatting strings for
# STR_TO_DATE().
# If you get this wrong, you may see "not all arguments converted
# during string formatting";
# http://stackoverflow.com/questions/9337134
if self.db_pythonlib in [PYTHONLIB_PYMYSQL, PYTHONLIB_MYSQLDB]:
# These engines use %, so we need to convert ? to %, without
# breaking literal % values.
sql = _PERCENT_REGEX.sub("%%", sql)
# ... replace all % with %% first
sql = _QUERY_VALUE_REGEX.sub("%s", sql)
# ... replace all ? with %s in the SQL
# Otherwise: engine uses ?, so we don't have to fiddle.
return sql | python | def localize_sql(self, sql: str) -> str:
"""Translates ?-placeholder SQL to appropriate dialect.
For example, MySQLdb uses %s rather than ?.
"""
# pyodbc seems happy with ? now (pyodbc.paramstyle is 'qmark');
# using ? is much simpler, because we may want to use % with LIKE
# fields or (in my case) with date formatting strings for
# STR_TO_DATE().
# If you get this wrong, you may see "not all arguments converted
# during string formatting";
# http://stackoverflow.com/questions/9337134
if self.db_pythonlib in [PYTHONLIB_PYMYSQL, PYTHONLIB_MYSQLDB]:
# These engines use %, so we need to convert ? to %, without
# breaking literal % values.
sql = _PERCENT_REGEX.sub("%%", sql)
# ... replace all % with %% first
sql = _QUERY_VALUE_REGEX.sub("%s", sql)
# ... replace all ? with %s in the SQL
# Otherwise: engine uses ?, so we don't have to fiddle.
return sql | [
"def",
"localize_sql",
"(",
"self",
",",
"sql",
":",
"str",
")",
"->",
"str",
":",
"# pyodbc seems happy with ? now (pyodbc.paramstyle is 'qmark');",
"# using ? is much simpler, because we may want to use % with LIKE",
"# fields or (in my case) with date formatting strings for",
"# STR... | Translates ?-placeholder SQL to appropriate dialect.
For example, MySQLdb uses %s rather than ?. | [
"Translates",
"?",
"-",
"placeholder",
"SQL",
"to",
"appropriate",
"dialect",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2029-L2049 | train | 53,262 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.insert_record_by_fieldspecs_with_values | def insert_record_by_fieldspecs_with_values(
self,
table: str,
fieldspeclist: FIELDSPECLIST_TYPE) -> int:
"""Inserts a record into the database using a list of fieldspecs having
their value stored under the 'value' key.
"""
fields = []
values = []
for fs in fieldspeclist:
fields.append(fs["name"])
values.append(fs["value"])
return self.insert_record(table, fields, values) | python | def insert_record_by_fieldspecs_with_values(
self,
table: str,
fieldspeclist: FIELDSPECLIST_TYPE) -> int:
"""Inserts a record into the database using a list of fieldspecs having
their value stored under the 'value' key.
"""
fields = []
values = []
for fs in fieldspeclist:
fields.append(fs["name"])
values.append(fs["value"])
return self.insert_record(table, fields, values) | [
"def",
"insert_record_by_fieldspecs_with_values",
"(",
"self",
",",
"table",
":",
"str",
",",
"fieldspeclist",
":",
"FIELDSPECLIST_TYPE",
")",
"->",
"int",
":",
"fields",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"for",
"fs",
"in",
"fieldspeclist",
":",
"field... | Inserts a record into the database using a list of fieldspecs having
their value stored under the 'value' key. | [
"Inserts",
"a",
"record",
"into",
"the",
"database",
"using",
"a",
"list",
"of",
"fieldspecs",
"having",
"their",
"value",
"stored",
"under",
"the",
"value",
"key",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2112-L2124 | train | 53,263 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.db_exec_with_cursor | def db_exec_with_cursor(self, cursor, sql: str, *args) -> int:
"""Executes SQL on a supplied cursor, with "?" placeholders,
substituting in the arguments. Returns number of rows affected."""
sql = self.localize_sql(sql)
try:
debug_sql(sql, args)
cursor.execute(sql, args)
return cursor.rowcount
except: # nopep8
log.exception("db_exec_with_cursor: SQL was: " + sql)
raise | python | def db_exec_with_cursor(self, cursor, sql: str, *args) -> int:
"""Executes SQL on a supplied cursor, with "?" placeholders,
substituting in the arguments. Returns number of rows affected."""
sql = self.localize_sql(sql)
try:
debug_sql(sql, args)
cursor.execute(sql, args)
return cursor.rowcount
except: # nopep8
log.exception("db_exec_with_cursor: SQL was: " + sql)
raise | [
"def",
"db_exec_with_cursor",
"(",
"self",
",",
"cursor",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"int",
":",
"sql",
"=",
"self",
".",
"localize_sql",
"(",
"sql",
")",
"try",
":",
"debug_sql",
"(",
"sql",
",",
"args",
")",
"cursor",
".... | Executes SQL on a supplied cursor, with "?" placeholders,
substituting in the arguments. Returns number of rows affected. | [
"Executes",
"SQL",
"on",
"a",
"supplied",
"cursor",
"with",
"?",
"placeholders",
"substituting",
"in",
"the",
"arguments",
".",
"Returns",
"number",
"of",
"rows",
"affected",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2184-L2194 | train | 53,264 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.db_exec_and_commit | def db_exec_and_commit(self, sql: str, *args) -> int:
"""Execute SQL and commit."""
rowcount = self.db_exec(sql, *args)
self.commit()
return rowcount | python | def db_exec_and_commit(self, sql: str, *args) -> int:
"""Execute SQL and commit."""
rowcount = self.db_exec(sql, *args)
self.commit()
return rowcount | [
"def",
"db_exec_and_commit",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"int",
":",
"rowcount",
"=",
"self",
".",
"db_exec",
"(",
"sql",
",",
"*",
"args",
")",
"self",
".",
"commit",
"(",
")",
"return",
"rowcount"
] | Execute SQL and commit. | [
"Execute",
"SQL",
"and",
"commit",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2208-L2212 | train | 53,265 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.db_exec_literal | def db_exec_literal(self, sql: str) -> int:
"""Executes SQL without modification. Returns rowcount."""
self.ensure_db_open()
cursor = self.db.cursor()
debug_sql(sql)
try:
cursor.execute(sql)
return cursor.rowcount
except: # nopep8
log.exception("db_exec_literal: SQL was: " + sql)
raise | python | def db_exec_literal(self, sql: str) -> int:
"""Executes SQL without modification. Returns rowcount."""
self.ensure_db_open()
cursor = self.db.cursor()
debug_sql(sql)
try:
cursor.execute(sql)
return cursor.rowcount
except: # nopep8
log.exception("db_exec_literal: SQL was: " + sql)
raise | [
"def",
"db_exec_literal",
"(",
"self",
",",
"sql",
":",
"str",
")",
"->",
"int",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"debug_sql",
"(",
"sql",
")",
"try",
":",
"cursor",
".",
"exec... | Executes SQL without modification. Returns rowcount. | [
"Executes",
"SQL",
"without",
"modification",
".",
"Returns",
"rowcount",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2214-L2224 | train | 53,266 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetchvalue | def fetchvalue(self, sql: str, *args) -> Optional[Any]:
"""Executes SQL; returns the first value of the first row, or None."""
row = self.fetchone(sql, *args)
if row is None:
return None
return row[0] | python | def fetchvalue(self, sql: str, *args) -> Optional[Any]:
"""Executes SQL; returns the first value of the first row, or None."""
row = self.fetchone(sql, *args)
if row is None:
return None
return row[0] | [
"def",
"fetchvalue",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"Optional",
"[",
"Any",
"]",
":",
"row",
"=",
"self",
".",
"fetchone",
"(",
"sql",
",",
"*",
"args",
")",
"if",
"row",
"is",
"None",
":",
"return",
"None",
"... | Executes SQL; returns the first value of the first row, or None. | [
"Executes",
"SQL",
";",
"returns",
"the",
"first",
"value",
"of",
"the",
"first",
"row",
"or",
"None",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2240-L2245 | train | 53,267 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetchone | def fetchone(self, sql: str, *args) -> Optional[Sequence[Any]]:
"""Executes SQL; returns the first row, or None."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return cursor.fetchone()
except: # nopep8
log.exception("fetchone: SQL was: " + sql)
raise | python | def fetchone(self, sql: str, *args) -> Optional[Sequence[Any]]:
"""Executes SQL; returns the first row, or None."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return cursor.fetchone()
except: # nopep8
log.exception("fetchone: SQL was: " + sql)
raise | [
"def",
"fetchone",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"Optional",
"[",
"Sequence",
"[",
"Any",
"]",
"]",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self... | Executes SQL; returns the first row, or None. | [
"Executes",
"SQL",
";",
"returns",
"the",
"first",
"row",
"or",
"None",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2247-L2256 | train | 53,268 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetchallfirstvalues | def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:
"""Executes SQL; returns list of first values of each row."""
rows = self.fetchall(sql, *args)
return [row[0] for row in rows] | python | def fetchallfirstvalues(self, sql: str, *args) -> List[Any]:
"""Executes SQL; returns list of first values of each row."""
rows = self.fetchall(sql, *args)
return [row[0] for row in rows] | [
"def",
"fetchallfirstvalues",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"List",
"[",
"Any",
"]",
":",
"rows",
"=",
"self",
".",
"fetchall",
"(",
"sql",
",",
"*",
"args",
")",
"return",
"[",
"row",
"[",
"0",
"]",
"for",
"... | Executes SQL; returns list of first values of each row. | [
"Executes",
"SQL",
";",
"returns",
"list",
"of",
"first",
"values",
"of",
"each",
"row",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2329-L2332 | train | 53,269 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetch_fieldnames | def fetch_fieldnames(self, sql: str, *args) -> List[str]:
"""Executes SQL; returns just the output fieldnames."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return [i[0] for i in cursor.description]
except: # nopep8
log.exception("fetch_fieldnames: SQL was: " + sql)
raise | python | def fetch_fieldnames(self, sql: str, *args) -> List[str]:
"""Executes SQL; returns just the output fieldnames."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
return [i[0] for i in cursor.description]
except: # nopep8
log.exception("fetch_fieldnames: SQL was: " + sql)
raise | [
"def",
"fetch_fieldnames",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"List",
"[",
"str",
"]",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self",
".",
"db_exec_wit... | Executes SQL; returns just the output fieldnames. | [
"Executes",
"SQL",
";",
"returns",
"just",
"the",
"output",
"fieldnames",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2334-L2343 | train | 53,270 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.delete_by_field | def delete_by_field(self, table: str, field: str, value: Any) -> int:
"""Deletes all records where "field" is "value"."""
sql = ("DELETE FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
return self.db_exec(sql, value) | python | def delete_by_field(self, table: str, field: str, value: Any) -> int:
"""Deletes all records where "field" is "value"."""
sql = ("DELETE FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
return self.db_exec(sql, value) | [
"def",
"delete_by_field",
"(",
"self",
",",
"table",
":",
"str",
",",
"field",
":",
"str",
",",
"value",
":",
"Any",
")",
"->",
"int",
":",
"sql",
"=",
"(",
"\"DELETE FROM \"",
"+",
"self",
".",
"delimit",
"(",
"table",
")",
"+",
"\" WHERE \"",
"+",
... | Deletes all records where "field" is "value". | [
"Deletes",
"all",
"records",
"where",
"field",
"is",
"value",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2368-L2372 | train | 53,271 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetch_all_objects_from_db | def fetch_all_objects_from_db(self,
cls: Type[T],
table: str,
fieldlist: Sequence[str],
construct_with_pk: bool,
*args) -> List[T]:
"""Fetches all objects from a table, returning an array of objects of
class cls."""
return self.fetch_all_objects_from_db_where(
cls, table, fieldlist, construct_with_pk, None, *args) | python | def fetch_all_objects_from_db(self,
cls: Type[T],
table: str,
fieldlist: Sequence[str],
construct_with_pk: bool,
*args) -> List[T]:
"""Fetches all objects from a table, returning an array of objects of
class cls."""
return self.fetch_all_objects_from_db_where(
cls, table, fieldlist, construct_with_pk, None, *args) | [
"def",
"fetch_all_objects_from_db",
"(",
"self",
",",
"cls",
":",
"Type",
"[",
"T",
"]",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"construct_with_pk",
":",
"bool",
",",
"*",
"args",
")",
"->",
"List",
"[",
"T... | Fetches all objects from a table, returning an array of objects of
class cls. | [
"Fetches",
"all",
"objects",
"from",
"a",
"table",
"returning",
"an",
"array",
"of",
"objects",
"of",
"class",
"cls",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2420-L2429 | train | 53,272 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fetch_all_objects_from_db_by_pklist | def fetch_all_objects_from_db_by_pklist(self,
cls: Type,
table: str,
fieldlist: Sequence[str],
pklist: Sequence[Any],
construct_with_pk: bool,
*args) -> List[T]:
"""Fetches all objects from a table, given a list of PKs."""
objarray = []
for pk in pklist:
if construct_with_pk:
obj = cls(pk, *args) # should do its own fetching
else:
obj = cls(*args)
self.fetch_object_from_db_by_pk(obj, table, fieldlist, pk)
objarray.append(obj)
return objarray | python | def fetch_all_objects_from_db_by_pklist(self,
cls: Type,
table: str,
fieldlist: Sequence[str],
pklist: Sequence[Any],
construct_with_pk: bool,
*args) -> List[T]:
"""Fetches all objects from a table, given a list of PKs."""
objarray = []
for pk in pklist:
if construct_with_pk:
obj = cls(pk, *args) # should do its own fetching
else:
obj = cls(*args)
self.fetch_object_from_db_by_pk(obj, table, fieldlist, pk)
objarray.append(obj)
return objarray | [
"def",
"fetch_all_objects_from_db_by_pklist",
"(",
"self",
",",
"cls",
":",
"Type",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"pklist",
":",
"Sequence",
"[",
"Any",
"]",
",",
"construct_with_pk",
":",
"bool",
",",
... | Fetches all objects from a table, given a list of PKs. | [
"Fetches",
"all",
"objects",
"from",
"a",
"table",
"given",
"a",
"list",
"of",
"PKs",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2431-L2447 | train | 53,273 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.save_object_to_db | def save_object_to_db(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
is_new_record: bool) -> None:
"""Saves a object to the database, inserting or updating as
necessary."""
if is_new_record:
pkvalue = getattr(obj, fieldlist[0])
if pkvalue is None:
self.insert_object_into_db_pk_unknown(obj, table, fieldlist)
else:
self.insert_object_into_db_pk_known(obj, table, fieldlist)
else:
self.update_object_in_db(obj, table, fieldlist) | python | def save_object_to_db(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
is_new_record: bool) -> None:
"""Saves a object to the database, inserting or updating as
necessary."""
if is_new_record:
pkvalue = getattr(obj, fieldlist[0])
if pkvalue is None:
self.insert_object_into_db_pk_unknown(obj, table, fieldlist)
else:
self.insert_object_into_db_pk_known(obj, table, fieldlist)
else:
self.update_object_in_db(obj, table, fieldlist) | [
"def",
"save_object_to_db",
"(",
"self",
",",
"obj",
":",
"Any",
",",
"table",
":",
"str",
",",
"fieldlist",
":",
"Sequence",
"[",
"str",
"]",
",",
"is_new_record",
":",
"bool",
")",
"->",
"None",
":",
"if",
"is_new_record",
":",
"pkvalue",
"=",
"getat... | Saves a object to the database, inserting or updating as
necessary. | [
"Saves",
"a",
"object",
"to",
"the",
"database",
"inserting",
"or",
"updating",
"as",
"necessary",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2561-L2575 | train | 53,274 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.create_index_from_fieldspec | def create_index_from_fieldspec(self,
table: str,
fieldspec: FIELDSPEC_TYPE,
indexname: str = None) -> None:
"""Calls create_index based on a fieldspec, if the fieldspec has
indexed = True."""
if "indexed" in fieldspec and fieldspec["indexed"]:
if "index_nchar" in fieldspec:
nchar = fieldspec["index_nchar"]
else:
nchar = None
self.create_index(table, fieldspec["name"], nchar,
indexname=indexname) | python | def create_index_from_fieldspec(self,
table: str,
fieldspec: FIELDSPEC_TYPE,
indexname: str = None) -> None:
"""Calls create_index based on a fieldspec, if the fieldspec has
indexed = True."""
if "indexed" in fieldspec and fieldspec["indexed"]:
if "index_nchar" in fieldspec:
nchar = fieldspec["index_nchar"]
else:
nchar = None
self.create_index(table, fieldspec["name"], nchar,
indexname=indexname) | [
"def",
"create_index_from_fieldspec",
"(",
"self",
",",
"table",
":",
"str",
",",
"fieldspec",
":",
"FIELDSPEC_TYPE",
",",
"indexname",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"if",
"\"indexed\"",
"in",
"fieldspec",
"and",
"fieldspec",
"[",
"\"index... | Calls create_index based on a fieldspec, if the fieldspec has
indexed = True. | [
"Calls",
"create_index",
"based",
"on",
"a",
"fieldspec",
"if",
"the",
"fieldspec",
"has",
"indexed",
"=",
"True",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2617-L2629 | train | 53,275 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fielddefsql_from_fieldspec | def fielddefsql_from_fieldspec(fieldspec: FIELDSPEC_TYPE) -> str:
"""Returns SQL fragment to define a field."""
sql = fieldspec["name"] + " " + fieldspec["sqltype"]
if "notnull" in fieldspec and fieldspec["notnull"]:
sql += " NOT NULL"
if "autoincrement" in fieldspec and fieldspec["autoincrement"]:
sql += " AUTO_INCREMENT"
if "pk" in fieldspec and fieldspec["pk"]:
sql += " PRIMARY KEY"
else:
if "unique" in fieldspec and fieldspec["unique"]:
sql += " UNIQUE"
if "comment" in fieldspec:
sql += " COMMENT " + sql_quote_string(fieldspec["comment"])
return sql | python | def fielddefsql_from_fieldspec(fieldspec: FIELDSPEC_TYPE) -> str:
"""Returns SQL fragment to define a field."""
sql = fieldspec["name"] + " " + fieldspec["sqltype"]
if "notnull" in fieldspec and fieldspec["notnull"]:
sql += " NOT NULL"
if "autoincrement" in fieldspec and fieldspec["autoincrement"]:
sql += " AUTO_INCREMENT"
if "pk" in fieldspec and fieldspec["pk"]:
sql += " PRIMARY KEY"
else:
if "unique" in fieldspec and fieldspec["unique"]:
sql += " UNIQUE"
if "comment" in fieldspec:
sql += " COMMENT " + sql_quote_string(fieldspec["comment"])
return sql | [
"def",
"fielddefsql_from_fieldspec",
"(",
"fieldspec",
":",
"FIELDSPEC_TYPE",
")",
"->",
"str",
":",
"sql",
"=",
"fieldspec",
"[",
"\"name\"",
"]",
"+",
"\" \"",
"+",
"fieldspec",
"[",
"\"sqltype\"",
"]",
"if",
"\"notnull\"",
"in",
"fieldspec",
"and",
"fieldsp... | Returns SQL fragment to define a field. | [
"Returns",
"SQL",
"fragment",
"to",
"define",
"a",
"field",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2665-L2679 | train | 53,276 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fielddefsql_from_fieldspeclist | def fielddefsql_from_fieldspeclist(
self, fieldspeclist: FIELDSPECLIST_TYPE) -> str:
"""Returns list of field-defining SQL fragments."""
return ",".join([
self.fielddefsql_from_fieldspec(x)
for x in fieldspeclist
]) | python | def fielddefsql_from_fieldspeclist(
self, fieldspeclist: FIELDSPECLIST_TYPE) -> str:
"""Returns list of field-defining SQL fragments."""
return ",".join([
self.fielddefsql_from_fieldspec(x)
for x in fieldspeclist
]) | [
"def",
"fielddefsql_from_fieldspeclist",
"(",
"self",
",",
"fieldspeclist",
":",
"FIELDSPECLIST_TYPE",
")",
"->",
"str",
":",
"return",
"\",\"",
".",
"join",
"(",
"[",
"self",
".",
"fielddefsql_from_fieldspec",
"(",
"x",
")",
"for",
"x",
"in",
"fieldspeclist",
... | Returns list of field-defining SQL fragments. | [
"Returns",
"list",
"of",
"field",
"-",
"defining",
"SQL",
"fragments",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2681-L2687 | train | 53,277 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.fieldspec_subset_by_name | def fieldspec_subset_by_name(
fieldspeclist: FIELDSPECLIST_TYPE,
fieldnames: Container[str]) -> FIELDSPECLIST_TYPE:
"""Returns a subset of the fieldspecs matching the fieldnames list."""
result = []
for x in fieldspeclist:
if x["name"] in fieldnames:
result.append(x)
return result | python | def fieldspec_subset_by_name(
fieldspeclist: FIELDSPECLIST_TYPE,
fieldnames: Container[str]) -> FIELDSPECLIST_TYPE:
"""Returns a subset of the fieldspecs matching the fieldnames list."""
result = []
for x in fieldspeclist:
if x["name"] in fieldnames:
result.append(x)
return result | [
"def",
"fieldspec_subset_by_name",
"(",
"fieldspeclist",
":",
"FIELDSPECLIST_TYPE",
",",
"fieldnames",
":",
"Container",
"[",
"str",
"]",
")",
"->",
"FIELDSPECLIST_TYPE",
":",
"result",
"=",
"[",
"]",
"for",
"x",
"in",
"fieldspeclist",
":",
"if",
"x",
"[",
"... | Returns a subset of the fieldspecs matching the fieldnames list. | [
"Returns",
"a",
"subset",
"of",
"the",
"fieldspecs",
"matching",
"the",
"fieldnames",
"list",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2690-L2698 | train | 53,278 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.drop_table | def drop_table(self, tablename: str) -> int:
"""Drops a table. Use caution!"""
sql = "DROP TABLE IF EXISTS {}".format(tablename)
log.info("Dropping table " + tablename + " (ignore any warning here)")
return self.db_exec_literal(sql) | python | def drop_table(self, tablename: str) -> int:
"""Drops a table. Use caution!"""
sql = "DROP TABLE IF EXISTS {}".format(tablename)
log.info("Dropping table " + tablename + " (ignore any warning here)")
return self.db_exec_literal(sql) | [
"def",
"drop_table",
"(",
"self",
",",
"tablename",
":",
"str",
")",
"->",
"int",
":",
"sql",
"=",
"\"DROP TABLE IF EXISTS {}\"",
".",
"format",
"(",
"tablename",
")",
"log",
".",
"info",
"(",
"\"Dropping table \"",
"+",
"tablename",
"+",
"\" (ignore any warni... | Drops a table. Use caution! | [
"Drops",
"a",
"table",
".",
"Use",
"caution!"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2728-L2732 | train | 53,279 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.drop_view | def drop_view(self, viewname: str) -> int:
"""Drops a view."""
sql = "DROP VIEW IF EXISTS {}".format(viewname)
log.info("Dropping view " + viewname + " (ignore any warning here)")
return self.db_exec_literal(sql) | python | def drop_view(self, viewname: str) -> int:
"""Drops a view."""
sql = "DROP VIEW IF EXISTS {}".format(viewname)
log.info("Dropping view " + viewname + " (ignore any warning here)")
return self.db_exec_literal(sql) | [
"def",
"drop_view",
"(",
"self",
",",
"viewname",
":",
"str",
")",
"->",
"int",
":",
"sql",
"=",
"\"DROP VIEW IF EXISTS {}\"",
".",
"format",
"(",
"viewname",
")",
"log",
".",
"info",
"(",
"\"Dropping view \"",
"+",
"viewname",
"+",
"\" (ignore any warning her... | Drops a view. | [
"Drops",
"a",
"view",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2734-L2738 | train | 53,280 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.rename_table | def rename_table(self, from_table: str, to_table: str) -> Optional[int]:
"""Renames a table. MySQL-specific."""
if not self.table_exists(from_table):
log.info("Skipping renaming of table " + from_table +
" (doesn't exist)")
return None
if self.table_exists(to_table):
raise RuntimeError("Can't rename table {} to {}: destination "
"already exists!".format(from_table, to_table))
log.info("Renaming table {} to {}", from_table, to_table)
sql = "RENAME TABLE {} TO {}".format(from_table, to_table)
return self.db_exec_literal(sql) | python | def rename_table(self, from_table: str, to_table: str) -> Optional[int]:
"""Renames a table. MySQL-specific."""
if not self.table_exists(from_table):
log.info("Skipping renaming of table " + from_table +
" (doesn't exist)")
return None
if self.table_exists(to_table):
raise RuntimeError("Can't rename table {} to {}: destination "
"already exists!".format(from_table, to_table))
log.info("Renaming table {} to {}", from_table, to_table)
sql = "RENAME TABLE {} TO {}".format(from_table, to_table)
return self.db_exec_literal(sql) | [
"def",
"rename_table",
"(",
"self",
",",
"from_table",
":",
"str",
",",
"to_table",
":",
"str",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"not",
"self",
".",
"table_exists",
"(",
"from_table",
")",
":",
"log",
".",
"info",
"(",
"\"Skipping ren... | Renames a table. MySQL-specific. | [
"Renames",
"a",
"table",
".",
"MySQL",
"-",
"specific",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2768-L2779 | train | 53,281 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.add_column | def add_column(self, tablename: str, fieldspec: FIELDSPEC_TYPE) -> int:
"""Adds a column to an existing table."""
sql = "ALTER TABLE {} ADD COLUMN {}".format(
tablename, self.fielddefsql_from_fieldspec(fieldspec))
log.info(sql)
return self.db_exec_literal(sql) | python | def add_column(self, tablename: str, fieldspec: FIELDSPEC_TYPE) -> int:
"""Adds a column to an existing table."""
sql = "ALTER TABLE {} ADD COLUMN {}".format(
tablename, self.fielddefsql_from_fieldspec(fieldspec))
log.info(sql)
return self.db_exec_literal(sql) | [
"def",
"add_column",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"fieldspec",
":",
"FIELDSPEC_TYPE",
")",
"->",
"int",
":",
"sql",
"=",
"\"ALTER TABLE {} ADD COLUMN {}\"",
".",
"format",
"(",
"tablename",
",",
"self",
".",
"fielddefsql_from_fieldspec",
"(",
... | Adds a column to an existing table. | [
"Adds",
"a",
"column",
"to",
"an",
"existing",
"table",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2781-L2786 | train | 53,282 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.modify_column_if_table_exists | def modify_column_if_table_exists(self,
tablename: str,
fieldname: str,
newdef: str) -> Optional[int]:
"""Alters a column's definition without renaming it."""
if not self.table_exists(tablename):
return None
sql = "ALTER TABLE {t} MODIFY COLUMN {field} {newdef}".format(
t=tablename,
field=fieldname,
newdef=newdef
)
log.info(sql)
return self.db_exec_literal(sql) | python | def modify_column_if_table_exists(self,
tablename: str,
fieldname: str,
newdef: str) -> Optional[int]:
"""Alters a column's definition without renaming it."""
if not self.table_exists(tablename):
return None
sql = "ALTER TABLE {t} MODIFY COLUMN {field} {newdef}".format(
t=tablename,
field=fieldname,
newdef=newdef
)
log.info(sql)
return self.db_exec_literal(sql) | [
"def",
"modify_column_if_table_exists",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"fieldname",
":",
"str",
",",
"newdef",
":",
"str",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"not",
"self",
".",
"table_exists",
"(",
"tablename",
")",
":",... | Alters a column's definition without renaming it. | [
"Alters",
"a",
"column",
"s",
"definition",
"without",
"renaming",
"it",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2794-L2807 | train | 53,283 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.change_column_if_table_exists | def change_column_if_table_exists(self,
tablename: str,
oldfieldname: str,
newfieldname: str,
newdef: str) -> Optional[int]:
"""Renames a column and alters its definition."""
if not self.table_exists(tablename):
return None
if not self.column_exists(tablename, oldfieldname):
return None
sql = "ALTER TABLE {t} CHANGE COLUMN {old} {new} {newdef}".format(
t=tablename,
old=oldfieldname,
new=newfieldname,
newdef=newdef,
)
log.info(sql)
return self.db_exec_literal(sql) | python | def change_column_if_table_exists(self,
tablename: str,
oldfieldname: str,
newfieldname: str,
newdef: str) -> Optional[int]:
"""Renames a column and alters its definition."""
if not self.table_exists(tablename):
return None
if not self.column_exists(tablename, oldfieldname):
return None
sql = "ALTER TABLE {t} CHANGE COLUMN {old} {new} {newdef}".format(
t=tablename,
old=oldfieldname,
new=newfieldname,
newdef=newdef,
)
log.info(sql)
return self.db_exec_literal(sql) | [
"def",
"change_column_if_table_exists",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"oldfieldname",
":",
"str",
",",
"newfieldname",
":",
"str",
",",
"newdef",
":",
"str",
")",
"->",
"Optional",
"[",
"int",
"]",
":",
"if",
"not",
"self",
".",
"table_... | Renames a column and alters its definition. | [
"Renames",
"a",
"column",
"and",
"alters",
"its",
"definition",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2809-L2826 | train | 53,284 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.create_or_update_table | def create_or_update_table(self,
tablename: str,
fieldspeclist: FIELDSPECLIST_TYPE,
drop_superfluous_columns: bool = False,
dynamic: bool = False,
compressed: bool = False) -> None:
"""
- Make table, if it doesn't exist.
- Add fields that aren't there.
- Warn about superfluous fields, but don't delete them, unless
``drop_superfluous_columns == True``.
- Make indexes, if requested.
"""
# 1. Make table, if it doesn't exist
self.make_table(tablename, fieldspeclist, dynamic=dynamic,
compressed=compressed)
# 2. Are all the fields there?
# ... copes fine with fieldnames coming back in Unicode and being
# compared to str
fields_in_db = set(self.fetch_column_names(tablename))
desired_fieldnames = set(
self.fieldnames_from_fieldspeclist(fieldspeclist))
missing_fieldnames = desired_fieldnames - fields_in_db
missing_fieldspecs = self.fieldspec_subset_by_name(fieldspeclist,
missing_fieldnames)
for f in missing_fieldspecs:
self.add_column(tablename, f)
# 3. Anything superfluous?
superfluous_fieldnames = fields_in_db - desired_fieldnames
for f in superfluous_fieldnames:
if drop_superfluous_columns:
log.warning("... dropping superfluous field: " + f)
self.drop_column(tablename, f)
else:
log.warning("... superfluous field (ignored): " + f)
# 4. Make indexes, if some have been requested:
for fs in fieldspeclist:
self.create_index_from_fieldspec(tablename, fs) | python | def create_or_update_table(self,
tablename: str,
fieldspeclist: FIELDSPECLIST_TYPE,
drop_superfluous_columns: bool = False,
dynamic: bool = False,
compressed: bool = False) -> None:
"""
- Make table, if it doesn't exist.
- Add fields that aren't there.
- Warn about superfluous fields, but don't delete them, unless
``drop_superfluous_columns == True``.
- Make indexes, if requested.
"""
# 1. Make table, if it doesn't exist
self.make_table(tablename, fieldspeclist, dynamic=dynamic,
compressed=compressed)
# 2. Are all the fields there?
# ... copes fine with fieldnames coming back in Unicode and being
# compared to str
fields_in_db = set(self.fetch_column_names(tablename))
desired_fieldnames = set(
self.fieldnames_from_fieldspeclist(fieldspeclist))
missing_fieldnames = desired_fieldnames - fields_in_db
missing_fieldspecs = self.fieldspec_subset_by_name(fieldspeclist,
missing_fieldnames)
for f in missing_fieldspecs:
self.add_column(tablename, f)
# 3. Anything superfluous?
superfluous_fieldnames = fields_in_db - desired_fieldnames
for f in superfluous_fieldnames:
if drop_superfluous_columns:
log.warning("... dropping superfluous field: " + f)
self.drop_column(tablename, f)
else:
log.warning("... superfluous field (ignored): " + f)
# 4. Make indexes, if some have been requested:
for fs in fieldspeclist:
self.create_index_from_fieldspec(tablename, fs) | [
"def",
"create_or_update_table",
"(",
"self",
",",
"tablename",
":",
"str",
",",
"fieldspeclist",
":",
"FIELDSPECLIST_TYPE",
",",
"drop_superfluous_columns",
":",
"bool",
"=",
"False",
",",
"dynamic",
":",
"bool",
"=",
"False",
",",
"compressed",
":",
"bool",
... | - Make table, if it doesn't exist.
- Add fields that aren't there.
- Warn about superfluous fields, but don't delete them, unless
``drop_superfluous_columns == True``.
- Make indexes, if requested. | [
"-",
"Make",
"table",
"if",
"it",
"doesn",
"t",
"exist",
".",
"-",
"Add",
"fields",
"that",
"aren",
"t",
"there",
".",
"-",
"Warn",
"about",
"superfluous",
"fields",
"but",
"don",
"t",
"delete",
"them",
"unless",
"drop_superfluous_columns",
"==",
"True",
... | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2828-L2869 | train | 53,285 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.get_comment | def get_comment(self, table: str, column: str) -> str:
"""Returns database SQL comment for a column."""
return self.flavour.get_comment(self, table, column) | python | def get_comment(self, table: str, column: str) -> str:
"""Returns database SQL comment for a column."""
return self.flavour.get_comment(self, table, column) | [
"def",
"get_comment",
"(",
"self",
",",
"table",
":",
"str",
",",
"column",
":",
"str",
")",
"->",
"str",
":",
"return",
"self",
".",
"flavour",
".",
"get_comment",
"(",
"self",
",",
"table",
",",
"column",
")"
] | Returns database SQL comment for a column. | [
"Returns",
"database",
"SQL",
"comment",
"for",
"a",
"column",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2899-L2901 | train | 53,286 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.debug_query | def debug_query(self, sql: str, *args) -> None:
"""Executes SQL and writes the result to the log."""
rows = self.fetchall(sql, *args)
debug_query_result(rows) | python | def debug_query(self, sql: str, *args) -> None:
"""Executes SQL and writes the result to the log."""
rows = self.fetchall(sql, *args)
debug_query_result(rows) | [
"def",
"debug_query",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"None",
":",
"rows",
"=",
"self",
".",
"fetchall",
"(",
"sql",
",",
"*",
"args",
")",
"debug_query_result",
"(",
"rows",
")"
] | Executes SQL and writes the result to the log. | [
"Executes",
"SQL",
"and",
"writes",
"the",
"result",
"to",
"the",
"log",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2903-L2906 | train | 53,287 |
RudolfCardinal/pythonlib | cardinal_pythonlib/rnc_db.py | DatabaseSupporter.wipe_table | def wipe_table(self, table: str) -> int:
"""Delete all records from a table. Use caution!"""
sql = "DELETE FROM " + self.delimit(table)
return self.db_exec(sql) | python | def wipe_table(self, table: str) -> int:
"""Delete all records from a table. Use caution!"""
sql = "DELETE FROM " + self.delimit(table)
return self.db_exec(sql) | [
"def",
"wipe_table",
"(",
"self",
",",
"table",
":",
"str",
")",
"->",
"int",
":",
"sql",
"=",
"\"DELETE FROM \"",
"+",
"self",
".",
"delimit",
"(",
"table",
")",
"return",
"self",
".",
"db_exec",
"(",
"sql",
")"
] | Delete all records from a table. Use caution! | [
"Delete",
"all",
"records",
"from",
"a",
"table",
".",
"Use",
"caution!"
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_db.py#L2908-L2911 | train | 53,288 |
davenquinn/Attitude | attitude/error/axes.py | noise_covariance | def noise_covariance(fit, dof=2, **kw):
"""
Covariance taking into account the 'noise covariance' of the data.
This is technically more realistic for continuously sampled data.
From Faber, 1993
"""
ev = fit.eigenvalues
measurement_noise = ev[-1]/(fit.n-dof)
return 4*ev*measurement_noise | python | def noise_covariance(fit, dof=2, **kw):
"""
Covariance taking into account the 'noise covariance' of the data.
This is technically more realistic for continuously sampled data.
From Faber, 1993
"""
ev = fit.eigenvalues
measurement_noise = ev[-1]/(fit.n-dof)
return 4*ev*measurement_noise | [
"def",
"noise_covariance",
"(",
"fit",
",",
"dof",
"=",
"2",
",",
"*",
"*",
"kw",
")",
":",
"ev",
"=",
"fit",
".",
"eigenvalues",
"measurement_noise",
"=",
"ev",
"[",
"-",
"1",
"]",
"/",
"(",
"fit",
".",
"n",
"-",
"dof",
")",
"return",
"4",
"*"... | Covariance taking into account the 'noise covariance' of the data.
This is technically more realistic for continuously sampled data.
From Faber, 1993 | [
"Covariance",
"taking",
"into",
"account",
"the",
"noise",
"covariance",
"of",
"the",
"data",
".",
"This",
"is",
"technically",
"more",
"realistic",
"for",
"continuously",
"sampled",
"data",
".",
"From",
"Faber",
"1993"
] | 2ce97b9aba0aa5deedc6617c2315e07e6396d240 | https://github.com/davenquinn/Attitude/blob/2ce97b9aba0aa5deedc6617c2315e07e6396d240/attitude/error/axes.py#L31-L40 | train | 53,289 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_ops.py | create_view | def create_view(operations, operation):
"""
Implements ``CREATE VIEW``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None``
"""
operations.execute("CREATE VIEW %s AS %s" % (
operation.target.name,
operation.target.sqltext
)) | python | def create_view(operations, operation):
"""
Implements ``CREATE VIEW``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None``
"""
operations.execute("CREATE VIEW %s AS %s" % (
operation.target.name,
operation.target.sqltext
)) | [
"def",
"create_view",
"(",
"operations",
",",
"operation",
")",
":",
"operations",
".",
"execute",
"(",
"\"CREATE VIEW %s AS %s\"",
"%",
"(",
"operation",
".",
"target",
".",
"name",
",",
"operation",
".",
"target",
".",
"sqltext",
")",
")"
] | Implements ``CREATE VIEW``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None`` | [
"Implements",
"CREATE",
"VIEW",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_ops.py#L195-L209 | train | 53,290 |
RudolfCardinal/pythonlib | cardinal_pythonlib/sqlalchemy/alembic_ops.py | create_sp | def create_sp(operations, operation):
"""
Implements ``CREATE FUNCTION``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None``
"""
operations.execute(
"CREATE FUNCTION %s %s" % (
operation.target.name, operation.target.sqltext
)
) | python | def create_sp(operations, operation):
"""
Implements ``CREATE FUNCTION``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None``
"""
operations.execute(
"CREATE FUNCTION %s %s" % (
operation.target.name, operation.target.sqltext
)
) | [
"def",
"create_sp",
"(",
"operations",
",",
"operation",
")",
":",
"operations",
".",
"execute",
"(",
"\"CREATE FUNCTION %s %s\"",
"%",
"(",
"operation",
".",
"target",
".",
"name",
",",
"operation",
".",
"target",
".",
"sqltext",
")",
")"
] | Implements ``CREATE FUNCTION``.
Args:
operations: instance of ``alembic.operations.base.Operations``
operation: instance of :class:`.ReversibleOp`
Returns:
``None`` | [
"Implements",
"CREATE",
"FUNCTION",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/sqlalchemy/alembic_ops.py#L228-L243 | train | 53,291 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/fields/isodatetimetz.py | iso_string_to_python_datetime | def iso_string_to_python_datetime(
isostring: str) -> Optional[datetime.datetime]:
"""
Takes an ISO-8601 string and returns a ``datetime``.
"""
if not isostring:
return None # if you parse() an empty string, you get today's date
return dateutil.parser.parse(isostring) | python | def iso_string_to_python_datetime(
isostring: str) -> Optional[datetime.datetime]:
"""
Takes an ISO-8601 string and returns a ``datetime``.
"""
if not isostring:
return None # if you parse() an empty string, you get today's date
return dateutil.parser.parse(isostring) | [
"def",
"iso_string_to_python_datetime",
"(",
"isostring",
":",
"str",
")",
"->",
"Optional",
"[",
"datetime",
".",
"datetime",
"]",
":",
"if",
"not",
"isostring",
":",
"return",
"None",
"# if you parse() an empty string, you get today's date",
"return",
"dateutil",
".... | Takes an ISO-8601 string and returns a ``datetime``. | [
"Takes",
"an",
"ISO",
"-",
"8601",
"string",
"and",
"returns",
"a",
"datetime",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/isodatetimetz.py#L52-L59 | train | 53,292 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/fields/isodatetimetz.py | python_utc_datetime_to_sqlite_strftime_string | def python_utc_datetime_to_sqlite_strftime_string(
value: datetime.datetime) -> str:
"""
Converts a Python datetime to a string literal compatible with SQLite,
including the millisecond field.
"""
millisec_str = str(round(value.microsecond / 1000)).zfill(3)
return value.strftime("%Y-%m-%d %H:%M:%S") + "." + millisec_str | python | def python_utc_datetime_to_sqlite_strftime_string(
value: datetime.datetime) -> str:
"""
Converts a Python datetime to a string literal compatible with SQLite,
including the millisecond field.
"""
millisec_str = str(round(value.microsecond / 1000)).zfill(3)
return value.strftime("%Y-%m-%d %H:%M:%S") + "." + millisec_str | [
"def",
"python_utc_datetime_to_sqlite_strftime_string",
"(",
"value",
":",
"datetime",
".",
"datetime",
")",
"->",
"str",
":",
"millisec_str",
"=",
"str",
"(",
"round",
"(",
"value",
".",
"microsecond",
"/",
"1000",
")",
")",
".",
"zfill",
"(",
"3",
")",
"... | Converts a Python datetime to a string literal compatible with SQLite,
including the millisecond field. | [
"Converts",
"a",
"Python",
"datetime",
"to",
"a",
"string",
"literal",
"compatible",
"with",
"SQLite",
"including",
"the",
"millisecond",
"field",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/isodatetimetz.py#L62-L69 | train | 53,293 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/fields/isodatetimetz.py | IsoDateTimeTzField.from_db_value | def from_db_value(self, value, expression, connection, context):
"""
Convert database value to Python value.
Called when data is loaded from the database.
"""
# log.debug("from_db_value: {}, {}", value, type(value))
if value is None:
return value
if value == '':
return None
return iso_string_to_python_datetime(value) | python | def from_db_value(self, value, expression, connection, context):
"""
Convert database value to Python value.
Called when data is loaded from the database.
"""
# log.debug("from_db_value: {}, {}", value, type(value))
if value is None:
return value
if value == '':
return None
return iso_string_to_python_datetime(value) | [
"def",
"from_db_value",
"(",
"self",
",",
"value",
",",
"expression",
",",
"connection",
",",
"context",
")",
":",
"# log.debug(\"from_db_value: {}, {}\", value, type(value))",
"if",
"value",
"is",
"None",
":",
"return",
"value",
"if",
"value",
"==",
"''",
":",
... | Convert database value to Python value.
Called when data is loaded from the database. | [
"Convert",
"database",
"value",
"to",
"Python",
"value",
".",
"Called",
"when",
"data",
"is",
"loaded",
"from",
"the",
"database",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/isodatetimetz.py#L206-L216 | train | 53,294 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/fields/isodatetimetz.py | IsoDateTimeTzField.get_prep_value | def get_prep_value(self, value):
"""
Convert Python value to database value for QUERYING.
We query with UTC, so this function converts datetime values to UTC.
Calls to this function are followed by calls to ``get_db_prep_value()``,
which is for backend-specific conversions.
"""
log.debug("get_prep_value: {}, {}", value, type(value))
if not value:
return ''
# For underlying (database) string types, e.g. VARCHAR, this
# function must always return a string type.
# https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/
# Convert to UTC
return value.astimezone(timezone.utc) | python | def get_prep_value(self, value):
"""
Convert Python value to database value for QUERYING.
We query with UTC, so this function converts datetime values to UTC.
Calls to this function are followed by calls to ``get_db_prep_value()``,
which is for backend-specific conversions.
"""
log.debug("get_prep_value: {}, {}", value, type(value))
if not value:
return ''
# For underlying (database) string types, e.g. VARCHAR, this
# function must always return a string type.
# https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/
# Convert to UTC
return value.astimezone(timezone.utc) | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"log",
".",
"debug",
"(",
"\"get_prep_value: {}, {}\"",
",",
"value",
",",
"type",
"(",
"value",
")",
")",
"if",
"not",
"value",
":",
"return",
"''",
"# For underlying (database) string types, e.g. VA... | Convert Python value to database value for QUERYING.
We query with UTC, so this function converts datetime values to UTC.
Calls to this function are followed by calls to ``get_db_prep_value()``,
which is for backend-specific conversions. | [
"Convert",
"Python",
"value",
"to",
"database",
"value",
"for",
"QUERYING",
".",
"We",
"query",
"with",
"UTC",
"so",
"this",
"function",
"converts",
"datetime",
"values",
"to",
"UTC",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/isodatetimetz.py#L235-L250 | train | 53,295 |
RudolfCardinal/pythonlib | cardinal_pythonlib/django/fields/isodatetimetz.py | IsoDateTimeTzField.get_db_prep_save | def get_db_prep_save(self, value, connection, prepared=False):
"""
Convert Python value to database value for SAVING.
We save with full timezone information.
"""
log.debug("get_db_prep_save: {}, {}", value, type(value))
if not value:
return ''
# For underlying (database) string types, e.g. VARCHAR, this
# function must always return a string type.
# https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/
return python_localized_datetime_to_human_iso(value) | python | def get_db_prep_save(self, value, connection, prepared=False):
"""
Convert Python value to database value for SAVING.
We save with full timezone information.
"""
log.debug("get_db_prep_save: {}, {}", value, type(value))
if not value:
return ''
# For underlying (database) string types, e.g. VARCHAR, this
# function must always return a string type.
# https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/
return python_localized_datetime_to_human_iso(value) | [
"def",
"get_db_prep_save",
"(",
"self",
",",
"value",
",",
"connection",
",",
"prepared",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"\"get_db_prep_save: {}, {}\"",
",",
"value",
",",
"type",
"(",
"value",
")",
")",
"if",
"not",
"value",
":",
"ret... | Convert Python value to database value for SAVING.
We save with full timezone information. | [
"Convert",
"Python",
"value",
"to",
"database",
"value",
"for",
"SAVING",
".",
"We",
"save",
"with",
"full",
"timezone",
"information",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/django/fields/isodatetimetz.py#L268-L279 | train | 53,296 |
RudolfCardinal/pythonlib | cardinal_pythonlib/tools/list_all_file_extensions.py | list_file_extensions | def list_file_extensions(path: str, reportevery: int = 1) -> List[str]:
"""
Returns a sorted list of every file extension found in a directory
and its subdirectories.
Args:
path: path to scan
reportevery: report directory progress after every *n* steps
Returns:
sorted list of every file extension found
"""
extensions = set()
count = 0
for root, dirs, files in os.walk(path):
count += 1
if count % reportevery == 0:
log.debug("Walking directory {}: {!r}", count, root)
for file in files:
filename, ext = os.path.splitext(file)
extensions.add(ext)
return sorted(list(extensions)) | python | def list_file_extensions(path: str, reportevery: int = 1) -> List[str]:
"""
Returns a sorted list of every file extension found in a directory
and its subdirectories.
Args:
path: path to scan
reportevery: report directory progress after every *n* steps
Returns:
sorted list of every file extension found
"""
extensions = set()
count = 0
for root, dirs, files in os.walk(path):
count += 1
if count % reportevery == 0:
log.debug("Walking directory {}: {!r}", count, root)
for file in files:
filename, ext = os.path.splitext(file)
extensions.add(ext)
return sorted(list(extensions)) | [
"def",
"list_file_extensions",
"(",
"path",
":",
"str",
",",
"reportevery",
":",
"int",
"=",
"1",
")",
"->",
"List",
"[",
"str",
"]",
":",
"extensions",
"=",
"set",
"(",
")",
"count",
"=",
"0",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
... | Returns a sorted list of every file extension found in a directory
and its subdirectories.
Args:
path: path to scan
reportevery: report directory progress after every *n* steps
Returns:
sorted list of every file extension found | [
"Returns",
"a",
"sorted",
"list",
"of",
"every",
"file",
"extension",
"found",
"in",
"a",
"directory",
"and",
"its",
"subdirectories",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/tools/list_all_file_extensions.py#L43-L65 | train | 53,297 |
RudolfCardinal/pythonlib | cardinal_pythonlib/platformfunc.py | are_debian_packages_installed | def are_debian_packages_installed(packages: List[str]) -> Dict[str, bool]:
"""
Check which of a list of Debian packages are installed, via ``dpkg-query``.
Args:
packages: list of Debian package names
Returns:
dict: mapping from package name to boolean ("present?")
"""
assert len(packages) >= 1
require_executable(DPKG_QUERY)
args = [
DPKG_QUERY,
"-W", # --show
# "-f='${Package} ${Status} ${Version}\n'",
"-f=${Package} ${Status}\n", # --showformat
] + packages
completed_process = subprocess.run(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False)
encoding = sys.getdefaultencoding()
stdout = completed_process.stdout.decode(encoding)
stderr = completed_process.stderr.decode(encoding)
present = OrderedDict()
for line in stdout.split("\n"):
if line: # e.g. "autoconf install ok installed"
words = line.split()
assert len(words) >= 2
package = words[0]
present[package] = "installed" in words[1:]
for line in stderr.split("\n"):
if line: # e.g. "dpkg-query: no packages found matching XXX"
words = line.split()
assert len(words) >= 2
package = words[-1]
present[package] = False
log.debug("Debian package presence: {}", present)
return present | python | def are_debian_packages_installed(packages: List[str]) -> Dict[str, bool]:
"""
Check which of a list of Debian packages are installed, via ``dpkg-query``.
Args:
packages: list of Debian package names
Returns:
dict: mapping from package name to boolean ("present?")
"""
assert len(packages) >= 1
require_executable(DPKG_QUERY)
args = [
DPKG_QUERY,
"-W", # --show
# "-f='${Package} ${Status} ${Version}\n'",
"-f=${Package} ${Status}\n", # --showformat
] + packages
completed_process = subprocess.run(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False)
encoding = sys.getdefaultencoding()
stdout = completed_process.stdout.decode(encoding)
stderr = completed_process.stderr.decode(encoding)
present = OrderedDict()
for line in stdout.split("\n"):
if line: # e.g. "autoconf install ok installed"
words = line.split()
assert len(words) >= 2
package = words[0]
present[package] = "installed" in words[1:]
for line in stderr.split("\n"):
if line: # e.g. "dpkg-query: no packages found matching XXX"
words = line.split()
assert len(words) >= 2
package = words[-1]
present[package] = False
log.debug("Debian package presence: {}", present)
return present | [
"def",
"are_debian_packages_installed",
"(",
"packages",
":",
"List",
"[",
"str",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"bool",
"]",
":",
"assert",
"len",
"(",
"packages",
")",
">=",
"1",
"require_executable",
"(",
"DPKG_QUERY",
")",
"args",
"=",
"[",... | Check which of a list of Debian packages are installed, via ``dpkg-query``.
Args:
packages: list of Debian package names
Returns:
dict: mapping from package name to boolean ("present?") | [
"Check",
"which",
"of",
"a",
"list",
"of",
"Debian",
"packages",
"are",
"installed",
"via",
"dpkg",
"-",
"query",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/platformfunc.py#L104-L144 | train | 53,298 |
RudolfCardinal/pythonlib | cardinal_pythonlib/platformfunc.py | require_debian_packages | def require_debian_packages(packages: List[str]) -> None:
"""
Ensure specific packages are installed under Debian.
Args:
packages: list of packages
Raises:
ValueError: if any are missing
"""
present = are_debian_packages_installed(packages)
missing_packages = [k for k, v in present.items() if not v]
if missing_packages:
missing_packages.sort()
msg = (
"Debian packages are missing, as follows. Suggest:\n\n"
"sudo apt install {}".format(" ".join(missing_packages))
)
log.critical(msg)
raise ValueError(msg) | python | def require_debian_packages(packages: List[str]) -> None:
"""
Ensure specific packages are installed under Debian.
Args:
packages: list of packages
Raises:
ValueError: if any are missing
"""
present = are_debian_packages_installed(packages)
missing_packages = [k for k, v in present.items() if not v]
if missing_packages:
missing_packages.sort()
msg = (
"Debian packages are missing, as follows. Suggest:\n\n"
"sudo apt install {}".format(" ".join(missing_packages))
)
log.critical(msg)
raise ValueError(msg) | [
"def",
"require_debian_packages",
"(",
"packages",
":",
"List",
"[",
"str",
"]",
")",
"->",
"None",
":",
"present",
"=",
"are_debian_packages_installed",
"(",
"packages",
")",
"missing_packages",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"present",
".",
"... | Ensure specific packages are installed under Debian.
Args:
packages: list of packages
Raises:
ValueError: if any are missing | [
"Ensure",
"specific",
"packages",
"are",
"installed",
"under",
"Debian",
"."
] | 0b84cb35f38bd7d8723958dae51b480a829b7227 | https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/platformfunc.py#L147-L167 | train | 53,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.