code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def list_by_x(self, item=None):
"""
:param item: Grouping key, one of "cid", "type" and "extensions"
:return:
A list of :class:`Processor` or its children classes grouped by
given 'item', [(cid, [:class:`Processor`)]] by default
"""
prs = self._processors
... | :param item: Grouping key, one of "cid", "type" and "extensions"
:return:
A list of :class:`Processor` or its children classes grouped by
given 'item', [(cid, [:class:`Processor`)]] by default | Below is the the instruction that describes the task:
### Input:
:param item: Grouping key, one of "cid", "type" and "extensions"
:return:
A list of :class:`Processor` or its children classes grouped by
given 'item', [(cid, [:class:`Processor`)]] by default
### Response:
def list_by... |
def grow(self, path):
"""
Grow the metadata tree for the given directory path
Note: For each path, grow() should be run only once. Growing the tree
from the same path multiple times with attribute adding using the "+"
sign leads to adding the value more than once!
"""
... | Grow the metadata tree for the given directory path
Note: For each path, grow() should be run only once. Growing the tree
from the same path multiple times with attribute adding using the "+"
sign leads to adding the value more than once! | Below is the the instruction that describes the task:
### Input:
Grow the metadata tree for the given directory path
Note: For each path, grow() should be run only once. Growing the tree
from the same path multiple times with attribute adding using the "+"
sign leads to adding the value mor... |
def adjust_to_360(val, key):
"""
Take in a value and a key. If the key is of the type:
declination/longitude/azimuth/direction, adjust it to be within
the range 0-360 as required by the MagIC data model
"""
CheckDec = ['_dec', '_lon', '_azimuth', 'dip_direction']
adjust = False
for dec_... | Take in a value and a key. If the key is of the type:
declination/longitude/azimuth/direction, adjust it to be within
the range 0-360 as required by the MagIC data model | Below is the the instruction that describes the task:
### Input:
Take in a value and a key. If the key is of the type:
declination/longitude/azimuth/direction, adjust it to be within
the range 0-360 as required by the MagIC data model
### Response:
def adjust_to_360(val, key):
"""
Take in a value ... |
def colorize(text='', opts=(), **kwargs):
"""
Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow'... | Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
Valid option... | Below is the the instruction that describes the task:
### Input:
Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'g... |
def switch_toggle(self, device):
"""Toggles the current state of the given device"""
state = self.get_state(device)
if(state == '1'):
return self.switch_off(device)
elif(state == '0'):
return self.switch_on(device)
else:
return state | Toggles the current state of the given device | Below is the the instruction that describes the task:
### Input:
Toggles the current state of the given device
### Response:
def switch_toggle(self, device):
"""Toggles the current state of the given device"""
state = self.get_state(device)
if(state == '1'):
return self.switch_o... |
def read_iso19115_metadata(layer_uri, keyword=None, version_35=False):
"""Retrieve keywords from a metadata object
:param layer_uri: Uri to layer.
:type layer_uri: basestring
:param keyword: The key of keyword that want to be read. If None, return
all keywords in dictionary.
:type keyword:... | Retrieve keywords from a metadata object
:param layer_uri: Uri to layer.
:type layer_uri: basestring
:param keyword: The key of keyword that want to be read. If None, return
all keywords in dictionary.
:type keyword: basestring
:returns: Dictionary of keywords or value of key as string.
... | Below is the the instruction that describes the task:
### Input:
Retrieve keywords from a metadata object
:param layer_uri: Uri to layer.
:type layer_uri: basestring
:param keyword: The key of keyword that want to be read. If None, return
all keywords in dictionary.
:type keyword: basestri... |
def status(self):
"""Return current readings, as a dictionary with:
duration -- the duration of the measurements, in seconds;
cpm -- the radiation count by minute;
uSvh -- the radiation dose, exprimed in Sievert per house (uSv/h);
uSvhError -- the incertitude for ... | Return current readings, as a dictionary with:
duration -- the duration of the measurements, in seconds;
cpm -- the radiation count by minute;
uSvh -- the radiation dose, exprimed in Sievert per house (uSv/h);
uSvhError -- the incertitude for the radiation dose. | Below is the the instruction that describes the task:
### Input:
Return current readings, as a dictionary with:
duration -- the duration of the measurements, in seconds;
cpm -- the radiation count by minute;
uSvh -- the radiation dose, exprimed in Sievert per house (uSv/h);
... |
def session_expired(self):
"""
Returns True if login_time not set or seconds since
login time is greater than 200 mins.
"""
if not self._login_time or (datetime.datetime.now()-self._login_time).total_seconds() > 12000:
return True | Returns True if login_time not set or seconds since
login time is greater than 200 mins. | Below is the the instruction that describes the task:
### Input:
Returns True if login_time not set or seconds since
login time is greater than 200 mins.
### Response:
def session_expired(self):
"""
Returns True if login_time not set or seconds since
login time is greater than 200 m... |
def _setup_mqs(self):
"""
**Purpose**: Setup RabbitMQ system on the client side. We instantiate queue(s) 'pendingq-*' for communication
between the enqueuer thread and the task manager process. We instantiate queue(s) 'completedq-*' for
communication between the task manager and dequeuer... | **Purpose**: Setup RabbitMQ system on the client side. We instantiate queue(s) 'pendingq-*' for communication
between the enqueuer thread and the task manager process. We instantiate queue(s) 'completedq-*' for
communication between the task manager and dequeuer thread. We instantiate queue 'sync-to-mas... | Below is the the instruction that describes the task:
### Input:
**Purpose**: Setup RabbitMQ system on the client side. We instantiate queue(s) 'pendingq-*' for communication
between the enqueuer thread and the task manager process. We instantiate queue(s) 'completedq-*' for
communication between th... |
def save(self, filename, binary=True):
"""
Writes a surface mesh to disk.
Written file may be an ASCII or binary ply, stl, or vtk mesh file.
Parameters
----------
filename : str
Filename of mesh to be written. File type is inferred from
the exte... | Writes a surface mesh to disk.
Written file may be an ASCII or binary ply, stl, or vtk mesh file.
Parameters
----------
filename : str
Filename of mesh to be written. File type is inferred from
the extension of the filename unless overridden with
ft... | Below is the the instruction that describes the task:
### Input:
Writes a surface mesh to disk.
Written file may be an ASCII or binary ply, stl, or vtk mesh file.
Parameters
----------
filename : str
Filename of mesh to be written. File type is inferred from
... |
def _extract_header_value(line):
"""
Extracts a key / value pair from a header line in an ODF file
"""
# Skip blank lines, returning None
if not line:
return None
# Attempt to split by equals sign
halves = line.split('=')
if len(halves) > 1:
key = halves[0].strip()
... | Extracts a key / value pair from a header line in an ODF file | Below is the the instruction that describes the task:
### Input:
Extracts a key / value pair from a header line in an ODF file
### Response:
def _extract_header_value(line):
"""
Extracts a key / value pair from a header line in an ODF file
"""
# Skip blank lines, returning None
if not line:
... |
def register_target(repo_cmd, repo_service):
"""Decorator to register a class with an repo_service"""
def decorate(klass):
log.debug('Loading service module class: {}'.format(klass.__name__) )
klass.command = repo_cmd
klass.name = repo_service
RepositoryService.service_map[repo_s... | Decorator to register a class with an repo_service | Below is the the instruction that describes the task:
### Input:
Decorator to register a class with an repo_service
### Response:
def register_target(repo_cmd, repo_service):
"""Decorator to register a class with an repo_service"""
def decorate(klass):
log.debug('Loading service module class: {}'.f... |
def status(url="http://127.0.0.1/status"):
"""
Return the data from an Nginx status page as a dictionary.
http://wiki.nginx.org/HttpStubStatusModule
url
The URL of the status page. Defaults to 'http://127.0.0.1/status'
CLI Example:
.. code-block:: bash
salt '*' nginx.status
... | Return the data from an Nginx status page as a dictionary.
http://wiki.nginx.org/HttpStubStatusModule
url
The URL of the status page. Defaults to 'http://127.0.0.1/status'
CLI Example:
.. code-block:: bash
salt '*' nginx.status | Below is the the instruction that describes the task:
### Input:
Return the data from an Nginx status page as a dictionary.
http://wiki.nginx.org/HttpStubStatusModule
url
The URL of the status page. Defaults to 'http://127.0.0.1/status'
CLI Example:
.. code-block:: bash
salt '*' ... |
def delete(self, data=None):
"""Delete this object from the JSS."""
if not self.can_delete:
raise JSSMethodNotAllowedError(self.__class__.__name__)
if data:
self.jss.delete(self.url, data)
else:
self.jss.delete(self.url) | Delete this object from the JSS. | Below is the the instruction that describes the task:
### Input:
Delete this object from the JSS.
### Response:
def delete(self, data=None):
"""Delete this object from the JSS."""
if not self.can_delete:
raise JSSMethodNotAllowedError(self.__class__.__name__)
if data:
... |
def get_children(self, recursive=False):
"""Return the children of this process as a list of Process
objects.
If recursive is True return all the parent descendants.
Example (A == this process):
A ββ
β
ββ B (child) ββ
β ββ X (gra... | Return the children of this process as a list of Process
objects.
If recursive is True return all the parent descendants.
Example (A == this process):
A ββ
β
ββ B (child) ββ
β ββ X (grandchild) ββ
β ... | Below is the the instruction that describes the task:
### Input:
Return the children of this process as a list of Process
objects.
If recursive is True return all the parent descendants.
Example (A == this process):
A ββ
β
ββ B (child) ββ
β ... |
def vec_to_surface(vec):
"""
Transform a float vector to a surface miller index with integers.
Args:
vec (1 by 3 array float vector): input float vector
Return:
the surface miller index of the input vector.
"""
miller = [None] * 3
index = ... | Transform a float vector to a surface miller index with integers.
Args:
vec (1 by 3 array float vector): input float vector
Return:
the surface miller index of the input vector. | Below is the the instruction that describes the task:
### Input:
Transform a float vector to a surface miller index with integers.
Args:
vec (1 by 3 array float vector): input float vector
Return:
the surface miller index of the input vector.
### Response:
def vec_to_surfac... |
def yeasttruth(args):
"""
%prog yeasttruth Pillars.tab *.gff
Prepare pairs data for 14 yeasts.
"""
p = OptionParser(yeasttruth.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) < 2:
sys.exit(not p.print_help())
pillars = args[0]
gffiles = args[1:]
... | %prog yeasttruth Pillars.tab *.gff
Prepare pairs data for 14 yeasts. | Below is the the instruction that describes the task:
### Input:
%prog yeasttruth Pillars.tab *.gff
Prepare pairs data for 14 yeasts.
### Response:
def yeasttruth(args):
"""
%prog yeasttruth Pillars.tab *.gff
Prepare pairs data for 14 yeasts.
"""
p = OptionParser(yeasttruth.__doc__)
p... |
def _find_logs(self, compile_workunit):
"""Finds all logs under the given workunit."""
for idx, workunit in enumerate(compile_workunit.children):
for output_name, outpath in workunit.output_paths().items():
if output_name in ('stdout', 'stderr'):
yield idx, workunit.name, output_name, ou... | Finds all logs under the given workunit. | Below is the the instruction that describes the task:
### Input:
Finds all logs under the given workunit.
### Response:
def _find_logs(self, compile_workunit):
"""Finds all logs under the given workunit."""
for idx, workunit in enumerate(compile_workunit.children):
for output_name, outpath in workuni... |
def setup_dir(f):
''' Decorate f to run inside the directory where setup.py resides.
'''
setup_dir = os.path.dirname(os.path.abspath(__file__))
def wrapped(*args, **kwargs):
with chdir(setup_dir):
return f(*args, **kwargs)
return wrapped | Decorate f to run inside the directory where setup.py resides. | Below is the the instruction that describes the task:
### Input:
Decorate f to run inside the directory where setup.py resides.
### Response:
def setup_dir(f):
''' Decorate f to run inside the directory where setup.py resides.
'''
setup_dir = os.path.dirname(os.path.abspath(__file__))
def wrapped(... |
def calculate_reshape(original_shape, new_shape, validate=False, name=None):
"""Calculates the reshaped dimensions (replacing up to one -1 in reshape)."""
batch_shape_static = tensorshape_util.constant_value_as_shape(new_shape)
if tensorshape_util.is_fully_defined(batch_shape_static):
return np.int32(batch_sh... | Calculates the reshaped dimensions (replacing up to one -1 in reshape). | Below is the the instruction that describes the task:
### Input:
Calculates the reshaped dimensions (replacing up to one -1 in reshape).
### Response:
def calculate_reshape(original_shape, new_shape, validate=False, name=None):
"""Calculates the reshaped dimensions (replacing up to one -1 in reshape)."""
batch... |
def _debug_info(self):
"""Show a list of recently variables info.
"""
self._msg('DEBUG')
self._msg2('WorkDir: {0}'.format(self._curdir))
self._msg2('Cookies: {0}'.format(self._session.cookies))
self._msg2('Headers: {0}'.format(self._session.headers))
self._msg2('C... | Show a list of recently variables info. | Below is the the instruction that describes the task:
### Input:
Show a list of recently variables info.
### Response:
def _debug_info(self):
"""Show a list of recently variables info.
"""
self._msg('DEBUG')
self._msg2('WorkDir: {0}'.format(self._curdir))
self._msg2('Cookies... |
def get_actuators(self):
"""
Get actuators as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.actuators} | Get actuators as a dictionary of format ``{name: status}`` | Below is the the instruction that describes the task:
### Input:
Get actuators as a dictionary of format ``{name: status}``
### Response:
def get_actuators(self):
"""
Get actuators as a dictionary of format ``{name: status}``
"""
return {i.name: i.status for i in self.system.act... |
def copy(self, resource_view):
# type: (Union[ResourceView,Dict,str]) -> None
"""Copies all fields except id, resource_id and package_id from another resource view.
Args:
resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ... | Copies all fields except id, resource_id and package_id from another resource view.
Args:
resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ResourceView object or a dictionary
Returns:
None | Below is the the instruction that describes the task:
### Input:
Copies all fields except id, resource_id and package_id from another resource view.
Args:
resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ResourceView object or a dic... |
def get_rotation_matrix(axis, angle):
"""Returns the rotation matrix.
This function returns a matrix for the counterclockwise rotation
around the given axis.
The Input angle is in radians.
Args:
axis (vector):
angle (float):
Returns:
Rotation matrix (np.array):
"""... | Returns the rotation matrix.
This function returns a matrix for the counterclockwise rotation
around the given axis.
The Input angle is in radians.
Args:
axis (vector):
angle (float):
Returns:
Rotation matrix (np.array): | Below is the the instruction that describes the task:
### Input:
Returns the rotation matrix.
This function returns a matrix for the counterclockwise rotation
around the given axis.
The Input angle is in radians.
Args:
axis (vector):
angle (float):
Returns:
Rotation ma... |
def find_atomics(formula: Formula) -> Set[PLAtomic]:
"""Finds all the atomic formulas"""
f = formula
res = set()
if isinstance(formula, PLFormula):
res = formula.find_atomics()
# elif isinstance(f, PLNot):
# res = res.union(find_atomics(f.f))
# elif isinstance(f, PLBinaryOperator... | Finds all the atomic formulas | Below is the the instruction that describes the task:
### Input:
Finds all the atomic formulas
### Response:
def find_atomics(formula: Formula) -> Set[PLAtomic]:
"""Finds all the atomic formulas"""
f = formula
res = set()
if isinstance(formula, PLFormula):
res = formula.find_atomics()
#... |
def ostype_2_json(self):
"""
transform ariane_clip3 OS Type object to Ariane server JSON obj
:return: Ariane JSON obj
"""
LOGGER.debug("OSType.ostype_2_json")
json_obj = {
'osTypeID': self.id,
'osTypeName': self.name,
'osTypeArchitectur... | transform ariane_clip3 OS Type object to Ariane server JSON obj
:return: Ariane JSON obj | Below is the the instruction that describes the task:
### Input:
transform ariane_clip3 OS Type object to Ariane server JSON obj
:return: Ariane JSON obj
### Response:
def ostype_2_json(self):
"""
transform ariane_clip3 OS Type object to Ariane server JSON obj
:return: Ariane JSON o... |
def load(self):
"""
Load the dataset using pylearn2.config.yaml_parse.
"""
from pylearn2.config import yaml_parse
from pylearn2.datasets import Dataset
dataset = yaml_parse.load(self.yaml_string)
assert isinstance(dataset, Dataset)
data = dataset.iterator... | Load the dataset using pylearn2.config.yaml_parse. | Below is the the instruction that describes the task:
### Input:
Load the dataset using pylearn2.config.yaml_parse.
### Response:
def load(self):
"""
Load the dataset using pylearn2.config.yaml_parse.
"""
from pylearn2.config import yaml_parse
from pylearn2.datasets import D... |
def predict(self, X, raw_score=False, num_iteration=None,
pred_leaf=False, pred_contrib=False, **kwargs):
"""Docstring is inherited from the LGBMModel."""
result = self.predict_proba(X, raw_score, num_iteration,
pred_leaf, pred_contrib, **kwargs)
... | Docstring is inherited from the LGBMModel. | Below is the the instruction that describes the task:
### Input:
Docstring is inherited from the LGBMModel.
### Response:
def predict(self, X, raw_score=False, num_iteration=None,
pred_leaf=False, pred_contrib=False, **kwargs):
"""Docstring is inherited from the LGBMModel."""
result... |
def open_recruitment(self, n=1):
"""Return initial experiment URL list, plus instructions
for finding subsequent recruitment events in experiemnt logs.
"""
logger.info("Opening CLI recruitment for {} participants".format(n))
recruitments = self.recruit(n)
message = (
... | Return initial experiment URL list, plus instructions
for finding subsequent recruitment events in experiemnt logs. | Below is the the instruction that describes the task:
### Input:
Return initial experiment URL list, plus instructions
for finding subsequent recruitment events in experiemnt logs.
### Response:
def open_recruitment(self, n=1):
"""Return initial experiment URL list, plus instructions
for fi... |
def deepcopy(x, memo=None, _nil=[]):
"""Deep copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
"""
if memo is None:
memo = {}
d = id(x)
y = memo.get(d, _nil)
if y is not _nil:
return y
cls = type(x)
copier = _deepcopy_disp... | Deep copy operation on arbitrary Python objects.
See the module's __doc__ string for more info. | Below is the the instruction that describes the task:
### Input:
Deep copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
### Response:
def deepcopy(x, memo=None, _nil=[]):
"""Deep copy operation on arbitrary Python objects.
See the module's __doc__ string for m... |
def get_transport_info(self, key: str) -> Any:
"""
Get extra info from the transport.
Supported keys:
- ``peername``
- ``socket``
- ``sockname``
- ``compression``
- ``cipher``
- ``peercert``
- ``sslcontext``
... | Get extra info from the transport.
Supported keys:
- ``peername``
- ``socket``
- ``sockname``
- ``compression``
- ``cipher``
- ``peercert``
- ``sslcontext``
- ``sslobject``
:raises SMTPServerDisconnected: c... | Below is the the instruction that describes the task:
### Input:
Get extra info from the transport.
Supported keys:
- ``peername``
- ``socket``
- ``sockname``
- ``compression``
- ``cipher``
- ``peercert``
- ``sslcontext``
... |
def label_boundary_cells(network=None, boundary_faces=None):
r"""
Takes 2D or 3D network and assign labels to boundary pores
Parameters
----------
network : dictionary
A dictionary as produced by the SNOW network extraction algorithms
containing edge/vertex, site/bond, node/link inf... | r"""
Takes 2D or 3D network and assign labels to boundary pores
Parameters
----------
network : dictionary
A dictionary as produced by the SNOW network extraction algorithms
containing edge/vertex, site/bond, node/link information.
boundary_faces : list of strings
The user ... | Below is the the instruction that describes the task:
### Input:
r"""
Takes 2D or 3D network and assign labels to boundary pores
Parameters
----------
network : dictionary
A dictionary as produced by the SNOW network extraction algorithms
containing edge/vertex, site/bond, node/link... |
def import_model(self, source):
"""Import and return model instance."""
source = self._resolve_source(source)
self._context = FilePathContext(source)
with self._context.open() as f:
self._reader = self._open_reader(f)
return self._reader.create_model() | Import and return model instance. | Below is the the instruction that describes the task:
### Input:
Import and return model instance.
### Response:
def import_model(self, source):
"""Import and return model instance."""
source = self._resolve_source(source)
self._context = FilePathContext(source)
with self._context.o... |
def make_requester(self, my_args=None):
"""
make a new requester instance and handle it from driver
:param my_args: dict like {request_q}. Default : None
:return: created requester proxy
"""
LOGGER.debug("natsd.Driver.make_requester")
if my_args is None:
... | make a new requester instance and handle it from driver
:param my_args: dict like {request_q}. Default : None
:return: created requester proxy | Below is the the instruction that describes the task:
### Input:
make a new requester instance and handle it from driver
:param my_args: dict like {request_q}. Default : None
:return: created requester proxy
### Response:
def make_requester(self, my_args=None):
"""
make a new reques... |
def value(self):
"""Retrieve the data value of this attachment.
Will show the filename of the attachment if there is an attachment available otherwise None
Use save_as in order to download as a file.
Example
-------
>>> file_attachment_property = project.part('Bike').p... | Retrieve the data value of this attachment.
Will show the filename of the attachment if there is an attachment available otherwise None
Use save_as in order to download as a file.
Example
-------
>>> file_attachment_property = project.part('Bike').property('file_attachment')
... | Below is the the instruction that describes the task:
### Input:
Retrieve the data value of this attachment.
Will show the filename of the attachment if there is an attachment available otherwise None
Use save_as in order to download as a file.
Example
-------
>>> file_att... |
def eval_one_max(traj, individual):
"""The fitness function"""
traj.f_add_result('$set.$.individual', list(individual))
fitness = sum(individual)
traj.f_add_result('$set.$.fitness', fitness)
traj.f_store()
return (fitness,) | The fitness function | Below is the the instruction that describes the task:
### Input:
The fitness function
### Response:
def eval_one_max(traj, individual):
"""The fitness function"""
traj.f_add_result('$set.$.individual', list(individual))
fitness = sum(individual)
traj.f_add_result('$set.$.fitness', fitness)
traj... |
def _clause_formatter(self, cond):
'''Formats conditions
args is a list of ['field', 'operator', 'value']
'''
if len(cond) == 2 :
cond = ' '.join(cond)
return cond
if 'in' in cond[1].lower() :
if not isinstance(cond[2], (tuple, list)):
... | Formats conditions
args is a list of ['field', 'operator', 'value'] | Below is the the instruction that describes the task:
### Input:
Formats conditions
args is a list of ['field', 'operator', 'value']
### Response:
def _clause_formatter(self, cond):
'''Formats conditions
args is a list of ['field', 'operator', 'value']
'''
if len(cond) == 2... |
def add(self, items):
"""Add items to options"""
options = self._create_options(items)
for k, v in options.items():
if k in self.labels and v not in self.items:
options.pop(k)
count = 0
while f'{k}_{count}' in self.labels:
... | Add items to options | Below is the the instruction that describes the task:
### Input:
Add items to options
### Response:
def add(self, items):
"""Add items to options"""
options = self._create_options(items)
for k, v in options.items():
if k in self.labels and v not in self.items:
op... |
def enumerate_builtins(tokens):
"""
Returns a list of all the builtins being used in *tokens*.
"""
out = []
for index, tok in enumerate(tokens):
token_type = tok[0]
token_string = tok[1]
if token_string in builtins:
# Note: I need to test if print can be replaced ... | Returns a list of all the builtins being used in *tokens*. | Below is the the instruction that describes the task:
### Input:
Returns a list of all the builtins being used in *tokens*.
### Response:
def enumerate_builtins(tokens):
"""
Returns a list of all the builtins being used in *tokens*.
"""
out = []
for index, tok in enumerate(tokens):
toke... |
def spearmanr(self, target, correlation_length, mask=NotSpecified):
"""
Construct a new Factor that computes rolling spearman rank correlation
coefficients between `target` and the columns of `self`.
This method can only be called on factors which are deemed safe for use
as inpu... | Construct a new Factor that computes rolling spearman rank correlation
coefficients between `target` and the columns of `self`.
This method can only be called on factors which are deemed safe for use
as inputs to other factors. This includes `Returns` and any factors
created from `Facto... | Below is the the instruction that describes the task:
### Input:
Construct a new Factor that computes rolling spearman rank correlation
coefficients between `target` and the columns of `self`.
This method can only be called on factors which are deemed safe for use
as inputs to other factors... |
def pprint(self, output, prefix=""):
"""
Pretty-print the encoded output using ascii art.
:param output: to print
:param prefix: printed before the header if specified
"""
print prefix,
description = self.getDescription() + [("end", self.getWidth())]
for i in xrange(len(description) - 1... | Pretty-print the encoded output using ascii art.
:param output: to print
:param prefix: printed before the header if specified | Below is the the instruction that describes the task:
### Input:
Pretty-print the encoded output using ascii art.
:param output: to print
:param prefix: printed before the header if specified
### Response:
def pprint(self, output, prefix=""):
"""
Pretty-print the encoded output using ascii art.
... |
def dropNonJournals(self, ptVal = 'J', dropBad = True, invert = False):
"""Drops the non journal type `Records` from the collection, this is done by checking _ptVal_ against the PT tag
# Parameters
_ptVal_ : `optional [str]`
> Default `'J'`, The value of the PT tag to be kept, default... | Drops the non journal type `Records` from the collection, this is done by checking _ptVal_ against the PT tag
# Parameters
_ptVal_ : `optional [str]`
> Default `'J'`, The value of the PT tag to be kept, default is `'J'` the journal tag, other tags can be substituted.
_dropBad_ : `opt... | Below is the the instruction that describes the task:
### Input:
Drops the non journal type `Records` from the collection, this is done by checking _ptVal_ against the PT tag
# Parameters
_ptVal_ : `optional [str]`
> Default `'J'`, The value of the PT tag to be kept, default is `'J'` the ... |
def set_config(config_file='/etc/dnsmasq.conf', follow=True, **kwargs):
'''
Sets a value or a set of values in the specified file. By default, if
conf-dir is configured in this file, salt will attempt to set the option
in any file inside the conf-dir where it has already been enabled. If it
does not... | Sets a value or a set of values in the specified file. By default, if
conf-dir is configured in this file, salt will attempt to set the option
in any file inside the conf-dir where it has already been enabled. If it
does not find it inside any files, it will append it to the main config
file. Setting fo... | Below is the the instruction that describes the task:
### Input:
Sets a value or a set of values in the specified file. By default, if
conf-dir is configured in this file, salt will attempt to set the option
in any file inside the conf-dir where it has already been enabled. If it
does not find it inside... |
def get_prep_value(self, value):
"""Convert value to JSON string before save"""
try:
return json.dumps(value)
except Exception as err:
raise ValidationError(str(err)) | Convert value to JSON string before save | Below is the the instruction that describes the task:
### Input:
Convert value to JSON string before save
### Response:
def get_prep_value(self, value):
"""Convert value to JSON string before save"""
try:
return json.dumps(value)
except Exception as err:
raise Valida... |
def getenv(variable_key, default=None, required=False, silent=True):
'''getenv will attempt to get an environment variable. If the variable
is not found, None is returned.
:param variable_key: the variable name
:param required: exit with error if not found
:param silent: Do not print debugging infor... | getenv will attempt to get an environment variable. If the variable
is not found, None is returned.
:param variable_key: the variable name
:param required: exit with error if not found
:param silent: Do not print debugging information for variable | Below is the the instruction that describes the task:
### Input:
getenv will attempt to get an environment variable. If the variable
is not found, None is returned.
:param variable_key: the variable name
:param required: exit with error if not found
:param silent: Do not print debugging information ... |
def ttl(self, name):
"""
get the number of seconds until the key's expiration
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
return pipe.ttl(self.redis_key(name)) | get the number of seconds until the key's expiration
:param name: str the name of the redis key
:return: Future() | Below is the the instruction that describes the task:
### Input:
get the number of seconds until the key's expiration
:param name: str the name of the redis key
:return: Future()
### Response:
def ttl(self, name):
"""
get the number of seconds until the key's expiration
... |
def storage_volumes(self):
"""
:class:`~zhmcclient.StorageVolumeManager`: Access to the
:term:`storage volumes <storage volume>` in this storage group.
"""
# We do here some lazy loading.
if not self._storage_volumes:
self._storage_volumes = StorageVolumeManag... | :class:`~zhmcclient.StorageVolumeManager`: Access to the
:term:`storage volumes <storage volume>` in this storage group. | Below is the the instruction that describes the task:
### Input:
:class:`~zhmcclient.StorageVolumeManager`: Access to the
:term:`storage volumes <storage volume>` in this storage group.
### Response:
def storage_volumes(self):
"""
:class:`~zhmcclient.StorageVolumeManager`: Access to the
... |
def percent_chance(self, pct):
"""Given a ``pct``% chance of something happening right now, decide at
random whether it actually happens, and return ``True`` or
``False`` as appropriate.
Values not between 0 and 100 are treated as though they
were 0 or 100, whichever is nearer.
... | Given a ``pct``% chance of something happening right now, decide at
random whether it actually happens, and return ``True`` or
``False`` as appropriate.
Values not between 0 and 100 are treated as though they
were 0 or 100, whichever is nearer. | Below is the the instruction that describes the task:
### Input:
Given a ``pct``% chance of something happening right now, decide at
random whether it actually happens, and return ``True`` or
``False`` as appropriate.
Values not between 0 and 100 are treated as though they
were 0 or... |
def is_js_date_utc(json):
"""Check if the string contains Date.UTC function
and return match group(s) if there is
"""
JS_date_utc_pattern = r'Date\.UTC\(([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?\)'
re_date = re.compile(JS_date_utc_pattern, re.M)
... | Check if the string contains Date.UTC function
and return match group(s) if there is | Below is the the instruction that describes the task:
### Input:
Check if the string contains Date.UTC function
and return match group(s) if there is
### Response:
def is_js_date_utc(json):
"""Check if the string contains Date.UTC function
and return match group(s) if there is
"""... |
def get_witness_for_key_prefix(db, node_hash, key):
"""
Get all witness given a keypath prefix.
Include
1. witness along the keypath and
2. witness in the subtrie of the last node in keypath
"""
validate_is_bytes(key)
return tuple(_get_witness_for_key_prefix(db, node_hash, encode_to_bi... | Get all witness given a keypath prefix.
Include
1. witness along the keypath and
2. witness in the subtrie of the last node in keypath | Below is the the instruction that describes the task:
### Input:
Get all witness given a keypath prefix.
Include
1. witness along the keypath and
2. witness in the subtrie of the last node in keypath
### Response:
def get_witness_for_key_prefix(db, node_hash, key):
"""
Get all witness given a ... |
def get_sections_by_building_and_term(building, term):
"""
Returns a list of uw_sws.models.SectionReference objects
for the passed building and term.
"""
url = "{}?{}".format(
section_res_url_prefix,
urlencode([("quarter", term.quarter.lower(),),
("facility_code", ... | Returns a list of uw_sws.models.SectionReference objects
for the passed building and term. | Below is the the instruction that describes the task:
### Input:
Returns a list of uw_sws.models.SectionReference objects
for the passed building and term.
### Response:
def get_sections_by_building_and_term(building, term):
"""
Returns a list of uw_sws.models.SectionReference objects
for the passe... |
def parse_version_information(self, version_struct):
"""Parse version information structure.
The date will be made available in three attributes of the PE object.
VS_VERSIONINFO will contain the first three fields of the main structure:
'Length', 'ValueLength', ... | Parse version information structure.
The date will be made available in three attributes of the PE object.
VS_VERSIONINFO will contain the first three fields of the main structure:
'Length', 'ValueLength', and 'Type'
VS_FIXEDFILEINFO will hold the re... | Below is the the instruction that describes the task:
### Input:
Parse version information structure.
The date will be made available in three attributes of the PE object.
VS_VERSIONINFO will contain the first three fields of the main structure:
'Length', 'ValueLeng... |
def run_parse(self):
"""Parse one or more log files"""
# Data set already has source file names from load_inputs
parsedset = {}
parsedset['data_set'] = []
for log in self.input_files:
parsemodule = self.parse_modules[self.args.parser]
try:
... | Parse one or more log files | Below is the the instruction that describes the task:
### Input:
Parse one or more log files
### Response:
def run_parse(self):
"""Parse one or more log files"""
# Data set already has source file names from load_inputs
parsedset = {}
parsedset['data_set'] = []
for log in se... |
def validate_class_type_arguments(operator):
"""
Decorator to validate all the arguments to function
are of the type of calling class for passed operator
"""
def inner(function):
def wrapper(self, *args, **kwargs):
for arg in args + tuple(kwargs.values()):
if no... | Decorator to validate all the arguments to function
are of the type of calling class for passed operator | Below is the the instruction that describes the task:
### Input:
Decorator to validate all the arguments to function
are of the type of calling class for passed operator
### Response:
def validate_class_type_arguments(operator):
"""
Decorator to validate all the arguments to function
are of the typ... |
def quad_genz_keister_24 ( order ):
"""
Hermite Genz-Keister 24 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscis... | Hermite Genz-Keister 24 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Examples:
>>> abscissas, weights = quad_genz_keister_24(1)
>... | Below is the the instruction that describes the task:
### Input:
Hermite Genz-Keister 24 rule.
Args:
order (int):
The quadrature order. Must be in the interval (0, 8).
Returns:
(:py:data:typing.Tuple[numpy.ndarray, numpy.ndarray]):
Abscissas and weights
Example... |
def dotenv_values(dotenv_path):
"""
:param dotenv_path: env file
:return: ordered dict
"""
values = OrderedDict(parse_dotenv(dotenv_path))
values = resolve_nested_variables(values)
return values | :param dotenv_path: env file
:return: ordered dict | Below is the the instruction that describes the task:
### Input:
:param dotenv_path: env file
:return: ordered dict
### Response:
def dotenv_values(dotenv_path):
"""
:param dotenv_path: env file
:return: ordered dict
"""
values = OrderedDict(parse_dotenv(dotenv_path))
values = resolve_n... |
def _gradient_penalty(self, real_samples, fake_samples, kwargs):
"""
Compute the norm of the gradients for each sample in a batch, and
penalize anything on either side of unit norm
"""
import torch
from torch.autograd import Variable, grad
real_samples = real_sam... | Compute the norm of the gradients for each sample in a batch, and
penalize anything on either side of unit norm | Below is the the instruction that describes the task:
### Input:
Compute the norm of the gradients for each sample in a batch, and
penalize anything on either side of unit norm
### Response:
def _gradient_penalty(self, real_samples, fake_samples, kwargs):
"""
Compute the norm of the gradien... |
def contains(self, x, y):
"""
Returns true if the given point is contained within the
bounding box, where all boundaries of the box are
considered to be inclusive.
"""
left, bottom, right, top = self.aarect().lbrt()
return (left <= x <= right) and (bottom <= y <= ... | Returns true if the given point is contained within the
bounding box, where all boundaries of the box are
considered to be inclusive. | Below is the the instruction that describes the task:
### Input:
Returns true if the given point is contained within the
bounding box, where all boundaries of the box are
considered to be inclusive.
### Response:
def contains(self, x, y):
"""
Returns true if the given point is conta... |
def setup(applicationName,
applicationType=None,
style='plastique',
splash='',
splashType=None,
splashTextColor='white',
splashTextAlign=None,
theme=''):
"""
Wrapper system for the QApplication creation process to handle all proper
... | Wrapper system for the QApplication creation process to handle all proper
pre-application setup. This method will verify that there is no application
running, creating one if necessary. If no application is created, a None
value is returned - signaling that there is already an app running. If you
... | Below is the the instruction that describes the task:
### Input:
Wrapper system for the QApplication creation process to handle all proper
pre-application setup. This method will verify that there is no application
running, creating one if necessary. If no application is created, a None
value is re... |
def create_runtime_class(self, body, **kwargs):
"""
create a RuntimeClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_runtime_class(body, async_req=True)
>>> result = thr... | create a RuntimeClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_runtime_class(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param V1beta1Runti... | Below is the the instruction that describes the task:
### Input:
create a RuntimeClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_runtime_class(body, async_req=True)
>>> result = th... |
def rank(self, score):
'''Return the 0-based index (rank) of ``score``. If the score is not
available it returns a negative integer which absolute score is the
left most closest index with score less than *score*.'''
node = self.__head
rank = 0
for i in range(self.__level-1, -1, -1):
... | Return the 0-based index (rank) of ``score``. If the score is not
available it returns a negative integer which absolute score is the
left most closest index with score less than *score*. | Below is the the instruction that describes the task:
### Input:
Return the 0-based index (rank) of ``score``. If the score is not
available it returns a negative integer which absolute score is the
left most closest index with score less than *score*.
### Response:
def rank(self, score):
'''Return the 0-b... |
def pack_str(cls, value):
"""
Pack string field
<field> ::= <int32_varint><data>
:param value: string to be packed
:type value: bytes or str
:return: packed value
:rtype: bytes
"""
assert isinstance(value, str)
value_len_packed = cls.pack... | Pack string field
<field> ::= <int32_varint><data>
:param value: string to be packed
:type value: bytes or str
:return: packed value
:rtype: bytes | Below is the the instruction that describes the task:
### Input:
Pack string field
<field> ::= <int32_varint><data>
:param value: string to be packed
:type value: bytes or str
:return: packed value
:rtype: bytes
### Response:
def pack_str(cls, value):
"""
P... |
def distribute(self, volume, source, dest, *args, **kwargs):
"""
Distribute will move a volume of liquid from a single of source
to a list of target locations. See :any:`Transfer` for details
and a full list of optional arguments.
Returns
-------
This instance o... | Distribute will move a volume of liquid from a single of source
to a list of target locations. See :any:`Transfer` for details
and a full list of optional arguments.
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> fro... | Below is the the instruction that describes the task:
### Input:
Distribute will move a volume of liquid from a single of source
to a list of target locations. See :any:`Transfer` for details
and a full list of optional arguments.
Returns
-------
This instance of :class:`Pi... |
def __access(self, ts):
""" Record an API access. """
with self.connection:
self.connection.execute("INSERT OR REPLACE INTO access_timestamp (timestamp, domain) VALUES (?, ?)",
(ts, self.domain)) | Record an API access. | Below is the the instruction that describes the task:
### Input:
Record an API access.
### Response:
def __access(self, ts):
""" Record an API access. """
with self.connection:
self.connection.execute("INSERT OR REPLACE INTO access_timestamp (timestamp, domain) VALUES (?, ?)",
... |
def draw_path(self, data, coordinates, pathcodes, style,
offset=None, offset_coordinates="data", mplobj=None):
"""
Draw a path.
In matplotlib, paths are created by filled regions, histograms,
contour plots, patches, etc.
Parameters
----------
d... | Draw a path.
In matplotlib, paths are created by filled regions, histograms,
contour plots, patches, etc.
Parameters
----------
data : array_like
A shape (N, 2) array of datapoints.
coordinates : string
A string code, which should be either 'data... | Below is the the instruction that describes the task:
### Input:
Draw a path.
In matplotlib, paths are created by filled regions, histograms,
contour plots, patches, etc.
Parameters
----------
data : array_like
A shape (N, 2) array of datapoints.
coordin... |
def get_neurommsig_score(graph: BELGraph,
genes: List[Gene],
ora_weight: Optional[float] = None,
hub_weight: Optional[float] = None,
top_percent: Optional[float] = None,
topology_weight: Optional... | Calculate the composite NeuroMMSig Score for a given list of genes.
:param graph: A BEL graph
:param genes: A list of gene nodes
:param ora_weight: The relative weight of the over-enrichment analysis score from
:py:func:`neurommsig_gene_ora`. Defaults to 1.0.
:param hub_weight: The relative weight... | Below is the the instruction that describes the task:
### Input:
Calculate the composite NeuroMMSig Score for a given list of genes.
:param graph: A BEL graph
:param genes: A list of gene nodes
:param ora_weight: The relative weight of the over-enrichment analysis score from
:py:func:`neurommsig_g... |
def Popen(*args, **kwargs):
"""
Executes a command using subprocess.Popen and redirects output to AETROS and stdout.
Parses stdout as well for stdout API calls.
Use read_line argument to read stdout of command's stdout line by line.
Use returned process stdin to communicate with the command.
:... | Executes a command using subprocess.Popen and redirects output to AETROS and stdout.
Parses stdout as well for stdout API calls.
Use read_line argument to read stdout of command's stdout line by line.
Use returned process stdin to communicate with the command.
:return: subprocess.Popen | Below is the the instruction that describes the task:
### Input:
Executes a command using subprocess.Popen and redirects output to AETROS and stdout.
Parses stdout as well for stdout API calls.
Use read_line argument to read stdout of command's stdout line by line.
Use returned process stdin to communi... |
def set_inode(self, ino):
# type: (inode.Inode) -> None
'''
A method to set the Inode associated with this El Torito Entry.
Parameters:
ino - The Inode object corresponding to this entry.
Returns:
Nothing.
'''
if not self._initialized:
... | A method to set the Inode associated with this El Torito Entry.
Parameters:
ino - The Inode object corresponding to this entry.
Returns:
Nothing. | Below is the the instruction that describes the task:
### Input:
A method to set the Inode associated with this El Torito Entry.
Parameters:
ino - The Inode object corresponding to this entry.
Returns:
Nothing.
### Response:
def set_inode(self, ino):
# type: (inode.Inode)... |
def add_port(self, br_name, port_name, may_exist, fake_iface,
iface_names, settings=None):
"""
:type settings: list of (column, value_json)
where column is str,
value_json is json that is represented
... | :type settings: list of (column, value_json)
where column is str,
value_json is json that is represented
by Datum.to_json() | Below is the the instruction that describes the task:
### Input:
:type settings: list of (column, value_json)
where column is str,
value_json is json that is represented
by Datum.to_json()
### Response:
def ... |
def daily_forecast(self, name, limit=None):
"""
Queries the OWM Weather API for daily weather forecast for the specified
location (eg: "London,uk"). A *Forecaster* object is returned,
containing a *Forecast* instance covering a global streak of fourteen
days by default: this inst... | Queries the OWM Weather API for daily weather forecast for the specified
location (eg: "London,uk"). A *Forecaster* object is returned,
containing a *Forecast* instance covering a global streak of fourteen
days by default: this instance encapsulates *Weather* objects, with a
time interva... | Below is the the instruction that describes the task:
### Input:
Queries the OWM Weather API for daily weather forecast for the specified
location (eg: "London,uk"). A *Forecaster* object is returned,
containing a *Forecast* instance covering a global streak of fourteen
days by default: this... |
def _get_requirements(fname):
"""
Create a list of requirements from the output of the pip freeze command
saved in a text file.
"""
packages = _read(fname).split('\n')
packages = (p.strip() for p in packages)
packages = (p for p in packages if p and not p.startswith('#'))
return list(pac... | Create a list of requirements from the output of the pip freeze command
saved in a text file. | Below is the the instruction that describes the task:
### Input:
Create a list of requirements from the output of the pip freeze command
saved in a text file.
### Response:
def _get_requirements(fname):
"""
Create a list of requirements from the output of the pip freeze command
saved in a text file... |
def modify_environment (self, env):
"""The headas-init.sh script generates its variables in a bit of a funky way
-- it runs a script that generates a list of settings. These are their
transcriptions.
"""
plat = self._platform
def path (*args):
return os.path... | The headas-init.sh script generates its variables in a bit of a funky way
-- it runs a script that generates a list of settings. These are their
transcriptions. | Below is the the instruction that describes the task:
### Input:
The headas-init.sh script generates its variables in a bit of a funky way
-- it runs a script that generates a list of settings. These are their
transcriptions.
### Response:
def modify_environment (self, env):
"""The headas-i... |
def add_logger(self, cb, level='NORMAL', filters='ALL'):
'''Add a callback to receive log events from this component.
@param cb The callback function to receive log events. It must have the
signature cb(name, time, source, level, message), where name is the
name of the component... | Add a callback to receive log events from this component.
@param cb The callback function to receive log events. It must have the
signature cb(name, time, source, level, message), where name is the
name of the component the log record came from, time is a
floating-point time... | Below is the the instruction that describes the task:
### Input:
Add a callback to receive log events from this component.
@param cb The callback function to receive log events. It must have the
signature cb(name, time, source, level, message), where name is the
name of the componen... |
def extract_fields(self):
"""Extract the given fieldnames from the object
:returns: Schema name/value mapping
:rtype: dict
"""
# get the proper data manager for the object
dm = IDataManager(self.context)
# filter out ignored fields
fieldnames = filter(l... | Extract the given fieldnames from the object
:returns: Schema name/value mapping
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Extract the given fieldnames from the object
:returns: Schema name/value mapping
:rtype: dict
### Response:
def extract_fields(self):
"""Extract the given fieldnames from the object
:returns: Schema name/value mappin... |
def get_fund_ownership(self, **kwargs):
"""Fund Ownership
Returns the top 10 fund holders, meaning any firm not defined as
buy-side or sell-side such as mutual funds, pension funds, endowments,
investment firms, and other large entities that manage funds on behalf
of other... | Fund Ownership
Returns the top 10 fund holders, meaning any firm not defined as
buy-side or sell-side such as mutual funds, pension funds, endowments,
investment firms, and other large entities that manage funds on behalf
of others.
Reference: https://iexcloud.io/docs/ap... | Below is the the instruction that describes the task:
### Input:
Fund Ownership
Returns the top 10 fund holders, meaning any firm not defined as
buy-side or sell-side such as mutual funds, pension funds, endowments,
investment firms, and other large entities that manage funds on behalf
... |
def _checkResponseRegisterAddress(payload, registeraddress):
"""Check that the start adress as given in the response is correct.
The first two bytes in the payload holds the address value.
Args:
* payload (string): The payload
* registeraddress (int): The register address (use decimal numb... | Check that the start adress as given in the response is correct.
The first two bytes in the payload holds the address value.
Args:
* payload (string): The payload
* registeraddress (int): The register address (use decimal numbers, not hex).
Raises:
TypeError, ValueError | Below is the the instruction that describes the task:
### Input:
Check that the start adress as given in the response is correct.
The first two bytes in the payload holds the address value.
Args:
* payload (string): The payload
* registeraddress (int): The register address (use decimal num... |
def translated(structure, values, lang_spec):
"""Return code associated to given structure and values,
translate with given language specification."""
# LANGUAGE SPECS
indentation = '\t'
endline = '\n'
object_code = ""
stack = []
# define shortcuts to behavior
push = lambda x: sta... | Return code associated to given structure and values,
translate with given language specification. | Below is the the instruction that describes the task:
### Input:
Return code associated to given structure and values,
translate with given language specification.
### Response:
def translated(structure, values, lang_spec):
"""Return code associated to given structure and values,
translate with given... |
def _format_file_lines(files):
'''Given a list of filenames that we're about to print, limit it to a
reasonable number of lines.'''
LINES_TO_SHOW = 10
if len(files) <= LINES_TO_SHOW:
lines = '\n'.join(files)
else:
lines = ('\n'.join(files[:LINES_TO_SHOW - 1]) + '\n...{} total'.format... | Given a list of filenames that we're about to print, limit it to a
reasonable number of lines. | Below is the the instruction that describes the task:
### Input:
Given a list of filenames that we're about to print, limit it to a
reasonable number of lines.
### Response:
def _format_file_lines(files):
'''Given a list of filenames that we're about to print, limit it to a
reasonable number of lines.'... |
def read_case(input, format=None):
""" Returns a case object from the given input file object. The data
format may be optionally specified.
"""
# Map of data file types to readers.
format_map = {"matpower": MATPOWERReader,
"psse": PSSEReader, "pickle": PickleReader}
# Read case data.
... | Returns a case object from the given input file object. The data
format may be optionally specified. | Below is the the instruction that describes the task:
### Input:
Returns a case object from the given input file object. The data
format may be optionally specified.
### Response:
def read_case(input, format=None):
""" Returns a case object from the given input file object. The data
format may be optio... |
def get_arctic_lib(connection_string, **kwargs):
"""
Returns a mongo library for the given connection string
Parameters
---------
connection_string: `str`
Format must be one of the following:
library@trading for known mongo servers
library@hostname:port
Returns:... | Returns a mongo library for the given connection string
Parameters
---------
connection_string: `str`
Format must be one of the following:
library@trading for known mongo servers
library@hostname:port
Returns:
--------
Arctic library | Below is the the instruction that describes the task:
### Input:
Returns a mongo library for the given connection string
Parameters
---------
connection_string: `str`
Format must be one of the following:
library@trading for known mongo servers
library@hostname:port
... |
def stroke_antialias(self, flag=True):
"""stroke antialias
:param flag: True or False. (default is True)
:type flag: bool
"""
antialias = pgmagick.DrawableStrokeAntialias(flag)
self.drawer.append(antialias) | stroke antialias
:param flag: True or False. (default is True)
:type flag: bool | Below is the the instruction that describes the task:
### Input:
stroke antialias
:param flag: True or False. (default is True)
:type flag: bool
### Response:
def stroke_antialias(self, flag=True):
"""stroke antialias
:param flag: True or False. (default is True)
:type fla... |
def register(scheme):
"""
Registers a new scheme to the urlparser.
:param schema | <str>
"""
scheme = nstr(scheme)
urlparse.uses_fragment.append(scheme)
urlparse.uses_netloc.append(scheme)
urlparse.uses_params.append(scheme)
urlparse.uses_query.append(scheme)
urlparse.u... | Registers a new scheme to the urlparser.
:param schema | <str> | Below is the the instruction that describes the task:
### Input:
Registers a new scheme to the urlparser.
:param schema | <str>
### Response:
def register(scheme):
"""
Registers a new scheme to the urlparser.
:param schema | <str>
"""
scheme = nstr(scheme)
urlparse.u... |
def summary(args):
"""
%prog summary gffile fastafile
Print summary stats, including:
- Gene/Exon/Intron
- Number
- Average size (bp)
- Median size (bp)
- Total length (Mb)
- % of genome
- % GC
"""
p = OptionParser(summary.__doc__)
opts, args = p.parse_args(args)
... | %prog summary gffile fastafile
Print summary stats, including:
- Gene/Exon/Intron
- Number
- Average size (bp)
- Median size (bp)
- Total length (Mb)
- % of genome
- % GC | Below is the the instruction that describes the task:
### Input:
%prog summary gffile fastafile
Print summary stats, including:
- Gene/Exon/Intron
- Number
- Average size (bp)
- Median size (bp)
- Total length (Mb)
- % of genome
- % GC
### Response:
def summary(args):
"""
%... |
def run(self, *args):
"""Affiliate unique identities to organizations."""
self.parser.parse_args(args)
code = self.affiliate()
return code | Affiliate unique identities to organizations. | Below is the the instruction that describes the task:
### Input:
Affiliate unique identities to organizations.
### Response:
def run(self, *args):
"""Affiliate unique identities to organizations."""
self.parser.parse_args(args)
code = self.affiliate()
return code |
def _store_work_results(self, results, collection, md5):
""" Internal: Stores the work results of a worker."""
self.data_store.store_work_results(results, collection, md5) | Internal: Stores the work results of a worker. | Below is the the instruction that describes the task:
### Input:
Internal: Stores the work results of a worker.
### Response:
def _store_work_results(self, results, collection, md5):
""" Internal: Stores the work results of a worker."""
self.data_store.store_work_results(results, collection, md5) |
def get_folder_list(folder='.'):
""" Get list of sub-folders contained in input folder
:param folder: input folder to list sub-folders. Default is ``'.'``
:type folder: str
:return: list of sub-folders
:rtype: list(str)
"""
dir_list = get_content_list(folder)
return [f for f in dir_list... | Get list of sub-folders contained in input folder
:param folder: input folder to list sub-folders. Default is ``'.'``
:type folder: str
:return: list of sub-folders
:rtype: list(str) | Below is the the instruction that describes the task:
### Input:
Get list of sub-folders contained in input folder
:param folder: input folder to list sub-folders. Default is ``'.'``
:type folder: str
:return: list of sub-folders
:rtype: list(str)
### Response:
def get_folder_list(folder='.'):
... |
def installed(name, default=False, user=None):
'''
Verify that the specified ruby is installed with rbenv. Rbenv is
installed if necessary.
name
The version of ruby to install
default : False
Whether to make this ruby the default.
user: None
The user to run rbenv as.
... | Verify that the specified ruby is installed with rbenv. Rbenv is
installed if necessary.
name
The version of ruby to install
default : False
Whether to make this ruby the default.
user: None
The user to run rbenv as.
.. versionadded:: 0.17.0
.. versionadded:: 0.1... | Below is the the instruction that describes the task:
### Input:
Verify that the specified ruby is installed with rbenv. Rbenv is
installed if necessary.
name
The version of ruby to install
default : False
Whether to make this ruby the default.
user: None
The user to run r... |
def getVariantAnnotationSets(self, datasetId):
"""
Returns the list of ReferenceSets for this server.
"""
# TODO this should be displayed per-variant set, not per dataset.
variantAnnotationSets = []
dataset = app.backend.getDataRepository().getDataset(datasetId)
f... | Returns the list of ReferenceSets for this server. | Below is the the instruction that describes the task:
### Input:
Returns the list of ReferenceSets for this server.
### Response:
def getVariantAnnotationSets(self, datasetId):
"""
Returns the list of ReferenceSets for this server.
"""
# TODO this should be displayed per-variant set... |
def formatTime(self, record, datefmt=None):
"""
Format time, including milliseconds.
"""
formatted = super(PalletFormatter, self).formatTime(
record, datefmt=datefmt)
return formatted + '.%03dZ' % record.msecs | Format time, including milliseconds. | Below is the the instruction that describes the task:
### Input:
Format time, including milliseconds.
### Response:
def formatTime(self, record, datefmt=None):
"""
Format time, including milliseconds.
"""
formatted = super(PalletFormatter, self).formatTime(
record, date... |
def latexify_spacegroup(spacegroup_symbol):
"""
Generates a latex formatted spacegroup. E.g., P2_1/c is converted to
P2$_{1}$/c and P-1 is converted to P$\\overline{1}$.
Args:
spacegroup_symbol (str): A spacegroup symbol
Returns:
A latex formatted spacegroup with proper subscripts ... | Generates a latex formatted spacegroup. E.g., P2_1/c is converted to
P2$_{1}$/c and P-1 is converted to P$\\overline{1}$.
Args:
spacegroup_symbol (str): A spacegroup symbol
Returns:
A latex formatted spacegroup with proper subscripts and overlines. | Below is the the instruction that describes the task:
### Input:
Generates a latex formatted spacegroup. E.g., P2_1/c is converted to
P2$_{1}$/c and P-1 is converted to P$\\overline{1}$.
Args:
spacegroup_symbol (str): A spacegroup symbol
Returns:
A latex formatted spacegroup with prope... |
def filePath(self, index):
"""
Gets the file path of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: str
"""
return self._fs_model_source.filePath(
self._fs_model_proxy.mapToSource(index)) | Gets the file path of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: str | Below is the the instruction that describes the task:
### Input:
Gets the file path of the item at the specified ``index``.
:param index: item index - QModelIndex
:return: str
### Response:
def filePath(self, index):
"""
Gets the file path of the item at the specified ``index``.
... |
def _log_diff_memory_data(self, prefix, new_memory_data, old_memory_data):
"""
Computes and logs the difference in memory utilization
between the given old and new memory data.
"""
def _vmem_used(memory_data):
return memory_data['machine_data'].used
def _proc... | Computes and logs the difference in memory utilization
between the given old and new memory data. | Below is the the instruction that describes the task:
### Input:
Computes and logs the difference in memory utilization
between the given old and new memory data.
### Response:
def _log_diff_memory_data(self, prefix, new_memory_data, old_memory_data):
"""
Computes and logs the difference in... |
def generate_synthetic_state_trajectory(self, nsteps, initial_Pi=None, start=None, stop=None, dtype=np.int32):
"""Generate a synthetic state trajectory.
Parameters
----------
nsteps : int
Number of steps in the synthetic state trajectory to be generated.
initial_Pi :... | Generate a synthetic state trajectory.
Parameters
----------
nsteps : int
Number of steps in the synthetic state trajectory to be generated.
initial_Pi : np.array of shape (nstates,), optional, default=None
The initial probability distribution, if samples are not... | Below is the the instruction that describes the task:
### Input:
Generate a synthetic state trajectory.
Parameters
----------
nsteps : int
Number of steps in the synthetic state trajectory to be generated.
initial_Pi : np.array of shape (nstates,), optional, default=None... |
def get_extra_commands():
"""Use the configuration to discover additional CLI packages to load"""
from ambry.run import find_config_file
from ambry.dbexceptions import ConfigurationError
from ambry.util import yaml
try:
plugins_dir = find_config_file('cli.yaml')
except ConfigurationErro... | Use the configuration to discover additional CLI packages to load | Below is the the instruction that describes the task:
### Input:
Use the configuration to discover additional CLI packages to load
### Response:
def get_extra_commands():
"""Use the configuration to discover additional CLI packages to load"""
from ambry.run import find_config_file
from ambry.dbexceptio... |
def set_blend_func(self, srgb='one', drgb='zero',
salpha=None, dalpha=None):
"""Specify pixel arithmetic for RGB and alpha
Parameters
----------
srgb : str
Source RGB factor.
drgb : str
Destination RGB factor.
salpha : s... | Specify pixel arithmetic for RGB and alpha
Parameters
----------
srgb : str
Source RGB factor.
drgb : str
Destination RGB factor.
salpha : str | None
Source alpha factor. If None, ``srgb`` is used.
dalpha : str
Destinat... | Below is the the instruction that describes the task:
### Input:
Specify pixel arithmetic for RGB and alpha
Parameters
----------
srgb : str
Source RGB factor.
drgb : str
Destination RGB factor.
salpha : str | None
Source alpha factor.... |
def create(max_kl, cg_iters, line_search_iters, cg_damping, entropy_coef, vf_iters, discount_factor,
gae_lambda=1.0, improvement_acceptance_ratio=0.1, max_grad_norm=0.5):
""" Vel factory function """
return TrpoPolicyGradient(
max_kl, int(cg_iters), int(line_search_iters), cg_damping, entropy... | Vel factory function | Below is the the instruction that describes the task:
### Input:
Vel factory function
### Response:
def create(max_kl, cg_iters, line_search_iters, cg_damping, entropy_coef, vf_iters, discount_factor,
gae_lambda=1.0, improvement_acceptance_ratio=0.1, max_grad_norm=0.5):
""" Vel factory function """
... |
def timestamp_update(sender, frames):
"""
Timestamp the modified field for all documents. This method should be
bound to a frame class like so:
```
MyFrameClass.listen('update', MyFrameClass.timestamp_update)
```
"""
for frame in frames:
frame... | Timestamp the modified field for all documents. This method should be
bound to a frame class like so:
```
MyFrameClass.listen('update', MyFrameClass.timestamp_update)
``` | Below is the the instruction that describes the task:
### Input:
Timestamp the modified field for all documents. This method should be
bound to a frame class like so:
```
MyFrameClass.listen('update', MyFrameClass.timestamp_update)
```
### Response:
def timestamp_update(sender, fra... |
def _partial_search_validator(self, sub, sup, anagram=False,
subsequence=False, supersequence=False):
"""
It's responsible for validating the partial results of `search` method.
If it returns True, the search would return its result. Else, search
method ... | It's responsible for validating the partial results of `search` method.
If it returns True, the search would return its result. Else, search
method would discard what it found and look for others.
First, checks to see if all elements of `sub` is in `sup` with at least
the same frequency... | Below is the the instruction that describes the task:
### Input:
It's responsible for validating the partial results of `search` method.
If it returns True, the search would return its result. Else, search
method would discard what it found and look for others.
First, checks to see if all e... |
def proxy(self):
"""Retrieve the upstream content and build an HttpResponse."""
headers = self.request.headers.filter(self.ignored_request_headers)
qs = self.request.query_string if self.pass_query_string else ''
# Fix for django 1.10.0 bug https://code.djangoproject.com/ticket/27005
... | Retrieve the upstream content and build an HttpResponse. | Below is the the instruction that describes the task:
### Input:
Retrieve the upstream content and build an HttpResponse.
### Response:
def proxy(self):
"""Retrieve the upstream content and build an HttpResponse."""
headers = self.request.headers.filter(self.ignored_request_headers)
qs = se... |
def configure(self):
""" The main configure function. Uses a schema file and an optional data file,
and combines them with user prompts to write a new data file. """
# Make the lazy folder if it doesn't already exist.
path = os.getcwd() + '/' + self.lazy_folder
if not os.pat... | The main configure function. Uses a schema file and an optional data file,
and combines them with user prompts to write a new data file. | Below is the the instruction that describes the task:
### Input:
The main configure function. Uses a schema file and an optional data file,
and combines them with user prompts to write a new data file.
### Response:
def configure(self):
""" The main configure function. Uses a schema file and an... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.