code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
tables = list(metadata.tables.values()) # type: List[Table] all_deps = get_all_dependencies(metadata, extra_dependencies) tdcmap = {} # type: Dict[Table, TableDependencyClassification] for table in tables: parents = [td.parent_table for td in all_deps if td.child_table ...
def classify_tables_by_dependency_type( metadata: MetaData, extra_dependencies: List[TableDependency] = None, sort: bool = True) \ -> List[TableDependencyClassification]
Inspects a metadata object (optionally adding other specified dependencies) and returns a list of objects describing their dependencies. Args: metadata: the :class:`MetaData` to inspect extra_dependencies: additional dependencies sort: sort the results by table name? Returns: ...
1.996452
2.055019
0.971501
self._parent.set_metadata(metadata) self._child.set_metadata(metadata)
def set_metadata(self, metadata: MetaData) -> None
Sets the metadata for the parent and child tables.
5.884161
2.238962
2.628075
self._parent.set_metadata_if_none(metadata) self._child.set_metadata_if_none(metadata)
def set_metadata_if_none(self, metadata: MetaData) -> None
Sets the metadata for the parent and child tables, unless they were set already.
3.871231
2.212611
1.749621
self.circular = circular self.circular_chain = chain or []
def set_circular(self, circular: bool, chain: List[Table] = None) -> None
Mark this table as circular (or not). Args: circular: is it circular? chain: if it's circular, this should be the list of tables participating in the circular chain
9.10388
7.734124
1.177106
if self.is_parent and self.is_child: desc = "parent+child" elif self.is_parent: desc = "parent" elif self.is_child: desc = "child" else: desc = "standalone" if self.circular: desc += "+CIRCULAR({})".format(self....
def description(self) -> str
Short description.
3.765327
3.466924
1.086071
memfile = io.BytesIO() wb.save(memfile) return memfile.getvalue()
def excel_to_bytes(wb: Workbook) -> bytes
Obtain a binary version of an :class:`openpyxl.Workbook` representation of an Excel file.
3.991449
3.573375
1.116997
c = coordinates r = N.linalg.norm(c,axis=0) theta = N.arccos(c[2]/r) phi = N.arctan2(c[1],c[0]) return N.column_stack((r,theta,phi))
def spherical(coordinates)
No error is propagated
2.310324
2.282236
1.012307
coordinates = N.array(coordinates) means = N.mean(coordinates,axis=0) return coordinates - means
def centered(coordinates)
Centers coordinate distribution with respect to its mean on all three axes. This is used as the input to the regression model, so it can be converted easily into radial coordinates.
4.924454
5.625759
0.87534
if offered_filename is None: offered_filename = '' if content_type is None: content_type = 'application/force-download' response['Content-Type'] = content_type if as_attachment: prefix = 'attachment; ' elif as_inline: prefix = 'inline; ' else: prefix ...
def add_http_headers_for_attachment(response: HttpResponse, offered_filename: str = None, content_type: str = None, as_attachment: bool = False, as_inline: bool = False, ...
Add HTTP headers to a Django response class object. Args: response: ``HttpResponse`` instance offered_filename: filename that the client browser will suggest content_type: HTTP content type as_attachment: if True, browsers will generally save to disk. If False, they may...
1.953668
2.10523
0.928007
# http://stackoverflow.com/questions/1156246/having-django-serve-downloadable-files # noqa # https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment # noqa # https://djangosnippets.org/snippets/365/ if offered_filename is None: ...
def serve_file(path_to_file: str, offered_filename: str = None, content_type: str = None, as_attachment: bool = False, as_inline: bool = False) -> HttpResponseBase
Serve up a file from disk. Two methods (chosen by ``settings.XSENDFILE``): (a) serve directly (b) serve by asking the web server to do so via the X-SendFile directive.
2.382401
2.333754
1.020845
response = HttpResponse(data) add_http_headers_for_attachment(response, offered_filename=offered_filename, content_type=content_type, as_attachment=as_attachment, ...
def serve_buffer(data: bytes, offered_filename: str = None, content_type: str = None, as_attachment: bool = True, as_inline: bool = False) -> HttpResponse
Serve up binary data from a buffer. Options as for ``serve_file()``.
2.456582
2.609002
0.941579
# https://docs.djangoproject.com/en/1.9/howto/outputting-csv/ add_http_headers_for_attachment(response) response['Content-Disposition'] = 'attachment; filename="{}"'.format( filename)
def add_download_filename(response: HttpResponse, filename: str) -> None
Adds a ``Content-Disposition`` header to the HTTP response to say that there is an attachment with the specified filename.
3.836474
3.631311
1.056499
response = HttpResponse(data, content_type=content_type) add_download_filename(response, filename) return response
def file_response(data: Union[bytes, str], # HttpResponse encodes str if req'd content_type: str, filename: str) -> HttpResponse
Returns an ``HttpResponse`` with an attachment containing the specified data with the specified filename as an attachment.
3.980323
4.185509
0.950977
pdf = get_concatenated_pdf_from_disk(filenames, **kwargs) return serve_buffer(pdf, offered_filename=offered_filename, content_type=MimeType.PDF, as_attachment=False, as_inline=True)
def serve_concatenated_pdf_from_disk( filenames: Iterable[str], offered_filename: str = "crate_download.pdf", **kwargs) -> HttpResponse
Concatenates PDFs from disk and serves them.
4.051478
3.719066
1.089381
pdf = get_pdf_from_html(html, **kwargs) return serve_buffer(pdf, offered_filename=offered_filename, content_type=MimeType.PDF, as_attachment=False, as_inline=True)
def serve_pdf_from_html(html: str, offered_filename: str = "test.pdf", **kwargs) -> HttpResponse
Same args as ``pdf_from_html()``. WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish.
4.281779
3.992598
1.072429
pdf = get_concatenated_pdf_in_memory(pdf_plans, start_recto=start_recto) return serve_buffer(pdf, offered_filename=offered_filename, content_type=MimeType.PDF, as_attachment=False, as_inline=True)
def serve_concatenated_pdf_from_memory( pdf_plans: Iterable[PdfPlan], start_recto: bool = True, offered_filename: str = "crate_download.pdf") -> HttpResponse
Concatenates PDFs into memory and serves it. WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish.
3.647211
3.254164
1.120783
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
Deletes files from filesystem when object is deleted.
2.533612
2.167041
1.169157
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 ...
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.
2.341697
2.2968
1.019548
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)
Creates an affine transformation matrix to rotate data in PCA axes into Cartesian plane
9.49833
10.10018
0.940412
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)
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...
11.150908
9.733251
1.145651
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)
Property to support lazy evaluation of residuals
7.500133
6.723348
1.115535
_ = self.rotated() _[:,-1] = 0 _ = N.dot(_,self.axes) return self.arr - _
def residuals(self)
Returns residuals of fit against all three data axes (singular values 1, 2, and 3). This takes the form of data along singular axis 3 (axes 1 and 2 define the plane)
16.302931
14.7822
1.102876
hyp_axes = self.method(self) return N.arctan2(hyp_axes[-1],axis_length)
def angular_error(self, axis_length)
The angular error for an in-plane axis of given length (either a PCA major axis or an intermediate direction).
12.050144
13.01838
0.925625
hyp_axes = self.method(self) v = angular_errors(hyp_axes) if degrees: v = N.degrees(v) return tuple(v)
def angular_errors(self, degrees=True)
Minimum and maximum angular errors corresponding to 1st and 2nd axes of PCA distribution.
8.745137
8.795812
0.994239
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')
Constructs the covariance matrix from PCA residuals
6.205337
6.267017
0.990158
v = N.diagonal(self.covariance_matrix) return v[0:2].sum()/v.sum()
def explained_variance(self)
Proportion of variance that is explained by the first two principal components (which together represent the planar fit). Analogous to R^2 of linear least squares.
10.097118
8.540428
1.182273
n = self.axes[2] r = N.linalg.norm(n) strike = N.degrees(N.arctan2(n[0],n[1]))-90 dip = N.degrees(N.arccos(n[2]/r)) # Since PCA errors are not pinned to the XYZ plane, # we need to make sure our results are in the # right quadrant. if dip > 90: ...
def strike_dip(self, degrees=True)
Computes strike and dip from a normal vector. Results are usually the same as LLSQ in strike (to a few decimal places) and close in dip. Sometimes, dips are greater by as much as 45 degrees, reflecting inclusion of errors in x-y plane.
4.635539
4.476001
1.035643
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)
Hyperbolic error area
7.477622
7.658988
0.97632
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) r...
def run(self, line)
Extract words from tweet 1. Remove non-ascii characters 2. Split line into individual words 3. Clean up puncuation characters
3.583657
2.736624
1.309517
# https://stackoverflow.com/questions/6455560/how-to-get-column-names-from-sqlalchemy-result-declarative-syntax # noqa # No! Returns e.g. "User" for session.Query(User)... # fieldnames = [cd['name'] for cd in query.column_descriptions] result = session.execute(query) # type: ResultProxy field...
def get_rows_fieldnames_from_query( session: Union[Session, Engine, Connection], query: Query) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]
Returns results and column names from a query. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object query: SQLAlchemy :class:`Query` Returns: ``(rows, fieldnames)`` where ``rows`` is the usual set of results and ``fieldnames`` a...
7.617562
7.88968
0.96551
# 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
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#...
3.86915
4.606661
0.839903
# 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
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)
3.190449
3.993726
0.798865
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) ...
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 ...
1.836168
1.985173
0.924941
count_query = (self.statement.with_only_columns([func.count()]) .order_by(None)) return self.session.execute(count_query).scalar()
def count_star(self) -> int
Implements the ``COUNT(*)`` specialization.
5.00194
3.410755
1.46652
geojson = None if not self.is_valid_src(src): error = "File < {0} > does not exists or does start with 'http'." raise ValueError(error.format(src)) if not self.is_url(src): return open(src, 'r').read().decode('latin-1').encode('utf-8') tmp = s...
def read(self, src)
Download GeoJSON file of US counties from url (S3 bucket)
3.83598
3.659729
1.04816
randbytes = os.urandom(num_bytes) # YES return base64.urlsafe_b64encode(randbytes).decode('ascii')
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...
4.9982
3.43814
1.453751
if self._table is not None: return self._table assert self._metadata, ( "Must specify metadata (in constructor or via set_metadata()/" "set_metadata_if_none() before you can get a Table from a " "tablename" ) for table in self._met...
def table(self) -> Table
Returns a SQLAlchemy :class:`Table` object. This is either the :class:`Table` object that was used for initialization, or one that was constructed from the ``tablename`` plus the ``metadata``.
4.211335
3.887373
1.083337
if self._tablename: return self._tablename return self.table.name
def tablename(self) -> str
Returns the string name of the table.
7.242191
4.619155
1.56786
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
Uses the Unix ``ps`` program to see if a process is running.
3.227955
2.775749
1.162913
parser = ArgumentParser( description="Pauses and resumes a process by disk space; LINUX ONLY." ) parser.add_argument( "process_id", type=int, help="Process ID." ) parser.add_argument( "--path", required=True, help="Path to check free space for (e.g. '/')"...
def main() -> None
Command-line handler for the ``pause_process_by_disk_space`` tool. Use the ``--help`` option for help.
2.461396
2.351258
1.046843
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.appen...
def bootstrap_noise(data, func, n=10000, std=1, symmetric=True)
Bootstrap by adding noise
3.582611
3.558661
1.00673
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 ...
def modelrepr(instance) -> str
Default ``repr`` version of a Django model object, for debugging.
2.726653
2.530723
1.07742
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 we...
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
3.472306
3.046674
1.139704
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, ...
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", ...
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
1.610314
1.472636
1.093491
memfile = io.BytesIO() writer.write(memfile) memfile.seek(0) return memfile.read()
def pdf_from_writer(writer: Union[PdfFileWriter, PdfFileMerger]) -> bytes
Extracts a PDF (as binary data) from a PyPDF2 writer or merger object.
3.141397
2.385976
1.316609
if not input_pdf: return if start_recto and writer.getNumPages() % 2 != 0: writer.addBlankPage() # ... suitable for double-sided printing infile = io.BytesIO(input_pdf) reader = PdfFileReader(infile) for page_num in range(reader.numPages): writer.addPage(reader.g...
def append_memory_pdf_to_writer(input_pdf: bytes, writer: PdfFileWriter, start_recto: bool = True) -> None
Appends a PDF (as bytes in memory) to a PyPDF2 writer. Args: input_pdf: the PDF, as ``bytes`` writer: the writer start_recto: start a new right-hand page?
3.728009
3.590209
1.038382
append_memory_pdf_to_writer(input_pdf=input_pdf, writer=output_writer)
def append_pdf(input_pdf: bytes, output_writer: PdfFileWriter)
Appends a PDF to a pyPDF writer. Legacy interface.
7.396873
5.868876
1.260356
# 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 !=...
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``
2.746227
2.806203
0.978627
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
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``
3.601739
3.791734
0.949892
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)...
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?
3.331005
3.238402
1.028595
if n == int(n): return int(n) return n
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``.
4.935056
4.82485
1.022841
if with_addr: return "<{qualname}({elements}) at {addr}>".format( qualname=obj.__class__.__qualname__, elements=joiner.join(elements), addr=hex(id(obj))) else: return "{qualname}({elements})".format( qualname=obj.__class__.__qualname__, ...
def repr_result(obj: Any, elements: List[str], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str
Internal function to make a :func:`repr`-style representation of an object. Args: obj: object to display elements: list of object ``attribute=value`` strings with_addr: include the memory address of ``obj`` joiner: string with which to join the elements Returns: string:...
2.139077
2.131951
1.003343
if sort_attrs: keys = sorted(obj.__dict__.keys()) else: keys = obj.__dict__.keys() elements = ["{}={}".format(k, repr(getattr(obj, k))) for k in keys] return repr_result(obj, elements, with_addr=with_addr, joiner=joiner)
def auto_repr(obj: Any, with_addr: bool = False, sort_attrs: bool = True, joiner: str = COMMA_SPACE) -> str
Convenience function for :func:`__repr__`. Works its way through the object's ``__dict__`` and reports accordingly. Args: obj: object to display with_addr: include the memory address of ``obj`` sort_attrs: sort the attributes into alphabetical order? joiner: string with which to...
2.848865
2.850729
0.999346
elements = ["{}={}".format(name, repr(getattr(obj, name))) for name in attrnames] return repr_result(obj, elements, with_addr=with_addr, joiner=joiner)
def simple_repr(obj: Any, attrnames: List[str], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str
Convenience function for :func:`__repr__`. Works its way through a list of attribute names, and creates a ``repr()`` representation assuming that parameters to the constructor have the same names. Args: obj: object to display attrnames: names of attributes to include with_addr: ...
4.184987
4.561297
0.917499
elements = ["{}={}".format(init_param_name, repr(getattr(obj, attr_name))) for attr_name, init_param_name in attributes] return repr_result(obj, elements, with_addr=with_addr, joiner=joiner)
def mapped_repr(obj: Any, attributes: List[Tuple[str, str]], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str
Convenience function for :func:`__repr__`. Takes attribute names and corresponding initialization parameter names (parameters to :func:`__init__`). Args: obj: object to display attributes: list of tuples, each ``(attr_name, init_param_name)``. with_addr: include the memory address o...
4.427923
3.493563
1.267452
attributes = [] for attr_name in attrnames: if attr_name.startswith('_'): init_param_name = attr_name[1:] else: init_param_name = attr_name attributes.append((attr_name, init_param_name)) return mapped_repr(obj, attributes, with_addr=with_addr, joiner=joi...
def mapped_repr_stripping_underscores( obj: Any, attrnames: List[str], with_addr: bool = False, joiner: str = COMMA_SPACE) -> str
Convenience function for :func:`__repr__`. Here, you pass a list of internal attributes, and it assumes that the :func:`__init__` parameter names have the leading underscore dropped. Args: obj: object to display attrnames: list of attribute names with_addr: include the memory addres...
2.639515
2.59006
1.019094
return "<{classname}({kvp})>".format( classname=type(obj).__name__, kvp=joiner.join("{}={}".format(a, repr(getattr(obj, a))) for a in attrlist) )
def ordered_repr(obj: object, attrlist: Iterable[str], joiner: str = COMMA_SPACE) -> str
Shortcut to make :func:`repr` functions ordered. Define your :func:`__repr__` like this: .. code-block:: python def __repr__(self): return ordered_repr(self, ["field1", "field2", "field3"]) Args: obj: object to display attrlist: iterable of attribute names join...
3.646069
4.251442
0.857607
return pprint.pformat(obj.__dict__, indent=indent, width=width, depth=depth, compact=compact)
def auto_str(obj: Any, indent: int = 4, width: int = 80, depth: int = None, compact: bool = False) -> str
Make a pretty :func:`str()` representation using :func:`pprint.pformat` and the object's ``__dict__`` attribute. Args: obj: object to display indent: see https://docs.python.org/3/library/pprint.html#pprint.PrettyPrinter width: as above depth: as above compac...
4.375093
5.001478
0.87476
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') ...
def timedelta_days(days: int) -> timedelta64
Convert a duration in days to a NumPy ``timedelta64`` object.
5.070814
5.051861
1.003752
# 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...
def _get_generic_two_antidep_episodes_result( rowdata: Tuple[Any, ...] = None) -> DataFrame
Create a results row for this application.
2.975374
2.886774
1.030692
# Say hello log.info("Running two_antidepressant_episodes...") start = Pendulum.now() # Work through each patient patient_ids = sorted(list(set(patient_drug_date_df[patient_colname]))) n_patients = len(patient_ids) log.info("Found {} patients", n_patients) flush_stdout_stderr() ...
def two_antidepressant_episodes( patient_drug_date_df: DataFrame, patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME, drug_colname: str = DEFAULT_SOURCE_DRUG_COLNAME, date_colname: str = DEFAULT_SOURCE_DATE_COLNAME, course_length_days: int = DEFAULT_ANTIDEPRESSANT_COURSE_LENGT...
Takes a *pandas* ``DataFrame``, ``patient_drug_date_df`` (or, via ``reticulate``, an R ``data.frame`` or ``data.table``). This should contain dated present-tense references to antidepressant drugs (only). Returns a set of result rows as a ``DataFrame``.
2.606895
2.643415
0.986184
required_unrtf_version = Version("0.21.9") # ... probably: http://hg.savannah.gnu.org/hgweb/unrtf/ # ... 0.21.9 definitely supports --quiet # ... 0.19.3 definitely doesn't support it unrtf_filename = shutil.which('unrtf') if not unrtf_filename: return False p = subprocess.Popen(...
def does_unrtf_support_quiet() -> bool
The unrtf tool supports the '--quiet' argument from a version that I'm not quite sure of, where ``0.19.3 < version <= 0.21.9``. We check against 0.21.9 here.
3.379261
2.956897
1.14284
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
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
2.594904
2.706159
0.958888
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
Returns the binary contents of a file, or of a BLOB.
2.611487
2.208583
1.182427
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) ...
def get_chardet_encoding(binary_contents: bytes) -> Optional[str]
Guess the character set encoding of the specified ``binary_contents``.
3.84173
3.798082
1.011492
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://doc...
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.
3.365636
3.222536
1.044406
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
Returns text output of a command.
3.327708
2.834369
1.174056
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
Returns text output of a command, passing binary data in via stdin.
2.544714
2.129573
1.194941
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_filelik...
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.
2.766392
2.694621
1.026635
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
Is a PDF-to-text tool available?
7.029561
5.324016
1.320349
try: z = zipfile.ZipFile(fp) filelist = z.namelist() for filename in filelist: if DOCX_HEADER_FILE_REGEX.match(filename): yield z.read(filename).decode("utf8") yield z.read(DOCX_DOC_FILE) for filename in filelist: if DOCX_FOOTER_FI...
def gen_xml_files_from_docx(fp: BinaryIO) -> Iterator[str]
Generate XML files (as strings) from a DOCX file. Args: fp: :class:`BinaryIO` object for reading the ``.DOCX`` file Yields: the string contents of each individual XML file within the ``.DOCX`` file Raises: zipfile.BadZipFile: if the zip is unreadable (encrypted?)
3.232994
3.129435
1.033092
root = ElementTree.fromstring(xml) return docx_text_from_xml_node(root, 0, config)
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
3.910561
5.343849
0.731787
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 ==...
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
2.407799
2.416476
0.996409
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 i...
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 representat...
2.331943
2.525872
0.923223
if width: return '\n'.join(textwrap.wrap(text, width=width)) else: return 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
4.125461
3.626994
1.137433
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 tab...
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 cre...
2.835045
2.738203
1.035367
# only called if docx loaded 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(): ...
def docx_docx_iter_block_items(parent: DOCX_CONTAINER_TYPE) \ -> Iterator[DOCX_BLOCK_ITEM_TYPE]
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...
2.741933
2.816
0.973698
# only called if docx loaded 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): yie...
def docx_docx_gen_text(doc: DOCX_DOCUMENT_TYPE, config: TextProcessingConfig) -> Iterator[str]
Iterate through a DOCX file and yield text. Args: doc: DOCX document to process config: :class:`TextProcessingConfig` control object Yields: pieces of text (paragraphs)
3.000235
3.372576
0.889597
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
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.py...
7.036184
4.526418
1.554471
# 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 = Eleme...
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.
6.53218
6.185168
1.056104
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
Converts HTML to text.
7.613908
5.626039
1.353334
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
Converts XML to text.
8.92321
6.911873
1.290997
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_stdi...
def convert_rtf_to_text(filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str
Converts RTF to text.
6.531465
6.347048
1.029056
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
Is an RTF processor available?
14.902426
10.961787
1.359489
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: ...
def convert_doc_to_text(filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str
Converts Microsoft Word DOC files to text.
9.620286
8.66169
1.110671
strings = tools['strings'] or tools['strings2'] if strings: if filename: return get_cmd_output(strings, filename) else: return get_cmd_output_from_stdin(blob, strings) else: raise AssertionError("No fallback string-reading tool available")
def convert_anything_to_text( filename: str = None, blob: bytes = None, config: TextProcessingConfig = _DEFAULT_CONFIG) -> str
Convert arbitrary files to text, using ``strings`` or ``strings2``. (``strings`` is a standard Unix command to get text from any old rubbish.)
12.095606
7.292756
1.658578
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") ...
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 argume...
3.363414
3.416853
0.98436
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() els...
def is_text_extractor_available(extension: str) -> bool
Is a text extractor available for the specified extension?
4.017738
3.459429
1.161388
logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() parser.add_argument("inputfile", nargs="?", help="Input file name") parser.add_argument( "--availability", nargs='*', help="File extensions to check availability for (use a '.' prefix, " "and us...
def main() -> None
Command-line processor. See ``--help`` for details.
3.604212
3.533477
1.020018
if verbose: set_loglevel(logging.DEBUG) else: set_loglevel(logging.INFO)
def set_verbose_logging(verbose: bool) -> None
Chooses basic or verbose logging.
3.505172
2.376782
1.474755
log.debug("SQL: %s" % sql) if args: log.debug("Args: %r" % args)
def debug_sql(sql: str, *args: Any) -> None
Writes SQL and arguments to the log.
4.17983
2.852317
1.465416
return delims[0] + x + delims[1]
def delimit(x: str, delims: Tuple[str, str]) -> str
Delimits x, using delims[0] (left) and delims[1] (right).
6.655415
3.30381
2.014467
return ( "SELECT " + ",".join([delimit(x, delims) for x in fieldlist]) + " FROM " + delimit(table, delims) + " WHERE " + delimit(keyname, delims) + "=?" )
def get_sql_select_all_fields_by_key( table: str, fieldlist: Sequence[str], keyname: str, delims: Tuple[str, str] = ("", "")) -> str
Returns SQL: SELECT [all fields in the fieldlist] WHERE [keyname] = ?
2.672793
2.406997
1.110426
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
Returns ?-marked SQL for an INSERT statement.
2.64294
2.407364
1.097856
# http://stackoverflow.com/questions/4205181 return .format( table=delimit(table, delims), fields=",".join([delimit(x, delims) for x in fieldlist]), placeholders=",".join(["?"] * len(fieldlist)), updatelist=",".join( ["{field}=VALUES({field})".format(field=delimi...
def get_sql_insert_or_update(table: str, fieldlist: Sequence[str], delims: Tuple[str, str] = ("", "")) -> str
Returns ?-marked SQL for an INSERT-or-if-duplicate-key-UPDATE statement.
3.740708
3.479119
1.075188
return get_sql_insert(table, fieldlist[1:], delims)
def get_sql_insert_without_first_field( table: str, fieldlist: Sequence[str], delims: Tuple[str, str] = ("", "")) -> str
Returns ?-marked SQL for an INSERT statement, ignoring the first field (typically, the PK).
7.031636
4.691419
1.498829
return ( "UPDATE " + delimit(table, delims) + " SET " + ",".join([delimit(x, delims) + "=?" for x in fieldlist[1:]]) + " WHERE " + delimit(fieldlist[0], delims) + "=?" )
def get_sql_update_by_first_field(table: str, fieldlist: Sequence[str], delims: Tuple[str, str] = ("", "")) -> str
Returns SQL for an UPDATE statement, to update all fields except the first field (PK) using the PK as the key.
2.801555
2.509061
1.116575
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
Reverses sql_quote_string.
5.438653
4.335155
1.254547
# 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_l...
def datetime2literal_rnc(d: datetime.datetime, c: Optional[Dict]) -> str
Format a DateTime object as something MySQL will actually accept.
7.171228
6.231665
1.150773
d = d.upper() (s, length) = split_long_sqltype(d) if d in ["VARCHAR(MAX)", "NVARCHAR(MAX)"]: # http://wiki.ispirer.com/sqlways/mysql/data-types/longtext return "LONGTEXT" elif d in ["VARBINARY(MAX)"] or s in ["IMAGE"]: # http://wiki.ispirer.com/sqlways/mysql/data-types/varbi...
def full_datatype_to_mysql(d: str) -> str
Converts a full datatype, e.g. INT, VARCHAR(10), VARCHAR(MAX), to a MySQL equivalent.
5.230367
4.832036
1.082435