positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def find(file_node, dirs=ICON_DIRS, default_name=None, file_ext='.png'): """ Iterating all icon dirs, try to find a file called like the node's extension / mime subtype / mime type (in that order). For instance, for an MP3 file ("audio/mpeg"), this would look for: "mp3.png" / "audio/mpeg.png" / "audio.png" """ names = [] for attr_name in ('extension', 'mimetype', 'mime_supertype'): attr = getattr(file_node, attr_name) if attr: names.append(attr) if default_name: names.append(default_name) icon_path = StaticPathFinder.find(names, dirs, file_ext) if icon_path: return StaticIconFile(file_node, icon_path)
Iterating all icon dirs, try to find a file called like the node's extension / mime subtype / mime type (in that order). For instance, for an MP3 file ("audio/mpeg"), this would look for: "mp3.png" / "audio/mpeg.png" / "audio.png"
def storage_keys(self): """ Return a list of the keys for values stored for the module. Keys will contain the following metadata entries: - '_ctime': storage creation timestamp - '_mtime': storage last modification timestamp """ if not self._module: return [] self._storage_init() module_name = self._module.module_full_name return self._storage.storage_keys(module_name)
Return a list of the keys for values stored for the module. Keys will contain the following metadata entries: - '_ctime': storage creation timestamp - '_mtime': storage last modification timestamp
def line_pos_from_number(self, line_number): """ Computes line position on Y-Axis (at the center of the line) from line number. :param line_number: The line number for which we want to know the position in pixels. :return: The center position of the line. """ editor = self._editor block = editor.document().findBlockByNumber(line_number) if block.isValid(): return int(editor.blockBoundingGeometry(block).translated( editor.contentOffset()).top()) if line_number <= 0: return 0 else: return int(editor.blockBoundingGeometry( block.previous()).translated(editor.contentOffset()).bottom())
Computes line position on Y-Axis (at the center of the line) from line number. :param line_number: The line number for which we want to know the position in pixels. :return: The center position of the line.
def setPendingKeyExchange(self, sequence, ourBaseKey, ourRatchetKey, ourIdentityKey): """ :type sequence: int :type ourBaseKey: ECKeyPair :type ourRatchetKey: ECKeyPair :type ourIdentityKey: IdentityKeyPair """ structure = self.sessionStructure.PendingKeyExchange() structure.sequence = sequence structure.localBaseKey = ourBaseKey.getPublicKey().serialize() structure.localBaseKeyPrivate = ourBaseKey.getPrivateKey().serialize() structure.localRatchetKey = ourRatchetKey.getPublicKey().serialize() structure.localRatchetKeyPrivate = ourRatchetKey.getPrivateKey().serialize() structure.localIdentityKey = ourIdentityKey.getPublicKey().serialize() structure.localIdentityKeyPrivate = ourIdentityKey.getPrivateKey().serialize() self.sessionStructure.pendingKeyExchange.MergeFrom(structure)
:type sequence: int :type ourBaseKey: ECKeyPair :type ourRatchetKey: ECKeyPair :type ourIdentityKey: IdentityKeyPair
def create_elb(self): """Create or Update the ELB after rendering JSON data from configs. Asserts that the ELB task was successful. """ json_data = self.make_elb_json() LOG.debug('Block ELB JSON Data:\n%s', pformat(json_data)) wait_for_task(json_data) self.add_listener_policy(json_data) self.add_backend_policy(json_data) self.configure_attributes(json_data)
Create or Update the ELB after rendering JSON data from configs. Asserts that the ELB task was successful.
def _set_serializer_by_mime_type(self, mime_type): """ :param mime_type: :return: used by content_type_set to set get a reference to the appropriate serializer """ # ignore if binary response if isinstance(self._app_iter, BinaryResponse): self.logger.info("ignoring setting serializer for binary response") return for available_serializer in self._serializers: if available_serializer.content_type() == mime_type: self._selected_serializer = available_serializer self.logger.info("set serializer for mime type: %s" % mime_type) return self.logger.info("could not find serializer for mime type: %s" % mime_type) raise exception.UnsupportedVocabularyError(mime_type, self.supported_mime_types_str)
:param mime_type: :return: used by content_type_set to set get a reference to the appropriate serializer
def add_segments(self, segments): """Add a list of segments to the composition :param segments: Segments to add to composition :type segments: list of :py:class:`radiotool.composer.Segment` """ self.tracks.update([seg.track for seg in segments]) self.segments.extend(segments)
Add a list of segments to the composition :param segments: Segments to add to composition :type segments: list of :py:class:`radiotool.composer.Segment`
def _prep_time_data(ds): """Prepare time coordinate information in Dataset for use in aospy. 1. If the Dataset contains a time bounds coordinate, add attributes representing the true beginning and end dates of the time interval used to construct the Dataset 2. If the Dataset contains a time bounds coordinate, overwrite the time coordinate values with the averages of the time bounds at each timestep 3. Decode the times into np.datetime64 objects for time indexing Parameters ---------- ds : Dataset Pre-processed Dataset with time coordinate renamed to internal_names.TIME_STR Returns ------- Dataset The processed Dataset """ ds = times.ensure_time_as_index(ds) if TIME_BOUNDS_STR in ds: ds = times.ensure_time_avg_has_cf_metadata(ds) ds[TIME_STR] = times.average_time_bounds(ds) else: logging.warning("dt array not found. Assuming equally spaced " "values in time, even though this may not be " "the case") ds = times.add_uniform_time_weights(ds) # Suppress enable_cftimeindex is a no-op warning; we'll keep setting it for # now to maintain backwards compatibility for older xarray versions. with warnings.catch_warnings(): warnings.filterwarnings('ignore') with xr.set_options(enable_cftimeindex=True): ds = xr.decode_cf(ds, decode_times=True, decode_coords=False, mask_and_scale=True) return ds
Prepare time coordinate information in Dataset for use in aospy. 1. If the Dataset contains a time bounds coordinate, add attributes representing the true beginning and end dates of the time interval used to construct the Dataset 2. If the Dataset contains a time bounds coordinate, overwrite the time coordinate values with the averages of the time bounds at each timestep 3. Decode the times into np.datetime64 objects for time indexing Parameters ---------- ds : Dataset Pre-processed Dataset with time coordinate renamed to internal_names.TIME_STR Returns ------- Dataset The processed Dataset
def find_loci(self, cluster_size, maxgap, locusview=False, colordict=None): ''' Finds the loci of a given cluster size & maximum gap between cluster members. Args cluster_size (int): minimum number of genes in the cluster. maxgap (int): max basepair gap between genes in the cluster. Kwargs locusview (bool): whether or not a map is generated for the locus_parent_organism colordict (list): pass a pre-made color scheme for identified proteins ''' if colordict != None: self.search.protein_arrow_color_dict = colordict for organism in self.organisms: print 'finding loci for', organism.name #reset loci if there is something in there already organism.loci = [] orghits = [] for protein in organism.proteins: if len(protein.hmm_hit_list) > 0: orghits.append((organism.accession, protein.accession, protein.start_bp, protein.end_bp, protein)) bp_start_pooled = [hit[2] for hit in orghits] try: clustered_data = self.cluster_number(bp_start_pooled, maxgap) significant_cluster_list = [] for cluster in clustered_data: if len(cluster) > cluster_size: significant_cluster_list.append(cluster) #print significant_cluster_list for cluster in significant_cluster_list: proteins_in_locus = [] cluster.sort() for bp_start in cluster: for hit in orghits: if bp_start == hit[2]: proteins_in_locus.append(hit[4]) organism.loci.append(Locus(proteins_in_locus, organism, self.search.query_names, locusview)) except IndexError,e: print 'Index error', str(e), organism.name print 'total of', str(len(organism.loci)), 'found for', organism.name
Finds the loci of a given cluster size & maximum gap between cluster members. Args cluster_size (int): minimum number of genes in the cluster. maxgap (int): max basepair gap between genes in the cluster. Kwargs locusview (bool): whether or not a map is generated for the locus_parent_organism colordict (list): pass a pre-made color scheme for identified proteins
def mute(func): """ Decorator Make stdout silent """ def _f(*args, **kwargs): sys.stdout = open(os.devnull, 'w') res = func(*args, **kwargs) sys.stdout.close() sys.stdout = sys.__stdout__ return res return _f
Decorator Make stdout silent
def create(self): """ Calls various methods sequentially in order to fully build the database. """ # Calls each of these methods in order. _populate_from_lines and # _update_relations must be implemented in subclasses. self._init_tables() self._populate_from_lines(self.iterator) self._update_relations() self._finalize()
Calls various methods sequentially in order to fully build the database.
def create_project(type, schema, server, name, output, verbose): """Create a new project on an entity matching server. See entity matching service documentation for details on mapping type and schema Returns authentication details for the created project. """ if verbose: log("Entity Matching Server: {}".format(server)) if schema is not None: schema_json = json.load(schema) # Validate the schema clkhash.schema.validate_schema_dict(schema_json) else: raise ValueError("Schema must be provided when creating new linkage project") name = name if name is not None else '' # Creating new project try: project_creation_reply = project_create(server, schema_json, type, name) except ServiceError as e: log("Unexpected response - {}".format(e.status_code)) log(e.text) raise SystemExit else: log("Project created") json.dump(project_creation_reply, output)
Create a new project on an entity matching server. See entity matching service documentation for details on mapping type and schema Returns authentication details for the created project.
def argmin(self, axis=None, skipna=True, *args, **kwargs): """ Returns the indices of the minimum values along an axis. See `numpy.ndarray.argmin` for more information on the `axis` parameter. See Also -------- numpy.ndarray.argmin """ nv.validate_argmin(args, kwargs) nv.validate_minmax_axis(axis) i8 = self.asi8 if self.hasnans: mask = self._isnan if mask.all() or not skipna: return -1 i8 = i8.copy() i8[mask] = np.iinfo('int64').max return i8.argmin()
Returns the indices of the minimum values along an axis. See `numpy.ndarray.argmin` for more information on the `axis` parameter. See Also -------- numpy.ndarray.argmin
def get_payload(self): """Return Payload.""" ret = bytes([self.status.value]) ret += bytes([self.session_id >> 8 & 255, self.session_id & 255]) return ret
Return Payload.
def timeout(timeout): """ A decorator to timeout a function. Decorated method calls are executed in a separate new thread with a specified timeout. Also check if a thread for the same function already exists before creating a new one. Note: Compatible with Windows (thread based). """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): key = "{0}:{1}:{2}:{3}".format(id(func), func.__name__, args, kwargs) if key in _thread_by_func: # A thread for the same function already exists. worker = _thread_by_func[key] else: worker = ThreadMethod(func, args, kwargs) _thread_by_func[key] = worker worker.join(timeout) if worker.is_alive(): raise TimeoutException() del _thread_by_func[key] if worker.exception: raise worker.exception else: return worker.result return wrapper return decorator
A decorator to timeout a function. Decorated method calls are executed in a separate new thread with a specified timeout. Also check if a thread for the same function already exists before creating a new one. Note: Compatible with Windows (thread based).
def download_urls(cls, urls, force_download=False): """Downloads all CTD URLs that don't exist :param iter[str] urls: iterable of URL of CTD :param bool force_download: force method to download """ for url in urls: file_path = cls.get_path_to_file_from_url(url) if os.path.exists(file_path) and not force_download: log.info('already downloaded %s to %s', url, file_path) else: log.info('downloading %s to %s', url, file_path) download_timer = time.time() urlretrieve(url, file_path) log.info('downloaded in %.2f seconds', time.time() - download_timer)
Downloads all CTD URLs that don't exist :param iter[str] urls: iterable of URL of CTD :param bool force_download: force method to download
def yaml_to_ordered_dict(stream, loader=yaml.SafeLoader): """Provides yaml.load alternative with preserved dictionary order. Args: stream (string): YAML string to load. loader (:class:`yaml.loader`): PyYAML loader class. Defaults to safe load. Returns: OrderedDict: Parsed YAML. """ class OrderedUniqueLoader(loader): """ Subclasses the given pyYAML `loader` class. Validates all sibling keys to insure no duplicates. Returns an OrderedDict instead of a Dict. """ # keys which require no duplicate siblings. NO_DUPE_SIBLINGS = ["stacks", "class_path"] # keys which require no duplicate children keys. NO_DUPE_CHILDREN = ["stacks"] def _error_mapping_on_dupe(self, node, node_name): """check mapping node for dupe children keys.""" if isinstance(node, MappingNode): mapping = {} for n in node.value: a = n[0] b = mapping.get(a.value, None) if b: msg = "{} mapping cannot have duplicate keys {} {}" raise ConstructorError( msg.format(node_name, b.start_mark, a.start_mark) ) mapping[a.value] = a def _validate_mapping(self, node, deep=False): if not isinstance(node, MappingNode): raise ConstructorError( None, None, "expected a mapping node, but found %s" % node.id, node.start_mark) mapping = OrderedDict() for key_node, value_node in node.value: key = self.construct_object(key_node, deep=deep) try: hash(key) except TypeError as exc: raise ConstructorError( "while constructing a mapping", node.start_mark, "found unhashable key (%s)" % exc, key_node.start_mark ) # prevent duplicate sibling keys for certain "keywords". if key in mapping and key in self.NO_DUPE_SIBLINGS: msg = "{} key cannot have duplicate siblings {} {}" raise ConstructorError( msg.format(key, node.start_mark, key_node.start_mark) ) if key in self.NO_DUPE_CHILDREN: # prevent duplicate children keys for this mapping. self._error_mapping_on_dupe(value_node, key_node.value) value = self.construct_object(value_node, deep=deep) mapping[key] = value return mapping def construct_mapping(self, node, deep=False): """Override parent method to use OrderedDict.""" if isinstance(node, MappingNode): self.flatten_mapping(node) return self._validate_mapping(node, deep=deep) def construct_yaml_map(self, node): data = OrderedDict() yield data value = self.construct_mapping(node) data.update(value) OrderedUniqueLoader.add_constructor( u'tag:yaml.org,2002:map', OrderedUniqueLoader.construct_yaml_map, ) return yaml.load(stream, OrderedUniqueLoader)
Provides yaml.load alternative with preserved dictionary order. Args: stream (string): YAML string to load. loader (:class:`yaml.loader`): PyYAML loader class. Defaults to safe load. Returns: OrderedDict: Parsed YAML.
def phenotypesGenerator(self, request): """ Returns a generator over the (phenotypes, nextPageToken) pairs defined by the (JSON string) request """ # TODO make paging work using SPARQL? compoundId = datamodel.PhenotypeAssociationSetCompoundId.parse( request.phenotype_association_set_id) dataset = self.getDataRepository().getDataset(compoundId.dataset_id) phenotypeAssociationSet = dataset.getPhenotypeAssociationSet( compoundId.phenotypeAssociationSetId) associations = phenotypeAssociationSet.getAssociations(request) phenotypes = [association.phenotype for association in associations] return self._protocolListGenerator( request, phenotypes)
Returns a generator over the (phenotypes, nextPageToken) pairs defined by the (JSON string) request
def refreshWidgets(self): """ This function manually refreshed all widgets attached to this simulation. You want to call this function if any particle data has been manually changed. """ if hasattr(self, '_widgets'): for w in self._widgets: w.refresh(isauto=0) else: raise RuntimeError("No widgets found")
This function manually refreshed all widgets attached to this simulation. You want to call this function if any particle data has been manually changed.
def _reindex_non_unique(self, target): """ Create a new index with target's values (move/add/delete values as necessary) use with non-unique Index and a possibly non-unique target. Parameters ---------- target : an iterable Returns ------- new_index : pd.Index Resulting index. indexer : np.ndarray or None Indices of output values in original index. """ target = ensure_index(target) indexer, missing = self.get_indexer_non_unique(target) check = indexer != -1 new_labels = self.take(indexer[check]) new_indexer = None if len(missing): length = np.arange(len(indexer)) missing = ensure_platform_int(missing) missing_labels = target.take(missing) missing_indexer = ensure_int64(length[~check]) cur_labels = self.take(indexer[check]).values cur_indexer = ensure_int64(length[check]) new_labels = np.empty(tuple([len(indexer)]), dtype=object) new_labels[cur_indexer] = cur_labels new_labels[missing_indexer] = missing_labels # a unique indexer if target.is_unique: # see GH5553, make sure we use the right indexer new_indexer = np.arange(len(indexer)) new_indexer[cur_indexer] = np.arange(len(cur_labels)) new_indexer[missing_indexer] = -1 # we have a non_unique selector, need to use the original # indexer here else: # need to retake to have the same size as the indexer indexer[~check] = -1 # reset the new indexer to account for the new size new_indexer = np.arange(len(self.take(indexer))) new_indexer[~check] = -1 new_index = self._shallow_copy_with_infer(new_labels, freq=None) return new_index, indexer, new_indexer
Create a new index with target's values (move/add/delete values as necessary) use with non-unique Index and a possibly non-unique target. Parameters ---------- target : an iterable Returns ------- new_index : pd.Index Resulting index. indexer : np.ndarray or None Indices of output values in original index.
def check_newline_after_last_paragraph(self, definition, docstring): """D209: Put multi-line docstring closing quotes on separate line. Unless the entire docstring fits on a line, place the closing quotes on a line by themselves. """ if docstring: lines = [l for l in ast.literal_eval(docstring).split('\n') if not is_blank(l)] if len(lines) > 1: if docstring.split("\n")[-1].strip() not in ['"""', "'''"]: return violations.D209()
D209: Put multi-line docstring closing quotes on separate line. Unless the entire docstring fits on a line, place the closing quotes on a line by themselves.
def collect_results(results_file): """Return the result (pass/fail) for json file.""" with open(results_file, 'r') as results: data = json.load(results) return data
Return the result (pass/fail) for json file.
def _generate_recommendation(self, query_analysis, db_name, collection_name): """Generates an ideal query recommendation""" index_rec = '{' for query_field in query_analysis['analyzedFields']: if query_field['fieldType'] is EQUIV_TYPE: if len(index_rec) is not 1: index_rec += ', ' index_rec += '"' + query_field['fieldName'] + '": 1' for query_field in query_analysis['analyzedFields']: if query_field['fieldType'] is SORT_TYPE: if len(index_rec) is not 1: index_rec += ', ' index_rec += '"' + query_field['fieldName'] + '": 1' for query_field in query_analysis['analyzedFields']: if query_field['fieldType'] is RANGE_TYPE: if len(index_rec) is not 1: index_rec += ', ' index_rec += '"' + query_field['fieldName'] + '": 1' index_rec += '}' # RECOMMENDATION return OrderedDict([('index',index_rec), ('shellCommand', self.generate_shell_command(collection_name, index_rec))])
Generates an ideal query recommendation
def get_basket_items(request): """ Get all items in the basket """ bid = basket_id(request) return BasketItem.objects.filter(basket_id=bid), bid
Get all items in the basket
def parse_azimuth(azimuth): """ Parses an azimuth measurement in azimuth or quadrant format. Parameters ----------- azimuth : string or number An azimuth measurement in degrees or a quadrant measurement of azimuth. Returns ------- azi : float The azimuth in degrees clockwise from north (range: 0-360) See Also -------- parse_quadrant_measurement parse_strike_dip parse_plunge_bearing """ try: azimuth = float(azimuth) except ValueError: if not azimuth[0].isalpha(): raise ValueError('Ambiguous azimuth: {}'.format(azimuth)) azimuth = parse_quadrant_measurement(azimuth) return azimuth
Parses an azimuth measurement in azimuth or quadrant format. Parameters ----------- azimuth : string or number An azimuth measurement in degrees or a quadrant measurement of azimuth. Returns ------- azi : float The azimuth in degrees clockwise from north (range: 0-360) See Also -------- parse_quadrant_measurement parse_strike_dip parse_plunge_bearing
def generate_date_tail_boost_queries( field, timedeltas_and_boosts, relative_to=None): """ Generate a list of RangeQueries usable to boost the scores of more recent documents. Example: ``` queries = generate_date_tail_boost_queries("publish_date", { timedelta(days=90): 1, timedelta(days=30): 2, timedelta(days=10): 4, }) s = Search(BoolQuery(must=..., should=queries)) # ... ``` Refs: http://elasticsearch-users.115913.n3.nabble.com/Boost-recent-documents-td2126107.html#a2126317 :param field: field name to generate the queries against :param timedeltas_and_boosts: dictionary of timedelta instances and their boosts. Negative or zero boost values will not generate rangequeries. :type timedeltas_and_boosts: dict[timedelta, float] :param relative_to: Relative to this datetime (may be None for "now") :return: List of RangeQueries """ relative_to = relative_to or datetime.datetime.now() times = {} for timedelta, boost in timedeltas_and_boosts.items(): date = (relative_to - timedelta).date() times[date] = boost times = sorted(times.items(), key=lambda i: i[0]) queries = [] for (x, time) in enumerate(times): kwargs = {"field": field, "boost": time[1]} if x == 0: kwargs["lte"] = time[0] else: kwargs["gt"] = time[0] if x < len(times) - 1: kwargs["lte"] = times[x + 1][0] if kwargs["boost"] > 0: q = RangeQuery() q.add_range(**kwargs) queries.append(q) return queries
Generate a list of RangeQueries usable to boost the scores of more recent documents. Example: ``` queries = generate_date_tail_boost_queries("publish_date", { timedelta(days=90): 1, timedelta(days=30): 2, timedelta(days=10): 4, }) s = Search(BoolQuery(must=..., should=queries)) # ... ``` Refs: http://elasticsearch-users.115913.n3.nabble.com/Boost-recent-documents-td2126107.html#a2126317 :param field: field name to generate the queries against :param timedeltas_and_boosts: dictionary of timedelta instances and their boosts. Negative or zero boost values will not generate rangequeries. :type timedeltas_and_boosts: dict[timedelta, float] :param relative_to: Relative to this datetime (may be None for "now") :return: List of RangeQueries
def to_json(self): """ Returns a JSON of the entire DataFrame that can be reconstructed back with raccoon.from_json(input). Any object that cannot be serialized will be replaced with the representation of the object using repr(). In that instance the DataFrame will have a string representation in place of the object and will not reconstruct exactly. :return: json string """ input_dict = {'data': self.to_dict(index=False), 'index': list(self._index)} # if blist, turn into lists if self.blist: input_dict['index'] = list(input_dict['index']) for key in input_dict['data']: input_dict['data'][key] = list(input_dict['data'][key]) meta_data = dict() for key in self.__slots__: if key not in ['_data', '_index']: value = self.__getattribute__(key) meta_data[key.lstrip('_')] = value if not isinstance(value, blist) else list(value) meta_data['use_blist'] = meta_data.pop('blist') input_dict['meta_data'] = meta_data return json.dumps(input_dict, default=repr)
Returns a JSON of the entire DataFrame that can be reconstructed back with raccoon.from_json(input). Any object that cannot be serialized will be replaced with the representation of the object using repr(). In that instance the DataFrame will have a string representation in place of the object and will not reconstruct exactly. :return: json string
def infer(self, input_data, input_label): """ Description : Print sentence for prediction result """ sum_losses = 0 len_losses = 0 for data, label in zip(input_data, input_label): pred = self.net(data) sum_losses += mx.nd.array(self.loss_fn(pred, label)).sum().asscalar() len_losses += len(data) pred_convert = char_beam_search(pred) label_convert = char_conv(label.asnumpy()) for target, pred in zip(label_convert, pred_convert): print("target:{t} pred:{p}".format(t=target, p=pred)) return sum_losses, len_losses
Description : Print sentence for prediction result
def _get_notmuch_message(self, mid): """returns :class:`notmuch.database.Message` with given id""" mode = Database.MODE.READ_ONLY db = Database(path=self.path, mode=mode) try: return db.find_message(mid) except: errmsg = 'no message with id %s exists!' % mid raise NonexistantObjectError(errmsg)
returns :class:`notmuch.database.Message` with given id
def levels(self): """ A generator of (idx, label) sequences representing the category hierarchy from the bottom up. The first level contains all leaf categories, and each subsequent is the next level up. """ def levels(categories): # yield all lower levels sub_categories = [ sc for c in categories for sc in c.sub_categories ] if sub_categories: for level in levels(sub_categories): yield level # yield this level yield [(cat.idx, cat.label) for cat in categories] for level in levels(self): yield level
A generator of (idx, label) sequences representing the category hierarchy from the bottom up. The first level contains all leaf categories, and each subsequent is the next level up.
def get_orthogonal_selection(self, selection, out=None, fields=None): """Retrieve data by making a selection for each dimension of the array. For example, if an array has 2 dimensions, allows selecting specific rows and/or columns. The selection for each dimension can be either an integer (indexing a single item), a slice, an array of integers, or a Boolean array where True values indicate a selection. Parameters ---------- selection : tuple A selection for each dimension of the array. May be any combination of int, slice, integer array or Boolean array. out : ndarray, optional If given, load the selected data directly into this array. fields : str or sequence of str, optional For arrays with a structured dtype, one or more fields can be specified to extract data for. Returns ------- out : ndarray A NumPy array containing the data for the requested selection. Examples -------- Setup a 2-dimensional array:: >>> import zarr >>> import numpy as np >>> z = zarr.array(np.arange(100).reshape(10, 10)) Retrieve rows and columns via any combination of int, slice, integer array and/or Boolean array:: >>> z.get_orthogonal_selection(([1, 4], slice(None))) array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]) >>> z.get_orthogonal_selection((slice(None), [1, 4])) array([[ 1, 4], [11, 14], [21, 24], [31, 34], [41, 44], [51, 54], [61, 64], [71, 74], [81, 84], [91, 94]]) >>> z.get_orthogonal_selection(([1, 4], [1, 4])) array([[11, 14], [41, 44]]) >>> sel = np.zeros(z.shape[0], dtype=bool) >>> sel[1] = True >>> sel[4] = True >>> z.get_orthogonal_selection((sel, sel)) array([[11, 14], [41, 44]]) For convenience, the orthogonal selection functionality is also available via the `oindex` property, e.g.:: >>> z.oindex[[1, 4], :] array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]) >>> z.oindex[:, [1, 4]] array([[ 1, 4], [11, 14], [21, 24], [31, 34], [41, 44], [51, 54], [61, 64], [71, 74], [81, 84], [91, 94]]) >>> z.oindex[[1, 4], [1, 4]] array([[11, 14], [41, 44]]) >>> sel = np.zeros(z.shape[0], dtype=bool) >>> sel[1] = True >>> sel[4] = True >>> z.oindex[sel, sel] array([[11, 14], [41, 44]]) Notes ----- Orthogonal indexing is also known as outer indexing. Slices with step > 1 are supported, but slices with negative step are not. See Also -------- get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, get_coordinate_selection, set_coordinate_selection, set_orthogonal_selection, vindex, oindex, __getitem__, __setitem__ """ # refresh metadata if not self._cache_metadata: self._load_metadata() # check args check_fields(fields, self._dtype) # setup indexer indexer = OrthogonalIndexer(selection, self) return self._get_selection(indexer=indexer, out=out, fields=fields)
Retrieve data by making a selection for each dimension of the array. For example, if an array has 2 dimensions, allows selecting specific rows and/or columns. The selection for each dimension can be either an integer (indexing a single item), a slice, an array of integers, or a Boolean array where True values indicate a selection. Parameters ---------- selection : tuple A selection for each dimension of the array. May be any combination of int, slice, integer array or Boolean array. out : ndarray, optional If given, load the selected data directly into this array. fields : str or sequence of str, optional For arrays with a structured dtype, one or more fields can be specified to extract data for. Returns ------- out : ndarray A NumPy array containing the data for the requested selection. Examples -------- Setup a 2-dimensional array:: >>> import zarr >>> import numpy as np >>> z = zarr.array(np.arange(100).reshape(10, 10)) Retrieve rows and columns via any combination of int, slice, integer array and/or Boolean array:: >>> z.get_orthogonal_selection(([1, 4], slice(None))) array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]) >>> z.get_orthogonal_selection((slice(None), [1, 4])) array([[ 1, 4], [11, 14], [21, 24], [31, 34], [41, 44], [51, 54], [61, 64], [71, 74], [81, 84], [91, 94]]) >>> z.get_orthogonal_selection(([1, 4], [1, 4])) array([[11, 14], [41, 44]]) >>> sel = np.zeros(z.shape[0], dtype=bool) >>> sel[1] = True >>> sel[4] = True >>> z.get_orthogonal_selection((sel, sel)) array([[11, 14], [41, 44]]) For convenience, the orthogonal selection functionality is also available via the `oindex` property, e.g.:: >>> z.oindex[[1, 4], :] array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]) >>> z.oindex[:, [1, 4]] array([[ 1, 4], [11, 14], [21, 24], [31, 34], [41, 44], [51, 54], [61, 64], [71, 74], [81, 84], [91, 94]]) >>> z.oindex[[1, 4], [1, 4]] array([[11, 14], [41, 44]]) >>> sel = np.zeros(z.shape[0], dtype=bool) >>> sel[1] = True >>> sel[4] = True >>> z.oindex[sel, sel] array([[11, 14], [41, 44]]) Notes ----- Orthogonal indexing is also known as outer indexing. Slices with step > 1 are supported, but slices with negative step are not. See Also -------- get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection, get_coordinate_selection, set_coordinate_selection, set_orthogonal_selection, vindex, oindex, __getitem__, __setitem__
def reordc(iorder, ndim, lenvals, array): """ Re-order the elements of an array of character strings according to a given order vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordc_c.html :param iorder: Order vector to be used to re-order array. :type iorder: Array of ints :param ndim: Dimension of array. :type ndim: int :param lenvals: String length. :type lenvals: int :param array: Array to be re-ordered. :type array: Array of strs :return: Re-ordered Array. :rtype: Array of strs """ iorder = stypes.toIntVector(iorder) ndim = ctypes.c_int(ndim) lenvals = ctypes.c_int(lenvals + 1) array = stypes.listToCharArray(array, xLen=lenvals, yLen=ndim) libspice.reordc_c(iorder, ndim, lenvals, array) return [stypes.toPythonString(x.value) for x in array]
Re-order the elements of an array of character strings according to a given order vector. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/reordc_c.html :param iorder: Order vector to be used to re-order array. :type iorder: Array of ints :param ndim: Dimension of array. :type ndim: int :param lenvals: String length. :type lenvals: int :param array: Array to be re-ordered. :type array: Array of strs :return: Re-ordered Array. :rtype: Array of strs
def create_random_population(num=100): """ create a list of people with randomly generated names and stats """ people = [] for _ in range(num): nme = 'blah' tax_min = random.randint(1,40)/100 tax_max = tax_min + random.randint(1,40)/100 tradition = random.randint(1,100)/100 equity = random.randint(1,100)/100 pers = mod_hap_env.Person(nme, {'tax_min':tax_min, 'tax_max':tax_max, 'tradition':tradition, 'equity':equity}) people.append(pers) print(pers) return people
create a list of people with randomly generated names and stats
def exact(self, *args, **kwargs): """Compare attributes of pairs exactly. Shortcut of :class:`recordlinkage.compare.Exact`:: from recordlinkage.compare import Exact indexer = recordlinkage.Compare() indexer.add(Exact()) """ compare = Exact(*args, **kwargs) self.add(compare) return self
Compare attributes of pairs exactly. Shortcut of :class:`recordlinkage.compare.Exact`:: from recordlinkage.compare import Exact indexer = recordlinkage.Compare() indexer.add(Exact())
def upload_supervisor_app_conf(app_name, template_name=None, context=None): """Upload Supervisor app configuration from a template.""" default = {'app_name': app_name} context = context or {} default.update(context) template_name = template_name or [u'supervisor/%s.conf' % app_name, u'supervisor/base.conf'] destination = u'/etc/supervisor/conf.d/%s.conf' % app_name upload_template(template_name, destination, context=default, use_sudo=True) supervisor_command(u'update')
Upload Supervisor app configuration from a template.
def translate_identifier(self, identifier, target_namespaces=None, translate_ncbi_namespace=None): """Given a string identifier, return a list of aliases (as identifiers) that refer to the same sequence. """ namespace, alias = identifier.split(nsa_sep) if nsa_sep in identifier else (None, identifier) aliases = self.translate_alias(alias=alias, namespace=namespace, target_namespaces=target_namespaces, translate_ncbi_namespace=translate_ncbi_namespace) return [nsa_sep.join((a["namespace"], a["alias"])) for a in aliases]
Given a string identifier, return a list of aliases (as identifiers) that refer to the same sequence.
def build(self, builder): """ Build XML by appending to builder .. note:: Questions can contain translations """ builder.start("Question", {}) for translation in self.translations: translation.build(builder) builder.end("Question")
Build XML by appending to builder .. note:: Questions can contain translations
def send_text(self, message, opcode=OPCODE_TEXT): """ Important: Fragmented(=continuation) messages are not supported since their usage cases are limited - when we don't know the payload length. """ # Validate message if isinstance(message, bytes): message = try_decode_UTF8(message) # this is slower but ensures we have UTF-8 if not message: logger.warning("Can\'t send message, message is not valid UTF-8") return False elif sys.version_info < (3,0) and (isinstance(message, str) or isinstance(message, unicode)): pass elif isinstance(message, str): pass else: logger.warning('Can\'t send message, message has to be a string or bytes. Given type is %s' % type(message)) return False header = bytearray() payload = encode_to_UTF8(message) payload_length = len(payload) # Normal payload if payload_length <= 125: header.append(FIN | opcode) header.append(payload_length) # Extended payload elif payload_length >= 126 and payload_length <= 65535: header.append(FIN | opcode) header.append(PAYLOAD_LEN_EXT16) header.extend(struct.pack(">H", payload_length)) # Huge extended payload elif payload_length < 18446744073709551616: header.append(FIN | opcode) header.append(PAYLOAD_LEN_EXT64) header.extend(struct.pack(">Q", payload_length)) else: raise Exception("Message is too big. Consider breaking it into chunks.") return self.request.send(header + payload)
Important: Fragmented(=continuation) messages are not supported since their usage cases are limited - when we don't know the payload length.
def remove_child_banks(self, bank_id): """Removes all children from a bank. arg: bank_id (osid.id.Id): the ``Id`` of a bank raise: NotFound - ``bank_id`` is not in hierarchy raise: NullArgument - ``bank_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.BinHierarchyDesignSession.remove_child_bin_template if self._catalog_session is not None: return self._catalog_session.remove_child_catalogs(catalog_id=bank_id) return self._hierarchy_session.remove_children(id_=bank_id)
Removes all children from a bank. arg: bank_id (osid.id.Id): the ``Id`` of a bank raise: NotFound - ``bank_id`` is not in hierarchy raise: NullArgument - ``bank_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred *compliance: mandatory -- This method must be implemented.*
def notify(cls, user_or_email_, object_id=None, **filters): """Start notifying the given user or email address when this event occurs and meets the criteria given in ``filters``. Return the created (or the existing matching) Watch so you can call :meth:`~tidings.models.Watch.activate()` on it if you're so inclined. Implementations in subclasses may take different arguments; see the docstring of :meth:`is_notifying()`. Send an activation email if an anonymous watch is created and :data:`~django.conf.settings.TIDINGS_CONFIRM_ANONYMOUS_WATCHES` is ``True``. If the activation request fails, raise a ActivationRequestFailed exception. Calling :meth:`notify()` twice for an anonymous user will send the email each time. """ # A test-for-existence-then-create race condition exists here, but it # doesn't matter: de-duplication on fire() and deletion of all matches # on stop_notifying() nullify its effects. try: # Pick 1 if >1 are returned: watch = cls._watches_belonging_to_user( user_or_email_, object_id=object_id, **filters)[0:1].get() except Watch.DoesNotExist: create_kwargs = {} if cls.content_type: create_kwargs['content_type'] = \ ContentType.objects.get_for_model(cls.content_type) create_kwargs['email' if isinstance(user_or_email_, string_types) else 'user'] = user_or_email_ # Letters that can't be mistaken for other letters or numbers in # most fonts, in case people try to type these: distinguishable_letters = \ 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXYZ' secret = ''.join(random.choice(distinguishable_letters) for x in range(10)) # Registered users don't need to confirm, but anonymous users do. is_active = ('user' in create_kwargs or not settings.TIDINGS_CONFIRM_ANONYMOUS_WATCHES) if object_id: create_kwargs['object_id'] = object_id watch = Watch.objects.create( secret=secret, is_active=is_active, event_type=cls.event_type, **create_kwargs) for k, v in iteritems(filters): WatchFilter.objects.create(watch=watch, name=k, value=hash_to_unsigned(v)) # Send email for inactive watches. if not watch.is_active: email = watch.user.email if watch.user else watch.email message = cls._activation_email(watch, email) try: message.send() except SMTPException as e: watch.delete() raise ActivationRequestFailed(e.recipients) return watch
Start notifying the given user or email address when this event occurs and meets the criteria given in ``filters``. Return the created (or the existing matching) Watch so you can call :meth:`~tidings.models.Watch.activate()` on it if you're so inclined. Implementations in subclasses may take different arguments; see the docstring of :meth:`is_notifying()`. Send an activation email if an anonymous watch is created and :data:`~django.conf.settings.TIDINGS_CONFIRM_ANONYMOUS_WATCHES` is ``True``. If the activation request fails, raise a ActivationRequestFailed exception. Calling :meth:`notify()` twice for an anonymous user will send the email each time.
def reset(self): """ (re)set all attributes to defaults (eg. empty sets or ``None``). """ # Use first matching element as title (0 or more xpath expressions) self.title = OrderedSet() # Use first matching element as body (0 or more xpath expressions) self.body = OrderedSet() # Use first matching element as author (0 or more xpath expressions) self.author = OrderedSet() # Use first matching element as date (0 or more xpath expressions) self.date = OrderedSet() # Put language here. It's not supported in siteconfig syntax, # but having it here allows more generic handling in extractor. self.language = ( '//html[@lang]/@lang', '//meta[@name="DC.language"]/@content', ) # Strip elements matching these xpath expressions (0 or more) self.strip = OrderedSet() # Strip 0 or more elements which contain these # strings in the id or class attribute. self.strip_id_or_class = OrderedSet() # Strip 0 or more images which contain # these strings in the src attribute. self.strip_image_src = OrderedSet() # Additional HTTP headers to send # NOT YET USED self.http_header = OrderedSet() # For those 3, None means that default will be used. But we need # None to distinguish from False during multiple configurations # merges. self.tidy = None self.prune = None self.autodetect_on_failure = None # Test URL - if present, can be used to test the config above self.test_url = OrderedSet() self.test_contains = OrderedSet() # Single-page link should identify a link element or URL pointing # to the page holding the entire article. # # This is useful for sites which split their articles across # multiple pages. Links to such pages tend to display the first # page with links to the other pages at the bottom. # # Often there is also a link to a page which displays the entire # article on one page (e.g. 'print view'). # # `single_page_link` should be an XPath expression identifying the # link to that single page. If present and we find a match, we will # retrieve that page and the rest of the options in this config will # be applied to the new page. self.single_page_link = OrderedSet() self.next_page_link = OrderedSet() # Single-page link in feed? - same as above, but patterns applied # to item description HTML taken from feed. XXX self.single_page_link_in_feed = OrderedSet() # Which parser to use for turning raw HTML into a DOMDocument, # either `libxml` (PHP) / `lxml` (Python) or `html5lib`. Defaults # to `lxml` if None. self.parser = None # Strings to search for in HTML before processing begins. Goes by # pairs with `replace_string`. Not a set because we can have more # than one of the same, to be replaced by different values. self.find_string = [] # Strings to replace those found in `find_string` before HTML # processing begins. self.replace_string = []
(re)set all attributes to defaults (eg. empty sets or ``None``).
def Input_synthesizePinchGesture(self, x, y, scaleFactor, **kwargs): """ Function path: Input.synthesizePinchGesture Domain: Input Method name: synthesizePinchGesture WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'x' (type: number) -> X coordinate of the start of the gesture in CSS pixels. 'y' (type: number) -> Y coordinate of the start of the gesture in CSS pixels. 'scaleFactor' (type: number) -> Relative scale factor after zooming (>1.0 zooms in, <1.0 zooms out). Optional arguments: 'relativeSpeed' (type: integer) -> Relative pointer speed in pixels per second (default: 800). 'gestureSourceType' (type: GestureSourceType) -> Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type). No return value. Description: Synthesizes a pinch gesture over a time period by issuing appropriate touch events. """ assert isinstance(x, (float, int) ), "Argument 'x' must be of type '['float', 'int']'. Received type: '%s'" % type( x) assert isinstance(y, (float, int) ), "Argument 'y' must be of type '['float', 'int']'. Received type: '%s'" % type( y) assert isinstance(scaleFactor, (float, int) ), "Argument 'scaleFactor' must be of type '['float', 'int']'. Received type: '%s'" % type( scaleFactor) if 'relativeSpeed' in kwargs: assert isinstance(kwargs['relativeSpeed'], (int,) ), "Optional argument 'relativeSpeed' must be of type '['int']'. Received type: '%s'" % type( kwargs['relativeSpeed']) expected = ['relativeSpeed', 'gestureSourceType'] passed_keys = list(kwargs.keys()) assert all([(key in expected) for key in passed_keys] ), "Allowed kwargs are ['relativeSpeed', 'gestureSourceType']. Passed kwargs: %s" % passed_keys subdom_funcs = self.synchronous_command('Input.synthesizePinchGesture', x =x, y=y, scaleFactor=scaleFactor, **kwargs) return subdom_funcs
Function path: Input.synthesizePinchGesture Domain: Input Method name: synthesizePinchGesture WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'x' (type: number) -> X coordinate of the start of the gesture in CSS pixels. 'y' (type: number) -> Y coordinate of the start of the gesture in CSS pixels. 'scaleFactor' (type: number) -> Relative scale factor after zooming (>1.0 zooms in, <1.0 zooms out). Optional arguments: 'relativeSpeed' (type: integer) -> Relative pointer speed in pixels per second (default: 800). 'gestureSourceType' (type: GestureSourceType) -> Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type). No return value. Description: Synthesizes a pinch gesture over a time period by issuing appropriate touch events.
def increase_writes_in_units( current_provisioning, units, max_provisioned_writes, consumed_write_units_percent, log_tag): """ Increase the current_provisioning with units units :type current_provisioning: int :param current_provisioning: The current provisioning :type units: int :param units: How many units should we increase with :returns: int -- New provisioning value :type max_provisioned_writes: int :param max_provisioned_writes: Configured max provisioned writes :type consumed_write_units_percent: float :param consumed_write_units_percent: Number of consumed write units :type log_tag: str :param log_tag: Prefix for the log """ units = int(units) current_provisioning = float(current_provisioning) consumed_write_units_percent = float(consumed_write_units_percent) consumption_based_current_provisioning = \ int(math.ceil(current_provisioning*(consumed_write_units_percent/100))) if consumption_based_current_provisioning > current_provisioning: updated_provisioning = consumption_based_current_provisioning + units else: updated_provisioning = int(current_provisioning) + units if max_provisioned_writes > 0: if updated_provisioning > max_provisioned_writes: logger.info( '{0} - Reached provisioned writes max limit: {1}'.format( log_tag, max_provisioned_writes)) return max_provisioned_writes logger.debug( '{0} - Write provisioning will be increased to {1:d} units'.format( log_tag, int(updated_provisioning))) return updated_provisioning
Increase the current_provisioning with units units :type current_provisioning: int :param current_provisioning: The current provisioning :type units: int :param units: How many units should we increase with :returns: int -- New provisioning value :type max_provisioned_writes: int :param max_provisioned_writes: Configured max provisioned writes :type consumed_write_units_percent: float :param consumed_write_units_percent: Number of consumed write units :type log_tag: str :param log_tag: Prefix for the log
def find_modules(module_path): """Find all modules in the module (possibly package) represented by `module_path`. Args: module_path: A pathlib.Path to a Python package or module. Returns: An iterable of paths Python modules (i.e. *py files). """ if module_path.is_file(): if module_path.suffix == '.py': yield module_path elif module_path.is_dir(): pyfiles = glob.glob('{}/**/*.py'.format(module_path), recursive=True) yield from (Path(pyfile) for pyfile in pyfiles)
Find all modules in the module (possibly package) represented by `module_path`. Args: module_path: A pathlib.Path to a Python package or module. Returns: An iterable of paths Python modules (i.e. *py files).
def getObject(self, url_or_requests_response, params=None): 'Take a url or some xml response from JottaCloud and wrap it up with the corresponding JFS* class' if isinstance(url_or_requests_response, requests.models.Response): # this is a raw xml response that we need to parse url = url_or_requests_response.url o = lxml.objectify.fromstring(url_or_requests_response.content) else: # this is an url that we need to fetch url = url_or_requests_response o = self.get(url, params=params) # (.get() will parse this for us) parent = os.path.dirname(url).replace('up.jottacloud.com', 'www.jottacloud.com') if o.tag == 'error': JFSError.raiseError(o, url) elif o.tag == 'device': return JFSDevice(o, jfs=self, parentpath=parent) elif o.tag == 'folder': return JFSFolder(o, jfs=self, parentpath=parent) elif o.tag == 'mountPoint': return JFSMountPoint(o, jfs=self, parentpath=parent) elif o.tag == 'restoredFiles': return JFSFile(o, jfs=self, parentpath=parent) elif o.tag == 'deleteFiles': return JFSFile(o, jfs=self, parentpath=parent) elif o.tag == 'file': return ProtoFile.factory(o, jfs=self, parentpath=parent) # try: # if o.latestRevision.state == 'INCOMPLETE': # return JFSIncompleteFile(o, jfs=self, parentpath=parent) # elif o.latestRevision.state == 'CORRUPT': # return JFSCorruptFile(o, jfs=self, parentpath=parent) # except AttributeError: # return JFSFile(o, jfs=self, parentpath=parent) elif o.tag == 'enableSharing': return JFSenableSharing(o, jfs=self) elif o.tag == 'user': self.fs = o return self.fs elif o.tag == 'filedirlist': return JFSFileDirList(o, jfs=self, parentpath=parent) elif o.tag == 'searchresult': return JFSsearchresult(o, jfs=self) raise JFSError("invalid object: %s <- %s" % (repr(o), url_or_requests_response))
Take a url or some xml response from JottaCloud and wrap it up with the corresponding JFS* class
def get(self, statediag): """ Args: statediag (list): The states of the PDA Returns: list: A reduced list of states using BFS """ if len(statediag) < 1: print 'PDA is empty and can not be reduced' return statediag newstatediag = self.bfs(statediag, statediag[0]) return newstatediag
Args: statediag (list): The states of the PDA Returns: list: A reduced list of states using BFS
def on_trial_remove(self, trial_runner, trial): """Marks trial as completed if it is paused and has previously ran.""" if trial.status is Trial.PAUSED and trial in self._results: self._completed_trials.add(trial)
Marks trial as completed if it is paused and has previously ran.
def for_format(filename, format=None, writable=False, prefix_dir=None): """ Create a MeshIO instance for file `filename` with forced `format`. Parameters ---------- filename : str The name of the mesh file. format : str One of supported formats. If None, :func:`MeshIO.any_from_filename()` is called instead. writable : bool If True, verify that the mesh format is writable. prefix_dir : str The directory name to prepend to `filename`. Returns ------- io : MeshIO subclass instance The MeshIO subclass instance corresponding to the `format`. """ ext = op.splitext(filename)[1].lower() try: _format = supported_formats[ext] except KeyError: _format = None format = get_default(format, _format) if format is None: io = MeshIO.any_from_filename(filename, prefix_dir=prefix_dir) else: if not isinstance(format, basestr): raise ValueError('ambigous suffix! (%s -> %s)' % (ext, format)) if format not in io_table: raise ValueError('unknown output mesh format! (%s)' % format) if writable and ('w' not in supported_capabilities[format]): output_writable_meshes() msg = 'write support not implemented for output mesh format "%s",' \ ' see above!' \ % format raise ValueError(msg) if prefix_dir is not None: filename = op.normpath(op.join(prefix_dir, filename)) io = io_table[format](filename) return io
Create a MeshIO instance for file `filename` with forced `format`. Parameters ---------- filename : str The name of the mesh file. format : str One of supported formats. If None, :func:`MeshIO.any_from_filename()` is called instead. writable : bool If True, verify that the mesh format is writable. prefix_dir : str The directory name to prepend to `filename`. Returns ------- io : MeshIO subclass instance The MeshIO subclass instance corresponding to the `format`.
def interconnect_all(self): """Propagate dependencies for provided instances""" for dep in topologically_sorted(self._provides): if hasattr(dep, '__injections__') and not hasattr(dep, '__injections_source__'): self.inject(dep)
Propagate dependencies for provided instances
async def container_load(self, container_type, params=None, container=None, obj=None): """ Loads container of elements from the reader. Supports the container ref. Returns loaded container. :param container_type: :param params: :param container: :param obj: :return: """ if isinstance(obj, IModel): obj = obj.val if obj is None: return NoSetSentinel() c_len = len(obj) elem_type = params[0] if params else None if elem_type is None: elem_type = container_type.ELEM_TYPE res = container if container else [] for i in range(c_len): try: self.tracker.push_index(i) fvalue = await self._load_field(elem_type, params[1:] if params else None, x.eref(res, i) if container else None, obj=obj[i]) self.tracker.pop() except Exception as e: raise helpers.ArchiveException(e, tracker=self.tracker) from e if not container and not isinstance(fvalue, NoSetSentinel): res.append(fvalue) return res
Loads container of elements from the reader. Supports the container ref. Returns loaded container. :param container_type: :param params: :param container: :param obj: :return:
def add_experiment(self, id, port, time, file_name, platform): '''set {key:value} paris to self.experiment''' self.experiments[id] = {} self.experiments[id]['port'] = port self.experiments[id]['startTime'] = time self.experiments[id]['endTime'] = 'N/A' self.experiments[id]['status'] = 'INITIALIZED' self.experiments[id]['fileName'] = file_name self.experiments[id]['platform'] = platform self.write_file()
set {key:value} paris to self.experiment
def execute(self, query, *parameters, **kwargs): """Same as query, but do not process results. Always returns `None`.""" cursor = self._cursor() try: self._execute(cursor, query, parameters, kwargs) except: raise finally: cursor.close()
Same as query, but do not process results. Always returns `None`.
def delete(self, **kwds): """ Endpoint: /action/<id>/delete.json Deletes this action. Returns True if successful. Raises a TroveboxError if not. """ result = self._client.action.delete(self, **kwds) self._delete_fields() return result
Endpoint: /action/<id>/delete.json Deletes this action. Returns True if successful. Raises a TroveboxError if not.
def get_root_path(self, name): """ Attempt to compute a root path for a (hopefully importable) name. Based in part on Flask's `root_path` calculation. See: https://github.com/mitsuhiko/flask/blob/master/flask/helpers.py#L777 """ module = modules.get(name) if module is not None and hasattr(module, '__file__'): return dirname(abspath(module.__file__)) # Flask keeps looking at this point. We instead set the root path to None, # assume that the user doesn't need resource loading, and raise an error # when resolving the resource path. return None
Attempt to compute a root path for a (hopefully importable) name. Based in part on Flask's `root_path` calculation. See: https://github.com/mitsuhiko/flask/blob/master/flask/helpers.py#L777
def _on_add_library(self, *event): """Callback method handling the addition of a new library """ self.view['library_tree_view'].grab_focus() if react_to_event(self.view, self.view['library_tree_view'], event): temp_library_name = "<LIB_NAME_%s>" % self._lib_counter self._lib_counter += 1 library_config = self.core_config_model.get_current_config_value("LIBRARY_PATHS", use_preliminary=True, default={}) library_config[temp_library_name] = "<LIB_PATH>" self.core_config_model.set_preliminary_config_value("LIBRARY_PATHS", library_config) self._select_row_by_column_value(self.view['library_tree_view'], self.library_list_store, self.KEY_STORAGE_ID, temp_library_name) return True
Callback method handling the addition of a new library
def print_update(self): """ print some status information in between. """ print("\r\n") now = datetime.datetime.now() print("Update info: (from: %s)" % now.strftime("%c")) current_total_size = self.total_stined_bytes + self.total_new_bytes if self.total_errored_items: print(" * WARNING: %i omitted files!" % self.total_errored_items) print(" * fast backup: %i files" % self.total_fast_backup) print( " * new content saved: %i files (%s %.1f%%)" % ( self.total_new_file_count, human_filesize(self.total_new_bytes), to_percent(self.total_new_bytes, current_total_size), ) ) print( " * stint space via hardlinks: %i files (%s %.1f%%)" % ( self.total_file_link_count, human_filesize(self.total_stined_bytes), to_percent(self.total_stined_bytes, current_total_size), ) ) duration = default_timer() - self.start_time performance = current_total_size / duration / 1024.0 / 1024.0 print(" * present performance: %.1fMB/s\n" % performance)
print some status information in between.
def error(self): """Check if the async response is an error. Take care to call `is_done` before calling `error`. Note that the error messages are always encoded as strings. :raises CloudUnhandledError: When not checking `is_done` first :return: the error value/payload, if found. :rtype: str """ status_code, error_msg, payload = self.check_error() if status_code != 200 and not error_msg and not payload: return "Async error (%s). Status code: %r" % (self.async_id, status_code) return error_msg
Check if the async response is an error. Take care to call `is_done` before calling `error`. Note that the error messages are always encoded as strings. :raises CloudUnhandledError: When not checking `is_done` first :return: the error value/payload, if found. :rtype: str
def get_next_action(self, request, application, roles): """ Retrieve the next state. """ application.reopen() link, is_secret = base.get_email_link(application) emails.send_invite_email(application, link, is_secret) messages.success( request, "Sent an invitation to %s." % application.applicant.email) return 'success'
Retrieve the next state.
def difference(self, other, sort=None): """ Compute set difference of two MultiIndex objects Parameters ---------- other : MultiIndex sort : False or None, default None Sort the resulting MultiIndex if possible .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- diff : MultiIndex """ self._validate_sort_keyword(sort) self._assert_can_do_setop(other) other, result_names = self._convert_can_do_setop(other) if len(other) == 0: return self if self.equals(other): return MultiIndex(levels=self.levels, codes=[[]] * self.nlevels, names=result_names, verify_integrity=False) this = self._get_unique_index() indexer = this.get_indexer(other) indexer = indexer.take((indexer != -1).nonzero()[0]) label_diff = np.setdiff1d(np.arange(this.size), indexer, assume_unique=True) difference = this.values.take(label_diff) if sort is None: difference = sorted(difference) if len(difference) == 0: return MultiIndex(levels=[[]] * self.nlevels, codes=[[]] * self.nlevels, names=result_names, verify_integrity=False) else: return MultiIndex.from_tuples(difference, sortorder=0, names=result_names)
Compute set difference of two MultiIndex objects Parameters ---------- other : MultiIndex sort : False or None, default None Sort the resulting MultiIndex if possible .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the default value from ``True`` to ``None`` (without change in behaviour). Returns ------- diff : MultiIndex
def _handle_heartbeat(self, sender, data): """ Handles a raw heart beat :param sender: Sender (address, port) tuple :param data: Raw packet data """ # Format of packet parsed, data = self._unpack("<B", data) format = parsed[0] if format == PACKET_FORMAT_VERSION: # Kind of beat parsed, data = self._unpack("<B", data) kind = parsed[0] if kind == PACKET_TYPE_HEARTBEAT: # Extract content parsed, data = self._unpack("<H", data) port = parsed[0] path, data = self._unpack_string(data) uid, data = self._unpack_string(data) node_uid, data = self._unpack_string(data) try: app_id, data = self._unpack_string(data) except struct.error: # Compatibility with previous version app_id = herald.DEFAULT_APPLICATION_ID elif kind == PACKET_TYPE_LASTBEAT: # Peer is going away uid, data = self._unpack_string(data) app_id, data = self._unpack_string(data) port = -1 path = None node_uid = None else: _logger.warning("Unknown kind of packet: %d", kind) return try: self._callback(kind, uid, node_uid, app_id, sender[0], port, path) except Exception as ex: _logger.exception("Error handling heart beat: %s", ex)
Handles a raw heart beat :param sender: Sender (address, port) tuple :param data: Raw packet data
def iso_datetime(timestamp=None): """ Convert UNIX timestamp to ISO datetime string. @param timestamp: UNIX epoch value (default: the current time). @return: Timestamp formatted as "YYYY-mm-dd HH:MM:SS". """ if timestamp is None: timestamp = time.time() return datetime.datetime.fromtimestamp(timestamp).isoformat(' ')[:19]
Convert UNIX timestamp to ISO datetime string. @param timestamp: UNIX epoch value (default: the current time). @return: Timestamp formatted as "YYYY-mm-dd HH:MM:SS".
def export(request, page_id, export_unpublished=False): """ API endpoint of this source site to export a part of the page tree rooted at page_id Requests are made by a destination site's import_from_api view. """ try: if export_unpublished: root_page = Page.objects.get(id=page_id) else: root_page = Page.objects.get(id=page_id, live=True) except Page.DoesNotExist: return JsonResponse({'error': _('page not found')}) payload = export_pages(root_page, export_unpublished=export_unpublished) return JsonResponse(payload)
API endpoint of this source site to export a part of the page tree rooted at page_id Requests are made by a destination site's import_from_api view.
def hide(cls): """ Hide the log interface. """ cls.el.style.display = "none" cls.overlay.hide() cls.bind()
Hide the log interface.
def _report_profile(self, command, lock_name, elapsed_time, memory): """ Writes a string to self.pipeline_profile_file. """ message_raw = str(command) + "\t " + \ str(lock_name) + "\t" + \ str(datetime.timedelta(seconds = round(elapsed_time, 2))) + "\t " + \ str(memory) with open(self.pipeline_profile_file, "a") as myfile: myfile.write(message_raw + "\n")
Writes a string to self.pipeline_profile_file.
def iterative_stratification(node_label_matrix, training_set_size, number_of_categories, random_seed=0): """ Iterative data fold stratification/balancing for two folds. Based on: Sechidis, K., Tsoumakas, G., & Vlahavas, I. (2011). On the stratification of multi-label data. In Machine Learning and Knowledge Discovery in Databases (pp. 145-158). Springer Berlin Heidelberg. Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format. - training_set_size: The minimum required size for the training set. - number_of_categories: The number of categories/classes in the learning. - random_seed: A seed for numpy random. Outputs: - train_set: A NumPy array containing the training set node ids. - test_set: A NumPy array containing the testing set node ids. """ number_of_labelled_nodes = node_label_matrix.shape[0] testing_set_size = number_of_labelled_nodes - training_set_size training_set_proportion = training_set_size/number_of_labelled_nodes testing_set_proportion = testing_set_size/number_of_labelled_nodes # Calculate the desired number of examples of each label at each subset. desired_label_number = np.zeros((2, number_of_categories), dtype=np.int64) node_label_matrix = node_label_matrix.tocsc() for j in range(number_of_categories): category_label_number = node_label_matrix.getcol(j).indices.size desired_label_number[0, j] = math.ceil(category_label_number*training_set_proportion) desired_label_number[1, j] = category_label_number - desired_label_number[0, j] train_ids = list() test_ids = list() append_train_id = train_ids.append append_test_id = test_ids.append # Randomize process np.random.seed(random_seed) while True: if len(train_ids) + len(test_ids) >= number_of_labelled_nodes: break # Find the label with the fewest (but at least one) remaining examples, breaking the ties randomly remaining_label_distribution = desired_label_number.sum(axis=0) min_label = np.min(remaining_label_distribution[np.where(remaining_label_distribution > 0)[0]]) label_indices = np.where(remaining_label_distribution == min_label)[0] chosen_label = int(np.random.choice(label_indices, 1)[0]) # Find the subset with the largest number of desired examples for this label, # breaking ties by considering the largest number of desired examples, breaking further ties randomly. fold_max_remaining_labels = np.max(desired_label_number[:, chosen_label]) fold_indices = np.where(desired_label_number[:, chosen_label] == fold_max_remaining_labels)[0] chosen_fold = int(np.random.choice(fold_indices, 1)[0]) # Choose a random example for the selected label. relevant_nodes = node_label_matrix.getcol(chosen_label).indices chosen_node = int(np.random.choice(np.setdiff1d(relevant_nodes, np.union1d(np.array(train_ids), np.array(test_ids))), 1)[0]) if chosen_fold == 0: append_train_id(chosen_node) desired_label_number[0, node_label_matrix.getrow(chosen_node).indices] -= 1 elif chosen_fold == 1: append_test_id(chosen_node) desired_label_number[1, node_label_matrix.getrow(chosen_node).indices] -= 1 else: raise RuntimeError return np.array(train_ids), np.array(test_ids)
Iterative data fold stratification/balancing for two folds. Based on: Sechidis, K., Tsoumakas, G., & Vlahavas, I. (2011). On the stratification of multi-label data. In Machine Learning and Knowledge Discovery in Databases (pp. 145-158). Springer Berlin Heidelberg. Inputs: - node_label_matrix: The node-label ground truth in a SciPy sparse matrix format. - training_set_size: The minimum required size for the training set. - number_of_categories: The number of categories/classes in the learning. - random_seed: A seed for numpy random. Outputs: - train_set: A NumPy array containing the training set node ids. - test_set: A NumPy array containing the testing set node ids.
def get_limits(self, limit_sum=None): """ Gets the current limit data if it is different from the data indicated by limit_sum. The db argument is used for hydrating the limit objects. Raises a NoChangeException if the limit_sum represents no change, otherwise returns a tuple consisting of the current limit_sum and a list of Limit objects. """ with self.limit_lock: # Any changes? if limit_sum and self.limit_sum == limit_sum: raise NoChangeException() # Return a tuple of the limits and limit sum return (self.limit_sum, self.limit_data)
Gets the current limit data if it is different from the data indicated by limit_sum. The db argument is used for hydrating the limit objects. Raises a NoChangeException if the limit_sum represents no change, otherwise returns a tuple consisting of the current limit_sum and a list of Limit objects.
def do_video(self, args): """Video management command demonstrates multiple layers of sub-commands being handled by AutoCompleter""" func = getattr(args, 'func', None) if func is not None: # Call whatever subcommand function was selected func(self, args) else: # No subcommand was provided, so call help self.do_help('video')
Video management command demonstrates multiple layers of sub-commands being handled by AutoCompleter
def copy_assets(self, path='assets'): """ Copy assets into the destination directory. """ path = os.path.join(self.root_path, path) for root, _, files in os.walk(path): for file in files: fullpath = os.path.join(root, file) relpath = os.path.relpath(fullpath, path) copy_to = os.path.join(self._get_dist_path(relpath, directory='assets')) LOG.debug('copying %r to %r', fullpath, copy_to) shutil.copyfile(fullpath, copy_to)
Copy assets into the destination directory.
def nvmlDeviceGetBoardId(handle): r""" /** * Retrieves the device boardId from 0-N. * Devices with the same boardId indicate GPUs connected to the same PLX. Use in conjunction with * \ref nvmlDeviceGetMultiGpuBoard() to decide if they are on the same board as well. * The boardId returned is a unique ID for the current configuration. Uniqueness and ordering across * reboots and system configurations is not guaranteed (i.e. if a Tesla K40c returns 0x100 and * the two GPUs on a Tesla K10 in the same system returns 0x200 it is not guaranteed they will * always return those values but they will always be different from each other). * * * For Fermi &tm; or newer fully supported devices. * * @param device The identifier of the target device * @param boardId Reference in which to return the device's board ID * * @return * - \ref NVML_SUCCESS if \a boardId has been set * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a boardId is NULL * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible * - \ref NVML_ERROR_UNKNOWN on any unexpected error */ nvmlReturn_t DECLDIR nvmlDeviceGetBoardId """ c_id = c_uint(); fn = _nvmlGetFunctionPointer("nvmlDeviceGetBoardId") ret = fn(handle, byref(c_id)) _nvmlCheckReturn(ret) return bytes_to_str(c_id.value)
r""" /** * Retrieves the device boardId from 0-N. * Devices with the same boardId indicate GPUs connected to the same PLX. Use in conjunction with * \ref nvmlDeviceGetMultiGpuBoard() to decide if they are on the same board as well. * The boardId returned is a unique ID for the current configuration. Uniqueness and ordering across * reboots and system configurations is not guaranteed (i.e. if a Tesla K40c returns 0x100 and * the two GPUs on a Tesla K10 in the same system returns 0x200 it is not guaranteed they will * always return those values but they will always be different from each other). * * * For Fermi &tm; or newer fully supported devices. * * @param device The identifier of the target device * @param boardId Reference in which to return the device's board ID * * @return * - \ref NVML_SUCCESS if \a boardId has been set * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a boardId is NULL * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible * - \ref NVML_ERROR_UNKNOWN on any unexpected error */ nvmlReturn_t DECLDIR nvmlDeviceGetBoardId
def reset(self, force_flush_cache: bool = False) -> None: """ Reset transaction back to original state, discarding all uncompleted transactions. """ super(LDAPwrapper, self).reset() if len(self._transactions) == 0: raise RuntimeError("reset called outside a transaction.") self._transactions[-1] = []
Reset transaction back to original state, discarding all uncompleted transactions.
def resource_request_send(self, request_id, uri_type, uri, transfer_type, storage, force_mavlink1=False): ''' The autopilot is requesting a resource (file, binary, other type of data) request_id : Request ID. This ID should be re-used when sending back URI contents (uint8_t) uri_type : The type of requested URI. 0 = a file via URL. 1 = a UAVCAN binary (uint8_t) uri : The requested unique resource identifier (URI). It is not necessarily a straight domain name (depends on the URI type enum) (uint8_t) transfer_type : The way the autopilot wants to receive the URI. 0 = MAVLink FTP. 1 = binary stream. (uint8_t) storage : The storage path the autopilot wants the URI to be stored in. Will only be valid if the transfer_type has a storage associated (e.g. MAVLink FTP). (uint8_t) ''' return self.send(self.resource_request_encode(request_id, uri_type, uri, transfer_type, storage), force_mavlink1=force_mavlink1)
The autopilot is requesting a resource (file, binary, other type of data) request_id : Request ID. This ID should be re-used when sending back URI contents (uint8_t) uri_type : The type of requested URI. 0 = a file via URL. 1 = a UAVCAN binary (uint8_t) uri : The requested unique resource identifier (URI). It is not necessarily a straight domain name (depends on the URI type enum) (uint8_t) transfer_type : The way the autopilot wants to receive the URI. 0 = MAVLink FTP. 1 = binary stream. (uint8_t) storage : The storage path the autopilot wants the URI to be stored in. Will only be valid if the transfer_type has a storage associated (e.g. MAVLink FTP). (uint8_t)
def receive(self, msg): ''' The message received from the queue specify a method of the class the actor represents. This invokes it. If the communication is an ASK, sends the result back to the channel included in the message as an ASKRESPONSE. If it is a FUTURE, generates a FUTURERESPONSE to send the result to the manager. :param msg: The message is a dictionary using the constants defined in util.py (:mod:`pyactor.util`). ''' if msg[TYPE] == TELL and msg[METHOD] == 'stop': self.running = False self.future_manager.stop() else: result = None try: invoke = getattr(self._obj, msg[METHOD]) params = msg[PARAMS] result = invoke(*params[0], **params[1]) except Exception, e: if msg[TYPE] == TELL: print e return result = e self.send_response(result, msg)
The message received from the queue specify a method of the class the actor represents. This invokes it. If the communication is an ASK, sends the result back to the channel included in the message as an ASKRESPONSE. If it is a FUTURE, generates a FUTURERESPONSE to send the result to the manager. :param msg: The message is a dictionary using the constants defined in util.py (:mod:`pyactor.util`).
def match_handle(loc, tokens): """Process match blocks.""" if len(tokens) == 4: matches, match_type, item, stmts = tokens cond = None elif len(tokens) == 5: matches, match_type, item, cond, stmts = tokens else: raise CoconutInternalException("invalid match statement tokens", tokens) if match_type == "in": invert = False elif match_type == "not in": invert = True else: raise CoconutInternalException("invalid match type", match_type) matching = Matcher(loc, match_check_var) matching.match(matches, match_to_var) if cond: matching.add_guard(cond) return ( match_to_var + " = " + item + "\n" + matching.build(stmts, invert=invert) )
Process match blocks.
def to_string_short(self): """ see also :meth:`to_string` :return: a shorter abreviated string reprentation of the parameter """ opt = np.get_printoptions() np.set_printoptions(threshold=8, edgeitems=3, linewidth=opt['linewidth']-len(self.uniquetwig)-2) str_ = super(FloatArrayParameter, self).to_string_short() np.set_printoptions(**opt) return str_
see also :meth:`to_string` :return: a shorter abreviated string reprentation of the parameter
def start(ctx, alias, description, f): """ Use it when you start working on the given activity. This will add the activity and the current time to your entries file. When you're finished, use the stop command. """ today = datetime.date.today() try: timesheet_collection = get_timesheet_collection_for_context(ctx, f) except ParseError as e: ctx.obj['view'].err(e) return t = timesheet_collection.latest() # If there's a previous entry on the same date, check if we can use its # end time as a start time for the newly started entry today_entries = t.entries.filter(date=today) if(today in today_entries and today_entries[today] and isinstance(today_entries[today][-1].duration, tuple) and today_entries[today][-1].duration[1] is not None): new_entry_start_time = today_entries[today][-1].duration[1] else: new_entry_start_time = datetime.datetime.now() description = ' '.join(description) if description else '?' duration = (new_entry_start_time, None) e = Entry(alias, duration, description) t.entries[today].append(e) t.save()
Use it when you start working on the given activity. This will add the activity and the current time to your entries file. When you're finished, use the stop command.
def insertIndividual(self, individual): """ Inserts the specified individual into this repository. """ try: models.Individual.create( id=individual.getId(), datasetId=individual.getParentContainer().getId(), name=individual.getLocalId(), description=individual.getDescription(), created=individual.getCreated(), updated=individual.getUpdated(), species=json.dumps(individual.getSpecies()), sex=json.dumps(individual.getSex()), attributes=json.dumps(individual.getAttributes())) except Exception: raise exceptions.DuplicateNameException( individual.getLocalId(), individual.getParentContainer().getLocalId())
Inserts the specified individual into this repository.
def validate_valid_transition(enum, from_value, to_value): """ Validate that to_value is a valid choice and that to_value is a valid transition from from_value. """ validate_available_choice(enum, to_value) if hasattr(enum, '_transitions') and not enum.is_valid_transition(from_value, to_value): message = _(six.text_type('{enum} can not go from "{from_value}" to "{to_value}"')) raise InvalidStatusOperationError(message.format( enum=enum.__name__, from_value=enum.name(from_value), to_value=enum.name(to_value) or to_value ))
Validate that to_value is a valid choice and that to_value is a valid transition from from_value.
def MessageSetItemEncoder(field_number): """Encoder for extensions of MessageSet. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } } """ start_bytes = b"".join([ TagBytes(1, wire_format.WIRETYPE_START_GROUP), TagBytes(2, wire_format.WIRETYPE_VARINT), _VarintBytes(field_number), TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)]) end_bytes = TagBytes(1, wire_format.WIRETYPE_END_GROUP) local_EncodeVarint = _EncodeVarint def EncodeField(write, value): write(start_bytes) local_EncodeVarint(write, value.ByteSize()) value._InternalSerialize(write) return write(end_bytes) return EncodeField
Encoder for extensions of MessageSet. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; required string message = 3; } }
def set_status(self, status): """ Save the new status and call all defined callbacks """ self.status = status for callback in self._update_status_callbacks: callback(self)
Save the new status and call all defined callbacks
def upvoters(self): """่Žทๅ–ๆ–‡็ซ ็š„็‚น่ตž็”จๆˆท :return: ๆ–‡็ซ ็š„็‚น่ตž็”จๆˆท๏ผŒ่ฟ”ๅ›ž็”Ÿๆˆๅ™จใ€‚ """ from .author import Author, ANONYMOUS self._make_soup() headers = dict(Default_Header) headers['Host'] = 'zhuanlan.zhihu.com' json = self._session.get( Post_Get_Upvoter.format(self.slug), headers=headers ).json() for au in json: try: yield Author( au['profileUrl'], au['name'], au['bio'], photo_url=au['avatar']['template'].format( id=au['avatar']['id'], size='r'), session=self._session ) except ValueError: # invalid url yield ANONYMOUS
่Žทๅ–ๆ–‡็ซ ็š„็‚น่ตž็”จๆˆท :return: ๆ–‡็ซ ็š„็‚น่ตž็”จๆˆท๏ผŒ่ฟ”ๅ›ž็”Ÿๆˆๅ™จใ€‚
async def get(self, request): """Get collection of resources.""" form = await self.get_form(request) ctx = dict(active=self, form=form, request=request) if self.resource: return self.app.ps.jinja2.render(self.template_item, **ctx) return self.app.ps.jinja2.render(self.template_list, **ctx)
Get collection of resources.
def replace_cells(self, key, sorted_row_idxs): """Replaces cells in current selection so that they are sorted""" row, col, tab = key new_keys = {} del_keys = [] selection = self.grid.actions.get_selection() for __row, __col, __tab in self.grid.code_array: if __tab == tab and \ (not selection or (__row, __col) in selection): new_row = sorted_row_idxs.index(__row) if __row != new_row: new_keys[(new_row, __col, __tab)] = \ self.grid.code_array((__row, __col, __tab)) del_keys.append((__row, __col, __tab)) for key in del_keys: self.grid.code_array.pop(key) for key in new_keys: CellActions.set_code(self, key, new_keys[key])
Replaces cells in current selection so that they are sorted
def unique(series: pd.Series) -> pd.Series: """Test that the data items do not repeat.""" return ~series.duplicated(keep=False)
Test that the data items do not repeat.
def parse_requirements(file_): """Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to parse. Raises: OSerror: If there's any issues accessing the file. Returns: tuple: The contents of the file, excluding comments. """ modules = [] delim = ["<", ">", "=", "!", "~"] # https://www.python.org/dev/peps/pep-0508/#complete-grammar try: f = open_func(file_, "r") except OSError: logging.error("Failed on file: {}".format(file_)) raise else: data = [x.strip() for x in f.readlines() if x != "\n"] finally: f.close() data = [x for x in data if x[0].isalpha()] for x in data: if not any([y in x for y in delim]): # Check for modules w/o a specifier. modules.append({"name": x, "version": None}) for y in x: if y in delim: module = x.split(y) module_name = module[0] module_version = module[-1].replace("=", "") module = {"name": module_name, "version": module_version} if module not in modules: modules.append(module) break return modules
Parse a requirements formatted file. Traverse a string until a delimiter is detected, then split at said delimiter, get module name by element index, create a dict consisting of module:version, and add dict to list of parsed modules. Args: file_: File to parse. Raises: OSerror: If there's any issues accessing the file. Returns: tuple: The contents of the file, excluding comments.
def codingthreads(self): """ Find CDS features in .gff files to filter out non-coding sequences from the analysis """ printtime('Extracting CDS features', self.start) # Create and start threads for i in range(self.cpus): # Send the threads to the appropriate destination function threads = Thread(target=self.codingsequences, args=()) # Set the daemon to true - something to do with thread management threads.setDaemon(True) # Start the threading threads.start() for sample in self.runmetadata.samples: self.codingqueue.put(sample) self.codingqueue.join() # Create CDS files and determine gene presence/absence self.corethreads()
Find CDS features in .gff files to filter out non-coding sequences from the analysis
def phonenumber(anon, obj, field, val): """ Generates a random US-style phone number """ return anon.faker.phone_number(field=field)
Generates a random US-style phone number
def tag_syntax(self): """ Parses this text with the syntactic analyzer (``self.__syntactic_parser``), and stores the found syntactic analyses: into the layer LAYER_CONLL (if MaltParser is used, default), or into the layer LAYER_VISLCG3 (if VISLCG3Parser is used). """ # Load default Syntactic tagger: if self.__syntactic_parser is None: self.__syntactic_parser = load_default_syntactic_parser() if not self.is_tagged(ANALYSIS): if isinstance(self.__syntactic_parser, MaltParser): # By default: Use disambiguation for MaltParser's input if 'disambiguate' not in self.__kwargs: self.__kwargs['disambiguate'] = True self.tag_analysis() elif isinstance(self.__syntactic_parser, VISLCG3Parser): # By default: Do not use disambiguation for VISLCG3Parser's input # (VISLCG3 already does its own rule-based disambiguation) if 'disambiguate' not in self.__kwargs: self.__kwargs['disambiguate'] = False self.tag_analysis() return self.__syntactic_parser.parse_text( self, **self.__kwargs )
Parses this text with the syntactic analyzer (``self.__syntactic_parser``), and stores the found syntactic analyses: into the layer LAYER_CONLL (if MaltParser is used, default), or into the layer LAYER_VISLCG3 (if VISLCG3Parser is used).
def async_lru(size=100): """ An LRU cache for asyncio coroutines in Python 3.5 .. @async_lru(1024) async def slow_coroutine(*args, **kwargs): return await some_other_slow_coroutine() .. """ cache = collections.OrderedDict() def decorator(fn): @wraps(fn) @asyncio.coroutine def memoizer(*args, **kwargs): key = str((args, kwargs)) try: result = cache.pop(key) cache[key] = result except KeyError: if len(cache) >= size: cache.popitem(last=False) result = cache[key] = yield from fn(*args, **kwargs) return result return memoizer return decorator
An LRU cache for asyncio coroutines in Python 3.5 .. @async_lru(1024) async def slow_coroutine(*args, **kwargs): return await some_other_slow_coroutine() ..
def get_connection(self, url, proxies=None): """Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool """ proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL("Please check proxy URL. It is malformed" " and could be missing the host.") proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool
def getTCPportConnStatus(self, ipv4=True, ipv6=True, include_listen=False, **kwargs): """Returns the number of TCP endpoints discriminated by status. @param ipv4: Include IPv4 ports in output if True. @param ipv6: Include IPv6 ports in output if True. @param include_listen: Include listening ports in output if True. @param **kwargs: Keyword variables are used for filtering the results depending on the values of the columns. Each keyword must correspond to a field name with an optional suffix: field: Field equal to value or in list of values. field_ic: Field equal to value or in list of values, using case insensitive comparison. field_regex: Field matches regex value or matches with any regex in list of values. field_ic_regex: Field matches regex value or matches with any regex in list of values using case insensitive match. @return: Dictionary mapping connection status to the number of endpoints. """ status_dict = {} result = self.getStats(tcp=True, udp=False, include_listen=include_listen, ipv4=ipv4, ipv6=ipv6, **kwargs) stats = result['stats'] for stat in stats: if stat is not None: status = stat[8].lower() status_dict[status] = status_dict.get(status, 0) + 1 return status_dict
Returns the number of TCP endpoints discriminated by status. @param ipv4: Include IPv4 ports in output if True. @param ipv6: Include IPv6 ports in output if True. @param include_listen: Include listening ports in output if True. @param **kwargs: Keyword variables are used for filtering the results depending on the values of the columns. Each keyword must correspond to a field name with an optional suffix: field: Field equal to value or in list of values. field_ic: Field equal to value or in list of values, using case insensitive comparison. field_regex: Field matches regex value or matches with any regex in list of values. field_ic_regex: Field matches regex value or matches with any regex in list of values using case insensitive match. @return: Dictionary mapping connection status to the number of endpoints.
def write(series, output, scale=None): """Write a `TimeSeries` to a WAV file Parameters ---------- series : `TimeSeries` the series to write output : `file`, `str` the file object or filename to write to scale : `float`, optional the factor to apply to scale the data to (-1.0, 1.0), pass `scale=1` to not apply any scale, otherwise the data will be auto-scaled See also -------- scipy.io.wavfile.write for details on how the WAV file is actually written Examples -------- >>> from gwpy.timeseries import TimeSeries >>> t = TimeSeries([1, 2, 3, 4, 5]) >>> t = TimeSeries.write('test.wav') """ fsamp = int(series.sample_rate.decompose().value) if scale is None: scale = 1 / numpy.abs(series.value).max() data = (series.value * scale).astype('float32') return wavfile.write(output, fsamp, data)
Write a `TimeSeries` to a WAV file Parameters ---------- series : `TimeSeries` the series to write output : `file`, `str` the file object or filename to write to scale : `float`, optional the factor to apply to scale the data to (-1.0, 1.0), pass `scale=1` to not apply any scale, otherwise the data will be auto-scaled See also -------- scipy.io.wavfile.write for details on how the WAV file is actually written Examples -------- >>> from gwpy.timeseries import TimeSeries >>> t = TimeSeries([1, 2, 3, 4, 5]) >>> t = TimeSeries.write('test.wav')
def fire(data, tag, timeout=None): ''' Fire an event on the local minion event bus. Data must be formed as a dict. CLI Example: .. code-block:: bash salt '*' event.fire '{"data":"my event data"}' 'tag' ''' if timeout is None: timeout = 60000 else: timeout = timeout * 1000 try: event = salt.utils.event.get_event(__opts__.get('__role', 'minion'), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'], opts=__opts__, keep_loop=True, listen=False) return event.fire_event(data, tag, timeout=timeout) except Exception: exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) log.debug(lines) return False
Fire an event on the local minion event bus. Data must be formed as a dict. CLI Example: .. code-block:: bash salt '*' event.fire '{"data":"my event data"}' 'tag'
def _get_containers(self): """Return available containers.""" def full_fn(path): return os.path.join(self.abs_root, path) return [self.cont_cls.from_path(self, d) for d in os.listdir(self.abs_root) if is_dir(full_fn(d))]
Return available containers.
def handle_data(self, data): ''' handle_data - Internal for parsing ''' if data: inTag = self._inTag if len(inTag) > 0: if inTag[-1].tagName not in PRESERVE_CONTENTS_TAGS: data = data.replace('\t', ' ').strip('\r\n') if data.startswith(' '): data = ' ' + data.lstrip() if data.endswith(' '): data = data.rstrip() + ' ' inTag[-1].appendText(data) elif data.strip(): # Must be text prior to or after root node raise MultipleRootNodeException()
handle_data - Internal for parsing
def auc(x, y, reorder=False): #from sklearn, http://scikit-learn.org, licensed under BSD License """Compute Area Under the Curve (AUC) using the trapezoidal rule This is a general fuction, given points on a curve. For computing the area under the ROC-curve, see :func:`auc_score`. Parameters ---------- x : array, shape = [n] x coordinates. y : array, shape = [n] y coordinates. reorder : boolean, optional (default=False) If True, assume that the curve is ascending in the case of ties, as for an ROC curve. If the curve is non-ascending, the result will be wrong. Returns ------- auc : float Examples -------- >>> import numpy as np >>> from sklearn import metrics >>> y = np.array([1, 1, 2, 2]) >>> pred = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2) >>> metrics.auc(fpr, tpr) 0.75 See also -------- auc_score : Computes the area under the ROC curve """ if np is None: raise ImportError("No numpy installed") # XXX: Consider using ``scipy.integrate`` instead, or moving to # ``utils.extmath`` if not isinstance(x, np.ndarray): x = np.array(x) if not isinstance(x, np.ndarray): y = np.array(y) if x.shape[0] < 2: raise ValueError('At least 2 points are needed to compute' ' area under curve, but x.shape = %s' % x.shape) if reorder: # reorder the data points according to the x axis and using y to # break ties x, y = np.array(sorted(points for points in zip(x, y))).T h = np.diff(x) else: h = np.diff(x) if np.any(h < 0): h *= -1 assert not np.any(h < 0), ("Reordering is not turned on, and " "The x array is not increasing: %s" % x) area = np.sum(h * (y[1:] + y[:-1])) / 2.0 return area
Compute Area Under the Curve (AUC) using the trapezoidal rule This is a general fuction, given points on a curve. For computing the area under the ROC-curve, see :func:`auc_score`. Parameters ---------- x : array, shape = [n] x coordinates. y : array, shape = [n] y coordinates. reorder : boolean, optional (default=False) If True, assume that the curve is ascending in the case of ties, as for an ROC curve. If the curve is non-ascending, the result will be wrong. Returns ------- auc : float Examples -------- >>> import numpy as np >>> from sklearn import metrics >>> y = np.array([1, 1, 2, 2]) >>> pred = np.array([0.1, 0.4, 0.35, 0.8]) >>> fpr, tpr, thresholds = metrics.roc_curve(y, pred, pos_label=2) >>> metrics.auc(fpr, tpr) 0.75 See also -------- auc_score : Computes the area under the ROC curve
def get(self, account_id): """ Return a specific account given its ID """ response = self.client._make_request('/accounts/{0}'.format(account_id)) return response.json()
Return a specific account given its ID
def find_skill(self, param, author=None, skills=None): # type: (str, str, List[SkillEntry]) -> SkillEntry """Find skill by name or url""" if param.startswith('https://') or param.startswith('http://'): repo_id = SkillEntry.extract_repo_id(param) for skill in self.list(): if skill.id == repo_id: return skill name = SkillEntry.extract_repo_name(param) path = SkillEntry.create_path(self.skills_dir, param) return SkillEntry(name, path, param, msm=self) else: skill_confs = { skill: skill.match(param, author) for skill in skills or self.list() } best_skill, score = max(skill_confs.items(), key=lambda x: x[1]) LOG.info('Best match ({}): {} by {}'.format( round(score, 2), best_skill.name, best_skill.author) ) if score < 0.3: raise SkillNotFound(param) low_bound = (score * 0.7) if score != 1.0 else 1.0 close_skills = [ skill for skill, conf in skill_confs.items() if conf >= low_bound and skill != best_skill ] if close_skills: raise MultipleSkillMatches([best_skill] + close_skills) return best_skill
Find skill by name or url
def use_federated_repository_view(self): """Pass through to provider AssetLookupSession.use_federated_repository_view""" self._repository_view = FEDERATED # self._get_provider_session('asset_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_federated_repository_view() except AttributeError: pass
Pass through to provider AssetLookupSession.use_federated_repository_view
def unique_rows(data, digits=None): """ Returns indices of unique rows. It will return the first occurrence of a row that is duplicated: [[1,2], [3,4], [1,2]] will return [0,1] Parameters --------- data: (n,m) set of floating point data digits: how many digits to consider for the purposes of uniqueness Returns -------- unique: (j) array, index in data which is a unique row inverse: (n) length array to reconstruct original example: unique[inverse] == data """ hashes = hashable_rows(data, digits=digits) garbage, unique, inverse = np.unique(hashes, return_index=True, return_inverse=True) return unique, inverse
Returns indices of unique rows. It will return the first occurrence of a row that is duplicated: [[1,2], [3,4], [1,2]] will return [0,1] Parameters --------- data: (n,m) set of floating point data digits: how many digits to consider for the purposes of uniqueness Returns -------- unique: (j) array, index in data which is a unique row inverse: (n) length array to reconstruct original example: unique[inverse] == data
def barplot(bars, title='', upColor='blue', downColor='red'): """ Create candlestick plot for the given bars. The bars can be given as a DataFrame or as a list of bar objects. """ import pandas as pd import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Rectangle if isinstance(bars, pd.DataFrame): ohlcTups = [ tuple(v) for v in bars[['open', 'high', 'low', 'close']].values] elif bars and hasattr(bars[0], 'open_'): ohlcTups = [(b.open_, b.high, b.low, b.close) for b in bars] else: ohlcTups = [(b.open, b.high, b.low, b.close) for b in bars] fig, ax = plt.subplots() ax.set_title(title) ax.grid(True) fig.set_size_inches(10, 6) for n, (open_, high, low, close) in enumerate(ohlcTups): if close >= open_: color = upColor bodyHi, bodyLo = close, open_ else: color = downColor bodyHi, bodyLo = open_, close line = Line2D( xdata=(n, n), ydata=(low, bodyLo), color=color, linewidth=1) ax.add_line(line) line = Line2D( xdata=(n, n), ydata=(high, bodyHi), color=color, linewidth=1) ax.add_line(line) rect = Rectangle( xy=(n - 0.3, bodyLo), width=0.6, height=bodyHi - bodyLo, edgecolor=color, facecolor=color, alpha=0.4, antialiased=True ) ax.add_patch(rect) ax.autoscale_view() return fig
Create candlestick plot for the given bars. The bars can be given as a DataFrame or as a list of bar objects.