docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
plot the tree using toyplot.graph. Parameters: ----------- show_tip_labels: bool Show tip names from tree. use_edge_lengths: bool Use edge lengths from newick tree. show_node_support: bool Show support values at nodes ...
def draw( self, show_tip_labels=True, show_node_support=False, use_edge_lengths=False, orient="right", print_args=False, *args, **kwargs): ## re-decompose tree for new orient and edges args self._decompose_tree(orient=orient, us...
610,286
Draw a multi-panel figure with tree, tests, and results Parameters: ----------- height: int ... width: int ... show_test_labels: bool ... use_edge_lengths: bool ... collapse_outgroups: bool ... pct_tre...
def plot(self, show_test_labels=True, use_edge_lengths=True, collapse_outgroup=False, pct_tree_x=0.5, pct_tree_y=0.2, subset_tests=None, #toytree_kwargs=None, *args, **kwargs): ## check for attributes if not...
610,435
Show list of identifiers for this prefix. Handles both the case of local file based identifiers and also image generators. Arguments: config - configuration object in which: config.klass_name - 'gen' if a generator function config.generator_dir - directory for generator cod...
def identifiers(config): ids = [] if (config.klass_name == 'gen'): for generator in os.listdir(config.generator_dir): if (generator == '__init__.py'): continue (gid, ext) = os.path.splitext(generator) if (ext == '.py' and os.pa...
610,569
Flask handler to produce HTML response for OpenSeadragon view of identifier. Arguments: config - Config object for this IIIF handler identifier - identifier of image/generator prefix - path prefix **args - other aguments ignored
def osd_page_handler(config=None, identifier=None, prefix=None, **args): template_dir = os.path.join(os.path.dirname(__file__), 'templates') with open(os.path.join(template_dir, 'testserver_osd.html'), 'r') as f: template = f.read() d = dict(prefix=prefix, identifier=identifier, ...
610,572
Parse accept header and look for preferred type in supported list. Arguments: accept - HTTP Accept header supported - list of MIME type supported by the server Returns: supported MIME type with highest q value in request, else None. FIXME - Should replace this with negotiator2
def do_conneg(accept, supported): for result in parse_accept_header(accept): mime_type = result[0] if (mime_type in supported): return mime_type return None
610,577
Add configargparser/argparse configs for shared argument. Arguments: p - configargparse.ArgParser object base_dir - base directory for file/path defaults.
def add_shared_configs(p, base_dir=''): p.add('--host', default='localhost', help="Service host") p.add('--port', '-p', type=int, default=8000, help="Service port") p.add('--app-host', default=None, help="Local application host for reverse proxy deployment, " ...
610,581
Setup Flask app and handle reverse proxy setup if configured. Arguments: app - Flask application cfg - configuration data
def setup_app(app, cfg): # Set up app_host and app_port in case that we are running # under reverse proxy setup, otherwise they default to # config.host and config.port. if (cfg.app_host and cfg.app_port): logging.warning("Reverse proxy for service at http://%s:%d/ ..." % (cfg.host, cfg.por...
610,585
Initialize reverse proxy wrapper, store host. Arguments: app - the application being reverse proxied host - the configured host name for the application
def __init__(self, app, host): self.app = app self.host = host
610,596
Create a Controller object. Arguments: host -- the address of the controller host; IP or name username -- the username to log in with password -- the password to log in with port -- the port of the controller host version -- the base version ...
def __init__(self, host, username, password, port=8443, version='v2', site_id='default'): self.host = host self.port = port self.version = version self.username = username self.password = password self.site_id = site_id self.url = 'https://' + host + ':'...
611,456
Restart an access point (by name). Arguments: name -- the name address of the AP to restart.
def restart_ap_name(self, name): if not name: raise APIError('%s is not a valid name' % str(name)) for ap in self.get_aps(): if ap.get('state', 0) == 1 and ap.get('name', None) == name: self.restart_ap(ap['mac'])
611,467
Get a backup archive from a controller. Arguments: target_file -- Filename or full path to download the backup archive to, should have .unf extension for restore.
def get_backup(self, target_file='unifi-backup.unf'): download_path = self.create_backup() opener = self.opener.open(self.url + download_path) unifi_archive = opener.read() backupfile = open(target_file, 'w') backupfile.write(unifi_archive) backupfile.close()
611,470
Authorize a guest based on his MAC address. Arguments: guest_mac -- the guest MAC address : aa:bb:cc:dd:ee:ff minutes -- duration of the authorization in minutes up_bandwith -- up speed allowed in kbps (optional) down_bandwith -- down speed allowed in...
def authorize_guest(self, guest_mac, minutes, up_bandwidth=None, down_bandwidth=None, byte_quota=None, ap_mac=None): cmd = 'authorize-guest' js = {'mac': guest_mac, 'minutes': minutes} if up_bandwidth: js['up'] = up_bandwidth if down_bandwidth: js['down'...
611,471
Unauthorize a guest based on his MAC address. Arguments: guest_mac -- the guest MAC address : aa:bb:cc:dd:ee:ff
def unauthorize_guest(self, guest_mac): cmd = 'unauthorize-guest' js = {'mac': guest_mac} return self._run_command(cmd, params=js)
611,472
Return true if the object is a user-defined generator function. Generator function objects provides same attributes as functions. See isfunction.__doc__ for attributes listing. Adapted from Python 2.6. Args: obj: an object to test. Returns: true if the object is generator function.
def is_generator_function(obj): CO_GENERATOR = 0x20 return bool(((inspect.isfunction(obj) or inspect.ismethod(obj)) and obj.func_code.co_flags & CO_GENERATOR))
611,966
Extend what Pipeline can serialize. Args: object_type: type of the object. encoder: a function that takes in an object and returns a dict of json primitives. decoder: inverse function of encoder.
def _register_json_primitive(object_type, encoder, decoder): global _TYPE_TO_ENCODER global _TYPE_NAME_TO_DECODER if object_type not in _TYPE_TO_ENCODER: _TYPE_TO_ENCODER[object_type] = encoder _TYPE_NAME_TO_DECODER[object_type.__name__] = decoder
611,967
Writes a JSON encoded value to a Cloud Storage File. This function will store the blob in a GCS file in the default bucket under the appengine_pipeline directory. Optionally using another directory level specified by pipeline_id Args: encoded_value: The encoded JSON string. pipeline_id: A pipeline id t...
def _write_json_blob(encoded_value, pipeline_id=None): default_bucket = app_identity.get_default_gcs_bucket_name() if default_bucket is None: raise Exception( "No default cloud storage bucket has been set for this application. " "This app was likely created before v1.9.0, please see: " "ht...
611,973
Converts a datetime.datetime to integer milliseconds since the epoch. Requires special handling to preserve microseconds. Args: when: A datetime.datetime instance. Returns: Integer time since the epoch in milliseconds. If the supplied 'when' is None, the return value will be None.
def _get_timestamp_ms(when): if when is None: return None ms_since_epoch = float(time.mktime(when.utctimetuple()) * 1000.0) ms_since_epoch += when.microsecond / 1000.0 return int(ms_since_epoch)
611,976
Gets the full status tree of a pipeline. Args: root_pipeline_id: The pipeline ID to get status for. Returns: Dictionary with the keys: rootPipelineId: The ID of the root pipeline. slots: Mapping of slot IDs to result of from _get_internal_slot. pipelines: Mapping of pipeline IDs to resul...
def get_status_tree(root_pipeline_id): root_pipeline_key = db.Key.from_path(_PipelineRecord.kind(), root_pipeline_id) root_pipeline_record = db.get(root_pipeline_key) if root_pipeline_record is None: raise PipelineStatusError( 'Could not find pipeline ID "%s"' % root_pipeline_id) # If the suppli...
611,979
Create new handlers map. Args: prefix: url prefix to use. Returns: list of (regexp, handler) pairs for WSGIApplication constructor.
def create_handlers_map(prefix='.*'): return [ (prefix + '/output', _BarrierHandler), (prefix + '/run', _PipelineHandler), (prefix + '/finalized', _PipelineHandler), (prefix + '/cleanup', _CleanupHandler), (prefix + '/abort', _PipelineHandler), (prefix + '/fanout', _FanoutHandle...
611,982
Initializer. Args: name: The name of this slot. slot_key: The db.Key for this slot's _SlotRecord if it's already been allocated by an up-stream pipeline. strict: If this Slot was created as an output of a strictly defined pipeline.
def __init__(self, name=None, slot_key=None, strict=False): if name is None: raise UnexpectedPipelineError('Slot with key "%s" missing a name.' % slot_key) if slot_key is None: slot_key = db.Key.from_path(_SlotRecord.kind(), uuid.uuid4().hex) self._exis...
611,983
Sets the value of this slot based on its corresponding _SlotRecord. Does nothing if the slot has not yet been filled. Args: slot_record: The _SlotRecord containing this Slot's value.
def _set_value(self, slot_record): if slot_record.status == _SlotRecord.FILLED: self.filled = True self._filler_pipeline_key = _SlotRecord.filler.get_value_for_datastore( slot_record) self._fill_datetime = slot_record.fill_time self._value = slot_record.value
611,987
Sets the value of this slot for use in testing. Args: filler_pipeline_key: The db.Key of the _PipelineRecord that filled this slot. value: The serializable value set for this slot.
def _set_value_test(self, filler_pipeline_key, value): self.filled = True self._filler_pipeline_key = filler_pipeline_key self._fill_datetime = datetime.datetime.utcnow() # Convert to JSON and back again, to simulate the behavior of production. self._value = json.loads(json.dumps( value...
611,988
Initializer. Args: output_names: The list of require output names that will be strictly enforced by this class. force_strict: If True, force this future to be in strict mode.
def __init__(self, output_names, force_strict=False): self._after_all_pipelines = set() self._output_dict = { 'default': Slot(name='default'), } self._strict = len(output_names) > 0 or force_strict if self._strict: for name in output_names: if name in self._output_dict: ...
611,990
Initializer. Args: *args: The positional arguments for this function-object. **kwargs: The keyword arguments for this function-object.
def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs self.outputs = None self.backoff_seconds = _DEFAULT_BACKOFF_SECONDS self.backoff_factor = _DEFAULT_BACKOFF_FACTOR self.max_attempts = _DEFAULT_MAX_ATTEMPTS self.target = None self.task_retry = False self....
611,994
Starts this pipeline in test fashion. Args: idempotence_key: Dummy idempotence_key to use for this root pipeline. base_path: Dummy base URL path to use for this root pipeline. kwargs: Ignored keyword arguments usually passed to start().
def start_test(self, idempotence_key=None, base_path='', **kwargs): if not idempotence_key: idempotence_key = uuid.uuid4().hex pipeline_key = db.Key.from_path(_PipelineRecord.kind(), idempotence_key) context = _PipelineContext('', 'default', base_path) future = PipelineFuture(self.output_name...
611,997
Forces a currently running asynchronous pipeline to retry. Note this may not be called by synchronous or generator pipelines. Those must instead raise the 'Retry' exception during execution. Args: retry_message: Optional message explaining why the retry happened. Returns: True if the Pipe...
def retry(self, retry_message=''): if not self.async: raise UnexpectedPipelineError( 'May only call retry() method for asynchronous pipelines.') if self.try_cancel(): self._context.transition_retry(self._pipeline_key, retry_message) return True else: return False
611,998
Mark the entire pipeline up to the root as aborted. Note this should only be called from *outside* the context of a running pipeline. Synchronous and generator pipelines should raise the 'Abort' exception to cause this behavior during execution. Args: abort_message: Optional message explaining w...
def abort(self, abort_message=''): # TODO: Use thread-local variable to enforce that this is not called # while a pipeline is executing in the current thread. if (self.async and self._root_pipeline_key == self._pipeline_key and not self.try_cancel()): # Handle the special case where the r...
611,999
Fills an output slot required by this Pipeline. Args: name_or_slot: The name of the slot (a string) or Slot record to fill. value: The serializable value to assign to this slot. Raises: UnexpectedPipelineError if the Slot no longer exists. SlotNotDeclaredError if trying to output to a ...
def fill(self, name_or_slot, value): if isinstance(name_or_slot, basestring): slot = getattr(self.outputs, name_or_slot) elif isinstance(name_or_slot, Slot): slot = name_or_slot else: raise UnexpectedPipelineError( 'Could not fill invalid output name: %r' % name_or_slot) ...
612,000
Marks this asynchronous Pipeline as complete. Args: default_output: What value the 'default' output slot should be assigned. Raises: UnexpectedPipelineError if the slot no longer exists or this method was called for a pipeline that is not async.
def complete(self, default_output=None): # TODO: Enforce that all outputs expected by this async pipeline were # filled before this complete() function was called. May required all # async functions to declare their outputs upfront. if not self.async: raise UnexpectedPipelineError( ...
612,002
Returns a relative URL for invoking this Pipeline's callback method. Args: kwargs: Dictionary mapping keyword argument names to single values that should be passed to the callback when it is invoked. Raises: UnexpectedPipelineError if this is invoked on pipeline that is not async.
def get_callback_url(self, **kwargs): # TODO: Support positional parameters. if not self.async: raise UnexpectedPipelineError( 'May only call get_callback_url() method for asynchronous pipelines.') kwargs['pipeline_id'] = self._pipeline_key.name() params = urllib.urlencode(sorted(kw...
612,003
Returns a task for calling back this Pipeline. Args: params: Keyword argument containing a dictionary of key/value pairs that will be passed to the callback when it is executed. args, kwargs: Passed to the taskqueue.Task constructor. Use these arguments to set the task name (for idempot...
def get_callback_task(self, *args, **kwargs): if not self.async: raise UnexpectedPipelineError( 'May only call get_callback_task() method for asynchronous pipelines.') params = kwargs.get('params', {}) kwargs['params'] = params params['pipeline_id'] = self._pipeline_key.name() ...
612,004
Sends an email to admins indicating this Pipeline has completed. For developer convenience. Automatically called from finalized for root Pipelines that do not override the default action. Args: sender: (optional) Override the sender's email address.
def send_result_email(self, sender=None): status = 'successful' if self.was_aborted: status = 'aborted' app_id = os.environ['APPLICATION_ID'] shard_index = app_id.find('~') if shard_index != -1: app_id = app_id[shard_index+1:] param_dict = { 'status': status, '...
612,005
Modify various execution parameters of a Pipeline before it runs. This method has no effect in test mode. Args: kwargs: Attributes to modify on this Pipeline instance before it has been executed. Returns: This Pipeline instance, for easy chaining.
def with_params(self, **kwargs): if _TEST_MODE: logging.info( 'Setting runtime parameters for %s#%s: %r', self, self.pipeline_id, kwargs) return self if self.pipeline_id is not None: raise UnexpectedPipelineError( 'May only call with_params() on a Pipeline t...
612,007
Sets the absolute path to this class as a string. Used by the Pipeline API to reconstruct the Pipeline sub-class object at execution time instead of passing around a serialized function. Args: module_dict: Used for testing.
def _set_class_path(cls, module_dict=sys.modules): # Do not traverse the class hierarchy fetching the class path attribute. found = cls.__dict__.get('_class_path') if found is not None: return # Do not set the _class_path for the base-class, otherwise all children's # lookups for _class_...
612,008
Sets the user-visible values provided as an API by this class. Args: context: The _PipelineContext used for this Pipeline. pipeline_key: The db.Key of this pipeline. root_pipeline_key: The db.Key of the root pipeline. outputs: The PipelineFuture for this pipeline. result_status: The r...
def _set_values_internal(self, context, pipeline_key, root_pipeline_key, outputs, result_status): self._context = context self._pipeline_key = pipeline_key self._root_p...
612,009
Initializer. Args: *futures: PipelineFutures that all subsequent pipelines should follow. May be empty, in which case this statement does nothing.
def __init__(self, *futures): for f in futures: if not isinstance(f, PipelineFuture): raise TypeError('May only pass PipelineFuture instances to After(). %r', type(f)) self._futures = set(futures)
612,014
Adds a future to the list of in-order futures thus far. Args: future: The future to add to the list.
def _add_future(cls, future): if cls._local._activated: cls._local._in_order_futures.add(future)
612,017
Initializer. Args: task_name: The name of the currently running task or empty if there is no task running. queue_name: The queue this pipeline should run on (may not be the current queue this request is on). base_path: Relative URL for the pipeline's handlers.
def __init__(self, task_name, queue_name, base_path): self.task_name = task_name self.queue_name = queue_name self.base_path = base_path self.barrier_handler_path = '%s/output' % base_path self.pipeline_handler_path = '%s/run' % base_path self.fi...
612,021
Fills a slot, enqueueing a task to trigger pending barriers. Args: filler_pipeline_key: db.Key or stringified key of the _PipelineRecord that filled this slot. slot: The Slot instance to fill. value: The serializable value to assign. Raises: UnexpectedPipelineError if the _Slot...
def fill_slot(self, filler_pipeline_key, slot, value): if not isinstance(filler_pipeline_key, db.Key): filler_pipeline_key = db.Key(filler_pipeline_key) if _TEST_MODE: slot._set_value_test(filler_pipeline_key, value) else: encoded_value = json.dumps(value, ...
612,023
Kicks off the abort process for a root pipeline and all its children. Args: root_pipeline_key: db.Key of the root pipeline to abort. abort_message: Message explaining why the abort happened, only saved into the root pipeline. Returns: True if the abort signal was sent successfully;...
def begin_abort(self, root_pipeline_key, abort_message): def txn(): pipeline_record = db.get(root_pipeline_key) if pipeline_record is None: logging.warning( 'Tried to abort root pipeline ID "%s" but it does not exist.', root_pipeline_key.name()) raise db.Roll...
612,025
Sends the abort signal to all children for a root pipeline. Args: root_pipeline_key: db.Key of the root pipeline to abort. cursor: The query cursor for enumerating _PipelineRecords when inserting tasks to cause child pipelines to terminate. max_to_notify: Used for testing.
def continue_abort(self, root_pipeline_key, cursor=None, max_to_notify=_MAX_ABORTS_TO_BEGIN): if not isinstance(root_pipeline_key, db.Key): root_pipeline_key = db.Key(root_pipeline_key) # NOTE: The results of this query may include _Pipel...
612,026
Starts a pipeline in the test mode. Args: pipeline: The Pipeline instance to test.
def start_test(self, pipeline): global _TEST_MODE, _TEST_ROOT_PIPELINE_KEY self.start(pipeline, return_task=True) _TEST_MODE = True _TEST_ROOT_PIPELINE_KEY = pipeline._pipeline_key try: self.evaluate_test(pipeline, root=True) finally: _TEST_MODE = False
612,028
Recursively evaluates the given pipeline in test mode. Args: stage: The Pipeline instance to run at this stage in the flow. root: True if the supplied stage is the root of the pipeline.
def evaluate_test(self, stage, root=False): args_adjusted = [] for arg in stage.args: if isinstance(arg, PipelineFuture): arg = arg.default if isinstance(arg, Slot): value = arg.value arg._touched = True else: value = arg args_adjusted.append(value) ...
612,029
Evaluates the given Pipeline and enqueues sub-stages for execution. Args: pipeline_key: The db.Key or stringified key of the _PipelineRecord to run. purpose: Why evaluate was called ('start', 'finalize', or 'abort'). attempt: The attempt number that should be tried.
def evaluate(self, pipeline_key, purpose=None, attempt=0): After._thread_init() InOrder._thread_init() InOrder._local._activated = False if not isinstance(pipeline_key, db.Key): pipeline_key = db.Key(pipeline_key) pipeline_record = db.get(pipeline_key) if pipeline_record is None: ...
612,030
Handles an exception raised by a Pipeline's user code. Args: pipeline_key: The pipeline that raised the error. pipeline_func: The class path name of the Pipeline that was running. e: The exception that was raised. Returns: True if the exception should be re-raised up through the callin...
def handle_run_exception(self, pipeline_key, pipeline_func, e): if isinstance(e, Retry): retry_message = str(e) logging.warning('User forced retry for pipeline ID "%s" of %r: %s', pipeline_key.name(), pipeline_func, retry_message) self.transition_retry(pipeline_key, retr...
612,032
Marks the given pipeline as complete. Does nothing if the pipeline is no longer in a state that can be completed. Args: pipeline_key: db.Key of the _PipelineRecord that has completed.
def transition_complete(self, pipeline_key): def txn(): pipeline_record = db.get(pipeline_key) if pipeline_record is None: logging.warning( 'Tried to mark pipeline ID "%s" as complete but it does not exist.', pipeline_key.name()) raise db.Rollback() if ...
612,034
Marks the given pipeline as requiring another retry. Does nothing if all attempts have been exceeded. Args: pipeline_key: db.Key of the _PipelineRecord that needs to be retried. retry_message: User-supplied message indicating the reason for the retry.
def transition_retry(self, pipeline_key, retry_message): def txn(): pipeline_record = db.get(pipeline_key) if pipeline_record is None: logging.warning( 'Tried to retry pipeline ID "%s" but it does not exist.', pipeline_key.name()) raise db.Rollback() if...
612,035
Converts a _BarrierIndex key to a _BarrierRecord key. Args: barrier_index_key: db.Key for a _BarrierIndex entity. Returns: db.Key for the corresponding _BarrierRecord entity.
def to_barrier_key(cls, barrier_index_key): barrier_index_path = barrier_index_key.to_path() # Pick out the items from the _BarrierIndex key path that we need to # construct the _BarrierRecord key path. (pipeline_kind, dependent_pipeline_id, unused_kind, purpose) = barrier_index_path[-4:] ...
612,074
Displays pipeline structure in the jupyter notebook. Args: structure_dict (dict): dict returned by :func:`~steppy.base.Step.upstream_structure`.
def display_upstream_structure(structure_dict): graph = _create_graph(structure_dict) plt = Image(graph.create_png()) display(plt)
613,034
Saves pipeline diagram to disk as png file. Args: structure_dict (dict): dict returned by :func:`~steppy.base.Step.upstream_structure` filepath (str): filepath to which the png with pipeline visualization should be persisted
def persist_as_png(structure_dict, filepath): graph = _create_graph(structure_dict) graph.write(filepath, format='png')
613,035
Creates pydot graph from the pipeline structure dict. Args: structure_dict (dict): dict returned by step.upstream_structure Returns: graph (pydot.Dot): object representing upstream pipeline structure (with regard to the current Step).
def _create_graph(structure_dict): graph = pydot.Dot() for node in structure_dict['nodes']: graph.add_node(pydot.Node(node)) for node1, node2 in structure_dict['edges']: graph.add_edge(pydot.Edge(node1, node2)) return graph
613,036
Adapt inputs for the transformer included in the step. Args: all_ouputs: Dict of outputs from parent steps. The keys should match the names of these steps and the values should be their respective outputs. Returns: Dictionary with the same keys a...
def adapt(self, all_ouputs: AllOutputs) -> DataPacket: adapted = {} for name, recipe in self.adapting_recipes.items(): adapted[name] = self._construct(all_ouputs, recipe) return adapted
613,037
Extracts step by name from the pipeline. Extracted Step is a fully functional pipeline as well. All upstream Steps are already defined. Args: name (str): name of the step to be fetched Returns: Step (obj): extracted step
def get_step_by_name(self, name): self._validate_step_name(name) name = str(name) try: return self.all_upstream_steps[name] except KeyError as e: msg = 'No Step with name "{}" found. ' \ 'You have following Steps: {}'.format(name, list(s...
613,053
Creates upstream steps diagram and persists it to disk as png file. Pydot graph is created and persisted to disk as png file under the filepath directory. Args: filepath (str): filepath to which the png with steps visualization should be persisted
def persist_upstream_diagram(self, filepath): assert isinstance(filepath, str),\ 'Step {} error, filepath must be str. Got {} instead'.format(self.name, type(filepath)) persist_as_png(self.upstream_structure, filepath)
613,055
Performs fit followed by transform. This method simply combines fit and transform. Args: args: positional arguments (can be anything) kwargs: keyword arguments (can be anything) Returns: dict: output
def fit_transform(self, *args, **kwargs): self.fit(*args, **kwargs) return self.transform(*args, **kwargs)
613,068
Initializes the splitwise class. Sets consumer and access token Args: consumer_key (str) : Consumer Key provided by Spliwise consumer_secret (str): Consumer Secret provided by Splitwise access_token (:obj: `dict`) Access Token is a combination of oauth_token and oauth_token_...
def __init__(self,consumer_key,consumer_secret,access_token=None): self.consumer = oauth.Consumer(consumer_key, consumer_secret) #If access token is present then set the Access token if access_token: self.setAccessToken(access_token)
613,701
Set the ``attribute`` attr to the field in question so this always gets deserialzed into the field name without ``_id``. Args: field_name (str): The name of the field (the attribute name being set in the schema). schema (marshmallow.Schema): The actual parent sch...
def _add_to_schema(self, field_name, schema): super(ForeignKeyField, self)._add_to_schema(field_name, schema) if self.get_field_value('convert_fks', default=True): self.attribute = field_name.replace('_id', '')
613,811
Configure from a module by import path. Effectively, you give this an absolute or relative import path, it will import it, and then pass the resulting object to ``_configure_from_object``. Args: item (str): A string pointing to a valid import path. ...
def _configure_from_module(self, item): package = None if item[0] == '.': package = self.import_name obj = importlib.import_module(item, package=package) self.config.from_object(obj) return self
613,841
Validate the data and create a model instance from the data. Args: data (dict): The unserialized data to insert into the new model instance through it's constructor. Returns: peewee.Model|sqlalchemy.Model: The model instance with it's data insert...
def make_instance(cls, data): schema = cls() if not hasattr(schema.Meta, 'model'): raise AttributeError("In order to make an instance, a model for " "the schema must be defined in the Meta " "class.") serial...
613,847
Lazy constructor for the :class:`Component` class. This method will allow the component to be used like a Flask extension/singleton. Args: app (flask.Flask): The Application to base this Component upon. Useful for app wide singletons. Keyword Args: ...
def init_app(self, app, context=DEFAULT_DICT): if context is not _CONTEXT_MISSING: self.update_context(context, app=app) # do not readd callbacks if already present; and if there's no context # present, there's no real need to add callbacks if (app not in _CONTEXT_C...
613,856
Replace the component's context with a new one. Args: context (dict): The new context to set this component's context to. Keyword Args: app (flask.Flask, optional): The app to update this context for. If not provided, the result of ``Component.app`` will be used...
def update_context(self, context, app=None): if (app is None and self._context is _CONTEXT_MISSING and not in_app_context()): raise RuntimeError("Attempted to update component context without" " a bound app context or eager app set! Please" ...
613,858
Encode individual objects into their JSON representation. This method is used by :class:`flask.json.JSONEncoder` to encode individual items in the JSON object. Args: obj (object): Any Python object we wish to convert to JSON. Returns: str: The stringified, vali...
def default(self, obj): if isinstance(obj, decimal.Decimal): obj = format(obj, 'f') str_digit = text_type(obj) return (str_digit.rstrip('0').rstrip('.') if '.' in str_digit else str_digit) elif isinstance(obj, phonenu...
613,890
Generate a JSON Schema from a Marshmallow schema. Args: schema (marshmallow.Schema|str): The Marshmallow schema, or the Python path to one, to create the JSON schema for. Keyword Args: file_pointer (file, optional): The path or pointer to the file ...
def generate_json_schema(cls, schema, context=DEFAULT_DICT): schema = cls._get_schema(schema) # Generate the JSON Schema return cls(context=context).dump(schema).data
613,914
Method that will fetch a Marshmallow schema flexibly. Args: schema (marshmallow.Schema|str): Either the schema class, an instance of a schema, or a Python path to a schema. Returns: marshmallow.Schema: The desired schema. Raises: TypeError: ...
def _get_schema(cls, schema): if isinstance(schema, string_types): schema = cls._get_object_from_python_path(schema) if isclass(schema): schema = schema() if not isinstance(schema, Schema): raise TypeError("The schema must be a path to a Marshmallow...
613,916
Method that will fetch a Marshmallow schema from a path to it. Args: python_path (str): The string path to the Marshmallow schema. Returns: marshmallow.Schema: The schema matching the provided path. Raises: TypeError: This is raised if the specified object ...
def _get_object_from_python_path(python_path): # Dissect the path python_path = python_path.split('.') module_path = python_path[:-1] object_class = python_path[-1] if isinstance(module_path, list): module_path = '.'.join(module_path) # Grab the obj...
613,917
Automatically register and init the Flask Marshmallow extension. Args: app (flask.Flask): The application instance in which to initialize Flask Marshmallow upon. Kwargs: settings (dict): The settings passed to this method from the parent app. ...
def post_create_app(cls, app, **settings): super(MarshmallowAwareApp, cls).post_create_app(app, **settings) marsh.init_app(app) return app
613,918
Copies possible foreign key values from the object into the Event, skipping common keys like modified and created. Args: event (Event): The Event instance to copy the FKs into obj (fleaker.db.Model): The object to pull the values from
def copy_foreign_keys(self, event): event_keys = set(event._meta.fields.keys()) obj_keys = self._meta.fields.keys() matching_keys = event_keys.intersection(obj_keys) for key in matching_keys: # Skip created_by because that will always be the current_user ...
613,928
Populates the the audit JSON fields with raw data from the model, so all changes can be tracked and diffed. Args: event (Event): The Event instance to attach the data to instance (fleaker.db.Model): The newly created/updated model
def populate_audit_fields(self, event): event.updated = self._data event.original = self.get_original()._data
613,930
Update a single record by id with the provided data. Args: data (dict): The new data to update the record with. Returns: self: This is an instance of itself with the updated data. Raises: AttributeError: This is raised if a key in the ``data`` isn't ...
def update_instance(self, data): for key, val in iteritems(data): if not hasattr(self, key): raise AttributeError( "No field named {key} for model {model}".format( key=key, model=self.__class__.__name__ ...
613,954
Returns the awacs Action for a stream type given an arn Args: stream_arn (str): The Arn of the stream. Returns: :class:`awacs.aws.Action`: The appropriate stream type awacs Action class Raises: ValueError: If the stream type doesn't match kinesis or dynamodb.
def get_stream_action_type(stream_arn): stream_type_map = { "kinesis": awacs.kinesis.Action, "dynamodb": awacs.dynamodb.Action, } stream_type = stream_arn.split(":")[2] try: return stream_type_map[stream_type] except KeyError: raise ValueError( "Inv...
614,451
Adds statements to the policy. Args: statements (:class:`awacs.aws.Statement` or list): Either a single Statment, or a list of statements.
def add_policy_statements(self, statements): if isinstance(statements, Statement): statements = [statements] self._policy_statements.extend(statements)
614,456
Merge two sets of tags into a new troposphere object Args: left (Union[dict, troposphere.Tags]): dictionary or Tags object to be merged with lower priority right (Union[dict, troposphere.Tags]): dictionary or Tags object to be merged with higher priority factory (typ...
def merge_tags(left, right, factory=Tags): if isinstance(left, Mapping): tags = dict(left) elif hasattr(left, 'tags'): tags = _tags_to_dict(left.tags) else: tags = _tags_to_dict(left) if isinstance(right, Mapping): tags.update(right) elif hasattr(left, 'tags'):...
614,515
Load a manually curated gene panel into scout Args: panel_path(str): path to gene panel file adapter(scout.adapter.MongoAdapter) date(str): date of gene panel on format 2017-12-24 display_name(str) version(float) panel_type(str) panel_id(str) inst...
def load_panel(panel_path, adapter, date=None, display_name=None, version=None, panel_type=None, panel_id=None, institute=None): panel_lines = get_file_handle(panel_path) try: # This will parse panel metadata if includeed in panel file panel_info = get_panel_info( ...
614,916
Load PanelApp panels into scout database If no panel_id load all PanelApp panels Args: adapter(scout.adapter.MongoAdapter) panel_id(str): The panel app panel id
def load_panel_app(adapter, panel_id=None, institute='cust000'): base_url = 'https://panelapp.genomicsengland.co.uk/WebServices/{0}/' hgnc_map = adapter.genes_by_alias() if panel_id: panel_ids = [panel_id] if not panel_id: LOG.info("Fetching all panel app panels"...
614,917
Export causative variants for a collaborator Args: adapter(MongoAdapter) collaborator(str) document_id(str): Search for a specific variant case_id(str): Search causative variants for a case Yields: variant_obj(scout.Models.Variant): Variants marked as causative ordered ...
def export_variants(adapter, collaborator, document_id=None, case_id=None): # Store the variants in a list for sorting variants = [] if document_id: yield adapter.variant(document_id) return variant_ids = adapter.get_causatives( institute_id=collaborator, case_id=c...
614,918
Create the lines for an excel file with verified variants for an institute Args: aggregate_variants(list): a list of variants with aggregates case data unique_callers(set): a unique list of available callers Returns: document_lines(list): list of lines to in...
def export_verified_variants(aggregate_variants, unique_callers): document_lines = [] for variant in aggregate_variants: # get genotype and allele depth for each sample samples = [] for sample in variant['samples']: line = [] # line elements corespond to contants.variant...
614,919
Export mitochondrial variants for a case to create a MT excel report Args: variants(list): all MT variants for a case, sorted by position sample_id(str) : the id of a sample within the case Returns: document_lines(list): list of lines to include in the document
def export_mt_variants(variants, sample_id): document_lines = [] for variant in variants: line = [] position = variant.get('position') change = '>'.join([variant.get('reference'),variant.get('alternative')]) line.append(position) line.append(change) line.appe...
614,920
Add the coordinates from ensembl Args: genes(dict): Dictionary with all genes ensembl_lines(iteable): Iteable with raw ensembl info
def add_ensembl_info(genes, ensembl_lines): LOG.info("Adding ensembl coordinates") # Parse and add the ensembl gene info if isinstance(ensembl_lines, DataFrame): ensembl_genes = parse_ensembl_gene_request(ensembl_lines) else: ensembl_genes = parse_ensembl_genes(ensembl_lines) ...
614,939
Add information from the exac genes Currently we only add the pLi score on gene level The exac resource only use HGNC symbol to identify genes so we need our alias mapping. Args: genes(dict): Dictionary with all genes alias_genes(dict): Genes mapped to all aliases ...
def add_exac_info(genes, alias_genes, exac_lines): LOG.info("Add exac pli scores") for exac_gene in parse_exac_genes(exac_lines): hgnc_symbol = exac_gene['hgnc_symbol'].upper() pli_score = exac_gene['pli_score'] for hgnc_id in get_correct_ids(hgnc_symbol, alias_genes): ...
614,940
Add omim information We collect information on what phenotypes that are associated with a gene, what inheritance models that are associated and the correct omim id. Args: genes(dict): Dictionary with all genes alias_genes(dict): Genes mapped to all aliases genemap_lines(ite...
def add_omim_info(genes, alias_genes, genemap_lines, mim2gene_lines): LOG.info("Add omim info") omim_genes = get_mim_genes(genemap_lines, mim2gene_lines) for hgnc_symbol in omim_genes: omim_info = omim_genes[hgnc_symbol] inheritance = omim_info.get('inheritance', set()) ...
614,941
Send a request to MatchMaker and return its response Args: url(str): url to send request to token(str): MME server authorization token method(str): 'GET', 'POST' or 'DELETE' content_type(str): MME request Content-Type accept(str): accepted response data(dict): eventu...
def matchmaker_request(url, token, method, content_type=None, accept=None, data=None): headers = Headers() headers = { 'X-Auth-Token': token} if content_type: headers['Content-Type'] = content_type if accept: headers['Accept'] = accept #sending data anyway so response will not ...
614,948
Return the available MatchMaker nodes Args: mme_base_url(str): base URL of MME service token(str): MME server authorization token Returns: nodes(list): a list of node disctionaries
def mme_nodes(mme_base_url, token): nodes = [] if not mme_base_url or not token: return nodes url = ''.join([mme_base_url, '/nodes']) nodes = matchmaker_request(url=url, token=token, method='GET') LOG.info('Matchmaker has the following connected nodes:{}'.format(nodes)) return nodes
614,949
Get the cytoband coordinate for a position Args: chrom(str) pos(int) Returns: coordinate(str)
def get_cytoband_coordinates(chrom, pos): coordinate = "" if chrom in CYTOBANDS: for interval in CYTOBANDS[chrom][pos]: coordinate = interval.data return coordinate
614,950
Get the subcategory for a VCF variant The sub categories are: 'snv', 'indel', 'del', 'ins', 'dup', 'bnd', 'inv' Args: alt_len(int) ref_len(int) category(str) svtype(str) Returns: subcategory(str)
def get_sub_category(alt_len, ref_len, category, svtype=None): subcategory = '' if category in ('snv', 'indel', 'cancer'): if ref_len == alt_len: subcategory = 'snv' else: subcategory = 'indel' elif category == 'sv': subcategory = svtype return subc...
614,951
Return the length of a variant Args: alt_len(int) ref_len(int) category(str) svtype(str) svlen(int)
def get_length(alt_len, ref_len, category, pos, end, svtype=None, svlen=None): # -1 would indicate uncertain length length = -1 if category in ('snv', 'indel', 'cancer'): if ref_len == alt_len: length = alt_len else: length = abs(ref_len - alt_len) elif cate...
614,952
Return the end coordinate for a variant Args: pos(int) alt(str) category(str) snvend(str) svend(int) svlen(int) Returns: end(int)
def get_end(pos, alt, category, snvend=None, svend=None, svlen=None): # If nothing is known we set end to be same as start end = pos # If variant is snv or indel we know that cyvcf2 can handle end pos if category in ('snv', 'indel', 'cancer'): end = snvend # With SVs we have to be a bi...
614,953
Find out the coordinates for a variant Args: variant(cyvcf2.Variant) Returns: coordinates(dict): A dictionary on the form: { 'position':<int>, 'end':<int>, 'end_chrom':<str>, 'length':<int>, 'sub_category':<str>, '...
def parse_coordinates(variant, category): ref = variant.REF if variant.ALT: alt = variant.ALT[0] if category=="str" and not variant.ALT: alt = '.' chrom_match = CHR_PATTERN.match(variant.CHROM) chrom = chrom_match.group(2) svtype = variant.INFO.get('SVTYPE') if svtype...
614,954
Parse iterable with cytoband coordinates Args: lines(iterable): Strings on format "chr1\t2300000\t5400000\tp36.32\tgpos25" Returns: cytobands(dict): Dictionary with chromosome names as keys and interval trees as values
def parse_cytoband(lines): cytobands = {} for line in lines: line = line.rstrip() splitted_line = line.split('\t') chrom = splitted_line[0].lstrip('chr') start = int(splitted_line[1]) stop = int(splitted_line[2]) name = splitted_line[3] if chrom in cy...
614,955
Update a gene panel in the database We need to update the actual gene panel and then all cases that refers to the panel. Args: adapter(scout.adapter.MongoAdapter) panel_name(str): Unique name for a gene panel panel_version(float) new_version(float) new_date(date...
def update_panel(adapter, panel_name, panel_version, new_version=None, new_date=None): panel_obj = adapter.gene_panel(panel_name, panel_version) if not panel_obj: raise IntegrityError("Panel %s version %s does not exist" % (panel_name, panel_version)) updated_panel = adapter.update_panel(pane...
614,957
Parse an exac formated line Args: line(list): A list with exac gene info header(list): A list with the header info Returns: exac_info(dict): A dictionary with the relevant info
def parse_exac_line(line, header): exac_gene = {} splitted_line = line.rstrip().split('\t') exac_gene = dict(zip(header, splitted_line)) exac_gene['hgnc_symbol'] = exac_gene['gene'] exac_gene['pli_score'] = float(exac_gene['pLI']) exac_gene['raw'] = line return exac_gene
614,959
Parse lines with exac formated genes This is designed to take a dump with genes from exac. This is downloaded from: ftp.broadinstitute.org/pub/ExAC_release//release0.3/functional_gene_constraint/ fordist_cleaned_exac_r03_march16_z_pli_rec_null_data.txt Args...
def parse_exac_genes(lines): header = [] logger.info("Parsing exac genes...") for index, line in enumerate(lines): if index == 0: header = line.rstrip().split('\t') elif len(line) > 0: exac_gene = parse_exac_line(line, header) yield exac_...
614,960
Parse a peddy.ped file Args: lines(iterable(str)) Returns: peddy_ped(list(dict))
def parse_peddy_ped(lines): peddy_ped = [] header = [] for i,line in enumerate(lines): line = line.rstrip() if i == 0: # Header line header = line.lstrip('#').split('\t') else: ind_info = dict(zip(header, line.split('\t'))) ...
614,967
Parse a .ped_check.csv file Args: lines(iterable(str)) Returns: ped_check(list(dict))
def parse_peddy_ped_check(lines): ped_check = [] header = [] for i,line in enumerate(lines): line = line.rstrip() if i == 0: # Header line header = line.lstrip('#').split(',') else: pair_info = dict(zip(header, line.split(','))) ...
614,968
Parse a .ped_check.csv file Args: lines(iterable(str)) Returns: sex_check(list(dict))
def parse_peddy_sex_check(lines): sex_check = [] header = [] for i,line in enumerate(lines): line = line.rstrip() if i == 0: # Header line header = line.lstrip('#').split(',') else: ind_info = dict(zip(header, line.split(','))) # ...
614,969
Retrieves a list of HPO terms from scout database Args: store (obj): an adapter to the scout database query (str): the term to search in the database limit (str): the number of desired results Returns: hpo_phenotypes (dict): the complete list of HPO objects stored in scout
def hpo_terms(store, query = None, limit = None): hpo_phenotypes = {} if limit: limit=int(limit) hpo_phenotypes['phenotypes'] = list(store.hpo_terms(text=query, limit=limit)) return hpo_phenotypes
614,970
Build a small phenotype object Build a dictionary with phenotype_id and description Args: phenotype_id (str): The phenotype id adapter (scout.adapter.MongoAdapter) Returns: phenotype_obj (dict): dict( phenotype_id = str, feature = str, # descri...
def build_phenotype(phenotype_id, adapter): phenotype_obj = {} phenotype = adapter.hpo_term(phenotype_id) if phenotype: phenotype_obj['phenotype_id'] = phenotype['hpo_id'] phenotype_obj['feature'] = phenotype['description'] return phenotype
614,972
Return a requests response from url Args: url(str) Returns: decoded_data(str): Decoded response
def get_request(url): try: LOG.info("Requesting %s", url) response = urllib.request.urlopen(url) if url.endswith('.gz'): LOG.info("Decompress zipped file") data = gzip.decompress(response.read()) # a `bytes` object else: data = response.r...
614,978
Fetch a resource and return the resulting lines in a list Send file_name to get more clean log messages Args: url(str) Returns: lines(list(str))
def fetch_resource(url): try: data = get_request(url) lines = data.split('\n') except Exception as err: raise err return lines
614,979
Fetch the necessary mim files using a api key Args: api_key(str): A api key necessary to fetch mim data Returns: mim_files(dict): A dictionary with the neccesary files
def fetch_mim_files(api_key, mim2genes=False, mimtitles=False, morbidmap=False, genemap2=False): LOG.info("Fetching OMIM files from https://omim.org/") mim2genes_url = 'https://omim.org/static/omim/data/mim2gene.txt' mimtitles_url= 'https://data.omim.org/downloads/{0}/mimTitles.txt'.format(api_key) ...
614,980
Fetch the ensembl genes Args: build(str): ['37', '38']
def fetch_ensembl_genes(build='37'): if build == '37': url = 'http://grch37.ensembl.org' else: url = 'http://www.ensembl.org' LOG.info("Fetching ensembl genes from %s", url) dataset_name = 'hsapiens_gene_ensembl' dataset = pybiomart.Dataset(name=dataset_name, host=url)...
614,981