code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_open_port() -> int:
"""
Gets a PORT that will (probably) be available on the machine.
It is possible that in-between the time in which the open PORT of found and when it is used, another process may
bind to it instead.
:return: the (probably) available PORT
"""
free_socket = socket.s... | Gets a PORT that will (probably) be available on the machine.
It is possible that in-between the time in which the open PORT of found and when it is used, another process may
bind to it instead.
:return: the (probably) available PORT |
def set_functions(self, f='a*x*cos(b*x)+c', p='a=-0.2, b, c=3', c=None, bg=None, **kwargs):
"""
Sets the function(s) used to describe the data.
Parameters
----------
f=['a*x*cos(b*x)+c', 'a*x+c']
This can be a string function, a defined function
my_fun... | Sets the function(s) used to describe the data.
Parameters
----------
f=['a*x*cos(b*x)+c', 'a*x+c']
This can be a string function, a defined function
my_function(x,a,b), or a list of some combination
of these two types of objects. The length of such
... |
def _request(self, method, path, data=None, reestablish_session=True):
"""Perform HTTP request for REST API."""
if path.startswith("http"):
url = path # For cases where URL of different form is needed.
else:
url = self._format_path(path)
headers = {"Content-Type... | Perform HTTP request for REST API. |
def encode_timestamp(timestamp: hints.Buffer) -> str:
"""
Encode the given buffer to a :class:`~str` using Base32 encoding.
The given :class:`~bytes` are expected to represent the first 6 bytes of a ULID, which
are a timestamp in milliseconds.
.. note:: This uses an optimized strategy from the `NU... | Encode the given buffer to a :class:`~str` using Base32 encoding.
The given :class:`~bytes` are expected to represent the first 6 bytes of a ULID, which
are a timestamp in milliseconds.
.. note:: This uses an optimized strategy from the `NUlid` project for encoding ULID
bytes specifically and is n... |
def expectScreen(self, filename, maxrms=0):
""" Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image
"""
log.debug('exp... | Wait until the display matches a target image
filename: an image file to read and compare against
maxrms: the maximum root mean square between histograms of the
screen and target image |
def setSubTitle(self, title):
"""
Sets the sub-title for this page to the inputed title.
:param title | <str>
"""
self._subTitleLabel.setText(title)
self._subTitleLabel.adjustSize()
self.adjustMargins() | Sets the sub-title for this page to the inputed title.
:param title | <str> |
def send(self, message_id, args=[], kwargs={}):
"""
Send a message to this state machine.
To send a message to a state machine by its name, use
`stmpy.Driver.send` instead.
"""
self._logger.debug('Send {} in stm {}'.format(message_id, self.id))
self._driver._add_... | Send a message to this state machine.
To send a message to a state machine by its name, use
`stmpy.Driver.send` instead. |
def is_feasible(self, solution):
"""Returns True if the given solution's derivatives may have potential
valid, complete solutions.
"""
newvars = solution.new.keys()
for newvar in newvars:
for c in self._constraints_for_var.get(newvar, []):
values = c.e... | Returns True if the given solution's derivatives may have potential
valid, complete solutions. |
def resize(image, target_size, **kwargs):
"""Resize an ndarray image of rank 3 or 4.
target_size can be a tuple `(width, height)` or scalar `width`."""
if isinstance(target_size, int):
target_size = (target_size, target_size)
if not isinstance(target_size, (list, tuple, np.ndarray)):
m... | Resize an ndarray image of rank 3 or 4.
target_size can be a tuple `(width, height)` or scalar `width`. |
def dhcp_options_exists(dhcp_options_id=None, name=None, dhcp_options_name=None,
tags=None, region=None, key=None, keyid=None, profile=None):
'''
Check if a dhcp option exists.
Returns True if the dhcp option exists; Returns False otherwise.
CLI Example:
.. code-block:: ba... | Check if a dhcp option exists.
Returns True if the dhcp option exists; Returns False otherwise.
CLI Example:
.. code-block:: bash
salt myminion boto_vpc.dhcp_options_exists dhcp_options_id='dhcp-a0bl34pp' |
def preprocess_dict(d):
'''
Preprocess a dict to be used as environment variables.
:param d: dict to be processed
'''
out_env = {}
for k, v in d.items():
if not type(v) in PREPROCESSORS:
raise KeyError('Invalid type in dict: {}'.format(type(v)))
out_env[k] = PREPR... | Preprocess a dict to be used as environment variables.
:param d: dict to be processed |
def signalflow(self, token, endpoint=None, timeout=None, compress=None):
"""Obtain a SignalFlow API client."""
from . import signalflow
compress = compress if compress is not None else self._compress
return signalflow.SignalFlowClient(
token=token,
endpoint=endpoi... | Obtain a SignalFlow API client. |
def _ast_option_group_to_code(self, option_group, **kwargs):
"""Convert an AST option group to python source code."""
lines = ["option("]
lines.extend(self._indent(self._ast_to_code(option_group.expression)))
lines.append(")")
return lines | Convert an AST option group to python source code. |
def resizeToContents(self):
"""
Resizes the list widget to fit its contents vertically.
"""
if self.count():
item = self.item(self.count() - 1)
rect = self.visualItemRect(item)
height = rect.bottom() + 8
height = max(28, height)
... | Resizes the list widget to fit its contents vertically. |
def contigs_to_positions(contigs, binning=10000):
"""Build positions from contig labels
From a list of contig labels and a binning parameter,
build a list of positions that's essentially a
concatenation of linspaces with step equal to the
binning.
Parameters
----------
contigs : list o... | Build positions from contig labels
From a list of contig labels and a binning parameter,
build a list of positions that's essentially a
concatenation of linspaces with step equal to the
binning.
Parameters
----------
contigs : list or array_like
The list of contig labels, must be s... |
def logical_chassis_fwdl_sanity_input_cluster_options_auto_activate_auto_activate(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logical_chassis_fwdl_sanity = ET.Element("logical_chassis_fwdl_sanity")
config = logical_chassis_fwdl_sanity
input =... | Auto Generated Code |
def _sample_orthonormal_to(mu):
"""Sample point on sphere orthogonal to mu."""
v = np.random.randn(mu.shape[0])
proj_mu_v = mu * np.dot(mu, v) / np.linalg.norm(mu)
orthto = v - proj_mu_v
return orthto / np.linalg.norm(orthto) | Sample point on sphere orthogonal to mu. |
def getVersionFromArchiveId(git_archive_id='$Format:%ct %d$'):
""" Extract the tag if a source is from git archive.
When source is exported via `git archive`, the git_archive_id init value is modified
and placeholders are expanded to the "archived" revision:
%ct: committer date, UNIX t... | Extract the tag if a source is from git archive.
When source is exported via `git archive`, the git_archive_id init value is modified
and placeholders are expanded to the "archived" revision:
%ct: committer date, UNIX timestamp
%d: ref names, like the --decorate option of git-l... |
def normalize(text, mode='NFKC', ignore=''):
"""Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana,
Full-width (Zenkaku) ASCII and DIGIT to Half-width (Hankaku) ASCII
and DIGIT.
Additionally, Full-width wave dash (〜) etc. are normalized
Parameters
----------
text : str
... | Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana,
Full-width (Zenkaku) ASCII and DIGIT to Half-width (Hankaku) ASCII
and DIGIT.
Additionally, Full-width wave dash (〜) etc. are normalized
Parameters
----------
text : str
Source string.
mode : str
Unicode... |
def list_cubes(self):
""" List all available JSON files. """
for file_name in os.listdir(self.directory):
if '.' in file_name:
name, ext = file_name.rsplit('.', 1)
if ext.lower() == 'json':
yield name | List all available JSON files. |
def _sm_to_pain(self, *args, **kwargs):
"""
Start the blockade event
"""
_logger.info("Starting chaos for blockade %s" % self._blockade_name)
self._do_blockade_event()
# start the timer to end the pain
millisec = random.randint(self._run_min_time, self._run_max_ti... | Start the blockade event |
def field_exists(self, well_x, well_y, field_x, field_y):
"Check if field exists ScanFieldArray."
return self.field(well_x, well_y, field_x, field_y) != None | Check if field exists ScanFieldArray. |
def _get_underlying_data(self, instance):
"""Return data from raw data store, rather than overridden
__get__ methods. Should NOT be overwritten.
"""
self._touch(instance)
return self.data.get(instance, None) | Return data from raw data store, rather than overridden
__get__ methods. Should NOT be overwritten. |
def ssh(cmd=''):
'''
SSH into the server(s) (sequentially if more than one)
Args:
cmd (str) ='': Command to run on the server
'''
with settings(warn_only=True):
local('ssh -A -o StrictHostKeyChecking=no -i "%s" %s@%s "%s"' % (
env.key_filename, env.user, env.host, cmd)) | SSH into the server(s) (sequentially if more than one)
Args:
cmd (str) ='': Command to run on the server |
def string(value,
allow_empty = False,
coerce_value = False,
minimum_length = None,
maximum_length = None,
whitespace_padding = False,
**kwargs):
"""Validate that ``value`` is a valid string.
:param value: The value to validate.
:type value:... | Validate that ``value`` is a valid string.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :obj:`None <python:None>`
:param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value``
is empty. If ``False``, raises a
:class:`EmptyValueError <validator... |
def add(ctx, alias, mapping, backend):
"""
Add a new alias to your configuration file.
"""
if not backend:
backends_list = ctx.obj['settings'].get_backends()
if len(backends_list) > 1:
raise click.UsageError(
"You're using more than 1 backend. Please set the b... | Add a new alias to your configuration file. |
def login(self, verify_code=''):
"""
登录微信公众平台
注意在实例化 ``WechatExt`` 的时候,如果没有传入 ``token`` 及 ``cookies`` ,将会自动调用该方法,无需手动调用
当且仅当捕获到 ``NeedLoginError`` 异常时才需要调用此方法进行登录重试
:param verify_code: 验证码, 不传入则为无验证码
:raises LoginVerifyCodeError: 需要验证码或验证码出错,该异常为 ``LoginError`` 的子类
... | 登录微信公众平台
注意在实例化 ``WechatExt`` 的时候,如果没有传入 ``token`` 及 ``cookies`` ,将会自动调用该方法,无需手动调用
当且仅当捕获到 ``NeedLoginError`` 异常时才需要调用此方法进行登录重试
:param verify_code: 验证码, 不传入则为无验证码
:raises LoginVerifyCodeError: 需要验证码或验证码出错,该异常为 ``LoginError`` 的子类
:raises LoginError: 登录出错异常,异常内容为微信服务器响应的内容,可作为日志记录下... |
def fit(self, X, y=None, **kwargs):
"""
The fit method is the primary drawing input for the dispersion
visualization.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generator
that yields a list of docume... | The fit method is the primary drawing input for the dispersion
visualization.
Parameters
----------
X : list or generator
Should be provided as a list of documents or a generator
that yields a list of documents that contain a list of
words in the ord... |
def pypi():
'''Build package and upload to pypi.'''
if query_yes_no('version updated in setup.py?'):
print(cyan('\n## clean-up\n'))
execute(clean)
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons()
# e.g. highest_minor: '3.6'
highest_minor... | Build package and upload to pypi. |
def verify_docker_image_sha(chain, link):
"""Verify that built docker shas match the artifact.
Args:
chain (ChainOfTrust): the chain we're operating on.
link (LinkOfTrust): the task link we're checking.
Raises:
CoTError: on failure.
"""
cot = link.cot
task = link.task
... | Verify that built docker shas match the artifact.
Args:
chain (ChainOfTrust): the chain we're operating on.
link (LinkOfTrust): the task link we're checking.
Raises:
CoTError: on failure. |
def write_to_file(self, file_path='', date=(datetime.date.today()),
organization='llnl'):
"""
Writes stargazers data to file.
"""
with open(file_path, 'w+') as out:
out.write('date,organization,stargazers\n')
sorted_stargazers = sorted(self.stargazers)#sor... | Writes stargazers data to file. |
def is_text(bytesio):
"""Return whether the first KB of contents seems to be binary.
This is roughly based on libmagic's binary/text detection:
https://github.com/file/file/blob/df74b09b9027676088c797528edcaae5a9ce9ad0/src/encoding.c#L203-L228
"""
text_chars = (
bytearray([7, 8, 9, 10, 11, ... | Return whether the first KB of contents seems to be binary.
This is roughly based on libmagic's binary/text detection:
https://github.com/file/file/blob/df74b09b9027676088c797528edcaae5a9ce9ad0/src/encoding.c#L203-L228 |
def load(self, file_key):
"""Load the data."""
var = self.sd.select(file_key)
data = xr.DataArray(from_sds(var, chunks=CHUNK_SIZE),
dims=['y', 'x']).astype(np.float32)
data = data.where(data != var._FillValue)
try:
data = data * np.float32(... | Load the data. |
def from_url(cls, url):
"""
Given a resource uri, return an instance of that cache initialized with the given
parameters. An example usage:
>>> from aiocache import Cache
>>> Cache.from_url('memory://')
<aiocache.backends.memory.SimpleMemoryCache object at 0x1081dbb00>
... | Given a resource uri, return an instance of that cache initialized with the given
parameters. An example usage:
>>> from aiocache import Cache
>>> Cache.from_url('memory://')
<aiocache.backends.memory.SimpleMemoryCache object at 0x1081dbb00>
a more advanced usage using querypar... |
def draw_on_image(self, image,
color=(0, 255, 0), color_lines=None, color_points=None,
alpha=1.0, alpha_lines=None, alpha_points=None,
size=1, size_lines=None, size_points=None,
antialiased=True,
raise_if_out_o... | Draw all line strings onto a given image.
Parameters
----------
image : ndarray
The `(H,W,C)` `uint8` image onto which to draw the line strings.
color : iterable of int, optional
Color to use as RGB, i.e. three values.
The color of the lines and poin... |
def _get_plugin_module_paths(self, plugin_dir):
''' Return a list of every module in `plugin_dir`. '''
filepaths = [
fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True)
if not fp.endswith('__init__.py')
]
rel_paths = [re.sub(plugin_dir.rstrip('... | Return a list of every module in `plugin_dir`. |
def check_learns_zero_output_rnn(model, sgd, X, Y, initial_hidden=None):
"""Check we can learn to output a zero vector"""
outputs, get_dX = model.begin_update(X, initial_hidden)
Yh, h_n = outputs
tupleDy = (Yh - Y, h_n)
dX = get_dX(tupleDy, sgd=sgd)
prev = numpy.abs(Yh.sum())
print(prev)
... | Check we can learn to output a zero vector |
def uri(self, value):
"""Set new uri value in record.
It will not change the location of the underlying file!
"""
jsonpointer.set_pointer(self.record, self.pointer, value) | Set new uri value in record.
It will not change the location of the underlying file! |
def A(g,i):
"""recursively constructs A line for g; i = len(g)-1"""
g1 = g&(2**i)
if i:
n = Awidth(i)
An = A(g,i-1)
if g1:
return An<<n | An
else:
return int('1'*n,2)<<n | An
else:
if g1:
return int('00',2)
else:
... | recursively constructs A line for g; i = len(g)-1 |
def close(self):
"""Close open file handle(s)."""
for tif in self._files.values():
tif.filehandle.close()
self._files = {} | Close open file handle(s). |
def _set_bottomMargin(self, value):
"""
value will be an int or float.
Subclasses may override this method.
"""
diff = value - self.bottomMargin
self.moveBy((0, diff))
self.height += diff | value will be an int or float.
Subclasses may override this method. |
def clear_high_level_pars(self):
"""
clears all high level pars display boxes
"""
for val in ['mean_type', 'dec', 'inc', 'alpha95', 'K', 'R', 'n_lines', 'n_planes']:
COMMAND = """self.%s_window.SetValue("")""" % (val)
exec(COMMAND)
if self.ie_open:
... | clears all high level pars display boxes |
def serialize_instance(instance):
'''
Serialize an *instance* from a metamodel.
'''
attr_count = 0
metaclass = xtuml.get_metaclass(instance)
s = 'INSERT INTO %s VALUES (' % metaclass.kind
for name, ty in metaclass.attributes:
value = getattr(instance, name)
s += ... | Serialize an *instance* from a metamodel. |
def set_form_widgets_attrs(form, attrs):
"""Applies a given HTML attributes to each field widget of a given form.
Example:
set_form_widgets_attrs(my_form, {'class': 'clickable'})
"""
for _, field in form.fields.items():
attrs_ = dict(attrs)
for name, val in attrs.items():
... | Applies a given HTML attributes to each field widget of a given form.
Example:
set_form_widgets_attrs(my_form, {'class': 'clickable'}) |
def create_unique_transfer_operation_id(src_ase, dst_ase):
# type: (blobxfer.models.azure.StorageEntity,
# blobxfer.models.azure.StorageEntity) -> str
"""Create a unique transfer operation id
:param blobxfer.models.azure.StorageEntity src_ase: src storage entity
:param blo... | Create a unique transfer operation id
:param blobxfer.models.azure.StorageEntity src_ase: src storage entity
:param blobxfer.models.azure.StorageEntity dst_ase: dst storage entity
:rtype: str
:return: unique transfer id |
def dyn_attr(self, dev_list):
"""Invoked to create dynamic attributes for the given devices.
Default implementation calls
:meth:`TT.initialize_dynamic_attributes` for each device
:param dev_list: list of devices
:type dev_list: :class:`tango.DeviceImpl`"""
for dev in de... | Invoked to create dynamic attributes for the given devices.
Default implementation calls
:meth:`TT.initialize_dynamic_attributes` for each device
:param dev_list: list of devices
:type dev_list: :class:`tango.DeviceImpl` |
def get_parcel(resource_root, product, version, cluster_name="default"):
"""
Lookup a parcel by name
@param resource_root: The root Resource object.
@param product: Parcel product name
@param version: Parcel version
@param cluster_name: Cluster name
@return: An ApiService object
"""
return _get_parcel... | Lookup a parcel by name
@param resource_root: The root Resource object.
@param product: Parcel product name
@param version: Parcel version
@param cluster_name: Cluster name
@return: An ApiService object |
def LdKL_dot(self, v, v1=None):
"""
Implements L(∂K)Lᵀv.
The array v can have one or two dimensions and the first dimension has to have
size n⋅p.
Let vec(V) = v. We have
L(∂K)Lᵀ⋅v = ((Lₕ∂C₀Lₕᵀ) ⊗ (LₓGGᵀLₓᵀ))vec(V) = vec(LₓGGᵀLₓᵀVLₕ∂C₀Lₕᵀ),
when the derivat... | Implements L(∂K)Lᵀv.
The array v can have one or two dimensions and the first dimension has to have
size n⋅p.
Let vec(V) = v. We have
L(∂K)Lᵀ⋅v = ((Lₕ∂C₀Lₕᵀ) ⊗ (LₓGGᵀLₓᵀ))vec(V) = vec(LₓGGᵀLₓᵀVLₕ∂C₀Lₕᵀ),
when the derivative is over the parameters of C₀. Similarly,
... |
def make_channel(name, samples, data=None, verbose=False):
"""
Create a Channel from a list of Samples
"""
if verbose:
llog = log['make_channel']
llog.info("creating channel {0}".format(name))
# avoid segfault if name begins with a digit by using "channel_" prefix
chan = Channel(... | Create a Channel from a list of Samples |
def OpenEnumerateInstancePaths(self, ClassName, namespace=None,
FilterQueryLanguage=None, FilterQuery=None,
OperationTimeout=None, ContinueOnError=None,
MaxObjectCount=None, **extra):
# pylint: disable=inval... | Open an enumeration session to enumerate the instance paths of
instances of a class (including instances of its subclasses) in
a namespace.
*New in pywbem 0.9.*
This method performs the OpenEnumerateInstancePaths operation
(see :term:`DSP0200`). See :ref:`WBEM operations` for a... |
def move_right(self):
"""Make the drone move right."""
self.at(ardrone.at.pcmd, True, self.speed, 0, 0, 0) | Make the drone move right. |
def _init_hex(self, hexval: str) -> None:
""" Initialize from a hex value string. """
self.hexval = hex2termhex(fix_hex(hexval))
self.code = hex2term(self.hexval)
self.rgb = hex2rgb(self.hexval) | Initialize from a hex value string. |
def separated(p, sep, mint, maxt=None, end=None):
'''Repeat a parser `p` separated by `s` between `mint` and `maxt` times.
When `end` is None, a trailing separator is optional.
When `end` is True, a trailing separator is required.
When `end` is False, a trailing separator is not allowed.
MATCHES AS ... | Repeat a parser `p` separated by `s` between `mint` and `maxt` times.
When `end` is None, a trailing separator is optional.
When `end` is True, a trailing separator is required.
When `end` is False, a trailing separator is not allowed.
MATCHES AS MUCH AS POSSIBLE.
Return list of values returned by `... |
def get_submission_filenames(self, tournament=None, round_num=None):
"""Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user... | Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user filenames (`dict`)
Each filenames in the list as the following str... |
def window_size(self):
""" returns render window size """
the_size = self.app_window.baseSize()
return the_size.width(), the_size.height() | returns render window size |
def Trim(lst, limit):
"""Trims a given list so that it is not longer than given limit.
Args:
lst: A list to trim.
limit: A maximum number of elements in the list after trimming.
Returns:
A suffix of the input list that was trimmed.
"""
limit = max(0, limit)
clipping = lst[limit:]
del lst[li... | Trims a given list so that it is not longer than given limit.
Args:
lst: A list to trim.
limit: A maximum number of elements in the list after trimming.
Returns:
A suffix of the input list that was trimmed. |
def validate_username(username):
""" Validate the new username. If the username is invalid, raises
:py:exc:`UsernameInvalid`.
:param username: Username to validate.
"""
# Check username looks ok
if not username.islower():
raise UsernameInvalid(six.u('Username must be all lowercase'))
... | Validate the new username. If the username is invalid, raises
:py:exc:`UsernameInvalid`.
:param username: Username to validate. |
def switch(self):
"""Switch if time for eAgc has come"""
t = self.system.dae.t
for idx in range(0, self.n):
if t >= self.tl[idx]:
if self.en[idx] == 0:
self.en[idx] = 1
logger.info(
'Extended ACE <{}> act... | Switch if time for eAgc has come |
def get_object(model, meteor_id, *args, **kwargs):
"""Return an object for the given meteor_id."""
# Django model._meta is now public API -> pylint: disable=W0212
meta = model._meta
if isinstance(meta.pk, AleaIdField):
# meteor_id is the primary key
return model.objects.filter(*args, **k... | Return an object for the given meteor_id. |
def _send_request(self, path, data, method):
"""
Uses the HTTP transport to query the Route53 API. Runs the response
through lxml's parser, before we hand it off for further picking
apart by our call-specific parsers.
:param str path: The RESTful path to tack on to the :py:attr:... | Uses the HTTP transport to query the Route53 API. Runs the response
through lxml's parser, before we hand it off for further picking
apart by our call-specific parsers.
:param str path: The RESTful path to tack on to the :py:attr:`endpoint`.
:param data: The params to send along with th... |
def add_tags(self):
"""Add a Vorbis comment block to the file."""
if self.tags is None:
self.tags = VCFLACDict()
self.metadata_blocks.append(self.tags)
else:
raise FLACVorbisError("a Vorbis comment already exists") | Add a Vorbis comment block to the file. |
def filter(objects, Type=None, min=-1, max=-1): #PYCHOK muppy filter
"""Filter objects.
The filter can be by type, minimum size, and/or maximum size.
Keyword arguments:
Type -- object type to filter by
min -- minimum object size
max -- maximum object size
"""
res = []
if min > max... | Filter objects.
The filter can be by type, minimum size, and/or maximum size.
Keyword arguments:
Type -- object type to filter by
min -- minimum object size
max -- maximum object size |
async def query_presence(self, query_presence_request):
"""Return presence status for a list of users."""
response = hangouts_pb2.QueryPresenceResponse()
await self._pb_request('presence/querypresence',
query_presence_request, response)
return response | Return presence status for a list of users. |
def HashFilePath(self, path, byte_count):
"""Updates underlying hashers with file on a given path.
Args:
path: A path to the file that is going to be fed to the hashers.
byte_count: A maximum numbers of bytes that are going to be processed.
"""
with open(path, "rb") as fd:
self.HashFi... | Updates underlying hashers with file on a given path.
Args:
path: A path to the file that is going to be fed to the hashers.
byte_count: A maximum numbers of bytes that are going to be processed. |
def queue_resize(self):
"""request the element to re-check it's child sprite sizes"""
self._children_resize_queued = True
parent = getattr(self, "parent", None)
if parent and isinstance(parent, graphics.Sprite) and hasattr(parent, "queue_resize"):
parent.queue_resize() | request the element to re-check it's child sprite sizes |
def resubmit(self, job_ids = None, also_success = False, running_jobs = False, new_command=None, keep_logs=False, **kwargs):
"""Re-submit jobs automatically"""
self.lock()
# iterate over all jobs
jobs = self.get_jobs(job_ids)
if new_command is not None:
if len(jobs) == 1:
jobs[0].set_c... | Re-submit jobs automatically |
def hdr(data, filename):
"""
write ENVI header files
Parameters
----------
data: str or dict
the file or dictionary to get the info from
filename: str
the HDR file to write
Returns
-------
"""
hdrobj = data if isinstance(data, HDRobject) else HDRobject(data)
... | write ENVI header files
Parameters
----------
data: str or dict
the file or dictionary to get the info from
filename: str
the HDR file to write
Returns
------- |
def init(self, xml, port, server=None,
server2=None, port2=None,
role=0, exp_uid=None, episode=0,
action_filter=None, resync=0, step_options=0, action_space=None):
""""Initialize a Malmo environment.
xml - the mission xml.
port - the MalmoEnv servic... | Initialize a Malmo environment.
xml - the mission xml.
port - the MalmoEnv service's port.
server - the MalmoEnv service address. Default is localhost.
server2 - the MalmoEnv service address for given role if not 0.
port2 - the MalmoEnv service port for given ... |
def coupling_to_arc(coupling_map:List[List[int]]) -> Architecture:
"""
Produces a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture` corresponding to a (directed) coupling map,
stating the pairs of qubits between which two-qubit interactions
(e.g. CXs) can be applied.
:param coupling... | Produces a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture` corresponding to a (directed) coupling map,
stating the pairs of qubits between which two-qubit interactions
(e.g. CXs) can be applied.
:param coupling_map: Pairs of indices where each pair [control, target]
permits the use of... |
def _get_stddevs(self, C, rup, shape, stddev_types):
"""
Return standard deviations as defined in p. 971.
"""
weight = self._compute_weight_std(C, rup.mag)
std_intra = weight * C["sd1"] * np.ones(shape)
std_inter = weight * C["sd2"] * np.ones(shape)
... | Return standard deviations as defined in p. 971. |
def predict_mu(self, X):
"""
preduct expected value of target given model and input X
Parameters
---------
X : array-like of shape (n_samples, m_features),
containing the input dataset
Returns
-------
y : np.array of shape (n_samples,)
... | preduct expected value of target given model and input X
Parameters
---------
X : array-like of shape (n_samples, m_features),
containing the input dataset
Returns
-------
y : np.array of shape (n_samples,)
containing expected values under the mo... |
def save_auxiliary_files(self, layer, destination):
"""Save auxiliary files when using the 'save as' function.
If some auxiliary files (.xml, .json) exist, this function will
copy them when the 'save as' function is used on the layer.
:param layer: The layer which has been saved as.
... | Save auxiliary files when using the 'save as' function.
If some auxiliary files (.xml, .json) exist, this function will
copy them when the 'save as' function is used on the layer.
:param layer: The layer which has been saved as.
:type layer: QgsMapLayer
:param destination: The... |
def nnz_obs(self):
""" get the number of non-zero weighted observations
Returns
-------
nnz_obs : int
the number of non-zeros weighted observations
"""
nnz = 0
for w in self.observation_data.weight:
if w > 0.0:
nnz += 1
... | get the number of non-zero weighted observations
Returns
-------
nnz_obs : int
the number of non-zeros weighted observations |
def parallel_evaluation_mp(candidates, args):
"""Evaluate the candidates in parallel using ``multiprocessing``.
This function allows parallel evaluation of candidate solutions.
It uses the standard multiprocessing library to accomplish the
parallelization. The function assigns the evaluation of each
... | Evaluate the candidates in parallel using ``multiprocessing``.
This function allows parallel evaluation of candidate solutions.
It uses the standard multiprocessing library to accomplish the
parallelization. The function assigns the evaluation of each
candidate to its own job, all of which are then di... |
def batch_filter(self, zs, Fs=None, Qs=None, Hs=None,
Rs=None, Bs=None, us=None, update_first=False,
saver=None):
""" Batch processes a sequences of measurements.
Parameters
----------
zs : list-like
list of measurements at each tim... | Batch processes a sequences of measurements.
Parameters
----------
zs : list-like
list of measurements at each time step `self.dt`. Missing
measurements must be represented by `None`.
Fs : None, list-like, default=None
optional value or list of valu... |
def getSiblings(self, textId, subreference):
""" Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:param reference: CapitainsCtsPassage Reference
:return: GetPrevNextUrn request response from the endpoint
"""
textId = "{}:{}".format(textI... | Retrieve the siblings of a textual node
:param textId: CtsTextMetadata Identifier
:param reference: CapitainsCtsPassage Reference
:return: GetPrevNextUrn request response from the endpoint |
def acknowledge_host_problem(self, host, sticky, notify, author, comment):
"""Acknowledge a host problem
Format of the line that triggers function call::
ACKNOWLEDGE_HOST_PROBLEM;<host_name>;<sticky>;<notify>;<persistent:obsolete>;<author>;
<comment>
:param host: host to acknow... | Acknowledge a host problem
Format of the line that triggers function call::
ACKNOWLEDGE_HOST_PROBLEM;<host_name>;<sticky>;<notify>;<persistent:obsolete>;<author>;
<comment>
:param host: host to acknowledge the problem
:type host: alignak.objects.host.Host
:param sticky:... |
def create_url(urlbase, urlargd, escape_urlargd=True, urlhash=None):
"""Creates a W3C compliant URL. Output will look like this:
'urlbase?param1=value1&param2=value2'
@param urlbase: base url (e.g. config.CFG_SITE_URL/search)
@param urlargd: dictionary of parameters. (e.g. p={'recid':3, 'of'='hb'}
... | Creates a W3C compliant URL. Output will look like this:
'urlbase?param1=value1&param2=value2'
@param urlbase: base url (e.g. config.CFG_SITE_URL/search)
@param urlargd: dictionary of parameters. (e.g. p={'recid':3, 'of'='hb'}
@param escape_urlargd: boolean indicating if the function should escape
... |
def is_python_binding_installed_on_pip(self):
"""Check if the Python binding has already installed."""
pip_version = self._get_pip_version()
Log.debug('Pip version: {0}'.format(pip_version))
pip_major_version = int(pip_version.split('.')[0])
installed = False
# --format ... | Check if the Python binding has already installed. |
def assertFileSizeLess(self, filename, size, msg=None):
'''Fail if ``filename``'s size is not less than ``size`` as
determined by the '<' operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
If not provided, the... | Fail if ``filename``'s size is not less than ``size`` as
determined by the '<' operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
If not provided, the :mod:`marbles.mixins` or
:mod:`unittest` standard mess... |
def _printf(self, *args, **kwargs):
'''Print to configured stream if any is specified and the file argument
is not already set for this specific call.
'''
if self._stream and not kwargs.get('file'):
kwargs['file'] = self._stream
_printf(*args, **kwargs) | Print to configured stream if any is specified and the file argument
is not already set for this specific call. |
def _get_deploy_image_params(data_holder, host_info, vm_name):
"""
:type data_holder: models.vCenterVMFromImageResourceModel.vCenterVMFromImageResourceModel
"""
image_params = OvfImageParams()
if hasattr(data_holder, 'vcenter_image_arguments') and data_holder.vcenter_image_argume... | :type data_holder: models.vCenterVMFromImageResourceModel.vCenterVMFromImageResourceModel |
def _asciify_dict(data):
""" Ascii-fies dict keys and values """
ret = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = _remove_accents(key)
key = key.encode('utf-8')
# # note new if
if isinstance(value, unicode):
value... | Ascii-fies dict keys and values |
def do_ranges_intersect(begin, end, old_begin, old_end):
"""
Determine if the two given memory address ranges intersect.
@type begin: int
@param begin: Start address of the first range.
@type end: int
@param end: End address of the first range.
@type old_beg... | Determine if the two given memory address ranges intersect.
@type begin: int
@param begin: Start address of the first range.
@type end: int
@param end: End address of the first range.
@type old_begin: int
@param old_begin: Start address of the second range.
... |
def merge_and_fit(self, segment):
""" Merges another segment with this one, ordering the points based on a
distance heuristic
Args:
segment (:obj:`Segment`): Segment to merge with
Returns:
:obj:`Segment`: self
"""
self.points = sort_segment_po... | Merges another segment with this one, ordering the points based on a
distance heuristic
Args:
segment (:obj:`Segment`): Segment to merge with
Returns:
:obj:`Segment`: self |
def fill_subparser(subparser):
"""Sets up a subparser to convert YouTube audio files.
Adds the compulsory `--youtube-id` flag as well as the optional
`sample` and `channels` flags.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `youtube_audio`... | Sets up a subparser to convert YouTube audio files.
Adds the compulsory `--youtube-id` flag as well as the optional
`sample` and `channels` flags.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `youtube_audio` command. |
def open(self, name, flags, preferred_fd=None):
"""
Open a symbolic file. Basically open(2).
:param name: Path of the symbolic file, as a string or bytes.
:type name: string or bytes
:param flags: File operation flags, a bitfield of constants fro... | Open a symbolic file. Basically open(2).
:param name: Path of the symbolic file, as a string or bytes.
:type name: string or bytes
:param flags: File operation flags, a bitfield of constants from open(2), as an AST
:param preferred_fd: Assign this fd ... |
def sub_path(self):
"""The path of the partition source, excluding the bundle path parts.
Includes the revision.
"""
try:
return os.path.join(*(self._local_parts()))
except TypeError as e:
raise TypeError(
"Path failed for partition {} :... | The path of the partition source, excluding the bundle path parts.
Includes the revision. |
def _sortkey(self, key='uri', language='any'):
'''
Provide a single sortkey for this conceptscheme.
:param string key: Either `uri`, `label` or `sortlabel`.
:param string language: The preferred language to receive the label in
if key is `label` or `sortlabel`. This should b... | Provide a single sortkey for this conceptscheme.
:param string key: Either `uri`, `label` or `sortlabel`.
:param string language: The preferred language to receive the label in
if key is `label` or `sortlabel`. This should be a valid IANA language tag.
:rtype: :class:`str` |
def _bundle_exists(self, path):
"""Checks if a bundle exists at the provided path
:param path: Bundle path
:return: bool
"""
for attached_bundle in self._attached_bundles:
if path == attached_bundle.path:
return True
return False | Checks if a bundle exists at the provided path
:param path: Bundle path
:return: bool |
def QueryUsers(self, database_link, query, options=None):
"""Queries users in a database.
:param str database_link:
The link to the database.
:param (str or dict) query:
:param dict options:
The request options for the request.
:return:
Query... | Queries users in a database.
:param str database_link:
The link to the database.
:param (str or dict) query:
:param dict options:
The request options for the request.
:return:
Query Iterable of Users.
:rtype:
query_iterable.Que... |
def from_environment_or_defaults(cls, environment=None):
"""Create a Run object taking values from the local environment where possible.
The run ID comes from WANDB_RUN_ID or is randomly generated.
The run mode ("dryrun", or "run") comes from WANDB_MODE or defaults to "dryrun".
The run ... | Create a Run object taking values from the local environment where possible.
The run ID comes from WANDB_RUN_ID or is randomly generated.
The run mode ("dryrun", or "run") comes from WANDB_MODE or defaults to "dryrun".
The run directory comes from WANDB_RUN_DIR or is generated from the run ID.
... |
def clean(tf_matrix,
tf_matrix_gene_names,
target_gene_name):
"""
:param tf_matrix: numpy array. The full transcription factor matrix.
:param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns.
:param target_gene_name: the target... | :param tf_matrix: numpy array. The full transcription factor matrix.
:param tf_matrix_gene_names: the full list of transcription factor names, corresponding to the tf_matrix columns.
:param target_gene_name: the target gene to remove from the tf_matrix and tf_names.
:return: a tuple of (matrix, names) equal... |
def runExperiment(args, model=None):
"""
Run a single OPF experiment.
.. note:: The caller is responsible for initializing python logging before
calling this function (e.g., import :mod:`nupic.support`;
:meth:`nupic.support.initLogging`)
See also: :meth:`.initExperimentPrng`.
:param args: (string... | Run a single OPF experiment.
.. note:: The caller is responsible for initializing python logging before
calling this function (e.g., import :mod:`nupic.support`;
:meth:`nupic.support.initLogging`)
See also: :meth:`.initExperimentPrng`.
:param args: (string) Experiment command-line args list. Too see ... |
def debug(self, msg, indent=0, **kwargs):
"""invoke ``self.logger.debug``"""
return self.logger.debug(self._indent(msg, indent), **kwargs) | invoke ``self.logger.debug`` |
def shift (*args):
"""`shift()` returns the leftmost element of `argv`.
`shitf(integer)` return the `integer` leftmost elements of `argv` as a list.
`shift(iterable)` and `shift(iterable, integer)` operate over `iterable`."""
if len(args) > 2:
raise ValueError("shift() takes 0, 1 or 2 arguments.... | `shift()` returns the leftmost element of `argv`.
`shitf(integer)` return the `integer` leftmost elements of `argv` as a list.
`shift(iterable)` and `shift(iterable, integer)` operate over `iterable`. |
def decode_to_unicode(content):
""" decode ISO-8859-1 to unicode, when using sf api """
if content and not isinstance(content, str):
try:
# Try to decode ISO-8859-1 to unicode
return content.decode("ISO-8859-1")
except UnicodeEncodeError:
# Assume content is u... | decode ISO-8859-1 to unicode, when using sf api |
def _render_mail(self, rebuild, success, auto_canceled, manual_canceled):
"""Render and return subject and body of the mail to send."""
subject_template = '%(endstate)s building image %(image_name)s'
body_template = '\n'.join([
'Image Name: %(image_name)s',
'Repositories:... | Render and return subject and body of the mail to send. |
async def _discard(self, path, *, recurse=None, separator=None, cas=None):
"""Deletes the Key
"""
path = "/v1/kv/%s" % path
response = await self._api.delete(path, params={
"cas": cas,
"recurse": recurse,
"separator": separator
})
retur... | Deletes the Key |
def normalize_bbox(bbox, rows, cols):
"""Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates
by image height.
"""
if rows == 0:
raise ValueError('Argument rows cannot be zero')
if cols == 0:
raise ValueError('Argument cols cannot be zero')
... | Normalize coordinates of a bounding box. Divide x-coordinates by image width and y-coordinates
by image height. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.