code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_worksheet(self, id_or_name): """ Gets a specific worksheet by id or name """ url = self.build_url(self._endpoints.get('get_worksheet').format(id=quote(id_or_name))) response = self.session.get(url) if not response: return None return self.worksheet_constructor...
Gets a specific worksheet by id or name
def remove_record(self, record): """Remove an already accepted record from the community. :param record: Record object. :type record: `invenio_records.api.Record` """ if not self.has_record(record): current_app.logger.warning( 'Community removal: reco...
Remove an already accepted record from the community. :param record: Record object. :type record: `invenio_records.api.Record`
def fetch_command(self, global_options, subcommand): """ Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "uliweb") if it can't be found. """ commands = self.get_commands(global_options) ...
Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "uliweb") if it can't be found.
def _sanity_check_coerce_type_outside_of_fold(ir_blocks): """Ensure that CoerceType not in a @fold are followed by a MarkLocation or Filter block.""" is_in_fold = False for first_block, second_block in pairwise(ir_blocks): if isinstance(first_block, Fold): is_in_fold = True if n...
Ensure that CoerceType not in a @fold are followed by a MarkLocation or Filter block.
def main(argv): """ Main mon :param argv: console arguments :return: """ input_file = "" output_file = "" monitor = None formula = None trace = None iformula = None itrace = None isys = None online = False fuzzer = False l2m = False debug = False r...
Main mon :param argv: console arguments :return:
def setData(self, data, setName=None): """ Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names. Args: data: The dataframe containing the data to be assigned. setName: The name of the set to which the indices val...
Assign the data in the dataframe to the AMPL entities with the names corresponding to the column names. Args: data: The dataframe containing the data to be assigned. setName: The name of the set to which the indices values of the DataFrame are to be assigned. ...
def getConfig(self, key): """ Get a Config Value """ if hasattr(self, key): return getattr(self, key) else: return False
Get a Config Value
def get_instance(self, payload): """ Build an instance of RoleInstance :param dict payload: Payload response from the API :returns: twilio.rest.chat.v2.service.role.RoleInstance :rtype: twilio.rest.chat.v2.service.role.RoleInstance """ return RoleInstance(self._...
Build an instance of RoleInstance :param dict payload: Payload response from the API :returns: twilio.rest.chat.v2.service.role.RoleInstance :rtype: twilio.rest.chat.v2.service.role.RoleInstance
def all_sharded_cluster_links(cluster_id, shard_id=None, router_id=None, rel_to=None): """Get a list of all links to be included with ShardedClusters.""" return [ sharded_cluster_link(rel, cluster_id, shard_id, router_id, self_rel=(rel == rel_to...
Get a list of all links to be included with ShardedClusters.
def parts(self, *args, **kwargs): """Retrieve parts belonging to this activity. Without any arguments it retrieves the Instances related to this task only. This call only returns the configured properties in an activity. So properties that are not configured are not in the returned par...
Retrieve parts belonging to this activity. Without any arguments it retrieves the Instances related to this task only. This call only returns the configured properties in an activity. So properties that are not configured are not in the returned parts. See :class:`pykechain.Client.par...
def _filter_desc(self, indexing): ''' Private function to filter data, goes with filter_desc ''' # now filter data if len(indexing) > 0: desc_tmp = np.zeros((len(indexing),len(self.header_desc)),dtype='|S1024') data_tmp = np.zeros((len(indexing),len(self...
Private function to filter data, goes with filter_desc
def update_group_states_for_vifs(self, vifs, ack): """Updates security groups by setting the ack field""" vif_keys = [self.vif_key(vif.device_id, vif.mac_address) for vif in vifs] self.set_fields(vif_keys, SECURITY_GROUP_ACK, ack)
Updates security groups by setting the ack field
def customchain(**kwargsChain): """ This decorator allows you to access ``ctx.bitshares`` which is an instance of BitShares. But in contrast to @chain, this is a decorator that expects parameters that are directed right to ``BitShares()``. ... code-block::python @ma...
This decorator allows you to access ``ctx.bitshares`` which is an instance of BitShares. But in contrast to @chain, this is a decorator that expects parameters that are directed right to ``BitShares()``. ... code-block::python @main.command() @click.opti...
def stop(self): """Stop the sensor. """ # Check that everything is running if not self._running: logging.warning('Webcam not running. Aborting stop') return False if self._cap: self._cap.release() self._cap = None self._run...
Stop the sensor.
def release(input_dict, environment_dict): """ <Purpose> Releases the specified vessels. <Arguments> input_dict: The commanddict representing the user's input. environment_dict: The dictionary representing the current seash environment. <Side Effects> Connects to the C...
<Purpose> Releases the specified vessels. <Arguments> input_dict: The commanddict representing the user's input. environment_dict: The dictionary representing the current seash environment. <Side Effects> Connects to the Clearinghouse and releases vessels. Removes the ...
def _onSize(self, evt): """ Called when wxEventSize is generated. In this application we attempt to resize to fit the window, so it is better to take the performance hit and redraw the whole window. """ DEBUG_MSG("_onSize()", 2, self) # Create a new, correctly s...
Called when wxEventSize is generated. In this application we attempt to resize to fit the window, so it is better to take the performance hit and redraw the whole window.
def new(partname, content_type): """ Return a new ``<Override>`` element with attributes set to parameter values. """ xml = '<Override xmlns="%s"/>' % nsmap['ct'] override = parse_xml(xml) override.set('PartName', partname) override.set('ContentType', cont...
Return a new ``<Override>`` element with attributes set to parameter values.
def add_multiple_to_queue(self, items, container=None): """Add a sequence of items to the queue. Args: items (list): A sequence of items to the be added to the queue container (DidlObject, optional): A container object which includes the items. """ ...
Add a sequence of items to the queue. Args: items (list): A sequence of items to the be added to the queue container (DidlObject, optional): A container object which includes the items.
def _get_sd(file_descr): """ Get streamdescriptor matching file_descr fileno. :param file_descr: file object :return: StreamDescriptor or None """ for stream_descr in NonBlockingStreamReader._streams: if file_descr == stream_descr.stream.fileno(): ...
Get streamdescriptor matching file_descr fileno. :param file_descr: file object :return: StreamDescriptor or None
def init_cas_a (year): """Insert an entry for Cas A into the table of models. Need to specify the year of the observations to account for the time variation of Cas A's emission. """ year = float (year) models['CasA'] = lambda f: cas_a (f, year)
Insert an entry for Cas A into the table of models. Need to specify the year of the observations to account for the time variation of Cas A's emission.
def consume(iterator, n): "Advance the iterator n-steps ahead. If n is none, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length deque collections.deque(iterator, maxlen=0) else: # advance to the empty ...
Advance the iterator n-steps ahead. If n is none, consume entirely.
def _legion_state(self, inputs, t, argv): """! @brief Returns new values of excitatory and inhibitory parts of oscillator and potential of oscillator. @param[in] inputs (list): Initial values (current) of oscillator [excitatory, inhibitory, potential]. @param[in] t (double)...
! @brief Returns new values of excitatory and inhibitory parts of oscillator and potential of oscillator. @param[in] inputs (list): Initial values (current) of oscillator [excitatory, inhibitory, potential]. @param[in] t (double): Current time of simulation. @param[in] argv...
def fix(self): """ Fix the layouts and calculate the locations of all the widgets. This function should be called once all Layouts have been added to the Frame and all widgets added to the Layouts. """ # Do up to 2 passes in case we have a variable height Layout. ...
Fix the layouts and calculate the locations of all the widgets. This function should be called once all Layouts have been added to the Frame and all widgets added to the Layouts.
def _getgrnam(name, root=None): ''' Alternative implementation for getgrnam, that use only /etc/group ''' root = root or '/' passwd = os.path.join(root, 'etc/group') with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) ...
Alternative implementation for getgrnam, that use only /etc/group
def hosts(self, **kwargs): """ Convenience wrapper around listHosts(...) for this channel ID. :param **kwargs: keyword arguments to the listHosts RPC. :returns: deferred that when fired returns a list of hosts (dicts). """ kwargs['channelID'] = self.id return sel...
Convenience wrapper around listHosts(...) for this channel ID. :param **kwargs: keyword arguments to the listHosts RPC. :returns: deferred that when fired returns a list of hosts (dicts).
def es_query_proto(path, selects, wheres, schema): """ RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE :param path: THE NESTED PATH (NOT INCLUDING TABLE NAME) :param wheres: MAP FROM path TO LIST OF WHERE CONDITIONS :return: (es_query, filters_map) TUPLE """ output = None last_where = MA...
RETURN TEMPLATE AND PATH-TO-FILTER AS A 2-TUPLE :param path: THE NESTED PATH (NOT INCLUDING TABLE NAME) :param wheres: MAP FROM path TO LIST OF WHERE CONDITIONS :return: (es_query, filters_map) TUPLE
def retrieveVals(self): """Retrieve values for graphs.""" file_stats = self._fileInfo.getContainerStats() for contname in self._fileContList: stats = file_stats.get(contname) if stats is not None: if self.hasGraph('rackspace_cloudfiles_container_size'): ...
Retrieve values for graphs.
def _add_access_token_to_response(self, response, access_token): # type: (oic.message.AccessTokenResponse, se_leg_op.access_token.AccessToken) -> None """ Adds the Access Token and the associated parameters to the Token Response. """ response['access_token'] = access_token.value ...
Adds the Access Token and the associated parameters to the Token Response.
def Create(self, *args, **kwargs): """Calls Driver.Create() with optionally provided creation options as dict, or falls back to driver specific defaults. """ if not self.writable: raise IOError('Driver does not support raster creation') options = kwargs.pop('options',...
Calls Driver.Create() with optionally provided creation options as dict, or falls back to driver specific defaults.
def wrap(self, sock): """Wrap and return the given socket, plus WSGI environ entries.""" EMPTY_RESULT = None, {} try: s = self.context.wrap_socket( sock, do_handshake_on_connect=True, server_side=True, ) except ssl.SSLError as ex: if ex...
Wrap and return the given socket, plus WSGI environ entries.
def _replace_coerce(self, to_replace, value, inplace=True, regex=False, convert=False, mask=None): """ Replace value corresponding to the given boolean array with another value. Parameters ---------- to_replace : object or pattern Scal...
Replace value corresponding to the given boolean array with another value. Parameters ---------- to_replace : object or pattern Scalar to replace or regular expression to match. value : object Replacement object. inplace : bool, default False ...
def assume_role_credentials(self, arn): """Return the environment variables for an assumed role""" log.info("Assuming role as %s", arn) # Clear out empty values for name in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN']: if name in ...
Return the environment variables for an assumed role
def _start(self): """ Starts the underlying send and receive threads. """ # Initialize the locks self._recv_lock = coros.Semaphore(0) self._send_lock = coros.Semaphore(0) # Boot the threads self._recv_thread = gevent.spawn(self._recv) self._send_...
Starts the underlying send and receive threads.
def get_memfree(memory, parallel): """Computes the memory required for the memfree field.""" number = int(memory.rstrip(string.ascii_letters)) memtype = memory.lstrip(string.digits) if not memtype: memtype = "G" return "%d%s" % (number*parallel, memtype)
Computes the memory required for the memfree field.
def select_by_index(self, index): """Select the option at the given index. This is done by examing the "index" attribute of an element, and not merely by counting. :Args: - index - The option at this index will be selected throws NoSuchElementException If there is ...
Select the option at the given index. This is done by examing the "index" attribute of an element, and not merely by counting. :Args: - index - The option at this index will be selected throws NoSuchElementException If there is no option with specified index in SELECT
def clearOldCalibrations(self, date=None): ''' if not only a specific date than remove all except of the youngest calibration ''' self.coeffs['dark current'] = [self.coeffs['dark current'][-1]] self.coeffs['noise'] = [self.coeffs['noise'][-1]] for light in self.co...
if not only a specific date than remove all except of the youngest calibration
def buscar_timeout_opcvip(self, id_ambiente_vip): """Buscar nome_opcao_txt das Opcoes VIp quando tipo_opcao = 'Timeout' pelo environmentvip_id :return: Dictionary with the following structure: :: {‘timeout_opt’: ‘timeout_opt’: <'nome_opcao_txt'>} :raise InvalidParameterErr...
Buscar nome_opcao_txt das Opcoes VIp quando tipo_opcao = 'Timeout' pelo environmentvip_id :return: Dictionary with the following structure: :: {‘timeout_opt’: ‘timeout_opt’: <'nome_opcao_txt'>} :raise InvalidParameterError: Environment VIP identifier is null and invalid. :...
def _shrink_list(self, shrink): """ Shrink list down to essentials :param shrink: List to shrink :type shrink: list :return: Shrunk list :rtype: list """ res = [] if len(shrink) == 1: return self.shrink(shrink[0]) else: ...
Shrink list down to essentials :param shrink: List to shrink :type shrink: list :return: Shrunk list :rtype: list
def updateTerms(self, data:list, LIMIT:int=20, _print:bool=True, crawl:bool=False,) -> list: """ Updates existing entities Args: data: needs: id <str> ilx_id <str> options: ...
Updates existing entities Args: data: needs: id <str> ilx_id <str> options: definition <str> #bug with qutations superclasses ...
def read(self): """Reads the data stored in the files we have been initialized with. It will ignore files that cannot be read, possibly leaving an empty configuration :return: Nothing :raise IOError: if a file cannot be handled""" if self._is_initialized: return ...
Reads the data stored in the files we have been initialized with. It will ignore files that cannot be read, possibly leaving an empty configuration :return: Nothing :raise IOError: if a file cannot be handled
def spaceout_and_resize_panels(self): """ Adjust the spacing between the panels and resize them to meet the aspect ratio """ ncol = self.ncol nrow = self.nrow figure = self.figure theme = self.theme get_property = theme.themeables.property ...
Adjust the spacing between the panels and resize them to meet the aspect ratio
def close(self): """ Stop listing for new connections and close all open connections. :returns: Deferred that calls back once everything is closed. """ assert self._opened, "RPC System is not opened" logger.debug("Closing rpc system. Stopping ping loop") ...
Stop listing for new connections and close all open connections. :returns: Deferred that calls back once everything is closed.
def _inferSchemaFromList(self, data, names=None): """ Infer schema from list of Row or tuple. :param data: list of Row or tuple :param names: list of column names :return: :class:`pyspark.sql.types.StructType` """ if not data: raise ValueError("can no...
Infer schema from list of Row or tuple. :param data: list of Row or tuple :param names: list of column names :return: :class:`pyspark.sql.types.StructType`
def distance_centimeters_continuous(self): """ Measurement of the distance detected by the sensor, in centimeters. The sensor will continue to take measurements so they are available for future reads. Prefer using the equivalent :meth:`UltrasonicSensor.distance_centimet...
Measurement of the distance detected by the sensor, in centimeters. The sensor will continue to take measurements so they are available for future reads. Prefer using the equivalent :meth:`UltrasonicSensor.distance_centimeters` property.
def build(self, X, Y, w=None, edges=None): """ Assigns data to this object and builds the requested topological structure @ In, X, an m-by-n array of values specifying m n-dimensional samples @ In, Y, a m vector of values specifying the output response...
Assigns data to this object and builds the requested topological structure @ In, X, an m-by-n array of values specifying m n-dimensional samples @ In, Y, a m vector of values specifying the output responses corresponding to the m samples specified by X ...
def adsSyncWriteControlReqEx( port, address, ads_state, device_state, data, plc_data_type ): # type: (int, AmsAddr, int, int, Any, Type) -> None """Change the ADS state and the machine-state of the ADS-server. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAd...
Change the ADS state and the machine-state of the ADS-server. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr adr: local or remote AmsAddr :param int ads_state: new ADS-state, according to ADSTATE constants :param int device_state: new machine-state :para...
def getTableAsCsv(self, networkId, tableType, verbose=None): """ Returns a CSV representation of the table specified by the `networkId` and `tableType` parameters. All column names are included in the first row. :param networkId: SUID of the network containing the table :param tableType...
Returns a CSV representation of the table specified by the `networkId` and `tableType` parameters. All column names are included in the first row. :param networkId: SUID of the network containing the table :param tableType: Table type :param verbose: print more :returns: 200: successfu...
def start_resolver(finder=None, wheel_cache=None): """Context manager to produce a resolver. :param finder: A package finder to use for searching the index :type finder: :class:`~pip._internal.index.PackageFinder` :return: A 3-tuple of finder, preparer, resolver :rtype: (:class:`~pip._internal.oper...
Context manager to produce a resolver. :param finder: A package finder to use for searching the index :type finder: :class:`~pip._internal.index.PackageFinder` :return: A 3-tuple of finder, preparer, resolver :rtype: (:class:`~pip._internal.operations.prepare.RequirementPreparer`, :class:`~pip._interna...
def find_by_id(self, organization_export, params={}, **options): """Returns details of a previously-requested Organization export. Parameters ---------- organization_export : {Id} Globally unique identifier for the Organization export. [params] : {Object} Parameters for the req...
Returns details of a previously-requested Organization export. Parameters ---------- organization_export : {Id} Globally unique identifier for the Organization export. [params] : {Object} Parameters for the request
def format_modes(modes, full_modes=False, current_mode=None): """ Creates a nice readily printable Table for a list of modes. Used in `displays list' and the candidates list in `displays set'. """ t = table.Table((( '*' if mode == current_mode else '', ...
Creates a nice readily printable Table for a list of modes. Used in `displays list' and the candidates list in `displays set'.
def __step1(self): """ For each row of the matrix, find the smallest element and subtract it from every element in its row. Go to Step 2. """ C = self.C n = self.n for i in range(n): minval = min(self.C[i]) # Find the minimum value for this...
For each row of the matrix, find the smallest element and subtract it from every element in its row. Go to Step 2.
def _handle_double_click(self, event): """ Double click with left mouse button focuses the element""" if event.get_button()[1] == 1: # Left mouse button path_info = self.tree_view.get_path_at_pos(int(event.x), int(event.y)) if path_info: # Valid entry was clicked on ...
Double click with left mouse button focuses the element
def transform(self, X): """ Parameters ---------- X : array-like, shape [n x m] The mask in form of n x m array. """ if self.mode_ == 'target': return np.apply_along_axis(self._target, 1, np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2]))...
Parameters ---------- X : array-like, shape [n x m] The mask in form of n x m array.
async def _async_connect(self): # pragma: no cover """ connect and authenticate to the XMPP server. Async mode. """ try: self.conn_coro = self.client.connected() aenter = type(self.conn_coro).__aenter__(self.conn_coro) self.stream = await aenter logger.in...
connect and authenticate to the XMPP server. Async mode.
def rytov_sc(radius=5e-6, sphere_index=1.339, medium_index=1.333, wavelength=550e-9, pixel_size=1e-7, grid_size=(80, 80), center=(39.5, 39.5), radius_sampling=42): r"""Field behind a dielectric sphere, systematically corrected Rytov This method implements a correction of :func:`qp...
r"""Field behind a dielectric sphere, systematically corrected Rytov This method implements a correction of :func:`qpsphere.models.rytov`, where the `radius` :math:`r_\text{Ryt}` and the `sphere_index` :math:`n_\text{Ryt}` are corrected using the approach described in :cite:`Mueller2018` (eqns. 3,4...
def keys(name, basepath='/etc/pki', **kwargs): ''' Manage libvirt keys. name The name variable used to track the execution basepath Defaults to ``/etc/pki``, this is the root location used for libvirt keys on the hypervisor The following parameters are optional: c...
Manage libvirt keys. name The name variable used to track the execution basepath Defaults to ``/etc/pki``, this is the root location used for libvirt keys on the hypervisor The following parameters are optional: country The country that the certificate should ...
def shapely_formatter(_, vertices, codes=None): """`Shapely`_ style contour formatter. Contours are returned as a list of :class:`shapely.geometry.LineString`, :class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point` geometry elements. Filled contours return a list of :class:`shap...
`Shapely`_ style contour formatter. Contours are returned as a list of :class:`shapely.geometry.LineString`, :class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point` geometry elements. Filled contours return a list of :class:`shapely.geometry.Polygon` elements instead. .. not...
def plot_data(): '''Plot sample data up with the fancy colormaps. ''' var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM'] # colorbar limits for each property lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2]...
Plot sample data up with the fancy colormaps.
def config_acl(args): ''' Retrieve access control list for a method configuration''' r = fapi.get_repository_config_acl(args.namespace, args.config, args.snapshot_id) fapi._check_response_code(r, 200) acls = sorted(r.json(), key=lambda k: k['user']) ...
Retrieve access control list for a method configuration
def set_current_limit(self, value, channel=1): """ channel: 1=OP1, 2=OP2, AUX is not supported""" cmd = "I%d %f" % (channel, value) self.write(cmd)
channel: 1=OP1, 2=OP2, AUX is not supported
def get_type_hints(obj, globalns=None, localns=None): """Return type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, and if necessary adds Optional[t] if a default value equal to None is set. The argument may be a mo...
Return type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, and if necessary adds Optional[t] if a default value equal to None is set. The argument may be a module, class, method, or function. The annotations are ret...
def average_data(self,ranges=[[None,None]],percentile=None): """ given a list of ranges, return single point averages for every sweep. Units are in seconds. Expects something like: ranges=[[1,2],[4,5],[7,7.5]] None values will be replaced with maximum/minimum bounds. ...
given a list of ranges, return single point averages for every sweep. Units are in seconds. Expects something like: ranges=[[1,2],[4,5],[7,7.5]] None values will be replaced with maximum/minimum bounds. For baseline subtraction, make a range baseline then sub it youtself. ...
def expanding_stdize(obj, **kwargs): """Standardize a pandas object column-wise on expanding window. **kwargs -> passed to `obj.expanding` Example ------- df = pd.DataFrame(np.random.randn(10, 3)) print(expanding_stdize(df, min_periods=5)) 0 1 2 0 ...
Standardize a pandas object column-wise on expanding window. **kwargs -> passed to `obj.expanding` Example ------- df = pd.DataFrame(np.random.randn(10, 3)) print(expanding_stdize(df, min_periods=5)) 0 1 2 0 NaN NaN NaN 1 NaN Na...
def _all_escape(self): """ u """ # Toggle all escaped URLs self.unesc = not self.unesc self.urls, self.urls_unesc = self.urls_unesc, self.urls urls = iter(self.urls) for item in self.items: # Each Column has (Text, Button). Update the Button label ...
u
def usable_ids(cls, id, accept_multi=True): """ Retrieve id from input which can be an id or a cn.""" try: qry_id = [int(id)] except ValueError: try: qry_id = cls.from_cn(id) except Exception: qry_id = None if not qry_i...
Retrieve id from input which can be an id or a cn.
def installed(name, pkgs=None, dir=None, user=None, force_reinstall=False, registry=None, env=None): ''' Verify that the given package is installed and is at the correct version (if specified). .. code-block:: yaml ...
Verify that the given package is installed and is at the correct version (if specified). .. code-block:: yaml coffee-script: npm.installed: - user: someuser coffee-script@1.0.1: npm.installed: [] name The package to install .. versionchang...
def print_summary(self): """Print a summary of the form. May help finding which fields need to be filled-in. """ for input in self.form.find_all( ("input", "textarea", "select", "button")): input_copy = copy.copy(input) # Text between the opening ...
Print a summary of the form. May help finding which fields need to be filled-in.
def preferred_format(incomplete_format, preferred_formats): """Return the preferred format for the given extension""" incomplete_format = long_form_one_format(incomplete_format) if 'format_name' in incomplete_format: return incomplete_format for fmt in long_form_multiple_formats(preferred_forma...
Return the preferred format for the given extension
def extract_fields(lines, delim, searches, match_lineno=1, **kwargs): """Return generator of fields matching `searches`. Parameters ---------- lines : iterable Provides line number (1-based) and line (str) delim : str Delimiter to split line by to produce fields searches : itera...
Return generator of fields matching `searches`. Parameters ---------- lines : iterable Provides line number (1-based) and line (str) delim : str Delimiter to split line by to produce fields searches : iterable Returns search (str) to match against line fields. match_line...
def completeness(self, catalogue, config, saveplot=False, filetype='png', timeout=120): ''' :param catalogue: Earthquake catalogue as instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue` :param dict config: Configuration para...
:param catalogue: Earthquake catalogue as instance of :class:`openquake.hmtk.seismicity.catalogue.Catalogue` :param dict config: Configuration parameters of the algorithm, containing the following information: 'magnitude_bin' Size of magnitude bin (non...
def get_local_annotations( cls, target, exclude=None, ctx=None, select=lambda *p: True ): """Get a list of local target annotations in the order of their definition. :param type cls: type of annotation to get from target. :param target: target from where get annotati...
Get a list of local target annotations in the order of their definition. :param type cls: type of annotation to get from target. :param target: target from where get annotations. :param tuple/type exclude: annotation types to exclude from selection. :param ctx: target ctx. ...
def _split_tidy(self, string, maxsplit=None): """Rstrips string for \n and splits string for \t""" if maxsplit is None: return string.rstrip("\n").split("\t") else: return string.rstrip("\n").split("\t", maxsplit)
Rstrips string for \n and splits string for \t
def ae_latent_softmax(latents_pred, latents_discrete, hparams): """Latent prediction and loss.""" vocab_size = 2 ** hparams.z_size if hparams.num_decode_blocks < 2: latents_logits = tf.layers.dense(latents_pred, vocab_size, name="extra_logits") if hparams.logit_normali...
Latent prediction and loss.
def get_all_groups(region=None, key=None, keyid=None, profile=None): ''' Return all AutoScale Groups visible in the account (as a list of boto.ec2.autoscale.group.AutoScalingGroup). .. versionadded:: 2016.11.0 CLI example: .. code-block:: bash salt-call boto_asg.get_all_groups region...
Return all AutoScale Groups visible in the account (as a list of boto.ec2.autoscale.group.AutoScalingGroup). .. versionadded:: 2016.11.0 CLI example: .. code-block:: bash salt-call boto_asg.get_all_groups region=us-east-1 --output yaml
def hessian(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 Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy """ #self._check_interp(grid_interp_x, grid_interp_y, f_, f_x, f_y, f_xx, f_yy, f_xy) ...
returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy
def add_interface_to_router(self, segment_id, router_name, gip, router_ip, mask, server): """Adds an interface to existing HW router on Arista HW device. :param segment_id: VLAN Id associated with interface that is added :param router_name: globally unique identi...
Adds an interface to existing HW router on Arista HW device. :param segment_id: VLAN Id associated with interface that is added :param router_name: globally unique identifier for router/VRF :param gip: Gateway IP associated with the subnet :param router_ip: IP address of the router ...
def issues(self): """ Returns a list of dicts representing issues from a remote service. """ for board in self.get_boards(): for lst in self.get_lists(board['id']): listextra = dict(boardname=board['name'], listname=lst['name']) for card in sel...
Returns a list of dicts representing issues from a remote service.
def get_analysis_question(hazard, exposure): """Construct analysis question based on hazard and exposure. :param hazard: A hazard definition. :type hazard: dict :param exposure: An exposure definition. :type exposure: dict :returns: Analysis question based on reporting standards. :rtype: ...
Construct analysis question based on hazard and exposure. :param hazard: A hazard definition. :type hazard: dict :param exposure: An exposure definition. :type exposure: dict :returns: Analysis question based on reporting standards. :rtype: str
def increment(self, key, value=1): """ Increment the value of an item in the cache. :param key: The cache key :type key: str :param value: The increment value :type value: int :rtype: int or bool """ data, time_ = self._get_payload(key) ...
Increment the value of an item in the cache. :param key: The cache key :type key: str :param value: The increment value :type value: int :rtype: int or bool
def update(self, response): """Update session information from device response. Increment sequence number when starting stream, not when playing. If device requires authentication resend previous message with auth. """ data = response.splitlines() _LOGGER.debug('Received...
Update session information from device response. Increment sequence number when starting stream, not when playing. If device requires authentication resend previous message with auth.
def from_string(string, _or=''): """ Parse a given string and turn it into an input token. """ if _or: and_or = 'or' else: and_or = '' return Input(string, and_or=and_or)
Parse a given string and turn it into an input token.
def eval(self, expression): """Evaluate `expression` in MATLAB engine. Parameters ---------- expression : str Expression is passed to MATLAB engine and evaluated. """ expression_wrapped = wrap_script.format(expression) ### Evaluate the expression ...
Evaluate `expression` in MATLAB engine. Parameters ---------- expression : str Expression is passed to MATLAB engine and evaluated.
def uninstall_pgpm_from_db(self): """ Removes pgpm from db and all related metadata (_pgpm schema). Install packages are left as they are :return: 0 if successful and error otherwise """ drop_schema_cascade_script = 'DROP SCHEMA {schema_name} CASCADE;' if self._conn.clos...
Removes pgpm from db and all related metadata (_pgpm schema). Install packages are left as they are :return: 0 if successful and error otherwise
def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int: """ Run the transaction with various gas limits, progressively approaching the minimum needed to succeed without an OutOfGas exception. The starting range of possible estimates is: [transaction.intrinsic...
Run the transaction with various gas limits, progressively approaching the minimum needed to succeed without an OutOfGas exception. The starting range of possible estimates is: [transaction.intrinsic_gas, state.gas_limit]. After the first OutOfGas exception, the range is: (largest_limit_out_of_gas, sta...
def product_data_request(self): """Request product data from a device. Not supported by all devices. Required after 01-Feb-2007. """ msg = StandardSend(self._address, COMMAND_PRODUCT_DATA_REQUEST_0X03_0X00) self._send_msg(msg)
Request product data from a device. Not supported by all devices. Required after 01-Feb-2007.
def chunks(seq, chunk_size): # type: (Sequence[T], int) -> Iterable[Sequence[T]] """ Split seq into chunk_size-sized chunks. :param seq: A sequence to chunk. :param chunk_size: The size of chunk. """ return (seq[i:i + chunk_size] for i in range(0, len(seq), chunk_size))
Split seq into chunk_size-sized chunks. :param seq: A sequence to chunk. :param chunk_size: The size of chunk.
def command(execute=None): # noqa: E501 """Execute a Command Execute a command # noqa: E501 :param execute: The data needed to execute this command :type execute: dict | bytes :rtype: Response """ if connexion.request.is_json: execute = Execute.from_dict(connexion.request.get_jso...
Execute a Command Execute a command # noqa: E501 :param execute: The data needed to execute this command :type execute: dict | bytes :rtype: Response
def get_pickled_ontology(filename): """ try to retrieve a cached ontology """ pickledfile = os.path.join(ONTOSPY_LOCAL_CACHE, filename + ".pickle") # pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle" if GLOBAL_DISABLE_CACHE: printDebug( "WARNING: DEMO MODE cache has been...
try to retrieve a cached ontology
def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; how...
Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health info...
def _extend_support_with_default_value(self, x, f, default_value): """Returns `f(x)` if x is in the support, and `default_value` otherwise. Given `f` which is defined on the support of this distribution (`x >= loc`), extend the function definition to the real line by defining `f(x) = default_value` for...
Returns `f(x)` if x is in the support, and `default_value` otherwise. Given `f` which is defined on the support of this distribution (`x >= loc`), extend the function definition to the real line by defining `f(x) = default_value` for `x < loc`. Args: x: Floating-point `Tensor` to evaluate `f` at...
def fetch_entity_cls_from_registry(entity): """Util Method to fetch an Entity class from an entity's name""" # Defensive check to ensure we only process if `to_cls` is a string if isinstance(entity, str): try: return repo_factory.get_entity(entity) except AssertionError: ...
Util Method to fetch an Entity class from an entity's name
def add_object(self, start, obj, object_size): """ Add/Store an object to this region at the given offset. :param start: :param obj: :param int object_size: Size of the object :return: """ self._store(start, obj, object_size, overwrite=False)
Add/Store an object to this region at the given offset. :param start: :param obj: :param int object_size: Size of the object :return:
def text_input(self, window, allow_resize=False): """ Transform a window into a text box that will accept user input and loop until an escape sequence is entered. If the escape key (27) is pressed, cancel the textbox and return None. Otherwise, the textbox will wait until it is ...
Transform a window into a text box that will accept user input and loop until an escape sequence is entered. If the escape key (27) is pressed, cancel the textbox and return None. Otherwise, the textbox will wait until it is full (^j, or a new line is entered on the bottom line) or the ...
def _merge(self, value): """ Returns a list based on `value`: * missing required value is converted to an empty list; * missing required items are never created; * nested items are merged recursively. """ if not value: return [] if value is not None...
Returns a list based on `value`: * missing required value is converted to an empty list; * missing required items are never created; * nested items are merged recursively.
def getRegionsByType(self, regionClass): """ Gets all region instances of a given class (for example, nupic.regions.sp_region.SPRegion). """ regions = [] for region in self.regions.values(): if type(region.getSelf()) is regionClass: regions.append(region) return regions
Gets all region instances of a given class (for example, nupic.regions.sp_region.SPRegion).
def get(self, name, default=None): ''' Retrieves the object with "name", like with SessionManager.get(), but removes the object from the database after retrieval, so that it can be retrieved only once ''' session_object = super(NotificationManager, self).get(name, defaul...
Retrieves the object with "name", like with SessionManager.get(), but removes the object from the database after retrieval, so that it can be retrieved only once
def tag_name(cls, tag): """return the name of the tag, with the namespace removed""" while isinstance(tag, etree._Element): tag = tag.tag return tag.split('}')[-1]
return the name of the tag, with the namespace removed
def get_levenshtein(first, second): """\ Get the Levenshtein distance between two strings. :param first: the first string :param second: the second string """ if not first: return len(second) if not second: return len(first) prev_distances = range(0, len(second)...
\ Get the Levenshtein distance between two strings. :param first: the first string :param second: the second string
def log(arg, base=None): """ Perform the logarithm using a specified base Parameters ---------- base : number, default None If None, base e is used Returns ------- logarithm : double type """ op = ops.Log(arg, base) return op.to_expr()
Perform the logarithm using a specified base Parameters ---------- base : number, default None If None, base e is used Returns ------- logarithm : double type
def _complete_path(path=None): """Perform completion of filesystem path. https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input """ if not path: return _listdir('.') dirname, rest = os.path.split(path) tmp = dirname if dirname else '.' res = [p for p ...
Perform completion of filesystem path. https://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input