text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def build_napp_package(napp_name):
"""Build the .napp file to be sent to the napps server.
Args:
napp_identifier (str): Identifier formatted as
<username>/<napp_name>
Return:
file_payload (binary): The binary representation of the napp
pa... | 0.001595 |
def validate(self, expected_type, is_array, val):
"""
Validates that the expected type matches the value
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
... | 0.002286 |
def delete_processing_block(processing_block_id):
"""Delete Processing Block with the specified ID"""
scheduling_block_id = processing_block_id.split(':')[0]
config = get_scheduling_block(scheduling_block_id)
processing_blocks = config.get('processing_blocks')
processing_block = list(filter(
... | 0.001332 |
def _register_if_needed(cls, run_object):
"""Registers Trainable or Function at runtime.
Assumes already registered if run_object is a string. Does not
register lambdas because they could be part of variant generation.
Also, does not inspect interface of given run_object.
Argum... | 0.001483 |
def set_fft_params(func):
"""Decorate a method to automatically convert quantities to samples
"""
@wraps(func)
def wrapped_func(series, method_func, *args, **kwargs):
"""Wrap function to normalize FFT params before execution
"""
if isinstance(series, tuple):
data = se... | 0.001748 |
def error(self, i: int=None) -> str:
"""
Returns an error message
"""
head = "[" + colors.red("error") + "]"
if i is not None:
head = str(i) + " " + head
return head | 0.017778 |
def segments(self, index=None, params=None):
"""
The segments command is the detailed view of Lucene segments per index.
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-segments.html>`_
:arg index: A comma-separated list of index names to limit the returned
... | 0.00409 |
def _process_stocks(self, limit):
"""
Stock definitions.
Here we instantiate them as instances of the given taxon.
:param limit:
:return:
"""
if self.test_mode:
graph = self.testgraph
else:
graph = self.graph
model = Model... | 0.001998 |
def parse_data_port_mappings(mappings, default_bridge='br-data'):
"""Parse data port mappings.
Mappings must be a space-delimited list of bridge:port.
Returns dict of the form {port:bridge} where ports may be mac addresses or
interface names.
"""
# NOTE(dosaboy): we use rvalue for key to allo... | 0.000981 |
def fqwe(fEM, time, freq, qweargs):
r"""Fourier Transform using Quadrature-With-Extrapolation.
It follows the QWE methodology [Key12]_ for the Hankel transform, see
``hqwe`` for more information.
The function is called from one of the modelling routines in :mod:`model`.
Consult these modelling rou... | 0.000285 |
def find_element_by_jquery(step, browser, selector):
"""Find a single HTML element using jQuery-style selectors."""
elements = find_elements_by_jquery(browser, selector)
assert_true(step, len(elements) > 0)
return elements[0] | 0.004149 |
def check_readable(self, timeout):
"""
Poll ``self.stdout`` and return True if it is readable.
:param float timeout: seconds to wait I/O
:return: True if readable, else False
:rtype: boolean
"""
rlist, wlist, xlist = select.select([self._stdout], [], [], timeout)... | 0.005682 |
def find_melody(file='440_480_clean.wav', chunksize=512):
"""Cut the sample into chunks and analyze each chunk.
Return a list [(Note, chunks)] where chunks is the number of chunks
where that note is the most dominant.
If two consequent chunks turn out to return the same Note they are
grouped toget... | 0.001323 |
def diff(section):
"""
For each section defined in the local config file, look up for a folder inside the local config folder
named after the section. Uploads the environemnt file named as in the S3CONF variable for this section
to the remote S3CONF path.
"""
try:
settings = config.Setti... | 0.00436 |
def _make_read_lob_request(self, readoffset, readlength):
"""Make low level request to HANA database (READLOBREQUEST).
Compose request message with proper parameters and read lob data from second part object of reply.
"""
self._connection._check_closed()
request = RequestMessage... | 0.005459 |
def topics(text):
"""Return a list of topics."""
detectors = [
detector_50_Cent
]
ts = []
for detector in detectors:
ts.append(detector(text))
return [t[0] for t in ts if t[1] > 0.95] | 0.004464 |
def get_transitions_for(brain_or_object):
"""List available workflow transitions for all workflows
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: All possible available and allowed transitions
:rtype:... | 0.001499 |
def dim_iter(self, *dim_strides, **kwargs):
"""
Recursively iterate over the (dimension, stride)
tuples specified in dim_strides, returning a tuple
of dictionaries describing a dimension update.
For example, the following call effectively produces
2 loops over the 'ntime... | 0.005397 |
def save(self):
"""
Save current state of config dictionary.
"""
with open(self.config_file, "w") as f:
f.write(dump(self.config, default_flow_style=False)) | 0.014925 |
def copy_file(aws_access_key_id, aws_secret_access_key, bucket_name, file, s3_folder):
"""
copies file to bucket s3_folder
"""
# Connect to the bucket
bucket = s3_bucket(aws_access_key_id, aws_secret_access_key, bucket_name)
key = boto.s3.key.Key(bucket)
if s3_folder:
target_name... | 0.003333 |
def duplicate(self, new_parent=None):
"Create a new object exactly similar to self"
kwargs = {}
for spec_name, spec in self._meta.specs.items():
value = getattr(self, spec_name)
if isinstance(value, Color):
print "COLOR", value, value.default
... | 0.003529 |
def get_timeout(self):
"""
Checks if any timeout for the requests to DigitalOcean is required.
To set a timeout, use the REQUEST_TIMEOUT_ENV_VAR environment
variable.
"""
timeout_str = os.environ.get(REQUEST_TIMEOUT_ENV_VAR)
if timeout_str:
... | 0.006525 |
def get_turn_delta(self, branch=None, turn=None, tick_from=0, tick_to=None):
"""Get a dictionary describing changes made on a given turn.
If ``tick_to`` is not supplied, report all changes after ``tick_from``
(default 0).
The keys are graph names. Their values are dictionaries of the g... | 0.003277 |
def add_field(self, model, field):
"""Ran when a field is added to a model."""
super(SchemaEditor, self).add_field(model, field)
for mixin in self.post_processing_mixins:
mixin.add_field(model, field) | 0.008403 |
async def set_version(self, tp, params, version=None, elem=None):
"""
Stores version to the stream if not stored yet
:param tp:
:param params:
:param version:
:param elem:
:return:
"""
self.registry.set_tr(None)
tw = TypeWrapper(tp, params... | 0.002457 |
def _convert_service_properties_to_xml(logging, hour_metrics, minute_metrics,
cors, target_version=None, delete_retention_policy=None, static_website=None):
'''
<?xml version="1.0" encoding="utf-8"?>
<StorageServiceProperties>
<Logging>
<Version>ver... | 0.003953 |
def get_task_workers(self, task_name=None, json_obj=None):
"""
Get workers from task
:param task_name: task name
:param json_obj: json object parsed from get_task_detail2
:return: list of workers
.. seealso:: :class:`odps.models.Worker`
"""
if task_name i... | 0.004959 |
def FromJsonString(self, value):
"""Converts a string to Duration.
Args:
value: A string to be converted. The string must end with 's'. Any
fractional digits (or none) are accepted as long as they fit into
precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s
Raises:
... | 0.01032 |
def _transform_to_2d(t):
"""Convert vectors to column matrices, to always have a 2d shape."""
t = np.asarray(t)
dim = len(t.shape)
assert dim <= 2
if dim < 2:
t = np.atleast_2d(t).T
return t | 0.004444 |
def get_instrument_variables(ds):
'''
Returns a list of instrument variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
candidates = []
for variable in ds.variables:
instrument = getattr(ds.variables[variable], 'instrument', '')
if instrument and instrument in ds.var... | 0.00161 |
def transform(self, X):
"""Convert categorical columns to numeric values.
Parameters
----------
X : pandas.DataFrame
Data to encode.
Returns
-------
Xt : pandas.DataFrame
Encoded data.
"""
check_is_fitted(self, "encoded_co... | 0.00317 |
def get_unit_waveforms(recording, sorting, unit_ids=None, grouping_property=None, start_frame=None, end_frame=None,
ms_before=3., ms_after=3., dtype=None, max_num_waveforms=np.inf, filter=False,
bandpass=[300, 6000], save_as_features=True, verbose=False, compute_property_from_r... | 0.004933 |
def GetStructFormatString(self):
"""Retrieves the Python struct format string.
Returns:
str: format string as used by Python struct or None if format string
cannot be determined.
"""
if self._format_string is None and self._data_type_maps:
format_strings = []
for member_data... | 0.008633 |
def make_psd_xmldoc(psddict, xmldoc=None):
"""Add a set of PSDs to a LIGOLW XML document. If the document is not
given, a new one is created first.
"""
xmldoc = ligolw.Document() if xmldoc is None else xmldoc.childNodes[0]
# the PSDs must be children of a LIGO_LW with name "psd"
root_name = u"p... | 0.001198 |
def send(self, test=None):
'''
Send the email through the Postmark system.
Pass test=True to just print out the resulting
JSON message being sent to Postmark
'''
self._check_values()
# Set up message dictionary
json_message = self.to_json_message()
... | 0.003406 |
def postinit(self, target, annotation, simple, value=None):
"""Do some setup after initialisation.
:param target: What is being assigned to.
:type target: NodeNG
:param annotation: The type annotation of what is being assigned to.
:type: NodeNG
:param simple: Whether :... | 0.003125 |
def save(self):
'''saves our config objet to file'''
if self.app.cfg_mode == 'json':
with open(self.app.cfg_file, 'w') as opened_file:
json.dump(self.app.cfg, opened_file)
else:
with open(self.app.cfg_file, 'w')as opened_file:
yaml.dump(sel... | 0.005831 |
def exists(self, path, **kwargs):
"""Return true if the given path exists"""
try:
self.get_file_status(path, **kwargs)
return True
except HdfsFileNotFoundException:
return False | 0.008439 |
def is_linear(self):
"""
Tests whether all filters in the list are linear. CascadeFilter and
ParallelFilter instances are also linear if all filters they group are
linear.
"""
return all(isinstance(filt, LinearFilter) or
(hasattr(filt, "is_linear") and filt.is_linear())
... | 0.002833 |
def get_nested_attribute(obj, attribute):
"""
Returns the value of the given (possibly dotted) attribute for the given
object.
If any of the parents on the nested attribute's name path are `None`, the
value of the nested attribute is also assumed as `None`.
:raises AttributeError: If any attri... | 0.00339 |
def generate_hooked_command(cmd_name, cmd_cls, hooks):
"""
Returns a generated subclass of ``cmd_cls`` that runs the pre- and
post-command hooks for that command before and after the ``cmd_cls.run``
method.
"""
def run(self, orig_run=cmd_cls.run):
self.run_command_hooks('pre_hooks')
... | 0.00165 |
def direction_vector(self, other: "Point2") -> "Point2":
""" Converts a vector to a direction that can face vertically, horizontally or diagonal or be zero, e.g. (0, 0), (1, -1), (1, 0) """
return self.__class__((_sign(other.x - self.x), _sign(other.y - self.y))) | 0.014337 |
def identifierify(name):
""" Clean up name so it works for a Python identifier. """
name = name.lower()
name = re.sub('[^a-z0-9]', '_', name)
return name | 0.005917 |
def _tf_predict(model_dir, input_csvlines):
"""Prediction with a tf savedmodel.
Args:
model_dir: directory that contains a saved model
input_csvlines: list of csv strings
Returns:
Dict in the form tensor_name:prediction_list. Note that the value is always
a list, even if there was only 1 row... | 0.010265 |
def apply_security_groups(self, security_groups):
"""
Applies security groups to the load balancer.
Applying security groups that are already registered with the
Load Balancer has no effect.
:type security_groups: string or List of strings
:param security_groups: The na... | 0.005814 |
def run(self):
"""Load all artists into the database
"""
df = ArtistsInputData().load()
# rename columns
df.rename(columns={'artistLabel': 'name',
'genderLabel': 'gender'},
inplace=True)
# attribute columns that exist in the... | 0.00311 |
def netconf_session_start_source_host(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
netconf_session_start = ET.SubElement(config, "netconf-session-start", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-notifications")
source_host = ET.SubElement(netco... | 0.006048 |
def elapsed(self):
"""
Return a timedelta representation of the time passed sine the worker
was running.
"""
if not self.start_date:
return None
return (self.end_date or datetime.utcnow()) - self.start_date | 0.007519 |
def query_state(self, StateType):
"""
Is a button depressed?
True if a button is pressed, false otherwise.
"""
if StateType == M_LEFT:
# Checking left mouse button
return self.left_pressed
elif StateType == M_MIDDLE:
# Checking middle m... | 0.004124 |
def latents_to_frames(z_top_interp, level_eps_interp, hparams):
"""Decodes latents to frames."""
# Decode [z^1_t, z^2_t .. z^l_t] to [X_t]
images, _, _, _ = glow_ops.encoder_decoder(
"codec", z_top_interp, hparams, eps=level_eps_interp, reverse=True)
images = glow_ops.postprocess(images)
return images | 0.018868 |
def vector_product(v0, v1, axis=0):
"""Return vector perpendicular to vectors.
>>> v = vector_product([2, 0, 0], [0, 3, 0])
>>> np.allclose(v, [0, 0, 6])
True
>>> v0 = [[2, 0, 0, 2], [0, 2, 0, 2], [0, 0, 2, 2]]
>>> v1 = [[3], [0], [0]]
>>> v = vector_product(v0, v1)
>>> np.allclose(v, [... | 0.001515 |
def called_with(self, *args, **kwargs):
"""Return True if the spy was called with the specified args/kwargs.
Otherwise raise VerificationError.
"""
expected_call = Call(*args, **kwargs)
if expected_call in calls(self.spy):
return True
raise VerificationError... | 0.004505 |
def PSD_fitting_eqn_with_background(A, OmegaTrap, Gamma, FlatBackground, omega):
"""
The value of the fitting equation:
A / ((OmegaTrap**2 - omega**2)**2 + (omega * Gamma)**2) + FlatBackground
to be fit to the PSD
Parameters
----------
A : float
Fitting constant A
A = γ**2*Γ... | 0.005978 |
def __substituteFromClientStatement(self,match,prevResponse,extraSymbol="",sessionID = "general"):
"""
Substitute from Client statement into respose
"""
prev = 0
startPadding = 1+len(extraSymbol)
finalResponse = ""
for m in re.finditer(r'%'+extraSymbol+'[0-9]+', p... | 0.016595 |
def apply(cls, self, *args, **kwargs):
"""
Applies kwargs arguments to the instance passed as the first
argument to the call.
For defined INPUTS, OUTPUTS and PARAMETERS the method extracts
a corresponding value from kwargs and sets it as an instance attribute.
For exampl... | 0.013819 |
def gotoHome(self):
"""
Navigates to the home position for the edit.
"""
mode = QTextCursor.MoveAnchor
# select the home
if QApplication.instance().keyboardModifiers() == Qt.ShiftModifier:
mode = QTextCursor.KeepAnchor
curso... | 0.012771 |
def get_child_by_qualifier(self, parent_qualifier):
"""
:param parent_qualifier: time_qualifier of the parent process
:return: <HierarchyEntry> child entry to the HierarchyEntry associated with the parent_qualifier
or None if the given parent_qualifier is not registered in this h... | 0.00527 |
def norm(self, x):
"""Calculate the norm of an element.
This is the standard implementation using `inner`.
Subclasses should override it for optimization purposes.
Parameters
----------
x1 : `LinearSpaceElement`
Element whose norm is calculated.
Ret... | 0.00432 |
def _note_reply_pending(self, option, state):
"""Record the status of requested Telnet options."""
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
self.telnet_opt_dict[option].reply_pending = state | 0.01087 |
def lemmatize(self):
"""Lemmatize all Units in self.unit_list.
Modifies:
- self.unit_list: converts the .text property into its lemmatized form.
This method lemmatizes all inflected variants of permissible words to
those words' respective canonical forms. This is done to en... | 0.006772 |
def populate_freqs(self):
"""
Populate frequency axis
"""
if self.header[b'foff'] < 0:
f0 = self.f_end
else:
f0 = self.f_begin
self._setup_chans()
#create freq array
i_vals = np.arange(self.chan_start_idx, self.chan_stop_idx)
... | 0.007692 |
def index(self):
'''
Index funtion.
'''
self.render('ext_excel/index.html',
userinfo=self.userinfo,
cfg=CMS_CFG,
kwd={}, ) | 0.009259 |
def clean_tempdir(context, scenario):
"""
Clean up temporary test dirs for passed tests.
Leave failed test dirs for manual inspection.
"""
tempdir = getattr(context, 'tempdir', None)
if tempdir and scenario.status == 'passed':
shutil.rmtree(tempdir)
del(context.tempdir) | 0.003205 |
def Print(self, output_writer):
"""Prints a human readable version of the filter.
Args:
output_writer (CLIOutputWriter): output writer.
"""
if self._date_time_ranges:
for date_time_range in self._date_time_ranges:
if date_time_range.start_date_time is None:
end_time_string... | 0.009632 |
def set_min_leverage(self, min_leverage, grace_period):
"""Set a limit on the minimum leverage of the algorithm.
Parameters
----------
min_leverage : float
The minimum leverage for the algorithm.
grace_period : pd.Timedelta
The offset from the start date ... | 0.003759 |
def Defaults(self,key):
"""Returns default configurations for resources deployed to this group.
If specified key is not defined returns None.
# {"cpu":{"inherited":false},"memoryGB":{"inherited":false},"networkId":{"inherited":false},
# "primaryDns":{"value":"172.17.1.26","inherited":true},"secondaryDns":{"va... | 0.03096 |
def pix2sky_ellipse(self, pixel, sx, sy, theta):
"""
Convert an ellipse from pixel to sky coordinates.
Parameters
----------
pixel : (float, float)
The (x, y) coordinates of the center of the ellipse.
sx, sy : float
The major and minor axes (FHWM)... | 0.002375 |
def _install_indv_pkg(self, pkg_name, pkg_file):
'''
Install one individual package
'''
self.ui.status('... installing {0}'.format(pkg_name))
formula_tar = tarfile.open(pkg_file, 'r:bz2')
formula_ref = formula_tar.extractfile('{0}/FORMULA'.format(pkg_name))
formul... | 0.002335 |
def write_encoded(file_obj,
stuff,
encoding='utf-8'):
"""
If a file is open in binary mode and a string is passed, encode and write
If a file is open in text mode and bytes are passed, decode and write
Parameters
-----------
file_obj: file object, with 'wr... | 0.001149 |
def partition(pred, iterable, tolist=False):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = itertools.tee(iterable)
ifalse = six.moves.filterfalse(pred, t1)
itrue = six.moves.filter(pred, t2)
if to... | 0.002469 |
def stats(data):
'''Dictionary with summary stats for data
Returns:
dicitonary with length, mean, sum, standard deviation,\
min and max of data
'''
return {'len': len(data),
'mean': np.mean(data),
'sum': np.sum(data),
'std': np.std(data),
... | 0.002653 |
def setTypingStatus(self, status, thread_id=None, thread_type=None):
"""
Sets users typing status in a thread
:param status: Specify the typing status
:param thread_id: User/Group ID to change status in. See :ref:`intro_threads`
:param thread_type: See :ref:`intro_threads`
... | 0.004866 |
def adjust_commission_cost_basis(self, asset, cost):
"""
A note about cost-basis in zipline: all positions are considered
to share a cost basis, even if they were executed in different
transactions with different commission costs, different prices, etc.
Due to limitations about ... | 0.00123 |
def nl_cb_call(cb, type_, msg):
"""Call a callback function.
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink-private/netlink.h#L136
Positional arguments:
cb -- nl_cb class instance.
type_ -- callback type integer (e.g. NL_CB_MSG_OUT).
msg -- Netlink message (nl_msg class inst... | 0.001789 |
def set(self, item, column=None, value=None):
"""
Query or set the value of given item.
With one argument, return a dictionary of column/value pairs for the
specified item. With two arguments, return the current value of the
specified column. With three arguments, set the value ... | 0.004011 |
def run_script(self,
script,
in_shell=True,
echo=None,
note=None,
loglevel=logging.DEBUG):
"""Run the passed-in string as a script on the target's command line.
@param script: String representing the script. It will be de-indented
... | 0.028436 |
def start_logging(out=_stdout, level='info'):
"""
Begin logging.
:param out: if provided, a file-like object to log to. By default, this is
stdout.
:param level: the maximum log-level to emit (a string)
"""
global _log_level, _loggers, _started_logging
if level not in log_le... | 0.000763 |
def map_version(self, requirement, local_version):
"""
Maps a local version name to one recognised by the Requirement class
Parameters
----------
requirement : str
Name of the requirement
version : str
version string
"""
if isinsta... | 0.003515 |
def build_plugin(cls, class_name, config):
"""Create an instance of the named plugin and return it
:param class_name: fully qualified name of class
:type class_name: str
:param config: the supporting configuration for plugin
:type config: PluginConfig
:rtype: AbstractPl... | 0.006908 |
def __initialize_ui(self):
"""
Initializes the Widget ui.
"""
self.setAutoScroll(True)
self.setIndentation(self.__tree_view_indentation)
self.setRootIsDecorated(False)
self.setDragDropMode(QAbstractItemView.DragOnly)
self.header().hide()
self.se... | 0.00381 |
def bindargs(fun, *argsbind, **kwbind):
"""
_ = bind.placeholder # unbound placeholder (arg)
f = bind(fun, _, _, arg3, kw=kw1, kw2=kw2), f(arg1, arg2)
:param fun:
:param argsbind:
:param kwbind:
:return:
"""
assert argsbind
argsb = list(argsbind)
iargs = [i for i in range(... | 0.002427 |
def merge_data_and_coords(data, coords, compat='broadcast_equals',
join='outer'):
"""Used in Dataset.__init__."""
objs = [data, coords]
explicit_coords = coords.keys()
indexes = dict(extract_indexes(coords))
return merge_core(objs, compat, join, explicit_coords=explicit_coo... | 0.002755 |
def as_matrix(self, depth=0):
"""
Create a matrix with self as node, cache it, return it.
Args:
depth (int): depth of the matrix.
Returns:
Matrix: an instance of Matrix.
"""
if depth in self._matrix_cache:
return self._matrix_cache[de... | 0.004796 |
def convert_dropout(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert dropout.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with k... | 0.002628 |
def get_localhost():
'''
Should return 127.0.0.1 in ipv4 and ::1 in ipv6
localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work
properly and takes a lot of time (had this issue on the pyunit server).
Using the IP directly solves the problem.
... | 0.005537 |
def read(self, **keys):
"""
Read the image.
If the HDU is an IMAGE_HDU, read the corresponding image. Compression
and scaling are dealt with properly.
"""
if not self.has_data():
return None
dtype, shape = self._get_dtype_and_shape()
array =... | 0.004728 |
def setdocument(self, doc):
"""Associate a document with this element.
Arguments:
doc (:class:`Document`): A document
Each element must be associated with a FoLiA document.
"""
assert isinstance(doc, Document)
if not self.doc:
self.doc = doc
... | 0.009804 |
def GetFlagSuggestions(attempt, longopt_list):
"""Get helpful similar matches for an invalid flag."""
# Don't suggest on very short strings, or if no longopts are specified.
if len(attempt) <= 2 or not longopt_list:
return []
option_names = [v.split('=')[0] for v in longopt_list]
# Find close approximat... | 0.018952 |
def bitsToString(arr):
"""Returns a string representing a numpy array of 0's and 1's"""
s = array('c','.'*len(arr))
for i in xrange(len(arr)):
if arr[i] == 1:
s[i]='*'
return s | 0.041237 |
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'sof... | 0.001021 |
def fix_lockfile(self):
"""Run each line of outfile through fix_pin"""
with open(self.outfile, 'rt') as fp:
lines = [
self.fix_pin(line)
for line in self.concatenated(fp)
]
with open(self.outfile, 'wt') as fp:
fp.writelines([
... | 0.004651 |
def _make_routing_list(api_provider):
"""
Returns a list of routes to configure the Local API Service based on the APIs configured in the template.
Parameters
----------
api_provider : samcli.commands.local.lib.sam_api_provider.SamApiProvider
Returns
-------
... | 0.007102 |
def coarse_grain_transition_matrix(P, M):
""" Coarse grain transition matrix P using memberships M
Computes
.. math:
Pc = (M' M)^-1 M' P M
Parameters
----------
P : ndarray(n, n)
microstate transition matrix
M : ndarray(n, m)
membership matrix. Membership to macros... | 0.002472 |
def amplification_type(self, channels=None):
"""
Get the amplification type used for the specified channel(s).
Each channel uses one of two amplification types: linear or
logarithmic. This function returns, for each channel, a tuple of
two numbers, in which the first number indi... | 0.001057 |
def _checkTimeValue( timevalue, maxvalue ):
"""Check that the given timevalue is valid.
Args:
* timevalue (numerical): The time value to be checked. Must be positive.
* maxvalue (numerical): Upper limit for time value. Must be positive.
Raises:
TypeError, ValueError
... | 0.016729 |
def classical(vulnerability_function, hazard_imls, hazard_poes, loss_ratios):
"""
:param vulnerability_function:
an instance of
:py:class:`openquake.risklib.scientific.VulnerabilityFunction`
representing the vulnerability function used to compute the curve.
:param hazard_imls:
... | 0.000788 |
def index():
"""
This is not served anywhere in the web application.
It is used explicitly in the context of generating static files since
flask-frozen requires url_for's to crawl content.
url_for's are not used with host.show_host directly and are instead
dynamically generated through javascrip... | 0.001445 |
def _getPFilename(self,native,prompt):
"""Get p_filename field for this parameter
Same as get for non-list params
"""
return self.get(native=native,prompt=prompt) | 0.025641 |
def size(self):
"""Get the current terminal size."""
for fd in range(3):
cr = self._ioctl_GWINSZ(fd)
if cr:
break
if not cr:
try:
fd = os.open(os.ctermid(), os.O_RDONLY)
cr = self._ioctl_GWINSZ(fd)
... | 0.003724 |
def throws(self, exception=Exception):
"""
Customizes the stub function to raise an exception. If conditions like withArgs or onCall
were specified, then the return value will only be returned when the conditions are met.
Args: exception (by default=Exception, it could be any customized... | 0.008945 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.