code stringlengths 1 18.2k |
|---|
= "can't delete the tmp.list* files" raise ProgramError(msg) # Removing the output.sub.* try: for fileName in glob.glob(outPrefix + "_output.sub.*"): os.remove(fileName) except IOError: msg = "can't delete the output.sub.* files" raise ProgramError(msg) # Closing the output files outputFile.close() outputLog.close() re... |
def runGenomeSGE(bfile, freqFile, nbJob, outPrefix, options): """Runs the genome command from plink, on SGE. :param bfile: the prefix of the input file. :param freqFile: the name of the frequency file (from Plink). :param nbJob: the number of jobs to launch. :param outPrefix: the prefix of all the output files. :param ... |
s.initialize() # Run for each sub task... jobIDs = [] jobTemplates = [] for i in xrange(1, nbJob + 1): for j in xrange(i, nbJob + 1): # The command to run plinkCommand = ["plink", "--noweb", "--bfile", bfile, "--read-freq", freqFile, "--genome", "--genome-full", "--genome-lists", "{}_tmp.list{}".format(outPrefix, i), "... |
in jobTemplates: s.deleteJobTemplate(jt) # Closing the session s.exit() # Checking for problems for hadProblem in hadProblems: if not hadProblem: msg = "Some SGE jobs had errors..." raise ProgramError(msg) |
def extractSNPs(snpsToExtract, options): """Extract markers using Plink. :param snpsToExtract: the name of the file containing markers to extract. :param options: the options :type snpsToExtract: str :type options: argparse.Namespace :returns: the prefix of the output files. """ outPrefix = options.out + ".pruned_data"... |
def selectSNPsAccordingToLD(options): """Compute LD using Plink. :param options: the options. :type options: argparse.Namespace :returns: the name of the output file (from Plink). """ # The plink command outPrefix = options.out + ".pruning_" + options.indep_pairwise[2] plinkCommand = [ "plink", "--noweb", "--bfile", op... |
>>o_file, snp return outPrefix + ".prune.in.autosomal" |
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... |
FLOAT" raise ProgramError(msg) # Check the maf value tmpMAF = None try: tmpMAF = float(args.maf) except ValueError: msg = "maf: must be a float, not %s" % args.maf raise ProgramError(msg) if (tmpMAF > 0.5) or (tmpMAF < 0.0): msg = "maf: must be between 0.0 and 0.5, not %s" % args.maf raise ProgramError(msg) # Check the... |
def spin_once(self, polling_sec=0.010): '''Read the queued data and call the callback for them. You have to handle KeyboardInterrupt (\C-c) manually. Example: >>> def callback(msg): ... print msg >>> sub = jps.Subscriber('topic_name', callback) >>> try: ... while True: ... sub.spin_once(): ... time.sleep(0.1) ... excep... |
def next(self): '''receive next data (block until next data)''' try: raw_msg = self._socket.recv() except KeyboardInterrupt: raise StopIteration() msg, topic_name = self._strip_topic_name_if_not_wildcard(raw_msg) if msg is None: return self.next() if self._user_callback_takes_topic_name: return (self.deserialize(msg), ... |
def open(self): """Open the URL with urllib.request.""" url = self.url try: request = urllib.request.Request(url) handle = urllib.request.build_opener() except IOError: return None return (request, handle) |
def _get_crawled_urls(self, handle, request): """ Main method where the crawler html content is parsed with beautiful soup and out of the DOM, we get the urls """ try: content = six.text_type(handle.open(request).read(), "utf-8", errors="replace") soup = BeautifulSoup(content, "html.parser") tags = soup('a') for tag in... |
def linkfetch(self): """" Public method to call the internal methods """ request, handle = self.open() self._add_headers(request) if handle: self._get_crawled_urls(handle, request) |
def _update_fields_with_objects(self): """ Convert dict fields into objects, where appropriate """ # Update the cover with a photo object if isinstance(self.cover, dict): self.cover = Photo(self._client, self.cover) # Update the photo list with photo objects try: for i, photo in enumerate(self.photos): if isinstance(ph... |
def cover_update(self, photo, **kwds): """ Endpoint: /album/<album_id>/cover/<photo_id>/update.json Update the cover photo of this album. """ result = self._client.album.cover_update(self, photo, **kwds) self._replace_fields(result.get_fields()) self._update_fields_with_objects() |
def delete(self, **kwds): """ Endpoint: /album/<id>/delete.json Deletes this album. Returns True if successful. Raises a TroveboxError if not. """ result = self._client.album.delete(self, **kwds) self._delete_fields() return result |
def add(self, objects, object_type=None, **kwds): """ Endpoint: /album/<id>/<type>/add.json Add objects (eg. Photos) to this album. The objects are a list of either IDs or Trovebox objects. If Trovebox objects are used, the object type is inferred automatically. Updates the album's fields with the response. """ result ... |
def handle_lock(handle): """ Decorate the handle method with a file lock to ensure there is only ever one process running at any one time. """ def wrapper(self, *args, **options): def on_interrupt(signum, frame): # It's necessary to release lockfile sys.exit() signal.signal(signal.SIGTERM, on_interrupt) start_time = ti... |
72) logging.warn(traceback.format_exc()) logging.warn('=' * 72) logger.debug("releasing lock...") lock.release() logger.debug("released.") logger.info("done in %.2f seconds" % (time.time() - start_time)) return return wrapper |
def highlightBlock(self, text): """Takes a block, applies format to the document. according to what's in it. """ # I need to know where in the document we are, # because our formatting info is global to # the document cb = self.currentBlock() p = cb.position() # The \n is not really needed, but sometimes # you are in a... |
range(len(str(text))): try: self.setFormat(i, 1, self.formatter.data[p + i]) except IndexError: pass # I may need to do something about this being called # too quickly. self.tstamp = time.time() |
def main(url): """Create, connect, and block on the listener worker.""" try: listener = ListenerWorker(url) listener.connect() listener.run_forever() except KeyboardInterrupt: listener.close() |
def hxbyterle_decode(output_size, data): """Decode HxRLE data stream If C-extension is not compiled it will use a (slower) Python equivalent :param int output_size: the number of items when ``data`` is uncompressed :param str data: a raw stream of data to be unpacked :return numpy.array output: an array of ``numpy.uint... |
def hxzip_decode(data_size, data): """Decode HxZip data stream :param int data_size: the number of items when ``data`` is uncompressed :param str data: a raw stream of data to be unpacked :return numpy.array output: an array of ``numpy.uint8`` """ import zlib data_stream = zlib.decompress(data) output = numpy.array(str... |
def unpack_binary(data_pointer, definitions, data): """Unpack binary data using ``struct.unpack`` :param data_pointer: metadata for the ``data_pointer`` attribute for this data stream :type data_pointer: ``ahds.header.Block`` :param definitions: definitions specified in the header :type definitions: ``ahds.header.Block... |
y, z = definitions.Lattice data_length = x * y * z output = numpy.array(struct.unpack('<' + '{}'.format(data_type) * data_length, data)) # assume little-endian output = output.reshape(data_length, data_dimension) return output |
def unpack_ascii(data): """Unpack ASCII data using string methods`` :param data_pointer: metadata for the ``data_pointer`` attribute for this data stream :type data_pointer: ``ahds.header.Block`` :param definitions: definitions specified in the header :type definitions: ``ahds.header.Block`` :param bytes data: raw bina... |
def as_contours(self): """A dictionary of lists of contours keyed by byte_value""" contours = dict() for byte_value in self.__byte_values: if byte_value == 0: continue mask = (self.__array == byte_value) * 255 found_contours = find_contours(mask, 254, fully_connected='high') # a list of array contours[byte_value] = Con... |
def show(self): """Display the image""" with_matplotlib = True try: import matplotlib.pyplot as plt except RuntimeError: import skimage.io as io with_matplotlib = False if with_matplotlib: equalised_img = self.equalise() _, ax = plt.subplots() ax.imshow(equalised_img, cmap='gray') import random for contour_set in self.... |
def segments(self): """A dictionary of lists of contours keyed by z-index""" segments = dict() for i in xrange(len(self)): image = self[i] for z, contour in image.as_segments.iteritems(): for byte_value, contour_set in contour.iteritems(): if byte_value not in segments: segments[byte_value] = dict() if z not in segment... |
def to_volume(self): """Return a 3D volume of the data""" if hasattr(self.header.definitions, "Lattice"): X, Y, Z = self.header.definitions.Lattice else: raise ValueError("Unable to determine data size") volume = self.decoded_data.reshape(Z, Y, X) return volume |
def parse_manifest(self, fp): """ Open manifest JSON file and build icon map Args: fp (string or fileobject): Either manifest filepath to open or manifest File object. Returns: dict: Webfont icon map. Contains: * ``class_name``: Builded icon classname with prefix configured in manifest (from parameters in Icomoon inter... |
name = icon_entry.get('properties').get('name') code = icon_entry.get('properties').get('code') hexa_code = hex(code) icons_map[name] = { 'class_name': icon_prefix + name, 'int': code, 'hex': hexa_code, 'unicode': 'U+'+''.join(hex(code).split('x')[1:]).upper(), 'utf8': '\\'+''.join(hex(code).split('x')[1:]).lower(), } ... |
def get(self, webfont_name, webfont_settings): """ Get a manifest file, parse and store it. Args: webfont_name (string): Webfont key name. Used to store manifest and potentially its parser error. webfont_settings (dict): Webfont settings (an item value from ``settings.ICOMOON_WEBFONTS``). """ try: webfont_settings = ex... |
def fetch(self, webfonts): """ Store every defined webfonts. Webfont are stored with sort on their name. Args: webfonts (dict): Dictionnary of webfont settings from ``settings.ICOMOON_WEBFONTS``. """ sorted_keys = sorted(webfonts.keys()) for webfont_name in sorted_keys: self.get(webfont_name, webfonts[webfont_name]) |
def _apply2parser(arguments, options, parser): """ :return the parser itself :type arguments: list[list[T], dict[str, T]] :type options: list[list[T], dict[str, T]] :type parser: cmdtree.parser.AParser :rtype: cmdtree.parser.AParser """ for args, kwargs in options: parser.option(*args, **kwargs) for args, kwargs in arg... |
def apply2parser(cmd_proxy, parser): """ Apply a CmdProxy's arguments and options to a parser of argparse. :type cmd_proxy: callable or CmdProxy :type parser: cmdtree.parser.AParser :rtype: cmdtree.parser.AParser """ if isinstance(cmd_proxy, CmdProxy): parser_proxy = cmd_proxy.meta.parser _apply2parser( parser_proxy.ar... |
def read_csv(filepath, sep=',', header='infer', names=None, usecols=None, dtype=None, converters=None, skiprows=None, nrows=None): """Read CSV into DataFrame. Eager implementation using pandas, i.e. entire file is read at this point. Only common/relevant parameters available at the moment; for full list, could use pand... |
skiprows : int, optional Number of lines to skip at start of file. nrows : int, optional Number of rows to read. Returns ------- DataFrame See Also -------- pandas.read_csv : https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html """ pd_df = pd_read_csv(filepath, sep=sep, header=header, names=names... |
def to_csv(df, filepath, sep=',', header=True, index=True): """Save DataFrame as csv. Note data is expected to be evaluated. Currently delegates to Pandas. Parameters ---------- df : DataFrame filepath : str sep : str, optional Separator used between values. header : bool, optional Whether to save the header. index : b... |
def kmer_lca(seqs_path: 'path to (optionally gzipped) fasta/fastq input', fastq: 'input is fastq; disable autodetection' = False, progress: 'show progress bar (sent to stderr)' = False): ''' Lowest common ancestor sequence assignment using the One Codex API. Streams annotated records to stdout in fasta format. Taxa ass... |
def annotate_diamond(fasta_path: 'path to fasta input', diamond_path: 'path to Diamond taxonomic classification output'): ''' Annotate fasta headers with taxonomy information from Diamond ''' records = tictax.parse_seqs(fasta_path) annotated_records = tictax.annotate_diamond(records, diamond_path) SeqIO.write(annotated... |
def filter_taxa(fasta_path: 'path to fasta input', taxids: 'comma delimited list of taxon IDs', unclassified: 'pass sequences unclassified at superkingdom level >(0)' = False, discard: 'discard specified taxa' = False, warnings: 'show warnings' = False): ''' Customisable filtering of tictax flavoured fasta files ''' co... |
def matrix(fasta_path: 'path to tictax annotated fasta input', scafstats_path: 'path to BBMap scaftstats file'): ''' Generate taxonomic count matrix from tictax classified contigs ''' records = SeqIO.parse(fasta_path, 'fasta') df = tictax.matrix(records, scafstats_path) df.to_csv(sys.stdout) |
def to_dict(self): """ Recusively exports object values to a dict :return: `dict`of values """ if not hasattr(self, '_fields'): return self.__dict__ result = dict() for field_name, field in self._fields.items(): if isinstance(field, xmlmap.NodeField): obj = getattr(self, field_name) if obj is None: result[field_name] =... |
def from_file(cls, file_path, validate=True): """ Creates a Python object from a XML file :param file_path: Path to the XML file :param validate: XML should be validated against the embedded XSD definition :type validate: Boolean :returns: the Python object """ return xmlmap.load_xmlobject_from_file(file_path, xmlclass... |
def from_string(cls, xml_string, validate=True): """ Creates a Python object from a XML string :param xml_string: XML string :param validate: XML should be validated against the embedded XSD definition :type validate: Boolean :returns: the Python object """ return xmlmap.load_xmlobject_from_string(xml_string, xmlclass=... |
def id(self): """ Computes the signature of the record, a SHA-512 of significant values :return: SHa-512 Hex string """ h = hashlib.new('sha512') for value in (self.machine.name, self.machine.os, self.user, self.application.name, self.application.path, self.event.report_type, self.event.type, self.event.time.isoformat(... |
def scratchpad(): """Dummy page for styling tests.""" return render_template( 'demo.html', config=dict( project_name='Scratchpad', style=request.args.get('style', 'default'), ), title='Style Scratchpad', ) |
def update_service(name, service_map): """Get an update from the specified service. Arguments: name (:py:class:`str`): The name of the service. service_map (:py:class:`dict`): A mapping of service names to :py:class:`flash.service.core.Service` instances. Returns: :py:class:`dict`: The updated data. """ if name in serv... |
def add_time(data): """And a friendly update time to the supplied data. Arguments: data (:py:class:`dict`): The response data and its update time. Returns: :py:class:`dict`: The data with a friendly update time. """ payload = data['data'] updated = data['updated'].date() if updated == date.today(): payload['last_update... |
def dtypes(self): """Series of NumPy dtypes present in the DataFrame with index of column names. Returns ------- Series """ return Series(np.array(list(self._gather_dtypes().values()), dtype=np.bytes_), self.keys()) |
def columns(self): """Index of the column names present in the DataFrame in order. Returns ------- Index """ return Index(np.array(self._gather_column_names(), dtype=np.bytes_), np.dtype(np.bytes_)) |
def astype(self, dtype): """Cast DataFrame columns to given dtype. Parameters ---------- dtype : numpy.dtype or dict Dtype or column_name -> dtype mapping to cast columns to. Note index is excluded. Returns ------- DataFrame With casted columns. """ if isinstance(dtype, np.dtype): new_data = OrderedDict((column.name, c... |
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True): """Evaluates by creating a DataFrame containing evaluated data and index. See `LazyResult` Returns ------- DataFrame DataFrame with evaluated data and index. """ evaluated_index = self.index.evaluate(verbose, decode, pa... |
def tail(self, n=5): """Return DataFrame with last n values per column. Parameters ---------- n : int Number of values. Returns ------- DataFrame DataFrame containing the last n values per column. Examples -------- >>> df = bl.DataFrame(OrderedDict((('a', np.arange(5, 8)), ('b', np.arange(3))))) >>> print(df.tail(2).ev... |
def rename(self, columns): """Returns a new DataFrame with renamed columns. Currently a simplified version of Pandas' rename. Parameters ---------- columns : dict Old names to new names. Returns ------- DataFrame With columns renamed, if found. """ new_data = OrderedDict() for column_name in self: if column_name in col... |
def drop(self, columns): """Drop 1 or more columns. Any column which does not exist in the DataFrame is skipped, i.e. not removed, without raising an exception. Unlike Pandas' drop, this is currently restricted to dropping columns. Parameters ---------- columns : str or list of str Column name or list of column names t... |
def agg(self, aggregations): """Multiple aggregations optimized. Parameters ---------- aggregations : list of str Which aggregations to perform. Returns ------- DataFrame DataFrame with the aggregations per column. """ check_type(aggregations, list) df = _drop_str_columns(self) if len(df._data) == 0: # conforming to wh... |
def reset_index(self): """Returns a new DataFrame with previous index as column(s). Returns ------- DataFrame DataFrame with the new index a RangeIndex of its length. """ new_columns = OrderedDict() new_index = default_index(_obtain_length(self._length, self._data)) new_columns.update((name, Series(data.values, new_ind... |
def set_index(self, keys): """Set the index of the DataFrame to be the keys columns. Note this means that the old index is removed. Parameters ---------- keys : str or list of str Which column(s) to set as the index. Returns ------- DataFrame DataFrame with the index set to the column(s) corresponding to the keys. """ ... |
string or a list of strings') |
def sort_index(self, ascending=True): """Sort the index of the DataFrame. Currently MultiIndex is not supported since Weld is missing multiple-column sort. Note this is an expensive operation (brings all data to Weld). Parameters ---------- ascending : bool, optional Returns ------- DataFrame DataFrame sorted according... |
def sort_values(self, by, ascending=True): """Sort the DataFrame based on a column. Unlike Pandas, one can sort by data from both index and regular columns. Currently possible to sort only on a single column since Weld is missing multiple-column sort. Note this is an expensive operation (brings all data to Weld). Param... |
column in new_columns] new_data = OrderedDict(zip(new_column_names, new_columns)) return DataFrame(new_data, new_index) |
def merge(self, other, how='inner', on=None, suffixes=('_x', '_y'), algorithm='merge', is_on_sorted=False, is_on_unique=True): """Database-like join this DataFrame with the other DataFrame. Currently assumes the on-column(s) values are unique! Note there's no automatic cast if the type of the on columns differs. Algori... |
require to sort the data so it can be significantly faster. Do add is_on_sorted=True if this is known to be true! - Uniqueness. If the on-columns data contains duplicates, the algorithm is more complicated, i.e. slow. Also hash-join cannot be used on a hashed (smaller) DataFrame with duplicates. Do add is_on_unique=Tru... |
has the same name. suffixes : tuple of str, optional To append on columns not in `on` that have the same name in the DataFrames. algorithm : {'merge', 'hash'}, optional Which algorithm to use. Note that for 'hash', the `other` DataFrame is the one hashed. is_on_sorted : bool, optional If we know that the on columns are... |
after implementation assert is_on_unique # TODO: this materialization/cache step could be skipped by encoding the whole sort + merge; # TODO this would use the sorted on columns from weld_sort ($.1) in the join to obtain join-output-indices # TODO which would then be passed through a 'translation table' (of $.0) to obt... |
_series_iloc weld_merge_func = weld_merge_join elif how in {'left', 'right'}: index_filter_func = fake_filter_func data_filter_func = _series_iloc_with_missing weld_merge_func = weld_merge_join else: index_filter_func = fake_filter_func data_filter_func = _series_iloc_with_missing weld_merge_func = weld_merge_outer_joi... |
def join(self, other, on=None, how='left', lsuffix=None, rsuffix=None, algorithm='merge', is_on_sorted=True, is_on_unique=True): """Database-like join this DataFrame with the other DataFrame. Currently assumes the `on` columns are sorted and the on-column(s) values are unique! Next work handles the other cases. Note th... |
columns that overlap from other. algorithm : {'merge', 'hash'}, optional Which algorithm to use. Note that for 'hash', the `other` DataFrame is the one hashed. is_on_sorted : bool, optional If we know that the on columns are already sorted, can employ faster algorithm. is_on_unique : bool, optional If we know that the ... |
= '' if rsuffix is None else rsuffix # TODO: pandas is more flexible, e.g. allows the index names to be different when joining on index # TODO i.e. df(ind + a, b) join df(ind2 + b, c) does work and the index is now called ind return self.merge(other, how, on, (lsuffix, rsuffix), algorithm, is_on_sorted, is_on_unique) |
def drop_duplicates(self, subset=None, keep='min'): """Return DataFrame with duplicate rows (excluding index) removed, optionally only considering subset columns. Note that the row order is NOT maintained due to hashing. Parameters ---------- subset : list of str, optional Which columns to consider keep : {'+', '*', 'm... |
self.index._gather_names()) else: new_index = new_index[0] new_data = OrderedDict((sr.name, Series(obj, new_index, sr.dtype, sr.name)) for sr, obj in zip(self._iter(), weld_objects[len(index_data):])) return DataFrame(new_data, new_index) |
def dropna(self, subset=None): """Remove missing values according to Baloo's convention. Parameters ---------- subset : list of str, optional Which columns to check for missing values in. Returns ------- DataFrame DataFrame with no null values in columns. """ subset = check_and_obtain_subset_columns(subset, self) not_n... |
def fillna(self, value): """Returns DataFrame with missing values replaced with value. Parameters ---------- value : {int, float, bytes, bool} or dict Scalar value to replace missing values with. If dict, replaces missing values only in the key columns with the value scalar. Returns ------- DataFrame With missing value... |
def groupby(self, by): """Group by certain columns, excluding index. Simply reset_index if desiring to group by some index column too. Parameters ---------- by : str or list of str Column(s) to groupby. Returns ------- DataFrameGroupBy Object encoding the groupby operation. """ check_str_or_list_str(by) by = as_list(by... |
def from_pandas(cls, df): """Create baloo DataFrame from pandas DataFrame. Parameters ---------- df : pandas.frame.DataFrame Returns ------- DataFrame """ from pandas import DataFrame as PandasDataFrame, Index as PandasIndex, MultiIndex as PandasMultiIndex check_type(df, PandasDataFrame) if isinstance(df.index, PandasI... |
def to_pandas(self): """Convert to pandas DataFrame. Note the data is expected to be evaluated. Returns ------- pandas.frame.DataFrame """ from pandas import DataFrame as PandasDataFrame pandas_index = self.index.to_pandas() pandas_data = OrderedDict((column.name, column.to_pandas()) for column in self._iter()) return ... |
def to_csv(self, filepath, sep=',', header=True, index=True): """Save DataFrame as csv. Parameters ---------- filepath : str sep : str, optional Separator used between values. header : bool, optional Whether to save the header. index : bool, optional Whether to save the index columns. Returns ------- None """ from ..io... |
def babelfy(self, text, params=None): """make a request to the babelfy api and babelfy param text set self._data with the babelfied text as json object """ self._entities = list() self._all_entities = list() self._merged_entities = list() self._all_merged_entities = list() self._text = " ".join(word.strip() for word in... |
def _parse_entities(self): """enrich the babelfied data with the text an the isEntity items set self._entities with the enriched data """ entities = list() for result in self._data: entity = dict() char_fragment = result.get('charFragment') start = char_fragment.get('start') end = char_fragment.get('end') entity['start... |
def _parse_non_entities(self): """create data for all non-entities in the babelfied text set self._all_entities with merged entity and non-entity data """ def _differ(tokens): inner, outer = tokens not_same_start = inner.get('start') != outer.get('start') not_same_end = inner.get('end') != outer.get('end') return not_s... |
'end': index, 'text': ',', 'isEntity': False, }) index += 1 token_tuples = list(product(all_tokens, self.entities)) redundant = [ tokens[0] for tokens in token_tuples if not _differ(tokens)] non_entity_tokens = [ item for item in all_tokens if item not in redundant] if add_dot_token: non_entity_tokens.append(_get_dot_t... |
def _parse_merged_entities(self): """set self._merged_entities to the longest possible(wrapping) tokens """ self._merged_entities = list(filterfalse( lambda token: self._is_wrapped(token, self.entities), self.entities)) |
def _parse_all_merged_entities(self): """set self._all_merged_entities to the longest possible(wrapping) tokens including non-entity tokens """ self._all_merged_entities = list(filterfalse( lambda token: self._is_wrapped(token, self.all_entities), self.all_entities)) |
def _wraps(self, tokens): """determine if a token is wrapped by another token """ def _differ(tokens): inner, outer = tokens not_same_start = inner.get('start') != outer.get('start') not_same_end = inner.get('end') != outer.get('end') return not_same_start or not_same_end def _in_range(tokens): inner, outer = tokens st... |
def _is_wrapped(self, token, tokens): """check if param token is wrapped by any token in tokens """ for t in tokens: is_wrapped = self._wraps((token, t)) if is_wrapped: return True return False |
def apply(self, joinpoint): """Apply this advice on input joinpoint. TODO: improve with internal methods instead of conditional test. """ if self._enable: result = self._impl(joinpoint) else: result = joinpoint.proceed() return result |
def set_enable(target, enable=True, advice_ids=None): """Enable or disable all target Advices designated by input advice_ids. If advice_ids is None, apply (dis|en)able state to all advices. """ advices = get_advices(target) for advice in advices: try: if isinstance(Advice) \ and (advice_ids is None or advice.uuid in ad... |
def weave(target, advices, pointcut=None, depth=1, public=False): """Weave advices such as Advice objects.""" advices = ( advice if isinstance(advice, Advice) else Advice(advice) for advice in advices ) weave( target=target, advices=advices, pointcut=pointcut, depth=depth, public=public ) |
def unweave(target, *advices): """Unweave advices from input target.""" advices = ( advice if isinstance(advice, Advice) else Advice(advice) for advice in advices ) unweave(target=target, *advices) |
def summarise( self, results ): """Generate a summary of results from a list of result dicts returned by running the underlying experiment. By default we generate mean, median, variance, and extrema for each value recorded. Override this method to create different or extra summary statistics. :param results: an array o... |
compute summaries for all fields we're interested in vs = [ res[Experiment.RESULTS][k] for res in results ] summary[self._mean(k)] = numpy.mean(vs) summary[self._median(k)] = numpy.median(vs) summary[self._variance(k)] = numpy.var(vs) summary[self._min(k)] = numpy.min(vs) summary[self._max(k)] = numpy.max(vs) return su... |
def do( self, params ): """Perform the underlying experiment and summarise its results. Our results are the summary statistics extracted from the results of the instances of the underlying experiment that we performed. We drop from the calculations any experiments whose completion status was False, indicating an error.... |
list results = [ rc ] # extract only the successful runs sresults = [ res for res in results if res[Experiment.METADATA][Experiment.STATUS] ] exs = [ res[Experiment.METADATA][Experiment.EXCEPTION] for res in results if not res[Experiment.METADATA][Experiment.STATUS] ] # add extra values to our metadata record self._met... |
def ss_to_xy(s: str): """convert spreadsheet coordinates to zero-index xy coordinates. return None if input is invalid""" result = re.match(r'\$*([A-Z]+)\$*([0-9]+)', s, re.I) if result == None: return None xstring = result.group(1).upper() multiplier = 1 x = 0 for i in xstring: x = x * multiplier + (ord(i) - 64) multi... |
def open( self ): """Open the database connection.""" if self._connection is None: self._connection = sqlite3.connect(self._dbfile) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.