text
stringlengths
81
112k
Finishes any unencrypted bytes and writes the final checksum. 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 pa...
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. def write(self, str): '''Write string str to the underlying file. Note that due to buffering, flush() or close() may be needed befor...
Return a logger with the specified name, creating it if necessary. 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...
remove a file 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 + ".")
copy file or directory at a given location; can be pasted later 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...
paste a file or directory that has been previously copied 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 ...
adds the ZFS repository 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() ...
installs a apt package 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 did...
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 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 ...
trust a new PGP key related to a apt-repository 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', 'runn...
adds an apt repository 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, ...
install a particular gem 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...
instals a python module using pip 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 --q...
checks if a particular package is installed 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'...
checks if a particular rpm package is installed 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...
installs a yum package 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_...
instals a yum group 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'"...
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 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 """ ...
abstractSearch in fields of collection and reset rendering. Returns number of results. If in_all is True, call get_all before doing the search. def recherche(self, pattern, entete, in_all=False): """abstractSearch in fields of collection and reset rendering. Returns number of results. ...
Launch the callable job in background thread. Succes or failure are controlled by on_error and on_success 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 ""...
Return a filter list, bases on criteres :param liste_base: Acces list :param criteres: Criteria { `attribut`:[valeurs,...] } def filtre(liste_base, criteres) -> groups.Collection: """ Return a filter list, bases on criteres :param liste_base: Acces list :param criteres...
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 def load_remote_data(self, callback_etat=print): """ Load remote data. On succes,...
Default implentation requires users from DB. Should setup `users` attribute 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}
Should instance interfaces and set them to interface, following `modules` 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 " ...
Read auto-connection parameters and returns local password or None 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.pr...
Check mdp and return True it's ok 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....
Convenience function def add_widget(self, w): """Convenience function""" if self.layout(): self.layout().addWidget(w) else: layout = QVBoxLayout(self) layout.addWidget(w)
Convenience function def add_layout(self, l): """Convenience function""" if self.layout(): self.layout().addLayout(l) else: layout = QVBoxLayout(self) layout.addLayout(l)
Find the length of the longest element of a list. Return that value + two. 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)...
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. 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 ...
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...
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. def prtcols(items, vpad=6): ''' After computing the size of our rows and columns based ...
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') def cmd2list(cmd): ''' Executes a command through the operating system and returns the output ...
Return a text formatted timer 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, ...
PRINT EXECUTION TIMES FOR THE LIST OF PROGRAMS 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...
This function combines and return the commanline call of the program. 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:...
This function appends the provided arguments to the program object. 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...
This function Executes the program with set arguments. 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) ...
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 ...
This function will read the standard out of the program and print it 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.stdo...
This function will read the standard out of the program, catch variables and return the values EG. #varname=value 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 ...
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") def find_err_pattern(self, pattern): """ This function will read the standard error of the program and return a matching pattern i...
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") def find_out_pattern(self, pattern): """ This function will read the standard error of the program and return a matching pattern i...
Decodes a byte string in NFO format (beloved by PC scener groups) from DOS Code Page 437 to Unicode. 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( [CP...
Run the necessary methods in the correct order 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)) ...
Runs the necessary methods to parse raw read outputs 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 sel...
Creates a dictionary from the profile scheme(s) 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() ...
Determines the sequence type of each strain based on comparisons to sequence type profiles 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:...
Parse the results into a report 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(...
If the pipeline has previously been run on these data, instead of reading through the results, parse the report instead def report_parse(self): """ If the pipeline has previously been run on these data, instead of reading through the results, parse the report instead """ ...
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. def guess_type(filename, **kwargs): """ Utility function to call classes based on ...
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 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 gi...
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. def get_db_mutations(mut_db_path, gene_list, res_stop_codons): """ This function opens the file res...
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...
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...
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...
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...
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. def find_nuc_indel(gapped_seq, indel_seq): """ This function finds the entire indel missing in from a gapped sequence c...
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. 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. ...
This function takes a sequece and a codon number and returns the codon found in the sequence at that position 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("-",...
This function is used to name a insertion mutation based on the HGVS recommendation. 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 le...
This function serves to name the individual mutations dependently on the type of the mutation. 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. "...
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...
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...
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...
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...
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...
Compare two models from different swagger APIs and tell if they are equal (return 0), or not (return != 0) 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 ...
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. def sync(self): ...
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...
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...
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. def re...
Run regression testing - lint and then run all tests. 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({}...
Deploy to pypi as specified version. 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().dec...
Install a new version of a package in the hitch venv. 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).abspat...
Set up your applications and the test environment. 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() ...
Validates single instance. Returns boolean value and store errors in self.errors 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(): g...
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 def main(self): ...
Run the typing methods def methods(self): """ Run the typing methods """ self.contamination_detection() ReportImage(self, 'confindr') self.run_genesippr() ReportImage(self, 'genesippr') self.run_sixteens() self.run_mash() self.run_gdcs() ...
Calculate the levels of contamination in the reads def contamination_detection(self): """ Calculate the levels of contamination in the reads """ self.qualityobject = quality.Quality(self) self.qualityobject.contamination_finder(input_path=self.sequencepath, ...
Run the genesippr analyses def run_genesippr(self): """ Run the genesippr analyses """ GeneSippr(args=self, pipelinecommit=self.commit, startingtime=self.starttime, scriptpath=self.homepath, analysistype='genesippr'...
Run the 16S analyses using the filtered database def run_sixteens(self): """ Run the 16S analyses using the filtered database """ SixteensFull(args=self, pipelinecommit=self.commit, startingtime=self.starttime, scriptpath=se...
Run MASH to determine the closest refseq genomes def run_mash(self): """ Run MASH to determine the closest refseq genomes """ self.pipeline = True mash.Mash(inputobject=self, analysistype='mash')
Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the sample.general.bestassemblyfile != 'NA' def complete(self): """ Determine if the analyses of the strains are complete e.g. there are no missing GDCS genes, and the sample.general.bestas...
Use this decorator to prevent an operation from being executed when the related uri resource is still in use. The parent_object must contain: * a request * with a registry.queryUtility(IReferencer) :raises pyramid.httpexceptions.HTTPConflict: Signals that we don't want to delete ...
Use this decorator to prevent an operation from being executed when the related uri resource is still in use. The request must contain a registry.queryUtility(IReferencer) :raises pyramid.httpexceptions.HTTPConflict: Signals that we don't want to delete a certain URI because it's still in use somewh...
allows adding `protected=True` to a view_config` def protected_view(view, info): """allows adding `protected=True` to a view_config`""" if info.options.get('protected'): def wrapper_view(context, request): response = _advice(request) if response is not None: ret...
Create tables if they don't exist def syncdb(pool=None): """ Create tables if they don't exist """ from flask_philo_sqlalchemy.schema import Base # noqa from flask_philo_sqlalchemy.orm import BaseModel # noqa from flask_philo_sqlalchemy.connection import create_pool if pool is None: ...
checks if a given package is installed on pip def checkInstalledPip(package, speak=True, speakSimilar=True): """checks if a given package is installed on pip""" packages = sorted([i.key for i in pip.get_installed_distributions()]) installed = package in packages similar = None if not installed: ...
checks if a given package is installed on homebrew def checkInstalledBrew(package, similar=True, speak=True, speakSimilar=True): """checks if a given package is installed on homebrew""" packages = subprocess.check_output(['brew', 'list']).split() installed = package in packages similar = [] if not...
Connnexion informations : remote_credences for remote acces OR local_path for local access def init_module(remote_credences=None,local_path=None): """Connnexion informations : remote_credences for remote acces OR local_path for local access""" if remote_credences is not None: RemoteConnexion.HOST = rem...
Create emmpt DB according to the given scheme : dict { table : [ (column_name, column_type), .. ]} Usefull at installation of application (and for developement) def cree_local_DB(scheme): """Create emmpt DB according to the given scheme : dict { table : [ (column_name, column_type), .. ]} Usefull at instal...
Execute one or many requests requete_SQL may be a tuple(requete,args) or a list of such tuples Return the result or a list of results def execute(self, requete_SQL): """Execute one or many requests requete_SQL may be a tuple(requete,args) or a list of such tuples Return the resu...
Placeholders for fields names and value binds def placeholders(cls,dic): """Placeholders for fields names and value binds""" keys = [str(x) for x in dic] entete = ",".join(keys) placeholders = ",".join(cls.named_style.format(x) for x in keys) entete = f"({entete})" place...
Renvoie un dictionnaire dont les champs dont compatibles avec SQL Utilise Json. Attention à None : il faut laisser None et non pas null def jsonise(dic): """Renvoie un dictionnaire dont les champs dont compatibles avec SQL Utilise Json. Attention à None : il faut laisser None et non pas null"""...
Insert row from datas :param table: Safe table name :param datas: List of dicts. :param avoid_conflict: Allows ignoring error if already exists (do nothing then) :return: def insert(table, datas, avoid_conflict=False): """ Insert row from datas :param table: Safe table...
Update row with Id from table. Set fields given by dic. def update(cls,table, dic, Id): """ Update row with Id from table. Set fields given by dic.""" if dic: req = "UPDATE {table} SET {SET} WHERE id = " + cls.named_style.format('__id') + " RETURNING * " r = abstractRequetesSQL...
Create ONE row from dic and returns the entry created def cree(table, dic, avoid_conflict=False): """ Create ONE row from dic and returns the entry created """ if avoid_conflict: req = """ INSERT INTO {table} {ENTETE_INSERT} VALUES {BIND_INSERT} ON CONFLICT DO NOTHING RETURNING *""" ...
Remove entries matchin given condition kwargs is a dict of column name : value , with length ONE. def supprime(cls,table, **kwargs): """ Remove entries matchin given condition kwargs is a dict of column name : value , with length ONE. """ assert len(kwargs) == 1 field,...
Enumerate the children of the given object, as would be visible and utilized by dispatch. def trace(self, context, obj): """Enumerate the children of the given object, as would be visible and utilized by dispatch.""" root = obj if isroutine(obj): yield Crumb(self, root, endpoint=True, handler=obj, optio...