code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def update(self, aspect_ratio=None, fov=None, near=None, far=None):
"""
Update the internal projection matrix based on current values
or values passed in if specified.
:param aspect_ratio: New aspect ratio
:param fov: New field of view
:param near: New near value
... | Update the internal projection matrix based on current values
or values passed in if specified.
:param aspect_ratio: New aspect ratio
:param fov: New field of view
:param near: New near value
:param far: New far value | Below is the the instruction that describes the task:
### Input:
Update the internal projection matrix based on current values
or values passed in if specified.
:param aspect_ratio: New aspect ratio
:param fov: New field of view
:param near: New near value
:param far: New fa... |
def parse(duration_seconds, resolution_seconds=Resolution.MAX_RESOLUTION, limit=None):
"""
num_datapoints = min(duration/resolution, limit)
:param duration_seconds: Time duration (in seconds) for which datapoints should be returned
:param resolution_seconds: Time interval (in seconds) b... | num_datapoints = min(duration/resolution, limit)
:param duration_seconds: Time duration (in seconds) for which datapoints should be returned
:param resolution_seconds: Time interval (in seconds) between data points
:param limit: Maximum number of datapoints to return | Below is the the instruction that describes the task:
### Input:
num_datapoints = min(duration/resolution, limit)
:param duration_seconds: Time duration (in seconds) for which datapoints should be returned
:param resolution_seconds: Time interval (in seconds) between data points
:param limi... |
def open(self, host, port=23):
"""Opens a telnet connection to the desired AttenuatorDevice and
queries basic information.
Args:
host: A valid hostname (IP address or DNS-resolvable name) to an
MC-DAT attenuator instrument.
port: An optional port number (... | Opens a telnet connection to the desired AttenuatorDevice and
queries basic information.
Args:
host: A valid hostname (IP address or DNS-resolvable name) to an
MC-DAT attenuator instrument.
port: An optional port number (defaults to telnet default 23) | Below is the the instruction that describes the task:
### Input:
Opens a telnet connection to the desired AttenuatorDevice and
queries basic information.
Args:
host: A valid hostname (IP address or DNS-resolvable name) to an
MC-DAT attenuator instrument.
port... |
def _binning(values, limits=(0,0), bin_num=10):
'''
Bins data that falls between certain limits, if the limits are (0, 0) the
minimum and maximum values are used.
Returns a list of tuples where the first element of the tuple is the center of the bin
and the second element of the tuple are the count... | Bins data that falls between certain limits, if the limits are (0, 0) the
minimum and maximum values are used.
Returns a list of tuples where the first element of the tuple is the center of the bin
and the second element of the tuple are the counts. | Below is the the instruction that describes the task:
### Input:
Bins data that falls between certain limits, if the limits are (0, 0) the
minimum and maximum values are used.
Returns a list of tuples where the first element of the tuple is the center of the bin
and the second element of the tuple are ... |
def _patch_hover(self, element, data):
"""
Replace edge start and end hover data with label_index data.
"""
if not (self.inspection_policy == 'edges' and 'hover' in self.handles):
return
lidx = element.nodes.get_dimension(self.label_index)
src, tgt = [dimensio... | Replace edge start and end hover data with label_index data. | Below is the the instruction that describes the task:
### Input:
Replace edge start and end hover data with label_index data.
### Response:
def _patch_hover(self, element, data):
"""
Replace edge start and end hover data with label_index data.
"""
if not (self.inspection_policy == '... |
def parse_gpr(str_expr):
"""parse gpr into AST
Parameters
----------
str_expr : string
string with the gene reaction rule to parse
Returns
-------
tuple
elements ast_tree and gene_ids as a set
"""
str_expr = str_expr.strip()
if len(str_expr) == 0:
return... | parse gpr into AST
Parameters
----------
str_expr : string
string with the gene reaction rule to parse
Returns
-------
tuple
elements ast_tree and gene_ids as a set | Below is the the instruction that describes the task:
### Input:
parse gpr into AST
Parameters
----------
str_expr : string
string with the gene reaction rule to parse
Returns
-------
tuple
elements ast_tree and gene_ids as a set
### Response:
def parse_gpr(str_expr):
... |
def resource_list(cls):
""" Get the possible list of resources (name, id). """
items = cls.list()
ret = [vlan['name'] for vlan in items]
ret.extend([str(vlan['id']) for vlan in items])
return ret | Get the possible list of resources (name, id). | Below is the the instruction that describes the task:
### Input:
Get the possible list of resources (name, id).
### Response:
def resource_list(cls):
""" Get the possible list of resources (name, id). """
items = cls.list()
ret = [vlan['name'] for vlan in items]
ret.extend([str(vlan... |
def selectAll(self):
"""
Selects the text within all the editors.
"""
self.blockEditorHandling(True)
for editor in self.editors():
editor.selectAll()
self.blockEditorHandling(False) | Selects the text within all the editors. | Below is the the instruction that describes the task:
### Input:
Selects the text within all the editors.
### Response:
def selectAll(self):
"""
Selects the text within all the editors.
"""
self.blockEditorHandling(True)
for editor in self.editors():
editor... |
def list_experiment(args):
'''Get experiment information'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('restServerPid')
if not detect_process(rest_pid):
print_error('Experiment is not running...')
... | Get experiment information | Below is the the instruction that describes the task:
### Input:
Get experiment information
### Response:
def list_experiment(args):
'''Get experiment information'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
rest_pid = nni_config.get_config('... |
def multihead_attention(query_antecedent,
memory_antecedent,
bias,
total_key_depth,
total_value_depth,
output_depth,
num_heads,
dropout_rate,
... | Multihead scaled-dot-product attention with input/output transformations.
Args:
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: a Tensor with shape [batch, length_m, channels] or None
bias: bias Tensor (see attention_bias())
total_key_depth: an integer
total_v... | Below is the the instruction that describes the task:
### Input:
Multihead scaled-dot-product attention with input/output transformations.
Args:
query_antecedent: a Tensor with shape [batch, length_q, channels]
memory_antecedent: a Tensor with shape [batch, length_m, channels] or None
bias: bias Tens... |
def get_command_handlers():
'''
Create a map of command names and handlers
'''
return {
'activate': activate,
'config': hconfig,
'deactivate': deactivate,
'help': cli_help,
'kill': kill,
'restart': restart,
'submit': submit,
'update': update,
'version': vers... | Create a map of command names and handlers | Below is the the instruction that describes the task:
### Input:
Create a map of command names and handlers
### Response:
def get_command_handlers():
'''
Create a map of command names and handlers
'''
return {
'activate': activate,
'config': hconfig,
'deactivate': deactivate,
'help'... |
def configure():
"""
Update config
"""
jira_url = utils.get_input(raw_input, "Jira url")
username = utils.get_input(raw_input, "username")
password = utils.get_input(getpass.getpass, "password")
error_reporting = True \
if 'n' not in raw_input("Would you like to automatically report ... | Update config | Below is the the instruction that describes the task:
### Input:
Update config
### Response:
def configure():
"""
Update config
"""
jira_url = utils.get_input(raw_input, "Jira url")
username = utils.get_input(raw_input, "username")
password = utils.get_input(getpass.getpass, "password")
... |
def subscribe(self, request, *args, **kwargs):
""" Performs the subscribe action. """
self.object = self.get_object()
self.object.subscribers.add(request.user)
messages.success(self.request, self.success_message)
return HttpResponseRedirect(self.get_success_url()) | Performs the subscribe action. | Below is the the instruction that describes the task:
### Input:
Performs the subscribe action.
### Response:
def subscribe(self, request, *args, **kwargs):
""" Performs the subscribe action. """
self.object = self.get_object()
self.object.subscribers.add(request.user)
messages.succ... |
def _compute_average_correct(input_, labels, per_example_weights, topk=1):
"""Returns the numerator and denominator of classifier accuracy."""
return _compute_sparse_average_correct(
input_,
tf.reshape(tf.argmax(labels, 1), [-1, 1]), per_example_weights, topk=topk) | Returns the numerator and denominator of classifier accuracy. | Below is the the instruction that describes the task:
### Input:
Returns the numerator and denominator of classifier accuracy.
### Response:
def _compute_average_correct(input_, labels, per_example_weights, topk=1):
"""Returns the numerator and denominator of classifier accuracy."""
return _compute_sparse_aver... |
def _GetRunFlowFlags(args=None):
"""Retrieves command line flags based on gflags module."""
# There's one rare situation where gsutil will not have argparse
# available, but doesn't need anything depending on argparse anyway,
# since they're bringing their own credentials. So we just allow this
# to... | Retrieves command line flags based on gflags module. | Below is the the instruction that describes the task:
### Input:
Retrieves command line flags based on gflags module.
### Response:
def _GetRunFlowFlags(args=None):
"""Retrieves command line flags based on gflags module."""
# There's one rare situation where gsutil will not have argparse
# available, b... |
def resize_image(image, tuple_wh, preserve_aspect=True):
"""Resizes an instance of a PIL Image.
In order to prevent un-intended side effects,
this function always returns a copy of the image,
as the resize function from PIL returns a copy
but the thumbnail function does not.
Args:
ima... | Resizes an instance of a PIL Image.
In order to prevent un-intended side effects,
this function always returns a copy of the image,
as the resize function from PIL returns a copy
but the thumbnail function does not.
Args:
image: An instance of a PIL Image.
tuple_wh: A tuple contai... | Below is the the instruction that describes the task:
### Input:
Resizes an instance of a PIL Image.
In order to prevent un-intended side effects,
this function always returns a copy of the image,
as the resize function from PIL returns a copy
but the thumbnail function does not.
Args:
... |
def slicenet_params1():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 1024
hparams.hidden_size = 768
hparams.dropout = 0.5
hparams.symbol_dropout = 0.2
hparams.label_smoothing = 0.1
hparams.clip_grad_norm = 2.0
hparams.num_hidden_layers = 4
hparams.kerne... | Set of hyperparameters. | Below is the the instruction that describes the task:
### Input:
Set of hyperparameters.
### Response:
def slicenet_params1():
"""Set of hyperparameters."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 1024
hparams.hidden_size = 768
hparams.dropout = 0.5
hparams.symbol_dropout = 0.2
... |
def translation_save_translated_fields(instance, **kwargs):
"""
Save all the translations of instance in post_save signal handler.
"""
if not hasattr(instance, '_translation_cache'):
return
for l_id, translation in instance._translation_cache.iteritems():
# set the translation ID jus... | Save all the translations of instance in post_save signal handler. | Below is the the instruction that describes the task:
### Input:
Save all the translations of instance in post_save signal handler.
### Response:
def translation_save_translated_fields(instance, **kwargs):
"""
Save all the translations of instance in post_save signal handler.
"""
if not hasattr(ins... |
def unversioned(cls, coord):
"""The coordinate without the version.
:param M2Coordinate coord: an M2Coordinate or JarDependency.
:return: the coordinate without the version.
:rtype: M2Coordinate
"""
coord = cls.create(coord)
if coord.rev is None:
return coord
return M2Coordinate(o... | The coordinate without the version.
:param M2Coordinate coord: an M2Coordinate or JarDependency.
:return: the coordinate without the version.
:rtype: M2Coordinate | Below is the the instruction that describes the task:
### Input:
The coordinate without the version.
:param M2Coordinate coord: an M2Coordinate or JarDependency.
:return: the coordinate without the version.
:rtype: M2Coordinate
### Response:
def unversioned(cls, coord):
"""The coordinate without t... |
def _GetElementDataTypeDefinition(self, data_type_definition):
"""Retrieves the element data type definition.
Args:
data_type_definition (DataTypeDefinition): data type definition.
Returns:
DataTypeDefinition: element data type definition.
Raises:
FormatError: if the element data ty... | Retrieves the element data type definition.
Args:
data_type_definition (DataTypeDefinition): data type definition.
Returns:
DataTypeDefinition: element data type definition.
Raises:
FormatError: if the element data type cannot be determined from the data
type definition. | Below is the the instruction that describes the task:
### Input:
Retrieves the element data type definition.
Args:
data_type_definition (DataTypeDefinition): data type definition.
Returns:
DataTypeDefinition: element data type definition.
Raises:
FormatError: if the element data typ... |
def get_multi_match_mapping(self) -> Dict[Type, List[Type]]:
"""
Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches.
"""
if self._multi_match_mapping is None:
self._multi_match_mapping = {}
basic_types = sel... | Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches. | Below is the the instruction that describes the task:
### Input:
Returns a mapping from each `MultiMatchNamedBasicType` to all the `NamedBasicTypes` that it
matches.
### Response:
def get_multi_match_mapping(self) -> Dict[Type, List[Type]]:
"""
Returns a mapping from each `MultiMatchNamedBa... |
def link_cloud(self, username=None, password=None, device_id=None):
"""Create and store a token for interacting with the IOTile Cloud API.
You will need to call link_cloud once for each virtualenv that
you create and want to use with any api calls that touch iotile cloud.
Note that this method is call... | Create and store a token for interacting with the IOTile Cloud API.
You will need to call link_cloud once for each virtualenv that
you create and want to use with any api calls that touch iotile cloud.
Note that this method is called on a ConfigManager instance
If you do not pass your username or pas... | Below is the the instruction that describes the task:
### Input:
Create and store a token for interacting with the IOTile Cloud API.
You will need to call link_cloud once for each virtualenv that
you create and want to use with any api calls that touch iotile cloud.
Note that this method is called on ... |
def p_operation_invocation_1(self, p):
'''instance_invocation : structure DOT identifier LPAREN parameter_list RPAREN'''
p[0] = InstanceInvocationNode(handle=p[1],
action_name=p[3],
parameter_list=p[5]) | instance_invocation : structure DOT identifier LPAREN parameter_list RPAREN | Below is the the instruction that describes the task:
### Input:
instance_invocation : structure DOT identifier LPAREN parameter_list RPAREN
### Response:
def p_operation_invocation_1(self, p):
'''instance_invocation : structure DOT identifier LPAREN parameter_list RPAREN'''
p[0] = InstanceInvocati... |
def collection(self, path):
"""To return all items generated by get collection."""
data = []
for item in self.get_collection(path):
data.append(item)
return data | To return all items generated by get collection. | Below is the the instruction that describes the task:
### Input:
To return all items generated by get collection.
### Response:
def collection(self, path):
"""To return all items generated by get collection."""
data = []
for item in self.get_collection(path):
data.append(item)
... |
def populate_connections(self, metamodel):
'''
Populate links in a *metamodel* with connections between them.
'''
storage = dict()
for ass in metamodel.associations:
source_class = ass.source_link.to_metaclass
target_class = ass.target_link.to_metaclass
... | Populate links in a *metamodel* with connections between them. | Below is the the instruction that describes the task:
### Input:
Populate links in a *metamodel* with connections between them.
### Response:
def populate_connections(self, metamodel):
'''
Populate links in a *metamodel* with connections between them.
'''
storage = dict()
fo... |
def _set_show_mpls_policy(self, v, load=False):
"""
Setter method for show_mpls_policy, mapped from YANG variable /brocade_mpls_rpc/show_mpls_policy (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_policy is considered as a private
method. Backends loo... | Setter method for show_mpls_policy, mapped from YANG variable /brocade_mpls_rpc/show_mpls_policy (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_policy is considered as a private
method. Backends looking to populate this variable should
do so via calling ... | Below is the the instruction that describes the task:
### Input:
Setter method for show_mpls_policy, mapped from YANG variable /brocade_mpls_rpc/show_mpls_policy (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_policy is considered as a private
method. Bac... |
def base_url(self):
"""A base_url that will be used to construct the final
URL we're going to query against.
:returns: A URL of the form: ``proto://host:port``.
:rtype: :obj:`string`
"""
return '{proto}://{host}:{port}{url_path}'.format(
proto=self.protocol,
... | A base_url that will be used to construct the final
URL we're going to query against.
:returns: A URL of the form: ``proto://host:port``.
:rtype: :obj:`string` | Below is the the instruction that describes the task:
### Input:
A base_url that will be used to construct the final
URL we're going to query against.
:returns: A URL of the form: ``proto://host:port``.
:rtype: :obj:`string`
### Response:
def base_url(self):
"""A base_url that will... |
def write_conll(self, fname):
"""
Serializes the dataset in CONLL format to fname
"""
if 'label' not in self.fields:
raise InvalidFieldsException("dataset is not in CONLL format: missing label field")
def instance_to_conll(inst):
tab = [v for k, v in inst... | Serializes the dataset in CONLL format to fname | Below is the the instruction that describes the task:
### Input:
Serializes the dataset in CONLL format to fname
### Response:
def write_conll(self, fname):
"""
Serializes the dataset in CONLL format to fname
"""
if 'label' not in self.fields:
raise InvalidFieldsExceptio... |
def get_breadcrumbs(self):
"""
Breadcrumb format: (('name', 'url'), ...) or None if not used.
"""
if not self.breadcrumbs:
return None
else:
allowed_breadcrumbs = []
for breadcrumb in self.breadcrumbs:
# check permission based ... | Breadcrumb format: (('name', 'url'), ...) or None if not used. | Below is the the instruction that describes the task:
### Input:
Breadcrumb format: (('name', 'url'), ...) or None if not used.
### Response:
def get_breadcrumbs(self):
"""
Breadcrumb format: (('name', 'url'), ...) or None if not used.
"""
if not self.breadcrumbs:
return... |
def multithreader(args, paths):
"""Execute multiple processes at once."""
def shellprocess(path):
"""Return a ready-to-use subprocess."""
import subprocess
return subprocess.Popen(args + [path],
stderr=subprocess.DEVNULL,
s... | Execute multiple processes at once. | Below is the the instruction that describes the task:
### Input:
Execute multiple processes at once.
### Response:
def multithreader(args, paths):
"""Execute multiple processes at once."""
def shellprocess(path):
"""Return a ready-to-use subprocess."""
import subprocess
return subp... |
def bind_arguments(func, args, kwargs):
"""Bind the arguments provided into a dict. When passed a function,
a tuple of arguments and a dict of keyword arguments `bind_arguments`
returns a dict of names as the function would see it. This can be useful
to implement a cache decorator that uses the functi... | Bind the arguments provided into a dict. When passed a function,
a tuple of arguments and a dict of keyword arguments `bind_arguments`
returns a dict of names as the function would see it. This can be useful
to implement a cache decorator that uses the function arguments to build
the cache key based o... | Below is the the instruction that describes the task:
### Input:
Bind the arguments provided into a dict. When passed a function,
a tuple of arguments and a dict of keyword arguments `bind_arguments`
returns a dict of names as the function would see it. This can be useful
to implement a cache decorato... |
def get_tags(self, tagtype):
''' Get all tags of a type '''
return [t for t in self.__tags if t.tagtype == tagtype] | Get all tags of a type | Below is the the instruction that describes the task:
### Input:
Get all tags of a type
### Response:
def get_tags(self, tagtype):
''' Get all tags of a type '''
return [t for t in self.__tags if t.tagtype == tagtype] |
def add_arguments(self, parser):
"""Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add... | Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None`` | Below is the the instruction that describes the task:
### Input:
Adds the arguments for the emulator command.
Args:
self (EmulatorCommand): the ``EmulatorCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
### Response:... |
def _get_current_minute(self):
"""
Internal utility method to get the current simulation time.
Possible answers are:
- whatever the algorithm's get_datetime() method returns (this is what
`self.simulation_dt_func()` points to)
- sometimes we're knowingly not in a mar... | Internal utility method to get the current simulation time.
Possible answers are:
- whatever the algorithm's get_datetime() method returns (this is what
`self.simulation_dt_func()` points to)
- sometimes we're knowingly not in a market minute, like if we're in
before_tra... | Below is the the instruction that describes the task:
### Input:
Internal utility method to get the current simulation time.
Possible answers are:
- whatever the algorithm's get_datetime() method returns (this is what
`self.simulation_dt_func()` points to)
- sometimes we're know... |
def read_stems(
filename,
out_type=np.float_,
stem_id=None,
start=0,
duration=None,
info=None
):
"""Read STEMS format into numpy Tensor
Parameters
----------
filename : str
Filename of STEMS format. Typically `filename.stem.mp4`.
out_type : type
Output type. ... | Read STEMS format into numpy Tensor
Parameters
----------
filename : str
Filename of STEMS format. Typically `filename.stem.mp4`.
out_type : type
Output type. Defaults to 32bit float aka `np.float32`.
stem_id : int
Stem ID (Stream ID) to read. Defaults to `None`, which reads... | Below is the the instruction that describes the task:
### Input:
Read STEMS format into numpy Tensor
Parameters
----------
filename : str
Filename of STEMS format. Typically `filename.stem.mp4`.
out_type : type
Output type. Defaults to 32bit float aka `np.float32`.
stem_id : int... |
def run_terraform_init(tf_bin, # pylint: disable=too-many-arguments
module_path, backend_options, env_name, env_region,
env_vars):
"""Run Terraform init."""
init_cmd = [tf_bin, 'init']
cmd_opts = {'env_vars': env_vars, 'exit_on_error': False}
if backend_op... | Run Terraform init. | Below is the the instruction that describes the task:
### Input:
Run Terraform init.
### Response:
def run_terraform_init(tf_bin, # pylint: disable=too-many-arguments
module_path, backend_options, env_name, env_region,
env_vars):
"""Run Terraform init."""
init... |
def refresh_signal_handler(self, signo, frame):
"""
This callback is called when SIGUSR1 signal is received.
It updates outputs of all modules by calling their `run` method.
Interval modules are updated in separate threads if their interval is
above a certain treshold value.
... | This callback is called when SIGUSR1 signal is received.
It updates outputs of all modules by calling their `run` method.
Interval modules are updated in separate threads if their interval is
above a certain treshold value.
This treshold is computed by :func:`compute_treshold_interval`... | Below is the the instruction that describes the task:
### Input:
This callback is called when SIGUSR1 signal is received.
It updates outputs of all modules by calling their `run` method.
Interval modules are updated in separate threads if their interval is
above a certain treshold value.
... |
def forward(self, x):
"""Feed-forward the model."""
return self.layers(x * (self._filter *
self.fs_filter).expand_as(x)) | Feed-forward the model. | Below is the the instruction that describes the task:
### Input:
Feed-forward the model.
### Response:
def forward(self, x):
"""Feed-forward the model."""
return self.layers(x * (self._filter *
self.fs_filter).expand_as(x)) |
def optimization_updates(self, params, gradients):
"""
Return updates from optimization.
"""
updates, free_parameters = optimize_updates(params, gradients, self.config)
self.network.free_parameters.extend(free_parameters)
logging.info("Added %d free parameters for optimiz... | Return updates from optimization. | Below is the the instruction that describes the task:
### Input:
Return updates from optimization.
### Response:
def optimization_updates(self, params, gradients):
"""
Return updates from optimization.
"""
updates, free_parameters = optimize_updates(params, gradients, self.config)
... |
def app_update_state(app_id,state):
"""
update app state
"""
try:
create_at = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
conn = get_conn()
c = conn.cursor()
c.execute("UPDATE app SET state='{0}',change_at='{1}' WHERE id='{2}'".format(state, create_at, app_id))
... | update app state | Below is the the instruction that describes the task:
### Input:
update app state
### Response:
def app_update_state(app_id,state):
"""
update app state
"""
try:
create_at = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
conn = get_conn()
c = conn.cursor()
c.e... |
def check(source):
"""Check code."""
compile(source, '<string>', 'exec', dont_inherit=True)
reporter = pyflakes.reporter.Reporter(sys.stderr, sys.stderr)
pyflakes.api.check(source, filename='<string>', reporter=reporter) | Check code. | Below is the the instruction that describes the task:
### Input:
Check code.
### Response:
def check(source):
"""Check code."""
compile(source, '<string>', 'exec', dont_inherit=True)
reporter = pyflakes.reporter.Reporter(sys.stderr, sys.stderr)
pyflakes.api.check(source, filename='<string>', report... |
def ScanForVolumeSystem(self, source_path_spec):
"""Scans the path specification for a supported volume system format.
Args:
source_path_spec (PathSpec): source path specification.
Returns:
PathSpec: volume system path specification or None if no supported volume
system type was foun... | Scans the path specification for a supported volume system format.
Args:
source_path_spec (PathSpec): source path specification.
Returns:
PathSpec: volume system path specification or None if no supported volume
system type was found.
Raises:
BackEndError: if the source cannot... | Below is the the instruction that describes the task:
### Input:
Scans the path specification for a supported volume system format.
Args:
source_path_spec (PathSpec): source path specification.
Returns:
PathSpec: volume system path specification or None if no supported volume
system ... |
def _process_sasl_success(self, stream, element):
"""Process incoming <sasl:success/> element.
[initiating entity only]
"""
if not self.authenticator:
logger.debug("Unexpected SASL response")
return False
content = element.text
if content:
... | Process incoming <sasl:success/> element.
[initiating entity only] | Below is the the instruction that describes the task:
### Input:
Process incoming <sasl:success/> element.
[initiating entity only]
### Response:
def _process_sasl_success(self, stream, element):
"""Process incoming <sasl:success/> element.
[initiating entity only]
"""
if... |
def process_args():
"""
Parse command-line arguments.
"""
parser = argparse.ArgumentParser(description="A file for overlaying POVRay files generated from NeuroML by NeuroML1ToPOVRay.py with cell activity (e.g. as generated from a neuroConstruct simulation)")
parser.add_argument('prefix',
... | Parse command-line arguments. | Below is the the instruction that describes the task:
### Input:
Parse command-line arguments.
### Response:
def process_args():
"""
Parse command-line arguments.
"""
parser = argparse.ArgumentParser(description="A file for overlaying POVRay files generated from NeuroML by NeuroML1ToPOVRay.py with... |
def get_group(self, group_id):
"""
Get a single group
"""
url = self.TEAM_GROUPS_ID_URL % group_id
connection = Connection(self.token)
connection.set_url(self.production, url)
return connection.get_request() | Get a single group | Below is the the instruction that describes the task:
### Input:
Get a single group
### Response:
def get_group(self, group_id):
"""
Get a single group
"""
url = self.TEAM_GROUPS_ID_URL % group_id
connection = Connection(self.token)
connection.set_url(self.productio... |
def check_token(self, renew=True):
"""
Checks the exp attribute of the access_token and either refreshes
the tokens by calling the renew_access_tokens method or does nothing
:param renew: bool indicating whether to refresh on expiration
:return: bool indicating whether access_tok... | Checks the exp attribute of the access_token and either refreshes
the tokens by calling the renew_access_tokens method or does nothing
:param renew: bool indicating whether to refresh on expiration
:return: bool indicating whether access_token has expired | Below is the the instruction that describes the task:
### Input:
Checks the exp attribute of the access_token and either refreshes
the tokens by calling the renew_access_tokens method or does nothing
:param renew: bool indicating whether to refresh on expiration
:return: bool indicating whet... |
def close(self):
''' Close the network connection and perform any other required cleanup
Note:
Auto closed when using goose as a context manager or when garbage collected '''
if self.fetcher is not None:
self.shutdown_network()
self.finalizer.atexit = Fal... | Close the network connection and perform any other required cleanup
Note:
Auto closed when using goose as a context manager or when garbage collected | Below is the the instruction that describes the task:
### Input:
Close the network connection and perform any other required cleanup
Note:
Auto closed when using goose as a context manager or when garbage collected
### Response:
def close(self):
''' Close the network connection... |
def send_message(self, message):
''' Send a Bokeh Server protocol message to the connected client.
Args:
message (Message) : a message to send
'''
try:
if _message_test_port is not None:
_message_test_port.sent.append(message)
yield m... | Send a Bokeh Server protocol message to the connected client.
Args:
message (Message) : a message to send | Below is the the instruction that describes the task:
### Input:
Send a Bokeh Server protocol message to the connected client.
Args:
message (Message) : a message to send
### Response:
def send_message(self, message):
''' Send a Bokeh Server protocol message to the connected client.
... |
def nvmlDeviceGetBoardId(handle):
r"""
/**
* Retrieves the device boardId from 0-N.
* Devices with the same boardId indicate GPUs connected to the same PLX. Use in conjunction with
* \ref nvmlDeviceGetMultiGpuBoard() to decide if they are on the same board as well.
* The boardId returned ... | r"""
/**
* Retrieves the device boardId from 0-N.
* Devices with the same boardId indicate GPUs connected to the same PLX. Use in conjunction with
* \ref nvmlDeviceGetMultiGpuBoard() to decide if they are on the same board as well.
* The boardId returned is a unique ID for the current configu... | Below is the the instruction that describes the task:
### Input:
r"""
/**
* Retrieves the device boardId from 0-N.
* Devices with the same boardId indicate GPUs connected to the same PLX. Use in conjunction with
* \ref nvmlDeviceGetMultiGpuBoard() to decide if they are on the same board as well... |
def try_fields(cls, *names) -> t.Optional[t.Any]:
"""Return first existing of given class field names."""
for name in names:
if hasattr(cls, name):
return getattr(cls, name)
raise AttributeError((cls, names)) | Return first existing of given class field names. | Below is the the instruction that describes the task:
### Input:
Return first existing of given class field names.
### Response:
def try_fields(cls, *names) -> t.Optional[t.Any]:
"""Return first existing of given class field names."""
for name in names:
if hasattr(cls, name):
... |
def HashFile(self, fd, byte_count):
"""Updates underlying hashers with a given file.
Args:
fd: A file object that is going to be fed to the hashers.
byte_count: A maximum number of bytes that are going to be processed.
"""
while byte_count > 0:
buf_size = min(byte_count, constants.CLI... | Updates underlying hashers with a given file.
Args:
fd: A file object that is going to be fed to the hashers.
byte_count: A maximum number of bytes that are going to be processed. | Below is the the instruction that describes the task:
### Input:
Updates underlying hashers with a given file.
Args:
fd: A file object that is going to be fed to the hashers.
byte_count: A maximum number of bytes that are going to be processed.
### Response:
def HashFile(self, fd, byte_count):
... |
def __train(self, n_clusters=4):
"""
Calculate cluster's centroids and standard deviations. If there are at least the number of threshold rows \
then:
* Observations will be normalised.
* Standard deviations will be returned.
* Clusters will be retu... | Calculate cluster's centroids and standard deviations. If there are at least the number of threshold rows \
then:
* Observations will be normalised.
* Standard deviations will be returned.
* Clusters will be returned.
* Centroids are ordered based on their... | Below is the the instruction that describes the task:
### Input:
Calculate cluster's centroids and standard deviations. If there are at least the number of threshold rows \
then:
* Observations will be normalised.
* Standard deviations will be returned.
* Clusters ... |
def encode_request(username, password, uuid, owner_uuid, is_owner_connection, client_type, serialization_version, client_hazelcast_version):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(username, password, uuid, owner_uuid, is_owner_connection, client_type... | Encode request into client_message | Below is the the instruction that describes the task:
### Input:
Encode request into client_message
### Response:
def encode_request(username, password, uuid, owner_uuid, is_owner_connection, client_type, serialization_version, client_hazelcast_version):
""" Encode request into client_message"""
client_mes... |
def _generate_barcode_ids(info_iter):
"""Create unique barcode IDs assigned to sequences
"""
bc_type = "SampleSheet"
barcodes = list(set([x[-1] for x in info_iter]))
barcodes.sort()
barcode_ids = {}
for i, bc in enumerate(barcodes):
barcode_ids[bc] = (bc_type, i+1)
return barcode... | Create unique barcode IDs assigned to sequences | Below is the the instruction that describes the task:
### Input:
Create unique barcode IDs assigned to sequences
### Response:
def _generate_barcode_ids(info_iter):
"""Create unique barcode IDs assigned to sequences
"""
bc_type = "SampleSheet"
barcodes = list(set([x[-1] for x in info_iter]))
ba... |
def add_on_gpu(self, transforms):
"""Add some transforms."""
if not isinstance(transforms, list):
transforms = [transforms]
self.gpu_transforms.extend(transforms or [])
return self | Add some transforms. | Below is the the instruction that describes the task:
### Input:
Add some transforms.
### Response:
def add_on_gpu(self, transforms):
"""Add some transforms."""
if not isinstance(transforms, list):
transforms = [transforms]
self.gpu_transforms.extend(transforms or [])
re... |
def nat_gateway_present(name, subnet_name=None, subnet_id=None,
region=None, key=None, keyid=None, profile=None, allocation_id=None):
'''
Ensure a nat gateway exists within the specified subnet
This function requires boto3.
.. versionadded:: 2016.11.0
Example:
.. code... | Ensure a nat gateway exists within the specified subnet
This function requires boto3.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
boto_vpc.nat_gateway_present:
- subnet_name: my-subnet
name
Name of the state
subnet_name
Name of the subnet wi... | Below is the the instruction that describes the task:
### Input:
Ensure a nat gateway exists within the specified subnet
This function requires boto3.
.. versionadded:: 2016.11.0
Example:
.. code-block:: yaml
boto_vpc.nat_gateway_present:
- subnet_name: my-subnet
name
... |
def lmx_base():
"""Transformer on languagemodel_lm1b32k_packed. 50M Params."""
hparams = transformer.transformer_tpu()
# sharing is counterproductive when underparameterized
hparams.shared_embedding_and_softmax_weights = False
# we judge by log-ppl, so label smoothing hurts.
hparams.label_smoothing = 0.0
... | Transformer on languagemodel_lm1b32k_packed. 50M Params. | Below is the the instruction that describes the task:
### Input:
Transformer on languagemodel_lm1b32k_packed. 50M Params.
### Response:
def lmx_base():
"""Transformer on languagemodel_lm1b32k_packed. 50M Params."""
hparams = transformer.transformer_tpu()
# sharing is counterproductive when underparameteriz... |
def prior_sediment_memory(*args, **kwargs):
"""Get the prior density of sediment memory
Returns
-------
y : ndarray
Array giving the density.
x : ndarray
Array of Memory (ratio) values over which the density was evaluated.
"""
# "plot the ... | Get the prior density of sediment memory
Returns
-------
y : ndarray
Array giving the density.
x : ndarray
Array of Memory (ratio) values over which the density was evaluated. | Below is the the instruction that describes the task:
### Input:
Get the prior density of sediment memory
Returns
-------
y : ndarray
Array giving the density.
x : ndarray
Array of Memory (ratio) values over which the density was evaluated.
### Response:
def... |
def send(self, request, **kwargs):
# type: (ClientRequest, Any) -> ClientResponse
"""Send request object according to configuration.
Allowed kwargs are:
- session : will override the driver session and use yours. Should NOT be done unless really required.
- anything else is sent... | Send request object according to configuration.
Allowed kwargs are:
- session : will override the driver session and use yours. Should NOT be done unless really required.
- anything else is sent straight to requests.
:param ClientRequest request: The request object to be sent. | Below is the the instruction that describes the task:
### Input:
Send request object according to configuration.
Allowed kwargs are:
- session : will override the driver session and use yours. Should NOT be done unless really required.
- anything else is sent straight to requests.
... |
def create_opengl_context(surface_size=(640, 480)):
"""Create offscreen OpenGL context and make it current.
Users are expected to directly use EGL API in case more advanced
context management is required.
Args:
surface_size: (width, height), size of the offscreen rendering surface.
"""
egl_display = e... | Create offscreen OpenGL context and make it current.
Users are expected to directly use EGL API in case more advanced
context management is required.
Args:
surface_size: (width, height), size of the offscreen rendering surface. | Below is the the instruction that describes the task:
### Input:
Create offscreen OpenGL context and make it current.
Users are expected to directly use EGL API in case more advanced
context management is required.
Args:
surface_size: (width, height), size of the offscreen rendering surface.
### Respons... |
def transform(x):
"""
Transform from Timeddelta to numerical format
"""
# microseconds
try:
x = np.array([_x.total_seconds()*10**6 for _x in x])
except TypeError:
x = x.total_seconds()*10**6
return x | Transform from Timeddelta to numerical format | Below is the the instruction that describes the task:
### Input:
Transform from Timeddelta to numerical format
### Response:
def transform(x):
"""
Transform from Timeddelta to numerical format
"""
# microseconds
try:
x = np.array([_x.total_seconds()*10**6 for _x ... |
def create(self, unique_name=values.unset, friendly_name=values.unset,
identity=values.unset, deployment_sid=values.unset,
enabled=values.unset):
"""
Create a new DeviceInstance
:param unicode unique_name: A unique, addressable name of this Device.
:param u... | Create a new DeviceInstance
:param unicode unique_name: A unique, addressable name of this Device.
:param unicode friendly_name: A human readable description for this Device.
:param unicode identity: An identifier of the Device user.
:param unicode deployment_sid: The unique SID of the ... | Below is the the instruction that describes the task:
### Input:
Create a new DeviceInstance
:param unicode unique_name: A unique, addressable name of this Device.
:param unicode friendly_name: A human readable description for this Device.
:param unicode identity: An identifier of the Devic... |
def _unregister_all_factories(self):
"""
Unregisters all factories. This method should be called only after the
iPOPO service has been unregistered (that's why it's not locked)
"""
factories = list(self.__factories.keys())
for factory_name in factories:
self.u... | Unregisters all factories. This method should be called only after the
iPOPO service has been unregistered (that's why it's not locked) | Below is the the instruction that describes the task:
### Input:
Unregisters all factories. This method should be called only after the
iPOPO service has been unregistered (that's why it's not locked)
### Response:
def _unregister_all_factories(self):
"""
Unregisters all factories. This met... |
def _empty_cache(self, termlist=None):
"""Empty the cache associated with each `Term` instance.
This method is called when merging Ontologies or including
new terms in the Ontology to make sure the cache of each
term is cleaned and avoid returning wrong memoized values
(such as ... | Empty the cache associated with each `Term` instance.
This method is called when merging Ontologies or including
new terms in the Ontology to make sure the cache of each
term is cleaned and avoid returning wrong memoized values
(such as Term.rchildren() TermLists, which get memoized for... | Below is the the instruction that describes the task:
### Input:
Empty the cache associated with each `Term` instance.
This method is called when merging Ontologies or including
new terms in the Ontology to make sure the cache of each
term is cleaned and avoid returning wrong memoized value... |
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
GzipFileEntry: a file entry or None if not available.
"""
path_spec = gzip_path_spec.GzipPathSpec(parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec) | Retrieves the root file entry.
Returns:
GzipFileEntry: a file entry or None if not available. | Below is the the instruction that describes the task:
### Input:
Retrieves the root file entry.
Returns:
GzipFileEntry: a file entry or None if not available.
### Response:
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
GzipFileEntry: a file entry or None if not av... |
def user(request, username):
"""
``User`` focused activity stream. (Eg: Profile page twitter.com/justquick)
"""
instance = get_object_or_404(
USER_MODEL,
**{'is_active': True, username_field: username}
)
return render(
request,
'actstream/actor.html',
cont... | ``User`` focused activity stream. (Eg: Profile page twitter.com/justquick) | Below is the the instruction that describes the task:
### Input:
``User`` focused activity stream. (Eg: Profile page twitter.com/justquick)
### Response:
def user(request, username):
"""
``User`` focused activity stream. (Eg: Profile page twitter.com/justquick)
"""
instance = get_object_or_404(
... |
def to_dict(self):
'''Return a dict of the attributes.'''
return dict(
raw=self.raw,
scheme=self.scheme,
authority=self.authority,
netloc=self.authority,
path=self.path,
query=self.query,
fragment=self.fragment,
... | Return a dict of the attributes. | Below is the the instruction that describes the task:
### Input:
Return a dict of the attributes.
### Response:
def to_dict(self):
'''Return a dict of the attributes.'''
return dict(
raw=self.raw,
scheme=self.scheme,
authority=self.authority,
netloc=s... |
def po_to_unicode(po_obj):
"""
Turns a polib :class:`polib.PoFile` or a :class:`polib.PoEntry`
into a :class:`unicode` string.
:param po_obj: Either a :class:`polib.PoFile` or :class:`polib.PoEntry`.
:rtype: :class:`unicode` string.
"""
po_text = po_obj.__str__()
if type(po_text) !... | Turns a polib :class:`polib.PoFile` or a :class:`polib.PoEntry`
into a :class:`unicode` string.
:param po_obj: Either a :class:`polib.PoFile` or :class:`polib.PoEntry`.
:rtype: :class:`unicode` string. | Below is the the instruction that describes the task:
### Input:
Turns a polib :class:`polib.PoFile` or a :class:`polib.PoEntry`
into a :class:`unicode` string.
:param po_obj: Either a :class:`polib.PoFile` or :class:`polib.PoEntry`.
:rtype: :class:`unicode` string.
### Response:
def po_to_unicod... |
def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
'''
nlines = []
edited = False
value = six.text_type(value)
# create /e... | Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50 | Below is the the instruction that describes the task:
### Input:
Assign and persist a simple sysctl parameter for this minion
CLI Example:
.. code-block:: bash
salt '*' sysctl.persist net.inet.icmp.icmplim 50
### Response:
def persist(name, value, config='/etc/sysctl.conf'):
'''
Assign a... |
async def scale(self, scale=None, scale_change=None):
"""
Set or adjust the scale of this (K8s) application.
One or the other of scale or scale_change must be provided.
:param int scale: Scale to which to set this application.
:param int scale_change: Amount by which to adjust ... | Set or adjust the scale of this (K8s) application.
One or the other of scale or scale_change must be provided.
:param int scale: Scale to which to set this application.
:param int scale_change: Amount by which to adjust the scale of this
application (can be positive or negative). | Below is the the instruction that describes the task:
### Input:
Set or adjust the scale of this (K8s) application.
One or the other of scale or scale_change must be provided.
:param int scale: Scale to which to set this application.
:param int scale_change: Amount by which to adjust the s... |
def builder_types(cls) -> List[Type[ParameterBuilder]]:
"""
Define the available builder types.
"""
return [
entry_point.load()
for entry_point in iter_entry_points(ENTRY_POINT)
] | Define the available builder types. | Below is the the instruction that describes the task:
### Input:
Define the available builder types.
### Response:
def builder_types(cls) -> List[Type[ParameterBuilder]]:
"""
Define the available builder types.
"""
return [
entry_point.load()
for entry_point... |
def log_entry_encode(self, id, num_logs, last_log_num, time_utc, size):
'''
Reply to LOG_REQUEST_LIST
id : Log id (uint16_t)
num_logs : Total number of logs (uint16_t)
last_log_num : Hig... | Reply to LOG_REQUEST_LIST
id : Log id (uint16_t)
num_logs : Total number of logs (uint16_t)
last_log_num : High log number (uint16_t)
time_utc : UTC timestamp of log in seconds since 19... | Below is the the instruction that describes the task:
### Input:
Reply to LOG_REQUEST_LIST
id : Log id (uint16_t)
num_logs : Total number of logs (uint16_t)
last_log_num : High log number (uint16_t)
... |
def start_monitor(redis_address,
stdout_file=None,
stderr_file=None,
autoscaling_config=None,
redis_password=None):
"""Run a process to monitor the other processes.
Args:
redis_address (str): The address that the Redis server is li... | Run a process to monitor the other processes.
Args:
redis_address (str): The address that the Redis server is listening on.
stdout_file: A file handle opened for writing to redirect stdout to. If
no redirection should happen, then this should be None.
stderr_file: A file handle ... | Below is the the instruction that describes the task:
### Input:
Run a process to monitor the other processes.
Args:
redis_address (str): The address that the Redis server is listening on.
stdout_file: A file handle opened for writing to redirect stdout to. If
no redirection should ... |
def query(self, wql):
"""Connect by wmi and run wql."""
try:
self.__wql = ['wmic', '-U',
self.args.domain + '\\' + self.args.user + '%' + self.args.password,
'//' + self.args.host,
'--namespace', self.args.namespac... | Connect by wmi and run wql. | Below is the the instruction that describes the task:
### Input:
Connect by wmi and run wql.
### Response:
def query(self, wql):
"""Connect by wmi and run wql."""
try:
self.__wql = ['wmic', '-U',
self.args.domain + '\\' + self.args.user + '%' + self.args.passwo... |
def get_recirc_content(self, published=True, count=3):
"""gets the first 3 content objects in the `included_ids`
"""
query = self.get_query()
# check if query has included_ids & if there are any ids in it,
# in case the ids have been removed from the array
if not query.g... | gets the first 3 content objects in the `included_ids` | Below is the the instruction that describes the task:
### Input:
gets the first 3 content objects in the `included_ids`
### Response:
def get_recirc_content(self, published=True, count=3):
"""gets the first 3 content objects in the `included_ids`
"""
query = self.get_query()
# chec... |
def get_known_periods(self):
"""
Get the list of periods the variable value is known for.
"""
return list(self._memory_storage.get_known_periods()) + list((
self._disk_storage.get_known_periods() if self._disk_storage else [])) | Get the list of periods the variable value is known for. | Below is the the instruction that describes the task:
### Input:
Get the list of periods the variable value is known for.
### Response:
def get_known_periods(self):
"""
Get the list of periods the variable value is known for.
"""
return list(self._memory_storage.get_known_perio... |
def parseprint(code, filename="<string>", mode="exec", **kwargs):
"""Parse some code from a string and pretty-print it."""
node = parse(code, mode=mode) # An ode to the code
print(dump(node, **kwargs)) | Parse some code from a string and pretty-print it. | Below is the the instruction that describes the task:
### Input:
Parse some code from a string and pretty-print it.
### Response:
def parseprint(code, filename="<string>", mode="exec", **kwargs):
"""Parse some code from a string and pretty-print it."""
node = parse(code, mode=mode) # An ode to the code
... |
def _restructure_if_volume_follows_journal(left, right):
"""Remove volume node if it follows a journal logically in the tree hierarchy.
Args:
left (ast.ASTElement): The journal KeywordOp node.
right (ast.ASTElement): The rest of the tree to be restructured.
Return:
(ast.ASTElement)... | Remove volume node if it follows a journal logically in the tree hierarchy.
Args:
left (ast.ASTElement): The journal KeywordOp node.
right (ast.ASTElement): The rest of the tree to be restructured.
Return:
(ast.ASTElement): The restructured tree, with the volume node removed.
Note... | Below is the the instruction that describes the task:
### Input:
Remove volume node if it follows a journal logically in the tree hierarchy.
Args:
left (ast.ASTElement): The journal KeywordOp node.
right (ast.ASTElement): The rest of the tree to be restructured.
Return:
(ast.ASTEle... |
def scan_recurse(self, node, path=()):
""" do a recursive scan of the top level target file
This lets us search for included files based on the
directory of the main file just as latex does"""
path_dict = dict(list(path))
queue = []
queue.extend( self.scan(node... | do a recursive scan of the top level target file
This lets us search for included files based on the
directory of the main file just as latex does | Below is the the instruction that describes the task:
### Input:
do a recursive scan of the top level target file
This lets us search for included files based on the
directory of the main file just as latex does
### Response:
def scan_recurse(self, node, path=()):
""" do a recursive scan of... |
def with_stmt_handle(self, tokens):
"""Process with statements."""
internal_assert(len(tokens) == 2, "invalid with statement tokens", tokens)
withs, body = tokens
if len(withs) == 1 or self.target_info >= (2, 7):
return "with " + ", ".join(withs) + body
else:
... | Process with statements. | Below is the the instruction that describes the task:
### Input:
Process with statements.
### Response:
def with_stmt_handle(self, tokens):
"""Process with statements."""
internal_assert(len(tokens) == 2, "invalid with statement tokens", tokens)
withs, body = tokens
if len(withs) ==... |
def container_new_folder(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /container-xxxx/newFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder
"""
return DXHTTPRequest('/%s/... | Invokes the /container-xxxx/newFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder | Below is the the instruction that describes the task:
### Input:
Invokes the /container-xxxx/newFolder API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder
### Response:
def container_new_folder(object_id, input_params=... |
def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:
"""Produce N identical layers."""
return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(num_copies)]) | Produce N identical layers. | Below is the the instruction that describes the task:
### Input:
Produce N identical layers.
### Response:
def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:
"""Produce N identical layers."""
return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(num_copies)]) |
def get_json_encoders_for_type(self, type_to_encode: type) -> Optional[Iterable[JSONEncoder]]:
"""
Gets the registered JSON encoder for the given type.
:param type_to_encode: the type of object that is to be encoded
:return: the encoder for the given object else `None` if unknown
... | Gets the registered JSON encoder for the given type.
:param type_to_encode: the type of object that is to be encoded
:return: the encoder for the given object else `None` if unknown | Below is the the instruction that describes the task:
### Input:
Gets the registered JSON encoder for the given type.
:param type_to_encode: the type of object that is to be encoded
:return: the encoder for the given object else `None` if unknown
### Response:
def get_json_encoders_for_type(self, t... |
def freeze(self):
"""Create a usable data structure for serializing."""
data = super(IndexBuilder, self).freeze()
try:
# Sphinx >= 1.5 format
# Due to changes from github.com/sphinx-doc/sphinx/pull/2454
base_file_names = data['docnames']
except KeyErro... | Create a usable data structure for serializing. | Below is the the instruction that describes the task:
### Input:
Create a usable data structure for serializing.
### Response:
def freeze(self):
"""Create a usable data structure for serializing."""
data = super(IndexBuilder, self).freeze()
try:
# Sphinx >= 1.5 format
... |
def get_app_kwarg_dict(appInstance):
"""Returns the dictionary of CORS specific app configurations."""
# In order to support blueprints which do not have a config attribute
app_config = getattr(appInstance, 'config', {})
return dict(
(k.lower().replace('cors_', ''), app_config.get(k))
fo... | Returns the dictionary of CORS specific app configurations. | Below is the the instruction that describes the task:
### Input:
Returns the dictionary of CORS specific app configurations.
### Response:
def get_app_kwarg_dict(appInstance):
"""Returns the dictionary of CORS specific app configurations."""
# In order to support blueprints which do not have a config attri... |
def list_files(dir_path, recursive=True):
"""
Return a list of files in dir_path.
"""
for root, dirs, files in os.walk(dir_path):
file_list = [os.path.join(root, f) for f in files]
if recursive:
for dir in dirs:
dir = os.path.join(root, dir)
... | Return a list of files in dir_path. | Below is the the instruction that describes the task:
### Input:
Return a list of files in dir_path.
### Response:
def list_files(dir_path, recursive=True):
"""
Return a list of files in dir_path.
"""
for root, dirs, files in os.walk(dir_path):
file_list = [os.path.join(root, f) for f in ... |
def get_template(file):
''' Lookup a template class for the given filename or file
extension. Return nil when no implementation is found.
'''
pattern = str(file).lower()
while len(pattern) and not Lean.is_registered(pattern):
pattern = os.path.basename(pattern)
pattern = re.sub(r'^[... | Lookup a template class for the given filename or file
extension. Return nil when no implementation is found. | Below is the the instruction that describes the task:
### Input:
Lookup a template class for the given filename or file
extension. Return nil when no implementation is found.
### Response:
def get_template(file):
''' Lookup a template class for the given filename or file
extension. Return nil w... |
def parse(query_string, info={}):
"""
:returns: a normalized query_dict as in the following examples:
>>> parse('kind=stats', {'stats': {'mean': 0, 'max': 1}})
{'kind': ['mean', 'max'], 'k': [0, 1], 'rlzs': False}
>>> parse('kind=rlzs', {'stats': {}, 'num_rlzs': 3})
{'kind': ['rlz-000', 'rlz-00... | :returns: a normalized query_dict as in the following examples:
>>> parse('kind=stats', {'stats': {'mean': 0, 'max': 1}})
{'kind': ['mean', 'max'], 'k': [0, 1], 'rlzs': False}
>>> parse('kind=rlzs', {'stats': {}, 'num_rlzs': 3})
{'kind': ['rlz-000', 'rlz-001', 'rlz-002'], 'k': [0, 1, 2], 'rlzs': True}
... | Below is the the instruction that describes the task:
### Input:
:returns: a normalized query_dict as in the following examples:
>>> parse('kind=stats', {'stats': {'mean': 0, 'max': 1}})
{'kind': ['mean', 'max'], 'k': [0, 1], 'rlzs': False}
>>> parse('kind=rlzs', {'stats': {}, 'num_rlzs': 3})
{'kin... |
def visit_starred(self, node, parent):
"""visit a Starred node and return a new instance of it"""
context = self._get_context(node)
newnode = nodes.Starred(
ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent
)
newnode.postinit(self.visit(node.v... | visit a Starred node and return a new instance of it | Below is the the instruction that describes the task:
### Input:
visit a Starred node and return a new instance of it
### Response:
def visit_starred(self, node, parent):
"""visit a Starred node and return a new instance of it"""
context = self._get_context(node)
newnode = nodes.Starred(
... |
def run_step(*args, prompt=None):
"""
Prints out the command and asks if it should be run.
If yes (default), runs it.
:param args: list of strings (command and args)
"""
global DRY_RUN
cmd = args
print(' '.join(cmd))
if skip_step():
print('--- Skipping...')
elif DRY_RUN:... | Prints out the command and asks if it should be run.
If yes (default), runs it.
:param args: list of strings (command and args) | Below is the the instruction that describes the task:
### Input:
Prints out the command and asks if it should be run.
If yes (default), runs it.
:param args: list of strings (command and args)
### Response:
def run_step(*args, prompt=None):
"""
Prints out the command and asks if it should be run.
... |
def get_feature_state_for_scope(self, feature_id, user_scope, scope_name, scope_value):
"""GetFeatureStateForScope.
[Preview API] Get the state of the specified feature for the given named scope
:param str feature_id: Contribution id of the feature
:param str user_scope: User-Scope at wh... | GetFeatureStateForScope.
[Preview API] Get the state of the specified feature for the given named scope
:param str feature_id: Contribution id of the feature
:param str user_scope: User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
:param s... | Below is the the instruction that describes the task:
### Input:
GetFeatureStateForScope.
[Preview API] Get the state of the specified feature for the given named scope
:param str feature_id: Contribution id of the feature
:param str user_scope: User-Scope at which to get the value. Should b... |
def _daily_suns(self, datetimes):
"""Get sun curve for multiple days of the year."""
for dt in datetimes:
# calculate sunrise sunset and noon
nss = self.calculate_sunrise_sunset(dt.month, dt.day)
dts = tuple(nss[k] for k in ('sunrise', 'noon', 'sunset'))
i... | Get sun curve for multiple days of the year. | Below is the the instruction that describes the task:
### Input:
Get sun curve for multiple days of the year.
### Response:
def _daily_suns(self, datetimes):
"""Get sun curve for multiple days of the year."""
for dt in datetimes:
# calculate sunrise sunset and noon
nss = sel... |
def get_language_progress(self, lang):
"""Get informations about user's progression in a language."""
if not self._is_current_language(lang):
self._switch_language(lang)
fields = ['streak', 'language_string', 'level_progress',
'num_skills_learned', 'level_percent',... | Get informations about user's progression in a language. | Below is the the instruction that describes the task:
### Input:
Get informations about user's progression in a language.
### Response:
def get_language_progress(self, lang):
"""Get informations about user's progression in a language."""
if not self._is_current_language(lang):
self._swi... |
def clear_group(self):
"""Clears the group designation.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for osid.resource.ResourceFo... | Clears the group designation.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Clears the group designation.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
### Response:
def clear_group(self):
... |
def download_encrypted_file(work_dir, url, key_path, name):
"""
Downloads encrypted file from S3
Input1: Working directory
Input2: S3 URL to be downloaded
Input3: Path to key necessary for decryption
Input4: name of file to be downloaded
"""
file_path = os.path.join(work_dir, name)
... | Downloads encrypted file from S3
Input1: Working directory
Input2: S3 URL to be downloaded
Input3: Path to key necessary for decryption
Input4: name of file to be downloaded | Below is the the instruction that describes the task:
### Input:
Downloads encrypted file from S3
Input1: Working directory
Input2: S3 URL to be downloaded
Input3: Path to key necessary for decryption
Input4: name of file to be downloaded
### Response:
def download_encrypted_file(work_dir, url, ke... |
def kegg_pathway(df, pathway, a, b=None, ids_from="Proteins", cmap=cm.PuOr_r, is_log2=False, fillna=None, z_score=1):
"""
Visualize data on a kegg pathway.
:param df:
:param pathway:
:param a:
:param b:
:param ids_from:
:param cmap:
:param is_log2:
:param fillna:
:param z_s... | Visualize data on a kegg pathway.
:param df:
:param pathway:
:param a:
:param b:
:param ids_from:
:param cmap:
:param is_log2:
:param fillna:
:param z_score:
:return: | Below is the the instruction that describes the task:
### Input:
Visualize data on a kegg pathway.
:param df:
:param pathway:
:param a:
:param b:
:param ids_from:
:param cmap:
:param is_log2:
:param fillna:
:param z_score:
:return:
### Response:
def kegg_pathway(df, pathwa... |
def plot_projected_dos(self, pdos_indices=None, legend=None):
"""Plot projected DOS
Parameters
----------
pdos_indices : list of list, optional
Sets of indices of atoms whose projected DOS are summed over.
The indices start with 0. An example is as follwos:
... | Plot projected DOS
Parameters
----------
pdos_indices : list of list, optional
Sets of indices of atoms whose projected DOS are summed over.
The indices start with 0. An example is as follwos:
pdos_indices=[[0, 1], [2, 3, 4, 5]]
Default is No... | Below is the the instruction that describes the task:
### Input:
Plot projected DOS
Parameters
----------
pdos_indices : list of list, optional
Sets of indices of atoms whose projected DOS are summed over.
The indices start with 0. An example is as follwos:
... |
def setup_cmd_parser(cls):
"""Returns the Groupsio argument parser."""
parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,
from_date=True,
token_auth=True)
# Backend token is required
... | Returns the Groupsio argument parser. | Below is the the instruction that describes the task:
### Input:
Returns the Groupsio argument parser.
### Response:
def setup_cmd_parser(cls):
"""Returns the Groupsio argument parser."""
parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES,
fr... |
def find_stars(self, data, mask=None):
"""
Find stars in an astronomical image.
Parameters
----------
data : 2D array_like
The 2D image array.
mask : 2D bool array, optional
A boolean mask with the same shape as ``data``, where a
`Tru... | Find stars in an astronomical image.
Parameters
----------
data : 2D array_like
The 2D image array.
mask : 2D bool array, optional
A boolean mask with the same shape as ``data``, where a
`True` value indicates the corresponding element of ``data``
... | Below is the the instruction that describes the task:
### Input:
Find stars in an astronomical image.
Parameters
----------
data : 2D array_like
The 2D image array.
mask : 2D bool array, optional
A boolean mask with the same shape as ``data``, where a
... |
def has_context_loop(state, incorrect_msg, exact_names):
"""When dispatched on loops, has_context the target vars are the attribute _target_vars.
Note: This is to allow people to call has_context on a node (e.g. for_loop) rather than
one of its attributes (e.g. body). Purely for convenience.
"""
... | When dispatched on loops, has_context the target vars are the attribute _target_vars.
Note: This is to allow people to call has_context on a node (e.g. for_loop) rather than
one of its attributes (e.g. body). Purely for convenience. | Below is the the instruction that describes the task:
### Input:
When dispatched on loops, has_context the target vars are the attribute _target_vars.
Note: This is to allow people to call has_context on a node (e.g. for_loop) rather than
one of its attributes (e.g. body). Purely for convenience.
###... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.