code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _set_show_mpls_ldp(self, v, load=False):
"""
Setter method for show_mpls_ldp, mapped from YANG variable /brocade_mpls_rpc/show_mpls_ldp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_ldp is considered as a private
method. Backends looking to popu... | Setter method for show_mpls_ldp, mapped from YANG variable /brocade_mpls_rpc/show_mpls_ldp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_ldp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._... | Below is the the instruction that describes the task:
### Input:
Setter method for show_mpls_ldp, mapped from YANG variable /brocade_mpls_rpc/show_mpls_ldp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_ldp is considered as a private
method. Backends loo... |
def escape_windows_cmd_string(s):
"""Returns a string that is usable by the Windows cmd.exe.
The escaping is based on details here and emperical testing:
http://www.robvanderwoude.com/escapechars.php
"""
for c in '()%!^<>&|"':
s = s.replace(c, '^' + c)
s = s.replace('/?', '/.')
retur... | Returns a string that is usable by the Windows cmd.exe.
The escaping is based on details here and emperical testing:
http://www.robvanderwoude.com/escapechars.php | Below is the the instruction that describes the task:
### Input:
Returns a string that is usable by the Windows cmd.exe.
The escaping is based on details here and emperical testing:
http://www.robvanderwoude.com/escapechars.php
### Response:
def escape_windows_cmd_string(s):
"""Returns a string that is... |
def save_var(name, value):
"""
Save a variable to the table specified by _State.vars_table_name. Key is
the name of the variable, and value is the value.
"""
connection = _State.connection()
_State.reflect_metadata()
vars_table = sqlalchemy.Table(
_State.vars_table_name, _State.meta... | Save a variable to the table specified by _State.vars_table_name. Key is
the name of the variable, and value is the value. | Below is the the instruction that describes the task:
### Input:
Save a variable to the table specified by _State.vars_table_name. Key is
the name of the variable, and value is the value.
### Response:
def save_var(name, value):
"""
Save a variable to the table specified by _State.vars_table_name. Key ... |
def set_pixel(self, x, y, value):
"""Set pixel at position x, y to the given value. X and Y should be values
of 0 to 8. Value should be OFF, GREEN, RED, or YELLOW.
"""
if x < 0 or x > 7 or y < 0 or y > 7:
# Ignore out of bounds pixels.
return
# Set green... | Set pixel at position x, y to the given value. X and Y should be values
of 0 to 8. Value should be OFF, GREEN, RED, or YELLOW. | Below is the the instruction that describes the task:
### Input:
Set pixel at position x, y to the given value. X and Y should be values
of 0 to 8. Value should be OFF, GREEN, RED, or YELLOW.
### Response:
def set_pixel(self, x, y, value):
"""Set pixel at position x, y to the given value. X and ... |
def convert_string_to_number(value):
"""
Convert strings to numbers
"""
if value is None:
return 1
if isinstance(value, int):
return value
if value.isdigit():
return int(value)
num_list = map(lambda s: NUMBERS[s], re.findall(numbers + '+', value.lower()))
return s... | Convert strings to numbers | Below is the the instruction that describes the task:
### Input:
Convert strings to numbers
### Response:
def convert_string_to_number(value):
"""
Convert strings to numbers
"""
if value is None:
return 1
if isinstance(value, int):
return value
if value.isdigit():
re... |
def get_allow_repeat_items_metadata(self):
"""get the metadata for allow repeat items"""
metadata = dict(self._allow_repeat_items_metadata)
metadata.update({'existing_id_values': self.my_osid_object_form._my_map['allowRepeatItems']})
return Metadata(**metadata) | get the metadata for allow repeat items | Below is the the instruction that describes the task:
### Input:
get the metadata for allow repeat items
### Response:
def get_allow_repeat_items_metadata(self):
"""get the metadata for allow repeat items"""
metadata = dict(self._allow_repeat_items_metadata)
metadata.update({'existing_id_va... |
def describe(table_name, region=None, key=None, keyid=None, profile=None):
'''
Describe a DynamoDB table.
CLI example::
salt myminion boto_dynamodb.describe table_name region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
table = Table(table_name, ... | Describe a DynamoDB table.
CLI example::
salt myminion boto_dynamodb.describe table_name region=us-east-1 | Below is the the instruction that describes the task:
### Input:
Describe a DynamoDB table.
CLI example::
salt myminion boto_dynamodb.describe table_name region=us-east-1
### Response:
def describe(table_name, region=None, key=None, keyid=None, profile=None):
'''
Describe a DynamoDB table.
... |
def is_valid_delta_name(file):
"""Return if a file has a valid name
A delta file name can be:
- pre-all.py
- pre-all.sql
- delta_x.x.x_ddmmyyyy.pre.py
- delta_x.x.x_ddmmyyyy.pre.sql
- delta_x.x.x_ddmmyyyy.py
- delta_x.x.x_ddmmyyyy.sql
- delta_x.x.... | Return if a file has a valid name
A delta file name can be:
- pre-all.py
- pre-all.sql
- delta_x.x.x_ddmmyyyy.pre.py
- delta_x.x.x_ddmmyyyy.pre.sql
- delta_x.x.x_ddmmyyyy.py
- delta_x.x.x_ddmmyyyy.sql
- delta_x.x.x_ddmmyyyy.post.py
- delta_x.x.x_d... | Below is the the instruction that describes the task:
### Input:
Return if a file has a valid name
A delta file name can be:
- pre-all.py
- pre-all.sql
- delta_x.x.x_ddmmyyyy.pre.py
- delta_x.x.x_ddmmyyyy.pre.sql
- delta_x.x.x_ddmmyyyy.py
- delta_x.x.x_ddmmyy... |
def stream_directory(directory,
recursive=False,
patterns='**',
chunk_size=default_chunk_size):
"""Gets a buffered generator for streaming directories.
Returns a buffered generator which encodes a directory as
:mimetype:`multipart/form-data` wi... | Gets a buffered generator for streaming directories.
Returns a buffered generator which encodes a directory as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
directory : str
The filepath of the directory to stream
recursive : bool
Stream a... | Below is the the instruction that describes the task:
### Input:
Gets a buffered generator for streaming directories.
Returns a buffered generator which encodes a directory as
:mimetype:`multipart/form-data` with the corresponding headers.
Parameters
----------
directory : str
The file... |
def filelist(jottapath, JFS):
"""Get a set() of files from a jottapath (a folder)"""
log.debug("filelist %r", jottapath)
try:
jf = JFS.getObject(jottapath)
except JFSNotFoundError:
return set() # folder does not exist, so pretend it is an empty folder
if not isinstance(jf, JFSFolder)... | Get a set() of files from a jottapath (a folder) | Below is the the instruction that describes the task:
### Input:
Get a set() of files from a jottapath (a folder)
### Response:
def filelist(jottapath, JFS):
"""Get a set() of files from a jottapath (a folder)"""
log.debug("filelist %r", jottapath)
try:
jf = JFS.getObject(jottapath)
except ... |
def render_to_message(self, extra_context=None, *args, **kwargs):
"""
Renders and returns an unsent message with the given context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional co... | Renders and returns an unsent message with the given context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional context to use when rendering
templated content.
:type extra_context... | Below is the the instruction that describes the task:
### Input:
Renders and returns an unsent message with the given context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional context to use when... |
def update_from_file(yaml_dict, filepaths):
'''
Override YAML settings with loaded values from filepaths.
- File paths in the list gets the priority by their orders of the list.
'''
# load YAML settings with only fields in yaml_dict
yaml_dict.update(registry.load(filepaths, list(yaml_dict))... | Override YAML settings with loaded values from filepaths.
- File paths in the list gets the priority by their orders of the list. | Below is the the instruction that describes the task:
### Input:
Override YAML settings with loaded values from filepaths.
- File paths in the list gets the priority by their orders of the list.
### Response:
def update_from_file(yaml_dict, filepaths):
'''
Override YAML settings with loaded values... |
def csv(self, jql, limit=1000):
"""
Get issues from jql search result with all related fields
:param jql: JQL query
:param limit: max results in the output file
:return: CSV file
"""
url = 'sr/jira.issueviews:searchrequest-csv-all-fields/temp/SearchRequest.csv?tem... | Get issues from jql search result with all related fields
:param jql: JQL query
:param limit: max results in the output file
:return: CSV file | Below is the the instruction that describes the task:
### Input:
Get issues from jql search result with all related fields
:param jql: JQL query
:param limit: max results in the output file
:return: CSV file
### Response:
def csv(self, jql, limit=1000):
"""
Get issues from j... |
def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):
"""
Add a path based resolver for the given tag.
A path is a list of keys that forms a path
to a node in the representation tree.
Keys can be string values, integers, or None.
"""
Loader.add_path_resolver(tag, path, k... | Add a path based resolver for the given tag.
A path is a list of keys that forms a path
to a node in the representation tree.
Keys can be string values, integers, or None. | Below is the the instruction that describes the task:
### Input:
Add a path based resolver for the given tag.
A path is a list of keys that forms a path
to a node in the representation tree.
Keys can be string values, integers, or None.
### Response:
def add_path_resolver(tag, path, kind=None, Loader=L... |
def get_display_dataframe(self):
'''
Gets list of terms to display that have some interesting diachronic variation.
Returns
-------
pd.DataFrame
e.g.,
term variable frequency trending
2 in 200310 1.0 0.000000
19 for 200310 1.0 0.000000
20 ... | Gets list of terms to display that have some interesting diachronic variation.
Returns
-------
pd.DataFrame
e.g.,
term variable frequency trending
2 in 200310 1.0 0.000000
19 for 200310 1.0 0.000000
20 to 200311 1.0 0.000000 | Below is the the instruction that describes the task:
### Input:
Gets list of terms to display that have some interesting diachronic variation.
Returns
-------
pd.DataFrame
e.g.,
term variable frequency trending
2 in 200310 1.0 0.000000
19 for 200310 ... |
def copy(self):
"""
Returns a copy of the distribution.
Returns
-------
LinearGaussianCPD: copy of the distribution
Examples
--------
>>> from pgmpy.factors.continuous import LinearGaussianCPD
>>> cpd = LinearGaussianCPD('Y', [0.2, -2, 3, 7], 9.... | Returns a copy of the distribution.
Returns
-------
LinearGaussianCPD: copy of the distribution
Examples
--------
>>> from pgmpy.factors.continuous import LinearGaussianCPD
>>> cpd = LinearGaussianCPD('Y', [0.2, -2, 3, 7], 9.6, ['X1', 'X2', 'X3'])
>>> c... | Below is the the instruction that describes the task:
### Input:
Returns a copy of the distribution.
Returns
-------
LinearGaussianCPD: copy of the distribution
Examples
--------
>>> from pgmpy.factors.continuous import LinearGaussianCPD
>>> cpd = LinearGaus... |
def get_loc(self, key, method=None, tolerance=None):
"""Adapted from pandas.tseries.index.DatetimeIndex.get_loc"""
if isinstance(key, str):
return self._get_string_slice(key)
else:
return pd.Index.get_loc(self, key, method=method,
toler... | Adapted from pandas.tseries.index.DatetimeIndex.get_loc | Below is the the instruction that describes the task:
### Input:
Adapted from pandas.tseries.index.DatetimeIndex.get_loc
### Response:
def get_loc(self, key, method=None, tolerance=None):
"""Adapted from pandas.tseries.index.DatetimeIndex.get_loc"""
if isinstance(key, str):
return self.... |
def _buildPointList(self):
"""
Upon connection to build the device point list and properties.
"""
try:
self.properties.pss.value = self.properties.network.read(
"{} device {} protocolServicesSupported".format(
self.properties.address... | Upon connection to build the device point list and properties. | Below is the the instruction that describes the task:
### Input:
Upon connection to build the device point list and properties.
### Response:
def _buildPointList(self):
"""
Upon connection to build the device point list and properties.
"""
try:
self.properties.pss.v... |
def _get_database(self, database_name):
"""
Get PyMongo client pointing to the current database.
:return: MongoDB client of the current database.
:raise DataSourceError
"""
try:
return self._client[database_name]
except InvalidName as ex:
... | Get PyMongo client pointing to the current database.
:return: MongoDB client of the current database.
:raise DataSourceError | Below is the the instruction that describes the task:
### Input:
Get PyMongo client pointing to the current database.
:return: MongoDB client of the current database.
:raise DataSourceError
### Response:
def _get_database(self, database_name):
"""
Get PyMongo client pointing to the... |
def __upload_title(self, kibiter_major):
"""Upload to Kibiter the title for the dashboard.
The title is shown on top of the dashboard menu, and is Usually
the name of the project being dashboarded.
This is done only for Kibiter 6.x.
:param kibiter_major: major version of kibite... | Upload to Kibiter the title for the dashboard.
The title is shown on top of the dashboard menu, and is Usually
the name of the project being dashboarded.
This is done only for Kibiter 6.x.
:param kibiter_major: major version of kibiter | Below is the the instruction that describes the task:
### Input:
Upload to Kibiter the title for the dashboard.
The title is shown on top of the dashboard menu, and is Usually
the name of the project being dashboarded.
This is done only for Kibiter 6.x.
:param kibiter_major: major ... |
def split_lines(source, maxline=79):
"""Split inputs according to lines.
If a line is short enough, just yield it.
Otherwise, fix it.
"""
result = []
extend = result.extend
append = result.append
line = []
multiline = False
count = 0
find = str.find
for item in sour... | Split inputs according to lines.
If a line is short enough, just yield it.
Otherwise, fix it. | Below is the the instruction that describes the task:
### Input:
Split inputs according to lines.
If a line is short enough, just yield it.
Otherwise, fix it.
### Response:
def split_lines(source, maxline=79):
"""Split inputs according to lines.
If a line is short enough, just yield it.
... |
def root_urns_for_deletion(self):
"""Roots of the graph of urns marked for deletion."""
roots = set()
for urn in self._urns_for_deletion:
new_root = True
str_urn = utils.SmartUnicode(urn)
fake_roots = []
for root in roots:
str_root = utils.SmartUnicode(root)
if str_... | Roots of the graph of urns marked for deletion. | Below is the the instruction that describes the task:
### Input:
Roots of the graph of urns marked for deletion.
### Response:
def root_urns_for_deletion(self):
"""Roots of the graph of urns marked for deletion."""
roots = set()
for urn in self._urns_for_deletion:
new_root = True
str_urn =... |
def wait_for(self, timeout=None):
""" When a timeout should be applied for awaiting use this method.
:param timeout: optional timeout in seconds.
:returns: a future returning the emitted value
"""
from broqer.op import OnEmitFuture # due circular dependency
return self |... | When a timeout should be applied for awaiting use this method.
:param timeout: optional timeout in seconds.
:returns: a future returning the emitted value | Below is the the instruction that describes the task:
### Input:
When a timeout should be applied for awaiting use this method.
:param timeout: optional timeout in seconds.
:returns: a future returning the emitted value
### Response:
def wait_for(self, timeout=None):
""" When a timeout shou... |
def due(self):
"""
The amount due for this invoice. Takes into account all entities in the invoice.
Can be < 0 if the invoice was overpaid.
"""
invoice_charges = Charge.objects.filter(invoice=self)
invoice_transactions = Transaction.successful.filter(invoice=self)
... | The amount due for this invoice. Takes into account all entities in the invoice.
Can be < 0 if the invoice was overpaid. | Below is the the instruction that describes the task:
### Input:
The amount due for this invoice. Takes into account all entities in the invoice.
Can be < 0 if the invoice was overpaid.
### Response:
def due(self):
"""
The amount due for this invoice. Takes into account all entities in the ... |
def connect(self, retry=0, delay=0):
"""Initiate connection to CM. Blocks until connected unless ``retry`` is specified.
:param retry: number of retries before returning. Unlimited when set to ``None``
:type retry: :class:`int`
:param delay: delay in secnds before connection attempt
... | Initiate connection to CM. Blocks until connected unless ``retry`` is specified.
:param retry: number of retries before returning. Unlimited when set to ``None``
:type retry: :class:`int`
:param delay: delay in secnds before connection attempt
:type delay: :class:`int`
:return: ... | Below is the the instruction that describes the task:
### Input:
Initiate connection to CM. Blocks until connected unless ``retry`` is specified.
:param retry: number of retries before returning. Unlimited when set to ``None``
:type retry: :class:`int`
:param delay: delay in secnds before c... |
def exif_name(self):
'''
Name of file in the form {lat}_{lon}_{ca}_{datetime}_{filename}_{hash}
'''
mapillary_description = json.loads(self.extract_image_description())
lat = None
lon = None
ca = None
date_time = None
if "MAPLatitude" in mapillar... | Name of file in the form {lat}_{lon}_{ca}_{datetime}_{filename}_{hash} | Below is the the instruction that describes the task:
### Input:
Name of file in the form {lat}_{lon}_{ca}_{datetime}_{filename}_{hash}
### Response:
def exif_name(self):
'''
Name of file in the form {lat}_{lon}_{ca}_{datetime}_{filename}_{hash}
'''
mapillary_description = json.load... |
def doDelete(self, WHAT={}):
"""This function will perform the command -delete."""
if hasattr(WHAT, '_modified'):
self._addDBParam('RECORDID', WHAT.RECORDID)
self._addDBParam('MODID', WHAT.MODID)
elif type(WHAT) == dict and WHAT.has_key('RECORDID'):
self._addDBParam('RECORDID', WHAT['RECORDID'])
else:... | This function will perform the command -delete. | Below is the the instruction that describes the task:
### Input:
This function will perform the command -delete.
### Response:
def doDelete(self, WHAT={}):
"""This function will perform the command -delete."""
if hasattr(WHAT, '_modified'):
self._addDBParam('RECORDID', WHAT.RECORDID)
self._addDBParam('M... |
def get_column_flat(self, field, components=None, computed_type='for_observations'):
"""
TODO: add documentation
return a single merged value (hstacked) from all meshes
:parameter str field: name of the mesh columnname
:parameter components:
"""
return self.pack... | TODO: add documentation
return a single merged value (hstacked) from all meshes
:parameter str field: name of the mesh columnname
:parameter components: | Below is the the instruction that describes the task:
### Input:
TODO: add documentation
return a single merged value (hstacked) from all meshes
:parameter str field: name of the mesh columnname
:parameter components:
### Response:
def get_column_flat(self, field, components=None, compute... |
def get_anchor_href(markup):
"""
Given HTML markup, return a list of hrefs for each anchor tag.
"""
soup = BeautifulSoup(markup, 'lxml')
return ['%s' % link.get('href') for link in soup.find_all('a')] | Given HTML markup, return a list of hrefs for each anchor tag. | Below is the the instruction that describes the task:
### Input:
Given HTML markup, return a list of hrefs for each anchor tag.
### Response:
def get_anchor_href(markup):
"""
Given HTML markup, return a list of hrefs for each anchor tag.
"""
soup = BeautifulSoup(markup, 'lxml')
return ['%s' % l... |
def grabImage(self, index):
"""Gets an image of the item at *index*
:param index: index of an item in the view
:type index: :qtdoc:`QModelIndex`
:returns: :qtdoc:`QPixmap`
"""
# rect = self._rects[index.row()][index.column()]
rect = self.visualRect(index)
... | Gets an image of the item at *index*
:param index: index of an item in the view
:type index: :qtdoc:`QModelIndex`
:returns: :qtdoc:`QPixmap` | Below is the the instruction that describes the task:
### Input:
Gets an image of the item at *index*
:param index: index of an item in the view
:type index: :qtdoc:`QModelIndex`
:returns: :qtdoc:`QPixmap`
### Response:
def grabImage(self, index):
"""Gets an image of the item at *i... |
def _shutdown_proc(p, timeout):
"""Wait for a proc to shut down, then terminate or kill it after `timeout`."""
freq = 10 # how often to check per second
for _ in range(1 + timeout * freq):
ret = p.poll()
if ret is not None:
logging.info("Shutdown gracefully.")
return ret
time.sleep(1 / fr... | Wait for a proc to shut down, then terminate or kill it after `timeout`. | Below is the the instruction that describes the task:
### Input:
Wait for a proc to shut down, then terminate or kill it after `timeout`.
### Response:
def _shutdown_proc(p, timeout):
"""Wait for a proc to shut down, then terminate or kill it after `timeout`."""
freq = 10 # how often to check per second
for... |
def collect_filtered_models(discard, *input_values):
''' Collect a duplicate-free list of all other Bokeh models referred to by
this model, or by any of its references, etc, unless filtered-out by the
provided callable.
Iterate over ``input_values`` and descend through their structure
collecting al... | Collect a duplicate-free list of all other Bokeh models referred to by
this model, or by any of its references, etc, unless filtered-out by the
provided callable.
Iterate over ``input_values`` and descend through their structure
collecting all nested ``Models`` on the go.
Args:
*discard (C... | Below is the the instruction that describes the task:
### Input:
Collect a duplicate-free list of all other Bokeh models referred to by
this model, or by any of its references, etc, unless filtered-out by the
provided callable.
Iterate over ``input_values`` and descend through their structure
colle... |
async def set_volume(self, vol: int):
""" Sets the player's volume (150% or 1000% limit imposed by lavalink depending on the version). """
if self._lavalink._server_version <= 2:
self.volume = max(min(vol, 150), 0)
else:
self.volume = max(min(vol, 1000), 0)
... | Sets the player's volume (150% or 1000% limit imposed by lavalink depending on the version). | Below is the the instruction that describes the task:
### Input:
Sets the player's volume (150% or 1000% limit imposed by lavalink depending on the version).
### Response:
async def set_volume(self, vol: int):
""" Sets the player's volume (150% or 1000% limit imposed by lavalink depending on the version).... |
def fit_transform(self, X, y=None, **params):
"""Learn vocabulary and return document id matrix.
This is equivalent to fit followed by transform.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
Returns:
list : docume... | Learn vocabulary and return document id matrix.
This is equivalent to fit followed by transform.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
Returns:
list : document id matrix.
list: label id matrix. | Below is the the instruction that describes the task:
### Input:
Learn vocabulary and return document id matrix.
This is equivalent to fit followed by transform.
Args:
X : iterable
an iterable which yields either str, unicode or file objects.
Returns:
l... |
def wide(self):
"""
``True`` if this instruction needs to be prefixed by the WIDE
opcode.
"""
if not opcode_table[self.opcode].get('can_be_wide'):
return False
if self.operands[0].value >= 255:
return True
if self.opcode == 0x84:
... | ``True`` if this instruction needs to be prefixed by the WIDE
opcode. | Below is the the instruction that describes the task:
### Input:
``True`` if this instruction needs to be prefixed by the WIDE
opcode.
### Response:
def wide(self):
"""
``True`` if this instruction needs to be prefixed by the WIDE
opcode.
"""
if not opcode_table[self... |
def load_html(self, mode, html):
"""Load HTML to this class with the mode specified.
There are two modes that can be used:
* HTML_FILE_MODE: Directly from a local HTML file.
* HTML_STR_MODE: From a valid HTML string.
:param mode: The mode.
:type mode: int
... | Load HTML to this class with the mode specified.
There are two modes that can be used:
* HTML_FILE_MODE: Directly from a local HTML file.
* HTML_STR_MODE: From a valid HTML string.
:param mode: The mode.
:type mode: int
:param html: The html that will be loaded... | Below is the the instruction that describes the task:
### Input:
Load HTML to this class with the mode specified.
There are two modes that can be used:
* HTML_FILE_MODE: Directly from a local HTML file.
* HTML_STR_MODE: From a valid HTML string.
:param mode: The mode.
... |
def create_char(self, location, bitmap):
"""Create a new character.
The HD44780 supports up to 8 custom characters (location 0-7).
:param location: The place in memory where the character is stored.
Values need to be integers between 0 and 7.
:type location: int
:pa... | Create a new character.
The HD44780 supports up to 8 custom characters (location 0-7).
:param location: The place in memory where the character is stored.
Values need to be integers between 0 and 7.
:type location: int
:param bitmap: The bitmap containing the character. Thi... | Below is the the instruction that describes the task:
### Input:
Create a new character.
The HD44780 supports up to 8 custom characters (location 0-7).
:param location: The place in memory where the character is stored.
Values need to be integers between 0 and 7.
:type location... |
def _parse_canonical_regex(doc):
"""Decode a JSON regex to bson.regex.Regex."""
regex = doc['$regularExpression']
if len(doc) != 1:
raise TypeError('Bad $regularExpression, extra field(s): %s' % (doc,))
if len(regex) != 2:
raise TypeError('Bad $regularExpression must include only "patter... | Decode a JSON regex to bson.regex.Regex. | Below is the the instruction that describes the task:
### Input:
Decode a JSON regex to bson.regex.Regex.
### Response:
def _parse_canonical_regex(doc):
"""Decode a JSON regex to bson.regex.Regex."""
regex = doc['$regularExpression']
if len(doc) != 1:
raise TypeError('Bad $regularExpression, ex... |
def _list_po_to_dict(tokens) -> ListAbundance:
"""Convert a list parse object to a node.
:type tokens: ParseResult
"""
func = tokens[FUNCTION]
dsl = FUNC_TO_LIST_DSL[func]
members = [parse_result_to_dsl(token) for token in tokens[MEMBERS]]
return dsl(members) | Convert a list parse object to a node.
:type tokens: ParseResult | Below is the the instruction that describes the task:
### Input:
Convert a list parse object to a node.
:type tokens: ParseResult
### Response:
def _list_po_to_dict(tokens) -> ListAbundance:
"""Convert a list parse object to a node.
:type tokens: ParseResult
"""
func = tokens[FUNCTION]
ds... |
def calc_model(cortex, model_argument, model_hemi=Ellipsis, radius=np.pi/3):
'''
calc_model loads the appropriate model object given the model argument, which may given the name
of the model or a model object itself.
Required afferent parameters:
@ model_argument Must be either a RegisteredRetino... | calc_model loads the appropriate model object given the model argument, which may given the name
of the model or a model object itself.
Required afferent parameters:
@ model_argument Must be either a RegisteredRetinotopyModel object or the name of a model that
can be loaded.
Optional afferen... | Below is the the instruction that describes the task:
### Input:
calc_model loads the appropriate model object given the model argument, which may given the name
of the model or a model object itself.
Required afferent parameters:
@ model_argument Must be either a RegisteredRetinotopyModel object or ... |
def enable_vxlan_feature(self, nexus_host, nve_int_num, src_intf):
"""Enable VXLAN on the switch."""
# Configure the "feature" commands and NVE interface
# (without "member" subcommand configuration).
# The Nexus 9K will not allow the "interface nve" configuration
# until the "f... | Enable VXLAN on the switch. | Below is the the instruction that describes the task:
### Input:
Enable VXLAN on the switch.
### Response:
def enable_vxlan_feature(self, nexus_host, nve_int_num, src_intf):
"""Enable VXLAN on the switch."""
# Configure the "feature" commands and NVE interface
# (without "member" subcomman... |
def source(self):
"""
Returns the single source name for a variant collection if it is unique,
otherwise raises an error.
"""
if len(self.sources) == 0:
raise ValueError("No source associated with %s" % self.__class__.__name__)
elif len(self.sources) > 1:
... | Returns the single source name for a variant collection if it is unique,
otherwise raises an error. | Below is the the instruction that describes the task:
### Input:
Returns the single source name for a variant collection if it is unique,
otherwise raises an error.
### Response:
def source(self):
"""
Returns the single source name for a variant collection if it is unique,
otherwise... |
def validate_location_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluates attempts to add location instances to arc, ensuring they are from same outline.
'''
if action == 'pre_add':
if reverse:
# Fetch arc definition through link.
... | Evaluates attempts to add location instances to arc, ensuring they are from same outline. | Below is the the instruction that describes the task:
### Input:
Evaluates attempts to add location instances to arc, ensuring they are from same outline.
### Response:
def validate_location_instance_valid_for_arc(sender, instance, action, reverse, pk_set, *args, **kwargs):
'''
Evaluates attempts to add lo... |
def find_one(cls, *args, **kw):
"""Get a single document from the collection this class is bound to.
Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional
parameters are interpreted as query fragments, parametric keyword arguments combined, and other keyw... | Get a single document from the collection this class is bound to.
Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional
parameters are interpreted as query fragments, parametric keyword arguments combined, and other keyword
arguments passed along with min... | Below is the the instruction that describes the task:
### Input:
Get a single document from the collection this class is bound to.
Additional arguments are processed according to `_prepare_find` prior to passing to PyMongo, where positional
parameters are interpreted as query fragments, parametric keyword ar... |
def onCancelButton(self, event):
"""
Quit grid with warning if unsaved changes present
"""
if self.grid.changes:
dlg1 = wx.MessageDialog(self, caption="Message:",
message="Are you sure you want to exit this grid?\nYour changes will not be s... | Quit grid with warning if unsaved changes present | Below is the the instruction that describes the task:
### Input:
Quit grid with warning if unsaved changes present
### Response:
def onCancelButton(self, event):
"""
Quit grid with warning if unsaved changes present
"""
if self.grid.changes:
dlg1 = wx.MessageDialog(self,... |
def find_node_type(ast, node_type):
"""Return list of array references in AST."""
if type(ast) is node_type:
return [ast]
elif type(ast) is list:
return reduce(operator.add, list(map(lambda a: find_node_type(a, node_type), ast)), [])
elif ast is None:
return []
else:
... | Return list of array references in AST. | Below is the the instruction that describes the task:
### Input:
Return list of array references in AST.
### Response:
def find_node_type(ast, node_type):
"""Return list of array references in AST."""
if type(ast) is node_type:
return [ast]
elif type(ast) is list:
return reduce(operator... |
def zoom2D(xi, yi, zi, xi_zoom=3., yi_zoom=3., order=3, mode="nearest", cval=0.):
"""Zoom a 2D array, with axes.
Parameters
----------
xi : 1D array
x axis points.
yi : 1D array
y axis points.
zi : 2D array
array values. Shape of (x, y).
xi_zoom : float (optional)
... | Zoom a 2D array, with axes.
Parameters
----------
xi : 1D array
x axis points.
yi : 1D array
y axis points.
zi : 2D array
array values. Shape of (x, y).
xi_zoom : float (optional)
Zoom factor along x axis. Default is 3.
yi_zoom : float (optional)
Zoom... | Below is the the instruction that describes the task:
### Input:
Zoom a 2D array, with axes.
Parameters
----------
xi : 1D array
x axis points.
yi : 1D array
y axis points.
zi : 2D array
array values. Shape of (x, y).
xi_zoom : float (optional)
Zoom factor al... |
def V_vertical_torispherical_concave(D, f, k, h):
r'''Calculates volume of a vertical tank with a concave torispherical bottom,
according to [1]_. No provision for the top of the tank is made here.
.. math::
V = \frac{\pi D^2 h}{4} - v_1(h=a_1+a_2) + v_1(h=a_1 + a_2 -h),\; 0 \le h < a_2
.. mat... | r'''Calculates volume of a vertical tank with a concave torispherical bottom,
according to [1]_. No provision for the top of the tank is made here.
.. math::
V = \frac{\pi D^2 h}{4} - v_1(h=a_1+a_2) + v_1(h=a_1 + a_2 -h),\; 0 \le h < a_2
.. math::
V = \frac{\pi D^2 h}{4} - v_1(h=a_1+a_2) +... | Below is the the instruction that describes the task:
### Input:
r'''Calculates volume of a vertical tank with a concave torispherical bottom,
according to [1]_. No provision for the top of the tank is made here.
.. math::
V = \frac{\pi D^2 h}{4} - v_1(h=a_1+a_2) + v_1(h=a_1 + a_2 -h),\; 0 \le h < ... |
def fly(self):
"""
Generate doc tree.
"""
dst_dir = Path(self.conf_file).parent.abspath
package_dir = Path(dst_dir, self.package.shortname)
# delete existing api document
try:
if package_dir.exists():
shutil.rmtree(package_dir.abspath... | Generate doc tree. | Below is the the instruction that describes the task:
### Input:
Generate doc tree.
### Response:
def fly(self):
"""
Generate doc tree.
"""
dst_dir = Path(self.conf_file).parent.abspath
package_dir = Path(dst_dir, self.package.shortname)
# delete existing api docum... |
def render(self, renderer=None, **kwargs):
"""Render the navigational item using a renderer.
:param renderer: An object implementing the :class:`~.Renderer`
interface.
:return: A markupsafe string with the rendered result.
"""
return Markup(get_renderer(... | Render the navigational item using a renderer.
:param renderer: An object implementing the :class:`~.Renderer`
interface.
:return: A markupsafe string with the rendered result. | Below is the the instruction that describes the task:
### Input:
Render the navigational item using a renderer.
:param renderer: An object implementing the :class:`~.Renderer`
interface.
:return: A markupsafe string with the rendered result.
### Response:
def render(self, ... |
def main():
"""
NAME
fishqq.py
DESCRIPTION
makes qq plot from dec,inc input data
INPUT FORMAT
takes dec/inc pairs in space delimited file
SYNTAX
fishqq.py [command line options]
OPTIONS
-h help message
-f FILE, specify file on command line
... | NAME
fishqq.py
DESCRIPTION
makes qq plot from dec,inc input data
INPUT FORMAT
takes dec/inc pairs in space delimited file
SYNTAX
fishqq.py [command line options]
OPTIONS
-h help message
-f FILE, specify file on command line
-F FILE, specify output ... | Below is the the instruction that describes the task:
### Input:
NAME
fishqq.py
DESCRIPTION
makes qq plot from dec,inc input data
INPUT FORMAT
takes dec/inc pairs in space delimited file
SYNTAX
fishqq.py [command line options]
OPTIONS
-h help message
-... |
def show_vcs_output_vcs_nodes_vcs_node_info_switch_fcf_mac(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
vcs_nodes = ET.SubElement(output, "v... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_vcs_output_vcs_nodes_vcs_node_info_switch_fcf_mac(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = ... |
def seoify_hyperlink(hyperlink):
"""Modify a hyperlink to make it SEO-friendly by replacing
hyphens with spaces and trimming multiple spaces.
:param hyperlink: URL to attempt to grab SEO from """
last_slash = hyperlink.rfind('/')
return re.sub(r' +|-', ' ', hyperlink[last_slash + 1:]) | Modify a hyperlink to make it SEO-friendly by replacing
hyphens with spaces and trimming multiple spaces.
:param hyperlink: URL to attempt to grab SEO from | Below is the the instruction that describes the task:
### Input:
Modify a hyperlink to make it SEO-friendly by replacing
hyphens with spaces and trimming multiple spaces.
:param hyperlink: URL to attempt to grab SEO from
### Response:
def seoify_hyperlink(hyperlink):
"""Modify a hyperlink to make it S... |
def update(self, scope, at=0):
"""Update scope. Add another scope to this one.
Args:
scope (Scope): Scope object
Kwargs:
at (int): Level to update
"""
if hasattr(scope, '_mixins') and not at:
self._mixins.update(scope._mixins)
self[at][... | Update scope. Add another scope to this one.
Args:
scope (Scope): Scope object
Kwargs:
at (int): Level to update | Below is the the instruction that describes the task:
### Input:
Update scope. Add another scope to this one.
Args:
scope (Scope): Scope object
Kwargs:
at (int): Level to update
### Response:
def update(self, scope, at=0):
"""Update scope. Add another scope to this o... |
def transaction_status(transaction):
"""Returns a FormattedItem describing the given transaction.
:param item: An object capable of having an active transaction
"""
if not transaction or not transaction.get('transactionStatus'):
return blank()
return FormattedItem(
transaction[... | Returns a FormattedItem describing the given transaction.
:param item: An object capable of having an active transaction | Below is the the instruction that describes the task:
### Input:
Returns a FormattedItem describing the given transaction.
:param item: An object capable of having an active transaction
### Response:
def transaction_status(transaction):
"""Returns a FormattedItem describing the given transaction.
... |
def listify_string(something):
"""Takes *something* and make it a list.
*something* is either a list of strings or a string, in which case the
function returns a list containing the string.
If *something* is None, an empty list is returned.
"""
if isinstance(something, (str, six.text_type)):
... | Takes *something* and make it a list.
*something* is either a list of strings or a string, in which case the
function returns a list containing the string.
If *something* is None, an empty list is returned. | Below is the the instruction that describes the task:
### Input:
Takes *something* and make it a list.
*something* is either a list of strings or a string, in which case the
function returns a list containing the string.
If *something* is None, an empty list is returned.
### Response:
def listify_stri... |
def get_gradebook_column_gradebook_assignment_session(self, proxy):
"""Gets the session for assigning gradebook column to gradebook mappings.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.grading.GradebookColumnGradebookAssignmentSession)
- a ``GradebookColumnGradebook... | Gets the session for assigning gradebook column to gradebook mappings.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.grading.GradebookColumnGradebookAssignmentSession)
- a ``GradebookColumnGradebookAssignmentSession``
raise: NullArgument - ``proxy`` is ``null``
... | Below is the the instruction that describes the task:
### Input:
Gets the session for assigning gradebook column to gradebook mappings.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.grading.GradebookColumnGradebookAssignmentSession)
- a ``GradebookColumnGradebookAssignment... |
def profile_config_set(name, config_key, config_value,
remote_addr=None,
cert=None, key=None, verify_cert=True):
''' Set a profile config item.
name :
The name of the profile to set the config item to.
config_key :
The items key... | Set a profile config item.
name :
The name of the profile to set the config item to.
config_key :
The items key.
config_value :
Its items value.
remote_addr :
An URL to a remote Server, you also have to give cert and key if
... | Below is the the instruction that describes the task:
### Input:
Set a profile config item.
name :
The name of the profile to set the config item to.
config_key :
The items key.
config_value :
Its items value.
remote_addr :
An URL t... |
def community_post_votes(self, post_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/votes#list-votes"
api_path = "/api/v2/community/posts/{post_id}/votes.json"
api_path = api_path.format(post_id=post_id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/help_center/votes#list-votes | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/help_center/votes#list-votes
### Response:
def community_post_votes(self, post_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/votes#list-votes"
api_path = "/api/v2/c... |
def get_content_charset(self, failobj=None):
"""Return the charset parameter of the Content-Type header.
The returned string is always coerced to lower case. If there is no
Content-Type header, or if that header has no charset parameter,
failobj is returned.
"""
missing... | Return the charset parameter of the Content-Type header.
The returned string is always coerced to lower case. If there is no
Content-Type header, or if that header has no charset parameter,
failobj is returned. | Below is the the instruction that describes the task:
### Input:
Return the charset parameter of the Content-Type header.
The returned string is always coerced to lower case. If there is no
Content-Type header, or if that header has no charset parameter,
failobj is returned.
### Response: ... |
def permission_to_pyramid_acls(permissions):
"""
Returns a list of permissions in a format understood by pyramid
:param permissions:
:return:
"""
acls = []
for perm in permissions:
if perm.type == "user":
acls.append((Allow, perm.user.id, perm.perm_name))
elif per... | Returns a list of permissions in a format understood by pyramid
:param permissions:
:return: | Below is the the instruction that describes the task:
### Input:
Returns a list of permissions in a format understood by pyramid
:param permissions:
:return:
### Response:
def permission_to_pyramid_acls(permissions):
"""
Returns a list of permissions in a format understood by pyramid
:param per... |
def run_rsync_project():
"""
Copies the project from the git repository to it's destination folder.
This has the nice side effect of rsync deleting all ``.pyc`` files and
removing other files that might have been left behind by sys admins messing
around on the server.
Usage::
fab <ser... | Copies the project from the git repository to it's destination folder.
This has the nice side effect of rsync deleting all ``.pyc`` files and
removing other files that might have been left behind by sys admins messing
around on the server.
Usage::
fab <server> run_rsync_project | Below is the the instruction that describes the task:
### Input:
Copies the project from the git repository to it's destination folder.
This has the nice side effect of rsync deleting all ``.pyc`` files and
removing other files that might have been left behind by sys admins messing
around on the server... |
def refresh_modules(self, module_string=None, exact=True):
"""
Update modules.
if module_string is None all modules are refreshed
if module_string then modules with the exact name or those starting
with the given string depending on exact parameter will be refreshed.
If a... | Update modules.
if module_string is None all modules are refreshed
if module_string then modules with the exact name or those starting
with the given string depending on exact parameter will be refreshed.
If a module is an i3status one then we refresh i3status.
To prevent abuse, ... | Below is the the instruction that describes the task:
### Input:
Update modules.
if module_string is None all modules are refreshed
if module_string then modules with the exact name or those starting
with the given string depending on exact parameter will be refreshed.
If a module is... |
def update_milestone(id, **kwargs):
"""
Update a ProductMilestone
"""
data = update_milestone_raw(id, **kwargs)
if data:
return utils.format_json(data) | Update a ProductMilestone | Below is the the instruction that describes the task:
### Input:
Update a ProductMilestone
### Response:
def update_milestone(id, **kwargs):
"""
Update a ProductMilestone
"""
data = update_milestone_raw(id, **kwargs)
if data:
return utils.format_json(data) |
def space_list(args):
''' List accessible workspaces, in TSV form: <namespace><TAB>workspace'''
r = fapi.list_workspaces()
fapi._check_response_code(r, 200)
spaces = []
project = args.project
if project:
project = re.compile('^' + project)
for space in r.json():
ns = space... | List accessible workspaces, in TSV form: <namespace><TAB>workspace | Below is the the instruction that describes the task:
### Input:
List accessible workspaces, in TSV form: <namespace><TAB>workspace
### Response:
def space_list(args):
''' List accessible workspaces, in TSV form: <namespace><TAB>workspace'''
r = fapi.list_workspaces()
fapi._check_response_code(r, 200)... |
async def processClaims(self, allClaims: Dict[ID, Claims]):
"""
Processes and saves received Claims.
:param claims: claims to be processed and saved for each claim
definition.
"""
res = []
for schemaId, (claim_signature, claim_attributes) in allClaims.items():
... | Processes and saves received Claims.
:param claims: claims to be processed and saved for each claim
definition. | Below is the the instruction that describes the task:
### Input:
Processes and saves received Claims.
:param claims: claims to be processed and saved for each claim
definition.
### Response:
async def processClaims(self, allClaims: Dict[ID, Claims]):
"""
Processes and saves receive... |
def add_done_callback(self, future, callback):
""" Add a callback on a future object put here so it can be
implemented with different event loops.
Parameters
-----------
future: Future or Deferred
Future implementation for the current EventLoop
... | Add a callback on a future object put here so it can be
implemented with different event loops.
Parameters
-----------
future: Future or Deferred
Future implementation for the current EventLoop
callback: callable
Callback ... | Below is the the instruction that describes the task:
### Input:
Add a callback on a future object put here so it can be
implemented with different event loops.
Parameters
-----------
future: Future or Deferred
Future implementation for the current EventLoop
... |
def _IfdEntryFactory(stream_rdr, offset):
"""
Return an |_IfdEntry| subclass instance containing the value of the
directory entry at *offset* in *stream_rdr*.
"""
ifd_entry_classes = {
TIFF_FLD.ASCII: _AsciiIfdEntry,
TIFF_FLD.SHORT: _ShortIfdEntry,
TIFF_FLD.LONG: _L... | Return an |_IfdEntry| subclass instance containing the value of the
directory entry at *offset* in *stream_rdr*. | Below is the the instruction that describes the task:
### Input:
Return an |_IfdEntry| subclass instance containing the value of the
directory entry at *offset* in *stream_rdr*.
### Response:
def _IfdEntryFactory(stream_rdr, offset):
"""
Return an |_IfdEntry| subclass instance containing the value of t... |
def sample(self, data, sample_size=15000,
blocked_proportion=0.5, original_length=None):
'''Draw a sample of record pairs from the dataset
(a mix of random pairs & pairs of similar records)
and initialize active learning with this sample
Arguments: data -- Dictionary of r... | Draw a sample of record pairs from the dataset
(a mix of random pairs & pairs of similar records)
and initialize active learning with this sample
Arguments: data -- Dictionary of records, where the keys are
record_ids and the values are dictionaries with the keys being
field nam... | Below is the the instruction that describes the task:
### Input:
Draw a sample of record pairs from the dataset
(a mix of random pairs & pairs of similar records)
and initialize active learning with this sample
Arguments: data -- Dictionary of records, where the keys are
record_ids ... |
def find_disulfide_bridges(self, threshold=3.0):
"""Run Biopython's search_ss_bonds to find potential disulfide bridges for each chain and store in ChainProp.
Will add a list of tuple pairs into the annotations field, looks like this::
[ ((' ', 79, ' '), (' ', 110, ' ')),
(('... | Run Biopython's search_ss_bonds to find potential disulfide bridges for each chain and store in ChainProp.
Will add a list of tuple pairs into the annotations field, looks like this::
[ ((' ', 79, ' '), (' ', 110, ' ')),
((' ', 174, ' '), (' ', 180, ' ')),
((' ', 369, '... | Below is the the instruction that describes the task:
### Input:
Run Biopython's search_ss_bonds to find potential disulfide bridges for each chain and store in ChainProp.
Will add a list of tuple pairs into the annotations field, looks like this::
[ ((' ', 79, ' '), (' ', 110, ' ')),
... |
def load_file(self, filename):
"""Load and parse a RiveScript document.
:param str filename: The path to a RiveScript file.
"""
self._say("Loading file: " + filename)
fh = codecs.open(filename, 'r', 'utf-8')
lines = fh.readlines()
fh.close()
self._sa... | Load and parse a RiveScript document.
:param str filename: The path to a RiveScript file. | Below is the the instruction that describes the task:
### Input:
Load and parse a RiveScript document.
:param str filename: The path to a RiveScript file.
### Response:
def load_file(self, filename):
"""Load and parse a RiveScript document.
:param str filename: The path to a RiveScript fi... |
def get_uri(source):
"""
Check a media source as a valid file or uri and return the proper uri
"""
import gst
src_info = source_info(source)
if src_info['is_file']: # Is this a file?
return get_uri(src_info['uri'])
elif gst.uri_is_valid(source): # Is this a valid URI source for... | Check a media source as a valid file or uri and return the proper uri | Below is the the instruction that describes the task:
### Input:
Check a media source as a valid file or uri and return the proper uri
### Response:
def get_uri(source):
"""
Check a media source as a valid file or uri and return the proper uri
"""
import gst
src_info = source_info(source)
... |
def subscribe(self, requested_timeout=None, auto_renew=False):
"""Subscribe to the service.
If requested_timeout is provided, a subscription valid for that number
of seconds will be requested, but not guaranteed. Check
`timeout` on return to find out what period of validity is
a... | Subscribe to the service.
If requested_timeout is provided, a subscription valid for that number
of seconds will be requested, but not guaranteed. Check
`timeout` on return to find out what period of validity is
actually allocated.
Note:
SoCo will try to unsubscribe... | Below is the the instruction that describes the task:
### Input:
Subscribe to the service.
If requested_timeout is provided, a subscription valid for that number
of seconds will be requested, but not guaranteed. Check
`timeout` on return to find out what period of validity is
actual... |
def getDatabaseFileSize(self):
""" Return the file size of the database as a pretty string. """
if DISABLE_PERSISTENT_CACHING:
return "?"
size = os.path.getsize(self.__db_filepath)
if size > 1000000000:
size = "%0.3fGB" % (size / 1000000000)
elif size > 1000000:
size = "%0.2fMB" % ... | Return the file size of the database as a pretty string. | Below is the the instruction that describes the task:
### Input:
Return the file size of the database as a pretty string.
### Response:
def getDatabaseFileSize(self):
""" Return the file size of the database as a pretty string. """
if DISABLE_PERSISTENT_CACHING:
return "?"
size = os.path.getsize(... |
def extractFromURL(url,
cache=False,
cacheDir='_cache',
verbose=False,
encoding=None,
filters=None,
userAgent=None,
timeout=5,
blur=5,
ignore_robotstxt=False,
only_mime_types=None,
raw=False):
"""
Extracts text from a URL.
Parameters:
url := string
Re... | Extracts text from a URL.
Parameters:
url := string
Remote URL or local filename where HTML will be read.
cache := bool
True=store and retrieve url from cache
False=always retrieve url from the web
cacheDir := str
Directory where cached url contents will be stored.
v... | Below is the the instruction that describes the task:
### Input:
Extracts text from a URL.
Parameters:
url := string
Remote URL or local filename where HTML will be read.
cache := bool
True=store and retrieve url from cache
False=always retrieve url from the web
cacheDir := ... |
def successors(self):
"""Yield Compounds below self in the hierarchy.
Yields
-------
mb.Compound
The next Particle below self in the hierarchy
"""
if not self.children:
return
for part in self.children:
# Parts local to the cu... | Yield Compounds below self in the hierarchy.
Yields
-------
mb.Compound
The next Particle below self in the hierarchy | Below is the the instruction that describes the task:
### Input:
Yield Compounds below self in the hierarchy.
Yields
-------
mb.Compound
The next Particle below self in the hierarchy
### Response:
def successors(self):
"""Yield Compounds below self in the hierarchy.
... |
def _CreateComplexTypeFromData(
self, elem_type, type_is_override, data, set_type_attrs):
"""Initialize a SOAP element with specific data.
Args:
elem_type: The type of the element to create.
type_is_override: A boolean specifying if the type is being overridden.
data: The data to hydrat... | Initialize a SOAP element with specific data.
Args:
elem_type: The type of the element to create.
type_is_override: A boolean specifying if the type is being overridden.
data: The data to hydrate the type with.
set_type_attrs: A boolean indicating whether or not attributes that end
... | Below is the the instruction that describes the task:
### Input:
Initialize a SOAP element with specific data.
Args:
elem_type: The type of the element to create.
type_is_override: A boolean specifying if the type is being overridden.
data: The data to hydrate the type with.
set_type_at... |
def stylize(self, images, style=None, verbose=True, max_size=800, batch_size = 4):
"""
Stylize an SFrame of Images given a style index or a list of
styles.
Parameters
----------
images : SFrame | Image
A dataset that has the same content image column that was... | Stylize an SFrame of Images given a style index or a list of
styles.
Parameters
----------
images : SFrame | Image
A dataset that has the same content image column that was used
during training.
style : int or list, optional
The selected styl... | Below is the the instruction that describes the task:
### Input:
Stylize an SFrame of Images given a style index or a list of
styles.
Parameters
----------
images : SFrame | Image
A dataset that has the same content image column that was used
during training.... |
def pick_flat_z(data):
"""Generate a 2D array of the quasiparticle weight by only selecting the
first particle data"""
zmes = []
for i in data['zeta']:
zmes.append(i[:, 0])
return np.asarray(zmes) | Generate a 2D array of the quasiparticle weight by only selecting the
first particle data | Below is the the instruction that describes the task:
### Input:
Generate a 2D array of the quasiparticle weight by only selecting the
first particle data
### Response:
def pick_flat_z(data):
"""Generate a 2D array of the quasiparticle weight by only selecting the
first particle data"""
zmes = []
... |
def get_covalent_bonds(self, tol=0.2):
"""
Determines the covalent bonds in a molecule.
Args:
tol (float): The tol to determine bonds in a structure. See
CovalentBond.is_bonded.
Returns:
List of bonds
"""
bonds = []
for si... | Determines the covalent bonds in a molecule.
Args:
tol (float): The tol to determine bonds in a structure. See
CovalentBond.is_bonded.
Returns:
List of bonds | Below is the the instruction that describes the task:
### Input:
Determines the covalent bonds in a molecule.
Args:
tol (float): The tol to determine bonds in a structure. See
CovalentBond.is_bonded.
Returns:
List of bonds
### Response:
def get_covalent_bon... |
def clear_preview(self):
"""stub"""
try:
rm = self.my_osid_object._get_provider_manager('REPOSITORY')
except AttributeError:
rm = self.my_osid_object_form._get_provider_manager('REPOSITORY')
try:
aas = rm.get_asset_admin_session_for_repository(
... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def clear_preview(self):
"""stub"""
try:
rm = self.my_osid_object._get_provider_manager('REPOSITORY')
except AttributeError:
rm = self.my_osid_object_form._get_provider_manager('REPOS... |
def _contextualise(self):
'''Determine contextual idents (cidents)'''
# loop through hierarchy identifying unique lineages
# TODO: gain other contextual information, not just ident
deja_vues = []
for rank in reversed(self.taxonomy):
# return named clades -- '' are ign... | Determine contextual idents (cidents) | Below is the the instruction that describes the task:
### Input:
Determine contextual idents (cidents)
### Response:
def _contextualise(self):
'''Determine contextual idents (cidents)'''
# loop through hierarchy identifying unique lineages
# TODO: gain other contextual information, not just... |
def close_hover(self, element, use_js=False):
"""
Close hover by moving to a set offset "away" from the element being hovered.
:param element: element that triggered the hover to open
:param use_js: use javascript to close hover
:return: None
"""
try:
... | Close hover by moving to a set offset "away" from the element being hovered.
:param element: element that triggered the hover to open
:param use_js: use javascript to close hover
:return: None | Below is the the instruction that describes the task:
### Input:
Close hover by moving to a set offset "away" from the element being hovered.
:param element: element that triggered the hover to open
:param use_js: use javascript to close hover
:return: None
### Response:
def close_hover(se... |
def get_entity_propnames(entity):
""" Get entity property names
:param entity: Entity
:type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta
:returns: Set of entity property names
:rtype: set
"""
ins = entity if isinstance(entity, InstanceState) else inspect(entity)
... | Get entity property names
:param entity: Entity
:type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta
:returns: Set of entity property names
:rtype: set | Below is the the instruction that describes the task:
### Input:
Get entity property names
:param entity: Entity
:type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta
:returns: Set of entity property names
:rtype: set
### Response:
def get_entity_propnames(entity):
""" G... |
def CreateGroup(self, GroupName):
"""Creates a custom contact group.
:Parameters:
GroupName : unicode
Group name.
:return: A group object.
:rtype: `Group`
:see: `DeleteGroup`
"""
groups = self.CustomGroups
self._DoCommand('CREATE G... | Creates a custom contact group.
:Parameters:
GroupName : unicode
Group name.
:return: A group object.
:rtype: `Group`
:see: `DeleteGroup` | Below is the the instruction that describes the task:
### Input:
Creates a custom contact group.
:Parameters:
GroupName : unicode
Group name.
:return: A group object.
:rtype: `Group`
:see: `DeleteGroup`
### Response:
def CreateGroup(self, GroupName):
... |
def add_sink(self, sink):
"""Add a vehicle data sink to the instance. ``sink`` should be a
sub-class of ``DataSink`` or at least have a ``receive(message,
**kwargs)`` method.
The sink will be started if it is startable. (i.e. it has a ``start()``
method).
"""
if ... | Add a vehicle data sink to the instance. ``sink`` should be a
sub-class of ``DataSink`` or at least have a ``receive(message,
**kwargs)`` method.
The sink will be started if it is startable. (i.e. it has a ``start()``
method). | Below is the the instruction that describes the task:
### Input:
Add a vehicle data sink to the instance. ``sink`` should be a
sub-class of ``DataSink`` or at least have a ``receive(message,
**kwargs)`` method.
The sink will be started if it is startable. (i.e. it has a ``start()``
... |
def managed(name,
venv_bin=None,
requirements=None,
system_site_packages=False,
distribute=False,
use_wheel=False,
clear=False,
python=None,
extra_search_dir=None,
never_download=None,
prompt=None,
... | Create a virtualenv and optionally manage it with pip
name
Path to the virtualenv.
venv_bin: virtualenv
The name (and optionally path) of the virtualenv command. This can also
be set globally in the minion config file as ``virtualenv.venv_bin``.
requirements: None
Path to ... | Below is the the instruction that describes the task:
### Input:
Create a virtualenv and optionally manage it with pip
name
Path to the virtualenv.
venv_bin: virtualenv
The name (and optionally path) of the virtualenv command. This can also
be set globally in the minion config file... |
def _crps_cdf_single(x, cdf_or_dist, xmin=None, xmax=None, tol=1e-6):
"""
See crps_cdf for docs.
"""
# TODO: this function is pretty slow. Look for clever ways to speed it up.
# allow for directly passing in scipy.stats distribution objects.
cdf = getattr(cdf_or_dist, 'cdf', cdf_or_dist)
a... | See crps_cdf for docs. | Below is the the instruction that describes the task:
### Input:
See crps_cdf for docs.
### Response:
def _crps_cdf_single(x, cdf_or_dist, xmin=None, xmax=None, tol=1e-6):
"""
See crps_cdf for docs.
"""
# TODO: this function is pretty slow. Look for clever ways to speed it up.
# allow for dir... |
def mean(data, n=3, **kwargs):
"""The mean forecast for the next point is the mean value of the previous ``n`` points in
the series.
Args:
data (np.array): Observed data, presumed to be ordered in time.
n (int): period over which to calculate the mean
Returns:
float: a single... | The mean forecast for the next point is the mean value of the previous ``n`` points in
the series.
Args:
data (np.array): Observed data, presumed to be ordered in time.
n (int): period over which to calculate the mean
Returns:
float: a single-valued forecast for the next value in... | Below is the the instruction that describes the task:
### Input:
The mean forecast for the next point is the mean value of the previous ``n`` points in
the series.
Args:
data (np.array): Observed data, presumed to be ordered in time.
n (int): period over which to calculate the mean
R... |
def create_core(self, thing_name, config_file, region=None,
cert_dir=None, account_id=None,
policy_name='ggc-default-policy', profile_name=None):
"""
Using the `thing_name` value, creates a Thing in AWS IoT, attaches and
downloads new keys & certs to the c... | Using the `thing_name` value, creates a Thing in AWS IoT, attaches and
downloads new keys & certs to the certificate directory, then records
the created information in the local config file for inclusion in the
Greengrass Group as a Greengrass Core.
:param thing_name: the name of the th... | Below is the the instruction that describes the task:
### Input:
Using the `thing_name` value, creates a Thing in AWS IoT, attaches and
downloads new keys & certs to the certificate directory, then records
the created information in the local config file for inclusion in the
Greengrass Group... |
def showLayer(self, title='', debugText=''):
"""
Shows the single layer.
:param title: A string with the title of the window where to render the image.
:param debugText: A string with some text to render over the image.
:rtype: Nothing.
"""
img = PIL.Image.fromarray(self.data, 'RGBA')
if debugText!='... | Shows the single layer.
:param title: A string with the title of the window where to render the image.
:param debugText: A string with some text to render over the image.
:rtype: Nothing. | Below is the the instruction that describes the task:
### Input:
Shows the single layer.
:param title: A string with the title of the window where to render the image.
:param debugText: A string with some text to render over the image.
:rtype: Nothing.
### Response:
def showLayer(self, title='', debugText... |
def solveConsPrefShock(solution_next,IncomeDstn,PrefShkDstn,
LivPrb,DiscFac,CRRA,Rfree,PermGroFac,BoroCnstArt,
aXtraGrid,vFuncBool,CubicBool):
'''
Solves a single period of a consumption-saving model with preference shocks
to marginal utility. Problem is solved... | Solves a single period of a consumption-saving model with preference shocks
to marginal utility. Problem is solved using the method of endogenous gridpoints.
Parameters
----------
solution_next : ConsumerSolution
The solution to the succeeding one period problem.
IncomeDstn : [np.array]
... | Below is the the instruction that describes the task:
### Input:
Solves a single period of a consumption-saving model with preference shocks
to marginal utility. Problem is solved using the method of endogenous gridpoints.
Parameters
----------
solution_next : ConsumerSolution
The solution... |
def _pyshark_read_frame(self):
"""Read frames."""
from pcapkit.toolkit.pyshark import packet2dict, tcp_traceflow
# fetch PyShark packet
packet = next(self._extmp)
# def _pyshark_packet2chain(packet):
# """Fetch PyShark packet protocol chain."""
# return ... | Read frames. | Below is the the instruction that describes the task:
### Input:
Read frames.
### Response:
def _pyshark_read_frame(self):
"""Read frames."""
from pcapkit.toolkit.pyshark import packet2dict, tcp_traceflow
# fetch PyShark packet
packet = next(self._extmp)
# def _pyshark_pac... |
def to_bedtool(iterator):
"""
Convert any iterator into a pybedtools.BedTool object.
Note that the supplied iterator is not consumed by this function. To save
to a temp file or to a known location, use the `.saveas()` method of the
returned BedTool object.
"""
def gen():
for i in it... | Convert any iterator into a pybedtools.BedTool object.
Note that the supplied iterator is not consumed by this function. To save
to a temp file or to a known location, use the `.saveas()` method of the
returned BedTool object. | Below is the the instruction that describes the task:
### Input:
Convert any iterator into a pybedtools.BedTool object.
Note that the supplied iterator is not consumed by this function. To save
to a temp file or to a known location, use the `.saveas()` method of the
returned BedTool object.
### Respons... |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep
"""
layer_purpose = self.parent.step_kw_purpose.selected_purpose()
if layer_purpose != layer_purpose_aggregation:
subcat... | Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep | Below is the the instruction that describes the task:
### Input:
Find the proper step when user clicks the Next button.
:returns: The step to be switched to
:rtype: WizardStep
### Response:
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns... |
def nth(series, n, order_by=None):
"""
Returns the nth value of a series.
Args:
series (pandas.Series): column to summarize.
n (integer): position of desired value. Returns `NaN` if out of range.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
... | Returns the nth value of a series.
Args:
series (pandas.Series): column to summarize.
n (integer): position of desired value. Returns `NaN` if out of range.
Kwargs:
order_by: a pandas.Series or list of series (can be symbolic) to order
the input series by before summarizati... | Below is the the instruction that describes the task:
### Input:
Returns the nth value of a series.
Args:
series (pandas.Series): column to summarize.
n (integer): position of desired value. Returns `NaN` if out of range.
Kwargs:
order_by: a pandas.Series or list of series (can be ... |
def list_customer_users(self, customer_id):
"""List all users from a specified customer id."""
content = self._fetch("/customer/users/%s" % customer_id)
return map(lambda x: FastlyUser(self, x), content) | List all users from a specified customer id. | Below is the the instruction that describes the task:
### Input:
List all users from a specified customer id.
### Response:
def list_customer_users(self, customer_id):
"""List all users from a specified customer id."""
content = self._fetch("/customer/users/%s" % customer_id)
return map(lambda x: FastlyUser(... |
def create_control(self, pid, callback, callback_parsed=None):
"""Create a control for this Thing with a local point id (pid) and a control request feedback
Returns a new [Control](Point.m.html#IoticAgent.IOT.Point.Control) object
or the existing one if the Control already exists
Raise... | Create a control for this Thing with a local point id (pid) and a control request feedback
Returns a new [Control](Point.m.html#IoticAgent.IOT.Point.Control) object
or the existing one if the Control already exists
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTExceptio... | Below is the the instruction that describes the task:
### Input:
Create a control for this Thing with a local point id (pid) and a control request feedback
Returns a new [Control](Point.m.html#IoticAgent.IOT.Point.Control) object
or the existing one if the Control already exists
Raises [IO... |
def discard_member(self, member, pipe=None):
"""
Remove *member* from the collection, unconditionally.
"""
pipe = self.redis if pipe is None else pipe
pipe.zrem(self.key, self._pickle(member)) | Remove *member* from the collection, unconditionally. | Below is the the instruction that describes the task:
### Input:
Remove *member* from the collection, unconditionally.
### Response:
def discard_member(self, member, pipe=None):
"""
Remove *member* from the collection, unconditionally.
"""
pipe = self.redis if pipe is None else pipe... |
def HA2(credentials, request, algorithm):
"""Create HA2 md5 hash
If the qop directive's value is "auth" or is unspecified, then HA2:
HA2 = md5(A2) = MD5(method:digestURI)
If the qop directive's value is "auth-int" , then HA2 is
HA2 = md5(A2) = MD5(method:digestURI:MD5(entityBody))
"""
... | Create HA2 md5 hash
If the qop directive's value is "auth" or is unspecified, then HA2:
HA2 = md5(A2) = MD5(method:digestURI)
If the qop directive's value is "auth-int" , then HA2 is
HA2 = md5(A2) = MD5(method:digestURI:MD5(entityBody)) | Below is the the instruction that describes the task:
### Input:
Create HA2 md5 hash
If the qop directive's value is "auth" or is unspecified, then HA2:
HA2 = md5(A2) = MD5(method:digestURI)
If the qop directive's value is "auth-int" , then HA2 is
HA2 = md5(A2) = MD5(method:digestURI:MD5(en... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.