code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def calculate_splits(sdf_file, split_size):
"""Retrieve
"""
counts = _sdfstats(sdf_file)["counts"]
splits = []
cur = 0
for i in range(counts // split_size + (0 if counts % split_size == 0 else 1)):
splits.append("%s-%s" % (cur, min(counts, cur + split_size)))
cur += split_size
... | Retrieve | Below is the the instruction that describes the task:
### Input:
Retrieve
### Response:
def calculate_splits(sdf_file, split_size):
"""Retrieve
"""
counts = _sdfstats(sdf_file)["counts"]
splits = []
cur = 0
for i in range(counts // split_size + (0 if counts % split_size == 0 else 1)):
... |
def _rapply(input_layer, operation, *op_args, **op_kwargs):
"""Applies the given operation to this after expanding op_args.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_kwargs: Keywor... | Applies the given operation to this after expanding op_args.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_kwargs: Keyword arguments for the operation.
Returns:
A new layer with op... | Below is the the instruction that describes the task:
### Input:
Applies the given operation to this after expanding op_args.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_kwargs: Ke... |
def _generic_convert_string(v, from_type, to_type, encoding):
"""
Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent,
with string values converted to given 'to_type' (str or unicode).
This method must be used with Python 2 interpreter only.
:param v: ... | Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent,
with string values converted to given 'to_type' (str or unicode).
This method must be used with Python 2 interpreter only.
:param v: The value to convert
:param from_type: The original string type to con... | Below is the the instruction that describes the task:
### Input:
Generic method to convert any argument type (string type, list, set, tuple, dict) to an equivalent,
with string values converted to given 'to_type' (str or unicode).
This method must be used with Python 2 interpreter only.
:param v: The v... |
def _generate_enumerated_subtypes_tag_mapping(self, ns, data_type):
"""
Generates attributes needed for serializing and deserializing structs
with enumerated subtypes. These assignments are made after all the
Python class definitions to ensure that all references exist.
"""
... | Generates attributes needed for serializing and deserializing structs
with enumerated subtypes. These assignments are made after all the
Python class definitions to ensure that all references exist. | Below is the the instruction that describes the task:
### Input:
Generates attributes needed for serializing and deserializing structs
with enumerated subtypes. These assignments are made after all the
Python class definitions to ensure that all references exist.
### Response:
def _generate_enumera... |
def row(self):
"""
Game Dataset(Row)
:return: {
'retro_game_id': Retrosheet Game id
'game_type': Game Type(S/R/F/D/L/W)
'game_type_des': Game Type Description
(Spring Training or Regular Season or Wild-card Game or Divisional Series or LCS or World... | Game Dataset(Row)
:return: {
'retro_game_id': Retrosheet Game id
'game_type': Game Type(S/R/F/D/L/W)
'game_type_des': Game Type Description
(Spring Training or Regular Season or Wild-card Game or Divisional Series or LCS or World Series)
'st_fl': Sprin... | Below is the the instruction that describes the task:
### Input:
Game Dataset(Row)
:return: {
'retro_game_id': Retrosheet Game id
'game_type': Game Type(S/R/F/D/L/W)
'game_type_des': Game Type Description
(Spring Training or Regular Season or Wild-card Game or... |
def get(self, server):
"""
Returns a registered GPServer object with a matching GenePattern server url or index
Returns None if no matching result was found
:param server:
:return:
"""
# Handle indexes
if isinstance(server, int):
if server >= ... | Returns a registered GPServer object with a matching GenePattern server url or index
Returns None if no matching result was found
:param server:
:return: | Below is the the instruction that describes the task:
### Input:
Returns a registered GPServer object with a matching GenePattern server url or index
Returns None if no matching result was found
:param server:
:return:
### Response:
def get(self, server):
"""
Returns a regis... |
def media(self, uri):
"""Play a media file."""
try:
local_path, _ = urllib.request.urlretrieve(uri)
metadata = mutagen.File(local_path, easy=True)
if metadata.tags:
self._tags = metadata.tags
title = self._tags.get(TAG_TITLE, [])
... | Play a media file. | Below is the the instruction that describes the task:
### Input:
Play a media file.
### Response:
def media(self, uri):
"""Play a media file."""
try:
local_path, _ = urllib.request.urlretrieve(uri)
metadata = mutagen.File(local_path, easy=True)
if metadata.tags:
... |
def state_transition(history_id_key, table_name, always_set=[], may_spend_tokens=False):
"""
Decorator for the check() method on state-transition operations.
Make sure that:
* there is a __table__ field set, which names the table in which this record is stored.
* there is a __history_id_key__ field ... | Decorator for the check() method on state-transition operations.
Make sure that:
* there is a __table__ field set, which names the table in which this record is stored.
* there is a __history_id_key__ field set, which identifies the table record's primary key.
Any fields named in @always_set will alway... | Below is the the instruction that describes the task:
### Input:
Decorator for the check() method on state-transition operations.
Make sure that:
* there is a __table__ field set, which names the table in which this record is stored.
* there is a __history_id_key__ field set, which identifies the table ... |
def import_transcript_from_fs(edx_video_id, language_code, file_name, provider, resource_fs, static_dir):
"""
Imports transcript file from file system and creates transcript record in DS.
Arguments:
edx_video_id (str): Video id of the video.
language_code (unicode): Language code of the req... | Imports transcript file from file system and creates transcript record in DS.
Arguments:
edx_video_id (str): Video id of the video.
language_code (unicode): Language code of the requested transcript.
file_name (unicode): File name of the transcript file.
provider (unicode): Transcri... | Below is the the instruction that describes the task:
### Input:
Imports transcript file from file system and creates transcript record in DS.
Arguments:
edx_video_id (str): Video id of the video.
language_code (unicode): Language code of the requested transcript.
file_name (unicode): F... |
def CBO_L(self, **kwargs):
'''
Returns the strain-shifted L-valley conduction band offset (CBO),
assuming the strain affects all conduction band valleys equally.
'''
return (self.unstrained.CBO_L(**kwargs) +
self.CBO_strain_shift(**kwargs)) | Returns the strain-shifted L-valley conduction band offset (CBO),
assuming the strain affects all conduction band valleys equally. | Below is the the instruction that describes the task:
### Input:
Returns the strain-shifted L-valley conduction band offset (CBO),
assuming the strain affects all conduction band valleys equally.
### Response:
def CBO_L(self, **kwargs):
'''
Returns the strain-shifted L-valley conduction ban... |
def vocabulary(self, levels=None):
"""
:param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http... | :param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http://www.wanikani.com/api/v1.2#vocabulary-list | Below is the the instruction that describes the task:
### Input:
:param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None... |
def urlfetch_async(self, url, method='GET', headers=None,
payload=None, deadline=None, callback=None,
follow_redirects=False):
"""Make an async urlfetch() call.
This is an async wrapper around urlfetch(). It adds an authentication
header.
Args:
url: the ... | Make an async urlfetch() call.
This is an async wrapper around urlfetch(). It adds an authentication
header.
Args:
url: the url to fetch.
method: the method in which to fetch.
headers: the http headers.
payload: the data to submit in the fetch.
deadline: the deadline in which... | Below is the the instruction that describes the task:
### Input:
Make an async urlfetch() call.
This is an async wrapper around urlfetch(). It adds an authentication
header.
Args:
url: the url to fetch.
method: the method in which to fetch.
headers: the http headers.
payload: t... |
def cli(context, mongodb, username, password, authdb, host, port, loglevel, config, demo):
"""scout: manage interactions with a scout instance."""
# log_format = "%(message)s" if sys.stdout.isatty() else None
log_format = None
coloredlogs.install(level=loglevel, fmt=log_format)
LOG.info("Running sco... | scout: manage interactions with a scout instance. | Below is the the instruction that describes the task:
### Input:
scout: manage interactions with a scout instance.
### Response:
def cli(context, mongodb, username, password, authdb, host, port, loglevel, config, demo):
"""scout: manage interactions with a scout instance."""
# log_format = "%(message)s" if... |
def delete_store_credit_payment_by_id(cls, store_credit_payment_id, **kwargs):
"""Delete StoreCreditPayment
Delete an instance of StoreCreditPayment by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>... | Delete StoreCreditPayment
Delete an instance of StoreCreditPayment by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_store_credit_payment_by_id(store_credit_payment_id, async=True)
... | Below is the the instruction that describes the task:
### Input:
Delete StoreCreditPayment
Delete an instance of StoreCreditPayment by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delet... |
def check_model(self):
"""
Check the model for various errors. This method checks for the following
errors.
* Checks if the sum of the probabilities for each state is equal to 1 (tol=0.01).
* Checks if the CPDs associated with nodes are consistent with their parents.
Re... | Check the model for various errors. This method checks for the following
errors.
* Checks if the sum of the probabilities for each state is equal to 1 (tol=0.01).
* Checks if the CPDs associated with nodes are consistent with their parents.
Returns
-------
check: boolea... | Below is the the instruction that describes the task:
### Input:
Check the model for various errors. This method checks for the following
errors.
* Checks if the sum of the probabilities for each state is equal to 1 (tol=0.01).
* Checks if the CPDs associated with nodes are consistent with ... |
def _register_handler(event, fun, external=False):
"""Register a function to be an event handler"""
registry = core.HANDLER_REGISTRY
if external:
registry = core.EXTERNAL_HANDLER_REGISTRY
if not isinstance(event, basestring):
# If not basestring, it is a BaseEvent subclass.
# Th... | Register a function to be an event handler | Below is the the instruction that describes the task:
### Input:
Register a function to be an event handler
### Response:
def _register_handler(event, fun, external=False):
"""Register a function to be an event handler"""
registry = core.HANDLER_REGISTRY
if external:
registry = core.EXTERNAL_HA... |
def from_element(self, element, defaults={}):
"""Populate object variables from SVD element"""
if isinstance(defaults, SvdElement):
defaults = vars(defaults)
for key in self.props:
try:
value = element.find(key).text
except AttributeError: # M... | Populate object variables from SVD element | Below is the the instruction that describes the task:
### Input:
Populate object variables from SVD element
### Response:
def from_element(self, element, defaults={}):
"""Populate object variables from SVD element"""
if isinstance(defaults, SvdElement):
defaults = vars(defaults)
... |
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise Sal... | .. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
### Response:
def list_storage_containers(kwargs=None, storage_con... |
def restart_service(service, log=False):
""" restarts a service """
with settings():
if log:
bookshelf2.logging_helpers.log_yellow(
'stoping service %s' % service)
sudo('service %s stop' % service)
if log:
bookshelf2.logging_helpers.log_yellow(
... | restarts a service | Below is the the instruction that describes the task:
### Input:
restarts a service
### Response:
def restart_service(service, log=False):
""" restarts a service """
with settings():
if log:
bookshelf2.logging_helpers.log_yellow(
'stoping service %s' % service)
... |
def get_default_property_values(self, classname):
"""Return a dict with default values for all properties declared on this class."""
schema_element = self.get_element_by_class_name(classname)
result = {
property_name: property_descriptor.default
for property_name, proper... | Return a dict with default values for all properties declared on this class. | Below is the the instruction that describes the task:
### Input:
Return a dict with default values for all properties declared on this class.
### Response:
def get_default_property_values(self, classname):
"""Return a dict with default values for all properties declared on this class."""
schema_ele... |
def scan(self, scanner, node_list):
"""Scan a list of this Executor's files (targets or sources) for
implicit dependencies and update all of the targets with them.
This essentially short-circuits an N*M scan of the sources for
each individual target, which is a hell of a lot more efficie... | Scan a list of this Executor's files (targets or sources) for
implicit dependencies and update all of the targets with them.
This essentially short-circuits an N*M scan of the sources for
each individual target, which is a hell of a lot more efficient. | Below is the the instruction that describes the task:
### Input:
Scan a list of this Executor's files (targets or sources) for
implicit dependencies and update all of the targets with them.
This essentially short-circuits an N*M scan of the sources for
each individual target, which is a hell... |
def file_rename(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /file-xxxx/rename API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Name#API-method%3A-%2Fclass-xxxx%2Frename
"""
return DXHTTPRequest('/%s/rename' % object_id, input_params, a... | Invokes the /file-xxxx/rename API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Name#API-method%3A-%2Fclass-xxxx%2Frename | Below is the the instruction that describes the task:
### Input:
Invokes the /file-xxxx/rename API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Name#API-method%3A-%2Fclass-xxxx%2Frename
### Response:
def file_rename(object_id, input_params={}, always_retry=True, **kwargs):
... |
def filter_records(self, records):
"""
Apply the filter to records
"""
for record in records:
try:
filtered = self.filter_record(record)
assert (filtered)
# Quick tracking whether the sequence was modified
if fil... | Apply the filter to records | Below is the the instruction that describes the task:
### Input:
Apply the filter to records
### Response:
def filter_records(self, records):
"""
Apply the filter to records
"""
for record in records:
try:
filtered = self.filter_record(record)
... |
def close(self):
"""Close this metrics repository."""
for reporter in self._reporters:
reporter.close()
self._metrics.clear() | Close this metrics repository. | Below is the the instruction that describes the task:
### Input:
Close this metrics repository.
### Response:
def close(self):
"""Close this metrics repository."""
for reporter in self._reporters:
reporter.close()
self._metrics.clear() |
def yn_prompt(text):
'''
Takes the text prompt, and presents it, takes only "y" or "n" for
answers, and returns True or False. Repeats itself on bad input.
'''
text = "\n"+ text + "\n('y' or 'n'): "
while True:
answer = input(text).strip()
if answer != 'y' and answer !... | Takes the text prompt, and presents it, takes only "y" or "n" for
answers, and returns True or False. Repeats itself on bad input. | Below is the the instruction that describes the task:
### Input:
Takes the text prompt, and presents it, takes only "y" or "n" for
answers, and returns True or False. Repeats itself on bad input.
### Response:
def yn_prompt(text):
'''
Takes the text prompt, and presents it, takes only "y" or "n... |
def transfer_bankcard(self, true_name, bank_card_no, bank_code, amount, desc=None, out_trade_no=None):
"""
企业付款到银行卡接口
:param true_name: 开户人名称
:param bank_card_no: 银行卡号
:param bank_code: 银行编号
:param amount: 付款金额,单位分
:param desc: 付款说明
:param out_trade_no: 可... | 企业付款到银行卡接口
:param true_name: 开户人名称
:param bank_card_no: 银行卡号
:param bank_code: 银行编号
:param amount: 付款金额,单位分
:param desc: 付款说明
:param out_trade_no: 可选,商户订单号,需保持唯一性,默认自动生成
:return: 返回的结果信息 | Below is the the instruction that describes the task:
### Input:
企业付款到银行卡接口
:param true_name: 开户人名称
:param bank_card_no: 银行卡号
:param bank_code: 银行编号
:param amount: 付款金额,单位分
:param desc: 付款说明
:param out_trade_no: 可选,商户订单号,需保持唯一性,默认自动生成
:return: 返回的结果信息
### Res... |
def delta_crl_distribution_points(self):
"""
Returns delta CRL URLs - does not include complete CRLs
:return:
A list of zero or more DistributionPoint objects
"""
if self._delta_crl_distribution_points is None:
self._delta_crl_distribution_points = self.... | Returns delta CRL URLs - does not include complete CRLs
:return:
A list of zero or more DistributionPoint objects | Below is the the instruction that describes the task:
### Input:
Returns delta CRL URLs - does not include complete CRLs
:return:
A list of zero or more DistributionPoint objects
### Response:
def delta_crl_distribution_points(self):
"""
Returns delta CRL URLs - does not includ... |
def on_map_clicked(self, pos):
""" Called when the map is clicked """
d = self.declaration
d.clicked({
'click': 'short',
'position': tuple(pos)
}) | Called when the map is clicked | Below is the the instruction that describes the task:
### Input:
Called when the map is clicked
### Response:
def on_map_clicked(self, pos):
""" Called when the map is clicked """
d = self.declaration
d.clicked({
'click': 'short',
'position': tuple(pos)
}) |
def fastqfilter(self):
"""Filter the reads into separate files based on taxonomic assignment"""
printtime('Creating filtered .fastqfiles', self.start)
# Create and start threads
for i in range(self.cpus):
# Send the threads to the appropriate destination function
... | Filter the reads into separate files based on taxonomic assignment | Below is the the instruction that describes the task:
### Input:
Filter the reads into separate files based on taxonomic assignment
### Response:
def fastqfilter(self):
"""Filter the reads into separate files based on taxonomic assignment"""
printtime('Creating filtered .fastqfiles', self.start)
... |
def write(self, data):
'''
Write some bytes to the transport.
'''
if not hasattr(self, '_sock'):
return None
try:
self._sock.sendall(data)
if self.connection.debug > 1:
self.connection.logger.debug(
'sent %... | Write some bytes to the transport. | Below is the the instruction that describes the task:
### Input:
Write some bytes to the transport.
### Response:
def write(self, data):
'''
Write some bytes to the transport.
'''
if not hasattr(self, '_sock'):
return None
try:
self._sock.sendall(dat... |
def vae(x, z_size, name=None):
"""Simple variational autoencoder without discretization.
Args:
x: Input to the discretization bottleneck.
z_size: Number of bits, where discrete codes range from 1 to 2**z_size.
name: Name for the bottleneck scope.
Returns:
Embedding function, latent, loss, mu and... | Simple variational autoencoder without discretization.
Args:
x: Input to the discretization bottleneck.
z_size: Number of bits, where discrete codes range from 1 to 2**z_size.
name: Name for the bottleneck scope.
Returns:
Embedding function, latent, loss, mu and log_simga. | Below is the the instruction that describes the task:
### Input:
Simple variational autoencoder without discretization.
Args:
x: Input to the discretization bottleneck.
z_size: Number of bits, where discrete codes range from 1 to 2**z_size.
name: Name for the bottleneck scope.
Returns:
Embeddi... |
def initialize(self):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.initialize`.
"""
# Allocate appropriate temporal memory object
# Retrieve the necessary extra arguments that were handled automatically
autoArgs = dict((name, getattr(self, name))
for name in self._te... | Overrides :meth:`~nupic.bindings.regions.PyRegion.initialize`. | Below is the the instruction that describes the task:
### Input:
Overrides :meth:`~nupic.bindings.regions.PyRegion.initialize`.
### Response:
def initialize(self):
"""
Overrides :meth:`~nupic.bindings.regions.PyRegion.initialize`.
"""
# Allocate appropriate temporal memory object
# Retrieve the... |
def create_archive(
self,
archive_name,
authority_name,
archive_path,
versioned,
raise_on_err=True,
metadata=None,
user_config=None,
tags=None,
helper=False):
'''
Create a new data arc... | Create a new data archive
Returns
-------
archive : object
new :py:class:`~datafs.core.data_archive.DataArchive` object | Below is the the instruction that describes the task:
### Input:
Create a new data archive
Returns
-------
archive : object
new :py:class:`~datafs.core.data_archive.DataArchive` object
### Response:
def create_archive(
self,
archive_name,
aut... |
def agents_email_show(self, email_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/agents#get-agent-by-email-id"
api_path = "/api/v2/agents/email/{email_id}"
api_path = api_path.format(email_id=email_id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/chat/agents#get-agent-by-email-id | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/chat/agents#get-agent-by-email-id
### Response:
def agents_email_show(self, email_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/agents#get-agent-by-email-id"
api_path = "/... |
def update_matches(self, other):
"""
Update this instance's Matches to point to the given other's Matches.
Find Matches with the same TextLogError as our Matches, updating their
score if less than ours and mark our matches for deletion.
If there are no other matches, update our... | Update this instance's Matches to point to the given other's Matches.
Find Matches with the same TextLogError as our Matches, updating their
score if less than ours and mark our matches for deletion.
If there are no other matches, update ours to point to the other
ClassifiedFailure. | Below is the the instruction that describes the task:
### Input:
Update this instance's Matches to point to the given other's Matches.
Find Matches with the same TextLogError as our Matches, updating their
score if less than ours and mark our matches for deletion.
If there are no other mat... |
def clear_measurements(self):
"""Remove all measurements from self.measurements. Reset the
measurement counter. All ID are invalidated.
"""
keys = list(self.measurements.keys())
for key in keys:
del(self.measurements[key])
self.meas_counter = -1 | Remove all measurements from self.measurements. Reset the
measurement counter. All ID are invalidated. | Below is the the instruction that describes the task:
### Input:
Remove all measurements from self.measurements. Reset the
measurement counter. All ID are invalidated.
### Response:
def clear_measurements(self):
"""Remove all measurements from self.measurements. Reset the
measurement counte... |
def update_layers_geonode_wm(service, num_layers=None):
"""
Update layers for a WorldMap instance.
Sample endpoint: http://localhost:8000/
"""
wm_api_url = urlparse.urljoin(service.url, 'worldmap/api/2.8/layer/?format=json')
if num_layers:
total = num_layers
else:
response =... | Update layers for a WorldMap instance.
Sample endpoint: http://localhost:8000/ | Below is the the instruction that describes the task:
### Input:
Update layers for a WorldMap instance.
Sample endpoint: http://localhost:8000/
### Response:
def update_layers_geonode_wm(service, num_layers=None):
"""
Update layers for a WorldMap instance.
Sample endpoint: http://localhost:8000/
... |
def balance(self, account_id=None):
"""
Returns balance information for a specific account.
Official docs:
https://monzo.com/docs/#read-balance
:param account_id: Monzo account ID
:type account_id: str
:raises: ValueError
:returns: Monzo balance inst... | Returns balance information for a specific account.
Official docs:
https://monzo.com/docs/#read-balance
:param account_id: Monzo account ID
:type account_id: str
:raises: ValueError
:returns: Monzo balance instance
:rtype: MonzoBalance | Below is the the instruction that describes the task:
### Input:
Returns balance information for a specific account.
Official docs:
https://monzo.com/docs/#read-balance
:param account_id: Monzo account ID
:type account_id: str
:raises: ValueError
:returns: Monzo... |
def _to_p(self, mode):
"""Convert the image to P or PA mode.
"""
if self.mode.endswith("A"):
chans = self.channels[:-1]
alpha = self.channels[-1]
self._secondary_mode = self.mode[:-1]
else:
chans = self.channels
alpha = None
... | Convert the image to P or PA mode. | Below is the the instruction that describes the task:
### Input:
Convert the image to P or PA mode.
### Response:
def _to_p(self, mode):
"""Convert the image to P or PA mode.
"""
if self.mode.endswith("A"):
chans = self.channels[:-1]
alpha = self.channels[-1]
... |
def get_group(value):
""" group = display-name ":" [group-list] ";" [CFWS]
"""
group = Group()
token, value = get_display_name(value)
if not value or value[0] != ':':
raise errors.HeaderParseError("expected ':' at end of group "
"display name but found '{}'".format(value))
g... | group = display-name ":" [group-list] ";" [CFWS] | Below is the the instruction that describes the task:
### Input:
group = display-name ":" [group-list] ";" [CFWS]
### Response:
def get_group(value):
""" group = display-name ":" [group-list] ";" [CFWS]
"""
group = Group()
token, value = get_display_name(value)
if not value or value[0] != ':':... |
def extract_from_commoncrawl(self, warc_download_url, callback_on_article_extracted, valid_hosts=None,
start_date=None, end_date=None,
strict_date=True, reuse_previously_downloaded_files=True, local_download_dir_warc=None,
... | Crawl and extract articles form the news crawl provided by commoncrawl.org. For each article that was extracted
successfully the callback function callback_on_article_extracted is invoked where the first parameter is the
article object.
:param log_pathname_fully_extracted_warcs:
:param d... | Below is the the instruction that describes the task:
### Input:
Crawl and extract articles form the news crawl provided by commoncrawl.org. For each article that was extracted
successfully the callback function callback_on_article_extracted is invoked where the first parameter is the
article object... |
def search(self, field_name, field_value, record=None, **options):
"""
Returns all matching records found in :any:`get_all`
>>> airtable.search('Gender', 'Male')
[{'fields': {'Name': 'John', 'Gender': 'Male'}, ... ]
Args:
field_name (``str``): Name of field ... | Returns all matching records found in :any:`get_all`
>>> airtable.search('Gender', 'Male')
[{'fields': {'Name': 'John', 'Gender': 'Male'}, ... ]
Args:
field_name (``str``): Name of field to match (column name).
field_value (``str``): Value of field to match.
... | Below is the the instruction that describes the task:
### Input:
Returns all matching records found in :any:`get_all`
>>> airtable.search('Gender', 'Male')
[{'fields': {'Name': 'John', 'Gender': 'Male'}, ... ]
Args:
field_name (``str``): Name of field to match (column nam... |
def enforce_versioning(force=False):
"""Install versioning on the db."""
connect_str, repo_url = get_version_data()
LOG.warning("Your database uses an unversioned benchbuild schema.")
if not force and not ui.ask(
"Should I enforce version control on your schema?"):
LOG.error("User de... | Install versioning on the db. | Below is the the instruction that describes the task:
### Input:
Install versioning on the db.
### Response:
def enforce_versioning(force=False):
"""Install versioning on the db."""
connect_str, repo_url = get_version_data()
LOG.warning("Your database uses an unversioned benchbuild schema.")
if not... |
def set(cls, obj, keys, value, fill_list_value=None):
"""
sets the value for the given keys on obj. if any of the given
keys does not exist, create the intermediate containers.
"""
current = obj
keys_list = keys.split(".")
for idx, key in enumerate(keys_list, 1):... | sets the value for the given keys on obj. if any of the given
keys does not exist, create the intermediate containers. | Below is the the instruction that describes the task:
### Input:
sets the value for the given keys on obj. if any of the given
keys does not exist, create the intermediate containers.
### Response:
def set(cls, obj, keys, value, fill_list_value=None):
"""
sets the value for the given keys o... |
def proximal(self, sigma):
"""Prox operator of TV. It allows the proximal step length to be a
vector of positive elements.
Examples
--------
Check that the proximal operator is the identity for sigma=0
>>> import odl.contrib.solvers.spdhg as spdhg, odl, numpy as np
... | Prox operator of TV. It allows the proximal step length to be a
vector of positive elements.
Examples
--------
Check that the proximal operator is the identity for sigma=0
>>> import odl.contrib.solvers.spdhg as spdhg, odl, numpy as np
>>> space = odl.uniform_discr([0, ... | Below is the the instruction that describes the task:
### Input:
Prox operator of TV. It allows the proximal step length to be a
vector of positive elements.
Examples
--------
Check that the proximal operator is the identity for sigma=0
>>> import odl.contrib.solvers.spdhg ... |
def depends_on(self, dependency):
"""
List of packages that depend on dependency
:param dependency: package name, e.g. 'vext' or 'Pillow'
"""
packages = self.package_info()
return [package for package in packages if dependency in package.get("requires", "")] | List of packages that depend on dependency
:param dependency: package name, e.g. 'vext' or 'Pillow' | Below is the the instruction that describes the task:
### Input:
List of packages that depend on dependency
:param dependency: package name, e.g. 'vext' or 'Pillow'
### Response:
def depends_on(self, dependency):
"""
List of packages that depend on dependency
:param dependency: pac... |
def next_retrieve_group_item(self, last_item=None, entry=None):
"""Return the item to start from in next reviews group."""
next_item = None
gerrit_version = self.version
if gerrit_version[0] == 2 and gerrit_version[1] > 9:
if last_item is None:
next_item = ... | Return the item to start from in next reviews group. | Below is the the instruction that describes the task:
### Input:
Return the item to start from in next reviews group.
### Response:
def next_retrieve_group_item(self, last_item=None, entry=None):
"""Return the item to start from in next reviews group."""
next_item = None
gerrit_version = ... |
def qualified_name(self):
"""Get the qualified name of the variant.
Returns:
str: Name of the variant with version and index, eg "maya-2016.1[1]".
"""
idxstr = '' if self.index is None else str(self.index)
return "%s[%s]" % (self.qualified_package_name, idxstr) | Get the qualified name of the variant.
Returns:
str: Name of the variant with version and index, eg "maya-2016.1[1]". | Below is the the instruction that describes the task:
### Input:
Get the qualified name of the variant.
Returns:
str: Name of the variant with version and index, eg "maya-2016.1[1]".
### Response:
def qualified_name(self):
"""Get the qualified name of the variant.
Returns:
... |
def diff(self, obj=None):
"""Determine if something has changed or not"""
if self.no_resource:
return NOOP
if not self.present:
if self.existing:
return DEL
return NOOP
if not obj:
obj = self.obj()
is_diff = NOOP... | Determine if something has changed or not | Below is the the instruction that describes the task:
### Input:
Determine if something has changed or not
### Response:
def diff(self, obj=None):
"""Determine if something has changed or not"""
if self.no_resource:
return NOOP
if not self.present:
if self.existing:... |
def __get_pricedb_session(self):
""" Provides initialization and access to module-level session """
from pricedb import dal
if not self.pricedb_session:
self.pricedb_session = dal.get_default_session()
return self.pricedb_session | Provides initialization and access to module-level session | Below is the the instruction that describes the task:
### Input:
Provides initialization and access to module-level session
### Response:
def __get_pricedb_session(self):
""" Provides initialization and access to module-level session """
from pricedb import dal
if not self.pricedb_session:... |
def do_dep(self, args):
"""Adds the name and attribute of a dependent variable to the list
for plotting/tabulating functions."""
vals = args.split()
twin = None
if len(vals) > 1:
if len(vals) == 2:
var, plot = vals
elif len(vals) == 3:
... | Adds the name and attribute of a dependent variable to the list
for plotting/tabulating functions. | Below is the the instruction that describes the task:
### Input:
Adds the name and attribute of a dependent variable to the list
for plotting/tabulating functions.
### Response:
def do_dep(self, args):
"""Adds the name and attribute of a dependent variable to the list
for plotting/tabulat... |
def is_blocked(self, ip):
"""Determine if an IP address should be considered blocked."""
blocked = True
if ip in self.allowed_admin_ips:
blocked = False
for allowed_range in self.allowed_admin_ip_ranges:
if ipaddress.ip_address(ip) in ipaddress.ip_network(allowe... | Determine if an IP address should be considered blocked. | Below is the the instruction that describes the task:
### Input:
Determine if an IP address should be considered blocked.
### Response:
def is_blocked(self, ip):
"""Determine if an IP address should be considered blocked."""
blocked = True
if ip in self.allowed_admin_ips:
block... |
def addAction(self, action, checked=None, autoBuild=True):
"""
Adds the inputed action to this widget's action group. This will auto-\
create a new group if no group is already defined.
:param action | <QAction> || <str>
:return <QAction>
... | Adds the inputed action to this widget's action group. This will auto-\
create a new group if no group is already defined.
:param action | <QAction> || <str>
:return <QAction> | Below is the the instruction that describes the task:
### Input:
Adds the inputed action to this widget's action group. This will auto-\
create a new group if no group is already defined.
:param action | <QAction> || <str>
:return <QAction>
### Response:
def... |
def paint(self, painter, option, index):
"""Paint checkbox and text
_
|_| My label
"""
body_rect = QtCore.QRectF(option.rect)
check_rect = QtCore.QRectF(body_rect)
check_rect.setWidth(check_rect.height())
check_rect.adjust(6, 6, -6, -6)
check... | Paint checkbox and text
_
|_| My label | Below is the the instruction that describes the task:
### Input:
Paint checkbox and text
_
|_| My label
### Response:
def paint(self, painter, option, index):
"""Paint checkbox and text
_
|_| My label
"""
body_rect = QtCore.QRectF(option.rect)
... |
def copy(self, texture, source_rect=None, dest_rect=None, rotation=0, center=None, flip=lib.SDL_FLIP_NONE):
"""Copy a portion of the source texture to the current rendering target, rotating it by angle around the given center.
Args:
texture (Texture): The source texture.
source_... | Copy a portion of the source texture to the current rendering target, rotating it by angle around the given center.
Args:
texture (Texture): The source texture.
source_rect (Rect): The source rectangle, or None for the entire texture.
dest_rect (Rect): The destination rectan... | Below is the the instruction that describes the task:
### Input:
Copy a portion of the source texture to the current rendering target, rotating it by angle around the given center.
Args:
texture (Texture): The source texture.
source_rect (Rect): The source rectangle, or None for the... |
def get_author_label(self, urn):
"""Get the label corresponding to the author identified by the CTS URN.
try to get an lang=en label (if multiple labels in this lang pick the shortest)
try to get a lang=la label (if multiple labels in this lang exist pick the shortest)
try to get a lang... | Get the label corresponding to the author identified by the CTS URN.
try to get an lang=en label (if multiple labels in this lang pick the shortest)
try to get a lang=la label (if multiple labels in this lang exist pick the shortest)
try to get a lang=None label (if multiple labels in this lang... | Below is the the instruction that describes the task:
### Input:
Get the label corresponding to the author identified by the CTS URN.
try to get an lang=en label (if multiple labels in this lang pick the shortest)
try to get a lang=la label (if multiple labels in this lang exist pick the shortest)
... |
def _make_value(self, field_name, field_spec, value_spec, field_params, value):
"""
Contructs an appropriate Asn1Value object for a field
:param field_name:
A unicode string of the field name
:param field_spec:
An Asn1Value class that is the field spec
... | Contructs an appropriate Asn1Value object for a field
:param field_name:
A unicode string of the field name
:param field_spec:
An Asn1Value class that is the field spec
:param value_spec:
An Asn1Value class that is the vaue spec
:param field_params... | Below is the the instruction that describes the task:
### Input:
Contructs an appropriate Asn1Value object for a field
:param field_name:
A unicode string of the field name
:param field_spec:
An Asn1Value class that is the field spec
:param value_spec:
... |
def kmeans(*args, **kwargs):
"""
Find centers of multi-modal clusters of data using a kmeans approach
modified for spherical measurements.
Parameters
----------
*args : 2 or 3 sequences of measurements
By default, this will be expected to be ``strike`` & ``dip``, both
array-lik... | Find centers of multi-modal clusters of data using a kmeans approach
modified for spherical measurements.
Parameters
----------
*args : 2 or 3 sequences of measurements
By default, this will be expected to be ``strike`` & ``dip``, both
array-like sequences representing poles to planes.... | Below is the the instruction that describes the task:
### Input:
Find centers of multi-modal clusters of data using a kmeans approach
modified for spherical measurements.
Parameters
----------
*args : 2 or 3 sequences of measurements
By default, this will be expected to be ``strike`` & ``d... |
def triangle_center(tri, uv=False):
""" Computes the center of mass of the input triangle.
:param tri: triangle object
:type tri: elements.Triangle
:param uv: if True, then finds parametric position of the center of mass
:type uv: bool
:return: center of mass of the triangle
:rtype: tuple
... | Computes the center of mass of the input triangle.
:param tri: triangle object
:type tri: elements.Triangle
:param uv: if True, then finds parametric position of the center of mass
:type uv: bool
:return: center of mass of the triangle
:rtype: tuple | Below is the the instruction that describes the task:
### Input:
Computes the center of mass of the input triangle.
:param tri: triangle object
:type tri: elements.Triangle
:param uv: if True, then finds parametric position of the center of mass
:type uv: bool
:return: center of mass of the tri... |
def enable(self, size, block_size=None, store=None, store_sync_interval=None):
"""Enables shared queue of the given size.
:param int size: Queue size.
:param int block_size: Block size in bytes. Default: 8 KiB.
:param str|unicode store: Persist the queue into file.
:param int... | Enables shared queue of the given size.
:param int size: Queue size.
:param int block_size: Block size in bytes. Default: 8 KiB.
:param str|unicode store: Persist the queue into file.
:param int store_sync_interval: Store sync interval in master cycles (usually seconds). | Below is the the instruction that describes the task:
### Input:
Enables shared queue of the given size.
:param int size: Queue size.
:param int block_size: Block size in bytes. Default: 8 KiB.
:param str|unicode store: Persist the queue into file.
:param int store_sync_interval:... |
def _pastore8(ins):
''' Stores 2º operand content into address of 1st operand.
1st operand is an array element. Dimensions are pushed into the
stack.
Use '*' for indirect store on 1st operand (A pointer to an array)
'''
output = _paddr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*'... | Stores 2º operand content into address of 1st operand.
1st operand is an array element. Dimensions are pushed into the
stack.
Use '*' for indirect store on 1st operand (A pointer to an array) | Below is the the instruction that describes the task:
### Input:
Stores 2º operand content into address of 1st operand.
1st operand is an array element. Dimensions are pushed into the
stack.
Use '*' for indirect store on 1st operand (A pointer to an array)
### Response:
def _pastore8(ins):
''' Stor... |
def evaluate_binop_math(self, operation, left, right, **kwargs):
"""
Evaluate given mathematical binary operation with given operands.
"""
if not operation in self.binops_math:
raise ValueError("Invalid math binary operation '{}'".format(operation))
if left is None or... | Evaluate given mathematical binary operation with given operands. | Below is the the instruction that describes the task:
### Input:
Evaluate given mathematical binary operation with given operands.
### Response:
def evaluate_binop_math(self, operation, left, right, **kwargs):
"""
Evaluate given mathematical binary operation with given operands.
"""
... |
def get_html_keywords(index_page):
"""
Return list of `keywords` parsed from HTML ``<meta>`` tags.
Args:
index_page (str): Content of the page as UTF-8 string
Returns:
list: List of :class:`.SourceString` objects.
"""
keyword_lists = (
keyword_list.split(",")
fo... | Return list of `keywords` parsed from HTML ``<meta>`` tags.
Args:
index_page (str): Content of the page as UTF-8 string
Returns:
list: List of :class:`.SourceString` objects. | Below is the the instruction that describes the task:
### Input:
Return list of `keywords` parsed from HTML ``<meta>`` tags.
Args:
index_page (str): Content of the page as UTF-8 string
Returns:
list: List of :class:`.SourceString` objects.
### Response:
def get_html_keywords(index_page):
... |
async def _handle_response(self, response: aiohttp.client_reqrep.ClientResponse, await_final_result: bool) -> dict:
"""
Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which
means that the API call returns just a job id. The actually expec... | Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which
means that the API call returns just a job id. The actually expected API response is postponed and a specific
asyncJobResults API has to be polled using the job id to get the final result once ... | Below is the the instruction that describes the task:
### Input:
Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which
means that the API call returns just a job id. The actually expected API response is postponed and a specific
asyncJobResult... |
def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None):
"""Updates an existing RRSet in the specified zone.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
... | Updates an existing RRSet in the specified zone.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
... | Below is the the instruction that describes the task:
### Input:
Updates an existing RRSet in the specified zone.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-k... |
def stop(self, signum=None, frame=None):
"""
handel's a termination signal
"""
BackgroundProcess.objects.filter(pk=self.process_id
).update(pid=0, last_update=now(), message='stopping..')
# run the cleanup
self.cleanup()
Ba... | handel's a termination signal | Below is the the instruction that describes the task:
### Input:
handel's a termination signal
### Response:
def stop(self, signum=None, frame=None):
"""
handel's a termination signal
"""
BackgroundProcess.objects.filter(pk=self.process_id
).... |
def relations_dict(rel_lst):
"""constructs a relation's dictionary from a list that describes amphidromus relations between objects
:param list rel_lst: a relationships list of the form [[a,b],[c, a, b]] # can include duplicates
:returns: a dictionary
:Example:
>>> rl = [('a', 'b', 'c'), ('a'... | constructs a relation's dictionary from a list that describes amphidromus relations between objects
:param list rel_lst: a relationships list of the form [[a,b],[c, a, b]] # can include duplicates
:returns: a dictionary
:Example:
>>> rl = [('a', 'b', 'c'), ('a', 'x', 'y'), ('x', 'y', 'z')]
... | Below is the the instruction that describes the task:
### Input:
constructs a relation's dictionary from a list that describes amphidromus relations between objects
:param list rel_lst: a relationships list of the form [[a,b],[c, a, b]] # can include duplicates
:returns: a dictionary
:Example:
... |
def clear(self):
"""
Clears out all the items from this tab bar.
"""
self.blockSignals(True)
items = list(self.items())
for item in items:
item.close()
self.blockSignals(False)
self._currentIndex = -1
self.currentIndexChanged.emit(self... | Clears out all the items from this tab bar. | Below is the the instruction that describes the task:
### Input:
Clears out all the items from this tab bar.
### Response:
def clear(self):
"""
Clears out all the items from this tab bar.
"""
self.blockSignals(True)
items = list(self.items())
for item in items:
... |
def configure_properties(self, tc_config_prop_filenames=None, behave_properties=None):
"""Configure selenium instance properties
:param tc_config_prop_filenames: test case specific properties filenames
:param behave_properties: dict with behave user data properties
"""
prop_file... | Configure selenium instance properties
:param tc_config_prop_filenames: test case specific properties filenames
:param behave_properties: dict with behave user data properties | Below is the the instruction that describes the task:
### Input:
Configure selenium instance properties
:param tc_config_prop_filenames: test case specific properties filenames
:param behave_properties: dict with behave user data properties
### Response:
def configure_properties(self, tc_config_pr... |
def split_strings(subtree: dict) -> List[str]:
"""
Produce the list of strings from the dictionary with concatenated chars \
and lengths. Opposite to :func:`merge_strings()`.
:param subtree: The dict with "strings" and "lengths".
:return: :class:`list` of :class:`str`-s or :class:`bytes`.
"""
... | Produce the list of strings from the dictionary with concatenated chars \
and lengths. Opposite to :func:`merge_strings()`.
:param subtree: The dict with "strings" and "lengths".
:return: :class:`list` of :class:`str`-s or :class:`bytes`. | Below is the the instruction that describes the task:
### Input:
Produce the list of strings from the dictionary with concatenated chars \
and lengths. Opposite to :func:`merge_strings()`.
:param subtree: The dict with "strings" and "lengths".
:return: :class:`list` of :class:`str`-s or :class:`bytes`.... |
def search(cls, term, weights=None, with_score=False, score_alias='score',
explicit_ordering=False):
"""Full-text search using selected `term`."""
return cls._search(
term,
weights,
with_score,
score_alias,
cls.rank,
... | Full-text search using selected `term`. | Below is the the instruction that describes the task:
### Input:
Full-text search using selected `term`.
### Response:
def search(cls, term, weights=None, with_score=False, score_alias='score',
explicit_ordering=False):
"""Full-text search using selected `term`."""
return cls._search... |
def _get_neighbor_conf(neigh_ip_address):
"""Returns neighbor configuration for given neighbor ip address.
Raises exception if no neighbor with `neigh_ip_address` exists.
"""
neigh_conf = \
CORE_MANAGER.neighbors_conf.get_neighbor_conf(neigh_ip_address)
if not neigh_conf:
raise Runt... | Returns neighbor configuration for given neighbor ip address.
Raises exception if no neighbor with `neigh_ip_address` exists. | Below is the the instruction that describes the task:
### Input:
Returns neighbor configuration for given neighbor ip address.
Raises exception if no neighbor with `neigh_ip_address` exists.
### Response:
def _get_neighbor_conf(neigh_ip_address):
"""Returns neighbor configuration for given neighbor ip add... |
def read_tmy3(filename=None, coerce_year=None, recolumn=True):
'''
Read a TMY3 file in to a pandas dataframe.
Note that values contained in the metadata dictionary are unchanged
from the TMY3 file (i.e. units are retained). In the case of any
discrepencies between this documentation and the TMY3 Us... | Read a TMY3 file in to a pandas dataframe.
Note that values contained in the metadata dictionary are unchanged
from the TMY3 file (i.e. units are retained). In the case of any
discrepencies between this documentation and the TMY3 User's Manual
[1], the TMY3 User's Manual takes precedence.
The TMY3... | Below is the the instruction that describes the task:
### Input:
Read a TMY3 file in to a pandas dataframe.
Note that values contained in the metadata dictionary are unchanged
from the TMY3 file (i.e. units are retained). In the case of any
discrepencies between this documentation and the TMY3 User's M... |
def get_metric_fns(metric_names, labels, outputs):
"""Generate a dictionary of metric name to metric function.
Args:
metric_names: list of strings in the format "prefix/metric_function_name".
metric_function_name should refer to a function name in metrics.py. The
prefix will be included in the key ... | Generate a dictionary of metric name to metric function.
Args:
metric_names: list of strings in the format "prefix/metric_function_name".
metric_function_name should refer to a function name in metrics.py. The
prefix will be included in the key in the returned dict.
labels: a tensor where batch i... | Below is the the instruction that describes the task:
### Input:
Generate a dictionary of metric name to metric function.
Args:
metric_names: list of strings in the format "prefix/metric_function_name".
metric_function_name should refer to a function name in metrics.py. The
prefix will be include... |
def parse(schema):
"""
Parse `schema`, either a string or a file-like object, and
return a :class:`MessageRegistry` with the loaded messages.
"""
if not isinstance(schema, basestring):
# assume it is file-like
schema = schema.read()
message = re.compile(r'^\(([^,]+),\s*(\d+)\):\... | Parse `schema`, either a string or a file-like object, and
return a :class:`MessageRegistry` with the loaded messages. | Below is the the instruction that describes the task:
### Input:
Parse `schema`, either a string or a file-like object, and
return a :class:`MessageRegistry` with the loaded messages.
### Response:
def parse(schema):
"""
Parse `schema`, either a string or a file-like object, and
return a :class:`Me... |
def fetch(self, zookeeper_path, settings=None):
"""
Download a partition from another server.
:param zookeeper_path: Path in zookeeper to fetch from
:param settings: Settings for executing request to ClickHouse over db.raw() method
:return: SQL Query
"""
re... | Download a partition from another server.
:param zookeeper_path: Path in zookeeper to fetch from
:param settings: Settings for executing request to ClickHouse over db.raw() method
:return: SQL Query | Below is the the instruction that describes the task:
### Input:
Download a partition from another server.
:param zookeeper_path: Path in zookeeper to fetch from
:param settings: Settings for executing request to ClickHouse over db.raw() method
:return: SQL Query
### Response:
def fetch(... |
def measure(function, xs, ys, popt, weights):
"""
measure the quality of a fit
"""
m = 0
n = 0
for x in xs:
try:
if len(popt) == 2:
m += (ys[n] - function(x, popt[0], popt[1]))**2 * weights[n]
elif len(popt) == 3:
m += (ys[n] - func... | measure the quality of a fit | Below is the the instruction that describes the task:
### Input:
measure the quality of a fit
### Response:
def measure(function, xs, ys, popt, weights):
"""
measure the quality of a fit
"""
m = 0
n = 0
for x in xs:
try:
if len(popt) == 2:
m += (ys[n] - f... |
def get_file(self, attr_name):
'''Return absolute path to logging file for obj's attribute.'''
return os.path.abspath(os.path.join(self.folder, "{}.log"
.format(attr_name))) | Return absolute path to logging file for obj's attribute. | Below is the the instruction that describes the task:
### Input:
Return absolute path to logging file for obj's attribute.
### Response:
def get_file(self, attr_name):
'''Return absolute path to logging file for obj's attribute.'''
return os.path.abspath(os.path.join(self.folder, "{}.log"
... |
def _subspan(self, s, span, nextspan):
"""Recursively subdivide spans based on a series of rules."""
text = s[span[0]:span[1]]
lowertext = text.lower()
# Skip if only a single character or a split sequence
if span[1] - span[0] < 2 or text in self.SPLIT or text in self.SPLIT_END_... | Recursively subdivide spans based on a series of rules. | Below is the the instruction that describes the task:
### Input:
Recursively subdivide spans based on a series of rules.
### Response:
def _subspan(self, s, span, nextspan):
"""Recursively subdivide spans based on a series of rules."""
text = s[span[0]:span[1]]
lowertext = text.lower()
... |
def _bsecurate_cli_component_file_refs(args):
'''Handles the component-file-refs subcommand'''
data = curate.component_file_refs(args.files)
s = ''
for cfile, cdata in data.items():
s += cfile + '\n'
rows = []
for el, refs in cdata:
rows.append((' ' + el, ' '.joi... | Handles the component-file-refs subcommand | Below is the the instruction that describes the task:
### Input:
Handles the component-file-refs subcommand
### Response:
def _bsecurate_cli_component_file_refs(args):
'''Handles the component-file-refs subcommand'''
data = curate.component_file_refs(args.files)
s = ''
for cfile, cdata in data.it... |
def available_backends():
"""Lists the currently available backend types"""
print 'The following LiveSync agents are available:'
for name, backend in current_plugin.backend_classes.iteritems():
print cformat(' - %{white!}{}%{reset}: {} ({})').format(name, backend.title, backend.description) | Lists the currently available backend types | Below is the the instruction that describes the task:
### Input:
Lists the currently available backend types
### Response:
def available_backends():
"""Lists the currently available backend types"""
print 'The following LiveSync agents are available:'
for name, backend in current_plugin.backend_classes... |
def init(plugin_manager, course_factory, client, config):
"""
Init the external grader plugin. This simple grader allows only anonymous requests, and submissions are not stored in database.
Available configuration:
::
plugins:
- plugin_module: inginious.frontend... | Init the external grader plugin. This simple grader allows only anonymous requests, and submissions are not stored in database.
Available configuration:
::
plugins:
- plugin_module: inginious.frontend.plugins.simple_grader
courseid : "external"
... | Below is the the instruction that describes the task:
### Input:
Init the external grader plugin. This simple grader allows only anonymous requests, and submissions are not stored in database.
Available configuration:
::
plugins:
- plugin_module: inginious.frontend.plug... |
def update_product(
self,
product,
location=None,
product_id=None,
update_mask=None,
project_id=None,
retry=None,
timeout=None,
metadata=None,
):
"""
For the documentation see:
:class:`~airflow.contrib.operators.gcp_visi... | For the documentation see:
:class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductUpdateOperator` | Below is the the instruction that describes the task:
### Input:
For the documentation see:
:class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductUpdateOperator`
### Response:
def update_product(
self,
product,
location=None,
product_id=None,
updat... |
def index_of_nearest(p, hot_points, distance_f=distance):
"""Given a point and a set of hot points it found the hot point
nearest to the given point. An arbitrary distance function can
be specified
:return the index of the nearest hot points, or None if the list of hot
points is empty
""... | Given a point and a set of hot points it found the hot point
nearest to the given point. An arbitrary distance function can
be specified
:return the index of the nearest hot points, or None if the list of hot
points is empty | Below is the the instruction that describes the task:
### Input:
Given a point and a set of hot points it found the hot point
nearest to the given point. An arbitrary distance function can
be specified
:return the index of the nearest hot points, or None if the list of hot
points is empty
##... |
def markdown(self, text, mode='', context='', raw=False):
"""Render an arbitrary markdown document.
:param str text: (required), the text of the document to render
:param str mode: (optional), 'markdown' or 'gfm'
:param str context: (optional), only important when using mode 'gfm',
... | Render an arbitrary markdown document.
:param str text: (required), the text of the document to render
:param str mode: (optional), 'markdown' or 'gfm'
:param str context: (optional), only important when using mode 'gfm',
this is the repository to use as the context for the renderin... | Below is the the instruction that describes the task:
### Input:
Render an arbitrary markdown document.
:param str text: (required), the text of the document to render
:param str mode: (optional), 'markdown' or 'gfm'
:param str context: (optional), only important when using mode 'gfm',
... |
def from_dict(data, ctx):
"""
Instantiate a new InstrumentCommission from a dict (generally from
loading a JSON response). The data used to instantiate the
InstrumentCommission is a shallow copy of the dict passed in, with any
complex child types instantiated appropriately.
... | Instantiate a new InstrumentCommission from a dict (generally from
loading a JSON response). The data used to instantiate the
InstrumentCommission is a shallow copy of the dict passed in, with any
complex child types instantiated appropriately. | Below is the the instruction that describes the task:
### Input:
Instantiate a new InstrumentCommission from a dict (generally from
loading a JSON response). The data used to instantiate the
InstrumentCommission is a shallow copy of the dict passed in, with any
complex child types instantiat... |
def validate_types(self, definition):
"""This function performs some basic sanity checks on the scalar definition:
- Checks that all the required fields are available.
- Checks that all the fields have the expected types.
:param definition: the dictionary containing the scalar p... | This function performs some basic sanity checks on the scalar definition:
- Checks that all the required fields are available.
- Checks that all the fields have the expected types.
:param definition: the dictionary containing the scalar properties.
:raises ParserError: if a scal... | Below is the the instruction that describes the task:
### Input:
This function performs some basic sanity checks on the scalar definition:
- Checks that all the required fields are available.
- Checks that all the fields have the expected types.
:param definition: the dictionary con... |
def find_imports(self, pbds):
"""Find all missing imports in list of Pbd instances.
"""
# List of types used, but not defined
imports = list(set(self.uses).difference(set(self.defines)))
# Clumpsy, but enought for now
for imp in imports:
for p in pbd... | Find all missing imports in list of Pbd instances. | Below is the the instruction that describes the task:
### Input:
Find all missing imports in list of Pbd instances.
### Response:
def find_imports(self, pbds):
"""Find all missing imports in list of Pbd instances.
"""
# List of types used, but not defined
imports = list(set(self.use... |
def load_entrypoint_plugins(entry_points, airflow_plugins):
"""
Load AirflowPlugin subclasses from the entrypoints
provided. The entry_point group should be 'airflow.plugins'.
:param entry_points: A collection of entrypoints to search for plugins
:type entry_points: Generator[setuptools.EntryPoint,... | Load AirflowPlugin subclasses from the entrypoints
provided. The entry_point group should be 'airflow.plugins'.
:param entry_points: A collection of entrypoints to search for plugins
:type entry_points: Generator[setuptools.EntryPoint, None, None]
:param airflow_plugins: A collection of existing airflo... | Below is the the instruction that describes the task:
### Input:
Load AirflowPlugin subclasses from the entrypoints
provided. The entry_point group should be 'airflow.plugins'.
:param entry_points: A collection of entrypoints to search for plugins
:type entry_points: Generator[setuptools.EntryPoint, No... |
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_nbr_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_fabric_trunk_info = ET.Element("show_fabric_trunk_info")
config = show_fabric_trunk_i... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_member_trunk_list_nbr_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
... |
def get_pickled_sizes(obj):
"""
Return the pickled sizes of an object and its direct attributes,
ordered by decreasing size. Here is an example:
>> total_size, partial_sizes = get_pickled_sizes(Monitor(''))
>> total_size
345
>> partial_sizes
[('_procs', 214), ('exc', 4), ('mem', 4), ('s... | Return the pickled sizes of an object and its direct attributes,
ordered by decreasing size. Here is an example:
>> total_size, partial_sizes = get_pickled_sizes(Monitor(''))
>> total_size
345
>> partial_sizes
[('_procs', 214), ('exc', 4), ('mem', 4), ('start_time', 4),
('_start_time', 4), ... | Below is the the instruction that describes the task:
### Input:
Return the pickled sizes of an object and its direct attributes,
ordered by decreasing size. Here is an example:
>> total_size, partial_sizes = get_pickled_sizes(Monitor(''))
>> total_size
345
>> partial_sizes
[('_procs', 214)... |
def attributes(self):
"""
Get or set this element's attributes as name/value pairs.
.. note::
Setting element attributes via this accessor will **remove**
any existing attributes, as opposed to the :meth:`set_attributes`
method which only updates and replaces... | Get or set this element's attributes as name/value pairs.
.. note::
Setting element attributes via this accessor will **remove**
any existing attributes, as opposed to the :meth:`set_attributes`
method which only updates and replaces them. | Below is the the instruction that describes the task:
### Input:
Get or set this element's attributes as name/value pairs.
.. note::
Setting element attributes via this accessor will **remove**
any existing attributes, as opposed to the :meth:`set_attributes`
method whic... |
def _from_binary_acl(cls, binary_stream):
"""See base class."""
''' Revision number - 1
Padding - 1
Size - 2
ACE Count - 2
Padding - 2
'''
rev_number, size, ace_len = cls._REPR.unpack(binary_stream[:cls._REPR.size])
#content = cls._REPR.unpack(binary_stream[:cls._REPR... | See base class. | Below is the the instruction that describes the task:
### Input:
See base class.
### Response:
def _from_binary_acl(cls, binary_stream):
"""See base class."""
''' Revision number - 1
Padding - 1
Size - 2
ACE Count - 2
Padding - 2
'''
rev_number, size, ace_len = cls._... |
def handleUpgradeTxn(self, txn) -> None:
"""
Handles transaction of type POOL_UPGRADE
Can schedule or cancel upgrade to a newer
version at specified time
:param txn:
"""
FINALIZING_EVENT_TYPES = [UpgradeLog.Events.succeeded, UpgradeLog.Events.failed]
if ... | Handles transaction of type POOL_UPGRADE
Can schedule or cancel upgrade to a newer
version at specified time
:param txn: | Below is the the instruction that describes the task:
### Input:
Handles transaction of type POOL_UPGRADE
Can schedule or cancel upgrade to a newer
version at specified time
:param txn:
### Response:
def handleUpgradeTxn(self, txn) -> None:
"""
Handles transaction of type P... |
def generate(env):
"""Add Builders and construction variables for lib to an Environment."""
SCons.Tool.createStaticLibBuilder(env)
SCons.Tool.createSharedLibBuilder(env)
SCons.Tool.createProgBuilder(env)
env['AR'] = 'mwld'
env['ARCOM'] = '$AR $ARFLAGS -library -o $TARGET $SOURCES'
env['LIB... | Add Builders and construction variables for lib to an Environment. | Below is the the instruction that describes the task:
### Input:
Add Builders and construction variables for lib to an Environment.
### Response:
def generate(env):
"""Add Builders and construction variables for lib to an Environment."""
SCons.Tool.createStaticLibBuilder(env)
SCons.Tool.createSharedLib... |
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container ... | .. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds i... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
... |
def contains_vasp_input(dir_name):
"""
Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR).
"""
for f in ["INCAR", "POSCAR... | Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR). | Below is the the instruction that describes the task:
### Input:
Checks if a directory contains valid VASP input.
Args:
dir_name:
Directory name to check.
Returns:
True if directory contains all four VASP input files (INCAR, POSCAR,
KPOINTS and POTCAR).
### Response:
d... |
def update(self, deltat=1.0):
'''fly a square circuit'''
DNFZ.update(self, deltat)
self.dist_flown += self.speed * deltat
if self.dist_flown > self.circuit_width:
self.desired_heading = self.heading + 90
self.dist_flown = 0
if self.getalt() < self.ground_h... | fly a square circuit | Below is the the instruction that describes the task:
### Input:
fly a square circuit
### Response:
def update(self, deltat=1.0):
'''fly a square circuit'''
DNFZ.update(self, deltat)
self.dist_flown += self.speed * deltat
if self.dist_flown > self.circuit_width:
self.des... |
def set_initial(self, C_in, scale_in, scale_high):
r"""Set the initial values for parameters and Wilson coefficients at
the scale `scale_in`, setting the new physics scale $\Lambda$ to
`scale_high`."""
self.C_in = C_in
self.scale_in = scale_in
self.scale_high = scale_high | r"""Set the initial values for parameters and Wilson coefficients at
the scale `scale_in`, setting the new physics scale $\Lambda$ to
`scale_high`. | Below is the the instruction that describes the task:
### Input:
r"""Set the initial values for parameters and Wilson coefficients at
the scale `scale_in`, setting the new physics scale $\Lambda$ to
`scale_high`.
### Response:
def set_initial(self, C_in, scale_in, scale_high):
r"""Set the i... |
def _parse_plan(self, match):
"""Parse a matching plan line."""
expected_tests = int(match.group("expected"))
directive = Directive(match.group("directive"))
# Only SKIP directives are allowed in the plan.
if directive.text and not directive.skip:
return Unknown()
... | Parse a matching plan line. | Below is the the instruction that describes the task:
### Input:
Parse a matching plan line.
### Response:
def _parse_plan(self, match):
"""Parse a matching plan line."""
expected_tests = int(match.group("expected"))
directive = Directive(match.group("directive"))
# Only SKIP direc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.