_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q55000
FASTA.ids
train
def ids(self): """A frozen set of all unique IDs in the file.""" as_list = [seq.description.split()[0] for seq in self] as_set = frozenset(as_list) assert len(as_set) == len(as_list) return as_set
python
{ "resource": "" }
q55001
FASTA.sql
train
def sql(self): """If you access this attribute, we will build an SQLite database out of the FASTA file and you will be able access everything in an indexed fashion, and use the blaze library via sql.frame""" from fasta.indexed import DatabaseFASTA, fasta_to_sql db = DatabaseFASTA...
python
{ "resource": "" }
q55002
FASTA.length_by_id
train
def length_by_id(self): """In some usecases you just need the sequence lengths in an indexed fashion. If you access this attribute, we will make a hash map in memory.""" hashmap = dict((seq.id, len(seq)) for seq in self) tmp = hashmap.copy() hashmap.update(tmp) return has...
python
{ "resource": "" }
q55003
FASTA.subsample
train
def subsample(self, down_to=1, new_path=None): """Pick a number of sequences from the file pseudo-randomly.""" # Auto path # if new_path is None: subsampled = self.__class__(new_temp_path()) elif isinstance(new_path, FASTA): subsampled = new_path else: subsampled =...
python
{ "resource": "" }
q55004
FASTA.rename_with_num
train
def rename_with_num(self, prefix="", new_path=None, remove_desc=True): """Rename every sequence based on a prefix and a number.""" # Temporary path # if new_path is None: numbered = self.__class__(new_temp_path()) else: numbered = self.__class__(new_path) # Generat...
python
{ "resource": "" }
q55005
FASTA.rename_with_prefix
train
def rename_with_prefix(self, prefix="", new_path=None, in_place=True, remove_desc=True): """Rename every sequence based on a prefix.""" # Temporary path # if new_path is None: prefixed = self.__class__(new_temp_path()) else: prefixed = self.__class__(new_path) # Ge...
python
{ "resource": "" }
q55006
FASTA.rename_sequences
train
def rename_sequences(self, mapping, new_path=None, in_place=False): """Will rename all sequences in the current fasta file using the mapping dictionary also provided. In place or at a new path.""" # Where is the new file # if new_path is None: new_fasta = self.__class__(new_temp_path()) ...
python
{ "resource": "" }
q55007
FASTA.extract_length
train
def extract_length(self, lower_bound=None, upper_bound=None, new_path=None): """Extract a certain length fraction and place them in a new file.""" # Temporary path # if new_path is None: fraction = self.__class__(new_temp_path()) elif isinstance(new_path, FASTA): fraction = new_path ...
python
{ "resource": "" }
q55008
FASTA.extract_sequences
train
def extract_sequences(self, ids, new_path=None): """Will take all the sequences from the current file who's id appears in the ids given and place them in the new file path given.""" # Temporary path # if new_path is None: new_fasta = self.__class__(new_temp_path()) elif isinstanc...
python
{ "resource": "" }
q55009
FASTA.remove_trailing_stars
train
def remove_trailing_stars(self, new_path=None, in_place=True, check=False): """Remove the bad character that can be inserted by some programs at the end of sequences.""" # Optional check # if check and int(sh.grep('-c', '\*', self.path, _ok_code=[0,1])) == 0: return self # Faster...
python
{ "resource": "" }
q55010
FASTA.align
train
def align(self, out_path=None): """We align the sequences in the fasta file with muscle.""" if out_path is None: out_path = self.prefix_path + '.aln' sh.muscle38("-in", self.path, "-out", out_path) return AlignedFASTA(out_path)
python
{ "resource": "" }
q55011
FASTA.template_align
train
def template_align(self, ref_path): """We align the sequences in the fasta file with mothur and a template.""" # Run it # sh.mothur("#align.seqs(candidate=%s, template=%s, search=blast, flip=false, processors=8);" % (self.path, ref_path)) # Move things # shutil.move(self.path[:-6...
python
{ "resource": "" }
q55012
FASTA.index_bowtie
train
def index_bowtie(self): """Create an index on the fasta file compatible with bowtie2.""" # It returns exit code 1 if the fasta is empty # assert self # Call the bowtie executable # sh.bowtie2_build(self.path, self.path) return FilePath(self.path + '.1.bt2')
python
{ "resource": "" }
q55013
FASTA.graphs
train
def graphs(self): """Sorry for the black magic. The result is an object whose attributes are all the graphs found in graphs.py initialized with this instance as only argument.""" result = Dummy() for graph in graphs.__all__: cls = getattr(graphs, graph) se...
python
{ "resource": "" }
q55014
Context.delete_node
train
def delete_node(self, key_chain): """ key_chain is an array of keys giving the path to the node that should be deleted. """ node = self._data for key in key_chain[:-1]: node = node[key] del node[key_chain[-1]]
python
{ "resource": "" }
q55015
assert_or_raise
train
def assert_or_raise(stmt: bool, exception: Exception, *exception_args, **exception_kwargs) -> None: """ If the statement is false, raise the given exception. """ if not stmt: raise exception(*exception_args, **exception_kwargs)
python
{ "resource": "" }
q55016
make_socket
train
def make_socket(): '''Creates a socket suitable for SSDP searches. The socket will have a default timeout of 0.2 seconds (this works well for the :py:func:search function which interleaves sending requests and reading responses. ''' mreq = struct.pack("4sl", socket.inet_aton(MCAST_IP), socket.I...
python
{ "resource": "" }
q55017
encode_request
train
def encode_request(request_line, **headers): '''Creates the data for a SSDP request. Args: request_line (string): The request line for the request (e.g. ``"M-SEARCH * HTTP/1.1"``). headers (dict of string -> string): Dictionary of header name - header value pairs to pres...
python
{ "resource": "" }
q55018
decode_response
train
def decode_response(data): '''Decodes the data from a SSDP response. Args: data (bytes): The encoded response. Returns: dict of string -> string: Case-insensitive dictionary of header name to header value pairs extracted from the response. ''' res = CaseInsensitiveDict() ...
python
{ "resource": "" }
q55019
request_via_socket
train
def request_via_socket(sock, search_target): '''Send an SSDP search request via the provided socket. Args: sock: A socket suitable for use to send a broadcast message - preferably one created by :py:func:`make_socket`. search_target (string): A :term:`resource type` target to search...
python
{ "resource": "" }
q55020
responses_from_socket
train
def responses_from_socket(sock, timeout=10): '''Yield SSDP search responses and advertisements from the provided socket. Args: sock: A socket suitable for use to send a broadcast message - preferably one created by :py:func:`make_socket`. timeout (int / float): Overall time in secon...
python
{ "resource": "" }
q55021
search
train
def search(target_types=None, timeout=12, tries=3): ''' Performs a search via SSDP to discover resources. Args: target_types (sequence of strings): A sequence of :term:`resource types` to search for. For convenience, this can also be a single string. If provided, then this f...
python
{ "resource": "" }
q55022
SocketTransport.start
train
def start(self): """Start watching the socket.""" if self.closed: raise ConnectionClosed() self.read_watcher.start() if self.write == self.buffered_write: self.write_watcher.start()
python
{ "resource": "" }
q55023
SocketTransport.stop
train
def stop(self): """Stop watching the socket.""" if self.closed: raise ConnectionClosed() if self.read_watcher.active: self.read_watcher.stop() if self.write_watcher.active: self.write_watcher.stop()
python
{ "resource": "" }
q55024
SocketTransport.unbuffered_write
train
def unbuffered_write(self, buf): """Performs an unbuffered write, the default unless socket.send does not send everything, in which case an unbuffered write is done and the write method is set to be a buffered write until the buffer is empty once again. buf -- bytes to send ...
python
{ "resource": "" }
q55025
SocketTransport.buffered_write
train
def buffered_write(self, buf): """Appends a bytes like object to the transport write buffer. Raises BufferOverflowError if buf would cause the buffer to grow beyond the specified maximum. buf -- bytes to send """ if self.closed: raise ConnectionClosed() ...
python
{ "resource": "" }
q55026
SocketTransport._close
train
def _close(self, e): """Really close the transport with a reason. e -- reason the socket is being closed. """ self.stop() self.sock.close() self.closed = True self.close_cb(e)
python
{ "resource": "" }
q55027
get_context
train
def get_context(name, doc): """Generate a command with given name. The command can be run immediately after generation. For example: dj generate command bar dj run manage.py bar """ name = inflection.underscore(name) return { 'name': name, 'doc': doc or name ...
python
{ "resource": "" }
q55028
install_optimal_reactor
train
def install_optimal_reactor(verbose=False): """ Try to install the optimal Twisted reactor for platform. :param verbose: If ``True``, print what happens. :type verbose: bool """ import sys from twisted.python import reflect ## determine currently installed reactor, if any ## if...
python
{ "resource": "" }
q55029
install_reactor
train
def install_reactor(explicitReactor=None, verbose=False): """ Install Twisted reactor. :param explicitReactor: If provided, install this reactor. Else, install optimal reactor. :type explicitReactor: obj :param verbose: If ``True``, print what happens. :type verbose: bool """ import sys...
python
{ "resource": "" }
q55030
QuickCache.clean_cache
train
def clean_cache(self, section=None): """Cleans the cache of this cache object.""" self.remove_all_locks() if section is not None and "/" in section: raise ValueError("invalid section '{0}'".format(section)) if section is not None: path = os.path.join(self._full_ba...
python
{ "resource": "" }
q55031
QuickCache.list_sections
train
def list_sections(self): """List all sections.""" if not os.path.exists(self._full_base): return [] return [ name for name in os.listdir(self._full_base) if os.path.isdir(os.path.join(self._full_base, name)) ]
python
{ "resource": "" }
q55032
QuickCache.get_file
train
def get_file(self, cache_id_obj, section=None): """Returns the file path for the given cache object.""" section = "default" if section is None else section if "/" in section: raise ValueError("invalid section '{0}'".format(section)) cache_id = "{:08x}".format( zli...
python
{ "resource": "" }
q55033
QuickCache.remove_all_locks
train
def remove_all_locks(self): """Removes all locks and ensures their content is written to disk.""" locks = list(self._locks.items()) locks.sort(key=lambda l: l[1].get_last_access()) for l in locks: self._remove_lock(l[0])
python
{ "resource": "" }
q55034
QuickCache.get_hnd
train
def get_hnd(self, cache_id_obj, section=None, method=None): """Gets a handle for the given cache file with exclusive access. The handle is meant to be used in a resource block. Parameters ---------- cache_id_obj : object An object uniquely identifying the cached r...
python
{ "resource": "" }
q55035
_CacheLock.ensure_cache_id
train
def ensure_cache_id(self, cache_id_obj): """Ensure the integrity of the cache id object.""" cache_id = self._get_canonical_id(cache_id_obj) if cache_id != self._cache_id_obj: raise ValueError( "cache mismatch {0} != {1}".format( cache_id, self._cac...
python
{ "resource": "" }
q55036
_CacheLock.has
train
def has(self): """Whether the cache file exists in the file system.""" self._done = os.path.exists(self._cache_file) return self._done or self._out is not None
python
{ "resource": "" }
q55037
_CacheLock.read
train
def read(self): """Reads the cache file as pickle file.""" def warn(msg, elapsed_time, current_time): desc = self._cache_id_desc() self._warnings( "{0} {1}: {2}s < {3}s", msg, desc, elapsed_time, current_time) file_time = get_time() out = self._o...
python
{ "resource": "" }
q55038
_CacheLock.write
train
def write(self, obj): """Writes the given object to the cache file as pickle. The cache file with its path is created if needed. """ if self.verbose: self._warnings("cache miss for {0}", self._cache_id_desc()) if self._start_time is not None: elapsed = ...
python
{ "resource": "" }
q55039
add_xml_declaration
train
def add_xml_declaration(fn): """ Decorator to add header with XML version declaration to output from FN. """ @wraps(fn) def add_xml_declaration_decorator(*args, **kwargs): return '<?xml version="1.0" encoding="UTF-8"?>\n\n' + fn( *args, **kwargs ) return ...
python
{ "resource": "" }
q55040
fix_missing_lang_tags
train
def fix_missing_lang_tags(marc_xml, dom): """ If the lang tags are missing, add them to the MODS. Lang tags are parsed from `marc_xml`. """ def get_lang_tag(lang): lang_str = '\n <mods:language>\n' lang_str += ' <mods:languageTerm authority="iso639-2b" type="code">' lang_...
python
{ "resource": "" }
q55041
postprocess_monograph
train
def postprocess_monograph(marc_xml, mods, uuid, counter, url): """ Fix bugs in `mods` produced by XSLT template. Args: marc_xml (str): Original Aleph record. mods (str): XML string generated by XSLT template. uuid (str): UUID of the package. counter (int): Number of record, ...
python
{ "resource": "" }
q55042
add_suffix
train
def add_suffix(string, suffix): """ Adds a suffix to a string, if the string does not already have that suffix. :param string: the string that should have a suffix added to it :param suffix: the suffix to be added to the string :return: the string with the suffix added, if it does not already end i...
python
{ "resource": "" }
q55043
Uploader.download
train
def download(csvpath, asset_manager_id, data_id_type, data_id_list): """retrieve the objs mainly for test purposes""" interface = interface_direct_csvpath(csvpath) logging.config.dictConfig(DEFAULT_LOGGING) logger = logging.getLogger(__name__) objs = [] for data_id in dat...
python
{ "resource": "" }
q55044
tuplify
train
def tuplify(*args): """ Convert args to a tuple, unless there's one arg and it's a function, then acts a decorator. """ if (len(args) == 1) and callable(args[0]): func = args[0] @wraps(func) def _inner(*args, **kwargs): return tuple(func(*args, **kwargs)) ...
python
{ "resource": "" }
q55045
listify
train
def listify(*args): """ Convert args to a list, unless there's one arg and it's a function, then acts a decorator. """ if (len(args) == 1) and callable(args[0]): func = args[0] @wraps(func) def _inner(*args, **kwargs): return list(func(*args, **kwargs)) r...
python
{ "resource": "" }
q55046
stringify
train
def stringify(*args): """ Joins args to build a string, unless there's one arg and it's a function, then acts a decorator. """ if (len(args) == 1) and callable(args[0]): func = args[0] @wraps(func) def _inner(*args, **kwargs): return "".join([str(i) for i in func...
python
{ "resource": "" }
q55047
make_endpoints
train
def make_endpoints(version, name, endpoints, kwargs=None): """ Returns a redirect handler and all endpoints with a version prefix added. :param version: the application version :param name: the application name :param endpoints: a list of application endpoints :param kwargs: an optional diction...
python
{ "resource": "" }
q55048
message_box
train
def message_box(type, title, message, icon=None, buttons=QMessageBox.Ok, custom_buttons=None): """ Provides a fast GUI message box. :param title: Current message title. :type title: unicode :param message: Message. :type message: unicode :param icon: Custom icon. :type icon: QConstant ...
python
{ "resource": "" }
q55049
itersplit
train
def itersplit(s, sep=None): """ Split a string by ``sep`` and yield chunks Args: s (str-type): string to split sep (str-type): delimiter to split by Yields: generator of strings: chunks of string s """ if not s: yield s return exp = re.compile(r'\s+'...
python
{ "resource": "" }
q55050
sh
train
def sh(cmd, ignore_error=False, cwd=None, shell=False, **kwargs): """ Execute a command with subprocess.Popen and block until output Args: cmd (tuple or str): same as subprocess.Popen args Keyword Arguments: ignore_error (bool): if False, raise an Exception if p.returncode is ...
python
{ "resource": "" }
q55051
listdir_find_repos
train
def listdir_find_repos(where): """ Search for repositories with a stack and ``os.listdir`` Args: where (str): path to search from Yields: Repository subclass instance """ stack = deque([(convert_path(where), '')]) while stack: where, prefix = stack.pop() try...
python
{ "resource": "" }
q55052
find_find_repos
train
def find_find_repos(where, ignore_error=True): """ Search for repositories with GNU find Args: where (str): path to search from ignore_error (bool): if False, raise Exception when the returncode is not zero. Yields: Repository subclass instance """ log.debug...
python
{ "resource": "" }
q55053
find_unique_repos
train
def find_unique_repos(where): """ Search for repositories and deduplicate based on ``repo.fpath`` Args: where (str): path to search from Yields: Repository subclass """ repos = Dict() path_uuids = Dict() log.debug("find_unique_repos(%r)" % where) for repo in find_fi...
python
{ "resource": "" }
q55054
do_tortoisehg_report
train
def do_tortoisehg_report(repos, output): """ Generate a thg-reporegistry.xml file from a list of repos and print to output Args: repos (iterable): iterable of Repository subclass instances output (writeable): output stream to which THG XML will be printed """ import operator ...
python
{ "resource": "" }
q55055
get_option_parser
train
def get_option_parser(): """ Build an ``optparse.OptionParser`` for pyrpo commandline use """ import optparse prs = optparse.OptionParser( usage=( "$0 pyrpo [-h] [-v] [-q] [-s .] " "[-r <report>] [--thg]")) prs.add_option('-s', '--scan', dest=...
python
{ "resource": "" }
q55056
Repository.relpath
train
def relpath(self): """ Determine the relative path to this repository Returns: str: relative path to this repository """ here = os.path.abspath(os.path.curdir) relpath = os.path.relpath(self.fpath, here) return relpath
python
{ "resource": "" }
q55057
Repository.log_iter
train
def log_iter(self, maxentries=None, template=None, **kwargs): """ Run the repository log command, parse, and yield log tuples Yields: tuple: self._tuple """ # op = self.sh(( # "hg log %s --template" # % (maxentries and ('-l%d' % maxentries) or '')...
python
{ "resource": "" }
q55058
Repository.full_report
train
def full_report(self): """ Show origin, last_commit, status, and parsed complete log history for this repository Yields: str: report lines """ yield '' yield "# %s" % next(self.origin_report()) yield "%s [%s]" % (self.last_commit, self) ...
python
{ "resource": "" }
q55059
Repository.sh_report
train
def sh_report(self, full=True, latest=False): """ Show shell command necessary to clone this repository If there is no primary remote url, prefix-comment the command Keyword Arguments: full (bool): also include commands to recreate branches and remotes latest (b...
python
{ "resource": "" }
q55060
Repository.pip_report
train
def pip_report(self): """ Show editable pip-requirements line necessary to clone this repository Yields: str: pip-requirements line necessary to clone this repository """ comment = '#' if not self.remote_url else '' if os.path.exists(os.path.join(self.fpath, ...
python
{ "resource": "" }
q55061
Repository.lately
train
def lately(self, count=15): """ Show ``count`` most-recently modified files by mtime Yields: tuple: (strftime-formatted mtime, self.fpath-relative file path) """ excludes = '|'.join(('*.pyc', '*.swp', '*.bak', '*~')) cmd = ('''find . -printf "%%T@ %%p\\n" '''...
python
{ "resource": "" }
q55062
Repository.sh
train
def sh(self, cmd, ignore_error=False, cwd=None, shell=False, **kwargs): """ Run a command with the current working directory set to self.fpath Args: cmd (str or tuple): cmdstring or listlike Keyword Arguments: ignore_error (bool): if False, raise an Exception if...
python
{ "resource": "" }
q55063
MercurialRepository._get_url_scheme_regexes
train
def _get_url_scheme_regexes(): """ Get configured mercurial schemes and convert them to regexes Returns: tuple: (scheme_name, scheme_value, compiled scheme_regex) """ output = sh("hg showconfig | grep '^schemes.'", shell=True).split('\n') log.debug(output) ...
python
{ "resource": "" }
q55064
MercurialRepository.to_hg_scheme_url
train
def to_hg_scheme_url(cls, url): """ Convert a URL to local mercurial URL schemes Args: url (str): URL to map to local mercurial URL schemes example:: # schemes.gh = git://github.com/ >> remote_url = git://github.com/westurner/dotfiles' >...
python
{ "resource": "" }
q55065
MercurialRepository.to_normal_url
train
def to_normal_url(cls, url): """ convert a URL from local mercurial URL schemes to "normal" URLS example:: # schemes.gh = git://github.com/ # remote_url = "gh://westurner/dotfiles" >> to_normal_url(remote_url) << 'git://github.com/westurner/dotfi...
python
{ "resource": "" }
q55066
GitRepository.remote_urls
train
def remote_urls(self): """ Get all configured remote urls for this Repository Returns: str: primary remote url for this Repository (``git config -l | grep "url"``) """ cmd = 'git config -l | grep "url"' return self.sh(cmd, ...
python
{ "resource": "" }
q55067
GitRepository.branch
train
def branch(self): """ Determine the branch name of the working directory of this Repository Returns: str: branch name (``git symbolic-ref --short HEAD``) """ # return self.sh(['git, 'branch'], shell=False) # parse for '*' cmd = ['git', 'symbolic-ref', '--sho...
python
{ "resource": "" }
q55068
GitRepository.cfg_file
train
def cfg_file(self): """ Return the configuration file for the given repo path """ default_path = os.path.join(self.relpath, '.git', 'config') if os.path.exists(default_path): return default_path dotgitpath = os.path.join(self.relpath, '.git') cfg_path...
python
{ "resource": "" }
q55069
BzrRepository._parselog
train
def _parselog(self, r): """ Parse bazaar log file format Args: r (str): bzr revision identifier Yields: dict: dict of (attr, value) pairs :: $ bzr log -l1 ------------------------------------------------------------ ...
python
{ "resource": "" }
q55070
SvnRepository.unique_id
train
def unique_id(self): """ Determine a "unique id" for this repository Returns: str: Repository UUID of this repository """ cmd = 'svn info | grep "^Repository UUID"' cmdo = self.sh(cmd, shell=True, ignore_error=Tru...
python
{ "resource": "" }
q55071
split_obj
train
def split_obj (obj, prefix = None): ''' Split the object, returning a 3-tuple with the flat object, optionally followed by the key for the subobjects and a list of those subobjects. ''' # copy the object, optionally add the prefix before each key new = obj.copy() if prefix is None else { '{}_{}...
python
{ "resource": "" }
q55072
flatten_json
train
def flatten_json(data, prefix = None): ''' Flatten the data, optionally with each key prefixed. ''' # iterate all items for item in data: # split the object flat, key, subs = split_obj(item, prefix) # just return fully flat objects if key is None: yield f...
python
{ "resource": "" }
q55073
parse_filename
train
def parse_filename(filename): """Parse media filename for metadata. :param str filename: the name of media file :returns: dict of metadata attributes found in filename or None if no matching expression. :rtype: dict """ _patterns = patterns.get_expressions() result = {} ...
python
{ "resource": "" }
q55074
system_summary
train
def system_summary(providername=None): """ returns SystemSummary class from mentioned provider """ _providername = providername if not _providername: _providername = provider_check() import_str = 'netshowlib.%s.system_summary' % _providername return import_module(import_str).SystemS...
python
{ "resource": "" }
q55075
portname_list
train
def portname_list(providername=None): """ Return list of ports found by the provider """ _providername = providername if not _providername: _providername = provider_check() import_str = 'netshowlib.%s.iface' % _providername return import_module(import_str).portname_list()
python
{ "resource": "" }
q55076
SafeRedisQueue.get
train
def get(self, timeout=0): """Return next item from queue. Blocking by default. Blocks if queue is empty, see `timeout` parameter. Internally this also pops uid from queue and writes it to ackbuffer. :param timeout: blocking timeout in seconds - 0: block...
python
{ "resource": "" }
q55077
SafeRedisQueue.ack
train
def ack(self, uid): """Acknowledge item as successfully consumed. Removes uid from ackbuffer and deletes the corresponding item. """ self._redis.pipeline()\ .lrem(self.ACKBUF_KEY, 0, uid)\ .lrem(self.BACKUP, 0, uid)\ .hdel(self.IT...
python
{ "resource": "" }
q55078
SafeRedisQueue.fail
train
def fail(self, uid): """Report item as not successfully consumed. Removes uid from ackbuffer and re-enqueues it. """ self._redis.pipeline()\ .lrem(self.ACKBUF_KEY, 0, uid)\ .lrem(self.BACKUP, 0, uid)\ .lpush(self.QUEUE_KEY, uid)\ ...
python
{ "resource": "" }
q55079
saccade_model_em
train
def saccade_model_em(pointlist): ''' Estimates the reaction time and duration of the saccade by fitting a saccade model to the data. The model consists of three phases: 1) source phase, gaze is fixated onto a point 2) saccade phase, gaze moves steadily from the source point onto th...
python
{ "resource": "" }
q55080
SharedResource.decorator
train
def decorator(cls, func_or_class): """A decorator method that adds this class to a 'resources' list on the decorated object.""" resources = getattr(func_or_class, 'resources', []) resources.append(cls) func_or_class.resources = resources return func_or_class
python
{ "resource": "" }
q55081
get_table_columns
train
def get_table_columns(dbconn, tablename): """ Return a list of tuples specifying the column name and type """ cur = dbconn.cursor() cur.execute("PRAGMA table_info('%s');" % tablename) info = cur.fetchall() cols = [(i[1], i[2]) for i in info] return cols
python
{ "resource": "" }
q55082
get_last_row
train
def get_last_row(dbconn, tablename, n=1, uuid=None): """ Returns the last `n` rows in the table """ return fetch(dbconn, tablename, n, uuid, end=True)
python
{ "resource": "" }
q55083
get_first_row
train
def get_first_row(dbconn, tablename, n=1, uuid=None): """ Returns the first `n` rows in the table """ return fetch(dbconn, tablename, n, uuid, end=False)
python
{ "resource": "" }
q55084
split_phylogeny
train
def split_phylogeny(p, level="s"): """ Return either the full or truncated version of a QIIME-formatted taxonomy string. :type p: str :param p: A QIIME-formatted taxonomy string: k__Foo; p__Bar; ... :type level: str :param level: The different level of identification are kingdom (k), phylum (p...
python
{ "resource": "" }
q55085
ensure_dir
train
def ensure_dir(d): """ Check to make sure the supplied directory path does not exist, if so, create it. The method catches OSError exceptions and returns a descriptive message instead of re-raising the error. :type d: str :param d: It is the full path to a directory. :return: Does not retu...
python
{ "resource": "" }
q55086
file_handle
train
def file_handle(fnh, mode="rU"): """ Takes either a file path or an open file handle, checks validity and returns an open file handle or raises an appropriate Exception. :type fnh: str :param fnh: It is the full path to a file, or open file handle :type mode: str :param mode: The way in wh...
python
{ "resource": "" }
q55087
gather_categories
train
def gather_categories(imap, header, categories=None): """ Find the user specified categories in the map and create a dictionary to contain the relevant data for each type within the categories. Multiple categories will have their types combined such that each possible combination will have its own entry...
python
{ "resource": "" }
q55088
parse_unifrac
train
def parse_unifrac(unifracFN): """ Parses the unifrac results file into a dictionary :type unifracFN: str :param unifracFN: The path to the unifrac results file :rtype: dict :return: A dictionary with keys: 'pcd' (principle coordinates data) which is a dictionary of the data keyed ...
python
{ "resource": "" }
q55089
parse_unifrac_v1_8
train
def parse_unifrac_v1_8(unifrac, file_data): """ Function to parse data from older version of unifrac file obtained from Qiime version 1.8 and earlier. :type unifrac: dict :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after...
python
{ "resource": "" }
q55090
parse_unifrac_v1_9
train
def parse_unifrac_v1_9(unifrac, file_data): """ Function to parse data from newer version of unifrac file obtained from Qiime version 1.9 and later. :type unifracFN: str :param unifracFN: The path to the unifrac results file :type file_data: list :param file_data: Unifrac data lines after ...
python
{ "resource": "" }
q55091
color_mapping
train
def color_mapping(sample_map, header, group_column, color_column=None): """ Determine color-category mapping. If color_column was specified, then map the category names to color values. Otherwise, use the palettable colors to automatically generate a set of colors for the group values. :type sample...
python
{ "resource": "" }
q55092
rev_c
train
def rev_c(read): """ return reverse completment of read """ rc = [] rc_nucs = {'A':'T', 'T':'A', 'G':'C', 'C':'G', 'N':'N'} for base in read: rc.extend(rc_nucs[base.upper()]) return rc[::-1]
python
{ "resource": "" }
q55093
shuffle_genome
train
def shuffle_genome(genome, cat, fraction = float(100), plot = True, \ alpha = 0.1, beta = 100000, \ min_length = 1000, max_length = 200000): """ randomly shuffle genome """ header = '>randomized_%s' % (genome.name) sequence = list(''.join([i[1] for i in parse_fasta(genome)])) len...
python
{ "resource": "" }
q55094
MultiVarLinReg._prune
train
def _prune(self, fit, p_max): """ If the fit contains statistically insignificant parameters, remove them. Returns a pruned fit where all parameters have p-values of the t-statistic below p_max Parameters ---------- fit: fm.ols fit object Can contain insignif...
python
{ "resource": "" }
q55095
MultiVarLinReg.find_best_rsquared
train
def find_best_rsquared(list_of_fits): """Return the best fit, based on rsquared""" res = sorted(list_of_fits, key=lambda x: x.rsquared) return res[-1]
python
{ "resource": "" }
q55096
MultiVarLinReg._predict
train
def _predict(self, fit, df): """ Return a df with predictions and confidence interval Notes ----- The df will contain the following columns: - 'predicted': the model output - 'interval_u', 'interval_l': upper and lower confidence bounds. The result will ...
python
{ "resource": "" }
q55097
relative_abundance
train
def relative_abundance(biomf, sampleIDs=None): """ Calculate the relative abundance of each OTUID in a Sample. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: list :param sampleIDs: A list of sample id's from BIOM format OTU table. :rtype: dict :return: Retu...
python
{ "resource": "" }
q55098
mean_otu_pct_abundance
train
def mean_otu_pct_abundance(ra, otuIDs): """ Calculate the mean OTU abundance percentage. :type ra: Dict :param ra: 'ra' refers to a dictionary keyed on SampleIDs, and the values are dictionaries keyed on OTUID's and their values represent the relative abundance of that OTU...
python
{ "resource": "" }
q55099
MRA
train
def MRA(biomf, sampleIDs=None, transform=None): """ Calculate the mean relative abundance percentage. :type biomf: A BIOM file. :param biomf: OTU table format. :type sampleIDs: list :param sampleIDs: A list of sample id's from BIOM format OTU table. :param transform: Mathematical function...
python
{ "resource": "" }