code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def load_kwargs(*args, **kwargs): """ Load geometry from a properly formatted dict or kwargs """ def handle_scene(): """ Load a scene from our kwargs: class: Scene geometry: dict, name: Trimesh kwargs graph: list of dict, kwargs for scene.graph.update...
Load geometry from a properly formatted dict or kwargs
def Runs(self): """Return all the run names in the `EventMultiplexer`. Returns: ``` {runName: { scalarValues: [tagA, tagB, tagC], graph: true, meta_graph: true}} ``` """ with self._accumulators_mutex: # To avoid nested locks, we construct a copy of the run-accumula...
Return all the run names in the `EventMultiplexer`. Returns: ``` {runName: { scalarValues: [tagA, tagB, tagC], graph: true, meta_graph: true}} ```
def emit(self, event, *args, **kwargs): """Send out an event and call it's associated functions :param event: Name of the event to trigger """ for func in self._registered_events[event].values(): func(*args, **kwargs)
Send out an event and call it's associated functions :param event: Name of the event to trigger
def _generate_normals(polygons): """ Takes a list of polygons and return an array of their normals. Normals point towards the viewer for a face with its vertices in counterclockwise order, following the right hand rule. Uses three points equally spaced around the polygon. This normal of course m...
Takes a list of polygons and return an array of their normals. Normals point towards the viewer for a face with its vertices in counterclockwise order, following the right hand rule. Uses three points equally spaced around the polygon. This normal of course might not make sense for polygons with more th...
def _as_rescale(self, get, targetbitdepth): """Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.""" width, height, pixels, meta = get() maxval = 2**meta['bitdepth'] - 1 targetmaxval = 2**targetbitdepth - 1 factor = float(targetmaxval) / float(maxval) meta['bitdepth'] = t...
Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.
def _file_model_from_db(self, record, content, format): """ Build a file model from database record. """ # TODO: Most of this is shared with _notebook_model_from_db. path = to_api_path(record['parent_name'] + record['name']) model = base_model(path) model['type'] ...
Build a file model from database record.
def fetch_routing_info(self, address): """ Fetch raw routing info from a given router address. :param address: router address :return: list of routing records or None if no connection could be established :raise ServiceUnavailable: if the server does not support routing...
Fetch raw routing info from a given router address. :param address: router address :return: list of routing records or None if no connection could be established :raise ServiceUnavailable: if the server does not support routing or if routing s...
def show_pattern(syncpr_output_dynamic, image_height, image_width): """! @brief Displays evolution of phase oscillators as set of patterns where the last one means final result of recognition. @param[in] syncpr_output_dynamic (syncpr_dynamic): Output dynamic of a syncpr network. ...
! @brief Displays evolution of phase oscillators as set of patterns where the last one means final result of recognition. @param[in] syncpr_output_dynamic (syncpr_dynamic): Output dynamic of a syncpr network. @param[in] image_height (uint): Height of the pattern (image_height * image_wi...
def status(request): # pylint: disable=unused-argument """Status""" token = request.GET.get("token", "") if not token or token != settings.STATUS_TOKEN: raise Http404() info = {} check_mapping = { 'REDIS': (get_redis_info, 'redis'), 'ELASTIC_SEARCH': (get_elasticsearch_info...
Status
def shapeless_placeholder(x, axis, name): """ Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape ...
Make the static shape of a tensor less specific. If you want to feed to a tensor, the shape of the feed value must match the tensor's static shape. This function creates a placeholder which defaults to x if not fed, but has a less specific static shape than x. See also `tensorflow#5680 <https://github....
def p_select_from_where_statement_1(self, p): ''' statement : SELECT ANY variable_name FROM INSTANCES OF identifier WHERE expression | SELECT MANY variable_name FROM INSTANCES OF identifier WHERE expression ''' p[0] = SelectFromWhereNode(cardinality=p[2], ...
statement : SELECT ANY variable_name FROM INSTANCES OF identifier WHERE expression | SELECT MANY variable_name FROM INSTANCES OF identifier WHERE expression
def to_ds9(self, coordsys='fk5', fmt='.6f', radunit='deg'): """ Converts a list of ``regions.Shape`` objects to ds9 region strings. Parameters ---------- coordsys : str This overrides the coordinate system frame for all regions. fmt : str A python...
Converts a list of ``regions.Shape`` objects to ds9 region strings. Parameters ---------- coordsys : str This overrides the coordinate system frame for all regions. fmt : str A python string format defining the output precision. Default is .6f, which ...
def htmlDocContentDumpFormatOutput(self, cur, encoding, format): """Dump an HTML document. """ if cur is None: cur__o = None else: cur__o = cur._o libxml2mod.htmlDocContentDumpFormatOutput(self._o, cur__o, encoding, format)
Dump an HTML document.
def registry_hostname(registry): """ Strip a reference to a registry to just the hostname:port """ if registry.startswith('http:') or registry.startswith('https:'): return urlparse(registry).netloc else: return registry
Strip a reference to a registry to just the hostname:port
def insert_successor(self, successor): """! @brief Insert successor to the node. @param[in] successor (cfnode): Successor for adding. """ self.feature += successor.feature; self.successors.append(successor); successor...
! @brief Insert successor to the node. @param[in] successor (cfnode): Successor for adding.
def start(self, version=None, **kwargs):#game_version=None, data_version=None, **kwargs): """Launch the game process.""" if not version: version = self.mostRecentVersion pysc2Version = lib.Version( # convert to pysc2 Version version.version, version.baseVersion, version.dataH...
Launch the game process.
def get_message(self, dummy0, sock_info, use_cmd=False): """Get a getmore message.""" ns = self.namespace() ctx = sock_info.compression_context if use_cmd: spec = self.as_command(sock_info)[0] if sock_info.op_msg_enabled: request_id, msg, size, _...
Get a getmore message.
def read_header(file): """ ----- Brief ----- Universal function for reading the header of .txt, .h5 and .edf files generated by OpenSignals. ----------- Description ----------- Each file generated by the OpenSignals software (available at https://www.biosignalsplux.com/en/software) ...
----- Brief ----- Universal function for reading the header of .txt, .h5 and .edf files generated by OpenSignals. ----------- Description ----------- Each file generated by the OpenSignals software (available at https://www.biosignalsplux.com/en/software) owns a set of metadata that all...
def org_find_members(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /org-xxxx/findMembers API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FfindMembers """ return DXHTTPRequest('/%s/findMembers' % ...
Invokes the /org-xxxx/findMembers API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Organizations#API-method%3A-%2Forg-xxxx%2FfindMembers
def patch_namespaced_replica_set_scale(self, name, namespace, body, **kwargs): """ partially update scale of the specified ReplicaSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_n...
partially update scale of the specified ReplicaSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_replica_set_scale(name, namespace, body, async_req=True) >>> result = thread.get(...
def addRelationships( self, data: list, LIMIT: int = 20, _print: bool = True, crawl: bool = False, ) -> list: """ data = [{ "term1_id", "term2_id", "relationship_tid", "term1_version", "term2_version", "relationship_term...
data = [{ "term1_id", "term2_id", "relationship_tid", "term1_version", "term2_version", "relationship_term_version",}]
def __sort_stats(self, sortedby=None): """Return the stats (dict) sorted by (sortedby).""" return sort_stats(self.stats, sortedby, reverse=glances_processes.sort_reverse)
Return the stats (dict) sorted by (sortedby).
def get_firmware(self): """ Gets baseline firmware information for a SAS Logical Interconnect. Returns: dict: SAS Logical Interconnect Firmware. """ firmware_uri = "{}/firmware".format(self.data["uri"]) return self._helper.do_get(firmware_uri)
Gets baseline firmware information for a SAS Logical Interconnect. Returns: dict: SAS Logical Interconnect Firmware.
def signature(cls): """Returns kwargs to construct a `TaskRule` that will construct the target Optionable. TODO: This indirection avoids a cycle between this module and the `rules` module. """ snake_scope = cls.options_scope.replace('-', '_') partial_construct_optionable = functools.partial(_constr...
Returns kwargs to construct a `TaskRule` that will construct the target Optionable. TODO: This indirection avoids a cycle between this module and the `rules` module.
def hash_contents(contents): """ Creates a hash of key names and hashes in a package dictionary. "contents" must be a GroupNode. """ assert isinstance(contents, GroupNode) result = hashlib.sha256() def _hash_int(value): result.update(struct.pack(">L", value)) def _hash_str(st...
Creates a hash of key names and hashes in a package dictionary. "contents" must be a GroupNode.
def _dequeue_function(self): """ Internal method to dequeue to events. """ from UcsBase import WriteUcsWarning, _GenericMO, WriteObject, UcsUtils while len(self._wbs): lowestTimeout = None for wb in self._wbs: pollSec = wb.params["pollSec"] managedObject = wb.params["managedObject"] timeoutSec ...
Internal method to dequeue to events.
def find_elements_by_xpath(self, xpath): """ Finds multiple elements by xpath. :Args: - xpath - The xpath locator of the elements to be found. :Returns: - list of WebElement - a list with elements if any was found. An empty list if not :Usage: ...
Finds multiple elements by xpath. :Args: - xpath - The xpath locator of the elements to be found. :Returns: - list of WebElement - a list with elements if any was found. An empty list if not :Usage: :: elements = driver.find_elements_...
async def create_webhook(self, *, name, avatar=None, reason=None): """|coro| Creates a webhook for this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. .. versionchanged:: 1.1.0 Added the ``reason`` keyword-only parameter. Parameters -...
|coro| Creates a webhook for this channel. Requires :attr:`~.Permissions.manage_webhooks` permissions. .. versionchanged:: 1.1.0 Added the ``reason`` keyword-only parameter. Parameters ------------- name: :class:`str` The webhook's name. ...
def classify_by_name(names): """Classify a (composite) ligand by the HETID(s)""" if len(names) > 3: # Polymer if len(set(config.RNA).intersection(set(names))) != 0: ligtype = 'RNA' elif len(set(config.DNA).intersection(set(names))) != 0: ligtype = 'DNA' else: ...
Classify a (composite) ligand by the HETID(s)
def unbroadcast(a, b): ''' unbroadcast(a, b) yields a tuple (aa, bb) that is equivalent to (a, b) except that aa and bb have been reshaped such that arithmetic numpy operations such as aa * bb will result in row-wise operation instead of column-wise broadcasting. ''' # they could be sparse: ...
unbroadcast(a, b) yields a tuple (aa, bb) that is equivalent to (a, b) except that aa and bb have been reshaped such that arithmetic numpy operations such as aa * bb will result in row-wise operation instead of column-wise broadcasting.
def get_replication_command_history(self, schedule_id, limit=20, offset=0, view=None): """ Retrieve a list of commands for a replication schedule. @param schedule_id: The id of the replication schedule. @param limit: Maximum number of commands to retrieve. @par...
Retrieve a list of commands for a replication schedule. @param schedule_id: The id of the replication schedule. @param limit: Maximum number of commands to retrieve. @param offset: Index of first command to retrieve. @param view: View to materialize. Valid values are 'full', 'summary', 'export', 'expor...
def _get_index(n_items, item_size, n): """Prepare an index attribute for GPU uploading.""" index = np.arange(n_items) index = np.repeat(index, item_size) index = index.astype(np.float64) assert index.shape == (n,) return index
Prepare an index attribute for GPU uploading.
def list_views(app, appbuilder): """ List all registered views """ _appbuilder = import_application(app, appbuilder) echo_header("List of registered views") for view in _appbuilder.baseviews: click.echo( "View:{0} | Route:{1} | Perms:{2}".format( view.__cl...
List all registered views
def last_modified(self) -> Optional[datetime.datetime]: """The value of Last-Modified HTTP header, or None. This header is represented as a `datetime` object. """ httpdate = self._headers.get(hdrs.LAST_MODIFIED) if httpdate is not None: timetuple = parsedate(httpdate...
The value of Last-Modified HTTP header, or None. This header is represented as a `datetime` object.
def get_version_naive(cls, name, ignore=''): """ Checks a string for a possible version of an object (no prefix, no suffix) without filtering date out Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(...
Checks a string for a possible version of an object (no prefix, no suffix) without filtering date out Assumes only up to 4 digit padding :param name: str, string that represents a possible name of an object :return: (float, int, list(str), None), gets the version number then the string matc...
def get_ref_indices(self): """ :return: list of all indices in object reference. """ ixn_obj = self ref_indices = [] while ixn_obj != ixn_obj.root: ref_indices.append(ixn_obj.ref.split(':')[-1]) ixn_obj = ixn_obj.parent return ref_indices[...
:return: list of all indices in object reference.
def jboss_standalone_main_config_files(broker): """Command: JBoss standalone main config files""" ps = broker[DefaultSpecs.ps_auxww].content results = [] search = re.compile(r"\-Djboss\.server\.base\.dir=(\S+)").search # JBoss progress command content should contain jboss.home.di...
Command: JBoss standalone main config files
def construct_xblock_from_class(self, cls, scope_ids, field_data=None, *args, **kwargs): """ Construct a new xblock of type cls, mixing in the mixins defined for this application. """ return self.mixologist.mix(cls)( runtime=self, field_data=field_data, ...
Construct a new xblock of type cls, mixing in the mixins defined for this application.
def run(self): """ This runs the leader process to issue and manage jobs. :raises: toil.leader.FailedJobsException if at the end of function their remain \ failed jobs :return: The return value of the root job's run function. :rtype: Any """ # Start the ...
This runs the leader process to issue and manage jobs. :raises: toil.leader.FailedJobsException if at the end of function their remain \ failed jobs :return: The return value of the root job's run function. :rtype: Any
def _find_class_construction_fn(cls): """Find the first __init__ or __new__ method in the given class's MRO.""" for base in type.mro(cls): if '__init__' in base.__dict__: return base.__init__ if '__new__' in base.__dict__: return base.__new__
Find the first __init__ or __new__ method in the given class's MRO.
def getdata(self): """ A sequence of pixel data relating to the changes that occurred since the last time :py:func:`redraw_required` was last called. :returns: A sequence of pixels or ``None``. :rtype: iterable """ if self.bounding_box: return self.im...
A sequence of pixel data relating to the changes that occurred since the last time :py:func:`redraw_required` was last called. :returns: A sequence of pixels or ``None``. :rtype: iterable
def get_file_size(file_object): '''Returns the size, in bytes, of a file. Expects an object that supports seek and tell methods. Args: file_object (file_object) - The object that represents the file Returns: (int): size of the file, in bytes''' position = file_object.tell() fi...
Returns the size, in bytes, of a file. Expects an object that supports seek and tell methods. Args: file_object (file_object) - The object that represents the file Returns: (int): size of the file, in bytes
def _make_regex(self): """ Build a re object based on keys in the current dictionary """ return re.compile("|".join(map(re.escape, self.keys())))
Build a re object based on keys in the current dictionary
def load_word_file(filename): """Loads a words file as a list of lines""" words_file = resource_filename(__name__, "words/%s" % filename) handle = open(words_file, 'r') words = handle.readlines() handle.close() return words
Loads a words file as a list of lines
def cache(self, f): """Cache a function using the context's cache directory.""" if self._memory is None: # pragma: no cover logger.debug("Joblib is not installed: skipping cacheing.") return f assert f # NOTE: discard self in instance methods. if 'self' i...
Cache a function using the context's cache directory.
def cosi_posterior(vsini_dist,veq_dist,vgrid=None,npts=100,vgrid_pts=1000): """returns posterior of cosI given dists for vsini and veq (incorporates unc. in vsini) """ if vgrid is None: vgrid = np.linspace(min(veq_dist.ppf(0.001),vsini_dist.ppf(0.001)), max(veq_dist.ppf(0...
returns posterior of cosI given dists for vsini and veq (incorporates unc. in vsini)
def find_recipes(folders, pattern=None, base=None): '''find recipes will use a list of base folders, files, or patterns over a subset of content to find recipe files (indicated by Starting with Singularity Parameters ========== base: if defined, consider folders recursively ...
find recipes will use a list of base folders, files, or patterns over a subset of content to find recipe files (indicated by Starting with Singularity Parameters ========== base: if defined, consider folders recursively below this level.
def validate(self): """Perform some basic configuration validation. """ if not self.conf.get('auth_token'): raise PacketManagerException('The auth token for Packet is not defined but required.') if not self.conf.get('projects'): raise PacketManagerException('Requi...
Perform some basic configuration validation.
def __intermediate_addresses(self, interface): """ converts NetJSON address to UCI intermediate data structure """ address_list = self.get_copy(interface, 'addresses') # do not ignore interfaces if they do not contain any address if not address_list: r...
converts NetJSON address to UCI intermediate data structure
def set_duty_cycle(self, pin, dutycycle): """Set percent duty cycle of PWM output on specified pin. Duty cycle must be a value 0.0 to 100.0 (inclusive). """ if dutycycle < 0.0 or dutycycle > 100.0: raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inc...
Set percent duty cycle of PWM output on specified pin. Duty cycle must be a value 0.0 to 100.0 (inclusive).
def add_dicts(d1, d2): """ Merge two dicts of addable values """ if d1 is None: return d2 if d2 is None: return d1 keys = set(d1) keys.update(set(d2)) ret = {} for key in keys: v1 = d1.get(key) v2 = d2.get(key) if v1 is None: ret[key] = v2 ...
Merge two dicts of addable values
def intersects_any(self, ray_origins, ray_directions): """ Check if a list of rays hits the surface. Parameters ---------- ray_origins: (n,3) float, origins of rays ray_directions: (n,3) float, direction (vector) of rays ...
Check if a list of rays hits the surface. Parameters ---------- ray_origins: (n,3) float, origins of rays ray_directions: (n,3) float, direction (vector) of rays Returns ---------- hit: (n,) bool, did each ray hit the surface
def _simplify_feature_value(self, name, value): """Return simplified and more pythonic feature values.""" if name == 'prefix': channel_modes, channel_chars = value.split(')') channel_modes = channel_modes[1:] # [::-1] to reverse order and go from lowest to highest pr...
Return simplified and more pythonic feature values.
def perl_cmd(): """Retrieve path to locally installed conda Perl or first in PATH. """ perl = which(os.path.join(get_bcbio_bin(), "perl")) if perl: return perl else: return which("perl")
Retrieve path to locally installed conda Perl or first in PATH.
def _check_backends(self): """ Check that every backend in roles and attributes is declared in main configuration """ backends = self.backends_params.keys() for b in self.roles.get_backends(): if b not in backends: raise MissingBackend(b, 'role') ...
Check that every backend in roles and attributes is declared in main configuration
def hybrid_threaded_worker(selector, workers): """Runs a set of workers, each in a separate thread. :param selector: A function that takes a hints-tuple and returns a key indexing a worker in the `workers` dictionary. :param workers: A dictionary of workers. :returns: A...
Runs a set of workers, each in a separate thread. :param selector: A function that takes a hints-tuple and returns a key indexing a worker in the `workers` dictionary. :param workers: A dictionary of workers. :returns: A connection for the scheduler. :rtype: Connection ...
def to_zhuyin(s, delimiter=' ', all_readings=False, container='[]'): """Convert a string's Chinese characters to Zhuyin readings. *s* is a string containing Chinese characters. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differentiate between words and charact...
Convert a string's Chinese characters to Zhuyin readings. *s* is a string containing Chinese characters. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differentiate between words and characters so that a more accurate reading can be returned. *all_readings*...
def get_default_config(self): """ Returns the default collector settings """ config = super(VMSFSCollector, self).get_default_config() config.update({ 'path': 'vmsfs' }) return config
Returns the default collector settings
def make_slash_number(self): """ Charset lines have \2 or \3 depending on type of partitioning and codon positions requested for our dataset. :return: """ if self.partitioning == 'by codon position' and self.codon_positions == '1st-2nd': return '\\2' ...
Charset lines have \2 or \3 depending on type of partitioning and codon positions requested for our dataset. :return:
def enable_hostgroup_passive_svc_checks(self, hostgroup): """Enable service passive checks for a hostgroup Format of the line that triggers function call:: ENABLE_HOSTGROUP_PASSIVE_SVC_CHECKS;<hostgroup_name> :param hostgroup: hostgroup to enable :type hostgroup: alignak.object...
Enable service passive checks for a hostgroup Format of the line that triggers function call:: ENABLE_HOSTGROUP_PASSIVE_SVC_CHECKS;<hostgroup_name> :param hostgroup: hostgroup to enable :type hostgroup: alignak.objects.hostgroup.Hostgroup :return: None
def _get_audio_duration_seconds(self, audio_abs_path): """ Parameters ---------- audio_abs_path : str Returns ------- total_seconds : int """ HHMMSS_duration = subprocess.check_output( ("""sox --i {} | grep "{}" | awk -F " : " '{{print...
Parameters ---------- audio_abs_path : str Returns ------- total_seconds : int
def toString(value, mode): """ Converts angle float to string. Mode refers to LAT/LON. """ string = angle.toString(value) sign = string[0] separator = CHAR[mode][sign] string = string.replace(':', separator, 1) return string[1:]
Converts angle float to string. Mode refers to LAT/LON.
def flick(self, x, y, speed): """Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead. Flick on the touch screen using finger motion events. This flickcommand starts at a particulat screen location. Support: iOS Args: x(f...
Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead. Flick on the touch screen using finger motion events. This flickcommand starts at a particulat screen location. Support: iOS Args: x(float}: The x offset in pixels to flick by...
def batch_update_conversations(self, event, conversation_ids): """ Batch update conversations. Perform a change on a set of conversations. Operates asynchronously; use the {api:ProgressController#show progress endpoint} to query the status of an operation. """ pat...
Batch update conversations. Perform a change on a set of conversations. Operates asynchronously; use the {api:ProgressController#show progress endpoint} to query the status of an operation.
def hypergraph(raw_events, entity_types=None, opts={}, drop_na=True, drop_edge_attrs=False, verbose=True, direct=False): """Transform a dataframe into a hypergraph. :param Dataframe raw_events: Dataframe to transform :param List entity_types: Optional list of columns (strings) to turn into node...
Transform a dataframe into a hypergraph. :param Dataframe raw_events: Dataframe to transform :param List entity_types: Optional list of columns (strings) to turn into nodes, None signifies all :param Dict opts: See below :param bool drop_edge_attrs: Whether to include each row's attribu...
def load(target, source_module=None): """Get the actual implementation of the target.""" module, klass, function = _get_module(target) if not module and source_module: module = source_module if not module: raise MissingModule( "No module name supplied or source_module provide...
Get the actual implementation of the target.
def _get_document_data(f, image_handler=None): ''' ``f`` is a ``ZipFile`` that is open Extract out the document data, numbering data and the relationship data. ''' if image_handler is None: def image_handler(image_id, relationship_dict): return relationship_dict.get(image_id) ...
``f`` is a ``ZipFile`` that is open Extract out the document data, numbering data and the relationship data.
def volume_mesh(mesh, count): """ Use rejection sampling to produce points randomly distributed in the volume of a mesh. Parameters ---------- mesh: Trimesh object count: int, number of samples desired Returns ---------- samples: (n,3) float, points in the volume of the mesh. ...
Use rejection sampling to produce points randomly distributed in the volume of a mesh. Parameters ---------- mesh: Trimesh object count: int, number of samples desired Returns ---------- samples: (n,3) float, points in the volume of the mesh. where: n <= count
def B(self,value): """ set phenotype """ assert value.shape[0]==self._K, 'Dimension mismatch' assert value.shape[1]==1, 'Dimension mismatch' self._B = value self.clear_cache('predict','Yres')
set phenotype
def get_storage(self): '''Get the storage instance. :return Redis: Redis instance ''' if self.storage: return self.storage self.storage = self.reconnect_redis() return self.storage
Get the storage instance. :return Redis: Redis instance
def default_headers(self): """ It's always OK to include these headers """ _headers = { "User-Agent": "Pyzotero/%s" % __version__, "Zotero-API-Version": "%s" % __api_version__, } if self.api_key: _headers["Authorization"] = "Bearer %s" ...
It's always OK to include these headers
def find_input(self, stream): """Find the input that responds to this stream. Args: stream (DataStream): The stream to find Returns: (index, None): The index if found or None """ for i, input_x in enumerate(self.inputs): if input_x[0].matche...
Find the input that responds to this stream. Args: stream (DataStream): The stream to find Returns: (index, None): The index if found or None
def run( self, cluster_config, rg_parser, partition_measurer, cluster_balancer, args, ): """Initialize cluster_config, args, and zk then call run_command.""" self.cluster_config = cluster_config self.args = args ...
Initialize cluster_config, args, and zk then call run_command.
def open(self): """Open an existing database""" if self._table_exists(): self.mode = "open" # get table info self._get_table_info() self.types = dict([ (f[0],self.conv_func[f[1].upper()]) for f in self.fields if f[1].upper() in self...
Open an existing database
def add(name, device): ''' Add new device to RAID array. CLI Example: .. code-block:: bash salt '*' raid.add /dev/md0 /dev/sda1 ''' cmd = 'mdadm --manage {0} --add {1}'.format(name, device) if __salt__['cmd.retcode'](cmd) == 0: return True return False
Add new device to RAID array. CLI Example: .. code-block:: bash salt '*' raid.add /dev/md0 /dev/sda1
def load_yaml_file(filename): """ Load a YAML file from disk, throw a ParserError on failure.""" try: with open(filename, 'r') as f: return yaml.safe_load(f) except IOError as e: raise ParserError('Error opening ' + filename + ': ' + e.message) except ValueError as e: ...
Load a YAML file from disk, throw a ParserError on failure.
def add_activity_form(self, activity_pattern, is_active): """Adds the pattern as an active or inactive form to an Agent. Parameters ---------- activity_pattern : dict A dictionary of site names and their states. is_active : bool Is True if the given patte...
Adds the pattern as an active or inactive form to an Agent. Parameters ---------- activity_pattern : dict A dictionary of site names and their states. is_active : bool Is True if the given pattern corresponds to an active state.
def _kip(self, cycle_end, mix_thresh, xaxis, sparse): """ *** Should be used with care, therefore has been flagged as a private routine *** This function uses a threshold diffusion coefficient, above which the the shell is considered to be convective, to plot a Kippenhahn...
*** Should be used with care, therefore has been flagged as a private routine *** This function uses a threshold diffusion coefficient, above which the the shell is considered to be convective, to plot a Kippenhahn diagram. Parameters ---------- cycle_end : integ...
def pointAt(self, **axis_values): """ Returns the point on the chart where the inputed values are located. :return <QPointF> """ scene_point = self.renderer().pointAt(self.axes(), axis_values) chart_point = self.uiChartVIEW.mapFromScene(scene_point) ...
Returns the point on the chart where the inputed values are located. :return <QPointF>
def delete_cluster_role_binding(self, name, **kwargs): # noqa: E501 """delete_cluster_role_binding # noqa: E501 delete a ClusterRoleBinding # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >...
delete_cluster_role_binding # noqa: E501 delete a ClusterRoleBinding # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_cluster_role_binding(name, async_req=True) >>> re...
def _delocalize_logging_command(self, logging_path, user_project): """Returns a command to delocalize logs. Args: logging_path: location of log files. user_project: name of the project to be billed for the request. Returns: eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12' ...
Returns a command to delocalize logs. Args: logging_path: location of log files. user_project: name of the project to be billed for the request. Returns: eg. 'gs://bucket/path/myfile' or 'gs://bucket/script-foobar-12'
def points_from_xywh(box): """ Constructs a polygon representation from a rectangle described as a dict with keys x, y, w, h. """ x, y, w, h = box['x'], box['y'], box['w'], box['h'] # tesseract uses a different region representation format return "%i,%i %i,%i %i,%i %i,%i" % ( x, y, ...
Constructs a polygon representation from a rectangle described as a dict with keys x, y, w, h.
def get_certs(context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE): ''' Get the available certificates in the given store. :param str context: The name of the certificate store location context. :param str store: The name of the certificate store. :return: A dictionary of the certificate thumbprints an...
Get the available certificates in the given store. :param str context: The name of the certificate store location context. :param str store: The name of the certificate store. :return: A dictionary of the certificate thumbprints and properties. :rtype: dict CLI Example: .. code-block:: bash ...
def get_choices(cls, condition=None, order_by=None, query=None, value_field=None, text_field=None): """ Get [(value, text),...] list :param condition: :param value_field: default is primary_key :param text_field: default is unicode(obj) :return: """ result...
Get [(value, text),...] list :param condition: :param value_field: default is primary_key :param text_field: default is unicode(obj) :return:
def json_decode(s: str) -> Any: """ Decodes an object from JSON using our custom decoder. """ try: return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s) except json.JSONDecodeError: log.warning("Failed to decode JSON (returning None): {!r}", s) return None
Decodes an object from JSON using our custom decoder.
def get_ref(self, cat, refname): """Return one of the rules in the category ``cat`` with the name ``refname``. If multiple rule defintions exist for the defintion name ``refname``, use :any:`gramfuzz.rand` to choose a rule at random. :param str cat: The category to look for the rule in....
Return one of the rules in the category ``cat`` with the name ``refname``. If multiple rule defintions exist for the defintion name ``refname``, use :any:`gramfuzz.rand` to choose a rule at random. :param str cat: The category to look for the rule in. :param str refname: The name of the...
def write_networking_file(version, pairs): """ Write the VMware networking file. """ vmnets = OrderedDict(sorted(pairs.items(), key=lambda t: t[0])) try: with open(VMWARE_NETWORKING_FILE, "w", encoding="utf-8") as f: f.write(version) for key, value in vmnets.items():...
Write the VMware networking file.
def _opcode_set(*names): """Return a set of opcodes by the names in `names`.""" s = set() for name in names: try: s.add(_opcode(name)) except KeyError: pass return s
Return a set of opcodes by the names in `names`.
def request_client_list(self, req, msg): """Request the list of connected clients. The list of clients is sent as a sequence of #client-list informs. Informs ------- addr : str The address of the client as host:port with host in dotted quad notation. If ...
Request the list of connected clients. The list of clients is sent as a sequence of #client-list informs. Informs ------- addr : str The address of the client as host:port with host in dotted quad notation. If the address of the client could not be determined ...
def write_properties(self, properties, file_datetime): """ Write properties to the ndata file specified by reference. :param reference: the reference to which to write :param properties: the dict to write to the file :param file_datetime: the datetime for the fil...
Write properties to the ndata file specified by reference. :param reference: the reference to which to write :param properties: the dict to write to the file :param file_datetime: the datetime for the file The properties param must not change during this method. Callers...
def validate_unwrap(self, value): ''' Checks that value is a ``dict``, that every key is a valid MongoDB key, and that every value validates based on DictField.value_type ''' if not isinstance(value, dict): self._fail_validation_type(value, dict) for k, v in value...
Checks that value is a ``dict``, that every key is a valid MongoDB key, and that every value validates based on DictField.value_type
def delivery_note_pdf(self, delivery_note_id): """ Opens a pdf of a delivery note :param delivery_note_id: the delivery note id :return: dict """ return self._create_get_request(resource=DELIVERY_NOTES, billomat_id=delivery_note_id, command=PDF)
Opens a pdf of a delivery note :param delivery_note_id: the delivery note id :return: dict
def show_instance(name, session=None, call=None): ''' Show information about a specific VM or template .. code-block:: bash salt-cloud -a show_instance xenvm01 .. note:: memory is memory_dynamic_max ''' if call == 'function': raise SaltCloudException( 'The...
Show information about a specific VM or template .. code-block:: bash salt-cloud -a show_instance xenvm01 .. note:: memory is memory_dynamic_max
def spksub(handle, descr, identin, begin, end, newh): """ Extract a subset of the data in an SPK segment into a separate segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spksub_c.html :param handle: Handle of source segment. :type handle: int :param descr: Descriptor of sou...
Extract a subset of the data in an SPK segment into a separate segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spksub_c.html :param handle: Handle of source segment. :type handle: int :param descr: Descriptor of source segment. :type descr: 5-Element Array of floats :param...
def _dqdv_split_frames(cell, tidy=False, **kwargs): """Returns dqdv data as pandas.DataFrames for all cycles. Args: cell (CellpyData-object). tidy (bool): return in wide format if False (default), long (tidy) format if True. Returns: (charge_ica_...
Returns dqdv data as pandas.DataFrames for all cycles. Args: cell (CellpyData-object). tidy (bool): return in wide format if False (default), long (tidy) format if True. Returns: (charge_ica_frame, discharge_ica_frame) where the frames are ...
def get_token(self, request): """ Create a stripe token for a card """ return stripe.Token.create( card={ "number": request.data["number"], "exp_month": request.data["exp_month"], "exp_year": request.data["exp_year"], "c...
Create a stripe token for a card
async def create_proof(self, proof_req: dict, briefs: Union[dict, Sequence[dict]], requested_creds: dict) -> str: """ Create proof as HolderProver. Raise: * AbsentLinkSecret if link secret not set * CredentialFocus on attempt to create proof on no briefs or multiple brie...
Create proof as HolderProver. Raise: * AbsentLinkSecret if link secret not set * CredentialFocus on attempt to create proof on no briefs or multiple briefs for a credential definition * AbsentTails if missing required tails file * | BadRevStateTime if a timestamp...
def transfer_sanity_check( name, consensus_hash ): """ Verify that data for a transfer is valid. Return True on success Raise Exception on error """ if name is not None and (not is_b40( name ) or "+" in name or name.count(".") > 1): raise Exception("Name '%s' has non-base-38 characters" ...
Verify that data for a transfer is valid. Return True on success Raise Exception on error
def _fracRoiSparse(self): """ Calculate an approximate pixel coverage fraction from the two masks. We have no way to know a priori how much the coverage of the two masks overlap in a give pixel. For example, masks that each have frac = 0.5 could have a combined frac = [0.0 to 0....
Calculate an approximate pixel coverage fraction from the two masks. We have no way to know a priori how much the coverage of the two masks overlap in a give pixel. For example, masks that each have frac = 0.5 could have a combined frac = [0.0 to 0.5]. The limits will be: ma...
def process_file(pyfile_name): '''Process a Python source file with Google style docstring comments. Reads file header comment, function definitions, function docstrings. Returns dictionary encapsulation for subsequent writing. Args: pyfile_name (str): file name to read. Returns: ...
Process a Python source file with Google style docstring comments. Reads file header comment, function definitions, function docstrings. Returns dictionary encapsulation for subsequent writing. Args: pyfile_name (str): file name to read. Returns: Dictionary object containing summary c...