code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_portchannel_info_by_intf_output_lacp_admin_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf")
config = get_portchannel_info_by_intf
output = ET.SubElement(get_port... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_portchannel_info_by_intf_output_lacp_admin_key(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_portchannel_info_by_intf = ET.Element("get_portchan... |
def setTableType( self, tableType ):
"""
Sets the table type for this record box to the inputed table type.
:param tableType | <orb.Table>
"""
self._tableType = tableType
if tableType:
self._tableTypeName = tableType.schema(... | Sets the table type for this record box to the inputed table type.
:param tableType | <orb.Table> | Below is the the instruction that describes the task:
### Input:
Sets the table type for this record box to the inputed table type.
:param tableType | <orb.Table>
### Response:
def setTableType( self, tableType ):
"""
Sets the table type for this record box to the inputed ... |
def prepare_notification(self, *, subscribers=None, instance=None,
loop=None, notify_external=True):
"""Sets up a and configures an `~.utils.Executor`:class: instance."""
# merge callbacks added to the class level with those added to the
# instance, giving the former... | Sets up a and configures an `~.utils.Executor`:class: instance. | Below is the the instruction that describes the task:
### Input:
Sets up a and configures an `~.utils.Executor`:class: instance.
### Response:
def prepare_notification(self, *, subscribers=None, instance=None,
loop=None, notify_external=True):
"""Sets up a and configures an `~.... |
def make_div(unit, length=24,
start='', end='',
literal_unit=False):
"""
Generate and return a custom divider.
:param unit: str containing a repeating unit
:param length: The maximum length (won't be exceeded) (default: 24)
:param start: optional starting string
:param... | Generate and return a custom divider.
:param unit: str containing a repeating unit
:param length: The maximum length (won't be exceeded) (default: 24)
:param start: optional starting string
:param end: optional ending string
:param literal_unit: if True will not try to break
unit down into smal... | Below is the the instruction that describes the task:
### Input:
Generate and return a custom divider.
:param unit: str containing a repeating unit
:param length: The maximum length (won't be exceeded) (default: 24)
:param start: optional starting string
:param end: optional ending string
:para... |
def has_error(self):
"""
Queries the server to check if the job has an error.
Returns True or False.
"""
self.get_info()
if 'status' not in self.info:
return False
if 'hasError' not in self.info['status']:
return False
return self... | Queries the server to check if the job has an error.
Returns True or False. | Below is the the instruction that describes the task:
### Input:
Queries the server to check if the job has an error.
Returns True or False.
### Response:
def has_error(self):
"""
Queries the server to check if the job has an error.
Returns True or False.
"""
self.ge... |
def resolve_action(self, p_action_str, p_size=None):
"""
Checks whether action specified in p_action_str is "built-in" or
contains topydo command (i.e. starts with 'cmd') and forwards it to
proper executing methods.
p_size should be specified for some of the builtin actions like... | Checks whether action specified in p_action_str is "built-in" or
contains topydo command (i.e. starts with 'cmd') and forwards it to
proper executing methods.
p_size should be specified for some of the builtin actions like 'up' or
'home' as they can interact with urwid.ListBox.keypress ... | Below is the the instruction that describes the task:
### Input:
Checks whether action specified in p_action_str is "built-in" or
contains topydo command (i.e. starts with 'cmd') and forwards it to
proper executing methods.
p_size should be specified for some of the builtin actions like 'up... |
def load(stream, container=dict):
"""
Load and parse a file or file-like object 'stream' provides simple shell
variables' definitions.
:param stream: A file or file like object
:param container:
Factory function to create a dict-like object to store properties
:return: Dict-like object ... | Load and parse a file or file-like object 'stream' provides simple shell
variables' definitions.
:param stream: A file or file like object
:param container:
Factory function to create a dict-like object to store properties
:return: Dict-like object holding shell variables' definitions
>>> ... | Below is the the instruction that describes the task:
### Input:
Load and parse a file or file-like object 'stream' provides simple shell
variables' definitions.
:param stream: A file or file like object
:param container:
Factory function to create a dict-like object to store properties
:re... |
def read_array(path, mmap_mode=None):
"""Read a .npy array."""
file_ext = op.splitext(path)[1]
if file_ext == '.npy':
return np.load(path, mmap_mode=mmap_mode)
raise NotImplementedError("The file extension `{}` ".format(file_ext) +
"is not currently supported.") | Read a .npy array. | Below is the the instruction that describes the task:
### Input:
Read a .npy array.
### Response:
def read_array(path, mmap_mode=None):
"""Read a .npy array."""
file_ext = op.splitext(path)[1]
if file_ext == '.npy':
return np.load(path, mmap_mode=mmap_mode)
raise NotImplementedError("The fi... |
def plot_leverages(self):
"""
Leverage (h) per observation, with a red line plotted at y = 1/Number of samples (expected
:return: Plot with observation leverages (h)
"""
plt.figure()
lev = self.leverages()
plt.xlabel('Sample Index')
plt.ylabel('Leverage')
... | Leverage (h) per observation, with a red line plotted at y = 1/Number of samples (expected
:return: Plot with observation leverages (h) | Below is the the instruction that describes the task:
### Input:
Leverage (h) per observation, with a red line plotted at y = 1/Number of samples (expected
:return: Plot with observation leverages (h)
### Response:
def plot_leverages(self):
"""
Leverage (h) per observation, with a red line ... |
def parse_doc_str(text=None, is_untabbed=True, is_stripped=True,
tab=None, split_character="::"):
"""
Returns a str of the parsed doc for example
the following would return 'a:A\nb:B' ::
a:A
b:B
:param text: str of the text to parse, by
... | Returns a str of the parsed doc for example
the following would return 'a:A\nb:B' ::
a:A
b:B
:param text: str of the text to parse, by
default uses calling function doc
:param is_untabbed: bool if True will untab the text
:param is_stripped: ... | Below is the the instruction that describes the task:
### Input:
Returns a str of the parsed doc for example
the following would return 'a:A\nb:B' ::
a:A
b:B
:param text: str of the text to parse, by
default uses calling function doc
:param is_unt... |
def can_undo(self):
"""
Are there actions to undo?
"""
return bool(self._undo) or bool(self._open and self._open[0]) | Are there actions to undo? | Below is the the instruction that describes the task:
### Input:
Are there actions to undo?
### Response:
def can_undo(self):
"""
Are there actions to undo?
"""
return bool(self._undo) or bool(self._open and self._open[0]) |
def verify_uploaded_file(
self,
destination_folder_id,
source_path,
verbose = True,
):
'''
Verifies the integrity of a file uploaded to Box
'''
source_file_size = os.stat(source_path).st_size
total_part_size = 0
file_po... | Verifies the integrity of a file uploaded to Box | Below is the the instruction that describes the task:
### Input:
Verifies the integrity of a file uploaded to Box
### Response:
def verify_uploaded_file(
self,
destination_folder_id,
source_path,
verbose = True,
):
'''
Verifies the integrity of a ... |
def inject_func_as_property(self, func, method_name=None, class_=None):
"""
WARNING:
properties are more safely injected using metaclasses
References:
http://stackoverflow.com/questions/13850114/dynamically-adding-methods-with-or-without-metaclass-in-python
"""
if method_name is Non... | WARNING:
properties are more safely injected using metaclasses
References:
http://stackoverflow.com/questions/13850114/dynamically-adding-methods-with-or-without-metaclass-in-python | Below is the the instruction that describes the task:
### Input:
WARNING:
properties are more safely injected using metaclasses
References:
http://stackoverflow.com/questions/13850114/dynamically-adding-methods-with-or-without-metaclass-in-python
### Response:
def inject_func_as_property(self,... |
def read_adjacency_matrix(filename, directed=True, **kwargs):
"""Read a file (containing an adjacency matrix) and convert it into a
directed or undirected networkx graph.
:param filename: file to read or DataFrame containing the data
:type filename: str or pandas.DataFrame
:param directed: Return d... | Read a file (containing an adjacency matrix) and convert it into a
directed or undirected networkx graph.
:param filename: file to read or DataFrame containing the data
:type filename: str or pandas.DataFrame
:param directed: Return directed graph
:type directed: bool
:param kwargs: extra param... | Below is the the instruction that describes the task:
### Input:
Read a file (containing an adjacency matrix) and convert it into a
directed or undirected networkx graph.
:param filename: file to read or DataFrame containing the data
:type filename: str or pandas.DataFrame
:param directed: Return d... |
def prj_created_data(project, role):
"""Return the data for created
:param project: the project that holds the data
:type project: :class:`jukeboxcore.djadapter.models.Project`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the created
:rtype: depending on... | Return the data for created
:param project: the project that holds the data
:type project: :class:`jukeboxcore.djadapter.models.Project`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the created
:rtype: depending on role
:raises: None | Below is the the instruction that describes the task:
### Input:
Return the data for created
:param project: the project that holds the data
:type project: :class:`jukeboxcore.djadapter.models.Project`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the created... |
def by_pattern(self,
pattern,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.zipcode.name,
ascending=True,
returns=DEFAULT_LIMIT):
"""
Search zipcode by wildcard.
Returns multiple results.
... | Search zipcode by wildcard.
Returns multiple results. | Below is the the instruction that describes the task:
### Input:
Search zipcode by wildcard.
Returns multiple results.
### Response:
def by_pattern(self,
pattern,
zipcode_type=ZipcodeType.Standard,
sort_by=SimpleZipcode.zipcode.name,
... |
def log(self, msg):
"Dejar mensaje en bitacora de depuración (método interno)"
if not isinstance(msg, unicode):
msg = unicode(msg, 'utf8', 'ignore')
if not self.Log:
self.Log = StringIO()
self.Log.write(msg)
self.Log.write('\n\r')
if DEBUG:
... | Dejar mensaje en bitacora de depuración (método interno) | Below is the the instruction that describes the task:
### Input:
Dejar mensaje en bitacora de depuración (método interno)
### Response:
def log(self, msg):
"Dejar mensaje en bitacora de depuración (método interno)"
if not isinstance(msg, unicode):
msg = unicode(msg, 'utf8', 'ignore')
... |
def _AddToSingleColumnTable(self, tableName, columnHeading, newValue):
"""
Add an entry to a table containing a single column. Checks existing
table entries to avoid duplicate entries if the given value already
exists in the table.
Parameters
----------
tableName : string
Name of ... | Add an entry to a table containing a single column. Checks existing
table entries to avoid duplicate entries if the given value already
exists in the table.
Parameters
----------
tableName : string
Name of table to add entry to.
columnHeading : string
Name of column heading... | Below is the the instruction that describes the task:
### Input:
Add an entry to a table containing a single column. Checks existing
table entries to avoid duplicate entries if the given value already
exists in the table.
Parameters
----------
tableName : string
Name of table to add e... |
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address):
"""Edit the properties of a service group."""
mgr = SoftLayer.LoadBalancerManager(env.client)
loadbal_id, service_id = loadbal.parse_id(identifier)
# check if any input is provided
if ((not any([ip_address, weight, por... | Edit the properties of a service group. | Below is the the instruction that describes the task:
### Input:
Edit the properties of a service group.
### Response:
def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address):
"""Edit the properties of a service group."""
mgr = SoftLayer.LoadBalancerManager(env.client)
loadbal_i... |
def _get_instance(self, **kwargs):
"""Loads the record specified by the `obj_id` path in the url and
stores it in g._resource_instance"""
current_app.logger.info("Getting instance")
current_app.logger.debug("kwargs: {}".format(kwargs))
current_app.logger.info(
"Lo... | Loads the record specified by the `obj_id` path in the url and
stores it in g._resource_instance | Below is the the instruction that describes the task:
### Input:
Loads the record specified by the `obj_id` path in the url and
stores it in g._resource_instance
### Response:
def _get_instance(self, **kwargs):
"""Loads the record specified by the `obj_id` path in the url and
stores i... |
def verify(path):
"""Verify that `path` is a phasics phase/intensity TIFF file"""
valid = False
try:
tf = SingleTifPhasics._get_tif(path)
except (ValueError, IsADirectoryError):
pass
else:
if (len(tf) == 3 and
"61243" in tf.page... | Verify that `path` is a phasics phase/intensity TIFF file | Below is the the instruction that describes the task:
### Input:
Verify that `path` is a phasics phase/intensity TIFF file
### Response:
def verify(path):
"""Verify that `path` is a phasics phase/intensity TIFF file"""
valid = False
try:
tf = SingleTifPhasics._get_tif(path)
... |
def _run_evolve(ssm_file, cnv_file, work_dir, data):
"""Run evolve.py to infer subclonal composition.
"""
exe = os.path.join(os.path.dirname(sys.executable), "evolve.py")
assert os.path.exists(exe), "Could not find evolve script for PhyloWGS runs."
out_dir = os.path.join(work_dir, "evolve")
out_... | Run evolve.py to infer subclonal composition. | Below is the the instruction that describes the task:
### Input:
Run evolve.py to infer subclonal composition.
### Response:
def _run_evolve(ssm_file, cnv_file, work_dir, data):
"""Run evolve.py to infer subclonal composition.
"""
exe = os.path.join(os.path.dirname(sys.executable), "evolve.py")
ass... |
def matches(self, ldap_filter):
"""
Tests if this configuration matches the given filter.
:param ldap_filter: A parsed LDAP filter object
:return: True if the properties of this configuration matches the
filter
"""
if not self.is_valid():
# D... | Tests if this configuration matches the given filter.
:param ldap_filter: A parsed LDAP filter object
:return: True if the properties of this configuration matches the
filter | Below is the the instruction that describes the task:
### Input:
Tests if this configuration matches the given filter.
:param ldap_filter: A parsed LDAP filter object
:return: True if the properties of this configuration matches the
filter
### Response:
def matches(self, ldap_filt... |
def make_default_short_help(help, max_length=45):
"""Return a condensed version of help string."""
words = help.split()
total_length = 0
result = []
done = False
for word in words:
if word[-1:] == '.':
done = True
new_length = result and 1 + len(word) or len(word)
... | Return a condensed version of help string. | Below is the the instruction that describes the task:
### Input:
Return a condensed version of help string.
### Response:
def make_default_short_help(help, max_length=45):
"""Return a condensed version of help string."""
words = help.split()
total_length = 0
result = []
done = False
for wo... |
def _slr_build_parser_table(productionset):
"""SLR method to build parser table"""
result = ParserTable()
statesset = build_states_sets(productionset)
for itemindex, itemset in enumerate(statesset):
LOG.debug("_slr_build_parser_table: Evaluating itemset:" + str(itemset))
for symbol in pr... | SLR method to build parser table | Below is the the instruction that describes the task:
### Input:
SLR method to build parser table
### Response:
def _slr_build_parser_table(productionset):
"""SLR method to build parser table"""
result = ParserTable()
statesset = build_states_sets(productionset)
for itemindex, itemset in enumerate(... |
def publish(self, topic, dct):
"""Send a dict with internal routing key to the exchange.
Args:
topic: topic to publish the message to
dct: dict object to send
"""
get_logger().info("Publishing message {} on routing key "
"{}...".format(... | Send a dict with internal routing key to the exchange.
Args:
topic: topic to publish the message to
dct: dict object to send | Below is the the instruction that describes the task:
### Input:
Send a dict with internal routing key to the exchange.
Args:
topic: topic to publish the message to
dct: dict object to send
### Response:
def publish(self, topic, dct):
"""Send a dict with internal routing ke... |
def line(
xo: int, yo: int, xd: int, yd: int, py_callback: Callable[[int, int], bool]
) -> bool:
""" Iterate over a line using a callback function.
Your callback function will take x and y parameters and return True to
continue iteration or False to stop iteration and return.
This function include... | Iterate over a line using a callback function.
Your callback function will take x and y parameters and return True to
continue iteration or False to stop iteration and return.
This function includes both the start and end points.
Args:
xo (int): X starting point.
yo (int): Y starting ... | Below is the the instruction that describes the task:
### Input:
Iterate over a line using a callback function.
Your callback function will take x and y parameters and return True to
continue iteration or False to stop iteration and return.
This function includes both the start and end points.
Ar... |
def plot(self, **kwargs):
"""
Produce a pretty-plot of the estimate.
"""
set_kwargs_drawstyle(kwargs, "default")
return _plot_estimate(
self, estimate=getattr(self, self._estimate_name), confidence_intervals=self.confidence_interval_, **kwargs
) | Produce a pretty-plot of the estimate. | Below is the the instruction that describes the task:
### Input:
Produce a pretty-plot of the estimate.
### Response:
def plot(self, **kwargs):
"""
Produce a pretty-plot of the estimate.
"""
set_kwargs_drawstyle(kwargs, "default")
return _plot_estimate(
self, est... |
def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result.round(digits)
return result | Return a vector with the elements rounded to the given number of digits. | Below is the the instruction that describes the task:
### Input:
Return a vector with the elements rounded to the given number of digits.
### Response:
def get_rounded(self, digits):
""" Return a vector with the elements rounded to the given number of digits. """
result = self.copy()
result... |
def store(self, mutagen_file, pictures):
"""``pictures`` is a list of mutagen.flac.Picture instances.
"""
mutagen_file.clear_pictures()
for pic in pictures:
mutagen_file.add_picture(pic) | ``pictures`` is a list of mutagen.flac.Picture instances. | Below is the the instruction that describes the task:
### Input:
``pictures`` is a list of mutagen.flac.Picture instances.
### Response:
def store(self, mutagen_file, pictures):
"""``pictures`` is a list of mutagen.flac.Picture instances.
"""
mutagen_file.clear_pictures()
for pic in... |
def write(filename, mesh):
"""Writes PERMAS dat files, cf.
http://www.intes.de # PERMAS-ASCII-file-format
"""
if mesh.points.shape[1] == 2:
logging.warning(
"PERMAS requires 3D points, but 2D points given. "
"Appending 0 third component."
)
mesh.points = n... | Writes PERMAS dat files, cf.
http://www.intes.de # PERMAS-ASCII-file-format | Below is the the instruction that describes the task:
### Input:
Writes PERMAS dat files, cf.
http://www.intes.de # PERMAS-ASCII-file-format
### Response:
def write(filename, mesh):
"""Writes PERMAS dat files, cf.
http://www.intes.de # PERMAS-ASCII-file-format
"""
if mesh.points.shape[1] == 2:
... |
def _store(self):
"""Creates a storage dictionary for the storage service.
If the data is not a supported sparse matrix, the
:func:`~pypet.parameter.ArrayParmater._store` method of the parent class is called.
Otherwise the matrix is split into parts with
:func:`~pypet.parameter... | Creates a storage dictionary for the storage service.
If the data is not a supported sparse matrix, the
:func:`~pypet.parameter.ArrayParmater._store` method of the parent class is called.
Otherwise the matrix is split into parts with
:func:`~pypet.parameter.SparseParameter._serialize_m... | Below is the the instruction that describes the task:
### Input:
Creates a storage dictionary for the storage service.
If the data is not a supported sparse matrix, the
:func:`~pypet.parameter.ArrayParmater._store` method of the parent class is called.
Otherwise the matrix is split into pa... |
def hook_tag(context, name, *args, **kwargs):
"""
Hook tag to call within templates
:param dict context: This is automatically passed,\
contains the template state/variables
:param str name: The hook which will be dispatched
:param \*args: Positional arguments, will be passed to hook callbacks
... | Hook tag to call within templates
:param dict context: This is automatically passed,\
contains the template state/variables
:param str name: The hook which will be dispatched
:param \*args: Positional arguments, will be passed to hook callbacks
:param \*\*kwargs: Keyword arguments, will be passed t... | Below is the the instruction that describes the task:
### Input:
Hook tag to call within templates
:param dict context: This is automatically passed,\
contains the template state/variables
:param str name: The hook which will be dispatched
:param \*args: Positional arguments, will be passed to hook... |
def _first_fill_value_loc(self):
"""
Get the location of the first missing value.
Returns
-------
int
"""
if len(self) == 0 or self.sp_index.npoints == len(self):
return -1
indices = self.sp_index.to_int_index().indices
if not len(ind... | Get the location of the first missing value.
Returns
-------
int | Below is the the instruction that describes the task:
### Input:
Get the location of the first missing value.
Returns
-------
int
### Response:
def _first_fill_value_loc(self):
"""
Get the location of the first missing value.
Returns
-------
int
... |
def handle_request(path):
"""
Return the current status.
"""
accept = bottle.request.get_header("accept", default="text/plain")
bottle.response.status = 200
try:
if "text/html" in accept:
ret = CURRENT_STATE.as_html(path=path)
bottle.response.content_type = "te... | Return the current status. | Below is the the instruction that describes the task:
### Input:
Return the current status.
### Response:
def handle_request(path):
"""
Return the current status.
"""
accept = bottle.request.get_header("accept", default="text/plain")
bottle.response.status = 200
try:
if "text/htm... |
def message_compose(request, recipients=None, compose_form=ComposeForm,
success_url=None, template_name="umessages/message_form.html",
recipient_filter=None, extra_context=None):
"""
Compose a new message
:recipients:
String containing the usernames to whom t... | Compose a new message
:recipients:
String containing the usernames to whom the message is send to. Can be
multiple username by seperating them with a ``+`` sign.
:param compose_form:
The form that is used for getting neccesary information. Defaults to
:class:`ComposeForm`.
... | Below is the the instruction that describes the task:
### Input:
Compose a new message
:recipients:
String containing the usernames to whom the message is send to. Can be
multiple username by seperating them with a ``+`` sign.
:param compose_form:
The form that is used for getting ... |
def set_xylims(self, limits, axes=None):
"""overwrite data for trace t """
if self.panel is not None:
self.panel.set_xylims(limits, axes=axes) | overwrite data for trace t | Below is the the instruction that describes the task:
### Input:
overwrite data for trace t
### Response:
def set_xylims(self, limits, axes=None):
"""overwrite data for trace t """
if self.panel is not None:
self.panel.set_xylims(limits, axes=axes) |
def _sendReset(self, sequenceId=0):
"""
Sends a reset signal to the network.
"""
for col in xrange(self.numColumns):
self.sensorInputs[col].addResetToQueue(sequenceId)
self.externalInputs[col].addResetToQueue(sequenceId)
self.network.run(1) | Sends a reset signal to the network. | Below is the the instruction that describes the task:
### Input:
Sends a reset signal to the network.
### Response:
def _sendReset(self, sequenceId=0):
"""
Sends a reset signal to the network.
"""
for col in xrange(self.numColumns):
self.sensorInputs[col].addResetToQueue(sequenceId)
sel... |
def handle_error(_, client_addr):
"""Mute tracebacks of common errors."""
exc_type, exc_value, _ = sys.exc_info()
if exc_type is socket.error and exc_value[0] == 32:
pass
elif exc_type is cPickle.UnpicklingError:
sys.stderr.write('Invalid connection from {0}\n'
... | Mute tracebacks of common errors. | Below is the the instruction that describes the task:
### Input:
Mute tracebacks of common errors.
### Response:
def handle_error(_, client_addr):
"""Mute tracebacks of common errors."""
exc_type, exc_value, _ = sys.exc_info()
if exc_type is socket.error and exc_value[0] == 32:
... |
def _getMessage(session, txid):
"""Getting message associated with txid"""
while True:
if txid in session.messages:
msg = session.messages[txid]
del session.messages[txid]
return msg
else:
try:
# apparently any timeout at all allow... | Getting message associated with txid | Below is the the instruction that describes the task:
### Input:
Getting message associated with txid
### Response:
def _getMessage(session, txid):
"""Getting message associated with txid"""
while True:
if txid in session.messages:
msg = session.messages[txid]
del session.m... |
def format_addresses(addrs):
"""
Given an iterable of addresses or name-address
tuples *addrs*, return a header value that joins
all of them together with a space and a comma.
"""
return ', '.join(
formataddr(item) if isinstance(item, tuple) else item
for item in addrs
) | Given an iterable of addresses or name-address
tuples *addrs*, return a header value that joins
all of them together with a space and a comma. | Below is the the instruction that describes the task:
### Input:
Given an iterable of addresses or name-address
tuples *addrs*, return a header value that joins
all of them together with a space and a comma.
### Response:
def format_addresses(addrs):
"""
Given an iterable of addresses or name-addre... |
def getOption(self, name):
"""
Get the the Option object associated with the given name.
:param name: the name of the option to retrieve; can be short or long name.
:raise InterfaceException: if the named option doesn't exist.
"""
name = name.strip()
for o in self.options:
if o.short ... | Get the the Option object associated with the given name.
:param name: the name of the option to retrieve; can be short or long name.
:raise InterfaceException: if the named option doesn't exist. | Below is the the instruction that describes the task:
### Input:
Get the the Option object associated with the given name.
:param name: the name of the option to retrieve; can be short or long name.
:raise InterfaceException: if the named option doesn't exist.
### Response:
def getOption(self, name):
... |
def __split_genomic_interval_filename(fn):
"""
Split a filename of the format chrom:start-end.ext or chrom.ext (full chrom).
:return: tuple of (chrom, start, end) -- 'start' and 'end' are None if not
present in the filename.
"""
if fn is None or fn == "":
raise ValueError("invalid filename: " ... | Split a filename of the format chrom:start-end.ext or chrom.ext (full chrom).
:return: tuple of (chrom, start, end) -- 'start' and 'end' are None if not
present in the filename. | Below is the the instruction that describes the task:
### Input:
Split a filename of the format chrom:start-end.ext or chrom.ext (full chrom).
:return: tuple of (chrom, start, end) -- 'start' and 'end' are None if not
present in the filename.
### Response:
def __split_genomic_interval_filename(fn):
... |
def md5sum(filename, blocksize=8192):
"""Get the MD5 checksum of a file."""
with open(filename, 'rb') as fh:
m = hashlib.md5()
while True:
data = fh.read(blocksize)
if not data:
break
m.update(data)
retur... | Get the MD5 checksum of a file. | Below is the the instruction that describes the task:
### Input:
Get the MD5 checksum of a file.
### Response:
def md5sum(filename, blocksize=8192):
"""Get the MD5 checksum of a file."""
with open(filename, 'rb') as fh:
m = hashlib.md5()
while True:
data = fh... |
def uma_rp_get_rpt(self, ticket, claim_token=None, claim_token_format=None,
pct=None, rpt=None, scope=None, state=None):
"""Function to be used by a UMA Requesting Party to get RPT token.
Parameters:
* **ticket (str, REQUIRED):** ticket
* **claim_token (st... | Function to be used by a UMA Requesting Party to get RPT token.
Parameters:
* **ticket (str, REQUIRED):** ticket
* **claim_token (str, OPTIONAL):** claim token
* **claim_token_format (str, OPTIONAL):** claim token format
* **pct (str, OPTIONAL):** pct
... | Below is the the instruction that describes the task:
### Input:
Function to be used by a UMA Requesting Party to get RPT token.
Parameters:
* **ticket (str, REQUIRED):** ticket
* **claim_token (str, OPTIONAL):** claim token
* **claim_token_format (str, OPTIONAL):** clai... |
def urlopen(self, method, url, **kw):
"""
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.
``url`` must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
"""
conn = self.connection_from_url(url)
... | Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.
``url`` must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it. | Below is the the instruction that describes the task:
### Input:
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`.
``url`` must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
### Response:
def urlopen(self, method, url, *... |
def separate_string(string):
"""
>>> separate_string("test <2>")
(['test ', ''], ['2'])
"""
string_list = regex.split(r'<(?![!=])', regex.sub(r'>', '<', string))
return string_list[::2], string_list[1::2] | >>> separate_string("test <2>")
(['test ', ''], ['2']) | Below is the the instruction that describes the task:
### Input:
>>> separate_string("test <2>")
(['test ', ''], ['2'])
### Response:
def separate_string(string):
"""
>>> separate_string("test <2>")
(['test ', ''], ['2'])
"""
string_list = regex.split(r'<(?![!=])', regex.sub(r'>', '<', stri... |
def post_db_dump(self):
"""
Runs methods services that have requested to be run before each
database dump.
"""
for service in self.genv.services:
service = service.strip().upper()
funcs = common.service_post_db_dumpers.get(service)
if funcs:
... | Runs methods services that have requested to be run before each
database dump. | Below is the the instruction that describes the task:
### Input:
Runs methods services that have requested to be run before each
database dump.
### Response:
def post_db_dump(self):
"""
Runs methods services that have requested to be run before each
database dump.
"""
... |
def construct_1d_arraylike_from_scalar(value, length, dtype):
"""
create a np.ndarray / pandas type of specified shape and dtype
filled with values
Parameters
----------
value : scalar value
length : int
dtype : pandas_dtype / np.dtype
Returns
-------
np.ndarray / pandas ty... | create a np.ndarray / pandas type of specified shape and dtype
filled with values
Parameters
----------
value : scalar value
length : int
dtype : pandas_dtype / np.dtype
Returns
-------
np.ndarray / pandas type of length, filled with value | Below is the the instruction that describes the task:
### Input:
create a np.ndarray / pandas type of specified shape and dtype
filled with values
Parameters
----------
value : scalar value
length : int
dtype : pandas_dtype / np.dtype
Returns
-------
np.ndarray / pandas type of... |
def _apply_section(self, section, hosts):
"""
Recursively find all the hosts that belong in or under a section and
add the section's group name and variables to every host.
"""
# Add the current group name to each host that this section covers.
if section['name'] is not N... | Recursively find all the hosts that belong in or under a section and
add the section's group name and variables to every host. | Below is the the instruction that describes the task:
### Input:
Recursively find all the hosts that belong in or under a section and
add the section's group name and variables to every host.
### Response:
def _apply_section(self, section, hosts):
"""
Recursively find all the hosts that bel... |
def _generate_date_with_wildcard_query(self, date_value):
"""Helper for generating a date keyword query containing a wildcard.
Returns:
(dict): The date query containing the wildcard or an empty dict in case the date value is malformed.
The policy followed here is quite conservativ... | Helper for generating a date keyword query containing a wildcard.
Returns:
(dict): The date query containing the wildcard or an empty dict in case the date value is malformed.
The policy followed here is quite conservative on what it accepts as valid input. Look into
:meth:`inspire... | Below is the the instruction that describes the task:
### Input:
Helper for generating a date keyword query containing a wildcard.
Returns:
(dict): The date query containing the wildcard or an empty dict in case the date value is malformed.
The policy followed here is quite conservativ... |
def greg2julian(year, month, day, hour, minute, second):
"""
Function to convert a date from Gregorian to Julian format
:param year:
Year of events (integer numpy.ndarray)
:param month:
Month of events (integer numpy.ndarray)
:param day:
Days of event (integer numpy.ndarray)... | Function to convert a date from Gregorian to Julian format
:param year:
Year of events (integer numpy.ndarray)
:param month:
Month of events (integer numpy.ndarray)
:param day:
Days of event (integer numpy.ndarray)
:param hour:
Hour of event (integer numpy.ndarray)
:... | Below is the the instruction that describes the task:
### Input:
Function to convert a date from Gregorian to Julian format
:param year:
Year of events (integer numpy.ndarray)
:param month:
Month of events (integer numpy.ndarray)
:param day:
Days of event (integer numpy.ndarray)... |
def simulate_as_gaussian(cls, shape, pixel_scale, sigma, centre=(0.0, 0.0), axis_ratio=1.0, phi=0.0):
"""Simulate the PSF as an elliptical Gaussian profile."""
from autolens.model.profiles.light_profiles import EllipticalGaussian
gaussian = EllipticalGaussian(centre=centre, axis_ratio=axis_ratio... | Simulate the PSF as an elliptical Gaussian profile. | Below is the the instruction that describes the task:
### Input:
Simulate the PSF as an elliptical Gaussian profile.
### Response:
def simulate_as_gaussian(cls, shape, pixel_scale, sigma, centre=(0.0, 0.0), axis_ratio=1.0, phi=0.0):
"""Simulate the PSF as an elliptical Gaussian profile."""
from aut... |
def set_to_cache(vk):
"""
Args:
vk (tuple): obj data (dict), obj key(str)
Return:
tuple: value (dict), key (string)
"""
v, k = vk
try:
cache.set(k, json.dumps(v), settings.CACHE_EXPIRE_DURATION)
except Exception as e:
... | Args:
vk (tuple): obj data (dict), obj key(str)
Return:
tuple: value (dict), key (string) | Below is the the instruction that describes the task:
### Input:
Args:
vk (tuple): obj data (dict), obj key(str)
Return:
tuple: value (dict), key (string)
### Response:
def set_to_cache(vk):
"""
Args:
vk (tuple): obj data (dict), obj key(str)
Re... |
def get_user_recent(self, username, *, mode=OsuMode.osu, limit=10):
"""Get a user's most recent scores, within the last 24 hours.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :cla... | Get a user's most recent scores, within the last 24 hours.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :class:`osuapi.enums.OsuMode`
The osu! game mode for which to look up. ... | Below is the the instruction that describes the task:
### Input:
Get a user's most recent scores, within the last 24 hours.
Parameters
----------
username : str or int
A `str` representing the user's username, or an `int` representing the user's id.
mode : :class:`osuapi... |
def on_api_error_15(self, request):
"""
15. Access denied
- due to scope
"""
logger.error('Authorization failed. Access token will be dropped')
self.access_token = self.get_access_token()
return self.send(request) | 15. Access denied
- due to scope | Below is the the instruction that describes the task:
### Input:
15. Access denied
- due to scope
### Response:
def on_api_error_15(self, request):
"""
15. Access denied
- due to scope
"""
logger.error('Authorization failed. Access token will be dropped')
... |
def generate_configfile_names(config_files, config_searchpath=None):
"""Generates all configuration file name combinations to read.
.. sourcecode::
# -- ALGORITHM:
# First basenames/directories are prefered and override other files.
for config_path in reversed(config_searchpath):
... | Generates all configuration file name combinations to read.
.. sourcecode::
# -- ALGORITHM:
# First basenames/directories are prefered and override other files.
for config_path in reversed(config_searchpath):
for config_basename in reversed(config_files):
con... | Below is the the instruction that describes the task:
### Input:
Generates all configuration file name combinations to read.
.. sourcecode::
# -- ALGORITHM:
# First basenames/directories are prefered and override other files.
for config_path in reversed(config_searchpath):
... |
def deliver(self, sender, receiver, packet):
"deliver on edge of timeout_window"
to = ConsensusManager.round_timeout
assert to > 0
print "in slow transport deliver"
super(SlowTransport, self).deliver(sender, receiver, packet, add_delay=to) | deliver on edge of timeout_window | Below is the the instruction that describes the task:
### Input:
deliver on edge of timeout_window
### Response:
def deliver(self, sender, receiver, packet):
"deliver on edge of timeout_window"
to = ConsensusManager.round_timeout
assert to > 0
print "in slow transport deliver"
... |
def get_issns_for_journal(nlm_id):
"""Get a list of the ISSN numbers for a journal given its NLM ID.
Information on NLM XML DTDs is available at
https://www.nlm.nih.gov/databases/dtd/
"""
params = {'db': 'nlmcatalog',
'retmode': 'xml',
'id': nlm_id}
tree = send_reque... | Get a list of the ISSN numbers for a journal given its NLM ID.
Information on NLM XML DTDs is available at
https://www.nlm.nih.gov/databases/dtd/ | Below is the the instruction that describes the task:
### Input:
Get a list of the ISSN numbers for a journal given its NLM ID.
Information on NLM XML DTDs is available at
https://www.nlm.nih.gov/databases/dtd/
### Response:
def get_issns_for_journal(nlm_id):
"""Get a list of the ISSN numbers for a jo... |
def user_exists(user,
host='localhost',
password=None,
password_hash=None,
passwordless=False,
unix_socket=False,
password_column=None,
**connection_args):
'''
Checks if a user exists on the MySQL ser... | Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``passwordless`` option was added.
CLI Example:
.. code-block:: bash
... | Below is the the instruction that describes the task:
### Input:
Checks if a user exists on the MySQL server. A login can be checked to see
if passwordless login is permitted by omitting ``password`` and
``password_hash``, and using ``passwordless=True``.
.. versionadded:: 0.16.2
The ``password... |
def _getframe(level=0):
'''
A reimplementation of `sys._getframe`.
`sys._getframe` is a private function, and isn't guaranteed to exist in all
versions and implementations of Python.
This function is about 2 times slower than the native implementation. It
relies on the asumption that the trace... | A reimplementation of `sys._getframe`.
`sys._getframe` is a private function, and isn't guaranteed to exist in all
versions and implementations of Python.
This function is about 2 times slower than the native implementation. It
relies on the asumption that the traceback objects have `tb_frame`
att... | Below is the the instruction that describes the task:
### Input:
A reimplementation of `sys._getframe`.
`sys._getframe` is a private function, and isn't guaranteed to exist in all
versions and implementations of Python.
This function is about 2 times slower than the native implementation. It
relie... |
def rmv_normal_chol(mu, sig, size=1):
"""
Random multivariate normal variates.
"""
mu_size = np.shape(mu)
if size == 1:
out = np.random.normal(size=mu_size)
try:
flib.dtrmm_wrap(sig, out, 'L', 'N', 'L', 1.)
except:
out = np.dot(sig, out)
out +... | Random multivariate normal variates. | Below is the the instruction that describes the task:
### Input:
Random multivariate normal variates.
### Response:
def rmv_normal_chol(mu, sig, size=1):
"""
Random multivariate normal variates.
"""
mu_size = np.shape(mu)
if size == 1:
out = np.random.normal(size=mu_size)
try:
... |
def light_novels(self, language="English"):
"""
Get a list of light novels under a certain language.
:param str language: Defaults to English. Replace with whatever language you want to query.
:return list: A list of tuples containing a title and pageid element in that order.
""... | Get a list of light novels under a certain language.
:param str language: Defaults to English. Replace with whatever language you want to query.
:return list: A list of tuples containing a title and pageid element in that order. | Below is the the instruction that describes the task:
### Input:
Get a list of light novels under a certain language.
:param str language: Defaults to English. Replace with whatever language you want to query.
:return list: A list of tuples containing a title and pageid element in that order.
### R... |
def pexpire_at(self, _time):
""" Sets the expiration time of :prop:key_prefix to @_time
@_time: absolute Unix timestamp (milliseconds
since January 1, 1970)
"""
return self._client.pexpireat(self.key_prefix, round(_time)) | Sets the expiration time of :prop:key_prefix to @_time
@_time: absolute Unix timestamp (milliseconds
since January 1, 1970) | Below is the the instruction that describes the task:
### Input:
Sets the expiration time of :prop:key_prefix to @_time
@_time: absolute Unix timestamp (milliseconds
since January 1, 1970)
### Response:
def pexpire_at(self, _time):
""" Sets the expiration time of :prop:key_prefi... |
def run(command, *args):
""" run command """
# show all clusters
if command == 'clusters':
return clusters.run(command, *args)
# show topologies
elif command == 'topologies':
return topologies.run(command, *args)
# physical plan
elif command == 'containers':
return physicalplan.run_container... | run command | Below is the the instruction that describes the task:
### Input:
run command
### Response:
def run(command, *args):
""" run command """
# show all clusters
if command == 'clusters':
return clusters.run(command, *args)
# show topologies
elif command == 'topologies':
return topologies.run(command,... |
def import_descriptor_loader(definition_name, importer=__import__):
"""Find objects by importing modules as needed.
A definition loader is a function that resolves a definition name to a
descriptor.
The import finder resolves definitions to their names by importing modules
when necessary.
Arg... | Find objects by importing modules as needed.
A definition loader is a function that resolves a definition name to a
descriptor.
The import finder resolves definitions to their names by importing modules
when necessary.
Args:
definition_name: Name of definition to find.
importer: Impor... | Below is the the instruction that describes the task:
### Input:
Find objects by importing modules as needed.
A definition loader is a function that resolves a definition name to a
descriptor.
The import finder resolves definitions to their names by importing modules
when necessary.
Args:
... |
def parse_characters(self, character_page):
"""Parses the DOM and returns media character attributes in the sidebar.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL character page's DOM
:rtype: dict
:return: character attributes.
"""
media_info = self.parse_sid... | Parses the DOM and returns media character attributes in the sidebar.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL character page's DOM
:rtype: dict
:return: character attributes. | Below is the the instruction that describes the task:
### Input:
Parses the DOM and returns media character attributes in the sidebar.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL character page's DOM
:rtype: dict
:return: character attributes.
### Response:
def par... |
def get_search(self):
"""Get current search or search from session, reset page if search is changed"""
old_search = self.get_session_value('search', '')
search = self.get_and_save_value('search', '')
if old_search != search:
self.page = 1
self.get_session_value('p... | Get current search or search from session, reset page if search is changed | Below is the the instruction that describes the task:
### Input:
Get current search or search from session, reset page if search is changed
### Response:
def get_search(self):
"""Get current search or search from session, reset page if search is changed"""
old_search = self.get_session_value('searc... |
def solve(expected: List[Tuple[float, float]],
actual: List[Tuple[float, float]]) -> np.ndarray:
"""
Takes two lists of 3 x-y points each, and calculates the matrix
representing the transformation from one space to the other.
The 3x3 matrix returned by this method represents the 2-D transform... | Takes two lists of 3 x-y points each, and calculates the matrix
representing the transformation from one space to the other.
The 3x3 matrix returned by this method represents the 2-D transformation
matrix from the actual point to the expected point.
Example:
If the expected points are:
... | Below is the the instruction that describes the task:
### Input:
Takes two lists of 3 x-y points each, and calculates the matrix
representing the transformation from one space to the other.
The 3x3 matrix returned by this method represents the 2-D transformation
matrix from the actual point to the expe... |
def sofia_process_text():
"""Process text with Sofia and return INDRA Statements."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
text = body.get('text')
auth = body.get('auth')
sp = sofia.process_text(text, auth... | Process text with Sofia and return INDRA Statements. | Below is the the instruction that describes the task:
### Input:
Process text with Sofia and return INDRA Statements.
### Response:
def sofia_process_text():
"""Process text with Sofia and return INDRA Statements."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decod... |
def stop_receive(self, stream):
"""
Mark the :attr:`receive_side <Stream.receive_side>` on `stream` as not
ready for reading. Safe to call from any thread.
"""
_vv and IOLOG.debug('%r.stop_receive(%r)', self, stream)
self.defer(self.poller.stop_receive, stream.receive_sid... | Mark the :attr:`receive_side <Stream.receive_side>` on `stream` as not
ready for reading. Safe to call from any thread. | Below is the the instruction that describes the task:
### Input:
Mark the :attr:`receive_side <Stream.receive_side>` on `stream` as not
ready for reading. Safe to call from any thread.
### Response:
def stop_receive(self, stream):
"""
Mark the :attr:`receive_side <Stream.receive_side>` on `... |
def runner_async(self, fun, **kwargs):
'''
Run `runner modules <all-salt.runners>` asynchronously
Wraps :py:meth:`salt.runner.RunnerClient.cmd_async`.
Note that runner functions must be called using keyword arguments.
Positional arguments are not supported.
:return: ev... | Run `runner modules <all-salt.runners>` asynchronously
Wraps :py:meth:`salt.runner.RunnerClient.cmd_async`.
Note that runner functions must be called using keyword arguments.
Positional arguments are not supported.
:return: event data and a job ID for the executed function. | Below is the the instruction that describes the task:
### Input:
Run `runner modules <all-salt.runners>` asynchronously
Wraps :py:meth:`salt.runner.RunnerClient.cmd_async`.
Note that runner functions must be called using keyword arguments.
Positional arguments are not supported.
:... |
def tag(check, version, push, dry_run):
"""Tag the HEAD of the git repo with the current release number for a
specific check. The tag is pushed to origin by default.
You can tag everything at once by setting the check to `all`.
Notice: specifying a different version than the one in __about__.py is
... | Tag the HEAD of the git repo with the current release number for a
specific check. The tag is pushed to origin by default.
You can tag everything at once by setting the check to `all`.
Notice: specifying a different version than the one in __about__.py is
a maintenance task that should be run under ve... | Below is the the instruction that describes the task:
### Input:
Tag the HEAD of the git repo with the current release number for a
specific check. The tag is pushed to origin by default.
You can tag everything at once by setting the check to `all`.
Notice: specifying a different version than the one ... |
def find_related_module(app, related_name):
"""Given an application name and a module name, tries to find that
module in the application."""
try:
app_path = importlib.import_module(app).__path__
except ImportError as exc:
warn('Autodiscover: Error importing %s.%s: %r' % (
ap... | Given an application name and a module name, tries to find that
module in the application. | Below is the the instruction that describes the task:
### Input:
Given an application name and a module name, tries to find that
module in the application.
### Response:
def find_related_module(app, related_name):
"""Given an application name and a module name, tries to find that
module in the applicat... |
def find_related(self, fullname):
"""
Return a list of non-stdlib modules that are imported directly or
indirectly by `fullname`, plus their parents.
This method is like :py:meth:`find_related_imports`, but also
recursively searches any modules which are imported by `fullname`.
... | Return a list of non-stdlib modules that are imported directly or
indirectly by `fullname`, plus their parents.
This method is like :py:meth:`find_related_imports`, but also
recursively searches any modules which are imported by `fullname`.
:param fullname: Fully qualified name of an _... | Below is the the instruction that describes the task:
### Input:
Return a list of non-stdlib modules that are imported directly or
indirectly by `fullname`, plus their parents.
This method is like :py:meth:`find_related_imports`, but also
recursively searches any modules which are imported ... |
def sftp(self):
"""
Return a `~paramiko.sftp_client.SFTPClient` object.
If called more than one time, memoizes the first result; thus, any
given `.Connection` instance will only ever have a single SFTP client,
and state (such as that managed by
`~paramiko.sftp_client.SFT... | Return a `~paramiko.sftp_client.SFTPClient` object.
If called more than one time, memoizes the first result; thus, any
given `.Connection` instance will only ever have a single SFTP client,
and state (such as that managed by
`~paramiko.sftp_client.SFTPClient.chdir`) will be preserved.
... | Below is the the instruction that describes the task:
### Input:
Return a `~paramiko.sftp_client.SFTPClient` object.
If called more than one time, memoizes the first result; thus, any
given `.Connection` instance will only ever have a single SFTP client,
and state (such as that managed by
... |
def plot_bbox(sf,bbox,inside_only=True):
"""
Plot the geometry of a shapefile within a bbox
:param sf: shapefile
:type sf: shapefile object
:param bbox: bounding box
:type bbox: list of floats [x_min,y_min,x_max,y_max]
:inside_only: True if the objects returned are those that lie within the... | Plot the geometry of a shapefile within a bbox
:param sf: shapefile
:type sf: shapefile object
:param bbox: bounding box
:type bbox: list of floats [x_min,y_min,x_max,y_max]
:inside_only: True if the objects returned are those that lie within the bbox and False if the objects returned are any that ... | Below is the the instruction that describes the task:
### Input:
Plot the geometry of a shapefile within a bbox
:param sf: shapefile
:type sf: shapefile object
:param bbox: bounding box
:type bbox: list of floats [x_min,y_min,x_max,y_max]
:inside_only: True if the objects returned are those tha... |
def validate(value, **kwds):
""" Validate a python value against json schema:
validate(value, schemaPath)
validate(value, schemaDict)
value: python object to validate against the schema
The json schema may be specified either as a path of the file containing
the json schema or as a python diction... | Validate a python value against json schema:
validate(value, schemaPath)
validate(value, schemaDict)
value: python object to validate against the schema
The json schema may be specified either as a path of the file containing
the json schema or as a python dictionary using one of the
following ke... | Below is the the instruction that describes the task:
### Input:
Validate a python value against json schema:
validate(value, schemaPath)
validate(value, schemaDict)
value: python object to validate against the schema
The json schema may be specified either as a path of the file containing
the ... |
def serviceViewChangerOutBox(self, limit: int = None) -> int:
"""
Service at most `limit` number of messages from the view_changer's outBox.
:return: the number of messages successfully serviced.
"""
msgCount = 0
while self.view_changer.outBox and (not limit or msgCount ... | Service at most `limit` number of messages from the view_changer's outBox.
:return: the number of messages successfully serviced. | Below is the the instruction that describes the task:
### Input:
Service at most `limit` number of messages from the view_changer's outBox.
:return: the number of messages successfully serviced.
### Response:
def serviceViewChangerOutBox(self, limit: int = None) -> int:
"""
Service at most... |
def popupChoices(self, event=None):
"""Popup right-click menu of special parameter operations
Relies on browserEnabled, clearEnabled, unlearnEnabled, helpEnabled
instance attributes to determine which items are available.
"""
# don't bother if all items are disabled
if N... | Popup right-click menu of special parameter operations
Relies on browserEnabled, clearEnabled, unlearnEnabled, helpEnabled
instance attributes to determine which items are available. | Below is the the instruction that describes the task:
### Input:
Popup right-click menu of special parameter operations
Relies on browserEnabled, clearEnabled, unlearnEnabled, helpEnabled
instance attributes to determine which items are available.
### Response:
def popupChoices(self, event=None):
... |
def _from_dict(cls, _dict):
"""Initialize a SemanticRolesResult object from a json dictionary."""
args = {}
if 'sentence' in _dict:
args['sentence'] = _dict.get('sentence')
if 'subject' in _dict:
args['subject'] = SemanticRolesResultSubject._from_dict(
... | Initialize a SemanticRolesResult object from a json dictionary. | Below is the the instruction that describes the task:
### Input:
Initialize a SemanticRolesResult object from a json dictionary.
### Response:
def _from_dict(cls, _dict):
"""Initialize a SemanticRolesResult object from a json dictionary."""
args = {}
if 'sentence' in _dict:
args... |
def from_dict(cls, d):
"""Used to create an instance of this class from a pstats dict item"""
stats = []
for (filename, lineno, name), stat_values in d.iteritems():
if len(stat_values) == 5:
ncalls, ncall_nr, total_time, cum_time, subcall_stats = stat_values
... | Used to create an instance of this class from a pstats dict item | Below is the the instruction that describes the task:
### Input:
Used to create an instance of this class from a pstats dict item
### Response:
def from_dict(cls, d):
"""Used to create an instance of this class from a pstats dict item"""
stats = []
for (filename, lineno, name), stat_values ... |
def timed_operation(msg, log_start=False):
"""
Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
time.sleep... | Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
time.sleep(1)
Will print:
.. code-block:: pytho... | Below is the the instruction that describes the task:
### Input:
Surround a context with a timer.
Args:
msg(str): the log to print.
log_start(bool): whether to print also at the beginning.
Example:
.. code-block:: python
with timed_operation('Good Stuff'):
... |
def get_statistics(self, id_or_uri, port_name=''):
"""
Gets the statistics from an interconnect.
Args:
id_or_uri: Can be either the interconnect id or the interconnect uri.
port_name (str): A specific port name of an interconnect.
Returns:
dict: Th... | Gets the statistics from an interconnect.
Args:
id_or_uri: Can be either the interconnect id or the interconnect uri.
port_name (str): A specific port name of an interconnect.
Returns:
dict: The statistics for the interconnect that matches id. | Below is the the instruction that describes the task:
### Input:
Gets the statistics from an interconnect.
Args:
id_or_uri: Can be either the interconnect id or the interconnect uri.
port_name (str): A specific port name of an interconnect.
Returns:
dict: The ... |
def add_gene_links(gene_obj, build=37):
"""Update a gene object with links
Args:
gene_obj(dict)
build(int)
Returns:
gene_obj(dict): gene_obj updated with many links
"""
try:
build = int(build)
except ValueError:
build = 37
# Add links that use the hg... | Update a gene object with links
Args:
gene_obj(dict)
build(int)
Returns:
gene_obj(dict): gene_obj updated with many links | Below is the the instruction that describes the task:
### Input:
Update a gene object with links
Args:
gene_obj(dict)
build(int)
Returns:
gene_obj(dict): gene_obj updated with many links
### Response:
def add_gene_links(gene_obj, build=37):
"""Update a gene object with links
... |
def read_profiles(profiles_dir=None):
"""This is only used for some error handling"""
if profiles_dir is None:
profiles_dir = PROFILES_DIR
raw_profiles = read_profile(profiles_dir)
if raw_profiles is None:
profiles = {}
else:
profiles = {k: v for (k, v) in raw_profiles.item... | This is only used for some error handling | Below is the the instruction that describes the task:
### Input:
This is only used for some error handling
### Response:
def read_profiles(profiles_dir=None):
"""This is only used for some error handling"""
if profiles_dir is None:
profiles_dir = PROFILES_DIR
raw_profiles = read_profile(profil... |
def _make_verb_helper(verb_func, add_groups=False):
"""
Create function that prepares verb for the verb function
The functions created add expressions to be evaluated to
the verb, then call the core verb function
Parameters
----------
verb_func : function
Core verb function. This i... | Create function that prepares verb for the verb function
The functions created add expressions to be evaluated to
the verb, then call the core verb function
Parameters
----------
verb_func : function
Core verb function. This is the function called after
expressions created and adde... | Below is the the instruction that describes the task:
### Input:
Create function that prepares verb for the verb function
The functions created add expressions to be evaluated to
the verb, then call the core verb function
Parameters
----------
verb_func : function
Core verb function. T... |
def get_components(self, root='C', visible=False):
""" Get components of chord quality
:param str root: the root note of the chord
:param bool visible: returns the name of notes if True
:rtype: list[str|int]
:return: components of chord quality
"""
root_val = not... | Get components of chord quality
:param str root: the root note of the chord
:param bool visible: returns the name of notes if True
:rtype: list[str|int]
:return: components of chord quality | Below is the the instruction that describes the task:
### Input:
Get components of chord quality
:param str root: the root note of the chord
:param bool visible: returns the name of notes if True
:rtype: list[str|int]
:return: components of chord quality
### Response:
def get_compo... |
def _unpack_fcn(fcn, p0, y, x):
""" reconfigure fitting fcn so inputs, outputs = flat arrays; hide x """
if y.shape is not None:
if p0.shape is not None:
def nfcn(p, x=x, fcn=fcn, pshape=p0.shape):
po = p.reshape(pshape)
ans = fcn(po) if x is False else fcn(x,... | reconfigure fitting fcn so inputs, outputs = flat arrays; hide x | Below is the the instruction that describes the task:
### Input:
reconfigure fitting fcn so inputs, outputs = flat arrays; hide x
### Response:
def _unpack_fcn(fcn, p0, y, x):
""" reconfigure fitting fcn so inputs, outputs = flat arrays; hide x """
if y.shape is not None:
if p0.shape is not None:
... |
def shuffle(self, count=None, utc=None):
'''
Randomize the order at which statuses for the specified social media
profile will be sent out of the buffer.
'''
url = PATHS['SHUFFLE'] % self.profile_id
post_data = ''
if count:
post_data += 'count=%s&' % count
if utc:
post_... | Randomize the order at which statuses for the specified social media
profile will be sent out of the buffer. | Below is the the instruction that describes the task:
### Input:
Randomize the order at which statuses for the specified social media
profile will be sent out of the buffer.
### Response:
def shuffle(self, count=None, utc=None):
'''
Randomize the order at which statuses for the specified social med... |
def get_subject_guide_for_section(section):
"""
Returns a SubjectGuide model for the passed SWS section model.
"""
return get_subject_guide_for_section_params(
section.term.year, section.term.quarter, section.curriculum_abbr,
section.course_number, section.section_id) | Returns a SubjectGuide model for the passed SWS section model. | Below is the the instruction that describes the task:
### Input:
Returns a SubjectGuide model for the passed SWS section model.
### Response:
def get_subject_guide_for_section(section):
"""
Returns a SubjectGuide model for the passed SWS section model.
"""
return get_subject_guide_for_section_param... |
def xorg(name):
'''
Set the keyboard layout for XOrg
layout
The keyboard layout to use
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
if __salt__['keyboard.get_x']() == name:
ret['result'] = True
ret['comment'] = '... | Set the keyboard layout for XOrg
layout
The keyboard layout to use | Below is the the instruction that describes the task:
### Input:
Set the keyboard layout for XOrg
layout
The keyboard layout to use
### Response:
def xorg(name):
'''
Set the keyboard layout for XOrg
layout
The keyboard layout to use
'''
ret = {'name': name,
'cha... |
def text_list_to_colors(names):
'''
Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors.
'''
# STEP A: compute strings distance between all combnations of strings
Dnames = np.zeros( (len(names), len(names)) )
for i in range(len(names)):
... | Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors. | Below is the the instruction that describes the task:
### Input:
Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors.
### Response:
def text_list_to_colors(names):
'''
Generates a list of colors based on a list of names (strings). Similar strings corr... |
def get_perm_name(cls, action, full=True):
"""
Return the name of the permission for a given model and action.
By default it returns the full permission name `app_label.perm_codename`. If `full=False`, it returns only the
`perm_codename`.
"""
codename = "{}_{}".format(action, cls.__name__.lower... | Return the name of the permission for a given model and action.
By default it returns the full permission name `app_label.perm_codename`. If `full=False`, it returns only the
`perm_codename`. | Below is the the instruction that describes the task:
### Input:
Return the name of the permission for a given model and action.
By default it returns the full permission name `app_label.perm_codename`. If `full=False`, it returns only the
`perm_codename`.
### Response:
def get_perm_name(cls, action, full... |
def set(self, key, value, ex=None, px=None, nx=False, xx=False):
"""Set key to hold the string value. If key already holds a value, it
is overwritten, regardless of its type. Any previous time to live
associated with the key is discarded on successful
:meth:`~tredis.RedisClient.set` oper... | Set key to hold the string value. If key already holds a value, it
is overwritten, regardless of its type. Any previous time to live
associated with the key is discarded on successful
:meth:`~tredis.RedisClient.set` operation.
If the value is not one of :class:`str`, :class:`bytes`, or
... | Below is the the instruction that describes the task:
### Input:
Set key to hold the string value. If key already holds a value, it
is overwritten, regardless of its type. Any previous time to live
associated with the key is discarded on successful
:meth:`~tredis.RedisClient.set` operation.
... |
def request(self, method, url, query_params=None, headers=None,
post_params=None, body=None):
"""
Makes the HTTP request using RESTClient.
"""
if method == "GET":
return self.rest_client.GET(url,
query_params=query_param... | Makes the HTTP request using RESTClient. | Below is the the instruction that describes the task:
### Input:
Makes the HTTP request using RESTClient.
### Response:
def request(self, method, url, query_params=None, headers=None,
post_params=None, body=None):
"""
Makes the HTTP request using RESTClient.
"""
if m... |
def model_creation(dicCnfg, varRat=None, strPathHrf=None):
"""
Create or load pRF model time courses.
Parameters
----------
dicCnfg : dict
Dictionary containing config parameters.
varRat : float, default None
Ratio of size suppressive surround to size of center pRF
strPathHr... | Create or load pRF model time courses.
Parameters
----------
dicCnfg : dict
Dictionary containing config parameters.
varRat : float, default None
Ratio of size suppressive surround to size of center pRF
strPathHrf : str or None:
Path to npy file with custom hrf parameters. I... | Below is the the instruction that describes the task:
### Input:
Create or load pRF model time courses.
Parameters
----------
dicCnfg : dict
Dictionary containing config parameters.
varRat : float, default None
Ratio of size suppressive surround to size of center pRF
strPathHrf ... |
def get(self, record_id):
"""
Retrieves a record by its id
>>> record = airtable.get('recwPQIfs4wKPyc9D')
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Record
"""
record_url = self.record_url(record... | Retrieves a record by its id
>>> record = airtable.get('recwPQIfs4wKPyc9D')
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Record | Below is the the instruction that describes the task:
### Input:
Retrieves a record by its id
>>> record = airtable.get('recwPQIfs4wKPyc9D')
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Record
### Response:
def get(self, record_... |
def blockshapes(self):
"""Raster all bands block shape."""
if self._blockshapes is None:
if self._filename:
self._populate_from_rasterio_object(read_image=False)
else:
# if no file is attached to the raster set the shape of each band to be the data... | Raster all bands block shape. | Below is the the instruction that describes the task:
### Input:
Raster all bands block shape.
### Response:
def blockshapes(self):
"""Raster all bands block shape."""
if self._blockshapes is None:
if self._filename:
self._populate_from_rasterio_object(read_image=False)
... |
def lmfe(signal, sampling_frequency, frame_length=0.020, frame_stride=0.01,
num_filters=40, fft_length=512, low_frequency=0, high_frequency=None):
"""Compute log Mel-filterbank energy features from an audio signal.
Args:
signal (array): the audio signal from which to compute features.
... | Compute log Mel-filterbank energy features from an audio signal.
Args:
signal (array): the audio signal from which to compute features.
Should be an N x 1 array
sampling_frequency (int): the sampling frequency of the signal
we are working with.
frame_length (fl... | Below is the the instruction that describes the task:
### Input:
Compute log Mel-filterbank energy features from an audio signal.
Args:
signal (array): the audio signal from which to compute features.
Should be an N x 1 array
sampling_frequency (int): the sampling frequency of t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.