code
stringlengths
1
18.2k
def annotate_diamond(records, diamond_path): ''' Retrieve scientific names and lineages for taxon IDs in Diamond output Returns taxonomically annotated SeqRecords with modified description attributes ''' contigs_metadata = {} with open(diamond_path) as diamond_tax_fh: for line in diamond_tax_fh: contig, taxid, evalue =...
def filter_taxa(records, taxids, unclassified=False, discard=False): ''' Selectively include or discard specified taxon IDs from tictax annotated FASTA/Qs Filters all children of specified taxon IDs Returns subset of input SeqRecords Taxon IDs of 1 and 2 are considered unclassified ''' taxids = set(taxids) kept_records...
def matrix(records, scafstats_path): ''' Generate taxonomic count matrix from BBMap scafstats output to tictax classified contigs ''' ncbi = ete3.NCBITaxa() # # Single file version # contigs_lineages = {r.id: r.description.strip().partition(' ')[2].split('|')[2] for r in records} # df = pd.read_csv(scafstats_path, sep=...
def do( self, params ): """Perform the number of repetitions we want. The results returned will be a list of the results dicts generated by the repeated experiments. The metedata for each experiment will include an entry :attr:`RepeatedExperiment.REPETITIONS` for the number of repetitions that occurred (which will be t...
= N # add the results to ours results.extend(res) return results
def add_view_permissions(sender, verbosity, **kwargs): """ This post_syncdb/post_migrate hooks takes care of adding a view permission too all our content types. """ from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission for content_type in ContentType.objects.all():...
def main(self, x): """ This works by keeping a history of 'window_len' elements and the sum of them. Every clock last element will be subtracted and new added to the sum. More good infos: https://www.dsprelated.com/showarticle/58.php :param x: input to average :return: averaged output :rtype: Sfix """ # divide by windo...
def build_slide(filename: Path, pptx_template: Path, master_slide_idx: int, slide_layout_idx: int, font_size: int, dst_dir: Path, font_name: str, slide_txt_alignment: str = "left") -> Path: """Builds a powerpoint presentation using data read from a yaml file :param filename: path to the yaml file :param pptx_template: ...
- (400000 * 2)) } slide_layout = prs.slide_masters[master_slide_idx].slide_layouts[slide_layout_idx] with filename.open() as f: yml_data = yaml.load(f) lyrics = yml_data.get('lyrics') hard_font_size = yml_data.get("font_size") if hard_font_size: msg = f"NOTE: Setting the font size to {hard_font_size} for {filename}" cl...
filename.with_suffix(".pptx") dst_path = Path(dst_dir, dst_file.name) if dst_path.exists(): dst_path.unlink() prs.save(str(dst_path)) return dst_path
def pick_master_slide(master_slides_path: Path) -> Path: """Returns path to a master slide. If argument is a directory, returns a randomly chosen file in the directory and if argument is a file, returns the argument itself :return: path to chosen master slide """ if master_slides_path.is_file(): return master_slides_pa...
def validate_yaml_file(schema: dict, yaml_file: Path): """Validates yaml data against the defined schema :param schema: schema in json format :param yaml_file: path to yaml_file :return: """ with yaml_file.open() as f: data = yaml.load(f) jsonschema.validate(data, schema)
def cli(yaml_paths, pptx_template_path, font_size, master_slide_idx, slide_layout_idx, dst_dir, font_name, slide_txt_alignment, validate): """ A powerpoint builder https://github.com/sukujgrg/pptx-builder-from-yaml """ dst_dir = Path(dst_dir) pptx_template_path = Path(pptx_template_path) pptx_template = pick_master_sli...
def exec_rule(self, rule): """ :rule : the Ant class of rule, which must have a start() function """ print("running Rule: {0}".format(rule.__name__)) ant = rule() ant.start()
def addTextOut(self, text): """add black text""" self._currentColor = self._black self.addText(text)
def addTextErr(self, text): """add red text""" self._currentColor = self._red self.addText(text)
def addText(self, text): """append text in the chosen color""" # move to the end of the doc self.moveCursor(QtGui.QTextCursor.End) # insert the text self.setTextColor(self._currentColor) self.textCursor().insertText(text)
def contextMenuEvent(self, event): """ Add menu action: * 'Show line numbers' * 'Save to file' """ menu = QtWidgets.QTextEdit.createStandardContextMenu(self) # create max.lines spin box: w = QtWidgets.QWidget() l = QtWidgets.QHBoxLayout() w.setLayout(l) e = QtWidgets.QSpinBox() e.setRange(1, 1e6) e.setValue(self.MAXLIN...
def generate_form(model, only=None, meta=None): """ Generate WTForm based on SQLAlchemy table :param model: SQLAlchemy sa.Table :param only: list or set of columns that should be used in final form :param meta: Meta class with settings for form :return: WTForm object """ fields = OrderedDict() if meta: fields['Meta'] =...
def main(self, din, reload): """ :param din: bit in :param reload: when True, reloads the initial value to LFSR :return: current LFSR value (integer), CRC is correct if this is 0. Once it gets to 0 it STAYS 0, reset needed. """ if reload: lfsr = self.INIT_GALOIS else: lfsr = self.lfsr out = lfsr & 0x8000 next = ((lfsr ...
def main(argString=None): """The main function of the module.. Here are the steps for duplicated samples: 1. Prints the options. 2. Reads the ``map`` file to gather marker's position (:py:func:`readMAP`). 3. Reads the ``tfam`` file (:py:func:`readTFAM`). 4. Finds the unique markers using the ``map`` file (:py:func:`fin...
of each of the duplicated markers (:py:func:`computeStatistics`). 10. Prints the problematic duplicated markers with a file containing the summary of the statistics (completion and pairwise concordance) (:py:func:`printProblems`). 11. Print the pairwise concordance in a file (matrices) (:py:func:`printConcordance`). 12...
mapF = readMAP(args.tfile + ".map", args.out) # Reading the tfam file logger.info("Reading TFAM file") tfam = readTFAM(args.tfile + ".tfam") # Find unique snps logger.info("Finding unique SNPs") uniqueSNPs = findUniques(mapF) # Process the TPED file logger.info("Reading TPED file") tped, duplicatedSNPs = processTPED(un...
We print the TPED and TFAM for the duplicated SNPs logger.info("Printing duplicated SNPs TPED and TFAM files") printDuplicatedTPEDandTFAM(tped, args.tfile + ".tfam", args.out) # Computing the frequency of the duplicated SNPs logger.info("Computing duplicated SNPs' frequencies") dupSNPsFreq = computeFrequency(args.out +...
tfam, duplicatedSNPs, args.out, chosenSNPs, comp, conc, snpsToComplete, args.tfile + ".tfam", args.snp_completion_threshold, args.snp_concordance_threshold, ) # Creates the final tped logger.info("Writing final TPED and TFAM file") createFinalTPEDandTFAM(newTPED, args.out + ".unique_snps", args.out, snpToRemove)
def createFinalTPEDandTFAM(tped, toReadPrefix, prefix, snpToRemove): """Creates the final TPED and TFAM. :param tped: a representation of the ``tped`` of duplicated markers. :param toReadPrefix: the prefix of the unique files. :param prefix: the prefix of the output files. :param snpToRemove: the markers to remove. :ty...
try: shutil.copy(toReadPrefix + ".tfam", prefix + ".final.tfam") except IOError: msg = "%(toReadPrefix)s.tfam: can't copy file to " \ "%(prefix)s.final.tfam" % locals() raise ProgramError(msg) # Next, copy the tped, and append at the end try: shutil.copy(toReadPrefix + ".tped", prefix + ".final.tped") except IOError: m...
def createAndCleanTPED(tped, tfam, snps, prefix, chosenSNPs, completion, concordance, snpsToComplete, tfamFileName, completionT, concordanceT): """Complete a TPED for duplicated SNPs. :param tped: a representation of the ``tped`` of duplicated markers. :param tfam: a representation of the ``tfam``. :param snps: the pos...
completion: numpy.array :type concordance: dict :type snpsToComplete: set :type tfamFileName: str :type completionT: float :type concordanceT: float :returns: a tuple containing the new ``tped`` after completion (:py:class:`numpy.array` as the first element, and the index of the markers that will need to be rid of (:py...
the genotypes are all the same. If the chosen one was not called, but the other ones were, then we complete the chosen one with the genotypes for the others (assuming that they are all the same). If there is a difference between the genotypes, it is zeroed out for the chosen marker. """ zeroedOutFile = None try: zeroed...
ProgramError(msg) notGoodEnoughSnps = set() # Split the tped in 'snpInfo' and 'genotypes' snpInfo = tped[:, :4] genotypes = tped[:, 4:] # The sed of index we want to get rid of at the end getRidOfIndex = set() for snpID, indexes in snps.iteritems(): if snpID not in snpsToComplete: # We don't want to complete this SNP, ...
in indexes: if index not in indexesToRemove: indexesToKeep.append(index) # Getting the chosen SNP chosenOne = chosenSNPs[snpID] if chosenOne not in set(indexesToKeep): # The chosen SNP is not a good SNP, so we go to next SNP logger.warning(" - {} chosen but not good enough".format( snpInfo[chosenOne, 1], )) continue # ...
they are all the same # len > 1 means discordance (might need to flip) # Just need to check the order of the alleles possibleAlleles = [ set() for k in xrange(len(uniqueCleanedCurGenotypes)) ] for k, geno in enumerate(uniqueCleanedCurGenotypes): possibleAlleles[k] |= set(geno.split(" ")) allEqual = True for k in xrange...
uniqueCleanedCurGenotypes[0] # We keep only the chose one for index in indexes: if index != chosenOne: getRidOfIndex.add(index) print >>removedFile, snpInfo[index, 1] # Writing the not good enough file for item in notGoodEnoughSnps: print >>notGoodEnoughFile, "\t".join(item) # Closing the output files zeroedOutFile.clo...
def chooseBestSnps(tped, snps, trueCompletion, trueConcordance, prefix): """Choose the best duplicates according to the completion and concordance. :param tped: a representation of the ``tped`` of duplicated markers. :param snps: the position of the duplicated markers in the ``tped``. :param trueCompletion: the complet...
It starts by computing the completion of each markers (dividing the number of calls divided by the total number of genotypes). Then, for each of the duplicated markers, we choose the best one according to completion and concordance (see explanation in :py:func:`DupSamples.duplicated_samples.chooseBestDuplicates` for mo...
completion[indexes] # Sorting those completion sortedCompletionInsexes = np.argsort(currCompletion) # Getting the concordance concordance = np.true_divide(trueConcordance[snp][0], trueConcordance[snp][1]) currConcordance = [[] for i in xrange(len(indexes))] for i in xrange(len(indexes)): indexToKeep = list(set(range(le...
chosenIndex = random.choice(list(toConsider)) break nbToCheck += 1 if chosenIndex is None: msg = "Could not choose the best snp ID" raise ProgramError(msg) # Printing the chosen SNPs print >>chosenFile, tped[indexes[chosenIndex], 1] # Printing the excluded SNPs for i, index in enumerate(indexes): if i != chosenIndex: p...
def computeFrequency(prefix, outPrefix): """Computes the frequency of the SNPs using Plink. :param prefix: the prefix of the input files. :param outPrefix: the prefix of the output files. :type prefix: str :type outPrefix: str :returns: a :py:class:`dict` containing the frequency of each marker. Start by computing the ...
# Checking the column titles for columnTitle in ["SNP", "MAF", "A1", "A2"]: if columnTitle not in headerIndex: msg = "%(outPrefix)s.duplicated_snps.frq: no " \ "column called %(columnTitle)s" % locals() raise ProgramError(msg) else: # This is data snpName = row[headerIndex["SNP"]] maf = row[headerIndex["MAF"]] a1 = row...
def printDuplicatedTPEDandTFAM(tped, tfamFileName, outPrefix): """Print the duplicated SNPs TPED and TFAM. :param tped: a representation of the ``tped`` of duplicated markers. :param tfamFileName: the name of the original ``tfam`` file. :param outPrefix: the output prefix. :type tped: numpy.array :type tfamFileName: st...
def printConcordance(concordance, prefix, tped, snps): """Print the concordance. :param concordance: the concordance. :param prefix: the prefix if the output files. :param tped: a representation of the ``tped`` of duplicated markers. :param snps: the position of the duplicated markers in the ``tped``. :type concordance...
msg = "%s: can't write file" % prefix + ".concordance" raise ProgramError(msg) for snpID in concordance.iterkeys(): print >>outFile, "#" + "\t".join( list(snpID) + list(tped[snps[snpID], 1]) ) # Doing the division true_concordance = np.true_divide(concordance[snpID][0], concordance[snpID][1]) output = StringIO.StringIO...
def printProblems(completion, concordance, tped, snps, frequencies, prefix, diffFreq): """Print the statistics. :param completion: the completion of each duplicated markers. :param concordance: the pairwise concordance between duplicated markers. :param tped: a representation of the ``tped`` of duplicated markers. :par...
allele are used to be certain that two duplicated markers are exactly the same marker (and not a tri-allelic one, for example). For each duplicated markers: 1. Constructs the set of available alleles for the first marker. 2. Constructs the set of available alleles for the second marker. 3. If the two sets are different...
set the status to ``homo_hetero``. If there are no allele in common, we try to flip one. If the new sets have one allele in common, we set the status to ``homo_hetero_flip``. 5. If the sets of available alleles are the same (without flip), we check the frequency and the minor alleles. If the minor allele is different, ...
= None try: outSummary = open(prefix + ".summary", "w") except IOError: msg = "%s: can't write file" % prefix + ".summary" raise ProgramError # Prints the header of the summary file print >>outSummary, "\t".join(["chr", "pos", "name", "alleles", "status", "% completion", "completion", "mean concordance"]) # The data st...
if "0" in alleles: alleles.remove("0") for j in xrange(i+1, len(indexes)): otherIndex = indexes[j] otherSnpName = tped[otherIndex, 1] # The frequency of the other SNP otherSnpFreq, otherMafAlleles = frequencies[otherSnpName] # Checking the alleles for genotype in np.unique(tped[otherIndex, 4:]): otherAlleles |= set(gen...
frequency if mafAlleles[0] != otherMafAlleles[0]: # They don't have the same minor allele status.append("diff_minor_allele") otherSnpNameWithProblem.add(otherSnpName) elif math.fabs(snpFreq - otherSnpFreq) > diffFreq: # They don't have same frequency status.append("diff_frequency") otherSnpNameWithProblem.add(otherSnpN...
outProblems = None try: outProblems = open(prefix + ".problems", "w") except IOError: msg = "%s: can't write file" % prefix + ".problems" raise ProgramError # Printing the header of the problem file... print >>outProblems, "\t".join(["chr", "pos", "name", "status"]) for snpID in problems.iterkeys(): toPrint = list(snpI...
def computeStatistics(tped, tfam, snps): """Computes the completion and concordance of each SNPs. :param tped: a representation of the ``tped``. :param tfam: a representation of the ``tfam`` :param snps: the position of the duplicated markers in the ``tped``. :type tped: numpy.array :type tfam: list :type snps: dict :r...
math:: Concordance_{i,j} = \\frac{ ||g \\in G_i \\cup G_j \\textrm{ where } g_i = g_j \\neq 0|| }{ ||g \\in G_i \\cup G_j \\textrm{ where } g \\neq 0|| } Hence, we only computes the numerators and denominators of the completion and concordance, for future reference. .. note:: When the genotypes are not comparable, the ...
4] == "2") noSexIndex = np.where(tfam[:, 4] == "0") for snpID, indexes in snps.iteritems(): nbDup = len(indexes) currGenotypes = tped[indexes, 4:] chromosome, position = snpID # if chromosome == "24": # # Remove the heterozygous men # menToRemove = getIndexOfHeteroMen(currGenotypes, menIndex) # # Remove the women and t...
nullGenotypeIndexes = np.where( np.any(currGenotypes[[i, j]] == "0 0", 0) ) subGenotypes = np.delete( currGenotypes, nullGenotypeIndexes, 1, ) # Finding the errors in the subseted genotypes errorIndexes = np.where(subGenotypes[i] != subGenotypes[j])[0] nbDiff = len(errorIndexes) for k in errorIndexes: # Getting the gen...
= nbTot concordance[snpID][1][j, i] = nbTot for snpID in concordance.iterkeys(): for i in range(len(concordance[snpID][0])): concordance[snpID][0][i, i] = 1 concordance[snpID][1][i, i] = 1 return completion, concordance
def getIndexOfHeteroMen(genotypes, menIndex): """Get the indexes of heterozygous men. :param genotypes: the genotypes of everybody. :param menIndex: the indexes of the men (for the genotypes). :type genotypes: numpy.array :type menIndex: numpy.array :returns: a :py:class:`numpy.array` containing the indexes of the geno...
def flipGenotype(genotype): """Flips a genotype. :param genotype: the genotype to flip. :type genotype: set :returns: the new flipped genotype (as a :py:class:`set`) .. testsetup:: from pyGenClean.DupSNPs.duplicated_snps import flipGenotype .. doctest:: >>> flipGenotype({"A", "T"}) set(['A', 'T']) >>> flipGenotype({"C"...
def processTPED(uniqueSNPs, mapF, fileName, tfam, prefix): """Process the TPED file. :param uniqueSNPs: the unique markers. :param mapF: a representation of the ``map`` file. :param fileName: the name of the ``tped`` file. :param tfam: the name of the ``tfam`` file. :param prefix: the prefix of all the files. :type uni...
prefix + ".unique_snps.tfam" raise ProgramError(msg) tped = [] updatedSNPs = defaultdict(list) outputFile = None try: outputFile = open(prefix + ".unique_snps.tped", "w") except IOError: msg = "%s: can't write to file" % prefix + ".unique_snps.tped" raise ProgramError(msg) nbSNP = 0 with open(fileName, 'r') as inputFil...
ProgramError(msg) tped = np.array(tped) return tped, updatedSNPs
def findUniques(mapF): """Finds the unique markers in a MAP. :param mapF: representation of a ``map`` file. :type mapF: list :returns: a :py:class:`dict` containing unique markers (according to their genomic localisation). """ uSNPs = {} dSNPs = defaultdict(list) for i, row in enumerate(mapF): chromosome = row[0] posit...
def readTFAM(fileName): """Reads the TFAM file. :param fileName: the name of the ``tfam`` file. :type fileName: str :returns: a representation the ``tfam`` file (:py:class:`numpy.array`). """ # Saving the TFAM file tfam = None with open(fileName, 'r') as inputFile: tfam = [ tuple(i.rstrip("\r\n").split("\t")) for i in ...
def readMAP(fileName, prefix): """Reads the MAP file. :param fileName: the name of the ``map`` file. :type fileName: str :returns: a list of tuples, representing the ``map`` file. While reading the ``map`` file, it saves a file (``prefix.duplicated_marker_names``) containing the name of the unique duplicated markers. "...
open(prefix + ".duplicated_marker_names", "w") except IOError: msg = "{}.duplicated_marker_names: can't write file".format(prefix) raise ProgramError(msg) for i in xrange(len(marker_names)): print >>duplicated_marker_names, "\t".join([marker_names[i]] + map(str, marker_chr_pos[i])) duplicated_marker_names.close() retur...
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t...
1)): msg = "snp-completion-threshold: must be between 0 and 1 " \ "(not %f)" % args.snp_completion_threshold raise ProgramError(msg) # Checking the difference in frequency if (args.frequency_difference < 0) or (args.frequency_difference > 1): msg = ("{}: maximal frequency difference: value must be between 0 and " "1 (i...
def findMenu(self, title): """ find a menu with a given title @type title: string @param title: English title of the menu @rtype: QMenu @return: None if no menu was found, else the menu with title """ # See also http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#differences-between-pyqt-and-qt #title =...
def insertMenuBefore(self, before_menu, new_menu): """ Insert a menu after another menu in the menubar @type: before_menu QMenu instance or title string of menu @param before_menu: menu which should be after the newly inserted menu @rtype: QAction instance @return: action for inserted menu """ if isinstance(before_menu...
def makeWidget(self): """ Return a single widget that should be placed in the second tree column. The widget must be given three attributes: ========== ============================================================ sigChanged a signal that is emitted when the widget's value is changed value a function that returns the va...
'dec': False, 'siPrefix': False, 'suffix': '' } defs.update(opts) if 'limits' in opts: defs['bounds'] = opts['limits'] w = SpinBox() w.setOpts(**defs) w.sigChanged = w.sigValueChanged w.sigChanging = w.sigValueChanging elif t == 'bool': w = QtWidgets.QCheckBox() w.sigChanged = w.toggled w.value = w.isChecked w.setValue...
self.hideWidget = False else: raise Exception("Unknown type '%s'" % asUnicode(t)) return w
def updateDisplayLabel(self, value=None): """Update the display label to reflect the value of the parameter.""" if value is None: value = self.param.value() opts = self.param.opts if isinstance(self.widget, QtWidgets.QAbstractSpinBox): text = asUnicode(self.widget.lineEdit().text()) elif isinstance(self.widget, QtWidge...
def widgetValueChanging(self, *args): """ Called when the widget's value is changing, but not finalized. For example: editing text before pressing enter or changing focus. """ # This is a bit sketchy: assume the last argument of each signal is # the value.. self.param.sigValueChanging.emit(self.param, args[-1])
def selected(self, sel): """Called when this item has been selected (sel=True) OR deselected (sel=False)""" ParameterItem.selected(self, sel) if self.widget is None: return if sel and self.param.writable(): self.showEditor() elif self.hideWidget: self.hideEditor()
def limitsChanged(self, param, limits): """Called when the parameter's limits have changed""" ParameterItem.limitsChanged(self, param, limits) t = self.param.opts['type'] if t == 'int' or t == 'float': self.widget.setOpts(bounds=limits) else: return
def treeWidgetChanged(self): """Called when this item is added or removed from a tree.""" ParameterItem.treeWidgetChanged(self) # add all widgets for this item into the tree if self.widget is not None: tree = self.treeWidget() if tree is None: return tree.setItemWidget(self, 1, self.layoutWidget) self.displayLabel.hide...
def optsChanged(self, param, opts): """Called when any options are changed that are not name, value, default, or limits""" # print "opts changed:", opts ParameterItem.optsChanged(self, param, opts) w = self.widget if 'readonly' in opts: self.updateDefaultBtn() if isinstance(w, (QtWidgets.QCheckBox, ColorButton)): w.set...
def addChanged(self): """Called when "add new" combo is changed The parameter MUST have an 'addNew' method defined. """ if self.addWidget.currentIndex() == 0: return typ = asUnicode(self.addWidget.currentText()) self.param.addNew(typ) self.addWidget.setCurrentIndex(0)
def zotero_inline_tags(parser, token): """ Render an inline formset of tags. Usage: {% zotero_inline_tags formset[ option] %} option = "all" | "media" | "formset" """ args = token.split_contents() length = len(args) if length == 2: rendered_node = RenderedAllNode(args[1]) elif length == 3 and args[2].lower() == u'all':...
def detect_format(fn, format_bytes=50, verbose=False, *args, **kwargs): """Detect Amira file format (AmiraMesh or HyperSurface) :param str fn: file name :param int format_bytes: number of bytes in which to search for the format [default: 50] :param bool verbose: verbose (default) or not :return str file_format: either ...
def get_header(fn, file_format, header_bytes=20000, verbose=False, *args, **kwargs): """Apply rules for detecting the boundary of the header :param str fn: file name :param str file_format: either ``AmiraMesh`` or ``HyperSurface`` :param int header_bytes: number of bytes in which to search for the header [default: 2000...
return data
def parse_header(data, verbose=False, *args, **kwargs): """Parse the data using the grammar specified in this module :param str data: delimited data to be parsed for metadata :return list parsed_data: structured metadata """ # the parser if verbose: print >> sys.stderr, "Creating parser object..." parser = Parser(amira...
def get_parsed_data(fn, *args, **kwargs): """All above functions as a single function :param str fn: file name :return list parsed_data: structured metadata """ file_format = detect_format(fn, *args, **kwargs) data = get_header(fn, file_format, *args, **kwargs) parsed_data = parse_header(data, *args, **kwargs) return p...
def create_parser(): """Creat a commandline parser for epubcheck :return Argumentparser: """ parser = ArgumentParser( prog='epubcheck', description="EpubCheck v%s - Validate your ebooks" % __version__ ) # Arguments parser.add_argument( 'path', nargs='?', default=getcwd(), help="Path to EPUB-file or folder for batch val...
def main(argv=None): """Command line app main function. :param list | None argv: Overrides command options (for libuse or testing) """ parser = create_parser() args = parser.parse_args() if argv is None else parser.parse_args(argv) if not os.path.exists(args.path): sys.exit(0) all_valid = True single = os.path.isfile(a...
def A_cylinder(D, L): r'''Returns the surface area of a cylinder. .. math:: A = \pi D L + 2\cdot \frac{\pi D^2}{4} Parameters ---------- D : float Diameter of the cylinder, [m] L : float Length of the cylinder, [m] Returns ------- A : float Surface area [m] Examples -------- >>> A_cylinder(0.01, .1) 0.00329867228626928...
def V_hollow_cylinder(Di, Do, L): r'''Returns the volume of a hollow cylinder. .. math:: V = \frac{\pi D_o^2}{4}L - L\frac{\pi D_i^2}{4} Parameters ---------- Di : float Diameter of the hollow in the cylinder, [m] Do : float Diameter of the exterior of the cylinder, [m] L : float Length of the cylinder, [m] Returns ---...
def V_multiple_hole_cylinder(Do, L, holes): r'''Returns the solid volume of a cylinder with multiple cylindrical holes. Calculation will naively return a negative value or other impossible result if the number of cylinders added is physically impossible. .. math:: V = \frac{\pi D_o^2}{4}L - L\frac{\pi D_i^2}{4} Paramet...
def urlencode_no_plus(query, doseq=0): """Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the para...
but that's a minor nit - since the original implementation # allowed empty dicts that type of behavior probably should be # preserved for consistency except TypeError: ty,va,tb = sys.exc_info() raise TypeError, "not a valid non-string sequence or mapping object", tb l = [] if not doseq: # preserve old behavior for k, v...
this a sufficient test for sequence-ness? len(v) except TypeError: # not a sequence v = urllib.quote(str(v)) l.append(k + '=' + v) else: # loop over the sequence for elt in v: l.append(k + '=' + urllib.quote(str(elt))) return '&'.join(l)
def handler500(request, template_name='500.html'): """ 500 error handler. Templates: `500.html` Context: MEDIA_URL Path of static media (e.g. "media.example.org") STATIC_URL """ t = loader.get_template(template_name) # You need to create a 500.html template. return http.HttpResponseServerError(t.render(Context({ 'MEDIA...
def handler404(request, template_name='404.html'): """ 404 error handler. Templates: `404.html` Context: MEDIA_URL Path of static media (e.g. "media.example.org") STATIC_URL """ t = loader.get_template(template_name) # You need to create a 404.html template. return http.HttpResponseNotFound(t.render(Context({ 'MEDIA_UR...
def pmxbot_excuse(self, rest): "Provide a convenient excuse" args = rest.split(' ')[:2] parser = argparse.ArgumentParser() parser.add_argument('word', nargs="?") parser.add_argument('index', type=int, nargs="?") args = parser.parse_args(args) if not args.word: return self.get() return self.find(args.word, args.index)
def load_with_scipy(file, data_name): import scipy.io """ Loads data from a netcdf file. Parameters ---------- file : string or file-like The name of the netcdf file to open. data_name : string The name of the data to extract from the netcdf file. Returns ------- data : ndarray The desired data from the netcdf file as ...
def cholesky(A, ordering_method='default', return_type=RETURN_P_L, use_long=False): ''' P A P' = L L' ''' logger.debug('Calculating cholesky decomposition for matrix {!r} with ordering method {}, return type {} and use_long {}.'.format(A, ordering_method, return_type, use_long)) ## check input return_types = (RETURN_L,...
cholesky(A, ordering_method=ordering_method, return_type=return_type, use_long=True) else: raise except sksparse.cholmod.CholmodNotPositiveDefiniteError as e: raise util.math.matrix.NoPositiveDefiniteMatrixError(A, 'Row/column {} makes matrix not positive definite.'.format(e.column)) del A ## calculate permutation matr...
and diagonal matrix {!r}.'.format(P, L, D)) return (L, D) else: logger.debug('Returning permutation matrix {!r}, lower triangular matrix {!r} and diagonal matrix {!r}.'.format(P, L, D)) return (P, L, D)
def _connect_database(config): """Create simple connection with Mongodb config comes with settings from .ini file. """ settings = config.registry.settings mongo_uri = "mongodb://localhost:27017" mongodb_name = "test" if settings.get("mongo_url"): mongo_uri = settings["mongo_url"] if settings.get("mongodb_name"): mongod...