Unnamed: 0 int64 0 389k | code stringlengths 26 79.6k | docstring stringlengths 1 46.9k |
|---|---|---|
361,400 | def get(self, sid):
return CallContext(self._version, account_sid=self._solution[], sid=sid, ) | Constructs a CallContext
:param sid: The unique string that identifies this resource
:returns: twilio.rest.api.v2010.account.call.CallContext
:rtype: twilio.rest.api.v2010.account.call.CallContext |
361,401 | def get_public_dsn(self, scheme=None):
if self.is_enabled():
url = self.remote.get_public_dsn()
if scheme:
return % (scheme, url)
return url | Returns a public DSN which is consumable by raven-js
>>> # Return scheme-less DSN
>>> print client.get_public_dsn()
>>> # Specify a scheme to use (http or https)
>>> print client.get_public_dsn('https') |
361,402 | def triangle_area(p0, p1, p2):
if p2.ndim < 2:
p2 = p2[np.newaxis, :]
area = 0.5 * np.abs(p0[0] * p1[1] - p0[0] * p2[:,1] +
p1[0] * p2[:,1] - p1[0] * p0[1] +
p2[:,0] * p0[1] - p2[:,0] * p1[1])
return area | p2 can be a vector |
361,403 | def read_data(self, offsets):
newoffset = None
if not self.local_path.use_stdin:
if offsets.num_bytes == 0:
return None, None
start = self.local_path.view.fd_start + offsets.range_start
with self... | Read data from file
:param Descriptor self: this
:param Offsets offsets: offsets
:rtype: tuple
:return: (file data bytes, new Offsets if stdin) |
361,404 | def create_pgroup_snapshot(self, source, **kwargs):
result = self.create_pgroup_snapshots([source], **kwargs)
if self._rest_version >= LooseVersion("1.4"):
headers = result.headers
result = ResponseDict(result[0])
result.he... | Create snapshot of pgroup from specified source.
:param source: Name of pgroup of which to take snapshot.
:type source: str
:param \*\*kwargs: See the REST API Guide on your array for the
documentation on the request:
**POST pgroup**
... |
361,405 | def email(self, email):
if email == self.email:
return
email = email.lower()
if self._email is None:
self._email = email
self.require_email_confirmation()
else:
self.email_new = email
self.require_email_confirmation() | Set email and generate confirmation |
361,406 | def has_edge_citation(self, u: BaseEntity, v: BaseEntity, key: str) -> bool:
return self._has_edge_attr(u, v, key, CITATION) | Check if the given edge has a citation. |
361,407 | def links(self):
dlinks = {}
for key, value in self.__dict__.items():
if isinstance(value, dict) and value[]:
dlinks[key] = value[]
return dlinks | returns {attr1: href, attr2: href2} |
361,408 | def impute(self, M_c, X_L, X_D, Y, Q, seed, n):
get_next_seed = make_get_next_seed(seed)
e = su.impute(M_c, X_L, X_D, Y, Q, n, get_next_seed)
return e | Impute values from predictive distribution of the given latent state.
:param Y: A list of constraints to apply when sampling. Each constraint
is a triplet of (r,d,v): r is the row index, d is the column
index and v is the value of the constraint
:type Y: list of lists
:... |
361,409 | def remove(self, vehID, reason=tc.REMOVE_VAPORIZED):
self._connection._sendByteCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.REMOVE, vehID, reason) | Remove vehicle with the given ID for the give reason.
Reasons are defined in module constants and start with REMOVE_ |
361,410 | def surface_deriv(self, param):
squeeze_out = (np.shape(param) == ())
param = np.array(param, dtype=float, copy=False, ndmin=1)
if self.check_bounds and not is_inside_bounds(param, self.params):
raise ValueError(
.format(param, self.params))
... | Return the surface derivative at ``param``.
This is a constant function evaluating to `axis` everywhere.
Parameters
----------
param : float or `array-like`
Parameter value(s) at which to evaluate.
Returns
-------
deriv : `numpy.ndarray`
... |
361,411 | def transform_multidim_to_1d_ref(aref, dimension_dict):
dims = []
name = aref
while type(name) is c_ast.ArrayRef:
dims.append(name.subscript)
name = name.name
subscript_list = []
for i, d in enumerate(dims):
if i == 0:
subscript_list.append(d)
else:
... | Transform ast of multidimensional reference to a single dimension reference.
In-place operation! |
361,412 | def btc_make_p2sh_address( script_hex ):
h = hashing.bin_hash160(binascii.unhexlify(script_hex))
addr = bin_hash160_to_address(h, version_byte=multisig_version_byte)
return addr | Make a P2SH address from a hex script |
361,413 | def mel(sr, n_dft, n_mels=128, fmin=0.0, fmax=None, htk=False, norm=1):
return librosa.filters.mel(sr=sr, n_fft=n_dft, n_mels=n_mels,
fmin=fmin, fmax=fmax,
htk=htk, norm=norm).astype(K.floatx()) | [np] create a filterbank matrix to combine stft bins into mel-frequency bins
use Slaney (said Librosa)
n_mels: numbre of mel bands
fmin : lowest frequency [Hz]
fmax : highest frequency [Hz]
If `None`, use `sr / 2.0` |
361,414 | def load(obj, env=None, silent=None, key=None):
client = get_client(obj)
env_list = _get_env_list(obj, env)
for env in env_list:
path = "/".join([obj.VAULT_PATH_FOR_DYNACONF, env]).replace("//", "/")
data = client.read(path)
if data:
data =... | Reads and loads in to "settings" a single key or all keys from vault
:param obj: the settings instance
:param env: settings env default='DYNACONF'
:param silent: if errors should raise
:param key: if defined load a single key, else load all in env
:return: None |
361,415 | def to_offset(freq):
if freq is None:
return None
if isinstance(freq, DateOffset):
return freq
if isinstance(freq, tuple):
name = freq[0]
stride = freq[1]
if isinstance(stride, str):
name, stride = stride, name
name, _ = libfreqs._base_and_s... | Return DateOffset object from string or tuple representation
or datetime.timedelta object
Parameters
----------
freq : str, tuple, datetime.timedelta, DateOffset or None
Returns
-------
DateOffset
None if freq is None.
Raises
------
ValueError
If freq is an inv... |
361,416 | def items(self, match="*", count=1000):
for field, value in self._client.hscan_iter(
self.key_prefix, match=match, count=count):
yield self._decode(field), self._loads(value) | :see::meth:RedisMap.items |
361,417 | def execute(self, env, args):
task_name = args.task_name
force = args.force
if env.task.active and env.task.name == task_name:
raise errors.ActiveTask
if not env.task.exists(task_name):
raise errors.TaskNotFound(task_name)
if force:
... | Removes a task.
`env`
Runtime ``Environment`` instance.
`args`
Arguments object from arg parser. |
361,418 | def _reset_lazymodule(module, cls_attrs):
modclass = type(module)
del modclass.__getattribute__
del modclass.__setattr__
try:
del modclass._LOADING
except AttributeError:
pass
for cls_attr in _CLS_ATTRS:
try:
setattr(modclass, cls_attr, cls_attrs[cls_attr... | Resets a module's lazy state from cached data. |
361,419 | def repeat(coro, times=1, step=1, limit=1, loop=None):
assert_corofunction(coro=coro)
times = max(int(times), 1)
iterable = range(1, times + 1, step)
return (yield from map(coro, iterable, limit=limit, loop=loop)) | Executes the coroutine function ``x`` number of times,
and accumulates results in order as you would use with ``map``.
Execution concurrency is configurable using ``limit`` param.
This function is a coroutine.
Arguments:
coro (coroutinefunction): coroutine function to schedule.
times... |
361,420 | def create_figure(width=20, height=10):
figure = plt.figure(figsize=(width, height))
axis = figure.add_subplot(1, 1, 1)
return figure, axis | Create a figure instance.
:params width: figure width
:params height: figure height |
361,421 | def extract(self, table: dict) -> List[Extraction]:
if table[][] != 2 and table[][] < 2:
return []
results = list()
for row in table[]:
if len(row[]) != 2:
continue
text = [row[][0][], row[][1][]]
for field_name in self.glo... | :param table: a table extracted by table extractor, as a json object
:return: list of all extractions from the input table |
361,422 | def extra_hosts(self, value):
if value is None:
self._extra_hosts = value
elif isinstance(value, list):
self._extra_hosts = value
elif isinstance(value, dict):
converted_extra_hosts = []
for k, v in sorted(six.iteritems(value)... | :param value:
:return None: |
361,423 | def seedRandom(self, seed):
low_seed = ckbytelist(seed)
rv = self.lib.C_SeedRandom(self.session, low_seed)
if rv != CKR_OK:
raise PyKCS11Error(rv) | C_SeedRandom
:param seed: seed material
:type seed: iterable |
361,424 | def check_dataset_format(ds_format):
if ds_format.lower() not in DATASET_FORMATS.keys():
raise ValueError(
"dataset_format is expected to be one of %s. is not valid"
% (", ".join(DATASET_FORMATS.keys()), ds_format)
) | Ensure dataset format is XML or CSV
:param str ds_format: Format of the Dataset (expected to be one of `csv` or `xml`) |
361,425 | def get(self, item):
if item in self:
item = getattr(self, item)
return item() | Helper method to avoid calling getattr |
361,426 | def _add(self):
is_valid_form = True
get_filter_args(self._filters)
exclude_cols = self._filters.get_relation_cols()
form = self.add_form.refresh()
if request.method == "POST":
self._fill_form_exclude_cols(exclude_cols, form)
if form.validate():
... | Add function logic, override to implement different logic
returns add widget or None |
361,427 | def did_parse(did):
if not isinstance(did, str):
raise TypeError(f)
match = re.match(, did)
if not match:
raise ValueError(f)
result = {
: match.group(1),
: match.group(2),
}
return result | Parse a DID into it's parts.
:param did: Asset did, str.
:return: Python dictionary with the method and the id. |
361,428 | def put_blob(kwargs=None, storage_conn=None, call=None):
Some contents content type.
blob_content_encoding:
Optional. Set the blobs content language.
blob_content_md5:
Optional. Set the blobs cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_i... | .. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of ... |
361,429 | def norm(value, dims, order=None):
if dims == 0:
return tf.math.abs(value)
elif dims == 1:
axis = -1
elif dims == 2:
axis = [-1, -2]
else:
ValueError(dims)
if order is None:
order = np.inf
return tf.norm(tensor=value, axis=axis, ord=order) | Compute the norm of the given (possibly batched) value.
Args:
value: A `Tensor` of real dtype.
dims: An Python integer with the number of non-batching dimensions in the
value, i.e. `dims=0` (scalars), `dims=1` (vectors), `dims=2` (matrices).
order: Order of the norm, defaults to `np.inf`. |
361,430 | def register_logging_factories(loader):
loader.register_factory(logging.Logger, LoggerFactory)
loader.register_factory(logging.Handler, LoggingHandlerFactory) | Registers default factories for logging standard package.
:param loader: Loader where you want register default logging factories |
361,431 | def op(name,
data,
display_name=None,
description=None,
collections=None):
import tensorflow.compat.v1 as tf
if display_name is None:
display_name = name
summary_metadata = metadata.create_summary_metadata(
display_name=display_name, description=description)
with tf.... | Create a legacy scalar summary op.
Arguments:
name: A unique name for the generated summary node.
data: A real numeric rank-0 `Tensor`. Must have `dtype` castable
to `float32`.
display_name: Optional name for this summary in TensorBoard, as a
constant `str`. Defaults to `name`.
descriptio... |
361,432 | def _connect_nntp (self, nntpserver):
tries = 0
nntp = None
while tries < 2:
tries += 1
try:
nntp = nntplib.NNTP(nntpserver, usenetrc=False)
except nntplib.NNTPTemporaryError:
self.wait()
except nntplib.NNTP... | This is done only once per checking task. Also, the newly
introduced error codes 504 and 505 (both inclining "Too busy, retry
later", are caught. |
361,433 | async def dnsbl_request(self, addr, provider):
response = None
error = None
try:
socket.inet_aton(addr)
except socket.error:
raise ValueError()
ip_reversed = .join(reversed(addr.split()))
dnsbl_query = "%s.%s" % (ip_reversed, provider.host... | Make lookup to dnsbl provider
Parameters:
* addr (string) - ip address to check
* provider (string) - dnsbl provider
Returns:
* DNSBLResponse object
Raises:
* ValueError |
361,434 | def _get_request(self, request_url, request_method, **params):
if request_method == :
if params:
request_url += % urlencode(params)
request = Request(request_url)
elif request_method == :
request = Request(request_url, urlencode(params, doseq... | Return a Request object that has the GET parameters
attached to the url or the POST data attached to the object. |
361,435 | def index(self, val, start=None, stop=None):
_len = self._len
if not _len:
raise ValueError(.format(val))
if start is None:
start = 0
if start < 0:
start += _len
if start < 0:
start = 0
if stop is None:
... | Return the smallest *k* such that L[k] == val and i <= k < j`. Raises
ValueError if *val* is not present. *stop* defaults to the end of the
list. *start* defaults to the beginning. Negative indices are supported,
as for slice indices. |
361,436 | def draw(args):
trunc_name_options = [, , , ]
p = OptionParser(draw.__doc__)
p.add_option("--input", help="path to single input tree file or a dir "\
"containing ONLY the input tree files")
p.add_option("--combine", type="string", default="1x1", \
help="combine mul... | %prog draw --input newicktrees [options]
Draw phylogenetic trees into single or combined plots.
Input trees should be one of the following:
1. single Newick format tree file
2. a dir containing *ONLY* the tree files to be drawn
Newick format:
http://evolution.genetics.washington.edu/phylip/n... |
361,437 | def write(self, data):
self.backingStream.write(data)
for listener in self.writeListeners:
listener(len(data)) | Write the given data to the file. |
361,438 | def option_registrations_iter(self):
def normalize_kwargs(args, orig_kwargs):
nkwargs = copy.copy(orig_kwargs)
dest = self.parse_dest(*args, **nkwargs)
nkwargs[] = dest
if not ( in nkwargs and isinstance(nkwargs[], RankedValue)):
nkwargs[] = self._compute_value(dest, nkwargs, []... | Returns an iterator over the normalized registration arguments of each option in this parser.
Useful for generating help and other documentation.
Each yielded item is an (args, kwargs) pair, as passed to register(), except that kwargs
will be normalized in the following ways:
- It will always have '... |
361,439 | def get_authenticated_user(self, callback):
oauth_ns = ""
for name, values in self.request.arguments.iteritems():
if name.startswith("openid.ns.") and \
values[-1] == u"http://specs.openid.net/extensions/oauth/1.0":
oauth_ns = name[10:]
... | Fetches the authenticated user data upon redirect. |
361,440 | def elementwise_cdf(self, p):
r
p = scipy.atleast_1d(p)
if len(p) != len(self.sigma):
raise ValueError("length of p must equal the number of parameters!")
if p.ndim != 1:
raise ValueError("p must be one-dimensional!")
return scipy.asarray([scipy.stats.norm... | r"""Convert a sample to random variates uniform on :math:`[0, 1]`.
For a univariate distribution, this is simply evaluating the CDF. To
facilitate efficient sampling, this function returns a *vector* of CDF
values, one value for each variable. Basically, the idea is that, given
... |
361,441 | def delete_group_entitlement(self, group_id, rule_option=None, remove_group_membership=None):
route_values = {}
if group_id is not None:
route_values[] = self._serialize.url(, group_id, )
query_parameters = {}
if rule_option is not None:
query_parameters[... | DeleteGroupEntitlement.
[Preview API] Delete a group entitlement.
:param str group_id: ID of the group to delete.
:param str rule_option: RuleOption [ApplyGroupRule/TestApplyGroupRule] - specifies if the rules defined in group entitlement should be deleted and the changes are applied to it’s mem... |
361,442 | def nav_filter_bias_send(self, usec, accel_0, accel_1, accel_2, gyro_0, gyro_1, gyro_2, force_mavlink1=False):
return self.send(self.nav_filter_bias_encode(usec, accel_0, accel_1, accel_2, gyro_0, gyro_1, gyro_2), force_mavlink1=force_mavlink1) | Accelerometer and Gyro biases from the navigation filter
usec : Timestamp (microseconds) (uint64_t)
accel_0 : b_f[0] (float)
accel_1 : b_f[1] (float)
accel_2 : b_f[2] (float)
... |
361,443 | def derive(self, input):
s a KeyError.
If you fall into oblivion, then the derivative is an FSM accepting no
strings.
'
try:
state = self.initial
for symbol in input:
if not symbol in self.alphabet:
if not anything_else in self.alphabet:
raise KeyError(symbol)
symbol = anything... | Compute the Brzozowski derivative of this FSM with respect to the input
string of symbols. <https://en.wikipedia.org/wiki/Brzozowski_derivative>
If any of the symbols are not members of the alphabet, that's a KeyError.
If you fall into oblivion, then the derivative is an FSM accepting no
strings. |
361,444 | def MakeNewConfig(self):
result = self.__class__()
result.type_infos = self.type_infos
result.defaults = self.defaults
result.context = self.context
result.valid_contexts = self.valid_contexts
return result | Creates a new configuration option based on this one.
Note that it is not normally possible to just instantiate the
config object because it will have an empty set of type
descriptors (i.e. no config options will be defined). Config
options are normally defined at import time, and then they get
add... |
361,445 | def kms_decrypt_value(self, lookup):
decrypted_lookup = ef_utils.kms_decrypt(EFAwsResolver.__CLIENTS["kms"], lookup)
return decrypted_lookup | Args:
lookup: the encrypted value to be decrypted by KMS; base64 encoded
Returns:
The decrypted lookup value |
361,446 | def do_min(environment, value, case_sensitive=False, attribute=None):
return _min_or_max(environment, value, min, case_sensitive, attribute) | Return the smallest item from the sequence.
.. sourcecode:: jinja
{{ [1, 2, 3]|min }}
-> 1
:param case_sensitive: Treat upper and lower case strings as distinct.
:param attribute: Get the object with the max value of this attribute. |
361,447 | def list(cls, rc_file=):
sessions = session.get_all(rc_file)
return [name for name in sessions
if sessions[name].get() == cls.__name__] | Return a list of all stored sessions available in the
`rc_file` file:
.. doctest::
:options: +SKIP
>>> import odoorpc
>>> odoorpc.ODOO.list()
['foo', 'bar']
Use the :func:`save <odoorpc.ODOO.save>` and
:func:`load <odoorpc.ODOO.load>` me... |
361,448 | def parse_kwargs(kwargs):
d = defaultdict(list)
for k, v in ((k.lstrip(), v) for k,v in (a.split() for a in kwargs)):
d[k].append(v)
ret = {}
for k, v in d.items():
if len(v) == 1 and type(v) is list:
ret[k] = v[0]
else:
ret[k] = v
... | Convert a list of kwargs into a dictionary. Duplicates of the same keyword
get added to an list within the dictionary.
>>> parse_kwargs(['--var1=1', '--var2=2', '--var1=3']
{'var1': [1, 3], 'var2': 2} |
361,449 | def iter_endpoints(graph, match_func):
for rule in graph.flask.url_map.iter_rules():
try:
operation, ns = Namespace.parse_endpoint(rule.endpoint, get_converter(rule))
except (IndexError, ValueError, InternalServerError):
continue
else:
... | Iterate through matching endpoints.
The `match_func` is expected to have a signature of:
def matches(operation, ns, rule):
return True
:returns: a generator over (`Operation`, `Namespace`, rule, func) tuples. |
361,450 | def get_fast_scanner(self):
r
from numpy_sugar.linalg import ddot, economic_qs, sum2diag
y = self.eta / self.tau
if self._QS is None:
K = eye(y.shape[0]) / self.tau
else:
Q0 = self._QS[0][0]
S0 = self._QS[1]
K = dot(ddot(Q0, self.... | r"""Return :class:`glimix_core.lmm.FastScanner` for the current
delta. |
361,451 | def _change_logging_kwargs(kwargs):
log_levels = kwargs.pop(, None)
log_folder = kwargs.pop(, )
logger_names = kwargs.pop(, )
if log_levels is None:
log_levels = kwargs.pop(, logging.INFO)
log_multiproc = kwargs.pop(, True)
if not isinstance(logger_names, (tuple, list)):
lo... | Helper function to turn the simple logging kwargs into a `log_config`. |
361,452 | def read(self):
if self._output_buffer:
b, self._output_buffer = (self._output_buffer[0:1],
self._output_buffer[1:])
return b
return b | Return a single byte from the output buffer |
361,453 | def _write_named_sockets(self, socket_map):
for socket_name, socket_info in socket_map.items():
self.write_named_socket(socket_name, socket_info) | Write multiple named sockets using a socket mapping. |
361,454 | def add_state_view_for_model(self, state_m, parent_v=None, rel_pos=(0, 0), size=(100, 100), hierarchy_level=1):
assert isinstance(state_m, AbstractStateModel)
state_meta = state_m.get_meta_data_editor()
if not gui_helper_meta_data.contains_geometric_info(state_meta[]):
... | Creates a `StateView` (recursively) and adds it to the canvas
The method uses the `StateModel` `state_m` to create the according `StateView`. For all content within
`state_m`, such as connections, states and ports, the views are also created. All views are added to the canvas.
:param rafcon.g... |
361,455 | def cancel(
self,
identifier: typing.Any,
exc_type: typing.Optional[type]=None,
) -> bool:
raise NotImplementedError() | Cancel an active coroutine and remove it from the schedule.
Args:
identifier (typing.Any): The identifier returned from add.
exc_type (typing.Optional[type]): The exception type to throw into
the coroutine on cancel. No exception is thrown if nothing is
g... |
361,456 | def from_config(config_file, use_admin=False):
with open(config_file) as f:
d = json.load(f)
user = d["admin_user"] if use_admin else d["readonly_user"]
password = d["admin_password"] if use_admin \
else d["readonly_password"]
return Query... | Initialize a QueryEngine from a JSON config file generated using mgdb
init.
Args:
config_file:
Filename of config file.
use_admin:
If True, the admin user and password in the config file is
used. Otherwise, the readonly_user and pa... |
361,457 | def _initialize_archive(self):
if not in self.parsed_args:
manager = None
elif self.parsed_args.no_archive:
manager = None
else:
if not self.parsed_args.archive_path:
archive_path = os.path.expanduser(ARCHIVES_DEFAULT_PATH)
... | Initialize archive based on the parsed parameters |
361,458 | def autoencoder_discrete_cifar():
hparams = autoencoder_ordered_discrete()
hparams.bottleneck_noise = 0.0
hparams.bottleneck_bits = 90
hparams.num_hidden_layers = 2
hparams.hidden_size = 256
hparams.num_residual_layers = 4
hparams.batch_size = 32
hparams.learning_rate_constant = 1.0
return hparams | Discrete autoencoder model for compressing cifar. |
361,459 | def post(self, request, hook_id):
try:
bot = caching.get_or_set(KikBot, hook_id)
except KikBot.DoesNotExist:
logger.warning("Hook id %s not associated to a bot" % hook_id)
return Response(status=status.HTTP_404_NOT_FOUND)
signature = request.META.get(... | Process Kik webhook:
1. Get an enabled Kik bot
2. Verify Kik signature
3. Serialize each message
4. For each message create :class:`KikMessage <permabots.models.kik_api.KikMessage>` and :class:`KikUser <permabots.models.kik_api.KikUser>`
5. Delay each message ... |
361,460 | def subdomain(self, hostname):
hostname = hostname.split(":")[0]
for domain in getDomainNames(self.siteStore):
if hostname.endswith("." + domain):
username = hostname[:-len(domain) - 1]
if username != "www":
return username, domain... | Determine of which known domain the given hostname is a subdomain.
@return: A two-tuple giving the subdomain part and the domain part or
C{None} if the domain is not a subdomain of any known domain. |
361,461 | def handle(client_message, handle_event_entry=None, to_object=None):
message_type = client_message.get_message_type()
if message_type == EVENT_ENTRY and handle_event_entry is not None:
key = None
if not client_message.read_bool():
key = client_message.read_data()
value =... | Event handler |
361,462 | def hybrid_forward(self, F, inputs, mask=None):
outputs, attention_weights =\
self.attention_cell(inputs, inputs, inputs, mask)
outputs = self.proj(outputs)
if self._dropout:
outputs = self.dropout_layer(outputs)
if self._use_residual:
... | Transformer Encoder Attention Cell.
Parameters
----------
inputs : Symbol or NDArray
Input sequence. Shape (batch_size, length, C_in)
mask : Symbol or NDArray or None
Mask for inputs. Shape (batch_size, length, length)
Returns
-------
enc... |
361,463 | def tasks(self, path, postmap=None, **params):
q = httpd.merge_query(path, postmap)
ans = {}
for name, tinfo in self._legion._tasknames.items():
t = tinfo[0]
info = {}
conf = t.get_config()
if conf:
info[] = t._get(conf.ge... | Return the task status. This delves into the operating structures
and picks out information about tasks that is useful for status
monitoring.
For each task, the response includes:
control - The active task control value, whoich may have been
changed via the manag... |
361,464 | def copy(string, cmd=copy_cmd, stdin=PIPE):
Popen(cmd, stdin=stdin).communicate(string.encode()) | Copy given string into system clipboard. |
361,465 | def default_view_method(pid, record, template=None):
record_viewed.send(
current_app._get_current_object(),
pid=pid,
record=record,
)
deposit_type = request.values.get()
return render_template(
template,
pid=pid,
record=record,
jsonschema=cu... | Default view method.
Sends ``record_viewed`` signal and renders template. |
361,466 | def load_related_model(self, name, load_only=None, dont_load=None):
field = self._meta.dfields.get(name)
if not field:
raise ValueError( % name)
elif not field.type == :
raise ValueError( % name)
return self._load_related_model(field, load_only, dont_load... | Load a the :class:`ForeignKey` field ``name`` if this is part of the
fields of this model and if the related object is not already loaded.
It is used by the lazy loading mechanism of :ref:`one-to-many <one-to-many>`
relationships.
:parameter name: the :attr:`Field.name` of the :class:`ForeignKey` to load.
:parameter l... |
361,467 | def window(self, window):
original = self.current_window
if window != original:
self.switch_to_window(window)
self._scopes.append(None)
try:
yield
finally:
self._scopes.pop()
if original != window:
self.swi... | This method does the following:
1. Switches to the given window (it can be located by window instance/lambda/string).
2. Executes the given block (within window located at previous step).
3. Switches back (this step will be invoked even if exception happens at second step).
Args:
... |
361,468 | def get_serializer_class(self):
klass = None
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
if lookup_url_kwarg in self.kwargs:
klass = self.get_object().__class__
elif "doctype" in self.request.REQUEST:
base = self.model.get_... | gets the class type of the serializer
:return: `rest_framework.Serializer` |
361,469 | def _to_enos_networks(networks):
nets = []
for roles, network in networks:
nets.append(network.to_enos(roles))
logger.debug(nets)
return nets | Transform the networks returned by deploy5k.
Args:
networks (dict): networks returned by
:py:func:`enoslib.infra.provider.Provider.init` |
361,470 | def get_sky_coords(self):
if self._ipix is None:
theta, phi = hp.pix2ang(
self._nside, list(range(self._npix)), self._nest)
else:
theta, phi = hp.pix2ang(self._nside, self._ipix, self._nest)
lat = np.degrees((np.pi / 2) - theta)
lon = np.... | Get the sky coordinates of all the pixels in this pixelization |
361,471 | def create(cls, name, enabled=True, superuser=True):
json = {
: enabled,
: name,
: superuser}
return ElementCreator(cls, json) | Create a new API Client. Once client is created,
you can create a new password by::
>>> client = ApiClient.create('myclient')
>>> print(client)
ApiClient(name=myclient)
>>> client.change_password('mynewpassword')
:param str name: name of client
:... |
361,472 | def get_shark_field(self, fields):
keys, exist, out = None, {}, None
if isinstance(fields, str):
fields = [fields]
elif not isinstance(fields, list):
logging.error()
return None
out = dict.fromkeys(fields)
if hasattr(self, ):
... | get parameters via wireshark syntax.
out = x.get_shark_field('wlan.fc.type')
out = x.get_shark_field(['wlan.fc.type', 'wlan.seq'])
:fields: str or str[]
:return: dict
out[fields[0]] = val[0] or None
out[fields[1]] = val[1] or None ... |
361,473 | def prepare_request(settings):
settings["sp"]["assertionConsumerService"] = {
"url": web.ctx.homedomain + web.ctx.homepath + "/auth/callback/" + settings["id"],
"binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
}
data = web.input()
return {
: if web.ct... | Prepare SAML request |
361,474 | def slicer(self):
return tuple(np.s_[l:r] for l,r in zip(*self.bounds)) | Array slicer object for this tile
>>> Tile((2,3)).slicer
(slice(0, 2, None), slice(0, 3, None))
>>> np.arange(10)[Tile((4,)).slicer]
array([0, 1, 2, 3]) |
361,475 | def tasks(self):
task_input = {: }
output = taskengine.execute(task_input, self._engine_name, cwd=self._cwd)
return output[][] | Returns a list of all tasks known to the engine.
:return: A list of task names. |
361,476 | def requestExec(self, commandLine):
data = common.NS(commandLine)
return self.sendRequest(, data, wantReply=True) | Request execution of :commandLine: and return a deferred reply. |
361,477 | def save_config(
self,
cmd="copy running-configuration startup-configuration",
confirm=False,
confirm_response="",
):
return super(DellDNOS6Base, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) | Saves Config |
361,478 | def matchRecordAttrs(mapobj, attrs):
for k,v in iteritems(attrs):
try: val = getattr(mapobj, k)
except AttributeError:
else: continue
return True | attempt to match given attributes against a single map object's attributes |
361,479 | def adjust(self, to):
if self.date == :
return
new = copy(self)
if type(to) in (str, unicode):
to = to.lower()
res = TIMESTRING_RE.search(to)
if res:
rgroup = res.groupdict()
if (rgroup.get() or rgroup.get()... | Adjusts the time from kwargs to timedelta
**Will change this object**
return new copy of self |
361,480 | def _expectation(p, kern, none1, none2, none3, nghp=None):
r
if not kern.on_separate_dimensions:
raise NotImplementedError(
"Product currently needs to be defined on separate dimensions.")
return functools.reduce(tf.multiply, [
expectation(p, k, nghp=nghp) for k in kern.kernel... | r"""
Compute the expectation:
<\HadamardProd_i diag(Ki_{X[:, active_dims_i], X[:, active_dims_i]})>_p(X)
- \HadamardProd_i Ki_{.,.} :: Product kernel
- p :: DiagonalGaussian distribution (p.cov NxD)
:return: N |
361,481 | def bins_range(self, axis=0, overflow=False):
nbins = self.nbins(axis=axis, overflow=False)
if overflow:
start = 0
end_offset = 2
else:
start = 1
end_offset = 1
return range(start, nbins + end_offset) | Return a range of bin indices for iterating along an axis
Parameters
----------
axis : int, optional (default=1)
The axis (0, 1 or 2).
overflow : bool, optional (default=False)
If True then include the underflow and overflow bins
otherwise only incl... |
361,482 | def _ConvertRowToUnicode(self, parser_mediator, row):
for key, value in iter(row.items()):
if isinstance(value, py2to3.UNICODE_TYPE):
continue
try:
row[key] = value.decode(self._encoding)
except UnicodeDecodeError:
replaced_value = value.decode(self._encoding, errors=... | Converts all strings in a DSV row dict to Unicode.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row (dict[str, bytes]): a row from a DSV file, where the dictionary
key contains the column name and the ... |
361,483 | def get_parameter_diff(awsclient, config):
client_cf = awsclient.get_client()
try:
stack_name = config[][]
if stack_name:
response = client_cf.describe_stacks(StackName=stack_name)
if response[]:
stack_id = response[][0][]
stack = resp... | get differences between local config and currently active config |
361,484 | def __getJoinerState(self):
maxDuration = 150
t_end = time.time() + maxDuration
while time.time() < t_end:
joinerState = self.__stripValue(self.__sendCommand()[0])
if joinerState == :
return True
elif joinerState == :
... | get joiner state |
361,485 | def toxml(self):
return + \
(.format(self.instance) if self.instance else ) +\
(.format(self.list) if self.list else ) + \
(.format(self.index) if self.index else ) + \
.format(self.instance, self.as_) | Exports this object into a LEMS XML object |
361,486 | def _print_command(self, cmd):
text = helpers.repr_bytes(cmd)
self.outf.write(text)
if not text.endswith(b):
self.outf.write(b) | Wrapper to avoid adding unnecessary blank lines. |
361,487 | def get_sleepstage(self, stage_idx=None):
if self.annot is None:
error_dialog = QErrorMessage()
error_dialog.setWindowTitle()
error_dialog.showMessage()
error_dialog.exec()
return
window_start = self.parent.value()
window_le... | Score the sleep stage, using shortcuts or combobox. |
361,488 | def unmasked_sparse_to_sparse_from_mask_and_pixel_centres(mask, unmasked_sparse_grid_pixel_centres,
total_sparse_pixels):
total_unmasked_sparse_pixels = unmasked_sparse_grid_pixel_centres.shape[0]
unmasked_sparse_to_sparse = np.zeros(total_unmaske... | Determine the mapping between every pixelization-grid pixel and masked pixelization-grid pixel. This is
performed by checking whether each pixelization-grid pixel is within the regular-masks, and mapping the indexes.
Pixelization pixels are paired with the next masked pixel index. This may mean that a pixel is... |
361,489 | def sort_dependencies(app_list):
model_dependencies = []
models = set()
for app_config, model_list in app_list:
if model_list is None:
model_list = app_config.get_models()
for model in model_list:
models.add(model)
if hasattr(model,... | Sort a list of (app_config, models) pairs into a single list of models.
The single list of models is sorted so that any model with a natural key
is serialized before a normal model, and any model with a natural key
dependency has it's dependencies serialized first. |
361,490 | def add_vertex(self, v):
if v not in self.adjacency:
self.adjacency[v] = Vertex(v)
return self.adjacency[v].vertex | Add a vertex to the graph. The vertex must implement __hash__ and __eq__ as it will be stored in a set.
:param v: vertex
:return: graph owned vertex |
361,491 | def render_template(self, template, **kwargs):
high = compile_template(template,
self.rend,
self.opts[],
self.opts[],
self.opts[],
**kwargs)
... | Enforce the states in a template |
361,492 | async def sync_recent_conversations(
self, sync_recent_conversations_request
):
response = hangouts_pb2.SyncRecentConversationsResponse()
await self._pb_request(,
sync_recent_conversations_request,
response)
r... | Return info on recent conversations and their events. |
361,493 | def fromTerm(cls, term):
if isinstance(term, Term):
term = term.handle
elif not isinstance(term, (c_void_p, int)):
raise ArgumentTypeError((str(Term), str(int)), str(type(term)))
f = functor_t()
if PL_get_functor(term, byref(f)):
... | Create a functor from a Term or term handle. |
361,494 | def read_task_from_index(task_family, index_file=None):
if index_file is None:
index_file = Config.instance().get_expanded("core", "index_file")
with open(index_file, "r") as f:
for line in f.readlines():
line = line.strip()
if line.count(":") >= 2:
... | Returns module id, task family and space-separated parameters in a tuple for a task given by
*task_family* from the *index_file*. When *None*, the *index_file* refers to the default as
defined in :py:mod:`law.config`. Returns *None* when the task could not be found. |
361,495 | def simulate(self, time,
feedforwardInputI,
feedforwardInputE,
v,
recurrent=True,
dt=None,
envelope=False,
inputNoise=None):
if self.plotting:
self.fig = plt.figure()
self.ax1 = self.fig.ad... | :param time: Amount of time to simulate.
Divided into chunks of len dt.
:param feedforwardInputI: feedforward input to inhibitory cells. Must have
shape (numInhibitory,). Should be total input over period time.
:param feedforwardInputE: feedforward input to excitatory cells. Must have
... |
361,496 | def addFailure(self, test: unittest.case.TestCase, exc_info: tuple) -> None:
self.add_result(TestState.failure, test, exc_info) | Transforms the test in a serializable version of it and sends it to a queue for further analysis
:param test: the test to save
:param exc_info: tuple of the form (Exception class, Exception instance, traceback) |
361,497 | def get_dev_asset_details(ipaddress, auth, url):
ipaddress = get_dev_details(ipaddress, auth, url)
if isinstance(ipaddress, dict):
ipaddress = ipaddress[]
else:
print("Asset DoesnnetAssetdeviceIp get_dev_asset_details: An Error has occured' | Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API
:param ipaddress: IP address of the device you wish to gather the asset details
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url... |
361,498 | def group_associations_types(
self,
main_type,
sub_type,
unique_id,
target,
api_branch=None,
api_entity=None,
owner=None,
params=None,
):
params = params or {}
if owner:
params[] = owner
api_branch ... | Args:
owner:
main_type:
sub_type:
unique_id:
target:
api_branch:
api_entity:
params:
Return: |
361,499 | def back_make(dev, cache_mode=, force=False, attach=True, bucket_size=None):
*
cache = uuid()
if not cache:
log.error()
return False
elif _sysfs_attr(_bcpath(dev)):
if not force:
log.error(, dev)
return False
elif uuid(dev) and not detach(dev... | Create a backing device for attachment to a set.
Because the block size must be the same, a cache set already needs to exist.
CLI example:
.. code-block:: bash
salt '*' bcache.back_make sdc cache_mode=writeback attach=True
:param cache_mode: writethrough, writeback, writearound or none.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.