code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def encode_produce_request(cls, client_id, correlation_id,
payloads=None, acks=1, timeout=1000):
"""
Encode some ProduceRequest structs
Arguments:
client_id: string
correlation_id: int
payloads: list of ProduceRequest
... | Encode some ProduceRequest structs
Arguments:
client_id: string
correlation_id: int
payloads: list of ProduceRequest
acks: How "acky" you want the request to be
0: immediate response
1: written to disk by the leader
... | Below is the the instruction that describes the task:
### Input:
Encode some ProduceRequest structs
Arguments:
client_id: string
correlation_id: int
payloads: list of ProduceRequest
acks: How "acky" you want the request to be
0: immediate resp... |
def disconnect_all(self, message=""):
"""Disconnects all connections."""
with self.mutex:
for conn in self.connections:
conn.disconnect(message) | Disconnects all connections. | Below is the the instruction that describes the task:
### Input:
Disconnects all connections.
### Response:
def disconnect_all(self, message=""):
"""Disconnects all connections."""
with self.mutex:
for conn in self.connections:
conn.disconnect(message) |
def changememokey(ctx, key, account):
""" Change the memo key of an account
"""
pprint(ctx.blockchain.update_memo_key(key, account=account)) | Change the memo key of an account | Below is the the instruction that describes the task:
### Input:
Change the memo key of an account
### Response:
def changememokey(ctx, key, account):
""" Change the memo key of an account
"""
pprint(ctx.blockchain.update_memo_key(key, account=account)) |
def _validate_fname(fname, arg_name):
"""Validate that a string is a valid file name."""
if fname is not None:
msg = "Argument `{0}` is not valid".format(arg_name)
if (not isinstance(fname, str)) or (isinstance(fname, str) and ("\0" in fname)):
raise RuntimeError(msg)
try:
... | Validate that a string is a valid file name. | Below is the the instruction that describes the task:
### Input:
Validate that a string is a valid file name.
### Response:
def _validate_fname(fname, arg_name):
"""Validate that a string is a valid file name."""
if fname is not None:
msg = "Argument `{0}` is not valid".format(arg_name)
if ... |
def query(self, req, timeout=None, metadata=None, credentials=None):
"""Runs query operation."""
return self.stub.Query(req, timeout=timeout, metadata=metadata,
credentials=credentials) | Runs query operation. | Below is the the instruction that describes the task:
### Input:
Runs query operation.
### Response:
def query(self, req, timeout=None, metadata=None, credentials=None):
"""Runs query operation."""
return self.stub.Query(req, timeout=timeout, metadata=metadata,
creden... |
def load_ui_from_file(name: str):
"""
Returns a tuple from uic.loadUiType(), loading the ui file with the given name.
:param name:
:return:
"""
ui_file = _get_ui_qfile(name)
try:
base_type = uic.loadUiType(ui_file, from_imports=True)
finally:
ui_file.close()
return ba... | Returns a tuple from uic.loadUiType(), loading the ui file with the given name.
:param name:
:return: | Below is the the instruction that describes the task:
### Input:
Returns a tuple from uic.loadUiType(), loading the ui file with the given name.
:param name:
:return:
### Response:
def load_ui_from_file(name: str):
"""
Returns a tuple from uic.loadUiType(), loading the ui file with the given name.
... |
def set_source(self, propname, pores):
r"""
Applies a given source term to the specified pores
Parameters
----------
propname : string
The property name of the source term model to be applied
pores : array_like
The pore indices where the source t... | r"""
Applies a given source term to the specified pores
Parameters
----------
propname : string
The property name of the source term model to be applied
pores : array_like
The pore indices where the source term should be applied
Notes
--... | Below is the the instruction that describes the task:
### Input:
r"""
Applies a given source term to the specified pores
Parameters
----------
propname : string
The property name of the source term model to be applied
pores : array_like
The pore indi... |
def get_focus_widget_properties(self):
"""Get properties of focus widget
Returns tuple (widget, properties) where properties is a tuple of
booleans: (is_console, not_readonly, readwrite_editor)"""
from spyder.plugins.editor.widgets.editor import TextEditBaseWidget
from spyde... | Get properties of focus widget
Returns tuple (widget, properties) where properties is a tuple of
booleans: (is_console, not_readonly, readwrite_editor) | Below is the the instruction that describes the task:
### Input:
Get properties of focus widget
Returns tuple (widget, properties) where properties is a tuple of
booleans: (is_console, not_readonly, readwrite_editor)
### Response:
def get_focus_widget_properties(self):
"""Get properties ... |
def settle(ctx, symbol, amount, account):
""" Fund the fee pool of an asset
"""
print_tx(ctx.bitshares.asset_settle(Amount(amount, symbol), account=account)) | Fund the fee pool of an asset | Below is the the instruction that describes the task:
### Input:
Fund the fee pool of an asset
### Response:
def settle(ctx, symbol, amount, account):
""" Fund the fee pool of an asset
"""
print_tx(ctx.bitshares.asset_settle(Amount(amount, symbol), account=account)) |
def register_frame(self, frame):
"""
Register the Frame that owns this Widget.
:param frame: The owning Frame.
"""
self._frame = frame
self.string_len = wcswidth if self._frame.canvas.unicode_aware else len | Register the Frame that owns this Widget.
:param frame: The owning Frame. | Below is the the instruction that describes the task:
### Input:
Register the Frame that owns this Widget.
:param frame: The owning Frame.
### Response:
def register_frame(self, frame):
"""
Register the Frame that owns this Widget.
:param frame: The owning Frame.
"""
... |
def matches(self, string, context=None):
"""
Search for all matches with current configuration against input_string
:param string: string to search into
:type string: str
:param context: context to use
:type context: dict
:return: A custom list of matches
... | Search for all matches with current configuration against input_string
:param string: string to search into
:type string: str
:param context: context to use
:type context: dict
:return: A custom list of matches
:rtype: Matches | Below is the the instruction that describes the task:
### Input:
Search for all matches with current configuration against input_string
:param string: string to search into
:type string: str
:param context: context to use
:type context: dict
:return: A custom list of matches
... |
def _build_model(self, traj, brian_list, network_dict):
"""Builds the neuron groups from `traj`.
Adds the neuron groups to `brian_list` and `network_dict`.
"""
model = traj.parameters.model
# Create the equations for both models
eqs_dict = self._build_model_eqs(traj)
... | Builds the neuron groups from `traj`.
Adds the neuron groups to `brian_list` and `network_dict`. | Below is the the instruction that describes the task:
### Input:
Builds the neuron groups from `traj`.
Adds the neuron groups to `brian_list` and `network_dict`.
### Response:
def _build_model(self, traj, brian_list, network_dict):
"""Builds the neuron groups from `traj`.
Adds the neuron ... |
def contains(self, times, keep_inside=True, delta_t=DEFAULT_OBSERVATION_TIME):
"""
Get a mask array (e.g. a numpy boolean array) of times being inside (or outside) the
TMOC instance.
Parameters
----------
times : `astropy.time.Time`
astropy times to check whe... | Get a mask array (e.g. a numpy boolean array) of times being inside (or outside) the
TMOC instance.
Parameters
----------
times : `astropy.time.Time`
astropy times to check whether they are contained in the TMOC or not.
keep_inside : bool, optional
True b... | Below is the the instruction that describes the task:
### Input:
Get a mask array (e.g. a numpy boolean array) of times being inside (or outside) the
TMOC instance.
Parameters
----------
times : `astropy.time.Time`
astropy times to check whether they are contained in the... |
def tuple(data, field_name):
"""
RETURN LIST OF TUPLES
"""
if isinstance(data, Cube):
Log.error("not supported yet")
if isinstance(data, FlatList):
Log.error("not supported yet")
if is_data(field_name) and "value" in field_name:
# SIMPLIFY {"value":value} AS STRING
... | RETURN LIST OF TUPLES | Below is the the instruction that describes the task:
### Input:
RETURN LIST OF TUPLES
### Response:
def tuple(data, field_name):
"""
RETURN LIST OF TUPLES
"""
if isinstance(data, Cube):
Log.error("not supported yet")
if isinstance(data, FlatList):
Log.error("not supported ye... |
def _main_loop(self):
'''
Main loop for the stats collector
'''
while self.active:
self.expire()
if self.roll and self.is_expired():
self.start_time = self.start_time + self.window
self._set_key()
self.purge_old()
... | Main loop for the stats collector | Below is the the instruction that describes the task:
### Input:
Main loop for the stats collector
### Response:
def _main_loop(self):
'''
Main loop for the stats collector
'''
while self.active:
self.expire()
if self.roll and self.is_expired():
... |
def fling_forward_horizontally(self, *args, **selectors):
"""
Perform fling forward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be fling or not.
"""
return self.device(**selectors).fling.horiz.forward() | Perform fling forward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be fling or not. | Below is the the instruction that describes the task:
### Input:
Perform fling forward (horizontally)action on the object which has *selectors* attributes.
Return whether the object can be fling or not.
### Response:
def fling_forward_horizontally(self, *args, **selectors):
"""
Perform fli... |
def forebrain():
"""Developing human forebrain.
Forebrain tissue of a week 10 embryo, focusing on the glutamatergic neuronal lineage.
Returns
-------
Returns `adata` object
"""
filename = 'data/ForebrainGlut/hgForebrainGlut.loom'
url = 'http://pklab.med.harvard.edu/velocyto/hgForebrainG... | Developing human forebrain.
Forebrain tissue of a week 10 embryo, focusing on the glutamatergic neuronal lineage.
Returns
-------
Returns `adata` object | Below is the the instruction that describes the task:
### Input:
Developing human forebrain.
Forebrain tissue of a week 10 embryo, focusing on the glutamatergic neuronal lineage.
Returns
-------
Returns `adata` object
### Response:
def forebrain():
"""Developing human forebrain.
Forebrain ... |
def _build(self, args):
'''
Build a package
'''
if len(args) < 2:
raise SPMInvocationError('A path to a formula must be specified')
self.abspath = args[1].rstrip('/')
comps = self.abspath.split('/')
self.relpath = comps[-1]
formula_path = '{0... | Build a package | Below is the the instruction that describes the task:
### Input:
Build a package
### Response:
def _build(self, args):
'''
Build a package
'''
if len(args) < 2:
raise SPMInvocationError('A path to a formula must be specified')
self.abspath = args[1].rstrip('/')
... |
def start(self):
"""Start transmitting message (add to list if needed)."""
if self._index is None:
self._index = ctypes.c_uint32()
_canlib.canSchedulerAddMessage(self._scheduler,
self._msg,
self... | Start transmitting message (add to list if needed). | Below is the the instruction that describes the task:
### Input:
Start transmitting message (add to list if needed).
### Response:
def start(self):
"""Start transmitting message (add to list if needed)."""
if self._index is None:
self._index = ctypes.c_uint32()
_canlib.canSc... |
def page_for(self, member, page_size=DEFAULT_PAGE_SIZE):
'''
Determine the page where a member falls in the leaderboard.
@param member [String] Member name.
@param page_size [int] Page size to be used in determining page location.
@return the page where a member falls in the lea... | Determine the page where a member falls in the leaderboard.
@param member [String] Member name.
@param page_size [int] Page size to be used in determining page location.
@return the page where a member falls in the leaderboard. | Below is the the instruction that describes the task:
### Input:
Determine the page where a member falls in the leaderboard.
@param member [String] Member name.
@param page_size [int] Page size to be used in determining page location.
@return the page where a member falls in the leaderboard... |
def decompose(
val: TValue,
*,
intercepting_decomposer: Callable[['cirq.Operation'],
Union[None,
NotImplementedType,
'cirq.OP_TREE']] = None,
fallback_decomposer: Callable[['cirq... | Recursively decomposes a value into `cirq.Operation`s meeting a criteria.
Args:
val: The value to decompose into operations.
intercepting_decomposer: An optional method that is called before the
default decomposer (the value's `_decompose_` method). If
`intercepting_decompos... | Below is the the instruction that describes the task:
### Input:
Recursively decomposes a value into `cirq.Operation`s meeting a criteria.
Args:
val: The value to decompose into operations.
intercepting_decomposer: An optional method that is called before the
default decomposer (the... |
def _convert_to_folder(self, packages):
"""
Silverstripe's page contains a list of composer packages. This
function converts those to folder names. These may be different due
to installer-name.
Implemented exponential backoff in order to prevent packager from
... | Silverstripe's page contains a list of composer packages. This
function converts those to folder names. These may be different due
to installer-name.
Implemented exponential backoff in order to prevent packager from
being overly sensitive about the number of requests I w... | Below is the the instruction that describes the task:
### Input:
Silverstripe's page contains a list of composer packages. This
function converts those to folder names. These may be different due
to installer-name.
Implemented exponential backoff in order to prevent packager fro... |
def msgconvert(email):
"""
Exec msgconvert tool, to convert msg Outlook
mail in eml mail format
Args:
email (string): file path of Outlook msg mail
Returns:
tuple with file path of mail converted and
standard output data (unicode Python 2, str Python 3)
"""
log.debu... | Exec msgconvert tool, to convert msg Outlook
mail in eml mail format
Args:
email (string): file path of Outlook msg mail
Returns:
tuple with file path of mail converted and
standard output data (unicode Python 2, str Python 3) | Below is the the instruction that describes the task:
### Input:
Exec msgconvert tool, to convert msg Outlook
mail in eml mail format
Args:
email (string): file path of Outlook msg mail
Returns:
tuple with file path of mail converted and
standard output data (unicode Python 2, ... |
def _parse_attr(self, attr_proto):
"""Convert a list of AttributeProto to a dict, with names as keys."""
attrs = {}
for a in attr_proto:
for f in ['f', 'i', 's']:
if a.HasField(f):
attrs[a.name] = getattr(a, f)
for f in ['floats', 'ints... | Convert a list of AttributeProto to a dict, with names as keys. | Below is the the instruction that describes the task:
### Input:
Convert a list of AttributeProto to a dict, with names as keys.
### Response:
def _parse_attr(self, attr_proto):
"""Convert a list of AttributeProto to a dict, with names as keys."""
attrs = {}
for a in attr_proto:
... |
def get_urls(self):
"""
Add the entries view to urls.
"""
urls = super(FormAdmin, self).get_urls()
extra_urls = [
re_path("^(?P<form_id>\d+)/entries/$",
self.admin_site.admin_view(self.entries_view),
name="form_entries"),
re... | Add the entries view to urls. | Below is the the instruction that describes the task:
### Input:
Add the entries view to urls.
### Response:
def get_urls(self):
"""
Add the entries view to urls.
"""
urls = super(FormAdmin, self).get_urls()
extra_urls = [
re_path("^(?P<form_id>\d+)/entries/$",
... |
def velocity_genes(data, vkey='velocity', min_r2=0.01, highly_variable=None, copy=False):
"""Estimates velocities in a gene-specific manner
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name under which to refer to the... | Estimates velocities in a gene-specific manner
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name under which to refer to the computed velocities for `velocity_graph` and `velocity_embedding`.
min_r2: `float` (default:... | Below is the the instruction that describes the task:
### Input:
Estimates velocities in a gene-specific manner
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name under which to refer to the computed velocities for `ve... |
def pprint_value_string(self, value):
"""Pretty print the dimension value and unit.
Args:
value: Dimension value to format
Returns:
Formatted dimension value string with unit
"""
unit = '' if self.unit is None else ' ' + bytes_to_unicode(self.unit)
... | Pretty print the dimension value and unit.
Args:
value: Dimension value to format
Returns:
Formatted dimension value string with unit | Below is the the instruction that describes the task:
### Input:
Pretty print the dimension value and unit.
Args:
value: Dimension value to format
Returns:
Formatted dimension value string with unit
### Response:
def pprint_value_string(self, value):
"""Pretty prin... |
def use(backend):
"""Use the given database backend, e.g. 'MySQLdb', 'psycopg2',
'MySQLdb', etc.
"""
global Backend
try:
Backend = importlib.import_module(backend)
except ImportError:
msg = 'Could not import (load) database.backend: %s' % backend
raise cfg.AitConfigError... | Use the given database backend, e.g. 'MySQLdb', 'psycopg2',
'MySQLdb', etc. | Below is the the instruction that describes the task:
### Input:
Use the given database backend, e.g. 'MySQLdb', 'psycopg2',
'MySQLdb', etc.
### Response:
def use(backend):
"""Use the given database backend, e.g. 'MySQLdb', 'psycopg2',
'MySQLdb', etc.
"""
global Backend
try:
Backen... |
def configurar_interface_de_rede(self, configuracao):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
"""
resp = self._http_post('configurarinterfacederede',
co... | Sobrepõe :meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT | Below is the the instruction that describes the task:
### Input:
Sobrepõe :meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
### Response:
def configurar_interface_de_rede(self, configuracao):
"""Sobrep... |
def identity(self, surface):
"""
Fast scale operation that does not sample the results
"""
return self._pygame.transform.scale(surface, self._output_size) | Fast scale operation that does not sample the results | Below is the the instruction that describes the task:
### Input:
Fast scale operation that does not sample the results
### Response:
def identity(self, surface):
"""
Fast scale operation that does not sample the results
"""
return self._pygame.transform.scale(surface, self._output_s... |
def inputhook_glut():
"""Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
... | Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
though for best performance. | Below is the the instruction that describes the task:
### Input:
Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 10... |
def flatten_rules(self, declarations):
"""
Flatten returned import rules from regex.
Because import rules can contains multiple items in the same rule
(called multiline import rule), the regex ``REGEX_IMPORT_RULE``
return a list of unquoted items for each rule.
Args:
... | Flatten returned import rules from regex.
Because import rules can contains multiple items in the same rule
(called multiline import rule), the regex ``REGEX_IMPORT_RULE``
return a list of unquoted items for each rule.
Args:
declarations (list): A SCSS source.
Retu... | Below is the the instruction that describes the task:
### Input:
Flatten returned import rules from regex.
Because import rules can contains multiple items in the same rule
(called multiline import rule), the regex ``REGEX_IMPORT_RULE``
return a list of unquoted items for each rule.
... |
def get_curve_name_by_oid(oid):
"""Return curve name matching specified OID, or raise KeyError."""
for curve_name, info in SUPPORTED_CURVES.items():
if info['oid'] == oid:
return curve_name
raise KeyError('Unknown OID: {!r}'.format(oid)) | Return curve name matching specified OID, or raise KeyError. | Below is the the instruction that describes the task:
### Input:
Return curve name matching specified OID, or raise KeyError.
### Response:
def get_curve_name_by_oid(oid):
"""Return curve name matching specified OID, or raise KeyError."""
for curve_name, info in SUPPORTED_CURVES.items():
if info['o... |
def accented_syllable_to_numbered(s):
"""Convert accented Pinyin syllable *s* to a numbered Pinyin syllable."""
if s[0] == '\u00B7':
lowercase_syllable, case_memory = _lower_case(s[1:])
lowercase_syllable = '\u00B7' + lowercase_syllable
else:
lowercase_syllable, case_memory = _lower_... | Convert accented Pinyin syllable *s* to a numbered Pinyin syllable. | Below is the the instruction that describes the task:
### Input:
Convert accented Pinyin syllable *s* to a numbered Pinyin syllable.
### Response:
def accented_syllable_to_numbered(s):
"""Convert accented Pinyin syllable *s* to a numbered Pinyin syllable."""
if s[0] == '\u00B7':
lowercase_syllable,... |
async def packet_receiver(queue):
""" Asynchronous function that processes queue until None is posted in queue """
LOG.info("Entering packet_receiver")
while True:
packet = await queue.get()
if packet is None:
break
LOG.info("Framenumber %s", packet.framenumber)
LOG.... | Asynchronous function that processes queue until None is posted in queue | Below is the the instruction that describes the task:
### Input:
Asynchronous function that processes queue until None is posted in queue
### Response:
async def packet_receiver(queue):
""" Asynchronous function that processes queue until None is posted in queue """
LOG.info("Entering packet_receiver")
... |
def split_sources(srcs):
"""
:param srcs: sources
:returns: a pair (split sources, split time) or just the split_sources
"""
from openquake.hazardlib.source import splittable
sources = []
split_time = {} # src.id -> time
for src in srcs:
t0 = time.time()
mag_a, mag_b = s... | :param srcs: sources
:returns: a pair (split sources, split time) or just the split_sources | Below is the the instruction that describes the task:
### Input:
:param srcs: sources
:returns: a pair (split sources, split time) or just the split_sources
### Response:
def split_sources(srcs):
"""
:param srcs: sources
:returns: a pair (split sources, split time) or just the split_sources
"""... |
async def export_chat_invite_link(self, chat_id: typing.Union[base.Integer, base.String]) -> base.String:
"""
Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the approp... | Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegram.org/bots/api#exportchatinvitelink
:param chat_id: Unique i... | Below is the the instruction that describes the task:
### Input:
Use this method to generate a new invite link for a chat; any previously generated link is revoked.
The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
Source: https://core.telegra... |
def __convert_node(node, default_value='', default_flags=vsflags()):
"""Converts a XML node to a JSON equivalent."""
name = __get_attribute(node, 'Name')
logging.debug('Found %s named %s', node.tagName, name)
converted = {}
converted['name'] = name
converted['switch'] = __get_attribute(node, 'S... | Converts a XML node to a JSON equivalent. | Below is the the instruction that describes the task:
### Input:
Converts a XML node to a JSON equivalent.
### Response:
def __convert_node(node, default_value='', default_flags=vsflags()):
"""Converts a XML node to a JSON equivalent."""
name = __get_attribute(node, 'Name')
logging.debug('Found %s name... |
def describe_ip(ip_address, source='whatismyip'):
''' a method to get the details associated with an ip address '''
# determine url
if source == 'nekudo':
source_url = 'https://geoip.nekudo.com/api/%s' % ip_address
elif source == 'geoip':
source_url = 'https://freegeoip.net/json/%s' % ... | a method to get the details associated with an ip address | Below is the the instruction that describes the task:
### Input:
a method to get the details associated with an ip address
### Response:
def describe_ip(ip_address, source='whatismyip'):
''' a method to get the details associated with an ip address '''
# determine url
if source == 'nekudo':
s... |
def predict(self, X):
r"""Predict labels.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted labels of given feature vector.
... | r"""Predict labels.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted labels of given feature vector. | Below is the the instruction that describes the task:
### Input:
r"""Predict labels.
Parameters
----------
X : array-like, shape=(n_samples, n_features)
Feature vector.
Returns
-------
pred : numpy array, shape=(n_samples, n_labels)
Predicted... |
def set_state(self, onoff, channel=None):
"""Turn state on/off"""
try:
onoff = bool(onoff)
except Exception as err:
LOG.debug("HelperActorState.set_state: Exception %s" % (err,))
return False
self.writeNodeData("STATE", onoff, channel) | Turn state on/off | Below is the the instruction that describes the task:
### Input:
Turn state on/off
### Response:
def set_state(self, onoff, channel=None):
"""Turn state on/off"""
try:
onoff = bool(onoff)
except Exception as err:
LOG.debug("HelperActorState.set_state: Exception %s" %... |
def verify_jwt_in_request():
"""
Ensure that the requester has a valid access token. This does not check the
freshness of the access token. Raises an appropiate exception there is
no token or if the token is invalid.
"""
if request.method not in config.exempt_methods:
jwt_data = _decode_... | Ensure that the requester has a valid access token. This does not check the
freshness of the access token. Raises an appropiate exception there is
no token or if the token is invalid. | Below is the the instruction that describes the task:
### Input:
Ensure that the requester has a valid access token. This does not check the
freshness of the access token. Raises an appropiate exception there is
no token or if the token is invalid.
### Response:
def verify_jwt_in_request():
"""
Ens... |
def to_next_pedalboard(self):
"""
Change the current :class:`.Pedalboard` for the next pedalboard.
If the current pedalboard is the last in the current :class:`.Bank`,
the current pedalboard is will be the **first of the current Bank**
.. warning::
If the current :... | Change the current :class:`.Pedalboard` for the next pedalboard.
If the current pedalboard is the last in the current :class:`.Bank`,
the current pedalboard is will be the **first of the current Bank**
.. warning::
If the current :attr:`.pedalboard` is ``None``, a :class:`.Current... | Below is the the instruction that describes the task:
### Input:
Change the current :class:`.Pedalboard` for the next pedalboard.
If the current pedalboard is the last in the current :class:`.Bank`,
the current pedalboard is will be the **first of the current Bank**
.. warning::
... |
def pointOnCircle(cx, cy, radius, angle):
"""
Calculates the coordinates of a point on a circle given the center point,
radius, and angle.
"""
angle = math.radians(angle) - (math.pi / 2)
x = cx + radius * math.cos(angle)
if x < cx:
x = math.ceil(x)
else:
x = math.floor(x)... | Calculates the coordinates of a point on a circle given the center point,
radius, and angle. | Below is the the instruction that describes the task:
### Input:
Calculates the coordinates of a point on a circle given the center point,
radius, and angle.
### Response:
def pointOnCircle(cx, cy, radius, angle):
"""
Calculates the coordinates of a point on a circle given the center point,
radius,... |
def check_dataset(self, dataset_id, project_id=None):
"""Check to see if a dataset exists.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
-------
bool
... | Check to see if a dataset exists.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
-------
bool
True if dataset at `dataset_id` exists, else Fasle | Below is the the instruction that describes the task:
### Input:
Check to see if a dataset exists.
Parameters
----------
dataset_id : str
Dataset unique id
project_id: str, optional
The project the dataset is in
Returns
-------
bool
... |
def read(self, request, pk=None):
"""
Mark the message as read (i.e. delete from inbox)
"""
from .settings import stored_messages_settings
backend = stored_messages_settings.STORAGE_BACKEND()
try:
backend.inbox_delete(request.user, pk)
except MessageD... | Mark the message as read (i.e. delete from inbox) | Below is the the instruction that describes the task:
### Input:
Mark the message as read (i.e. delete from inbox)
### Response:
def read(self, request, pk=None):
"""
Mark the message as read (i.e. delete from inbox)
"""
from .settings import stored_messages_settings
backend... |
def _maybe_call_volatility_fn_and_grads(volatility_fn,
state,
volatility_fn_results=None,
grads_volatility_fn=None,
sample_shape=None,
... | Helper which computes `volatility_fn` results and grads, if needed. | Below is the the instruction that describes the task:
### Input:
Helper which computes `volatility_fn` results and grads, if needed.
### Response:
def _maybe_call_volatility_fn_and_grads(volatility_fn,
state,
volatility_fn_results=None... |
def reset(self):
"""" Reset the state as new """
self.last_usage = None
self.last_collect = None
self.last_metrics = None
self.snapshot_countdown = 0
self.run() | Reset the state as new | Below is the the instruction that describes the task:
### Input:
Reset the state as new
### Response:
def reset(self):
"""" Reset the state as new """
self.last_usage = None
self.last_collect = None
self.last_metrics = None
self.snapshot_countdown = 0
self.run() |
def combine_reports(original, new):
"""Combines two gcov reports for a file into one by adding the number of hits on each line
"""
if original is None:
return new
report = {}
report['name'] = original['name']
report['source_digest'] = original['source_digest']
coverage = []
for o... | Combines two gcov reports for a file into one by adding the number of hits on each line | Below is the the instruction that describes the task:
### Input:
Combines two gcov reports for a file into one by adding the number of hits on each line
### Response:
def combine_reports(original, new):
"""Combines two gcov reports for a file into one by adding the number of hits on each line
"""
if or... |
def reply(cls, name, *args, **kwargs):
"""Helper method for creating reply messages.
Parameters
----------
name : str
The name of the message.
args : list of strings
The message arguments.
Keyword Arguments
-----------------
mid :... | Helper method for creating reply messages.
Parameters
----------
name : str
The name of the message.
args : list of strings
The message arguments.
Keyword Arguments
-----------------
mid : str or None
Message ID to use or None... | Below is the the instruction that describes the task:
### Input:
Helper method for creating reply messages.
Parameters
----------
name : str
The name of the message.
args : list of strings
The message arguments.
Keyword Arguments
------------... |
def loads(s, **kwargs):
"""
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
"""
if not isinstance(s, string_type):
raise TypeError("Expected s to be a str, got %s" % type(s))
try:
fp = unicodeIO(s)
except TypeError:
... | Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object. | Below is the the instruction that describes the task:
### Input:
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
### Response:
def loads(s, **kwargs):
"""
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Pytho... |
def McNelly(rhol, rhog, kl, Cpl, Hvap, sigma, P, Te=None, q=None):
r'''Calculates heat transfer coefficient for a evaporator operating
in the nucleate boiling regime according to [2]_ as presented in [1]_.
Either heat flux or excess temperature is required.
With `Te` specified:
.. math::
... | r'''Calculates heat transfer coefficient for a evaporator operating
in the nucleate boiling regime according to [2]_ as presented in [1]_.
Either heat flux or excess temperature is required.
With `Te` specified:
.. math::
h = \left(0.225\left(\frac{\Delta T_e C_{p,l}}{H_{vap}}\right)^{0.6... | Below is the the instruction that describes the task:
### Input:
r'''Calculates heat transfer coefficient for a evaporator operating
in the nucleate boiling regime according to [2]_ as presented in [1]_.
Either heat flux or excess temperature is required.
With `Te` specified:
.. math::
... |
def calculate_overlap(self):
"""Create the array that describes how junctions overlap"""
overs = []
if not self.tx_obj1.range.overlaps(self.tx_obj2.range): return [] # if they dont overlap wont find anything
for i in range(0,len(self.j1)):
for j in range(0,len(self.j2)):
if sel... | Create the array that describes how junctions overlap | Below is the the instruction that describes the task:
### Input:
Create the array that describes how junctions overlap
### Response:
def calculate_overlap(self):
"""Create the array that describes how junctions overlap"""
overs = []
if not self.tx_obj1.range.overlaps(self.tx_obj2.range): return [... |
def _maybe_handle(self, prefix, handler, path, params, data=None):
"""Apply the handler if the prefix matches."""
if path.startswith(prefix):
relpath = path[len(prefix):]
if data:
handler(relpath, params, data)
else:
handler(relpath, params)
return True
else:
re... | Apply the handler if the prefix matches. | Below is the the instruction that describes the task:
### Input:
Apply the handler if the prefix matches.
### Response:
def _maybe_handle(self, prefix, handler, path, params, data=None):
"""Apply the handler if the prefix matches."""
if path.startswith(prefix):
relpath = path[len(prefix):]
if d... |
def _validate_fasta_vs_seqres(self):
'''Check that the FASTA and SEQRES sequences agree (they sometimes differ)'''
pdb_id = self.pdb_id
for chain_id, sequence in self.pdb.seqres_sequences.iteritems():
if str(sequence) != self.FASTA[pdb_id][chain_id]:
if self.pdb_id in... | Check that the FASTA and SEQRES sequences agree (they sometimes differ) | Below is the the instruction that describes the task:
### Input:
Check that the FASTA and SEQRES sequences agree (they sometimes differ)
### Response:
def _validate_fasta_vs_seqres(self):
'''Check that the FASTA and SEQRES sequences agree (they sometimes differ)'''
pdb_id = self.pdb_id
for ... |
def return_current_uri_page_only(self):
"""
Args:
* None
Returns:
String - Returns the full postpath & semantic components
*NOTE* may not contain the server & port numbers. That depends on
what was provided to the parser.
"""
uri = post... | Args:
* None
Returns:
String - Returns the full postpath & semantic components
*NOTE* may not contain the server & port numbers. That depends on
what was provided to the parser. | Below is the the instruction that describes the task:
### Input:
Args:
* None
Returns:
String - Returns the full postpath & semantic components
*NOTE* may not contain the server & port numbers. That depends on
what was provided to the parser.
### Response:
def ret... |
def send_response(self, response_dict):
"""
Encode a response according to the request.
:param dict response_dict: the response to send
:raises: :class:`tornado.web.HTTPError` if no acceptable content
type exists
This method will encode `response_dict` using the mo... | Encode a response according to the request.
:param dict response_dict: the response to send
:raises: :class:`tornado.web.HTTPError` if no acceptable content
type exists
This method will encode `response_dict` using the most appropriate
encoder based on the :mailheader:`Acc... | Below is the the instruction that describes the task:
### Input:
Encode a response according to the request.
:param dict response_dict: the response to send
:raises: :class:`tornado.web.HTTPError` if no acceptable content
type exists
This method will encode `response_dict` usi... |
def perform_pilon(self):
"""
Determine if pilon polishing should be attempted. Do not perform polishing if confindr determines that the
sample is contaminated or if there are > 500 contigs
"""
for sample in self.metadata:
try:
if sample[self.analysisty... | Determine if pilon polishing should be attempted. Do not perform polishing if confindr determines that the
sample is contaminated or if there are > 500 contigs | Below is the the instruction that describes the task:
### Input:
Determine if pilon polishing should be attempted. Do not perform polishing if confindr determines that the
sample is contaminated or if there are > 500 contigs
### Response:
def perform_pilon(self):
"""
Determine if pilon poli... |
def get_capabilities(_, data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n796.
Positional arguments:
data -- bytearray data to read.
Returns:
List.
"""
answers = list()
for i in range(len(data)):
base = i * 8
for bit in range(8):
... | http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n796.
Positional arguments:
data -- bytearray data to read.
Returns:
List. | Below is the the instruction that describes the task:
### Input:
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n796.
Positional arguments:
data -- bytearray data to read.
Returns:
List.
### Response:
def get_capabilities(_, data):
"""http://git.kernel.org/cgit/... |
def ROL(self, a):
"""
Rotates all bits of the register one place left through the C (carry)
bit. This is a 9-bit rotation.
source code forms: ROL Q; ROLA; ROLB
CC bits "HNZVC": -aaas
"""
r = (a << 1) | self.C
self.clear_NZVC()
self.update_NZVC_8(... | Rotates all bits of the register one place left through the C (carry)
bit. This is a 9-bit rotation.
source code forms: ROL Q; ROLA; ROLB
CC bits "HNZVC": -aaas | Below is the the instruction that describes the task:
### Input:
Rotates all bits of the register one place left through the C (carry)
bit. This is a 9-bit rotation.
source code forms: ROL Q; ROLA; ROLB
CC bits "HNZVC": -aaas
### Response:
def ROL(self, a):
"""
Rotates all... |
def images():
"""Upload images via REST interface
Check if file upload was successful and sanatize user input.
TODO: return file URL instead of filename
"""
if request.method == 'POST':
file_upload = request.files['file']
if file_upload:
image = dict()
imag... | Upload images via REST interface
Check if file upload was successful and sanatize user input.
TODO: return file URL instead of filename | Below is the the instruction that describes the task:
### Input:
Upload images via REST interface
Check if file upload was successful and sanatize user input.
TODO: return file URL instead of filename
### Response:
def images():
"""Upload images via REST interface
Check if file upload was succes... |
def customer_source_webhook_handler(event):
"""Handle updates to customer payment-source objects.
Docs: https://stripe.com/docs/api#customer_object-sources.
"""
customer_data = event.data.get("object", {})
source_type = customer_data.get("object", {})
# TODO: handle other types of sources (https://stripe.com/do... | Handle updates to customer payment-source objects.
Docs: https://stripe.com/docs/api#customer_object-sources. | Below is the the instruction that describes the task:
### Input:
Handle updates to customer payment-source objects.
Docs: https://stripe.com/docs/api#customer_object-sources.
### Response:
def customer_source_webhook_handler(event):
"""Handle updates to customer payment-source objects.
Docs: https://stripe.co... |
def vaddg(v1, v2, ndim):
""" Add two n-dimensional vectors
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vaddg_c.html
:param v1: First vector to be added.
:type v1: list[ndim]
:param v2: Second vector to be added.
:type v2: list[ndim]
:param ndim: Dimension of v1 and v2.
:t... | Add two n-dimensional vectors
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vaddg_c.html
:param v1: First vector to be added.
:type v1: list[ndim]
:param v2: Second vector to be added.
:type v2: list[ndim]
:param ndim: Dimension of v1 and v2.
:type ndim: int
:return: v1+v2
... | Below is the the instruction that describes the task:
### Input:
Add two n-dimensional vectors
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vaddg_c.html
:param v1: First vector to be added.
:type v1: list[ndim]
:param v2: Second vector to be added.
:type v2: list[ndim]
:param n... |
def play(self, name, streamUrl, encoding = ''):
""" use a multimedia player to play a stream """
self.close()
self.name = name
self.oldUserInput = {'Input': '', 'Volume': '', 'Title': ''}
self.muted = False
self.show_volume = True
self.title_prefix = ''
se... | use a multimedia player to play a stream | Below is the the instruction that describes the task:
### Input:
use a multimedia player to play a stream
### Response:
def play(self, name, streamUrl, encoding = ''):
""" use a multimedia player to play a stream """
self.close()
self.name = name
self.oldUserInput = {'Input': '', 'V... |
def draw(self, x, y, char=None, colour=7, bg=0, thin=False):
"""
Draw a line from drawing cursor to the specified position.
This uses a modified Bressenham algorithm, interpolating twice as many points to
render down to anti-aliased characters when no character is specified,
or ... | Draw a line from drawing cursor to the specified position.
This uses a modified Bressenham algorithm, interpolating twice as many points to
render down to anti-aliased characters when no character is specified,
or uses standard algorithm plotting with the specified character.
:param x:... | Below is the the instruction that describes the task:
### Input:
Draw a line from drawing cursor to the specified position.
This uses a modified Bressenham algorithm, interpolating twice as many points to
render down to anti-aliased characters when no character is specified,
or uses standar... |
def illumf(method, target, ilusrc, et, fixref, abcorr, obsrvr, spoint):
"""
Compute the illumination angles---phase, incidence, and
emission---at a specified point on a target body. Return logical
flags indicating whether the surface point is visible from
the observer's position and whether the surf... | Compute the illumination angles---phase, incidence, and
emission---at a specified point on a target body. Return logical
flags indicating whether the surface point is visible from
the observer's position and whether the surface point is
illuminated.
The target body's surface is represented using to... | Below is the the instruction that describes the task:
### Input:
Compute the illumination angles---phase, incidence, and
emission---at a specified point on a target body. Return logical
flags indicating whether the surface point is visible from
the observer's position and whether the surface point is
... |
def _fetch_rrd_meta(self, connection, rrd_path_root, whitelist, field_names, tags):
''' Fetch metadata about each RRD in this Cacti DB, returning a list of
tuples of (hostname, device_name, rrd_path)
'''
def _in_whitelist(rrd):
path = rrd.replace('<path_rra>/', '')
... | Fetch metadata about each RRD in this Cacti DB, returning a list of
tuples of (hostname, device_name, rrd_path) | Below is the the instruction that describes the task:
### Input:
Fetch metadata about each RRD in this Cacti DB, returning a list of
tuples of (hostname, device_name, rrd_path)
### Response:
def _fetch_rrd_meta(self, connection, rrd_path_root, whitelist, field_names, tags):
''' Fetch metadata a... |
def in_hours(self, office=None, when=None):
"""
Finds if it is business hours in the given office.
:param office: Office ID to look up, or None to check if any office is in business hours.
:type office: str or None
:param datetime.datetime when: When to check the office is open, or None for now.
:returns... | Finds if it is business hours in the given office.
:param office: Office ID to look up, or None to check if any office is in business hours.
:type office: str or None
:param datetime.datetime when: When to check the office is open, or None for now.
:returns: True if it is business hours, False otherwise.
:... | Below is the the instruction that describes the task:
### Input:
Finds if it is business hours in the given office.
:param office: Office ID to look up, or None to check if any office is in business hours.
:type office: str or None
:param datetime.datetime when: When to check the office is open, or None for... |
def start(self, listen_ip=LISTEN_IP, listen_port=0):
"""Start discovery task."""
coro = self.loop.create_datagram_endpoint(
lambda: self, local_addr=(listen_ip, listen_port))
self.task = self.loop.create_task(coro)
return self.task | Start discovery task. | Below is the the instruction that describes the task:
### Input:
Start discovery task.
### Response:
def start(self, listen_ip=LISTEN_IP, listen_port=0):
"""Start discovery task."""
coro = self.loop.create_datagram_endpoint(
lambda: self, local_addr=(listen_ip, listen_port))
se... |
def _escape(value):
"""
Escape a single value of a URL string or a query parameter. If it is a list
or tuple, turn it into a comma-separated string first.
"""
# make sequences into comma-separated stings
if isinstance(value, (list, tuple)):
value = ",".join(value)
# dates and datet... | Escape a single value of a URL string or a query parameter. If it is a list
or tuple, turn it into a comma-separated string first. | Below is the the instruction that describes the task:
### Input:
Escape a single value of a URL string or a query parameter. If it is a list
or tuple, turn it into a comma-separated string first.
### Response:
def _escape(value):
"""
Escape a single value of a URL string or a query parameter. If it is ... |
def make_app(httpd_config):
""" Factory for the monitoring webapp.
"""
#mimetypes.add_type('image/vnd.microsoft.icon', '.ico')
# Default paths to serve static file from
htdocs_paths = [
os.path.realpath(os.path.join(config.config_dir, "htdocs")),
os.path.join(os.path.dirname(config.... | Factory for the monitoring webapp. | Below is the the instruction that describes the task:
### Input:
Factory for the monitoring webapp.
### Response:
def make_app(httpd_config):
""" Factory for the monitoring webapp.
"""
#mimetypes.add_type('image/vnd.microsoft.icon', '.ico')
# Default paths to serve static file from
htdocs_path... |
def pendingvalidation(self, warnonly=None):
"""Perform any pending validations
Parameters:
warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5)
Returns:
... | Perform any pending validations
Parameters:
warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5)
Returns:
bool | Below is the the instruction that describes the task:
### Input:
Perform any pending validations
Parameters:
warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based on the document's FoLiA version (Warn only before FoLiA v1.5)
... |
def _insert_single_batch_into_database(
batchIndex,
log,
dbTableName,
uniqueKeyList,
dateModified,
replace,
batchSize,
reDatetime,
dateCreated):
"""*summary of function*
**Key Arguments:**
- ``batchIndex`` -- the index of the batch... | *summary of function*
**Key Arguments:**
- ``batchIndex`` -- the index of the batch to insert
- ``dbConn`` -- mysql database connection
- ``log`` -- logger
**Return:**
- None
**Usage:**
.. todo::
add usage info
create a sublime snippet for ... | Below is the the instruction that describes the task:
### Input:
*summary of function*
**Key Arguments:**
- ``batchIndex`` -- the index of the batch to insert
- ``dbConn`` -- mysql database connection
- ``log`` -- logger
**Return:**
- None
**Usage:**
.. todo::
... |
def is_elementary_type(elem_type):
"""
Returns True if the type is elementary - not versioned
:param elem_type:
:return:
"""
if not oh.is_type(elem_type, bt.XmrType):
return False
if oh.is_type(elem_type, (bt.UVarintType, bt.IntType, mt.UnicodeType)):
... | Returns True if the type is elementary - not versioned
:param elem_type:
:return: | Below is the the instruction that describes the task:
### Input:
Returns True if the type is elementary - not versioned
:param elem_type:
:return:
### Response:
def is_elementary_type(elem_type):
"""
Returns True if the type is elementary - not versioned
:param elem_type:
... |
def get_account_info(self):
"""获得当前账号的信息
查看当前请求方(请求鉴权使用的 AccessKey 的属主)的账号信息。
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回用户信息,失败返回None
- ResponseInfo 请求的Response信息
"""
url = '{0}/v3/info'.format(self.host)
... | 获得当前账号的信息
查看当前请求方(请求鉴权使用的 AccessKey 的属主)的账号信息。
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回用户信息,失败返回None
- ResponseInfo 请求的Response信息 | Below is the the instruction that describes the task:
### Input:
获得当前账号的信息
查看当前请求方(请求鉴权使用的 AccessKey 的属主)的账号信息。
Returns:
返回一个tuple对象,其格式为(<result>, <ResponseInfo>)
- result 成功返回用户信息,失败返回None
- ResponseInfo 请求的Response信息
### Response:
def get_account... |
def student_welcome_view(request):
"""Welcome/first run page for students."""
if not request.user.is_student:
return redirect("index")
# context = {"first_login": request.session["first_login"] if "first_login" in request.session else False}
# return render(request, "welcome/old_student.html", c... | Welcome/first run page for students. | Below is the the instruction that describes the task:
### Input:
Welcome/first run page for students.
### Response:
def student_welcome_view(request):
"""Welcome/first run page for students."""
if not request.user.is_student:
return redirect("index")
# context = {"first_login": request.session[... |
def __create_driver_from_browser_config(self):
'''
Reads the config value for browser type.
'''
try:
browser_type = self._config_reader.get(
WebDriverFactory.BROWSER_TYPE_CONFIG)
except KeyError:
_wtflog("%s missing is missing from config f... | Reads the config value for browser type. | Below is the the instruction that describes the task:
### Input:
Reads the config value for browser type.
### Response:
def __create_driver_from_browser_config(self):
'''
Reads the config value for browser type.
'''
try:
browser_type = self._config_reader.get(
... |
async def set_speaker_settings(self, target: str, value: str):
"""Set speaker settings."""
params = {"settings": [{"target": target, "value": value}]}
return await self.services["audio"]["setSpeakerSettings"](params) | Set speaker settings. | Below is the the instruction that describes the task:
### Input:
Set speaker settings.
### Response:
async def set_speaker_settings(self, target: str, value: str):
"""Set speaker settings."""
params = {"settings": [{"target": target, "value": value}]}
return await self.services["audio"]["se... |
def wheel_dist_name(self):
"""Return distribution full name with - replaced with _"""
return '-'.join((safer_name(self.distribution.get_name()),
safer_version(self.distribution.get_version()))) | Return distribution full name with - replaced with _ | Below is the the instruction that describes the task:
### Input:
Return distribution full name with - replaced with _
### Response:
def wheel_dist_name(self):
"""Return distribution full name with - replaced with _"""
return '-'.join((safer_name(self.distribution.get_name()),
... |
def _compute_rtfilter_map(self):
"""Returns neighbor's RT filter (permit/allow filter based on RT).
Walks RT filter tree and computes current RT filters for each peer that
have advertised RT NLRIs.
Returns:
dict of peer, and `set` of rts that a particular neighbor is
... | Returns neighbor's RT filter (permit/allow filter based on RT).
Walks RT filter tree and computes current RT filters for each peer that
have advertised RT NLRIs.
Returns:
dict of peer, and `set` of rts that a particular neighbor is
interested in. | Below is the the instruction that describes the task:
### Input:
Returns neighbor's RT filter (permit/allow filter based on RT).
Walks RT filter tree and computes current RT filters for each peer that
have advertised RT NLRIs.
Returns:
dict of peer, and `set` of rts that a parti... |
def decode_params_utf8(params):
"""Ensures that all parameters in a list of 2-element tuples are decoded to
unicode using UTF-8.
"""
decoded = []
for k, v in params:
decoded.append((
k.decode('utf-8') if isinstance(k, bytes) else k,
v.decode('utf-8') if isinstance(v, ... | Ensures that all parameters in a list of 2-element tuples are decoded to
unicode using UTF-8. | Below is the the instruction that describes the task:
### Input:
Ensures that all parameters in a list of 2-element tuples are decoded to
unicode using UTF-8.
### Response:
def decode_params_utf8(params):
"""Ensures that all parameters in a list of 2-element tuples are decoded to
unicode using UTF-8.
... |
def stop(ctx, service, editable):
"""Stop a running service daemon."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
service_path = plugin_utils.get_plugin_path(home, SERVICES, ser... | Stop a running service daemon. | Below is the the instruction that describes the task:
### Input:
Stop a running service daemon.
### Response:
def stop(ctx, service, editable):
"""Stop a running service daemon."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "pa... |
def check_cell_type(cell, cell_type):
'''
Checks the cell type to see if it represents the cell_type passed in.
Args:
cell_type: The type id for a cell match or None for empty match.
'''
if cell_type == None or cell_type == type(None):
return cell == None or (isinstance(cell, basest... | Checks the cell type to see if it represents the cell_type passed in.
Args:
cell_type: The type id for a cell match or None for empty match. | Below is the the instruction that describes the task:
### Input:
Checks the cell type to see if it represents the cell_type passed in.
Args:
cell_type: The type id for a cell match or None for empty match.
### Response:
def check_cell_type(cell, cell_type):
'''
Checks the cell type to see if i... |
def _split_params(tag_prefix, tag_suffix):
"Split comma-separated tag_suffix[:-1] and map with _maybe_int"
if tag_suffix[-1:] != ')':
raise ValueError, "unbalanced parenthesis in type %s%s" % (tag_prefix, tag_suffix)
return map(_maybe_int, tag_suffix[:-1].split(',')) | Split comma-separated tag_suffix[:-1] and map with _maybe_int | Below is the the instruction that describes the task:
### Input:
Split comma-separated tag_suffix[:-1] and map with _maybe_int
### Response:
def _split_params(tag_prefix, tag_suffix):
"Split comma-separated tag_suffix[:-1] and map with _maybe_int"
if tag_suffix[-1:] != ')':
raise ValueError, "unbal... |
def weather_at_place(self, name):
"""
Queries the OWM Weather API for the currently observed weather at the
specified toponym (eg: "London,uk")
:param name: the location's toponym
:type name: str or unicode
:returns: an *Observation* instance or ``None`` if no weather da... | Queries the OWM Weather API for the currently observed weather at the
specified toponym (eg: "London,uk")
:param name: the location's toponym
:type name: str or unicode
:returns: an *Observation* instance or ``None`` if no weather data is
available
:raises: *ParseRes... | Below is the the instruction that describes the task:
### Input:
Queries the OWM Weather API for the currently observed weather at the
specified toponym (eg: "London,uk")
:param name: the location's toponym
:type name: str or unicode
:returns: an *Observation* instance or ``None`` i... |
def _validate_profile(self, bag):
"""
Validate against OCRD BagIt profile (bag-info fields, algos etc)
"""
if not self.profile_validator.validate(bag):
raise Exception(str(self.profile_validator.report)) | Validate against OCRD BagIt profile (bag-info fields, algos etc) | Below is the the instruction that describes the task:
### Input:
Validate against OCRD BagIt profile (bag-info fields, algos etc)
### Response:
def _validate_profile(self, bag):
"""
Validate against OCRD BagIt profile (bag-info fields, algos etc)
"""
if not self.profile_validator.va... |
def _setitem_via_pathlist(external_dict,path_list,value,**kwargs):
'''
y = {'c': {'b': {}}}
_setitem_via_pathlist(y,['c','b'],200)
'''
if('s2n' in kwargs):
s2n = kwargs['s2n']
else:
s2n = 0
if('n2s' in kwargs):
n2s = kwargs['n2s']
else:
n2s = 0
... | y = {'c': {'b': {}}}
_setitem_via_pathlist(y,['c','b'],200) | Below is the the instruction that describes the task:
### Input:
y = {'c': {'b': {}}}
_setitem_via_pathlist(y,['c','b'],200)
### Response:
def _setitem_via_pathlist(external_dict,path_list,value,**kwargs):
'''
y = {'c': {'b': {}}}
_setitem_via_pathlist(y,['c','b'],200)
'''
if('s... |
def bill(request, abbr, session, bill_id):
'''
Context:
- vote_preview_row_template
- abbr
- metadata
- bill
- show_all_sponsors
- sponsors
- sources
- nav_active
Templates:
- billy/web/public/bill.html
- billy/web/public/vote_... | Context:
- vote_preview_row_template
- abbr
- metadata
- bill
- show_all_sponsors
- sponsors
- sources
- nav_active
Templates:
- billy/web/public/bill.html
- billy/web/public/vote_preview_row.html | Below is the the instruction that describes the task:
### Input:
Context:
- vote_preview_row_template
- abbr
- metadata
- bill
- show_all_sponsors
- sponsors
- sources
- nav_active
Templates:
- billy/web/public/bill.html
- billy/we... |
def make_safe_url(self, url):
"""Makes a URL safe by removing optional hostname and port.
Example:
| ``make_safe_url('https://hostname:80/path1/path2?q1=v1&q2=v2#fragment')``
| returns ``'/path1/path2?q1=v1&q2=v2#fragment'``
Override this method if you need to allow a ... | Makes a URL safe by removing optional hostname and port.
Example:
| ``make_safe_url('https://hostname:80/path1/path2?q1=v1&q2=v2#fragment')``
| returns ``'/path1/path2?q1=v1&q2=v2#fragment'``
Override this method if you need to allow a list of safe hostnames. | Below is the the instruction that describes the task:
### Input:
Makes a URL safe by removing optional hostname and port.
Example:
| ``make_safe_url('https://hostname:80/path1/path2?q1=v1&q2=v2#fragment')``
| returns ``'/path1/path2?q1=v1&q2=v2#fragment'``
Override this me... |
def send_location(self, geo_uri, name, thumb_url=None, **thumb_info):
"""Send a location to the room.
See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location
for thumb_info
Args:
geo_uri (str): The geo uri representing the location.
name (str): Desc... | Send a location to the room.
See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location
for thumb_info
Args:
geo_uri (str): The geo uri representing the location.
name (str): Description for the location.
thumb_url (str): URL to the thumbnail of th... | Below is the the instruction that describes the task:
### Input:
Send a location to the room.
See http://matrix.org/docs/spec/client_server/r0.2.0.html#m-location
for thumb_info
Args:
geo_uri (str): The geo uri representing the location.
name (str): Description for ... |
def archive(self, format, path='', ref='master'):
"""Get the tarball or zipball archive for this repo at ref.
See: http://developer.github.com/v3/repos/contents/#get-archive-link
:param str format: (required), accepted values: ('tarball',
'zipball')
:param path: (optional),... | Get the tarball or zipball archive for this repo at ref.
See: http://developer.github.com/v3/repos/contents/#get-archive-link
:param str format: (required), accepted values: ('tarball',
'zipball')
:param path: (optional), path where the file should be saved
to, default ... | Below is the the instruction that describes the task:
### Input:
Get the tarball or zipball archive for this repo at ref.
See: http://developer.github.com/v3/repos/contents/#get-archive-link
:param str format: (required), accepted values: ('tarball',
'zipball')
:param path: (op... |
def copyVarStatesFrom(self, particleState, varNames):
"""Copy specific variables from particleState into this particle.
Parameters:
--------------------------------------------------------------
particleState: dict produced by a particle's getState() method
varNames: which variab... | Copy specific variables from particleState into this particle.
Parameters:
--------------------------------------------------------------
particleState: dict produced by a particle's getState() method
varNames: which variables to copy | Below is the the instruction that describes the task:
### Input:
Copy specific variables from particleState into this particle.
Parameters:
--------------------------------------------------------------
particleState: dict produced by a particle's getState() method
varNames: whic... |
def rootnode_solver(A, B=None, BH=None,
symmetry='hermitian', strength='symmetric',
aggregate='standard', smooth='energy',
presmoother=('block_gauss_seidel',
{'sweep': 'symmetric'}),
postsmoother=('block_gau... | Create a multilevel solver using root-node based Smoothed Aggregation (SA).
See the notes below, for the major differences with the classical-style
smoothed aggregation solver in aggregation.smoothed_aggregation_solver.
Parameters
----------
A : csr_matrix, bsr_matrix
Sparse NxN matrix in ... | Below is the the instruction that describes the task:
### Input:
Create a multilevel solver using root-node based Smoothed Aggregation (SA).
See the notes below, for the major differences with the classical-style
smoothed aggregation solver in aggregation.smoothed_aggregation_solver.
Parameters
--... |
def minimum_pitch(self):
""" Returns the minimal pitch between two neighboring nodes of the mesh in each direction.
:return: Minimal pitch in each direction.
"""
pitch = self.pitch
minimal_pitch = []
for p in pitch:
minimal_pitch.append(min(p))
retu... | Returns the minimal pitch between two neighboring nodes of the mesh in each direction.
:return: Minimal pitch in each direction. | Below is the the instruction that describes the task:
### Input:
Returns the minimal pitch between two neighboring nodes of the mesh in each direction.
:return: Minimal pitch in each direction.
### Response:
def minimum_pitch(self):
""" Returns the minimal pitch between two neighboring nodes of th... |
def fit_mle(self,
init_vals,
print_res=True,
method="BFGS",
loss_tol=1e-06,
gradient_tol=1e-06,
maxiter=1000,
ridge=None,
*args):
"""
Parameters
----------
init... | Parameters
----------
init_vals : 1D ndarray.
The initial values to start the optimizatin process with. There
should be one value for each utility coefficient, outside intercept
parameter, shape parameter, and nest parameter being estimated.
print_res : bool, ... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
init_vals : 1D ndarray.
The initial values to start the optimizatin process with. There
should be one value for each utility coefficient, outside intercept
parameter, shape para... |
def kind_name(self):
"e.g. 'Gig' or 'Movie'."
return {k:v for (k,v) in self.KIND_CHOICES}[self.kind] | e.g. 'Gig' or 'Movie'. | Below is the the instruction that describes the task:
### Input:
e.g. 'Gig' or 'Movie'.
### Response:
def kind_name(self):
"e.g. 'Gig' or 'Movie'."
return {k:v for (k,v) in self.KIND_CHOICES}[self.kind] |
def historical_rates(self, date, symbols=None):
"""
Get historical rates for any day since `date`.
:param date: a date
:type date: date or str
:param symbols: currency symbols to request specific exchange rates.
:type symbols: list or tuple
:return: the historica... | Get historical rates for any day since `date`.
:param date: a date
:type date: date or str
:param symbols: currency symbols to request specific exchange rates.
:type symbols: list or tuple
:return: the historical rates for any day since `date`.
:rtype: dict
:rais... | Below is the the instruction that describes the task:
### Input:
Get historical rates for any day since `date`.
:param date: a date
:type date: date or str
:param symbols: currency symbols to request specific exchange rates.
:type symbols: list or tuple
:return: the historic... |
def get_tunnel_statistics_input_filter_type_filter_by_gateway_gw_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_tunnel_statistics = ET.Element("get_tunnel_statistics")
config = get_tunnel_statistics
input = ET.SubElement(get_tunnel_stat... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_tunnel_statistics_input_filter_type_filter_by_gateway_gw_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_tunnel_statistics = ET.Element("get_... |
def doExperiment(locationModuleWidth,
bumpType,
cellCoordinateOffsets,
initialIncrement,
minAccuracy,
capacityResolution,
capacityPercentageResolution,
featuresPerObject,
objectWidth,
... | Finds the capacity of the specified model and object configuration. The
algorithm has two stages. First it finds an upper bound for the capacity by
repeatedly incrementing the number of objects by initialIncrement. After it
finds a number of objects that is above capacity, it begins the second stage:
performing... | Below is the the instruction that describes the task:
### Input:
Finds the capacity of the specified model and object configuration. The
algorithm has two stages. First it finds an upper bound for the capacity by
repeatedly incrementing the number of objects by initialIncrement. After it
finds a number of obj... |
def get_relname_and_parent(self, treepos):
"""Return the (relation name, parent ID) tuple that a node is in.
Return None if this node is not in a relation.
"""
node = self.dgtree[treepos]
node_type = get_node_type(node)
assert node_type in (TreeNodeTypes.relation_node, Tr... | Return the (relation name, parent ID) tuple that a node is in.
Return None if this node is not in a relation. | Below is the the instruction that describes the task:
### Input:
Return the (relation name, parent ID) tuple that a node is in.
Return None if this node is not in a relation.
### Response:
def get_relname_and_parent(self, treepos):
"""Return the (relation name, parent ID) tuple that a node is in.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.