code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _store_status(self, section, command, name):
"""
Based on new command execution attempt, update instance's
data structures with information about the success/fail status.
Return the result of the execution test.
"""
succeeded = is_command_callable(command, name)
... | Based on new command execution attempt, update instance's
data structures with information about the success/fail status.
Return the result of the execution test. | Below is the the instruction that describes the task:
### Input:
Based on new command execution attempt, update instance's
data structures with information about the success/fail status.
Return the result of the execution test.
### Response:
def _store_status(self, section, command, name):
... |
def debug_transform(ctx, transform, params, value, fields):
"""Runs Canari local transforms in a terminal-friendly fashion."""
from canari.commands.debug_transform import debug_transform
debug_transform(transform, value, fields, params, ctx.project, ctx.config) | Runs Canari local transforms in a terminal-friendly fashion. | Below is the the instruction that describes the task:
### Input:
Runs Canari local transforms in a terminal-friendly fashion.
### Response:
def debug_transform(ctx, transform, params, value, fields):
"""Runs Canari local transforms in a terminal-friendly fashion."""
from canari.commands.debug_transform imp... |
def get_worker_class(worker_class=None):
"""
Return worker class from RQ settings, otherwise return Worker.
If `worker_class` is not None, it is used as an override (can be
python import path as string).
"""
RQ = getattr(settings, 'RQ', {})
if worker_class is None:
worker_class = Wo... | Return worker class from RQ settings, otherwise return Worker.
If `worker_class` is not None, it is used as an override (can be
python import path as string). | Below is the the instruction that describes the task:
### Input:
Return worker class from RQ settings, otherwise return Worker.
If `worker_class` is not None, it is used as an override (can be
python import path as string).
### Response:
def get_worker_class(worker_class=None):
"""
Return worker cl... |
def _can_hold_identifiers_and_holds_name(self, name):
"""
Faster check for ``name in self`` when we know `name` is a Python
identifier (e.g. in NDFrame.__getattr__, which hits this to support
. key lookup). For indexes that can't hold identifiers (everything
but object & categori... | Faster check for ``name in self`` when we know `name` is a Python
identifier (e.g. in NDFrame.__getattr__, which hits this to support
. key lookup). For indexes that can't hold identifiers (everything
but object & categorical) we just return False.
https://github.com/pandas-dev/pandas/i... | Below is the the instruction that describes the task:
### Input:
Faster check for ``name in self`` when we know `name` is a Python
identifier (e.g. in NDFrame.__getattr__, which hits this to support
. key lookup). For indexes that can't hold identifiers (everything
but object & categorical) ... |
def fetchDynamicProperties(target, encoding):
"""
Sends a gooey-seed-ui request to the client program it retrieve
dynamically generated defaults with which to seed the UI
"""
cmd = '{} {}'.format(target, 'gooey-seed-ui --ignore-gooey')
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, s... | Sends a gooey-seed-ui request to the client program it retrieve
dynamically generated defaults with which to seed the UI | Below is the the instruction that describes the task:
### Input:
Sends a gooey-seed-ui request to the client program it retrieve
dynamically generated defaults with which to seed the UI
### Response:
def fetchDynamicProperties(target, encoding):
"""
Sends a gooey-seed-ui request to the client progra... |
def chmod(self, path, mode):
"""
Change the mode (permissions) of a file. The permissions are
unix-style and identical to those used by python's C{os.chmod}
function.
@param path: path of the file to change the permissions of
@type path: str
@param mode: new per... | Change the mode (permissions) of a file. The permissions are
unix-style and identical to those used by python's C{os.chmod}
function.
@param path: path of the file to change the permissions of
@type path: str
@param mode: new permissions
@type mode: int | Below is the the instruction that describes the task:
### Input:
Change the mode (permissions) of a file. The permissions are
unix-style and identical to those used by python's C{os.chmod}
function.
@param path: path of the file to change the permissions of
@type path: str
... |
def get_whole_assignment_expression(line, varname, seq_type):
"""
Example:
line = "x = Container(cargs=(a, b, c))"
varname = cargs
delimiter pair = "()"
return "a, b, c"
:return:
"""
tokens = list(tk.generate_tokens(io.StringIO(line).readline))
if issubclass(seq_type, tuple)... | Example:
line = "x = Container(cargs=(a, b, c))"
varname = cargs
delimiter pair = "()"
return "a, b, c"
:return: | Below is the the instruction that describes the task:
### Input:
Example:
line = "x = Container(cargs=(a, b, c))"
varname = cargs
delimiter pair = "()"
return "a, b, c"
:return:
### Response:
def get_whole_assignment_expression(line, varname, seq_type):
"""
Example:
line = "x = ... |
def stop(self, timeout=None):
"""
Stops the task thread. Synchronous!
"""
with self._lock:
if self._thread:
self._queue.put_nowait(self._terminator)
self._thread.join(timeout=timeout)
self._thread = None
self._th... | Stops the task thread. Synchronous! | Below is the the instruction that describes the task:
### Input:
Stops the task thread. Synchronous!
### Response:
def stop(self, timeout=None):
"""
Stops the task thread. Synchronous!
"""
with self._lock:
if self._thread:
self._queue.put_nowait(self._ter... |
def to_pil_image(pic, mode=None):
"""Convert a tensor or an ndarray to PIL Image.
See :class:`~torchvision.transforms.ToPILImage` for more details.
Args:
pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
mode (`PIL.Image mode`_): color space and pixel depth of input data (... | Convert a tensor or an ndarray to PIL Image.
See :class:`~torchvision.transforms.ToPILImage` for more details.
Args:
pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
mode (`PIL.Image mode`_): color space and pixel depth of input data (optional).
.. _PIL.Image mode: https... | Below is the the instruction that describes the task:
### Input:
Convert a tensor or an ndarray to PIL Image.
See :class:`~torchvision.transforms.ToPILImage` for more details.
Args:
pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
mode (`PIL.Image mode`_): color space and... |
def pixelInMicrolensRegion(ch, col, row):
"""Returns `True` if the given pixel falls inside the K2C9 superstamp.
The superstamp is used for microlensing experiment and is an almost
contiguous area of 2.8e6 pixels.
"""
# First try the superstamp
try:
vertices_col = SUPERSTAMP["channels"]... | Returns `True` if the given pixel falls inside the K2C9 superstamp.
The superstamp is used for microlensing experiment and is an almost
contiguous area of 2.8e6 pixels. | Below is the the instruction that describes the task:
### Input:
Returns `True` if the given pixel falls inside the K2C9 superstamp.
The superstamp is used for microlensing experiment and is an almost
contiguous area of 2.8e6 pixels.
### Response:
def pixelInMicrolensRegion(ch, col, row):
"""Returns `... |
def get_stream_or_content_from_request(request):
"""Ensure the proper content is uploaded.
Stream might be already consumed by authentication process.
Hence flask.request.stream might not be readable and return improper value.
This methods checks if the stream has already been consumed and if so
r... | Ensure the proper content is uploaded.
Stream might be already consumed by authentication process.
Hence flask.request.stream might not be readable and return improper value.
This methods checks if the stream has already been consumed and if so
retrieve the data from flask.request.data where it has be... | Below is the the instruction that describes the task:
### Input:
Ensure the proper content is uploaded.
Stream might be already consumed by authentication process.
Hence flask.request.stream might not be readable and return improper value.
This methods checks if the stream has already been consumed an... |
def all_minutes(self):
"""
Returns a DatetimeIndex representing all the minutes in this calendar.
"""
opens_in_ns = self._opens.values.astype(
'datetime64[ns]',
).view('int64')
closes_in_ns = self._closes.values.astype(
'datetime64[ns]',
)... | Returns a DatetimeIndex representing all the minutes in this calendar. | Below is the the instruction that describes the task:
### Input:
Returns a DatetimeIndex representing all the minutes in this calendar.
### Response:
def all_minutes(self):
"""
Returns a DatetimeIndex representing all the minutes in this calendar.
"""
opens_in_ns = self._opens.value... |
def findall(self, name):
"""Similar to ElementTree.Element.findall()
"""
return [
S3Element(self.root_name, elem)
for elem in self.element.findall('s3:{}'.format(name), _S3_NS)
] | Similar to ElementTree.Element.findall() | Below is the the instruction that describes the task:
### Input:
Similar to ElementTree.Element.findall()
### Response:
def findall(self, name):
"""Similar to ElementTree.Element.findall()
"""
return [
S3Element(self.root_name, elem)
for elem in self.element.findall... |
def pywt_pad_mode(pad_mode, pad_const=0):
"""Convert ODL-style padding mode to pywt-style padding mode.
Parameters
----------
pad_mode : str
The ODL padding mode to use at the boundaries.
pad_const : float, optional
Value to use outside the signal boundaries when ``pad_mode`` is
... | Convert ODL-style padding mode to pywt-style padding mode.
Parameters
----------
pad_mode : str
The ODL padding mode to use at the boundaries.
pad_const : float, optional
Value to use outside the signal boundaries when ``pad_mode`` is
'constant'. Only a value of 0. is supported ... | Below is the the instruction that describes the task:
### Input:
Convert ODL-style padding mode to pywt-style padding mode.
Parameters
----------
pad_mode : str
The ODL padding mode to use at the boundaries.
pad_const : float, optional
Value to use outside the signal boundaries when... |
def complete_worker(self, text, line, begidx, endidx):
''' Tab-complete worker command. '''
return [i for i in PsiturkNetworkShell.worker_commands if \
i.startswith(text)] | Tab-complete worker command. | Below is the the instruction that describes the task:
### Input:
Tab-complete worker command.
### Response:
def complete_worker(self, text, line, begidx, endidx):
''' Tab-complete worker command. '''
return [i for i in PsiturkNetworkShell.worker_commands if \
i.startswith(text)] |
def get(self, wg_uuid, uuid, tree=False):
""" Get one workgroup member."""
url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % {
'base': self.local_base_url,
'wg_uuid': wg_uuid,
'uuid': uuid
}
param = {}
if tree:
param['tree'] = True
... | Get one workgroup member. | Below is the the instruction that describes the task:
### Input:
Get one workgroup member.
### Response:
def get(self, wg_uuid, uuid, tree=False):
""" Get one workgroup member."""
url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % {
'base': self.local_base_url,
'wg_uuid': wg_uuid... |
def send(self, email=None):
""" send email message """
if email is None and self.send_as_one:
self.smtp.send_message(
self.multipart, self.config['EMAIL'], self.addresses)
elif email is not None and self.send_as_one is False:
self.smtp.send_message(
... | send email message | Below is the the instruction that describes the task:
### Input:
send email message
### Response:
def send(self, email=None):
""" send email message """
if email is None and self.send_as_one:
self.smtp.send_message(
self.multipart, self.config['EMAIL'], self.addresse... |
def getValidItem(self, specfile, identifier):
"""Returns a ``Sii`` instance from ``self.container`` if it is valid,
if all elements of ``self.container[specfile][identifier] are
``Sii.isValid == False`` then ``None`` is returned.
:param specfile: a ms-run file name
:param identi... | Returns a ``Sii`` instance from ``self.container`` if it is valid,
if all elements of ``self.container[specfile][identifier] are
``Sii.isValid == False`` then ``None`` is returned.
:param specfile: a ms-run file name
:param identifier: item identifier ``Sii.id``
:returns: ``Sii... | Below is the the instruction that describes the task:
### Input:
Returns a ``Sii`` instance from ``self.container`` if it is valid,
if all elements of ``self.container[specfile][identifier] are
``Sii.isValid == False`` then ``None`` is returned.
:param specfile: a ms-run file name
:... |
def playlist_song_delete(self, playlist_song):
"""Delete song from playlist.
Parameters:
playlist_song (str): A playlist song dict.
Returns:
dict: Playlist dict including songs.
"""
self.playlist_songs_delete([playlist_song])
return self.playlist(playlist_song['playlistId'], include_songs=True) | Delete song from playlist.
Parameters:
playlist_song (str): A playlist song dict.
Returns:
dict: Playlist dict including songs. | Below is the the instruction that describes the task:
### Input:
Delete song from playlist.
Parameters:
playlist_song (str): A playlist song dict.
Returns:
dict: Playlist dict including songs.
### Response:
def playlist_song_delete(self, playlist_song):
"""Delete song from playlist.
Parameters:
... |
def deserialize(data):
""" Deserialize `data` to an exception instance.
If the `exc_path` value matches an exception registered as
``deserializable``, return an instance of that exception type.
Otherwise, return a `RemoteError` instance describing the exception
that occurred.
"""
key = data... | Deserialize `data` to an exception instance.
If the `exc_path` value matches an exception registered as
``deserializable``, return an instance of that exception type.
Otherwise, return a `RemoteError` instance describing the exception
that occurred. | Below is the the instruction that describes the task:
### Input:
Deserialize `data` to an exception instance.
If the `exc_path` value matches an exception registered as
``deserializable``, return an instance of that exception type.
Otherwise, return a `RemoteError` instance describing the exception
... |
def patSiemensStar(s0, n=72, vhigh=255, vlow=0, antiasing=False):
'''make line pattern'''
arr = np.full((s0,s0),vlow, dtype=np.uint8)
c = int(round(s0/2.))
s = 2*np.pi/(2*n)
step = 0
for i in range(2*n):
p0 = round(c+np.sin(step)*2*s0)
p1 = round(c+np.cos(step)*2*s0)
... | make line pattern | Below is the the instruction that describes the task:
### Input:
make line pattern
### Response:
def patSiemensStar(s0, n=72, vhigh=255, vlow=0, antiasing=False):
'''make line pattern'''
arr = np.full((s0,s0),vlow, dtype=np.uint8)
c = int(round(s0/2.))
s = 2*np.pi/(2*n)
step = 0
for ... |
def get_container_name(self, repo: str, branch: str, git_repo: Repo):
""" Returns the name of the container used for the repo.
"""
return "arca_{}_{}_{}".format(
self._arca.repo_id(repo),
branch,
self._arca.current_git_hash(repo, branch, git_repo, short=True)
... | Returns the name of the container used for the repo. | Below is the the instruction that describes the task:
### Input:
Returns the name of the container used for the repo.
### Response:
def get_container_name(self, repo: str, branch: str, git_repo: Repo):
""" Returns the name of the container used for the repo.
"""
return "arca_{}_{}_{}".forma... |
def format_usage(self, usage=None):
"""Return a formatted usage string.
If usage is None, use self.docs['usage'], and if that is also None,
generate one.
"""
if usage is None:
usage = self.docs['usage']
if usage is not None:
return usage... | Return a formatted usage string.
If usage is None, use self.docs['usage'], and if that is also None,
generate one. | Below is the the instruction that describes the task:
### Input:
Return a formatted usage string.
If usage is None, use self.docs['usage'], and if that is also None,
generate one.
### Response:
def format_usage(self, usage=None):
"""Return a formatted usage string.
... |
def list_(): # pylint: disable=redefined-builtin
"""
Display all MultiplyParameters nodes
"""
load_dbenv_if_not_loaded(
) # Important to load the dbenv in the last moment
from aiida.orm.querybuilder import QueryBuilder
from aiida.orm import DataFactory
MultiplyParameters = DataFactory... | Display all MultiplyParameters nodes | Below is the the instruction that describes the task:
### Input:
Display all MultiplyParameters nodes
### Response:
def list_(): # pylint: disable=redefined-builtin
"""
Display all MultiplyParameters nodes
"""
load_dbenv_if_not_loaded(
) # Important to load the dbenv in the last moment
f... |
def bilateral3(data, size_filter, sigma_p, sigma_x = 10.):
"""bilateral filter """
dtype = data.dtype.type
dtypes_kernels = {np.float32:"bilat3_float",}
if not dtype in dtypes_kernels:
logger.info("data type %s not supported yet (%s), casting to float:"%(dtype,list(dtypes_kernels.keys())))
... | bilateral filter | Below is the the instruction that describes the task:
### Input:
bilateral filter
### Response:
def bilateral3(data, size_filter, sigma_p, sigma_x = 10.):
"""bilateral filter """
dtype = data.dtype.type
dtypes_kernels = {np.float32:"bilat3_float",}
if not dtype in dtypes_kernels:
logger.i... |
def setrange(self, key, offset, value):
"""Overwrites part of the string stored at key, starting at the
specified offset, for the entire length of value. If the offset is
larger than the current length of the string at key, the string is
padded with zero-bytes to make offset fit. Non-exi... | Overwrites part of the string stored at key, starting at the
specified offset, for the entire length of value. If the offset is
larger than the current length of the string at key, the string is
padded with zero-bytes to make offset fit. Non-existing keys are
considered as empty strings,... | Below is the the instruction that describes the task:
### Input:
Overwrites part of the string stored at key, starting at the
specified offset, for the entire length of value. If the offset is
larger than the current length of the string at key, the string is
padded with zero-bytes to make o... |
def managed(name, table, data, record=None):
'''
Ensures that the specified columns of the named record have the specified
values.
Args:
name: The name of the record.
table: The name of the table to which the record belongs.
data: Dictionary containing a mapping from column name... | Ensures that the specified columns of the named record have the specified
values.
Args:
name: The name of the record.
table: The name of the table to which the record belongs.
data: Dictionary containing a mapping from column names to the desired
values. Columns that exist, ... | Below is the the instruction that describes the task:
### Input:
Ensures that the specified columns of the named record have the specified
values.
Args:
name: The name of the record.
table: The name of the table to which the record belongs.
data: Dictionary containing a mapping from... |
def getclosurevars(func):
"""
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
Not... | Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
Note:
Modified function from the ... | Below is the the instruction that describes the task:
### Input:
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be reso... |
def remove_comment(self, topic_id, comment_id, reason='0', other=None):
"""
删除评论(自己发的话题所有的都可以删除,否则只能删自己发的)
:param topic_id: 话题ID
:param comment_id: 评论ID
:param reason: 原因 0/1/2 (内容不符/反动/其它)
:param other: 其它原因的具体(2)
:return: None
"""
params... | 删除评论(自己发的话题所有的都可以删除,否则只能删自己发的)
:param topic_id: 话题ID
:param comment_id: 评论ID
:param reason: 原因 0/1/2 (内容不符/反动/其它)
:param other: 其它原因的具体(2)
:return: None | Below is the the instruction that describes the task:
### Input:
删除评论(自己发的话题所有的都可以删除,否则只能删自己发的)
:param topic_id: 话题ID
:param comment_id: 评论ID
:param reason: 原因 0/1/2 (内容不符/反动/其它)
:param other: 其它原因的具体(2)
:return: None
### Response:
def remove_comment(self, topic_id,... |
def print_most_common(counter, number=5, tab=1):
"""print the most common elements of a counter"""
for key, count in counter.most_common(number):
print "{0}{1} - {2}".format('\t'*tab, key, count) | print the most common elements of a counter | Below is the the instruction that describes the task:
### Input:
print the most common elements of a counter
### Response:
def print_most_common(counter, number=5, tab=1):
"""print the most common elements of a counter"""
for key, count in counter.most_common(number):
print "{0}{1} - {2}".format('\... |
def pitch(self):
""" Calculates the Pitch of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z) | Calculates the Pitch of the Quaternion. | Below is the the instruction that describes the task:
### Input:
Calculates the Pitch of the Quaternion.
### Response:
def pitch(self):
""" Calculates the Pitch of the Quaternion. """
x, y, z, w = self.x, self.y, self.z, self.w
return math.atan2(2*x*w - 2*y*z, 1 - 2*x*x - 2*z*z) |
def com_google_fonts_check_name_mandatory_entries(ttFont, style):
"""Font has all mandatory 'name' table entries ?"""
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import RIBBI_STYLE_NAMES
required_nameIDs = [NameID.FONT_FAMILY_NAME,
NameID.FONT_SUBFAMILY_N... | Font has all mandatory 'name' table entries ? | Below is the the instruction that describes the task:
### Input:
Font has all mandatory 'name' table entries ?
### Response:
def com_google_fonts_check_name_mandatory_entries(ttFont, style):
"""Font has all mandatory 'name' table entries ?"""
from fontbakery.utils import get_name_entry_strings
from fontbaker... |
def get_zones(region=None, key=None, keyid=None, profile=None):
'''
Get a list of AZs for the configured region.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_zones
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
return [z.name for z in c... | Get a list of AZs for the configured region.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_zones | Below is the the instruction that describes the task:
### Input:
Get a list of AZs for the configured region.
CLI Example:
.. code-block:: bash
salt myminion boto_ec2.get_zones
### Response:
def get_zones(region=None, key=None, keyid=None, profile=None):
'''
Get a list of AZs for the con... |
def assert_secure_file(file):
"""checks if a file is stored securely"""
if not is_secure_file(file):
msg = """
File {0} can be read by other users.
This is not secure. Please run 'chmod 600 "{0}"'"""
raise SecurityError(dedent(msg).replace('\n', ' ').format(file))
return True | checks if a file is stored securely | Below is the the instruction that describes the task:
### Input:
checks if a file is stored securely
### Response:
def assert_secure_file(file):
"""checks if a file is stored securely"""
if not is_secure_file(file):
msg = """
File {0} can be read by other users.
This is not secure. ... |
def parse_cl_function(cl_code, dependencies=()):
"""Parse the given OpenCL string to a single SimpleCLFunction.
If the string contains more than one function, we will return only the last, with all the other added as a
dependency.
Args:
cl_code (str): the input string containing one or more fu... | Parse the given OpenCL string to a single SimpleCLFunction.
If the string contains more than one function, we will return only the last, with all the other added as a
dependency.
Args:
cl_code (str): the input string containing one or more functions.
dependencies (Iterable[CLCodeObject]): ... | Below is the the instruction that describes the task:
### Input:
Parse the given OpenCL string to a single SimpleCLFunction.
If the string contains more than one function, we will return only the last, with all the other added as a
dependency.
Args:
cl_code (str): the input string containing o... |
def get_data(self, doi_id, idx):
"""
Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary
"""
tmp_dict = self.root_dict['pub'][0].copy()
try:
... | Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary | Below is the the instruction that describes the task:
### Input:
Resolve DOI and compile all attributes into one dictionary
:param str doi_id:
:param int idx: Publication index
:return dict: Updated publication dictionary
### Response:
def get_data(self, doi_id, idx):
"""
Re... |
def WriteFile(self, printer):
"""Write the services in this registry to out."""
self.Validate()
client_info = self.__client_info
printer('"""Generated client library for %s version %s."""',
client_info.package, client_info.version)
printer('# NOTE: This file is au... | Write the services in this registry to out. | Below is the the instruction that describes the task:
### Input:
Write the services in this registry to out.
### Response:
def WriteFile(self, printer):
"""Write the services in this registry to out."""
self.Validate()
client_info = self.__client_info
printer('"""Generated client li... |
def parse_value(self, value):
"""Parse value to proper model type."""
if not isinstance(value, dict):
return value
embed_type = self._get_embed_type()
return embed_type(**value) | Parse value to proper model type. | Below is the the instruction that describes the task:
### Input:
Parse value to proper model type.
### Response:
def parse_value(self, value):
"""Parse value to proper model type."""
if not isinstance(value, dict):
return value
embed_type = self._get_embed_type()
return... |
def get_nth_weekday_in_month(year, month, weekday, n=1, start=None):
"""Get the nth weekday in a given month. e.g:
>>> # the 1st monday in Jan 2013
>>> Calendar.get_nth_weekday_in_month(2013, 1, MON)
datetime.date(2013, 1, 7)
>>> # The 2nd monday in Jan 2013
>>> Calendar... | Get the nth weekday in a given month. e.g:
>>> # the 1st monday in Jan 2013
>>> Calendar.get_nth_weekday_in_month(2013, 1, MON)
datetime.date(2013, 1, 7)
>>> # The 2nd monday in Jan 2013
>>> Calendar.get_nth_weekday_in_month(2013, 1, MON, 2)
datetime.date(2013, 1, 14) | Below is the the instruction that describes the task:
### Input:
Get the nth weekday in a given month. e.g:
>>> # the 1st monday in Jan 2013
>>> Calendar.get_nth_weekday_in_month(2013, 1, MON)
datetime.date(2013, 1, 7)
>>> # The 2nd monday in Jan 2013
>>> Calendar.get_nth_we... |
def get_pretty_app_names(self):
"""
Return the list of pretty app names that are available in the database.
Returns:
set of str.
"""
pretty_app_names = set()
for app_name in self.get_app_names():
pretty_app_names.add(self.get_name(app_name))
... | Return the list of pretty app names that are available in the database.
Returns:
set of str. | Below is the the instruction that describes the task:
### Input:
Return the list of pretty app names that are available in the database.
Returns:
set of str.
### Response:
def get_pretty_app_names(self):
"""
Return the list of pretty app names that are available in the database... |
def _get_intra_event_phi(self, C, mag, rjb, vs30, num_sites):
"""
Returns the intra-event standard deviation (phi), dependent on
magnitude, distance and vs30
"""
base_vals = np.zeros(num_sites)
# Magnitude Dependent phi (Equation 17)
if mag <= 4.5:
bas... | Returns the intra-event standard deviation (phi), dependent on
magnitude, distance and vs30 | Below is the the instruction that describes the task:
### Input:
Returns the intra-event standard deviation (phi), dependent on
magnitude, distance and vs30
### Response:
def _get_intra_event_phi(self, C, mag, rjb, vs30, num_sites):
"""
Returns the intra-event standard deviation (phi), depe... |
def field_alpha_histogram(
self, name, n_bins=10, include_queries=True, **query_dict
):
"""Generates a histogram of values from a string field.
Output is: [[low, high, count, query], ... ]. Bin edges is determined by equal
division of the fields.
"""
bin_list = []
... | Generates a histogram of values from a string field.
Output is: [[low, high, count, query], ... ]. Bin edges is determined by equal
division of the fields. | Below is the the instruction that describes the task:
### Input:
Generates a histogram of values from a string field.
Output is: [[low, high, count, query], ... ]. Bin edges is determined by equal
division of the fields.
### Response:
def field_alpha_histogram(
self, name, n_bins=10, inclu... |
def _divide_filter_args(self, filter_args):
"""
Divide the filter arguments into filter query parameters for filtering
on the server side, and the remaining client-side filters.
Parameters:
filter_args (dict):
Filter arguments that narrow the list of returned reso... | Divide the filter arguments into filter query parameters for filtering
on the server side, and the remaining client-side filters.
Parameters:
filter_args (dict):
Filter arguments that narrow the list of returned resources to
those that match the specified filter argum... | Below is the the instruction that describes the task:
### Input:
Divide the filter arguments into filter query parameters for filtering
on the server side, and the remaining client-side filters.
Parameters:
filter_args (dict):
Filter arguments that narrow the list of returned... |
def trajectory(start=None, stop=None, step=None):
'''Useful command to iterate on the trajectory frames by time (in
ns). It is meant to be used in a for loop::
for i in trajectory(0, 10, 0.1):
coords = current_frame()
t = current_time()
# Do something
The previo... | Useful command to iterate on the trajectory frames by time (in
ns). It is meant to be used in a for loop::
for i in trajectory(0, 10, 0.1):
coords = current_frame()
t = current_time()
# Do something
The previous snippet will stop at every frame from 0 to 10 ns with
... | Below is the the instruction that describes the task:
### Input:
Useful command to iterate on the trajectory frames by time (in
ns). It is meant to be used in a for loop::
for i in trajectory(0, 10, 0.1):
coords = current_frame()
t = current_time()
# Do something
... |
def retry(tries, CatchExceptions=(Exception,), delay=0.01, backoff=2):
'''
错误重试的修饰器
:param tries: 重试次数
:param CatchExceptions: 需要重试的exception列表
:param delay: 重试前等待
:param backoff: 重试n次后,需要等待delay * n * backoff
:return:
@retry(5,ValueError)
def test():
raise ValueError
... | 错误重试的修饰器
:param tries: 重试次数
:param CatchExceptions: 需要重试的exception列表
:param delay: 重试前等待
:param backoff: 重试n次后,需要等待delay * n * backoff
:return:
@retry(5,ValueError)
def test():
raise ValueError | Below is the the instruction that describes the task:
### Input:
错误重试的修饰器
:param tries: 重试次数
:param CatchExceptions: 需要重试的exception列表
:param delay: 重试前等待
:param backoff: 重试n次后,需要等待delay * n * backoff
:return:
@retry(5,ValueError)
def test():
raise ValueError
### Response:
def ... |
def _set_permit_list(self, v, load=False):
"""
Setter method for permit_list, mapped from YANG variable /arp/access_list/permit/permit_list (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_permit_list is considered as a private
method. Backends looking to popul... | Setter method for permit_list, mapped from YANG variable /arp/access_list/permit/permit_list (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_permit_list is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj.... | Below is the the instruction that describes the task:
### Input:
Setter method for permit_list, mapped from YANG variable /arp/access_list/permit/permit_list (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_permit_list is considered as a private
method. Backends lo... |
def waitUpTo(self, timeoutSeconds, pollInterval=DEFAULT_POLL_INTERVAL):
'''
Popen.waitUpTo - Wait up to a certain number of seconds for the process to end.
@param timeoutSeconds <float> - Number of seconds to wait
@param pollInterval <float> (default .05) - Number of seconds in bet... | Popen.waitUpTo - Wait up to a certain number of seconds for the process to end.
@param timeoutSeconds <float> - Number of seconds to wait
@param pollInterval <float> (default .05) - Number of seconds in between each poll
@return - Returncode of application, or None if did not term... | Below is the the instruction that describes the task:
### Input:
Popen.waitUpTo - Wait up to a certain number of seconds for the process to end.
@param timeoutSeconds <float> - Number of seconds to wait
@param pollInterval <float> (default .05) - Number of seconds in between each poll
... |
def jacobian_graph(predictions, x, nb_classes):
"""
Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return:
"""
# This fun... | Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return: | Below is the the instruction that describes the task:
### Input:
Create the Jacobian graph to be ran later in a TF session
:param predictions: the model's symbolic output (linear output,
pre-softmax)
:param x: the input placeholder
:param nb_classes: the number of classes the model has
:return:
### Re... |
async def forward(self, n, *, timeout=None) -> int:
r"""Skip over the next *n* rows.
:param float timeout: Optional timeout value in seconds.
:return: A number of rows actually skipped over (<= *n*).
"""
self._check_ready()
if n <= 0:
raise exceptions.Interf... | r"""Skip over the next *n* rows.
:param float timeout: Optional timeout value in seconds.
:return: A number of rows actually skipped over (<= *n*). | Below is the the instruction that describes the task:
### Input:
r"""Skip over the next *n* rows.
:param float timeout: Optional timeout value in seconds.
:return: A number of rows actually skipped over (<= *n*).
### Response:
async def forward(self, n, *, timeout=None) -> int:
r"""Skip o... |
def _kill_cursors(self, cursor_ids, address, topology, session):
"""Send a kill cursors message with the given ids."""
listeners = self._event_listeners
publish = listeners.enabled_for_commands
if address:
# address could be a tuple or _CursorAddress, but
# select... | Send a kill cursors message with the given ids. | Below is the the instruction that describes the task:
### Input:
Send a kill cursors message with the given ids.
### Response:
def _kill_cursors(self, cursor_ids, address, topology, session):
"""Send a kill cursors message with the given ids."""
listeners = self._event_listeners
publish = l... |
def _SetPath(self, path):
"""Sets the current path to watch for new events.
This also records the size of the old path, if any. If the size can't be
found, an error is logged.
Args:
path: The full path of the file to watch.
"""
old_path = self._path
if old_path and not io_wrapper.IsC... | Sets the current path to watch for new events.
This also records the size of the old path, if any. If the size can't be
found, an error is logged.
Args:
path: The full path of the file to watch. | Below is the the instruction that describes the task:
### Input:
Sets the current path to watch for new events.
This also records the size of the old path, if any. If the size can't be
found, an error is logged.
Args:
path: The full path of the file to watch.
### Response:
def _SetPath(self, pa... |
def get_diadefs(self, project, linker):
"""Get the diagrams configuration data
:param project:The pyreverse project
:type project: pyreverse.utils.Project
:param linker: The linker
:type linker: pyreverse.inspector.Linker(IdGeneratorMixIn, LocalsVisitor)
:returns: The l... | Get the diagrams configuration data
:param project:The pyreverse project
:type project: pyreverse.utils.Project
:param linker: The linker
:type linker: pyreverse.inspector.Linker(IdGeneratorMixIn, LocalsVisitor)
:returns: The list of diagram definitions
:rtype: list(:cl... | Below is the the instruction that describes the task:
### Input:
Get the diagrams configuration data
:param project:The pyreverse project
:type project: pyreverse.utils.Project
:param linker: The linker
:type linker: pyreverse.inspector.Linker(IdGeneratorMixIn, LocalsVisitor)
... |
def _needs_java(data):
"""Check if a caller needs external java for MuTect.
No longer check for older GATK (<3.6) versions because of time cost; this
won't be relevant to most runs so we skip the sanity check.
"""
vc = dd.get_variantcaller(data)
if isinstance(vc, dict):
out = {}
... | Check if a caller needs external java for MuTect.
No longer check for older GATK (<3.6) versions because of time cost; this
won't be relevant to most runs so we skip the sanity check. | Below is the the instruction that describes the task:
### Input:
Check if a caller needs external java for MuTect.
No longer check for older GATK (<3.6) versions because of time cost; this
won't be relevant to most runs so we skip the sanity check.
### Response:
def _needs_java(data):
"""Check if a ca... |
def elem2json(elem, options, strip_ns=1, strip=1):
"""Convert an ElementTree or Element into a JSON string."""
if hasattr(elem, 'getroot'):
elem = elem.getroot()
if options.pretty:
return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip), sort_keys=True, indent=4, separato... | Convert an ElementTree or Element into a JSON string. | Below is the the instruction that describes the task:
### Input:
Convert an ElementTree or Element into a JSON string.
### Response:
def elem2json(elem, options, strip_ns=1, strip=1):
"""Convert an ElementTree or Element into a JSON string."""
if hasattr(elem, 'getroot'):
elem = elem.getroot()
... |
def make_trace_api(client):
"""
Create an instance of the gapic Trace API.
Args:
client (~google.cloud.trace.client.Client): The client that holds
configuration details.
Returns:
A :class:`~google.cloud.trace._gapic._TraceAPI` instance with the
proper configurations... | Create an instance of the gapic Trace API.
Args:
client (~google.cloud.trace.client.Client): The client that holds
configuration details.
Returns:
A :class:`~google.cloud.trace._gapic._TraceAPI` instance with the
proper configurations. | Below is the the instruction that describes the task:
### Input:
Create an instance of the gapic Trace API.
Args:
client (~google.cloud.trace.client.Client): The client that holds
configuration details.
Returns:
A :class:`~google.cloud.trace._gapic._TraceAPI` instance with the
... |
def loadRule(rule_json_object):
""" Method to load the rules - when adding a new rule it must be added to the if statement within this method. """
name = rule_json_object['name']
rule_type = rule_json_object['rule_type']
validation_regex = None
required = False
removehtml = False
include_end... | Method to load the rules - when adding a new rule it must be added to the if statement within this method. | Below is the the instruction that describes the task:
### Input:
Method to load the rules - when adding a new rule it must be added to the if statement within this method.
### Response:
def loadRule(rule_json_object):
""" Method to load the rules - when adding a new rule it must be added to the if statement wi... |
def filter_empty_files(files, ifo=None):
"""Remove empty PyCBC-HDF5 files from a list
Parameters
----------
files : `list`
A list of file paths to test.
ifo : `str`, optional
prefix for the interferometer of interest (e.g. ``'L1'``),
include this for a more robust test of '... | Remove empty PyCBC-HDF5 files from a list
Parameters
----------
files : `list`
A list of file paths to test.
ifo : `str`, optional
prefix for the interferometer of interest (e.g. ``'L1'``),
include this for a more robust test of 'emptiness'
Returns
-------
nonempty... | Below is the the instruction that describes the task:
### Input:
Remove empty PyCBC-HDF5 files from a list
Parameters
----------
files : `list`
A list of file paths to test.
ifo : `str`, optional
prefix for the interferometer of interest (e.g. ``'L1'``),
include this for a ... |
def add_event_callback(self, event_groups, callback):
"""Register callback for a group of timeline events."""
if not event_groups:
return False
if not isinstance(event_groups, (tuple, list)):
event_groups = [event_groups]
for event_group in event_groups:
... | Register callback for a group of timeline events. | Below is the the instruction that describes the task:
### Input:
Register callback for a group of timeline events.
### Response:
def add_event_callback(self, event_groups, callback):
"""Register callback for a group of timeline events."""
if not event_groups:
return False
if no... |
def min_width(self) -> int:
"""Minimum width necessary to render the block's contents."""
return max(
max(len(e) for e in self.content.split('\n')),
# Only horizontal lines can cross 0 width blocks.
int(any([self.top, self.bottom]))
) | Minimum width necessary to render the block's contents. | Below is the the instruction that describes the task:
### Input:
Minimum width necessary to render the block's contents.
### Response:
def min_width(self) -> int:
"""Minimum width necessary to render the block's contents."""
return max(
max(len(e) for e in self.content.split('\n')),
... |
def _set_af_ipv6_unicast(self, v, load=False):
"""
Setter method for af_ipv6_unicast, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_ipv6_uni... | Setter method for af_ipv6_unicast, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_af_ipv6_unicast is considered as a private
method. Backends lookin... | Below is the the instruction that describes the task:
### Input:
Setter method for af_ipv6_unicast, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_a... |
def fit_predict(training_data, fitting_data, tau=1, samples_per_job=0, save_results=True, show=False):
from disco.worker.pipeline.worker import Worker, Stage
from disco.core import Job, result_iterator
from disco.core import Disco
"""
training_data - training samples
fitting_data - dataset to b... | training_data - training samples
fitting_data - dataset to be fitted to training data.
tau - controls how quickly the weight of a training sample falls off with distance of its x(i) from the query point x.
samples_per_job - define a number of samples that will be processed in single mapreduce job. If 0, alg... | Below is the the instruction that describes the task:
### Input:
training_data - training samples
fitting_data - dataset to be fitted to training data.
tau - controls how quickly the weight of a training sample falls off with distance of its x(i) from the query point x.
samples_per_job - define a number... |
def add_ipdu(self, information, timeout=-1):
"""
Add an HP iPDU and bring all components under management by discovery of its management module. Bring the
management module under exclusive management by the appliance, configure any management or data collection
settings, and create a pri... | Add an HP iPDU and bring all components under management by discovery of its management module. Bring the
management module under exclusive management by the appliance, configure any management or data collection
settings, and create a private set of administrative credentials to enable ongoing communic... | Below is the the instruction that describes the task:
### Input:
Add an HP iPDU and bring all components under management by discovery of its management module. Bring the
management module under exclusive management by the appliance, configure any management or data collection
settings, and create a... |
def make_all_dirs(path, mode=0o777):
"""
Ensure local dir, with all its parent dirs, are created.
Unlike os.makedirs(), will not fail if the path already exists.
"""
# Avoid races inherent to doing this in two steps (check then create).
# Python 3 has exist_ok but the approach below works for Python 2+3.
... | Ensure local dir, with all its parent dirs, are created.
Unlike os.makedirs(), will not fail if the path already exists. | Below is the the instruction that describes the task:
### Input:
Ensure local dir, with all its parent dirs, are created.
Unlike os.makedirs(), will not fail if the path already exists.
### Response:
def make_all_dirs(path, mode=0o777):
"""
Ensure local dir, with all its parent dirs, are created.
Unlike os... |
def didLastExecutedUpgradeSucceeded(self) -> bool:
"""
Checks last record in upgrade log to find out whether it
is about scheduling upgrade. If so - checks whether current version
is equals to the one in that record
:returns: upgrade execution result
"""
lastEven... | Checks last record in upgrade log to find out whether it
is about scheduling upgrade. If so - checks whether current version
is equals to the one in that record
:returns: upgrade execution result | Below is the the instruction that describes the task:
### Input:
Checks last record in upgrade log to find out whether it
is about scheduling upgrade. If so - checks whether current version
is equals to the one in that record
:returns: upgrade execution result
### Response:
def didLastExec... |
def create_timedelta(timespec):
"""Utility function to translate DD:HH:MM:SS into a timedelta object."""
duration = timespec.split(':')
seconds = int(duration[-1])
minutes = 0
hours = 0
days = 0
if len(duration) > 1:
minutes = int(duration[-2])
if len(duration) > 2:
hour... | Utility function to translate DD:HH:MM:SS into a timedelta object. | Below is the the instruction that describes the task:
### Input:
Utility function to translate DD:HH:MM:SS into a timedelta object.
### Response:
def create_timedelta(timespec):
"""Utility function to translate DD:HH:MM:SS into a timedelta object."""
duration = timespec.split(':')
seconds = int(duratio... |
def process(self, batch):
"""Process a single, partitioned query or read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_query_batches`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`... | Process a single, partitioned query or read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_query_batches`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set insta... | Below is the the instruction that describes the task:
### Input:
Process a single, partitioned query or read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_query_batches`.
:rtype: :class:`~google.cloud.spanne... |
def json_to_key_value(json_data, key_field, value_field=None, array=False):
"""Convert JSON data to a KeyValue/KeyValueArray.
Args:
json_data (dictionary|list): Array/List of JSON data.
key_field (string): Field name for the key.
value_field (string): Field name for ... | Convert JSON data to a KeyValue/KeyValueArray.
Args:
json_data (dictionary|list): Array/List of JSON data.
key_field (string): Field name for the key.
value_field (string): Field name for the value or use the value of the key field.
array (boolean): Always return... | Below is the the instruction that describes the task:
### Input:
Convert JSON data to a KeyValue/KeyValueArray.
Args:
json_data (dictionary|list): Array/List of JSON data.
key_field (string): Field name for the key.
value_field (string): Field name for the value or use t... |
def _setupaA(self,pot=None,type='staeckel',**kwargs):
"""
NAME:
_setupaA
PURPOSE:
set up an actionAngle module for this Orbit
INPUT:
pot - potential
type= ('staeckel') type of actionAngle module to use
1) 'adiabatic'
... | NAME:
_setupaA
PURPOSE:
set up an actionAngle module for this Orbit
INPUT:
pot - potential
type= ('staeckel') type of actionAngle module to use
1) 'adiabatic'
2) 'staeckel'
3) 'isochroneApprox'
4) 'spheri... | Below is the the instruction that describes the task:
### Input:
NAME:
_setupaA
PURPOSE:
set up an actionAngle module for this Orbit
INPUT:
pot - potential
type= ('staeckel') type of actionAngle module to use
1) 'adiabatic'
2) '... |
def load_books_of_speaker(corpus, path, speaker):
"""
Load all utterances for the speaker at the given path.
"""
utt_ids = []
for book_path in MailabsReader.get_folders(path):
meta_path = os.path.join(book_path, 'metadata.csv')
wavs_path = os.path.join(bo... | Load all utterances for the speaker at the given path. | Below is the the instruction that describes the task:
### Input:
Load all utterances for the speaker at the given path.
### Response:
def load_books_of_speaker(corpus, path, speaker):
"""
Load all utterances for the speaker at the given path.
"""
utt_ids = []
for book_path ... |
def is_diagonal_scale(scale):
"""Returns `True` if `scale` is a `LinearOperator` that is known to be diag.
Args:
scale: `LinearOperator` instance.
Returns:
Python `bool`.
Raises:
TypeError: If `scale` is not a `LinearOperator`.
"""
if not isinstance(scale, tf.linalg.LinearOperator):
rai... | Returns `True` if `scale` is a `LinearOperator` that is known to be diag.
Args:
scale: `LinearOperator` instance.
Returns:
Python `bool`.
Raises:
TypeError: If `scale` is not a `LinearOperator`. | Below is the the instruction that describes the task:
### Input:
Returns `True` if `scale` is a `LinearOperator` that is known to be diag.
Args:
scale: `LinearOperator` instance.
Returns:
Python `bool`.
Raises:
TypeError: If `scale` is not a `LinearOperator`.
### Response:
def is_diagonal_sc... |
def set_target_variable (self, targets, variable, value, append=0):
""" Sets a target variable.
The 'variable' will be available to bjam when it decides
where to generate targets, and will also be available to
updating rule for that 'taret'.
"""
if isinstance (targets, s... | Sets a target variable.
The 'variable' will be available to bjam when it decides
where to generate targets, and will also be available to
updating rule for that 'taret'. | Below is the the instruction that describes the task:
### Input:
Sets a target variable.
The 'variable' will be available to bjam when it decides
where to generate targets, and will also be available to
updating rule for that 'taret'.
### Response:
def set_target_variable (self, targets, v... |
def tablify(*args):
r"""
>>> tablify(range(3), range(10, 13))
[[0, 10], [1, 11], [2, 12]]
"""
table = []
args = [listify(arg) for arg in args]
for row in zip(*args):
r = []
for x in row:
r += listify(x)
table += [r]
return table
return [sum([listif... | r"""
>>> tablify(range(3), range(10, 13))
[[0, 10], [1, 11], [2, 12]] | Below is the the instruction that describes the task:
### Input:
r"""
>>> tablify(range(3), range(10, 13))
[[0, 10], [1, 11], [2, 12]]
### Response:
def tablify(*args):
r"""
>>> tablify(range(3), range(10, 13))
[[0, 10], [1, 11], [2, 12]]
"""
table = []
args = [listify(arg) for arg ... |
def get_node(self, path):
"""
Returns ``Node`` object from the given ``path``. If there is no node at
the given ``path``, ``ChangesetError`` would be raised.
"""
path = self._fix_path(path)
if not path in self.nodes:
if path in self._file_paths:
... | Returns ``Node`` object from the given ``path``. If there is no node at
the given ``path``, ``ChangesetError`` would be raised. | Below is the the instruction that describes the task:
### Input:
Returns ``Node`` object from the given ``path``. If there is no node at
the given ``path``, ``ChangesetError`` would be raised.
### Response:
def get_node(self, path):
"""
Returns ``Node`` object from the given ``path``. If th... |
def load( self, stats ):
"""Build a squaremap-compatible model from a pstats class"""
rows = self.rows
for func, raw in stats.iteritems():
try:
rows[func] = row = PStatRow( func,raw )
except ValueError, err:
log.info( 'Null row: %s', func )... | Build a squaremap-compatible model from a pstats class | Below is the the instruction that describes the task:
### Input:
Build a squaremap-compatible model from a pstats class
### Response:
def load( self, stats ):
"""Build a squaremap-compatible model from a pstats class"""
rows = self.rows
for func, raw in stats.iteritems():
try:
... |
def binormal_curve_single_list(obj, param_list, normalize):
""" Evaluates the curve binormal vectors at the given list of parameter values.
:param obj: input curve
:type obj: abstract.Curve
:param param_list: parameter list
:type param_list: list or tuple
:param normalize: if True, the returned... | Evaluates the curve binormal vectors at the given list of parameter values.
:param obj: input curve
:type obj: abstract.Curve
:param param_list: parameter list
:type param_list: list or tuple
:param normalize: if True, the returned vector is converted to a unit vector
:type normalize: bool
... | Below is the the instruction that describes the task:
### Input:
Evaluates the curve binormal vectors at the given list of parameter values.
:param obj: input curve
:type obj: abstract.Curve
:param param_list: parameter list
:type param_list: list or tuple
:param normalize: if True, the returne... |
def __patch_pipe_write_method(tango_device_klass, pipe):
"""
Checks if method given by it's name for the given DeviceImpl
class has the correct signature. If a read/write method doesn't
have a parameter (the traditional Pipe), then the method is
wrapped into another method which has correct paramete... | Checks if method given by it's name for the given DeviceImpl
class has the correct signature. If a read/write method doesn't
have a parameter (the traditional Pipe), then the method is
wrapped into another method which has correct parameter definition
to make it work.
:param tango_device_klass: a D... | Below is the the instruction that describes the task:
### Input:
Checks if method given by it's name for the given DeviceImpl
class has the correct signature. If a read/write method doesn't
have a parameter (the traditional Pipe), then the method is
wrapped into another method which has correct paramete... |
def _set_enum_list_local_type(self, specifications):
""" This method is needed until get_type_name() is enhanced to include specification subtype and local_name
"""
for rest_name, specification in specifications.items():
for attribute in specification.attributes:
if a... | This method is needed until get_type_name() is enhanced to include specification subtype and local_name | Below is the the instruction that describes the task:
### Input:
This method is needed until get_type_name() is enhanced to include specification subtype and local_name
### Response:
def _set_enum_list_local_type(self, specifications):
""" This method is needed until get_type_name() is enhanced to include ... |
def previous_row(self):
"""Move to previous row from currently selected row."""
row = self.currentIndex().row()
rows = self.proxy_model.rowCount()
if row == 0:
row = rows
self.selectRow(row - 1) | Move to previous row from currently selected row. | Below is the the instruction that describes the task:
### Input:
Move to previous row from currently selected row.
### Response:
def previous_row(self):
"""Move to previous row from currently selected row."""
row = self.currentIndex().row()
rows = self.proxy_model.rowCount()
if ... |
def read_if_vcf(params):
"""
Checks if input is VCF and reads in appropriately if it is
"""
ref = None
aln = params.aln
fixed_pi = None
if hasattr(params, 'aln') and params.aln is not None:
if any([params.aln.lower().endswith(x) for x in ['.vcf', '.vcf.gz']]):
if not para... | Checks if input is VCF and reads in appropriately if it is | Below is the the instruction that describes the task:
### Input:
Checks if input is VCF and reads in appropriately if it is
### Response:
def read_if_vcf(params):
"""
Checks if input is VCF and reads in appropriately if it is
"""
ref = None
aln = params.aln
fixed_pi = None
if hasattr(pa... |
def params(self):
""" A combined :class:`MultiDict` with values from :attr:`forms` and
:attr:`GET`. File-uploads are not included. """
params = MultiDict(self.GET)
for key, value in self.forms.iterallitems():
params[key] = value
return params | A combined :class:`MultiDict` with values from :attr:`forms` and
:attr:`GET`. File-uploads are not included. | Below is the the instruction that describes the task:
### Input:
A combined :class:`MultiDict` with values from :attr:`forms` and
:attr:`GET`. File-uploads are not included.
### Response:
def params(self):
""" A combined :class:`MultiDict` with values from :attr:`forms` and
:attr:`G... |
def relative_ref(*parts):
"""
Create a reference builder with specified relative location.
using getter.relative_ref("some", "submodel") to get a value with key
"toto" will gives reference.Relative("some", "submodel", "toto")
"""
def relative_ref(_value, context, **_params):
return refe... | Create a reference builder with specified relative location.
using getter.relative_ref("some", "submodel") to get a value with key
"toto" will gives reference.Relative("some", "submodel", "toto") | Below is the the instruction that describes the task:
### Input:
Create a reference builder with specified relative location.
using getter.relative_ref("some", "submodel") to get a value with key
"toto" will gives reference.Relative("some", "submodel", "toto")
### Response:
def relative_ref(*parts):
""... |
def seed_args(subparsers):
"""Add command line options for the seed operation"""
seed_parser = subparsers.add_parser('seed')
secretfile_args(seed_parser)
vars_args(seed_parser)
seed_parser.add_argument('--mount-only',
dest='mount_only',
help=... | Add command line options for the seed operation | Below is the the instruction that describes the task:
### Input:
Add command line options for the seed operation
### Response:
def seed_args(subparsers):
"""Add command line options for the seed operation"""
seed_parser = subparsers.add_parser('seed')
secretfile_args(seed_parser)
vars_args(seed_par... |
def jwks_to_keyjar(jwks, iss=''):
"""
Convert a JWKS to a KeyJar instance.
:param jwks: String representation of a JWKS
:return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
"""
if not isinstance(jwks, dict):
try:
jwks = json.loads(jwks)
except json.JSONDecodeError:... | Convert a JWKS to a KeyJar instance.
:param jwks: String representation of a JWKS
:return: A :py:class:`oidcmsg.key_jar.KeyJar` instance | Below is the the instruction that describes the task:
### Input:
Convert a JWKS to a KeyJar instance.
:param jwks: String representation of a JWKS
:return: A :py:class:`oidcmsg.key_jar.KeyJar` instance
### Response:
def jwks_to_keyjar(jwks, iss=''):
"""
Convert a JWKS to a KeyJar instance.
:p... |
def segments(self):
"""List of :class:`ChatMessageSegment` in message (:class:`list`)."""
seg_list = self._event.chat_message.message_content.segment
return [ChatMessageSegment.deserialize(seg) for seg in seg_list] | List of :class:`ChatMessageSegment` in message (:class:`list`). | Below is the the instruction that describes the task:
### Input:
List of :class:`ChatMessageSegment` in message (:class:`list`).
### Response:
def segments(self):
"""List of :class:`ChatMessageSegment` in message (:class:`list`)."""
seg_list = self._event.chat_message.message_content.segment
... |
def process_incoming(self):
"""
process incoming messages
data is a dict with several arrays
"""
model = self.model
sockets = self.sockets
# Check for new messages
if not sockets:
return
# unpack sockets
poller = sockets['pol... | process incoming messages
data is a dict with several arrays | Below is the the instruction that describes the task:
### Input:
process incoming messages
data is a dict with several arrays
### Response:
def process_incoming(self):
"""
process incoming messages
data is a dict with several arrays
"""
model = self.model
... |
async def pop_transaction_async(self):
"""Decrement async transaction depth.
"""
depth = self.transaction_depth_async()
if depth > 0:
depth -= 1
self._task_data.set('depth', depth)
if depth == 0:
conn = self._task_data.get('conn')
... | Decrement async transaction depth. | Below is the the instruction that describes the task:
### Input:
Decrement async transaction depth.
### Response:
async def pop_transaction_async(self):
"""Decrement async transaction depth.
"""
depth = self.transaction_depth_async()
if depth > 0:
depth -= 1
... |
def get_cert_store(self):
"""
Get the certificate store for the context. This can be used to add
"trusted" certificates without using the
:meth:`load_verify_locations` method.
:return: A X509Store object or None if it does not have one.
"""
store = _lib.SSL_CTX_... | Get the certificate store for the context. This can be used to add
"trusted" certificates without using the
:meth:`load_verify_locations` method.
:return: A X509Store object or None if it does not have one. | Below is the the instruction that describes the task:
### Input:
Get the certificate store for the context. This can be used to add
"trusted" certificates without using the
:meth:`load_verify_locations` method.
:return: A X509Store object or None if it does not have one.
### Response:
def... |
def map_trips(
feed: "Feed",
trip_ids: List[str],
color_palette: List[str] = cs.COLORS_SET2,
*,
include_stops: bool = True,
):
"""
Return a Folium map showing the given trips and (optionally)
their stops.
Parameters
----------
feed : Feed
trip_ids : list
IDs of t... | Return a Folium map showing the given trips and (optionally)
their stops.
Parameters
----------
feed : Feed
trip_ids : list
IDs of trips in ``feed.trips``
color_palette : list
Palette to use to color the routes. If more routes than colors,
then colors will be recycled.
... | Below is the the instruction that describes the task:
### Input:
Return a Folium map showing the given trips and (optionally)
their stops.
Parameters
----------
feed : Feed
trip_ids : list
IDs of trips in ``feed.trips``
color_palette : list
Palette to use to color the routes... |
def to_original(self, x, y):
"""
Convert the input (x, y) positions from the rectified image to
the original (unrectified) image.
Parameters
----------
x, y: float or array-like of float
The zero-index pixel coordinates in the rectified image.
Retur... | Convert the input (x, y) positions from the rectified image to
the original (unrectified) image.
Parameters
----------
x, y: float or array-like of float
The zero-index pixel coordinates in the rectified image.
Returns
-------
x, y: float or array-... | Below is the the instruction that describes the task:
### Input:
Convert the input (x, y) positions from the rectified image to
the original (unrectified) image.
Parameters
----------
x, y: float or array-like of float
The zero-index pixel coordinates in the rectified i... |
def trigger(self):
"""
Sets the LED trigger. A trigger is a kernel based source of LED events.
Triggers can either be simple or complex. A simple trigger isn't
configurable and is designed to slot into existing subsystems with
minimal additional code. Examples are the `ide-disk` ... | Sets the LED trigger. A trigger is a kernel based source of LED events.
Triggers can either be simple or complex. A simple trigger isn't
configurable and is designed to slot into existing subsystems with
minimal additional code. Examples are the `ide-disk` and `nand-disk`
triggers.
... | Below is the the instruction that describes the task:
### Input:
Sets the LED trigger. A trigger is a kernel based source of LED events.
Triggers can either be simple or complex. A simple trigger isn't
configurable and is designed to slot into existing subsystems with
minimal additional code... |
def _to_narrow(self, terms, data, mask, dates, symbols):
"""
Convert raw computed pipeline results into a DataFrame for public APIs.
Parameters
----------
terms : dict[str -> Term]
Dict mapping column names to terms.
data : dict[str -> ndarray[ndim=2]]
... | Convert raw computed pipeline results into a DataFrame for public APIs.
Parameters
----------
terms : dict[str -> Term]
Dict mapping column names to terms.
data : dict[str -> ndarray[ndim=2]]
Dict mapping column names to computed results for those names.
... | Below is the the instruction that describes the task:
### Input:
Convert raw computed pipeline results into a DataFrame for public APIs.
Parameters
----------
terms : dict[str -> Term]
Dict mapping column names to terms.
data : dict[str -> ndarray[ndim=2]]
Di... |
def list_subscriptions(self, client_id, client_secret):
"""
List current webhook event subscriptions in place for the current application.
http://strava.github.io/api/partner/v3/events/#list-push-subscriptions
:param client_id: application's ID, obtained during registration
:ty... | List current webhook event subscriptions in place for the current application.
http://strava.github.io/api/partner/v3/events/#list-push-subscriptions
:param client_id: application's ID, obtained during registration
:type client_id: int
:param client_secret: application's secret, obtai... | Below is the the instruction that describes the task:
### Input:
List current webhook event subscriptions in place for the current application.
http://strava.github.io/api/partner/v3/events/#list-push-subscriptions
:param client_id: application's ID, obtained during registration
:type clie... |
def parse_single_meta(self, fname, selected_meta_data):
"""
Parses a single meta data file
:param fname: name of the file
:param selected_meta_data: If not none then only the specified columns of metadata are parsed
:return: the resulting pandas series
"""
# reads... | Parses a single meta data file
:param fname: name of the file
:param selected_meta_data: If not none then only the specified columns of metadata are parsed
:return: the resulting pandas series | Below is the the instruction that describes the task:
### Input:
Parses a single meta data file
:param fname: name of the file
:param selected_meta_data: If not none then only the specified columns of metadata are parsed
:return: the resulting pandas series
### Response:
def parse_single_me... |
def load_configuration(self):
"""Loading configuration."""
filename = os.path.join(os.path.dirname(__file__), 'templates/spline-loc.yml.j2')
with open(filename) as handle:
return Adapter(safe_load(handle)).configuration | Loading configuration. | Below is the the instruction that describes the task:
### Input:
Loading configuration.
### Response:
def load_configuration(self):
"""Loading configuration."""
filename = os.path.join(os.path.dirname(__file__), 'templates/spline-loc.yml.j2')
with open(filename) as handle:
retur... |
def clear_credentials():
"""De-authenticate by clearing all the names back to None."""
global identity, regions, services, cloudservers, cloudfiles, cloud_cdn
global cloud_loadbalancers, cloud_databases, cloud_blockstorage, cloud_dns
global cloud_networks, cloud_monitoring, autoscale, images, queues
... | De-authenticate by clearing all the names back to None. | Below is the the instruction that describes the task:
### Input:
De-authenticate by clearing all the names back to None.
### Response:
def clear_credentials():
"""De-authenticate by clearing all the names back to None."""
global identity, regions, services, cloudservers, cloudfiles, cloud_cdn
global cl... |
def _get_interpolator_nd(method, **kwargs):
'''helper function to select the appropriate interpolator class
returns interpolator class and keyword arguments for the class
'''
valid_methods = ['linear', 'nearest']
try:
from scipy import interpolate
except ImportError:
raise Impo... | helper function to select the appropriate interpolator class
returns interpolator class and keyword arguments for the class | Below is the the instruction that describes the task:
### Input:
helper function to select the appropriate interpolator class
returns interpolator class and keyword arguments for the class
### Response:
def _get_interpolator_nd(method, **kwargs):
'''helper function to select the appropriate interpolator c... |
def get_local_ep(*args, **kwargs):
"""
Warning:
DEPRECATED: Use ``globus_sdk.LocalGlobusConnectPersonal().endpoint_id`` instead.
"""
if kwargs.get("warn", True):
raise DeprecationWarning("'get_local_ep()' has been deprecated in favor of "
"'globus_sdk.Loc... | Warning:
DEPRECATED: Use ``globus_sdk.LocalGlobusConnectPersonal().endpoint_id`` instead. | Below is the the instruction that describes the task:
### Input:
Warning:
DEPRECATED: Use ``globus_sdk.LocalGlobusConnectPersonal().endpoint_id`` instead.
### Response:
def get_local_ep(*args, **kwargs):
"""
Warning:
DEPRECATED: Use ``globus_sdk.LocalGlobusConnectPersonal().endpoint_id`` in... |
def copy_data(self, project, logstore, from_time, to_time=None,
to_client=None, to_project=None, to_logstore=None,
shard_list=None,
batch_size=None, compress=None, new_topic=None, new_source=None):
"""
copy data from one logstore to another one ... | copy data from one logstore to another one (could be the same or in different region), the time is log received time on server side.
:type project: string
:param project: project name
:type logstore: string
:param logstore: logstore name
:type from_time: string/int
... | Below is the the instruction that describes the task:
### Input:
copy data from one logstore to another one (could be the same or in different region), the time is log received time on server side.
:type project: string
:param project: project name
:type logstore: string
:par... |
def on_lstUnits_itemSelectionChanged(self):
"""Update unit description label and field widgets.
.. note:: This is an automatic Qt slot
executed when the unit selection changes.
"""
self.clear_further_steps()
# Set widgets
unit = self.selected_unit()
# ... | Update unit description label and field widgets.
.. note:: This is an automatic Qt slot
executed when the unit selection changes. | Below is the the instruction that describes the task:
### Input:
Update unit description label and field widgets.
.. note:: This is an automatic Qt slot
executed when the unit selection changes.
### Response:
def on_lstUnits_itemSelectionChanged(self):
"""Update unit description label a... |
def warning_ret(f, *args, **kwargs):
"""Automatically log progress on function entry and exit. Logging
value: warning. The function's return value will be included in the logs.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted ... | Automatically log progress on function entry and exit. Logging
value: warning. The function's return value will be included in the logs.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the decorated ... | Below is the the instruction that describes the task:
### Input:
Automatically log progress on function entry and exit. Logging
value: warning. The function's return value will be included in the logs.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.