_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q2300
generic_filename
train
def generic_filename(path): ''' Extract filename of given path os-indepently, taking care of known path separators. :param path: path :return: filename :rtype: str or unicode (depending on given path) ''' for sep in common_path_separators: if sep in path: _, path = ...
python
{ "resource": "" }
q2301
clean_restricted_chars
train
def clean_restricted_chars(path, restricted_chars=restricted_chars): ''' Get path without restricted characters. :param path: path :return: path without restricted characters :rtype: str or unicode (depending on given path) ''' for character in restricted_chars: path = path.replace(...
python
{ "resource": "" }
q2302
check_forbidden_filename
train
def check_forbidden_filename(filename, destiny_os=os.name, restricted_names=restricted_names): ''' Get if given filename is forbidden for current OS or filesystem. :param filename: :param destiny_os: destination operative system :param fs_en...
python
{ "resource": "" }
q2303
check_path
train
def check_path(path, base, os_sep=os.sep): ''' Check if both given paths are equal. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :type base: str :return: wether two path are equal or not ...
python
{ "resource": "" }
q2304
check_base
train
def check_base(path, base, os_sep=os.sep): ''' Check if given absolute path is under or given base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :return: wether path is under given base or no...
python
{ "resource": "" }
q2305
check_under_base
train
def check_under_base(path, base, os_sep=os.sep): ''' Check if given absolute path is under given base. :param path: absolute path :type path: str :param base: absolute base path :type base: str :param os_sep: path separator, defaults to os.sep :return: wether file is under given base or...
python
{ "resource": "" }
q2306
secure_filename
train
def secure_filename(path, destiny_os=os.name, fs_encoding=compat.FS_ENCODING): ''' Get rid of parent path components and special filenames. If path is invalid or protected, return empty string. :param path: unsafe path, only basename will be used :type: str :param destiny_os: destination opera...
python
{ "resource": "" }
q2307
alternative_filename
train
def alternative_filename(filename, attempt=None): ''' Generates an alternative version of given filename. If an number attempt parameter is given, will be used on the alternative name, a random value will be used otherwise. :param filename: original filename :param attempt: optional attempt nu...
python
{ "resource": "" }
q2308
scandir
train
def scandir(path, app=None): ''' Config-aware scandir. Currently, only aware of ``exclude_fnc``. :param path: absolute path :type path: str :param app: flask application :type app: flask.Flask or None :returns: filtered scandir entries :rtype: iterator ''' exclude = app and app....
python
{ "resource": "" }
q2309
Node.link
train
def link(self): ''' Get last widget with place "entry-link". :returns: widget on entry-link (ideally a link one) :rtype: namedtuple instance ''' link = None for widget in self.widgets: if widget.place == 'entry-link': link = widget ...
python
{ "resource": "" }
q2310
Node.can_remove
train
def can_remove(self): ''' Get if current node can be removed based on app config's directory_remove. :returns: True if current node can be removed, False otherwise. :rtype: bool ''' dirbase = self.app.config["directory_remove"] return bool(dirbase and che...
python
{ "resource": "" }
q2311
Node.parent
train
def parent(self): ''' Get parent node if available based on app config's directory_base. :returns: parent object if available :rtype: Node instance or None ''' if check_path(self.path, self.app.config['directory_base']): return None parent = os.path.d...
python
{ "resource": "" }
q2312
Node.ancestors
train
def ancestors(self): ''' Get list of ancestors until app config's directory_base is reached. :returns: list of ancestors starting from nearest. :rtype: list of Node objects ''' ancestors = [] parent = self.parent while parent: ancestors.append...
python
{ "resource": "" }
q2313
Node.modified
train
def modified(self): ''' Get human-readable last modification date-time. :returns: iso9008-like date-time string (without timezone) :rtype: str ''' try: dt = datetime.datetime.fromtimestamp(self.stats.st_mtime) return dt.strftime('%Y.%m.%d %H:%M:%S...
python
{ "resource": "" }
q2314
Node.from_urlpath
train
def from_urlpath(cls, path, app=None): ''' Alternative constructor which accepts a path as taken from URL and uses the given app or the current app config to get the real path. If class has attribute `generic` set to True, `directory_class` or `file_class` will be used as type. ...
python
{ "resource": "" }
q2315
WhisperFinder._find_paths
train
def _find_paths(self, current_dir, patterns): """Recursively generates absolute paths whose components underneath current_dir match the corresponding pattern in patterns""" pattern = patterns[0] patterns = patterns[1:] has_wildcard = is_pattern(pattern) using_glob...
python
{ "resource": "" }
q2316
union_overlapping
train
def union_overlapping(intervals): """Union any overlapping intervals in the given set.""" disjoint_intervals = [] for interval in intervals: if disjoint_intervals and disjoint_intervals[-1].overlaps(interval): disjoint_intervals[-1] = disjoint_intervals[-1].union(interval) else:...
python
{ "resource": "" }
q2317
recurse
train
def recurse(query, index): """ Recursively walk across paths, adding leaves to the index as they're found. """ for node in app.store.find(query): if node.is_leaf: index.add(node.path) else: recurse('{0}.*'.format(node.path), index)
python
{ "resource": "" }
q2318
__archive_fetch
train
def __archive_fetch(fh, archive, fromTime, untilTime): """ Fetch data from a single archive. Note that checks for validity of the time period requested happen above this level so it's possible to wrap around the archive on a read and request data older than the archive's retention """ fromInterval = int( fromTime -...
python
{ "resource": "" }
q2319
merge
train
def merge(path_from, path_to): """ Merges the data from one whisper file into another. Each file must have the same archive configuration """ fh_from = open(path_from, 'rb') fh_to = open(path_to, 'rb+') return file_merge(fh_from, fh_to)
python
{ "resource": "" }
q2320
diff
train
def diff(path_from, path_to, ignore_empty = False): """ Compare two whisper databases. Each file must have the same archive configuration """ fh_from = open(path_from, 'rb') fh_to = open(path_to, 'rb') diffs = file_diff(fh_from, fh_to, ignore_empty) fh_to.close() fh_from.close() return diffs
python
{ "resource": "" }
q2321
DataStore.add_data
train
def add_data(self, path, time_info, data, exprs): """ Stores data before it can be put into a time series """ # Dont add if empty if not nonempty(data): for d in self.data[path]: if nonempty(d['values']): return # Add data ...
python
{ "resource": "" }
q2322
CarbonLinkPool.select_host
train
def select_host(self, metric): """ Returns the carbon host that has data for the given metric. """ key = self.keyfunc(metric) nodes = [] servers = set() for node in self.hash_ring.get_nodes(key): server, instance = node if server in servers...
python
{ "resource": "" }
q2323
safeArgs
train
def safeArgs(args): """Iterate over valid, finite values in an iterable. Skip any items that are None, NaN, or infinite. """ return (arg for arg in args if arg is not None and not math.isnan(arg) and not math.isinf(arg))
python
{ "resource": "" }
q2324
format_units
train
def format_units(v, step=None, system="si", units=None): """Format the given value in standardized units. ``system`` is either 'binary' or 'si' For more info, see: http://en.wikipedia.org/wiki/SI_prefix http://en.wikipedia.org/wiki/Binary_prefix """ if v is None: return 0, ...
python
{ "resource": "" }
q2325
_AxisTics.checkFinite
train
def checkFinite(value, name='value'): """Check that value is a finite number. If it is, return it. If not, raise GraphError describing the problem, using name in the error message. """ if math.isnan(value): raise GraphError('Encountered NaN %s' % (name,)) eli...
python
{ "resource": "" }
q2326
_AxisTics.reconcileLimits
train
def reconcileLimits(self): """If self.minValue is not less than self.maxValue, fix the problem. If self.minValue is not less than self.maxValue, adjust self.minValue and/or self.maxValue (depending on which was not specified explicitly by the user) to make self.minValue < self.m...
python
{ "resource": "" }
q2327
_AxisTics.applySettings
train
def applySettings(self, axisMin=None, axisMax=None, axisLimit=None): """Apply the specified settings to this axis. Set self.minValue, self.minValueSource, self.maxValue, self.maxValueSource, and self.axisLimit reasonably based on the parameters provided. Arguments: axi...
python
{ "resource": "" }
q2328
_AxisTics.makeLabel
train
def makeLabel(self, value): """Create a label for the specified value. Create a label string containing the value and its units (if any), based on the values of self.step, self.span, and self.unitSystem. """ value, prefix = format_units(value, self.step, ...
python
{ "resource": "" }
q2329
_LinearAxisTics.generateSteps
train
def generateSteps(self, minStep): """Generate allowed steps with step >= minStep in increasing order.""" self.checkFinite(minStep) if self.binary: base = 2.0 mantissas = [1.0] exponent = math.floor(math.log(minStep, 2) - EPSILON) else: bas...
python
{ "resource": "" }
q2330
_LinearAxisTics.computeSlop
train
def computeSlop(self, step, divisor): """Compute the slop that would result from step and divisor. Return the slop, or None if this combination can't cover the full range. See chooseStep() for the definition of "slop". """ bottom = step * math.floor(self.minValue / float(step) ...
python
{ "resource": "" }
q2331
_LinearAxisTics.chooseStep
train
def chooseStep(self, divisors=None, binary=False): """Choose a nice, pretty size for the steps between axis labels. Our main constraint is that the number of divisions must be taken from the divisors list. We pick a number of divisions and a step size that minimizes the amount of whites...
python
{ "resource": "" }
q2332
formatPathExpressions
train
def formatPathExpressions(seriesList): """ Returns a comma-separated list of unique path expressions. """ pathExpressions = sorted(set([s.pathExpression for s in seriesList])) return ','.join(pathExpressions)
python
{ "resource": "" }
q2333
rangeOfSeries
train
def rangeOfSeries(requestContext, *seriesLists): """ Takes a wildcard seriesList. Distills down a set of inputs into the range of the series Example:: &target=rangeOfSeries(Server*.connections.total) """ if not seriesLists or not any(seriesLists): return [] seriesList, sta...
python
{ "resource": "" }
q2334
percentileOfSeries
train
def percentileOfSeries(requestContext, seriesList, n, interpolate=False): """ percentileOfSeries returns a single series which is composed of the n-percentile values taken across a wildcard series at each point. Unless `interpolate` is set to True, percentile values are actual values contained in on...
python
{ "resource": "" }
q2335
weightedAverage
train
def weightedAverage(requestContext, seriesListAvg, seriesListWeight, *nodes): """ Takes a series of average values and a series of weights and produces a weighted average for all values. The corresponding values should share one or more zero-indexed nodes. Example:: &target=weightedAverag...
python
{ "resource": "" }
q2336
scale
train
def scale(requestContext, seriesList, factor): """ Takes one metric or a wildcard seriesList followed by a constant, and multiplies the datapoint by the constant provided at each point. Example:: &target=scale(Server.instance01.threads.busy,10) &target=scale(Server.instance*.threads.bu...
python
{ "resource": "" }
q2337
scaleToSeconds
train
def scaleToSeconds(requestContext, seriesList, seconds): """ Takes one metric or a wildcard seriesList and returns "value per seconds" where seconds is a last argument to this functions. Useful in conjunction with derivative or integral function if you want to normalize its result to a known resolu...
python
{ "resource": "" }
q2338
pow
train
def pow(requestContext, seriesList, factor): """ Takes one metric or a wildcard seriesList followed by a constant, and raises the datapoint by the power of the constant provided at each point. Example:: &target=pow(Server.instance01.threads.busy,10) &target=pow(Server.instance*.threads...
python
{ "resource": "" }
q2339
powSeries
train
def powSeries(requestContext, *seriesLists): """ Takes two or more series and pows their points. A constant line may be used. Example:: &target=powSeries(Server.instance01.app.requests, Server.instance01.app.replies) """ if not seriesLists or not any(seriesLi...
python
{ "resource": "" }
q2340
squareRoot
train
def squareRoot(requestContext, seriesList): """ Takes one metric or a wildcard seriesList, and computes the square root of each datapoint. Example:: &target=squareRoot(Server.instance01.threads.busy) """ for series in seriesList: series.name = "squareRoot(%s)" % (series.name) ...
python
{ "resource": "" }
q2341
absolute
train
def absolute(requestContext, seriesList): """ Takes one metric or a wildcard seriesList and applies the mathematical abs function to each datapoint transforming it to its absolute value. Example:: &target=absolute(Server.instance01.threads.busy) &target=absolute(Server.instance*.thread...
python
{ "resource": "" }
q2342
offset
train
def offset(requestContext, seriesList, factor): """ Takes one metric or a wildcard seriesList followed by a constant, and adds the constant to each datapoint. Example:: &target=offset(Server.instance01.threads.busy,10) """ for series in seriesList: series.name = "offset(%s,%g)...
python
{ "resource": "" }
q2343
offsetToZero
train
def offsetToZero(requestContext, seriesList): """ Offsets a metric or wildcard seriesList by subtracting the minimum value in the series from each datapoint. Useful to compare different series where the values in each series may be higher or lower on average but you're only interested in the re...
python
{ "resource": "" }
q2344
consolidateBy
train
def consolidateBy(requestContext, seriesList, consolidationFunc): """ Takes one metric or a wildcard seriesList and a consolidation function name. Valid function names are 'sum', 'average', 'min', and 'max'. When a graph is drawn where width of the graph size in pixels is smaller than the numb...
python
{ "resource": "" }
q2345
integral
train
def integral(requestContext, seriesList): """ This will show the sum over time, sort of like a continuous addition function. Useful for finding totals or trends in metrics that are collected per minute. Example:: &target=integral(company.sales.perMinute) This would start at zero on th...
python
{ "resource": "" }
q2346
areaBetween
train
def areaBetween(requestContext, *seriesLists): """ Draws the vertical area in between the two series in seriesList. Useful for visualizing a range such as the minimum and maximum latency for a service. areaBetween expects **exactly one argument** that results in exactly two series (see example belo...
python
{ "resource": "" }
q2347
alias
train
def alias(requestContext, seriesList, newName): """ Takes one metric or a wildcard seriesList and a string in quotes. Prints the string instead of the metric name in the legend. Example:: &target=alias(Sales.widgets.largeBlue,"Large Blue Widgets") """ try: seriesList.name = ne...
python
{ "resource": "" }
q2348
_getFirstPathExpression
train
def _getFirstPathExpression(name): """Returns the first metric path in an expression.""" tokens = grammar.parseString(name) pathExpression = None while pathExpression is None: if tokens.pathExpression: pathExpression = tokens.pathExpression elif tokens.expression: ...
python
{ "resource": "" }
q2349
alpha
train
def alpha(requestContext, seriesList, alpha): """ Assigns the given alpha transparency setting to the series. Takes a float value between 0 and 1. """ for series in seriesList: series.options['alpha'] = alpha return seriesList
python
{ "resource": "" }
q2350
color
train
def color(requestContext, seriesList, theColor): """ Assigns the given color to the seriesList Example:: &target=color(collectd.hostname.cpu.0.user, 'green') &target=color(collectd.hostname.cpu.0.system, 'ff0000') &target=color(collectd.hostname.cpu.0.idle, 'gray') &target=...
python
{ "resource": "" }
q2351
logarithm
train
def logarithm(requestContext, seriesList, base=10): """ Takes one metric or a wildcard seriesList, a base, and draws the y-axis in logarithmic format. If base is omitted, the function defaults to base 10. Example:: &target=log(carbon.agents.hostname.avgUpdateTime,2) """ results = [] ...
python
{ "resource": "" }
q2352
maximumBelow
train
def maximumBelow(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by a constant n. Draws only the metrics with a maximum value below n. Example:: &target=maximumBelow(system.interface.eth*.packetsSent,1000) This would only display interfaces which alw...
python
{ "resource": "" }
q2353
minimumBelow
train
def minimumBelow(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by a constant n. Draws only the metrics with a minimum value below n. Example:: &target=minimumBelow(system.interface.eth*.packetsSent,1000) This would only display interfaces which sen...
python
{ "resource": "" }
q2354
highestMax
train
def highestMax(requestContext, seriesList, n=1): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the N metrics with the highest maximum value in the time period specified. Example:: &target=highestMax(server*.instance*.threads....
python
{ "resource": "" }
q2355
currentAbove
train
def currentAbove(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the metrics whose value is above N at the end of the time period specified. Example:: &target=currentAbove(server*.instance*.thread...
python
{ "resource": "" }
q2356
averageAbove
train
def averageAbove(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the metrics with an average value above N for the time period specified. Example:: &target=averageAbove(server*.instance*.threads.b...
python
{ "resource": "" }
q2357
nPercentile
train
def nPercentile(requestContext, seriesList, n): """Returns n-percent of each series in the seriesList.""" assert n, 'The requested percent is required to be greater than 0' results = [] for s in seriesList: # Create a sorted copy of the TimeSeries excluding None values in the # values l...
python
{ "resource": "" }
q2358
averageOutsidePercentile
train
def averageOutsidePercentile(requestContext, seriesList, n): """ Removes functions lying inside an average percentile interval """ averages = [safeAvg(s) for s in seriesList] if n < 50: n = 100 - n lowPercentile = _getPercentile(averages, 100 - n) highPercentile = _getPercentile(av...
python
{ "resource": "" }
q2359
removeBetweenPercentile
train
def removeBetweenPercentile(requestContext, seriesList, n): """ Removes lines who do not have an value lying in the x-percentile of all the values at a moment """ if n < 50: n = 100 - n transposed = list(zip_longest(*seriesList)) lowPercentiles = [_getPercentile(col, 100-n) for col...
python
{ "resource": "" }
q2360
removeAboveValue
train
def removeAboveValue(requestContext, seriesList, n): """ Removes data above the given threshold from the series or list of series provided. Values above this threshold are assigned a value of None. """ for s in seriesList: s.name = 'removeAboveValue(%s, %g)' % (s.name, n) s.pathExpre...
python
{ "resource": "" }
q2361
removeBelowPercentile
train
def removeBelowPercentile(requestContext, seriesList, n): """ Removes data below the nth percentile from the series or list of series provided. Values below this percentile are assigned a value of None. """ for s in seriesList: s.name = 'removeBelowPercentile(%s, %g)' % (s.name, n) s...
python
{ "resource": "" }
q2362
useSeriesAbove
train
def useSeriesAbove(requestContext, seriesList, value, search, replace): """ Compares the maximum of each series against the given `value`. If the series maximum is greater than `value`, the regular expression search and replace is applied against the series name to plot a related metric. e.g. given...
python
{ "resource": "" }
q2363
secondYAxis
train
def secondYAxis(requestContext, seriesList): """ Graph the series on the secondary Y axis. """ for series in seriesList: series.options['secondYAxis'] = True series.name = 'secondYAxis(%s)' % series.name return seriesList
python
{ "resource": "" }
q2364
holtWintersForecast
train
def holtWintersForecast(requestContext, seriesList): """ Performs a Holt-Winters forecast using the series as input data. Data from one week previous to the series is used to bootstrap the initial forecast. """ previewSeconds = 7 * 86400 # 7 days # ignore original data and pull new, including o...
python
{ "resource": "" }
q2365
holtWintersConfidenceBands
train
def holtWintersConfidenceBands(requestContext, seriesList, delta=3): """ Performs a Holt-Winters forecast using the series as input data and plots upper and lower bands with the predicted forecast deviations. """ previewSeconds = 7 * 86400 # 7 days # ignore original data and pull new, including...
python
{ "resource": "" }
q2366
holtWintersAberration
train
def holtWintersAberration(requestContext, seriesList, delta=3): """ Performs a Holt-Winters forecast using the series as input data and plots the positive or negative deviation of the series data from the forecast. """ results = [] for series in seriesList: confidenceBands = holtWintersC...
python
{ "resource": "" }
q2367
holtWintersConfidenceArea
train
def holtWintersConfidenceArea(requestContext, seriesList, delta=3): """ Performs a Holt-Winters forecast using the series as input data and plots the area between the upper and lower bands of the predicted forecast deviations. """ bands = holtWintersConfidenceBands(requestContext, seriesList, de...
python
{ "resource": "" }
q2368
linearRegressionAnalysis
train
def linearRegressionAnalysis(series): """ Returns factor and offset of linear regression function by least squares method. """ n = safeLen(series) sumI = sum([i for i, v in enumerate(series) if v is not None]) sumV = sum([v for i, v in enumerate(series) if v is not None]) sumII = sum([i...
python
{ "resource": "" }
q2369
linearRegression
train
def linearRegression(requestContext, seriesList, startSourceAt=None, endSourceAt=None): """ Graphs the liner regression function by least squares method. Takes one metric or a wildcard seriesList, followed by a quoted string with the time to start the line and another quoted string...
python
{ "resource": "" }
q2370
drawAsInfinite
train
def drawAsInfinite(requestContext, seriesList): """ Takes one metric or a wildcard seriesList. If the value is zero, draw the line at 0. If the value is above zero, draw the line at infinity. If the value is null or less than zero, do not draw the line. Useful for displaying on/off metrics, suc...
python
{ "resource": "" }
q2371
constantLine
train
def constantLine(requestContext, value): """ Takes a float F. Draws a horizontal line at value F across the graph. Example:: &target=constantLine(123.456) """ name = "constantLine(%s)" % str(value) start = int(epoch(requestContext['startTime'])) end = int(epoch(requestContext...
python
{ "resource": "" }
q2372
aggregateLine
train
def aggregateLine(requestContext, seriesList, func='avg'): """ Takes a metric or wildcard seriesList and draws a horizontal line based on the function applied to each series. Note: By default, the graphite renderer consolidates data points by averaging data points over time. If you are using the 'm...
python
{ "resource": "" }
q2373
verticalLine
train
def verticalLine(requestContext, ts, label=None, color=None): """ Takes a timestamp string ts. Draws a vertical line at the designated timestamp with optional 'label' and 'color'. Supported timestamp formats include both relative (e.g. -3h) and absolute (e.g. 16:00_20110501) strings, such as th...
python
{ "resource": "" }
q2374
transformNull
train
def transformNull(requestContext, seriesList, default=0, referenceSeries=None): """ Takes a metric or wildcard seriesList and replaces null values with the value specified by `default`. The value 0 used if not specified. The optional referenceSeries, if specified, is a metric or wildcard series lis...
python
{ "resource": "" }
q2375
countSeries
train
def countSeries(requestContext, *seriesLists): """ Draws a horizontal line representing the number of nodes found in the seriesList. Example:: &target=countSeries(carbon.agents.*.*) """ if not seriesLists or not any(seriesLists): series = constantLine(requestContext, 0).pop() ...
python
{ "resource": "" }
q2376
group
train
def group(requestContext, *seriesLists): """ Takes an arbitrary number of seriesLists and adds them to a single seriesList. This is used to pass multiple seriesLists to a function which only takes one. """ seriesGroup = [] for s in seriesLists: seriesGroup.extend(s) return serie...
python
{ "resource": "" }
q2377
groupByNode
train
def groupByNode(requestContext, seriesList, nodeNum, callback): """ Takes a serieslist and maps a callback to subgroups within as defined by a common node. Example:: &target=groupByNode(ganglia.by-function.*.*.cpu.load5,2,"sumSeries") Would return multiple series which are each the result...
python
{ "resource": "" }
q2378
groupByNodes
train
def groupByNodes(requestContext, seriesList, callback, *nodes): """ Takes a serieslist and maps a callback to subgroups within as defined by multiple nodes. Example:: &target=groupByNodes(ganglia.server*.*.cpu.load*,"sumSeries",1,4) Would return multiple series which are each the result o...
python
{ "resource": "" }
q2379
exclude
train
def exclude(requestContext, seriesList, pattern): """ Takes a metric or a wildcard seriesList, followed by a regular expression in double quotes. Excludes metrics that match the regular expression. Example:: &target=exclude(servers*.instance*.threads.busy,"server02") """ regex = re....
python
{ "resource": "" }
q2380
summarize
train
def summarize(requestContext, seriesList, intervalString, func='sum', alignToFrom=False): """ Summarize the data into interval buckets of a certain size. By default, the contents of each interval bucket are summed together. This is useful for counters where each increment represents a dis...
python
{ "resource": "" }
q2381
Medium.apply
train
def apply(self, model): """Set the defined medium on the given model.""" model.medium = {row.exchange: row.uptake for row in self.data.itertuples(index=False)}
python
{ "resource": "" }
q2382
MemoteResult.add_environment_information
train
def add_environment_information(meta): """Record environment information.""" meta["timestamp"] = datetime.utcnow().isoformat(" ") meta["platform"] = platform.system() meta["release"] = platform.release() meta["python"] = platform.python_version() meta["packages"] = get_pk...
python
{ "resource": "" }
q2383
find_transported_elements
train
def find_transported_elements(rxn): """ Return a dictionary showing the amount of transported elements of a rxn. Collects the elements for each metabolite participating in a reaction, multiplies the amount by the metabolite's stoichiometry in the reaction and bins the result according to the compar...
python
{ "resource": "" }
q2384
find_transport_reactions
train
def find_transport_reactions(model): """ Return a list of all transport reactions. Parameters ---------- model : cobra.Model The metabolic model under investigation. Notes ----- A transport reaction is defined as follows: 1. It contains metabolites from at least 2 compartme...
python
{ "resource": "" }
q2385
find_converting_reactions
train
def find_converting_reactions(model, pair): """ Find all reactions which convert a given metabolite pair. Parameters ---------- model : cobra.Model The metabolic model under investigation. pair: tuple or list A pair of metabolite identifiers without compartment suffix. Retu...
python
{ "resource": "" }
q2386
find_demand_reactions
train
def find_demand_reactions(model): u""" Return a list of demand reactions. Parameters ---------- model : cobra.Model The metabolic model under investigation. Notes ----- [1] defines demand reactions as: -- 'unbalanced network reactions that allow the accumulation of a compou...
python
{ "resource": "" }
q2387
find_sink_reactions
train
def find_sink_reactions(model): u""" Return a list of sink reactions. Parameters ---------- model : cobra.Model The metabolic model under investigation. Notes ----- [1] defines sink reactions as: -- 'similar to demand reactions' but reversible, thus able to supply the m...
python
{ "resource": "" }
q2388
find_exchange_rxns
train
def find_exchange_rxns(model): u""" Return a list of exchange reactions. Parameters ---------- model : cobra.Model The metabolic model under investigation. Notes ----- [1] defines exchange reactions as: -- reactions that 'define the extracellular environment' -- 'unbala...
python
{ "resource": "" }
q2389
find_interchange_biomass_reactions
train
def find_interchange_biomass_reactions(model, biomass=None): """ Return the set of all transport, boundary, and biomass reactions. These reactions are either pseudo-reactions, or incorporated to allow metabolites to pass between compartments. Some tests focus on purely metabolic reactions and hence...
python
{ "resource": "" }
q2390
run_fba
train
def run_fba(model, rxn_id, direction="max", single_value=True): """ Return the solution of an FBA to a set objective function. Parameters ---------- model : cobra.Model The metabolic model under investigation. rxn_id : string A string containing the reaction ID of the desired FB...
python
{ "resource": "" }
q2391
close_boundaries_sensibly
train
def close_boundaries_sensibly(model): """ Return a cobra model with all boundaries closed and changed constraints. In the returned model previously fixed reactions are no longer constrained as such. Instead reactions are constrained according to their reversibility. This is to prevent the FBA from ...
python
{ "resource": "" }
q2392
metabolites_per_compartment
train
def metabolites_per_compartment(model, compartment_id): """ Identify all metabolites that belong to a given compartment. Parameters ---------- model : cobra.Model The metabolic model under investigation. compartment_id : string Model specific compartment identifier. Returns...
python
{ "resource": "" }
q2393
largest_compartment_id_met
train
def largest_compartment_id_met(model): """ Return the ID of the compartment with the most metabolites. Parameters ---------- model : cobra.Model The metabolic model under investigation. Returns ------- string Compartment ID of the compartment with the most metabolites. ...
python
{ "resource": "" }
q2394
find_compartment_id_in_model
train
def find_compartment_id_in_model(model, compartment_id): """ Identify a model compartment by looking up names in COMPARTMENT_SHORTLIST. Parameters ---------- model : cobra.Model The metabolic model under investigation. compartment_id : string Memote internal compartment identifi...
python
{ "resource": "" }
q2395
find_met_in_model
train
def find_met_in_model(model, mnx_id, compartment_id=None): """ Return specific metabolites by looking up IDs in METANETX_SHORTLIST. Parameters ---------- model : cobra.Model The metabolic model under investigation. mnx_id : string Memote internal MetaNetX metabolite identifier u...
python
{ "resource": "" }
q2396
find_bounds
train
def find_bounds(model): """ Return the median upper and lower bound of the metabolic model. Bounds can vary from model to model. Cobrapy defaults to (-1000, 1000) but this may not be the case for merged or autogenerated models. In these cases, this function is used to iterate over all the bounds of...
python
{ "resource": "" }
q2397
Report.render_html
train
def render_html(self): """Render an HTML report.""" return self._template.safe_substitute( report_type=self._report_type, results=self.render_json() )
python
{ "resource": "" }
q2398
Report.compute_score
train
def compute_score(self): """Calculate the overall test score using the configuration.""" # LOGGER.info("Begin scoring") cases = self.get_configured_tests() | set(self.result.cases) scores = DataFrame({"score": 0.0, "max": 1.0}, index=sorted(cases)) self...
python
{ "resource": "" }
q2399
find_components_without_sbo_terms
train
def find_components_without_sbo_terms(model, components): """ Find model components that are not annotated with any SBO terms. Parameters ---------- model : cobra.Model The metabolic model under investigation. components : {"metabolites", "reactions", "genes"} A string denoting ...
python
{ "resource": "" }