sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _build_fields(self): """ Builds a list of valid fields """ declared_fields = self.solr._send_request('get', ADMIN_URL) result = decoder.decode(declared_fields) self.field_list = self._parse_fields(result, 'fields') # Build regular expressions to match dynamic fields....
Builds a list of valid fields
entailment
def _clean_doc(self, doc, namespace, timestamp): """Reformats the given document before insertion into Solr. This method reformats the document in the following ways: - removes extraneous fields that aren't defined in schema.xml - unwinds arrays in order to find and later flatten su...
Reformats the given document before insertion into Solr. This method reformats the document in the following ways: - removes extraneous fields that aren't defined in schema.xml - unwinds arrays in order to find and later flatten sub-documents - flattens the document so that there ...
entailment
def apply_update(self, doc, update_spec): """Override DocManagerBase.apply_update to have flat documents.""" # Replace a whole document if not '$set' in update_spec and not '$unset' in update_spec: # update_spec contains the new document. # Update the key in Solr based on...
Override DocManagerBase.apply_update to have flat documents.
entailment
def update(self, document_id, update_spec, namespace, timestamp): """Apply updates given in update_spec to the document whose id matches that of doc. """ # Commit outstanding changes so that the document to be updated is the # same version to which the changes apply. sel...
Apply updates given in update_spec to the document whose id matches that of doc.
entailment
def upsert(self, doc, namespace, timestamp): """Update or insert a document into Solr This method should call whatever add/insert/update method exists for the backend engine and add the document in there. The input will always be one mongo document, represented as a Python dictionary. ...
Update or insert a document into Solr This method should call whatever add/insert/update method exists for the backend engine and add the document in there. The input will always be one mongo document, represented as a Python dictionary.
entailment
def bulk_upsert(self, docs, namespace, timestamp): """Update or insert multiple documents into Solr docs may be any iterable """ if self.auto_commit_interval is not None: add_kwargs = { "commit": (self.auto_commit_interval == 0), "commitWithin...
Update or insert multiple documents into Solr docs may be any iterable
entailment
def remove(self, document_id, namespace, timestamp): """Removes documents from Solr The input is a python dictionary that represents a mongo document. """ self.solr.delete(id=u(document_id), commit=(self.auto_commit_interval == 0))
Removes documents from Solr The input is a python dictionary that represents a mongo document.
entailment
def _stream_search(self, query): """Helper method for iterating over Solr search results.""" for doc in self.solr.search(query, rows=100000000): if self.unique_key != "_id": doc["_id"] = doc.pop(self.unique_key) yield doc
Helper method for iterating over Solr search results.
entailment
def search(self, start_ts, end_ts): """Called to query Solr for documents in a time range.""" query = '_ts: [%s TO %s]' % (start_ts, end_ts) return self._stream_search(query)
Called to query Solr for documents in a time range.
entailment
def get_last_doc(self): """Returns the last document stored in the Solr engine. """ #search everything, sort by descending timestamp, return 1 row try: result = self.solr.search('*:*', sort='_ts desc', rows=1) except ValueError: return None for r ...
Returns the last document stored in the Solr engine.
entailment
def pbkdf2_single(password, salt, key_length, prf): '''Returns the result of the Password-Based Key Derivation Function 2 with a single iteration (i.e. count = 1). prf - a psuedorandom function See http://en.wikipedia.org/wiki/PBKDF2 ''' block_number = 0 result = b'' # The i...
Returns the result of the Password-Based Key Derivation Function 2 with a single iteration (i.e. count = 1). prf - a psuedorandom function See http://en.wikipedia.org/wiki/PBKDF2
entailment
def salsa20_8(B): '''Salsa 20/8 stream cypher; Used by BlockMix. See http://en.wikipedia.org/wiki/Salsa20''' # Create a working copy x = B[:] # Expanded form of this code. The expansion is significantly faster but # this is much easier to understand # ROUNDS = ( # (4, 0, 12, 7), (8, ...
Salsa 20/8 stream cypher; Used by BlockMix. See http://en.wikipedia.org/wiki/Salsa20
entailment
def blockmix_salsa8(BY, Yi, r): '''Blockmix; Used by SMix.''' start = (2 * r - 1) * 16 X = BY[start:start + 16] # BlockMix - 1 for i in xrange(0, 2 * r): # BlockMix - 2 for xi in xrange(0, 16): ...
Blockmix; Used by SMix.
entailment
def smix(B, Bi, r, N, V, X): '''SMix; a specific case of ROMix. See scrypt.pdf in the links above.''' X[:32 * r] = B[Bi:Bi + 32 * r] # ROMix - 1 for i in xrange(0, N): # ROMix - 2 aod = i * 32 * r # ROMix - 3 V[aod:aod...
SMix; a specific case of ROMix. See scrypt.pdf in the links above.
entailment
def hash(password, salt, N, r, p, dkLen): """Returns the result of the scrypt password-based key derivation function. Constraints: r * p < (2 ** 30) dkLen <= (((2 ** 32) - 1) * 32 N must be a power of 2 greater than 1 (eg. 2, 4, 8, 16, 32...) N, r, p must be positive ...
Returns the result of the scrypt password-based key derivation function. Constraints: r * p < (2 ** 30) dkLen <= (((2 ** 32) - 1) * 32 N must be a power of 2 greater than 1 (eg. 2, 4, 8, 16, 32...) N, r, p must be positive
entailment
def _load_get_attr(self, name): 'Return an internal attribute after ensuring the headers is loaded if necessary.' if self._mode in _allowed_read and self._N is None: self._read_header() return getattr(self, name)
Return an internal attribute after ensuring the headers is loaded if necessary.
entailment
def close(self): '''Close the underlying file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status ...
Close the underlying file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status upon closing.
entailment
def verify_file(fp, password): 'Returns whether a scrypt encrypted file is valid.' sf = ScryptFile(fp = fp, password = password) for line in sf: pass sf.close() return sf.valid
Returns whether a scrypt encrypted file is valid.
entailment
def readline(self, size = None): '''Next line from the decrypted file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF.''' if self.closed: raise Valu...
Next line from the decrypted file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF.
entailment
def _read_header(self): '''Read and parse the header and calculate derived keys.''' try: # Read the entire header header = self._fp.read(96) if len(header) != 96: raise InvalidScryptFileFormat("Incomplete header") # Magic number ...
Read and parse the header and calculate derived keys.
entailment
def read(self, size = None): '''Read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.''' ...
Read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.
entailment
def _write_header(self): 'Writes the header to the underlying file object.' header = b'scrypt' + CHR0 + struct.pack('>BII', int(math.log(self.N, 2)), self.r, self.p) + self.salt # Add the header checksum to the header checksum = hashlib.sha256(header).digest()[:16] header += ch...
Writes the header to the underlying file object.
entailment
def _finalize_write(self): 'Finishes any unencrypted bytes and writes the final checksum.' # Make sure we have written the header if not self._done_header: self._write_header() # Write the remaining decrypted part to disk block = self._crypto.encrypt(self._decrypted...
Finishes any unencrypted bytes and writes the final checksum.
entailment
def write(self, str): '''Write string str to the underlying file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.''' if self.closed: raise ValueError('File closed') if self._mode in _allowed_read: raise...
Write string str to the underlying file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.
entailment
def get_logger(logger_name): """ Return a logger with the specified name, creating it if necessary. """ # Use default global logger if logger_name is None: return __instance assert isinstance(logger_name, str), 'Logger name must be a string!' with __lock: if logger_name in...
Return a logger with the specified name, creating it if necessary.
entailment
def removeFile(file): """remove a file""" if "y" in speech.question("Are you sure you want to remove " + file + "? (Y/N): "): speech.speak("Removing " + file + " with the 'rm' command.") subprocess.call(["rm", "-r", file]) else: speech.speak("Okay, I won't remove " + file + ".")
remove a file
entailment
def copy(location): """copy file or directory at a given location; can be pasted later""" copyData = settings.getDataFile() copyFileLocation = os.path.abspath(location) copy = {"copyLocation": copyFileLocation} dataFile = open(copyData, "wb") pickle.dump(copy, dataFile) speech.speak(location + " copied successfu...
copy file or directory at a given location; can be pasted later
entailment
def paste(location): """paste a file or directory that has been previously copied""" copyData = settings.getDataFile() if not location: location = "." try: data = pickle.load(open(copyData, "rb")) speech.speak("Pasting " + data["copyLocation"] + " to current directory.") except: speech.fail("It doesn't loo...
paste a file or directory that has been previously copied
entailment
def add_zfs_apt_repository(): """ adds the ZFS repository """ with settings(hide('warnings', 'running', 'stdout'), warn_only=False, capture=True): sudo('DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get update') install_ubuntu_development_tools() apt_install(packages=['so...
adds the ZFS repository
entailment
def apt_install(**kwargs): """ installs a apt package """ for pkg in list(kwargs['packages']): if is_package_installed(distribution='ubuntu', pkg=pkg) is False: sudo("DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get install -y %s" % pkg) # if we didn't abort above, we shou...
installs a apt package
entailment
def apt_install_from_url(pkg_name, url, log=False): """ installs a pkg from a url p pkg_name: the name of the package to install p url: the full URL for the rpm package """ if is_package_installed(distribution='ubuntu', pkg=pkg_name) is False: if log: log_green( ...
installs a pkg from a url p pkg_name: the name of the package to install p url: the full URL for the rpm package
entailment
def apt_add_key(keyid, keyserver='keyserver.ubuntu.com', log=False): """ trust a new PGP key related to a apt-repository """ if log: log_green( 'trusting keyid %s from %s' % (keyid, keyserver) ) with settings(hide('warnings', 'running', 'stdout')): sudo('apt-key adv --key...
trust a new PGP key related to a apt-repository
entailment
def enable_apt_repositories(prefix, url, version, repositories): """ adds an apt repository """ with settings(hide('warnings', 'running', 'stdout'), warn_only=False, capture=True): sudo('apt-add-repository "%s %s %s %s"' % (prefix, url...
adds an apt repository
entailment
def install_gem(gem): """ install a particular gem """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=False, capture=True): # convert 0 into True, any errors will always raise an exception return not bool( run("gem install %s --no-rdoc --no...
install a particular gem
entailment
def install_python_module_locally(name): """ instals a python module using pip """ with settings(hide('everything'), warn_only=False, capture=True): # convert 0 into True, any errors will always raise an exception print(not bool(local('pip --quiet install %s' % name).return_cod...
instals a python module using pip
entailment
def is_package_installed(distribution, pkg): """ checks if a particular package is installed """ if ('centos' in distribution or 'el' in distribution or 'redhat' in distribution): return(is_rpm_package_installed(pkg)) if ('ubuntu' in distribution or 'debian' in d...
checks if a particular package is installed
entailment
def is_rpm_package_installed(pkg): """ checks if a particular rpm package is installed """ with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True, capture=True): result = sudo("rpm -q %s" % pkg) if result.return_code == 0: return True ...
checks if a particular rpm package is installed
entailment
def yum_install(**kwargs): """ installs a yum package """ if 'repo' in kwargs: repo = kwargs['repo'] for pkg in list(kwargs['packages']): if is_package_installed(distribution='el', pkg=pkg) is False: if 'repo' in locals(): log_green( ...
installs a yum package
entailment
def yum_group_install(**kwargs): """ instals a yum group """ for grp in list(kwargs['groups']): log_green("installing %s ..." % grp) if 'repo' in kwargs: repo = kwargs['repo'] sudo("yum groupinstall -y --quiet " "--enablerepo=%s '%s'" % (repo, grp)) ...
instals a yum group
entailment
def yum_install_from_url(pkg_name, url): """ installs a pkg from a url p pkg_name: the name of the package to install p url: the full URL for the rpm package """ if is_package_installed(distribution='el', pkg=pkg_name) is False: log_green( "installing %s from %s" % (pkg_n...
installs a pkg from a url p pkg_name: the name of the package to install p url: the full URL for the rpm package
entailment
def recherche(self, pattern, entete, in_all=False): """abstractSearch in fields of collection and reset rendering. Returns number of results. If in_all is True, call get_all before doing the search.""" if in_all: self.collection = self.get_all() self.collection.recher...
abstractSearch in fields of collection and reset rendering. Returns number of results. If in_all is True, call get_all before doing the search.
entailment
def launch_background_job(self, job, on_error=None, on_success=None): """Launch the callable job in background thread. Succes or failure are controlled by on_error and on_success """ if not self.main.mode_online: self.sortie_erreur_GUI( "Local mode activated. ...
Launch the callable job in background thread. Succes or failure are controlled by on_error and on_success
entailment
def filtre(liste_base, criteres) -> groups.Collection: """ Return a filter list, bases on criteres :param liste_base: Acces list :param criteres: Criteria { `attribut`:[valeurs,...] } """ def choisi(ac): for cat, li in criteres.items(): v = a...
Return a filter list, bases on criteres :param liste_base: Acces list :param criteres: Criteria { `attribut`:[valeurs,...] }
entailment
def load_remote_data(self, callback_etat=print): """ Load remote data. On succes, build base. On failure, raise :class:`~.Core.exceptions.StructureError`, :class:`~.Core.exceptions.ConnexionError` :param callback_etat: State renderer str , int , int -> None """ callback_...
Load remote data. On succes, build base. On failure, raise :class:`~.Core.exceptions.StructureError`, :class:`~.Core.exceptions.ConnexionError` :param callback_etat: State renderer str , int , int -> None
entailment
def _load_users(self): """Default implentation requires users from DB. Should setup `users` attribute""" r = sql.abstractRequetesSQL.get_users()() self.users = {d["id"]: dict(d) for d in r}
Default implentation requires users from DB. Should setup `users` attribute
entailment
def load_modules(self): """Should instance interfaces and set them to interface, following `modules`""" if self.INTERFACES_MODULE is None: raise NotImplementedError("A module containing interfaces modules " "should be setup in INTERFACES_MODULE !") ...
Should instance interfaces and set them to interface, following `modules`
entailment
def has_autolog(self, user_id): """ Read auto-connection parameters and returns local password or None """ try: with open("local/init", "rb") as f: s = f.read() s = security.protege_data(s, False) self.autolog = json.loads(s).ge...
Read auto-connection parameters and returns local password or None
entailment
def loggin(self, user_id, mdp, autolog): """Check mdp and return True it's ok""" r = sql.abstractRequetesSQL.check_mdp_user(user_id, mdp) if r(): # update auto-log params self.autolog[user_id] = autolog and mdp or False self.modules = self.users[user_id]["modu...
Check mdp and return True it's ok
entailment
def add_widget(self, w): """Convenience function""" if self.layout(): self.layout().addWidget(w) else: layout = QVBoxLayout(self) layout.addWidget(w)
Convenience function
entailment
def add_layout(self, l): """Convenience function""" if self.layout(): self.layout().addLayout(l) else: layout = QVBoxLayout(self) layout.addLayout(l)
Convenience function
entailment
def mkpad(items): ''' Find the length of the longest element of a list. Return that value + two. ''' pad = 0 stritems = [str(e) for e in items] # cast list to strings for e in stritems: index = stritems.index(e) if len(stritems[index]) > pad: pad = len(stritems[index...
Find the length of the longest element of a list. Return that value + two.
entailment
def mkcols(l, rows): ''' Compute the size of our columns by first making them a divisible of our row height and then splitting our list into smaller lists the size of the row height. ''' cols = [] base = 0 while len(l) > rows and len(l) % rows != 0: l.append("") for i in rang...
Compute the size of our columns by first making them a divisible of our row height and then splitting our list into smaller lists the size of the row height.
entailment
def mkrows(l, pad, width, height): ''' Compute the optimal number of rows based on our lists' largest element and our terminal size in columns and rows. Work out our maximum column number by dividing the width of the terminal by our largest element. While the length of our list is greater than...
Compute the optimal number of rows based on our lists' largest element and our terminal size in columns and rows. Work out our maximum column number by dividing the width of the terminal by our largest element. While the length of our list is greater than the total number of elements we can fit on...
entailment
def prtcols(items, vpad=6): ''' After computing the size of our rows and columns based on the terminal size and length of the largest element, use zip to aggregate our column lists into row lists and then iterate over the row lists and print them. ''' from os import get_terminal_size items =...
After computing the size of our rows and columns based on the terminal size and length of the largest element, use zip to aggregate our column lists into row lists and then iterate over the row lists and print them.
entailment
def cmd2list(cmd): ''' Executes a command through the operating system and returns the output as a list, or on error a string with the standard error. EXAMPLE: >>> from subprocess import Popen, PIPE >>> CMDout2array('ls -l') ''' p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True) stdout, ...
Executes a command through the operating system and returns the output as a list, or on error a string with the standard error. EXAMPLE: >>> from subprocess import Popen, PIPE >>> CMDout2array('ls -l')
entailment
def return_timer(self, name, status, timer): ''' Return a text formatted timer ''' timer_template = '%s %s %s : %s : %9s' t = str(timedelta(0, timer)).split(',')[-1].strip().split(':') #t = str(timedelta(0, timer)).split(':') if len(t) == 4: h, m, s = int(t[0])*24 + int(t[1]), i...
Return a text formatted timer
entailment
def print_timers(self): ''' PRINT EXECUTION TIMES FOR THE LIST OF PROGRAMS ''' self.timer += time() total_time = self.timer tmp = '* %s *' debug.log( '', '* '*29, tmp%(' '*51), tmp%('%s %s %s'%('Program Name'.ljust(20), 'Status'.ljust(7), 'Execute Ti...
PRINT EXECUTION TIMES FOR THE LIST OF PROGRAMS
entailment
def get_cmd(self): """ This function combines and return the commanline call of the program. """ cmd = [] if self.path is not None: if '/' in self.path and not os.path.exists(self.path): debug.log('Error: path contains / but does not exist: %s'%self.path) else: ...
This function combines and return the commanline call of the program.
entailment
def append_args(self, arg): """ This function appends the provided arguments to the program object. """ debug.log("Adding Arguments: %s"%(arg)) if isinstance(arg, (int,float)): self.args.append(str(arg)) if isinstance(arg, str): self.args.append(arg) if isinstance(arg, list): ...
This function appends the provided arguments to the program object.
entailment
def execute(self): """ This function Executes the program with set arguments. """ prog_cmd = self.get_cmd().strip() if prog_cmd == '': self.status = 'Failure' debug.log("Error: No program to execute for %s!"%self.name) debug.log(("Could not combine path and arguments into cm...
This function Executes the program with set arguments.
entailment
def wait(self, pattern='Done', interval=None, epatterns=['error','Error','STACK','Traceback']): """ This function will wait on a given pattern being shown on the last line of a given outputfile. OPTIONS pattern - The string pattern to recognise when a program ...
This function will wait on a given pattern being shown on the last line of a given outputfile. OPTIONS pattern - The string pattern to recognise when a program finished properly. interval - The amount of seconds to wait between checking the ...
entailment
def print_stdout(self): """ This function will read the standard out of the program and print it """ # First we check if the file we want to print does exists if self.wdir != '': stdout = "%s/%s"%(self.wdir, self.stdout) else: stdout = self.stdout if os.path.exists(...
This function will read the standard out of the program and print it
entailment
def find_out_var(self, varnames=[]): """ This function will read the standard out of the program, catch variables and return the values EG. #varname=value """ if self.wdir != '': stdout = "%s/%s"%(self.wdir, self.stdout) else: stdout = self.stdout res...
This function will read the standard out of the program, catch variables and return the values EG. #varname=value
entailment
def find_err_pattern(self, pattern): """ This function will read the standard error of the program and return a matching pattern if found. EG. prog_obj.FindErrPattern("Update of mySQL failed") """ if self.wdir != '': stderr = "%s/%s"%(self.wdir, self.stderr) else: ...
This function will read the standard error of the program and return a matching pattern if found. EG. prog_obj.FindErrPattern("Update of mySQL failed")
entailment
def find_out_pattern(self, pattern): """ This function will read the standard error of the program and return a matching pattern if found. EG. prog_obj.FindErrPattern("Update of mySQL failed") """ if self.wdir != '': stdout = "%s/%s"%(self.wdir, self.stdout) else: ...
This function will read the standard error of the program and return a matching pattern if found. EG. prog_obj.FindErrPattern("Update of mySQL failed")
entailment
def decode_nfo( buffer ): """Decodes a byte string in NFO format (beloved by PC scener groups) from DOS Code Page 437 to Unicode.""" assert utils.is_bytes( buffer ) return '\n'.join( [''.join( [CP437[y] for y in x] ) for x in buffer.split( b'\r\n' )] )
Decodes a byte string in NFO format (beloved by PC scener groups) from DOS Code Page 437 to Unicode.
entailment
def runner(self): """ Run the necessary methods in the correct order """ if os.path.isfile(self.report): self.report_parse() else: logging.info('Starting {} analysis pipeline'.format(self.analysistype)) # Create the objects to be used in the an...
Run the necessary methods in the correct order
entailment
def reporter(self): """ Runs the necessary methods to parse raw read outputs """ logging.info('Preparing reports') # Populate self.plusdict in order to reuse parsing code from an assembly-based method for sample in self.runmetadata.samples: self.plusdict[sampl...
Runs the necessary methods to parse raw read outputs
entailment
def profiler(self): """Creates a dictionary from the profile scheme(s)""" logging.info('Loading profiles') # Initialise variables profiledata = defaultdict(make_dict) reverse_profiledata = dict() profileset = set() # Find all the unique profiles to use with a set ...
Creates a dictionary from the profile scheme(s)
entailment
def sequencetyper(self): """Determines the sequence type of each strain based on comparisons to sequence type profiles""" logging.info('Performing sequence typing') for sample in self.runmetadata.samples: if sample.general.bestassemblyfile != 'NA': if type(sample[self...
Determines the sequence type of each strain based on comparisons to sequence type profiles
entailment
def mlstreporter(self): """ Parse the results into a report""" logging.info('Writing reports') # Initialise variables header_row = str() combinedrow = str() combined_header_row = str() reportdirset = set() mlst_dict = dict() # Populate a set of all...
Parse the results into a report
entailment
def report_parse(self): """ If the pipeline has previously been run on these data, instead of reading through the results, parse the report instead """ # Initialise lists report_strains = list() genus_list = list() if self.analysistype == 'mlst': ...
If the pipeline has previously been run on these data, instead of reading through the results, parse the report instead
entailment
def guess_type(filename, **kwargs): """ Utility function to call classes based on filename extension. Just usefull if you are reading the file and don't know file extension. You can pass kwargs and these args are passed to class only if they are used in class. """ extension = os.path.splitext(f...
Utility function to call classes based on filename extension. Just usefull if you are reading the file and don't know file extension. You can pass kwargs and these args are passed to class only if they are used in class.
entailment
def get_gene_seqs(database_path, gene): """ This function takes the database path and a gene name as inputs and returns the gene sequence contained in the file given by the gene name """ gene_path = database_path + "/" + gene + ".fsa" gene_seq = "" # Open fasta file with open(gene_path)...
This function takes the database path and a gene name as inputs and returns the gene sequence contained in the file given by the gene name
entailment
def get_db_mutations(mut_db_path, gene_list, res_stop_codons): """ This function opens the file resistenss-overview.txt, and reads the content into a dict of dicts. The dict will contain information about all known mutations given in the database. This dict is returned. """ # Open resistens-ove...
This function opens the file resistenss-overview.txt, and reads the content into a dict of dicts. The dict will contain information about all known mutations given in the database. This dict is returned.
entailment
def KMA(inputfile_1, gene_list, kma_db, out_path, sample_name, min_cov, mapping_path): """ This function is called when KMA is the method of choice. The function calls kma externally and waits for it to finish. The kma output files with the prefixes .res and .aln are parsed throught to obtain the...
This function is called when KMA is the method of choice. The function calls kma externally and waits for it to finish. The kma output files with the prefixes .res and .aln are parsed throught to obtain the required alignment informations. The subject and query sequences as well as the start and sto...
entailment
def find_best_sequence(hits_found, specie_path, gene, silent_N_flag): """ This function takes the list hits_found as argument. This contains all hits found for the blast search of one gene. A hit includes the subjct sequence, the query, and the start and stop position of the allignment correspond...
This function takes the list hits_found as argument. This contains all hits found for the blast search of one gene. A hit includes the subjct sequence, the query, and the start and stop position of the allignment corresponding to the subject sequence. This function finds the best hit by concatinatin...
entailment
def find_mismatches(gene, sbjct_start, sbjct_seq, qry_seq, alternative_overlaps = []): """ This function finds mis matches between two sequeces. Depending on the the sequence type either the function find_codon_mismatches or find_nucleotid_mismatches are called, if the sequences contains both a pr...
This function finds mis matches between two sequeces. Depending on the the sequence type either the function find_codon_mismatches or find_nucleotid_mismatches are called, if the sequences contains both a promoter and a coding region both functions are called. The function can also call it self if al...
entailment
def find_nucleotid_mismatches(sbjct_start, sbjct_seq, qry_seq, promoter = False): """ This function takes two alligned sequence (subject and query), and the position on the subject where the alignment starts. The sequences are compared one nucleotide at a time. If mis matches are found they are ...
This function takes two alligned sequence (subject and query), and the position on the subject where the alignment starts. The sequences are compared one nucleotide at a time. If mis matches are found they are saved. If a gap is found the function find_nuc_indel is called to find the entire indel and...
entailment
def find_nuc_indel(gapped_seq, indel_seq): """ This function finds the entire indel missing in from a gapped sequence compared to the indel_seqeunce. It is assumes that the sequences start with the first position of the gap. """ ref_indel = indel_seq[0] for j in range(1,len(gapped_seq)): ...
This function finds the entire indel missing in from a gapped sequence compared to the indel_seqeunce. It is assumes that the sequences start with the first position of the gap.
entailment
def aa(codon): """ This function converts a codon to an amino acid. If the codon is not valid an error message is given, or else, the amino acid is returned. """ codon = codon.upper() aa = {"ATT": "I", "ATC": "I", "ATA": "I", "CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L", "TTA": "L...
This function converts a codon to an amino acid. If the codon is not valid an error message is given, or else, the amino acid is returned.
entailment
def get_codon(seq, codon_no, start_offset): """ This function takes a sequece and a codon number and returns the codon found in the sequence at that position """ seq = seq.replace("-","") codon_start_pos = int(codon_no - 1)*3 - start_offset codon = seq[codon_start_pos:codon_start_pos + 3] ...
This function takes a sequece and a codon number and returns the codon found in the sequence at that position
entailment
def name_insertion(sbjct_seq, codon_no, sbjct_nucs, aa_alt, start_offset): """ This function is used to name a insertion mutation based on the HGVS recommendation. """ start_codon_no = codon_no - 1 if len(sbjct_nucs) == 3: start_codon_no = codon_no start_codon = get_codon(sbjct_seq...
This function is used to name a insertion mutation based on the HGVS recommendation.
entailment
def name_indel_mutation(sbjct_seq, indel, sbjct_rf_indel, qry_rf_indel, codon_no, mut, start_offset): """ This function serves to name the individual mutations dependently on the type of the mutation. """ # Get the subject and query sequences without gaps sbjct_nucs = sbjct_rf_indel.replace("-"...
This function serves to name the individual mutations dependently on the type of the mutation.
entailment
def get_inframe_gap(seq, nucs_needed = 3): """ This funtion takes a sequnece starting with a gap or the complementary seqeuence to the gap, and the number of nucleotides that the seqeunce should contain in order to maintain the correct reading frame. The sequence is gone through and the number of ...
This funtion takes a sequnece starting with a gap or the complementary seqeuence to the gap, and the number of nucleotides that the seqeunce should contain in order to maintain the correct reading frame. The sequence is gone through and the number of non-gap characters are counted. When the number ha...
entailment
def get_indels(sbjct_seq, qry_seq, start_pos): """ This function uses regex to find inserts and deletions in sequences given as arguments. A list of these indels are returned. The list includes, type of mutations(ins/del), subject codon no of found mutation, subject sequence position, insert/delet...
This function uses regex to find inserts and deletions in sequences given as arguments. A list of these indels are returned. The list includes, type of mutations(ins/del), subject codon no of found mutation, subject sequence position, insert/deletions nucleotide sequence, and the affected qry codon n...
entailment
def find_codon_mismatches(sbjct_start, sbjct_seq, qry_seq): """ This function takes two alligned sequence (subject and query), and the position on the subject where the alignment starts. The sequences are compared codon by codon. If a mis matches is found it is saved in 'mis_matches'. If a gap is ...
This function takes two alligned sequence (subject and query), and the position on the subject where the alignment starts. The sequences are compared codon by codon. If a mis matches is found it is saved in 'mis_matches'. If a gap is found the function get_inframe_gap is used to find the indel sequen...
entailment
def write_output(gene, gene_name, mis_matches, known_mutations, known_stop_codon, unknown_flag, GENES): """ This function takes a gene name a list of mis matches found betreewn subject and query of this gene, the dictionary of known mutation in the point finder database, and the flag telling weather th...
This function takes a gene name a list of mis matches found betreewn subject and query of this gene, the dictionary of known mutation in the point finder database, and the flag telling weather the user wants unknown mutations to be reported. All mis matches are looked up in the known mutation dict to se if...
entailment
def merge(self): """Try merging all the bravado_core models across all loaded APIs. If duplicates occur, use the same bravado-core model to represent each, so bravado-core won't treat them as different models when passing them from one PyMacaron client stub to an other or when returning ...
Try merging all the bravado_core models across all loaded APIs. If duplicates occur, use the same bravado-core model to represent each, so bravado-core won't treat them as different models when passing them from one PyMacaron client stub to an other or when returning them via the PyMacar...
entailment
def _cmp_models(self, m1, m2): """Compare two models from different swagger APIs and tell if they are equal (return 0), or not (return != 0)""" # Don't alter m1/m2 by mistake m1 = copy.deepcopy(m1) m2 = copy.deepcopy(m2) # Remove keys added by bravado-core def _...
Compare two models from different swagger APIs and tell if they are equal (return 0), or not (return != 0)
entailment
def sync(self): """Sync this model with latest data on the saltant server. Note that in addition to returning the updated object, it also updates the existing object. Returns: :class:`saltant.models.base_task_type.BaseTaskType`: This task type instance after...
Sync this model with latest data on the saltant server. Note that in addition to returning the updated object, it also updates the existing object. Returns: :class:`saltant.models.base_task_type.BaseTaskType`: This task type instance after syncing.
entailment
def create( self, name, command_to_run, description="", environment_variables=None, required_arguments=None, required_arguments_default_values=None, extra_data_to_post=None, ): """Create a task type. Args: name (str): The n...
Create a task type. Args: name (str): The name of the task. command_to_run (str): The command to run to execute the task. description (str, optional): The description of the task type. environment_variables (list, optional): The environment variab...
entailment
def put( self, id, name, description, command_to_run, environment_variables, required_arguments, required_arguments_default_values, extra_data_to_put=None, ): """Updates a task type on the saltant server. Args: id (...
Updates a task type on the saltant server. Args: id (int): The ID of the task type. name (str): The name of the task type. description (str): The description of the task type. command_to_run (str): The command to run to execute the task. environment_v...
entailment
def response_data_to_model_instance(self, response_data): """Convert response data to a task type model. Args: response_data (dict): The data from the request's response. Returns: :class:`saltant.models.base_task_type.BaseTaskType`: A model instance repr...
Convert response data to a task type model. Args: response_data (dict): The data from the request's response. Returns: :class:`saltant.models.base_task_type.BaseTaskType`: A model instance representing the task type from the reponse data.
entailment
def regression(): """ Run regression testing - lint and then run all tests. """ # HACK: Start using hitchbuildpy to get around this. Command("touch", DIR.project.joinpath("pathquery", "__init__.py").abspath()).run() storybook = _storybook({}).only_uninherited() #storybook.with_params(**{"pyt...
Run regression testing - lint and then run all tests.
entailment
def deploy(version): """ Deploy to pypi as specified version. """ NAME = "pathquery" git = Command("git").in_dir(DIR.project) version_file = DIR.project.joinpath("VERSION") old_version = version_file.bytes().decode('utf8') if version_file.bytes().decode("utf8") != version: DIR.pr...
Deploy to pypi as specified version.
entailment
def hvenvup(package, directory): """ Install a new version of a package in the hitch venv. """ pip = Command(DIR.gen.joinpath("hvenv", "bin", "pip")) pip("uninstall", package, "-y").run() pip("install", DIR.project.joinpath(directory).abspath()).run()
Install a new version of a package in the hitch venv.
entailment
def set_up(self): """Set up your applications and the test environment.""" self.path.state = self.path.gen.joinpath("state") if self.path.state.exists(): self.path.state.rmtree(ignore_errors=True) self.path.state.mkdir() if self.path.gen.joinpath("q").exists(): ...
Set up your applications and the test environment.
entailment
def is_valid(self): """ Validates single instance. Returns boolean value and store errors in self.errors """ self.errors = [] for field in self.get_all_field_names_declared_by_user(): getattr(type(self), field).is_valid(self, type(self), field) field_erro...
Validates single instance. Returns boolean value and store errors in self.errors
entailment
def main(self): """ Run the analyses using the inputted values for forward and reverse read length. However, if not all strains pass the quality thresholds, continue to periodically run the analyses on these incomplete strains until either all strains are complete, or the sequencing run ...
Run the analyses using the inputted values for forward and reverse read length. However, if not all strains pass the quality thresholds, continue to periodically run the analyses on these incomplete strains until either all strains are complete, or the sequencing run is finished
entailment