text
stringlengths
81
112k
Render basicly the text. def render(self, display): """Render basicly the text.""" # to handle changing objects / callable if self.text != self._last_text: self._render() display.blit(self._surface, (self.topleft, self.size))
The position of the cursor in the text. def cursor(self): """The position of the cursor in the text.""" if self._cursor < 0: self.cursor = 0 if self._cursor > len(self): self.cursor = len(self) return self._cursor
Move the cursor of one letter to the right (1) or the the left. def move_cursor_one_letter(self, letter=RIGHT): """Move the cursor of one letter to the right (1) or the the left.""" assert letter in (self.RIGHT, self.LEFT) if letter == self.RIGHT: self.cursor += 1 if se...
Move the cursor of one word to the right (1) or the the left (-1). def move_cursor_one_word(self, word=LEFT): """Move the cursor of one word to the right (1) or the the left (-1).""" assert word in (self.RIGHT, self.LEFT) if word == self.RIGHT: papy = self.text.find(' ', self.curs...
Delete one letter the right or the the left of the cursor. def delete_one_letter(self, letter=RIGHT): """Delete one letter the right or the the left of the cursor.""" assert letter in (self.RIGHT, self.LEFT) if letter == self.LEFT: papy = self.cursor self.text = self.t...
Delete one word the right or the the left of the cursor. def delete_one_word(self, word=RIGHT): """Delete one word the right or the the left of the cursor.""" assert word in (self.RIGHT, self.LEFT) if word == self.RIGHT: papy = self.text.find(' ', self.cursor) + 1 if n...
Add a letter at the cursor pos. def add_letter(self, letter): """Add a letter at the cursor pos.""" assert isinstance(letter, str) assert len(letter) == 1 self.text = self.text[:self.cursor] + letter + self.text[self.cursor:] self.cursor += 1
Update the text and position of cursor according to the event passed. def update(self, event_or_list): """Update the text and position of cursor according to the event passed.""" event_or_list = super().update(event_or_list) for e in event_or_list: if e.type == KEYDOWN: ...
Render the text. Avoid using this fonction too many times as it is slow as it is slow to render text and blit it. def _render(self): """ Render the text. Avoid using this fonction too many times as it is slow as it is slow to render text and blit it. """ self._last_te...
The text displayed instead of the real one. def shawn_text(self): """The text displayed instead of the real one.""" if len(self._shawn_text) == len(self): return self._shawn_text if self.style == self.DOTS: return chr(0x2022) * len(self) ranges = [ ...
The cursor position in pixels. def cursor_pos(self): """The cursor position in pixels.""" if len(self) == 0: return self.left + self.default_text.get_width() papy = self._surface.get_width() if papy > self.w: shift = papy - self.width else: s...
Render the text. Avoid using this fonction too many times as it is slow as it is slow to render text and blit it. def _render(self): """ Render the text. Avoid using this fonction too many times as it is slow as it is slow to render text and blit it. """ self._last_te...
Render basicly the text. def render(self, display): """Render basicly the text.""" # to handle changing objects / callable if self.shawn_text != self._last_text: self._render() if self.text: papy = self._surface.get_width() if papy <= self.width: ...
Return a pygame image from a latex template. def latex_to_img(tex): """Return a pygame image from a latex template.""" with tempfile.TemporaryDirectory() as tmpdirname: with open(tmpdirname + r'\tex.tex', 'w') as f: f.write(tex) os.system(r"latex {0}\tex.tex -ha...
Return the mix of two colors at a state of :pos: Retruns color1 * pos + color2 * (1 - pos) def mix(color1, color2, pos=0.5): """ Return the mix of two colors at a state of :pos: Retruns color1 * pos + color2 * (1 - pos) """ opp_pos = 1 - pos red = color1[0] * pos + color2[0] * opp_pos ...
Convert the name of a color into its RGB value def name2rgb(name): """Convert the name of a color into its RGB value""" try: import colour except ImportError: raise ImportError('You need colour to be installed: pip install colour') c = colour.Color(name) color = int(c.red * 255), i...
Parse the command man page. def parse_page(page): """Parse the command man page.""" colors = get_config()['colors'] with io.open(page, encoding='utf-8') as f: lines = f.readlines() output_lines = [] for line in lines[1:]: if is_headline(line): continue elif is_de...
Configure the module logging engine. def configure_logging(level=logging.DEBUG): """Configure the module logging engine.""" if level == logging.DEBUG: # For debugging purposes, log from everyone! logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(levelname...
Wrapper around `os.path.join`. Makes sure to join paths of the same type (bytes). def path_join(*args): """ Wrapper around `os.path.join`. Makes sure to join paths of the same type (bytes). """ args = (paramiko.py3compat.u(arg) for arg in args) return os.path.join(*args)
Parse a command line string and return username, password, remote hostname and remote path. :param remote_url: A command line string. :return: A tuple, containing username, password, remote hostname and remote path. def parse_username_password_hostname(remote_url): """ Parse a command line string and ...
Ask the SSH agent for a list of keys, and return it. :return: A reference to the SSH agent and a list of keys. def get_ssh_agent_keys(logger): """ Ask the SSH agent for a list of keys, and return it. :return: A reference to the SSH agent and a list of keys. """ agent, agent_keys = None, None ...
Create the CLI argument parser. def create_parser(): """Create the CLI argument parser.""" parser = argparse.ArgumentParser( description='Sync a local and a remote folder through SFTP.' ) parser.add_argument( "path", type=str, metavar="local-path", help="the pat...
The main. def main(args=None): """The main.""" parser = create_parser() args = vars(parser.parse_args(args)) log_mapping = { 'CRITICAL': logging.CRITICAL, 'ERROR': logging.ERROR, 'WARNING': logging.WARNING, 'INFO': logging.INFO, 'DEBUG': logging.DEBUG, '...
Return True if the remote correspondent of local_path has to be deleted. i.e. if it doesn't exists locally or if it has a different type from the remote one. def _must_be_deleted(local_path, r_st): """Return True if the remote correspondent of local_path has to be deleted. i.e. if it doesn't ...
Match mod, utime and uid/gid with locals one. def _match_modes(self, remote_path, l_st): """Match mod, utime and uid/gid with locals one.""" self.sftp.chmod(remote_path, S_IMODE(l_st.st_mode)) self.sftp.utime(remote_path, (l_st.st_atime, l_st.st_mtime)) if self.chown: self....
Upload local_path to remote_path and set permission and mtime. def file_upload(self, local_path, remote_path, l_st): """Upload local_path to remote_path and set permission and mtime.""" self.sftp.put(local_path, remote_path) self._match_modes(remote_path, l_st)
Remove the remote directory node. def remote_delete(self, remote_path, r_st): """Remove the remote directory node.""" # If it's a directory, then delete content and directory if S_ISDIR(r_st.st_mode): for item in self.sftp.listdir_attr(remote_path): full_path = path_...
Traverse the entire remote_path tree. Find files/directories that need to be deleted, not being present in the local folder. def check_for_deletion(self, relative_path=None): """Traverse the entire remote_path tree. Find files/directories that need to be deleted, not being pre...
Create a new link pointing to link_destination in remote_path position. def create_update_symlink(self, link_destination, remote_path): """Create a new link pointing to link_destination in remote_path position.""" try: # if there's anything, delete it self.sftp.remove(remote_path) ...
Check if the given directory tree node has to be uploaded/created on the remote folder. def node_check_for_upload_create(self, relative_path, f): """Check if the given directory tree node has to be uploaded/created on the remote folder.""" if not relative_path: # we're at the root of the sh...
Traverse the relative_path tree and check for files that need to be uploaded/created. Relativity here refers to the shared directory tree. def check_for_upload_create(self, relative_path=None): """Traverse the relative_path tree and check for files that need to be uploaded/created. Relativity...
Run the sync. Confront the local and the remote directories and perform the needed changes. def run(self): """Run the sync. Confront the local and the remote directories and perform the needed changes.""" # Check if remote path is present try: self.sftp.stat(self....
tree unix command replacement. def list_files(start_path): """tree unix command replacement.""" s = u'\n' for root, dirs, files in os.walk(start_path): level = root.replace(start_path, '').count(os.sep) indent = ' ' * 4 * level s += u'{}{}/\n'.format(indent, os.path.basename(root)) ...
Create a nested dictionary that represents the folder structure of `start_path`. Liberally adapted from http://code.activestate.com/recipes/577879-create-a-nested-dictionary-from-oswalk/ def file_tree(start_path): """ Create a nested dictionary that represents the folder structure of `start_path`. ...
Capture standard output and error. def capture_sys_output(): """Capture standard output and error.""" capture_out, capture_err = StringIO(), StringIO() current_out, current_err = sys.stdout, sys.stderr try: sys.stdout, sys.stderr = capture_out, capture_err yield capture_out, capture_err...
Suppress logging. def suppress_logging(log_level=logging.CRITICAL): """Suppress logging.""" logging.disable(log_level) yield logging.disable(logging.NOTSET)
Override user environmental variables with custom one. def override_env_variables(): """Override user environmental variables with custom one.""" env_vars = ("LOGNAME", "USER", "LNAME", "USERNAME") old = [os.environ[v] if v in os.environ else None for v in env_vars] for v in env_vars: os.envir...
Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent. def override_ssh_auth_env(): """Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent.""" ssh_auth_sock = "SSH_AUTH_SOCK" old_ssh_auth_sock = os.environ.get(ssh_auth_sock) del os.environ[ssh_auth_s...
Get the configurations from .tldrrc and return it as a dict. def get_config(): """Get the configurations from .tldrrc and return it as a dict.""" config_path = path.join( (os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')), '.tldrrc') if not path.exists(config_path): sys.exi...
Parse the man page and return the parsed lines. def parse_man_page(command, platform): """Parse the man page and return the parsed lines.""" page_path = find_page_location(command, platform) output_lines = parse_page(page_path) return output_lines
Find the command man page in the pages directory. def find_page_location(command, specified_platform): """Find the command man page in the pages directory.""" repo_directory = get_config()['repo_directory'] default_platform = get_config()['platform'] command_platform = ( specified_platform if s...
Find the command usage. def find(command, on): """Find the command usage.""" output_lines = parse_man_page(command, on) click.echo(''.join(output_lines))
Update to the latest pages. def update(): """Update to the latest pages.""" repo_directory = get_config()['repo_directory'] os.chdir(repo_directory) click.echo("Check for updates...") local = subprocess.check_output('git rev-parse master'.split()).strip() remote = subprocess.check_output( ...
Init config file. def init(): """Init config file.""" default_config_path = path.join( (os.environ.get('TLDR_CONFIG_DIR') or path.expanduser('~')), '.tldrrc') if path.exists(default_config_path): click.echo("There is already a config file exists, " "skip initializ...
Locate the command's man page. def locate(command, on): """Locate the command's man page.""" location = find_page_location(command, on) click.echo(location)
Produce a relationship between this mapped table and another one. This makes usage of SQLAlchemy's :func:`sqlalchemy.orm.relationship` construct. def relate(cls, propname, *args, **kwargs): """Produce a relationship between this mapped table and another one. ...
Execute a SQL statement. The statement may be a string SQL string, an :func:`sqlalchemy.sql.expression.select` construct, or a :func:`sqlalchemy.sql.expression.text` construct. def execute(self, stmt, **params): """Execute a SQL statement. The statement may be a stri...
Configure a mapping to the given attrname. This is the "master" method that can be used to create any configuration. :param attrname: String attribute name which will be established as an attribute on this :class:.`.SQLSoup` instance. :param base: a Python class wh...
Map a selectable directly. The class and its mapping are not cached and will be discarded once dereferenced (as of 0.6.6). :param selectable: an :func:`.expression.select` construct. :param base: a Python class which will be used as the base for the mapped class. If ``None``,...
Map a selectable directly, wrapping the selectable in a subquery with labels. The class and its mapping are not cached and will be discarded once dereferenced (as of 0.6.6). :param selectable: an :func:`.expression.select` construct. :param base: a Python class which will be u...
Create an :func:`.expression.join` and map to it. The class and its mapping are not cached and will be discarded once dereferenced (as of 0.6.6). :param left: a mapped class or table object. :param right: a mapped class or table object. :param onclause: optional "ON" clause con...
Return the named entity from this :class:`.SQLSoup`, or create if not present. For more generalized mapping, see :meth:`.map_to`. def entity(self, attr, schema=None): """Return the named entity from this :class:`.SQLSoup`, or create if not present. For more generalized mappi...
\ Distance between 2 features. The integer result is always positive or zero. If the features overlap or touch, it is zero. >>> from intersecter import Feature, distance >>> distance(Feature(1, 2), Feature(12, 13)) 10 >>> distance(Feature(1, 2), Feature(2, 3)) 0 >>> distance(Feature(1, 1...
Return a object of all stored intervals intersecting between (start, end) inclusive. def find(self, start, end, chrom=None): """Return a object of all stored intervals intersecting between (start, end) inclusive.""" intervals = self.intervals[chrom] ilen = len(intervals) # NOTE: we only...
return the nearest n features strictly to the left of a Feature f. Overlapping features are not considered as to the left. f: a Feature object n: the number of features to return def left(self, f, n=1): """return the nearest n features strictly to the left of a Feature f. Overl...
return the nearest n features strictly to the right of a Feature f. Overlapping features are not considered as to the right. f: a Feature object n: the number of features to return def right(self, f, n=1): """return the nearest n features strictly to the right of a Feature f. O...
find n upstream features where upstream is determined by the strand of the query Feature f Overlapping features are not considered. f: a Feature object n: the number of features to return def upstream(self, f, n=1): """find n upstream features where upstream is determined by ...
find n downstream features where downstream is determined by the strand of the query Feature f Overlapping features are not considered. f: a Feature object n: the number of features to return def downstream(self, f, n=1): """find n downstream features where downstream is determ...
return the n nearest neighbors to the given feature f: a Feature object k: the number of features to return def knearest(self, f_or_start, end=None, chrom=None, k=1): """return the n nearest neighbors to the given feature f: a Feature object k: the number of features to return ...
find all elements between (or overlapping) start and end def find(self, start, end): """find all elements between (or overlapping) start and end""" if self.intervals and not end < self.intervals[0].start: overlapping = [i for i in self.intervals if i.end >= start ...
return the sequence for a region using the UCSC DAS server. note the start is 1-based each feature will have it's own .sequence method which sends the correct start and end to this function. >>> sequence('hg18', 'chr2', 2223, 2230) 'caacttag' def sequence(db, chrom, start, end): """ return...
alter the table to work between different dialects def set_table(genome, table, table_name, connection_string, metadata): """ alter the table to work between different dialects """ table = Table(table_name, genome._metadata, autoload=True, autoload_with=genome.bind, extend_e...
internal: create a dburl from a set of parameters or the defaults on this object def create_url(self, db="", user="genome", host="genome-mysql.cse.ucsc.edu", password="", dialect="mysqldb"): """ internal: create a dburl from a set of parameters or the defaults on this object ...
miror a set of `tables` from `dest_url` Returns a new Genome object Parameters ---------- tables : list an iterable of tables dest_url: str a dburl string, e.g. 'sqlite:///local.db' def mirror(self, tables, dest_url): """ miror a set o...
create a pandas dataframe from a table or query Parameters ---------- table : table a table in this database or a query limit: integer an integer limit on the query offset: integer an offset for the query def dataframe(self, table): ...
use some of the machinery in pandas to load a file into a table Parameters ---------- fname : str filename or filehandle to load table : str table to load the file to sep : str CSV separator bins : bool add a "bin" colu...
open a web-browser to the DAVID online enrichment tool Parameters ---------- refseq_list : list list of refseq names to check for enrichment annot : list iterable of DAVID annotations to check for enrichment def david_go(refseq_list, annot=('SP_PIR_KEYWORDS', 'G...
perform an efficient spatial query using the bin column if available. The possible bins are calculated from the `start` and `end` sent to this function. Parameters ---------- table : str or table table to query chrom : str chromosome for the query...
Return k-nearest upstream features Parameters ---------- table : str or table table against which to query chrom_or_feat : str or feat either a chromosome, e.g. 'chr3' or a feature with .chrom, .start, .end attributes start : int ...
Return k-nearest features Parameters ---------- table : str or table table against which to query chrom_or_feat : str or feat either a chromosome, e.g. 'chr3' or a feature with .chrom, .start, .end attributes start : int if `chr...
annotate a file with a number of tables Parameters ---------- fname : str or file file name or file-handle tables : list list of tables with which to annotate `fname` feature_strand : bool if this is True, then the up/downstream designations...
Get all the bin numbers for a particular interval defined by (start, end] def bins(start, end): """ Get all the bin numbers for a particular interval defined by (start, end] """ if end - start < 536870912: offsets = [585, 73, 9, 1] else: r...
write a bed12 file of the query. Parameters ---------- query : query a table or query to save to file filename : file string or filehandle to write output def save_bed(cls, query, filename=sys.stdout): """ write a bed12 file of the query. ...
For example: {% staticfile "/js/foo.js" %} or {% staticfile "/js/foo.js" as variable_name %} Or for multiples: {% staticfile "/foo.js; /bar.js" %} or {% staticfile "/foo.js; /bar.js" as variable_name %} def staticfile_node(parser, token, optimize_if_possible=Fa...
works the way a good mkdir should :) - already exists, silently complete - regular file in the way, raise an exception - parent directory(ies) does not exist, make them as well def _mkdir(newdir): """works the way a good mkdir should :) - already exists, silently complete - ...
Look for filename in all MEDIA_ROOTS, and return the first one found. def _find_filepath_in_roots(filename): """Look for filename in all MEDIA_ROOTS, and return the first one found.""" for root in settings.DJANGO_STATIC_MEDIA_ROOTS: filepath = _filename2filepath(filename, root) if os.path.isfil...
Return a new filename to use as the combined file name for a bunch of files. A precondition is that they all have the same file extension Given that the list of files can have different paths, we aim to use the most common path. Example: /somewhere/else/foo.js /somewhere/bar.js /...
inspect the code and look for files that can be turned into combos. Basically, the developer could type this: {% slimall %} <link href="/one.css"/> <link href="/two.css"/> {% endslimall %} And it should be reconsidered like this: <link href="{% slimfile "/on...
check for overlap with the other interval def overlaps(self, other): """ check for overlap with the other interval """ if self.chrom != other.chrom: return False if self.start >= other.end: return False if other.start >= self.end: return False return True
check if this is upstream of the `other` interval taking the strand of the other interval into account def is_upstream_of(self, other): """ check if this is upstream of the `other` interval taking the strand of the other interval into account """ if self.chrom != other.c...
check the distance between this an another interval Parameters ---------- other_or_start : Interval or int either an integer or an Interval with a start attribute indicating the start of the interval end : int if `other_or_start` is an integer, this ...
return a list of exons [(start, stop)] for this object if appropriate def exons(self): """ return a list of exons [(start, stop)] for this object if appropriate """ # drop the trailing comma if not self.is_gene_pred: return [] if hasattr(self, "exonStarts"): ...
return a list of features for the gene features of this object. This would include exons, introns, utrs, etc. def gene_features(self): """ return a list of features for the gene features of this object. This would include exons, introns, utrs, etc. """ nm, strand = self....
Return a start, end tuple of positions around the transcription-start site Parameters ---------- up : int if greature than 0, the strand is used to add this many upstream bases in the appropriate direction down : int if greature than 0, the str...
Return a start, end tuple of positions for the promoter region of this gene Parameters ---------- up : int this distance upstream that is considered the promoter down : int the strand is used to add this many downstream bases into the gene. def promoter(...
includes the entire exon as long as any of it is > cdsStart and < cdsEnd def coding_exons(self): """ includes the entire exon as long as any of it is > cdsStart and < cdsEnd """ # drop the trailing comma starts = (long(s) for s in self.exonStarts[:-1].split(","))...
just the parts of the exons that are translated def cds(self): """just the parts of the exons that are translated""" ces = self.coding_exons if len(ces) < 1: return ces ces[0] = (self.cdsStart, ces[0][1]) ces[-1] = (ces[-1][0], self.cdsEnd) assert all((s < e for s, e in ...
return a boolean indicating whether this feature is downstream of `other` taking the strand of other into account def is_downstream_of(self, other): """ return a boolean indicating whether this feature is downstream of `other` taking the strand of other into account """ ...
return e.g. "intron;exon" if the other_start, end overlap introns and exons def features(self, other_start, other_end): """ return e.g. "intron;exon" if the other_start, end overlap introns and exons """ # completely encases gene. if other_start <= self.start and...
return the (start, end) of the region before the geneStart def upstream(self, distance): """ return the (start, end) of the region before the geneStart """ if getattr(self, "strand", None) == "+": e = self.start s = e - distance else: s = self...
return the 5' UTR if appropriate def utr5(self): """ return the 5' UTR if appropriate """ if not self.is_coding or len(self.exons) < 2: return (None, None) if self.strand == "+": s, e = (self.txStart, self.cdsStart) else: s, e = (self.cdsEnd, self...
Return the sequence for this feature. if per-exon is True, return an array of exon sequences This sequence is never reverse complemented def sequence(self, per_exon=False): """ Return the sequence for this feature. if per-exon is True, return an array of exon sequences T...
perform an NCBI blast against the sequence of this feature def ncbi_blast(self, db="nr", megablast=True, sequence=None): """ perform an NCBI blast against the sequence of this feature """ import requests requests.defaults.max_retries = 4 assert sequence in (None, "cds", ...
make a request to the genome-browsers BLAT interface sequence is one of None, "mrna", "cds" returns a list of features that are hits to this sequence. def blat(self, db=None, sequence=None, seq_type="DNA"): """ make a request to the genome-browsers BLAT interface sequence is one...
return a bed formatted string of this feature def bed(self, *attrs, **kwargs): """ return a bed formatted string of this feature """ exclude = ("chrom", "start", "end", "txStart", "txEnd", "chromStart", "chromEnd") if self.is_gene_pred: return self.be...
return a bed12 (http://genome.ucsc.edu/FAQ/FAQformat.html#format1) representation of this interval def bed12(self, score="0", rgb="."): """ return a bed12 (http://genome.ucsc.edu/FAQ/FAQformat.html#format1) representation of this interval """ if not self.is_gene_pred: ...
convert global coordinate(s) to local taking introns into account and cds/tx-Start depending on cdna=True kwarg def localize(self, *positions, **kwargs): """ convert global coordinate(s) to local taking introns into account and cds/tx-Start depending on cdna=True kwarg """ ...
check the distance between this an another interval Parameters ---------- other_or_start : Interval or int either an integer or an Interval with a start attribute indicating the start of the interval end : int if `other_or_start` is an integer, this ...
annotate bed file in fname with tables. distances are integers for distance. and intron/exon/utr5 etc for gene-pred tables. if the annotation features have a strand, the distance reported is negative if the annotation feature is upstream of the feature in question if feature_strand is True, then the dis...
External entry point which calls main() and if Stop is raised, calls sys.exit() def entry_point(): """ External entry point which calls main() and if Stop is raised, calls sys.exit() """ try: main("omego", items=[ (InstallCommand.NAME, InstallCommand), (UpgradeCo...