sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def ask_yesno(msg="Proceed?", dft=None): """Prompts the user for a yes or no answer. Returns True for yes, False for no.""" yes = ["y", "yes", "Y", "YES"] no = ["n", "no", "N", "NO"] if dft != None: dft = yes[0] if (dft in yes or dft == True) else no[0] return ask(msg, dft=dft, vld=yes+n...
Prompts the user for a yes or no answer. Returns True for yes, False for no.
entailment
def ask_int(msg="Enter an integer", dft=None, vld=None, hlp=None): """Prompts the user for an integer.""" vld = vld or [int] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=int), hlp=hlp)
Prompts the user for an integer.
entailment
def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp)
Prompts the user for a float.
entailment
def ask_str(msg="Enter a string", dft=None, vld=None, shw=True, blk=True, hlp=None): """Prompts the user for a string.""" vld = vld or [str] return ask(msg, dft=dft, vld=vld, shw=shw, blk=blk, hlp=hlp)
Prompts the user for a string.
entailment
def ask_captcha(length=4): """Prompts the user for a random string.""" captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length)) ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False)
Prompts the user for a random string.
entailment
def clear(): """Clears the console.""" if sys.platform.startswith("win"): call("cls", shell=True) else: call("clear", shell=True)
Clears the console.
entailment
def status(*args, **kwargs): """Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: ...
Prints a status message at the start and finish of an associated function. Can be used as a function decorator or as a function that accepts another function as the first parameter. **Params**: The following parameters are available when used as a decorator: - msg (str) [args] - Message to prin...
entailment
def fatal(msg, exitcode=1, **kwargs): """Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.""" # NOTE: Can't use normal arg named `pause` since function has same name. pause_before_exit = kwargs.pop("pause") if "pause" in kwargs.keys() else False echo("[FA...
Prints a message then exits the program. Optionally pause before exit with `pause=True` kwarg.
entailment
def hrule(width=None, char=None): """Outputs or returns a horizontal line of the given character and width. Returns printed string.""" width = width or HRWIDTH char = char or HRCHAR return echo(getline(char, width))
Outputs or returns a horizontal line of the given character and width. Returns printed string.
entailment
def title(msg): """Sets the title of the console window.""" if sys.platform.startswith("win"): ctypes.windll.kernel32.SetConsoleTitleW(tounicode(msg))
Sets the title of the console window.
entailment
def wrap(item, args=None, krgs=None, **kwargs): """Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item. "...
Wraps the given item content between horizontal lines. Item can be a string or a function. **Examples**: :: qprompt.wrap("Hi, this will be wrapped.") # String item. qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
entailment
def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue ...
Attempts to guess the menu entry name from the function name.
entailment
def add(self, name, desc, func=None, args=None, krgs=None): """Add a menu entry.""" self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
Add a menu entry.
entailment
def enum(self, desc, func=None, args=None, krgs=None): """Add a menu entry whose name will be an auto indexed number.""" name = str(len(self.entries)+1) self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {}))
Add a menu entry whose name will be an auto indexed number.
entailment
def show(self, **kwargs): """Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.""" show_kwargs = copy.deepcopy(self._show_kwargs) show_kwargs.update(kwargs) return show_menu(self.entries, **show_kwargs)
Shows the menu. Any `kwargs` supplied will be passed to `show_menu()`.
entailment
def run(self, name): """Runs the function associated with the given entry `name`.""" for entry in self.entries: if entry.name == name: run_func(entry) break
Runs the function associated with the given entry `name`.
entailment
def main(self, auto=None, loop=False, quit=("q", "Quit"), **kwargs): """Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provide...
Runs the standard menu main logic. Any `kwargs` supplied will be pass to `Menu.show()`. If `argv` is provided to the script, it will be used as the `auto` parameter. **Params**: - auto ([str]) - If provided, the list of strings with be used as input for the menu prompts. ...
entailment
def partition_scripts(scripts, start_type1, start_type2): """Return two lists of scripts out of the original `scripts` list. Scripts that begin with a `start_type1` or `start_type2` blocks are returned first. All other scripts are returned second. """ match, other = [], [] for script in scrip...
Return two lists of scripts out of the original `scripts` list. Scripts that begin with a `start_type1` or `start_type2` blocks are returned first. All other scripts are returned second.
entailment
def attribute_result(cls, sprites): """Return mapping of attributes to if they were initialized or not.""" retval = dict((x, True) for x in cls.ATTRIBUTES) for properties in sprites.values(): for attribute, state in properties.items(): retval[attribute] &= state != cl...
Return mapping of attributes to if they were initialized or not.
entailment
def attribute_state(cls, scripts, attribute): """Return the state of the scripts for the given attribute. If there is more than one 'when green flag clicked' script and they both modify the attribute, then the attribute is considered to not be initialized. """ green_fla...
Return the state of the scripts for the given attribute. If there is more than one 'when green flag clicked' script and they both modify the attribute, then the attribute is considered to not be initialized.
entailment
def output_results(cls, sprites): """Output whether or not each attribute was correctly initialized. Attributes that were not modified at all are considered to be properly initialized. """ print(' '.join(cls.ATTRIBUTES)) format_strs = ['{{{}!s:^{}}}'.format(x, len(x)) f...
Output whether or not each attribute was correctly initialized. Attributes that were not modified at all are considered to be properly initialized.
entailment
def sprite_changes(cls, sprite): """Return a mapping of attributes to their initilization state.""" retval = dict((x, cls.attribute_state(sprite.scripts, x)) for x in (x for x in cls.ATTRIBUTES if x != 'background')) return retval
Return a mapping of attributes to their initilization state.
entailment
def analyze(self, scratch, **kwargs): """Run and return the results of the AttributeInitialization plugin.""" changes = dict((x.name, self.sprite_changes(x)) for x in scratch.sprites) changes['stage'] = { 'background': self.attribute_state(scratch.stage.scripts...
Run and return the results of the AttributeInitialization plugin.
entailment
def variable_state(cls, scripts, variables): """Return the initialization state for each variable in variables. The state is determined based on the scripts passed in via the scripts parameter. If there is more than one 'when green flag clicked' script and they both modify the ...
Return the initialization state for each variable in variables. The state is determined based on the scripts passed in via the scripts parameter. If there is more than one 'when green flag clicked' script and they both modify the attribute, then the attribute is considered to not be ...
entailment
def analyze(self, scratch, **kwargs): """Run and return the results of the VariableInitialization plugin.""" variables = dict((x, self.variable_state(x.scripts, x.variables)) for x in scratch.sprites) variables['global'] = self.variable_state(self.iter_scripts(scratch), ...
Run and return the results of the VariableInitialization plugin.
entailment
def finalize(self): """Output the default sprite names found in the project.""" print('{} default sprite names found:'.format(self.total_default)) for name in self.list_default: print(name)
Output the default sprite names found in the project.
entailment
def analyze(self, scratch, **kwargs): """Run and return the results from the SpriteNaming plugin.""" for sprite in self.iter_sprites(scratch): for default in self.default_names: if default in sprite.name: self.total_default += 1 self.li...
Run and return the results from the SpriteNaming plugin.
entailment
def get_tunneling(handler, registry): """ Allows all methods to be tunneled via GET for dev/debuging purposes. """ log.info('get_tunneling enabled') def get_tunneling(request): if request.method == 'GET': method = request.GET.pop('_m', 'GET') request.method = method ...
Allows all methods to be tunneled via GET for dev/debuging purposes.
entailment
def enable_selfalias(config, id_name): """ This allows replacing id_name with "self". e.g. /users/joe/account == /users/self/account if joe is in the session as an authorized user """ def context_found_subscriber(event): request = event.request user = getattr(request, 'user', No...
This allows replacing id_name with "self". e.g. /users/joe/account == /users/self/account if joe is in the session as an authorized user
entailment
def convert_dotted(params): """ Convert dotted keys in :params: dictset to a nested dictset. E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}} """ if not isinstance(params, dictset): params = dictset(params) dotted_items = {k: v for k, v in params.items()...
Convert dotted keys in :params: dictset to a nested dictset. E.g. {'settings.foo': 'bar'} -> {'settings': {'foo': 'bar'}}
entailment
def prepare_request_params(self, _query_params, _json_params): """ Prepare query and update params. """ self._query_params = dictset( _query_params or self.request.params.mixed()) self._json_params = dictset(_json_params) ctype = self.request.content_type if self.req...
Prepare query and update params.
entailment
def set_override_rendered(self): """ Set self.request.override_renderer if needed. """ if '' in self.request.accept: self.request.override_renderer = self._default_renderer elif 'application/json' in self.request.accept: self.request.override_renderer = 'nefertari_json' ...
Set self.request.override_renderer if needed.
entailment
def _setup_aggregation(self, aggregator=None): """ Wrap `self.index` method with ESAggregator. This makes `self.index` to first try to run aggregation and only on fail original method is run. Method is wrapped only if it is defined and `elasticsearch.enable_aggregations` setting is true...
Wrap `self.index` method with ESAggregator. This makes `self.index` to first try to run aggregation and only on fail original method is run. Method is wrapped only if it is defined and `elasticsearch.enable_aggregations` setting is true.
entailment
def get_collection_es(self): """ Query ES collection and return results. This is default implementation of querying ES collection with `self._query_params`. It must return found ES collection results for default response renderers to work properly. """ from nefertari.ela...
Query ES collection and return results. This is default implementation of querying ES collection with `self._query_params`. It must return found ES collection results for default response renderers to work properly.
entailment
def fill_null_values(self): """ Fill missing model fields in JSON with {key: null value}. Only run for PUT requests. """ if not self.Model: log.info("%s has no model defined" % self.__class__.__name__) return empty_values = self.Model.get_null_values() ...
Fill missing model fields in JSON with {key: null value}. Only run for PUT requests.
entailment
def set_public_limits(self): """ Set public limits if auth is enabled and user is not authenticated. Also sets default limit for GET, HEAD requests. """ if self.request.method.upper() in ['GET', 'HEAD']: self._query_params.process_int_param('_limit', 20) if s...
Set public limits if auth is enabled and user is not authenticated. Also sets default limit for GET, HEAD requests.
entailment
def convert_ids2objects(self): """ Convert object IDs from `self._json_params` to objects if needed. Only IDs that belong to relationship field of `self.Model` are converted. """ if not self.Model: log.info("%s has no model defined" % self.__class__.__name__) ...
Convert object IDs from `self._json_params` to objects if needed. Only IDs that belong to relationship field of `self.Model` are converted.
entailment
def setup_default_wrappers(self): """ Setup defaulf wrappers. Wrappers are applied when view method does not return instance of Response. In this case nefertari renderers call wrappers and handle response generation. """ # Index self._after_calls['index'] = [ ...
Setup defaulf wrappers. Wrappers are applied when view method does not return instance of Response. In this case nefertari renderers call wrappers and handle response generation.
entailment
def migrate_codec(config_old, config_new): '''Migrate data from mongodict <= 0.2.1 to 0.3.0 `config_old` and `config_new` should be dictionaries with the keys regarding to MongoDB server: - `host` - `port` - `database` - `collection` ''' assert mongodict.__version__ i...
Migrate data from mongodict <= 0.2.1 to 0.3.0 `config_old` and `config_new` should be dictionaries with the keys regarding to MongoDB server: - `host` - `port` - `database` - `collection`
entailment
def from_dict(cls, data, model): """ Generate map of `fieldName: clsInstance` from dict. :param data: Dict where keys are field names and values are new values of field. :param model: Model class to which fields from :data: belong. """ model_provided = model is not N...
Generate map of `fieldName: clsInstance` from dict. :param data: Dict where keys are field names and values are new values of field. :param model: Model class to which fields from :data: belong.
entailment
def register(self): """ Register new user by POSTing all required data. """ user, created = self.Model.create_account( self._json_params) if not created: raise JHTTPConflict('Looks like you already have an account.') self.request._user = user pk_field = ...
Register new user by POSTing all required data.
entailment
def register(self): """ Register a new user by POSTing all required data. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ user, created = self.Model.create_account(self._json_params) if user.api_key is None: raise JHTTPBadReq...
Register a new user by POSTing all required data. User's `Authorization` header value is returned in `WWW-Authenticate` header.
entailment
def claim_token(self, **params): """Claim current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ self._json_params.update(params) success, self.user = self.Model.authenticate_by_password( ...
Claim current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header.
entailment
def reset_token(self, **params): """ Reset current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header. """ response = self.claim_token(**params) if not self.user: return response self...
Reset current token by POSTing 'login' and 'password'. User's `Authorization` header value is returned in `WWW-Authenticate` header.
entailment
def _apply_nested_privacy(self, data): """ Apply privacy to nested documents. :param data: Dict of data to which privacy is already applied. """ kw = { 'is_admin': self.is_admin, 'drop_hidden': self.drop_hidden, } for key, val in data.items(): ...
Apply privacy to nested documents. :param data: Dict of data to which privacy is already applied.
entailment
def _set_object_self(self, obj): """ Add '_self' key value to :obj: dict. """ from nefertari.elasticsearch import ES location = self.request.path_url route_kwargs = {} """ Check for parents """ if self.request.matchdict: route_kwargs.update(self.request.match...
Add '_self' key value to :obj: dict.
entailment
def get_root_resource(config): """Returns the root resource.""" app_package_name = get_app_package_name(config) return config.registry._root_resources.setdefault( app_package_name, Resource(config))
Returns the root resource.
entailment
def add_resource_routes(config, view, member_name, collection_name, **kwargs): """ ``view`` is a dotted name of (or direct reference to) a Python view class, e.g. ``'my.package.views.MyView'``. ``member_name`` should be the appropriate singular version of the resource given your locale and used...
``view`` is a dotted name of (or direct reference to) a Python view class, e.g. ``'my.package.views.MyView'``. ``member_name`` should be the appropriate singular version of the resource given your locale and used with members of the collection. ``collection_name`` will be used to refer to the reso...
entailment
def get_default_view_path(resource): "Returns the dotted path to the default view class." parts = [a.member_name for a in resource.ancestors] +\ [resource.collection_name or resource.member_name] if resource.prefix: parts.insert(-1, resource.prefix) view_file = '%s' % '_'.join(par...
Returns the dotted path to the default view class.
entailment
def get_ancestors(self): "Returns the list of ancestor resources." if self._ancestors: return self._ancestors if not self.parent: return [] obj = self.resource_map.get(self.parent.uid) while obj and obj.member_name: self._ancestors.append(o...
Returns the list of ancestor resources.
entailment
def add(self, member_name, collection_name='', parent=None, uid='', **kwargs): """ :param member_name: singular name of the resource. It should be the appropriate singular version of the resource given your locale and used with members of the collection. :par...
:param member_name: singular name of the resource. It should be the appropriate singular version of the resource given your locale and used with members of the collection. :param collection_name: plural name of the resource. It will be used to refer to the resource collectio...
entailment
def add_from_child(self, resource, **kwargs): """ Add a resource with its all children resources to the current resource. """ new_resource = self.add( resource.member_name, resource.collection_name, **kwargs) for child in resource.children: new_resource.a...
Add a resource with its all children resources to the current resource.
entailment
def add(self, path): """ Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str """ name_with_ext = os.path.split(path)[1] # spli...
Add the path of a data set to the list of available sets NOTE: a data set is assumed to be a pickled and gzip compressed Pandas DataFrame Parameters ---------- path : str
entailment
def unpack(self, name): """ Unpacks a data set to a Pandas DataFrame Parameters ---------- name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame """ path = self.list[name] df = pd.read_pickl...
Unpacks a data set to a Pandas DataFrame Parameters ---------- name : str call `.list` to see all availble datasets Returns ------- pd.DataFrame
entailment
def six_frame(genome, table, minimum = 10): """ translate each sequence into six reading frames """ for seq in parse_fasta(genome): dna = Seq(seq[1].upper().replace('U', 'T'), IUPAC.ambiguous_dna) counter = 0 for sequence in ['f', dna], ['rc', dna.reverse_complement()]: ...
translate each sequence into six reading frames
entailment
def publish_processed_network_packets( name="not-set", task_queue=None, result_queue=None, need_response=False, shutdown_msg="SHUTDOWN"): """ # Redis/RabbitMQ/SQS messaging endpoints for pub-sub routing_key = ev("PUBLISH_EXCHANGE", "reporting.acc...
# Redis/RabbitMQ/SQS messaging endpoints for pub-sub routing_key = ev("PUBLISH_EXCHANGE", "reporting.accounts") queue_name = ev("PUBLISH_QUEUE", "reporting.accounts") auth_url = ev("PUB_BROKER_URL", "redis://localhost:6379/15") serializer = "jso...
entailment
def run_main( need_response=False, callback=None): """run_main start the packet consumers and the packet processors :param need_response: should send response back to publisher :param callback: handler method """ stop_file = ev("STOP_FILE", "/opt/stop_record...
run_main start the packet consumers and the packet processors :param need_response: should send response back to publisher :param callback: handler method
entailment
def best_model(seq2hmm): """ determine the best model: archaea, bacteria, eukarya (best score) """ for seq in seq2hmm: best = [] for model in seq2hmm[seq]: best.append([model, sorted([i[-1] for i in seq2hmm[seq][model]], reverse = True)[0]]) best_model = sorted(best, ...
determine the best model: archaea, bacteria, eukarya (best score)
entailment
def check_gaps(matches, gap_threshold = 0): """ check for large gaps between alignment windows """ gaps = [] prev = None for match in sorted(matches, key = itemgetter(0)): if prev is None: prev = match continue if match[0] - prev[1] >= gap_threshold: ...
check for large gaps between alignment windows
entailment
def check_overlap(current, hit, overlap = 200): """ determine if sequence has already hit the same part of the model, indicating that this hit is for another 16S rRNA gene """ for prev in current: p_coords = prev[2:4] coords = hit[2:4] if get_overlap(coords, p_coords) >= over...
determine if sequence has already hit the same part of the model, indicating that this hit is for another 16S rRNA gene
entailment
def check_order(current, hit, overlap = 200): """ determine if hits are sequential on model and on the same strand * if not, they should be split into different groups """ prev_model = current[-1][2:4] prev_strand = current[-1][-2] hit_model = hit[2:4] hit_strand = hit[-2] # ...
determine if hits are sequential on model and on the same strand * if not, they should be split into different groups
entailment
def hit_groups(hits): """ * each sequence may have more than one 16S rRNA gene * group hits for each gene """ groups = [] current = False for hit in sorted(hits, key = itemgetter(0)): if current is False: current = [hit] elif check_overlap(current, hit) is True or...
* each sequence may have more than one 16S rRNA gene * group hits for each gene
entailment
def find_coordinates(hmms, bit_thresh): """ find 16S rRNA gene sequence coordinates """ # get coordinates from cmsearch output seq2hmm = parse_hmm(hmms, bit_thresh) seq2hmm = best_model(seq2hmm) group2hmm = {} # group2hmm[seq][group] = [model, strand, coordinates, matches, gaps] for seq,...
find 16S rRNA gene sequence coordinates
entailment
def get_info(line, bit_thresh): """ get info from either ssu-cmsearch or cmsearch output """ if len(line) >= 18: # output is from cmsearch id, model, bit, inc = line[0].split()[0], line[2], float(line[14]), line[16] sstart, send, strand = int(line[7]), int(line[8]), line[9] mstar...
get info from either ssu-cmsearch or cmsearch output
entailment
def check_buffer(coords, length, buffer): """ check to see how much of the buffer is being used """ s = min(coords[0], buffer) e = min(length - coords[1], buffer) return [s, e]
check to see how much of the buffer is being used
entailment
def convert_parser_to(parser, parser_or_type, metadata_props=None): """ :return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type is a type, an instance of it must contain a update method. The update method must also process the set of properties supported by...
:return: a parser of type parser_or_type, initialized with the properties of parser. If parser_or_type is a type, an instance of it must contain a update method. The update method must also process the set of properties supported by MetadataParser for the conversion to have any affect. :param parser: the pa...
entailment
def get_metadata_parser(metadata_container, **metadata_defaults): """ Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file. :return: a new instance of a parser corresponding to the standard represented by metadata_container :see: get_parsed_content(metdata_con...
Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file. :return: a new instance of a parser corresponding to the standard represented by metadata_container :see: get_parsed_content(metdata_content) for more on types of content that can be parsed
entailment
def get_parsed_content(metadata_content): """ Parses any of the following types of content: 1. XML string or file object: parses XML content 2. MetadataParser instance: deep copies xml_tree 3. Dictionary with nested objects containing: - name (required): the name of the element tag -...
Parses any of the following types of content: 1. XML string or file object: parses XML content 2. MetadataParser instance: deep copies xml_tree 3. Dictionary with nested objects containing: - name (required): the name of the element tag - text: the text contained by element - tail: t...
entailment
def _import_parsers(): """ Lazy imports to prevent circular dependencies between this module and utils """ global ARCGIS_NODES global ARCGIS_ROOTS global ArcGISParser global FGDC_ROOT global FgdcParser global ISO_ROOTS global IsoParser global VALID_ROOTS if ARCGIS_NODES is N...
Lazy imports to prevent circular dependencies between this module and utils
entailment
def _init_metadata(self): """ Dynamically sets attributes from a Dictionary passed in by children. The Dictionary will contain the name of each attribute as keys, and either an XPATH mapping to a text value in _xml_tree, or a function that takes no parameters and returns the inte...
Dynamically sets attributes from a Dictionary passed in by children. The Dictionary will contain the name of each attribute as keys, and either an XPATH mapping to a text value in _xml_tree, or a function that takes no parameters and returns the intended value.
entailment
def _init_data_map(self): """ Default data map initialization: MUST be overridden in children """ if self._data_map is None: self._data_map = {'_root': None} self._data_map.update({}.fromkeys(self._metadata_props))
Default data map initialization: MUST be overridden in children
entailment
def _get_template(self, root=None, **metadata_defaults): """ Iterate over items metadata_defaults {prop: val, ...} to populate template """ if root is None: if self._data_map is None: self._init_data_map() root = self._xml_root = self._data_map['_root'] ...
Iterate over items metadata_defaults {prop: val, ...} to populate template
entailment
def _get_xpath_for(self, prop): """ :return: the configured xpath for a given property """ xpath = self._data_map.get(prop) return getattr(xpath, 'xpath', xpath)
:return: the configured xpath for a given property
entailment
def _parse_complex(self, prop): """ Default parsing operation for a complex struct """ xpath_root = None xpath_map = self._data_structures[prop] return parse_complex(self._xml_tree, xpath_root, xpath_map, prop)
Default parsing operation for a complex struct
entailment
def _parse_complex_list(self, prop): """ Default parsing operation for lists of complex structs """ xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return parse_complex_list(self._xml_tree, xpath_root, xpath_map, prop)
Default parsing operation for lists of complex structs
entailment
def _parse_dates(self, prop=DATES): """ Creates and returns a Date Types data structure parsed from the metadata """ return parse_dates(self._xml_tree, self._data_structures[prop])
Creates and returns a Date Types data structure parsed from the metadata
entailment
def _update_complex(self, **update_props): """ Default update operation for a complex struct """ prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex(xpath_root=xpath_root, xpath_map=xpath_map, **update...
Default update operation for a complex struct
entailment
def _update_complex_list(self, **update_props): """ Default update operation for lists of complex structs """ prop = update_props['prop'] xpath_root = self._get_xroot_for(prop) xpath_map = self._data_structures[prop] return update_complex_list(xpath_root=xpath_root, xpath_map=x...
Default update operation for lists of complex structs
entailment
def _update_dates(self, xpath_root=None, **update_props): """ Default update operation for Dates metadata :see: gis_metadata.utils._complex_definitions[DATES] """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = (update_props['...
Default update operation for Dates metadata :see: gis_metadata.utils._complex_definitions[DATES]
entailment
def write(self, use_template=False, out_file_or_path=None, encoding=DEFAULT_ENCODING): """ Validates instance properties, updates an XML tree with them, and writes the content to a file. :param use_template: if True, updates a new template XML tree; otherwise the original XML tree :param...
Validates instance properties, updates an XML tree with them, and writes the content to a file. :param use_template: if True, updates a new template XML tree; otherwise the original XML tree :param out_file_or_path: optionally override self.out_file_or_path with a custom file path :param encodin...
entailment
def validate(self): """ Default validation for updated properties: MAY be overridden in children """ validate_properties(self._data_map, self._metadata_props) for prop in self._data_map: validate_any(prop, getattr(self, prop), self._data_structures.get(prop)) return self
Default validation for updated properties: MAY be overridden in children
entailment
def _search_regex(ops: dict, regex_pat: str): """ Search order: * specified regexps * operators sorted from longer to shorter """ custom_regexps = list(filter(None, [dic['regex'] for op, dic in ops.items() if 'regex' in dic])) op_names = [op for op, dic in ops.items() if 'regex' not in d...
Search order: * specified regexps * operators sorted from longer to shorter
entailment
def spec(self, postf_un_ops: str) -> list: """Return prefix unary operators list""" spec = [(l + op, {'pat': self.pat(pat), 'postf': self.postf(r, postf_un_ops), 'regex': None}) for op, pat in self.styles.items() for l, ...
Return prefix unary operators list
entailment
def spec(self) -> list: """Returns prefix unary operators list. Sets only one regex for all items in the dict.""" spec = [item for op, pat in self.ops.items() for item in [('{' + op, {'pat': pat, 'postf': self.postf, 'regex': None}), (...
Returns prefix unary operators list. Sets only one regex for all items in the dict.
entailment
def fill(self, postf_un_ops: str): """ Insert: * math styles * other styles * unary prefix operators without brackets * defaults """ for op, dic in self.ops.items(): if 'postf' not in dic: dic['postf'] = self.postf ...
Insert: * math styles * other styles * unary prefix operators without brackets * defaults
entailment
def one_symbol_ops_str(self) -> str: """Regex-escaped string with all one-symbol operators""" return re.escape(''.join((key for key in self.ops.keys() if len(key) == 1)))
Regex-escaped string with all one-symbol operators
entailment
def _su_scripts_regex(self): """ :return: [compiled regex, function] """ sups = re.escape(''.join([k for k in self.superscripts.keys()])) subs = re.escape(''.join([k for k in self.subscripts.keys()])) # language=PythonRegExp su_regex = (r'\\([{su_}])|([{sub}]...
:return: [compiled regex, function]
entailment
def _local_map(match, loc: str = 'lr') -> list: """ :param match: :param loc: str "l" or "r" or "lr" turns on/off left/right local area calculation :return: list list of the same size as the string + 2 it's the local map that counted { and ...
:param match: :param loc: str "l" or "r" or "lr" turns on/off left/right local area calculation :return: list list of the same size as the string + 2 it's the local map that counted { and } list can contain: None or int>=0 from the ...
entailment
def _operators_replace(self, string: str) -> str: """ Searches for first unary or binary operator (via self.op_regex that has only one group that contain operator) then replaces it (or escapes it if brackets do not match). Everything until: * space ' ' * begin...
Searches for first unary or binary operator (via self.op_regex that has only one group that contain operator) then replaces it (or escapes it if brackets do not match). Everything until: * space ' ' * begin/end of the string * bracket from outer scope (like '{a/b}':...
entailment
def replace(self, src: str) -> str: """ Extends LaTeX syntax via regex preprocess :param src: str LaTeX string :return: str New LaTeX string """ if not self.readied: self.ready() # Brackets + simple pre replacements: sr...
Extends LaTeX syntax via regex preprocess :param src: str LaTeX string :return: str New LaTeX string
entailment
def plot_gaps(plot, columns): """ plot % of gaps at each position """ from plot_window import window_plot_convolve as plot_window # plot_window([columns], len(columns)*.01, plot) plot_window([[100 - i for i in columns]], len(columns)*.01, plot)
plot % of gaps at each position
entailment
def strip_msa_100(msa, threshold, plot = False): """ strip out columns of a MSA that represent gaps for X percent (threshold) of sequences """ msa = [seq for seq in parse_fasta(msa)] columns = [[0, 0] for pos in msa[0][1]] # [[#bases, #gaps], [#bases, #gaps], ...] for seq in msa: for position, base in enumerate...
strip out columns of a MSA that represent gaps for X percent (threshold) of sequences
entailment
def sample_group(sid, groups): """ Iterate through all categories in an OrderedDict and return category name if SampleID present in that category. :type sid: str :param sid: SampleID from dataset. :type groups: OrderedDict :param groups: Returned dict from phylotoast.util.gather_categories...
Iterate through all categories in an OrderedDict and return category name if SampleID present in that category. :type sid: str :param sid: SampleID from dataset. :type groups: OrderedDict :param groups: Returned dict from phylotoast.util.gather_categories() function. :return type: str :re...
entailment
def combine_sets(*sets): """ Combine multiple sets to create a single larger set. """ combined = set() for s in sets: combined.update(s) return combined
Combine multiple sets to create a single larger set.
entailment
def unique_otuids(groups): """ Get unique OTUIDs of each category. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on category name and unique OTUIDs as values. """ uniques = {key: set() for key in groups} for i, group in...
Get unique OTUIDs of each category. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on category name and unique OTUIDs as values.
entailment
def shared_otuids(groups): """ Get shared OTUIDs between all unique combinations of groups. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on group combination and their shared OTUIDs as values. """ for g in sorted(groups): ...
Get shared OTUIDs between all unique combinations of groups. :type groups: Dict :param groups: {Category name: OTUIDs in category} :return type: dict :return: Dict keyed on group combination and their shared OTUIDs as values.
entailment
def write_uniques(path, prefix, uniques): """ Given a path, the method writes out one file for each group name in the uniques dictionary with the file name in the pattern PATH/prefix_group.txt with each file containing the unique OTUIDs found when comparing that group to all the other grou...
Given a path, the method writes out one file for each group name in the uniques dictionary with the file name in the pattern PATH/prefix_group.txt with each file containing the unique OTUIDs found when comparing that group to all the other groups in uniques. :type path: str :param path: O...
entailment
def storeFASTA(fastaFNH): """ Parse the records in a FASTA-format file by first reading the entire file into memory. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to resolve to a collection ...
Parse the records in a FASTA-format file by first reading the entire file into memory. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to resolve to a collection that can be iterated through, such as ...
entailment
def parseFASTA(fastaFNH): """ Parse the records in a FASTA-format file keeping the file open, and reading through one line at a time. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to res...
Parse the records in a FASTA-format file keeping the file open, and reading through one line at a time. :type source: path to FAST file or open file handle :param source: The data source from which to parse the FASTA records. Expects the input to resolve to a collection that can be itera...
entailment
def parse_map_file(mapFNH): """ Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID (default) or a user-supplied one. The only required fields are SampleID, BarcodeSequence, LinkerPrimerSequence (in that order), and Description (which must be the final field). :...
Opens a QIIME mapping file and stores the contents in a dictionary keyed on SampleID (default) or a user-supplied one. The only required fields are SampleID, BarcodeSequence, LinkerPrimerSequence (in that order), and Description (which must be the final field). :type mapFNH: str :param mapFNH: Eith...
entailment