code
stringlengths
1
18.2k
def delayed_close(self): """ Delayed close - won't close immediately, but on the next reactor loop. """ self.state = SESSION_STATE.CLOSING reactor.callLater(0, self.close)
def is_closed(self): """ Check if session was closed. """ return (self.state == SESSION_STATE.CLOSED or self.state == SESSION_STATE.CLOSING)
def _random_key(self): """ Return random session key """ hashstr = '%s%s' % (random.random(), self.time_module.time()) return hashlib.md5(hashstr).hexdigest()
def promote(self): """ Mark object as alive, so it won't be collected during next run of the garbage collector. """ if self.expiry is not None: self.promoted = self.time_module.time() + self.expiry
def set_handler(self, handler, start_heartbeat=True): """ Set active handler for the session @param handler: Associate active cyclone handler with the session @param start_heartbeat: Should session start heartbeat immediately """ # Check if session already has associated handler if self.handler is not None: handler.sen...
def verify_state(self): """ Verify if session was not yet opened. If it is, open it and call connections C{connectionMade} """ # If we're in CONNECTING state - send 'o' message to the client if self.state == SESSION_STATE.CONNECTING: self.handler.send_pack(proto.CONNECT) # Call parent implementation super(Session, self...
def send_message(self, msg, stats=True): """ Send or queue outgoing message @param msg: Message to send @param stats: If set to True, will update statistics after operation completes """ self.send_jsonified(proto.json_encode(msg), stats)
def send_jsonified(self, msg, stats=True): """ Send JSON-encoded message @param msg: JSON encoded string to send @param stats: If set to True, will update statistics after operation completes """ assert isinstance(msg, basestring), 'Can only send strings' if isinstance(msg, unicode): msg = msg.encode('utf-8') if self._...
def flush(self): """ Flush message queue if there's an active connection running """ self._pending_flush = False if self.handler is None: return if self.send_queue.is_empty(): return self.handler.send_pack('a[%s]' % self.send_queue.get()) self.send_queue.clear()
def close(self, code=3000, message='Go away!'): """ Close session. @param code: Closing code @param message: Closing message """ if self.state != SESSION_STATE.CLOSED: # Notify handler if self.handler is not None: self.handler.send_pack(proto.disconnect(code, message)) super(Session, self).close(code, message)
def start_heartbeat(self): """ Reset hearbeat timer """ self.stop_heartbeat() self._heartbeat_timer = task.LoopingCall(self._heartbeat) self._heartbeat_timer.start(self._heartbeat_interval, False)
def messagesReceived(self, msg_list): """ Handle incoming messages @param msg_list: Message list to process """ self.stats.packReceived(len(msg_list)) for msg in msg_list: self.conn.messageReceived(msg)
def parser(cls, v): """Ensure that the upstream parser gets two digits. """ return geoid.census.State.parse(str(v).zfill(2))
def get_dependency_structure(self, artifact=None, include_dependencies=False): """ Reads dependency structure. If an artifact is passed in you get only its dependencies otherwise the complete structure is returned. :param artifact: an artifact task or artifact name if only an artifact's deps are needed :param include_d...
def _do_read_config(self, config_file, pommanipext): """Reads config for a single job defined by section.""" parser = InterpolationConfigParser() dataset = parser.read(config_file) if config_file not in dataset: raise IOError("Config file %s not found." % config_file) if parser.has_option('common','include'): include =...
common_section['tag'] = parser.get('common', 'tag') common_section['target'] = parser.get('common', 'target') common_section['jobprefix'] = parser.get('common', 'jobprefix') common_section['jobciprefix'] = parser.get('common', 'jobciprefix') common_section['jobjdk'] = parser.get('common', 'jobjdk') if parser.has_option...
in parser.get('common', 'globalproperties').replace(",\n", ",").split(',')) else: # Always ensure properties has a valid dictionary so code below doesn't need multiple checks. common_section['options']['properties'] = {} # The same for global profiles if parser.has_option('common', 'globalprofiles'): common_section['op...
def transform_generator(fn): """A decorator that marks transform pipes that should be called to create the real transform""" if six.PY2: fn.func_dict['is_transform_generator'] = True else: # py3 fn.__dict__['is_transform_generator'] = True return fn
def is_transform_generator(fn): """Return true of the function has been marked with @transform_generator""" try: if six.PY2: fn.func_dict['is_transform_generator'] = True else: # py3 return fn.__dict__.get('is_transform_generator', False) except AttributeError: return False
def nullify(v): """Convert empty strings and strings with only spaces to None values. """ if isinstance(v, six.string_types): v = v.strip() if v is None or v == '': return None else: return v
def clean_float(v): """Remove commas from a float""" if v is None or not str(v).strip(): return None return float(str(v).replace(',', ''))
def clean_int(v): """Remove commas from a float""" if v is None or not str(v).strip(): return None return int(str(v).replace(',', ''))
def parse_int(v, header_d): """Parse as an integer, or a subclass of Int.""" v = nullify(v) if v is None: return None try: # The converson to float allows converting float strings to ints. # The conversion int('2.134') will fail. return int(round(float(v), 0)) except (TypeError, ValueError) as e: raise CastingError(int...
def _parse_text(v, header_d): """ Parses unicode. Note: unicode types for py2 and str types for py3. """ v = nullify(v) if v is None: return None try: return six.text_type(v).strip() except Exception as e: raise CastingError(six.text_type, header_d, v, str(e))
def _parse_binary(v, header_d): """ Parses binary string. Note: <str> for py2 and <binary> for py3. """ # This is often a no-op, but it ocassionally converts numbers into strings v = nullify(v) if v is None: return None if six.PY2: try: return six.binary_type(v).strip() except UnicodeEncodeError: return six.text_type(v...
def parseJuiceHeaders(lines): """ Create a JuiceBox from a list of header lines. @param lines: a list of lines. """ b = JuiceBox() bodylen = 0 key = None for L in lines: if L[0] == ' ': # continuation assert key is not None b[key] += '\r\n'+L[1:] continue parts = L.split(': ', 1) if len(parts) != 2: raise MalformedJuic...
def lookupFunction(self, proto, name, namespace): """Return a callable to invoke when executing the named command. """ # Try to find a method to be invoked in a transaction first # Otherwise fallback to a "regular" method fName = self.autoDispatchPrefix + name fObj = getattr(self, fName, None) if fObj is not None: # pa...
def sendBoxCommand(self, command, box, requiresAnswer=True): """ Send a command across the wire with the given C{juice.Box}. Returns a Deferred which fires with the response C{juice.Box} when it is received, or fails with a C{juice.RemoteJuiceError} if an error is received. If the Deferred fails and the error is not ha...
def _switchTo(self, newProto, clientFactory=None): """ Switch this Juice instance to a new protocol. You need to do this 'simultaneously' on both ends of a connection; the easiest way to do this is to use a subclass of ProtocolSwitchCommand. """ assert self.innerProtocol is None, "Protocol can only be safely switched o...
def sendPacket(self, completeBox): """ Send a juice.Box to my peer. Note: transport.write is never called outside of this method. """ assert not self.__locked, "You cannot send juice packets when a connection is locked" if self._startingTLSBuffer is not None: self._startingTLSBuffer.append(completeBox) else: if debug: ...
def dataframe(self, filtered_dims={}, unstack=False, df_class=None, add_code=False): """ Yield rows in a reduced format, with one dimension as an index, one measure column per secondary dimension, and all other dimensions filtered. :param measure: The column names of one or more measures :param p_dim: The primary dimen...
if isinstance(v, string_types): return '"{}"'.format(v) else: return v all_dims = [p_dim.name] + filtered_dims.keys() if s_dim: all_dims.append(s_dim.name) if filtered_dims: all_dims += filtered_dims.keys() all_dims = [text_type(c) for c in all_dims] # "primary_dimensions" means something different here, all of the dim...
if filtered_dims: code = ' and '.join("row.{} == {}".format(k, maybe_quote(v)) for k, v in filtered_dims.items()) predicate = eval('lambda row: {}'.format(code)) else: predicate = lambda row: True df = self.analysis.dataframe(predicate, columns=columns, df_class=df_class) if unstack: # Need to set the s_dim in the inde...
def get_dependency_graph_for_set(self, id, **kwargs): """ Gets dependency graph for a Build Group Record (running and completed). This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback...
def search(self, search_phrase, limit=None): """ Finds datasets by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to return. None means without limit. Returns: list of DatasetSearchResult instances. """ # SQLite FTS can't find terms with `-`, therefore all hyphens were repl...
DatasetSearchResult() datasets[vid].vid = vid datasets[vid].b_score = score logger.debug('Extending datasets with partitions.') for partition in self.backend.partition_index.search(search_phrase): datasets[partition.dataset_vid].p_score += partition.score datasets[partition.dataset_vid].partitions.add(partition) return...
def _as_document(self, dataset): """ Converts dataset to document indexed by to FTS index. Args: dataset (orm.Dataset): dataset to convert. Returns: dict with structure matches to BaseDatasetIndex._schema. """ assert isinstance(dataset, Dataset) doc = super(self.__class__, self)._as_document(dataset) # SQLite FTS can't...
def _index_document(self, document, force=False): """ Adds document to the index. """ query = text(""" INSERT INTO dataset_index(vid, title, keywords, doc) VALUES(:vid, :title, :keywords, :doc); """) self.backend.library.database.connection.execute(query, **document)
def _delete(self, vid=None): """ Deletes given dataset from index. Args: vid (str): dataset vid. """ query = text(""" DELETE FROM dataset_index WHERE vid = :vid; """) self.backend.library.database.connection.execute(query, vid=vid)
def is_indexed(self, dataset): """ Returns True if dataset is already indexed. Otherwise returns False. """ query = text(""" SELECT vid FROM dataset_index WHERE vid = :vid; """) result = self.backend.library.database.connection.execute(query, vid=dataset.vid) return bool(result.fetchall())
def all(self): """ Returns list with all indexed datasets. """ datasets = [] query = text(""" SELECT vid FROM dataset_index;""") for result in self.backend.library.database.connection.execute(query): res = DatasetSearchResult() res.vid = result[0] res.b_score = 1 datasets.append(res) return datasets
def list_documents(self, limit=None): """ Generates vids of all indexed identifiers. Args: limit (int, optional): If not empty, the maximum number of results to return Generates: str: vid of the document. """ limit_str = '' if limit: try: limit_str = 'LIMIT {}'.format(int(limit)) except (TypeError, ValueError): pass qu...
def reset(self): """ Drops index table. """ query = """ DROP TABLE identifier_index; """ self.backend.library.database.connection.execute(query)
def _delete(self, identifier=None): """ Deletes given identifier from index. Args: identifier (str): identifier of the document to delete. """ query = text(""" DELETE FROM identifier_index WHERE identifier = :identifier; """) self.backend.library.database.connection.execute(query, identifier=identifier)
def is_indexed(self, identifier): """ Returns True if identifier is already indexed. Otherwise returns False. """ query = text(""" SELECT identifier FROM identifier_index WHERE identifier = :identifier; """) result = self.backend.library.database.connection.execute(query, identifier=identifier['identifier']) return boo...
def all(self): """ Returns list with all indexed identifiers. """ identifiers = [] query = text(""" SELECT identifier, type, name FROM identifier_index;""") for result in self.backend.library.database.connection.execute(query): vid, type_, name = result res = IdentifierSearchResult( score=1, vid=vid, type=type_, name=n...
def search(self, search_phrase, limit=None): """ Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Generates: PartitionSearchResult instances. """ # SQLite FTS can't find terms with `-`, therefore all hyphens replaced ...
# # So, filter years range here. results = connection.execute(query, query_params).fetchall() for result in results: vid, dataset_vid, score, db_from_year, db_to_year = result if from_year and from_year < db_from_year: continue if to_year and to_year > db_to_year: continue yield PartitionSearchResult( vid=vid, dataset_...
def _as_document(self, partition): """ Converts partition to document indexed by to FTS index. Args: partition (orm.Partition): partition to convert. Returns: dict with structure matches to BasePartitionIndex._schema. """ doc = super(self.__class__, self)._as_document(partition) # SQLite FTS can't find terms with `-`, ...
def _make_query_from_terms(self, terms): """ Creates a query for partition from decomposed search terms. Args: terms (dict or unicode or string): Returns: tuple of (str, dict): First element is str with FTS query, second is parameters of the query. """ match_query = '' expanded_terms = self._expand_terms(terms) if expa...
def _index_document(self, document, force=False): """ Adds parition document to the index. """ from ambry.util import int_maybe time_coverage = document.pop('time_coverage', []) from_year = None to_year = None if time_coverage: from_year = int_maybe(time_coverage[0]) to_year = int_maybe(time_coverage[-1]) query = text(...
def all(self): """ Returns list with vids of all indexed partitions. """ partitions = [] query = text(""" SELECT dataset_vid, vid FROM partition_index;""") for result in self.backend.library.database.connection.execute(query): dataset_vid, vid = result partitions.append(PartitionSearchResult(dataset_vid=dataset_vid, vi...
def timedelta_seconds(td): ''' Return the offset stored by a :class:`datetime.timedelta` object as an integer number of seconds. Microseconds, if present, are rounded to the nearest second. Delegates to :meth:`timedelta.total_seconds() <datetime.timedelta.total_seconds()>` if available. >>> timedelta_seconds(timedelta(...
def timezone(utcoffset): ''' Return a string representing the timezone offset. Remaining seconds are rounded to the nearest minute. >>> timezone(3600) '+01:00' >>> timezone(5400) '+01:30' >>> timezone(-28800) '-08:00' ''' hours, seconds = divmod(abs(utcoffset), 3600) minutes = round(float(seconds) / 60) if utcoffset >=...
def id_exists(api, search_id): """ Test if an ID exists within any arbitrary API :param api: api to search for search_id :param search_id: id to test for :return: True if an entity with ID search_id exists, false otherwise """ response = utils.checked_api_call(api, 'get_specific', id=search_id) return response is not N...
def get_id_by_name(api, search_name): """ calls 'get_all' on the given API with a search name and returns the ID of the entity retrieved, if any, None otherwise :param api: api to search :param search_name: name to test for :return ID of entity matching search_name, None otherwise """ entities = api.get_all(q='name==' ...
def get_entity(api, entity_id): """ Generic "getSpecific" call that calls get_specific with the given id :param api: api to call get_specific on :param id: id of the entity to retrieve :return: REST entity """ response = utils.checked_api_call(api, 'get_specific', id=entity_id) if response: return response.content retu...
def build_duration(self): """Return the difference between build and build_done states""" return int(self.state.build_done) - int(self.state.build)
def build_duration_pretty(self): """Return the difference between build and build_done states, in a human readable format""" from ambry.util import pretty_time from time import time if not self.state.building: return None built = self.state.built or time() try: return pretty_time(int(built) - int(self.state.building)) ...
def built_datetime(self): """Return the built time as a datetime object""" from datetime import datetime try: return datetime.fromtimestamp(self.state.build_done) except TypeError: # build_done is null return None
def new_datetime(self): """Return the time the bundle was created as a datetime object""" from datetime import datetime try: return datetime.fromtimestamp(self.state.new) except TypeError: return None
def last_datetime(self): """Return the time of the last operation on the bundle as a datetime object""" from datetime import datetime try: return datetime.fromtimestamp(self.state.lasttime) except TypeError: return None
def add(self, session): """ Add session to the container. @param session: Session object """ self._items[session.session_id] = session if session.expiry is not None: self._queue.push(session)
def expire(self, current_time=None): """ Expire any old entries @param current_time: Optional time to be used to clean up queue (can be used in unit tests) """ if self._queue.is_empty(): return if current_time is None: current_time = time.time() while not self._queue.is_empty(): # Get top most item top = self._queue.pe...
it if need_reschedule: top.expiry_date = top.promoted top.promoted = None self._queue.push(top) else: del self._items[top.session_id]
def send_email(recipients, subject, message, attachments=None): """ Sends email. Args: recipients (list of str): subject (str): message (str): attachments (list of str): list containing full paths (txt files only) to attach to email. """ if not attachments: attachments = [] if os.path.exists(EMAIL_SETTINGS_FILE): email...
= smtplib.SMTP(server) if use_tls: srv.starttls() if username: srv.login(username, password) srv.sendmail(sender, ','.join(recipients), msg.as_string()) srv.quit()
def list_product_versions(page_size=200, page_index=0, sort="", q=""): """ List all ProductVersions """ content = list_product_versions_raw(page_size, page_index, sort, q) if content: return utils.format_json_list(content)
def create_product_version(product_id, version, **kwargs): """ Create a new ProductVersion. Each ProductVersion represents a supported product release stream, which includes milestones and releases typically associated with a single major.minor version of a Product. Follows the Red Hat product support cycle, and typica...
def update_product_version(id, **kwargs): """ Update the ProductVersion with ID id with new values. """ content = update_product_version_raw(id, **kwargs) if content: return utils.format_json(content)
def prepare_data(self): ''' Method returning data passed to template. Subclasses can override it. ''' value = self.get_raw_value() return dict(widget=self, field=self.field, value=value, readonly=not self.field.writable)
def render(self): ''' Renders widget to template ''' data = self.prepare_data() if self.field.readable: return self.env.template.render(self.template, **data) return ''
def _request(self, url, *, method='GET', headers=None, data=None, result_callback=None): """Perform asynchronous request. :param str url: request URL. :param str method: request method. :param dict headers: request headers. :param object data: JSON-encodable object. :param object -> object result_callback: result callb...
yield gen.sleep(retry_in) continue elif 400 <= err.code < 500: raise ClientError(err.code, resp_body) from None raise ServerError(err.code, resp_body) from None
def _prepare_request(self, url, method, headers, data): """Prepare HTTP request. :param str url: request URL. :param str method: request method. :param dict headers: request headers. :param object data: JSON-encodable object. :rtype: httpclient.HTTPRequest """ request = httpclient.HTTPRequest( url=url, method=method, h...
def iter(self): """ Extract BLAST records and yield C{ReadAlignments} instances. For each file except the first, check that the BLAST parameters are compatible with those found (above, in __init__) in the first file. @return: A generator that yields C{ReadAlignments} instances. """ # Note that self._reader is already i...
self.scoreClass) differences = checkCompatibleParams( self.params.applicationParams, reader.params) if differences: raise ValueError( 'Incompatible BLAST parameters found. The parameters ' 'in %s differ from those originally found in %s. %s' % (blastFilename, self.blastFilenames[0], differences)) for readAlignments in ...
def getSubjectSequence(self, title): """ Obtain information about a subject sequence given its title. This information is cached in self._subjectTitleToSubject. It can be obtained from either a) an sqlite database (given via the sqliteDatabaseFilename argument to __init__), b) the FASTA that was originally given to BLA...
Fall back to blastdbcmd. ncbidb has to be imported # as below so ncbidb.getSequence can be patched by our # test suite. from dark import ncbidb seq = ncbidb.getSequence( title, self.params.applicationParams['database']) return readClass(seq.description, str(seq.seq)) else: # An Sqlite3 database is used to look up subje...
def adjustHspsForPlotting(self, titleAlignments): """ Our HSPs are about to be plotted. If we are using e-values, these need to be adjusted. @param titleAlignments: An instance of L{TitleAlignment}. """ # If we're using bit scores, there's nothing to do. if self.scoreClass is HigherIsBetterScore: return # Convert all e...
self._maxConvertedEValue = maxConvertedEValue self._zeroEValueFound = True # Adjust all zero e-value HSPs to have numerically high values. if self.randomizeZeroEValues: for hsp in zeroHsps: hsp.score.score = (maxConvertedEValue + 2 + uniform( 0, ZERO_EVALUE_UPPER_RANDOM_INCREMENT)) else: for count, hsp in enumerate(zer...
def adjustPlot(self, readsAx): """ Add a horizontal line to the plotted reads if we're plotting e-values and a zero e-value was found. @param readsAx: A Matplotlib sub-plot instance, as returned by matplotlib.pyplot.subplot. """ # If we're using bit scores, there's nothing to do. if self.scoreClass is HigherIsBetterSco...
def sum(self, axis=0, dtype=None): """Sum over rows or columns. Overrides the default `pandas.DataFrame.sum()` function to prevent temporary in-memory copies. """ if axis not in [0, 1, 'index', 'columns']: raise ValueError('"axis" parameter must be one of 0, 1, "index", ' 'or "columns".') sum_kwargs = {} if dtype is no...
def get_heatmap(self, highlight_genes=None, highlight_samples=None, highlight_color=None, **kwargs): """Generate a heatmap (`ExpHeatmap`) of the matrix. See :class:`ExpHeatmap` constructor for keyword arguments. Parameters ---------- highlight_genes : list of str List of genes to highlight highlight_color : str Color t...
) return ExpHeatmap(self, gene_annotations=gene_annotations, sample_annotations=sample_annotations, **kwargs)
def get_figure(self, heatmap_kw=None, **kwargs): """Generate a plotly figure showing the matrix as a heatmap. This is a shortcut for ``ExpMatrix.get_heatmap(...).get_figure(...)``. See :func:`ExpHeatmap.get_figure` for keyword arguments. Parameters ---------- heatmap_kw : dict or None If not None, dictionary containing...
def sort_genes(self, stable=True, inplace=False, ascending=True): """Sort the rows of the matrix alphabetically by gene name. Parameters ---------- stable: bool, optional Whether to use a stable sorting algorithm. [True] inplace: bool, optional Whether to perform the operation in place.[False] ascending: bool, optional...
def sort_samples(self, stable=True, inplace=False, ascending=True): """Sort the columns of the matrix alphabetically by sample name. Parameters ---------- stable: bool, optional Whether to use a stable sorting algorithm. [True] inplace: bool, optional Whether to perform the operation in place.[False] ascending: bool, o...
def center_genes(self, use_median=False, inplace=False): """Center the expression of each gene (row).""" if use_median: X = self.X - \ np.tile(np.median(self.X, axis=1), (self.n, 1)).T else: X = self.X - \ np.tile(np.mean(self.X, axis=1), (self.n, 1)).T if inplace: self.X[:,:] = X matrix = self else: matrix = ExpMatrix...
def standardize_genes(self, inplace=False): """Standardize the expression of each gene (row).""" matrix = self.center_genes(inplace=inplace) matrix.X[:,:] = matrix.X / \ np.tile(np.std(matrix.X, axis=1, ddof=1), (matrix.n, 1)).T return matrix
def filter_genes(self, gene_names : Iterable[str], inplace=False): """Filter the expression matrix against a _genome (set of genes). Parameters ---------- gene_names: list of str The genome to filter the genes against. inplace: bool, optional Whether to perform the operation in-place. Returns ------- ExpMatrix The filt...
def sample_correlations(self): """Returns an `ExpMatrix` containing all pairwise sample correlations. Returns ------- `ExpMatrix` The sample correlation matrix. """ C = np.corrcoef(self.X.T) corr_matrix = ExpMatrix(genes=self.samples, samples=self.samples, X=C) return corr_matrix
def read_tsv(cls, file_path: str, gene_table: ExpGeneTable = None, encoding: str = 'UTF-8', sep: str = '\t'): """Read expression matrix from a tab-delimited text file. Parameters ---------- file_path: str The path of the text file. gene_table: `ExpGeneTable` object, optional The set of valid genes. If given, the genes ...
#ind = pd.read_csv(file_path, sep=sep, usecols=[0, ], header=0, # encoding=encoding, na_filter=False) ind = pd.read_csv(file_path, sep=sep, usecols=[0, ], header=None, skiprows=1, encoding=encoding, na_filter=False) matrix.index = ind.iloc[:, 0] matrix.index.name = 'Genes' if gene_table is not None: # filter genes matr...
def write_tsv(self, file_path: str, encoding: str = 'UTF-8', sep: str = '\t'): """Write expression matrix to a tab-delimited text file. Parameters ---------- file_path: str The path of the output file. encoding: str, optional The file encoding. ("UTF-8") Returns ------- None """ #if six.PY2: # sep = sep.encode('UTF-8')...
def write_sparse(self, file_path: str): """Write a sparse representation to a tab-delimited text file. TODO: docstring""" coo = sparse.coo_matrix(self.X) data = OrderedDict([(0, coo.row+1), (1, coo.col+1), (2, coo.data)]) df = pd.DataFrame(data, columns=data.keys()) with open(file_path, 'w') as ofh: ofh.write('%%Matrix...
def read_sparse(cls, file_path: str): """Read a sparse representation from a tab-delimited text file. TODO: docstring""" with open(file_path) as fh: next(fh) # skip header line genes = next(fh)[1:-1].split('\t') cells = next(fh)[1:-1].split('\t') next(fh) m, n, nnz = [int(s) for s in next(fh)[:-1].split(' ')] t = pd.re...
def read_10xgenomics(cls, tarball_fpath: str, prefix: str, use_ensembl_ids: bool = False): """Read a 10X genomics compressed tarball containing expression data. Note: common prefix patterns: - "filtered_gene_bc_matrices/[annotations]/" - "filtered_matrices_mex/[annotations]/" TODO: docstring""" _LOGGER.info('Reading fi...
def get_argument_parser(): """Function to obtain the argument parser. Parameters ---------- Returns ------- `argparse.ArgumentParser` A fully configured `argparse.ArgumentParser` object. Notes ----- This function can also be used by the `sphinx-argparse` extension for sphinx to generate documentation for this script. "...
return parser