code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def set_group(self, group):
"""Set group size of Dataset (used for ranking).
Parameters
----------
group : list, numpy 1-D array, pandas Series or None
Group size of each group.
Returns
-------
self : Dataset
Dataset with set group.
... | Set group size of Dataset (used for ranking).
Parameters
----------
group : list, numpy 1-D array, pandas Series or None
Group size of each group.
Returns
-------
self : Dataset
Dataset with set group. | Below is the the instruction that describes the task:
### Input:
Set group size of Dataset (used for ranking).
Parameters
----------
group : list, numpy 1-D array, pandas Series or None
Group size of each group.
Returns
-------
self : Dataset
... |
def delimiter_groups(line, begin_delim=begin_delim,
end_delim=end_delim):
"""Split a line into alternating groups.
The first group cannot have a line feed inserted,
the next one can, etc.
"""
text = []
line = iter(line)
while True:
# First build and yield a... | Split a line into alternating groups.
The first group cannot have a line feed inserted,
the next one can, etc. | Below is the the instruction that describes the task:
### Input:
Split a line into alternating groups.
The first group cannot have a line feed inserted,
the next one can, etc.
### Response:
def delimiter_groups(line, begin_delim=begin_delim,
end_delim=end_delim):
"""Split a l... |
def StartObject(self, numfields):
"""StartObject initializes bookkeeping for writing a new object."""
self.assertNotNested()
# use 32-bit offsets so that arithmetic doesn't overflow.
self.current_vtable = [0 for _ in range_func(numfields)]
self.objectEnd = self.Offset()
... | StartObject initializes bookkeeping for writing a new object. | Below is the the instruction that describes the task:
### Input:
StartObject initializes bookkeeping for writing a new object.
### Response:
def StartObject(self, numfields):
"""StartObject initializes bookkeeping for writing a new object."""
self.assertNotNested()
# use 32-bit offsets so... |
def copy_config_input_with_inactive(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
copy_config = ET.Element("copy_config")
config = copy_config
input = ET.SubElement(copy_config, "input")
with_inactive = ET.SubElement(input, "with-inacti... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def copy_config_input_with_inactive(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
copy_config = ET.Element("copy_config")
config = copy_config
... |
def create_hosted_zone(Name, VPCId=None, VPCName=None, VPCRegion=None, CallerReference=None,
Comment='', PrivateZone=False, DelegationSetId=None,
region=None, key=None, keyid=None, profile=None):
'''
Create a new Route53 Hosted Zone. Returns a Python data structure ... | Create a new Route53 Hosted Zone. Returns a Python data structure with information about the
newly created Hosted Zone.
Name
The name of the domain. This should be a fully-specified domain, and should terminate with
a period. This is the name you have registered with your DNS registrar. It is a... | Below is the the instruction that describes the task:
### Input:
Create a new Route53 Hosted Zone. Returns a Python data structure with information about the
newly created Hosted Zone.
Name
The name of the domain. This should be a fully-specified domain, and should terminate with
a period. ... |
def add_option(self, *args, **kwargs):
"""add_option(Option)
add_option(opt_str, ..., kwarg=val, ...)
"""
if type(args[0]) in types.StringTypes:
option = self.option_class(*args, **kwargs)
elif len(args) == 1 and not kwargs:
option = args[0]
... | add_option(Option)
add_option(opt_str, ..., kwarg=val, ...) | Below is the the instruction that describes the task:
### Input:
add_option(Option)
add_option(opt_str, ..., kwarg=val, ...)
### Response:
def add_option(self, *args, **kwargs):
"""add_option(Option)
add_option(opt_str, ..., kwarg=val, ...)
"""
if type(args[0]) in type... |
def _setup_file_logger(cls, session: AppSession, args):
'''Set up the file message logger.
A file log handler and with a formatter is added to the root logger.
'''
if not (args.output_file or args.append_output):
return
logger = logging.getLogger()
formatte... | Set up the file message logger.
A file log handler and with a formatter is added to the root logger. | Below is the the instruction that describes the task:
### Input:
Set up the file message logger.
A file log handler and with a formatter is added to the root logger.
### Response:
def _setup_file_logger(cls, session: AppSession, args):
'''Set up the file message logger.
A file log handler... |
def during(rrule, duration=None, timestamp=None, **kwargs):
"""
Check if input timestamp is in rrule+duration period
:param rrule: rrule to check
:type rrule: str or dict
(freq, dtstart, interval, count, wkst, until, bymonth, byminute, etc.)
:param dict duration: time duration from rrule st... | Check if input timestamp is in rrule+duration period
:param rrule: rrule to check
:type rrule: str or dict
(freq, dtstart, interval, count, wkst, until, bymonth, byminute, etc.)
:param dict duration: time duration from rrule step. Ex:{'minutes': 60}
:param float timestamp: timestamp to check be... | Below is the the instruction that describes the task:
### Input:
Check if input timestamp is in rrule+duration period
:param rrule: rrule to check
:type rrule: str or dict
(freq, dtstart, interval, count, wkst, until, bymonth, byminute, etc.)
:param dict duration: time duration from rrule step.... |
def disable_contactgroup_svc_notifications(self, contactgroup):
"""Disable service notifications for a contactgroup
Format of the line that triggers function call::
DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS;<contactgroup_name>
:param contactgroup: contactgroup to disable
:type con... | Disable service notifications for a contactgroup
Format of the line that triggers function call::
DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS;<contactgroup_name>
:param contactgroup: contactgroup to disable
:type contactgroup: alignak.objects.contactgroup.Contactgroup
:return: None | Below is the the instruction that describes the task:
### Input:
Disable service notifications for a contactgroup
Format of the line that triggers function call::
DISABLE_CONTACTGROUP_SVC_NOTIFICATIONS;<contactgroup_name>
:param contactgroup: contactgroup to disable
:type contactgr... |
def _fix_bias(op_name, attrs, num_inputs):
"""A workaround for 'use_bias' attribute since onnx don't provide this attribute,
we have to check the number of inputs to decide it."""
if num_inputs == 3:
attrs['no_bias'] = False
elif num_inputs == 2:
attrs['no_bias'] = True
else:
... | A workaround for 'use_bias' attribute since onnx don't provide this attribute,
we have to check the number of inputs to decide it. | Below is the the instruction that describes the task:
### Input:
A workaround for 'use_bias' attribute since onnx don't provide this attribute,
we have to check the number of inputs to decide it.
### Response:
def _fix_bias(op_name, attrs, num_inputs):
"""A workaround for 'use_bias' attribute since onnx do... |
def imported_classifiers_package(p: ecore.EPackage):
"""Determines which classifiers have to be imported into given package."""
classes = {c for c in p.eClassifiers if isinstance(c, ecore.EClass)}
references = itertools.chain(*(c.eAllReferences() for c in classes))
references_types = (r... | Determines which classifiers have to be imported into given package. | Below is the the instruction that describes the task:
### Input:
Determines which classifiers have to be imported into given package.
### Response:
def imported_classifiers_package(p: ecore.EPackage):
"""Determines which classifiers have to be imported into given package."""
classes = {c for c in p... |
def center_widget_on_screen(widget, screen=None):
"""
Centers given Widget on the screen.
:param widget: Current Widget.
:type widget: QWidget
:param screen: Screen used for centering.
:type screen: int
:return: Definition success.
:rtype: bool
"""
screen = screen and screen or... | Centers given Widget on the screen.
:param widget: Current Widget.
:type widget: QWidget
:param screen: Screen used for centering.
:type screen: int
:return: Definition success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Centers given Widget on the screen.
:param widget: Current Widget.
:type widget: QWidget
:param screen: Screen used for centering.
:type screen: int
:return: Definition success.
:rtype: bool
### Response:
def center_widget_on... |
def configure(self):
"""
Configure the Python logging module for this file.
"""
# build a file handler for this file
handler = logging.FileHandler(self.path, delay=True)
# if we got a format string, create a formatter with it
if self._format:
handler.... | Configure the Python logging module for this file. | Below is the the instruction that describes the task:
### Input:
Configure the Python logging module for this file.
### Response:
def configure(self):
"""
Configure the Python logging module for this file.
"""
# build a file handler for this file
handler = logging.FileHandle... |
def base(self, *paths, **query_kwargs):
"""create a new url object using the current base path as a base
if you had requested /foo/bar, then this would append *paths and **query_kwargs
to /foo/bar
:example:
# current path: /foo/bar
print url # http://host.com/f... | create a new url object using the current base path as a base
if you had requested /foo/bar, then this would append *paths and **query_kwargs
to /foo/bar
:example:
# current path: /foo/bar
print url # http://host.com/foo/bar
print url.base() # http://host.... | Below is the the instruction that describes the task:
### Input:
create a new url object using the current base path as a base
if you had requested /foo/bar, then this would append *paths and **query_kwargs
to /foo/bar
:example:
# current path: /foo/bar
print url #... |
def get_resources_for_api_version(self, prefix, group, version, preferred):
""" returns a dictionary of resources associated with provided (prefix, group, version)"""
resources = defaultdict(list)
subresources = {}
path = '/'.join(filter(None, [prefix, group, version]))
resourc... | returns a dictionary of resources associated with provided (prefix, group, version) | Below is the the instruction that describes the task:
### Input:
returns a dictionary of resources associated with provided (prefix, group, version)
### Response:
def get_resources_for_api_version(self, prefix, group, version, preferred):
""" returns a dictionary of resources associated with provided (pref... |
def parse(self, plist):
"""Update the builder using the provided `plist`. `plist` can
be either a Packet() or a PacketList().
"""
if not isinstance(plist, PacketList):
plist = PacketList(plist)
for pkt in plist[LLTD]:
if LLTDQueryLargeTlv in pkt:
... | Update the builder using the provided `plist`. `plist` can
be either a Packet() or a PacketList(). | Below is the the instruction that describes the task:
### Input:
Update the builder using the provided `plist`. `plist` can
be either a Packet() or a PacketList().
### Response:
def parse(self, plist):
"""Update the builder using the provided `plist`. `plist` can
be either a Packet() or a P... |
def _parse_logging(log_values: dict, service_config: dict):
"""Parse log key.
Args:
log_values (dict): logging configuration values
service_config (dict): Service specification
"""
for log_key, log_value in log_values.items():
if 'driver' in log_key:
... | Parse log key.
Args:
log_values (dict): logging configuration values
service_config (dict): Service specification | Below is the the instruction that describes the task:
### Input:
Parse log key.
Args:
log_values (dict): logging configuration values
service_config (dict): Service specification
### Response:
def _parse_logging(log_values: dict, service_config: dict):
"""Parse log key.
... |
def convert_binary_field_to_attachment(env, field_spec):
"""This method converts the 8.0 binary fields to attachments like Odoo 9.0
makes with the new attachment=True attribute. It has to be called on
post-migration script, as there's a call to get the res_name of the
target model, which is not yet load... | This method converts the 8.0 binary fields to attachments like Odoo 9.0
makes with the new attachment=True attribute. It has to be called on
post-migration script, as there's a call to get the res_name of the
target model, which is not yet loaded on pre-migration.
You need to rename the involved column... | Below is the the instruction that describes the task:
### Input:
This method converts the 8.0 binary fields to attachments like Odoo 9.0
makes with the new attachment=True attribute. It has to be called on
post-migration script, as there's a call to get the res_name of the
target model, which is not yet... |
def _list_directories_and_files(self, share_name, directory_name=None,
marker=None, max_results=None, timeout=None):
'''
Returns a list of the directories and files under the specified share.
:param str share_name:
Name of existing share.
... | Returns a list of the directories and files under the specified share.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param str marker:
A string value that identifies the portion of the list
t... | Below is the the instruction that describes the task:
### Input:
Returns a list of the directories and files under the specified share.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param str marker:
... |
def status(self):
"""
[str] 合约状态。’Active’ - 正常上市, ‘Delisted’ - 终止上市, ‘TemporarySuspended’ - 暂停上市,
‘PreIPO’ - 发行配售期间, ‘FailIPO’ - 发行失败(股票专用)
"""
try:
return self.__dict__["status"]
except (KeyError, ValueError):
raise AttributeError(
... | [str] 合约状态。’Active’ - 正常上市, ‘Delisted’ - 终止上市, ‘TemporarySuspended’ - 暂停上市,
‘PreIPO’ - 发行配售期间, ‘FailIPO’ - 发行失败(股票专用) | Below is the the instruction that describes the task:
### Input:
[str] 合约状态。’Active’ - 正常上市, ‘Delisted’ - 终止上市, ‘TemporarySuspended’ - 暂停上市,
‘PreIPO’ - 发行配售期间, ‘FailIPO’ - 发行失败(股票专用)
### Response:
def status(self):
"""
[str] 合约状态。’Active’ - 正常上市, ‘Delisted’ - 终止上市, ‘TemporarySuspended’ - 暂停... |
def write_to_csv(self, filename=None, extension='.dat', overwrite=False,
stride=1, chunksize=None, **kw):
""" write all data to csv with numpy.savetxt
Parameters
----------
filename : str, optional
filename string, which may contain placeholders {itraj} ... | write all data to csv with numpy.savetxt
Parameters
----------
filename : str, optional
filename string, which may contain placeholders {itraj} and {stride}:
* itraj will be replaced by trajetory index
* stride is stride argument of this method
... | Below is the the instruction that describes the task:
### Input:
write all data to csv with numpy.savetxt
Parameters
----------
filename : str, optional
filename string, which may contain placeholders {itraj} and {stride}:
* itraj will be replaced by trajetory index... |
def rfcformat(dt, localtime=False):
"""Return the RFC822-formatted representation of a datetime object.
:param datetime dt: The datetime.
:param bool localtime: If ``True``, return the date relative to the local
timezone instead of UTC, displaying the proper offset,
e.g. "Sun, 10 Nov 2013 0... | Return the RFC822-formatted representation of a datetime object.
:param datetime dt: The datetime.
:param bool localtime: If ``True``, return the date relative to the local
timezone instead of UTC, displaying the proper offset,
e.g. "Sun, 10 Nov 2013 08:23:45 -0600" | Below is the the instruction that describes the task:
### Input:
Return the RFC822-formatted representation of a datetime object.
:param datetime dt: The datetime.
:param bool localtime: If ``True``, return the date relative to the local
timezone instead of UTC, displaying the proper offset,
... |
def parse_hosts(hosts, ssh_port=None, ssh_config=None):
"""
Parse a list of hosts (string) and return a list of `msshcopyid.Host` objects.
The information about the host are taken in this order of priority:
- host:
- from the host (string) itself.
- user:
- from the host (string) i... | Parse a list of hosts (string) and return a list of `msshcopyid.Host` objects.
The information about the host are taken in this order of priority:
- host:
- from the host (string) itself.
- user:
- from the host (string) itself.
- from the `paramiko.config.SSHConfig` object.
... | Below is the the instruction that describes the task:
### Input:
Parse a list of hosts (string) and return a list of `msshcopyid.Host` objects.
The information about the host are taken in this order of priority:
- host:
- from the host (string) itself.
- user:
- from the host (string) ... |
def replace_pattern(
df,
column: str,
*,
pat: str,
repl: str,
new_column: str = None,
case: bool = True,
regex: bool = True
):
"""
Replace occurrences of pattern/regex in `column` with some other string
See [pandas doc](
https://pandas.pyda... | Replace occurrences of pattern/regex in `column` with some other string
See [pandas doc](
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html) for more information
---
### Parameters
*mandatory :*
- `column` (*str*): the column
- `pat` (*str*): charac... | Below is the the instruction that describes the task:
### Input:
Replace occurrences of pattern/regex in `column` with some other string
See [pandas doc](
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html) for more information
---
### Parameters
*mandat... |
def gen_configs_permutate(self,
injections_raw,
only_same_dipole_length=False,
ignore_crossed_dipoles=False,
silent=False):
""" Create measurement configurations out of a pool of current
... | Create measurement configurations out of a pool of current
injections. Use only the provided dipoles for potential dipole
selection. This means that we have always reciprocal measurements.
Remove quadpoles where electrodes are used both as current and voltage
dipoles.
Paramete... | Below is the the instruction that describes the task:
### Input:
Create measurement configurations out of a pool of current
injections. Use only the provided dipoles for potential dipole
selection. This means that we have always reciprocal measurements.
Remove quadpoles where electrodes ar... |
def p_unrelate_statement_using_1(self, p):
'''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id USING instance_name'''
p[0] = UnrelateUsingNode(from_variable_name=p[2],
to_variable_name=p[4],
rel_id=p[6],
... | statement : UNRELATE instance_name FROM instance_name ACROSS rel_id USING instance_name | Below is the the instruction that describes the task:
### Input:
statement : UNRELATE instance_name FROM instance_name ACROSS rel_id USING instance_name
### Response:
def p_unrelate_statement_using_1(self, p):
'''statement : UNRELATE instance_name FROM instance_name ACROSS rel_id USING instance_name'''
... |
async def update(self, db=None, data=None):
'''
Update the entire document by replacing its content with new data, retaining its primary key
'''
db = db or self.db
if data: # update model explicitely with a new data structure
# merge the current model's data with the... | Update the entire document by replacing its content with new data, retaining its primary key | Below is the the instruction that describes the task:
### Input:
Update the entire document by replacing its content with new data, retaining its primary key
### Response:
async def update(self, db=None, data=None):
'''
Update the entire document by replacing its content with new data, retaining it... |
def _parse_path(self, path):
"""Parses paths in the following formats:
url: username/project/runs/run_id
path: username/project/run_id
docker: username/project:run_id
username is optional and will fallback to the current logged in user.
"""
run = self.settings['... | Parses paths in the following formats:
url: username/project/runs/run_id
path: username/project/run_id
docker: username/project:run_id
username is optional and will fallback to the current logged in user. | Below is the the instruction that describes the task:
### Input:
Parses paths in the following formats:
url: username/project/runs/run_id
path: username/project/run_id
docker: username/project:run_id
username is optional and will fallback to the current logged in user.
### Response... |
def select_key(self, key, bucket_name=None,
expression='SELECT * FROM S3Object',
expression_type='SQL',
input_serialization=None,
output_serialization=None):
"""
Reads a key with S3 Select.
:param key: S3 key that will ... | Reads a key with S3 Select.
:param key: S3 key that will point to the file
:type key: str
:param bucket_name: Name of the bucket in which the file is stored
:type bucket_name: str
:param expression: S3 Select expression
:type expression: str
:param expression_typ... | Below is the the instruction that describes the task:
### Input:
Reads a key with S3 Select.
:param key: S3 key that will point to the file
:type key: str
:param bucket_name: Name of the bucket in which the file is stored
:type bucket_name: str
:param expression: S3 Select e... |
def parse_JSON(self, JSON_string):
"""
Parses a *pyowm.stationsapi30.station.Station* instance out of raw JSON
data.
:param JSON_string: a raw JSON string
:type JSON_string: str
:return: a *pyowm.stationsapi30.station.Station** instance or ``None``
if no data... | Parses a *pyowm.stationsapi30.station.Station* instance out of raw JSON
data.
:param JSON_string: a raw JSON string
:type JSON_string: str
:return: a *pyowm.stationsapi30.station.Station** instance or ``None``
if no data is available
:raises: *ParseResponseError* if ... | Below is the the instruction that describes the task:
### Input:
Parses a *pyowm.stationsapi30.station.Station* instance out of raw JSON
data.
:param JSON_string: a raw JSON string
:type JSON_string: str
:return: a *pyowm.stationsapi30.station.Station** instance or ``None``
... |
def _create_folder(local_folder, parent_folder_id):
"""
Function for creating a remote folder and returning the id. This should be
a building block for user-level functions.
:param local_folder: full path to a local folder
:type local_folder: string
:param parent_folder_id: id of parent folder ... | Function for creating a remote folder and returning the id. This should be
a building block for user-level functions.
:param local_folder: full path to a local folder
:type local_folder: string
:param parent_folder_id: id of parent folder on the Midas Server instance,
where the new folder will ... | Below is the the instruction that describes the task:
### Input:
Function for creating a remote folder and returning the id. This should be
a building block for user-level functions.
:param local_folder: full path to a local folder
:type local_folder: string
:param parent_folder_id: id of parent fo... |
def get_signals(signal_array, frame, root_or_cache, ns, multiplex_id, float_factory):
# type: (typing.Sequence[_Element], canmatrix.Frame, _DocRoot, str, _MultiplexId, typing.Callable) -> None
"""Add signals from xml to the Frame."""
global signal_rxs
group_id = 1
if signal_array is None: # Empty s... | Add signals from xml to the Frame. | Below is the the instruction that describes the task:
### Input:
Add signals from xml to the Frame.
### Response:
def get_signals(signal_array, frame, root_or_cache, ns, multiplex_id, float_factory):
# type: (typing.Sequence[_Element], canmatrix.Frame, _DocRoot, str, _MultiplexId, typing.Callable) -> None
... |
def simxSetJointPosition(clientID, jointHandle, position, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
return c_SetJointPosition(clientID, jointHandle, position, operationMode) | Please have a look at the function description/documentation in the V-REP user manual | Below is the the instruction that describes the task:
### Input:
Please have a look at the function description/documentation in the V-REP user manual
### Response:
def simxSetJointPosition(clientID, jointHandle, position, operationMode):
'''
Please have a look at the function description/documentation in ... |
def install_handler(self, event_type, handler, user_handle=None):
"""Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_ha... | Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_handle: A value specified by an application that can be used for identifying ha... | Below is the the instruction that describes the task:
### Input:
Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_handle: A ... |
def characterize_psf(self):
""" Get support size and drift polynomial for current set of params """
# there may be an issue with the support and characterization--
# it might be best to do the characterization with the same support
# as the calculated psf.
l,u = max(self.zrange[0... | Get support size and drift polynomial for current set of params | Below is the the instruction that describes the task:
### Input:
Get support size and drift polynomial for current set of params
### Response:
def characterize_psf(self):
""" Get support size and drift polynomial for current set of params """
# there may be an issue with the support and characteriz... |
def set_fraction(self, value):
"""Set the meter indicator. Value should be between 0 and 1."""
if value < 0:
value *= -1
value = min(value, 1)
if self.horizontal:
width = int(self.width * value)
height = self.height
else:
width = se... | Set the meter indicator. Value should be between 0 and 1. | Below is the the instruction that describes the task:
### Input:
Set the meter indicator. Value should be between 0 and 1.
### Response:
def set_fraction(self, value):
"""Set the meter indicator. Value should be between 0 and 1."""
if value < 0:
value *= -1
value = min(value, 1)... |
def write_screen(self, font, color, screen_pos, text, align="left",
valign="top"):
"""Write to the screen in font.size relative coordinates."""
pos = point.Point(*screen_pos) * point.Point(0.75, 1) * font.get_linesize()
text_surf = font.render(str(text), True, color)
rect = text_surf.... | Write to the screen in font.size relative coordinates. | Below is the the instruction that describes the task:
### Input:
Write to the screen in font.size relative coordinates.
### Response:
def write_screen(self, font, color, screen_pos, text, align="left",
valign="top"):
"""Write to the screen in font.size relative coordinates."""
pos = poin... |
def get_datas(callback, macs=[], run_flag=RunFlag(), bt_device=''):
"""
Get data for all ruuvitag sensors or sensors in the MAC's list.
Args:
callback (func): callback funcion to be called when new data is received
macs (list): MAC addresses
run_flag (object)... | Get data for all ruuvitag sensors or sensors in the MAC's list.
Args:
callback (func): callback funcion to be called when new data is received
macs (list): MAC addresses
run_flag (object): RunFlag object. Function executes while run_flag.running
bt_device (string... | Below is the the instruction that describes the task:
### Input:
Get data for all ruuvitag sensors or sensors in the MAC's list.
Args:
callback (func): callback funcion to be called when new data is received
macs (list): MAC addresses
run_flag (object): RunFlag object. F... |
def is_invertible(self,X):
"""checks if Z is invertible"""
if len(X.shape) == 2:
return X.shape[0] == X.shape[1] and np.linalg.matrix_rank(X) == X.shape[0]
else:
return False | checks if Z is invertible | Below is the the instruction that describes the task:
### Input:
checks if Z is invertible
### Response:
def is_invertible(self,X):
"""checks if Z is invertible"""
if len(X.shape) == 2:
return X.shape[0] == X.shape[1] and np.linalg.matrix_rank(X) == X.shape[0]
else:
... |
def handle_part(self, params):
"""
Handle a client parting from channel(s).
"""
for pchannel in params.split(','):
if pchannel.strip() in self.server.channels:
# Send message to all clients in all channels user is in, and
# remove the user from... | Handle a client parting from channel(s). | Below is the the instruction that describes the task:
### Input:
Handle a client parting from channel(s).
### Response:
def handle_part(self, params):
"""
Handle a client parting from channel(s).
"""
for pchannel in params.split(','):
if pchannel.strip() in self.server.c... |
def labels(self, leaves=True, internal=True):
'''Generator over the (non-``None``) ``Node`` labels of this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False``
... | Generator over the (non-``None``) ``Node`` labels of this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``False`` | Below is the the instruction that describes the task:
### Input:
Generator over the (non-``None``) ``Node`` labels of this ``Tree``
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``... |
def getLocalTempDir(self):
"""
Get a new local temporary directory in which to write files that persist for the duration of
the job.
:return: The absolute path to a new local temporary directory. This directory will exist
for the duration of the job only, and is guarant... | Get a new local temporary directory in which to write files that persist for the duration of
the job.
:return: The absolute path to a new local temporary directory. This directory will exist
for the duration of the job only, and is guaranteed to be deleted once the job
... | Below is the the instruction that describes the task:
### Input:
Get a new local temporary directory in which to write files that persist for the duration of
the job.
:return: The absolute path to a new local temporary directory. This directory will exist
for the duration of the jo... |
def get_subclass_tree(cls, ensure_unique=True):
"""Returns all subclasses (direct and recursive) of cls."""
subclasses = []
# cls.__subclasses__() fails on classes inheriting from type
for subcls in type.__subclasses__(cls):
subclasses.append(subcls)
subclasses.extend(get_subclass_tree(s... | Returns all subclasses (direct and recursive) of cls. | Below is the the instruction that describes the task:
### Input:
Returns all subclasses (direct and recursive) of cls.
### Response:
def get_subclass_tree(cls, ensure_unique=True):
"""Returns all subclasses (direct and recursive) of cls."""
subclasses = []
# cls.__subclasses__() fails on classes inheri... |
def remove(self, item):
"""
See :meth:`~pluginsmanager.observer.observable_list.ObservableList.remove()` method
"""
self.real_list.remove(item)
self._items.remove(item) | See :meth:`~pluginsmanager.observer.observable_list.ObservableList.remove()` method | Below is the the instruction that describes the task:
### Input:
See :meth:`~pluginsmanager.observer.observable_list.ObservableList.remove()` method
### Response:
def remove(self, item):
"""
See :meth:`~pluginsmanager.observer.observable_list.ObservableList.remove()` method
"""
self... |
def typeseq(types):
"""
Returns an escape for a terminal text formatting type, or a list of types.
Valid types are:
* 'i' for 'italic'
* 'b' for 'bold'
* 'u' for 'underline'
* 'r' for 'reverse'
"""
ret = ""
for t in types:
ret += termcap.get(fmttypes[t])
... | Returns an escape for a terminal text formatting type, or a list of types.
Valid types are:
* 'i' for 'italic'
* 'b' for 'bold'
* 'u' for 'underline'
* 'r' for 'reverse' | Below is the the instruction that describes the task:
### Input:
Returns an escape for a terminal text formatting type, or a list of types.
Valid types are:
* 'i' for 'italic'
* 'b' for 'bold'
* 'u' for 'underline'
* 'r' for 'reverse'
### Response:
def typeseq(types):
"""
... |
def _dataset_concat(datasets, dim, data_vars, coords, compat, positions):
"""
Concatenate a sequence of datasets along a new or existing dimension
"""
from .dataset import Dataset
if compat not in ['equals', 'identical']:
raise ValueError("compat=%r invalid: must be 'equals' "
... | Concatenate a sequence of datasets along a new or existing dimension | Below is the the instruction that describes the task:
### Input:
Concatenate a sequence of datasets along a new or existing dimension
### Response:
def _dataset_concat(datasets, dim, data_vars, coords, compat, positions):
"""
Concatenate a sequence of datasets along a new or existing dimension
"""
... |
def make_set(value):
''' Takes a value and turns it into a set
!!!! This is important because set(string) will parse a string to
individual characters vs. adding the string as an element of
the set i.e.
x = 'setvalue'
set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'}
make_set(x) = {'... | Takes a value and turns it into a set
!!!! This is important because set(string) will parse a string to
individual characters vs. adding the string as an element of
the set i.e.
x = 'setvalue'
set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'}
make_set(x) = {'setvalue'}
or use set... | Below is the the instruction that describes the task:
### Input:
Takes a value and turns it into a set
!!!! This is important because set(string) will parse a string to
individual characters vs. adding the string as an element of
the set i.e.
x = 'setvalue'
set(x) = {'t', 'a', 'e', 'v',... |
def _request_pre_prepare(self, three_pc_key: Tuple[int, int],
stash_data: Optional[Tuple[str, str, str]] = None) -> bool:
"""
Request preprepare
"""
recipients = self.primaryName
return self._request_three_phase_msg(three_pc_key,
... | Request preprepare | Below is the the instruction that describes the task:
### Input:
Request preprepare
### Response:
def _request_pre_prepare(self, three_pc_key: Tuple[int, int],
stash_data: Optional[Tuple[str, str, str]] = None) -> bool:
"""
Request preprepare
"""
recipie... |
def compare_string(self, expected_str, actual_str):
"""
Returns True if the two strings are equal, False otherwise
The time taken is independent of the number of characters that match
For the sake of simplicity, this function executes in constant time only
when the two strings ha... | Returns True if the two strings are equal, False otherwise
The time taken is independent of the number of characters that match
For the sake of simplicity, this function executes in constant time only
when the two strings have the same length. It short-circuits when they
have different l... | Below is the the instruction that describes the task:
### Input:
Returns True if the two strings are equal, False otherwise
The time taken is independent of the number of characters that match
For the sake of simplicity, this function executes in constant time only
when the two strings have ... |
def funcNrlTcMotPred(idxPrc,
varPixX,
varPixY,
NrlMdlChunk,
varNumTP,
aryBoxCar, # aryCond
path,
varNumNrlMdls,
varNumMtDrctn,
var... | Function for creating neural time course models.
This function should be used to create neural models if different
predictors for every motion direction are included. | Below is the the instruction that describes the task:
### Input:
Function for creating neural time course models.
This function should be used to create neural models if different
predictors for every motion direction are included.
### Response:
def funcNrlTcMotPred(idxPrc,
varPixX,
... |
def wrap_with_try(self, node):
"""Wrap an ast node in a 'try' node to enter debug on exception."""
handlers = []
if self.ignore_exceptions is None:
handlers.append(ast.ExceptHandler(type=None,
name=None,
... | Wrap an ast node in a 'try' node to enter debug on exception. | Below is the the instruction that describes the task:
### Input:
Wrap an ast node in a 'try' node to enter debug on exception.
### Response:
def wrap_with_try(self, node):
"""Wrap an ast node in a 'try' node to enter debug on exception."""
handlers = []
if self.ignore_exceptions is None:
... |
def build(self, builder):
"""Build XML by appending to builder"""
builder.start("CheckValue", {})
builder.data(str(self.value))
builder.end("CheckValue") | Build XML by appending to builder | Below is the the instruction that describes the task:
### Input:
Build XML by appending to builder
### Response:
def build(self, builder):
"""Build XML by appending to builder"""
builder.start("CheckValue", {})
builder.data(str(self.value))
builder.end("CheckValue") |
def _inner(x, y, axis=-1):
"""Patched version of :func:`sporco.linalg.inner`."""
return cp.sum(x * y, axis=axis, keepdims=True) | Patched version of :func:`sporco.linalg.inner`. | Below is the the instruction that describes the task:
### Input:
Patched version of :func:`sporco.linalg.inner`.
### Response:
def _inner(x, y, axis=-1):
"""Patched version of :func:`sporco.linalg.inner`."""
return cp.sum(x * y, axis=axis, keepdims=True) |
def construct_channel(self, *args, **kwargs):
"""
Create ChannelNode and build topic tree.
"""
channel = self.get_channel(*args, **kwargs) # creates ChannelNode from data in self.channel_info
_build_tree(channel, SAMPLE_TREE)
raise_for_invalid_channel(channel)
... | Create ChannelNode and build topic tree. | Below is the the instruction that describes the task:
### Input:
Create ChannelNode and build topic tree.
### Response:
def construct_channel(self, *args, **kwargs):
"""
Create ChannelNode and build topic tree.
"""
channel = self.get_channel(*args, **kwargs) # creates ChannelNode ... |
def _parse_txtinfo(self, data):
"""
Converts the python list returned by self._txtinfo_to_python()
to a NetworkX Graph object, which is then returned.
"""
graph = self._init_graph()
for link in data:
graph.add_edge(link['source'],
li... | Converts the python list returned by self._txtinfo_to_python()
to a NetworkX Graph object, which is then returned. | Below is the the instruction that describes the task:
### Input:
Converts the python list returned by self._txtinfo_to_python()
to a NetworkX Graph object, which is then returned.
### Response:
def _parse_txtinfo(self, data):
"""
Converts the python list returned by self._txtinfo_to_python(... |
def set_position_target_local_ned_send(self, time_boot_ms, target_system, target_component, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate, force_mavlink1=False):
'''
Sets a desired vehicle position in a local north-east-down coordinate
fra... | Sets a desired vehicle position in a local north-east-down coordinate
frame. Used by an external controller to command the
vehicle (manual controller or other system).
time_boot_ms : Timestamp in milliseconds since system boot (uint32_t)
targ... | Below is the the instruction that describes the task:
### Input:
Sets a desired vehicle position in a local north-east-down coordinate
frame. Used by an external controller to command the
vehicle (manual controller or other system).
time_boot_ms : Timest... |
def user(self):
"""Creates a User object when requested."""
try:
return self._user
except AttributeError:
self._user = MatrixUser(self.mxid, self.Api(identity=self.mxid))
return self._user | Creates a User object when requested. | Below is the the instruction that describes the task:
### Input:
Creates a User object when requested.
### Response:
def user(self):
"""Creates a User object when requested."""
try:
return self._user
except AttributeError:
self._user = MatrixUser(self.mxid, self.Api(... |
def set(self, name: str, value: str) -> None:
"""
重写请求中的 header, 不推荐使用
"""
name = name.casefold()
self._headers[name] = value | 重写请求中的 header, 不推荐使用 | Below is the the instruction that describes the task:
### Input:
重写请求中的 header, 不推荐使用
### Response:
def set(self, name: str, value: str) -> None:
"""
重写请求中的 header, 不推荐使用
"""
name = name.casefold()
self._headers[name] = value |
def _buildArgs(f, self=None, kwargs={}):
"""
Get the default arguments from the function and assign as instance vars.
Return a list of 3-tuples with (name, description, defaultValue) for each
argument to the function.
Assigns all arguments to the function as instance variables of TMRegion.
If the argume... | Get the default arguments from the function and assign as instance vars.
Return a list of 3-tuples with (name, description, defaultValue) for each
argument to the function.
Assigns all arguments to the function as instance variables of TMRegion.
If the argument was not provided, uses the default value.
P... | Below is the the instruction that describes the task:
### Input:
Get the default arguments from the function and assign as instance vars.
Return a list of 3-tuples with (name, description, defaultValue) for each
argument to the function.
Assigns all arguments to the function as instance variables of TMReg... |
def _grep_qstat(self, status_type='complete'):
""" Greps qstat -e <job_id> for information from the queue.
:paramsstatus_type: complete, queued, running, error, gone
"""
args = "qstat -e {}".format(self.id).split()
res, _ = call(args)
if res == '': return False
re... | Greps qstat -e <job_id> for information from the queue.
:paramsstatus_type: complete, queued, running, error, gone | Below is the the instruction that describes the task:
### Input:
Greps qstat -e <job_id> for information from the queue.
:paramsstatus_type: complete, queued, running, error, gone
### Response:
def _grep_qstat(self, status_type='complete'):
""" Greps qstat -e <job_id> for information from the queue... |
def baba_panel_plot(
ttree,
tests,
boots,
show_tip_labels=True,
show_test_labels=True,
use_edge_lengths=False,
collapse_outgroup=False,
pct_tree_x=0.4,
pct_tree_y=0.2,
alpha=3.0,
*args,
**kwargs):
"""
signature...
"""
## create Panel plot object an... | signature... | Below is the the instruction that describes the task:
### Input:
signature...
### Response:
def baba_panel_plot(
ttree,
tests,
boots,
show_tip_labels=True,
show_test_labels=True,
use_edge_lengths=False,
collapse_outgroup=False,
pct_tree_x=0.4,
pct_tree_y=0.2,
alpha=3.0... |
def _element(cls):
''' find the element 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"]).un... | find the element with controls | Below is the the instruction that describes the task:
### Input:
find the element with controls
### Response:
def _element(cls):
''' find the element with controls '''
if not cls.__is_selector():
raise Exception("Invalid selector[%s]." %cls.__control["by"])
drive... |
def copen(fileobj, mode='rb', **kwargs):
"""Detects and opens compressed file for reading and writing.
Args:
fileobj (File): any File-like object supported by an underlying
compression algorithm
mode (unicode): mode to open fileobj with
**kwargs: keyword-argume... | Detects and opens compressed file for reading and writing.
Args:
fileobj (File): any File-like object supported by an underlying
compression algorithm
mode (unicode): mode to open fileobj with
**kwargs: keyword-arguments to pass to the compression algorithm
Re... | Below is the the instruction that describes the task:
### Input:
Detects and opens compressed file for reading and writing.
Args:
fileobj (File): any File-like object supported by an underlying
compression algorithm
mode (unicode): mode to open fileobj with
**k... |
def rgb_to_hsv(rgb):
"""
Convert an RGB color representation to an HSV color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: HSV representa... | Convert an RGB color representation to an HSV color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: HSV representation of the input RGB value.
... | Below is the the instruction that describes the task:
### Input:
Convert an RGB color representation to an HSV color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blu... |
def _build_generator_list(network):
"""Builds DataFrames with all generators in MV and LV grids
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
A DataFrame with id of and reference to MV generators
:pandas:`pandas.DataFrame<dataframe>`
A DataFrame with id of and refere... | Builds DataFrames with all generators in MV and LV grids
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
A DataFrame with id of and reference to MV generators
:pandas:`pandas.DataFrame<dataframe>`
A DataFrame with id of and reference to LV generators
:pandas:`pandas.Da... | Below is the the instruction that describes the task:
### Input:
Builds DataFrames with all generators in MV and LV grids
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
A DataFrame with id of and reference to MV generators
:pandas:`pandas.DataFrame<dataframe>`
A DataF... |
def cmd_tool(args=None):
""" Command line tool to make a md5sum comparison of two .fil files. """
if 'bl' in local_host:
header_loc = '/usr/local/sigproc/bin/header' #Current location of header command in GBT.
else:
raise IOError('Script only able to run in BL systems.')
p = OptionPars... | Command line tool to make a md5sum comparison of two .fil files. | Below is the the instruction that describes the task:
### Input:
Command line tool to make a md5sum comparison of two .fil files.
### Response:
def cmd_tool(args=None):
""" Command line tool to make a md5sum comparison of two .fil files. """
if 'bl' in local_host:
header_loc = '/usr/local/sigproc/... |
def synchronized(obj):
"""
This function has two purposes:
1. Decorate a function that automatically synchronizes access to the object
passed as the first argument (usually `self`, for member methods)
2. Synchronize access to the object, used in a `with`-statement.
Note that you can use #wait(), #notif... | This function has two purposes:
1. Decorate a function that automatically synchronizes access to the object
passed as the first argument (usually `self`, for member methods)
2. Synchronize access to the object, used in a `with`-statement.
Note that you can use #wait(), #notify() and #notify_all() only on
... | Below is the the instruction that describes the task:
### Input:
This function has two purposes:
1. Decorate a function that automatically synchronizes access to the object
passed as the first argument (usually `self`, for member methods)
2. Synchronize access to the object, used in a `with`-statement.
... |
def _hash_file(self, algo):
"""Get the hash of the given file
:param algo: The algorithm to use.
:type algo: str
:return: The hexdigest of the data.
:rtype: str
"""
# We het the algorithm function.
hash_data = getattr(hashlib, algo)()
with open... | Get the hash of the given file
:param algo: The algorithm to use.
:type algo: str
:return: The hexdigest of the data.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Get the hash of the given file
:param algo: The algorithm to use.
:type algo: str
:return: The hexdigest of the data.
:rtype: str
### Response:
def _hash_file(self, algo):
"""Get the hash of the given file
... |
def build(path, query=None, fragment=''):
"""
Generates a URL based on the inputted path and given query options and
fragment. The query should be a dictionary of terms that will be
generated into the URL, while the fragment is the anchor point within the
target path that will be navigated to. If ... | Generates a URL based on the inputted path and given query options and
fragment. The query should be a dictionary of terms that will be
generated into the URL, while the fragment is the anchor point within the
target path that will be navigated to. If there are any wildcards within
the path that are f... | Below is the the instruction that describes the task:
### Input:
Generates a URL based on the inputted path and given query options and
fragment. The query should be a dictionary of terms that will be
generated into the URL, while the fragment is the anchor point within the
target path that will be nav... |
def add_observer(self, o, component_type=ComponentType):
"""
Add a callback that will get invoked after each component is called.
Args:
o (func): the callback function
Keyword Args:
component_type (ComponentType): the :class:`ComponentType` to observe.
... | Add a callback that will get invoked after each component is called.
Args:
o (func): the callback function
Keyword Args:
component_type (ComponentType): the :class:`ComponentType` to observe.
The callback will fire any time an instance of the class or its
... | Below is the the instruction that describes the task:
### Input:
Add a callback that will get invoked after each component is called.
Args:
o (func): the callback function
Keyword Args:
component_type (ComponentType): the :class:`ComponentType` to observe.
T... |
def this_and_prev(iterable):
"""Walk an iterable, returning the current and previous items
as a two-tuple."""
try:
item = next(iterable)
while True:
next_item = next(iterable)
yield item, next_item
item = next_item
except StopIteration:
return | Walk an iterable, returning the current and previous items
as a two-tuple. | Below is the the instruction that describes the task:
### Input:
Walk an iterable, returning the current and previous items
as a two-tuple.
### Response:
def this_and_prev(iterable):
"""Walk an iterable, returning the current and previous items
as a two-tuple."""
try:
item = next(iterable)
... |
def monitor(app):
"""Set up application monitoring."""
heroku_app = HerokuApp(dallinger_uid=app)
webbrowser.open(heroku_app.dashboard_url)
webbrowser.open("https://requester.mturk.com/mturk/manageHITs")
heroku_app.open_logs()
check_call(["open", heroku_app.db_uri])
while _keep_running():
... | Set up application monitoring. | Below is the the instruction that describes the task:
### Input:
Set up application monitoring.
### Response:
def monitor(app):
"""Set up application monitoring."""
heroku_app = HerokuApp(dallinger_uid=app)
webbrowser.open(heroku_app.dashboard_url)
webbrowser.open("https://requester.mturk.com/mturk... |
def boundary_difference_exponential(graph, xxx_todo_changeme4):
r"""
Boundary term processing adjacent voxels difference value using an exponential relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
Finds ... | r"""
Boundary term processing adjacent voxels difference value using an exponential relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
Finds all edges between all neighbours of the image and uses their differe... | Below is the the instruction that describes the task:
### Input:
r"""
Boundary term processing adjacent voxels difference value using an exponential relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
Finds... |
def get_module(self, module_name):
"""Return loaded module from the given name."""
try:
return self.module[module_name]
except KeyError:
return sys.modules[module_name] | Return loaded module from the given name. | Below is the the instruction that describes the task:
### Input:
Return loaded module from the given name.
### Response:
def get_module(self, module_name):
"""Return loaded module from the given name."""
try:
return self.module[module_name]
except KeyError:
return s... |
def _init_metadata(self):
"""stub"""
self._start_timestamp_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'start_timestamp'),
'element_label': 'start timestamp',
... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def _init_metadata(self):
"""stub"""
self._start_timestamp_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
... |
def poisson(lam=1, shape=_Null, dtype=_Null, **kwargs):
"""Draw random samples from a Poisson distribution.
Samples are distributed according to a Poisson distribution parametrized
by *lambda* (rate). Samples will always be returned as a floating point data type.
Parameters
----------
lam : fl... | Draw random samples from a Poisson distribution.
Samples are distributed according to a Poisson distribution parametrized
by *lambda* (rate). Samples will always be returned as a floating point data type.
Parameters
----------
lam : float or Symbol, optional
Expectation of interval, should... | Below is the the instruction that describes the task:
### Input:
Draw random samples from a Poisson distribution.
Samples are distributed according to a Poisson distribution parametrized
by *lambda* (rate). Samples will always be returned as a floating point data type.
Parameters
----------
la... |
def _zoom_rows(self, zoom):
"""Zooms grid rows"""
self.grid.SetDefaultRowSize(self.grid.std_row_size * zoom,
resizeExistingRows=True)
self.grid.SetRowLabelSize(self.grid.row_label_size * zoom)
for row, tab in self.code_array.row_heights:
... | Zooms grid rows | Below is the the instruction that describes the task:
### Input:
Zooms grid rows
### Response:
def _zoom_rows(self, zoom):
"""Zooms grid rows"""
self.grid.SetDefaultRowSize(self.grid.std_row_size * zoom,
resizeExistingRows=True)
self.grid.SetRowLabelSize... |
def awd_lstm_lm_split(model:nn.Module) -> List[nn.Module]:
"Split a RNN `model` in groups for differential learning rates."
groups = [[rnn, dp] for rnn, dp in zip(model[0].rnns, model[0].hidden_dps)]
return groups + [[model[0].encoder, model[0].encoder_dp, model[1]]] | Split a RNN `model` in groups for differential learning rates. | Below is the the instruction that describes the task:
### Input:
Split a RNN `model` in groups for differential learning rates.
### Response:
def awd_lstm_lm_split(model:nn.Module) -> List[nn.Module]:
"Split a RNN `model` in groups for differential learning rates."
groups = [[rnn, dp] for rnn, dp in zip(mo... |
def create_vmss(access_token, subscription_id, resource_group, vmss_name, vm_size, capacity,
publisher, offer, sku, version, subnet_id, location, be_pool_id=None,
lb_pool_id=None, storage_type='Standard_LRS', username='azure', password=None,
public_key=None, overprovision... | Create virtual machine scale set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vmss_name (str): Name of the new scale set.
vm_size (str): Size of virtual machine, ... | Below is the the instruction that describes the task:
### Input:
Create virtual machine scale set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vmss_name (str): Name o... |
def _do_search(conf):
'''
Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use.
'''
# Build LDAP connection args
connargs = {}
for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']:
connar... | Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use. | Below is the the instruction that describes the task:
### Input:
Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use.
### Response:
def _do_search(conf):
'''
Builds connection and search arguments, performs the LDAP search ... |
def copy_inner(self, scope):
"""Copy block contents (properties, inner blocks).
Renames inner block from current scope.
Used for mixins.
args:
scope (Scope): Current scope
returns:
list (block contents)
"""
if self.tokens[1]:
to... | Copy block contents (properties, inner blocks).
Renames inner block from current scope.
Used for mixins.
args:
scope (Scope): Current scope
returns:
list (block contents) | Below is the the instruction that describes the task:
### Input:
Copy block contents (properties, inner blocks).
Renames inner block from current scope.
Used for mixins.
args:
scope (Scope): Current scope
returns:
list (block contents)
### Response:
def copy_... |
def save(self, filename=None, directory=None):
"""Save the DOT source to file. Ensure the file ends with a newline.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
Returns:
... | Save the DOT source to file. Ensure the file ends with a newline.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
Returns:
The (possibly relative) path of the saved source fi... | Below is the the instruction that describes the task:
### Input:
Save the DOT source to file. Ensure the file ends with a newline.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
Ret... |
def newline(self):
"""Write eol, then start new line."""
self.write_str(self.eol)
self.room = self.maxlinelen | Write eol, then start new line. | Below is the the instruction that describes the task:
### Input:
Write eol, then start new line.
### Response:
def newline(self):
"""Write eol, then start new line."""
self.write_str(self.eol)
self.room = self.maxlinelen |
def script_to_html(script_file, html_file, args=None, unknown_args=None):
'''
Convert sos file to html format with syntax highlighting, and
either save the output either to a HTML file or view it in a broaser.
This converter accepts additional parameters --style or pygments
styles, --linenos for dis... | Convert sos file to html format with syntax highlighting, and
either save the output either to a HTML file or view it in a broaser.
This converter accepts additional parameters --style or pygments
styles, --linenos for displaying linenumbers, and a parameter --raw
to embed a URL to the raw sos file. | Below is the the instruction that describes the task:
### Input:
Convert sos file to html format with syntax highlighting, and
either save the output either to a HTML file or view it in a broaser.
This converter accepts additional parameters --style or pygments
styles, --linenos for displaying linenumbe... |
async def eventuallyAll(*coroFuncs: FlexFunc, # (use functools.partials if needed)
totalTimeout: float,
retryWait: float=0.1,
acceptableExceptions=None,
acceptableFails: int=0,
override_timeout_limit... | :param coroFuncs: iterable of no-arg functions
:param totalTimeout:
:param retryWait:
:param acceptableExceptions:
:param acceptableFails: how many of the passed in coroutines can
ultimately fail and still be ok
:return: | Below is the the instruction that describes the task:
### Input:
:param coroFuncs: iterable of no-arg functions
:param totalTimeout:
:param retryWait:
:param acceptableExceptions:
:param acceptableFails: how many of the passed in coroutines can
ultimately fail and still be ok
:return... |
def editHook(self, repo_user, repo_name, hook_id, name, config,
events=None, add_events=None, remove_events=None, active=None):
"""
PATCH /repos/:owner/:repo/hooks/:id
:param hook_id: Id of the hook.
:param name: The name of the service that is being called.
:param ... | PATCH /repos/:owner/:repo/hooks/:id
:param hook_id: Id of the hook.
:param name: The name of the service that is being called.
:param config: A Hash containing key/value pairs to provide settings
for this hook. | Below is the the instruction that describes the task:
### Input:
PATCH /repos/:owner/:repo/hooks/:id
:param hook_id: Id of the hook.
:param name: The name of the service that is being called.
:param config: A Hash containing key/value pairs to provide settings
for th... |
def _collection_html_response(resources, start=0, stop=20):
"""Return the HTML representation of the collection *resources*.
:param list resources: list of :class:`sandman.model.Model`s to render
:rtype: :class:`flask.Response`
"""
return make_response(render_template(
'collection.html',
... | Return the HTML representation of the collection *resources*.
:param list resources: list of :class:`sandman.model.Model`s to render
:rtype: :class:`flask.Response` | Below is the the instruction that describes the task:
### Input:
Return the HTML representation of the collection *resources*.
:param list resources: list of :class:`sandman.model.Model`s to render
:rtype: :class:`flask.Response`
### Response:
def _collection_html_response(resources, start=0, stop=20):
... |
def ipv6_prefix_to_mask(prefix):
"""
ipv6 cidr prefix to net mask
:param prefix: cidr prefix, rang in (0, 128)
:type prefix: int
:return: comma separated ipv6 net mask code,
eg: ffff:ffff:ffff:ffff:0000:0000:0000:0000
:rtype: str
"""
if prefix > 128 or prefix < 0:
r... | ipv6 cidr prefix to net mask
:param prefix: cidr prefix, rang in (0, 128)
:type prefix: int
:return: comma separated ipv6 net mask code,
eg: ffff:ffff:ffff:ffff:0000:0000:0000:0000
:rtype: str | Below is the the instruction that describes the task:
### Input:
ipv6 cidr prefix to net mask
:param prefix: cidr prefix, rang in (0, 128)
:type prefix: int
:return: comma separated ipv6 net mask code,
eg: ffff:ffff:ffff:ffff:0000:0000:0000:0000
:rtype: str
### Response:
def ipv6_pref... |
def configure(
self,
*,
read_fragment_size=None,
write_fragment_size=None,
use_display_names=None,
single_bit_uint_as_bool=None,
integer_interpolation=None,
):
""" configure MDF parameters
Parameters
----------
read_fragment_si... | configure MDF parameters
Parameters
----------
read_fragment_size : int
size hint of split data blocks, default 8MB; if the initial size is
smaller, then no data list is used. The actual split size depends on
the data groups' records size
write_fragme... | Below is the the instruction that describes the task:
### Input:
configure MDF parameters
Parameters
----------
read_fragment_size : int
size hint of split data blocks, default 8MB; if the initial size is
smaller, then no data list is used. The actual split size depe... |
def run_script(self, script_name, keys=None, args=None):
"""
Execute a walrus script with the given arguments.
:param script_name: The base name of the script to execute.
:param list keys: Keys referenced by the script.
:param list args: Arguments passed in to the script.
... | Execute a walrus script with the given arguments.
:param script_name: The base name of the script to execute.
:param list keys: Keys referenced by the script.
:param list args: Arguments passed in to the script.
:returns: Return value of script.
.. note:: Redis scripts require ... | Below is the the instruction that describes the task:
### Input:
Execute a walrus script with the given arguments.
:param script_name: The base name of the script to execute.
:param list keys: Keys referenced by the script.
:param list args: Arguments passed in to the script.
:retur... |
def removeNotification(self, notificationId):
"""Destroy a notification, hiding it first if it currently shown to the user."""
fn = self.function_table.removeNotification
result = fn(notificationId)
return result | Destroy a notification, hiding it first if it currently shown to the user. | Below is the the instruction that describes the task:
### Input:
Destroy a notification, hiding it first if it currently shown to the user.
### Response:
def removeNotification(self, notificationId):
"""Destroy a notification, hiding it first if it currently shown to the user."""
fn = self.functio... |
def unix_time(dt=None, as_int=False):
"""Generate a unix style timestamp (in seconds)"""
if dt is None:
dt = datetime.datetime.utcnow()
if type(dt) is datetime.date:
dt = date_to_datetime(dt)
epoch = datetime.datetime.utcfromtimestamp(0)
delta = dt - epoch
if as_int:
... | Generate a unix style timestamp (in seconds) | Below is the the instruction that describes the task:
### Input:
Generate a unix style timestamp (in seconds)
### Response:
def unix_time(dt=None, as_int=False):
"""Generate a unix style timestamp (in seconds)"""
if dt is None:
dt = datetime.datetime.utcnow()
if type(dt) is datetime.date:
... |
def user_names_like(cls, user_name, db_session=None):
"""
fetch users with similar names using LIKE clause
:param user_name:
:param db_session:
:return:
"""
db_session = get_db_session(db_session)
query = db_session.query(cls.model)
query = query.... | fetch users with similar names using LIKE clause
:param user_name:
:param db_session:
:return: | Below is the the instruction that describes the task:
### Input:
fetch users with similar names using LIKE clause
:param user_name:
:param db_session:
:return:
### Response:
def user_names_like(cls, user_name, db_session=None):
"""
fetch users with similar names using LIKE ... |
def match_tokens(ast_tokens, ast_types):
"""
Verify that each token in order does match the expected types.
The list provided by `get_tokens` does have three more elements
at the beginning of the list which should be always the same
for a condition (Module and Expr). Those are a... | Verify that each token in order does match the expected types.
The list provided by `get_tokens` does have three more elements
at the beginning of the list which should be always the same
for a condition (Module and Expr). Those are automatically
added first to the final list of expecte... | Below is the the instruction that describes the task:
### Input:
Verify that each token in order does match the expected types.
The list provided by `get_tokens` does have three more elements
at the beginning of the list which should be always the same
for a condition (Module and Expr). Tho... |
def get_data(name='sms-spam', nrows=None, limit=None):
""" Load data from a json, csv, or txt file if it exists in the data dir.
References:
[cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp)
[cities](http://download.geonames.org/export/dump/cities.zip)
[cities_us](ht... | Load data from a json, csv, or txt file if it exists in the data dir.
References:
[cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp)
[cities](http://download.geonames.org/export/dump/cities.zip)
[cities_us](http://download.geonames.org/export/dump/cities_us.zip)
>>> ... | Below is the the instruction that describes the task:
### Input:
Load data from a json, csv, or txt file if it exists in the data dir.
References:
[cities_air_pollution_index](https://www.numbeo.com/pollution/rankings.jsp)
[cities](http://download.geonames.org/export/dump/cities.zip)
[cities_... |
def get_objective_lookup_session(self, proxy):
"""Gets the ``OsidSession`` associated with the objective lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveLookupSession) - an
``ObjectiveLookupSession``
raise: NullArgument - ``prox... | Gets the ``OsidSession`` associated with the objective lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveLookupSession) - an
``ObjectiveLookupSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable t... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the objective lookup service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveLookupSession) - an
``ObjectiveLookupSession``
raise: NullArgume... |
def generate_listall_output(lines, resources, aws_config, template, arguments, nodup = False):
"""
Format and print the output of ListAll
:param lines:
:param resources:
:param aws_config:
:param template:
:param arguments:
:param nodup:
:return:
"""
for line in lines:
... | Format and print the output of ListAll
:param lines:
:param resources:
:param aws_config:
:param template:
:param arguments:
:param nodup:
:return: | Below is the the instruction that describes the task:
### Input:
Format and print the output of ListAll
:param lines:
:param resources:
:param aws_config:
:param template:
:param arguments:
:param nodup:
:return:
### Response:
def generate_listall_output(lines, resources, aws_config, t... |
def get_inflators(target_year):
'''
Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement
à partir des masses de comptabilité nationale et des masses de consommation de bdf.
'''
data_year = find_nearest_inferior(data_years, target_year)
inflators_bdf_t... | Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement
à partir des masses de comptabilité nationale et des masses de consommation de bdf. | Below is the the instruction that describes the task:
### Input:
Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement
à partir des masses de comptabilité nationale et des masses de consommation de bdf.
### Response:
def get_inflators(target_year):
'''
Foncti... |
def new_app(self, App, prefix=None, callable=None, **params):
"""Invoke this method in the :meth:`build` method as many times
as the number of :class:`Application` required by this
:class:`MultiApp`.
:param App: an :class:`Application` class.
:param prefix: The prefix to use for... | Invoke this method in the :meth:`build` method as many times
as the number of :class:`Application` required by this
:class:`MultiApp`.
:param App: an :class:`Application` class.
:param prefix: The prefix to use for the application,
the prefix is appended to
the a... | Below is the the instruction that describes the task:
### Input:
Invoke this method in the :meth:`build` method as many times
as the number of :class:`Application` required by this
:class:`MultiApp`.
:param App: an :class:`Application` class.
:param prefix: The prefix to use for the... |
def string_presenter(self, dumper, data):
"""Presenter to force yaml.dump to use multi-line string style."""
if '\n' in data:
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
else:
return dumper.represent_scalar('tag:yaml.org,2002:str', data) | Presenter to force yaml.dump to use multi-line string style. | Below is the the instruction that describes the task:
### Input:
Presenter to force yaml.dump to use multi-line string style.
### Response:
def string_presenter(self, dumper, data):
"""Presenter to force yaml.dump to use multi-line string style."""
if '\n' in data:
return dumper.represent_scalar('tag... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.