repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FilesIterator.rename
python
def rename(self, old_key, new_key): assert new_key not in self assert old_key != new_key file_ = self[old_key] old_data = self.filesmap[old_key] # Create a new version with the new name obj = ObjectVersion.create( bucket=self.bucket, key=new_key, ...
Rename a file. :param old_key: Old key that holds the object. :param new_key: New key that will hold the object. :returns: The object that has been renamed.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L195-L218
null
class FilesIterator(object): """Iterator for files.""" def __init__(self, record, bucket=None, file_cls=None): """Initialize iterator.""" self._it = None self.record = record self.model = record.model self.file_cls = file_cls or FileObject self.bucket = bucket ...
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FilesIterator.dumps
python
def dumps(self, bucket=None): return [ self.file_cls(o, self.filesmap.get(o.key, {})).dumps() for o in sorted_files_from_bucket(bucket or self.bucket, self.keys) ]
Serialize files from a bucket. :param bucket: Instance of files :class:`invenio_files_rest.models.Bucket`. (Default: ``self.bucket``) :returns: List of serialized files.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L220-L231
[ "def sorted_files_from_bucket(bucket, keys=None):\n \"\"\"Return files from bucket sorted by given keys.\n\n :param bucket: :class:`~invenio_files_rest.models.Bucket` containing the\n files.\n :param keys: Keys order to be used.\n :returns: Sorted list of bucket items.\n \"\"\"\n keys = key...
class FilesIterator(object): """Iterator for files.""" def __init__(self, record, bucket=None, file_cls=None): """Initialize iterator.""" self._it = None self.record = record self.model = record.model self.file_cls = file_cls or FileObject self.bucket = bucket ...
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FilesMixin.files
python
def files(self): if self.model is None: raise MissingModelError() records_buckets = RecordsBuckets.query.filter_by( record_id=self.id).first() if not records_buckets: bucket = self._create_bucket() if not bucket: return None ...
Get files iterator. :returns: Files iterator.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L263-L282
null
class FilesMixin(object): """Implement files attribute for Record models. .. note:: Implement ``_create_bucket()`` in subclass to allow files property to automatically create a bucket in case no bucket is present. """ file_cls = FileObject """File class used to generate the instance...
inveniosoftware/invenio-records-files
invenio_records_files/api.py
FilesMixin.files
python
def files(self, data): current_files = self.files if current_files: raise RuntimeError('Can not update existing files.') for key in data: current_files[key] = data[key]
Set files from data.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L285-L291
null
class FilesMixin(object): """Implement files attribute for Record models. .. note:: Implement ``_create_bucket()`` in subclass to allow files property to automatically create a bucket in case no bucket is present. """ file_cls = FileObject """File class used to generate the instance...
inveniosoftware/invenio-records-files
invenio_records_files/api.py
Record.delete
python
def delete(self, force=False): if force: RecordsBuckets.query.filter_by( record=self.model, bucket=self.files.bucket ).delete() return super(Record, self).delete(force)
Delete a record and also remove the RecordsBuckets if necessary. :param force: True to remove also the :class:`~invenio_records_files.models.RecordsBuckets` object. :returns: Deleted record.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L297-L309
null
class Record(_Record, FilesMixin): """Define API for files manipulation using ``FilesMixin``."""
inveniosoftware/invenio-records-files
invenio_records_files/models.py
RecordsBuckets.create
python
def create(cls, record, bucket): rb = cls(record=record, bucket=bucket) db.session.add(rb) return rb
Create a new RecordsBuckets and adds it to the session. :param record: Record used to relate with the ``Bucket``. :param bucket: Bucket used to relate with the ``Record``. :returns: The :class:`~invenio_records_files.models.RecordsBuckets` object created.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/models.py#L48-L58
null
class RecordsBuckets(db.Model): """Relationship between Records and Buckets.""" __tablename__ = 'records_buckets' record_id = db.Column( UUIDType, db.ForeignKey(RecordMetadata.id), primary_key=True, nullable=False, # NOTE no unique constrain for better future ... ...
inveniosoftware/invenio-records-files
invenio_records_files/utils.py
sorted_files_from_bucket
python
def sorted_files_from_bucket(bucket, keys=None): keys = keys or [] total = len(keys) sortby = dict(zip(keys, range(total))) values = ObjectVersion.get_by_bucket(bucket).all() return sorted(values, key=lambda x: sortby.get(x.key, total))
Return files from bucket sorted by given keys. :param bucket: :class:`~invenio_files_rest.models.Bucket` containing the files. :param keys: Keys order to be used. :returns: Sorted list of bucket items.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/utils.py#L19-L31
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Implementention of various utility functions.""" from __future__ import absolute_...
inveniosoftware/invenio-records-files
invenio_records_files/utils.py
record_file_factory
python
def record_file_factory(pid, record, filename): try: if not (hasattr(record, 'files') and record.files): return None except MissingModelError: return None try: return record.files[filename] except KeyError: return None
Get file from a record. :param pid: Not used. It keeps the function signature. :param record: Record which contains the files. :param filename: Name of the file to be returned. :returns: File object or ``None`` if not found.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/utils.py#L34-L51
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Implementention of various utility functions.""" from __future__ import absolute_...
inveniosoftware/invenio-records-files
invenio_records_files/utils.py
file_download_ui
python
def file_download_ui(pid, record, _record_file_factory=None, **kwargs): _record_file_factory = _record_file_factory or record_file_factory # Extract file from record. fileobj = _record_file_factory( pid, record, kwargs.get('filename') ) if not fileobj: abort(404) obj = fileobj....
File download view for a given record. Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration: .. code-block:: python RECORDS_UI_ENDPOINTS = dict( recid=dict( # ... route='/records/<pid_value/files/<filename>', view_imp='invenio_r...
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/utils.py#L54-L101
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Implementention of various utility functions.""" from __future__ import absolute_...
inveniosoftware/invenio-records-files
invenio_records_files/links.py
default_bucket_link_factory
python
def default_bucket_link_factory(pid): try: record = Record.get_record(pid.get_assigned_object()) bucket = record.files.bucket return url_for('invenio_files_rest.bucket_api', bucket_id=bucket.id, _external=True) except AttributeError: return None
Factory for record bucket generation.
train
https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/links.py#L16-L25
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Link for file bucket creation.""" from flask import url_for from .api import Rec...
tmoerman/arboreto
arboreto/core.py
to_tf_matrix
python
def to_tf_matrix(expression_matrix, gene_names, tf_names): tuples = [(index, gene) for index, gene in enumerate(gene_names) if gene in tf_names] tf_indices = [t[0] for t in tuples] tf_matrix_names = [t[1] for t in tuples] return expression_matrix[:, tf_indices], tf_m...
:param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index. :param tf_names: a list of transcription factor names. Should be a subset of gene_names. :return: tuple of: ...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L85-L102
null
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from ...
tmoerman/arboreto
arboreto/core.py
fit_model
python
def fit_model(regressor_type, regressor_kwargs, tf_matrix, target_gene_expression, early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, seed=DEMON_SEED): regressor_type = regressor_type.upper() assert tf_matrix.shape[0] == len(target_gene_expr...
:param regressor_type: string. Case insensitive. :param regressor_kwargs: a dictionary of key-value pairs that configures the regressor. :param tf_matrix: the predictor matrix (transcription factor matrix) as a numpy array. :param target_gene_expression: the target (y) gene expression to predict in function...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L105-L141
[ "def is_sklearn_regressor(regressor_type):\n \"\"\"\n :param regressor_type: string. Case insensitive.\n :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API.\n \"\"\"\n return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys()\n", "def do_sklearn_...
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from ...
tmoerman/arboreto
arboreto/core.py
to_feature_importances
python
def to_feature_importances(regressor_type, regressor_kwargs, trained_regressor): if is_oob_heuristic_supported(regressor_type, regressor_kwargs): n_estimators = len(trained_regressor.estimators_) denormalized_importances = trained_regressor.fea...
Motivation: when the out-of-bag improvement heuristic is used, we cancel the effect of normalization by dividing by the number of trees in the regression ensemble by multiplying again by the number of trees used. This enables prioritizing links that were inferred in a regression where lots of :param regre...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L144-L166
[ "def is_oob_heuristic_supported(regressor_type, regressor_kwargs):\n \"\"\"\n :param regressor_type: on\n :param regressor_kwargs:\n :return: whether early stopping heuristic based on out-of-bag improvement is supported.\n\n \"\"\"\n return \\\n regressor_type.upper() == 'GBM' and \\\n ...
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from ...
tmoerman/arboreto
arboreto/core.py
to_meta_df
python
def to_meta_df(trained_regressor, target_gene_name): n_estimators = len(trained_regressor.estimators_) return pd.DataFrame({'target': [target_gene_name], 'n_estimators': [n_estimators]})
:param trained_regressor: the trained model from which to extract the meta information. :param target_gene_name: the name of the target gene. :return: a Pandas DataFrame containing side information about the regression.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L169-L178
null
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from ...
tmoerman/arboreto
arboreto/core.py
to_links_df
python
def to_links_df(regressor_type, regressor_kwargs, trained_regressor, tf_matrix_gene_names, target_gene_name): def pythonic(): # feature_importances = trained_regressor.feature_importances_ feature_importances = to_feature_importances(r...
:param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param trained_regressor: the trained model from which to extract the feature importances. :param tf_matrix_gene_names: the list of names corresponding to the columns of the tf_ma...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L181-L212
[ "def is_sklearn_regressor(regressor_type):\n \"\"\"\n :param regressor_type: string. Case insensitive.\n :return: whether the regressor type is a scikit-learn regressor, following the scikit-learn API.\n \"\"\"\n return regressor_type.upper() in SKLEARN_REGRESSOR_FACTORY.keys()\n", "def is_xgboost_...
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from ...
tmoerman/arboreto
arboreto/core.py
clean
python
def clean(tf_matrix, tf_matrix_gene_names, target_gene_name): if target_gene_name not in tf_matrix_gene_names: clean_tf_matrix = tf_matrix else: clean_tf_matrix = np.delete(tf_matrix, tf_matrix_gene_names.index(target_gene_name), 1) clean_tf_names = [tf for tf in tf_mat...
:param tf_matrix: numpy array. The full transcription factor matrix. :param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns. :param target_gene_name: the target gene to remove from the tf_matrix and tf_names. :return: a tuple of (matrix, names) equal...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L215-L235
null
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from ...
tmoerman/arboreto
arboreto/core.py
retry
python
def retry(fn, max_retries=10, warning_msg=None, fallback_result=None): nr_retries = 0 result = fallback_result for attempt in range(max_retries): try: result = fn() except Exception as cause: nr_retries += 1 msg_head = '' if warning_msg is None else rep...
Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn: * https://github.com/scikit-learn/scikit-learn/issues/2755 * https://github.com/scikit-learn/scikit-learn/issues/7346 :param fn: the function to retry. :param max_retries: the maximum number o...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L238-L267
[ "def blue_skies():\n return 1\n", "def i_will_never_work():\n raise ValueError('never')\n", "def i_procrastinate(self):\n self.attempts += 1\n\n if self.attempts == 3:\n return 1\n else:\n raise ValueError('later')\n", "def fn():\n (clean_tf_matrix, clean_tf_matrix_gene_names) ...
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from ...
tmoerman/arboreto
arboreto/core.py
infer_partial_network
python
def infer_partial_network(regressor_type, regressor_kwargs, tf_matrix, tf_matrix_gene_names, target_gene_name, target_gene_expression, include_meta=False, ...
Ties together regressor model training with regulatory links and meta data extraction. :param regressor_type: string. Case insensitive. :param regressor_kwargs: dict of key-value pairs that configures the regressor. :param tf_matrix: numpy matrix. The feature matrix X to use for the regression. :param ...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L270-L323
[ "def retry(fn, max_retries=10, warning_msg=None, fallback_result=None):\n \"\"\"\n Minimalistic retry strategy to compensate for failures probably caused by a thread-safety bug in scikit-learn:\n * https://github.com/scikit-learn/scikit-learn/issues/2755\n * https://github.com/scikit-learn/scikit-learn/...
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from ...
tmoerman/arboreto
arboreto/core.py
target_gene_indices
python
def target_gene_indices(gene_names, target_genes): if isinstance(target_genes, list) and len(target_genes) == 0: return [] if isinstance(target_genes, str) and target_genes.upper() == 'ALL': return list(range(len(gene_names))) elif isinstance(target_genes, int): ...
:param gene_names: list of gene names. :param target_genes: either int (the top n), 'all', or a collection (subset of gene_names). :return: the (column) indices of the target genes in the expression_matrix.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L326-L357
null
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from ...
tmoerman/arboreto
arboreto/core.py
create_graph
python
def create_graph(expression_matrix, gene_names, tf_names, regressor_type, regressor_kwargs, client, target_genes='all', limit=None, include_meta=False, early_stop_wind...
Main API function. Create a Dask computation graph. Note: fixing the GC problems was fixed by 2 changes: [1] and [2] !!! :param expression_matrix: numpy matrix. Rows are observations and columns are genes. :param gene_names: list of gene names. Each entry corresponds to the expression_matrix column with s...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L364-L450
[ "def to_tf_matrix(expression_matrix,\n gene_names,\n tf_names):\n \"\"\"\n :param expression_matrix: numpy matrix. Rows are observations and columns are genes.\n :param gene_names: a list of gene names. Each entry corresponds to the expression_matrix column with same index.\...
""" Core functional building blocks, composed in a Dask graph for distributed computation. """ import numpy as np import pandas as pd import logging from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor, ExtraTreesRegressor from dask import delayed from dask.dataframe import from_delayed from ...
tmoerman/arboreto
arboreto/core.py
EarlyStopMonitor.window_boundaries
python
def window_boundaries(self, current_round): lo = max(0, current_round - self.window_length + 1) hi = current_round + 1 return lo, hi
:param current_round: :return: the low and high boundaries of the estimators window to consider.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/core.py#L462-L471
null
class EarlyStopMonitor: def __init__(self, window_length=EARLY_STOP_WINDOW_LENGTH): """ :param window_length: length of the window over the out-of-bag errors. """ self.window_length = window_length def __call__(self, current_round, regressor, _): """ Implement...
tmoerman/arboreto
arboreto/algo.py
grnboost2
python
def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): return diy(expression_data=expressio...
Launch arboreto with [GRNBoost2] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or sp...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L10-L41
[ "def diy(expression_data,\n regressor_type,\n regressor_kwargs,\n gene_names=None,\n tf_names='all',\n client_or_address='local',\n early_stop_window_length=EARLY_STOP_WINDOW_LENGTH,\n limit=None,\n seed=None,\n verbose=False):\n \"\"\"\n :param e...
""" Top-level functions. """ import pandas as pd from distributed import Client, LocalCluster from arboreto.core import create_graph, SGBM_KWARGS, RF_KWARGS, EARLY_STOP_WINDOW_LENGTH def genie3(expression_data, gene_names=None, tf_names='all', client_or_address='local', l...
tmoerman/arboreto
arboreto/algo.py
genie3
python
def genie3(expression_data, gene_names=None, tf_names='all', client_or_address='local', limit=None, seed=None, verbose=False): return diy(expression_data=expression_data, regressor_type='RF', regressor_kwargs=RF_KWARGS, gene_names=gen...
Launch arboreto with [GENIE3] profile. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list of gene names (strings). Required when a (dense or spars...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L44-L73
[ "def diy(expression_data,\n regressor_type,\n regressor_kwargs,\n gene_names=None,\n tf_names='all',\n client_or_address='local',\n early_stop_window_length=EARLY_STOP_WINDOW_LENGTH,\n limit=None,\n seed=None,\n verbose=False):\n \"\"\"\n :param e...
""" Top-level functions. """ import pandas as pd from distributed import Client, LocalCluster from arboreto.core import create_graph, SGBM_KWARGS, RF_KWARGS, EARLY_STOP_WINDOW_LENGTH def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', ...
tmoerman/arboreto
arboreto/algo.py
diy
python
def diy(expression_data, regressor_type, regressor_kwargs, gene_names=None, tf_names='all', client_or_address='local', early_stop_window_length=EARLY_STOP_WINDOW_LENGTH, limit=None, seed=None, verbose=False): if verbose: print('preparin...
:param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param regressor_type: string. One of: 'RF', 'GBM', 'ET'. Case insensitive. :param regressor_kwargs: a dictionary of key-value pa...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L76-L142
[ "def create_graph(expression_matrix,\n gene_names,\n tf_names,\n regressor_type,\n regressor_kwargs,\n client,\n target_genes='all',\n limit=None,\n include_meta=False,\n e...
""" Top-level functions. """ import pandas as pd from distributed import Client, LocalCluster from arboreto.core import create_graph, SGBM_KWARGS, RF_KWARGS, EARLY_STOP_WINDOW_LENGTH def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', ...
tmoerman/arboreto
arboreto/algo.py
_prepare_client
python
def _prepare_client(client_or_address): if client_or_address is None or str(client_or_address).lower() == 'local': local_cluster = LocalCluster(diagnostics_port=None) client = Client(local_cluster) def close_client_and_local_cluster(verbose=False): if verbose: p...
:param client_or_address: one of: * None * verbatim: 'local' * string address * a Client instance :return: a tuple: (Client instance, shutdown callback function). :raises: ValueError if no valid client input was provided.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L145-L191
null
""" Top-level functions. """ import pandas as pd from distributed import Client, LocalCluster from arboreto.core import create_graph, SGBM_KWARGS, RF_KWARGS, EARLY_STOP_WINDOW_LENGTH def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', ...
tmoerman/arboreto
arboreto/algo.py
_prepare_input
python
def _prepare_input(expression_data, gene_names, tf_names): if isinstance(expression_data, pd.DataFrame): expression_matrix = expression_data.as_matrix() gene_names = list(expression_data.columns) else: expression_matrix = expression_data ass...
Wrangle the inputs into the correct formats. :param expression_data: one of: * a pandas DataFrame (rows=observations, columns=genes) * a dense 2D numpy.ndarray * a sparse scipy.sparse.csc_matrix :param gene_names: optional list...
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/algo.py#L194-L231
null
""" Top-level functions. """ import pandas as pd from distributed import Client, LocalCluster from arboreto.core import create_graph, SGBM_KWARGS, RF_KWARGS, EARLY_STOP_WINDOW_LENGTH def grnboost2(expression_data, gene_names=None, tf_names='all', client_or_address='local', ...
tmoerman/arboreto
arboreto/utils.py
load_tf_names
python
def load_tf_names(path): with open(path) as file: tfs_in_file = [line.strip() for line in file.readlines()] return tfs_in_file
:param path: the path of the transcription factor list file. :return: a list of transcription factor names read from the file.
train
https://github.com/tmoerman/arboreto/blob/3ff7b6f987b32e5774771751dea646fa6feaaa52/arboreto/utils.py#L6-L15
null
""" Utility functions. """
TadLeonard/tfatool
tfatool/sync.py
up_down_by_arrival
python
def up_down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): local_monitor = watch_local_files(*filters, local_dir=local_dir) remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, lfile_set = next(local_monitor) _, rfile_set = next(remote_monit...
Monitors a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The generator yields bef...
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L83-L115
[ "def watch_local_files(*filters, local_dir=\".\"):\n list_local = partial(list_local_files, *filters, local_dir=local_dir)\n old_files = new_files = set(list_local())\n while True:\n yield new_files - old_files, new_files\n old_files = new_files\n new_files = set(list_local())\n", "d...
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFil...
TadLeonard/tfatool
tfatool/sync.py
up_by_arrival
python
def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): local_monitor = watch_local_files(*filters, local_dir=local_dir) _, file_set = next(local_monitor) _notify_sync_ready(len(file_set), local_dir, remote_dir) for new_arrivals, file_set in local_monitor: yield Direction.up, ...
Monitors a local directory and generates sets of new files to be uploaded to FlashAir. Sets to upload are generated in a tuple like (Direction.up, {...}). The generator yields before each upload actually takes place.
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L118-L131
[ "def watch_local_files(*filters, local_dir=\".\"):\n list_local = partial(list_local_files, *filters, local_dir=local_dir)\n old_files = new_files = set(list_local())\n while True:\n yield new_files - old_files, new_files\n old_files = new_files\n new_files = set(list_local())\n", "d...
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFil...
TadLeonard/tfatool
tfatool/sync.py
down_by_arrival
python
def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR): remote_monitor = watch_remote_files(*filters, remote_dir=remote_dir) _, file_set = next(remote_monitor) _notify_sync_ready(len(file_set), remote_dir, local_dir) for new_arrivals, file_set in remote_monitor: if new_arriv...
Monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place.
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L134-L147
[ "def watch_remote_files(*filters, remote_dir=\".\"):\n command.memory_changed() # clear change status to start\n list_remote = partial(command.list_files,\n *filters, remote_dir=remote_dir)\n old_files = new_files = set(list_remote())\n while True:\n yield new_files - ol...
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFil...
TadLeonard/tfatool
tfatool/sync.py
down_by_time
python
def down_by_time(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): files = command.list_files(*filters, remote_dir=remote_dir) most_recent = sorted(files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local...
Sync most recent file by date, time attribues
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L164-L170
[ "def _notify_sync(direction, files):\n logger.info(\"{:d} files to {:s}:\\n{}\".format(\n len(files), direction,\n \"\\n\".join(\" \" + f.filename for f in files)))\n", "def down_by_files(to_sync, local_dir=\".\"):\n \"\"\"Sync a given list of files from `command.list_files` to `local_dir` di...
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFil...
TadLeonard/tfatool
tfatool/sync.py
down_by_name
python
def down_by_name(*filters, remote_dir=DEFAULT_REMOTE_DIR, local_dir=".", count=1): files = command.list_files(*filters, remote_dir=remote_dir) greatest = sorted(files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync(Direction.down, to_sync) down_by_files(to_sync[::-1], local_dir=l...
Sync files whose filename attribute is highest in alphanumeric order
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L173-L179
[ "def _notify_sync(direction, files):\n logger.info(\"{:d} files to {:s}:\\n{}\".format(\n len(files), direction,\n \"\\n\".join(\" \" + f.filename for f in files)))\n", "def down_by_files(to_sync, local_dir=\".\"):\n \"\"\"Sync a given list of files from `command.list_files` to `local_dir` di...
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFil...
TadLeonard/tfatool
tfatool/sync.py
_write_file_safely
python
def _write_file_safely(local_path, fileinfo, response): try: _write_file(local_path, fileinfo, response) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial file".format( e.__class__.__name__, local_path)) ...
attempts to stream a remote file into a local file object, removes the local file if it's interrupted by any error
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L215-L225
null
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFil...
TadLeonard/tfatool
tfatool/sync.py
up_by_files
python
def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None): if remote_files is None: remote_files = command.map_files_raw(remote_dir=remote_dir) for local_file in to_sync: _sync_local_file(local_file, remote_dir, remote_files)
Sync a given list of local files to `remote_dir` dir
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L289-L294
[ "def _sync_local_file(local_file_info, remote_dir, remote_files):\n local_name = local_file_info.filename\n local_size = local_file_info.size\n if local_name in remote_files:\n remote_file_info = remote_files[local_name]\n remote_size = remote_file_info.size\n if local_size == remote_s...
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFil...
TadLeonard/tfatool
tfatool/sync.py
up_by_time
python
def up_by_time(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) most_recent = sorted(local_files, key=lambda f: f.datetime) to_sync = most_recent[-count:] _notif...
Sync most recent file by date, time attribues
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L297-L304
[ "def _notify_sync(direction, files):\n logger.info(\"{:d} files to {:s}:\\n{}\".format(\n len(files), direction,\n \"\\n\".join(\" \" + f.filename for f in files)))\n", "def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None):\n \"\"\"Sync a given list of local files to `re...
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFil...
TadLeonard/tfatool
tfatool/sync.py
up_by_name
python
def up_by_name(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR, count=1): remote_files = command.map_files_raw(remote_dir=remote_dir) local_files = list_local_files(*filters, local_dir=local_dir) greatest = sorted(local_files, key=lambda f: f.filename) to_sync = greatest[-count:] _notify_sync...
Sync files whose filename attribute is highest in alphanumeric order
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L307-L314
[ "def _notify_sync(direction, files):\n logger.info(\"{:d} files to {:s}:\\n{}\".format(\n len(files), direction,\n \"\\n\".join(\" \" + f.filename for f in files)))\n", "def up_by_files(to_sync, remote_dir=DEFAULT_REMOTE_DIR, remote_files=None):\n \"\"\"Sync a given list of local files to `re...
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFil...
TadLeonard/tfatool
tfatool/sync.py
_upload_file_safely
python
def _upload_file_safely(fileinfo, remote_dir): try: upload.upload_file(fileinfo.path, remote_dir=remote_dir) except BaseException as e: logger.warning("{} interrupted writing {} -- " "cleaning up partial remote file".format( e.__class__.__name__, fil...
attempts to upload a local file to FlashAir, tries to remove the remote file if interrupted by any error
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/sync.py#L344-L354
null
import logging import os import threading import time from enum import Enum from functools import partial from pathlib import Path from urllib.parse import urljoin import arrow import requests import tqdm from . import command, upload from .info import URL, DEFAULT_REMOTE_DIR from .info import RawFileInfo, SimpleFil...
TadLeonard/tfatool
tfatool/config.py
config
python
def config(param_map, mastercode=DEFAULT_MASTERCODE): pmap = {Config.mastercode: mastercode} pmap.update(param_map) processed_params = dict(_process_params(pmap)) return processed_params
Takes a dictionary of {Config.key: value} and returns a dictionary of processed keys and values to be used in the construction of a POST request to FlashAir's config.cgi
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/config.py#L8-L15
[ "def _process_params(params):\n for param, value in params.items():\n assert param in Config, \"Invalid param: {}\".format(param)\n yield param.value, value_validators[param](value)\n" ]
import logging from functools import partial from . import cgi from .info import URL, DEFAULT_MASTERCODE from .info import WifiMode, WifiModeOnBoot, ModeValue, DriveMode, Config def _process_params(params): for param, value in params.items(): assert param in Config, "Invalid param: {}".format(param) ...
TadLeonard/tfatool
tfatool/config.py
post
python
def post(param_map, url=URL): prepped_request = _prep_post(url=url, **param_map) return cgi.send(prepped_request)
Posts a `param_map` created with `config` to the FlashAir config.cgi entrypoint
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/config.py#L24-L28
null
import logging from functools import partial from . import cgi from .info import URL, DEFAULT_MASTERCODE from .info import WifiMode, WifiModeOnBoot, ModeValue, DriveMode, Config def config(param_map, mastercode=DEFAULT_MASTERCODE): """Takes a dictionary of {Config.key: value} and returns a dictionary of proce...
TadLeonard/tfatool
tfatool/config.py
_validate_timeout
python
def _validate_timeout(seconds: float): val = int(seconds * 1000) assert 60000 <= val <= 4294967294, "Bad value: {}".format(val) return val
Creates an int from 60000 to 4294967294 that represents a valid millisecond wireless LAN timeout
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/config.py#L48-L53
null
import logging from functools import partial from . import cgi from .info import URL, DEFAULT_MASTERCODE from .info import WifiMode, WifiModeOnBoot, ModeValue, DriveMode, Config def config(param_map, mastercode=DEFAULT_MASTERCODE): """Takes a dictionary of {Config.key: value} and returns a dictionary of proce...
TadLeonard/tfatool
tfatool/util.py
parse_datetime
python
def parse_datetime(datetime_input): date_els, time_els = _split_datetime(datetime_input) date_vals = _parse_date(date_els) time_vals = _parse_time(time_els) vals = tuple(date_vals) + tuple(time_vals) return arrow.get(*vals)
The arrow library is sadly not good enough to parse certain date strings. It even gives unexpected results for partial date strings such as '2015-01' or just '2015', which I think should be seen as 'the first moment of 2014'. This function should overcome those limitations.
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/util.py#L7-L17
[ "def _split_datetime(datetime_input):\n dt_input = datetime_input.split(\" \")\n if len(dt_input) == 1:\n dt_input.append(\"\")\n date_input, time_input = dt_input\n if \":\" in date_input:\n date_input, time_input = time_input, date_input\n if not date_input:\n date_input = arro...
import arrow from itertools import groupby from operator import attrgetter, itemgetter def _split_datetime(datetime_input): dt_input = datetime_input.split(" ") if len(dt_input) == 1: dt_input.append("") date_input, time_input = dt_input if ":" in date_input: date_input, time_input =...
TadLeonard/tfatool
tfatool/upload.py
_encode_time
python
def _encode_time(mtime: float): dt = arrow.get(mtime) dt = dt.to("local") date_val = ((dt.year - 1980) << 9) | (dt.month << 5) | dt.day secs = dt.second + dt.microsecond / 10**6 time_val = (dt.hour << 11) | (dt.minute << 5) | math.floor(secs / 2) return (date_val << 16) | time_val
Encode a mtime float as a 32-bit FAT time
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/upload.py#L84-L91
null
import math import os import arrow from functools import partial from . import cgi from .info import DEFAULT_REMOTE_DIR, DEFAULT_MASTERCODE, URL from .info import WriteProtectMode, Upload, ResponseCode from requests import RequestException def upload_file(local_path: str, url=URL, remote_dir=DEFAULT_REMOTE_DIR): ...
TadLeonard/tfatool
tfatool/command.py
memory_changed
python
def memory_changed(url=URL): response = _get(Operation.memory_changed, url) try: return int(response.text) == 1 except ValueError: raise IOError("Likely no FlashAir connection, " "memory changed CGI command failed")
Returns True if memory has been written to, False otherwise
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/command.py#L46-L53
[ "def _get(operation: Operation, url=URL, **params):\n \"\"\"HTTP GET of the FlashAir command.cgi entrypoint\"\"\"\n prepped_request = _prep_get(operation, url=url, **params)\n return cgi.send(prepped_request)\n" ]
import logging import arrow from pathlib import PurePosixPath from collections import namedtuple from . import cgi from .info import URL, DEFAULT_REMOTE_DIR from .info import WifiMode, WifiModeOnBoot, ModeValue, Operation from .info import FileInfo, RawFileInfo logger = logging.getLogger(__name__) ################...
TadLeonard/tfatool
tfatool/command.py
_get
python
def _get(operation: Operation, url=URL, **params): prepped_request = _prep_get(operation, url=url, **params) return cgi.send(prepped_request)
HTTP GET of the FlashAir command.cgi entrypoint
train
https://github.com/TadLeonard/tfatool/blob/12da2807b5fb538c5317ef255d846b32ceb174d0/tfatool/command.py#L147-L150
[ "def _prep_get(operation: Operation, url=URL, **params):\n params.update(op=int(operation)) # op param required\n return cgi.prep_get(cgi.Entrypoint.command, url=url, **params)\n" ]
import logging import arrow from pathlib import PurePosixPath from collections import namedtuple from . import cgi from .info import URL, DEFAULT_REMOTE_DIR from .info import WifiMode, WifiModeOnBoot, ModeValue, Operation from .info import FileInfo, RawFileInfo logger = logging.getLogger(__name__) ################...
python-astrodynamics/spacetrack
shovel/docs.py
watch
python
def watch(): # Start with a clean build sphinx_build['-b', 'html', '-E', 'docs', 'docs/_build/html'] & FG handler = ShellCommandTrick( shell_command='sphinx-build -b html docs docs/_build/html', patterns=['*.rst', '*.py'], ignore_patterns=['_build/*'], ignore_directories=['...
Renerate documentation when it changes.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/docs.py#L18-L31
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import os from shutil import rmtree from plumbum import FG from plumbum.cmd import pandoc, sphinx_build from shovel import task from watchdog.observers import Observer from watchdog.tricks import ShellCommandTrick from watchdog.watchmedo...
python-astrodynamics/spacetrack
shovel/docs.py
gen
python
def gen(skipdirhtml=False): docs_changelog = 'docs/changelog.rst' check_git_unchanged(docs_changelog) pandoc('--from=markdown', '--to=rst', '--output=' + docs_changelog, 'CHANGELOG.md') if not skipdirhtml: sphinx_build['-b', 'dirhtml', '-W', '-E', 'docs', 'docs/_build/dirhtml'] & FG sphinx_b...
Generate html and dirhtml output.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/docs.py#L35-L42
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import os from shutil import rmtree from plumbum import FG from plumbum.cmd import pandoc, sphinx_build from shovel import task from watchdog.observers import Observer from watchdog.tricks import ShellCommandTrick from watchdog.watchmedo...
python-astrodynamics/spacetrack
shovel/_helpers.py
check_git_unchanged
python
def check_git_unchanged(filename, yes=False): if check_staged(filename): s = 'There are staged changes in {}, overwrite? [y/n] '.format(filename) if yes or input(s) in ('y', 'yes'): return else: raise RuntimeError('There are staged changes in ' ...
Check git to avoid overwriting user changes.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/_helpers.py#L7-L22
[ "def check_staged(filename=None):\n \"\"\"Check if there are 'changes to be committed' in the index.\"\"\"\n retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD',\n filename].run(retcode=None)\n if retcode == 1:\n return True\n elif retcode == 0:\n ...
# coding: utf-8 from __future__ import absolute_import, division, print_function from plumbum.cmd import git def check_staged(filename=None): """Check if there are 'changes to be committed' in the index.""" retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD', fi...
python-astrodynamics/spacetrack
shovel/_helpers.py
check_staged
python
def check_staged(filename=None): retcode, _, stdout = git['diff-index', '--quiet', '--cached', 'HEAD', filename].run(retcode=None) if retcode == 1: return True elif retcode == 0: return False else: raise RuntimeError(stdout)
Check if there are 'changes to be committed' in the index.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/shovel/_helpers.py#L25-L34
null
# coding: utf-8 from __future__ import absolute_import, division, print_function from plumbum.cmd import git def check_git_unchanged(filename, yes=False): """Check git to avoid overwriting user changes.""" if check_staged(filename): s = 'There are staged changes in {}, overwrite? [y/n] '.format(filen...
python-astrodynamics/spacetrack
spacetrack/aio.py
_raise_for_status
python
async def _raise_for_status(response): try: response.raise_for_status() except aiohttp.ClientResponseError as exc: reason = response.reason spacetrack_error_msg = None try: json = await response.json() if isinstance(json, Mapping): space...
Raise an appropriate error for a given response. Arguments: response (:py:class:`aiohttp.ClientResponse`): The API response. Raises: :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate error for the response's status. This function was taken from the aslack project and m...
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L349-L409
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import asyncio import ssl import time from collections.abc import AsyncIterator, Mapping import aiohttp import aiohttp.web_exceptions import requests.certs from aiohttp.helpers import parse_mimetype from .base import AuthenticationError...
python-astrodynamics/spacetrack
spacetrack/aio.py
AsyncSpaceTrackClient.generic_request
python
async def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): if iter_lines and iter_content: raise ValueError('iter_lines and iter_content cannot both be True') if 'format' in kwargs and parse_type...
Generic Space-Track query coroutine. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **st) st.basicspacedata.tle_publish(*args, **st) st.file(*args, **st) st.filesh...
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L70-L213
[ "def _stringify_predicate_value(value):\n \"\"\"Convert Python objects to Space-Track compatible strings\n\n - Booleans (``True`` -> ``'true'``)\n - Sequences (``[25544, 34602]`` -> ``'25544,34602'``)\n - dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)\n - ``None`` -> ``'null-val'``\n ...
class AsyncSpaceTrackClient(SpaceTrackClient): """Asynchronous SpaceTrack client class. This class should be considered experimental. It must be closed by calling :meth:`~spacetrack.aio.AsyncSpaceTrackClient.close`. Alternatively, instances of this class can be used as a context manager. Para...
python-astrodynamics/spacetrack
spacetrack/aio.py
AsyncSpaceTrackClient._download_predicate_data
python
async def _download_predicate_data(self, class_, controller): await self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) resp = await self._ratelimited_get(url) await _raise_for_status(resp) resp_json = await resp.j...
Get raw predicate information for given request class, and cache for subsequent calls.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/aio.py#L242-L256
[ "async def _raise_for_status(response):\n \"\"\"Raise an appropriate error for a given response.\n\n Arguments:\n response (:py:class:`aiohttp.ClientResponse`): The API response.\n\n Raises:\n :py:class:`aiohttp.web_exceptions.HTTPException`: The appropriate\n error for the response's stat...
class AsyncSpaceTrackClient(SpaceTrackClient): """Asynchronous SpaceTrack client class. This class should be considered experimental. It must be closed by calling :meth:`~spacetrack.aio.AsyncSpaceTrackClient.close`. Alternatively, instances of this class can be used as a context manager. Para...
python-astrodynamics/spacetrack
spacetrack/operators.py
_stringify_predicate_value
python
def _stringify_predicate_value(value): if isinstance(value, bool): return str(value).lower() elif isinstance(value, Sequence) and not isinstance(value, six.string_types): return ','.join(_stringify_predicate_value(x) for x in value) elif isinstance(value, datetime.datetime): return v...
Convert Python objects to Space-Track compatible strings - Booleans (``True`` -> ``'true'``) - Sequences (``[25544, 34602]`` -> ``'25544,34602'``) - dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``) - ``None`` -> ``'null-val'``
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/operators.py#L45-L64
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import datetime import six try: from collections.abc import Sequence except ImportError: from collections import Sequence def greater_than(value): """``'>value'``.""" return '>' + _stringify_predicate_value(value) de...
python-astrodynamics/spacetrack
spacetrack/base.py
_iter_content_generator
python
def _iter_content_generator(response, decode_unicode): for chunk in response.iter_content(100 * 1024, decode_unicode=decode_unicode): if decode_unicode: # Replace CRLF newlines with LF, Python will handle # platform specific newlines if written to file. chunk = chunk.repl...
Generator used to yield 100 KiB chunks for a given response.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L640-L649
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import datetime as dt import re import threading import time import weakref from collections import OrderedDict from functools import partial import requests from logbook import Logger from ratelimiter import RateLimiter from represent i...
python-astrodynamics/spacetrack
spacetrack/base.py
_iter_lines_generator
python
def _iter_lines_generator(response, decode_unicode): pending = None for chunk in _iter_content_generator(response, decode_unicode=decode_unicode): if pending is not None: chunk = pending + chunk lines = chunk.splitlines() if lines and lines[-1] and chunk and lines[-1][-1]...
Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The function is taken from :meth:`requests.models.Response.iter_lines`, but modified to use our :func:`~spacetrack.base._iter_content_ge...
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L652-L683
[ "def _iter_content_generator(response, decode_unicode):\n \"\"\"Generator used to yield 100 KiB chunks for a given response.\"\"\"\n for chunk in response.iter_content(100 * 1024, decode_unicode=decode_unicode):\n if decode_unicode:\n # Replace CRLF newlines with LF, Python will handle\n ...
# coding: utf-8 from __future__ import absolute_import, division, print_function import datetime as dt import re import threading import time import weakref from collections import OrderedDict from functools import partial import requests from logbook import Logger from ratelimiter import RateLimiter from represent i...
python-astrodynamics/spacetrack
spacetrack/base.py
_raise_for_status
python
def _raise_for_status(response): http_error_msg = '' if 400 <= response.status_code < 500: http_error_msg = '%s Client Error: %s for url: %s' % ( response.status_code, response.reason, response.url) elif 500 <= response.status_code < 600: http_error_msg = '%s Server Error: %s ...
Raises stored :class:`HTTPError`, if one occurred. This is the :meth:`requests.models.Response.raise_for_status` method, modified to add the response from Space-Track, if given.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L686-L719
null
# coding: utf-8 from __future__ import absolute_import, division, print_function import datetime as dt import re import threading import time import weakref from collections import OrderedDict from functools import partial import requests from logbook import Logger from ratelimiter import RateLimiter from represent i...
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient.generic_request
python
def generic_request(self, class_, iter_lines=False, iter_content=False, controller=None, parse_types=False, **kwargs): r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python ...
r"""Generic Space-Track query. The request class methods use this method internally; the public API is as follows: .. code-block:: python st.tle_publish(*args, **kw) st.basicspacedata.tle_publish(*args, **kw) st.file(*args, **kw) st.fileshare.fi...
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L245-L402
[ "def _stringify_predicate_value(value):\n \"\"\"Convert Python objects to Space-Track compatible strings\n\n - Booleans (``True`` -> ``'true'``)\n - Sequences (``[25544, 34602]`` -> ``'25544,34602'``)\n - dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``)\n - ``None`` -> ``'null-val'``\n ...
class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #...
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient._ratelimited_get
python
def _ratelimited_get(self, *args, **kwargs): with self._ratelimiter: resp = self.session.get(*args, **kwargs) # It's possible that Space-Track will return HTTP status 500 with a # query rate limit violation. This can happen if a script is cancelled # before it has finished s...
Perform get request, handling rate limiting.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L415-L441
null
class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #...
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient._find_controller
python
def _find_controller(self, class_): for controller, classes in self.request_controllers.items(): if class_ in classes: return controller else: raise ValueError('Unknown request class {!r}'.format(class_))
Find first controller that matches given request class. Order is specified by the keys of ``SpaceTrackClient.request_controllers`` (:class:`~collections.OrderedDict`)
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L479-L490
null
class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #...
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient._download_predicate_data
python
def _download_predicate_data(self, class_, controller): self.authenticate() url = ('{0}{1}/modeldef/class/{2}' .format(self.base_url, controller, class_)) logger.debug(requests.utils.requote_uri(url)) resp = self._ratelimited_get(url) _raise_for_status(resp) ...
Get raw predicate information for given request class, and cache for subsequent calls.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L492-L507
[ "def _raise_for_status(response):\n \"\"\"Raises stored :class:`HTTPError`, if one occurred.\n\n This is the :meth:`requests.models.Response.raise_for_status` method,\n modified to add the response from Space-Track, if given.\n \"\"\"\n\n http_error_msg = ''\n\n if 400 <= response.status_code < 50...
class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #...
python-astrodynamics/spacetrack
spacetrack/base.py
SpaceTrackClient.get_predicates
python
def get_predicates(self, class_, controller=None): if class_ not in self._predicates: if controller is None: controller = self._find_controller(class_) else: classes = self.request_controllers.get(controller, None) if classes is None: ...
Get full predicate information for given request class, and cache for subsequent calls.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L509-L529
[ "def _find_controller(self, class_):\n \"\"\"Find first controller that matches given request class.\n\n Order is specified by the keys of\n ``SpaceTrackClient.request_controllers``\n (:class:`~collections.OrderedDict`)\n \"\"\"\n for controller, classes in self.request_controllers.items():\n ...
class SpaceTrackClient(object): """SpaceTrack client class. Parameters: identity: Space-Track username. password: Space-Track password. For more information, refer to the `Space-Track documentation`_. .. _`Space-Track documentation`: https://www.space-track.org/documentation #...
python-astrodynamics/spacetrack
spacetrack/base.py
_ControllerProxy.get_predicates
python
def get_predicates(self, class_): return self.client.get_predicates( class_=class_, controller=self.controller)
Proxy ``get_predicates`` to client with stored request controller.
train
https://github.com/python-astrodynamics/spacetrack/blob/18f63b7de989a31b983d140a11418e01bd6fd398/spacetrack/base.py#L632-L637
null
class _ControllerProxy(object): """Proxies request class methods with a preset request controller.""" def __init__(self, client, controller): # The client will cache _ControllerProxy instances, so only store # a weak reference to it. self.client = weakref.proxy(client) self.contr...
howl-anderson/MicroTokenizer
MicroTokenizer/tokenizer_loader.py
TokenizerLoader.create_tokenizer
python
def create_tokenizer(self, name, config=dict()): if name not in self.factories: raise KeyError(Errors.E002.format(name=name)) factory = self.factories[name] return factory(self, **config)
Create a pipeline component from a factory. name (unicode): Factory name to look up in `Language.factories`. config (dict): Configuration parameters to initialise component. RETURNS (callable): Pipeline component.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/tokenizer_loader.py#L44-L54
null
class TokenizerLoader(object): Defaults = BaseDefaults factories = { 'max_match_forward_tokenizer': lambda nlp, **cfg: MaxMatchForwardTokenizer(**cfg), 'max_match_backward_tokenizer': lambda nlp, **cfg: MaxMatchBackwardTokenizer(**cfg), 'max_match_bidirectional_tokenizer': lambda nlp, *...
howl-anderson/MicroTokenizer
MicroTokenizer/errors.py
add_codes
python
def add_codes(err_cls): class ErrorsWithCodes(object): def __getattribute__(self, code): msg = getattr(err_cls, code) return '[{code}] {msg}'.format(code=code, msg=msg) return ErrorsWithCodes()
Add error codes to string messages via class attribute names.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/errors.py#L9-L15
null
# coding: utf8 from __future__ import unicode_literals import os import warnings import inspect @add_codes class Warnings(object): W001 = ("As of spaCy v2.0, the keyword argument `path=` is deprecated. " "You can now call spacy.load with the path as its first argument, " "and the model's...
howl-anderson/MicroTokenizer
MicroTokenizer/errors.py
_warn
python
def _warn(message, warn_type='user'): w_id = message.split('[', 1)[1].split(']', 1)[0] # get ID from string if warn_type in SPACY_WARNING_TYPES and w_id not in SPACY_WARNING_IGNORE: category = WARNINGS[warn_type] stack = inspect.stack()[-1] with warnings.catch_warnings(): if...
message (unicode): The message to display. category (Warning): The Warning to show.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/errors.py#L314-L326
null
# coding: utf8 from __future__ import unicode_literals import os import warnings import inspect def add_codes(err_cls): """Add error codes to string messages via class attribute names.""" class ErrorsWithCodes(object): def __getattribute__(self, code): msg = getattr(err_cls, code) ...
howl-anderson/MicroTokenizer
MicroTokenizer/cli_command/download.py
download
python
def download(model=None, direct=False, *pip_args): if model is None: model = about.__default_corpus__ if direct: dl = download_model('{m}/{m}.tar.gz#egg={m}'.format(m=model), pip_args) else: shortcuts = get_json(about.__shortcuts__, "available shortcuts") model_name = shortc...
Download compatible model from default download path using pip. Model can be shortcut, model name or, if --direct flag is set, full model name with version.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/cli_command/download.py#L22-L53
[ "def get_version(model, comp):\n model = model.rsplit('.dev', 1)[0]\n if model not in comp:\n prints(Messages.M007.format(name=model, version=about.__version__),\n title=Messages.M005, exits=1)\n return comp[model][0]\n", "def prints(*texts, **kwargs):\n \"\"\"Print formatted mess...
# coding: utf8 from __future__ import unicode_literals import plac import requests import os import subprocess import sys from MicroTokenizer.cli_command._messages import Messages from MicroTokenizer.cli_command.link import link from MicroTokenizer.util import prints, get_package_path from MicroTokenizer import about...
howl-anderson/MicroTokenizer
MicroTokenizer/cli_command/link.py
link
python
def link(origin, link_name, force=False, model_path=None): if util.is_package(origin): model_path = util.get_package_path(origin) else: model_path = Path(origin) if model_path is None else Path(model_path) if not model_path.exists(): prints(Messages.M009.format(path=path2str(model_pa...
Create a symlink for models within the spacy/data directory. Accepts either the name of a pip package, or the local path to the model data directory. Linking models allows loading them via spacy.load(link_name).
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/cli_command/link.py#L17-L53
[ "def is_package(name):\n \"\"\"Check if string maps to a package installed via pip.\n\n name (unicode): Name of package.\n RETURNS (bool): True if installed package, False if not.\n \"\"\"\n name = name.lower() # compare package name against lowercase name\n packages = pkg_resources.working_set.b...
# coding: utf8 from __future__ import unicode_literals import plac from pathlib import Path from ._messages import Messages from ..compat import symlink_to, path2str from ..util import prints from .. import util @plac.annotations( origin=("package name or local path to model", "positional", None, str), link...
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
load_model_from_path
python
def load_model_from_path(model_path, meta=False, **overrides): from .tokenizer_loader import TokenizerLoader if not meta: meta = get_model_meta(model_path) tokenizer_loader = TokenizerLoader(meta=meta, **overrides) tokenizers = meta.get('tokenizers', []) disable = overrides.get('disable', [...
Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L101-L120
[ "def get_model_meta(path):\n \"\"\"Get model meta.json from a directory path and validate its contents.\n\n path (unicode or Path): Path to model directory.\n RETURNS (dict): The model's meta data.\n \"\"\"\n model_path = ensure_path(path)\n if not model_path.exists():\n raise IOError(Error...
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_...
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
is_package
python
def is_package(name): name = name.lower() # compare package name against lowercase name packages = pkg_resources.working_set.by_key.keys() for package in packages: if package.lower().replace('-', '_') == name: return True return False
Check if string maps to a package installed via pip. name (unicode): Name of package. RETURNS (bool): True if installed package, False if not.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L159-L170
null
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_...
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
decaying
python
def decaying(start, stop, decay): def clip(value): return max(value, stop) if (start > stop) else min(value, stop) nr_upd = 1. while True: yield clip(start * 1./(1. + decay * nr_upd)) nr_upd += 1
Yield an infinite series of linearly decaying values.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L272-L279
[ "def clip(value):\n return max(value, stop) if (start > stop) else min(value, stop)\n" ]
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_...
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
read_json
python
def read_json(location): location = ensure_path(location) with location.open('r', encoding='utf8') as f: return ujson.load(f)
Open and load JSON from file. location (Path): Path to JSON file. RETURNS (dict): Loaded JSON content.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L311-L319
[ "def ensure_path(path):\n \"\"\"Ensure string is converted to a Path.\n\n path: Anything. If string, it's converted to Path.\n RETURNS: Path or original argument.\n \"\"\"\n if isinstance(path, basestring_):\n return Path(path)\n else:\n return path\n" ]
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_...
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
get_raw_input
python
def get_raw_input(description, default=False): additional = ' (default: %s)' % default if default else '' prompt = ' %s%s: ' % (description, additional) user_input = input_(prompt) return user_input
Get user input from the command line via raw_input / input. description (unicode): Text to display before prompt. default (unicode or False/None): Default value to display with prompt. RETURNS (unicode): User input.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L322-L332
null
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_...
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
print_table
python
def print_table(data, title=None): if isinstance(data, dict): data = list(data.items()) tpl_row = ' {:<15}' * len(data[0]) table = '\n'.join([tpl_row.format(l, unicode_(v)) for l, v in data]) if title: print('\n \033[93m{}\033[0m'.format(title)) print('\n{}\n'.format(table))
Print data in table format. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be printed above.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L355-L367
null
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_...
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
print_markdown
python
def print_markdown(data, title=None): def excl_value(value): # contains path, i.e. personal info return isinstance(value, basestring_) and Path(value).exists() if isinstance(data, dict): data = list(data.items()) markdown = ["* **{}:** {}".format(l, unicode_(v)) for ...
Print data in GitHub-flavoured Markdown format for issues etc. data (dict or list of tuples): Label/value pairs. title (unicode or None): Title, will be rendered as headline 2.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L370-L386
null
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_...
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
prints
python
def prints(*texts, **kwargs): exits = kwargs.get('exits', None) title = kwargs.get('title', None) title = '\033[93m{}\033[0m\n'.format(_wrap(title)) if title else '' message = '\n\n'.join([_wrap(text) for text in texts]) print('\n{}{}\n'.format(title, message)) if exits is not None: sys....
Print formatted message (manual ANSI escape sequences to avoid dependency) *texts (unicode): Texts to print. Each argument is rendered as paragraph. **kwargs: 'title' becomes coloured headline. exits=True performs sys exit.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L389-L402
[ "def _wrap(text, wrap_max=80, indent=4):\n \"\"\"Wrap text at given width using textwrap module.\n\n text (unicode): Text to wrap. If it's a Path, it's converted to string.\n wrap_max (int): Maximum line length (indent is deducted).\n indent (int): Number of spaces for indentation.\n RETURNS (unicode...
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_...
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
_wrap
python
def _wrap(text, wrap_max=80, indent=4): indent = indent * ' ' wrap_width = wrap_max - len(indent) if isinstance(text, Path): text = path2str(text) return textwrap.fill(text, width=wrap_width, initial_indent=indent, subsequent_indent=indent, break_long_words=False, ...
Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped text.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L405-L419
[ "path2str = lambda path: str(path)\n" ]
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_...
howl-anderson/MicroTokenizer
MicroTokenizer/util.py
escape_html
python
def escape_html(text): text = text.replace('&', '&amp;') text = text.replace('<', '&lt;') text = text.replace('>', '&gt;') text = text.replace('"', '&quot;') return text
Replace <, >, &, " with their HTML encoded representation. Intended to prevent HTML errors in rendered displaCy markup. text (unicode): The original text. RETURNS (unicode): Equivalent text to be safely used within HTML.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/util.py#L433-L444
null
# coding: utf8 from __future__ import unicode_literals, print_function import functools import importlib import random import sys import textwrap import ujson from pathlib import Path import numpy.random import pkg_resources import regex as re from .compat import import_file from .compat import path2str, basestring_...
howl-anderson/MicroTokenizer
MicroTokenizer/compat.py
normalize_string_keys
python
def normalize_string_keys(old): new = {} for key, value in old.items(): if isinstance(key, bytes_): new[key.decode('utf8')] = value else: new[key] = value return new
Given a dictionary, make sure keys are unicode strings, not bytes.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/compat.py#L78-L86
null
# coding: utf8 from __future__ import unicode_literals import sys import ujson import itertools import locale try: import cPickle as pickle except ImportError: import pickle try: import copy_reg except ImportError: import copyreg as copy_reg pickle = pickle copy_reg = copy_reg izip = getattr(itertoo...
howl-anderson/MicroTokenizer
MicroTokenizer/compat.py
locale_escape
python
def locale_escape(string, errors='replace'): ''' Mangle non-supported characters, for savages with ascii terminals. ''' encoding = locale.getpreferredencoding() string = string.encode(encoding, errors).decode('utf8') return string
Mangle non-supported characters, for savages with ascii terminals.
train
https://github.com/howl-anderson/MicroTokenizer/blob/41bbe9c31d202b4f751ad5201d343ad1123b42b5/MicroTokenizer/compat.py#L102-L108
null
# coding: utf8 from __future__ import unicode_literals import sys import ujson import itertools import locale try: import cPickle as pickle except ImportError: import pickle try: import copy_reg except ImportError: import copyreg as copy_reg pickle = pickle copy_reg = copy_reg izip = getattr(itertoo...
jmvrbanac/Specter
specter/reporting/dots.py
DotsReporter.print_error
python
def print_error(self, wrapper): level = 0 parent = wrapper.parent while parent: print_test_msg(parent.name, level, TestStatus.FAIL, self.use_color) level += 1 parent = parent.parent print_test_msg(wrapper.name, level, TestStatus.FAIL, self.use_color) ...
A crude way of output the errors for now. This needs to be cleaned up into something better.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/reporting/dots.py#L29-L53
[ "def print_expects(test_case, level, use_color=True, use_unicode=True):\n # Print expects\n for expect in test_case.expects:\n mark = u'\\u2718'\n if not use_unicode:\n mark = 'x'\n\n status = TestStatus.FAIL\n if expect.success:\n status = TestStatus.PASS\n ...
class DotsReporter(AbstractConsoleReporter, AbstractParallelReporter): def __init__(self): super(DotsReporter, self).__init__() self.total = 0 self.failed_tests = [] self.use_color = True def get_name(self): return _('Dots Reporter') def subscribe_to_spec(self, spe...
jmvrbanac/Specter
specter/runner.py
SpecterRunner.combine_coverage_reports
python
def combine_coverage_reports(self, omit, parallel): tmp_cov = coverage.coverage(omit=omit, data_suffix=parallel) tmp_cov.load() tmp_cov.combine() tmp_cov.save()
Method to force the combination of parallel coverage reports.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/runner.py#L120-L125
null
class SpecterRunner(object): DESCRIPTION = _('Specter is a spec-based testing library to help ' 'facilitate BDD in Python.') def __init__(self): super(SpecterRunner, self).__init__() self.coverage = None self.suite_scanner = None self.arg_parser = ArgumentPar...
jmvrbanac/Specter
specter/spec.py
CaseWrapper.serialize
python
def serialize(self): expects = [exp.serialize() for exp in self.expects] converted_dict = { 'id': self.id, 'name': self.pretty_name, 'raw_name': self.name, 'doc': self.doc, 'error': self.error, 'skipped': self.skipped, '...
Serializes the CaseWrapper object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/spec.py#L53-L76
[ "def remove_empty_entries_from_dict(input_dict):\n return {k: v for k, v in six.iteritems(input_dict) if v is not None}\n" ]
class CaseWrapper(TimedObject): def __init__(self, case_func, parent, execute_kwargs=None, metadata={}): super(CaseWrapper, self).__init__() self.id = str(uuid.uuid4()) self.case_func = case_func self.expects = [] self.parent = parent self.failed = None self.e...
jmvrbanac/Specter
specter/spec.py
Describe.serialize
python
def serialize(self): cases = [case.serialize() for key, case in six.iteritems(self.cases)] specs = [spec.serialize() for spec in self.describes] converted_dict = { 'id': self.id, 'name': self.name, 'class_path': self.real_class_path, 'doc': self....
Serializes the Spec/Describe object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/spec.py#L280-L299
null
class Describe(EventDispatcher): __FIXTURE__ = False #: List of methods to be called after every test hooks = () def __init__(self, parent=None): super(Describe, self).__init__() self.id = str(uuid.uuid4()) wrappers = self.__wrappers__ self.parent = parent self....
jmvrbanac/Specter
specter/spec.py
Describe._run_hooks
python
def _run_hooks(self): for hook in self.hooks: getattr(self, hook)(self._state)
Calls any registered hooks providing the current state.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/spec.py#L301-L304
null
class Describe(EventDispatcher): __FIXTURE__ = False #: List of methods to be called after every test hooks = () def __init__(self, parent=None): super(Describe, self).__init__() self.id = str(uuid.uuid4()) wrappers = self.__wrappers__ self.parent = parent self....
jmvrbanac/Specter
specter/reporting/__init__.py
ReporterPluginManager.subscribe_all_to_spec
python
def subscribe_all_to_spec(self, spec): for reporter in self.reporters: if self.can_use_reporter(reporter, self.parallel): reporter.subscribe_to_spec(spec)
Will automatically not subscribe reporters that are not parallel or serial depending on the current mode.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/reporting/__init__.py#L77-L83
[ "def can_use_reporter(self, reporter, parallel):\n can_use = False\n if parallel:\n if isinstance(reporter, AbstractParallelReporter):\n can_use = True\n else:\n if isinstance(reporter, AbstractSerialReporter):\n can_use = True\n return can_use\n" ]
class ReporterPluginManager(object): def __init__(self, parallel=False): self.reporters = [] self.load_reporters() self.parallel = parallel def get_console_reporters(self): return [reporter for reporter in self.reporters if issubclass(type(reporter), AbstractCon...
jmvrbanac/Specter
specter/reporting/console.py
ConsoleReporter.output
python
def output(self, msg, indent, status=None): color = None if self.use_color: color = get_color_from_status(status) print_indent_msg(msg, indent, color)
Alias for print_indent_msg with color determined by status.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/reporting/console.py#L139-L144
[ "def get_color_from_status(status):\n color = None\n if status == TestStatus.PASS:\n color = ConsoleColors.GREEN\n elif status == TestStatus.SKIP:\n color = ConsoleColors.YELLOW\n elif status == TestStatus.INCOMPLETE:\n color = ConsoleColors.MAGENTA\n elif status is not None:\n ...
class ConsoleReporter(AbstractConsoleReporter, AbstractSerialReporter): """ Simple BDD Style console reporter. """ def __init__(self, output_docstrings=False, use_color=True): super(ConsoleReporter, self).__init__() self.use_color = use_color self.use_unicode = True self.test_to...
jmvrbanac/Specter
specter/util.py
get_real_last_traceback
python
def get_real_last_traceback(exception): traceback_blocks = [] _n, _n, exc_traceback = sys.exc_info() tb_list = get_all_tracebacks(exc_traceback)[1:] # Remove already captured tracebacks # TODO(jmv): This must be a better way of doing this. Need to revisit. tb_list = [tb for tb in tb_list if tb ...
An unfortunate evil... All because Python's traceback cannot determine where my executed code is coming from...
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/util.py#L155-L183
[ "def get_numbered_source(lines, line_num, starting_line=0):\n try:\n center = (line_num - starting_line) - 1\n start = center - 2 if center - 2 > 0 else 0\n end = center + 2 if center + 2 <= len(lines) else len(lines)\n\n orig_src_lines = [line.rstrip('\\n') for line in lines[start:en...
import ast import inspect import re import itertools import sys import six from specter.vendor.ast_decompiler import decompile try: import __builtin__ except ImportError: import builtins as __builtin__ CAPTURED_TRACEBACKS = [] class ExpectParams(object): types_with_args = [ 'equal', 'al...
jmvrbanac/Specter
specter/vendor/ast_decompiler.py
decompile
python
def decompile(ast, indentation=4, line_length=100, starting_indentation=0): decompiler = Decompiler( indentation=indentation, line_length=line_length, starting_indentation=starting_indentation, ) return decompiler.run(ast)
Decompiles an AST into Python code. Arguments: - ast: code to decompile, using AST objects as generated by the standard library ast module - indentation: indentation level of lines - line_length: if lines become longer than this length, ast_decompiler will try to break them up (but it will not ne...
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/vendor/ast_decompiler.py#L94-L110
[ "def run(self, ast):\n self.visit(ast)\n if self.current_line:\n self.lines.append(''.join(self.current_line))\n self.current_line = []\n return ''.join(self.lines)\n" ]
""" Vendored Project: AST Decompiler Package: ast-decompiler Version: 0.2 Author: Jelle Zijlstra License: Apache v2 Project: https://github.com/JelleZijlstra/ast_decompiler """ import ast from contextlib import contextmanager import sys try: _basestring = basestring _long = long PY3 = False except NameErr...
jmvrbanac/Specter
specter/vendor/ast_decompiler.py
Decompiler.write_expression_list
python
def write_expression_list(self, nodes, separator=', ', allow_newlines=True, need_parens=True, final_separator_if_multiline=True): first = True last_line = len(self.lines) current_line = list(self.current_line) for node in nodes: if first: ...
Writes a list of nodes, separated by separator. If allow_newlines, will write the expression over multiple lines if necessary to say within max_line_length. If need_parens, will surround the expression with parentheses in this case. If final_separator_if_multiline, will write a separator at the...
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/vendor/ast_decompiler.py#L164-L208
[ "def visit(self, node):\n self.node_stack.append(node)\n try:\n return super(Decompiler, self).visit(node)\n finally:\n if self.node_stack:\n self.node_stack.pop()\n", "def write(self, code):\n assert isinstance(code, _basestring), 'invalid code %r' % code\n self.current_li...
class Decompiler(ast.NodeVisitor): def __init__(self, indentation, line_length, starting_indentation): self.lines = [] self.current_line = [] self.current_indentation = starting_indentation self.node_stack = [] self.indentation = indentation self.max_line_length = lin...
jmvrbanac/Specter
specter/expect.py
expect
python
def expect(obj, caller_args=[]): line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) expect_obj = ExpectAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(expect_obj) return expect_obj
Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L202-L217
[ "def get_module_and_line(use_child_attr=None):\n last_frame = inspect.currentframe()\n\n steps = 2\n for i in range(steps):\n last_frame = last_frame.f_back\n\n self = module = last_frame.f_locals['self']\n # Use an attr instead of self\n if use_child_attr:\n module = getattr(self, u...
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedExcepti...
jmvrbanac/Specter
specter/expect.py
require
python
def require(obj, caller_args=[]): line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) require_obj = RequireAssert( obj, src_params=src_params, caller_args=caller_args ) _add_expect_to_wrapper(require_obj) return require_obj
Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L220-L235
[ "def get_module_and_line(use_child_attr=None):\n last_frame = inspect.currentframe()\n\n steps = 2\n for i in range(steps):\n last_frame = last_frame.f_back\n\n self = module = last_frame.f_locals['self']\n # Use an attr instead of self\n if use_child_attr:\n module = getattr(self, u...
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedExcepti...
jmvrbanac/Specter
specter/expect.py
skip
python
def skip(reason): def decorator(test_func): if not isinstance(test_func, (type, ClassObjType)): func_data = None if test_func.__name__ == 'DECORATOR_ONCALL': # Call down and save the results func_data = test_func() @functools.wraps(test_fu...
The skip decorator allows for you to always bypass a test. :param reason: Expects a string
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L238-L259
null
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedExcepti...
jmvrbanac/Specter
specter/expect.py
skip_if
python
def skip_if(condition, reason=None): if condition: return skip(reason) def wrapper(func): return func return wrapper
The skip_if decorator allows for you to bypass a test on conditions :param condition: Expects a boolean :param reason: Expects a string
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L262-L273
[ "def skip(reason):\n \"\"\"The skip decorator allows for you to always bypass a test.\n\n :param reason: Expects a string\n \"\"\"\n def decorator(test_func):\n if not isinstance(test_func, (type, ClassObjType)):\n func_data = None\n if test_func.__name__ == 'DECORATOR_ONCAL...
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedExcepti...
jmvrbanac/Specter
specter/expect.py
incomplete
python
def incomplete(test_func): if not isinstance(test_func, (type, ClassObjType)): @functools.wraps(test_func) def skip_wrapper(*args, **kwargs): raise TestIncompleteException(test_func, _('Test is incomplete')) return skip_wrapper
The incomplete decorator behaves much like a normal skip; however, tests that are marked as incomplete get tracked under a different metric. This allows for you to create a skeleton around all of your features and specifications, and track what tests have been written and what tests are left outstanding...
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L276-L294
null
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedExcepti...
jmvrbanac/Specter
specter/expect.py
metadata
python
def metadata(**key_value_pairs): def onTestFunc(func): def DECORATOR_ONCALL(*args, **kwargs): return (func, key_value_pairs) return DECORATOR_ONCALL return onTestFunc
The metadata decorator allows for you to tag specific tests with key/value data for run-time processing or reporting. The common use case is to use metadata to tag a test as a positive or negative test type. .. code-block:: python # Example of using the metadata decorator @metadata(type='n...
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L297-L313
null
import functools import inspect # Making sure we support 2.7 and 3+ try: from types import ClassType as ClassObjType except ImportError: from types import ModuleType as ClassObjType from specter import _ from specter.spec import (CaseWrapper, FailedRequireException, TestSkippedExcepti...
jmvrbanac/Specter
specter/expect.py
ExpectAssert.serialize
python
def serialize(self): converted_dict = { 'success': self.success, 'assertion': str(self), 'required': self.required } return converted_dict
Serializes the ExpectAssert object for collection. Warning, this will only grab the available information. It is strongly that you only call this once all specs and tests have completed.
train
https://github.com/jmvrbanac/Specter/blob/1f5a729b0aa16242add8c1c754efa268335e3944/specter/expect.py#L41-L53
null
class ExpectAssert(object): def __init__(self, target, required=False, src_params=None, caller_args=[]): super(ExpectAssert, self).__init__() self.prefix = _('expect') self.target = target self.src_params = src_params self.actions = [target] self.suc...
beregond/super_state_machine
super_state_machine/utils.py
is_
python
def is_(self, state): translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state
Check if machine is in given state.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L9-L13
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def can_be_(self, state): """Check if machine can transit to given state.""" translator = self._meta['translator'] state = translator.translate(state) if self._meta['complete']: ...
beregond/super_state_machine
super_state_machine/utils.py
can_be_
python
def can_be_(self, state): translator = self._meta['translator'] state = translator.translate(state) if self._meta['complete']: return True if self.actual_state is None: return True transitions = self._meta['transitions'][self.actual_state] return state in transitions
Check if machine can transit to given state.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L16-L28
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state def f...
beregond/super_state_machine
super_state_machine/utils.py
force_set
python
def force_set(self, state): translator = self._meta['translator'] state = translator.translate(state) attr = self._meta['state_attribute_name'] setattr(self, attr, state)
Set new state without checking if transition is allowed.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L31-L36
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state def ca...
beregond/super_state_machine
super_state_machine/utils.py
set_
python
def set_(self, state): if not self.can_be_(state): state = self._meta['translator'].translate(state) raise TransitionError( "Cannot transit from '{actual_value}' to '{value}'." .format(actual_value=self.actual_state.value, value=state.value) ) self.force_set(stat...
Set new state for machine.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L39-L48
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state def ca...
beregond/super_state_machine
super_state_machine/utils.py
generate_getter
python
def generate_getter(value): @property @wraps(is_) def getter(self): return self.is_(value) return getter
Generate getter for given value.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L64-L71
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state def ca...