code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def send_response(self, msgid, response):
"""Send a response."""
msg = dumps([2, msgid, response])
self.send(msg) | Send a response. | Below is the the instruction that describes the task:
### Input:
Send a response.
### Response:
def send_response(self, msgid, response):
"""Send a response."""
msg = dumps([2, msgid, response])
self.send(msg) |
def open(self, input_id, **kwargs):
"""
Open input data.
Parameters
----------
input_id : string
input identifier from configuration file or file path
kwargs : driver specific parameters (e.g. resampling)
Returns
-------
tiled input d... | Open input data.
Parameters
----------
input_id : string
input identifier from configuration file or file path
kwargs : driver specific parameters (e.g. resampling)
Returns
-------
tiled input data : InputTile
reprojected input data withi... | Below is the the instruction that describes the task:
### Input:
Open input data.
Parameters
----------
input_id : string
input identifier from configuration file or file path
kwargs : driver specific parameters (e.g. resampling)
Returns
-------
... |
def splits(cls, fields, root=".data", train="train.txt",
test="test.txt", validation_frac=0.1, **kwargs):
"""Downloads and loads the CoNLL 2000 Chunking dataset.
NOTE: There is only a train and test dataset so we use
10% of the train set as validation
"""
tr... | Downloads and loads the CoNLL 2000 Chunking dataset.
NOTE: There is only a train and test dataset so we use
10% of the train set as validation | Below is the the instruction that describes the task:
### Input:
Downloads and loads the CoNLL 2000 Chunking dataset.
NOTE: There is only a train and test dataset so we use
10% of the train set as validation
### Response:
def splits(cls, fields, root=".data", train="train.txt",
... |
def clean_part_ethn(body):
"""
Prepare a string to be parsed for ethnicities.
Returns a "translated" string (e.g. all instances of "china" converted to "chinese")
"""
# patterns that can create false positive situations
patterns_to_remove = [r'black ?or ?african', r'african ?or ?black', r'no ?black', ... | Prepare a string to be parsed for ethnicities.
Returns a "translated" string (e.g. all instances of "china" converted to "chinese") | Below is the the instruction that describes the task:
### Input:
Prepare a string to be parsed for ethnicities.
Returns a "translated" string (e.g. all instances of "china" converted to "chinese")
### Response:
def clean_part_ethn(body):
"""
Prepare a string to be parsed for ethnicities.
Returns a ... |
def derivativeZ(self,x,y,z):
'''
Evaluate the first derivative with respect to z of the function at given
state space points.
Parameters
----------
x : np.array
First input values.
y : np.array
Second input values; should be of same shap... | Evaluate the first derivative with respect to z of the function at given
state space points.
Parameters
----------
x : np.array
First input values.
y : np.array
Second input values; should be of same shape as x.
z : np.array
Third i... | Below is the the instruction that describes the task:
### Input:
Evaluate the first derivative with respect to z of the function at given
state space points.
Parameters
----------
x : np.array
First input values.
y : np.array
Second input values; sh... |
def get_terms_complete(self) -> pd.DataFrame:
''' Gets complete entity data like term/view '''
if not self.terms_complete.empty:
return self.terms_complete
if self.from_backup:
self.terms_complete = open_pickle(TERMS_COMPLETE_BACKUP_PATH)
return self.terms_com... | Gets complete entity data like term/view | Below is the the instruction that describes the task:
### Input:
Gets complete entity data like term/view
### Response:
def get_terms_complete(self) -> pd.DataFrame:
''' Gets complete entity data like term/view '''
if not self.terms_complete.empty:
return self.terms_complete
if ... |
def normalize_table_name(name):
"""Check if the table name is obviously invalid."""
if not isinstance(name, six.string_types):
raise ValueError("Invalid table name: %r" % name)
name = name.strip()[:63]
if not len(name):
raise ValueError("Invalid table name: %r" % name)
return name | Check if the table name is obviously invalid. | Below is the the instruction that describes the task:
### Input:
Check if the table name is obviously invalid.
### Response:
def normalize_table_name(name):
"""Check if the table name is obviously invalid."""
if not isinstance(name, six.string_types):
raise ValueError("Invalid table name: %r" % nam... |
def load(filename, default=None):
'''
Try to load @filename. If there is no loader for @filename's filetype,
return @default.
'''
ext = get_ext(filename)
if ext in ldict:
return ldict[ext](filename)
else:
return default | Try to load @filename. If there is no loader for @filename's filetype,
return @default. | Below is the the instruction that describes the task:
### Input:
Try to load @filename. If there is no loader for @filename's filetype,
return @default.
### Response:
def load(filename, default=None):
'''
Try to load @filename. If there is no loader for @filename's filetype,
return @default.
... |
def obfn_reg(self):
"""Compute regularisation term and contribution to objective
function.
"""
rl1 = np.linalg.norm((self.Wl1 * self.obfn_g1var()).ravel(), 1)
rtv = np.sum(np.sqrt(np.sum(self.obfn_g0var()**2, axis=-1)))
return (self.lmbda*rl1 + self.mu*rtv, rl1, rtv) | Compute regularisation term and contribution to objective
function. | Below is the the instruction that describes the task:
### Input:
Compute regularisation term and contribution to objective
function.
### Response:
def obfn_reg(self):
"""Compute regularisation term and contribution to objective
function.
"""
rl1 = np.linalg.norm((self.Wl1 *... |
def _string_from_ip_int(cls, ip_int):
"""Turns a 32-bit integer into dotted decimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
The IP address as a string in dotted decimal notation.
"""
return '.'.join(_compat_str(struct.unpack(b'!B', ... | Turns a 32-bit integer into dotted decimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
The IP address as a string in dotted decimal notation. | Below is the the instruction that describes the task:
### Input:
Turns a 32-bit integer into dotted decimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
The IP address as a string in dotted decimal notation.
### Response:
def _string_from_ip_int(cls, ip_int... |
def rename_file(self, old_path, new_path):
"""Rename the current notebook, as well as its alternative representations"""
if old_path not in self.paired_notebooks:
try:
# we do not know yet if this is a paired notebook (#190)
# -> to get this information we ope... | Rename the current notebook, as well as its alternative representations | Below is the the instruction that describes the task:
### Input:
Rename the current notebook, as well as its alternative representations
### Response:
def rename_file(self, old_path, new_path):
"""Rename the current notebook, as well as its alternative representations"""
if old_path not in self.pai... |
def get_preparation_data(name):
'''
Return info about parent needed by child to unpickle process object.
Monkey-patch from
'''
d = dict(
name=name,
sys_path=sys.path,
sys_argv=sys.argv,
log_to_stderr=_log_to_stderr,
orig_dir=process.ORIGINAL_DIR,
... | Return info about parent needed by child to unpickle process object.
Monkey-patch from | Below is the the instruction that describes the task:
### Input:
Return info about parent needed by child to unpickle process object.
Monkey-patch from
### Response:
def get_preparation_data(name):
'''
Return info about parent needed by child to unpickle process object.
Monkey-patch from
'... |
def matches_query(self, key, query):
"""
增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回结果相同。
:param key: 查询条件字段名
:param query: 查询对象
:type query: Query
:rtype: Query
"""
dumped = query.dump()
dumped['className'] = query._query_class._class_name
self._a... | 增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回结果相同。
:param key: 查询条件字段名
:param query: 查询对象
:type query: Query
:rtype: Query | Below is the the instruction that describes the task:
### Input:
增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回结果相同。
:param key: 查询条件字段名
:param query: 查询对象
:type query: Query
:rtype: Query
### Response:
def matches_query(self, key, query):
"""
增加查询条件,限制查询结果对象指定字段的值,与另外一个查询对象的返回... |
async def text(self,
encoding: Optional[str]=None, errors: str='strict') -> str:
"""Read response payload and decode."""
if self._body is None:
await self.read()
if encoding is None:
encoding = self.get_encoding()
return self._body.decode(enco... | Read response payload and decode. | Below is the the instruction that describes the task:
### Input:
Read response payload and decode.
### Response:
async def text(self,
encoding: Optional[str]=None, errors: str='strict') -> str:
"""Read response payload and decode."""
if self._body is None:
await self.... |
def get_pipeline(self, *args, **kwargs):
'''
Returns the `time` and `flux` arrays for the target obtained by a given
pipeline.
Options :py:obj:`args` and :py:obj:`kwargs` are passed directly to
the :py:func:`pipelines.get` function of the mission.
'''
return ge... | Returns the `time` and `flux` arrays for the target obtained by a given
pipeline.
Options :py:obj:`args` and :py:obj:`kwargs` are passed directly to
the :py:func:`pipelines.get` function of the mission. | Below is the the instruction that describes the task:
### Input:
Returns the `time` and `flux` arrays for the target obtained by a given
pipeline.
Options :py:obj:`args` and :py:obj:`kwargs` are passed directly to
the :py:func:`pipelines.get` function of the mission.
### Response:
def get_... |
def _new_replica(self, instance_id: int, is_master: bool, bls_bft: BlsBft) -> Replica:
"""
Create a new replica with the specified parameters.
"""
return self._replica_class(self._node, instance_id, self._config, is_master, bls_bft, self._metrics) | Create a new replica with the specified parameters. | Below is the the instruction that describes the task:
### Input:
Create a new replica with the specified parameters.
### Response:
def _new_replica(self, instance_id: int, is_master: bool, bls_bft: BlsBft) -> Replica:
"""
Create a new replica with the specified parameters.
"""
retur... |
async def fire(self, *args, **kwargs):
"""Fire this event, calling all observers with the same arguments."""
logger.debug('Fired {}'.format(self))
for observer in self._observers:
gen = observer(*args, **kwargs)
if asyncio.iscoroutinefunction(observer):
aw... | Fire this event, calling all observers with the same arguments. | Below is the the instruction that describes the task:
### Input:
Fire this event, calling all observers with the same arguments.
### Response:
async def fire(self, *args, **kwargs):
"""Fire this event, calling all observers with the same arguments."""
logger.debug('Fired {}'.format(self))
f... |
def _invert(color, **kwargs):
""" Returns the inverse (negative) of a color.
The red, green, and blue values are inverted, while the opacity is left alone.
"""
col = ColorValue(color)
args = [
255.0 - col.value[0],
255.0 - col.value[1],
255.0 - col.value[2],
col.v... | Returns the inverse (negative) of a color.
The red, green, and blue values are inverted, while the opacity is left alone. | Below is the the instruction that describes the task:
### Input:
Returns the inverse (negative) of a color.
The red, green, and blue values are inverted, while the opacity is left alone.
### Response:
def _invert(color, **kwargs):
""" Returns the inverse (negative) of a color.
The red, green, a... |
def _set_mac_group(self, v, load=False):
"""
Setter method for mac_group, mapped from YANG variable /mac_group (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_group is considered as a private
method. Backends looking to populate this variable should
do... | Setter method for mac_group, mapped from YANG variable /mac_group (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_group is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mac_group() directly. | Below is the the instruction that describes the task:
### Input:
Setter method for mac_group, mapped from YANG variable /mac_group (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_group is considered as a private
method. Backends looking to populate this variab... |
def check_web_config_consistency(config):
'''
Check the web application config file for consistency.
'''
login_conf_deps = {
'LOGIN_TWITTER_OAUTH_KEY': ['LOGIN_TWITTER_OAUTH_SECRET'],
'LOGIN_GOOGLE_OAUTH_KEY': ['LOGIN_GOOGLE_OAUTH_SECRET'],
'LOGIN_GITHUB_OAUTH_KEY': ['LOGIN_G... | Check the web application config file for consistency. | Below is the the instruction that describes the task:
### Input:
Check the web application config file for consistency.
### Response:
def check_web_config_consistency(config):
'''
Check the web application config file for consistency.
'''
login_conf_deps = {
'LOGIN_TWITTER_OAUTH_KEY': [... |
def _makeTags(tagStr, xml):
"""Internal helper to construct opening and closing tag expressions, given a tag name"""
if isinstance(tagStr,basestring):
resname = tagStr
tagStr = Keyword(tagStr, caseless=not xml)
else:
resname = tagStr.name
tagAttrName = Word(alphas,alphan... | Internal helper to construct opening and closing tag expressions, given a tag name | Below is the the instruction that describes the task:
### Input:
Internal helper to construct opening and closing tag expressions, given a tag name
### Response:
def _makeTags(tagStr, xml):
"""Internal helper to construct opening and closing tag expressions, given a tag name"""
if isinstance(tagStr,bases... |
def summary(self, raw):
"""
Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the most malicious level found
... | Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the most malicious level found
Examples:
Input
{... | Below is the the instruction that describes the task:
### Input:
Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the mos... |
def rowlengths(table):
"""
Report on row lengths found in the table. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar', 'baz'],
... ['A', 1, 2],
... ['B', '2', '3.4'],
... [u'B', u'3', u'7.8', True],
... ['D', 'xyz', 9.0... | Report on row lengths found in the table. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar', 'baz'],
... ['A', 1, 2],
... ['B', '2', '3.4'],
... [u'B', u'3', u'7.8', True],
... ['D', 'xyz', 9.0],
... ['E', None]... | Below is the the instruction that describes the task:
### Input:
Report on row lengths found in the table. E.g.::
>>> import petl as etl
>>> table = [['foo', 'bar', 'baz'],
... ['A', 1, 2],
... ['B', '2', '3.4'],
... [u'B', u'3', u'7.8', True],
... |
def read_header_at( cls, f):
"""
Given an open file-like object, read a block header
from it and return it as a dict containing:
* version (int)
* prev_block_hash (hex str)
* merkle_root (hex str)
* timestamp (int)
* bits (int)
* nonce (ini)
... | Given an open file-like object, read a block header
from it and return it as a dict containing:
* version (int)
* prev_block_hash (hex str)
* merkle_root (hex str)
* timestamp (int)
* bits (int)
* nonce (ini)
* hash (hex str) | Below is the the instruction that describes the task:
### Input:
Given an open file-like object, read a block header
from it and return it as a dict containing:
* version (int)
* prev_block_hash (hex str)
* merkle_root (hex str)
* timestamp (int)
* bits (int)
... |
def cmd_status(args):
'''show status'''
if len(args) == 0:
mpstate.status.show(sys.stdout, pattern=None)
else:
for pattern in args:
mpstate.status.show(sys.stdout, pattern=pattern) | show status | Below is the the instruction that describes the task:
### Input:
show status
### Response:
def cmd_status(args):
'''show status'''
if len(args) == 0:
mpstate.status.show(sys.stdout, pattern=None)
else:
for pattern in args:
mpstate.status.show(sys.stdout, pattern=pattern) |
def type_map_directive_reducer(
map_: TypeMap, directive: GraphQLDirective = None
) -> TypeMap:
"""Reducer function for creating the type map from given directives."""
# Directives are not validated until validate_schema() is called.
if not is_directive(directive):
return map_
directive = ca... | Reducer function for creating the type map from given directives. | Below is the the instruction that describes the task:
### Input:
Reducer function for creating the type map from given directives.
### Response:
def type_map_directive_reducer(
map_: TypeMap, directive: GraphQLDirective = None
) -> TypeMap:
"""Reducer function for creating the type map from given directive... |
def _package(self, task, *args, **kw):
"""
Used internally. Simply wraps the arguments up in a list and encodes
the list.
"""
# Implementation note: it is faster to use a tuple than a list here,
# because json does the list-like check like so (json/encoder.py:424):
... | Used internally. Simply wraps the arguments up in a list and encodes
the list. | Below is the the instruction that describes the task:
### Input:
Used internally. Simply wraps the arguments up in a list and encodes
the list.
### Response:
def _package(self, task, *args, **kw):
"""
Used internally. Simply wraps the arguments up in a list and encodes
the list.
... |
def write_timestamp(self, v):
"""
Write out a Python datetime.datetime object as a 64-bit integer
representing seconds since the Unix epoch.
"""
self.out.write(pack('>q', long(mktime(v.timetuple())))) | Write out a Python datetime.datetime object as a 64-bit integer
representing seconds since the Unix epoch. | Below is the the instruction that describes the task:
### Input:
Write out a Python datetime.datetime object as a 64-bit integer
representing seconds since the Unix epoch.
### Response:
def write_timestamp(self, v):
"""
Write out a Python datetime.datetime object as a 64-bit integer
... |
def check(self):
"""
Returns #True if the time interval has passed.
"""
if self.value is None:
return True
return (time.clock() - self.start) >= self.value | Returns #True if the time interval has passed. | Below is the the instruction that describes the task:
### Input:
Returns #True if the time interval has passed.
### Response:
def check(self):
"""
Returns #True if the time interval has passed.
"""
if self.value is None:
return True
return (time.clock() - self.start) >= self.value |
def to_bytes(data: Union[str, bytes]) -> bytes:
"""
:param data: Data to convert to bytes.
:type data: Union[str, bytes]
:return: `data` encoded to UTF8.
:rtype: bytes
"""
if isinstance(data, bytes):
return data
return data.encode('utf-8') | :param data: Data to convert to bytes.
:type data: Union[str, bytes]
:return: `data` encoded to UTF8.
:rtype: bytes | Below is the the instruction that describes the task:
### Input:
:param data: Data to convert to bytes.
:type data: Union[str, bytes]
:return: `data` encoded to UTF8.
:rtype: bytes
### Response:
def to_bytes(data: Union[str, bytes]) -> bytes:
"""
:param data: Data to convert to bytes.
:type... |
def add(self, record):
"""Add a reference to the provided record"""
self._field.validate_value(record)
self._elements[record.id] = record
self._sync_field() | Add a reference to the provided record | Below is the the instruction that describes the task:
### Input:
Add a reference to the provided record
### Response:
def add(self, record):
"""Add a reference to the provided record"""
self._field.validate_value(record)
self._elements[record.id] = record
self._sync_field() |
def n_feature_hash(feature, dims, seeds):
"""N-hot-encoded feature hashing.
Args:
feature (str): Target feature represented as string.
dims (list of int): Number of dimensions for each hash value.
seeds (list of float): Seed of each hash function (mmh3).
Returns:
numpy 1d a... | N-hot-encoded feature hashing.
Args:
feature (str): Target feature represented as string.
dims (list of int): Number of dimensions for each hash value.
seeds (list of float): Seed of each hash function (mmh3).
Returns:
numpy 1d array: n-hot-encoded feature vector for `s`. | Below is the the instruction that describes the task:
### Input:
N-hot-encoded feature hashing.
Args:
feature (str): Target feature represented as string.
dims (list of int): Number of dimensions for each hash value.
seeds (list of float): Seed of each hash function (mmh3).
Returns... |
def data_and_labels(self):
"""
Dataset features and labels in a matrix form for learning.
Also returns sample_ids in the same order.
Returns
-------
data_matrix : ndarray
2D array of shape [num_samples, num_features]
with features corresponding r... | Dataset features and labels in a matrix form for learning.
Also returns sample_ids in the same order.
Returns
-------
data_matrix : ndarray
2D array of shape [num_samples, num_features]
with features corresponding row-wise to sample_ids
labels : ndarray
... | Below is the the instruction that describes the task:
### Input:
Dataset features and labels in a matrix form for learning.
Also returns sample_ids in the same order.
Returns
-------
data_matrix : ndarray
2D array of shape [num_samples, num_features]
with fe... |
def write_addons_items(xml_tree, records, app_id, api_ver=3, app_ver=None):
"""Generate the addons blocklists.
<emItem blockID="i372" id="5nc3QHFgcb@r06Ws9gvNNVRfH.com">
<versionRange minVersion="0" maxVersion="*" severity="3">
<targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
... | Generate the addons blocklists.
<emItem blockID="i372" id="5nc3QHFgcb@r06Ws9gvNNVRfH.com">
<versionRange minVersion="0" maxVersion="*" severity="3">
<targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
<versionRange minVersion="39.0a1" maxVersion="*"/>
</targetApplication... | Below is the the instruction that describes the task:
### Input:
Generate the addons blocklists.
<emItem blockID="i372" id="5nc3QHFgcb@r06Ws9gvNNVRfH.com">
<versionRange minVersion="0" maxVersion="*" severity="3">
<targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
<versionR... |
def create(self, group_view=False):
""" Update with current tools """
self.add_handlers({'^T': self.quit, '^Q': self.quit})
self.add(npyscreen.TitleText,
name='Select which tools to ' + self.action['action'] + ':',
editable=False)
togglable = ['remove']
... | Update with current tools | Below is the the instruction that describes the task:
### Input:
Update with current tools
### Response:
def create(self, group_view=False):
""" Update with current tools """
self.add_handlers({'^T': self.quit, '^Q': self.quit})
self.add(npyscreen.TitleText,
name='Select wh... |
async def jsk_show(self, ctx: commands.Context):
"""
Shows Jishaku in the help command.
"""
if not self.jsk.hidden:
return await ctx.send("Jishaku is already visible.")
self.jsk.hidden = False
await ctx.send("Jishaku is now visible.") | Shows Jishaku in the help command. | Below is the the instruction that describes the task:
### Input:
Shows Jishaku in the help command.
### Response:
async def jsk_show(self, ctx: commands.Context):
"""
Shows Jishaku in the help command.
"""
if not self.jsk.hidden:
return await ctx.send("Jishaku is alread... |
def weibull(target, seeds, shape, scale, loc):
r"""
Produces values from a Weibull distribution given a set of random numbers.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also pro... | r"""
Produces values from a Weibull distribution given a set of random numbers.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.... | Below is the the instruction that describes the task:
### Input:
r"""
Produces values from a Weibull distribution given a set of random numbers.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated a... |
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
NWSRFS Read from File Method
"""
# Set file extension property
self.fileExtension = extension
# Open file and parse
with open(path, 'r') as nw... | NWSRFS Read from File Method | Below is the the instruction that describes the task:
### Input:
NWSRFS Read from File Method
### Response:
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
"""
NWSRFS Read from File Method
"""
# Set file extension ... |
def compute_n_digit_freqs(filename, n):
"""
Read digits of pi from a file and compute the n digit frequencies.
"""
d = txt_file_to_digits(filename)
freqs = n_digit_freqs(d, n)
return freqs | Read digits of pi from a file and compute the n digit frequencies. | Below is the the instruction that describes the task:
### Input:
Read digits of pi from a file and compute the n digit frequencies.
### Response:
def compute_n_digit_freqs(filename, n):
"""
Read digits of pi from a file and compute the n digit frequencies.
"""
d = txt_file_to_digits(filename)
f... |
def _copy(self):
"""
Called during a PUT request where the action specifies
a copy operation. Returns resource URI of the new file.
"""
copypath = self.action['copypath']
try:
self.fs.copy(self.fp,copypath)
except OSError:
raise tornado.web... | Called during a PUT request where the action specifies
a copy operation. Returns resource URI of the new file. | Below is the the instruction that describes the task:
### Input:
Called during a PUT request where the action specifies
a copy operation. Returns resource URI of the new file.
### Response:
def _copy(self):
"""
Called during a PUT request where the action specifies
a copy operation.... |
def send_tunnelling_request(self, cemi, auto_connect=True):
"""Sends a tunneling request based on the given CEMI data.
This method does not wait for an acknowledge or result frame.
"""
if not self.connected:
if auto_connect:
if not self.connect():
... | Sends a tunneling request based on the given CEMI data.
This method does not wait for an acknowledge or result frame. | Below is the the instruction that describes the task:
### Input:
Sends a tunneling request based on the given CEMI data.
This method does not wait for an acknowledge or result frame.
### Response:
def send_tunnelling_request(self, cemi, auto_connect=True):
"""Sends a tunneling request based on the... |
def est_payouts(self):
'''
Calculate current estimate of average payout for each bandit.
Returns
-------
array of floats or None
'''
if len(self.choices) < 1:
print('slots: No trials run so far.')
return None
else:
ret... | Calculate current estimate of average payout for each bandit.
Returns
-------
array of floats or None | Below is the the instruction that describes the task:
### Input:
Calculate current estimate of average payout for each bandit.
Returns
-------
array of floats or None
### Response:
def est_payouts(self):
'''
Calculate current estimate of average payout for each bandit.
... |
def add_feature(self, label, value=None):
"""
label: A VW label (not containing characters from escape_dict.keys(),
unless 'escape' mode is on)
value: float giving the weight or magnitude of this feature
"""
if self.escape:
label = escape_vw_string(label)
... | label: A VW label (not containing characters from escape_dict.keys(),
unless 'escape' mode is on)
value: float giving the weight or magnitude of this feature | Below is the the instruction that describes the task:
### Input:
label: A VW label (not containing characters from escape_dict.keys(),
unless 'escape' mode is on)
value: float giving the weight or magnitude of this feature
### Response:
def add_feature(self, label, value=None):
"""
... |
def ps(self):
"""
Get the process information from the system PS command.
"""
# Get the process ID
pid = self.get()
# Parent / child processes
parent = None
children = []
# If the process is running
if pid:
... | Get the process information from the system PS command. | Below is the the instruction that describes the task:
### Input:
Get the process information from the system PS command.
### Response:
def ps(self):
"""
Get the process information from the system PS command.
"""
# Get the process ID
pid = self.get()
... |
def _clearLists(self):
"""
Clear all list before sync : feeds and categories
"""
self.feedsById = {}
self.feeds = []
self.categoriesById = {}
self.categories = []
self.orphanFeeds = [] | Clear all list before sync : feeds and categories | Below is the the instruction that describes the task:
### Input:
Clear all list before sync : feeds and categories
### Response:
def _clearLists(self):
"""
Clear all list before sync : feeds and categories
"""
self.feedsById = {}
self.feeds = []
self.ca... |
def main():
'''Main routine.'''
# validate command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--sourcedir', '-s', required=True, action='store',
help='Source folder containing python files.')
arg_parser.add_argument('--docfile', '-o', ... | Main routine. | Below is the the instruction that describes the task:
### Input:
Main routine.
### Response:
def main():
'''Main routine.'''
# validate command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--sourcedir', '-s', required=True, action='store',
... |
def set_section( self, section_name ):
"""set current section during parsing"""
if not self.sections.has_key( section_name ):
section = DocSection( section_name )
self.sections[section_name] = section
self.section = section
else:
se... | set current section during parsing | Below is the the instruction that describes the task:
### Input:
set current section during parsing
### Response:
def set_section( self, section_name ):
"""set current section during parsing"""
if not self.sections.has_key( section_name ):
section = DocSection( section_name )
... |
def update_account(self, account):
"""
Update the passed account. Returns the updated account.
https://canvas.instructure.com/doc/api/accounts.html#method.accounts.update
"""
url = ACCOUNTS_API.format(account.account_id)
body = {"account": {"name": account.name}}
... | Update the passed account. Returns the updated account.
https://canvas.instructure.com/doc/api/accounts.html#method.accounts.update | Below is the the instruction that describes the task:
### Input:
Update the passed account. Returns the updated account.
https://canvas.instructure.com/doc/api/accounts.html#method.accounts.update
### Response:
def update_account(self, account):
"""
Update the passed account. Returns the u... |
def _get_path_pattern_tornado4(self):
"""Return the path pattern used when routing a request. (Tornado<4.5)
:rtype: str
"""
for host, handlers in self.application.handlers:
if host.match(self.request.host):
for handler in handlers:
if hand... | Return the path pattern used when routing a request. (Tornado<4.5)
:rtype: str | Below is the the instruction that describes the task:
### Input:
Return the path pattern used when routing a request. (Tornado<4.5)
:rtype: str
### Response:
def _get_path_pattern_tornado4(self):
"""Return the path pattern used when routing a request. (Tornado<4.5)
:rtype: str
"""... |
def _clean_workers(self):
"""Delete periodically workers in workers bag."""
while self._bag_collector:
self._bag_collector.popleft()
self._timer_worker_delete.stop() | Delete periodically workers in workers bag. | Below is the the instruction that describes the task:
### Input:
Delete periodically workers in workers bag.
### Response:
def _clean_workers(self):
"""Delete periodically workers in workers bag."""
while self._bag_collector:
self._bag_collector.popleft()
self._timer_worker_dele... |
def import_job(db, calc_id, calc_mode, description, user_name, status,
hc_id, datadir):
"""
Insert a calculation inside the database, if calc_id is not taken
"""
job = dict(id=calc_id,
calculation_mode=calc_mode,
description=description,
user_n... | Insert a calculation inside the database, if calc_id is not taken | Below is the the instruction that describes the task:
### Input:
Insert a calculation inside the database, if calc_id is not taken
### Response:
def import_job(db, calc_id, calc_mode, description, user_name, status,
hc_id, datadir):
"""
Insert a calculation inside the database, if calc_id is... |
def get_namespace(self):
"""
Find the name the user is using to access holoviews.
"""
if 'holoviews' not in sys.modules:
raise ImportError('HoloViews does not seem to be imported')
matches = [k for k,v in get_ipython().user_ns.items() # noqa (get_ipython)
i... | Find the name the user is using to access holoviews. | Below is the the instruction that describes the task:
### Input:
Find the name the user is using to access holoviews.
### Response:
def get_namespace(self):
"""
Find the name the user is using to access holoviews.
"""
if 'holoviews' not in sys.modules:
raise ImportError(... |
def results(self, limit=100):
"""
Yields the results from the API, efficiently handling the pagination and
properly passing all paramaters.
"""
limited = True if self.high_mark is not None else False
rmax = self.high_mark - self.low_mark if limited else None
rnum ... | Yields the results from the API, efficiently handling the pagination and
properly passing all paramaters. | Below is the the instruction that describes the task:
### Input:
Yields the results from the API, efficiently handling the pagination and
properly passing all paramaters.
### Response:
def results(self, limit=100):
"""
Yields the results from the API, efficiently handling the pagination and... |
def seek_to(self, position):
"""Move the Shard's iterator to the earliest record after the :class:`~datetime.datetime` time.
Returns the first records at or past ``position``. If the list is empty,
the seek failed to find records, either because the Shard is exhausted or it
reached the... | Move the Shard's iterator to the earliest record after the :class:`~datetime.datetime` time.
Returns the first records at or past ``position``. If the list is empty,
the seek failed to find records, either because the Shard is exhausted or it
reached the HEAD of an open Shard.
:param ... | Below is the the instruction that describes the task:
### Input:
Move the Shard's iterator to the earliest record after the :class:`~datetime.datetime` time.
Returns the first records at or past ``position``. If the list is empty,
the seek failed to find records, either because the Shard is exhaus... |
def proximal(self):
"""Return the ``proximal factory`` of the functional.
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_l1 :
`proximal factory` for the L1-norm.
"""
if self.pointwise_norm.exponent == 1:
return proximal_l1(spa... | Return the ``proximal factory`` of the functional.
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_l1 :
`proximal factory` for the L1-norm. | Below is the the instruction that describes the task:
### Input:
Return the ``proximal factory`` of the functional.
See Also
--------
odl.solvers.nonsmooth.proximal_operators.proximal_l1 :
`proximal factory` for the L1-norm.
### Response:
def proximal(self):
"""Return t... |
def find(self, *args, **kwargs):
"""Same as :meth:`pymongo.collection.Collection.find`, except
it returns the right document class.
"""
return Cursor(self, *args, wrap=self.document_class, **kwargs) | Same as :meth:`pymongo.collection.Collection.find`, except
it returns the right document class. | Below is the the instruction that describes the task:
### Input:
Same as :meth:`pymongo.collection.Collection.find`, except
it returns the right document class.
### Response:
def find(self, *args, **kwargs):
"""Same as :meth:`pymongo.collection.Collection.find`, except
it returns the right ... |
def textile(text, **kwargs):
"""
Applies Textile conversion to a string, and returns the HTML.
This is simply a pass-through to the ``textile`` template filter
included in ``django.contrib.markup``, which works around issues
PyTextile has with Unicode strings. If you're not using Django but
... | Applies Textile conversion to a string, and returns the HTML.
This is simply a pass-through to the ``textile`` template filter
included in ``django.contrib.markup``, which works around issues
PyTextile has with Unicode strings. If you're not using Django but
want to use Textile with ``MarkupFormatt... | Below is the the instruction that describes the task:
### Input:
Applies Textile conversion to a string, and returns the HTML.
This is simply a pass-through to the ``textile`` template filter
included in ``django.contrib.markup``, which works around issues
PyTextile has with Unicode strings. If you... |
def describe_reserved_db_instances_offerings(ReservedDBInstancesOfferingId=None, DBInstanceClass=None, Duration=None, ProductDescription=None, OfferingType=None, MultiAZ=None, Filters=None, MaxRecords=None, Marker=None):
"""
Lists available reserved DB instance offerings.
See also: AWS API Documentation
... | Lists available reserved DB instance offerings.
See also: AWS API Documentation
Examples
This example lists information for all reserved DB instance offerings for the specified DB instance class, duration, product, offering type, and availability zone settings.
Expected Output:
:example: r... | Below is the the instruction that describes the task:
### Input:
Lists available reserved DB instance offerings.
See also: AWS API Documentation
Examples
This example lists information for all reserved DB instance offerings for the specified DB instance class, duration, product, offering type, and ... |
def save_matlab_model(model, file_name, varname=None):
"""Save the cobra model as a .mat file.
This .mat file can be used directly in the MATLAB version of COBRA.
Parameters
----------
model : cobra.core.Model.Model object
The model to save
file_name : str or file-like object
T... | Save the cobra model as a .mat file.
This .mat file can be used directly in the MATLAB version of COBRA.
Parameters
----------
model : cobra.core.Model.Model object
The model to save
file_name : str or file-like object
The file to save to
varname : string
The name of the... | Below is the the instruction that describes the task:
### Input:
Save the cobra model as a .mat file.
This .mat file can be used directly in the MATLAB version of COBRA.
Parameters
----------
model : cobra.core.Model.Model object
The model to save
file_name : str or file-like object
... |
def sortByKey(self, ascending=True, numPartitions=None, keyfunc=lambda x: x):
"""
Sorts this RDD, which is assumed to consist of (key, value) pairs.
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortByKey().first()
('1', 3)
>>> sc.p... | Sorts this RDD, which is assumed to consist of (key, value) pairs.
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortByKey().first()
('1', 3)
>>> sc.parallelize(tmp).sortByKey(True, 1).collect()
[('1', 3), ('2', 5), ('a', 1), ('b', 2), ('d'... | Below is the the instruction that describes the task:
### Input:
Sorts this RDD, which is assumed to consist of (key, value) pairs.
>>> tmp = [('a', 1), ('b', 2), ('1', 3), ('d', 4), ('2', 5)]
>>> sc.parallelize(tmp).sortByKey().first()
('1', 3)
>>> sc.parallelize(tmp).sortByKey(Tru... |
def db_continue( block_id, consensus_hash ):
"""
(required by virtualchain state engine)
Called when virtualchain has synchronized all state for this block.
Blockstack uses this as a preemption point where it can safely
exit if the user has so requested.
"""
# every so often, clean up
... | (required by virtualchain state engine)
Called when virtualchain has synchronized all state for this block.
Blockstack uses this as a preemption point where it can safely
exit if the user has so requested. | Below is the the instruction that describes the task:
### Input:
(required by virtualchain state engine)
Called when virtualchain has synchronized all state for this block.
Blockstack uses this as a preemption point where it can safely
exit if the user has so requested.
### Response:
def db_continue( ... |
def debug(self): # pragma: no cover
"""Prints all configuration registries for debugging purposes."""
print("Aliases:")
pprint.pprint(self._aliases)
print("Override:")
pprint.pprint(self._override)
print("Args:")
pprint.pprint(self._args)
print("Env:")
... | Prints all configuration registries for debugging purposes. | Below is the the instruction that describes the task:
### Input:
Prints all configuration registries for debugging purposes.
### Response:
def debug(self): # pragma: no cover
"""Prints all configuration registries for debugging purposes."""
print("Aliases:")
pprint.pprint(self._aliases)
... |
def _match_serializers_by_query_arg(self, serializers):
"""Match serializer by query arg."""
# if the format query argument is present, match the serializer
arg_name = current_app.config.get('REST_MIMETYPE_QUERY_ARG_NAME')
if arg_name:
arg_value = request.args.get(arg_name, N... | Match serializer by query arg. | Below is the the instruction that describes the task:
### Input:
Match serializer by query arg.
### Response:
def _match_serializers_by_query_arg(self, serializers):
"""Match serializer by query arg."""
# if the format query argument is present, match the serializer
arg_name = current_app.c... |
def encode(number, alphabet):
"""
Converts an integer to a base n string where n is the length of the
provided alphabet.
Modified from http://en.wikipedia.org/wiki/Base_36
"""
if not isinstance(number, (int, long)):
raise TypeError("Number must be an integer.")
base_n = ""
sign... | Converts an integer to a base n string where n is the length of the
provided alphabet.
Modified from http://en.wikipedia.org/wiki/Base_36 | Below is the the instruction that describes the task:
### Input:
Converts an integer to a base n string where n is the length of the
provided alphabet.
Modified from http://en.wikipedia.org/wiki/Base_36
### Response:
def encode(number, alphabet):
"""
Converts an integer to a base n string where n ... |
def get_vm_config_file(name, datacenter, placement, datastore,
service_instance=None):
'''
Queries the virtual machine config file and returns
vim.host.DatastoreBrowser.SearchResults object on success None on failure
name
Name of the virtual machine
datacenter
... | Queries the virtual machine config file and returns
vim.host.DatastoreBrowser.SearchResults object on success None on failure
name
Name of the virtual machine
datacenter
Datacenter name
datastore
Datastore where the virtual machine files are stored
service_instance
... | Below is the the instruction that describes the task:
### Input:
Queries the virtual machine config file and returns
vim.host.DatastoreBrowser.SearchResults object on success None on failure
name
Name of the virtual machine
datacenter
Datacenter name
datastore
Datastore wh... |
def _get_context():
"""Determine the most specific context that we're in.
Returns:
_CONTEXT_COLAB: If in Colab with an IPython notebook context.
_CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook
context (e.g., from running `jupyter notebook` at the command
line).
_CONTEXT... | Determine the most specific context that we're in.
Returns:
_CONTEXT_COLAB: If in Colab with an IPython notebook context.
_CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook
context (e.g., from running `jupyter notebook` at the command
line).
_CONTEXT_NONE: Otherwise (e.g., b... | Below is the the instruction that describes the task:
### Input:
Determine the most specific context that we're in.
Returns:
_CONTEXT_COLAB: If in Colab with an IPython notebook context.
_CONTEXT_IPYTHON: If not in Colab, but we are in an IPython notebook
context (e.g., from running `jupyter notebo... |
def partial_transform(self, sequence, mode='clip'):
"""Transform a sequence to internal indexing
Recall that `sequence` can be arbitrary labels, whereas ``transmat_``
and ``countsmat_`` are indexed with integers between 0 and
``n_states - 1``. This methods maps a set of sequences from t... | Transform a sequence to internal indexing
Recall that `sequence` can be arbitrary labels, whereas ``transmat_``
and ``countsmat_`` are indexed with integers between 0 and
``n_states - 1``. This methods maps a set of sequences from the labels
onto this internal indexing.
Paramet... | Below is the the instruction that describes the task:
### Input:
Transform a sequence to internal indexing
Recall that `sequence` can be arbitrary labels, whereas ``transmat_``
and ``countsmat_`` are indexed with integers between 0 and
``n_states - 1``. This methods maps a set of sequences ... |
def blow_out(self, location=None):
"""
Force any remaining liquid to dispense, by moving
this pipette's plunger to the calibrated `blow_out` position
Notes
-----
If no `location` is passed, the pipette will blow_out
from it's current position.
Parameters... | Force any remaining liquid to dispense, by moving
this pipette's plunger to the calibrated `blow_out` position
Notes
-----
If no `location` is passed, the pipette will blow_out
from it's current position.
Parameters
----------
location : :any:`Placeable`... | Below is the the instruction that describes the task:
### Input:
Force any remaining liquid to dispense, by moving
this pipette's plunger to the calibrated `blow_out` position
Notes
-----
If no `location` is passed, the pipette will blow_out
from it's current position.
... |
async def auth_crypt(wallet_handle: int,
sender_vk: str,
recipient_vk: str,
msg: bytes) -> bytes:
"""
**** THIS FUNCTION WILL BE DEPRECATED USE pack_message INSTEAD ****
Encrypt a message by authenticated-encryption scheme.
Sender can encr... | **** THIS FUNCTION WILL BE DEPRECATED USE pack_message INSTEAD ****
Encrypt a message by authenticated-encryption scheme.
Sender can encrypt a confidential message specifically for Recipient, using Sender's public key.
Using Recipient's public key, Sender can compute a shared secret key.
Using Sender'... | Below is the the instruction that describes the task:
### Input:
**** THIS FUNCTION WILL BE DEPRECATED USE pack_message INSTEAD ****
Encrypt a message by authenticated-encryption scheme.
Sender can encrypt a confidential message specifically for Recipient, using Sender's public key.
Using Recipient's ... |
def submit(self, new_queue = None):
"""Sets the status of this job to 'submitted'."""
self.status = 'submitted'
self.result = None
self.machine_name = None
if new_queue is not None:
self.queue_name = new_queue
for array_job in self.array:
array_job.status = 'submitted'
array_jo... | Sets the status of this job to 'submitted'. | Below is the the instruction that describes the task:
### Input:
Sets the status of this job to 'submitted'.
### Response:
def submit(self, new_queue = None):
"""Sets the status of this job to 'submitted'."""
self.status = 'submitted'
self.result = None
self.machine_name = None
if new_queue is ... |
def _select_by_field_or_tag(self, tag=None, field=None):
"""For internal use only. Returns an OrderedDict of {identifier: field}
representing fields which match the supplied field/tag.
Parameters
----------
tag : str
Optionally specifies that the mask should only inc... | For internal use only. Returns an OrderedDict of {identifier: field}
representing fields which match the supplied field/tag.
Parameters
----------
tag : str
Optionally specifies that the mask should only include fields with
the specified tag.
field : str
... | Below is the the instruction that describes the task:
### Input:
For internal use only. Returns an OrderedDict of {identifier: field}
representing fields which match the supplied field/tag.
Parameters
----------
tag : str
Optionally specifies that the mask should only in... |
def make_temp(string, suffix='', decode=True, delete=True):
""" xmlsec needs files in some cases where only strings exist, hence the
need for this function. It creates a temporary file with the
string as only content.
:param string: The information to be placed in the file
:param suffix: The tempor... | xmlsec needs files in some cases where only strings exist, hence the
need for this function. It creates a temporary file with the
string as only content.
:param string: The information to be placed in the file
:param suffix: The temporary file might have to have a specific
suffix in certain cir... | Below is the the instruction that describes the task:
### Input:
xmlsec needs files in some cases where only strings exist, hence the
need for this function. It creates a temporary file with the
string as only content.
:param string: The information to be placed in the file
:param suffix: The tempo... |
def remove_profile(self):
"""Remove the current profile.
Make sure the user is sure.
"""
profile_name = self.profile_combo.currentText()
# noinspection PyTypeChecker
button_selected = QMessageBox.warning(
None,
'Remove Profile',
self.t... | Remove the current profile.
Make sure the user is sure. | Below is the the instruction that describes the task:
### Input:
Remove the current profile.
Make sure the user is sure.
### Response:
def remove_profile(self):
"""Remove the current profile.
Make sure the user is sure.
"""
profile_name = self.profile_combo.currentText()
... |
def render_roughpage(request, t):
"""
Internal interface to the rough page view.
"""
import django
if django.VERSION >= (1, 8):
c = {}
response = HttpResponse(t.render(c, request))
else:
c = RequestContext(request)
response = HttpResponse(t.render(c))
return r... | Internal interface to the rough page view. | Below is the the instruction that describes the task:
### Input:
Internal interface to the rough page view.
### Response:
def render_roughpage(request, t):
"""
Internal interface to the rough page view.
"""
import django
if django.VERSION >= (1, 8):
c = {}
response = HttpRespons... |
def layer_with(self, sample: np.ndarray, value: int) -> np.ndarray:
"""Create an identical 2d array where the second row is filled with value"""
b = np.full((2, len(sample)), value, dtype=float)
b[0] = sample
return b | Create an identical 2d array where the second row is filled with value | Below is the the instruction that describes the task:
### Input:
Create an identical 2d array where the second row is filled with value
### Response:
def layer_with(self, sample: np.ndarray, value: int) -> np.ndarray:
"""Create an identical 2d array where the second row is filled with value"""
b = ... |
def url(self):
"""
The URL present in this inline results. If you want to "click"
this URL to open it in your browser, you should use Python's
`webbrowser.open(url)` for such task.
"""
if isinstance(self.result, types.BotInlineResult):
return self.result.url | The URL present in this inline results. If you want to "click"
this URL to open it in your browser, you should use Python's
`webbrowser.open(url)` for such task. | Below is the the instruction that describes the task:
### Input:
The URL present in this inline results. If you want to "click"
this URL to open it in your browser, you should use Python's
`webbrowser.open(url)` for such task.
### Response:
def url(self):
"""
The URL present in this... |
def _combine_coverages(items, work_dir, input_backs=None):
"""Combine coverage cnns calculated for individual inputs into single file.
Optionally moves over pre-calculated coverage samples from a background file.
"""
out_file = os.path.join(work_dir, "sample_coverages.txt")
if not utils.file_exists... | Combine coverage cnns calculated for individual inputs into single file.
Optionally moves over pre-calculated coverage samples from a background file. | Below is the the instruction that describes the task:
### Input:
Combine coverage cnns calculated for individual inputs into single file.
Optionally moves over pre-calculated coverage samples from a background file.
### Response:
def _combine_coverages(items, work_dir, input_backs=None):
"""Combine covera... |
def extract_common_fields(self, data):
"""Extract fields from a metadata query."""
return dict(
dc=data.get('dc'),
role=data.get('role'),
account_name=data.get('accountname'),
user_id=data.get('user_id'),
login=data.get('login'),
lo... | Extract fields from a metadata query. | Below is the the instruction that describes the task:
### Input:
Extract fields from a metadata query.
### Response:
def extract_common_fields(self, data):
"""Extract fields from a metadata query."""
return dict(
dc=data.get('dc'),
role=data.get('role'),
account_... |
def set_contents_from_stream(self, fp, headers=None, replace=True,
cb=None, num_cb=10, policy=None,
reduced_redundancy=False, query_args=None, callback=None):
"""
Store an object using the name of the Key object as the key in
clou... | Store an object using the name of the Key object as the key in
cloud and the contents of the data stream pointed to by 'fp' as
the contents.
The stream object is not seekable and total size is not known.
This has the implication that we can't specify the Content-Size and
Content-... | Below is the the instruction that describes the task:
### Input:
Store an object using the name of the Key object as the key in
cloud and the contents of the data stream pointed to by 'fp' as
the contents.
The stream object is not seekable and total size is not known.
This has the im... |
def _normalize(self, name):
"""
Normalizes a legislator name by stripping titles from the front,
converting to lowercase and removing punctuation.
"""
name = re.sub(
r'^(Senator|Representative|Sen\.?|Rep\.?|'
'Hon\.?|Right Hon\.?|Mr\.?|Mrs\.?|Ms\.?|L\'hon\... | Normalizes a legislator name by stripping titles from the front,
converting to lowercase and removing punctuation. | Below is the the instruction that describes the task:
### Input:
Normalizes a legislator name by stripping titles from the front,
converting to lowercase and removing punctuation.
### Response:
def _normalize(self, name):
"""
Normalizes a legislator name by stripping titles from the front,
... |
def _getSimplePassage(self, reference=None):
""" Retrieve a single node representing the passage.
.. warning:: Range support is awkward.
:param reference: Identifier of the subreference / passages
:type reference: list, reference
:returns: Asked passage
:rtype: Capitain... | Retrieve a single node representing the passage.
.. warning:: Range support is awkward.
:param reference: Identifier of the subreference / passages
:type reference: list, reference
:returns: Asked passage
:rtype: CapitainsCtsPassage | Below is the the instruction that describes the task:
### Input:
Retrieve a single node representing the passage.
.. warning:: Range support is awkward.
:param reference: Identifier of the subreference / passages
:type reference: list, reference
:returns: Asked passage
:rty... |
def write_turbomole(basis):
'''Converts a basis set to Gaussian format
'''
s = '$basis\n'
s += '*\n'
# TM basis sets are completely uncontracted
basis = manip.uncontract_general(basis, True)
basis = manip.uncontract_spdf(basis, 0, False)
basis = sort.sort_basis(basis, False)
# Ele... | Converts a basis set to Gaussian format | Below is the the instruction that describes the task:
### Input:
Converts a basis set to Gaussian format
### Response:
def write_turbomole(basis):
'''Converts a basis set to Gaussian format
'''
s = '$basis\n'
s += '*\n'
# TM basis sets are completely uncontracted
basis = manip.uncontract_... |
def read(self,file):
"""Read DX field from file.
dx = OpenDX.field.read(dxfile)
The classid is discarded and replaced with the one from the file.
"""
DXfield = self
p = DXParser(file)
p.parse(DXfield) | Read DX field from file.
dx = OpenDX.field.read(dxfile)
The classid is discarded and replaced with the one from the file. | Below is the the instruction that describes the task:
### Input:
Read DX field from file.
dx = OpenDX.field.read(dxfile)
The classid is discarded and replaced with the one from the file.
### Response:
def read(self,file):
"""Read DX field from file.
dx = OpenDX.field.read... |
def add_rolling_statistics_variables(
df = None,
variable = None,
window = 20,
upper_factor = 2,
lower_factor = 2
):
"""
Add rolling statistics variables derived from a specified variable in a
DataFrame.
"""
df[variable + "_rolling_mean"] = p... | Add rolling statistics variables derived from a specified variable in a
DataFrame. | Below is the the instruction that describes the task:
### Input:
Add rolling statistics variables derived from a specified variable in a
DataFrame.
### Response:
def add_rolling_statistics_variables(
df = None,
variable = None,
window = 20,
upper_factor = 2,
lower_factor... |
def get_fail_graph(self, failure_index=None):
"""Returns a graph showing a solve failure.
Args:
failure_index: See `failure_reason`
Returns:
A pygraph.digraph object.
"""
phase, _ = self._get_failed_phase(failure_index)
return phase.get_graph() | Returns a graph showing a solve failure.
Args:
failure_index: See `failure_reason`
Returns:
A pygraph.digraph object. | Below is the the instruction that describes the task:
### Input:
Returns a graph showing a solve failure.
Args:
failure_index: See `failure_reason`
Returns:
A pygraph.digraph object.
### Response:
def get_fail_graph(self, failure_index=None):
"""Returns a graph sho... |
def generate_X_grid(self, term, n=100, meshgrid=False):
"""create a nice grid of X data
array is sorted by feature and uniformly spaced,
so the marginal and joint distributions are likely wrong
if term is >= 0, we generate n samples per feature,
which results in n^deg samples,
... | create a nice grid of X data
array is sorted by feature and uniformly spaced,
so the marginal and joint distributions are likely wrong
if term is >= 0, we generate n samples per feature,
which results in n^deg samples,
where deg is the degree of the interaction of the term
... | Below is the the instruction that describes the task:
### Input:
create a nice grid of X data
array is sorted by feature and uniformly spaced,
so the marginal and joint distributions are likely wrong
if term is >= 0, we generate n samples per feature,
which results in n^deg samples... |
def send_error_explain(self, code, message=None, headers=None, content_type=None):
"do not use directly"
if headers is None:
headers = {}
if code in self.responses:
if message is None:
message = self.responses[code][0]
explain = self.response... | do not use directly | Below is the the instruction that describes the task:
### Input:
do not use directly
### Response:
def send_error_explain(self, code, message=None, headers=None, content_type=None):
"do not use directly"
if headers is None:
headers = {}
if code in self.responses:
if... |
def get_or_create_head_node(config, config_file, no_restart, restart_only, yes,
override_cluster_name):
"""Create the cluster head node, which in turn creates the workers."""
provider = get_node_provider(config["provider"], config["cluster_name"])
try:
head_node_tags = {
... | Create the cluster head node, which in turn creates the workers. | Below is the the instruction that describes the task:
### Input:
Create the cluster head node, which in turn creates the workers.
### Response:
def get_or_create_head_node(config, config_file, no_restart, restart_only, yes,
override_cluster_name):
"""Create the cluster head node, wh... |
def subvol_delete(self, path):
"""
Delete a btrfs subvolume in the specified path
:param path: path to delete
"""
args = {
'path': path
}
self._subvol_chk.check(args)
self._client.sync('btrfs.subvol_delete', args) | Delete a btrfs subvolume in the specified path
:param path: path to delete | Below is the the instruction that describes the task:
### Input:
Delete a btrfs subvolume in the specified path
:param path: path to delete
### Response:
def subvol_delete(self, path):
"""
Delete a btrfs subvolume in the specified path
:param path: path to delete
"""
... |
def _make_writeable(filename):
"""
Make sure that the file is writeable. Useful if our source is
read-only.
"""
import stat
if sys.platform.startswith('java'):
# On Jython there is no os.access()
return
if not os.access(filename, os.W_OK):
st = os.stat(filename)
... | Make sure that the file is writeable. Useful if our source is
read-only. | Below is the the instruction that describes the task:
### Input:
Make sure that the file is writeable. Useful if our source is
read-only.
### Response:
def _make_writeable(filename):
"""
Make sure that the file is writeable. Useful if our source is
read-only.
"""
import stat
if sys.plat... |
def hooked_by(self, addr):
"""
Returns the current hook for `addr`.
:param addr: An address.
:returns: None if the address is not hooked.
"""
if not self.is_hooked(addr):
l.warning("Address %s is not hooked", self._addr_to_str(addr))
return N... | Returns the current hook for `addr`.
:param addr: An address.
:returns: None if the address is not hooked. | Below is the the instruction that describes the task:
### Input:
Returns the current hook for `addr`.
:param addr: An address.
:returns: None if the address is not hooked.
### Response:
def hooked_by(self, addr):
"""
Returns the current hook for `addr`.
:param addr: An... |
def image_coordinates(self, point):
'''given a point in window coordinates, calculate image coordinates'''
# the dragpos is the top left position in image coordinates
ret = wx.Point(int(self.dragpos.x + point.x/self.zoom),
int(self.dragpos.y + point.y/self.zoom))
r... | given a point in window coordinates, calculate image coordinates | Below is the the instruction that describes the task:
### Input:
given a point in window coordinates, calculate image coordinates
### Response:
def image_coordinates(self, point):
'''given a point in window coordinates, calculate image coordinates'''
# the dragpos is the top left position in image ... |
def extend_dict_key_value(
in_dict,
keys,
value,
delimiter=DEFAULT_TARGET_DELIM,
ordered_dict=False):
'''
Ensures that in_dict contains the series of recursive keys defined in keys.
Also extends the list, that is at the end of `in_dict` traversed with `keys`,
with... | Ensures that in_dict contains the series of recursive keys defined in keys.
Also extends the list, that is at the end of `in_dict` traversed with `keys`,
with `value`.
:param dict in_dict: The dictionary to work with
:param str keys: The delimited string with one or more keys.
:param any value: The... | Below is the the instruction that describes the task:
### Input:
Ensures that in_dict contains the series of recursive keys defined in keys.
Also extends the list, that is at the end of `in_dict` traversed with `keys`,
with `value`.
:param dict in_dict: The dictionary to work with
:param str keys: ... |
def upload_file(path, destination_frame=None, header=0, sep=None, col_names=None, col_types=None,
na_strings=None, skipped_columns=None):
"""
Upload a dataset from the provided local path to the H2O cluster.
Does a single-threaded push to H2O. Also see :meth:`import_file`.
:param path:... | Upload a dataset from the provided local path to the H2O cluster.
Does a single-threaded push to H2O. Also see :meth:`import_file`.
:param path: A path specifying the location of the data to upload.
:param destination_frame: The unique hex key assigned to the imported file. If none is given, a key will
... | Below is the the instruction that describes the task:
### Input:
Upload a dataset from the provided local path to the H2O cluster.
Does a single-threaded push to H2O. Also see :meth:`import_file`.
:param path: A path specifying the location of the data to upload.
:param destination_frame: The unique ... |
def _register_live_trades_channels(self):
"""
Registers the binding for the live_trades_channels channels.
:return:
"""
channels = {'live_trades': self.btcusd_lt_callback,
'live_trades_btceur': self.btceur_lt_callback,
'live_trades_eurusd'... | Registers the binding for the live_trades_channels channels.
:return: | Below is the the instruction that describes the task:
### Input:
Registers the binding for the live_trades_channels channels.
:return:
### Response:
def _register_live_trades_channels(self):
"""
Registers the binding for the live_trades_channels channels.
:return:
"""
... |
def get_endpoint_obj(client, endpoint, object_id):
''' Tiny helper function that gets used all over the place to join the object ID to the endpoint and run a GET request, returning the result '''
endpoint = '/'.join([endpoint, str(object_id)])
return client.authenticated_request(endpoint).json() | Tiny helper function that gets used all over the place to join the object ID to the endpoint and run a GET request, returning the result | Below is the the instruction that describes the task:
### Input:
Tiny helper function that gets used all over the place to join the object ID to the endpoint and run a GET request, returning the result
### Response:
def get_endpoint_obj(client, endpoint, object_id):
''' Tiny helper function that gets used all ... |
def scan_config_path(cls, project, scan_config):
"""Return a fully-qualified scan_config string."""
return google.api_core.path_template.expand(
"projects/{project}/scanConfigs/{scan_config}",
project=project,
scan_config=scan_config,
) | Return a fully-qualified scan_config string. | Below is the the instruction that describes the task:
### Input:
Return a fully-qualified scan_config string.
### Response:
def scan_config_path(cls, project, scan_config):
"""Return a fully-qualified scan_config string."""
return google.api_core.path_template.expand(
"projects/{project... |
def user_follows(uid, offset='0', limit=30):
"""获取用户关注列表
:param uid: 用户的ID,可通过登录或者其他接口获取
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 30
"""
if uid is None:
raise ParamsError()
r = NCloudBot()
r.method = 'USER_FOLLOWS'
r.params = {'uid': uid}
... | 获取用户关注列表
:param uid: 用户的ID,可通过登录或者其他接口获取
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 30 | Below is the the instruction that describes the task:
### Input:
获取用户关注列表
:param uid: 用户的ID,可通过登录或者其他接口获取
:param offset: (optional) 分段起始位置,默认 0
:param limit: (optional) 数据上限多少行,默认 30
### Response:
def user_follows(uid, offset='0', limit=30):
"""获取用户关注列表
:param uid: 用户的ID,可通过登录或者其他接口获取
:pa... |
def _get_ATOM_sequences(self):
'''Creates the ATOM Sequences.'''
# Get a list of all residues with ATOM or HETATM records
atom_sequences = {}
structural_residue_IDs_set = set() # use a set for a quicker lookup
ignore_HETATMs = True # todo: fix this if we need to deal with HETATM... | Creates the ATOM Sequences. | Below is the the instruction that describes the task:
### Input:
Creates the ATOM Sequences.
### Response:
def _get_ATOM_sequences(self):
'''Creates the ATOM Sequences.'''
# Get a list of all residues with ATOM or HETATM records
atom_sequences = {}
structural_residue_IDs_set = set(... |
def new_from_list(cls, content, fill_title=True, **kwargs):
"""Populates the Table with a list of tuples of strings.
Args:
content (list): list of tuples of strings. Each tuple is a row.
fill_title (bool): if true, the first tuple in the list will
be set as title... | Populates the Table with a list of tuples of strings.
Args:
content (list): list of tuples of strings. Each tuple is a row.
fill_title (bool): if true, the first tuple in the list will
be set as title | Below is the the instruction that describes the task:
### Input:
Populates the Table with a list of tuples of strings.
Args:
content (list): list of tuples of strings. Each tuple is a row.
fill_title (bool): if true, the first tuple in the list will
be set as title
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.