code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_collection_class(resource):
"""
Returns the registered collection resource class for the given marker
interface or member resource class or instance.
:param rc: registered resource
:type rc: class implementing or instance providing or subclass of
a registered resource interface.
... | Returns the registered collection resource class for the given marker
interface or member resource class or instance.
:param rc: registered resource
:type rc: class implementing or instance providing or subclass of
a registered resource interface. | Below is the the instruction that describes the task:
### Input:
Returns the registered collection resource class for the given marker
interface or member resource class or instance.
:param rc: registered resource
:type rc: class implementing or instance providing or subclass of
a registered re... |
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` s... | Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
... | Below is the the instruction that describes the task:
### Input:
Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
T... |
def snapshot(opts):
"""snapshot a seqrepo data directory by hardlinking sequence files,
copying sqlite databases, and remove write permissions from directories
"""
seqrepo_dir = os.path.join(opts.root_directory, opts.instance_name)
dst_dir = opts.destination_name
if not dst_dir.startswith("/")... | snapshot a seqrepo data directory by hardlinking sequence files,
copying sqlite databases, and remove write permissions from directories | Below is the the instruction that describes the task:
### Input:
snapshot a seqrepo data directory by hardlinking sequence files,
copying sqlite databases, and remove write permissions from directories
### Response:
def snapshot(opts):
"""snapshot a seqrepo data directory by hardlinking sequence files,
... |
def run(self, start_point=None, stop_before=None, stop_after=None):
"""
Run the pipeline, optionally specifying start and/or stop points.
:param str start_point: Name of stage at which to begin execution.
:param str stop_before: Name of stage at which to cease execution;
exc... | Run the pipeline, optionally specifying start and/or stop points.
:param str start_point: Name of stage at which to begin execution.
:param str stop_before: Name of stage at which to cease execution;
exclusive, i.e. this stage is not run
:param str stop_after: Name of stage at which... | Below is the the instruction that describes the task:
### Input:
Run the pipeline, optionally specifying start and/or stop points.
:param str start_point: Name of stage at which to begin execution.
:param str stop_before: Name of stage at which to cease execution;
exclusive, i.e. this s... |
def _jacobian_both(nodes, degree, dimension):
r"""Compute :math:`s` and :math:`t` partial of :math:`B`.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): Array of nodes in a surface.
degree ... | r"""Compute :math:`s` and :math:`t` partial of :math:`B`.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): Array of nodes in a surface.
degree (int): The degree of the surface.
dimensio... | Below is the the instruction that describes the task:
### Input:
r"""Compute :math:`s` and :math:`t` partial of :math:`B`.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Args:
nodes (numpy.ndarray): Array of nodes in a surfa... |
def get_parser():
"""Return the parser object for this script."""
project_root = utils.get_project_root()
# Get latest model folder
models_folder = os.path.join(project_root, "models")
latest_model = utils.get_latest_folder(models_folder)
# Get command line arguments
from argparse import A... | Return the parser object for this script. | Below is the the instruction that describes the task:
### Input:
Return the parser object for this script.
### Response:
def get_parser():
"""Return the parser object for this script."""
project_root = utils.get_project_root()
# Get latest model folder
models_folder = os.path.join(project_root, "m... |
def keyPressEvent(self, event):
"""
Qt override.
"""
QToolTip.hideText()
ctrl = event.modifiers() & Qt.ControlModifier
if event.key() in [Qt.Key_Enter, Qt.Key_Return]:
if ctrl:
self.process_text(array=False)
else:
... | Qt override. | Below is the the instruction that describes the task:
### Input:
Qt override.
### Response:
def keyPressEvent(self, event):
"""
Qt override.
"""
QToolTip.hideText()
ctrl = event.modifiers() & Qt.ControlModifier
if event.key() in [Qt.Key_Enter, Qt.Key_Return]:... |
def generate_doc_length_stats(self):
"""Analyze document length statistics for padding strategy"""
heuristic = self.heuristic_pct
histdf = (pd.DataFrame([(a, b) for a, b in self.document_length_histogram.items()],
columns=['bin', 'doc_count'])
.so... | Analyze document length statistics for padding strategy | Below is the the instruction that describes the task:
### Input:
Analyze document length statistics for padding strategy
### Response:
def generate_doc_length_stats(self):
"""Analyze document length statistics for padding strategy"""
heuristic = self.heuristic_pct
histdf = (pd.DataFrame([(a... |
def _start_scan(self, active):
"""Begin scanning forever
"""
success, retval = self._set_scan_parameters(active=active)
if not success:
return success, retval
try:
response = self._send_command(6, 2, [2])
if response.payload[0] != 0:
... | Begin scanning forever | Below is the the instruction that describes the task:
### Input:
Begin scanning forever
### Response:
def _start_scan(self, active):
"""Begin scanning forever
"""
success, retval = self._set_scan_parameters(active=active)
if not success:
return success, retval
... |
def lookup_stdout(self, pk=None, start_line=None, end_line=None,
full=True):
"""
Internal method that lies to our `monitor` method by returning
a scorecard for the workflow job where the standard out
would have been expected.
"""
uj_res = get_resourc... | Internal method that lies to our `monitor` method by returning
a scorecard for the workflow job where the standard out
would have been expected. | Below is the the instruction that describes the task:
### Input:
Internal method that lies to our `monitor` method by returning
a scorecard for the workflow job where the standard out
would have been expected.
### Response:
def lookup_stdout(self, pk=None, start_line=None, end_line=None,
... |
def get_relationship_dicts(self):
"""Given GO DAG relationships, return summaries per GO ID."""
if not self.relationships:
return None
for goid, goobj in self.go2obj.items():
for reltyp, relset in goobj.relationship.items():
relfwd_goids = set(o.id for o i... | Given GO DAG relationships, return summaries per GO ID. | Below is the the instruction that describes the task:
### Input:
Given GO DAG relationships, return summaries per GO ID.
### Response:
def get_relationship_dicts(self):
"""Given GO DAG relationships, return summaries per GO ID."""
if not self.relationships:
return None
for goid,... |
def get_code(self):
"""Returns code that generates figure from widgets"""
def dict2str(attr_dict):
"""Returns string with dict content with values as code
Code means that string identifiers are removed
"""
result = u"{"
for key in attr_dic... | Returns code that generates figure from widgets | Below is the the instruction that describes the task:
### Input:
Returns code that generates figure from widgets
### Response:
def get_code(self):
"""Returns code that generates figure from widgets"""
def dict2str(attr_dict):
"""Returns string with dict content with values as code
... |
def SAS_NG(self):
"""
Set-up for the ungridded superposition of analytical solutions
method for solving flexure
"""
if self.filename:
# Define the (scalar) elastic thickness
self.Te = self.configGet("float", "input", "ElasticThickness")
# See if it wants to be run in lat/lon
... | Set-up for the ungridded superposition of analytical solutions
method for solving flexure | Below is the the instruction that describes the task:
### Input:
Set-up for the ungridded superposition of analytical solutions
method for solving flexure
### Response:
def SAS_NG(self):
"""
Set-up for the ungridded superposition of analytical solutions
method for solving flexure
"""
if s... |
def available_perm_status(user):
"""
Get a boolean map of the permissions available to a user
based on that user's roles.
"""
roles = get_user_roles(user)
permission_hash = {}
for role in roles:
permission_names = role.permission_names_list()
for permission_name in permissi... | Get a boolean map of the permissions available to a user
based on that user's roles. | Below is the the instruction that describes the task:
### Input:
Get a boolean map of the permissions available to a user
based on that user's roles.
### Response:
def available_perm_status(user):
"""
Get a boolean map of the permissions available to a user
based on that user's roles.
"""
r... |
def get_sys_info():
"Returns system information as a dict"
blob = []
# get full commit hash
commit = None
if os.path.isdir(".git") and os.path.isdir("xarray"):
try:
pipe = subprocess.Popen('git log --format="%H" -n 1'.split(" "),
stdout=subpr... | Returns system information as a dict | Below is the the instruction that describes the task:
### Input:
Returns system information as a dict
### Response:
def get_sys_info():
"Returns system information as a dict"
blob = []
# get full commit hash
commit = None
if os.path.isdir(".git") and os.path.isdir("xarray"):
try:
... |
def create_autoscale_rule(subscription_id, resource_group, vmss_name, metric_name, operator,
threshold, direction, change_count, time_grain='PT1M',
time_window='PT5M', cool_down='PT1M'):
'''Create a new autoscale rule - pass the output in a list to create_autoscal... | Create a new autoscale rule - pass the output in a list to create_autoscale_setting().
Args:
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vmss_name (str): Name of scale set to apply scale events to.
metric_name (str): Name of metric ... | Below is the the instruction that describes the task:
### Input:
Create a new autoscale rule - pass the output in a list to create_autoscale_setting().
Args:
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vmss_name (str): Name of scale set... |
def single_or_default(self, default, predicate=None):
'''The only element (which satisfies a condition) or a default.
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the predicat... | The only element (which satisfies a condition) or a default.
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the predicate evaluates to True. A default value
is returned if there... | Below is the the instruction that describes the task:
### Input:
The only element (which satisfies a condition) or a default.
If the predicate is omitted or is None this query returns the only
element in the sequence; otherwise, it returns the only element in
the sequence for which the pred... |
def _best_version(fields):
"""Detect the best version depending on the fields used."""
def _has_marker(keys, markers):
for marker in markers:
if marker in keys:
return True
return False
keys = []
for key, value in fields.items():
if value in ([], 'UNK... | Detect the best version depending on the fields used. | Below is the the instruction that describes the task:
### Input:
Detect the best version depending on the fields used.
### Response:
def _best_version(fields):
"""Detect the best version depending on the fields used."""
def _has_marker(keys, markers):
for marker in markers:
if marker in... |
def handle_startendtag(self, tag, attrs):
"""Function called for empty tags (e.g. <br />)"""
if tag.lower() in self.allowed_tag_whitelist:
self.result += '<' + tag
for (attr, value) in attrs:
if attr.lower() in self.allowed_attribute_whitelist:
... | Function called for empty tags (e.g. <br />) | Below is the the instruction that describes the task:
### Input:
Function called for empty tags (e.g. <br />)
### Response:
def handle_startendtag(self, tag, attrs):
"""Function called for empty tags (e.g. <br />)"""
if tag.lower() in self.allowed_tag_whitelist:
self.result += '<' + tag... |
def args(self) -> str:
"""Provides arguments for the command."""
return '{}{}{}'.format(
ChangeSpecialDeviceCommand.args,
to_ascii_hex(encode_value_using_ma(self._message_attribute,
self._control_high_limit), 2),
to_ascii... | Provides arguments for the command. | Below is the the instruction that describes the task:
### Input:
Provides arguments for the command.
### Response:
def args(self) -> str:
"""Provides arguments for the command."""
return '{}{}{}'.format(
ChangeSpecialDeviceCommand.args,
to_ascii_hex(encode_value_using_ma(sel... |
def get(self, card_id):
"""
查询卡券详情
"""
result = self._post(
'card/get',
data={
'card_id': card_id
},
result_processor=lambda x: x['card']
)
return result | 查询卡券详情 | Below is the the instruction that describes the task:
### Input:
查询卡券详情
### Response:
def get(self, card_id):
"""
查询卡券详情
"""
result = self._post(
'card/get',
data={
'card_id': card_id
},
result_processor=lambda x: x['ca... |
def sequence_type(self):
'''Guess the type of input sequence provided to graftM (i.e. nucleotide
or amino acid) and return'''
if self.known_sequence_type is not None:
return self.known_sequence_type
else:
# If its Gzipped and fastq make a small sample of the seque... | Guess the type of input sequence provided to graftM (i.e. nucleotide
or amino acid) and return | Below is the the instruction that describes the task:
### Input:
Guess the type of input sequence provided to graftM (i.e. nucleotide
or amino acid) and return
### Response:
def sequence_type(self):
'''Guess the type of input sequence provided to graftM (i.e. nucleotide
or amino acid) and r... |
def resolve(self, requirements, env=None, installer=None,
replace_conflicting=False):
"""List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environment`` instance. If
... | List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environment`` instance. If
not supplied, it defaults to all distributions available within any
entry or distribution in t... | Below is the the instruction that describes the task:
### Input:
List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environment`` instance. If
not supplied, it defaults to all ... |
def listxattr(self, req, ino, size):
"""List extended attribute names
Valid replies:
reply_buf
reply_data
reply_xattr
reply_err
"""
self.reply_err(req, errno.ENOSYS) | List extended attribute names
Valid replies:
reply_buf
reply_data
reply_xattr
reply_err | Below is the the instruction that describes the task:
### Input:
List extended attribute names
Valid replies:
reply_buf
reply_data
reply_xattr
reply_err
### Response:
def listxattr(self, req, ino, size):
"""List extended attribute names
Valid replies:
... |
def parseBasicOptions(parser):
"""Setups the standard things from things added by getBasicOptionParser.
"""
(options, args) = parser.parse_args()
setLoggingFromOptions(options)
#Set up the temp dir root
if options.tempDirRoot == "None":
options.tempDirRoot = os.getcwd()
return opt... | Setups the standard things from things added by getBasicOptionParser. | Below is the the instruction that describes the task:
### Input:
Setups the standard things from things added by getBasicOptionParser.
### Response:
def parseBasicOptions(parser):
"""Setups the standard things from things added by getBasicOptionParser.
"""
(options, args) = parser.parse_args()
set... |
def xs(self, key, axis=1):
"""
Return slice of panel along selected axis.
Parameters
----------
key : object
Label
axis : {'items', 'major', 'minor}, default 1/'major'
Returns
-------
y : ndim(self)-1
Notes
-----
... | Return slice of panel along selected axis.
Parameters
----------
key : object
Label
axis : {'items', 'major', 'minor}, default 1/'major'
Returns
-------
y : ndim(self)-1
Notes
-----
xs is only for getting, not setting values.... | Below is the the instruction that describes the task:
### Input:
Return slice of panel along selected axis.
Parameters
----------
key : object
Label
axis : {'items', 'major', 'minor}, default 1/'major'
Returns
-------
y : ndim(self)-1
No... |
def set_count(self, cnt):
""" Sets 'count' parameter used to define the number of \
tweets to return per page. Maximum and default value is 100
:param cnt: Integer containing the number of tweets per \
page within a range of 1 to 100
:raises: TwitterSearchException
"""
... | Sets 'count' parameter used to define the number of \
tweets to return per page. Maximum and default value is 100
:param cnt: Integer containing the number of tweets per \
page within a range of 1 to 100
:raises: TwitterSearchException | Below is the the instruction that describes the task:
### Input:
Sets 'count' parameter used to define the number of \
tweets to return per page. Maximum and default value is 100
:param cnt: Integer containing the number of tweets per \
page within a range of 1 to 100
:raises: Twitt... |
def enable_data_link(self, instance, link):
"""
Enables a data link.
:param str instance: A Yamcs instance name.
:param str link: The name of the data link.
"""
req = rest_pb2.EditLinkRequest()
req.state = 'enabled'
url = '/links/{}/{}'.format(instance, l... | Enables a data link.
:param str instance: A Yamcs instance name.
:param str link: The name of the data link. | Below is the the instruction that describes the task:
### Input:
Enables a data link.
:param str instance: A Yamcs instance name.
:param str link: The name of the data link.
### Response:
def enable_data_link(self, instance, link):
"""
Enables a data link.
:param str insta... |
def set_layout_settings(self, settings, dont_goto=None):
"""Restore layout state for the splitter panels.
Apply the settings to restore a saved layout within the editor. If
the splitsettings key doesn't exist, then return without restoring
any settings.
The current Edit... | Restore layout state for the splitter panels.
Apply the settings to restore a saved layout within the editor. If
the splitsettings key doesn't exist, then return without restoring
any settings.
The current EditorSplitter (self) calls split() for each element
in split_se... | Below is the the instruction that describes the task:
### Input:
Restore layout state for the splitter panels.
Apply the settings to restore a saved layout within the editor. If
the splitsettings key doesn't exist, then return without restoring
any settings.
The current Edit... |
async def file_upload(
request: web.Request, session: UpdateSession) -> web.Response:
""" Serves /update/:session/file
Requires multipart (encoding doesn't matter) with a file field in the
body called 'ot2-system.zip'.
"""
if session.stage != Stages.AWAITING_FILE:
return web.json_re... | Serves /update/:session/file
Requires multipart (encoding doesn't matter) with a file field in the
body called 'ot2-system.zip'. | Below is the the instruction that describes the task:
### Input:
Serves /update/:session/file
Requires multipart (encoding doesn't matter) with a file field in the
body called 'ot2-system.zip'.
### Response:
async def file_upload(
request: web.Request, session: UpdateSession) -> web.Response:
... |
def delete(self, id, **kwargs):
"""Delete an object on the server.
Args:
id: ID of the object to delete
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteErro... | Delete an object on the server.
Args:
id: ID of the object to delete
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabDeleteError: If the server cannot perform the request | Below is the the instruction that describes the task:
### Input:
Delete an object on the server.
Args:
id: ID of the object to delete
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
... |
def delete_attachment(request, link_field=None, uri=None):
"""Delete existing file and link."""
if link_field is None:
link_field = "record_uri"
if uri is None:
uri = record_uri(request)
# Remove file.
filters = [Filter(link_field, uri, core_utils.COMPARISON.EQ)]
storage = reque... | Delete existing file and link. | Below is the the instruction that describes the task:
### Input:
Delete existing file and link.
### Response:
def delete_attachment(request, link_field=None, uri=None):
"""Delete existing file and link."""
if link_field is None:
link_field = "record_uri"
if uri is None:
uri = record_uri... |
def generate_warning_text(self):
"""
generates warnings for the current specimen then adds them to the
current warning text for the GUI which will be rendered on a call to
update_warning_box.
"""
self.warning_text = ""
if self.s in list(self.pmag_results_data['spe... | generates warnings for the current specimen then adds them to the
current warning text for the GUI which will be rendered on a call to
update_warning_box. | Below is the the instruction that describes the task:
### Input:
generates warnings for the current specimen then adds them to the
current warning text for the GUI which will be rendered on a call to
update_warning_box.
### Response:
def generate_warning_text(self):
"""
generates wa... |
def edit(self, image_id, name=None, note=None, tag=None):
"""Edit image related details.
:param int image_id: The ID of the image
:param string name: Name of the Image.
:param string note: Note of the image.
:param string tag: Tags of the image to be updated to.
"""
... | Edit image related details.
:param int image_id: The ID of the image
:param string name: Name of the Image.
:param string note: Note of the image.
:param string tag: Tags of the image to be updated to. | Below is the the instruction that describes the task:
### Input:
Edit image related details.
:param int image_id: The ID of the image
:param string name: Name of the Image.
:param string note: Note of the image.
:param string tag: Tags of the image to be updated to.
### Response:
d... |
def rtl_assert(w, exp, block=None):
""" Add hardware assertions to be checked on the RTL design.
:param w: should be a WireVector
:param Exception exp: Exception to throw when assertion fails
:param Block block: block to which the assertion should be added (default to working block)
:return: the Ou... | Add hardware assertions to be checked on the RTL design.
:param w: should be a WireVector
:param Exception exp: Exception to throw when assertion fails
:param Block block: block to which the assertion should be added (default to working block)
:return: the Output wire for the assertion (can be ignored ... | Below is the the instruction that describes the task:
### Input:
Add hardware assertions to be checked on the RTL design.
:param w: should be a WireVector
:param Exception exp: Exception to throw when assertion fails
:param Block block: block to which the assertion should be added (default to working b... |
async def process_ltd_doc(session, github_api_token, ltd_product_url,
mongo_collection=None):
"""Ingest any kind of LSST document hosted on LSST the Docs from its
source.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client sess... | Ingest any kind of LSST document hosted on LSST the Docs from its
source.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/client.html.
github_api_token : `str`
A GitHub personal AP... | Below is the the instruction that describes the task:
### Input:
Ingest any kind of LSST document hosted on LSST the Docs from its
source.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/c... |
def create_message(username, message):
""" Creates a standard message from a given user with the message
Replaces newline with html break """
message = message.replace('\n', '<br/>')
return '{{"service":1, "data":{{"message":"{mes}", "username":"{user}"}} }}'.format(mes=message, user=username) | Creates a standard message from a given user with the message
Replaces newline with html break | Below is the the instruction that describes the task:
### Input:
Creates a standard message from a given user with the message
Replaces newline with html break
### Response:
def create_message(username, message):
""" Creates a standard message from a given user with the message
Replaces ne... |
def ch_start_time(self, *channels: List[Channel]) -> int:
"""Return earliest start time in this collection.
Args:
*channels: Channels over which to obtain start_time.
"""
intervals = list(itertools.chain(*(self._table[chan] for chan in channels
... | Return earliest start time in this collection.
Args:
*channels: Channels over which to obtain start_time. | Below is the the instruction that describes the task:
### Input:
Return earliest start time in this collection.
Args:
*channels: Channels over which to obtain start_time.
### Response:
def ch_start_time(self, *channels: List[Channel]) -> int:
"""Return earliest start time in this colle... |
def _open_playlist(self):
""" open playlist """
self._get_active_stations()
self.jumpnr = ''
self._random_requested = False
txt = '''Reading playlists. Please wait...'''
self._show_help(txt, NORMAL_MODE, caption=' ', prompt=' ', is_message=True)
self.selections[se... | open playlist | Below is the the instruction that describes the task:
### Input:
open playlist
### Response:
def _open_playlist(self):
""" open playlist """
self._get_active_stations()
self.jumpnr = ''
self._random_requested = False
txt = '''Reading playlists. Please wait...'''
self... |
def log(self, n=None, template=None, **kwargs):
"""
Run the repository log command
Returns:
str: output of log command (``svn log -l <n> <--kwarg=value>``)
"""
cmd = ['svn', 'log']
if n:
cmd.append('-l%d' % n)
cmd.extend(
(('--... | Run the repository log command
Returns:
str: output of log command (``svn log -l <n> <--kwarg=value>``) | Below is the the instruction that describes the task:
### Input:
Run the repository log command
Returns:
str: output of log command (``svn log -l <n> <--kwarg=value>``)
### Response:
def log(self, n=None, template=None, **kwargs):
"""
Run the repository log command
Ret... |
def _minimize_in_graph(build_loss_fn, num_steps=200, optimizer=None):
"""Run an optimizer within the graph to minimize a loss function."""
optimizer = tf.compat.v1.train.AdamOptimizer(
0.1) if optimizer is None else optimizer
def train_loop_body(step):
train_op = optimizer.minimize(
build_loss_... | Run an optimizer within the graph to minimize a loss function. | Below is the the instruction that describes the task:
### Input:
Run an optimizer within the graph to minimize a loss function.
### Response:
def _minimize_in_graph(build_loss_fn, num_steps=200, optimizer=None):
"""Run an optimizer within the graph to minimize a loss function."""
optimizer = tf.compat.v1.train... |
def send(self, **kwargs):
""" Combines api_payload and api_method to submit the current object to the API """
payload = self.api_payload()
payload.update(**kwargs)
return self.api_method()(**payload) | Combines api_payload and api_method to submit the current object to the API | Below is the the instruction that describes the task:
### Input:
Combines api_payload and api_method to submit the current object to the API
### Response:
def send(self, **kwargs):
""" Combines api_payload and api_method to submit the current object to the API """
payload = self.api_payload()
... |
def coin_trig(peaks, stachans, samp_rate, moveout, min_trig, trig_int):
"""
Find network coincidence triggers within peaks of detection statistics.
Useful for finding network detections from sets of detections on individual
stations.
:type peaks: list
:param peaks: List of lists of tuples of (... | Find network coincidence triggers within peaks of detection statistics.
Useful for finding network detections from sets of detections on individual
stations.
:type peaks: list
:param peaks: List of lists of tuples of (peak, index) for each \
station-channel. Index should be in samples.
:t... | Below is the the instruction that describes the task:
### Input:
Find network coincidence triggers within peaks of detection statistics.
Useful for finding network detections from sets of detections on individual
stations.
:type peaks: list
:param peaks: List of lists of tuples of (peak, index) fo... |
def _override_locale(self, locale: str = locales.DEFAULT_LOCALE) -> None:
"""Overrides current locale with passed and pull data for new locale.
:param locale: Locale
:return: Nothing.
"""
self.locale = locale
self.pull.cache_clear()
self.pull() | Overrides current locale with passed and pull data for new locale.
:param locale: Locale
:return: Nothing. | Below is the the instruction that describes the task:
### Input:
Overrides current locale with passed and pull data for new locale.
:param locale: Locale
:return: Nothing.
### Response:
def _override_locale(self, locale: str = locales.DEFAULT_LOCALE) -> None:
"""Overrides current locale wi... |
def schedule_job(date, callable_name, content_object=None, expires='7d',
args=(), kwargs={}):
"""Schedule a job.
`date` may be a datetime.datetime or a datetime.timedelta.
The callable to be executed may be specified in two ways:
- set `callable_name` to an identifier ('mypackage.mya... | Schedule a job.
`date` may be a datetime.datetime or a datetime.timedelta.
The callable to be executed may be specified in two ways:
- set `callable_name` to an identifier ('mypackage.myapp.some_function').
- specify an instance of a model as content_object and set
`callable_name` to a method... | Below is the the instruction that describes the task:
### Input:
Schedule a job.
`date` may be a datetime.datetime or a datetime.timedelta.
The callable to be executed may be specified in two ways:
- set `callable_name` to an identifier ('mypackage.myapp.some_function').
- specify an instance of... |
def request_encode_body(self, method, url, fields=None, headers=None,
encode_multipart=True, multipart_boundary=None,
**urlopen_kw):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for reques... | Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for request methods like POST, PUT, PATCH, etc.
When ``encode_multipart=True`` (default), then
:meth:`urllib3.filepost.encode_multipart_formdata` is used to encode
the payload with the appropria... | Below is the the instruction that describes the task:
### Input:
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for request methods like POST, PUT, PATCH, etc.
When ``encode_multipart=True`` (default), then
:meth:`urllib3.filepost.encode_multipa... |
def stock_image(width: Union[int, str] = 1920,
height: Union[int, str] = 1080,
keywords: Optional[List[str]] = None,
writable: bool = False) -> Union[str, bytes]:
"""Generate random stock image (JPEG) hosted on Unsplash.
.. note:: This method ... | Generate random stock image (JPEG) hosted on Unsplash.
.. note:: This method required an active HTTP connection.
:param width: Width of the image.
:param height: Height of the image.
:param keywords: List of search keywords.
:param writable: Return image as sequence ob bytes.
... | Below is the the instruction that describes the task:
### Input:
Generate random stock image (JPEG) hosted on Unsplash.
.. note:: This method required an active HTTP connection.
:param width: Width of the image.
:param height: Height of the image.
:param keywords: List of search ke... |
def nvmlDeviceGetPowerManagementMode(handle):
r"""
/**
* This API has been deprecated.
*
* Retrieves the power management mode associated with this device.
*
* For products from the Fermi family.
* - Requires \a NVML_INFOROM_POWER version 3.0 or higher.
*
* For from t... | r"""
/**
* This API has been deprecated.
*
* Retrieves the power management mode associated with this device.
*
* For products from the Fermi family.
* - Requires \a NVML_INFOROM_POWER version 3.0 or higher.
*
* For from the Kepler or newer families.
* - Does not... | Below is the the instruction that describes the task:
### Input:
r"""
/**
* This API has been deprecated.
*
* Retrieves the power management mode associated with this device.
*
* For products from the Fermi family.
* - Requires \a NVML_INFOROM_POWER version 3.0 or higher.
... |
def revoc_info(creds: dict, filt: dict = None) -> dict:
"""
Given a creds structure, return a dict mapping pairs
(revocation registry identifier, credential revocation identifier)
to (decoded) attribute name:value dicts.
If the caller includes a filter of attribute:value pairs, retain only matching... | Given a creds structure, return a dict mapping pairs
(revocation registry identifier, credential revocation identifier)
to (decoded) attribute name:value dicts.
If the caller includes a filter of attribute:value pairs, retain only matching attributes.
:param creds: creds structure returned by HolderPr... | Below is the the instruction that describes the task:
### Input:
Given a creds structure, return a dict mapping pairs
(revocation registry identifier, credential revocation identifier)
to (decoded) attribute name:value dicts.
If the caller includes a filter of attribute:value pairs, retain only matchin... |
def set_https_port(port=443):
'''
Configure the port HTTPS should listen on
CLI Example:
.. code-block:: bash
salt '*' ilo.set_https_port 4334
'''
_current = global_settings()
if _current['Global Settings']['HTTP_PORT']['VALUE'] == port:
return True
_xml = """<RIBCL ... | Configure the port HTTPS should listen on
CLI Example:
.. code-block:: bash
salt '*' ilo.set_https_port 4334 | Below is the the instruction that describes the task:
### Input:
Configure the port HTTPS should listen on
CLI Example:
.. code-block:: bash
salt '*' ilo.set_https_port 4334
### Response:
def set_https_port(port=443):
'''
Configure the port HTTPS should listen on
CLI Example:
.... |
def sync_svc(state):
"""
Mirror some service calls in manticore. Happens after qemu executed a SVC
instruction, but before manticore did.
"""
syscall = state.cpu.R7 # Grab idx from manticore since qemu could have exited
name = linux_syscalls.armv7[syscall]
logger.debug(f"Syncing syscall: {n... | Mirror some service calls in manticore. Happens after qemu executed a SVC
instruction, but before manticore did. | Below is the the instruction that describes the task:
### Input:
Mirror some service calls in manticore. Happens after qemu executed a SVC
instruction, but before manticore did.
### Response:
def sync_svc(state):
"""
Mirror some service calls in manticore. Happens after qemu executed a SVC
instruct... |
def list_all_before(self, message_id, limit=None):
"""Return all group messages created before a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator
"""
return self.li... | Return all group messages created before a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator | Below is the the instruction that describes the task:
### Input:
Return all group messages created before a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator
### Response:
def list_all... |
def _log_file_ind(self,inum):
"""
Information about available profile.data or log.data files.
Parameters
----------
inum : integer
Attempt to get number of inum's profile.data file.
inum_max: max number of profile.data or log.data files
availa... | Information about available profile.data or log.data files.
Parameters
----------
inum : integer
Attempt to get number of inum's profile.data file.
inum_max: max number of profile.data or log.data files
available | Below is the the instruction that describes the task:
### Input:
Information about available profile.data or log.data files.
Parameters
----------
inum : integer
Attempt to get number of inum's profile.data file.
inum_max: max number of profile.data or log.data files... |
def parse_sync_points(names, tests):
"""
Slice list of test names on sync points.
If test is test file find full path to file.
Returns:
A list of test file sets and sync point strings.
Examples:
['test_hard_reboot']
[set('test1', 'test2')]
[set('test1', 'test2'), 't... | Slice list of test names on sync points.
If test is test file find full path to file.
Returns:
A list of test file sets and sync point strings.
Examples:
['test_hard_reboot']
[set('test1', 'test2')]
[set('test1', 'test2'), 'test_soft_reboot']
[set('test1', 'test2'),... | Below is the the instruction that describes the task:
### Input:
Slice list of test names on sync points.
If test is test file find full path to file.
Returns:
A list of test file sets and sync point strings.
Examples:
['test_hard_reboot']
[set('test1', 'test2')]
[set('... |
def compute_reciprocal_errors(self, key="r"):
r"""
Compute reciprocal erros following LaBrecque et al. (1996) according
to:
.. math::
\epsilon = \left|\frac{2(|R_n| - |R_r|)}{|R_n| + |R_r|}\right|
Parameters
----------
key : str
Paramete... | r"""
Compute reciprocal erros following LaBrecque et al. (1996) according
to:
.. math::
\epsilon = \left|\frac{2(|R_n| - |R_r|)}{|R_n| + |R_r|}\right|
Parameters
----------
key : str
Parameter to calculate the reciprocal error for (default is "r... | Below is the the instruction that describes the task:
### Input:
r"""
Compute reciprocal erros following LaBrecque et al. (1996) according
to:
.. math::
\epsilon = \left|\frac{2(|R_n| - |R_r|)}{|R_n| + |R_r|}\right|
Parameters
----------
key : str
... |
def count_vowels(text):
"""Count number of occurrences of vowels in a given string"""
count = 0
for i in text:
if i.lower() in config.AVRO_VOWELS:
count += 1
return count | Count number of occurrences of vowels in a given string | Below is the the instruction that describes the task:
### Input:
Count number of occurrences of vowels in a given string
### Response:
def count_vowels(text):
"""Count number of occurrences of vowels in a given string"""
count = 0
for i in text:
if i.lower() in config.AVRO_VOWELS:
c... |
def perform(self):
""" Loads and starts the main task for this job, the saves the result. """
if self.data is None:
return
context.log.debug("Starting %s(%s)" % (self.data["path"], self.data["params"]))
task_class = load_class_by_path(self.data["path"])
self.task =... | Loads and starts the main task for this job, the saves the result. | Below is the the instruction that describes the task:
### Input:
Loads and starts the main task for this job, the saves the result.
### Response:
def perform(self):
""" Loads and starts the main task for this job, the saves the result. """
if self.data is None:
return
context.... |
def initialize(self):
"""Initialize the BLE provider. Must be called once before any other
calls are made to the provider.
"""
# Setup the central manager and its delegate.
self._central_manager = CBCentralManager.alloc()
self._central_manager.initWithDelegate_queue_opti... | Initialize the BLE provider. Must be called once before any other
calls are made to the provider. | Below is the the instruction that describes the task:
### Input:
Initialize the BLE provider. Must be called once before any other
calls are made to the provider.
### Response:
def initialize(self):
"""Initialize the BLE provider. Must be called once before any other
calls are made to the... |
def _set_vrrp(self, v, load=False):
"""
Setter method for vrrp, mapped from YANG variable /rbridge_id/vrrp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vrrp is considered as a private
method. Backends looking to populate this variable should
do so ... | Setter method for vrrp, mapped from YANG variable /rbridge_id/vrrp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vrrp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_vrrp() directly. | Below is the the instruction that describes the task:
### Input:
Setter method for vrrp, mapped from YANG variable /rbridge_id/vrrp (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_vrrp is considered as a private
method. Backends looking to populate this varia... |
def lock_access(repository_path, callback):
""" Synchronise access to the user file between processes, this specifies
which user is allowed write access at the current time """
with open(cpjoin(repository_path, 'lock_file'), 'w') as fd:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB... | Synchronise access to the user file between processes, this specifies
which user is allowed write access at the current time | Below is the the instruction that describes the task:
### Input:
Synchronise access to the user file between processes, this specifies
which user is allowed write access at the current time
### Response:
def lock_access(repository_path, callback):
""" Synchronise access to the user file between processes, ... |
def write_config_file(config_instance, appdirs=DEFAULT_APPDIRS,
file_name=DEFAULT_CONFIG_FILENAME):
"""
Write a ConfigParser instance to file at the correct location.
Args:
config_instance: Config instance to safe to file.
appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` insta... | Write a ConfigParser instance to file at the correct location.
Args:
config_instance: Config instance to safe to file.
appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` instance storing app/user specific
path information.
file_name (text_type, optional): Name of the config ... | Below is the the instruction that describes the task:
### Input:
Write a ConfigParser instance to file at the correct location.
Args:
config_instance: Config instance to safe to file.
appdirs (HamsterAppDirs, optional): ``HamsterAppDirs`` instance storing app/user specific
path info... |
def is_file(jottapath, JFS):
"""Check if a file exists on jottacloud"""
log.debug("is_file %r", jottapath)
try:
jf = JFS.getObject(jottapath)
except JFSNotFoundError:
return False
return isinstance(jf, JFSFile) | Check if a file exists on jottacloud | Below is the the instruction that describes the task:
### Input:
Check if a file exists on jottacloud
### Response:
def is_file(jottapath, JFS):
"""Check if a file exists on jottacloud"""
log.debug("is_file %r", jottapath)
try:
jf = JFS.getObject(jottapath)
except JFSNotFoundError:
... |
def get_dist(dist_name, lookup_dirs=None):
"""Get dist for installed version of dist_name avoiding pkg_resources cache
"""
# note: based on pip/utils/__init__.py, get_installed_version(...)
# Create a requirement that we'll look for inside of setuptools.
req = pkg_resources.Requirement.parse(dist_n... | Get dist for installed version of dist_name avoiding pkg_resources cache | Below is the the instruction that describes the task:
### Input:
Get dist for installed version of dist_name avoiding pkg_resources cache
### Response:
def get_dist(dist_name, lookup_dirs=None):
"""Get dist for installed version of dist_name avoiding pkg_resources cache
"""
# note: based on pip/utils/_... |
def authorize(self, ctx, identity, ops):
'''Implements Authorizer.authorize by calling identity.allow to
determine whether the identity is a member of the ACLs associated with
the given operations.
'''
if len(ops) == 0:
# Anyone is allowed to do nothing.
r... | Implements Authorizer.authorize by calling identity.allow to
determine whether the identity is a member of the ACLs associated with
the given operations. | Below is the the instruction that describes the task:
### Input:
Implements Authorizer.authorize by calling identity.allow to
determine whether the identity is a member of the ACLs associated with
the given operations.
### Response:
def authorize(self, ctx, identity, ops):
'''Implements Aut... |
def get_first_edge_id_by_node_ids(self, node_a, node_b):
"""Returns the first (and possibly only) edge connecting node_a and node_b."""
ret = self.get_edge_ids_by_node_ids(node_a, node_b)
if not ret:
return None
else:
return ret[0] | Returns the first (and possibly only) edge connecting node_a and node_b. | Below is the the instruction that describes the task:
### Input:
Returns the first (and possibly only) edge connecting node_a and node_b.
### Response:
def get_first_edge_id_by_node_ids(self, node_a, node_b):
"""Returns the first (and possibly only) edge connecting node_a and node_b."""
ret = self.... |
def getlogger(pkg='', handler=None):
"""
패키지 혹은 채널 로거
logging.getLogger(package_name) or logg.getLogger()
:param pkg: str
"""
from .caller import caller
if not pkg:
m = caller.modulename()
s = m.split('.', 1)
if len(s) > 1:
pkg = s[0]
if haslogger(pk... | 패키지 혹은 채널 로거
logging.getLogger(package_name) or logg.getLogger()
:param pkg: str | Below is the the instruction that describes the task:
### Input:
패키지 혹은 채널 로거
logging.getLogger(package_name) or logg.getLogger()
:param pkg: str
### Response:
def getlogger(pkg='', handler=None):
"""
패키지 혹은 채널 로거
logging.getLogger(package_name) or logg.getLogger()
:param pkg: str
"""
... |
def parents(self, name=None):
"""
Yields all parents of this element, back to the root element.
:param name: If specified, only consider elements with this tag name
"""
p = self.parent
while p is not None:
if name is None or p.tagname == name:
... | Yields all parents of this element, back to the root element.
:param name: If specified, only consider elements with this tag name | Below is the the instruction that describes the task:
### Input:
Yields all parents of this element, back to the root element.
:param name: If specified, only consider elements with this tag name
### Response:
def parents(self, name=None):
"""
Yields all parents of this element, back to th... |
def _denom(self, R, z):
"""
NAME:
_denom
PURPOSE:
evaluate R^2 + (a + |z|)^2 which is used in the denominator
of most equations
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
OUTPUT:
R^2 + (a + |z... | NAME:
_denom
PURPOSE:
evaluate R^2 + (a + |z|)^2 which is used in the denominator
of most equations
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
OUTPUT:
R^2 + (a + |z|)^2
HISTORY:
2016-05-09 ... | Below is the the instruction that describes the task:
### Input:
NAME:
_denom
PURPOSE:
evaluate R^2 + (a + |z|)^2 which is used in the denominator
of most equations
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
OUTPUT:... |
def in6_isvalid(address):
"""Return True if 'address' is a valid IPv6 address string, False
otherwise."""
try:
socket.inet_pton(socket.AF_INET6, address)
return True
except Exception:
return False | Return True if 'address' is a valid IPv6 address string, False
otherwise. | Below is the the instruction that describes the task:
### Input:
Return True if 'address' is a valid IPv6 address string, False
otherwise.
### Response:
def in6_isvalid(address):
"""Return True if 'address' is a valid IPv6 address string, False
otherwise."""
try:
socket.inet_pton(soc... |
def __parameter_default(self, final_subfield):
"""Returns default value of final subfield if it has one.
If this subfield comes from a field list returned from __field_to_subfields,
none of the fields in the subfield list can have a default except the final
one since they all must be message fields.
... | Returns default value of final subfield if it has one.
If this subfield comes from a field list returned from __field_to_subfields,
none of the fields in the subfield list can have a default except the final
one since they all must be message fields.
Args:
final_subfield: A simple field from the... | Below is the the instruction that describes the task:
### Input:
Returns default value of final subfield if it has one.
If this subfield comes from a field list returned from __field_to_subfields,
none of the fields in the subfield list can have a default except the final
one since they all must be mes... |
def is_ignored(mod_or_pkg, ignored_package):
"""Test, if this :class:`docfly.pkg.picage.Module`
or :class:`docfly.pkg.picage.Package` should be included to generate
API reference document.
:param mod_or_pkg: module or package
:param ignored_package: ignored package
**中文文档**
根据全名判断一个包或者模块是... | Test, if this :class:`docfly.pkg.picage.Module`
or :class:`docfly.pkg.picage.Package` should be included to generate
API reference document.
:param mod_or_pkg: module or package
:param ignored_package: ignored package
**中文文档**
根据全名判断一个包或者模块是否要被包含到自动生成的API文档中。 | Below is the the instruction that describes the task:
### Input:
Test, if this :class:`docfly.pkg.picage.Module`
or :class:`docfly.pkg.picage.Package` should be included to generate
API reference document.
:param mod_or_pkg: module or package
:param ignored_package: ignored package
**中文文档**
... |
def get(key, host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Retrieve value for a key
CLI Example:
.. code-block:: bash
salt '*' memcached.get <key>
'''
conn = _connect(host, port)
_check_stats(conn)
return conn.get(key) | Retrieve value for a key
CLI Example:
.. code-block:: bash
salt '*' memcached.get <key> | Below is the the instruction that describes the task:
### Input:
Retrieve value for a key
CLI Example:
.. code-block:: bash
salt '*' memcached.get <key>
### Response:
def get(key, host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Retrieve value for a key
CLI Example:
.. code-block:: b... |
def call_hpp(self, message, action, hmac_key="", **kwargs):
"""This will call the adyen hpp. hmac_key and platform are pulled from
root module level and or self object.
AdyenResult will be returned on 200 response.
Otherwise, an exception is raised.
Args:
request_dat... | This will call the adyen hpp. hmac_key and platform are pulled from
root module level and or self object.
AdyenResult will be returned on 200 response.
Otherwise, an exception is raised.
Args:
request_data (dict): The dictionary of the request to place. This
... | Below is the the instruction that describes the task:
### Input:
This will call the adyen hpp. hmac_key and platform are pulled from
root module level and or self object.
AdyenResult will be returned on 200 response.
Otherwise, an exception is raised.
Args:
request_data ... |
def set_identities(self,identities):
"""Set identities in the disco#info object.
Remove all existing identities from `self`.
:Parameters:
- `identities`: list of identities or identity properties
(jid,node,category,type,name).
:Types:
- `identities... | Set identities in the disco#info object.
Remove all existing identities from `self`.
:Parameters:
- `identities`: list of identities or identity properties
(jid,node,category,type,name).
:Types:
- `identities`: sequence of `DiscoIdentity` or sequence of se... | Below is the the instruction that describes the task:
### Input:
Set identities in the disco#info object.
Remove all existing identities from `self`.
:Parameters:
- `identities`: list of identities or identity properties
(jid,node,category,type,name).
:Types:
... |
def qry_create(options):
"""Create query from the args specified and command chosen.
Creates a query string that incorporates the args in the options
object, and creates the title for the 'list' function.
Args:
options (object): contains args and data from parser
Returns:
qry_strin... | Create query from the args specified and command chosen.
Creates a query string that incorporates the args in the options
object, and creates the title for the 'list' function.
Args:
options (object): contains args and data from parser
Returns:
qry_string (str): the query to be used ag... | Below is the the instruction that describes the task:
### Input:
Create query from the args specified and command chosen.
Creates a query string that incorporates the args in the options
object, and creates the title for the 'list' function.
Args:
options (object): contains args and data from ... |
def pulse_train(time, start, duration, repeat_time, end):
""" Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
... | Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0 | Below is the the instruction that describes the task:
### Input:
Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
... |
def get_global_config(*args):
'''Get (a subset of) the global configuration.
If no arguments are provided, returns the entire configuration.
Otherwise, start with the entire configuration, and get the item
named by the first parameter; then search that for the second
parameter; and so on.
:par... | Get (a subset of) the global configuration.
If no arguments are provided, returns the entire configuration.
Otherwise, start with the entire configuration, and get the item
named by the first parameter; then search that for the second
parameter; and so on.
:param args: configuration name path to f... | Below is the the instruction that describes the task:
### Input:
Get (a subset of) the global configuration.
If no arguments are provided, returns the entire configuration.
Otherwise, start with the entire configuration, and get the item
named by the first parameter; then search that for the second
... |
def certificate(self):
"""
An asn1crypto.x509.Certificate object of the end-entity certificate
presented by the server
"""
if self._ssl is None:
self._raise_closed()
if self._certificate is None:
self._read_certificates()
return self._ce... | An asn1crypto.x509.Certificate object of the end-entity certificate
presented by the server | Below is the the instruction that describes the task:
### Input:
An asn1crypto.x509.Certificate object of the end-entity certificate
presented by the server
### Response:
def certificate(self):
"""
An asn1crypto.x509.Certificate object of the end-entity certificate
presented by the ... |
def _get_exposures_requiring_pyephem_positions(
self,
concurrentSnapshots=10):
"""*get next batch of exposures requiring pyephem positions*
**Key Arguments:**
- ``concurrentSnapshots`` -- number of concurrent PyEphem snapshots to process
"""
self.log... | *get next batch of exposures requiring pyephem positions*
**Key Arguments:**
- ``concurrentSnapshots`` -- number of concurrent PyEphem snapshots to process | Below is the the instruction that describes the task:
### Input:
*get next batch of exposures requiring pyephem positions*
**Key Arguments:**
- ``concurrentSnapshots`` -- number of concurrent PyEphem snapshots to process
### Response:
def _get_exposures_requiring_pyephem_positions(
... |
def _update_x_transforms(self):
"""
Compute a new set of x-transform functions phik.
phik(xk) = theta(y) - sum of phii(xi) over i!=k
This is the first of the eponymous conditional expectations. The conditional
expectations are computed using the SuperSmoother.
"""
... | Compute a new set of x-transform functions phik.
phik(xk) = theta(y) - sum of phii(xi) over i!=k
This is the first of the eponymous conditional expectations. The conditional
expectations are computed using the SuperSmoother. | Below is the the instruction that describes the task:
### Input:
Compute a new set of x-transform functions phik.
phik(xk) = theta(y) - sum of phii(xi) over i!=k
This is the first of the eponymous conditional expectations. The conditional
expectations are computed using the SuperSmoother.
... |
def report(self, verbose=1):
"""
Creates a human readable report
Args:
verbose (int): verbosity level. Either 1, 2, or 3.
Returns:
str: the report
SeeAlso:
timerit.Timerit.print
Example:
>>> import math
>>> t... | Creates a human readable report
Args:
verbose (int): verbosity level. Either 1, 2, or 3.
Returns:
str: the report
SeeAlso:
timerit.Timerit.print
Example:
>>> import math
>>> ti = Timerit(num=1).call(math.factorial, 5)
... | Below is the the instruction that describes the task:
### Input:
Creates a human readable report
Args:
verbose (int): verbosity level. Either 1, 2, or 3.
Returns:
str: the report
SeeAlso:
timerit.Timerit.print
Example:
>>> import ma... |
def tohdf5(input_files, output_file, n_events, conv_times_to_jte, **kwargs):
"""Convert Any file to HDF5 file"""
if len(input_files) > 1:
cprint(
"Preparing to convert {} files to HDF5.".format(len(input_files))
)
from km3pipe import Pipeline # noqa
from km3pipe.io import... | Convert Any file to HDF5 file | Below is the the instruction that describes the task:
### Input:
Convert Any file to HDF5 file
### Response:
def tohdf5(input_files, output_file, n_events, conv_times_to_jte, **kwargs):
"""Convert Any file to HDF5 file"""
if len(input_files) > 1:
cprint(
"Preparing to convert {} files t... |
def update_pypsa_grid_reinforcement(network, equipment_changes):
"""
Update equipment data of lines and transformers after grid reinforcement.
During grid reinforcement (cf.
:func:`edisgo.flex_opt.reinforce_grid.reinforce_grid`) grid topology and
equipment of lines and transformers are changed.
... | Update equipment data of lines and transformers after grid reinforcement.
During grid reinforcement (cf.
:func:`edisgo.flex_opt.reinforce_grid.reinforce_grid`) grid topology and
equipment of lines and transformers are changed.
In order to save time and not do a full translation of eDisGo's grid
top... | Below is the the instruction that describes the task:
### Input:
Update equipment data of lines and transformers after grid reinforcement.
During grid reinforcement (cf.
:func:`edisgo.flex_opt.reinforce_grid.reinforce_grid`) grid topology and
equipment of lines and transformers are changed.
In orde... |
def push(tool, slug, config_loader, prompt=lambda included, excluded: True):
"""
Push to github.com/org/repo=username/slug if tool exists.
Returns username, commit hash
"""
check_dependencies()
org, (included, excluded) = connect(slug, config_loader)
with authenticate(org) as user, prepare... | Push to github.com/org/repo=username/slug if tool exists.
Returns username, commit hash | Below is the the instruction that describes the task:
### Input:
Push to github.com/org/repo=username/slug if tool exists.
Returns username, commit hash
### Response:
def push(tool, slug, config_loader, prompt=lambda included, excluded: True):
"""
Push to github.com/org/repo=username/slug if tool exist... |
def extensions(self):
"""
Generate the regular expression to match all the known extensions.
@return: the regular expression.
@rtype: regular expression object
"""
_tmp_extensions = self.mimes.encodings_map.keys() + \
self.mimes.suffix_map.keys() + \
... | Generate the regular expression to match all the known extensions.
@return: the regular expression.
@rtype: regular expression object | Below is the the instruction that describes the task:
### Input:
Generate the regular expression to match all the known extensions.
@return: the regular expression.
@rtype: regular expression object
### Response:
def extensions(self):
"""
Generate the regular expression to match al... |
def myfoo(i,s, course=['s'],gg=2,fdf=3,**d):
"""
return course id
Keyword arguments,
course, -- course object (default None)
"""
print ('data:',d)
if course:
print (course)
return course.get('id')
else:
print("No Course!")
return None | return course id
Keyword arguments,
course, -- course object (default None) | Below is the the instruction that describes the task:
### Input:
return course id
Keyword arguments,
course, -- course object (default None)
### Response:
def myfoo(i,s, course=['s'],gg=2,fdf=3,**d):
"""
return course id
Keyword arguments,
course, -- course object (default None)
"""
... |
def get_comment_object(self):
"""
NB: Overridden to remove dupe comment check for admins (necessary for
canned responses)
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError i... | NB: Overridden to remove dupe comment check for admins (necessary for
canned responses)
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
ValueError if not.
Does not set any of the fields tha... | Below is the the instruction that describes the task:
### Input:
NB: Overridden to remove dupe comment check for admins (necessary for
canned responses)
Return a new (unsaved) comment object based on the information in this
form. Assumes that the form is already validated and will throw a
... |
def get_brokers(self, names_only=False):
"""Get information on all the available brokers.
:rtype : dict of brokers
"""
try:
broker_ids = self.get_children("/brokers/ids")
except NoNodeError:
_log.info(
"cluster is empty."
)
... | Get information on all the available brokers.
:rtype : dict of brokers | Below is the the instruction that describes the task:
### Input:
Get information on all the available brokers.
:rtype : dict of brokers
### Response:
def get_brokers(self, names_only=False):
"""Get information on all the available brokers.
:rtype : dict of brokers
"""
try:... |
def get_ancestors(self):
""" Get all unique instance ancestors """
ancestors = list(self.get_parents())
ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors])
ancestors_with_parents = [a for a in ancestors if isinstance(a, DescendantMixin)]
for ancestor in anc... | Get all unique instance ancestors | Below is the the instruction that describes the task:
### Input:
Get all unique instance ancestors
### Response:
def get_ancestors(self):
""" Get all unique instance ancestors """
ancestors = list(self.get_parents())
ancestor_unique_attributes = set([(a.__class__, a.id) for a in ancestors])... |
def regex_opt_inner(strings, open_paren):
"""Return a regex that matches any string in the sorted list of strings."""
close_paren = open_paren and ')' or ''
# print strings, repr(open_paren)
if not strings:
# print '-> nothing left'
return ''
first = strings[0]
if len(strings) ==... | Return a regex that matches any string in the sorted list of strings. | Below is the the instruction that describes the task:
### Input:
Return a regex that matches any string in the sorted list of strings.
### Response:
def regex_opt_inner(strings, open_paren):
"""Return a regex that matches any string in the sorted list of strings."""
close_paren = open_paren and ')' or ''
... |
def count_star(session: Union[Session, Engine, Connection],
tablename: str,
*criteria: Any) -> int:
"""
Returns the result of ``COUNT(*)`` from the specified table (with
additional ``WHERE`` criteria if desired).
Args:
session: SQLAlchemy :class:`Session`, :class:`... | Returns the result of ``COUNT(*)`` from the specified table (with
additional ``WHERE`` criteria if desired).
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
tablename: name of the table
criteria: optional SQLAlchemy "where" criteria... | Below is the the instruction that describes the task:
### Input:
Returns the result of ``COUNT(*)`` from the specified table (with
additional ``WHERE`` criteria if desired).
Args:
session: SQLAlchemy :class:`Session`, :class:`Engine`, or
:class:`Connection` object
tablename: nam... |
def add_transition(self, output,
probability_func=lambda index: np.ones(len(index), dtype=float),
triggered=Trigger.NOT_TRIGGERED):
"""Builds a transition from this state to the given state.
output : State
The end state after the transition.
... | Builds a transition from this state to the given state.
output : State
The end state after the transition. | Below is the the instruction that describes the task:
### Input:
Builds a transition from this state to the given state.
output : State
The end state after the transition.
### Response:
def add_transition(self, output,
probability_func=lambda index: np.ones(len(index), d... |
def find(cls, *args, **kwargs):
"""
Returns all document dicts that pass the filter
"""
return list(cls.collection.find(*args, **kwargs)) | Returns all document dicts that pass the filter | Below is the the instruction that describes the task:
### Input:
Returns all document dicts that pass the filter
### Response:
def find(cls, *args, **kwargs):
"""
Returns all document dicts that pass the filter
"""
return list(cls.collection.find(*args, **kwargs)) |
def subfield_get(self, obj, type=None):
"""
Verbatim copy from:
https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38
"""
if obj is None:
return self
return obj.__dict__[self.field.name] | Verbatim copy from:
https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38 | Below is the the instruction that describes the task:
### Input:
Verbatim copy from:
https://github.com/django/django/blob/1.9.13/django/db/models/fields/subclassing.py#L38
### Response:
def subfield_get(self, obj, type=None):
"""
Verbatim copy from:
https://github.com/django/django/blob/1.9.13/dja... |
def canFetchMore(self, parentIndex):
""" Returns true if there is more data available for parent; otherwise returns false.
"""
parentItem = self.getItem(parentIndex)
if not parentItem:
return False
return parentItem.canFetchChildren() | Returns true if there is more data available for parent; otherwise returns false. | Below is the the instruction that describes the task:
### Input:
Returns true if there is more data available for parent; otherwise returns false.
### Response:
def canFetchMore(self, parentIndex):
""" Returns true if there is more data available for parent; otherwise returns false.
"""
par... |
def put_shebang(f, version):
"""
Writes a shebang to the first line of the file according to the specified
version. (2 | 3 | default)
"""
if not contains_shebang(f):
f.seek(0)
original_text = f.read()
f.seek(0)
f.write(shebangs[version] + original_text) | Writes a shebang to the first line of the file according to the specified
version. (2 | 3 | default) | Below is the the instruction that describes the task:
### Input:
Writes a shebang to the first line of the file according to the specified
version. (2 | 3 | default)
### Response:
def put_shebang(f, version):
"""
Writes a shebang to the first line of the file according to the specified
version. (2 ... |
def find_surface_sites_by_height(self, slab, height=0.9, xy_tol=0.05):
"""
This method finds surface sites by determining which sites are within
a threshold value in height from the topmost site in a list of sites
Args:
site_list (list): list of sites from which to select su... | This method finds surface sites by determining which sites are within
a threshold value in height from the topmost site in a list of sites
Args:
site_list (list): list of sites from which to select surface sites
height (float): threshold in angstroms of distance from topmost
... | Below is the the instruction that describes the task:
### Input:
This method finds surface sites by determining which sites are within
a threshold value in height from the topmost site in a list of sites
Args:
site_list (list): list of sites from which to select surface sites
... |
def _check_properties(cls, property_names, require_indexed=True):
"""Internal helper to check the given properties exist and meet specified
requirements.
Called from query.py.
Args:
property_names: List or tuple of property names -- each being a string,
possibly containing dots (to addre... | Internal helper to check the given properties exist and meet specified
requirements.
Called from query.py.
Args:
property_names: List or tuple of property names -- each being a string,
possibly containing dots (to address subproperties of structured
properties).
Raises:
In... | Below is the the instruction that describes the task:
### Input:
Internal helper to check the given properties exist and meet specified
requirements.
Called from query.py.
Args:
property_names: List or tuple of property names -- each being a string,
possibly containing dots (to address s... |
def _update_tcs_helper_catalogue_views_info_with_new_views(
self):
""" update tcs helper catalogue tables info with new tables
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage ex... | update tcs helper catalogue tables info with new tables
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exi... | Below is the the instruction that describes the task:
### Input:
update tcs helper catalogue tables info with new tables
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
... |
def colormode(self, mode=None, crange=None):
'''Sets the current colormode (can be RGB or HSB) and eventually
the color range.
If called without arguments, it returns the current colormode.
'''
if mode is not None:
if mode == "rgb":
self.color_mode = ... | Sets the current colormode (can be RGB or HSB) and eventually
the color range.
If called without arguments, it returns the current colormode. | Below is the the instruction that describes the task:
### Input:
Sets the current colormode (can be RGB or HSB) and eventually
the color range.
If called without arguments, it returns the current colormode.
### Response:
def colormode(self, mode=None, crange=None):
'''Sets the current colo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.