text
stringlengths
81
112k
Reads a markdown file and returns the contents formatted as rst def readme(fname): """Reads a markdown file and returns the contents formatted as rst""" md = open(os.path.join(os.path.dirname(__file__), fname)).read() output = md try: import pypandoc output = pypandoc.convert(md, 'rst',...
Loads a configuration file from multiple locations, and merge the results into one. This function will load configuration files from a number of locations in sequence, and will overwrite values in the previous level if they are redefined in the current. The levels are in sequence: 1. Distribution level configura...
Load an entire directory of configuration files, merging them into one. This function will load multiple configuration files matching the given pattern, in the given path, and merge them. The found files are first sorted alphabetically, and then loaded and merged. A good practice is to use ConfigObj sections, for e...
Resolve the promise. def resolve(self, *pargs, **kwargs): """Resolve the promise.""" self._cached = (pargs, kwargs) self._try_then()
Check to see if self has been resolved yet, if so invoke then. def _try_then(self): """Check to see if self has been resolved yet, if so invoke then.""" if self._cached is not None and self._callback is not None: self._callback(*self._cached[0], **self._cached[1])
Hault execution until self resolves. def wait_for(self, timeout=3000): """Hault execution until self resolves.""" results = [None] results_called = [False] def results_callback(val): results[0] = val results_called[0] = True self.then(results_callback) ...
Wrapper for opening an IO object to a local file or URL :param path_or_url: :return: def open(path_or_url): """ Wrapper for opening an IO object to a local file or URL :param path_or_url: :return: """ is_url = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?...
Determine if the value is a primitive def _is_primitive(thing): """Determine if the value is a primitive""" primitive = (int, str, bool, float) return isinstance(thing, primitive)
Guess the input type of the parameter based off the default value, if unknown use text def _guess_type(val): """Guess the input type of the parameter based off the default value, if unknown use text""" if isinstance(val, bool): return "choice" elif isinstance(val, int): ...
Read params, values and annotations from the signature def _params(sig): """Read params, values and annotations from the signature""" params = [] for p in sig.parameters: param = sig.parameters[p] optional = param.default != inspect.Signature.empty default = ...
Return the namespace path to the function def _import(func): """Return the namespace path to the function""" func_name = func.__name__ # from foo.bar import func // func() # WARNING: May be broken in IPython, in which case the widget will use a fallback if func_name in globals(...
Create a Python logging Logger for the given name. A special case is when the name is None, as this will represent the root Logger object. When handlers are specified, the currently configured handlers for this name are removed, and the specified handlers are set. Parameters ---------- name: string Name of th...
Dynamically attaches endpoint callables to this client def _attach_endpoints(self): """Dynamically attaches endpoint callables to this client""" for name, value in inspect.getmembers(self): if inspect.isclass(value) and issubclass(value, self._Endpoint) and (value is not self._Endpoint): ...
load mutations into dict indexed by HGNC ID. Args: path: path to file containing de novo data. This should have five tab- separated columns e.g. hgnc chr pos consequence var_type CTC1 17 8139190 missense_variant snv CTC1 17 813919...
Register a new Thread , under the given descriptive name. Trying to register multiple threads under the same name will raise an Exception. Parameters ---------- name: string Name to register the given thread under. thread: threading.Thread, or a subclass Thread object to register. def registerThread(...
Retrieve the Thread registered under the given name. If the given name does not exists in the Thread list, an Exception is raised. Parameters ---------- name: string Name of the Thread to retrieve def getThread(self, name): """ Retrieve the Thread registered under the given name. If the given name ...
Unregister the Thread registered under the given name. Make sure that the given Thread is properly stopped, or that a reference is kept in another place. Once unregistered, this class will not keep any other references to the Thread. Parameters ---------- name: string Name of the Thread to unregister ...
Start all registered Threads. def startAll(self): """ Start all registered Threads. """ self.logger.info("Starting all threads...") for thread in self.getThreads(): thr = self.getThread(thread) self.logger.debug("Starting {0}".format(thr.name)) thr.start() self.logger.info("Started all threads")
Stop all registered Threads. This is method assumes that the Thread is using and internal variable called stop to control its main loop. Stopping a Thread is achieved as follows: 1. The Thread is retrieved. 2. $thread.stop is set to False. 3. The Thread is joined, and will wait until the Thread exits. 4. T...
Returns the current ``UserSettings`` based on the SITE_ID in the project's settings as context variables If there is no 'usersettings' attribute in the request, fetches the current UserSettings (from usersettings.shortcuts.get_current_usersettings). def usersettings(request): """ Returns the curre...
check the ensembl api version matches a currently working version This function is included so when the api version changes, we notice the change, and we can manually check the responses for the new version. def check_ensembl_api_version(self): """ check the ensembl api version matches...
open url with python libraries def open_url(self, url, headers): """ open url with python libraries """ data = self.cache.get_cached_data(url) if data is not None: return data, 200, headers self.rate_limit_ensembl_requests() req = request.Re...
obtain sequence via the ensembl REST API def ensembl_request(self, ext, headers): """ obtain sequence via the ensembl REST API """ self.attempt += 1 if self.attempt > 5: raise ValueError("too many attempts, figure out why its failing") response, sta...
obtain the ensembl gene IDs that correspond to a HGNC symbol def get_genes_for_hgnc_id(self, hgnc_symbol): """ obtain the ensembl gene IDs that correspond to a HGNC symbol """ headers = {"content-type": "application/json"} # http://grch37.rest.ensembl.org/xrefs/symbol/...
sometimes we get HGNC symbols that do not match the ensembl rest version that we are currently using. We can look for earlier HGNC symbols for the gene using the service at rest.genenames.org Args: hgnc_symbol: HGNC symbol for the gene (eg "MLL2") Returns: ...
fetch the ensembl transcript IDs for a given ensembl gene ID. Args: gene_ids: list of Ensembl gene IDs for the gene hgnc_symbols: list of possible HGNC symbols for gene def get_transcript_ids_for_ensembl_gene_ids(self, gene_ids, hgnc_symbols): """ fetch the ensembl tran...
obtain the sequence for a transcript from ensembl def get_genomic_seq_for_transcript(self, transcript_id, expand): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "application/json"} self.attempt = 0 ext = "/sequence/id/{0}?...
obtain the sequence for a transcript from ensembl def get_cds_seq_for_transcript(self, transcript_id): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "text/plain"} self.attempt = 0 ext = "/sequence/id/{}?type=cds".format(tr...
obtain the sequence for a transcript from ensembl def get_protein_seq_for_transcript(self, transcript_id): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "text/plain"} self.attempt = 0 ext = "/sequence/id/{}?type=protein".f...
obtain the sequence for a genomic region def get_genomic_seq_for_region(self, chrom, start_pos, end_pos): """ obtain the sequence for a genomic region """ headers = {"content-type": "text/plain"} self.attempt = 0 ext = "/sequence/region/human/{}:{}..{}:1".forma...
obtain the sequence for a transcript from ensembl def get_chrom_for_transcript(self, transcript_id, hgnc_id): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "application/json"} self.attempt = 0 ext = "/overlap/id/{}?feature...
obtain the sequence for a transcript from ensembl def get_exon_ranges_for_transcript(self, transcript_id): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "application/json"} self.attempt = 0 ext = "/overlap/id/{}?feature=ex...
obtain the sequence for a transcript from ensembl def get_cds_ranges_for_transcript(self, transcript_id): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "application/json"} self.attempt = 0 ext = "/overlap/id/{}?feature=cds...
limit ensembl requests to one per 0.067 s def rate_limit_ensembl_requests(self): """ limit ensembl requests to one per 0.067 s """ current_time = time.time() diff_time = current_time - self.prior_time # sleep until the current rate limit period is finished ...
Register the provided NBTool object def register(nbtool): """ Register the provided NBTool object """ global _py_funcs _lazy_init() # Save references to the tool's load() and render() functions load_key = nbtool.origin + '|' + nbtool.id + '|load' render_key = nbtool.origin + '|' + nbto...
Simple wrapper around SimpleCliTool. Simple. def call_simple_cli(command, cwd=None, universal_newlines=False, redirect_stderr=False): """ Simple wrapper around SimpleCliTool. Simple. """ return SimpleCliTool()._call_cli(command, cwd, universal_newlines, redirect_stderr)
Executes the given command, internally using Popen. The output of stdout and stderr are returned as a tuple. The returned tuple looks like: (stdout, stderr, returncode) Parameters ---------- command: string The command to execute. cwd: string Change the working directory of the program to the specifi...
Executes a list of statements, returning an iterator of results sets. Each statement should be a tuple of (statement, params). def _execute(self, cursor, statements): """" Executes a list of statements, returning an iterator of results sets. Each statement should be a tuple of (statem...
Handle messages from the front-end def _on_msg(self, msg): """Handle messages from the front-end""" data = msg['content']['data'] # If the message is a call invoke, run the function and send # the results. if 'callback' in data: guid = data['callback'] c...
Serialize an object for sending to the front-end. def serialize(self, obj): """Serialize an object for sending to the front-end.""" if hasattr(obj, '_jsid'): return {'immutable': False, 'value': obj._jsid} else: obj_json = {'immutable': True} try: ...
Deserialize an object from the front-end. def deserialize(self, obj): """Deserialize an object from the front-end.""" if obj['immutable']: return obj['value'] else: guid = obj['value'] if not guid in object_registry: instance = JSObject(self, ...
Sends a message to the front-end and returns a promise. def _send(self, method, **parameters): """Sends a message to the front-end and returns a promise.""" msg = { 'index': self._calls, 'method': method, } msg.update(parameters) promise = SimplePromise(...
Reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue. Parameters ---------- channel: object Properly initialized AMQP channel to use. original_headers: dict The headers of the originating message that caused this reply. message: string Message to reply ...
Initialize consuming of messages from an AMQP RPC queue. Messages will be consumed after start_consuming() is called. An internal callback will be used to handle incoming RPC responses. Only responses that have been registered with register_response() will be kept internally, all other responses will be dropped si...
Internal callback used by consume() Parameters ---------- channel: object Channel from which the callback originated method_frame: dict Information about the message header_frame: dict Headers of the message body: string Body of the message def _rpc_response_callback(self, channel, method_fram...
Register the receiving of a RPC response. Will return the given correlation_id after registering, or if correlation_id is None, will generate a correlation_id and return it after registering. If the given correlation_id has already been used, an KeyError will be raised. UUID version 1 will be used when generatin...
Retrieve a registered RPC response. If the correlation_id was not registered, an KeyError will the raised. If not value has been received yet, None will be returned. After retrieving the response, the value will be unset internally. The returned value will include the entire RabbitMQ message, consisting of a dict ...
This function wraps publish, and sets the properties necessary to allow end-to-end communication using the Rpc paradigm. This function assumes that the named exchange and routing_key combination will result in a AMQP queue to pickup the request, and reply using another AMQP message. To achieve this, the following ...
Publish a message to an AMQP exchange. Parameters ---------- exchange: string Exchange to publish to. routing_key: string Routing key to use for this message. message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the ...
Reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue. Parameters ---------- original_headers: dict The headers of the originating message that caused this reply. message: string Message to reply with properties: dict Properties to set on message...
Clears the cache (if primed) each time a ``UserSettings`` is saved or deleted def clear_usersettings_cache(sender, **kwargs): """ Clears the cache (if primed) each time a ``UserSettings`` is saved or deleted """ instance = kwargs['instance'] try: del USERSETTINGS_CACHE[instance.site.pk] ...
Returns the current ``UserSettings`` based on the SITE_ID in the project's settings. The ``UserSettings`` object is cached the first time it's retrieved from the database. def get_current(self): """ Returns the current ``UserSettings`` based on the SITE_ID in the project's setti...
Append path to base_url in a sensible way. def append_url(base_url, path): """ Append path to base_url in a sensible way. """ if base_url[-1] != "/": base_url += "/" if path[0] == "/": path = path[1:] return urljoin(base_url, path)
add per-gene frameshift mutation rates to the output file We make a crude estimate of the frameshift mutation rate by assessing the total frameshift burden (across all genes in a dataset) as 1.25 times the nonsense burden. Then apportion the frameshift burden proportional to each genes CDS length. ...
Random string for message signing def _randomString(): """Random string for message signing""" return ''.join( random.choice(string.ascii_uppercase + string.digits) for x in range(10))
Call custom cjdns admin function def _callFunc(session, funcName, password, args): """Call custom cjdns admin function""" txid = _randomString() sock = session.socket sock.send(bytearray('d1:q6:cookie4:txid10:%se' % txid, 'utf-8')) msg = _getMessage(session, txid) cookie = msg['cookie'] tx...
Receiving messages from cjdns admin server def _receiverThread(session): """Receiving messages from cjdns admin server""" timeOfLastSend = time.time() timeOfLastRecv = time.time() try: while True: if timeOfLastSend + KEEPALIVE_INTERVAL_SECONDS < time.time(): if time...
Getting message associated with txid def _getMessage(session, txid): """Getting message associated with txid""" while True: if txid in session.messages: msg = session.messages[txid] del session.messages[txid] return msg else: try: ...
Function fabric for Session class def _functionFabric(func_name, argList, oargList, password): """Function fabric for Session class""" def functionHandler(self, *args, **kwargs): call_args = {} for (key, value) in oargList.items(): call_args[key] = value for i, arg in enu...
Connect to cjdns admin with this attributes def connect(ipAddr, port, password): """Connect to cjdns admin with this attributes""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect((ipAddr, port)) sock.settimeout(2) # Make sure it pongs. sock.send(b'd1:q4:pinge') data =...
Connect to cjdns admin with data from user file def connectWithAdminInfo(path=None): """Connect to cjdns admin with data from user file""" if path is None: path = os.path.expanduser('~/.cjdnsadmin') try: with open(path, 'r') as adminInfo: data = json.load(adminInfo) except ...
Publish a message to an AMQP exchange. Parameters ---------- channel: object Properly initialized AMQP channel to use. exchange: string Exchange to publish to. routing_key: string Routing key to use for this message. message: string Message to publish. properties: dict Properties to set on message. Th...
Publish a message to an AMQP exchange. Parameters ---------- message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: content_type: string - what content_type to specify, default is 'text/pla...
load a file listing gene and transcript IDs Args: path: path to file containing gene IDs and transcript IDs e.g. gene_1 transcript_1.1 length_1 denovo_count gene_2 transcript_2.1 length_3 denovo_count Returns: dict of transcripts eg {'CTC1': ["...
determines mutation rates per functional category for transcripts Args: transcripts: list of transcript IDs for a gene mut_dict: dictionary of local sequence context mutation rates ensembl: EnsemblRequest object, to retrieve information from Ensembl. Returns: tuple of (...
get the command line switches def get_options(): """ get the command line switches """ parser = argparse.ArgumentParser(description='denovonear cli interface') ############################################################################ # CLI options in common parent = argparse.Argume...
Get IPv6 address from a public key. def to_ipv6(key): """Get IPv6 address from a public key.""" if key[-2:] != '.k': raise ValueError('Key does not end with .k') key_bytes = base32.decode(key[:-2]) hash_one = sha512(key_bytes).digest() hash_two = sha512(hash_one).hexdigest() return '...
Traverse directory, and return all absolute filenames of files that match the globbing patterns. def glob(self): """ Traverse directory, and return all absolute filenames of files that match the globbing patterns. """ matches = [] for root, dirnames, filenames in os.walk(self.path): if not self.recurs...
Display a choice form to select which site to add settings. def select_site_view(self, request, form_url=''): """ Display a choice form to select which site to add settings. """ if not self.has_add_permission(request): raise PermissionDenied extra_qs = '' if...
Render the site choice form. def render_select_site_form(self, request, context, form_url=''): """ Render the site choice form. """ app_label = self.opts.app_label context.update({ 'has_change_permission': self.has_change_permission(request), 'form_url': ...
Returns an OAuth token tuple that can be used with clients.ReaderClient. :param base_url_template: Template for generating Readability API urls. :param consumer_key: Readability consumer key, otherwise read from READABILITY_CONSUMER_KEY. :param consumer_secret: Readability consumer secret, otherwise read ...
log transform a numeric value, unless it is zero, or negative def log_transform(rates): """ log transform a numeric value, unless it is zero, or negative """ transformed = [] for key in ['missense', 'nonsense', 'splice_lof', 'splice_region', 'synonymous']: try: ...
Returns the ``UserSettings`` model that is active in this project. def get_usersettings_model(): """ Returns the ``UserSettings`` model that is active in this project. """ try: from django.apps import apps get_model = apps.get_model except ImportError: from django.db.models....
Returns the current ``UserSettings`` based on the SITE_ID in the project's settings def get_current_usersettings(): """ Returns the current ``UserSettings`` based on the SITE_ID in the project's settings """ USERSETTINGS_MODEL = get_usersettings_model() try: current_usersettings = U...
find the probability of getting de novos with a mean conservation The probability is the number of simulations where the mean conservation between simulated de novos is less than the observed conservation. Args: transcript: Transcript object for the current gene. rates: SiteRates o...
get the command line options def get_options(): """ get the command line options """ parser = argparse.ArgumentParser(description="Script to batch process de" "novo clustering.") parser.add_argument("--in", dest="input", required=True, help="Path to" "file listing known mutations i...
count the number of missense variants in each gene. def count_missense_per_gene(lines): """ count the number of missense variants in each gene. """ counts = {} for x in lines: x = x.split("\t") gene = x[0] consequence = x[3] if gene not in counts: ...
split de novos from an input file into files, one for each gene def split_denovos(denovo_path, temp_dir): """ split de novos from an input file into files, one for each gene """ # open the de novos, drop the header line, then sort them (which will be by # HGNC symbol, as the first element of each ...
make a random string, which we can use for bsub job IDs, so that different jobs do not have the same job IDs. def get_random_string(): """ make a random string, which we can use for bsub job IDs, so that different jobs do not have the same job IDs. """ # set up a random string to associate wit...
construct a bsub job submission command Args: command: list of strings that forma unix command job_id: string for job ID for submission dependent_id: job ID, or list of job IDs which the current command needs to have finished before the current command will start. Note that ...
sets up a lsf job array def batch_process(de_novo_path, temp_dir, output_path): """ sets up a lsf job array """ temp_dir = tempfile.mkdtemp(dir=temp_dir) count = split_denovos(de_novo_path, temp_dir) # set up run parameters job_name = "denovonear" job_id = "{0}[1-{1}]%20".format(j...
load sequence context-based mutation rates Args: path: path to table of sequence context-based mutation rates. If None, this defaults to per-trinucleotide rates provided by Kaitlin Samocha (Broad Institute). Returns: list of [initial, changed, rate] lists e.g. [...
Returns the user authenticated by ``auth`` :param auth.Authentication auth: authentication for user to retrieve :return: user authenticated by the provided authentication :rtype: GogsUser :raises NetworkFailure: if there is an error communicating with the server :raises ApiFail...
Returns the tokens owned by the specified user. If no user is specified, uses the user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, ...
Creates a new token with the specified name for the specified user. If no user is specified, uses user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must be a username-password authentication, ...
Ensures the existence of a token with the specified name for the specified user. Creates a new token if none exists. If no user is specified, uses user authenticated by ``auth``. :param auth.Authentication auth: authentication for user to retrieve. Must ...
Creates a new repository, and returns the created repository. :param auth.Authentication auth: authentication object :param str name: name of the repository to create :param str description: description of the repository to create :param bool private: whether the create repository shoul...
Returns whether a repository with name ``repo_name`` owned by the user with username ``username`` exists. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: whether the repository ...
Returns a the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: a representation of the re...
Returns the repositories owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :return: a list of repositories :rtype: List[GogsRepo] :raises NetworkFailure: if there is ...
Returns the branch with name ``branch_name`` in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository containing the branch :param str repo_name: n...
Returns the branches in the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository containing the branch :param str repo_name: name of the repository wi...
Deletes the repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository to delete :param str repo_name: name of repository to delete :raises NetworkFailure: i...
Migrate a repository from another Git hosting source for the authenticated user. :param auth.Authentication auth: authentication object :param str clone_addr: Remote Git address (HTTP/HTTPS URL or local path) :param int uid: user ID of repository owner :param str repo_name: Repository n...
Creates a new user, and returns the created user. :param auth.Authentication auth: authentication object, must be admin-level :param str login_name: login name for created user :param str username: username for created user :param str email: email address for created user :param...
Returns whether a user with username ``username`` exists. :param str username: username of user :return: whether a user with the specified username exists :rtype: bool :raises NetworkFailure: if there is an error communicating with the server :return: def user_exists(self, user...
Searches for users whose username matches ``username_keyword``, and returns a list of matched users. :param str username_keyword: keyword to search with :param int limit: maximum number of returned users :return: a list of matched users :rtype: List[GogsUser] :raises Net...
Returns a representing the user with username ``username``. :param auth.Authentication auth: authentication object, can be ``None`` :param str username: username of user to get :return: the retrieved user :rtype: GogsUser :raises NetworkFailure: if there is an error communicatin...
Updates the user with username ``username`` according to ``update``. :param auth.Authentication auth: authentication object, must be admin-level :param str username: username of user to update :param GogsUserUpdate update: a ``GogsUserUpdate`` object describing the requested update :ret...
Deletes the user with username ``username``. Should only be called if the to-be-deleted user has no repositories. :param auth.Authentication auth: authentication object, must be admin-level :param str username: username of user to delete def delete_user(self, auth, username): """ ...