positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def process_timer(self, key, fields):
"""
Process a received timer event
:param key: Key of timer
:param fields: Received fields
"""
try:
if key not in self.timers:
self.timers[key] = []
self.timers[key].append(float(fields[0]))
... | Process a received timer event
:param key: Key of timer
:param fields: Received fields |
def _get_indirect_shadowing_information(contract):
"""
Obtain a string that describes variable shadowing for the given variable. None if no shadowing exists.
:param var: The variable to collect shadowing information for.
:param contract: The contract in which this variable is being analy... | Obtain a string that describes variable shadowing for the given variable. None if no shadowing exists.
:param var: The variable to collect shadowing information for.
:param contract: The contract in which this variable is being analyzed.
:return: Returns a string describing variable shadowing fo... |
def bosonic_constraints(a):
"""Return a set of constraints that define fermionic ladder operators.
:param a: The non-Hermitian variables.
:type a: list of :class:`sympy.physics.quantum.operator.Operator`.
:returns: a dict of substitutions.
"""
substitutions = {}
for i, ai in enumerate(a):
... | Return a set of constraints that define fermionic ladder operators.
:param a: The non-Hermitian variables.
:type a: list of :class:`sympy.physics.quantum.operator.Operator`.
:returns: a dict of substitutions. |
def _convert_to_floats(self, data):
"""
Convert all values in a dict to floats
"""
for key, value in data.items():
data[key] = float(value)
return data | Convert all values in a dict to floats |
def invert(self, points):
"""Invert the distortion
Parameters
------------------
points : ndarray
Input image points
Returns
-----------------
ndarray
Undistorted points
"""
X = points if not points.ndim == 1 else points.r... | Invert the distortion
Parameters
------------------
points : ndarray
Input image points
Returns
-----------------
ndarray
Undistorted points |
def _update_grammar(self):
"""
We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also
has the new entities that are extracted from the utterance. Stitching together the expressions
to form the grammar is a little tedious here, but it is worth it because we ... | We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also
has the new entities that are extracted from the utterance. Stitching together the expressions
to form the grammar is a little tedious here, but it is worth it because we don't have to create
a new grammar from... |
def string_array_to_list(a):
"""
Turns the Java string array into Python unicode string list.
:param a: the string array to convert
:type a: JB_Object
:return: the string list
:rtype: list
"""
result = []
length = javabridge.get_env().get_array_length(a)
wrapped = javabridge.get... | Turns the Java string array into Python unicode string list.
:param a: the string array to convert
:type a: JB_Object
:return: the string list
:rtype: list |
def tree_libs(start_path, filt_func=None):
""" Return analysis of library dependencies within `start_path`
Parameters
----------
start_path : str
root path of tree to search for libraries depending on other libraries.
filt_func : None or callable, optional
If None, inspect all files... | Return analysis of library dependencies within `start_path`
Parameters
----------
start_path : str
root path of tree to search for libraries depending on other libraries.
filt_func : None or callable, optional
If None, inspect all files for library dependencies. If callable,
acc... |
def build_config(ctx, target, config_path, c, extra_path, ignore, verbose, silent, debug):
""" Creates a LintConfig object based on a set of commandline parameters. """
config_builder = LintConfigBuilder()
try:
# Config precedence:
# First, load default config or config from configfile
... | Creates a LintConfig object based on a set of commandline parameters. |
def parse_man_page(command, platform):
"""Parse the man page and return the parsed lines."""
page_path = find_page_location(command, platform)
output_lines = parse_page(page_path)
return output_lines | Parse the man page and return the parsed lines. |
def unhumanize_bandwidth(bitsstr):
'''
Take a string representing a link capacity, e.g., 10 Mb/s, and
return an integer representing the number of bits/sec.
Recognizes:
- 'bits/sec' or 'b/s' are treated as plain bits per second
- 'Kb' or 'kb' as thousand bits/sec
- 'Mb' or 'mb' a... | Take a string representing a link capacity, e.g., 10 Mb/s, and
return an integer representing the number of bits/sec.
Recognizes:
- 'bits/sec' or 'b/s' are treated as plain bits per second
- 'Kb' or 'kb' as thousand bits/sec
- 'Mb' or 'mb' as million bits/sec
- 'Gb' or 'gb' as bi... |
def _assertion(self, matcher, value):
""" Perform the actual assertion for the given matcher and value. Override
this method to apply a special configuration when performing the assertion.
If the assertion fails it should raise an AssertionError.
"""
# To support the synt... | Perform the actual assertion for the given matcher and value. Override
this method to apply a special configuration when performing the assertion.
If the assertion fails it should raise an AssertionError. |
def aes_b64_encrypt(value, secret, block_size=AES.block_size):
""" AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
... | AES encrypt @value with @secret using the |CFB| mode of AES
with a cryptographically secure initialization vector.
-> (#str) AES encrypted @value
..
from vital.security import aes_encrypt, aes_decrypt
aes_encrypt("Hello, world",
"aLWEFlwgwlreWELF... |
def GetValue(self):
'''
NOTE: Added on plane. Cannot remember exact implementation
of counter objects. I believe that they count sequentail
pairings of options
e.g.
-vvvvv
But I'm not sure. That's what I'm going with for now.
Returns
str(action.options_string[0]) * DropDown Valu... | NOTE: Added on plane. Cannot remember exact implementation
of counter objects. I believe that they count sequentail
pairings of options
e.g.
-vvvvv
But I'm not sure. That's what I'm going with for now.
Returns
str(action.options_string[0]) * DropDown Value |
def add_signature_headers(mail, sigs, error_msg):
'''Add pseudo headers to the mail indicating whether the signature
verification was successful.
:param mail: :class:`email.message.Message` the message to entitle
:param sigs: list of :class:`gpg.results.Signature`
:param error_msg: An error message... | Add pseudo headers to the mail indicating whether the signature
verification was successful.
:param mail: :class:`email.message.Message` the message to entitle
:param sigs: list of :class:`gpg.results.Signature`
:param error_msg: An error message if there is one, or None
:type error_msg: :class:`st... |
def invalidate_model_cache(self):
"""
Invalidate model cache by generating new key for the model.
"""
logger.info('Invalidating cache for table {0}'.format(self.model._meta.db_table))
if django.VERSION >= (1, 8):
related_tables = set(
[f.related_model.... | Invalidate model cache by generating new key for the model. |
def clean_data(self, data, rename_col=None, drop_col=None,
resample=True, freq='h', resampler='mean',
interpolate=True, limit=1, method='linear',
remove_na=True, remove_na_how='any',
remove_outliers=True, sd_val=3,
remov... | Cleans dataframe according to user specifications and stores result in self.cleaned_data.
Parameters
----------
data : pd.DataFrame()
Dataframe to be cleaned.
rename_col : list(str)
List of new column names.
drop_col ... |
def normalize_col_name(self, col_name, used_column_names, is_relation):
"""
Modify the column name to make it Python-compatible as a field name
"""
field_params = {}
field_notes = []
new_name = col_name.lower()
if new_name != col_name:
field_notes.app... | Modify the column name to make it Python-compatible as a field name |
def classes_can_admin(self):
"""Return all the classes (sorted) that this user can admin."""
if self.is_admin:
return sorted(Session.query(Class).all())
else:
return sorted(self.admin_for) | Return all the classes (sorted) that this user can admin. |
async def send_cred_def(self, s_id: str, revocation: bool = True, rr_size: int = None) -> str:
"""
Create a credential definition as Issuer, store it in its wallet, and send it to the ledger.
Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure
to sen... | Create a credential definition as Issuer, store it in its wallet, and send it to the ledger.
Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure
to send credential definition to ledger if need be, or IndyError for any other failure
to create and store creden... |
def Decrypt(self, encrypted_data):
"""Decrypts the encrypted data.
Args:
encrypted_data (bytes): encrypted data.
Returns:
tuple[bytes, bytes]: decrypted data and remaining encrypted data.
"""
index_split = -(len(encrypted_data) % AES.block_size)
if index_split:
remaining_encr... | Decrypts the encrypted data.
Args:
encrypted_data (bytes): encrypted data.
Returns:
tuple[bytes, bytes]: decrypted data and remaining encrypted data. |
def list(self, enabled=values.unset, date_created_after=values.unset,
date_created_before=values.unset, friendly_name=values.unset,
limit=None, page_size=None):
"""
Lists CompositionHookInstance records from the API as a list.
Unlike stream(), this operation is eager an... | Lists CompositionHookInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param bool enabled: Only show Composition Hooks enabled or disabled.
:param datetime date_created_after: Only show Composit... |
def use_isolated_objective_bank_view(self):
"""Pass through to provider ObjectiveLookupSession.use_isolated_objective_bank_view"""
self._objective_bank_view = ISOLATED
# self._get_provider_session('objective_lookup_session') # To make sure the session is tracked
for session in self._get_... | Pass through to provider ObjectiveLookupSession.use_isolated_objective_bank_view |
def do_driz(insci, input_wcs, inwht,
output_wcs, outsci, outwht, outcon,
expin, in_units, wt_scl,
wcslin_pscale=1.0,uniqid=1, pixfrac=1.0, kernel='square',
fillval="INDEF", stepsize=10,wcsmap=None):
"""
Core routine for performing 'drizzle' operation on a single i... | Core routine for performing 'drizzle' operation on a single input image
All input values will be Python objects such as ndarrays, instead
of filenames.
File handling (input and output) will be performed by calling routine. |
def singletrial(num_trials, skipstep=1):
""" Single-trial cross-validation schema
Use one trial for training, all others for testing.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
only use every `skipstep` trial for training
Returns
-----... | Single-trial cross-validation schema
Use one trial for training, all others for testing.
Parameters
----------
num_trials : int
Total number of trials
skipstep : int
only use every `skipstep` trial for training
Returns
-------
gen : generator object
the generat... |
def run_duplicated_snps(in_prefix, in_type, out_prefix, base_dir, options):
"""Runs step2 (duplicated snps).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options:... | Runs step2 (duplicated snps).
:param in_prefix: the prefix of the input files.
:param in_type: the type of the input files.
:param out_prefix: the output prefix.
:param base_dir: the output directory.
:param options: the options needed.
:type in_prefix: str
:type in_type: str
:type out... |
def get_corner(self, time):
"""
Gets the corner array indices of the STObject at a given time that corresponds
to the upper left corner of the bounding box for the STObject.
Args:
time: time at which the corner is being extracted.
Returns:
corner inde... | Gets the corner array indices of the STObject at a given time that corresponds
to the upper left corner of the bounding box for the STObject.
Args:
time: time at which the corner is being extracted.
Returns:
corner index. |
def order_assets(self, asset_ids, composition_id):
"""Reorders a set of assets in a composition.
arg: asset_ids (osid.id.Id[]): ``Ids`` for a set of
``Assets``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
raise: NotFound - ``comp... | Reorders a set of assets in a composition.
arg: asset_ids (osid.id.Id[]): ``Ids`` for a set of
``Assets``
arg: composition_id (osid.id.Id): ``Id`` of the
``Composition``
raise: NotFound - ``composition_id`` not found or, an
``asset_id`` not... |
def p_ioport_head(self, p):
'ioport_head : sigtypes portname'
p[0] = self.create_ioport(p[1], p[2], lineno=p.lineno(2))
p.set_lineno(0, p.lineno(1)) | ioport_head : sigtypes portname |
def lv_load_areas(self):
""" #TODO: description
"""
for lv_load_area in self._grid._graph.nodes():
if isinstance(lv_load_area, LVLoadAreaDing0):
if lv_load_area.ring == self:
yield lv_load_area | #TODO: description |
def _query(self, action, qobj):
"""
returns wikidata query string
"""
if action == 'labels':
return qobj.labels(self._pop_entities())
elif action == 'wikidata':
return qobj.wikidata(self.params.get('title'),
self.params.get... | returns wikidata query string |
def cmd_shodan_open(ip, no_cache, json_output, nmap_command, verbose, output):
"""Output the open ports for an IP against shodan (nmap format).
Example:
\b
$ habu.shodan.open 8.8.8.8
T:53,U:53
"""
habucfg = loadcfg()
if 'SHODAN_APIKEY' not in habucfg:
print('You must provide ... | Output the open ports for an IP against shodan (nmap format).
Example:
\b
$ habu.shodan.open 8.8.8.8
T:53,U:53 |
def to_potential(f):
'''
to_potential(f) yields f if f is a potential function; if f is not, but f can be converted to
a potential function, that conversion is performed then the result is yielded.
to_potential(Ellipsis) yields a potential function whose output is simply its input (i.e., the
ide... | to_potential(f) yields f if f is a potential function; if f is not, but f can be converted to
a potential function, that conversion is performed then the result is yielded.
to_potential(Ellipsis) yields a potential function whose output is simply its input (i.e., the
identity function).
to_potential... |
def _get_key_alias_from_cache(self, key_arn):
'''
Find a key's alias by looking up its key_arn in the KEY_METADATA
cache. This function will only work after a key has been lookedup by
its alias and is meant as a convenience function for turning an ARN
that's already been looked u... | Find a key's alias by looking up its key_arn in the KEY_METADATA
cache. This function will only work after a key has been lookedup by
its alias and is meant as a convenience function for turning an ARN
that's already been looked up back into its alias. |
def getSet(self, setID):
'''
Gets the information of one specific build using its Brickset set ID.
:param str setID: The ID of the build from Brickset.
:returns: A single Build object.
:rtype: :class:`brickfront.build.Build`
:raises brickfront.errors.InvalidSetID: If no ... | Gets the information of one specific build using its Brickset set ID.
:param str setID: The ID of the build from Brickset.
:returns: A single Build object.
:rtype: :class:`brickfront.build.Build`
:raises brickfront.errors.InvalidSetID: If no sets exist by that ID. |
def zipline_root(environ=None):
"""
Get the root directory for all zipline-managed files.
For testing purposes, this accepts a dictionary to interpret as the os
environment.
Parameters
----------
environ : dict, optional
A dict to interpret as the os environment.
Returns
-... | Get the root directory for all zipline-managed files.
For testing purposes, this accepts a dictionary to interpret as the os
environment.
Parameters
----------
environ : dict, optional
A dict to interpret as the os environment.
Returns
-------
root : string
Path to the... |
def generate(env):
"""Add Builders and construction variables for lib to an Environment."""
SCons.Tool.createStaticLibBuilder(env)
# Set-up ms tools paths
msvc_setup_env_once(env)
env['AR'] = 'lib'
env['ARFLAGS'] = SCons.Util.CLVar('/nologo')
env['ARCOM'] = "${TEMPFILE('... | Add Builders and construction variables for lib to an Environment. |
def get_organizers_events(self, id, **data):
"""
GET /organizers/:id/events/
Gets events of the :format:`organizer`.
"""
return self.get("/organizers/{0}/events/".format(id), data=data) | GET /organizers/:id/events/
Gets events of the :format:`organizer`. |
def getfilearchive(self, project_id, filepath=None):
"""
Get an archive of the repository
:param project_id: project id
:param filepath: path to save the file to
:return: True if the file was saved to the filepath
"""
if not filepath:
filepath = ''
... | Get an archive of the repository
:param project_id: project id
:param filepath: path to save the file to
:return: True if the file was saved to the filepath |
def players(game_id):
"""Gets player/coach/umpire information for the game with matching id."""
# get data
data = mlbgame.data.get_players(game_id)
# parse data
parsed = etree.parse(data)
root = parsed.getroot()
output = {}
output['game_id'] = game_id
# get player/coach data
fo... | Gets player/coach/umpire information for the game with matching id. |
def set_sim_data(inj, field, data):
"""Sets data of a SimInspiral instance."""
try:
sim_field = sim_inspiral_map[field]
except KeyError:
sim_field = field
# for tc, map to geocentric times
if sim_field == 'tc':
inj.geocent_end_time = int(data)
inj.geocent_end_time_ns ... | Sets data of a SimInspiral instance. |
def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs):
"""
Generate mass random date.
:param size: int, number of
:param start: date similar object, int / str / date / datetime
:param end: date similar object, int / str / date / datetime, default today's date
:par... | Generate mass random date.
:param size: int, number of
:param start: date similar object, int / str / date / datetime
:param end: date similar object, int / str / date / datetime, default today's date
:param kwargs: args placeholder
:return: list of datetime.date |
def app_score(self):
""" Computes the area under the app curve. """
# compute curve
precisions, pct_pred_pos, taus = self.precision_pct_pred_pos_curve(interval=False)
# compute area
app = 0
total = 0
for k in range(len(precisions)-1):
# read cur data
... | Computes the area under the app curve. |
def extractDate(text):
""" Tries to extract a date from a given :obj:`str`.
:param str text: Input date. A :obj:`datetime.date` object is passed
thought without modification.
:rtype: :obj:`datetime.date`"""
if type(text) is datetime.date:
return text
match = date_format... | Tries to extract a date from a given :obj:`str`.
:param str text: Input date. A :obj:`datetime.date` object is passed
thought without modification.
:rtype: :obj:`datetime.date` |
def GetMountPoint(self, path=None):
"""Walk back from the path to find the mount point.
Args:
path: a Unicode string containing the path or None. If path is None the
value in self.path is used.
Returns:
path string of the mount point
"""
path = os.path.abspath(
client_u... | Walk back from the path to find the mount point.
Args:
path: a Unicode string containing the path or None. If path is None the
value in self.path is used.
Returns:
path string of the mount point |
def set_unobserved_after(self,tlen,qlen,nt,p):
"""Set the unobservable sequence data after this base
:param tlen: target homopolymer length
:param qlen: query homopolymer length
:param nt: nucleotide
:param p: p is the probability of attributing this base to the unobserved error
:type tlen: int... | Set the unobservable sequence data after this base
:param tlen: target homopolymer length
:param qlen: query homopolymer length
:param nt: nucleotide
:param p: p is the probability of attributing this base to the unobserved error
:type tlen: int
:type qlen: int
:type nt: char
:type p: f... |
def from_xyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF):
"""Create a new instance based on the specifed CIE-XYZ values.
Parameters:
:x:
The Red component value [0...1]
:y:
The Green component value [0...1]
:z:
The Blue component value [0...1]
:alpha:
The col... | Create a new instance based on the specifed CIE-XYZ values.
Parameters:
:x:
The Red component value [0...1]
:y:
The Green component value [0...1]
:z:
The Blue component value [0...1]
:alpha:
The color transparency [0...1], default is opaque
:wref:
... |
def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
"""Error 307 -- relocated, but turn POST into error."""
if data is None:
return self.http_error_302(url, fp, errcode, errmsg, headers, data)
else:
return self.http_error_default(url, fp, errcode, errm... | Error 307 -- relocated, but turn POST into error. |
def install(self):
"""Install packages from the packages_dict."""
self.distro = distro_check()
package_list = self.packages_dict.get(self.distro)
self._installer(package_list=package_list.get('packages')) | Install packages from the packages_dict. |
def validate_items(self, item_list, item_type):
"""
Go through a list Pmag_objects and check for:
parent errors,
children errors,
type errors.
Return a dictionary of exceptions in this format:
{sample1: {'parent': [warning1, warning2, warning3], 'child': [warning1... | Go through a list Pmag_objects and check for:
parent errors,
children errors,
type errors.
Return a dictionary of exceptions in this format:
{sample1: {'parent': [warning1, warning2, warning3], 'child': [warning1, warning2]},
sample2: {'child': [warning1], 'type': [warni... |
def get_templates(path: Path) -> List[str]:
'''List all files in ``templates`` directory, including all subdirectories.
The resulting list contains UNIX-like relative paths starting with ``templates``.
'''
result = []
for item in path.glob('**/*'):
if item.is_file() and not item.name.star... | List all files in ``templates`` directory, including all subdirectories.
The resulting list contains UNIX-like relative paths starting with ``templates``. |
def p_information_duration_speed(self, p):
'information : duration AT speed'
logger.debug('information = duration %s at speed %s', p[1], p[3])
p[0] = p[3].for_duration(p[1]) | information : duration AT speed |
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
BDEFileEntry: file entry or None.
"""
path_spec = bde_path_spec.BDEPathSpec(parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec) | Retrieves the root file entry.
Returns:
BDEFileEntry: file entry or None. |
def disable_inside(item, *elems, **kwargs):
"""Prevent elems from matching inside of item.
Returns (item with elem disabled, *new versions of elems).
"""
_invert = kwargs.get("_invert", False)
internal_assert(set(kwargs.keys()) <= set(("_invert",)), "excess keyword arguments passed to disable_insid... | Prevent elems from matching inside of item.
Returns (item with elem disabled, *new versions of elems). |
def setup():
"""Walk the user though the Wallace setup."""
# Create the Wallace config file if it does not already exist.
config_name = ".wallaceconfig"
config_path = os.path.join(os.path.expanduser("~"), config_name)
if os.path.isfile(config_path):
log("Wallace config file already exists."... | Walk the user though the Wallace setup. |
def get_url(path, host, port, method="http"):
"""
make url from path, host and port
:param method: str
:param path: str, path within the request, e.g. "/api/version"
:param host: str
:param port: str or int
:return: str
"""
return urlunsplit(
(method, "%s:%s" % (host, port),... | make url from path, host and port
:param method: str
:param path: str, path within the request, e.g. "/api/version"
:param host: str
:param port: str or int
:return: str |
def get_process_pid(process_name):
""" check for process' pid file and returns pid from there """
try:
pid_filename = get_pid_filename(process_name)
with open(pid_filename, mode='r') as pid_file:
pid = int(pid_file.read().strip())
except IOError:
pid = None
return pid | check for process' pid file and returns pid from there |
def get_cfg(ast_func):
"""
Traverses the AST and returns the corresponding CFG
:param ast_func: The AST representation of function
:type ast_func: ast.Function
:returns: The CFG representation of the function
:rtype: cfg.Function
"""
cfg_func = cfg.Function()
for ast_var in ast_fun... | Traverses the AST and returns the corresponding CFG
:param ast_func: The AST representation of function
:type ast_func: ast.Function
:returns: The CFG representation of the function
:rtype: cfg.Function |
def _create_array(self, arr: np.ndarray) -> int:
"""Returns the handle of a RawArray created from the given numpy array.
Args:
arr: A numpy ndarray.
Returns:
The handle (int) of the array.
Raises:
ValueError: if arr is not a ndarray or of an unsupported d... | Returns the handle of a RawArray created from the given numpy array.
Args:
arr: A numpy ndarray.
Returns:
The handle (int) of the array.
Raises:
ValueError: if arr is not a ndarray or of an unsupported dtype. If
the array is of an unsupported type, us... |
def _u_distance_covariance_sqr_naive(x, y, exponent=1):
"""
Naive unbiased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm.
"""
a = _u_distance_matrix(x, exponent=exponent)
b = _u_distance_mat... | Naive unbiased estimator for distance covariance.
Computes the unbiased estimator for distance covariance between two
matrices, using an :math:`O(N^2)` algorithm. |
def liquid_jet_pump_ancillary(rhop, rhos, Kp, Ks, d_nozzle=None, d_mixing=None,
Qp=None, Qs=None, P1=None, P2=None):
r'''Calculates the remaining variable in a liquid jet pump when solving for
one if the inlet variables only and the rest of them are known. The
equation comes f... | r'''Calculates the remaining variable in a liquid jet pump when solving for
one if the inlet variables only and the rest of them are known. The
equation comes from conservation of energy and momentum in the mixing
chamber.
The variable to be solved for must be one of `d_nozzle`, `d_mixing`,
`Qp... |
def _validated(self, data):
"""Validate data if all subschemas validate it."""
for sub in self.schemas:
data = sub(data)
return data | Validate data if all subschemas validate it. |
async def pop(self, full):
'''
Remove and return the value for the given node.
'''
node = self.nodes.get(full)
if node is None:
return
valu = await self._popHiveNode(node)
return valu | Remove and return the value for the given node. |
def _operator_generator(self, index, conj):
"""
Internal method to generate the appropriate ladder operator at fermion
orbital at 'index'
If conj == -1 --> creation
conj == +1 --> annihilation
:param int index: fermion orbital to generate ladder operator at
:p... | Internal method to generate the appropriate ladder operator at fermion
orbital at 'index'
If conj == -1 --> creation
conj == +1 --> annihilation
:param int index: fermion orbital to generate ladder operator at
:param int conj: -1 for creation, +1 for annihilation |
def spectral(data, lambd, *kwargs):
""" Compute spectral contrast of image
Performs bandpass filtering in Fourier space according to optical
limit of detection system, approximated by twice the wavelength.
Parameters
----------
data : 2d ndarray
the image to compute the norm from
... | Compute spectral contrast of image
Performs bandpass filtering in Fourier space according to optical
limit of detection system, approximated by twice the wavelength.
Parameters
----------
data : 2d ndarray
the image to compute the norm from
lambd : float
wavelength of the ligh... |
def encode(cls, value):
"""
take a list and turn it into a utf-8 encoded byte-string for redis.
:param value: list
:return: bytes
"""
try:
coerced = list(value)
if coerced == value:
return json.dumps(coerced).encode(cls._encoding)
... | take a list and turn it into a utf-8 encoded byte-string for redis.
:param value: list
:return: bytes |
def _fake_modifyinstance(self, namespace, **params):
"""
Implements a server responder for
:meth:`~pywbem.WBEMConnection.CreateInstance`
Modify a CIM instance in the local repository.
Raises:
CIMError: CIM_ERR_ALREADY_EXISTS, CIM_ERR_INVALID_CLASS
"""
... | Implements a server responder for
:meth:`~pywbem.WBEMConnection.CreateInstance`
Modify a CIM instance in the local repository.
Raises:
CIMError: CIM_ERR_ALREADY_EXISTS, CIM_ERR_INVALID_CLASS |
def _get_part(pointlist, strokes):
"""Get some strokes of pointlist
Parameters
----------
pointlist : list of lists of dicts
strokes : list of integers
Returns
-------
list of lists of dicts
"""
result = []
strokes = sorted(strokes)
for stroke_index in strokes:
... | Get some strokes of pointlist
Parameters
----------
pointlist : list of lists of dicts
strokes : list of integers
Returns
-------
list of lists of dicts |
def quaternion_imag(quaternion):
"""Return imaginary part of quaternion.
>>> quaternion_imag([3, 0, 1, 2])
array([0., 1., 2.])
"""
return np.array(quaternion[1:4], dtype=np.float64, copy=True) | Return imaginary part of quaternion.
>>> quaternion_imag([3, 0, 1, 2])
array([0., 1., 2.]) |
def _retrieve_remote(fnames):
"""Retrieve remote inputs found in the same bucket as the template or metadata files.
"""
for fname in fnames:
if objectstore.is_remote(fname):
inputs = []
regions = []
remote_base = os.path.dirname(fname)
for rfname in ob... | Retrieve remote inputs found in the same bucket as the template or metadata files. |
def inv(self):
"""The inverse translation"""
result = Translation(-self.t)
result._cache_inv = self
return result | The inverse translation |
def fkg_allowing_type_hints(
namespace: Optional[str],
fn: Callable,
to_str: Callable[[Any], str] = repr) -> Callable[[Any], str]:
"""
Replacement for :func:`dogpile.cache.util.function_key_generator` that
handles type-hinted functions like
.. code-block:: python
def te... | Replacement for :func:`dogpile.cache.util.function_key_generator` that
handles type-hinted functions like
.. code-block:: python
def testfunc(param: str) -> str:
return param + "hello"
... at which :func:`inspect.getargspec` balks; plus
:func:`inspect.getargspec` is deprecated in ... |
def runner(self):
"""
Run the necessary methods in the correct order
"""
logging.info('Starting {} analysis pipeline'.format(self.analysistype))
# Initialise the GenObject
for sample in self.runmetadata.samples:
setattr(sample, self.analysistype, GenObject())
... | Run the necessary methods in the correct order |
def stop(self):
"""Mark the stop of the interval.
Calling stop on an already stopped interval has no effect.
An interval can only be stopped once.
:returns: the duration if the interval is truely stopped otherwise ``False``.
"""
if self._start_instant is None:
... | Mark the stop of the interval.
Calling stop on an already stopped interval has no effect.
An interval can only be stopped once.
:returns: the duration if the interval is truely stopped otherwise ``False``. |
def main(**kwargs):
"""
Draw a couple of simple graphs and optionally generate an HTML file to upload them
"""
draw_lines()
draw_histogram()
draw_bar_chart()
destination = "-r /report"
if use_html:
generate_html()
command = "dx-build-report-html {h} {d}".format(h=html_fil... | Draw a couple of simple graphs and optionally generate an HTML file to upload them |
def generate_net(df,tf_idf,dump_path=None):
'''Generate WordNetwork dict of Word() instance, and dump as a file if asked to.
@Args:
--
df : IDF value generated by find_tf_idf()
tf_idf : TF-IDF value generated by find_tf_idf()
dump_path : file_path where to dump network entities, stand... | Generate WordNetwork dict of Word() instance, and dump as a file if asked to.
@Args:
--
df : IDF value generated by find_tf_idf()
tf_idf : TF-IDF value generated by find_tf_idf()
dump_path : file_path where to dump network entities, standart format is '.wrnt' (default=None)
@returns:... |
def parse_rule(tokens, variables, neighbors, parents, is_merc):
""" Parse a rule set, return a list of declarations.
Requires a dictionary of declared variables. Selectors in the neighbors
list are simply grouped, and are generated from comma-delimited lists
of selectors in the styl... | Parse a rule set, return a list of declarations.
Requires a dictionary of declared variables. Selectors in the neighbors
list are simply grouped, and are generated from comma-delimited lists
of selectors in the stylesheet. Selectors in the parents list should
be combined with th... |
def _Tension(T):
"""Equation for the surface tension
Parameters
----------
T : float
Temperature, [K]
Returns
-------
σ : float
Surface tension, [N/m]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 248.15 ≤ T ≤ 647
*... | Equation for the surface tension
Parameters
----------
T : float
Temperature, [K]
Returns
-------
σ : float
Surface tension, [N/m]
Notes
------
Raise :class:`NotImplementedError` if input isn't in limit:
* 248.15 ≤ T ≤ 647
* Estrapolate to -25ºC in... |
def touch_tip(self, location=None, radius=1.0, v_offset=-1.0, speed=60.0):
"""
Touch the :any:`Pipette` tip to the sides of a well,
with the intent of removing left-over droplets
Notes
-----
If no `location` is passed, the pipette will touch_tip
from it's current... | Touch the :any:`Pipette` tip to the sides of a well,
with the intent of removing left-over droplets
Notes
-----
If no `location` is passed, the pipette will touch_tip
from it's current position.
Parameters
----------
location : :any:`Placeable` or tuple(... |
def run(self):
"""Run the App main logic.
This method should contain the core logic of the App.
"""
# read inputs
indent = int(self.tcex.playbook.read(self.args.indent))
json_data = self.tcex.playbook.read(self.args.json_data)
# get the playbook variable type
... | Run the App main logic.
This method should contain the core logic of the App. |
def create(self, filename, filedata):
"""Create a file from raw data"""
attributes = {'filename': filename,
'source': filedata}
return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data') | Create a file from raw data |
def get_assessment(self, assessment):
"""
To get Assessment by id
"""
response = self.http.get('/Assessment/' + str(assessment))
assessment = Schemas.Assessment(assessment=response)
return assessment | To get Assessment by id |
def parse_alarm(self, global_params, region, alarm):
"""
Parse a single CloudWatch trail
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param alarm: Alarm
"""
alarm['arn'... | Parse a single CloudWatch trail
:param global_params: Parameters shared for all regions
:param region: Name of the AWS region
:param alarm: Alarm |
def modify_target_group(TargetGroupArn=None, HealthCheckProtocol=None, HealthCheckPort=None, HealthCheckPath=None, HealthCheckIntervalSeconds=None, HealthCheckTimeoutSeconds=None, HealthyThresholdCount=None, UnhealthyThresholdCount=None, Matcher=None):
"""
Modifies the health checks used when evaluating the hea... | Modifies the health checks used when evaluating the health state of the targets in the specified target group.
To monitor the health of the targets, use DescribeTargetHealth .
See also: AWS API Documentation
Examples
This example changes the configuration of the health checks used to evaluate the ... |
def get_sampletype_data(self):
"""Returns a list of SampleType data
"""
for obj in self.get_sampletypes():
info = self.get_base_info(obj)
yield info | Returns a list of SampleType data |
def getCPUuse(self):
"""Return cpu time utilization in seconds.
@return: Dictionary of stats.
"""
hz = os.sysconf('SC_CLK_TCK')
info_dict = {}
try:
fp = open(cpustatFile, 'r')
line = fp.readline()
fp.close()
ex... | Return cpu time utilization in seconds.
@return: Dictionary of stats. |
def dict_partial_cmp(target_dict, dict_list, ducktype):
"""
Whether partial dict are in dict_list or not
"""
for called_dict in dict_list:
# ignore invalid test case
if len(target_dict) > len(called_dict):
continue
# get the intersection of two dicts
intersect... | Whether partial dict are in dict_list or not |
def hstack(tup):
"""
Horizontally stack a sequence of value bounds pairs.
Parameters
----------
tup: sequence
a sequence of value, ``Bound`` pairs
Returns
-------
value: ndarray
a horizontally concatenated array1d
bounds:
a list of Bounds
"""
vals, b... | Horizontally stack a sequence of value bounds pairs.
Parameters
----------
tup: sequence
a sequence of value, ``Bound`` pairs
Returns
-------
value: ndarray
a horizontally concatenated array1d
bounds:
a list of Bounds |
def show_xyzs(self, xs, ys, zs, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs):
"Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`."
title = 'Input / Prediction / Target'
axs = subplots(len(xs), 3, imgsize=imgsize, figsize=figsize, title=title, w... | Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`. |
def find_locales(self) -> Dict[str, gettext.GNUTranslations]:
"""
Load all compiled locales from path
:return: dict with locales
"""
translations = {}
for name in os.listdir(self.path):
if not os.path.isdir(os.path.join(self.path, name)):
con... | Load all compiled locales from path
:return: dict with locales |
def makedirs(directory):
""" Resursively create a named directory. """
parent = os.path.dirname(os.path.abspath(directory))
if not os.path.exists(parent):
makedirs(parent)
os.mkdir(directory) | Resursively create a named directory. |
def init_model_based_tags(self, model):
"""Initializing the model based memory and NIC information tags.
It should be called just after instantiating a RIBCL object.
ribcl = ribcl.RIBCLOperations(host, login, password, timeout,
port, cacert=cacert... | Initializing the model based memory and NIC information tags.
It should be called just after instantiating a RIBCL object.
ribcl = ribcl.RIBCLOperations(host, login, password, timeout,
port, cacert=cacert)
model = ribcl.get_product_name()
... |
def _replace_constant_methods(self):
"""Replaces conventional distribution methods by its constant counterparts."""
self.cumulative_distribution = self._constant_cumulative_distribution
self.percent_point = self._constant_percent_point
self.probability_density = self._constant_probabilit... | Replaces conventional distribution methods by its constant counterparts. |
async def deploy(
self, *, user_data: typing.Union[bytes, str] = None,
distro_series: str = None, hwe_kernel: str = None,
comment: str = None, wait: bool = False, wait_interval: int = 5):
"""Deploy this machine.
:param user_data: User-data to provide to the machine w... | Deploy this machine.
:param user_data: User-data to provide to the machine when booting. If
provided as a byte string, it will be base-64 encoded prior to
transmission. If provided as a Unicode string it will be assumed
to be already base-64 encoded.
:param distro_se... |
def view(self, **kwds):
"""
Endpoint: /action/<id>/view.json
Requests the full contents of the action.
Updates the action object's fields with the response.
"""
result = self._client.action.view(self, **kwds)
self._replace_fields(result.get_fields())
self... | Endpoint: /action/<id>/view.json
Requests the full contents of the action.
Updates the action object's fields with the response. |
def center(self, axis=1):
"""
Subtract the mean either within or across records.
Parameters
----------
axis : int, optional, default = 1
Which axis to center along, within (1) or across (0) records.
"""
if axis == 1:
return self.map(lambda... | Subtract the mean either within or across records.
Parameters
----------
axis : int, optional, default = 1
Which axis to center along, within (1) or across (0) records. |
def image(self):
"""An Image like array of ``self.data`` convenient for image processing tasks
* 2D array for single band, grayscale image data
* 3D array for three band, RGB image data
Enables working with ``self.data`` as if it were a PIL image.
See https://planetaryimage.re... | An Image like array of ``self.data`` convenient for image processing tasks
* 2D array for single band, grayscale image data
* 3D array for three band, RGB image data
Enables working with ``self.data`` as if it were a PIL image.
See https://planetaryimage.readthedocs.io/en/latest/usage... |
def createPolygon(self, points, strokewidth=1, stroke='black', fill='none'):
"""
Creates a Polygon
@type points: string in the form "x1,y1 x2,y2 x3,y3"
@param points: all points relevant to the polygon
@type strokewidth: string or int
@param strokewidth: width of the ... | Creates a Polygon
@type points: string in the form "x1,y1 x2,y2 x3,y3"
@param points: all points relevant to the polygon
@type strokewidth: string or int
@param strokewidth: width of the pen used to draw
@type stroke: string (either css constants like "black" or numerical va... |
def soldOutForRole(self,role,includeTemporaryRegs=False):
'''
Accepts a DanceRole object and responds if the number of registrations for that
role exceeds the capacity for that role at this event.
'''
return self.numRegisteredForRole(
role,includeTemporaryRegs=include... | Accepts a DanceRole object and responds if the number of registrations for that
role exceeds the capacity for that role at this event. |
def add_ring(self, ring):
"""Adds a ring to _rings if not already existing"""
if ring not in self._rings and isinstance(ring, RingDing0):
self._rings.append(ring) | Adds a ring to _rings if not already existing |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.