code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def insert_check(self, index, check_item):
self.checks.insert(index, check_item)
for other in self.others:
other.insert_check(index, check_item) | Inserts a check universally. |
def attach(self, num_name, write=0):
mode = write and 'w' or 'r'
if isinstance(num_name, str):
num = self.find(num_name)
else:
num = num_name
vd = _C.VSattach(self._hdf_inst._id, num, mode)
if vd < 0:
_checkErr('attach', vd, 'cannot attach vdat... | Locate an existing vdata or create a new vdata in the HDF file,
returning a VD instance.
Args::
num_name Name or reference number of the vdata. An existing vdata
can be specified either through its reference number or
its name. Use -1 to create a new ... |
def get_posts(self) -> Iterator[Post]:
self._obtain_metadata()
yield from (Post(self._context, node, self) for node in
self._context.graphql_node_list("472f257a40c653c64c666ce877d59d2b",
{'id': self.userid},
... | Retrieve all posts from a profile. |
def release_references(self, keys):
keys = set(self.referenced_by) & set(keys)
for key in keys:
self.referenced_by.pop(key) | Non-recursively indicate that an iterable of _ReferenceKey no longer
exist. Unknown keys are ignored.
:param Iterable[_ReferenceKey] keys: The keys to drop. |
def _create_auth(team, timeout=None):
url = get_registry_url(team)
contents = _load_auth()
auth = contents.get(url)
if auth is not None:
if auth['expires_at'] < time.time() + 60:
try:
auth = _update_auth(team, auth['refresh_token'], timeout)
except Command... | Reads the credentials, updates the access token if necessary, and returns it. |
def save(self, *args, **kwargs):
from organizations.exceptions import OrganizationMismatch
if self.organization_user.organization.pk != self.organization.pk:
raise OrganizationMismatch
else:
super(AbstractBaseOrganizationOwner, self).save(*args, **kwargs) | Extends the default save method by verifying that the chosen
organization user is associated with the organization.
Method validates against the primary key of the organization because
when validating an inherited model it may be checking an instance of
`Organization` against an instanc... |
def load_module_from_name(dotted_name, path=None, use_sys=True):
return load_module_from_modpath(dotted_name.split("."), path, use_sys) | Load a Python module from its name.
:type dotted_name: str
:param dotted_name: python name of a module or package
:type path: list or None
:param path:
optional list of path where the module or package should be
searched (use sys.path if nothing or None is given)
:type use_sys: bool
... |
def cdate_range(start=None, end=None, periods=None, freq='C', tz=None,
normalize=True, name=None, closed=None, **kwargs):
warnings.warn("cdate_range is deprecated and will be removed in a future "
"version, instead use pd.bdate_range(..., freq='{freq}')"
.format(f... | Return a fixed frequency DatetimeIndex, with CustomBusinessDay as the
default frequency
.. deprecated:: 0.21.0
Parameters
----------
start : string or datetime-like, default None
Left bound for generating dates
end : string or datetime-like, default None
Right bound for generat... |
def get_ordered_children(self):
ordered_keys = self.element.ordered_children if self.element.ordered_children is not None else []
children = [self.indexes.get(k, None) for k in ordered_keys]
return children | Return the list of children ordered according to the element structure
:return: a list of :class:`Element <hl7apy.core.Element>` |
def _ExtractYandexSearchQuery(self, url):
if 'text=' not in url:
return None
_, _, line = url.partition('text=')
before_and, _, _ = line.partition('&')
if not before_and:
return None
yandex_search_url = before_and.split()[0]
return yandex_search_url.replace('+', ' ') | Extracts a search query from a Yandex search URL.
Yandex: https://www.yandex.com/search/?text=query
Args:
url (str): URL.
Returns:
str: search query or None if no query was found. |
def noise_new(
dim: int,
h: float = NOISE_DEFAULT_HURST,
l: float = NOISE_DEFAULT_LACUNARITY,
random: Optional[tcod.random.Random] = None,
) -> tcod.noise.Noise:
return tcod.noise.Noise(dim, hurst=h, lacunarity=l, seed=random) | Return a new Noise instance.
Args:
dim (int): Number of dimensions. From 1 to 4.
h (float): The hurst exponent. Should be in the 0.0-1.0 range.
l (float): The noise lacunarity.
random (Optional[Random]): A Random instance, or None.
Returns:
Noise: The new Noise instan... |
def appendSpacePadding(str, blocksize=AES_blocksize):
'Pad with spaces'
pad_len = paddingLength(len(str), blocksize)
padding = '\0'*pad_len
return str + padding | Pad with spaces |
def get_bin_admin_session(self):
if not self.supports_bin_admin():
raise errors.Unimplemented()
return sessions.BinAdminSession(runtime=self._runtime) | Gets the bin administrative session for creating, updating and deleteing bins.
return: (osid.resource.BinAdminSession) - a ``BinAdminSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_bin_admin()`` is ``false``
*compliance: optional -- This... |
def cmd(self, *args, **kwargs):
args = list(args)
if self.socket_name:
args.insert(0, '-L{0}'.format(self.socket_name))
if self.socket_path:
args.insert(0, '-S{0}'.format(self.socket_path))
if self.config_file:
args.insert(0, '-f{0}'.format(self.config... | Execute tmux command and return output.
Returns
-------
:class:`common.tmux_cmd`
Notes
-----
.. versionchanged:: 0.8
Renamed from ``.tmux`` to ``.cmd``. |
def to_text(self):
message = ''
last_was_text = False
for m in self.message:
if last_was_text and not isinstance(m, Text):
message += '\n'
message += m.to_text()
if isinstance(m, Text):
last_was_text = True
else:
... | Render a MessageElement queue as plain text.
:returns: Plain text representation of the message.
:rtype: str |
def _clear(self, wait):
i = 0
t1 = time.time()
for k in self.bucket.get_keys():
i += 1
self.bucket.get(k).delete()
print("\nDELETION TOOK: %s" % round(time.time() - t1, 2))
if wait:
while self._model_class.objects.count():
time.... | clear outs the all content of current bucket
only for development purposes |
def send_to_contact(self, obj_id, contact_id):
response = self._client.session.post(
'{url}/{id}/send/contact/{contact_id}'.format(
url=self.endpoint_url, id=obj_id, contact_id=contact_id
)
)
return self.process_response(response) | Send email to a specific contact
:param obj_id: int
:param contact_id: int
:return: dict|str |
def _get_representation_doc(self):
if not self.representation:
return 'N/A'
fields = {}
for name, field in self.representation.fields.items():
fields[name] = self._get_field_doc(field)
return fields | Return documentation for the representation of the resource. |
def root(self):
ret = self
while hasattr(ret, 'parent') and ret.parent:
ret = ret.parent
return ret if isinstance(ret, SchemaABC) else None | Reference to the `Schema` that this field belongs to even if it is buried in a `List`.
Return `None` for unbound fields. |
def get_event_list(config):
eventinstances = session_request(
config.session.post, device_event_url.format(
proto=config.web_proto, host=config.host, port=config.port),
auth=config.session.auth, headers=headers, data=request_xml)
raw_event_list = _prepare_event(eventinstances)
ev... | Get a dict of supported events from device. |
def next(self):
msg = cr.Message()
msg.type = cr.NEXT
self.send_message(msg) | Sends a "next" command to the player. |
def regularization(variables, regtype, regcoef, name="regularization"):
with tf.name_scope(name):
if regtype != 'none':
regs = tf.constant(0.0)
for v in variables:
if regtype == 'l2':
regs = tf.add(regs, tf.nn.l2_loss(v))
... | Compute the regularization tensor.
Parameters
----------
variables : list of tf.Variable
List of model variables.
regtype : str
Type of regularization. Can be ["none", "l1", "l2"]
regcoef : float,
Regularization coefficient.
name :... |
def base64_decodefile(instr, outfile):
r
encoded_f = StringIO(instr)
with salt.utils.files.fopen(outfile, 'wb') as f:
base64.decode(encoded_f, f)
return True | r'''
Decode a base64-encoded string and write the result to a file
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' hashutil.base64_decodefile instr='Z2V0IHNhbHRlZAo=' outfile='/path/to/binary_file' |
def biLSTM(f_lstm, b_lstm, inputs, batch_size=None, dropout_x=0., dropout_h=0.):
for f, b in zip(f_lstm, b_lstm):
inputs = nd.Dropout(inputs, dropout_x, axes=[0])
fo, fs = f.unroll(length=inputs.shape[0], inputs=inputs, layout='TNC', merge_outputs=True)
bo, bs = b.unroll(length=inputs.shape[... | Feature extraction through BiLSTM
Parameters
----------
f_lstm : VariationalDropoutCell
Forward cell
b_lstm : VariationalDropoutCell
Backward cell
inputs : NDArray
seq_len x batch_size
dropout_x : float
Variational dropout on inputs
dropout_h :
Not us... |
def run_all_evals(models, treebanks, out_file, check_parse, print_freq_tasks):
print_header = True
for tb_lang, treebank_list in treebanks.items():
print()
print("Language", tb_lang)
for text_path in treebank_list:
print(" Evaluating on", text_path)
gold_path = te... | Run an evaluation for each language with its specified models and treebanks |
def init_shell(self):
self.shell = PlayerTerminalInteractiveShell.instance(
commands=self.commands,
speed=self.speed,
parent=self,
display_banner=False,
profile_dir=self.profile_dir,
ipython_dir=self.ipython_dir,
user_ns=self.us... | initialize the InteractiveShell instance |
def set_evaluation_parameter(self, parameter_name, parameter_value):
if 'evaluation_parameters' not in self._expectations_config:
self._expectations_config['evaluation_parameters'] = {}
self._expectations_config['evaluation_parameters'].update(
{parameter_name: parameter_value}) | Provide a value to be stored in the data_asset evaluation_parameters object and used to evaluate
parameterized expectations.
Args:
parameter_name (string): The name of the kwarg to be replaced at evaluation time
parameter_value (any): The value to be used |
def buffer_read(self, frames=-1, dtype=None):
frames = self._check_frames(frames, fill_value=None)
ctype = self._check_dtype(dtype)
cdata = _ffi.new(ctype + '[]', frames * self.channels)
read_frames = self._cdata_io('read', cdata, ctype, frames)
assert read_frames == frames
... | Read from the file and return data as buffer object.
Reads the given number of `frames` in the given data format
starting at the current read/write position. This advances the
read/write position by the same number of frames.
By default, all frames from the current read/write position ... |
def notify_slaves(self):
if self.disable_slave_notify is not None:
LOGGER.debug('Slave notifications disabled')
return False
if self.zone_data()['kind'] == 'Master':
response_code = self._put('/zones/' + self.domain + '/notify').status_code
if response_cod... | Checks to see if slaves should be notified, and notifies them if needed |
def project_sequence(s, permutation=None):
xs, ys = unzip([project_point(p, permutation=permutation) for p in s])
return xs, ys | Projects a point or sequence of points using `project_point` to lists xs, ys
for plotting with Matplotlib.
Parameters
----------
s, Sequence-like
The sequence of points (3-tuples) to be projected.
Returns
-------
xs, ys: The sequence of projected points in coordinates as two lists |
def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats,
stat_dtype):
if self._fused:
batch_norm_op, mean, variance = self._fused_batch_norm_op(
input_batch,
self._moving_mean, self._moving_variance, use_batch_stats)
else:
batch_norm_op = tf.nn.... | Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Tensor of arbitrary dimension.
mean: A mean tensor, of the same dtype as `input_batch`.
variance: A var... |
def close(self):
if not self.__closed:
self.__closed = True
self.pool.return_socket(self.sock)
self.sock, self.pool = None, None | Return this instance's socket to the connection pool. |
def _parse_hostname(self):
value = 'localhost'
match = re.search(r'^hostname ([^\s]+)$', self.config, re.M)
if match:
value = match.group(1)
return dict(hostname=value) | Parses the global config and returns the hostname value
Returns:
dict: The configured value for hostname. The returned dict
object is intended to be merged into the resource dict |
def resolve_and_build(self):
pdebug("resolving and building task '%s'" % self.name,
groups=["build_task"])
indent_text(indent="++2")
toret = self.build(**self.resolve_dependencies())
indent_text(indent="--2")
return toret | resolves the dependencies of this build target and builds it |
def filter_metadata(self, key):
filtered = [field[key] for field in self.metadata if key in field]
if len(filtered) == 0:
raise KeyError("Key not found in metadata")
return filtered | Return a list of values for the metadata key from each field
of the project's metadata.
Parameters
----------
key: str
A known key in the metadata structure
Returns
-------
filtered :
attribute list from each field |
def pyobjc_method_signature(signature_str):
_objc_so.PyObjCMethodSignature_WithMetaData.restype = ctypes.py_object
return _objc_so.PyObjCMethodSignature_WithMetaData(ctypes.create_string_buffer(signature_str), None, False) | Return a PyObjCMethodSignature object for given signature string.
:param signature_str: A byte string containing the type encoding for the method signature
:return: A method signature object, assignable to attributes like __block_signature__
:rtype: <type objc._method_signature> |
def disconnect_session(session_id):
try:
win32ts.WTSDisconnectSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True)
except PyWinError as error:
_LOG.error('Error calling WTSDisconnectSession: %s', error)
return False
return True | Disconnect a session.
.. versionadded:: 2016.11.0
:param session_id: The numeric Id of the session.
:return: A boolean representing whether the disconnect succeeded.
CLI Example:
.. code-block:: bash
salt '*' rdp.disconnect_session session_id
salt '*' rdp.disconnect_session 99 |
def page(self, start_date=values.unset, end_date=values.unset,
identity=values.unset, tag=values.unset, page_token=values.unset,
page_number=values.unset, page_size=values.unset):
params = values.of({
'StartDate': serialize.iso8601_date(start_date),
'EndDate': s... | Retrieve a single page of BindingInstance records from the API.
Request is executed immediately
:param date start_date: Only include usage that has occurred on or after this date
:param date end_date: Only include usage that occurred on or before this date
:param unicode identity: The `... |
def without_extra_phrases(self):
name = re.sub(r'\s*\([^)]*\)?\s*$', '', self.name)
name = re.sub(r'(?i)\s* formerly.*$', '', name)
name = re.sub(r'(?i)\s*and its affiliates$', '', name)
name = re.sub(r'\bet al\b', '', name)
if "-" in name:
hyphen_parts = name.rsplit(... | Removes parenthethical and dashed phrases |
def from_swagger(cls, pclass_for_definition, name, definition):
return cls(
name=name,
doc=definition.get(u"description", name),
attributes=cls._attributes_for_definition(
pclass_for_definition,
definition,
),
) | Create a new ``_ClassModel`` from a single Swagger definition.
:param pclass_for_definition: A callable like
``Swagger.pclass_for_definition`` which can be used to resolve
type references encountered in the definition.
:param unicode name: The name of the definition.
:... |
def refresh_db(jail=None, chroot=None, root=None, force=False, **kwargs):
salt.utils.pkg.clear_rtag(__opts__)
cmd = _pkg(jail, chroot, root)
cmd.append('update')
if force:
cmd.append('-f')
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | Refresh PACKAGESITE contents
.. note::
This function can accessed using ``pkg.update`` in addition to
``pkg.refresh_db``, to more closely match the CLI usage of ``pkg(8)``.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
jail
Refresh the pkg database withi... |
def get_trace(self):
tblist = traceback.extract_tb(sys.exc_info()[2])
tblist = [item for item in tblist if ('pexpect/__init__' not in item[0])
and ('pexpect/expect' not in item[0])]
tblist = traceback.format_list(tblist)
return ''.join(tblist) | This returns an abbreviated stack trace with lines that only concern
the caller. In other words, the stack trace inside the Pexpect module
is not included. |
async def push_transaction_async(self):
await self.connect_async(loop=self.loop)
depth = self.transaction_depth_async()
if not depth:
conn = await self._async_conn.acquire()
self._task_data.set('conn', conn)
self._task_data.set('depth', depth + 1) | Increment async transaction depth. |
def pretty_flags(flags):
names = []
result = "0x%08x" % flags
for i in range(32):
flag = 1 << i
if flags & flag:
names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
flags ^= flag
if not flags:
break
else:
names.append(hex(fla... | Return pretty representation of code flags. |
def addSourceGroup(self, sourceGroupUri, weight):
assert isinstance(weight, (float, int)), "weight value has to be a positive or negative integer"
self.topicPage["sourceGroups"].append({"uri": sourceGroupUri, "wgt": weight}) | add a list of relevant sources by specifying a whole source group to the topic page
@param sourceGroupUri: uri of the source group to add
@param weight: importance of the provided list of sources (typically in range 1 - 50) |
def output_best_scores(self, best_epoch_str: str) -> None:
BEST_SCORES_FILENAME = "best_scores.txt"
with open(os.path.join(self.exp_dir, BEST_SCORES_FILENAME),
"w", encoding=ENCODING) as best_f:
print(best_epoch_str, file=best_f, flush=True) | Output best scores to the filesystem |
def read_envvar_file(name, extension):
envvar_file = environ.get('{}_config_file'.format(name).upper())
if envvar_file:
return loadf(envvar_file)
else:
return NotConfigured | Read values from a file provided as a environment variable
``NAME_CONFIG_FILE``.
:param name: environment variable prefix to look for (without the
``_CONFIG_FILE``)
:param extension: *(unused)*
:return: a `.Configuration`, possibly `.NotConfigured` |
def count_items(self):
soup_items = self.soup.findAll('item')
full_soup_items = self.full_soup.findAll('item')
return len(soup_items), len(full_soup_items) | Counts Items in full_soup and soup. For debugging |
def retry_unpaid_invoices(self):
self._sync_invoices()
for invoice in self.invoices.filter(paid=False, closed=False):
try:
invoice.retry()
except InvalidRequestError as exc:
if str(exc) != "Invoice is already paid":
raise | Attempt to retry collecting payment on the customer's unpaid invoices. |
def _safe_str_cmp(a, b):
if len(a) != len(b):
return False
rv = 0
for x, y in zip(a, b):
rv |= ord(x) ^ ord(y)
return rv == 0 | Internal function to efficiently iterate over the hashes
Regular string compare will bail at the earliest opportunity
which allows timing attacks |
def cause_repertoire(self, mechanism, purview):
return self.repertoire(Direction.CAUSE, mechanism, purview) | Return the cause repertoire. |
def get_context_data(self, **kwargs):
context = {'obj': self.object }
if 'queryset' in kwargs:
context['conf_msg'] = self.get_confirmation_message(kwargs['queryset'])
context.update(kwargs)
return context | Hook for adding arguments to the context. |
def _load_forms_and_lemmas(self):
rel_path = os.path.join(CLTK_DATA_DIR,
'old_english',
'model',
'old_english_models_cltk',
'data',
'oe.lemmas')
path... | Load the dictionary of lemmas and forms from the OE models repository. |
def sliding_tensor(mv_time_series, width, step, order='F'):
D = mv_time_series.shape[1]
data = [sliding_window(mv_time_series[:, j], width, step, order) for j in range(D)]
return np.stack(data, axis=2) | segments multivariate time series with sliding window
Parameters
----------
mv_time_series : array like shape [n_samples, n_variables]
multivariate time series or sequence
width : int > 0
segment width in samples
step : int > 0
stepsize for sliding in samples
Returns
... |
def do_asg(self,args):
parser = CommandArgumentParser("asg")
parser.add_argument(dest='asg',help='asg index or name');
args = vars(parser.parse_args(args))
print "loading auto scaling group {}".format(args['asg'])
try:
index = int(args['asg'])
asgSummary =... | Go to the specified auto scaling group. asg -h for detailed help |
def density_angle(rho0: Density, rho1: Density) -> bk.BKTensor:
return fubini_study_angle(rho0.vec, rho1.vec) | The Fubini-Study angle between density matrices |
def auth_view(name, **kwargs):
ctx = Context(**kwargs)
ctx.execute_action('auth:group:view', **{
'storage': ctx.repo.create_secure_service('storage'),
'name': name,
}) | Shows an authorization group's content. |
def transform_sparql_construct(rdf, construct_query):
logging.debug("performing SPARQL CONSTRUCT transformation")
if construct_query[0] == '@':
construct_query = file(construct_query[1:]).read()
logging.debug("CONSTRUCT query: %s", construct_query)
newgraph = Graph()
for triple in rdf.query(... | Perform a SPARQL CONSTRUCT query on the RDF data and return a new graph. |
def send_webhook(config, payload):
try:
response = requests.post(
config['webhook_url'],
data=json.dumps(payload, cls=ModelJSONEncoder),
headers={config['api_key_header_name']: config['api_key']},
)
except Exception as e:
logger.warning('Unable to send... | Sends a HTTP request to the configured server.
All exceptions are suppressed but emit a warning message in the log. |
def action(name, text, confirmation=None, icon=None, multiple=True, single=True):
def wrap(f):
f._action = (name, text, confirmation, icon, multiple, single)
return f
return wrap | Use this decorator to expose actions
:param name:
Action name
:param text:
Action text.
:param confirmation:
Confirmation text. If not provided, action will be executed
unconditionally.
:param icon:
Font Awesome icon name
... |
def direction_to_nearest_place(feature, parent):
_ = feature, parent
layer = exposure_summary_layer()
if not layer:
return None
index = layer.fields().lookupField(
direction_field['field_name'])
if index < 0:
return None
feature = next(layer.getFeatures())
return feat... | If the impact layer has a distance field, it will return the direction
to the nearest place.
e.g. direction_to_nearest_place() -> NW |
def dtw(x, y, dist=None):
x, y, dist = __prep_inputs(x, y, dist)
return __dtw(x, y, None, dist) | return the distance between 2 time series without approximation
Parameters
----------
x : array_like
input array 1
y : array_like
input array 2
dist : function or int
The method for calculating the distance between x[i] and y[j]. If
... |
def _flatten_list(x):
result = []
x = list(filter(None.__ne__, x))
for el in x:
x_is_iter = isinstance(x, collections.Iterable)
if x_is_iter and not isinstance(el, (str, tuple)):
result.extend(_flatten_list(el))
else:
result.append(el)
return result | Flatten an arbitrarily nested list into a new list.
This can be useful to select pandas DataFrame columns.
From https://stackoverflow.com/a/16176969/10581531
Examples
--------
>>> from pingouin.utils import _flatten_list
>>> x = ['X1', ['M1', 'M2'], 'Y1', ['Y2']]
>>> _flatten_list(x)
... |
def reliability_curves(self, prob_thresholds):
all_rel_curves = {}
for model_name in self.model_names:
all_rel_curves[model_name] = {}
for size_threshold in self.size_thresholds:
all_rel_curves[model_name][size_threshold] = {}
for h, hour_window in... | Output reliability curves for each machine learning model, size threshold, and time window.
:param prob_thresholds:
:param dilation_radius:
:return: |
def normalize_id(string):
if not isinstance(string, basestring):
fail("Type of argument must be string, found '{}'"
.format(type(string)))
normalizer = getUtility(IIDNormalizer).normalize
return normalizer(string) | Normalize the id
:param string: A string to normalize
:type string: str
:returns: Normalized ID
:rtype: str |
def _advance_params(self):
for p in ['x','y','direction']:
self.force_new_dynamic_value(p)
self.last_time = self.time_fn() | Explicitly generate new values for these parameters only
when appropriate. |
def create_river(self, river, river_name=None):
if isinstance(river, River):
body = river.serialize()
river_name = river.name
else:
body = river
return self._send_request('PUT', '/_river/%s/_meta' % river_name, body) | Create a river |
def tmdb_search_movies(
api_key, title, year=None, adult=False, region=None, page=1, cache=True
):
url = "https://api.themoviedb.org/3/search/movie"
try:
if year:
year = int(year)
except ValueError:
raise MapiProviderException("year must be numeric")
parameters = {
... | Search for movies using The Movie Database
Online docs: developers.themoviedb.org/3/search/search-movies |
def rollback(self, path, pretend=False):
self._notes = []
migrations = self._repository.get_last()
if not migrations:
self._note('<info>Nothing to rollback.</info>')
return len(migrations)
for migration in migrations:
self._run_down(path, migration, pr... | Rollback the last migration operation.
:param path: The path
:type path: str
:param pretend: Whether we execute the migrations as dry-run
:type pretend: bool
:rtype: int |
def verify_time(self, now):
return now.time() >= self.start_time and now.time() <= self.end_time | Verify the time |
def MultiOpenOrdered(self, urns, **kwargs):
precondition.AssertIterableType(urns, rdfvalue.RDFURN)
urn_filedescs = {}
for filedesc in self.MultiOpen(urns, **kwargs):
urn_filedescs[filedesc.urn] = filedesc
filedescs = []
for urn in urns:
try:
filedescs.append(urn_filedescs[urn])
... | Opens many URNs and returns handles in the same order.
`MultiOpen` can return file handles in arbitrary order. This makes it more
efficient and in most cases the order does not matter. However, there are
cases where order is important and this function should be used instead.
Args:
urns: A list ... |
def get_class_that_defined_method(meth):
if is_classmethod(meth):
return meth.__self__
if hasattr(meth, 'im_class'):
return meth.im_class
elif hasattr(meth, '__qualname__'):
try:
cls_names = meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0].split('.')
... | Determines the class owning the given method. |
def get_summary(self):
func_summaries = [f.get_summary() for f in self.functions]
modif_summaries = [f.get_summary() for f in self.modifiers]
return (self.name, [str(x) for x in self.inheritance], [str(x) for x in self.variables], func_summaries, modif_summaries) | Return the function summary
Returns:
(str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries) |
def toggle_standby(self, **kwargs):
trafficgroup = kwargs.pop('trafficgroup')
state = kwargs.pop('state')
if kwargs:
raise TypeError('Unexpected **kwargs: %r' % kwargs)
arguments = {'standby': state, 'traffic-group': trafficgroup}
return self.exec_cmd('run', **argumen... | Toggle the standby status of a traffic group.
WARNING: This method which used POST obtains json keys from the device
that are not available in the response to a GET against the same URI.
NOTE: This method method is deprecated and probably will be removed,
usage of exec_cmd is... |
def _per_file_event_handler(self):
file_event_handler = PatternMatchingEventHandler()
file_event_handler.on_created = self._on_file_created
file_event_handler.on_modified = self._on_file_modified
file_event_handler.on_moved = self._on_file_moved
file_event_handler._patterns = [
... | Create a Watchdog file event handler that does different things for every file |
def set_status(self, trial, status):
trial.status = status
if status in [Trial.TERMINATED, Trial.ERROR]:
self.try_checkpoint_metadata(trial) | Sets status and checkpoints metadata if needed.
Only checkpoints metadata if trial status is a terminal condition.
PENDING, PAUSED, and RUNNING switches have checkpoints taken care of
in the TrialRunner.
Args:
trial (Trial): Trial to checkpoint.
status (Trial.st... |
def get_relations(self, database, schema):
schema = _lower(schema)
with self.lock:
results = [
r.inner for r in self.relations.values()
if (r.schema == _lower(schema) and
r.database == _lower(database))
]
if None in resu... | Case-insensitively yield all relations matching the given schema.
:param str schema: The case-insensitive schema name to list from.
:return List[BaseRelation]: The list of relations with the given
schema |
def get_snapshot(nexus_url, repository, group_id, artifact_id, packaging, version, snapshot_version=None, target_dir='/tmp', target_file=None, classifier=None, username=None, password=None):
log.debug('======================== MODULE FUNCTION: nexus.get_snapshot(nexus_url=%s, repository=%s, group_id=%s, artifact_id... | Gets snapshot of the desired version of the artifact
nexus_url
URL of nexus instance
repository
Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots
group_id
Group Id of the artifact
artifact_id
Artifact Id of the ar... |
def delete_additional_charge(self, recurring_billing_id):
fmt = 'recurringBillItems/{}'.format(recurring_billing_id)
return self.client._delete(self.url + fmt, headers=self.get_headers()) | Remove an extra charge from an invoice.
Args:
recurring_billing_id: Identifier of the additional charge.
Returns: |
def has_next(self):
if self._result_cache:
return self._result_cache.has_next
return self.all().has_next | Return True if there are more values present |
def _get_schema(cls, schema):
if isinstance(schema, string_types):
schema = cls._get_object_from_python_path(schema)
if isclass(schema):
schema = schema()
if not isinstance(schema, Schema):
raise TypeError("The schema must be a path to a Marshmallow "
... | Method that will fetch a Marshmallow schema flexibly.
Args:
schema (marshmallow.Schema|str): Either the schema class, an
instance of a schema, or a Python path to a schema.
Returns:
marshmallow.Schema: The desired schema.
Raises:
TypeError: ... |
def get_cls_for_collection(self, collection):
for cls, params in self.classes.items():
if params['collection'] == collection:
return cls
raise AttributeError("Unknown collection: %s" % collection) | Return the class for a given collection name.
:param collection: The name of the collection for which to return the class.
:returns: A reference to the class for the given collection name. |
def get_contract_data(self, contract_name):
contract_data_path = self.output_dir + '/{0}.json'.format(contract_name)
with open(contract_data_path, 'r') as contract_data_file:
contract_data = json.load(contract_data_file)
abi = contract_data['abi']
bytecode = contract_data['ev... | Returns the contract data for a given contract
Args:
contract_name (str): Name of the contract to return.
Returns:
str, str: ABI and bytecode of the contract |
def is_proxy(elt):
if ismethod(elt):
elt = get_method_function(elt)
result = hasattr(elt, __PROXIFIED__)
return result | Return True if elt is a proxy.
:param elt: elt to check such as a proxy.
:return: True iif elt is a proxy.
:rtype: bool |
def delete_attachment(request, link_field=None, uri=None):
if link_field is None:
link_field = "record_uri"
if uri is None:
uri = record_uri(request)
filters = [Filter(link_field, uri, core_utils.COMPARISON.EQ)]
storage = request.registry.storage
file_links, _ = storage.get_all("", F... | Delete existing file and link. |
def Arrow(start=(0.,0.,0.), direction=(1.,0.,0.), tip_length=0.25,
tip_radius=0.1, shaft_radius=0.05, shaft_resolution=20):
arrow = vtk.vtkArrowSource()
arrow.SetTipLength(tip_length)
arrow.SetTipRadius(tip_radius)
arrow.SetShaftRadius(shaft_radius)
arrow.SetShaftResolution(shaft_resolutio... | Create a vtk Arrow
Parameters
----------
start : np.ndarray
Start location in [x, y, z]
direction : list or np.ndarray
Direction the arrow points to in [x, y, z]
tip_length : float, optional
Length of the tip.
tip_radius : float, optional
Radius of the tip.
... |
def profile(self, frame, event, arg):
if (self.events == None) or (event in self.events):
frame_info = inspect.getframeinfo(frame)
cp = (frame_info[0], frame_info[2], frame_info[1])
if self.codepoint_included(cp):
objects = muppy.get_objects()
... | Profiling method used to profile matching codepoints and events. |
def plot_samples(self,prop,fig=None,label=True,
histtype='step',bins=50,lw=3,
**kwargs):
setfig(fig)
samples,stats = self.prop_samples(prop)
fig = plt.hist(samples,bins=bins,normed=True,
histtype=histtype,lw=lw,**kwargs)
plt.xlab... | Plots histogram of samples of desired property.
:param prop:
Desired property (must be legit column of samples)
:param fig:
Argument for :func:`plotutils.setfig` (``None`` or int).
:param histtype, bins, lw:
Passed to :func:`plt.hist`.
... |
def is_json(value,
schema = None,
json_serializer = None,
**kwargs):
try:
value = validators.json(value,
schema = schema,
json_serializer = json_serializer,
**kwargs)
excep... | Indicate whether ``value`` is a valid JSON object.
.. note::
``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the
meta-schema using a ``$schema`` property, the schema will be assumed to conform to
Draft 7.
:param value: The value to evaluate.
:param schema... |
def list_by_instance(self, instance_id):
ports = port_list(self.request, device_id=instance_id)
sg_ids = []
for p in ports:
sg_ids += p.security_groups
return self._list(id=set(sg_ids)) if sg_ids else [] | Gets security groups of an instance.
:returns: List of SecurityGroup objects associated with the instance |
def _read_config_file(self):
try:
with open(self.config, 'r') as f:
config_data = json.load(f)
except FileNotFoundError:
config_data = {}
return config_data | read in the configuration file, a json file defined at self.config |
def setup_model(x, y, model_type='random_forest', seed=None, **kwargs):
assert len(x) > 1 and len(y) > 1, 'Not enough data objects to train on (minimum is at least two, you have (x: {0}) and (y: {1}))'.format(len(x), len(y))
sets = namedtuple('Datasets', ['train', 'test'])
x_train, x_test, y_train, y_test =... | Initializes a machine learning model
Args:
x: Pandas DataFrame, X axis of features
y: Pandas Series, Y axis of targets
model_type: Machine Learning model to use
Valid values: 'random_forest'
seed: Random state to use when splitting sets and creating the model
**k... |
def _JRAxiIntegrand(r,E,L,pot):
return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.) | The J_R integrand |
def message_from_file(fp, *args, **kws):
from future.backports.email.parser import Parser
return Parser(*args, **kws).parse(fp) | Read a file and parse its contents into a Message object model.
Optional _class and strict are passed to the Parser constructor. |
def set_console(stream=STDOUT, foreground=None, background=None, style=None):
if foreground is None:
foreground = _default_foreground
if background is None:
background = _default_background
if style is None:
style = _default_style
attrs = get_attrs(foreground, background, style)
... | Set console foreground and background attributes. |
def credentials_match(self, user_detail, key):
if user_detail:
creds = user_detail.get('auth')
try:
auth_encoder, creds_dict = \
swauth.authtypes.validate_creds(creds)
except ValueError as e:
self.logger.error('%s' % e.args[... | Returns True if the key is valid for the user_detail.
It will use auth_encoder type the password was encoded with,
to check for a key match.
:param user_detail: The dict for the user.
:param key: The key to validate for the user.
:returns: True if the key is valid for the user, ... |
def strip_el_text(el, max_depth=0, cur_depth=0):
el_text = strip_str(el.text if el.text is not None else "")
if cur_depth < max_depth:
for child in el:
el_text += " "+strip_el_text(child, max_depth=max_depth, cur_depth=cur_depth+1)
else:
children = list(el)
if children is... | Recursively strips the plain text out of the given XML etree element up to the desired depth.
Args:
el: The etree element to scan.
max_depth: The depth to which to recursively strip text (default: 0).
cur_depth: The current recursive depth to which we've scanned so far.
Returns:
... |
def _collect_derived_entries(state, traces, identifiers):
identifiers = set(identifiers)
if not identifiers:
return {}
entries = {}
extras = {}
for identifier, requirement in state.mapping.items():
routes = {trace[1] for trace in traces[identifier] if len(trace) > 1}
if ident... | Produce a mapping containing all candidates derived from `identifiers`.
`identifiers` should provide a collection of requirement identifications
from a section (i.e. `packages` or `dev-packages`). This function uses
`trace` to filter out candidates in the state that are present because of
an entry in t... |
def send_example(self,
*args,
**kwargs
):
parse_result = kwargs.pop('parse_result', True)
line = self.make_line(*args, **kwargs)
result = self.send_line(line, parse_result=parse_result)
return result | Send a labeled or unlabeled example to the VW instance.
If 'parse_result' kwarg is False, ignore the result and return None.
All other parameters are passed to self.send_line().
Returns a VWResult object. |
def strp_isoformat(strg):
if isinstance(strg, datetime):
return strg
if len(strg) < 19 or len(strg) > 26:
if len(strg) > 30:
strg = strg[:30] + '...'
raise ValueError("Invalid ISO formatted time string '%s'"%strg)
if strg.find(".") == -1:
strg += '.000000'
if ... | Decode an ISO formatted string to a datetime object.
Allow a time-string without microseconds.
We handle input like: 2011-11-14T12:51:25.123456 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.