code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def on_state_changed(self, state): """ Connects/Disconnects to the painted event of the editor :param state: Enable state """ if state: self.editor.painted.connect(self._paint_margin) self.editor.repaint() else: self.editor.painted.dis...
Connects/Disconnects to the painted event of the editor :param state: Enable state
def write_index_and_rst_files(self, overwrite: bool = False, mock: bool = False) -> None: """ Writes both the individual RST files and the index. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't ...
Writes both the individual RST files and the index. Args: overwrite: allow existing files to be overwritten? mock: pretend to write, but don't
def murmur_hash3_x86_32(data, offset, size, seed=0x01000193): """ murmur3 hash function to determine partition :param data: (byte array), input byte array :param offset: (long), offset. :param size: (long), byte length. :param seed: murmur hash seed hazelcast uses 0x01000193 :return: (int32...
murmur3 hash function to determine partition :param data: (byte array), input byte array :param offset: (long), offset. :param size: (long), byte length. :param seed: murmur hash seed hazelcast uses 0x01000193 :return: (int32), calculated hash value.
def subdir_findall(dir, subdir): """ Find all files in a subdirectory and return paths relative to dir This is similar to (and uses) setuptools.findall However, the paths returned are in the form needed for package_data """ strip_n = len(dir.split('/')) path = '/'.join((dir, subdir)) re...
Find all files in a subdirectory and return paths relative to dir This is similar to (and uses) setuptools.findall However, the paths returned are in the form needed for package_data
def update_event(self, event, uid): """Edit event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be updated) uid : uid of event to be updated """ ev_for_change = self.calendar.get(uid) ev_for_change.cont...
Edit event Parameters ---------- event : iCalendar file as a string (calendar containing one event to be updated) uid : uid of event to be updated
def get_meta_fields(self, fields, kwargs={}): ''' Return a dictionary of metadata fields ''' fields = to_list(fields) meta = self.get_meta() return {field: meta.get(field) for field in fields}
Return a dictionary of metadata fields
def brightness_multi(x, gamma=1, gain=1, is_random=False): """Change the brightness of multiply images, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpyarray List of images with dimension of ...
Change the brightness of multiply images, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpyarray List of images with dimension of [n_images, row, col, channel] (default). others : args ...
def _apply_sources(self): """r Update 'A' and 'b' applying source terms to specified pores Notes ----- Applying source terms to 'A' and 'b' is performed after (optionally) under-relaxing the source term to improve numerical stability. Physics are also updated bef...
r Update 'A' and 'b' applying source terms to specified pores Notes ----- Applying source terms to 'A' and 'b' is performed after (optionally) under-relaxing the source term to improve numerical stability. Physics are also updated before applying source terms to ensure t...
def _reset(self): """Clear internal data structure.""" self.records = list() self.featsbyid = dict() self.featsbyparent = dict() self.countsbytype = dict()
Clear internal data structure.
def _payload(fields, values): """Implement the ``*_payload`` methods. It's frequently useful to create a dict of values that can be encoded to JSON and sent to the server. Unfortunately, there are mismatches between the field names used by NailGun and the field names the server expects. This method...
Implement the ``*_payload`` methods. It's frequently useful to create a dict of values that can be encoded to JSON and sent to the server. Unfortunately, there are mismatches between the field names used by NailGun and the field names the server expects. This method provides a default translation that ...
def namedtuple_with_defaults(typename, field_names, default_values=[]): """Create a namedtuple with default values >>> Node = namedtuple_with_defaults('Node', 'val left right') >>> Node() Node(val=None, left=None, right=None) >>> Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3]) ...
Create a namedtuple with default values >>> Node = namedtuple_with_defaults('Node', 'val left right') >>> Node() Node(val=None, left=None, right=None) >>> Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3]) >>> Node() Node(val=1, left=2, right=3) >>> Node = namedtuple_with_...
def connect(self, source, target, witnesses): """ :type source: integer :type target: integer """ # print("Adding Edge: "+source+":"+target) if self.graph.has_edge(source, target): self.graph[source][target]["label"] += ", " + str(witnesses) else: ...
:type source: integer :type target: integer
def has_layer(self, class_: Type[L], became: bool=True) -> bool: """ Test the presence of a given layer type. :param class_: Layer class you're interested in. :param became: Allow transformed layers in results """ return (class_ in self._index or (became...
Test the presence of a given layer type. :param class_: Layer class you're interested in. :param became: Allow transformed layers in results
def interval_intersection_width(a, b, c, d): """returns the width of the intersection of intervals [a,b] and [c,d] (thinking of these as intervals on the real number line)""" return max(0, min(b, d) - max(a, c))
returns the width of the intersection of intervals [a,b] and [c,d] (thinking of these as intervals on the real number line)
def append_column(self, header, column): """Append a column to end of the table. Parameters ---------- header : str Title of the column column : iterable Any iterable of appropriate length. """ self.insert_column(self._column_count, heade...
Append a column to end of the table. Parameters ---------- header : str Title of the column column : iterable Any iterable of appropriate length.
def extraction_to_conll(ex: Extraction) -> List[str]: """ Return a conll representation of a given input Extraction. """ ex = split_predicate(ex) toks = ex.sent.split(' ') ret = ['*'] * len(toks) args = [ex.arg1] + ex.args2 rels_and_args = [("ARG{}".format(arg_ind), arg) ...
Return a conll representation of a given input Extraction.
def parse_list_objects_v2(data, bucket_name): """ Parser for list objects version 2 response. :param data: Response data for list objects. :param bucket_name: Response for the bucket. :return: Returns three distinct components: - List of :class:`Object <Object>` - True if list is trun...
Parser for list objects version 2 response. :param data: Response data for list objects. :param bucket_name: Response for the bucket. :return: Returns three distinct components: - List of :class:`Object <Object>` - True if list is truncated, False otherwise. - Continuation Token for th...
def op(cls,text,*args,**kwargs): """ This method must be overriden in derived classes """ return cls.fn(text,*args,**kwargs)
This method must be overriden in derived classes
def run_simulations(self, parameter_list, data_folder): """ Run several simulations using a certain combination of parameters. Yields results as simulations are completed. Args: parameter_list (list): list of parameter combinations to simulate. data_folder (str)...
Run several simulations using a certain combination of parameters. Yields results as simulations are completed. Args: parameter_list (list): list of parameter combinations to simulate. data_folder (str): folder in which to save subfolders containing simulation o...
def transform(self, transformer): """ Add transformer to flow and apply transformer to data in flow Parameters ---------- transformer : Transformer a transformer to transform data """ self.transformers.append(transformer) from languageflow.tra...
Add transformer to flow and apply transformer to data in flow Parameters ---------- transformer : Transformer a transformer to transform data
def addDrizKeywords(self,hdr,versions): """ Add drizzle parameter keywords to header. """ # Extract some global information for the keywords _geom = 'User parameters' _imgnum = 0 for pl in self.parlist: # Start by building up the keyword prefix based # ...
Add drizzle parameter keywords to header.
def applyHotspot(self, lon, lat): """ Exclude objects that are too close to hotspot True if passes hotspot cut """ self.loadRealResults() cut_detect_real = (self.data_real['SIG'] >= self.config[self.algorithm]['sig_threshold']) lon_real = self.data_real['RA'][cut...
Exclude objects that are too close to hotspot True if passes hotspot cut
def notify(self, level, value, target=None, ntype=None, rule=None): """Notify main reactor about event.""" # Did we see the event before? if target in self.state and level == self.state[target]: return False # Do we see the event first time? if target not in self.sta...
Notify main reactor about event.
def variables(template): '''Returns the set of keywords in a uri template''' vars = set() for varlist in TEMPLATE.findall(template): if varlist[0] in OPERATOR: varlist = varlist[1:] varspecs = varlist.split(',') for var in varspecs: # handle prefix values ...
Returns the set of keywords in a uri template
def leaveEvent(self, event): """If cursor has not been restored yet, do it now""" if self.__cursor_changed: QApplication.restoreOverrideCursor() self.__cursor_changed = False self.QT_CLASS.leaveEvent(self, event)
If cursor has not been restored yet, do it now
def from_dict(data, ctx): """ Instantiate a new UnitsAvailable from a dict (generally from loading a JSON response). The data used to instantiate the UnitsAvailable is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ ...
Instantiate a new UnitsAvailable from a dict (generally from loading a JSON response). The data used to instantiate the UnitsAvailable is a shallow copy of the dict passed in, with any complex child types instantiated appropriately.
def standard_to_absl(level): """Converts an integer level from the standard value to the absl value. Args: level: int, a Python standard logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in absl logging. """ if not isinstan...
Converts an integer level from the standard value to the absl value. Args: level: int, a Python standard logging level. Raises: TypeError: Raised when level is not an integer. Returns: The corresponding integer level for use in absl logging.
def get_docs(r_session, url, encoder=None, headers=None, **params): """ Provides a helper for functions that require GET or POST requests with a JSON, text, or raw response containing documents. :param r_session: Authentication session from the client :param str url: URL containing the endpoint ...
Provides a helper for functions that require GET or POST requests with a JSON, text, or raw response containing documents. :param r_session: Authentication session from the client :param str url: URL containing the endpoint :param JSONEncoder encoder: Custom encoder from the client :param dict head...
def validateAQLQuery(self, query, bindVars = None, options = None) : "returns the server answer is the query is valid. Raises an AQLQueryError if not" if bindVars is None : bindVars = {} if options is None : options = {} payload = {'query' : query, 'bindVars' : bi...
returns the server answer is the query is valid. Raises an AQLQueryError if not
def compute_log_degrees(brands, exemplars): """ For each follower, let Z be the total number of brands they follow. Return a dictionary of 1. / log(Z), for each follower. """ counts = Counter() for followers in brands.values(): # + exemplars.values(): # Include exemplars in these counts? No, don't...
For each follower, let Z be the total number of brands they follow. Return a dictionary of 1. / log(Z), for each follower.
def _load_history_from_file(path, size=-1): """Load a history list from a file and split it into lines. :param path: the path to the file that should be loaded :type path: str :param size: the number of lines to load (0 means no lines, < 0 means all lines) :type size...
Load a history list from a file and split it into lines. :param path: the path to the file that should be loaded :type path: str :param size: the number of lines to load (0 means no lines, < 0 means all lines) :type size: int :returns: a list of history items (the li...
def cli(env, identifier): """View details of a placement group. IDENTIFIER can be either the Name or Id of the placement group you want to view """ manager = PlacementManager(env.client) group_id = helpers.resolve_id(manager.resolve_ids, identifier, 'placement_group') result = manager.get_objec...
View details of a placement group. IDENTIFIER can be either the Name or Id of the placement group you want to view
def build(self, builder): """Build XML by appending to builder""" params = {} if self.edit_point is not None: params["EditPoint"] = self.edit_point if self.used_imputation_method is not None: params['UsedImputationMethod'] = bool_to_yes_no(self.used_imputation_m...
Build XML by appending to builder
def rotate(name, **kwargs): ''' Add a log to the logadm configuration name : string alias for entryname kwargs : boolean|string|int optional additional flags and parameters ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} ...
Add a log to the logadm configuration name : string alias for entryname kwargs : boolean|string|int optional additional flags and parameters
def _get_or_insert(*args, **kwds): """Transactionally retrieves an existing entity or creates a new one. Positional Args: name: Key name to retrieve or create. Keyword Args: namespace: Optional namespace. app: Optional app ID. parent: Parent entity key, if any. context_option...
Transactionally retrieves an existing entity or creates a new one. Positional Args: name: Key name to retrieve or create. Keyword Args: namespace: Optional namespace. app: Optional app ID. parent: Parent entity key, if any. context_options: ContextOptions object (not keyword args...
def initLogger(): ''' This code taken from Matt's Suspenders for initializing a logger ''' global logger logger = logging.getLogger('root') logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) formatter = logging.Formatter("[%(asctime)s] %(l...
This code taken from Matt's Suspenders for initializing a logger
def add_job(cls, identifier, queue_name=None, priority=0, queue_model=None, prepend=False, delayed_for=None, delayed_until=None, **fields_if_new): """ Add a job to a queue. If this job already exists, check it's current priority. If its higher than the new...
Add a job to a queue. If this job already exists, check it's current priority. If its higher than the new one, don't touch it, else move the job to the wanted queue. Before setting/moving the job to the queue, check for a `delayed_for` (int/foat/timedelta) or `delayed_until` (datetime) a...
def resolve_return_value_options(self, options): """Handle dynamic option value lookups in the format ^^task_name.attr""" for key, value in options.items(): if isinstance(value, str) and value.startswith(RETURN_VALUE_OPTION_PREFIX): path, name = value[len(RETURN_VALUE_OPTION_...
Handle dynamic option value lookups in the format ^^task_name.attr
def gps_date_time_send(self, year, month, day, hour, min, sec, clockStat, visSat, useSat, GppGl, sigUsedMask, percentUsed, force_mavlink1=False): ''' Pilot console PWM messges. year : Year reported by Gps (uint8_t) month ...
Pilot console PWM messges. year : Year reported by Gps (uint8_t) month : Month reported by Gps (uint8_t) day : Day reported by Gps (uint8_t) hour : Hour reported by Gps (u...
def metadata_path(self, m_path): """Provide pointers to the paths of the metadata file Args: m_path: Path to metadata file """ if not m_path: self.metadata_dir = None self.metadata_file = None else: if not op.exists(m_path): ...
Provide pointers to the paths of the metadata file Args: m_path: Path to metadata file
def sys_info(): """Return useful information about IPython and the system, as a string. Example ------- In [2]: print sys_info() {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_ve...
Return useful information about IPython and the system, as a string. Example ------- In [2]: print sys_info() {'commit_hash': '144fdae', # random 'commit_source': 'repository', 'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython', 'ipython_version': '0.11.dev', ...
def derivatives(self, x, y, grid_interp_x=None, grid_interp_y=None, f_=None, f_x=None, f_y=None, f_xx=None, f_yy=None, f_xy=None): """ returns df/dx and df/dy of the function """ #self._check_interp(grid_interp_x, grid_interp_y, f_, f_x, f_y, f_xx, f_yy, f_xy) n = len(np.atleast_...
returns df/dx and df/dy of the function
def vms(message, level=1): """Writes the specified message *only* if verbose output is enabled.""" if verbose is not None and verbose != False: if isinstance(verbose, bool) or (isinstance(verbose, int) and level <= verbose): std(message)
Writes the specified message *only* if verbose output is enabled.
def get_alerts_unarchived(self): """Return a list of Alerts unarchived.""" js = json.dumps({'_sort': '-time', 'archived': False}) params = urllib.urlencode({'json': js}) return self._read(self.api_url + 'list/alarm', params)
Return a list of Alerts unarchived.
def _implicit_solver(self): """Invertes and solves the matrix problem for diffusion matrix and temperature T. The method is called by the :func:`~climlab.process.implicit.ImplicitProcess._compute()` function of the :class:`~climlab.process.implicit.ImplicitProcess` class and ...
Invertes and solves the matrix problem for diffusion matrix and temperature T. The method is called by the :func:`~climlab.process.implicit.ImplicitProcess._compute()` function of the :class:`~climlab.process.implicit.ImplicitProcess` class and solves the matrix problem ...
def interpret(self, msg): """ Try and find the image file some magic here would be good. FIXME move elsewhere and make so everyone can use. interpreter that finds things? """ for gallery in msg.get('galleries', []): self.add_folder(gallery) ...
Try and find the image file some magic here would be good. FIXME move elsewhere and make so everyone can use. interpreter that finds things?
def gatk_variant_filtration(job, vcf_id, filter_name, filter_expression, ref_fasta, ref_fai, ref_dict): """ Filters VCF file using GATK VariantFiltration. Fixes extra pair of quotation marks in VCF header that may interfere with other VCF tools. :param JobFunctionWrappingJob job: passed automatically b...
Filters VCF file using GATK VariantFiltration. Fixes extra pair of quotation marks in VCF header that may interfere with other VCF tools. :param JobFunctionWrappingJob job: passed automatically by Toil :param str vcf_id: FileStoreID for input VCF file :param str filter_name: Name of filter for VCF head...
def download_cf_standard_name_table(version, location=None): ''' Downloads the specified CF standard name table version and saves it to file :param str version: CF standard name table version number (i.e 34) :param str location: Path/filename to write downloaded xml file to ''' if location is ...
Downloads the specified CF standard name table version and saves it to file :param str version: CF standard name table version number (i.e 34) :param str location: Path/filename to write downloaded xml file to
def get_val(self, x): """Converts to int.""" try: if self.subtype == 'integer': return int(round(x[self.col_name])) else: if np.isnan(x[self.col_name]): return self.default_val return x[self.col_name] e...
Converts to int.
def parse_charset(header_string): '''Parse a "Content-Type" string for the document encoding. Returns: str, None ''' match = re.search( r'''charset[ ]?=[ ]?["']?([a-z0-9_-]+)''', header_string, re.IGNORECASE ) if match: return match.group(1)
Parse a "Content-Type" string for the document encoding. Returns: str, None
def get_ids_in_region( self, resource, resolution, x_range, y_range, z_range, time_range=[0, 1]): """Get all ids in the region defined by x_range, y_range, z_range. Args: resource (intern.resource.Resource): An annotation channel. resolution (int): 0 indi...
Get all ids in the region defined by x_range, y_range, z_range. Args: resource (intern.resource.Resource): An annotation channel. resolution (int): 0 indicates native resolution. x_range (list[int]): x range such as [10, 20] which means x>=10 and x<20. y_range (l...
def markets(self): ''' 获取实时市场列表 :return: pd.dataFrame or None ''' with self.client.connect(*self.bestip): data = self.client.get_markets() return self.client.to_df(data) return None
获取实时市场列表 :return: pd.dataFrame or None
def danke(client, event, channel, nick, rest): 'Danke schön!' if rest: rest = rest.strip() Karma.store.change(rest, 1) rcpt = rest else: rcpt = channel return f'Danke schön, {rcpt}! Danke schön!'
Danke schön!
def childRecords(self): """ Returns a record set of children for this item based on the record. If no record set is manually set for this instance, then it will use the hierarchyColumn value from the tree widget with this record. If no hierarchyColumn is speified, then a b...
Returns a record set of children for this item based on the record. If no record set is manually set for this instance, then it will use the hierarchyColumn value from the tree widget with this record. If no hierarchyColumn is speified, then a blank record set is returned. ...
def flatten_dict(d, prefix='', sep='.'): """In place dict flattening. """ def apply_and_resolve_conflicts(dest, item, prefix): for k, v in flatten_dict(item, prefix=prefix, sep=sep).items(): new_key = k i = 2 while new_key in d: new_key = '{key}{se...
In place dict flattening.
def determine_hbonds_for_drawing(self, analysis_cutoff): """ Since plotting all hydrogen bonds could lead to a messy plot, a cutoff has to be imple- mented. In this function the frequency of each hydrogen bond is summated and the total compared against analysis cutoff - a fraction multip...
Since plotting all hydrogen bonds could lead to a messy plot, a cutoff has to be imple- mented. In this function the frequency of each hydrogen bond is summated and the total compared against analysis cutoff - a fraction multiplied by trajectory count. Those hydrogen bonds that are present for l...
def _http_req_user_agent(self): """Return the User-Agent value to specify in HTTP requests, defaulting to ``service/version`` if configured in the application settings, or if used in a consumer, it will attempt to obtain a user-agent from the consumer's process. If it can not auto-set th...
Return the User-Agent value to specify in HTTP requests, defaulting to ``service/version`` if configured in the application settings, or if used in a consumer, it will attempt to obtain a user-agent from the consumer's process. If it can not auto-set the User-Agent, it defaults to ``spro...
def update_path(self): """ Tries to update the $PATH automatically. """ if WINDOWS: return self.add_to_windows_path() # Updating any profile we can on UNIX systems export_string = self.get_export_string() addition = "\n{}\n".format(export_string) ...
Tries to update the $PATH automatically.
def delete_agent(self, agent_id): """Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict. """ # Raises an error when agent_id is ...
Delete an agent. :param str agent_id: The id of the agent to delete. It must be an str containing only characters in "a-zA-Z0-9_-" and must be between 1 and 36 characters. :return: agent deleted. :rtype: dict.
def append(self, other, inplace=False, **kwargs): """ Append any input which can be converted to MAGICCData to self. Parameters ---------- other : MAGICCData, pd.DataFrame, pd.Series, str Source of data to append. inplace : bool If True, append `...
Append any input which can be converted to MAGICCData to self. Parameters ---------- other : MAGICCData, pd.DataFrame, pd.Series, str Source of data to append. inplace : bool If True, append ``other`` inplace, otherwise return a new ``MAGICCData`` in...
def injector_ui_tree_menu_entity_2_json(self, ignore_genealogy=False): """ transform this local object to JSON :param ignore_genealogy: ignore the genealogy of this object if true (awaited format for Ariane server) :return: the resulting JSON of transformation """ LOGGER....
transform this local object to JSON :param ignore_genealogy: ignore the genealogy of this object if true (awaited format for Ariane server) :return: the resulting JSON of transformation
def _handle_argument(self, token): """Handle a case where an argument is at the head of the tokens.""" name = None self._push() while self._tokens: token = self._tokens.pop() if isinstance(token, tokens.ArgumentSeparator): name = self._pop() ...
Handle a case where an argument is at the head of the tokens.
def GetNodes(r, bulk=False): """ Gets all nodes in the cluster. @type bulk: bool @param bulk: whether to return all information about all instances @rtype: list of dict or str @return: if bulk is true, info about nodes in the cluster, else list of nodes in the cluster """ ...
Gets all nodes in the cluster. @type bulk: bool @param bulk: whether to return all information about all instances @rtype: list of dict or str @return: if bulk is true, info about nodes in the cluster, else list of nodes in the cluster
def _apply_Create(self, change): '''A record from change must be created. :param change: a change object :type change: octodns.record.Change :type return: void ''' ar = _AzureRecord(self._resource_group, change.new) create = self._dns_client.record_...
A record from change must be created. :param change: a change object :type change: octodns.record.Change :type return: void
def _make_summary_tables(self): """ prints the summary of the regression. It shows the waveform metadata, diagnostics of the fit, and results of the hypothesis tests for each comparison encoded in the design matrix """ try: self._Bhat except: ...
prints the summary of the regression. It shows the waveform metadata, diagnostics of the fit, and results of the hypothesis tests for each comparison encoded in the design matrix
def filtered_rows_from_args(self, args): '''extracts filters from args, rows from manifests, returns filtered rows''' if len(self.manifests) == 0: print("fw: No manifests downloaded. Try 'manifest download'") return None (filters,remainder) = self.filters_from_args(args...
extracts filters from args, rows from manifests, returns filtered rows
def version(self): """Get the version of MongoDB that this Server runs as a tuple.""" if not self.__version: command = (self.name, '--version') logger.debug(command) stdout, _ = subprocess.Popen( command, stdout=subprocess.PIPE).communicate() ...
Get the version of MongoDB that this Server runs as a tuple.
def set_state_process(self, context, process): """Method to append process for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param process: A text explain the process. ...
Method to append process for a context in the IF state. :param context: It can be a layer purpose or a section (impact function, post processor). :type context: str, unicode :param process: A text explain the process. :type process: str, unicode
def decimal_day_to_day_hour_min_sec( self, daysFloat): """*Convert a day from decimal format to hours mins and sec* Precision should be respected. **Key Arguments:** - ``daysFloat`` -- the day as a decimal. **Return:** - ``daysInt`` -- ...
*Convert a day from decimal format to hours mins and sec* Precision should be respected. **Key Arguments:** - ``daysFloat`` -- the day as a decimal. **Return:** - ``daysInt`` -- day as an integer - ``hoursInt`` -- hour as an integer (None if input precsion...
def fast_boolean(operandA, operandB, operation, precision=0.001, max_points=199, layer=0, datatype=0): """ Execute any boolean operation between 2 polygons or polygon sets. Parameters ---------- op...
Execute any boolean operation between 2 polygons or polygon sets. Parameters ---------- operandA : polygon or array-like First operand. Must be a ``PolygonSet``, ``CellReference``, ``CellArray``, or an array. The array may contain any of the previous objects or an array-like[N][2]...
def _set_id_from_xml_frameid(self, xml, xmlpath, var): ''' Set a single variable with the frameids of matching entity ''' e = xml.find(xmlpath) if e is not None: setattr(self, var, e.attrib['frameid'])
Set a single variable with the frameids of matching entity
def sparse_surface(self): """ Filled cells on the surface of the mesh. Returns ---------------- voxels: (n, 3) int, filled cells on mesh surface """ if self._method == 'ray': func = voxelize_ray elif self._method == 'subdivide': fu...
Filled cells on the surface of the mesh. Returns ---------------- voxels: (n, 3) int, filled cells on mesh surface
def begin(self): ''' Start over and get a track. ''' # Check for a start metasong if self.start: # We are in the beginning song self.at_beginning = True # And on the first track. self.pos = 0 else: # We aren't in...
Start over and get a track.
def call(self, callname, data=None, **args): """ Generic interface to REST apiGeneric interface to REST api :param callname: query name :param data: dictionary of inputs :param args: keyword arguments added to the payload :return: """ url = f"{self.u...
Generic interface to REST apiGeneric interface to REST api :param callname: query name :param data: dictionary of inputs :param args: keyword arguments added to the payload :return:
def _ann_store_annotations(self, item_with_annotations, node, overwrite=False): """Stores annotations into an hdf5 file.""" # If we overwrite delete all annotations first if overwrite is True or overwrite == 'v_annotations': annotated = self._all_get_from_attrs(node, HDF5StorageServ...
Stores annotations into an hdf5 file.
def update_url_params(url, replace_all=False, **url_params): """ :return: url with its query updated from url_query (non-matching params are retained) """ # Ensure 'replace_all' can be sent as a url param if not (replace_all is True or replace_all is False): url_params['replace_all'] = replace_all ...
:return: url with its query updated from url_query (non-matching params are retained)
def list(self, request, *args, **kwargs): """ To get a list of price list items, run **GET** against */api/merged-price-list-items/* as authenticated user. If service is not specified default price list items are displayed. Otherwise service specific price list items are display...
To get a list of price list items, run **GET** against */api/merged-price-list-items/* as authenticated user. If service is not specified default price list items are displayed. Otherwise service specific price list items are displayed. In this case rendered object contains {"is_manuall...
def process_text(text, output_fmt='json', outbuf=None, cleanup=True, key='', **kwargs): """Return processor with Statements extracted by reading text with Sparser. Parameters ---------- text : str The text to be processed output_fmt: Optional[str] The output format ...
Return processor with Statements extracted by reading text with Sparser. Parameters ---------- text : str The text to be processed output_fmt: Optional[str] The output format to obtain from Sparser, with the two options being 'json' and 'xml'. Default: 'json' outbuf : Option...
def has_tensor(obj) -> bool: """ Given a possibly complex data structure, check if it has any torch.Tensors in it. """ if isinstance(obj, torch.Tensor): return True elif isinstance(obj, dict): return any(has_tensor(value) for value in obj.values()) elif isinstance(obj, (list,...
Given a possibly complex data structure, check if it has any torch.Tensors in it.
def await_message(self, *args, **kwargs) -> 'asyncio.Future[Message]': """ Block until a message matches. See `on_message` """ fut = asyncio.Future() @self.on_message(*args, **kwargs) async def handler(message): fut.set_result(message) # remove handler...
Block until a message matches. See `on_message`
def getFields(self): """ Returns all the class attributues. @rtype: dict @return: A dictionary containing all the class attributes. """ d = {} for i in self._attrsList: key = i value = getattr(self, i) d[key] = value ...
Returns all the class attributues. @rtype: dict @return: A dictionary containing all the class attributes.
def get_definition(self, name): '''Returns xaddr and wsdl of specified service''' # Check if the service is supported if name not in SERVICES: raise ONVIFError('Unknown service %s' % name) wsdl_file = SERVICES[name]['wsdl'] ns = SERVICES[name]['ns'] wsdlpath ...
Returns xaddr and wsdl of specified service
def put(self): """Updates this task type on the saltant server. Returns: :class:`saltant.models.container_task_type.ExecutableTaskType`: An executable task type model instance representing the task type just updated. """ return self.manager.pu...
Updates this task type on the saltant server. Returns: :class:`saltant.models.container_task_type.ExecutableTaskType`: An executable task type model instance representing the task type just updated.
def errorprint(): """Print out descriptions from ConfigurationError.""" try: yield except ConfigurationError as e: click.secho('%s' % e, err=True, fg='red') sys.exit(1)
Print out descriptions from ConfigurationError.
def find_group(self, star, starlist): """ Find the ids of those stars in ``starlist`` which are at a distance less than ``crit_separation`` from ``star``. Parameters ---------- star : `~astropy.table.Row` Star which will be either the head of a cluster or an ...
Find the ids of those stars in ``starlist`` which are at a distance less than ``crit_separation`` from ``star``. Parameters ---------- star : `~astropy.table.Row` Star which will be either the head of a cluster or an isolated one. starlist : `~astropy.tab...
def load(cls, fpath): """Loads a module and returns its object. :param str|unicode fpath: :rtype: module """ module_name = os.path.splitext(os.path.basename(fpath))[0] sys.path.insert(0, os.path.dirname(fpath)) try: module = import_module(module_name...
Loads a module and returns its object. :param str|unicode fpath: :rtype: module
def recipe(package, repository=None, depends_on=None, release=False, output_path=None, auto=False, overwrite=False, name=None): """Create a new upgrade recipe, for developers.""" upgrader = InvenioUpgrader() logger = upgrader.get_logger() try: path, found_repository = _upgrade_recipe...
Create a new upgrade recipe, for developers.
def parse_string(progression): """Return a tuple (roman numeral, accidentals, chord suffix). Examples: >>> parse_string('I') ('I', 0, '') >>> parse_string('bIM7') ('I', -1, 'M7') """ acc = 0 roman_numeral = '' suffix = '' i = 0 for c in progression: if c == '#': ...
Return a tuple (roman numeral, accidentals, chord suffix). Examples: >>> parse_string('I') ('I', 0, '') >>> parse_string('bIM7') ('I', -1, 'M7')
def get_queryset(self): """ Fixes get_query_set vs get_queryset for Django <1.6 """ try: qs = super(UserManager, self).get_queryset() except AttributeError: # pragma: no cover qs = super(UserManager, self).get_query_set() return qs
Fixes get_query_set vs get_queryset for Django <1.6
def parse_unit(name, parse_strict='warn', format='gwpy'): """Attempt to intelligently parse a `str` as a `~astropy.units.Unit` Parameters ---------- name : `str` unit name to parse parse_strict : `str` one of 'silent', 'warn', or 'raise' depending on how pedantic you want t...
Attempt to intelligently parse a `str` as a `~astropy.units.Unit` Parameters ---------- name : `str` unit name to parse parse_strict : `str` one of 'silent', 'warn', or 'raise' depending on how pedantic you want the parser to be format : `~astropy.units.format.Base` ...
def editAccountInfo(self, short_name=None, author_name=None, author_url=None): """Use this method to update information about a Telegraph account. :param short_name: Optional. New account name. :type short_name: str :param author_name: Optional. New default author name used when ...
Use this method to update information about a Telegraph account. :param short_name: Optional. New account name. :type short_name: str :param author_name: Optional. New default author name used when creating new articles. :type author_name: str :param author_url: Option...
def openFile(self, openDQ=False): """ Open file and set up filehandle for image file """ if self._im.closed: if not self._dq.closed: self._dq.release() assert(self._dq.closed) fi = FileExtMaskInfo(clobber=False, ...
Open file and set up filehandle for image file
def cache_as_field(cache_name): """Cache a functions return value as the field 'cache_name'.""" def cache_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs): value = getattr(self, cache_name, UndefToken) if value != UndefToken: ...
Cache a functions return value as the field 'cache_name'.
def bhattacharyya(Ks, dim, required, clamp=True, to_self=False): r''' Estimate the Bhattacharyya coefficient between distributions, based on kNN distances: \int \sqrt{p q} If clamp (the default), enforces 0 <= BC <= 1. Returns an array of shape (num_Ks,). ''' est = required if clamp: ...
r''' Estimate the Bhattacharyya coefficient between distributions, based on kNN distances: \int \sqrt{p q} If clamp (the default), enforces 0 <= BC <= 1. Returns an array of shape (num_Ks,).
def pull(self, path, use_sudo=False, user=None, force=False): """ Fetch changes from the default remote repository and merge them. :param path: Path of the working copy directory. This directory must exist and be a Git working copy with a default remote to pull from. ...
Fetch changes from the default remote repository and merge them. :param path: Path of the working copy directory. This directory must exist and be a Git working copy with a default remote to pull from. :type path: str :param use_sudo: If ``True`` execute ``git`` with ...
def sequence_set(self) -> SequenceSet: """The sequence set to use when finding the messages to match against. This will default to all messages unless the search criteria set contains a sequence set. """ try: seqset_crit = next(crit for crit in self.all_criteria ...
The sequence set to use when finding the messages to match against. This will default to all messages unless the search criteria set contains a sequence set.
def parse_refresh_header(self, refresh): """ >>> parse_refresh_header("1; url=http://example.com/") (1.0, 'http://example.com/') >>> parse_refresh_header("1; url='http://example.com/'") (1.0, 'http://example.com/') >>> parse_refresh_header("1") (1.0, None) ...
>>> parse_refresh_header("1; url=http://example.com/") (1.0, 'http://example.com/') >>> parse_refresh_header("1; url='http://example.com/'") (1.0, 'http://example.com/') >>> parse_refresh_header("1") (1.0, None) >>> parse_refresh_header("blah") # doctest: +IGNORE_EXCEPTI...
def StartingKey(self, evt): """ If the editor is enabled by pressing keys on the grid, this will be called to let the editor do something about that first key if desired. """ key = evt.GetKeyCode() ch = None if key in [ wx.WXK_NUMPAD0, wx.WXK_NUMP...
If the editor is enabled by pressing keys on the grid, this will be called to let the editor do something about that first key if desired.
def temperature(self, what): """Set temperature.""" self._temperature = units.validate_quantity(what, u.K)
Set temperature.
def estimate(self, significance_level=0.01): """ Estimates a DAG for the data set, using the PC constraint-based structure learning algorithm. Independencies are identified from the data set using a chi-squared statistic with the acceptance threshold of `significance_level`. PC i...
Estimates a DAG for the data set, using the PC constraint-based structure learning algorithm. Independencies are identified from the data set using a chi-squared statistic with the acceptance threshold of `significance_level`. PC identifies a partially directed acyclic graph (PDAG), given ...