code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_trees_as_list(self):
"""
Iterator that returns the constituency trees
@rtype: L{Ctree}
@return: iterator to all the constituency trees
"""
mytrees = []
if self.constituency_layer is not None:
for tree in self.constituency_layer.get_trees():
... | Iterator that returns the constituency trees
@rtype: L{Ctree}
@return: iterator to all the constituency trees | Below is the the instruction that describes the task:
### Input:
Iterator that returns the constituency trees
@rtype: L{Ctree}
@return: iterator to all the constituency trees
### Response:
def get_trees_as_list(self):
"""
Iterator that returns the constituency trees
@rtype: ... |
def runGetRnaQuantificationSet(self, id_):
"""
Runs a getRnaQuantificationSet request for the specified ID.
"""
compoundId = datamodel.RnaQuantificationSetCompoundId.parse(id_)
dataset = self.getDataRepository().getDataset(compoundId.dataset_id)
rnaQuantificationSet = dat... | Runs a getRnaQuantificationSet request for the specified ID. | Below is the the instruction that describes the task:
### Input:
Runs a getRnaQuantificationSet request for the specified ID.
### Response:
def runGetRnaQuantificationSet(self, id_):
"""
Runs a getRnaQuantificationSet request for the specified ID.
"""
compoundId = datamodel.RnaQuant... |
def density_2d(self, x, y, Rs, rho0, r_trunc, center_x=0, center_y=0):
"""
projected two dimenstional NFW profile (kappa*Sigma_crit)
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization... | projected two dimenstional NFW profile (kappa*Sigma_crit)
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization (characteristic density)
:type rho0: float
:param r200: radius of (sub)hal... | Below is the the instruction that describes the task:
### Input:
projected two dimenstional NFW profile (kappa*Sigma_crit)
:param R: radius of interest
:type R: float/numpy array
:param Rs: scale radius
:type Rs: float
:param rho0: density normalization (characteristic densi... |
def get_abs_filename_with_sub_path(sub_path, filename):
"""
生成当前路径下一级路径某文件的完整文件名;
:param:
* sub_path: (string) 下一级的某路径名称
* filename: (string) 下一级路径的某个文件名
:returns:
* 返回类型 (tuple),有两个值,第一个为 flag,第二个为文件名,说明见下
* flag: (bool) 如果文件存在,返回 True,文件不存在... | 生成当前路径下一级路径某文件的完整文件名;
:param:
* sub_path: (string) 下一级的某路径名称
* filename: (string) 下一级路径的某个文件名
:returns:
* 返回类型 (tuple),有两个值,第一个为 flag,第二个为文件名,说明见下
* flag: (bool) 如果文件存在,返回 True,文件不存在,返回 False
* abs_filename: (string) 指定 filename 的包含路径的长文件名
... | Below is the the instruction that describes the task:
### Input:
生成当前路径下一级路径某文件的完整文件名;
:param:
* sub_path: (string) 下一级的某路径名称
* filename: (string) 下一级路径的某个文件名
:returns:
* 返回类型 (tuple),有两个值,第一个为 flag,第二个为文件名,说明见下
* flag: (bool) 如果文件存在,返回 True,文件不存在,返回 ... |
def is_cdl(filename):
'''
Quick check for .cdl ascii file
Example:
netcdf sample_file {
dimensions:
name_strlen = 7 ;
time = 96 ;
variables:
float lat ;
lat:units = "degrees_north" ;
lat:standard_name = "latitude" ;... | Quick check for .cdl ascii file
Example:
netcdf sample_file {
dimensions:
name_strlen = 7 ;
time = 96 ;
variables:
float lat ;
lat:units = "degrees_north" ;
lat:standard_name = "latitude" ;
lat:long_name = "... | Below is the the instruction that describes the task:
### Input:
Quick check for .cdl ascii file
Example:
netcdf sample_file {
dimensions:
name_strlen = 7 ;
time = 96 ;
variables:
float lat ;
lat:units = "degrees_north" ;
... |
def modify_schema(self, field_schema):
"""Modify field schema."""
field_schema['pattern'] = utilities.convert_python_regex_to_ecma(
self.pattern, self.flags) | Modify field schema. | Below is the the instruction that describes the task:
### Input:
Modify field schema.
### Response:
def modify_schema(self, field_schema):
"""Modify field schema."""
field_schema['pattern'] = utilities.convert_python_regex_to_ecma(
self.pattern, self.flags) |
def committer(self) -> Developer:
"""
Return the committer of the commit as a Developer object.
:return: committer
"""
return Developer(self._c_object.committer.name,
self._c_object.committer.email) | Return the committer of the commit as a Developer object.
:return: committer | Below is the the instruction that describes the task:
### Input:
Return the committer of the commit as a Developer object.
:return: committer
### Response:
def committer(self) -> Developer:
"""
Return the committer of the commit as a Developer object.
:return: committer
""... |
def insert_embedding(cur, source_nodelist, source_edgelist, target_nodelist, target_edgelist,
embedding, embedding_tag):
"""Insert an embedding into the cache.
Args:
cur (:class:`sqlite3.Cursor`):
An sqlite3 cursor. This function is meant to be run within a :obj:`with` ... | Insert an embedding into the cache.
Args:
cur (:class:`sqlite3.Cursor`):
An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.
source_nodelist (list):
The nodes in the source graph. Should be integer valued.
source_edgelist (list):
... | Below is the the instruction that describes the task:
### Input:
Insert an embedding into the cache.
Args:
cur (:class:`sqlite3.Cursor`):
An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement.
source_nodelist (list):
The nodes in the source ... |
def clear_lock(self, lock_type='update'):
'''
Clear update.lk
'''
lock_file = self._get_lock_file(lock_type=lock_type)
def _add_error(errlist, exc):
msg = ('Unable to remove update lock for {0} ({1}): {2} '
.format(self.url, lock_file, exc))
... | Clear update.lk | Below is the the instruction that describes the task:
### Input:
Clear update.lk
### Response:
def clear_lock(self, lock_type='update'):
'''
Clear update.lk
'''
lock_file = self._get_lock_file(lock_type=lock_type)
def _add_error(errlist, exc):
msg = ('Unable to ... |
def get_memory_tar(image_path):
'''get an in memory tar of an image. Use carefully, not as reliable
as get_image_tar
'''
byte_array = Client.image.export(image_path)
file_object = io.BytesIO(byte_array)
tar = tarfile.open(mode="r|*", fileobj=file_object)
return (file_object,tar) | get an in memory tar of an image. Use carefully, not as reliable
as get_image_tar | Below is the the instruction that describes the task:
### Input:
get an in memory tar of an image. Use carefully, not as reliable
as get_image_tar
### Response:
def get_memory_tar(image_path):
'''get an in memory tar of an image. Use carefully, not as reliable
as get_image_tar
'''
byte_ar... |
def generate_astrometric_catalog(imglist, **pars):
"""Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for ca... | Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
ref_table :... | Below is the the instruction that describes the task:
### Input:
Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be ... |
def get_built_image_info(self):
"""
query docker about built image
:return dict
"""
logger.info("getting information about built image '%s'", self.image)
image_info = self.tasker.get_image_info_by_image_name(self.image)
items_count = len(image_info)
if it... | query docker about built image
:return dict | Below is the the instruction that describes the task:
### Input:
query docker about built image
:return dict
### Response:
def get_built_image_info(self):
"""
query docker about built image
:return dict
"""
logger.info("getting information about built image '%s'", ... |
def asynciotask(
func: None = None,
*,
loop_getter: typing.Union[
typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop
] = asyncio.get_event_loop,
loop_getter_need_context: bool = False,
) -> AsyncIOTask:
"""Overload: no function.""" | Overload: no function. | Below is the the instruction that describes the task:
### Input:
Overload: no function.
### Response:
def asynciotask(
func: None = None,
*,
loop_getter: typing.Union[
typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop
] = asyncio.get_event_loop,
loop_getter_need... |
def compose_config(self):
""" Generate phantom tool run config """
streams_config = ''
stat_benchmarks = ''
for stream in self.streams:
streams_config += stream.compose_config()
if not stream.is_main:
stat_benchmarks += " " + "benchma... | Generate phantom tool run config | Below is the the instruction that describes the task:
### Input:
Generate phantom tool run config
### Response:
def compose_config(self):
""" Generate phantom tool run config """
streams_config = ''
stat_benchmarks = ''
for stream in self.streams:
streams_c... |
def render(self,
data,
chart_type,
chart_package='corechart',
options=None,
div_id="chart",
head=""):
"""Render the data in HTML template."""
if not self.is_valid_name(div_id):
raise ValueError(
... | Render the data in HTML template. | Below is the the instruction that describes the task:
### Input:
Render the data in HTML template.
### Response:
def render(self,
data,
chart_type,
chart_package='corechart',
options=None,
div_id="chart",
head=""):
""... |
def get_template(template_name, data_dir=None, url=None, resume=True, verbose=1):
"""Download and load a template"""
warn(DEPRECATION_MSG)
if template_name.startswith('tpl-'):
template_name = template_name[4:]
# An aliasing mechanism. Please avoid
template_name = TEMPLATE_ALIASES.get(templa... | Download and load a template | Below is the the instruction that describes the task:
### Input:
Download and load a template
### Response:
def get_template(template_name, data_dir=None, url=None, resume=True, verbose=1):
"""Download and load a template"""
warn(DEPRECATION_MSG)
if template_name.startswith('tpl-'):
template_na... |
def isempty(result):
''' Finds out if a scraping result should be considered empty. '''
if isinstance(result, list):
for element in result:
if isinstance(element, list):
if not isempty(element):
return False
else:
if element is not None:
return False
else:
if result is not None:
retur... | Finds out if a scraping result should be considered empty. | Below is the the instruction that describes the task:
### Input:
Finds out if a scraping result should be considered empty.
### Response:
def isempty(result):
''' Finds out if a scraping result should be considered empty. '''
if isinstance(result, list):
for element in result:
if isinstance(element, list):... |
def setupMobileTerminated(RepeatIndicator_presence=0,
BearerCapability_presence=0,
BearerCapability_presence1=0,
Facility_presence=0, ProgressIndicator_presence=0,
Signal_presence=0,
Calling... | SETUP Section 9.3.23.1 | Below is the the instruction that describes the task:
### Input:
SETUP Section 9.3.23.1
### Response:
def setupMobileTerminated(RepeatIndicator_presence=0,
BearerCapability_presence=0,
BearerCapability_presence1=0,
Facility_presence=0, P... |
def get_absolute_tool_path(command):
"""
Given an invocation command,
return the absolute path to the command. This works even if commnad
has not path element and is present in PATH.
"""
assert isinstance(command, basestring)
if os.path.dirname(command):
return os.path.di... | Given an invocation command,
return the absolute path to the command. This works even if commnad
has not path element and is present in PATH. | Below is the the instruction that describes the task:
### Input:
Given an invocation command,
return the absolute path to the command. This works even if commnad
has not path element and is present in PATH.
### Response:
def get_absolute_tool_path(command):
"""
Given an invocation comma... |
def mac_addr_info():
"""Returns mac address.
"""
mac = get_mac()
if mac == get_mac(): # not random generated
hexa = '%012x' % mac
value = ':'.join(hexa[i:i+2] for i in range(0, 12, 2))
else:
value = None
return {'mac': value} | Returns mac address. | Below is the the instruction that describes the task:
### Input:
Returns mac address.
### Response:
def mac_addr_info():
"""Returns mac address.
"""
mac = get_mac()
if mac == get_mac(): # not random generated
hexa = '%012x' % mac
value = ':'.join(hexa[i:i+2] for i in range(0, 12, 2... |
def binning(keys, start, end, count, axes=None):
"""Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10)
"""
if isinstance(keys, tuple):
n_keys = len(keys)
e... | Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10) | Below is the the instruction that describes the task:
### Input:
Perform binning over the given axes of the keys
Parameters
----------
keys : indexable or tuple of indexable
Examples
--------
binning(np.random.rand(100), 0, 1, 10)
### Response:
def binning(keys, start, end, count, axes=No... |
def sync(self, sync_set, force=0, site=None, role=None):
"""
Uploads media to an Amazon S3 bucket using s3sync.
Requires s3cmd. Install with:
pip install s3cmd
"""
from burlap.dj import dj
force = int(force)
r = self.local_renderer
r.env.s... | Uploads media to an Amazon S3 bucket using s3sync.
Requires s3cmd. Install with:
pip install s3cmd | Below is the the instruction that describes the task:
### Input:
Uploads media to an Amazon S3 bucket using s3sync.
Requires s3cmd. Install with:
pip install s3cmd
### Response:
def sync(self, sync_set, force=0, site=None, role=None):
"""
Uploads media to an Amazon S3 bucket u... |
def open(self, _file, target=DEFAULT_TARGET):
"""
Open the existing file for reading.
@param _file : A filename of file descriptor.
@param target: A user-specific BFD target name.
@return : None
"""
# Close any existing BFD structure instance.
self.clos... | Open the existing file for reading.
@param _file : A filename of file descriptor.
@param target: A user-specific BFD target name.
@return : None | Below is the the instruction that describes the task:
### Input:
Open the existing file for reading.
@param _file : A filename of file descriptor.
@param target: A user-specific BFD target name.
@return : None
### Response:
def open(self, _file, target=DEFAULT_TARGET):
"""
... |
def cleanup(self):
"""
Attempt to switch the device off or put into low power mode (this
helps prolong the life of the device), clear the screen and close
resources associated with the underlying serial interface.
If :py:attr:`persist` is ``True``, the device will not be switche... | Attempt to switch the device off or put into low power mode (this
helps prolong the life of the device), clear the screen and close
resources associated with the underlying serial interface.
If :py:attr:`persist` is ``True``, the device will not be switched off.
This is a managed funct... | Below is the the instruction that describes the task:
### Input:
Attempt to switch the device off or put into low power mode (this
helps prolong the life of the device), clear the screen and close
resources associated with the underlying serial interface.
If :py:attr:`persist` is ``True``, ... |
def _init_map(self, record_types=None, **kwargs):
"""Initialize form map"""
osid_objects.OsidObjectForm._init_map(self, record_types=record_types)
self._my_map['nextAssessmentPartId'] = str(kwargs['next_assessment_part_id'])
self._my_map['cumulative'] = self._cumulative_default
s... | Initialize form map | Below is the the instruction that describes the task:
### Input:
Initialize form map
### Response:
def _init_map(self, record_types=None, **kwargs):
"""Initialize form map"""
osid_objects.OsidObjectForm._init_map(self, record_types=record_types)
self._my_map['nextAssessmentPartId'] = str(kw... |
def _is_uuid(uuid):
'''
Check if uuid is a valid smartos uuid
Example: e69a0918-055d-11e5-8912-e3ceb6df4cf8
'''
if uuid and list((len(x) for x in uuid.split('-'))) == [8, 4, 4, 4, 12]:
return True
return False | Check if uuid is a valid smartos uuid
Example: e69a0918-055d-11e5-8912-e3ceb6df4cf8 | Below is the the instruction that describes the task:
### Input:
Check if uuid is a valid smartos uuid
Example: e69a0918-055d-11e5-8912-e3ceb6df4cf8
### Response:
def _is_uuid(uuid):
'''
Check if uuid is a valid smartos uuid
Example: e69a0918-055d-11e5-8912-e3ceb6df4cf8
'''
if uuid and li... |
def reducePrecision(element):
"""
Because opacities, letter spacings, stroke widths and all that don't need
to be preserved in SVG files with 9 digits of precision.
Takes all of these attributes, in the given element node and its children,
and reduces their precision to the current Decimal context'... | Because opacities, letter spacings, stroke widths and all that don't need
to be preserved in SVG files with 9 digits of precision.
Takes all of these attributes, in the given element node and its children,
and reduces their precision to the current Decimal context's precision.
Also checks for the attri... | Below is the the instruction that describes the task:
### Input:
Because opacities, letter spacings, stroke widths and all that don't need
to be preserved in SVG files with 9 digits of precision.
Takes all of these attributes, in the given element node and its children,
and reduces their precision to t... |
def aliases(self):
"""
Returns dict with aliases names as keys and pairs of actual
subcommand and alias args as values.
"""
aliases = self.cp.items('aliases')
alias_dict = dict()
for alias, meaning in aliases:
try:
meaning = shlex.spli... | Returns dict with aliases names as keys and pairs of actual
subcommand and alias args as values. | Below is the the instruction that describes the task:
### Input:
Returns dict with aliases names as keys and pairs of actual
subcommand and alias args as values.
### Response:
def aliases(self):
"""
Returns dict with aliases names as keys and pairs of actual
subcommand and alias arg... |
def normalize_whitespace(self, value):
"""Normalizes whitespace; called if ``ignore_ws`` is true."""
if isinstance(value, unicode):
return u" ".join(
x for x in re.split(r'\s+', value, flags=re.UNICODE) if
len(x)
)
else:
return ... | Normalizes whitespace; called if ``ignore_ws`` is true. | Below is the the instruction that describes the task:
### Input:
Normalizes whitespace; called if ``ignore_ws`` is true.
### Response:
def normalize_whitespace(self, value):
"""Normalizes whitespace; called if ``ignore_ws`` is true."""
if isinstance(value, unicode):
return u" ".join(
... |
def get_build_path(self):
"""
Used to determine where to build the page. Override this if you
would like your page at a different location. By default it
will be built at self.get_url() + "/index.html"
"""
target_path = path.join(settings.BUILD_DIR, self.get_url().lstrip(... | Used to determine where to build the page. Override this if you
would like your page at a different location. By default it
will be built at self.get_url() + "/index.html" | Below is the the instruction that describes the task:
### Input:
Used to determine where to build the page. Override this if you
would like your page at a different location. By default it
will be built at self.get_url() + "/index.html"
### Response:
def get_build_path(self):
"""
Us... |
def listener(self, sock, *args):
'''Asynchronous connection listener. Starts a handler for each connection.'''
conn, addr = sock.accept()
f = conn.makefile(conn)
self.shell = ShoebotCmd(self.bot, stdin=f, stdout=f, intro=INTRO)
print(_("Connected"))
GObject.io_add_watch(... | Asynchronous connection listener. Starts a handler for each connection. | Below is the the instruction that describes the task:
### Input:
Asynchronous connection listener. Starts a handler for each connection.
### Response:
def listener(self, sock, *args):
'''Asynchronous connection listener. Starts a handler for each connection.'''
conn, addr = sock.accept()
f ... |
def save_ipyvolumejs(
target="", devmode=False, version=ipyvolume._version.__version_js__, version3js=__version_threejs__
):
"""Output the ipyvolume javascript to a local file.
:type target: str
:param bool devmode: if True get index.js from js/dist directory
:param str version: version number of i... | Output the ipyvolume javascript to a local file.
:type target: str
:param bool devmode: if True get index.js from js/dist directory
:param str version: version number of ipyvolume
:param str version3js: version number of threejs | Below is the the instruction that describes the task:
### Input:
Output the ipyvolume javascript to a local file.
:type target: str
:param bool devmode: if True get index.js from js/dist directory
:param str version: version number of ipyvolume
:param str version3js: version number of threejs
### R... |
def clean_source_index(self):
"""
Cleanup broken symbolic links in the local source distribution index.
The purpose of this method requires some context to understand. Let me
preface this by stating that I realize I'm probably overcomplicating
things, but I like to preserve forw... | Cleanup broken symbolic links in the local source distribution index.
The purpose of this method requires some context to understand. Let me
preface this by stating that I realize I'm probably overcomplicating
things, but I like to preserve forward / backward compatibility when
possible... | Below is the the instruction that describes the task:
### Input:
Cleanup broken symbolic links in the local source distribution index.
The purpose of this method requires some context to understand. Let me
preface this by stating that I realize I'm probably overcomplicating
things, but I li... |
def handle_wikidata_errors(data, query):
"""
Raises LookupError if wikidata error found
"""
entities = data.get('entities')
if not entities:
raise LookupError(query)
elif '-1' in entities:
raise LookupError(query)
else:
item = list(entities.values())[0]
if 'm... | Raises LookupError if wikidata error found | Below is the the instruction that describes the task:
### Input:
Raises LookupError if wikidata error found
### Response:
def handle_wikidata_errors(data, query):
"""
Raises LookupError if wikidata error found
"""
entities = data.get('entities')
if not entities:
raise LookupError(query... |
def BGPSessionState_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
BGPSessionState = ET.SubElement(config, "BGPSessionState", xmlns="http://brocade.com/ns/brocade-notification-stream")
originator_switch_info = ET... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def BGPSessionState_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
BGPSessionState = ET.SubElement(config, "BGPSessi... |
def get_access_token(tenant_id, application_id, application_secret):
'''get an Azure access token using the adal library.
Args:
tenant_id (str): Tenant id of the user's account.
application_id (str): Application id of a Service Principal account.
application_secret (str): Application se... | get an Azure access token using the adal library.
Args:
tenant_id (str): Tenant id of the user's account.
application_id (str): Application id of a Service Principal account.
application_secret (str): Application secret (password) of the Service Principal account.
Returns:
An A... | Below is the the instruction that describes the task:
### Input:
get an Azure access token using the adal library.
Args:
tenant_id (str): Tenant id of the user's account.
application_id (str): Application id of a Service Principal account.
application_secret (str): Application secret (p... |
def pull(config, repo, tag=None, username=None, password=None, email=None, *args, **kwargs):
'''
Pulls an repo from any registry. See above documentation for
how to configure authenticated access.
:type repo: string
:param repo: The repository to pull. \
[registryurl://]REPOSITORY_NAME
... | Pulls an repo from any registry. See above documentation for
how to configure authenticated access.
:type repo: string
:param repo: The repository to pull. \
[registryurl://]REPOSITORY_NAME
eg::
index.docker.io:MyRepo
superaddress.cdn:MyRepo
MyRepo
... | Below is the the instruction that describes the task:
### Input:
Pulls an repo from any registry. See above documentation for
how to configure authenticated access.
:type repo: string
:param repo: The repository to pull. \
[registryurl://]REPOSITORY_NAME
eg::
index.docker.i... |
def set_subject(self,subject):
"""
Send a subject change request to the room.
:Parameters:
- `subject`: the new subject.
:Types:
- `subject`: `unicode`
"""
m=Message(to_jid=self.room_jid.bare(),stanza_type="groupchat",subject=subject)
self... | Send a subject change request to the room.
:Parameters:
- `subject`: the new subject.
:Types:
- `subject`: `unicode` | Below is the the instruction that describes the task:
### Input:
Send a subject change request to the room.
:Parameters:
- `subject`: the new subject.
:Types:
- `subject`: `unicode`
### Response:
def set_subject(self,subject):
"""
Send a subject change reque... |
def calc_schm_wats_v1(self):
"""Calculate the actual amount of water melting within the snow cover.
Required control parameters:
|NHRU|
|Lnk|
Required flux sequences:
|SBes|
|WGTF|
Calculated flux sequence:
|Schm|
Updated state sequence:
|WATS|
Basic equa... | Calculate the actual amount of water melting within the snow cover.
Required control parameters:
|NHRU|
|Lnk|
Required flux sequences:
|SBes|
|WGTF|
Calculated flux sequence:
|Schm|
Updated state sequence:
|WATS|
Basic equations:
:math:`\\frac{dWATS}{dt... | Below is the the instruction that describes the task:
### Input:
Calculate the actual amount of water melting within the snow cover.
Required control parameters:
|NHRU|
|Lnk|
Required flux sequences:
|SBes|
|WGTF|
Calculated flux sequence:
|Schm|
Updated state seque... |
def get_item_creator(item_type):
"""Get item creator according registered item type.
:param item_type: The type of item to be checed.
:type item_type: types.TypeType.
:returns: Creator function. None if type not found.
"""
if item_type not in Pipe.pipe_item_types:
for registered_type in... | Get item creator according registered item type.
:param item_type: The type of item to be checed.
:type item_type: types.TypeType.
:returns: Creator function. None if type not found. | Below is the the instruction that describes the task:
### Input:
Get item creator according registered item type.
:param item_type: The type of item to be checed.
:type item_type: types.TypeType.
:returns: Creator function. None if type not found.
### Response:
def get_item_creator(item_type):
"""... |
def list_trilegal_filtersystems():
'''
This just lists all the filter systems available for TRILEGAL.
'''
print('%-40s %s' % ('FILTER SYSTEM NAME','DESCRIPTION'))
print('%-40s %s' % ('------------------','-----------'))
for key in sorted(TRILEGAL_FILTER_SYSTEMS.keys()):
print('%-40s %s... | This just lists all the filter systems available for TRILEGAL. | Below is the the instruction that describes the task:
### Input:
This just lists all the filter systems available for TRILEGAL.
### Response:
def list_trilegal_filtersystems():
'''
This just lists all the filter systems available for TRILEGAL.
'''
print('%-40s %s' % ('FILTER SYSTEM NAME','DESCRIP... |
def get_ip_interface_output_interface_vrf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubEle... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_ip_interface_output_interface_vrf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = g... |
def label(self, name, internal=False, definition=False):
"""Generates label name (helper function)
name - label name
internal - boolean value, adds "@" prefix to label
definition - boolean value, adds ":" suffix to label
"""
return "{0}{1}{2}".format(self.i... | Generates label name (helper function)
name - label name
internal - boolean value, adds "@" prefix to label
definition - boolean value, adds ":" suffix to label | Below is the the instruction that describes the task:
### Input:
Generates label name (helper function)
name - label name
internal - boolean value, adds "@" prefix to label
definition - boolean value, adds ":" suffix to label
### Response:
def label(self, name, internal=False, d... |
def wrap_sequence(sequence, books=None, tensor_shape=None):
"""Creates an input layer representing the given sequence of tensors.
Args:
sequence: A sequence of tensors.
books: The bookkeeper.
tensor_shape: An optional shape that will be set on the Tensor or verified
to match the tensor.
Returns... | Creates an input layer representing the given sequence of tensors.
Args:
sequence: A sequence of tensors.
books: The bookkeeper.
tensor_shape: An optional shape that will be set on the Tensor or verified
to match the tensor.
Returns:
A layer. | Below is the the instruction that describes the task:
### Input:
Creates an input layer representing the given sequence of tensors.
Args:
sequence: A sequence of tensors.
books: The bookkeeper.
tensor_shape: An optional shape that will be set on the Tensor or verified
to match the tensor.
Ret... |
def schedule(target=None, args=(), kwargs=None):
"""insert a greenlet into the scheduler
If provided a function, it is wrapped in a new greenlet
:param target: what to schedule
:type target: function or greenlet
:param args:
arguments for the function (only used if ``target`` is a function... | insert a greenlet into the scheduler
If provided a function, it is wrapped in a new greenlet
:param target: what to schedule
:type target: function or greenlet
:param args:
arguments for the function (only used if ``target`` is a function)
:type args: tuple
:param kwargs:
keywo... | Below is the the instruction that describes the task:
### Input:
insert a greenlet into the scheduler
If provided a function, it is wrapped in a new greenlet
:param target: what to schedule
:type target: function or greenlet
:param args:
arguments for the function (only used if ``target`` ... |
def start (self):
'''
Starts (Subscribes) the client.
'''
self.subrgb = rospy.Subscriber(self.topicrgb, ImageROS)
self.subd = rospy.Subscriber(self.topicd, ImageROS)
self.ts = message_filters.ApproximateTimeSynchronizer([subrgb, subd], 1, 0.1, allow_headerless=True)
... | Starts (Subscribes) the client. | Below is the the instruction that describes the task:
### Input:
Starts (Subscribes) the client.
### Response:
def start (self):
'''
Starts (Subscribes) the client.
'''
self.subrgb = rospy.Subscriber(self.topicrgb, ImageROS)
self.subd = rospy.Subscriber(self.topicd, ImageRO... |
def build_ml_phyml(alignment, outfile, work_dir=".", **kwargs):
"""
build maximum likelihood tree of DNA seqs with PhyML
"""
phy_file = op.join(work_dir, "work", "aln.phy")
AlignIO.write(alignment, file(phy_file, "w"), "phylip-relaxed")
phyml_cl = PhymlCommandline(cmd=PHYML_BIN("phyml"), input=... | build maximum likelihood tree of DNA seqs with PhyML | Below is the the instruction that describes the task:
### Input:
build maximum likelihood tree of DNA seqs with PhyML
### Response:
def build_ml_phyml(alignment, outfile, work_dir=".", **kwargs):
"""
build maximum likelihood tree of DNA seqs with PhyML
"""
phy_file = op.join(work_dir, "work", "aln.... |
def _setup_adc(self, flags):
'''Initialize ADC
'''
self._intf.write(self._base_addr + self.MAX11644_ADD, array('B', pack('B', flags | self.MAX11644_SETUP))) | Initialize ADC | Below is the the instruction that describes the task:
### Input:
Initialize ADC
### Response:
def _setup_adc(self, flags):
'''Initialize ADC
'''
self._intf.write(self._base_addr + self.MAX11644_ADD, array('B', pack('B', flags | self.MAX11644_SETUP))) |
def allLinesMatchingPattern(pattern, lines):
""" Like lineMatchingPattern, but returns all lines that match the specified pattern
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: list of re.Match objects for each line matched, or an empty list if ... | Like lineMatchingPattern, but returns all lines that match the specified pattern
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: list of re.Match objects for each line matched, or an empty list if none matched
:rtype: list | Below is the the instruction that describes the task:
### Input:
Like lineMatchingPattern, but returns all lines that match the specified pattern
:type pattern: Compiled regular expression pattern to use
:type lines: List of lines to search
:return: list of re.Match objects for each line matched, or a... |
def get_stats(self, start=int(time()), stop=int(time())+10, step=10):
"""
Get stats of a monitored machine
:param start: Time formatted as integer, from when to fetch stats (default now)
:param stop: Time formatted as integer, until when to fetch stats (default +10 seconds)
:par... | Get stats of a monitored machine
:param start: Time formatted as integer, from when to fetch stats (default now)
:param stop: Time formatted as integer, until when to fetch stats (default +10 seconds)
:param step: Step to fetch stats (default 10 seconds)
:returns: A dict of stats | Below is the the instruction that describes the task:
### Input:
Get stats of a monitored machine
:param start: Time formatted as integer, from when to fetch stats (default now)
:param stop: Time formatted as integer, until when to fetch stats (default +10 seconds)
:param step: Step to fetc... |
def MakeParser(prog):
"""Create an argument parser.
Args:
prog: The name of the program to use when outputting help text.
Returns:
An argparse.ArgumentParser built to specification.
"""
def AddStandardOptions(parser, *args):
"""Add common endpoints options to a parser.
Args:
parser: ... | Create an argument parser.
Args:
prog: The name of the program to use when outputting help text.
Returns:
An argparse.ArgumentParser built to specification. | Below is the the instruction that describes the task:
### Input:
Create an argument parser.
Args:
prog: The name of the program to use when outputting help text.
Returns:
An argparse.ArgumentParser built to specification.
### Response:
def MakeParser(prog):
"""Create an argument parser.
Args:
... |
def set_estimator_and_feature_spec(self, estimator, feature_spec):
"""Sets the model for inference as a TF Estimator.
Instead of using TF Serving to host a model for WIT to query, WIT can
directly use a TF Estimator object as the model to query. In order to
accomplish this, a feature_spec must also be ... | Sets the model for inference as a TF Estimator.
Instead of using TF Serving to host a model for WIT to query, WIT can
directly use a TF Estimator object as the model to query. In order to
accomplish this, a feature_spec must also be provided to parse the
example protos for input into the estimator.
... | Below is the the instruction that describes the task:
### Input:
Sets the model for inference as a TF Estimator.
Instead of using TF Serving to host a model for WIT to query, WIT can
directly use a TF Estimator object as the model to query. In order to
accomplish this, a feature_spec must also be provi... |
def yield_pair_gradients(self, index1, index2):
"""Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))"""
d_2 = 1/self.distances[index1, index2]**2
if self.charges is not None:
c1 = self.charges[index1]
c2 = self.charges[index2]
yield -c1*c2*d_2, np.zeros(3)
... | Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij)) | Below is the the instruction that describes the task:
### Input:
Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))
### Response:
def yield_pair_gradients(self, index1, index2):
"""Yields pairs ((s'(r_ij), grad_i v(bar{r}_ij))"""
d_2 = 1/self.distances[index1, index2]**2
if self.charges is not N... |
def load(path):
'''
Load additional configuration from the specified file.
path
Path to the configuration file.
CLI Example:
.. code-block:: bash
salt '*' vmctl.load path=/etc/vm.switches.conf
'''
ret = False
cmd = 'vmctl load {0}'.format(path)
result = __salt__['... | Load additional configuration from the specified file.
path
Path to the configuration file.
CLI Example:
.. code-block:: bash
salt '*' vmctl.load path=/etc/vm.switches.conf | Below is the the instruction that describes the task:
### Input:
Load additional configuration from the specified file.
path
Path to the configuration file.
CLI Example:
.. code-block:: bash
salt '*' vmctl.load path=/etc/vm.switches.conf
### Response:
def load(path):
'''
Loa... |
def _fetchall(self, query, vars, limit=None, offset=0):
"""
Return multiple rows.
"""
if limit is None:
limit = current_app.config['DEFAULT_PAGE_SIZE']
query += ' LIMIT %s OFFSET %s''' % (limit, offset)
cursor = self.get_db().cursor()
self._log(cursor,... | Return multiple rows. | Below is the the instruction that describes the task:
### Input:
Return multiple rows.
### Response:
def _fetchall(self, query, vars, limit=None, offset=0):
"""
Return multiple rows.
"""
if limit is None:
limit = current_app.config['DEFAULT_PAGE_SIZE']
query += '... |
def scan_and_reimport(mod_type: str) -> List[Tuple[str, str]]:
"""Scans folder for modules."""
mod_enabled, mod_disabled = get_modules(mod_type)
errors = []
for mod in mod_enabled + mod_disabled:
if mod in sys.modules:
msg = safe_reload(sys.modules[mod])
else:
msg... | Scans folder for modules. | Below is the the instruction that describes the task:
### Input:
Scans folder for modules.
### Response:
def scan_and_reimport(mod_type: str) -> List[Tuple[str, str]]:
"""Scans folder for modules."""
mod_enabled, mod_disabled = get_modules(mod_type)
errors = []
for mod in mod_enabled + mod_disabled... |
def CheckPreviousBarline(self, staff):
"""method which checks the bar before the current for changes we need to make to it's barlines"""
measure_before_last = self.getMeasureAtPosition(-2, staff)
last_measure = self.getMeasureAtPosition(-1, staff)
if last_measure is not None and measure_... | method which checks the bar before the current for changes we need to make to it's barlines | Below is the the instruction that describes the task:
### Input:
method which checks the bar before the current for changes we need to make to it's barlines
### Response:
def CheckPreviousBarline(self, staff):
"""method which checks the bar before the current for changes we need to make to it's barlines"""... |
def createLogger(name, level=logging.WARNING):
""":Return: a logger with the given `name` and optional `level`."""
logger = logging.getLogger(name)
logger.setLevel(level)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s'))
... | :Return: a logger with the given `name` and optional `level`. | Below is the the instruction that describes the task:
### Input:
:Return: a logger with the given `name` and optional `level`.
### Response:
def createLogger(name, level=logging.WARNING):
""":Return: a logger with the given `name` and optional `level`."""
logger = logging.getLogger(name)
logger.setLeve... |
def IsDirty(self, proto):
"""Return and clear the dirty state of the python object."""
if proto.dirty:
return True
for python_format, _, type_descriptor in itervalues(proto.GetRawData()):
if python_format is not None and type_descriptor.IsDirty(python_format):
proto.dirty = True
... | Return and clear the dirty state of the python object. | Below is the the instruction that describes the task:
### Input:
Return and clear the dirty state of the python object.
### Response:
def IsDirty(self, proto):
"""Return and clear the dirty state of the python object."""
if proto.dirty:
return True
for python_format, _, type_descriptor in iterva... |
def _save_nb(nb_name):
"""
Attempts to save notebook. If unsuccessful, shows a warning.
"""
display(Javascript('IPython.notebook.save_checkpoint();'))
display(Javascript('IPython.notebook.save_notebook();'))
print('Saving notebook...', end=' ')
if _wait_for_save(nb_name):
print("Sav... | Attempts to save notebook. If unsuccessful, shows a warning. | Below is the the instruction that describes the task:
### Input:
Attempts to save notebook. If unsuccessful, shows a warning.
### Response:
def _save_nb(nb_name):
"""
Attempts to save notebook. If unsuccessful, shows a warning.
"""
display(Javascript('IPython.notebook.save_checkpoint();'))
disp... |
def paginate_get(self, url,
headers=None,
return_json=True,
start_page=None):
'''paginate_call is a wrapper for get to paginate results
'''
geturl = '%s&page=1' %(url)
if start_page is not None:
geturl = '%s&page=%s' %(url,start_page)
re... | paginate_call is a wrapper for get to paginate results | Below is the the instruction that describes the task:
### Input:
paginate_call is a wrapper for get to paginate results
### Response:
def paginate_get(self, url,
headers=None,
return_json=True,
start_page=None):
'''paginate_call is a wrapper for get to pagin... |
def increment_version(context):
"""Increments the __version__ attribute of your module's __init__."""
attributes.replace_attribute(
context.module_name, '__version__', context.new_version, dry_run=context.dry_run
)
log.info(
'Bumped version from %s to %s' % (context.current_version, con... | Increments the __version__ attribute of your module's __init__. | Below is the the instruction that describes the task:
### Input:
Increments the __version__ attribute of your module's __init__.
### Response:
def increment_version(context):
"""Increments the __version__ attribute of your module's __init__."""
attributes.replace_attribute(
context.module_name, '_... |
def check_mismatches(read, pair, mismatches, mm_option, req_map):
"""
- check to see if the read maps with <= threshold number of mismatches
- mm_option = 'one' or 'both' depending on whether or not one or both reads
in a pair need to pass the mismatch threshold
- pair can be False if read does n... | - check to see if the read maps with <= threshold number of mismatches
- mm_option = 'one' or 'both' depending on whether or not one or both reads
in a pair need to pass the mismatch threshold
- pair can be False if read does not have a pair
- make sure alignment score is not 0, which would indicate ... | Below is the the instruction that describes the task:
### Input:
- check to see if the read maps with <= threshold number of mismatches
- mm_option = 'one' or 'both' depending on whether or not one or both reads
in a pair need to pass the mismatch threshold
- pair can be False if read does not have a... |
def execute_undo(self, message):
"""
Manage the response when the server rejects a message.
An undo is when required this client sends a message that the server
refuses to pass on to the other clients playing the game. When this
happens, the client must undo the changes that ... | Manage the response when the server rejects a message.
An undo is when required this client sends a message that the server
refuses to pass on to the other clients playing the game. When this
happens, the client must undo the changes that the message made to the
world before being s... | Below is the the instruction that describes the task:
### Input:
Manage the response when the server rejects a message.
An undo is when required this client sends a message that the server
refuses to pass on to the other clients playing the game. When this
happens, the client must undo t... |
def add_aux_param(self, param_name, layer_index, blob_index):
"""Add an aux param to .params file. Example: moving_mean in BatchNorm layer """
self.add_param('aux:%s' % param_name, layer_index, blob_index) | Add an aux param to .params file. Example: moving_mean in BatchNorm layer | Below is the the instruction that describes the task:
### Input:
Add an aux param to .params file. Example: moving_mean in BatchNorm layer
### Response:
def add_aux_param(self, param_name, layer_index, blob_index):
"""Add an aux param to .params file. Example: moving_mean in BatchNorm layer """
sel... |
def write_table(self):
"""
|write_table| with HTML table format.
:Example:
:ref:`example-html-table-writer`
.. note::
- |None| is not written
"""
tags = _get_tags_module()
with self._logger:
self._verify_property()
... | |write_table| with HTML table format.
:Example:
:ref:`example-html-table-writer`
.. note::
- |None| is not written | Below is the the instruction that describes the task:
### Input:
|write_table| with HTML table format.
:Example:
:ref:`example-html-table-writer`
.. note::
- |None| is not written
### Response:
def write_table(self):
"""
|write_table| with HTML table format... |
def train_input_fn(params):
"""Load and return dataset of batched examples for use during training."""
file_pattern = os.path.join(getattr(params, "data_dir", ""), "*encoded-train*")
return _read_and_batch_from_files(
file_pattern, params.batch_size, params.max_length, params.num_cpu_cores,
shuffle=Tr... | Load and return dataset of batched examples for use during training. | Below is the the instruction that describes the task:
### Input:
Load and return dataset of batched examples for use during training.
### Response:
def train_input_fn(params):
"""Load and return dataset of batched examples for use during training."""
file_pattern = os.path.join(getattr(params, "data_dir", ""),... |
def get_distance_matrix(self):
"""
Compute and return distances between each pairs of points in the mesh.
This method requires that the coordinate arrays are one-dimensional.
NB: the depth of the points is ignored
.. warning::
Because of its quadratic space and time... | Compute and return distances between each pairs of points in the mesh.
This method requires that the coordinate arrays are one-dimensional.
NB: the depth of the points is ignored
.. warning::
Because of its quadratic space and time complexity this method
is safe to use ... | Below is the the instruction that describes the task:
### Input:
Compute and return distances between each pairs of points in the mesh.
This method requires that the coordinate arrays are one-dimensional.
NB: the depth of the points is ignored
.. warning::
Because of its quadra... |
def vertical_headers(self, value):
"""
Setter for **self.__vertical_headers** attribute.
:param value: Attribute value.
:type value: OrderedDict
"""
if value is not None:
assert type(value) is OrderedDict, "'{0}' attribute: '{1}' type is not 'OrderedDict'!".... | Setter for **self.__vertical_headers** attribute.
:param value: Attribute value.
:type value: OrderedDict | Below is the the instruction that describes the task:
### Input:
Setter for **self.__vertical_headers** attribute.
:param value: Attribute value.
:type value: OrderedDict
### Response:
def vertical_headers(self, value):
"""
Setter for **self.__vertical_headers** attribute.
... |
def _connect(self):
"""
Connexion à la base XAIR
"""
try:
# On passe par Oracle Instant Client avec le TNS ORA_FULL
self.conn = cx_Oracle.connect(self._ORA_FULL)
self.cursor = self.conn.cursor()
print('XAIR: Connexion établie')
exc... | Connexion à la base XAIR | Below is the the instruction that describes the task:
### Input:
Connexion à la base XAIR
### Response:
def _connect(self):
"""
Connexion à la base XAIR
"""
try:
# On passe par Oracle Instant Client avec le TNS ORA_FULL
self.conn = cx_Oracle.connect(self._OR... |
def verify(password, hash):
"""
Verify a password against a passed hash
"""
_, algorithm, cost, salt, password_hash = hash.split("$")
password = pbkdf2.pbkdf2_hex(password, salt, int(cost) * 500)
return _safe_str_cmp(password, password_hash) | Verify a password against a passed hash | Below is the the instruction that describes the task:
### Input:
Verify a password against a passed hash
### Response:
def verify(password, hash):
"""
Verify a password against a passed hash
"""
_, algorithm, cost, salt, password_hash = hash.split("$")
password = pbkdf2.pbkdf2_hex(password, sa... |
def get_distinct_values_from_cols(self, l_col_list):
"""
returns the list of distinct combinations in a dataset
based on the columns in the list. Note that this is
currently implemented as MAX permutations of the combo
so it is not guarenteed to have values in each case.
... | returns the list of distinct combinations in a dataset
based on the columns in the list. Note that this is
currently implemented as MAX permutations of the combo
so it is not guarenteed to have values in each case. | Below is the the instruction that describes the task:
### Input:
returns the list of distinct combinations in a dataset
based on the columns in the list. Note that this is
currently implemented as MAX permutations of the combo
so it is not guarenteed to have values in each case.
### Respons... |
def import_and_get_class(path_to_pex, python_class_name):
"""Imports and load a class from a given pex file path and python class name
For example, if you want to get a class called `Sample` in
/some-path/sample.pex/heron/examples/src/python/sample.py,
``path_to_pex`` needs to be ``/some-path/sample.pex``, and... | Imports and load a class from a given pex file path and python class name
For example, if you want to get a class called `Sample` in
/some-path/sample.pex/heron/examples/src/python/sample.py,
``path_to_pex`` needs to be ``/some-path/sample.pex``, and
``python_class_name`` needs to be ``heron.examples.src.pytho... | Below is the the instruction that describes the task:
### Input:
Imports and load a class from a given pex file path and python class name
For example, if you want to get a class called `Sample` in
/some-path/sample.pex/heron/examples/src/python/sample.py,
``path_to_pex`` needs to be ``/some-path/sample.pex`... |
def kill_ghosts():
"""
Kill process from previous GNS3 session
"""
detect_process = ["vpcs", "ubridge", "dynamips"]
for proc in psutil.process_iter():
try:
name = proc.name().lower().split(".")[0]
if name in detect_process:
proc.kill()
... | Kill process from previous GNS3 session | Below is the the instruction that describes the task:
### Input:
Kill process from previous GNS3 session
### Response:
def kill_ghosts():
"""
Kill process from previous GNS3 session
"""
detect_process = ["vpcs", "ubridge", "dynamips"]
for proc in psutil.process_iter():
try:
... |
def authenticate(org):
"""
Authenticate with GitHub via SSH if possible
Otherwise authenticate via HTTPS
Returns an authenticated User
"""
with ProgressBar(_("Authenticating")) as progress_bar:
user = _authenticate_ssh(org)
progress_bar.stop()
if user is None:
... | Authenticate with GitHub via SSH if possible
Otherwise authenticate via HTTPS
Returns an authenticated User | Below is the the instruction that describes the task:
### Input:
Authenticate with GitHub via SSH if possible
Otherwise authenticate via HTTPS
Returns an authenticated User
### Response:
def authenticate(org):
"""
Authenticate with GitHub via SSH if possible
Otherwise authenticate via HTTPS
... |
def render(self, context, instance, placeholder):
''' Create a UUID and check if a voucher with that ID exists before rendering '''
context = super(StripeGiftCertificateFormPlugin, self).render(context, instance, placeholder)
context.update({
'stripe_key': getattr(settings,'STR... | Create a UUID and check if a voucher with that ID exists before rendering | Below is the the instruction that describes the task:
### Input:
Create a UUID and check if a voucher with that ID exists before rendering
### Response:
def render(self, context, instance, placeholder):
''' Create a UUID and check if a voucher with that ID exists before rendering '''
context = su... |
def get_conn():
'''
Return a conn object for the passed VM data
'''
vm_ = get_configured_provider()
kwargs = vm_.copy() # pylint: disable=E1103
kwargs['username'] = vm_['user']
kwargs['project_id'] = vm_['tenant']
kwargs['auth_url'] = vm_['identity_url']
kwargs['region_name'] = vm... | Return a conn object for the passed VM data | Below is the the instruction that describes the task:
### Input:
Return a conn object for the passed VM data
### Response:
def get_conn():
'''
Return a conn object for the passed VM data
'''
vm_ = get_configured_provider()
kwargs = vm_.copy() # pylint: disable=E1103
kwargs['username'] = ... |
def update(self):
"""Update |UH| based on |MaxBaz|.
.. note::
This method also updates the shape of log sequence |QUH|.
|MaxBaz| determines the end point of the triangle. A value of
|MaxBaz| being not larger than the simulation step size is
identical with applying... | Update |UH| based on |MaxBaz|.
.. note::
This method also updates the shape of log sequence |QUH|.
|MaxBaz| determines the end point of the triangle. A value of
|MaxBaz| being not larger than the simulation step size is
identical with applying no unit hydrograph at all:
... | Below is the the instruction that describes the task:
### Input:
Update |UH| based on |MaxBaz|.
.. note::
This method also updates the shape of log sequence |QUH|.
|MaxBaz| determines the end point of the triangle. A value of
|MaxBaz| being not larger than the simulation step... |
def pick(self, selector, entity_set, min_quantity=None):
"""
Pick entities from a set by selector. In most cases you should use one
of the higher-level pick_* functions.
"""
if isinstance(selector, int):
for e in entity_set:
if e.id == selector:
... | Pick entities from a set by selector. In most cases you should use one
of the higher-level pick_* functions. | Below is the the instruction that describes the task:
### Input:
Pick entities from a set by selector. In most cases you should use one
of the higher-level pick_* functions.
### Response:
def pick(self, selector, entity_set, min_quantity=None):
"""
Pick entities from a set by selector. In m... |
def put_subsegment(self, subsegment):
"""
Refresh the facade segment every time this function is invoked to prevent
a new subsegment from being attached to a leaked segment/subsegment.
"""
current_entity = self.get_trace_entity()
if not self._is_subsegment(current_entity... | Refresh the facade segment every time this function is invoked to prevent
a new subsegment from being attached to a leaked segment/subsegment. | Below is the the instruction that describes the task:
### Input:
Refresh the facade segment every time this function is invoked to prevent
a new subsegment from being attached to a leaked segment/subsegment.
### Response:
def put_subsegment(self, subsegment):
"""
Refresh the facade segment ... |
def connect(self):
"""
Creates connection to RabbitMQ server
"""
if self.connecting:
log.info('PikaClient: Already connecting to RabbitMQ')
return
log.info('PikaClient: Connecting to RabbitMQ')
self.connecting = True
self.connection = Tor... | Creates connection to RabbitMQ server | Below is the the instruction that describes the task:
### Input:
Creates connection to RabbitMQ server
### Response:
def connect(self):
"""
Creates connection to RabbitMQ server
"""
if self.connecting:
log.info('PikaClient: Already connecting to RabbitMQ')
re... |
def make_kick_request(self,nick,reason):
"""
Make the iq stanza a MUC room participant kick request.
:Parameters:
- `nick`: nickname of user to kick.
- `reason`: reason of the kick.
:Types:
- `nick`: `unicode`
- `reason`: `unicode`
... | Make the iq stanza a MUC room participant kick request.
:Parameters:
- `nick`: nickname of user to kick.
- `reason`: reason of the kick.
:Types:
- `nick`: `unicode`
- `reason`: `unicode`
:return: object describing the kick request details.
... | Below is the the instruction that describes the task:
### Input:
Make the iq stanza a MUC room participant kick request.
:Parameters:
- `nick`: nickname of user to kick.
- `reason`: reason of the kick.
:Types:
- `nick`: `unicode`
- `reason`: `unicode`... |
def submit(**kwargs):
"""Shortcut that takes an alert to evaluate and makes the appropriate API
call based on the results.
:param kwargs: A list of keyword arguments
:type kwargs: dict
"""
if 'alert' not in kwargs:
raise ValueError('Alert required')
if 'value' not in kwargs:
... | Shortcut that takes an alert to evaluate and makes the appropriate API
call based on the results.
:param kwargs: A list of keyword arguments
:type kwargs: dict | Below is the the instruction that describes the task:
### Input:
Shortcut that takes an alert to evaluate and makes the appropriate API
call based on the results.
:param kwargs: A list of keyword arguments
:type kwargs: dict
### Response:
def submit(**kwargs):
"""Shortcut that takes an alert to ev... |
def transformByDistance(wV, subModel, alphabetSize=4):
"""
transform wV by given substitution matrix
"""
nc = [0.0]*alphabetSize
for i in xrange(0, alphabetSize):
j = wV[i]
k = subModel[i]
for l in xrange(0, alphabetSize):
nc[l] += j * k[l]
return nc | transform wV by given substitution matrix | Below is the the instruction that describes the task:
### Input:
transform wV by given substitution matrix
### Response:
def transformByDistance(wV, subModel, alphabetSize=4):
"""
transform wV by given substitution matrix
"""
nc = [0.0]*alphabetSize
for i in xrange(0, alphabetSize):
j =... |
def _strBinary(n):
"""Conert an integer to binary (i.e., a string of 1s and 0s)."""
results = []
for i in range(8):
n, r = divmod(n, 2)
results.append('01'[r])
results.reverse()
return ''.join(results) | Conert an integer to binary (i.e., a string of 1s and 0s). | Below is the the instruction that describes the task:
### Input:
Conert an integer to binary (i.e., a string of 1s and 0s).
### Response:
def _strBinary(n):
"""Conert an integer to binary (i.e., a string of 1s and 0s)."""
results = []
for i in range(8):
n, r = divmod(n, 2)
results.appen... |
def process_image(self, image, image_format, save_kwargs,
width, height):
"""
Return a BytesIO instance of `image` cropped to `width` and `height`.
Cropping will first reduce an image down to its longest side
and then crop inwards centered on the Primary Point of I... | Return a BytesIO instance of `image` cropped to `width` and `height`.
Cropping will first reduce an image down to its longest side
and then crop inwards centered on the Primary Point of Interest
(as specified by `self.ppoi`) | Below is the the instruction that describes the task:
### Input:
Return a BytesIO instance of `image` cropped to `width` and `height`.
Cropping will first reduce an image down to its longest side
and then crop inwards centered on the Primary Point of Interest
(as specified by `self.ppoi`)
#... |
def create_records(marcxml, verbose=CFG_BIBRECORD_DEFAULT_VERBOSE_LEVEL,
correct=CFG_BIBRECORD_DEFAULT_CORRECT, parser='',
keep_singletons=CFG_BIBRECORD_KEEP_SINGLETONS):
"""
Create a list of records from the marcxml description.
:returns: a list of objects initiated b... | Create a list of records from the marcxml description.
:returns: a list of objects initiated by the function create_record().
Please see that function's docstring. | Below is the the instruction that describes the task:
### Input:
Create a list of records from the marcxml description.
:returns: a list of objects initiated by the function create_record().
Please see that function's docstring.
### Response:
def create_records(marcxml, verbose=CFG_BIBRECORD_DEF... |
def default_option(self, fn, optstr):
"""Make an entry in the options_table for fn, with value optstr"""
if fn not in self.lsmagic():
error("%s is not a magic function" % fn)
self.options_table[fn] = optstr | Make an entry in the options_table for fn, with value optstr | Below is the the instruction that describes the task:
### Input:
Make an entry in the options_table for fn, with value optstr
### Response:
def default_option(self, fn, optstr):
"""Make an entry in the options_table for fn, with value optstr"""
if fn not in self.lsmagic():
error("%s is... |
def getLogger(name=None, filename=None, filemode=None, level=WARNING):
"""Gets a customized logger.
.. note:: `getLogger` is deprecated. Use `get_logger` instead.
"""
warnings.warn("getLogger is deprecated, Use get_logger instead.",
DeprecationWarning, stacklevel=2)
return get_lo... | Gets a customized logger.
.. note:: `getLogger` is deprecated. Use `get_logger` instead. | Below is the the instruction that describes the task:
### Input:
Gets a customized logger.
.. note:: `getLogger` is deprecated. Use `get_logger` instead.
### Response:
def getLogger(name=None, filename=None, filemode=None, level=WARNING):
"""Gets a customized logger.
.. note:: `getLogger` is deprecat... |
def set_posts_param_modified_after(self, params, post_type, status):
"""
Set modified_after date to "continue where we left off" if appropriate
:param params: the GET params dict, which may be updated to include the "modified_after" key
:param post_type: post, page, attachment, or any c... | Set modified_after date to "continue where we left off" if appropriate
:param params: the GET params dict, which may be updated to include the "modified_after" key
:param post_type: post, page, attachment, or any custom post type set up in the WP API
:param status: publish, private, draft, etc.... | Below is the the instruction that describes the task:
### Input:
Set modified_after date to "continue where we left off" if appropriate
:param params: the GET params dict, which may be updated to include the "modified_after" key
:param post_type: post, page, attachment, or any custom post type set ... |
def wait_until(func,
check_return_value=True,
total_timeout=60,
interval=0.5,
exc_list=None,
error_message="",
*args,
**kwargs):
"""Run a command in a loop until desired result or timeout occurs.
:param fun... | Run a command in a loop until desired result or timeout occurs.
:param func: Function to call and wait for
:param bool check_return_value: Examine return value
:param int total_timeout: Wait timeout,
:param float interval: Sleep interval between retries
:param list exc_list: Acceptable exception li... | Below is the the instruction that describes the task:
### Input:
Run a command in a loop until desired result or timeout occurs.
:param func: Function to call and wait for
:param bool check_return_value: Examine return value
:param int total_timeout: Wait timeout,
:param float interval: Sleep inter... |
def hexdump(self, lfilter=None):
"""Same as nsummary(), except that packets are also hexdumped
lfilter: a truth function that decides whether a packet must be displayed""" # noqa: E501
for i, res in enumerate(self.res):
p = self._elt2pkt(res)
if lfilter is not None and n... | Same as nsummary(), except that packets are also hexdumped
lfilter: a truth function that decides whether a packet must be displayed | Below is the the instruction that describes the task:
### Input:
Same as nsummary(), except that packets are also hexdumped
lfilter: a truth function that decides whether a packet must be displayed
### Response:
def hexdump(self, lfilter=None):
"""Same as nsummary(), except that packets are also he... |
def complete_dict(
self,
values_dict):
"""
Keys of nested dictionaries can be arbitrary objects.
"""
if self.orientation != "rows":
values_dict = transpose_nested_dictionary(values_dict)
row_keys, column_keys = collect_nested_keys(values_dict)... | Keys of nested dictionaries can be arbitrary objects. | Below is the the instruction that describes the task:
### Input:
Keys of nested dictionaries can be arbitrary objects.
### Response:
def complete_dict(
self,
values_dict):
"""
Keys of nested dictionaries can be arbitrary objects.
"""
if self.orientation != "r... |
def enumerate(self, mol):
"""Enumerate all possible tautomers and return them as a list.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:return: A list of all possible tautomers of the molecule.
:rtype: list of rdkit.Chem.rdchem.Mol
"""
smiles =... | Enumerate all possible tautomers and return them as a list.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:return: A list of all possible tautomers of the molecule.
:rtype: list of rdkit.Chem.rdchem.Mol | Below is the the instruction that describes the task:
### Input:
Enumerate all possible tautomers and return them as a list.
:param mol: The input molecule.
:type mol: rdkit.Chem.rdchem.Mol
:return: A list of all possible tautomers of the molecule.
:rtype: list of rdkit.Chem.rdchem.... |
def _append_instruction(self, obj, qargs=None):
"""Update the current Operator by apply an instruction."""
if isinstance(obj, Instruction):
mat = None
if hasattr(obj, 'to_matrix'):
# If instruction is a gate first we see if it has a
# `to_matrix` d... | Update the current Operator by apply an instruction. | Below is the the instruction that describes the task:
### Input:
Update the current Operator by apply an instruction.
### Response:
def _append_instruction(self, obj, qargs=None):
"""Update the current Operator by apply an instruction."""
if isinstance(obj, Instruction):
mat = None
... |
def stream_stats(self):
"""
Display basic statistics of callback execution: ideal period
between callbacks, average measured period between callbacks,
and average time spent in the callback.
"""
Tp = self.frame_length/float(self.fs)*1000
print('D... | Display basic statistics of callback execution: ideal period
between callbacks, average measured period between callbacks,
and average time spent in the callback. | Below is the the instruction that describes the task:
### Input:
Display basic statistics of callback execution: ideal period
between callbacks, average measured period between callbacks,
and average time spent in the callback.
### Response:
def stream_stats(self):
"""
Display ... |
def parse_number_from_substring(substring) -> Optional[float]:
'''
Returns the number in the expected string "N:12.3", where "N" is the
key, and "12.3" is a floating point value
For the temp-deck or thermocycler's temperature response, one expected
input is something like "T:none", where "none" sho... | Returns the number in the expected string "N:12.3", where "N" is the
key, and "12.3" is a floating point value
For the temp-deck or thermocycler's temperature response, one expected
input is something like "T:none", where "none" should return a None value | Below is the the instruction that describes the task:
### Input:
Returns the number in the expected string "N:12.3", where "N" is the
key, and "12.3" is a floating point value
For the temp-deck or thermocycler's temperature response, one expected
input is something like "T:none", where "none" should re... |
def handle_publishable_m2m_changed(
sender, instance, action, reverse, model, pk_set, **kwargs):
"""
Cache related published objects in `pre_clear` so they can be restored in
`post_clear`.
"""
# Do nothing if the target model is not publishable.
if not issubclass(model, PublishingModel):... | Cache related published objects in `pre_clear` so they can be restored in
`post_clear`. | Below is the the instruction that describes the task:
### Input:
Cache related published objects in `pre_clear` so they can be restored in
`post_clear`.
### Response:
def handle_publishable_m2m_changed(
sender, instance, action, reverse, model, pk_set, **kwargs):
"""
Cache related published obj... |
def batting_avg(self, benchmark):
"""Percentage of periods when `self` outperformed `benchmark`.
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarray}
The benchmark security to which `self` is compared.
Returns
-------
float
"... | Percentage of periods when `self` outperformed `benchmark`.
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarray}
The benchmark security to which `self` is compared.
Returns
-------
float | Below is the the instruction that describes the task:
### Input:
Percentage of periods when `self` outperformed `benchmark`.
Parameters
----------
benchmark : {pd.Series, TSeries, 1d np.ndarray}
The benchmark security to which `self` is compared.
Returns
-------... |
def _parse_iso8601(text):
"""
Maybe parse an ISO8601 datetime string into a datetime.
:param text: Either a ``unicode`` string to parse or any other object
(ideally a ``datetime`` instance) to pass through.
:return: A ``datetime.datetime`` representing ``text``. Or ``text`` if it
was ... | Maybe parse an ISO8601 datetime string into a datetime.
:param text: Either a ``unicode`` string to parse or any other object
(ideally a ``datetime`` instance) to pass through.
:return: A ``datetime.datetime`` representing ``text``. Or ``text`` if it
was anything but a ``unicode`` string. | Below is the the instruction that describes the task:
### Input:
Maybe parse an ISO8601 datetime string into a datetime.
:param text: Either a ``unicode`` string to parse or any other object
(ideally a ``datetime`` instance) to pass through.
:return: A ``datetime.datetime`` representing ``text``. ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.