Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def add_result(self, scan_id, result_type, host='', name='', value='', port='', test_id='', severity='', qod=''): assert scan_id assert len(name) or len(value) result = dict() result['type'] = result_type r...
[ " Add a result to a scan in the table. " ]
Please provide a description of the function:def set_progress(self, scan_id, progress): if progress > 0 and progress <= 100: self.scans_table[scan_id]['progress'] = progress if progress == 100: self.scans_table[scan_id]['end_time'] = int(time.time())
[ " Sets scan_id scan's progress. " ]
Please provide a description of the function:def set_target_progress(self, scan_id, target, host, progress): if progress > 0 and progress <= 100: targets = self.scans_table[scan_id]['target_progress'] targets[target][host] = progress # Set scan_info's target_progres...
[ " Sets scan_id scan's progress. " ]
Please provide a description of the function:def set_host_finished(self, scan_id, target, host): finished_hosts = self.scans_table[scan_id]['finished_hosts'] finished_hosts[target].extend(host) self.scans_table[scan_id]['finished_hosts'] = finished_hosts
[ " Add the host in a list of finished hosts " ]
Please provide a description of the function:def get_hosts_unfinished(self, scan_id): unfinished_hosts = list() for target in self.scans_table[scan_id]['finished_hosts']: unfinished_hosts.extend(target_str_to_list(target)) for target in self.scans_table[scan_id]['finished_h...
[ " Get a list of finished hosts." ]
Please provide a description of the function:def results_iterator(self, scan_id, pop_res): if pop_res: result_aux = self.scans_table[scan_id]['results'] self.scans_table[scan_id]['results'] = list() return iter(result_aux) return iter(self.scans_table[scan_i...
[ " Returns an iterator over scan_id scan's results. If pop_res is True,\n it removed the fetched results from the list.\n " ]
Please provide a description of the function:def del_results_for_stopped_hosts(self, scan_id): unfinished_hosts = self.get_hosts_unfinished(scan_id) for result in self.results_iterator(scan_id, False): if result['host'] in unfinished_hosts: self.remove_single_result(...
[ " Remove results from the result table for those host\n " ]
Please provide a description of the function:def resume_scan(self, scan_id, options): self.scans_table[scan_id]['status'] = ScanStatus.INIT if options: self.scans_table[scan_id]['options'] = options self.del_results_for_stopped_hosts(scan_id) return scan_id
[ " Reset the scan status in the scan_table to INIT.\n Also, overwrite the options, because a resume task cmd\n can add some new option. E.g. exclude hosts list.\n Parameters:\n scan_id (uuid): Scan ID to identify the scan process to be resumed.\n options (dict): Options for...
Please provide a description of the function:def create_scan(self, scan_id='', targets='', options=None, vts=''): if self.data_manager is None: self.data_manager = multiprocessing.Manager() # Check if it is possible to resume task. To avoid to resume, the # scan must be de...
[ " Creates a new scan with provided scan information. " ]
Please provide a description of the function:def set_option(self, scan_id, name, value): self.scans_table[scan_id]['options'][name] = value
[ " Set a scan_id scan's name option to value. " ]
Please provide a description of the function:def get_target_progress(self, scan_id, target): total_hosts = len(target_str_to_list(target)) host_progresses = self.scans_table[scan_id]['target_progress'].get(target) try: t_prog = sum(host_progresses.values()) / total_hosts ...
[ " Get a target's current progress value.\n The value is calculated with the progress of each single host\n in the target." ]
Please provide a description of the function:def get_target_list(self, scan_id): target_list = [] for target, _, _ in self.scans_table[scan_id]['targets']: target_list.append(target) return target_list
[ " Get a scan's target list. " ]
Please provide a description of the function:def get_ports(self, scan_id, target): if target: for item in self.scans_table[scan_id]['targets']: if target == item[0]: return item[1] return self.scans_table[scan_id]['targets'][0][1]
[ " Get a scan's ports list. If a target is specified\n it will return the corresponding port for it. If not,\n it returns the port item of the first nested list in\n the target's list.\n " ]
Please provide a description of the function:def get_credentials(self, scan_id, target): if target: for item in self.scans_table[scan_id]['targets']: if target == item[0]: return item[2]
[ " Get a scan's credential list. It return dictionary with\n the corresponding credential for a given target.\n " ]
Please provide a description of the function:def delete_scan(self, scan_id): if self.get_status(scan_id) == ScanStatus.RUNNING: return False self.scans_table.pop(scan_id) if len(self.scans_table) == 0: del self.data_manager self.data_manager = None ...
[ " Delete a scan if fully finished. " ]
Please provide a description of the function:def get_str(cls, result_type): if result_type == cls.ALARM: return "Alarm" elif result_type == cls.LOG: return "Log Message" elif result_type == cls.ERROR: return "Error Message" elif result_type ==...
[ " Return string name of a result type. " ]
Please provide a description of the function:def get_type(cls, result_name): if result_name == "Alarm": return cls.ALARM elif result_name == "Log Message": return cls.LOG elif result_name == "Error Message": return cls.ERROR elif result_name =...
[ " Return string name of a result type. " ]
Please provide a description of the function:def is_float(obj): is_f = isinstance(obj, float) if not is_f: try: float(obj) is_f = True except (ValueError, TypeError): is_f = False return is_f and not is_bool(obj)
[ "\n Valid types are:\n - objects of float type\n - Strings that can be converted to float. For example '1e-06'\n " ]
Please provide a description of the function:def is_timestamp(obj): return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj)
[ "\n Yaml either have automatically converted it to a datetime object\n or it is a string that will be validated later.\n " ]
Please provide a description of the function:def init_logging(log_level): log_level = log_level_to_string_map[min(log_level, 5)] msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if log_level in os.environ else "%(levelname)s - %(message)s" logging_conf = { "version": 1, "root...
[ "\n Init logging settings with default set to INFO\n " ]
Please provide a description of the function:def keywords(self): defined_keywords = [ ('allowempty_map', 'allowempty_map'), ('assertion', 'assertion'), ('default', 'default'), ('class', 'class'), ('desc', 'desc'), ('enum', 'enum'),...
[ "\n Returns a list of all keywords that this rule object has defined.\n A keyword is considered defined if the value it returns != None.\n " ]
Please provide a description of the function:def check_type_keywords(self, schema, rule, path): if not self.strict_rule_validation: return global_keywords = ['type', 'desc', 'example', 'extensions', 'name', 'nullable', 'version', 'func', 'include'] all_allowed_keywords = { ...
[ "\n All supported keywords:\n - allowempty_map\n - assertion\n - class\n - date\n - default\n - desc\n - enum\n - example\n - extensions\n - func\n - ident\n - include_name\n - map_regex_rule\n - m...
Please provide a description of the function:def _load_extensions(self): log.debug(u"loading all extensions : %s", self.extensions) self.loaded_extensions = [] for f in self.extensions: if not os.path.isabs(f): f = os.path.abspath(f) if not os....
[ "\n Load all extension files into the namespace pykwalify.ext\n " ]
Please provide a description of the function:def _handle_func(self, value, rule, path, done=None): func = rule.func # func keyword is not defined so nothing to do if not func: return found_method = False for extension in self.loaded_extensions: ...
[ "\n Helper function that should check if func is specified for this rule and\n then handle it for all cases in a generic way.\n " ]
Please provide a description of the function:def _validate_range(self, max_, min_, max_ex, min_ex, value, path, prefix): if not isinstance(value, int) and not isinstance(value, float): raise CoreError("Value must be a integer type") log.debug( u"Validate range : %s : %s...
[ "\n Validate that value is within range values.\n " ]
Please provide a description of the function:def parse_cli(): # # 1. parse cli arguments # __docopt__ = # Import pykwalify package import pykwalify args = docopt(__docopt__, version=pykwalify.__version__) pykwalify.init_logging(1 if args["--quiet"] else args["--verbose"]) ...
[ "\n The outline of this function needs to be like this:\n\n 1. parse arguments\n 2. validate arguments only, dont go into other logic/code\n 3. run application logic\n ", "\nusage: pykwalify -d FILE -s FILE ... [-e FILE ...]\n [--strict-rule-validation] [--fix-ruby-style-regex] [--allow-asser...
Please provide a description of the function:def run(cli_args): from .core import Core c = Core( source_file=cli_args["--data-file"], schema_files=cli_args["--schema-file"], extensions=cli_args['--extension'], strict_rule_validation=cli_args['--strict-rule-validation'], ...
[ "\n Split the functionality into 2 methods.\n\n One for parsing the cli and one that runs the application.\n " ]
Please provide a description of the function:def pbdesign(n): assert n>0, 'Number of factors must be a positive integer' keep = int(n) n = 4*(int(n/4) + 1) # calculate the correct number of rows (multiple of 4) f, e = np.frexp([n, n/12., n/20.]) k = [idx for idx, val in enumerate(np.logi...
[ "\r\n Generate a Plackett-Burman design\r\n \r\n Parameter\r\n ---------\r\n n : int\r\n The number of factors to create a matrix for.\r\n \r\n Returns\r\n -------\r\n H : 2d-array\r\n An orthogonal design matrix with n columns, one for each factor, and\r\n the number...
Please provide a description of the function:def star(n, alpha='faced', center=(1, 1)): # Star points at the center of each face of the factorial if alpha=='faced': a = 1 elif alpha=='orthogonal': nc = 2**n # factorial points nco = center[0] # center points to factorial...
[ "\r\n Create the star points of various design matrices\r\n \r\n Parameters\r\n ----------\r\n n : int\r\n The number of variables in the design\r\n \r\n Optional\r\n --------\r\n alpha : str\r\n Available values are 'faced' (default), 'orthogonal', or 'rotatable'\r\n cen...
Please provide a description of the function:def fold(H, columns=None): H = np.array(H) assert len(H.shape)==2, 'Input design matrix must be 2d.' if columns is None: columns = range(H.shape[1]) Hf = H.copy() for col in columns: vals = np.unique(H[:, col...
[ "\r\n Fold a design to reduce confounding effects.\r\n \r\n Parameters\r\n ----------\r\n H : 2d-array\r\n The design matrix to be folded.\r\n columns : array\r\n Indices of of columns to fold (Default: None). If ``columns=None`` is\r\n used, then all columns will be folded.\r...
Please provide a description of the function:def build_regression_matrix(H, model, build=None): ListOfTokens = model.split(' ') if H.shape[1]==1: size_index = len(str(H.shape[0])) else: size_index = len(str(H.shape[1])) if build is None: build = [True]*len(List...
[ "\r\n Build a regression matrix using a DOE matrix and a list of monomials.\r\n \r\n Parameters\r\n ----------\r\n H : 2d-array\r\n model : str\r\n build : bool-array\r\n \r\n Returns\r\n -------\r\n R : 2d-array\r\n \r\n " ]
Please provide a description of the function:def to_bedtool(iterator): def gen(): for i in iterator: yield helpers.asinterval(i) return pybedtools.BedTool(gen())
[ "\n Convert any iterator into a pybedtools.BedTool object.\n\n Note that the supplied iterator is not consumed by this function. To save\n to a temp file or to a known location, use the `.saveas()` method of the\n returned BedTool object.\n " ]
Please provide a description of the function:def tsses(db, merge_overlapping=False, attrs=None, attrs_sep=":", merge_kwargs=None, as_bed6=False, bedtools_227_or_later=True): _override = os.environ.get('GFFUTILS_USES_BEDTOOLS_227_OR_LATER', None) if _override is not None: if _override == '...
[ "\n Create 1-bp transcription start sites for all transcripts in the database\n and return as a sorted pybedtools.BedTool object pointing to a temporary\n file.\n\n To save the file to a known location, use the `.moveto()` method on the\n resulting `pybedtools.BedTool` object.\n\n To extend region...
Please provide a description of the function:def write_gene_recs(self, db, gene_id): gene_rec = db[gene_id] # Output gene record self.write_rec(gene_rec) # Get each mRNA's lengths mRNA_lens = {} c = list(db.children(gene_id, featuretype="mRNA")) for mRNA ...
[ "\n NOTE: The goal of this function is to have a canonical ordering when\n outputting a gene and all of its records to a file. The order is\n intended to be:\n\n gene\n # mRNAs sorted by length, with longest mRNA first\n mRNA_1\n # Exons of mRNA, sorted by s...
Please provide a description of the function:def write_mRNA_children(self, db, mRNA_id): mRNA_children = db.children(mRNA_id, order_by='start') nonexonic_children = [] for child_rec in mRNA_children: if child_rec.featuretype == "exon": self.write_rec(child_re...
[ "\n Write out the children records of the mRNA given by the ID\n (not including the mRNA record itself) in a canonical\n order, where exons are sorted by start position and given\n first.\n " ]
Please provide a description of the function:def write_exon_children(self, db, exon_id): exon_children = db.children(exon_id, order_by='start') for exon_child in exon_children: self.write_rec(exon_child)
[ "\n Write out the children records of the exon given by\n the ID (not including the exon record itself).\n " ]
Please provide a description of the function:def close(self): self.out_stream.close() # If we're asked to write in place, substitute the named # temporary file for the current file if self.in_place: shutil.move(self.temp_file.name, self.out)
[ "\n Close the stream. Assumes stream has 'close' method.\n " ]
Please provide a description of the function:def var_regression_matrix(H, x, model, sigma=1): x = np.atleast_2d(x) H = np.atleast_2d(H) if x.shape[0]==1: x = x.T if np.rank(H)<(np.dot(H.T, H)).shape[0]: raise ValueError("model and DOE don't suit together") ...
[ "\r\n Compute the variance of the 'regression error'.\r\n \r\n Parameters\r\n ----------\r\n H : 2d-array\r\n The regression matrix\r\n x : 2d-array\r\n The coordinates to calculate the regression error variance at.\r\n model : str\r\n A string of tokens that define the reg...
Please provide a description of the function:def to_seqfeature(feature): if isinstance(feature, six.string_types): feature = feature_from_line(feature) qualifiers = { 'source': [feature.source], 'score': [feature.score], 'seqid': [feature.seqid], 'frame': [feature.f...
[ "\n Converts a gffutils.Feature object to a Bio.SeqFeature object.\n\n The GFF fields `source`, `score`, `seqid`, and `frame` are stored as\n qualifiers. GFF `attributes` are also stored as qualifiers.\n\n Parameters\n ----------\n feature : Feature object, or string\n If string, assume it...
Please provide a description of the function:def from_seqfeature(s, **kwargs): source = s.qualifiers.get('source', '.')[0] score = s.qualifiers.get('score', '.')[0] seqid = s.qualifiers.get('seqid', '.')[0] frame = s.qualifiers.get('frame', '.')[0] strand = _feature_strand[s.strand] # BioP...
[ "\n Converts a Bio.SeqFeature object to a gffutils.Feature object.\n\n The GFF fields `source`, `score`, `seqid`, and `frame` are assumed to be\n stored as qualifiers. Any other qualifiers will be assumed to be GFF\n attributes.\n " ]
Please provide a description of the function:def set_pragmas(self, pragmas): self.pragmas = pragmas c = self.conn.cursor() c.executescript( ';\n'.join( ['PRAGMA %s=%s' % i for i in self.pragmas.items()] ) ) self.conn.commit()
[ "\n Set pragmas for the current database connection.\n\n Parameters\n ----------\n pragmas : dict\n Dictionary of pragmas; see constants.default_pragmas for a template\n and http://www.sqlite.org/pragma.html for a full list.\n " ]
Please provide a description of the function:def _feature_returner(self, **kwargs): kwargs.setdefault('dialect', self.dialect) kwargs.setdefault('keep_order', self.keep_order) kwargs.setdefault('sort_attribute_values', self.sort_attribute_values) return Feature(**kwargs)
[ "\n Returns a feature, adding additional database-specific defaults\n " ]
Please provide a description of the function:def schema(self): c = self.conn.cursor() c.execute( ''' SELECT sql FROM sqlite_master ''') results = [] for i, in c: if i is not None: results.append(i) return '\...
[ "\n Returns the database schema as a string.\n " ]
Please provide a description of the function:def count_features_of_type(self, featuretype=None): c = self.conn.cursor() if featuretype is not None: c.execute( ''' SELECT count() FROM features WHERE featuretype = ? ''', ...
[ "\n Simple count of features.\n\n Can be faster than \"grep\", and is faster than checking the length of\n results from :meth:`gffutils.FeatureDB.features_of_type`.\n\n Parameters\n ----------\n\n featuretype : string\n\n Feature type (e.g., \"gene\") to count. ...
Please provide a description of the function:def features_of_type(self, featuretype, limit=None, strand=None, order_by=None, reverse=False, completely_within=False): query, args = helpers.make_query( args=[], limit=limit, ...
[ "\n Returns an iterator of :class:`gffutils.Feature` objects.\n\n Parameters\n ----------\n {_method_doc}\n " ]
Please provide a description of the function:def iter_by_parent_childs(self, featuretype="gene", level=None, order_by=None, reverse=False, completely_within=False): # Get all the parent records of the requested feature type parent_recs...
[ "\n For each parent of type `featuretype`, yield a list L of that parent\n and all of its children (`[parent] + list(children)`). The parent will\n always be L[0].\n\n This is useful for \"sanitizing\" a GFF file for downstream tools.\n\n Additional kwargs are passed to :meth:`Fea...
Please provide a description of the function:def featuretypes(self): c = self.conn.cursor() c.execute( ''' SELECT DISTINCT featuretype from features ''') for i, in c: yield i
[ "\n Iterate over feature types found in the database.\n\n Returns\n -------\n A generator object that yields featuretypes (as strings)\n " ]
Please provide a description of the function:def _relation(self, id, join_on, join_to, level=None, featuretype=None, order_by=None, reverse=False, completely_within=False, limit=None): # The following docstring will be included in the parents() and # children() docst...
[ "\n Parameters\n ----------\n\n id : string or a Feature object\n\n level : None or int\n\n If `level=None` (default), then return all children regardless\n of level. If `level` is an integer, then constrain to just that\n level.\n {_method_doc}\n...
Please provide a description of the function:def parents(self, id, level=None, featuretype=None, order_by=None, reverse=False, completely_within=False, limit=None): return self._relation( id, join_on='parent', join_to='child', level=level, featuretype=featuretype...
[ "\n Return parents of feature `id`.\n {_relation_docstring}\n " ]
Please provide a description of the function:def execute(self, query): c = self.conn.cursor() return c.execute(query)
[ "\n Execute arbitrary queries on the db.\n\n .. seealso::\n\n :class:`FeatureDB.schema` may be helpful when writing your own\n queries.\n\n Parameters\n ----------\n\n query : str\n\n Query to execute -- trailing \";\" optional.\n\n ...
Please provide a description of the function:def region(self, region=None, seqid=None, start=None, end=None, strand=None, featuretype=None, completely_within=False): # Argument handling. if region is not None: if (seqid is not None) or (start is not None) or (end is n...
[ "\n Return features within specified genomic coordinates.\n\n Specifying genomic coordinates can be done in a flexible manner\n\n Parameters\n ----------\n region : string, tuple, or Feature instance\n If string, then of the form \"seqid:start-end\". If tuple, then\n ...
Please provide a description of the function:def interfeatures(self, features, new_featuretype=None, merge_attributes=True, dialect=None, attribute_func=None, update_attributes=None): for i, f in enumerate(features): # no inter-feature for the fir...
[ "\n Construct new features representing the space between features.\n\n For example, if `features` is a list of exons, then this method will\n return the introns. If `features` is a list of genes, then this method\n will return the intergenic regions.\n\n Providing N features wil...
Please provide a description of the function:def delete(self, features, make_backup=True, **kwargs): if make_backup: if isinstance(self.dbfn, six.string_types): shutil.copy2(self.dbfn, self.dbfn + '.bak') c = self.conn.cursor() query1 = query2 = ...
[ "\n Delete features from database.\n\n features : str, iterable, FeatureDB instance\n If FeatureDB, all features will be used. If string, assume it's the\n ID of the feature to remove. Otherwise, assume it's an iterable of\n Feature objects. The classes in gffutils.ite...
Please provide a description of the function:def update(self, data, make_backup=True, **kwargs): from gffutils import create from gffutils import iterators if make_backup: if isinstance(self.dbfn, six.string_types): shutil.copy2(self.dbfn, self.dbfn + '.bak')...
[ "\n Update database with features in `data`.\n\n data : str, iterable, FeatureDB instance\n If FeatureDB, all data will be used. If string, assume it's\n a filename of a GFF or GTF file. Otherwise, assume it's an\n iterable of Feature objects. The classes in gffutils...
Please provide a description of the function:def add_relation(self, parent, child, level, parent_func=None, child_func=None): if isinstance(parent, six.string_types): parent = self[parent] if isinstance(child, six.string_types): child = self[child] ...
[ "\n Manually add relations to the database.\n\n Parameters\n ----------\n parent : str or Feature instance\n Parent feature to add.\n\n child : str or Feature instance\n Child feature to add\n\n level : int\n Level of the relation. For exa...
Please provide a description of the function:def _insert(self, feature, cursor): try: cursor.execute(constants._INSERT, feature.astuple()) except sqlite3.ProgrammingError: cursor.execute( constants._INSERT, feature.astuple(self.default_encoding))
[ "\n Insert a feature into the database.\n " ]
Please provide a description of the function:def create_introns(self, exon_featuretype='exon', grandparent_featuretype='gene', parent_featuretype=None, new_featuretype='intron', merge_attributes=True): if (grandparent_featuretype and parent_featuretype) or ...
[ "\n Create introns from existing annotations.\n\n\n Parameters\n ----------\n exon_featuretype : string\n Feature type to use in order to infer introns. Typically `\"exon\"`.\n\n grandparent_featuretype : string\n If `grandparent_featuretype` is not None, th...
Please provide a description of the function:def merge(self, features, ignore_strand=False): # Consume iterator up front... features = list(features) if len(features) == 0: raise StopIteration # Either set all strands to '+' or check for strand-consistency. ...
[ "\n Merge overlapping features together.\n\n Parameters\n ----------\n\n features : iterator of Feature instances\n\n ignore_strand : bool\n If True, features on multiple strands will be merged, and the final\n strand will be set to '.'. Otherwise, ValueErro...
Please provide a description of the function:def children_bp(self, feature, child_featuretype='exon', merge=False, ignore_strand=False): children = self.children(feature, featuretype=child_featuretype, order_by='start') if merge: ...
[ "\n Total bp of all children of a featuretype.\n\n Useful for getting the exonic bp of an mRNA.\n\n Parameters\n ----------\n\n feature : str or Feature instance\n\n child_featuretype : str\n Which featuretype to consider. For example, to get exonic bp of an\n ...
Please provide a description of the function:def bed12(self, feature, block_featuretype=['exon'], thick_featuretype=['CDS'], thin_featuretype=None, name_field='ID', color=None): if thick_featuretype and thin_featuretype: raise ValueError("Can only specify one of ...
[ "\n Converts `feature` into a BED12 format.\n\n GFF and GTF files do not necessarily define genes consistently, so this\n method provides flexiblity in specifying what to call a \"transcript\".\n\n Parameters\n ----------\n feature : str or Feature instance\n In ...
Please provide a description of the function:def DataIterator(data, checklines=10, transform=None, force_dialect_check=False, from_string=False, **kwargs): _kwargs = dict(data=data, checklines=checklines, transform=transform, force_dialect_check=force_dialect_check, **kwarg...
[ "\n Iterate over features, no matter how they are provided.\n\n Parameters\n ----------\n data : str, iterable of Feature objs, FeatureDB\n `data` can be a string (filename, URL, or contents of a file, if\n from_string=True), any arbitrary iterable of features, or a FeatureDB\n (in ...
Please provide a description of the function:def bbdesign(n, center=None): assert n>=3, 'Number of variables must be at least 3' # First, compute a factorial DOE with 2 parameters H_fact = ff2n(2) # Now we populate the real DOE with this DOE # We made a factorial design on eac...
[ "\r\n Create a Box-Behnken design\r\n \r\n Parameters\r\n ----------\r\n n : int\r\n The number of factors in the design\r\n \r\n Optional\r\n --------\r\n center : int\r\n The number of center points to include (default = 1).\r\n \r\n Returns\r\n -------\r\n mat...
Please provide a description of the function:def inspect(data, look_for=['featuretype', 'chrom', 'attribute_keys', 'feature_count'], limit=None, verbose=True): results = {} obj_attrs = [] for i in look_for: if i not in ['attribute_keys', 'feature_count']: ...
[ "\n Inspect a GFF or GTF data source.\n\n This function is useful for figuring out the different featuretypes found\n in a file (for potential removal before creating a FeatureDB).\n\n Returns a dictionary with a key for each item in `look_for` and\n a corresponding value that is a dictionary of how ...
Please provide a description of the function:def fullfact(levels): n = len(levels) # number of factors nb_lines = np.prod(levels) # number of trial conditions H = np.zeros((nb_lines, n)) level_repeat = 1 range_repeat = np.prod(levels) for i in range(n): range_repeat ...
[ "\r\n Create a general full-factorial design\r\n \r\n Parameters\r\n ----------\r\n levels : array-like\r\n An array of integers that indicate the number of levels of each input\r\n design factor.\r\n \r\n Returns\r\n -------\r\n mat : 2d-array\r\n The design matrix w...
Please provide a description of the function:def fracfact(gen): # Recognize letters and combinations A = [item for item in re.split('\-?\s?\+?', gen) if item] # remove empty strings C = [len(item) for item in A] # Indices of single letters (main factors) I = [i for i, item in enume...
[ "\r\n Create a 2-level fractional-factorial design with a generator string.\r\n \r\n Parameters\r\n ----------\r\n gen : str\r\n A string, consisting of lowercase, uppercase letters or operators \"-\"\r\n and \"+\", indicating the factors of the experiment\r\n \r\n Returns\r\n ...
Please provide a description of the function:def lhs(n, samples=None, criterion=None, iterations=None): H = None if samples is None: samples = n if criterion is not None: assert criterion.lower() in ('center', 'c', 'maximin', 'm', 'centermaximin', 'cm', '...
[ "\r\n Generate a latin-hypercube design\r\n \r\n Parameters\r\n ----------\r\n n : int\r\n The number of factors to generate samples for\r\n \r\n Optional\r\n --------\r\n samples : int\r\n The number of samples to generate for each factor (Default: n)\r\n criterion : str...
Please provide a description of the function:def _pdist(x): x = np.atleast_2d(x) assert len(x.shape)==2, 'Input array must be 2d-dimensional' m, n = x.shape if m<2: return [] d = [] for i in range(m - 1): for j in range(i + 1, m): d.ap...
[ "\r\n Calculate the pair-wise point distances of a matrix\r\n \r\n Parameters\r\n ----------\r\n x : 2d-array\r\n An m-by-n array of scalars, where there are m points in n dimensions.\r\n \r\n Returns\r\n -------\r\n d : array\r\n A 1-by-b array of scalars, where b = m*(m - ...
Please provide a description of the function:def clean_gff(gff, cleaned, add_chr=False, chroms_to_ignore=None, featuretypes_to_ignore=None): logger.info("Cleaning GFF") chroms_to_ignore = chroms_to_ignore or [] featuretypes_to_ignore = featuretypes_to_ignore or [] with open(cleaned, '...
[ "\n Cleans a GFF file by removing features on unwanted chromosomes and of\n unwanted featuretypes. Optionally adds \"chr\" to chrom names.\n " ]
Please provide a description of the function:def ccdesign(n, center=(4, 4), alpha='orthogonal', face='circumscribed'): # Check inputs assert isinstance(n, int) and n>1, '"n" must be an integer greater than 1.' assert alpha.lower() in ('orthogonal', 'o', 'rotatable', 'r'), 'Invalid value f...
[ "\r\n Central composite design\r\n \r\n Parameters\r\n ----------\r\n n : int\r\n The number of factors in the design.\r\n \r\n Optional\r\n --------\r\n center : int array\r\n A 1-by-2 array of integers, the number of center points in each block\r\n of the design. (D...
Please provide a description of the function:def feature_from_line(line, dialect=None, strict=True, keep_order=False): if not strict: lines = line.splitlines(False) _lines = [] for i in lines: i = i.strip() if len(i) > 0: _lines.append(i) ...
[ "\n Given a line from a GFF file, return a Feature object\n\n Parameters\n ----------\n line : string\n\n strict : bool\n If True (default), assume `line` is a single, tab-delimited string that\n has at least 9 fields.\n\n If False, then the input can have a more flexible format,...
Please provide a description of the function:def calc_bin(self, _bin=None): if _bin is None: try: _bin = bins.bins(self.start, self.end, one=True) except TypeError: _bin = None return _bin
[ "\n Calculate the smallest UCSC genomic bin that will contain this feature.\n " ]
Please provide a description of the function:def astuple(self, encoding=None): if not encoding: return ( self.id, self.seqid, self.source, self.featuretype, self.start, self.end, self.score, self.strand, self.frame, helpers._jsonify(self.attri...
[ "\n Return a tuple suitable for import into a database.\n\n Attributes field and extra field jsonified into strings. The order of\n fields is such that they can be supplied as arguments for the query\n defined in :attr:`gffutils.constants._INSERT`.\n\n If `encoding` is not None, t...
Please provide a description of the function:def sequence(self, fasta, use_strand=True): if isinstance(fasta, six.string_types): fasta = Fasta(fasta, as_raw=False) # recall GTF/GFF is 1-based closed; pyfaidx uses Python slice notation # and is therefore 0-based half-open. ...
[ "\n Retrieves the sequence of this feature as a string.\n\n Uses the pyfaidx package.\n\n Parameters\n ----------\n\n fasta : str\n If str, then it's a FASTA-format filename; otherwise assume it's\n a pyfaidx.Fasta object.\n\n use_strand : bool\n ...
Please provide a description of the function:def to_bed12(f, db, child_type='exon', name_field='ID'): if isinstance(f, six.string_types): f = db[f] children = list(db.children(f, featuretype=child_type, order_by='start')) sizes = [len(i) for i in children] starts = [i.start - f.start for i ...
[ "\n Given a top-level feature (e.g., transcript), construct a BED12 entry\n Parameters\n ----------\n f : Feature object or string\n This is the top-level feature represented by one BED12 line. For\n a canonical GFF or GTF, this will generally be a transcript.\n db : a FeatureDB object...
Please provide a description of the function:def infer_dialect(attributes): if isinstance(attributes, six.string_types): attributes = [attributes] dialects = [parser._split_keyvals(i)[1] for i in attributes] return _choose_dialect(dialects)
[ "\n Infer the dialect based on the attributes.\n\n Parameters\n ----------\n attributes : str or iterable\n A single attributes string from a GTF or GFF line, or an iterable of\n such strings.\n\n Returns\n -------\n Dictionary representing the inferred dialect\n " ]
Please provide a description of the function:def _choose_dialect(dialects): # NOTE: can use helpers.dialect_compare if you need to make this more # complex.... # For now, this function favors the first dialect, and then appends the # order of additional fields seen in the attributes of other lines...
[ "\n Given a list of dialects, choose the one to use as the \"canonical\" version.\n\n If `dialects` is an empty list, then use the default GFF3 dialect\n\n Parameters\n ----------\n dialects : iterable\n iterable of dialect dictionaries\n\n Returns\n -------\n dict\n " ]
Please provide a description of the function:def make_query(args, other=None, limit=None, strand=None, featuretype=None, extra=None, order_by=None, reverse=False, completely_within=False): _QUERY = ("{_SELECT} {OTHER} {EXTRA} {FEATURETYPE} " "{LIMIT} {STRAND} {ORDER...
[ "\n Multi-purpose, bare-bones ORM function.\n\n This function composes queries given some commonly-used kwargs that can be\n passed to FeatureDB methods (like .parents(), .children(), .all_features(),\n .features_of_type()). It handles, in one place, things like restricting to\n featuretype, limitin...
Please provide a description of the function:def _bin_from_dict(d): try: start = int(d['start']) end = int(d['end']) return bins.bins(start, end, one=True) # e.g., if "." except ValueError: return None
[ "\n Given a dictionary yielded by the parser, return the genomic \"UCSC\" bin\n " ]
Please provide a description of the function:def _jsonify(x): if isinstance(x, dict_class): return json.dumps(x._d, separators=(',', ':')) return json.dumps(x, separators=(',', ':'))
[ "Use most compact form of JSON" ]
Please provide a description of the function:def _unjsonify(x, isattributes=False): if isattributes: obj = json.loads(x) return dict_class(obj) return json.loads(x)
[ "Convert JSON string to an ordered defaultdict." ]
Please provide a description of the function:def _feature_to_fields(f, jsonify=True): x = [] for k in constants._keys: v = getattr(f, k) if jsonify and (k in ('attributes', 'extra')): x.append(_jsonify(v)) else: x.append(v) return tuple(x)
[ "\n Convert feature to tuple, for faster sqlite3 import\n " ]
Please provide a description of the function:def _dict_to_fields(d, jsonify=True): x = [] for k in constants._keys: v = d[k] if jsonify and (k in ('attributes', 'extra')): x.append(_jsonify(v)) else: x.append(v) return tuple(x)
[ "\n Convert dict to tuple, for faster sqlite3 import\n " ]
Please provide a description of the function:def merge_attributes(attr1, attr2): new_d = copy.deepcopy(attr1) new_d.update(attr2) #all of attr2 key : values just overwrote attr1, fix it for k, v in new_d.items(): if not isinstance(v, list): new_d[k] = [v] for k, v in six....
[ "\n Merges two attribute dictionaries into a single dictionary.\n\n Parameters\n ----------\n `attr1`, `attr2` : dict\n\n Returns\n -------\n dict\n " ]
Please provide a description of the function:def dialect_compare(dialect1, dialect2): orig = set(dialect1.items()) new = set(dialect2.items()) return dict( added=dict(list(new.difference(orig))), removed=dict(list(orig.difference(new))) )
[ "\n Compares two dialects.\n " ]
Please provide a description of the function:def sanitize_gff_db(db, gid_field="gid"): def sanitized_iterator(): # Iterate through the database by each gene's records for gene_recs in db.iter_by_parent_childs(): # The gene's ID gene_id = gene_recs[0].id for r...
[ "\n Sanitize given GFF db. Returns a sanitized GFF db.\n\n Sanitizing means:\n\n - Ensuring that start < stop for all features\n - Standardizing gene units by adding a 'gid' attribute\n that makes the file grep-able\n\n TODO: Do something with negative coordinates?\n " ]
Please provide a description of the function:def sanitize_gff_file(gff_fname, in_memory=True, in_place=False): db = None if is_gff_db(gff_fname): # It's a database filename, so load it db = gffutils.FeatureDB(gff_fname) else: # Need to...
[ "\n Sanitize a GFF file.\n " ]
Please provide a description of the function:def is_gff_db(db_fname): if not os.path.isfile(db_fname): return False if db_fname.endswith(".db"): return True return False
[ "\n Return True if the given filename is a GFF database.\n\n For now, rely on .db extension.\n " ]
Please provide a description of the function:def get_gff_db(gff_fname, ext=".db"): if not os.path.isfile(gff_fname): # Not sure how we should deal with errors normally in # gffutils -- Ryan? raise ValueError("GFF %s does not exist." % (gff_fname)) candidate_db_fname =...
[ "\n Get db for GFF file. If the database has a .db file,\n load that. Otherwise, create a named temporary file,\n serialize the db to that, and return the loaded database.\n " ]
Please provide a description of the function:def bins(start, stop, fmt='gff', one=True): # For very large coordinates, return 1 which is "somewhere on the # chromosome". if start >= MAX_CHROM_SIZE or stop >= MAX_CHROM_SIZE: if one: return 1 else: return set([1])...
[ "\n Uses the definition of a \"genomic bin\" described in Fig 7 of\n http://genome.cshlp.org/content/12/6/996.abstract.\n\n Parameters\n ----------\n one : boolean\n If `one=True` (default), then only return the smallest bin that\n completely contains these coordinates (useful for assig...
Please provide a description of the function:def print_bin_sizes(): for i, offset in enumerate(OFFSETS): binstart = offset try: binstop = OFFSETS[i + 1] except IndexError: binstop = binstart bin_size = 2 ** (FIRST_SHIFT + (i * NEXT_SHIFT)) actual...
[ "\n Useful for debugging: how large is each bin, and what are the bin IDs?\n " ]
Please provide a description of the function:def _reconstruct(keyvals, dialect, keep_order=False, sort_attribute_values=False): if not dialect: raise AttributeStringError() if not keyvals: return "" parts = [] # Re-encode when reconstructing attributes if const...
[ "\n Reconstructs the original attributes string according to the dialect.\n\n Parameters\n ==========\n keyvals : dict\n Attributes from a GFF/GTF feature\n\n dialect : dict\n Dialect containing info on how to reconstruct a string version of the\n attributes\n\n keep_order : b...
Please provide a description of the function:def _split_keyvals(keyval_str, dialect=None): def _unquote_quals(quals, dialect): if not constants.ignore_url_escape_characters and dialect['fmt'] == 'gff3': for key, vals in quals.items(): unquoted = [urllib.parse.unquo...
[ "\n Given the string attributes field of a GFF-like line, split it into an\n attributes dictionary and a \"dialect\" dictionary which contains information\n needed to reconstruct the original string.\n\n Lots of logic here to handle all the corner cases.\n\n If `dialect` is None, then do all the logi...
Please provide a description of the function:def create_db(data, dbfn, id_spec=None, force=False, verbose=False, checklines=10, merge_strategy='error', transform=None, gtf_transcript_key='transcript_id', gtf_gene_key='gene_id', gtf_subfeature='exon', force_gff=False, ...
[ "\n Create a database from a GFF or GTF file.\n\n For more details on when and how to use the kwargs below, see the examples\n in the online documentation (:ref:`examples`).\n\n Parameters\n ----------\n data : string or iterable\n\n If a string (and `from_string` is False), then `data` is ...
Please provide a description of the function:def _id_handler(self, f): # If id_spec is a string, convert to iterable for later if isinstance(self.id_spec, six.string_types): id_key = [self.id_spec] elif hasattr(self.id_spec, '__call__'): id_key = [self.id_spec]...
[ "\n Given a Feature from self.iterator, figure out what the ID should be.\n\n This uses `self.id_spec` identify the ID.\n " ]
Please provide a description of the function:def _do_merge(self, f, merge_strategy, add_duplicate=False): if merge_strategy == 'error': raise ValueError("Duplicate ID {0.id}".format(f)) if merge_strategy == 'warning': logger.warning( "Duplicate lines in ...
[ "\n Different merge strategies upon name conflicts.\n\n \"error\":\n Raise error\n\n \"warning\"\n Log a warning\n\n \"merge\":\n Combine old and new attributes -- but only if everything else\n matches; otherwise error. This can be slow, but i...
Please provide a description of the function:def _add_duplicate(self, idspecid, newid): c = self.conn.cursor() try: c.execute( ''' INSERT INTO duplicates (idspecid, newid) VALUES (?, ?)''', (idspecid, ne...
[ "\n Adds a duplicate ID (as identified by id_spec) and its new ID to the\n duplicates table so that they can be later searched for merging.\n\n Parameters\n ----------\n newid : str\n The primary key used in the features table\n\n idspecid : str\n The ...
Please provide a description of the function:def _candidate_merges(self, f): candidates = [self._get_feature(f.id)] c = self.conn.cursor() results = c.execute( constants._SELECT + ''' JOIN duplicates ON duplicates.newid = features.id WHERE duplicates....
[ "\n Identifies those features that originally had the same ID as `f`\n (according to the id_spec), but were modified because of duplicate\n IDs.\n " ]
Please provide a description of the function:def _init_tables(self): c = self.conn.cursor() v = sqlite3.sqlite_version_info self.set_pragmas(self.pragmas) c.executescript(constants.SCHEMA) self.conn.commit()
[ "\n Table creation\n " ]
Please provide a description of the function:def _finalize(self): c = self.conn.cursor() directives = self.directives + self.iterator.directives c.executemany(''' INSERT INTO directives VALUES (?) ''', ((i,) for i in directives)) c.exe...
[ "\n Various last-minute stuff to perform after file has been parsed and\n imported.\n\n In general, if you'll be adding stuff to the meta table, do it here.\n " ]
Please provide a description of the function:def create(self): # Calls each of these methods in order. _populate_from_lines and # _update_relations must be implemented in subclasses. self._init_tables() self._populate_from_lines(self.iterator) self._update_relations() ...
[ "\n Calls various methods sequentially in order to fully build the\n database.\n " ]