positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def getNode(self, name, **context):
"""Return tree node found by name"""
if name == self.name:
return self
else:
return self.getBranch(name, **context).getNode(name, **context) | Return tree node found by name |
def check_and_generate_next_task(self):
"""
check if the previous task is done and proceed to fire another task
:return:
"""
# if self.task_future is None:
# # there's no any ongoing task
# self._update_status(False)
# self.generate_next_task()... | check if the previous task is done and proceed to fire another task
:return: |
def get_active_topics_count(last_seen_timestamp=None):
"""
Returns count of new topics since last visit, or one day.
{% get_active_topics_count as active_topic_count %}
"""
if not last_seen_timestamp:
last_seen_timestamp = yesterday_timestamp()
return Topic.objects.filter(modified_int__g... | Returns count of new topics since last visit, or one day.
{% get_active_topics_count as active_topic_count %} |
def find_minimum_spanning_tree(graph):
"""Calculates a minimum spanning tree for a graph.
Returns a list of edges that define the tree.
Returns an empty list for an empty graph.
"""
mst = []
if graph.num_nodes() == 0:
return mst
if graph.num_edges() == 0:
return mst
con... | Calculates a minimum spanning tree for a graph.
Returns a list of edges that define the tree.
Returns an empty list for an empty graph. |
def get_anki_phrases(lang='english', limit=None):
""" Retrieve as many anki paired-statement corpora as you can for the requested language
If `ankis` (requested languages) is more than one, then get the english texts associated with those languages.
TODO: improve modularity: def function that takes a sing... | Retrieve as many anki paired-statement corpora as you can for the requested language
If `ankis` (requested languages) is more than one, then get the english texts associated with those languages.
TODO: improve modularity: def function that takes a single language and call it recursively if necessary
>>> g... |
def print_port(self, stream=sys.stdout):
"""
Print port this EPC server runs on.
As Emacs client reads port number from STDOUT, you need to
call this just before calling :meth:`serve_forever`.
:type stream: text stream
:arg stream: A stream object to write port on.
... | Print port this EPC server runs on.
As Emacs client reads port number from STDOUT, you need to
call this just before calling :meth:`serve_forever`.
:type stream: text stream
:arg stream: A stream object to write port on.
Default is :data:`sys.stdout`. |
def mechanism(self, mechanism):
"""
Sets the mechanism of this DeviceData.
The ID of the channel used to communicate with the device.
:param mechanism: The mechanism of this DeviceData.
:type: str
"""
allowed_values = ["connector", "direct"]
if mechanism ... | Sets the mechanism of this DeviceData.
The ID of the channel used to communicate with the device.
:param mechanism: The mechanism of this DeviceData.
:type: str |
def default_profiler(f, _type, _value):
''' inspects an input frame and pretty prints the following:
<src-path>:<src-line> -> <function-name>
<source-code>
<local-variables>
----------------------------------------
'''
try:
profile_print(
'\n'.join([
... | inspects an input frame and pretty prints the following:
<src-path>:<src-line> -> <function-name>
<source-code>
<local-variables>
---------------------------------------- |
def _has_app(self, app, webpage):
"""
Determine whether the web page matches the app signature.
"""
# Search the easiest things first and save the full-text search of the
# HTML for last
for regex in app['url']:
if regex.search(webpage.url):
r... | Determine whether the web page matches the app signature. |
def get_cutout(self, clearance=0):
" get the cutout for the shaft"
return cq.Workplane('XY', origin=(0, 0, 0)) \
.circle((self.diam / 2) + clearance) \
.extrude(10) | get the cutout for the shaft |
def _unwrap_func(cls, decorated_func):
'''
This unwraps a decorated func, returning the inner wrapped func.
This may become unnecessary with Python 3.4's inspect.unwrap().
'''
if click is not None:
# Workaround for click.command() decorator not setting
# ... | This unwraps a decorated func, returning the inner wrapped func.
This may become unnecessary with Python 3.4's inspect.unwrap(). |
def add_user(self, username, password, full_name=None, trusted=False, readonly=False):
""" Add user to SQLite database.
* `username` [string]
Username of new user.
* `password` [string]
Password of new user.
* `full_name` [string]
... | Add user to SQLite database.
* `username` [string]
Username of new user.
* `password` [string]
Password of new user.
* `full_name` [string]
Full name of new user.
* `trusted` [boolean]
Whether the new user s... |
def evtx_chunk_xml_view(chunk):
"""
Generate XML representations of the records in an EVTX chunk.
Does not include the XML <?xml... header.
Records are ordered by chunk.records()
Args:
chunk (Evtx.Chunk): the chunk to render.
Yields:
tuple[str, Evtx.Record]: the rendered XML docum... | Generate XML representations of the records in an EVTX chunk.
Does not include the XML <?xml... header.
Records are ordered by chunk.records()
Args:
chunk (Evtx.Chunk): the chunk to render.
Yields:
tuple[str, Evtx.Record]: the rendered XML document and the raw record. |
def get(self, attr, default=None):
"""Get an attribute defined by this session"""
attrs = self.body.get('attributes') or {}
return attrs.get(attr, default) | Get an attribute defined by this session |
def rollout(policy, env, timestep_limit=None, add_noise=False, offset=0):
"""Do a rollout.
If add_noise is True, the rollout will take noisy actions with
noise drawn from that stream. Otherwise, no action noise will be added.
Parameters
----------
policy: tf object
policy from which to... | Do a rollout.
If add_noise is True, the rollout will take noisy actions with
noise drawn from that stream. Otherwise, no action noise will be added.
Parameters
----------
policy: tf object
policy from which to draw actions
env: GymEnv
environment from which to draw rewards, don... |
def sort_sam(sam, sort):
"""
sort sam file
"""
tempdir = '%s/' % (os.path.abspath(sam).rsplit('/', 1)[0])
if sort is True:
mapping = '%s.sorted.sam' % (sam.rsplit('.', 1)[0])
if sam != '-':
if os.path.exists(mapping) is False:
os.system("\
... | sort sam file |
def y(self):
'''
np.array: The grid points in y.
'''
if None not in (self.y_min, self.y_max, self.y_step) and \
self.y_min != self.y_max:
y = np.arange(self.y_min, self.y_max-self.y_step*0.1, self.y_step)
else:
y = np.array([])
retu... | np.array: The grid points in y. |
def language_list(
maintenance_db,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
.. versionadded:: 2016.3.0
Return a list of languages in a database.
CLI Example:
.. code-block:: bash
salt '*' postgres.language_list dbnam... | .. versionadded:: 2016.3.0
Return a list of languages in a database.
CLI Example:
.. code-block:: bash
salt '*' postgres.language_list dbname
maintenance_db
The database to check
user
database username if different from config or default
password
user passw... |
def get(self, task_id=None, params=None):
"""
Retrieve information for a particular task.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_
:arg task_id: Return the task with specified id (node_id:task_number)
:arg wait_for_completion: Wait for the m... | Retrieve information for a particular task.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/tasks.html>`_
:arg task_id: Return the task with specified id (node_id:task_number)
:arg wait_for_completion: Wait for the matching tasks to complete
(default: false)
... |
def top_k_accuracy(input:Tensor, targs:Tensor, k:int=5)->Rank0Tensor:
"Computes the Top-k accuracy (target is in the top k predictions)."
input = input.topk(k=k, dim=-1)[1]
targs = targs.unsqueeze(dim=-1).expand_as(input)
return (input == targs).max(dim=-1)[0].float().mean() | Computes the Top-k accuracy (target is in the top k predictions). |
def set_options(self, **kwargs):
"""
Set options.
@param kwargs: keyword arguments.
@see: L{Options}
"""
p = Unskin(self.options)
p.update(kwargs) | Set options.
@param kwargs: keyword arguments.
@see: L{Options} |
def _cancel_callback(self, request_id):
"""Construct a cancellation callback for the given request ID."""
def callback(future):
if future.cancelled():
self.notify(CANCEL_METHOD, {'id': request_id})
future.set_exception(JsonRpcRequestCancelled())
return... | Construct a cancellation callback for the given request ID. |
def check(self, value):
"""
check if a value is correct according to threshold
arguments:
value: the value to check
"""
if self._inclusive:
return False if self._min <= value <= self._max else True
else:
return False if value > self._m... | check if a value is correct according to threshold
arguments:
value: the value to check |
def imshow(image, auto_subplot=False, **kwargs):
""" Displays an image.
Parameters
----------
image : :obj:`perception.Image`
image to display
auto_subplot : bool
whether or not to automatically subplot for multi-channel images e.g. rgbd
"""
... | Displays an image.
Parameters
----------
image : :obj:`perception.Image`
image to display
auto_subplot : bool
whether or not to automatically subplot for multi-channel images e.g. rgbd |
def compute(self, xt1, yt1, xt, yt, theta1t1, theta2t1, theta1, theta2):
"""
Accumulate the various inputs.
"""
dx = xt - xt1
dy = yt - yt1
if self.numPoints < self.maxPoints:
self.dxValues[self.numPoints,0] = dx
self.dxValues[self.numPoints,1] = dy
self.thetaValues[self.numP... | Accumulate the various inputs. |
def is_public(self):
"""``True`` if this is a public key, otherwise ``False``"""
return isinstance(self._key, Public) and not isinstance(self._key, Private) | ``True`` if this is a public key, otherwise ``False`` |
def sumaclust_denovo_cluster(seq_path=None,
result_path=None,
shortest_len=True,
similarity=0.97,
threads=1,
exact=False,
HALT_EXEC=False
... | Function : launch SumaClust de novo OTU picker
Parameters: seq_path, filepath to reads;
result_path, filepath to output OTU map;
shortest_len, boolean;
similarity, the similarity threshold (between (0,1]);
threads, number of threa... |
def distances_indices_sorted(self, points, sign=False):
"""
Computes the distances from the plane to each of the points. Positive distances are on the side of the
normal of the plane while negative distances are on the other side. Indices sorting the points from closest
to furthest is al... | Computes the distances from the plane to each of the points. Positive distances are on the side of the
normal of the plane while negative distances are on the other side. Indices sorting the points from closest
to furthest is also computed.
:param points: Points for which distances are computed
... |
def MultiWritePathHistory(self, client_path_histories):
"""Writes a collection of hash and stat entries observed for given paths."""
for client_path, client_path_history in iteritems(client_path_histories):
if client_path.client_id not in self.metadatas:
raise db.UnknownClientError(client_path.cli... | Writes a collection of hash and stat entries observed for given paths. |
def selectisinstance(table, field, value, complement=False):
"""Select rows where the given field is an instance of the given type."""
return selectop(table, field, value, isinstance, complement=complement) | Select rows where the given field is an instance of the given type. |
def get_role_config_group(self, name):
"""
Get a role configuration group in the service by name.
@param name: The name of the role config group.
@return: An ApiRoleConfigGroup object.
@since: API v3
"""
return role_config_groups.get_role_config_group(
self._get_resource_root(), sel... | Get a role configuration group in the service by name.
@param name: The name of the role config group.
@return: An ApiRoleConfigGroup object.
@since: API v3 |
def refresh_token(self, client_id, client_secret, refresh_token, grant_type='refresh_token'):
"""Calls oauth/token endpoint with refresh token grant type
Use this endpoint to refresh an access token, using the refresh token you got during authorization.
Args:
grant_type (str): Deno... | Calls oauth/token endpoint with refresh token grant type
Use this endpoint to refresh an access token, using the refresh token you got during authorization.
Args:
grant_type (str): Denotes the flow you're using. For refresh token
use refresh_token
client_id (str): ... |
def effective_n(mcmc):
"""
Args:
mcmc (MCMCResults): Pre-sliced MCMC samples to compute diagnostics for.
"""
if mcmc.n_chains < 2:
raise ValueError(
'Calculation of effective sample size requires multiple chains '
'of the same length.')
def get_neff(x):
... | Args:
mcmc (MCMCResults): Pre-sliced MCMC samples to compute diagnostics for. |
def delete(self, id):
""" delete a time entry. """
path = partial(_path, self.adapter)
path = path(id)
return self._delete(path) | delete a time entry. |
def copy_workspace(self, uri, new_name):
'''
Copy the current workspace.
Args:
- uri (dict): the uri of the workspace being copied. Needs to have a did and wid key.
- new_name (str): the new name of the copied workspace.
Returns:
- requests.Response:... | Copy the current workspace.
Args:
- uri (dict): the uri of the workspace being copied. Needs to have a did and wid key.
- new_name (str): the new name of the copied workspace.
Returns:
- requests.Response: Onshape response data |
def Tensors(self, run, tag):
"""Retrieve the tensor events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not availab... | Retrieve the tensor events associated with a run and tag.
Args:
run: A string name of the run for which values are retrieved.
tag: A string name of the tag for which values are retrieved.
Raises:
KeyError: If the run is not found, or the tag is not available for
the given run.
R... |
def get(self, request, *args, **kwargs):
""" Retrieve list of nodes of the specified layer """
self.get_layer()
# get nodes of layer
nodes = self.get_nodes(request, *args, **kwargs)
return Response(nodes) | Retrieve list of nodes of the specified layer |
def as_list(callable):
"""Convert a scalar validator in a list validator"""
@wraps(callable)
def wrapper(value_iter):
return [callable(value) for value in value_iter]
return wrapper | Convert a scalar validator in a list validator |
def GetRelativePath(self, path_spec):
"""Returns the relative path based on a resolved path specification.
The relative path is the location of the upper most path specification.
The the location of the mount point is stripped off if relevant.
Args:
path_spec (PathSpec): path specification.
... | Returns the relative path based on a resolved path specification.
The relative path is the location of the upper most path specification.
The the location of the mount point is stripped off if relevant.
Args:
path_spec (PathSpec): path specification.
Returns:
str: corresponding relative p... |
def monitor_session_span_command_dest_tengigabitethernet(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
monitor = ET.SubElement(config, "monitor", xmlns="urn:brocade.com:mgmt:brocade-span")
session = ET.SubElement(monitor, "session")
session_num... | Auto Generated Code |
def volume_montecarlo(found_d, missed_d, found_mchirp, missed_mchirp,
distribution_param, distribution, limits_param,
min_param=None, max_param=None):
"""
Compute sensitive volume and standard error via direct Monte Carlo integral
Injections should be made over a... | Compute sensitive volume and standard error via direct Monte Carlo integral
Injections should be made over a range of distances such that sensitive
volume due to signals closer than D_min is negligible, and efficiency at
distances above D_max is negligible
TODO : Replace this function by Collin's formu... |
def montage(data, ref_chan=None, ref_to_avg=False, bipolar=None,
method='average'):
"""Apply linear transformation to the channels.
Parameters
----------
data : instance of DataRaw
the data to filter
ref_chan : list of str
list of channels used as reference
ref_to_av... | Apply linear transformation to the channels.
Parameters
----------
data : instance of DataRaw
the data to filter
ref_chan : list of str
list of channels used as reference
ref_to_avg : bool
if re-reference to average or not
bipolar : float
distance in mm to consid... |
def cast_problem(problem):
"""
Casts problem object with known interface as OptProblem.
Parameters
----------
problem : Object
"""
# Optproblem
if isinstance(problem,OptProblem):
return problem
# Other
else:
# Type Base
if (not hasattr(... | Casts problem object with known interface as OptProblem.
Parameters
----------
problem : Object |
def iteritems(self):
"""
Wow this class is messed up. I had to overwrite items when
moving to python3, just because I haden't called it yet
"""
for (key, val) in six.iteritems(self.__dict__):
if key in self._printable_exclude:
continue
yiel... | Wow this class is messed up. I had to overwrite items when
moving to python3, just because I haden't called it yet |
def retro_schema(schema):
"""
CONVERT SCHEMA FROM 5.x to 1.x
:param schema:
:return:
"""
output = wrap({
"mappings":{
typename: {
"dynamic_templates": [
retro_dynamic_template(*(t.items()[0]))
for t in details.dynamic_te... | CONVERT SCHEMA FROM 5.x to 1.x
:param schema:
:return: |
def file_upload(self, local_path, remote_path, l_st):
"""Upload local_path to remote_path and set permission and mtime."""
self.sftp.put(local_path, remote_path)
self._match_modes(remote_path, l_st) | Upload local_path to remote_path and set permission and mtime. |
def _add_channel(self, chn, color_min, color_max):
"""Adds a channel to the image object
"""
if isinstance(chn, np.ma.core.MaskedArray):
chn_data = chn.data
chn_mask = chn.mask
else:
chn_data = np.array(chn)
chn_mask = False
scaled ... | Adds a channel to the image object |
def get_selection(self):
"""
Read text from the X selection
Usage: C{clipboard.get_selection()}
@return: text contents of the mouse selection
@rtype: C{str}
@raise Exception: if no text was found in the selection
"""
Gdk.threads_enter()
t... | Read text from the X selection
Usage: C{clipboard.get_selection()}
@return: text contents of the mouse selection
@rtype: C{str}
@raise Exception: if no text was found in the selection |
def mounts():
"""Get a list of all mounted volumes as [[mountpoint,device],[...]]"""
with open('/proc/mounts') as f:
# [['/mount/point','/dev/path'],[...]]
system_mounts = [m[1::-1] for m in [l.strip().split()
for l in f.readlines()]]
return system... | Get a list of all mounted volumes as [[mountpoint,device],[...]] |
def read(self, file_path: str) -> Iterable[Instance]:
"""
Returns an ``Iterable`` containing all the instances
in the specified dataset.
If ``self.lazy`` is False, this calls ``self._read()``,
ensures that the result is a list, then returns the resulting list.
If ``self... | Returns an ``Iterable`` containing all the instances
in the specified dataset.
If ``self.lazy`` is False, this calls ``self._read()``,
ensures that the result is a list, then returns the resulting list.
If ``self.lazy`` is True, this returns an object whose
``__iter__`` method ... |
def make_chunk(chunk_type, chunk_data):
"""Create a raw chunk by composing chunk type and data. It
calculates chunk length and CRC for you.
:arg str chunk_type: PNG chunk type.
:arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**.
:rtype: bytes
"""
out = struct.pack("!I", len(chunk_d... | Create a raw chunk by composing chunk type and data. It
calculates chunk length and CRC for you.
:arg str chunk_type: PNG chunk type.
:arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**.
:rtype: bytes |
def get(self, id): # pylint: disable=invalid-name,redefined-builtin
"""Get a package.
:param id: Package ID as an int.
:return: :class:`packages.Package <packages.Package>` object
:rtype: packages.Package
"""
schema = PackageSchema()
resp = self.service.get_id(se... | Get a package.
:param id: Package ID as an int.
:return: :class:`packages.Package <packages.Package>` object
:rtype: packages.Package |
def set_type(self, value):
"""Setter for type attribute"""
if self.action == "remove" and value != "probes":
log = "Sources field 'type' when action is remove should always be 'probes'."
raise MalFormattedSource(log)
self._type = value | Setter for type attribute |
def simxGetDistanceHandle(clientID, distanceObjectName, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
handle = ct.c_int()
if (sys.version_info[0] == 3) and (type(distanceObjectName) is str):
distanceObjectName=distanceObjectNam... | Please have a look at the function description/documentation in the V-REP user manual |
def _get_registerd_func(name_or_func):
""" get a xcorr function from a str or callable. """
# get the function or register callable
if callable(name_or_func):
func = register_array_xcorr(name_or_func)
else:
func = XCOR_FUNCS[name_or_func or 'default']
assert callable(func), 'func is ... | get a xcorr function from a str or callable. |
def task(self):
"""
Find the task for this build.
Wraps the getTaskInfo RPC.
:returns: deferred that when fired returns the Task object, or None if
we could not determine the task for this build.
"""
# If we have no .task_id, this is a no-op to return ... | Find the task for this build.
Wraps the getTaskInfo RPC.
:returns: deferred that when fired returns the Task object, or None if
we could not determine the task for this build. |
def _inner_func_anot(func):
"""must be applied to all inner functions that return contexts.
Wraps all instances of pygame.Surface in the input in Surface"""
@wraps(func)
def new_func(*args):
return func(*_lmap(_wrap_surface, args))
return new_func | must be applied to all inner functions that return contexts.
Wraps all instances of pygame.Surface in the input in Surface |
def events_for_balanceproof(
channelidentifiers_to_channels: ChannelMap,
transfers_pair: List[MediationPairState],
pseudo_random_generator: random.Random,
block_number: BlockNumber,
secret: Secret,
secrethash: SecretHash,
) -> List[Event]:
""" While it's safe do the o... | While it's safe do the off-chain unlock. |
def _pfp__width(self):
"""Return the width of the field (sizeof)
"""
raw_output = six.BytesIO()
output = bitwrap.BitwrappedStream(raw_output)
self._pfp__build(output)
output.flush()
return len(raw_output.getvalue()) | Return the width of the field (sizeof) |
def drawing_update(self):
'''update line drawing'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if self.draw_callback is None:
return
self.draw_line.append(self.click_position)
if len(self.draw_line) > 1:
self.mpstate.map.add_object(mp_slipmap.Sli... | update line drawing |
def DEFINE_integer_list(self, name, default, help, constant=False):
"""A helper for defining lists of integer options."""
self.AddOption(
type_info.List(
name=name,
default=default,
description=help,
validator=type_info.Integer()),
constant=constan... | A helper for defining lists of integer options. |
def gaussian_window(t, params):
"""
Calculates a Gaussian window function in the time domain which will broaden
peaks in the frequency domain by params["line_broadening"] Hertz.
:param t:
:param params:
:return:
"""
window = suspect.basis.gaussian(t, 0, 0, params["line_broadening"])
... | Calculates a Gaussian window function in the time domain which will broaden
peaks in the frequency domain by params["line_broadening"] Hertz.
:param t:
:param params:
:return: |
def merge_groundings(stmts_in):
"""Gather and merge original grounding information from evidences.
Each Statement's evidences are traversed to find original grounding
information. These groundings are then merged into an overall consensus
grounding dict with as much detail as possible.
The current... | Gather and merge original grounding information from evidences.
Each Statement's evidences are traversed to find original grounding
information. These groundings are then merged into an overall consensus
grounding dict with as much detail as possible.
The current implementation is only applicable to S... |
def network_sub_create_notif(self, tenant_id, tenant_name, cidr):
"""Network create notification. """
if not self.fw_init:
return
self.network_create_notif(tenant_id, tenant_name, cidr) | Network create notification. |
def block_by_command(cls, command):
"""Return the block with the given :attr:`command`.
Returns None if the block is not found.
"""
for block in cls.blocks:
if block.has_command(command):
return block | Return the block with the given :attr:`command`.
Returns None if the block is not found. |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extract dictionaries of coefficients specific to required
# ... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
def put_user(self, username, body, params=None):
"""
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-put-user.html>`_
:arg username: The username of the User
:arg body: The user to add
:arg refresh: If `true` (the default) then refresh the affected... | `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-put-user.html>`_
:arg username: The username of the User
:arg body: The user to add
:arg refresh: If `true` (the default) then refresh the affected shards
to make this operation visible to search, if `wai... |
def _covar_mstep_spherical(*args):
"""Performing the covariance M step for spherical cases"""
cv = _covar_mstep_diag(*args)
return np.tile(cv.mean(axis=1)[:, np.newaxis], (1, cv.shape[1])) | Performing the covariance M step for spherical cases |
def modprobe(module, persist=True):
"""Load a kernel module and configure for auto-load on reboot."""
cmd = ['modprobe', module]
log('Loading kernel module %s' % module, level=INFO)
subprocess.check_call(cmd)
if persist:
persistent_modprobe(module) | Load a kernel module and configure for auto-load on reboot. |
def create_namespace(
name,
**kwargs):
'''
Creates a namespace with the specified name.
CLI Example:
salt '*' kubernetes.create_namespace salt
salt '*' kubernetes.create_namespace name=salt
'''
meta_obj = kubernetes.client.V1ObjectMeta(name=name)
body = kubernet... | Creates a namespace with the specified name.
CLI Example:
salt '*' kubernetes.create_namespace salt
salt '*' kubernetes.create_namespace name=salt |
def split_lists(d, split_keys, new_name='split',
check_length=True, deepcopy=True):
"""split_lists key:list pairs into dicts for each item in the lists
NB: will only split if all split_keys are present
Parameters
----------
d : dict
split_keys : list
keys to split
ne... | split_lists key:list pairs into dicts for each item in the lists
NB: will only split if all split_keys are present
Parameters
----------
d : dict
split_keys : list
keys to split
new_name : str
top level key for split items
check_length : bool
if true, raise error if ... |
def children(self, alias, bank_id):
"""
URL for getting or setting child relationships for the specified bank
:param alias:
:param bank_id:
:return:
"""
return self._root + self._safe_alias(alias) + '/child/ids/' + str(bank_id) | URL for getting or setting child relationships for the specified bank
:param alias:
:param bank_id:
:return: |
def unlink_from(self, provider):
'''
解绑特定第三方平台
'''
if type(provider) != str:
raise TypeError('input should be a string')
self.link_with(provider, None)
# self._sync_auth_data(provider)
return self | 解绑特定第三方平台 |
def EvalGeneric(self, hashers=None):
"""Causes the entire file to be hashed by the given hash functions.
This sets up a 'finger' for fingerprinting, where the entire file
is passed through a pre-defined (or user defined) set of hash functions.
Args:
hashers: An iterable of hash classes (e.g. out... | Causes the entire file to be hashed by the given hash functions.
This sets up a 'finger' for fingerprinting, where the entire file
is passed through a pre-defined (or user defined) set of hash functions.
Args:
hashers: An iterable of hash classes (e.g. out of hashlib) which will
be in... |
def count_args(node, results):
# type: (Node, Dict[str, Base]) -> Tuple[int, bool, bool, bool]
"""Count arguments and check for self and *args, **kwds.
Return (selfish, count, star, starstar) where:
- count is total number of args (including *args, **kwds)
- selfish is True if the initial arg is na... | Count arguments and check for self and *args, **kwds.
Return (selfish, count, star, starstar) where:
- count is total number of args (including *args, **kwds)
- selfish is True if the initial arg is named 'self' or 'cls'
- star is True iff *args is found
- starstar is True iff **kwds is found |
def cache_file(package, mode):
"""
Yields a file-like object for the purpose of writing to or
reading from the cache.
The code:
with cache_file(...) as f:
# do stuff with f
is guaranteed to convert any exceptions to warnings (*),
both in the cache_file(...) call and the 'd... | Yields a file-like object for the purpose of writing to or
reading from the cache.
The code:
with cache_file(...) as f:
# do stuff with f
is guaranteed to convert any exceptions to warnings (*),
both in the cache_file(...) call and the 'do stuff with f'
block.
The file is... |
def timestamp_to_local_time_str(
timestamp, timezone_name, fmt="yyyy-MM-dd HH:mm:ss"):
"""Convert epoch timestamp to a localized datetime string.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local... | Convert epoch timestamp to a localized datetime string.
Arguments
---------
timestamp : int
The timestamp to convert.
timezone_name : datetime.timezone
The timezone of the desired local time.
fmt : str
The format of the output string.
Returns
-------
str
... |
def output(self, mode='file', forced=False, context=None):
"""
The general output method, override in subclass if you need to do
any custom modification. Calls other mode specific methods or simply
returns the content directly.
"""
output = '\n'.join(self.filter_input(forced, context=context))
... | The general output method, override in subclass if you need to do
any custom modification. Calls other mode specific methods or simply
returns the content directly. |
def replace(self, re_text, replace_str, text):
"""
正则表达式替换
:param re_text: 正则表达式
:param replace_str: 替换字符串
:param text: 搜索文档
:return: 替换后的字符串
"""
return re.sub(re_text, replace_str, text) | 正则表达式替换
:param re_text: 正则表达式
:param replace_str: 替换字符串
:param text: 搜索文档
:return: 替换后的字符串 |
def parsePositionFile(filename):
"""
Parses Android GPS logger csv file and returns list of dictionaries
"""
l=[]
with open( filename, "rb" ) as theFile:
reader = csv.DictReader( theFile )
for line in reader:
# Convert the time string to something
# a bit more... | Parses Android GPS logger csv file and returns list of dictionaries |
def set_trapezoidal_integration(self, n):
"""Set the code to use trapezoidal integration.
**Call signature**
*n*
Use this many nodes
Returns
*self* for convenience in chaining.
"""
if not (n >= 2):
raise ValueError('must have n >= 2; got... | Set the code to use trapezoidal integration.
**Call signature**
*n*
Use this many nodes
Returns
*self* for convenience in chaining. |
def generateNamespaceChildrenString(self, nspace):
'''
Helper method for :func:`~exhale.graph.ExhaleRoot.generateSingleNamespace`, and
:func:`~exhale.graph.ExhaleRoot.generateFileNodeDocuments`. Builds the
body text for the namespace node document that links to all of the child
... | Helper method for :func:`~exhale.graph.ExhaleRoot.generateSingleNamespace`, and
:func:`~exhale.graph.ExhaleRoot.generateFileNodeDocuments`. Builds the
body text for the namespace node document that links to all of the child
namespaces, structs, classes, functions, typedefs, unions, and variable... |
def cycle(arrays, descs=None, cadence=0.6, toworlds=None,
drawoverlay=None, yflip=False, tostatuses=None, run_main=True,
save_after_viewing=None):
"""Interactively display a series of 2D data arrays.
arrays
An iterable of 2D arrays (a 3D array works).
descs
An iterable of te... | Interactively display a series of 2D data arrays.
arrays
An iterable of 2D arrays (a 3D array works).
descs
An iterable of text descriptions, one for each array
cadence
The time delay before the next array is shown, in seconds.
tostatuses
An iterable of functions that convert cu... |
def pubkey(self, identity, ecdh=False):
"""Return public key."""
_verify_support(identity, ecdh)
return trezor.Trezor.pubkey(self, identity=identity, ecdh=ecdh) | Return public key. |
def send_registration_mail(email, *, request, **kwargs):
"""send_registration_mail(email, *, request, **kwargs)
Sends the registration mail
* ``email``: The email address where the registration link should be
sent to.
* ``request``: A HTTP request instance, used to construct the complete
UR... | send_registration_mail(email, *, request, **kwargs)
Sends the registration mail
* ``email``: The email address where the registration link should be
sent to.
* ``request``: A HTTP request instance, used to construct the complete
URL (including protocol and domain) for the registration link.
... |
def setEnv(self, name, value=None):
"""
Set an environment variable for the worker process before it is launched. The worker
process will typically inherit the environment of the machine it is running on but this
method makes it possible to override specific variables in that inherited e... | Set an environment variable for the worker process before it is launched. The worker
process will typically inherit the environment of the machine it is running on but this
method makes it possible to override specific variables in that inherited environment
before the worker is launched. Note t... |
def _read_para_cert(self, code, cbit, clen, *, desc, length, version):
"""Read HIP CERT parameter.
Structure of HIP CERT parameter [RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
... | Read HIP CERT parameter.
Structure of HIP CERT parameter [RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
... |
def load_vocab(fin):
"""
Load vocabulary from vocab file created by word2vec with
``-save-vocab <file>`` option.
Args:
fin (File): File-like object to read from.
encoding (bytes): Encoding of the input file as defined in ``codecs``
module of Python standard library.
... | Load vocabulary from vocab file created by word2vec with
``-save-vocab <file>`` option.
Args:
fin (File): File-like object to read from.
encoding (bytes): Encoding of the input file as defined in ``codecs``
module of Python standard library.
errors (bytes): Set the error han... |
def subsol(datetime):
"""Finds subsolar geocentric latitude and longitude.
Parameters
==========
datetime : :class:`datetime.datetime`
Returns
=======
sbsllat : float
Latitude of subsolar point
sbsllon : float
Longitude of subsolar point
Notes
=====
Based o... | Finds subsolar geocentric latitude and longitude.
Parameters
==========
datetime : :class:`datetime.datetime`
Returns
=======
sbsllat : float
Latitude of subsolar point
sbsllon : float
Longitude of subsolar point
Notes
=====
Based on formulas in Astronomical Al... |
def circos_radius(n_nodes, node_r):
"""
Automatically computes the origin-to-node centre radius of the Circos plot
using the triangle equality sine rule.
a / sin(A) = b / sin(B) = c / sin(C)
:param n_nodes: the number of nodes in the plot.
:type n_nodes: int
:param node_r: the radius of ea... | Automatically computes the origin-to-node centre radius of the Circos plot
using the triangle equality sine rule.
a / sin(A) = b / sin(B) = c / sin(C)
:param n_nodes: the number of nodes in the plot.
:type n_nodes: int
:param node_r: the radius of each node.
:type node_r: float
:returns: O... |
async def send_contact(self, phone_number: base.String,
first_name: base.String, last_name: typing.Union[base.String, None] = None,
disable_notification: typing.Union[base.Boolean, None] = None,
reply_markup=None,
... | Use this method to send phone contacts.
Source: https://core.telegram.org/bots/api#sendcontact
:param phone_number: Contact's phone number
:type phone_number: :obj:`base.String`
:param first_name: Contact's first name
:type first_name: :obj:`base.String`
:param last_nam... |
def rlzs(self):
"""
:returns: an array of realizations
"""
tups = [(r.ordinal, r.uid, r.weight['weight'])
for r in self.get_rlzs_assoc().realizations]
return numpy.array(tups, rlz_dt) | :returns: an array of realizations |
def init_parser(self):
"""
Init command line parser
:return:
"""
parser = argparse.ArgumentParser(description='ROCA Fingerprinter')
parser.add_argument('--tmp', dest='tmp_dir', default='.',
help='Temporary dir for subprocessing (e.g. APK parsi... | Init command line parser
:return: |
def sha1_digest(instr):
'''
Generate an sha1 hash of a given string.
'''
if six.PY3:
b = salt.utils.stringutils.to_bytes(instr)
return hashlib.sha1(b).hexdigest()
return hashlib.sha1(instr).hexdigest() | Generate an sha1 hash of a given string. |
def get_value(self, default=None):
"""Get int from widget.
Parameters
----------
default : list
list with widgets
Returns
-------
list
list that might contain int or str or float etc
"""
if default is None:
de... | Get int from widget.
Parameters
----------
default : list
list with widgets
Returns
-------
list
list that might contain int or str or float etc |
def qsize(self):
"""
Returns the number of items currently in the queue
:return: Integer containing size of the queue
:exception: ConnectionError if queue is not connected
"""
if not self.connected:
raise QueueNotConnectedError("Queue is not Connected")
... | Returns the number of items currently in the queue
:return: Integer containing size of the queue
:exception: ConnectionError if queue is not connected |
def routerify(obj):
"""
Scan through attributes of object parameter looking for any which
match a route signature.
A router will be created and added to the object with parameter.
Args:
obj (object): The object (with attributes) from which to
setup a router
Returns:
... | Scan through attributes of object parameter looking for any which
match a route signature.
A router will be created and added to the object with parameter.
Args:
obj (object): The object (with attributes) from which to
setup a router
Returns:
Router: The router created from... |
def view_graph(graph_str, parent=None, prune_to=None):
"""View a graph."""
from rezgui.dialogs.ImageViewerDialog import ImageViewerDialog
from rez.config import config
# check for already written tempfile
h = hash((graph_str, prune_to))
filepath = graph_file_lookup.get(h)
if filepath and no... | View a graph. |
def get_capacity_vol(self, min_voltage=None, max_voltage=None,
use_overall_normalization=True):
"""
Get the volumetric capacity of the electrode.
Args:
min_voltage (float): The minimum allowable voltage for a given
step.
max_volta... | Get the volumetric capacity of the electrode.
Args:
min_voltage (float): The minimum allowable voltage for a given
step.
max_voltage (float): The maximum allowable voltage allowable for a
given step.
use_overall_normalization (booL): If False,... |
def partial_trace(self, qubits: Qubits) -> 'Channel':
"""Return the partial trace over the specified qubits"""
vec = self.vec.partial_trace(qubits)
return Channel(vec.tensor, vec.qubits) | Return the partial trace over the specified qubits |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.