code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def is_data_dependent(fmto, data):
"""Check whether a formatoption is data dependent
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to check
data: xarray.DataArray
The data array to use if the :attr:`~Formatoption.data_dependent`
attribute is a c... | Check whether a formatoption is data dependent
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to check
data: xarray.DataArray
The data array to use if the :attr:`~Formatoption.data_dependent`
attribute is a callable
Returns
-------
bool
... | Below is the the instruction that describes the task:
### Input:
Check whether a formatoption is data dependent
Parameters
----------
fmto: Formatoption
The :class:`Formatoption` instance to check
data: xarray.DataArray
The data array to use if the :attr:`~Formatoption.data_dependen... |
def metadata(self, run_id=None):
"""Provide metadata on a Ding0 run
Parameters
----------
run_id: str, (defaults to current date)
Distinguish multiple versions of Ding0 data by a `run_id`. If not
set it defaults to current date in the format YYYYMMDDhhmmss
... | Provide metadata on a Ding0 run
Parameters
----------
run_id: str, (defaults to current date)
Distinguish multiple versions of Ding0 data by a `run_id`. If not
set it defaults to current date in the format YYYYMMDDhhmmss
Returns
-------
dict
... | Below is the the instruction that describes the task:
### Input:
Provide metadata on a Ding0 run
Parameters
----------
run_id: str, (defaults to current date)
Distinguish multiple versions of Ding0 data by a `run_id`. If not
set it defaults to current date in the for... |
def getAllData(self, temp = True, accel = True, gyro = True):
"""!
Get all the available data.
@param temp: True - Allow to return Temperature data
@param accel: True - Allow to return Accelerometer data
@param gyro: True - Allow to return Gyroscope data
@return a dicti... | !
Get all the available data.
@param temp: True - Allow to return Temperature data
@param accel: True - Allow to return Accelerometer data
@param gyro: True - Allow to return Gyroscope data
@return a dictionary data
@retval {} Did not read any data
@retv... | Below is the the instruction that describes the task:
### Input:
!
Get all the available data.
@param temp: True - Allow to return Temperature data
@param accel: True - Allow to return Accelerometer data
@param gyro: True - Allow to return Gyroscope data
@return a dictionar... |
def file_detector_context(self, file_detector_class, *args, **kwargs):
"""
Overrides the current file detector (if necessary) in limited context.
Ensures the original file detector is set afterwards.
Example:
with webdriver.file_detector_context(UselessFileDetector):
... | Overrides the current file detector (if necessary) in limited context.
Ensures the original file detector is set afterwards.
Example:
with webdriver.file_detector_context(UselessFileDetector):
someinput.send_keys('/etc/hosts')
:Args:
- file_detector_class - Class ... | Below is the the instruction that describes the task:
### Input:
Overrides the current file detector (if necessary) in limited context.
Ensures the original file detector is set afterwards.
Example:
with webdriver.file_detector_context(UselessFileDetector):
someinput.send_keys(... |
def cmdloop(self):
"""Start CLI REPL."""
while True:
cmdline = input(self.prompt)
tokens = shlex.split(cmdline)
if not tokens:
if self.last_cmd:
tokens = self.last_cmd
else:
print('No previous com... | Start CLI REPL. | Below is the the instruction that describes the task:
### Input:
Start CLI REPL.
### Response:
def cmdloop(self):
"""Start CLI REPL."""
while True:
cmdline = input(self.prompt)
tokens = shlex.split(cmdline)
if not tokens:
if self.last_cmd:
... |
def isTemporal(inferenceType):
""" Returns True if the inference type is 'temporal', i.e. requires a
temporal memory in the network.
"""
if InferenceType.__temporalInferenceTypes is None:
InferenceType.__temporalInferenceTypes = \
set([InferenceType.TemporalNextStep... | Returns True if the inference type is 'temporal', i.e. requires a
temporal memory in the network. | Below is the the instruction that describes the task:
### Input:
Returns True if the inference type is 'temporal', i.e. requires a
temporal memory in the network.
### Response:
def isTemporal(inferenceType):
""" Returns True if the inference type is 'temporal', i.e. requires a
temporal memory in the ne... |
def is_instance_factory(_type):
"""
Parameters
----------
`_type` - the type to be checked against
Returns
-------
validator - a function of a single argument x , which returns the
True if x is an instance of `_type`
"""
if isinstance(_type, (tuple, list)):
_t... | Parameters
----------
`_type` - the type to be checked against
Returns
-------
validator - a function of a single argument x , which returns the
True if x is an instance of `_type` | Below is the the instruction that describes the task:
### Input:
Parameters
----------
`_type` - the type to be checked against
Returns
-------
validator - a function of a single argument x , which returns the
True if x is an instance of `_type`
### Response:
def is_instance_fac... |
def _get_filename(class_name, language):
"""
Generate the specific filename.
Parameters
----------
:param class_name : str
The used class name.
:param language : {'c', 'go', 'java', 'js', 'php', 'ruby'}
The target programming language.
R... | Generate the specific filename.
Parameters
----------
:param class_name : str
The used class name.
:param language : {'c', 'go', 'java', 'js', 'php', 'ruby'}
The target programming language.
Returns
-------
filename : str
... | Below is the the instruction that describes the task:
### Input:
Generate the specific filename.
Parameters
----------
:param class_name : str
The used class name.
:param language : {'c', 'go', 'java', 'js', 'php', 'ruby'}
The target programming language.
... |
def __check_mem(self):
''' raise exception on RAM exceeded '''
mem_free = psutil.virtual_memory().available / 2**20
self.log.debug("Memory free: %s/%s", mem_free, self.mem_limit)
if mem_free < self.mem_limit:
raise RuntimeError(
"Not enough resources: free mem... | raise exception on RAM exceeded | Below is the the instruction that describes the task:
### Input:
raise exception on RAM exceeded
### Response:
def __check_mem(self):
''' raise exception on RAM exceeded '''
mem_free = psutil.virtual_memory().available / 2**20
self.log.debug("Memory free: %s/%s", mem_free, self.mem_limit)
... |
def as_tree(self, visitor=None, children=None):
""" Recursively traverses each tree (starting from each root) in order
to generate a dictionary-based tree structure of the entire forest.
Each level of the forest/tree is a list of nodes, and each node
consists of a dictionary ... | Recursively traverses each tree (starting from each root) in order
to generate a dictionary-based tree structure of the entire forest.
Each level of the forest/tree is a list of nodes, and each node
consists of a dictionary representation, where the entry
``children`` (by... | Below is the the instruction that describes the task:
### Input:
Recursively traverses each tree (starting from each root) in order
to generate a dictionary-based tree structure of the entire forest.
Each level of the forest/tree is a list of nodes, and each node
consists of a di... |
def convenience_calc_fisher_approx(self, params):
"""
Calculates the BHHH approximation of the Fisher Information Matrix for
this model / dataset.
"""
shapes, intercepts, betas = self.convenience_split_params(params)
args = [betas,
self.design,
... | Calculates the BHHH approximation of the Fisher Information Matrix for
this model / dataset. | Below is the the instruction that describes the task:
### Input:
Calculates the BHHH approximation of the Fisher Information Matrix for
this model / dataset.
### Response:
def convenience_calc_fisher_approx(self, params):
"""
Calculates the BHHH approximation of the Fisher Information Matri... |
def enver(*args):
"""
%prog [<name>=[value]]
To show all environment variables, call with no parameters:
%prog
To Add/Modify/Delete environment variable:
%prog <name>=[value]
If <name> is PATH or PATHEXT, %prog will by default append the value using
a semicolon as a separator. Use -r to disable this behavio... | %prog [<name>=[value]]
To show all environment variables, call with no parameters:
%prog
To Add/Modify/Delete environment variable:
%prog <name>=[value]
If <name> is PATH or PATHEXT, %prog will by default append the value using
a semicolon as a separator. Use -r to disable this behavior or -a to force
it for... | Below is the the instruction that describes the task:
### Input:
%prog [<name>=[value]]
To show all environment variables, call with no parameters:
%prog
To Add/Modify/Delete environment variable:
%prog <name>=[value]
If <name> is PATH or PATHEXT, %prog will by default append the value using
a semicolon a... |
def save_tip_length(labware: Labware, length: float):
"""
Function to be used whenever an updated tip length is found for
of a given tip rack. If an offset file does not exist, create the file
using labware id as the filename. If the file does exist, load it and
modify the length and the lastModifie... | Function to be used whenever an updated tip length is found for
of a given tip rack. If an offset file does not exist, create the file
using labware id as the filename. If the file does exist, load it and
modify the length and the lastModified fields under the "tipLength" key. | Below is the the instruction that describes the task:
### Input:
Function to be used whenever an updated tip length is found for
of a given tip rack. If an offset file does not exist, create the file
using labware id as the filename. If the file does exist, load it and
modify the length and the lastModi... |
def step2(expnums, ccd, version, prefix=None, dry_run=False, default="WCS"):
"""run the actual step2 on the given exp/ccd combo"""
jmp_trans = ['step2ajmp']
jmp_args = ['step2bjmp']
matt_args = ['step2matt_jmp']
idx = 0
for expnum in expnums:
jmp_args.append(
storage.get_f... | run the actual step2 on the given exp/ccd combo | Below is the the instruction that describes the task:
### Input:
run the actual step2 on the given exp/ccd combo
### Response:
def step2(expnums, ccd, version, prefix=None, dry_run=False, default="WCS"):
"""run the actual step2 on the given exp/ccd combo"""
jmp_trans = ['step2ajmp']
jmp_args = ['ste... |
def broadcast(self, command, *args, **kwargs):
"""
Notifies each user with a specified command.
"""
criterion = kwargs.pop('criterion', self.BROADCAST_FILTER_ALL)
for index, user in items(self.users()):
if criterion(user, command, *args, **kwargs):
sel... | Notifies each user with a specified command. | Below is the the instruction that describes the task:
### Input:
Notifies each user with a specified command.
### Response:
def broadcast(self, command, *args, **kwargs):
"""
Notifies each user with a specified command.
"""
criterion = kwargs.pop('criterion', self.BROADCAST_FILTER_A... |
def page(title=None, pageid=None, auto_suggest=True, redirect=True, preload=False):
'''
Get a WikipediaPage object for the page with title `title` or the pageid
`pageid` (mutually exclusive).
Keyword arguments:
* title - the title of the page to load
* pageid - the numeric pageid of the page to load
* a... | Get a WikipediaPage object for the page with title `title` or the pageid
`pageid` (mutually exclusive).
Keyword arguments:
* title - the title of the page to load
* pageid - the numeric pageid of the page to load
* auto_suggest - let Wikipedia find a valid page title for the query
* redirect - allow redir... | Below is the the instruction that describes the task:
### Input:
Get a WikipediaPage object for the page with title `title` or the pageid
`pageid` (mutually exclusive).
Keyword arguments:
* title - the title of the page to load
* pageid - the numeric pageid of the page to load
* auto_suggest - let Wikip... |
def _lookup_vpc_allocs(query_type, session=None, order=None, **bfilter):
"""Look up 'query_type' Nexus VPC Allocs matching the filter.
:param query_type: 'all', 'one' or 'first'
:param session: db session
:param order: select what field to order data
:param bfilter: filter for mappings query
:r... | Look up 'query_type' Nexus VPC Allocs matching the filter.
:param query_type: 'all', 'one' or 'first'
:param session: db session
:param order: select what field to order data
:param bfilter: filter for mappings query
:returns: VPCs if query gave a result, else
raise NexusVPCAllocNotFou... | Below is the the instruction that describes the task:
### Input:
Look up 'query_type' Nexus VPC Allocs matching the filter.
:param query_type: 'all', 'one' or 'first'
:param session: db session
:param order: select what field to order data
:param bfilter: filter for mappings query
:returns: VPC... |
def system_find_affiliates(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/findAffiliates API method.
"""
return DXHTTPRequest('/system/findAffiliates', input_params, always_retry=always_retry, **kwargs) | Invokes the /system/findAffiliates API method. | Below is the the instruction that describes the task:
### Input:
Invokes the /system/findAffiliates API method.
### Response:
def system_find_affiliates(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/findAffiliates API method.
"""
return DXHTTPRequest('/system/findAffiliates... |
def echo(text, **kwargs):
""" Print results to the console
:param text: the text string to print
:type text: str
:return: a string
:rtype: str
"""
if shakedown.cli.quiet:
return
if not 'n' in kwargs:
kwargs['n'] = True
if 'd' in kwargs:
te... | Print results to the console
:param text: the text string to print
:type text: str
:return: a string
:rtype: str | Below is the the instruction that describes the task:
### Input:
Print results to the console
:param text: the text string to print
:type text: str
:return: a string
:rtype: str
### Response:
def echo(text, **kwargs):
""" Print results to the console
:param text: the ... |
def _base_type(self):
"""Return str like 'enum.numeric' representing dimension type.
This string is a 'type.subclass' concatenation of the str keys
used to identify the dimension type in the cube response JSON.
The '.subclass' suffix only appears where a subtype is present.
"""
... | Return str like 'enum.numeric' representing dimension type.
This string is a 'type.subclass' concatenation of the str keys
used to identify the dimension type in the cube response JSON.
The '.subclass' suffix only appears where a subtype is present. | Below is the the instruction that describes the task:
### Input:
Return str like 'enum.numeric' representing dimension type.
This string is a 'type.subclass' concatenation of the str keys
used to identify the dimension type in the cube response JSON.
The '.subclass' suffix only appears wher... |
def tpx(mt, x, t):
""" tpx : Returns the probability that x will survive within t years """
""" npx : Returns n years survival probability at age x """
return mt.lx[x + t] / mt.lx[x] | tpx : Returns the probability that x will survive within t years | Below is the the instruction that describes the task:
### Input:
tpx : Returns the probability that x will survive within t years
### Response:
def tpx(mt, x, t):
""" tpx : Returns the probability that x will survive within t years """
""" npx : Returns n years survival probability at age x """
return ... |
def parse_field(field: str) -> Tuple[str, Optional[str]]:
"""Parses fields with underscores, and return field and suffix.
Example:
foo => foo, None
metric.foo => metric, foo
"""
_field = field.split('.')
_field = [f.strip() for f in _field]
if len(_field) == 1 and _field[0]:
... | Parses fields with underscores, and return field and suffix.
Example:
foo => foo, None
metric.foo => metric, foo | Below is the the instruction that describes the task:
### Input:
Parses fields with underscores, and return field and suffix.
Example:
foo => foo, None
metric.foo => metric, foo
### Response:
def parse_field(field: str) -> Tuple[str, Optional[str]]:
"""Parses fields with underscores, and r... |
def _pwl_gen_costs(self, generators, base_mva):
""" Returns the basin constraints for piece-wise linear gen cost
variables. CCV cost formulation expressed as Ay * x <= by.
Based on makeAy.m from MATPOWER by C. E. Murillo-Sanchez, developed at
PSERC Cornell. See U{http://www.pserc.corne... | Returns the basin constraints for piece-wise linear gen cost
variables. CCV cost formulation expressed as Ay * x <= by.
Based on makeAy.m from MATPOWER by C. E. Murillo-Sanchez, developed at
PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more
information. | Below is the the instruction that describes the task:
### Input:
Returns the basin constraints for piece-wise linear gen cost
variables. CCV cost formulation expressed as Ay * x <= by.
Based on makeAy.m from MATPOWER by C. E. Murillo-Sanchez, developed at
PSERC Cornell. See U{http://www.ps... |
def index_of(self, name):
"""
Returns the index of the actor with the given name.
:param name: the name of the Actor to find
:type name: str
:return: the index, -1 if not found
:rtype: int
"""
result = -1
for index, actor in enumerate(self.actors)... | Returns the index of the actor with the given name.
:param name: the name of the Actor to find
:type name: str
:return: the index, -1 if not found
:rtype: int | Below is the the instruction that describes the task:
### Input:
Returns the index of the actor with the given name.
:param name: the name of the Actor to find
:type name: str
:return: the index, -1 if not found
:rtype: int
### Response:
def index_of(self, name):
"""
... |
def from_grpc_error(rpc_exc):
"""Create a :class:`GoogleAPICallError` from a :class:`grpc.RpcError`.
Args:
rpc_exc (grpc.RpcError): The gRPC error.
Returns:
GoogleAPICallError: An instance of the appropriate subclass of
:class:`GoogleAPICallError`.
"""
if isinstance(rpc... | Create a :class:`GoogleAPICallError` from a :class:`grpc.RpcError`.
Args:
rpc_exc (grpc.RpcError): The gRPC error.
Returns:
GoogleAPICallError: An instance of the appropriate subclass of
:class:`GoogleAPICallError`. | Below is the the instruction that describes the task:
### Input:
Create a :class:`GoogleAPICallError` from a :class:`grpc.RpcError`.
Args:
rpc_exc (grpc.RpcError): The gRPC error.
Returns:
GoogleAPICallError: An instance of the appropriate subclass of
:class:`GoogleAPICallError... |
def rpcexec(self, payload):
""" Execute a call by sending the payload
:param dict payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error
"""
log.debug(json.dumps(payload)... | Execute a call by sending the payload
:param dict payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error | Below is the the instruction that describes the task:
### Input:
Execute a call by sending the payload
:param dict payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error
### Response:
def r... |
def process_event(self, event, ipmicmd, seldata):
"""Modify an event according with OEM understanding.
Given an event, allow an OEM module to augment it. For example,
event data fields can have OEM bytes. Other times an OEM may wish
to apply some transform to some field to suit their ... | Modify an event according with OEM understanding.
Given an event, allow an OEM module to augment it. For example,
event data fields can have OEM bytes. Other times an OEM may wish
to apply some transform to some field to suit their conventions. | Below is the the instruction that describes the task:
### Input:
Modify an event according with OEM understanding.
Given an event, allow an OEM module to augment it. For example,
event data fields can have OEM bytes. Other times an OEM may wish
to apply some transform to some field to sui... |
def set_pump_status(self, status):
"""
Updates pump status and logs update to console.
"""
self.pump_status = status
_logger.info("%r partition %r", status, self.lease.partition_id) | Updates pump status and logs update to console. | Below is the the instruction that describes the task:
### Input:
Updates pump status and logs update to console.
### Response:
def set_pump_status(self, status):
"""
Updates pump status and logs update to console.
"""
self.pump_status = status
_logger.info("%r partition %r",... |
async def connect(channel: discord.VoiceChannel):
"""
Connects to a discord voice channel.
This is the publicly exposed way to connect to a discord voice channel.
The :py:func:`initialize` function must be called first!
Parameters
----------
channel
Returns
-------
Player
... | Connects to a discord voice channel.
This is the publicly exposed way to connect to a discord voice channel.
The :py:func:`initialize` function must be called first!
Parameters
----------
channel
Returns
-------
Player
The created Player object.
Raises
------
Inde... | Below is the the instruction that describes the task:
### Input:
Connects to a discord voice channel.
This is the publicly exposed way to connect to a discord voice channel.
The :py:func:`initialize` function must be called first!
Parameters
----------
channel
Returns
-------
Play... |
def loop_read(self, max_packets=1):
"""Process read network events. Use in place of calling loop() if you
wish to handle your client reads as part of your own application.
Use socket() to obtain the client socket to call select() or equivalent
on.
Do not use if you are using th... | Process read network events. Use in place of calling loop() if you
wish to handle your client reads as part of your own application.
Use socket() to obtain the client socket to call select() or equivalent
on.
Do not use if you are using the threaded interface loop_start(). | Below is the the instruction that describes the task:
### Input:
Process read network events. Use in place of calling loop() if you
wish to handle your client reads as part of your own application.
Use socket() to obtain the client socket to call select() or equivalent
on.
Do not u... |
def occult(target1, shape1, frame1, target2, shape2, frame2, abcorr, observer,
et):
"""
Determines the occultation condition (not occulted, partially,
etc.) of one target relative to another target as seen by
an observer at a given time.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/c... | Determines the occultation condition (not occulted, partially,
etc.) of one target relative to another target as seen by
an observer at a given time.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/occult_c.html
:param target1: Name or ID of first target.
:type target1: str
:param shap... | Below is the the instruction that describes the task:
### Input:
Determines the occultation condition (not occulted, partially,
etc.) of one target relative to another target as seen by
an observer at a given time.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/occult_c.html
:param target... |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(KafkaConsumerLagCollector, self).get_default_config()
config.update({
'path': 'kafka.ConsumerLag',
'bin': '/opt/kafka/bin/kafka-run-class.sh',
'zookeepe... | Returns the default collector settings | Below is the the instruction that describes the task:
### Input:
Returns the default collector settings
### Response:
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(KafkaConsumerLagCollector, self).get_default_config()
config.upda... |
def from_span(cls, inputs, window_length, span, **kwargs):
"""
Convenience constructor for passing `decay_rate` in terms of `span`.
Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the
behavior equivalent to passing `span` to pandas.ewma.
Examples
-----... | Convenience constructor for passing `decay_rate` in terms of `span`.
Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the
behavior equivalent to passing `span` to pandas.ewma.
Examples
--------
.. code-block:: python
# Equivalent to:
# ... | Below is the the instruction that describes the task:
### Input:
Convenience constructor for passing `decay_rate` in terms of `span`.
Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the
behavior equivalent to passing `span` to pandas.ewma.
Examples
--------
... |
def add_filter(self, filter_, frequencies=None, dB=True,
analog=False, sample_rate=None, **kwargs):
"""Add a linear time-invariant filter to this BodePlot
Parameters
----------
filter_ : `~scipy.signal.lti`, `tuple`
the filter to plot, either as a `~scipy.... | Add a linear time-invariant filter to this BodePlot
Parameters
----------
filter_ : `~scipy.signal.lti`, `tuple`
the filter to plot, either as a `~scipy.signal.lti`, or a
`tuple` with the following number and meaning of elements
- 2: (numerator, denomin... | Below is the the instruction that describes the task:
### Input:
Add a linear time-invariant filter to this BodePlot
Parameters
----------
filter_ : `~scipy.signal.lti`, `tuple`
the filter to plot, either as a `~scipy.signal.lti`, or a
`tuple` with the following numb... |
def __update_offsets(self, fileobj, atoms, delta, offset):
"""Update offset tables in all 'stco' and 'co64' atoms."""
if delta == 0:
return
moov = atoms[b"moov"]
for atom in moov.findall(b'stco', True):
self.__update_offset_table(fileobj, ">%dI", atom, delta, offs... | Update offset tables in all 'stco' and 'co64' atoms. | Below is the the instruction that describes the task:
### Input:
Update offset tables in all 'stco' and 'co64' atoms.
### Response:
def __update_offsets(self, fileobj, atoms, delta, offset):
"""Update offset tables in all 'stco' and 'co64' atoms."""
if delta == 0:
return
moov = ... |
def from_hdf5_path(cls, hdf5_path):
"""
:param hdf5_path: hdf5 path which can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system.
:return: BigDL Model
"""
from keras.models import load_model
hdf5_local_path = BCommon.get_local_file(hdf5_path)
... | :param hdf5_path: hdf5 path which can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system.
:return: BigDL Model | Below is the the instruction that describes the task:
### Input:
:param hdf5_path: hdf5 path which can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system.
:return: BigDL Model
### Response:
def from_hdf5_path(cls, hdf5_path):
"""
:param hdf5_path: hdf5 path whic... |
def data(self):
"""
return (data_dict, key) tuple instead of models instances
"""
clone = copy.deepcopy(self)
clone._cfg['rtype'] = ReturnType.Object
return clone | return (data_dict, key) tuple instead of models instances | Below is the the instruction that describes the task:
### Input:
return (data_dict, key) tuple instead of models instances
### Response:
def data(self):
"""
return (data_dict, key) tuple instead of models instances
"""
clone = copy.deepcopy(self)
clone._cfg['rtype'] = Return... |
def save(self):
"""POST the object to the JSS."""
try:
response = requests.post(self._upload_url,
auth=self.jss.session.auth,
verify=self.jss.session.verify,
files=self.resource)
... | POST the object to the JSS. | Below is the the instruction that describes the task:
### Input:
POST the object to the JSS.
### Response:
def save(self):
"""POST the object to the JSS."""
try:
response = requests.post(self._upload_url,
auth=self.jss.session.auth,
... |
def get_permission_request(parser, token):
"""
Performs a permission request check with the given signature, user and objects
and assigns the result to a context variable.
Syntax::
{% get_permission_request PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %}
{% get_permissi... | Performs a permission request check with the given signature, user and objects
and assigns the result to a context variable.
Syntax::
{% get_permission_request PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %}
{% get_permission_request "poll_permission.change_poll"
fo... | Below is the the instruction that describes the task:
### Input:
Performs a permission request check with the given signature, user and objects
and assigns the result to a context variable.
Syntax::
{% get_permission_request PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %}
{... |
def keyphrases_table(keyphrases, texts, similarity_measure=None, synonimizer=None,
language=consts.Language.ENGLISH):
"""
Constructs the keyphrases table, containing their matching scores in a set of texts.
The resulting table is stored as a dictionary of dictionaries,
where the en... | Constructs the keyphrases table, containing their matching scores in a set of texts.
The resulting table is stored as a dictionary of dictionaries,
where the entry table["keyphrase"]["text"] corresponds
to the matching score (0 <= score <= 1) of keyphrase "keyphrase"
in the text named "text".
... | Below is the the instruction that describes the task:
### Input:
Constructs the keyphrases table, containing their matching scores in a set of texts.
The resulting table is stored as a dictionary of dictionaries,
where the entry table["keyphrase"]["text"] corresponds
to the matching score (0 <= score <... |
def update(self, *fields):
"""
Update this document. Optionally a specific list of fields to update can
be specified.
"""
from mongoframes.queries import to_refs
assert '_id' in self._document, "Can't update documents without `_id`"
# Send update signal
... | Update this document. Optionally a specific list of fields to update can
be specified. | Below is the the instruction that describes the task:
### Input:
Update this document. Optionally a specific list of fields to update can
be specified.
### Response:
def update(self, *fields):
"""
Update this document. Optionally a specific list of fields to update can
be specified.... |
def get_client():
"""Returns an ``InfluxDBClient`` instance."""
return InfluxDBClient(
settings.INFLUXDB_HOST,
settings.INFLUXDB_PORT,
settings.INFLUXDB_USER,
settings.INFLUXDB_PASSWORD,
settings.INFLUXDB_DATABASE,
timeout=settings.INFLUXDB_TIMEOUT,
ssl=ge... | Returns an ``InfluxDBClient`` instance. | Below is the the instruction that describes the task:
### Input:
Returns an ``InfluxDBClient`` instance.
### Response:
def get_client():
"""Returns an ``InfluxDBClient`` instance."""
return InfluxDBClient(
settings.INFLUXDB_HOST,
settings.INFLUXDB_PORT,
settings.INFLUXDB_USER,
... |
def parse_clubs(self, clubs_page):
"""Parses the DOM and returns character clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL character clubs page's DOM
:rtype: dict
:return: character clubs attributes.
"""
character_info = self.parse_sidebar(clubs_page)... | Parses the DOM and returns character clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL character clubs page's DOM
:rtype: dict
:return: character clubs attributes. | Below is the the instruction that describes the task:
### Input:
Parses the DOM and returns character clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL character clubs page's DOM
:rtype: dict
:return: character clubs attributes.
### Response:
def parse_clubs(se... |
def find_l50(contig_lengths_dict, genome_length_dict):
"""
Calculate the L50 for each strain. L50 is defined as the number of contigs required to achieve the N50
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:param genome_length_dict: dictionary of stra... | Calculate the L50 for each strain. L50 is defined as the number of contigs required to achieve the N50
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:param genome_length_dict: dictionary of strain name: total genome length
:return: l50_dict: dictionary of s... | Below is the the instruction that describes the task:
### Input:
Calculate the L50 for each strain. L50 is defined as the number of contigs required to achieve the N50
:param contig_lengths_dict: dictionary of strain name: reverse-sorted list of all contig lengths
:param genome_length_dict: dictionary of st... |
def load_all(path, include_core=True, subfolders=None, path_in_arc=None):
""" Loads a full IO system with all extension in path
Parameters
----------
path : pathlib.Path or string
Path or path with para file name for the data to load.
This must either point to the directory containing t... | Loads a full IO system with all extension in path
Parameters
----------
path : pathlib.Path or string
Path or path with para file name for the data to load.
This must either point to the directory containing the uncompressed
data or the location of a compressed zip file with the dat... | Below is the the instruction that describes the task:
### Input:
Loads a full IO system with all extension in path
Parameters
----------
path : pathlib.Path or string
Path or path with para file name for the data to load.
This must either point to the directory containing the uncompress... |
def decrypt(ciphertext, secret, inital_vector, checksum=True, lazy=True):
"""Decrypts ciphertext with secret
ciphertext - encrypted content to decrypt
secret - secret to decrypt ciphertext
inital_vector - initial vector
lazy - pad secret if less than legal blocksize (default: ... | Decrypts ciphertext with secret
ciphertext - encrypted content to decrypt
secret - secret to decrypt ciphertext
inital_vector - initial vector
lazy - pad secret if less than legal blocksize (default: True)
checksum - verify crc32 byte encoded checksum (default: True)
... | Below is the the instruction that describes the task:
### Input:
Decrypts ciphertext with secret
ciphertext - encrypted content to decrypt
secret - secret to decrypt ciphertext
inital_vector - initial vector
lazy - pad secret if less than legal blocksize (default: True)
ch... |
def redfearn(lat, lon, false_easting=None, false_northing=None,
zone=None, central_meridian=None, scale_factor=None):
"""Compute UTM projection using Redfearn's formula
lat, lon is latitude and longitude in decimal degrees
If false easting and northing are specified they will override
the... | Compute UTM projection using Redfearn's formula
lat, lon is latitude and longitude in decimal degrees
If false easting and northing are specified they will override
the standard
If zone is specified reproject lat and long to specified zone instead of
standard zone
If meridian is specified, r... | Below is the the instruction that describes the task:
### Input:
Compute UTM projection using Redfearn's formula
lat, lon is latitude and longitude in decimal degrees
If false easting and northing are specified they will override
the standard
If zone is specified reproject lat and long to specifi... |
def post(self, url, data, params=None):
"""
Initiate a POST request
"""
r = self.session.post(url, data=data, params=params)
return self._response_parser(r, expect_json=False) | Initiate a POST request | Below is the the instruction that describes the task:
### Input:
Initiate a POST request
### Response:
def post(self, url, data, params=None):
"""
Initiate a POST request
"""
r = self.session.post(url, data=data, params=params)
return self._response_parser(r, expect_json=Fal... |
def callgrind(self, out, filename=None, commandline=None, relative_path=False):
"""
Dump statistics in callgrind format.
Contains:
- per-line hit count, time and time-per-hit
- call associations (call tree)
Note: hit count is not inclusive, in that it is not the sum of ... | Dump statistics in callgrind format.
Contains:
- per-line hit count, time and time-per-hit
- call associations (call tree)
Note: hit count is not inclusive, in that it is not the sum of all
hits inside that call.
Time unit: microsecond (1e-6 second).
out (file... | Below is the the instruction that describes the task:
### Input:
Dump statistics in callgrind format.
Contains:
- per-line hit count, time and time-per-hit
- call associations (call tree)
Note: hit count is not inclusive, in that it is not the sum of all
hits inside that ... |
def _prm_get_longest_stringsize(string_list):
""" Returns the longest string size for a string entry across data."""
maxlength = 1
for stringar in string_list:
if isinstance(stringar, np.ndarray):
if stringar.ndim > 0:
for string in stringar.ravel... | Returns the longest string size for a string entry across data. | Below is the the instruction that describes the task:
### Input:
Returns the longest string size for a string entry across data.
### Response:
def _prm_get_longest_stringsize(string_list):
""" Returns the longest string size for a string entry across data."""
maxlength = 1
for stringar in ... |
def line_spacing(self):
"""
|float| or |Length| value specifying the space between baselines in
successive lines of the paragraph. A value of |None| indicates line
spacing is inherited from the style hierarchy. A float value, e.g.
``2.0`` or ``1.75``, indicates spacing is applied... | |float| or |Length| value specifying the space between baselines in
successive lines of the paragraph. A value of |None| indicates line
spacing is inherited from the style hierarchy. A float value, e.g.
``2.0`` or ``1.75``, indicates spacing is applied in multiples of
line heights. A |Le... | Below is the the instruction that describes the task:
### Input:
|float| or |Length| value specifying the space between baselines in
successive lines of the paragraph. A value of |None| indicates line
spacing is inherited from the style hierarchy. A float value, e.g.
``2.0`` or ``1.75``, ind... |
def info(self, msg):
""" Log Info Messages """
self._execActions('info', msg)
msg = self._execFilters('info', msg)
self._processMsg('info', msg)
self._sendMsg('info', msg) | Log Info Messages | Below is the the instruction that describes the task:
### Input:
Log Info Messages
### Response:
def info(self, msg):
""" Log Info Messages """
self._execActions('info', msg)
msg = self._execFilters('info', msg)
self._processMsg('info', msg)
self._sendMsg('info', msg) |
def imagetransformerpp_base_8l_8h_big_cond_dr03_dan():
"""big 1d model for conditional image generation.2.99 on cifar10."""
hparams = imagetransformerpp_sep_channels_8l_8h()
hparams.hidden_size = 512
hparams.num_heads = 8
hparams.filter_size = 2048
hparams.batch_size = 4
hparams.max_length = 3075
hparam... | big 1d model for conditional image generation.2.99 on cifar10. | Below is the the instruction that describes the task:
### Input:
big 1d model for conditional image generation.2.99 on cifar10.
### Response:
def imagetransformerpp_base_8l_8h_big_cond_dr03_dan():
"""big 1d model for conditional image generation.2.99 on cifar10."""
hparams = imagetransformerpp_sep_channels_8l_... |
def _add_secondary_if_exists(secondary, out, get_retriever):
"""Add secondary files only if present locally or remotely.
"""
secondary = [_file_local_or_remote(y, get_retriever) for y in secondary]
secondary = [z for z in secondary if z]
if secondary:
out["secondaryFiles"] = [{"class": "File... | Add secondary files only if present locally or remotely. | Below is the the instruction that describes the task:
### Input:
Add secondary files only if present locally or remotely.
### Response:
def _add_secondary_if_exists(secondary, out, get_retriever):
"""Add secondary files only if present locally or remotely.
"""
secondary = [_file_local_or_remote(y, get_... |
def _produceIt(self, segments, thunk):
"""
Underlying implmeentation of L{PrefixURLMixin.produceResource} and
L{PrefixURLMixin.sessionlessProduceResource}.
@param segments: the URL segments to dispatch.
@param thunk: a 0-argument callable which returns an L{IResource}
p... | Underlying implmeentation of L{PrefixURLMixin.produceResource} and
L{PrefixURLMixin.sessionlessProduceResource}.
@param segments: the URL segments to dispatch.
@param thunk: a 0-argument callable which returns an L{IResource}
provider, or None.
@return: a 2-tuple of C{(resourc... | Below is the the instruction that describes the task:
### Input:
Underlying implmeentation of L{PrefixURLMixin.produceResource} and
L{PrefixURLMixin.sessionlessProduceResource}.
@param segments: the URL segments to dispatch.
@param thunk: a 0-argument callable which returns an L{IResource}... |
def generate_csr(self, basename='djangoafip'):
"""
Creates a CSR for this TaxPayer's key
Creates a file-like object that contains the CSR which can be used to
request a new certificate from AFIP.
"""
csr = BytesIO()
crypto.create_csr(
self.key.file,
... | Creates a CSR for this TaxPayer's key
Creates a file-like object that contains the CSR which can be used to
request a new certificate from AFIP. | Below is the the instruction that describes the task:
### Input:
Creates a CSR for this TaxPayer's key
Creates a file-like object that contains the CSR which can be used to
request a new certificate from AFIP.
### Response:
def generate_csr(self, basename='djangoafip'):
"""
Creates... |
def set_qos(self, prefetch_size=0, prefetch_count=0, apply_globally=False):
"""
Specify quality of service by requesting that messages be pre-fetched
from the server. Pre-fetching means that the server will deliver messages
to the client while the client is still processing unacknowledge... | Specify quality of service by requesting that messages be pre-fetched
from the server. Pre-fetching means that the server will deliver messages
to the client while the client is still processing unacknowledged messages.
This method is a :ref:`coroutine <coroutine>`.
:param int prefetch... | Below is the the instruction that describes the task:
### Input:
Specify quality of service by requesting that messages be pre-fetched
from the server. Pre-fetching means that the server will deliver messages
to the client while the client is still processing unacknowledged messages.
This m... |
def find_channel_groups(chan):
"""Channels are often organized in groups (different grids / strips or
channels in different brain locations), so we use a simple heuristic to
get these channel groups.
Parameters
----------
chan : instance of Channels
channels to group
Returns
--... | Channels are often organized in groups (different grids / strips or
channels in different brain locations), so we use a simple heuristic to
get these channel groups.
Parameters
----------
chan : instance of Channels
channels to group
Returns
-------
groups : dict
channe... | Below is the the instruction that describes the task:
### Input:
Channels are often organized in groups (different grids / strips or
channels in different brain locations), so we use a simple heuristic to
get these channel groups.
Parameters
----------
chan : instance of Channels
channe... |
def _update_remote_children(remote_parent, children):
"""
Update remote_ids based on on parent matching up the names of children.
:param remote_parent: RemoteProject/RemoteFolder who has children
:param children: [LocalFolder,LocalFile] children to set remote_ids based on remote children
"""
nam... | Update remote_ids based on on parent matching up the names of children.
:param remote_parent: RemoteProject/RemoteFolder who has children
:param children: [LocalFolder,LocalFile] children to set remote_ids based on remote children | Below is the the instruction that describes the task:
### Input:
Update remote_ids based on on parent matching up the names of children.
:param remote_parent: RemoteProject/RemoteFolder who has children
:param children: [LocalFolder,LocalFile] children to set remote_ids based on remote children
### Response... |
def from_string(cls, address, case_sensitive=False):
"""Alternate constructor for building from a string.
:param str address: An email address in <user>@<domain> form
:param bool case_sensitive: passed directly to the constructor argument
of the same name.
:returns: An accou... | Alternate constructor for building from a string.
:param str address: An email address in <user>@<domain> form
:param bool case_sensitive: passed directly to the constructor argument
of the same name.
:returns: An account from the given arguments
:rtype: :class:`Account` | Below is the the instruction that describes the task:
### Input:
Alternate constructor for building from a string.
:param str address: An email address in <user>@<domain> form
:param bool case_sensitive: passed directly to the constructor argument
of the same name.
:returns: An ... |
def _xysxy2(date):
"""Here we deviate from what has been done everywhere else. Instead of taking the formulas
available in the Vallado, we take those described in the files tab5.2{a,b,d}.txt.
The result should be equivalent, but they are the last iteration of the IAU2000A as of June 2016
Args:
... | Here we deviate from what has been done everywhere else. Instead of taking the formulas
available in the Vallado, we take those described in the files tab5.2{a,b,d}.txt.
The result should be equivalent, but they are the last iteration of the IAU2000A as of June 2016
Args:
date (Date)
Return:
... | Below is the the instruction that describes the task:
### Input:
Here we deviate from what has been done everywhere else. Instead of taking the formulas
available in the Vallado, we take those described in the files tab5.2{a,b,d}.txt.
The result should be equivalent, but they are the last iteration of the ... |
def get_factors_iterative2(n):
"""[summary]
analog as above
Arguments:
n {[int]} -- [description]
Returns:
[list of lists] -- [all factors of n]
"""
ans, stack, x = [], [], 2
while True:
if x > n // x:
if not stack:
return ans
... | [summary]
analog as above
Arguments:
n {[int]} -- [description]
Returns:
[list of lists] -- [all factors of n] | Below is the the instruction that describes the task:
### Input:
[summary]
analog as above
Arguments:
n {[int]} -- [description]
Returns:
[list of lists] -- [all factors of n]
### Response:
def get_factors_iterative2(n):
"""[summary]
analog as above
Arguments:
... |
def incremental_a_value(bval, min_mag, mag_inc):
'''
Incremental a-value from cumulative - using the version of the
Hermann (1979) formula described in Wesson et al. (2003)
:param float bval:
Gutenberg & Richter (1944) b-value
:param np.ndarray min_mag:
Minimum magnitude of complet... | Incremental a-value from cumulative - using the version of the
Hermann (1979) formula described in Wesson et al. (2003)
:param float bval:
Gutenberg & Richter (1944) b-value
:param np.ndarray min_mag:
Minimum magnitude of completeness table
:param float mag_inc:
Magnitude incr... | Below is the the instruction that describes the task:
### Input:
Incremental a-value from cumulative - using the version of the
Hermann (1979) formula described in Wesson et al. (2003)
:param float bval:
Gutenberg & Richter (1944) b-value
:param np.ndarray min_mag:
Minimum magnitude of... |
def _make_input(self, action, old_quat):
"""
Helper function that returns a dictionary with keys dpos, rotation from a raw input
array. The first three elements are taken to be displacement in position, and a
quaternion indicating the change in rotation with respect to @old_quat.
... | Helper function that returns a dictionary with keys dpos, rotation from a raw input
array. The first three elements are taken to be displacement in position, and a
quaternion indicating the change in rotation with respect to @old_quat. | Below is the the instruction that describes the task:
### Input:
Helper function that returns a dictionary with keys dpos, rotation from a raw input
array. The first three elements are taken to be displacement in position, and a
quaternion indicating the change in rotation with respect to @old_quat.... |
def _elements(cls):
''' find the elements with controls '''
if not cls.__is_selector():
raise Exception("Invalid selector[%s]." %cls.__control["by"])
driver = Web.driver
try:
elements = WebDriverWait(driver, cls.__control["timeout"]).... | find the elements with controls | Below is the the instruction that describes the task:
### Input:
find the elements with controls
### Response:
def _elements(cls):
''' find the elements with controls '''
if not cls.__is_selector():
raise Exception("Invalid selector[%s]." %cls.__control["by"])
dr... |
def hide_me(tb, g=globals()):
"""Hide stack traceback of given stack"""
base_tb = tb
try:
while tb and tb.tb_frame.f_globals is not g:
tb = tb.tb_next
while tb and tb.tb_frame.f_globals is g:
tb = tb.tb_next
except Exception as e:
logging.exception(e)
... | Hide stack traceback of given stack | Below is the the instruction that describes the task:
### Input:
Hide stack traceback of given stack
### Response:
def hide_me(tb, g=globals()):
"""Hide stack traceback of given stack"""
base_tb = tb
try:
while tb and tb.tb_frame.f_globals is not g:
tb = tb.tb_next
while tb ... |
def namelist(self):
"""Return a list of file names in the archive."""
names = []
for member in self.filelist:
names.append(member.filename)
return names | Return a list of file names in the archive. | Below is the the instruction that describes the task:
### Input:
Return a list of file names in the archive.
### Response:
def namelist(self):
"""Return a list of file names in the archive."""
names = []
for member in self.filelist:
names.append(member.filename)
return n... |
def namespace(self):
"""
Get the element's namespace.
@return: The element's namespace by resolving the prefix, the explicit
namespace or the inherited namespace.
@rtype: (I{prefix}, I{name})
"""
if self.prefix is None:
return self.defaultNamespa... | Get the element's namespace.
@return: The element's namespace by resolving the prefix, the explicit
namespace or the inherited namespace.
@rtype: (I{prefix}, I{name}) | Below is the the instruction that describes the task:
### Input:
Get the element's namespace.
@return: The element's namespace by resolving the prefix, the explicit
namespace or the inherited namespace.
@rtype: (I{prefix}, I{name})
### Response:
def namespace(self):
"""
... |
async def delayNdefProps(self):
'''
Hold this during a series of renames to delay ndef
secondary property processing until the end....
'''
async with self.getTempSlab() as slab:
seqn = s_slabseqn.SlabSeqn(slab, 'ndef')
self.ndefdelay = seqn
... | Hold this during a series of renames to delay ndef
secondary property processing until the end.... | Below is the the instruction that describes the task:
### Input:
Hold this during a series of renames to delay ndef
secondary property processing until the end....
### Response:
async def delayNdefProps(self):
'''
Hold this during a series of renames to delay ndef
secondary property... |
def p_FuncDef(p):
'''
FuncDef : DEF RefModifier INDENTIFIER LPARENT ParamList RPARENT COLON ReturnTypeModifier Terminator Block
'''
p[0] = FuncDef(p[2], p[3], p[5], p[8], p[9], p[10]) | FuncDef : DEF RefModifier INDENTIFIER LPARENT ParamList RPARENT COLON ReturnTypeModifier Terminator Block | Below is the the instruction that describes the task:
### Input:
FuncDef : DEF RefModifier INDENTIFIER LPARENT ParamList RPARENT COLON ReturnTypeModifier Terminator Block
### Response:
def p_FuncDef(p):
'''
FuncDef : DEF RefModifier INDENTIFIER LPARENT ParamList RPARENT COLON ReturnTypeModifier Terminator ... |
def get(self, rid, data_callback=None, raise_on_error=True):
"""Get cached data from the data store.
Args:
rid (str): The record identifier.
data_callback (callable): A method that will return the data.
raise_on_error (bool): If True and not r.ok this method will rai... | Get cached data from the data store.
Args:
rid (str): The record identifier.
data_callback (callable): A method that will return the data.
raise_on_error (bool): If True and not r.ok this method will raise a RunTimeError.
Returns:
object : Python request... | Below is the the instruction that describes the task:
### Input:
Get cached data from the data store.
Args:
rid (str): The record identifier.
data_callback (callable): A method that will return the data.
raise_on_error (bool): If True and not r.ok this method will raise ... |
def get_region_from_metadata():
'''
Try to get region from instance identity document and cache it
.. versionadded:: 2015.5.6
'''
global __Location__
if __Location__ == 'do-not-get-from-metadata':
log.debug('Previously failed to get AWS region from metadata. Not trying again.')
... | Try to get region from instance identity document and cache it
.. versionadded:: 2015.5.6 | Below is the the instruction that describes the task:
### Input:
Try to get region from instance identity document and cache it
.. versionadded:: 2015.5.6
### Response:
def get_region_from_metadata():
'''
Try to get region from instance identity document and cache it
.. versionadded:: 2015.5.6
... |
def _create_doc(self):
'''
Create document.
:return:
'''
root = etree.Element('image')
root.set('schemaversion', '6.3')
root.set('name', self.name)
return root | Create document.
:return: | Below is the the instruction that describes the task:
### Input:
Create document.
:return:
### Response:
def _create_doc(self):
'''
Create document.
:return:
'''
root = etree.Element('image')
root.set('schemaversion', '6.3')
root.set('name', self.na... |
def licenses(self):
"""OSI Approved license."""
return {self._acronym_lic(l): l for l in self.resp_text.split('\n')
if l.startswith(self.prefix_lic)} | OSI Approved license. | Below is the the instruction that describes the task:
### Input:
OSI Approved license.
### Response:
def licenses(self):
"""OSI Approved license."""
return {self._acronym_lic(l): l for l in self.resp_text.split('\n')
if l.startswith(self.prefix_lic)} |
def as_proto(self):
"""Returns this shape as a `TensorShapeProto`."""
if self._dims is None:
return tensor_shape_pb2.TensorShapeProto(unknown_rank=True)
else:
return tensor_shape_pb2.TensorShapeProto(
dim=[
tensor_shape_pb2.TensorShapeP... | Returns this shape as a `TensorShapeProto`. | Below is the the instruction that describes the task:
### Input:
Returns this shape as a `TensorShapeProto`.
### Response:
def as_proto(self):
"""Returns this shape as a `TensorShapeProto`."""
if self._dims is None:
return tensor_shape_pb2.TensorShapeProto(unknown_rank=True)
els... |
def cmd_rollback(self, name):
"""Rollback migrations."""
from peewee_migrate.router import Router, LOGGER
LOGGER.setLevel('INFO')
LOGGER.propagate = 0
router = Router(self.database,
migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'],
... | Rollback migrations. | Below is the the instruction that describes the task:
### Input:
Rollback migrations.
### Response:
def cmd_rollback(self, name):
"""Rollback migrations."""
from peewee_migrate.router import Router, LOGGER
LOGGER.setLevel('INFO')
LOGGER.propagate = 0
router = Router(self.d... |
def getPropAllSupers(self, aURI):
"""
note: requires SPARQL 1.1
2015-06-04: currenlty not used, inferred from above
"""
aURI = aURI
try:
qres = self.rdflib_graph.query("""SELECT DISTINCT ?x
WHERE {
{ <%s> rdfs:subP... | note: requires SPARQL 1.1
2015-06-04: currenlty not used, inferred from above | Below is the the instruction that describes the task:
### Input:
note: requires SPARQL 1.1
2015-06-04: currenlty not used, inferred from above
### Response:
def getPropAllSupers(self, aURI):
"""
note: requires SPARQL 1.1
2015-06-04: currenlty not used, inferred from above
""... |
def _value_format(self, value):
"""
Format value for map value display.
"""
return '%s: %s' % (
self.area_names.get(self.adapt_code(value[0]), '?'),
self._y_format(value[1])
) | Format value for map value display. | Below is the the instruction that describes the task:
### Input:
Format value for map value display.
### Response:
def _value_format(self, value):
"""
Format value for map value display.
"""
return '%s: %s' % (
self.area_names.get(self.adapt_code(value[0]), '?'),
... |
def delete(self):
"""
Delete this Vlan interface from the parent interface.
This will also remove stale routes if the interface has
networks associated with it.
:return: None
"""
if self in self._parent.vlan_interface:
self._parent.data['vlanI... | Delete this Vlan interface from the parent interface.
This will also remove stale routes if the interface has
networks associated with it.
:return: None | Below is the the instruction that describes the task:
### Input:
Delete this Vlan interface from the parent interface.
This will also remove stale routes if the interface has
networks associated with it.
:return: None
### Response:
def delete(self):
"""
Delete this ... |
def connect(self, deleteOldVersions=False, recreate=False):
""" Locate the current version of the jobs DB or create a new one, and
optionally delete old versions laying around. If desired, this method
can be called at any time to re-create the tables from scratch, delete
old versions of the database, et... | Locate the current version of the jobs DB or create a new one, and
optionally delete old versions laying around. If desired, this method
can be called at any time to re-create the tables from scratch, delete
old versions of the database, etc.
Parameters:
--------------------------------------------... | Below is the the instruction that describes the task:
### Input:
Locate the current version of the jobs DB or create a new one, and
optionally delete old versions laying around. If desired, this method
can be called at any time to re-create the tables from scratch, delete
old versions of the database, e... |
def iter_insert_items(tree):
""" Iterate over the items to insert from an INSERT statement """
if tree.list_values:
keys = tree.attrs
for values in tree.list_values:
if len(keys) != len(values):
raise SyntaxError(
"Values '%s' do not match attribut... | Iterate over the items to insert from an INSERT statement | Below is the the instruction that describes the task:
### Input:
Iterate over the items to insert from an INSERT statement
### Response:
def iter_insert_items(tree):
""" Iterate over the items to insert from an INSERT statement """
if tree.list_values:
keys = tree.attrs
for values in tree.l... |
def sha256(message, encoder=nacl.encoding.HexEncoder):
"""
Hashes ``message`` with SHA256.
:param message: The message to hash.
:type message: bytes
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes
"""
return encoder.enco... | Hashes ``message`` with SHA256.
:param message: The message to hash.
:type message: bytes
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes | Below is the the instruction that describes the task:
### Input:
Hashes ``message`` with SHA256.
:param message: The message to hash.
:type message: bytes
:param encoder: A class that is able to encode the hashed message.
:returns: The hashed message.
:rtype: bytes
### Response:
def sha256(mes... |
def _remove_list_item(self, beacon_config, label):
'''
Remove an item from a beacon config list
'''
index = self._get_index(beacon_config, label)
del beacon_config[index] | Remove an item from a beacon config list | Below is the the instruction that describes the task:
### Input:
Remove an item from a beacon config list
### Response:
def _remove_list_item(self, beacon_config, label):
'''
Remove an item from a beacon config list
'''
index = self._get_index(beacon_config, label)
del beac... |
def extended_arg_patterns(self):
"""Iterator over patterns for positional arguments to be matched
This yields the elements of :attr:`args`, extended by their `mode`
value
"""
for arg in self._arg_iterator(self.args):
if isinstance(arg, Pattern):
if ar... | Iterator over patterns for positional arguments to be matched
This yields the elements of :attr:`args`, extended by their `mode`
value | Below is the the instruction that describes the task:
### Input:
Iterator over patterns for positional arguments to be matched
This yields the elements of :attr:`args`, extended by their `mode`
value
### Response:
def extended_arg_patterns(self):
"""Iterator over patterns for positional ar... |
def get_still_seg_belonged(dt_str, seg_duration, fmt='%Y-%m-%d %H:%M:%S'):
"""
获取该时刻所属的非滑动时间片
:param dt_str: datetime string, eg: 2016-10-31 12:22:11
:param seg_duration: 时间片长度, unit: minute
:param fmt: datetime string format
:return:
"""
dt = time_util.str_to_datetime(dt_str, fmt)
m... | 获取该时刻所属的非滑动时间片
:param dt_str: datetime string, eg: 2016-10-31 12:22:11
:param seg_duration: 时间片长度, unit: minute
:param fmt: datetime string format
:return: | Below is the the instruction that describes the task:
### Input:
获取该时刻所属的非滑动时间片
:param dt_str: datetime string, eg: 2016-10-31 12:22:11
:param seg_duration: 时间片长度, unit: minute
:param fmt: datetime string format
:return:
### Response:
def get_still_seg_belonged(dt_str, seg_duration, fmt='%Y-%m-%d %... |
def check_calendar(self, ds):
'''
Check the calendar attribute for variables defining time and ensure it
is a valid calendar prescribed by CF.
CF §4.4.1 In order to calculate a new date and time given a base date, base
time and a time increment one must know what calendar to use... | Check the calendar attribute for variables defining time and ensure it
is a valid calendar prescribed by CF.
CF §4.4.1 In order to calculate a new date and time given a base date, base
time and a time increment one must know what calendar to use.
The values currently defined for calend... | Below is the the instruction that describes the task:
### Input:
Check the calendar attribute for variables defining time and ensure it
is a valid calendar prescribed by CF.
CF §4.4.1 In order to calculate a new date and time given a base date, base
time and a time increment one must know w... |
def asserts(self, *args, **kwargs):
"""Wraps match method and places under an assertion. Override this for higher-level control,
such as returning a custom object for additional validation (e.g. expect().to.change())
"""
result = self.match(*args, **kwargs)
self.expect(resul... | Wraps match method and places under an assertion. Override this for higher-level control,
such as returning a custom object for additional validation (e.g. expect().to.change()) | Below is the the instruction that describes the task:
### Input:
Wraps match method and places under an assertion. Override this for higher-level control,
such as returning a custom object for additional validation (e.g. expect().to.change())
### Response:
def asserts(self, *args, **kwargs):
"""W... |
def tasks(self):
"""
Returns a list of all tasks known to the engine.
:return: A list of task names.
"""
task_input = {'taskName': 'QueryTaskCatalog'}
output = taskengine.execute(task_input, self._engine_name, cwd=self._cwd)
return output['outputParameters']['TAS... | Returns a list of all tasks known to the engine.
:return: A list of task names. | Below is the the instruction that describes the task:
### Input:
Returns a list of all tasks known to the engine.
:return: A list of task names.
### Response:
def tasks(self):
"""
Returns a list of all tasks known to the engine.
:return: A list of task names.
"""
t... |
def unpitched_low(dur, idx):
"""
Non-harmonic bass/lower frequency sound as a list (due to memoization).
Parameters
----------
dur:
Duration, in samples.
idx:
Zero or one (integer), for a small difference to the sound played.
Returns
-------
A list with the synthesized note.
"""
env = s... | Non-harmonic bass/lower frequency sound as a list (due to memoization).
Parameters
----------
dur:
Duration, in samples.
idx:
Zero or one (integer), for a small difference to the sound played.
Returns
-------
A list with the synthesized note. | Below is the the instruction that describes the task:
### Input:
Non-harmonic bass/lower frequency sound as a list (due to memoization).
Parameters
----------
dur:
Duration, in samples.
idx:
Zero or one (integer), for a small difference to the sound played.
Returns
-------
A list with the sy... |
def p_case_list(p):
'''case_list : empty
| case_list CASE expr case_separator inner_statement_list
| case_list DEFAULT case_separator inner_statement_list'''
if len(p) == 6:
p[0] = p[1] + [ast.Case(p[3], p[5], lineno=p.lineno(2))]
elif len(p) == 5:
p[0] = p[... | case_list : empty
| case_list CASE expr case_separator inner_statement_list
| case_list DEFAULT case_separator inner_statement_list | Below is the the instruction that describes the task:
### Input:
case_list : empty
| case_list CASE expr case_separator inner_statement_list
| case_list DEFAULT case_separator inner_statement_list
### Response:
def p_case_list(p):
'''case_list : empty
| case_l... |
def create_lv(self, name, length, units):
"""
Creates a logical volume and returns the LogicalVolume instance associated with
the lv_t handle::
from lvm2py import *
lvm = LVM()
vg = lvm.get_vg("myvg", "w")
lv = vg.create_lv("mylv", 40, "MiB")
... | Creates a logical volume and returns the LogicalVolume instance associated with
the lv_t handle::
from lvm2py import *
lvm = LVM()
vg = lvm.get_vg("myvg", "w")
lv = vg.create_lv("mylv", 40, "MiB")
*Args:*
* name (str): The des... | Below is the the instruction that describes the task:
### Input:
Creates a logical volume and returns the LogicalVolume instance associated with
the lv_t handle::
from lvm2py import *
lvm = LVM()
vg = lvm.get_vg("myvg", "w")
lv = vg.create_lv("mylv", 40, "Mi... |
def clean(bundle, before, after, keep_last):
"""Clean up data downloaded with the ingest command.
"""
bundles_module.clean(
bundle,
before,
after,
keep_last,
) | Clean up data downloaded with the ingest command. | Below is the the instruction that describes the task:
### Input:
Clean up data downloaded with the ingest command.
### Response:
def clean(bundle, before, after, keep_last):
"""Clean up data downloaded with the ingest command.
"""
bundles_module.clean(
bundle,
before,
after,
... |
def parse_child_elements(self, element):
'''parses all children of an etree element'''
for child in element.iterchildren():
self.parsers[child.tag](child) | parses all children of an etree element | Below is the the instruction that describes the task:
### Input:
parses all children of an etree element
### Response:
def parse_child_elements(self, element):
'''parses all children of an etree element'''
for child in element.iterchildren():
self.parsers[child.tag](child) |
def make_dependent(self, source, target, action):
'''
Create a dependency between path 'source' and path 'target' via the
callable 'action'.
>>> permuter._generators
[IterValueGenerator(one), IterValueGenerator(two)]
>>> permuter.make_dependent('one', 'two', lambda x: x ... | Create a dependency between path 'source' and path 'target' via the
callable 'action'.
>>> permuter._generators
[IterValueGenerator(one), IterValueGenerator(two)]
>>> permuter.make_dependent('one', 'two', lambda x: x + 1)
Going forward, 'two' will only contain values that are (... | Below is the the instruction that describes the task:
### Input:
Create a dependency between path 'source' and path 'target' via the
callable 'action'.
>>> permuter._generators
[IterValueGenerator(one), IterValueGenerator(two)]
>>> permuter.make_dependent('one', 'two', lambda x: x +... |
def _update_dPrxy(self):
"""Update `dPrxy`."""
super(ExpCM_fitprefs, self)._update_dPrxy()
if 'zeta' in self.freeparams:
tildeFrxyQxy = self.tildeFrxy * self.Qxy
j = 0
zetaxterm = scipy.ndarray((self.nsites, N_CODON, N_CODON), dtype='float')
zetay... | Update `dPrxy`. | Below is the the instruction that describes the task:
### Input:
Update `dPrxy`.
### Response:
def _update_dPrxy(self):
"""Update `dPrxy`."""
super(ExpCM_fitprefs, self)._update_dPrxy()
if 'zeta' in self.freeparams:
tildeFrxyQxy = self.tildeFrxy * self.Qxy
j = 0
... |
def _param_callback(self, name, value):
"""Generic callback registered for all the groups"""
print('{0}: {1}'.format(name, value))
# Remove each parameter from the list and close the link when
# all are fetched
self._param_check_list.remove(name)
if len(self._param_check... | Generic callback registered for all the groups | Below is the the instruction that describes the task:
### Input:
Generic callback registered for all the groups
### Response:
def _param_callback(self, name, value):
"""Generic callback registered for all the groups"""
print('{0}: {1}'.format(name, value))
# Remove each parameter from the ... |
def StringIO(*args, **kw):
"""Thunk to load the real StringIO on demand"""
global StringIO
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
return StringIO(*args,**kw) | Thunk to load the real StringIO on demand | Below is the the instruction that describes the task:
### Input:
Thunk to load the real StringIO on demand
### Response:
def StringIO(*args, **kw):
"""Thunk to load the real StringIO on demand"""
global StringIO
try:
from cStringIO import StringIO
except ImportError:
from StringIO i... |
def _check_neg(self, level, *tokens):
"""Check that the different tokens were NOT logged in one record, assert by level."""
for record in self.records:
if level is not None and record.levelno != level:
continue
if all(token in record.message for token in tokens):
... | Check that the different tokens were NOT logged in one record, assert by level. | Below is the the instruction that describes the task:
### Input:
Check that the different tokens were NOT logged in one record, assert by level.
### Response:
def _check_neg(self, level, *tokens):
"""Check that the different tokens were NOT logged in one record, assert by level."""
for record in se... |
def _set_get_vnetwork_hosts(self, v, load=False):
"""
Setter method for get_vnetwork_hosts, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_hosts (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_vnetwork_hosts is considered as a private
method. B... | Setter method for get_vnetwork_hosts, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_hosts (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_vnetwork_hosts is considered as a private
method. Backends looking to populate this variable should
do so via... | Below is the the instruction that describes the task:
### Input:
Setter method for get_vnetwork_hosts, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_hosts (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_vnetwork_hosts is considered as a private
me... |
def assert_reset(self, asserted):
"""Assert or de-assert target reset line"""
try:
self._invalidate_cached_registers()
self._link.assert_reset(asserted)
except DAPAccess.Error as exc:
six.raise_from(self._convert_exception(exc), exc) | Assert or de-assert target reset line | Below is the the instruction that describes the task:
### Input:
Assert or de-assert target reset line
### Response:
def assert_reset(self, asserted):
"""Assert or de-assert target reset line"""
try:
self._invalidate_cached_registers()
self._link.assert_reset(asserted)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.