code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def find_session(self, session_name): """Finds guest sessions by their friendly name and returns an interface array with all found guest sessions. in session_name of type str The session's friendly name to find. Wildcards like ? and * are allowed. return sessions of type :c...
Finds guest sessions by their friendly name and returns an interface array with all found guest sessions. in session_name of type str The session's friendly name to find. Wildcards like ? and * are allowed. return sessions of type :class:`IGuestSession` Array with all g...
def _convert_old_schema(self, parameters): """ Convert an ugly old schema, using dotted names, to the hot new schema, using List and Structure. The old schema assumes that every other dot implies an array. So a list of two parameters, [Integer("foo.bar.baz.quux"), I...
Convert an ugly old schema, using dotted names, to the hot new schema, using List and Structure. The old schema assumes that every other dot implies an array. So a list of two parameters, [Integer("foo.bar.baz.quux"), Integer("foo.bar.shimmy")] becomes:: [List...
def canonical_new_peer_list( self, peers_to_add ): """ Make a list of canonical new peers, using the self.new_peers and the given peers to add Return a shuffled list of canonicalized host:port strings. """ new_peers = list(set(self.new_peers + peers_to_add)) ...
Make a list of canonical new peers, using the self.new_peers and the given peers to add Return a shuffled list of canonicalized host:port strings.
def to_unix_ts(start_time): """Given a datetime object, returns its value as a unix timestamp""" if isinstance(start_time, datetime): if is_timezone_aware(start_time): start_time = start_time.astimezone(pytz.utc) else: log.warning( "Non timezone-aware date...
Given a datetime object, returns its value as a unix timestamp
def get_target(self): """ Reads the android target based on project.properties file. Returns A string containing the project target (android-23 being the default if none is found) """ with open('%s/project.properties' % self.path) as f: for line in f.readlines(): matches = re.fi...
Reads the android target based on project.properties file. Returns A string containing the project target (android-23 being the default if none is found)
def event_later(self, delay, data_tuple): """ Schedule an event to be emitted after a delay. :param delay: number of seconds :param data_tuple: a 2-tuple (flavor, data) :return: an event object, useful for cancelling. """ return self._base.event_later(delay, self...
Schedule an event to be emitted after a delay. :param delay: number of seconds :param data_tuple: a 2-tuple (flavor, data) :return: an event object, useful for cancelling.
def trash_for(self, user): """ Returns all messages that were either received or sent by the given user and are marked as deleted. """ return self.filter( recipient=user, recipient_deleted_at__isnull=False, ) | self.filter( sender=user,...
Returns all messages that were either received or sent by the given user and are marked as deleted.
def remove_global_exception_handler(handler): """remove a callback from the list of global exception handlers :param handler: the callback, previously added via :func:`global_exception_handler`, to remove :type handler: function :returns: bool, whether the handler was found (and theref...
remove a callback from the list of global exception handlers :param handler: the callback, previously added via :func:`global_exception_handler`, to remove :type handler: function :returns: bool, whether the handler was found (and therefore removed)
def emit(_): """Serialize metrics to the memory mapped buffer.""" if not initialized: raise NotInitialized view = { 'version': __version__, 'counters': {}, 'gauges': {}, 'histograms': {}, 'meters': {}, 'timers': {}, } for (ty, module, name), ...
Serialize metrics to the memory mapped buffer.
def refresh_save_all_action(self): """Enable 'Save All' if there are files to be saved""" editorstack = self.get_current_editorstack() if editorstack: state = any(finfo.editor.document().isModified() or finfo.newly_created for finfo in editorstack.data) ...
Enable 'Save All' if there are files to be saved
def codons(self, frame): """ A generator that yields DNA in one codon blocks "frame" counts for 0. This function yields a tuple (triplet, index) with index relative to the original DNA sequence """ start = frame while start + 3 <= self.size: yield self.sequenc...
A generator that yields DNA in one codon blocks "frame" counts for 0. This function yields a tuple (triplet, index) with index relative to the original DNA sequence
def get_coord_system_name(header): """Return an appropriate key code for the axes coordinate system by examining the FITS header. """ try: ctype = header['CTYPE1'].strip().upper() except KeyError: try: # see if we have an "RA" header ra = header['RA'] # noqa ...
Return an appropriate key code for the axes coordinate system by examining the FITS header.
def get_path_to_repo(self, repo: str) -> Path: """ Returns a :class:`Path <pathlib.Path>` to the location where all the branches from this repo are stored. :param repo: Repo URL :return: Path to where branches from this repository are cloned. """ return Path(self.base_dir) / "re...
Returns a :class:`Path <pathlib.Path>` to the location where all the branches from this repo are stored. :param repo: Repo URL :return: Path to where branches from this repository are cloned.
def _infer_unknown_dims(old_shape, shape_spec): """Attempts to replace DIM_REST (if present) with a value. Because of `pt.DIM_SAME`, this has more information to compute a shape value than the default reshape's shape function. Args: old_shape: The current shape of the Tensor as a list. shape_spec: A s...
Attempts to replace DIM_REST (if present) with a value. Because of `pt.DIM_SAME`, this has more information to compute a shape value than the default reshape's shape function. Args: old_shape: The current shape of the Tensor as a list. shape_spec: A shape spec, see `pt.reshape`. Returns: A list de...
def syncTree(self, recursive=False, blockSignals=True): """ Syncs the information from this item to the tree. """ tree = self.treeWidget() # sync the tree information if not tree: return items = [self] if recursive:...
Syncs the information from this item to the tree.
def _replace_envvar(s, _): """env:KEY or env:KEY:DEFAULT""" e = s.split(":") if len(e) > 3 or len(e) == 1 or e[0] != "env": raise ValueError() elif len(e) == 2: # Note: this can/should raise a KeyError (according to spec). return os.environ[e[1]] else: # len(e) == 3 ...
env:KEY or env:KEY:DEFAULT
def branches(self): """Get basic block branches. """ branches = [] if self._taken_branch: branches += [(self._taken_branch, 'taken')] if self._not_taken_branch: branches += [(self._not_taken_branch, 'not-taken')] if self._direct_branch: ...
Get basic block branches.
def extend_to_data(self, data, **kwargs): """Build transition matrix from new data to the graph Creates a transition matrix such that `Y` can be approximated by a linear combination of landmarks. Any transformation of the landmarks can be trivially applied to `Y` by performing ...
Build transition matrix from new data to the graph Creates a transition matrix such that `Y` can be approximated by a linear combination of landmarks. Any transformation of the landmarks can be trivially applied to `Y` by performing `transform_Y = transitions.dot(transform)` ...
def wrap_paragraphs(content, hard_breaks=False): """ Returns *content* with all paragraphs wrapped in `<p>` tags. If *hard_breaks* is set, line breaks are converted to `<br />` tags. """ paras = filter(None, [para.strip() for para in content.split('\n\n')]) paras = [build_paragraph(para, hard_breaks) for ...
Returns *content* with all paragraphs wrapped in `<p>` tags. If *hard_breaks* is set, line breaks are converted to `<br />` tags.
def compile_dir(dfn, optimize_python=True): ''' Compile *.py in directory `dfn` to *.pyo ''' if PYTHON is None: return if int(PYTHON_VERSION[0]) >= 3: args = [PYTHON, '-m', 'compileall', '-b', '-f', dfn] else: args = [PYTHON, '-m', 'compileall', '-f', dfn] if optimi...
Compile *.py in directory `dfn` to *.pyo
def mtf_image_transformer_base_imagenet_mp64(): """Model parallel ImageNet parameters.""" hparams = mtf_image_transformer_base_imagenet() hparams.mesh_shape = "model:8;batch:4" hparams.layout = "batch:batch;d_ff:model;heads:model" hparams.batch_size = 8 hparams.img_len = 64 hparams.num_decoder_layers = 8 ...
Model parallel ImageNet parameters.
def create_placeholder_access_object(self, instance): """ Created objects with placeholder slots as properties. Each placeholder created for an object will be added to a `PlaceHolderAccess` object as a set property. """ related_model = self.related_model def get...
Created objects with placeholder slots as properties. Each placeholder created for an object will be added to a `PlaceHolderAccess` object as a set property.
def initialize(config): """ Initialize a connection to the Redis database. """ # Determine the client class to use if 'redis_client' in config: client = utils.find_entrypoint('turnstile.redis_client', config['redis_client'], required=True) else: ...
Initialize a connection to the Redis database.
def sheets(self): """return the sheets of data.""" data = Dict() for src in [src for src in self.zipfile.namelist() if 'xl/worksheets/' in src]: name = os.path.splitext(os.path.basename(src))[0] xml = self.xml(src) data[name] = xml return data
return the sheets of data.
def main(args,parser,subparser=None): '''this is the main entrypoint for a container based web server, with most of the variables coming from the environment. See the Dockerfile template for how this function is executed. ''' # First priority to args.base base = args.base if base is ...
this is the main entrypoint for a container based web server, with most of the variables coming from the environment. See the Dockerfile template for how this function is executed.
def get_all(self, sort_order=None, sort_target='key'): """Get all keys currently stored in etcd. :returns: sequence of (value, metadata) tuples """ return self.get( key=_encode(b'\0'), metadata=True, sort_order=sort_order, sort_target=sort...
Get all keys currently stored in etcd. :returns: sequence of (value, metadata) tuples
def PartialDynamicSystem(self, ieq, variable): """ returns dynamical system blocks associated to output variable """ if ieq == 0: # U2-U1=signal if variable == self.physical_nodes[0].variable: # U1 is output # U1=U2-signal ...
returns dynamical system blocks associated to output variable
def get_path_for_termid(self,termid): """ This function returns the path (in terms of phrase types) from one term the root @type termid: string @param termid: one term id @rtype: list @return: the path, list of phrase types """ terminal_id = self.term...
This function returns the path (in terms of phrase types) from one term the root @type termid: string @param termid: one term id @rtype: list @return: the path, list of phrase types
def find_path(network, pore_pairs, weights=None): r""" Find the shortest path between pairs of pores. Parameters ---------- network : OpenPNM Network Object The Network object on which the search should be performed pore_pairs : array_like An N x 2 array containing N pairs of p...
r""" Find the shortest path between pairs of pores. Parameters ---------- network : OpenPNM Network Object The Network object on which the search should be performed pore_pairs : array_like An N x 2 array containing N pairs of pores for which the shortest path is sought. ...
def blob_services(self): """Instance depends on the API version: * 2018-07-01: :class:`BlobServicesOperations<azure.mgmt.storage.v2018_07_01.operations.BlobServicesOperations>` """ api_version = self._get_api_version('blob_services') if api_version == '2018-07-01': ...
Instance depends on the API version: * 2018-07-01: :class:`BlobServicesOperations<azure.mgmt.storage.v2018_07_01.operations.BlobServicesOperations>`
def configure_interface(self, name, commands): """Configures the specified interface with the commands Args: name (str): The interface name to configure commands: The commands to configure in the interface Returns: True if the commands completed successfully...
Configures the specified interface with the commands Args: name (str): The interface name to configure commands: The commands to configure in the interface Returns: True if the commands completed successfully
def _init_sbc_config(self, config): """ Translator from namedtuple config representation to the sbc_t type. :param namedtuple config: See :py:class:`.SBCCodecConfig` :returns: """ if (config.channel_mode == SBCChannelMode.CHANNEL_MODE_MONO): self.conf...
Translator from namedtuple config representation to the sbc_t type. :param namedtuple config: See :py:class:`.SBCCodecConfig` :returns:
def last_or_default(self, default, predicate=None): '''The last element (optionally satisfying a predicate) or a default. If the predicate is omitted or is None this query returns the last element in the sequence; otherwise, it returns the last element in the sequence for which the pred...
The last element (optionally satisfying a predicate) or a default. If the predicate is omitted or is None this query returns the last element in the sequence; otherwise, it returns the last element in the sequence for which the predicate evaluates to True. If there is no such element th...
def lein(word, max_length=4, zero_pad=True): """Return the Lein code for a word. This is a wrapper for :py:meth:`Lein.encode`. Parameters ---------- word : str The word to transform max_length : int The length of the code returned (defaults to 4) zero_pad : bool Pad...
Return the Lein code for a word. This is a wrapper for :py:meth:`Lein.encode`. Parameters ---------- word : str The word to transform max_length : int The length of the code returned (defaults to 4) zero_pad : bool Pad the end of the return value with 0s to achieve a ma...
def image_alias_delete(image, alias, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Delete an alias (this is currently not restricted to the image) image : An image ...
Delete an alias (this is currently not restricted to the image) image : An image alias, a fingerprint or a image object alias : The alias to delete remote_addr : An URL to a remote Server, you also have to give cert and key if you provide remote...
def move_entry(self, entry = None, group = None): """Move an entry to another group. A v1Group group and a v1Entry entry are needed. """ if entry is None or group is None or type(entry) is not v1Entry or \ type(group) is not v1Group: raise KPError("Need an entr...
Move an entry to another group. A v1Group group and a v1Entry entry are needed.
def style_node(self, additional_style_attrib=None): """ generate a style node (for automatic-styles) could specify additional attributes such as 'style:parent-style-name' or 'style:list-style-name' """ style_attrib = {"style:name": self.name, "style:family": self.FAMILY...
generate a style node (for automatic-styles) could specify additional attributes such as 'style:parent-style-name' or 'style:list-style-name'
def TryLink( self, text, extension ): """Compiles the program given in text to an executable env.Program, using extension as file extension (e.g. '.c'). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing). """ ...
Compiles the program given in text to an executable env.Program, using extension as file extension (e.g. '.c'). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing).
def simplified(self): """A simplified representation of the same transformation. """ if self._simplified is None: self._simplified = SimplifiedChainTransform(self) return self._simplified
A simplified representation of the same transformation.
def wnfild(small, window): """ Fill small gaps between adjacent intervals of a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnfild_c.html :param small: Limiting measure of small gaps. :type small: float :param window: Window to be filled :type window: ...
Fill small gaps between adjacent intervals of a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnfild_c.html :param small: Limiting measure of small gaps. :type small: float :param window: Window to be filled :type window: spiceypy.utils.support_types.SpiceCell ...
def pad_light(self, values): """Accept an array of up to 4 values, and return an array of 4 values. If the input array is less than length 4, pad it with zeroes until it is length 4. Also ensure each value is a float""" while len(values) < 4: values.append(0.) return...
Accept an array of up to 4 values, and return an array of 4 values. If the input array is less than length 4, pad it with zeroes until it is length 4. Also ensure each value is a float
def vq_loss(x, targets, codebook_size, beta=0.25, decay=0.999, epsilon=1e-5, soft_em=False, num_samples=10, temperature=None, do_update=True): """Compute the loss of large vocab tensors using a VQAE codebook. ...
Compute the loss of large vocab tensors using a VQAE codebook. Args: x: Tensor of inputs to be quantized to nearest code targets: Tensor of target indices to target codes codebook_size: Size of quantization codebook beta: scalar float for moving averages decay: scalar float for moving averages ...
def get_form(self, request, obj=None, **kwargs): """ Returns a Form class for use in the admin add view. This is used by add_view and change_view. """ parent_id = request.REQUEST.get('parent_id', None) if parent_id: return FolderForm else: ...
Returns a Form class for use in the admin add view. This is used by add_view and change_view.
def _parse_snapshot_share(response, name): ''' Extracts snapshot return header. ''' snapshot = response.headers.get('x-ms-snapshot') return _parse_share(response, name, snapshot)
Extracts snapshot return header.
def pprint(sequence_file, annotation=None, annotation_file=None, block_length=10, blocks_per_line=6): """ Pretty-print sequence(s) from a file. """ annotations = [] if annotation: annotations.append([(first - 1, last) for first, last in annotation]) try: # Peek to se...
Pretty-print sequence(s) from a file.
def detect_language(index_page): """ Detect `languages` using `langdetect` library. Args: index_page (str): HTML content of the page you wish to analyze. Returns: obj: One :class:`.SourceString` object. """ dom = dhtmlparser.parseString(index_page) clean_content = dhtmlpar...
Detect `languages` using `langdetect` library. Args: index_page (str): HTML content of the page you wish to analyze. Returns: obj: One :class:`.SourceString` object.
def copy(self, key=None): """ Return a new collection with the same items as this one. If *key* is specified, create the new collection with the given Redis key. """ other = self.__class__( redis=self.redis, key=key, writeback=self.writeback ) ...
Return a new collection with the same items as this one. If *key* is specified, create the new collection with the given Redis key.
def list_space_systems(self, page_size=None): """ Lists the space systems visible to this client. Space systems are returned in lexicographical order. :rtype: :class:`.SpaceSystem` iterator """ params = {} if page_size is not None: params['limit'] =...
Lists the space systems visible to this client. Space systems are returned in lexicographical order. :rtype: :class:`.SpaceSystem` iterator
def mutate(self, node, index): """Modify the numeric value on `node`.""" assert index < len(OFFSETS), 'received count with no associated offset' assert isinstance(node, parso.python.tree.Number) val = eval(node.value) + OFFSETS[index] # pylint: disable=W0123 return parso.pytho...
Modify the numeric value on `node`.
def create_or_update_issue_remote_links(self, issue_key, link_url, title, global_id=None, relationship=None): """ Add Remote Link to Issue, update url if global_id is passed :param issue_key: str :param link_url: str :param title: str :param global_id: str, OPTIONAL: ...
Add Remote Link to Issue, update url if global_id is passed :param issue_key: str :param link_url: str :param title: str :param global_id: str, OPTIONAL: :param relationship: str, OPTIONAL: Default by built-in method: 'Web Link'
def make_secure_stub(credentials, user_agent, stub_class, host, extra_options=()): """Makes a secure stub for an RPC service. Uses / depends on gRPC. :type credentials: :class:`google.auth.credentials.Credentials` :param credentials: The OAuth2 Credentials to use for creating a...
Makes a secure stub for an RPC service. Uses / depends on gRPC. :type credentials: :class:`google.auth.credentials.Credentials` :param credentials: The OAuth2 Credentials to use for creating access tokens. :type user_agent: str :param user_agent: The user agent to be used ...
def get_shell_history(): """ This only works with some shells. """ # try for ipython if 'get_ipython' in globals(): a = list(get_ipython().history_manager.input_hist_raw) a.reverse() return a elif 'SPYDER_SHELL_ID' in _os.environ: try: p = _os.path.jo...
This only works with some shells.
def tag_secondary_structure(self, force=False): """Tags each `Monomer` in the `Assembly` with it's secondary structure. Notes ----- DSSP must be available to call. Check by running `isambard.external_programs.dssp.test_dssp`. If DSSP is not available, please follow instr...
Tags each `Monomer` in the `Assembly` with it's secondary structure. Notes ----- DSSP must be available to call. Check by running `isambard.external_programs.dssp.test_dssp`. If DSSP is not available, please follow instruction here to add it: https://github.com/woolfson-...
def update_config(configclass: type(Config)): """Command line function to update and the a config.""" # we build the real click command inside the function, because it needs to be done # dynamically, depending on the config. # we ignore the type errors, keeping the the defaults if needed # everyth...
Command line function to update and the a config.
def list_all(dev: Device): """List all available API calls.""" for name, service in dev.services.items(): click.echo(click.style("\nService %s" % name, bold=True)) for method in service.methods: click.echo(" %s" % method.name)
List all available API calls.
def generate_labels_from_classifications(classifications, timestamps): """ This is to generate continuous segments out of classified small windows :param classifications: :param timestamps: :return: """ window_length = timestamps[1] - timestamps[0] combo_l...
This is to generate continuous segments out of classified small windows :param classifications: :param timestamps: :return:
def get_client(self, initial_timeout=0.1, next_timeout=30): """ Wait until a client instance is available :param float initial_timeout: how long to wait initially for an existing client to complete :param float next_timeout: if the pool could not obtain a client durin...
Wait until a client instance is available :param float initial_timeout: how long to wait initially for an existing client to complete :param float next_timeout: if the pool could not obtain a client during the initial timeout, and we have allocated the maximum available num...
def one_way(data, n): """ One-way chi-square test of independence. Takes a 1D array as input and compares activation at each voxel to proportion expected under a uniform distribution throughout the array. Note that if you're testing activation with this, make sure that only valid voxels (e.g., in-ma...
One-way chi-square test of independence. Takes a 1D array as input and compares activation at each voxel to proportion expected under a uniform distribution throughout the array. Note that if you're testing activation with this, make sure that only valid voxels (e.g., in-mask gray matter voxels) are inc...
def _visit_for(self, cls, node, parent): """visit a For node by returning a fresh instance of it""" newnode = cls(node.lineno, node.col_offset, parent) type_annotation = self.check_type_comment(node) newnode.postinit( target=self.visit(node.target, newnode), iter=...
visit a For node by returning a fresh instance of it
def multi_constructor_pkl(loader, tag_suffix, node): """ Constructor function passed to PyYAML telling it how to load objects from paths to .pkl files. See PyYAML documentation for details on the call signature. """ mapping = loader.construct_yaml_str(node) if tag_suffix != "" and tag_suffi...
Constructor function passed to PyYAML telling it how to load objects from paths to .pkl files. See PyYAML documentation for details on the call signature.
def run_inference(examples, serving_bundle): """Run inference on examples given model information Args: examples: A list of examples that matches the model spec. serving_bundle: A `ServingBundle` object that contains the information to make the inference request. Returns: A ClassificationRespo...
Run inference on examples given model information Args: examples: A list of examples that matches the model spec. serving_bundle: A `ServingBundle` object that contains the information to make the inference request. Returns: A ClassificationResponse or RegressionResponse proto.
def K_separator_demister_York(P, horizontal=False): r'''Calculates the Sounders Brown `K` factor as used in determining maximum permissible gas velocity in a two-phase separator in either a horizontal or vertical orientation, *with a demister*. This function is a curve fit to [1]_ published in [2]_ an...
r'''Calculates the Sounders Brown `K` factor as used in determining maximum permissible gas velocity in a two-phase separator in either a horizontal or vertical orientation, *with a demister*. This function is a curve fit to [1]_ published in [2]_ and is widely used. For 1 < P < 15 psia: ...
def decree(cls, path, concrete_start='', **kwargs): """ Constructor for Decree binary analysis. :param str path: Path to binary to analyze :param str concrete_start: Concrete stdin to use before symbolic input :param kwargs: Forwarded to the Manticore constructor :return...
Constructor for Decree binary analysis. :param str path: Path to binary to analyze :param str concrete_start: Concrete stdin to use before symbolic input :param kwargs: Forwarded to the Manticore constructor :return: Manticore instance, initialized with a Decree State :rtype: Ma...
def put_stream(self, rel_path, metadata=None, cb=None): '''Return a Flo object that can be written to to send data to S3. This will result in a multi-part upload, possibly with each part being sent in its own thread ''' import Queue import time import threading ...
Return a Flo object that can be written to to send data to S3. This will result in a multi-part upload, possibly with each part being sent in its own thread
def get_next(self): """Return the next node for this walk of the tree. This function is intentionally iterative, not recursive, to sidestep any issues of stack size limitations. """ while self.stack: if self.stack[-1].wkids: node = self.stack[-1].wki...
Return the next node for this walk of the tree. This function is intentionally iterative, not recursive, to sidestep any issues of stack size limitations.
def get_matrix_index(graph: BELGraph) -> Set[str]: """Return set of HGNC names from Proteins/Rnas/Genes/miRNA, nodes that can be used by SPIA.""" # TODO: Using HGNC Symbols for now return { node.name for node in graph if isinstance(node, CentralDogma) and node.namespace.upper() == 'H...
Return set of HGNC names from Proteins/Rnas/Genes/miRNA, nodes that can be used by SPIA.
def update_commands(self, commands_str): """ update with commands from the block """ commands = dict(parse_qsl(commands_str, keep_blank_values=True)) _if = commands.get("if", self._if) if _if: self._if = Condition(_if) self._set_int(commands, "max_leng...
update with commands from the block
def check_trytes_codec(encoding): """ Determines which codec to use for the specified encoding. References: - https://docs.python.org/3/library/codecs.html#codecs.register """ if encoding == AsciiTrytesCodec.name: return AsciiTrytesCodec.get_codec_info() elif encoding == AsciiTryt...
Determines which codec to use for the specified encoding. References: - https://docs.python.org/3/library/codecs.html#codecs.register
def merge_intervals(intervals): """ Merge intervals in the form of a list. """ if intervals is None: return None intervals.sort(key=lambda i: i[0]) out = [intervals.pop(0)] for i in intervals: if out[-1][-1] >= i[0]: out[-1][-1] = max(out[-1][-1], i[-1]) else: ...
Merge intervals in the form of a list.
def serialize_to_xml_str(obj_pyxb, pretty=True, strip_prolog=False, xslt_url=None): """Serialize PyXB object to pretty printed XML ``str`` for display. Args: obj_pyxb: PyXB object PyXB object to serialize. pretty: bool False: Disable pretty print formatting. XML will not have line ...
Serialize PyXB object to pretty printed XML ``str`` for display. Args: obj_pyxb: PyXB object PyXB object to serialize. pretty: bool False: Disable pretty print formatting. XML will not have line breaks. strip_prolog: True: remove any XML prolog (e.g., ``<?xml version="1....
def get_optimized_molecule(self): """Return a molecule object of the optimal geometry""" opt_coor = self.get_optimization_coordinates() if len(opt_coor) == 0: return None else: return Molecule( self.molecule.numbers, opt_coor[-1], ...
Return a molecule object of the optimal geometry
def sample_from_distribution(self, distribution, k, proportions=False): """Return a new table with the same number of rows and a new column. The values in the distribution column are define a multinomial. They are replaced by sample counts/proportions in the output. >>> sizes = Table(['...
Return a new table with the same number of rows and a new column. The values in the distribution column are define a multinomial. They are replaced by sample counts/proportions in the output. >>> sizes = Table(['size', 'count']).with_rows([ ... ['small', 50], ... ['mediu...
def _drop_duplicate_ij(self): """ Drops duplicate entries from the network dataframe. """ self.network['ij'] = list(map(lambda x: tuple(sorted(x)), list( zip(*[self.network['i'].values, self.network['j'].values])))) self.network.drop_duplicates(['ij', 't'], inplace=Tr...
Drops duplicate entries from the network dataframe.
def create_many(self, statements): """ Creates multiple statement entries. """ create_statements = [] for statement in statements: statement_data = statement.serialize() tag_data = list(set(statement_data.pop('tags', []))) statement_data['tags...
Creates multiple statement entries.
async def execute(self, query: str, *args, timeout: float=None) -> str: """Execute an SQL command (or commands). Pool performs this operation using one of its connections. Other than that, it behaves identically to :meth:`Connection.execute() <connection.Connection.execute>`. ...
Execute an SQL command (or commands). Pool performs this operation using one of its connections. Other than that, it behaves identically to :meth:`Connection.execute() <connection.Connection.execute>`. .. versionadded:: 0.10.0
def setBaudrate(self, baudrate): '''set baudrate''' from . import mavutil if self.baudrate == baudrate: return self.baudrate = baudrate self.mav.mav.serial_control_send(self.port, ...
set baudrate
def PopEvent(self): """Pops an event from the heap. Returns: tuple: containing: str: identifier of the event MACB group or None if the event cannot be grouped. str: identifier of the event content. EventObject: event. """ try: macb_group_identifier, cont...
Pops an event from the heap. Returns: tuple: containing: str: identifier of the event MACB group or None if the event cannot be grouped. str: identifier of the event content. EventObject: event.
def op( name, labels, predictions, num_thresholds=None, weights=None, display_name=None, description=None, collections=None): """Create a PR curve summary op for a single binary classifier. Computes true/false positive/negative values for the given `predictions` against the ground...
Create a PR curve summary op for a single binary classifier. Computes true/false positive/negative values for the given `predictions` against the ground truth `labels`, against a list of evenly distributed threshold values in `[0, 1]` of length `num_thresholds`. Each number in `predictions`, a float in `[0, 1...
def add_template(self, tpl): """ Adds and index a template into the `templates` container. This implementation takes into account that a service has two naming attribute: `host_name` and `service_description`. :param tpl: The template to add :type tpl: :return: ...
Adds and index a template into the `templates` container. This implementation takes into account that a service has two naming attribute: `host_name` and `service_description`. :param tpl: The template to add :type tpl: :return: None
def _send(self, data): """Send data to statsd.""" try: self._sock.sendto(data.encode('ascii'), self._addr) except (socket.error, RuntimeError): # No time for love, Dr. Jones! pass
Send data to statsd.
def display_name(self): """ Find the most appropriate display name for a user: look for a "display_name", then a "real_name", and finally fall back to the always-present "name". """ for k in self._NAME_KEYS: if self._raw.get(k): return self._raw[k] ...
Find the most appropriate display name for a user: look for a "display_name", then a "real_name", and finally fall back to the always-present "name".
def hash(self): ''' :rtype: int :return: hash of the condition ''' hashed = super(Compare, self).hash() return khash(hashed, self._comp_value, self._comp_type)
:rtype: int :return: hash of the condition
def _get_bq_service(credentials=None, service_url=None): """Construct an authorized BigQuery service object.""" assert credentials, 'Must provide ServiceAccountCredentials' http = credentials.authorize(Http()) service = build( 'bigquery', 'v2', http=http, discoveryServi...
Construct an authorized BigQuery service object.
def list_(): ''' Return the list of frozen states. CLI Example: .. code-block:: bash salt '*' freezer.list ''' ret = [] states_path = _states_path() if not os.path.isdir(states_path): return ret for state in os.listdir(states_path): if state.endswith(('-p...
Return the list of frozen states. CLI Example: .. code-block:: bash salt '*' freezer.list
def numberOfXTilesAtZoom(self, zoom): "Returns the number of tiles over x at a given zoom level" [minRow, minCol, maxRow, maxCol] = self.getExtentAddress(zoom) return maxCol - minCol + 1
Returns the number of tiles over x at a given zoom level
def get_last_weeks(number_of_weeks): """Get the last weeks.""" time_now = datetime.now() year = time_now.isocalendar()[0] week = time_now.isocalendar()[1] weeks = [] for i in range(0, number_of_weeks): start = get_week_dates(year, week - i, as_timestamp=True)[0] n_year, n_week = ...
Get the last weeks.
def from_pubkey(cls, pubkey, compressed=True, version=56, prefix=None): # Ensure this is a public key pubkey = PublicKey(pubkey, prefix=prefix or Prefix.prefix) if compressed: pubkey_plain = pubkey.compressed() else: pubkey_plain = pubkey.uncompressed() "...
Derive address using ``RIPEMD160(SHA512(x))``
def save_model(model, output_file=None, output_dir=None, output_prefix='pymzn'): """Save a model to file. Parameters ---------- model : str The minizinc model (i.e. the content of a ``.mzn`` file). output_file : str The path to the output file. If this parameter is ``None`` (default...
Save a model to file. Parameters ---------- model : str The minizinc model (i.e. the content of a ``.mzn`` file). output_file : str The path to the output file. If this parameter is ``None`` (default), a temporary file is created with the given model in the specified output ...
def get_point(self, *position): """Return the noise value of a specific position. Example usage: value = noise.getPoint(x, y, z) Args: position (Tuple[float, ...]): The point to sample at. Returns: float: The noise value at position. This will ...
Return the noise value of a specific position. Example usage: value = noise.getPoint(x, y, z) Args: position (Tuple[float, ...]): The point to sample at. Returns: float: The noise value at position. This will be a floating point in the 0.0-1.0 range.
def set_boolean(self, option, value): """Set a boolean option. Args: option (str): name of option. value (bool): value of the option. Raises: TypeError: Value must be a boolean. """ if not isinstance(value, bool): ...
Set a boolean option. Args: option (str): name of option. value (bool): value of the option. Raises: TypeError: Value must be a boolean.
def plot(self, format='segments', bits=None, **kwargs): """Plot the data for this `StateVector` Parameters ---------- format : `str`, optional, default: ``'segments'`` The type of plot to make, either 'segments' to plot the SegmentList for each bit, or 'timeserie...
Plot the data for this `StateVector` Parameters ---------- format : `str`, optional, default: ``'segments'`` The type of plot to make, either 'segments' to plot the SegmentList for each bit, or 'timeseries' to plot the raw data for this `StateVector` ...
def idxmax(self, axis=0, skipna=True, *args, **kwargs): """ Return the row label of the maximum value. If multiple values equal the maximum, the first row label with that value is returned. Parameters ---------- skipna : bool, default True Exclude NA...
Return the row label of the maximum value. If multiple values equal the maximum, the first row label with that value is returned. Parameters ---------- skipna : bool, default True Exclude NA/null values. If the entire Series is NA, the result will be NA....
def from_df(cls, df, **kwargs): """ DataFrame must have the right columns. these are: name, band, resolution, mag, e_mag, separation, pa """ tree = cls(**kwargs) for (n,b), g in df.groupby(['name','band']): #g.sort('separation', inplace=True) #ensures that t...
DataFrame must have the right columns. these are: name, band, resolution, mag, e_mag, separation, pa
def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['channel'] = self.channel json_dict['disable_inhibit_forced'] = self.disable_inhibit_forced json_dict['status'] = self.status json_dict['led_status'] = self.led_status ...
:return: str
def _doBottomUpCompute(self, rfInput, resetSignal): """ Do one iteration of inference and/or learning and return the result Parameters: -------------------------------------------- rfInput: Input vector. Shape is: (1, inputVectorLen). resetSignal: True if reset is asserted """ #...
Do one iteration of inference and/or learning and return the result Parameters: -------------------------------------------- rfInput: Input vector. Shape is: (1, inputVectorLen). resetSignal: True if reset is asserted
def get_value_from_handle(self, handle, key, handlerecord_json=None): ''' Retrieve a single value from a single Handle. If several entries with this key exist, the methods returns the first one. If the handle does not exist, the method will raise a HandleNotFoundException. :para...
Retrieve a single value from a single Handle. If several entries with this key exist, the methods returns the first one. If the handle does not exist, the method will raise a HandleNotFoundException. :param handle: The handle to take the value from. :param key: The key. :return:...
def assign_valence(mol): """Assign pi electron and hydrogens""" for u, v, bond in mol.bonds_iter(): if bond.order == 2: mol.atom(u).pi = 1 mol.atom(v).pi = 1 if mol.atom(u).symbol == "O" and not mol.atom(u).charge: mol.atom(v).carbonyl_C = 1 ...
Assign pi electron and hydrogens
def get_curline(): """Return the current python source line.""" if Frame: frame = Frame.get_selected_python_frame() if frame: line = '' f = frame.get_pyop() if f and not f.is_optimized_out(): cwd = os.path.join(os.getcwd(), '') ...
Return the current python source line.
def setUp(self, mfd_conf): ''' Input core configuration parameters as specified in the configuration file :param dict mfd_conf: Configuration file containing the following attributes: * 'Type' - Choose between the 1st, 2nd or 3rd type of recurrence mo...
Input core configuration parameters as specified in the configuration file :param dict mfd_conf: Configuration file containing the following attributes: * 'Type' - Choose between the 1st, 2nd or 3rd type of recurrence model {'First' | 'Second' | 'Third'} ...
def deploy(stage, lambda_package, no_lambda, rebuild_deps, config_file): """Deploy the project to the development stage.""" config = _load_config(config_file) if stage is None: stage = config['devstage'] s3 = boto3.client('s3') cfn = boto3.client('cloudformation') region = _get_aws_regi...
Deploy the project to the development stage.