code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def run_and_measure_payload(quil_program, qubits, trials, random_seed):
"""REST payload for :py:func:`ForestConnection._run_and_measure`"""
if not quil_program:
raise ValueError("You have attempted to run an empty program."
" Please provide gates or measure instructions to your ... | REST payload for :py:func:`ForestConnection._run_and_measure` | Below is the the instruction that describes the task:
### Input:
REST payload for :py:func:`ForestConnection._run_and_measure`
### Response:
def run_and_measure_payload(quil_program, qubits, trials, random_seed):
"""REST payload for :py:func:`ForestConnection._run_and_measure`"""
if not quil_program:
... |
def _wrap(obj, wrapper=None, methods_to_add=(), name=None, skip=(), wrap_return_values=False, wrap_filenames=(),
filename=None, wrapped_name_func=None, wrapped=None):
"""
Wrap module, class, function or another variable recursively
:param Any obj: Object to wrap recursively
:param Optional[Ca... | Wrap module, class, function or another variable recursively
:param Any obj: Object to wrap recursively
:param Optional[Callable] wrapper: Wrapper to wrap functions and methods in (accepts function as argument)
:param Collection[Callable] methods_to_add: Container of functions, which accept class as argume... | Below is the the instruction that describes the task:
### Input:
Wrap module, class, function or another variable recursively
:param Any obj: Object to wrap recursively
:param Optional[Callable] wrapper: Wrapper to wrap functions and methods in (accepts function as argument)
:param Collection[Callable]... |
def touch(self, conn, key, exptime):
"""The command is used to update the expiration time of
an existing item without fetching it.
:param key: ``bytes``, is the key to update expiration time
:param exptime: ``int``, is expiration time. This replaces the existing
expiration time.... | The command is used to update the expiration time of
an existing item without fetching it.
:param key: ``bytes``, is the key to update expiration time
:param exptime: ``int``, is expiration time. This replaces the existing
expiration time.
:return: ``bool``, True in case of succ... | Below is the the instruction that describes the task:
### Input:
The command is used to update the expiration time of
an existing item without fetching it.
:param key: ``bytes``, is the key to update expiration time
:param exptime: ``int``, is expiration time. This replaces the existing
... |
def get_build_configuration_by_name(name):
"""
Returns the build configuration matching the name
:param name: name of build configuration
:return: The matching build configuration, or None if no match found
"""
response = utils.checked_api_call(pnc_api.build_configs, 'get_all', q='name==' + name... | Returns the build configuration matching the name
:param name: name of build configuration
:return: The matching build configuration, or None if no match found | Below is the the instruction that describes the task:
### Input:
Returns the build configuration matching the name
:param name: name of build configuration
:return: The matching build configuration, or None if no match found
### Response:
def get_build_configuration_by_name(name):
"""
Returns the b... |
def validate(self, cipher_text, max_timedelta=None):
"""
Will decrypt the url safe base64 encoded crypted str or bytes array.
Args:
cipher_text: the encrypted text
max_timedelta: maximum timedelta in seconds
Returns:
the original message list
... | Will decrypt the url safe base64 encoded crypted str or bytes array.
Args:
cipher_text: the encrypted text
max_timedelta: maximum timedelta in seconds
Returns:
the original message list | Below is the the instruction that describes the task:
### Input:
Will decrypt the url safe base64 encoded crypted str or bytes array.
Args:
cipher_text: the encrypted text
max_timedelta: maximum timedelta in seconds
Returns:
the original message list
### Response... |
def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']):
"""place a leaf node"""
if part.startswith(':'):
if self.param and self.param != part:
err = """Cannot place param '{}' as '{self.param_name}' exist on node already!"""
raise ParamAlreadyExist(e... | place a leaf node | Below is the the instruction that describes the task:
### Input:
place a leaf node
### Response:
def place(self, part: str, val: Union['ApiNode', 'ApiEndpoint']):
"""place a leaf node"""
if part.startswith(':'):
if self.param and self.param != part:
err = """Cannot place... |
def dump_state(self):
"""Dump the current state of this emulated object as a dictionary.
Returns:
dict: The current state of the object that could be passed to load_state.
"""
state = {}
state['tile_states'] = {}
for address, tile in self._tiles.items():
... | Dump the current state of this emulated object as a dictionary.
Returns:
dict: The current state of the object that could be passed to load_state. | Below is the the instruction that describes the task:
### Input:
Dump the current state of this emulated object as a dictionary.
Returns:
dict: The current state of the object that could be passed to load_state.
### Response:
def dump_state(self):
"""Dump the current state of this emul... |
def event_list_to_event_roll(source_event_list, event_label_list=None, time_resolution=0.01):
"""Convert event list into event roll, binary activity matrix
Parameters
----------
source_event_list : list, shape=(n,)
A list containing event dicts
event_label_list : list, shape=(k,) or None
... | Convert event list into event roll, binary activity matrix
Parameters
----------
source_event_list : list, shape=(n,)
A list containing event dicts
event_label_list : list, shape=(k,) or None
A list of containing unique labels in alphabetical order
(Default value = None)
ti... | Below is the the instruction that describes the task:
### Input:
Convert event list into event roll, binary activity matrix
Parameters
----------
source_event_list : list, shape=(n,)
A list containing event dicts
event_label_list : list, shape=(k,) or None
A list of containing uniq... |
def wait(object_ids, num_returns=1, timeout=None):
"""Return a list of IDs that are ready and a list of IDs that are not.
This method is identical to `ray.wait` except it adds support for tuples
and ndarrays.
Args:
object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)):
L... | Return a list of IDs that are ready and a list of IDs that are not.
This method is identical to `ray.wait` except it adds support for tuples
and ndarrays.
Args:
object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)):
List like of object IDs for objects that may or may not be ... | Below is the the instruction that describes the task:
### Input:
Return a list of IDs that are ready and a list of IDs that are not.
This method is identical to `ray.wait` except it adds support for tuples
and ndarrays.
Args:
object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)):
... |
def get_html(self):
"""Bibliographic entry in html format."""
# Author links
au_link = ('<a href="https://www.scopus.com/authid/detail.url'
'?origin=AuthorProfile&authorId={0}">{1}</a>')
if len(self.authors) > 1:
authors = u', '.join([au_link.format(a.auid,... | Bibliographic entry in html format. | Below is the the instruction that describes the task:
### Input:
Bibliographic entry in html format.
### Response:
def get_html(self):
"""Bibliographic entry in html format."""
# Author links
au_link = ('<a href="https://www.scopus.com/authid/detail.url'
'?origin=AuthorPr... |
def decode_hparams(overrides=""):
"""Hyperparameters for decoding."""
hp = hparam.HParams(
save_images=False,
log_results=True,
extra_length=100,
min_length_ratio=0.0,
batch_size=0,
beam_size=4,
alpha=0.6,
eos_penalty=0.0,
block_size=0,
guess_and_check_top... | Hyperparameters for decoding. | Below is the the instruction that describes the task:
### Input:
Hyperparameters for decoding.
### Response:
def decode_hparams(overrides=""):
"""Hyperparameters for decoding."""
hp = hparam.HParams(
save_images=False,
log_results=True,
extra_length=100,
min_length_ratio=0.0,
batc... |
def set_write_buffer_limits(self, high=None, low=None):
"""
Called by the client protocol to set the high- and low-water
limits for write flow control.
These two values control when call the protocol's
``pause_writing()`` and ``resume_writing()`` methods are
called.
... | Called by the client protocol to set the high- and low-water
limits for write flow control.
These two values control when call the protocol's
``pause_writing()`` and ``resume_writing()`` methods are
called.
:param high: The high-water limit. Must be a non-negative
... | Below is the the instruction that describes the task:
### Input:
Called by the client protocol to set the high- and low-water
limits for write flow control.
These two values control when call the protocol's
``pause_writing()`` and ``resume_writing()`` methods are
called.
:p... |
def getdata(inputfile, argnum=None, close=False):
"""
Get data from the .dat files
args:
inputfile: file
Input File
close: bool, default=False
Closes inputfile if True
inputfile (File): Input file
close (boolean): Closes inputfile if True (default: Fa... | Get data from the .dat files
args:
inputfile: file
Input File
close: bool, default=False
Closes inputfile if True
inputfile (File): Input file
close (boolean): Closes inputfile if True (default: False)
returns:
dictionary:
data: list o... | Below is the the instruction that describes the task:
### Input:
Get data from the .dat files
args:
inputfile: file
Input File
close: bool, default=False
Closes inputfile if True
inputfile (File): Input file
close (boolean): Closes inputfile if True (defa... |
def remove_update_callback(self, group, name=None, cb=None):
"""Remove the supplied callback for a group or a group.name"""
if not cb:
return
if not name:
if group in self.group_update_callbacks:
self.group_update_callbacks[group].remove_callback(cb)
... | Remove the supplied callback for a group or a group.name | Below is the the instruction that describes the task:
### Input:
Remove the supplied callback for a group or a group.name
### Response:
def remove_update_callback(self, group, name=None, cb=None):
"""Remove the supplied callback for a group or a group.name"""
if not cb:
return
... |
def compute_rewards(self, scores):
"""Compute the velocity of thte k+1 most recent scores.
The velocity is the average distance between scores. Return a list with those k velocities
padded out with zeros so that the count remains the same.
"""
# take the k + 1 most recent scores... | Compute the velocity of thte k+1 most recent scores.
The velocity is the average distance between scores. Return a list with those k velocities
padded out with zeros so that the count remains the same. | Below is the the instruction that describes the task:
### Input:
Compute the velocity of thte k+1 most recent scores.
The velocity is the average distance between scores. Return a list with those k velocities
padded out with zeros so that the count remains the same.
### Response:
def compute_rewar... |
def checkfuncname(b, frame):
"""Check whether we should break here because of `b.funcname`."""
if not b.funcname:
# Breakpoint was set via line number.
if b.line != frame.f_lineno:
# Breakpoint was set at a line with a def statement and the function
# defined is called: d... | Check whether we should break here because of `b.funcname`. | Below is the the instruction that describes the task:
### Input:
Check whether we should break here because of `b.funcname`.
### Response:
def checkfuncname(b, frame):
"""Check whether we should break here because of `b.funcname`."""
if not b.funcname:
# Breakpoint was set via line number.
... |
def asinh(x, context=None):
"""
Return the inverse hyperbolic sine of x.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_asinh,
(BigFloat._implicit_convert(x),),
context,
) | Return the inverse hyperbolic sine of x. | Below is the the instruction that describes the task:
### Input:
Return the inverse hyperbolic sine of x.
### Response:
def asinh(x, context=None):
"""
Return the inverse hyperbolic sine of x.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_asinh,
(BigFlo... |
def status():
'''Display the database migrations status'''
for plugin, package, filename in available_migrations():
migration = get_migration(plugin, filename)
if migration:
status = green(migration['date'].strftime(DATE_FORMAT))
else:
status = yellow('Not applied... | Display the database migrations status | Below is the the instruction that describes the task:
### Input:
Display the database migrations status
### Response:
def status():
'''Display the database migrations status'''
for plugin, package, filename in available_migrations():
migration = get_migration(plugin, filename)
if migration:... |
def constructor(self, random, args):
"""Return a candidate solution for an ant colony optimization."""
self._use_ants = True
candidate = []
while len(candidate) < len(self.weights) - 1:
# Find feasible components
feasible_components = []
if len(candida... | Return a candidate solution for an ant colony optimization. | Below is the the instruction that describes the task:
### Input:
Return a candidate solution for an ant colony optimization.
### Response:
def constructor(self, random, args):
"""Return a candidate solution for an ant colony optimization."""
self._use_ants = True
candidate = []
whil... |
def constructFiniteStateMachine(inputs, outputs, states, table, initial,
richInputs, inputContext, world,
logger=LOGGER):
"""
Construct a new finite state machine from a definition of its states.
@param inputs: Definitions of all input symbols... | Construct a new finite state machine from a definition of its states.
@param inputs: Definitions of all input symbols the resulting machine will
need to handle, as a L{twisted.python.constants.Names} subclass.
@param outputs: Definitions of all output symbols the resulting machine is
allowed t... | Below is the the instruction that describes the task:
### Input:
Construct a new finite state machine from a definition of its states.
@param inputs: Definitions of all input symbols the resulting machine will
need to handle, as a L{twisted.python.constants.Names} subclass.
@param outputs: Definit... |
def cancel_order(self, order_id):
"""
Send a request to cancel an order, return the response.
Arguments:
order_id - the order id to cancel
"""
request = '/v1/order/cancel'
url = self.base_url + request
params = {
'request': request,
... | Send a request to cancel an order, return the response.
Arguments:
order_id - the order id to cancel | Below is the the instruction that describes the task:
### Input:
Send a request to cancel an order, return the response.
Arguments:
order_id - the order id to cancel
### Response:
def cancel_order(self, order_id):
"""
Send a request to cancel an order, return the response.
... |
def _html_escape(string):
"""HTML escape all of these " & < >"""
html_codes = {
'"': '"',
'<': '<',
'>': '>',
}
# & must be handled first
string = string.replace('&', '&')
for char in html_codes:
string = string.replace(char, html_codes[char])
... | HTML escape all of these " & < > | Below is the the instruction that describes the task:
### Input:
HTML escape all of these " & < >
### Response:
def _html_escape(string):
"""HTML escape all of these " & < >"""
html_codes = {
'"': '"',
'<': '<',
'>': '>',
}
# & must be handled first
string =... |
def list_basebackups_http(self, arg):
"""List available basebackups from a HTTP source"""
self.storage = HTTPRestore(arg.host, arg.port, arg.site)
self.storage.show_basebackup_list(verbose=arg.verbose) | List available basebackups from a HTTP source | Below is the the instruction that describes the task:
### Input:
List available basebackups from a HTTP source
### Response:
def list_basebackups_http(self, arg):
"""List available basebackups from a HTTP source"""
self.storage = HTTPRestore(arg.host, arg.port, arg.site)
self.storage.show_b... |
def from_string(date_str):
"""
construction from the following string patterns
'%Y-%m-%d'
'%d.%m.%Y'
'%m/%d/%Y'
'%Y%m%d'
:param str date_str:
:return BusinessDate:
"""
if date_str.count('-'):
str_format = '%Y-%m-%d'
eli... | construction from the following string patterns
'%Y-%m-%d'
'%d.%m.%Y'
'%m/%d/%Y'
'%Y%m%d'
:param str date_str:
:return BusinessDate: | Below is the the instruction that describes the task:
### Input:
construction from the following string patterns
'%Y-%m-%d'
'%d.%m.%Y'
'%m/%d/%Y'
'%Y%m%d'
:param str date_str:
:return BusinessDate:
### Response:
def from_string(date_str):
"""
constru... |
def _checkpath(self, path):
""" Checks that a given path is valid. If it's not, raises NotFoundException """
if path.startswith("/") or ".." in path or path.strip() != path:
raise NotFoundException() | Checks that a given path is valid. If it's not, raises NotFoundException | Below is the the instruction that describes the task:
### Input:
Checks that a given path is valid. If it's not, raises NotFoundException
### Response:
def _checkpath(self, path):
""" Checks that a given path is valid. If it's not, raises NotFoundException """
if path.startswith("/") or ".." in pat... |
def filter_properties(self, model, context=None):
"""
Filter simple properties
Runs filters on simple properties changing them in place.
:param model: object or dict
:param context: object, dict or None
:return: None
"""
if model is None:
retu... | Filter simple properties
Runs filters on simple properties changing them in place.
:param model: object or dict
:param context: object, dict or None
:return: None | Below is the the instruction that describes the task:
### Input:
Filter simple properties
Runs filters on simple properties changing them in place.
:param model: object or dict
:param context: object, dict or None
:return: None
### Response:
def filter_properties(self, model, conte... |
def FileEntryExistsByPathSpec(self, path_spec):
"""Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): a path specification.
Returns:
bool: True if the file entry exists, false otherwise.
"""
location = getattr(path_spec, 'location', None)
if lo... | Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): a path specification.
Returns:
bool: True if the file entry exists, false otherwise. | Below is the the instruction that describes the task:
### Input:
Determines if a file entry for a path specification exists.
Args:
path_spec (PathSpec): a path specification.
Returns:
bool: True if the file entry exists, false otherwise.
### Response:
def FileEntryExistsByPathSpec(self, path_... |
def arrow_from_wid(self, wid):
"""Make a real portal and its arrow from a dummy arrow.
This doesn't handle touch events. It takes a widget as its
argument: the one the user has been dragging to indicate where
they want the arrow to go. Said widget ought to be invisible.
It check... | Make a real portal and its arrow from a dummy arrow.
This doesn't handle touch events. It takes a widget as its
argument: the one the user has been dragging to indicate where
they want the arrow to go. Said widget ought to be invisible.
It checks if the dummy arrow connects two real spo... | Below is the the instruction that describes the task:
### Input:
Make a real portal and its arrow from a dummy arrow.
This doesn't handle touch events. It takes a widget as its
argument: the one the user has been dragging to indicate where
they want the arrow to go. Said widget ought to be ... |
def open( self ):
"""Open the database connection."""
if self._connection is None:
self._connection = sqlite3.connect(self._dbfile) | Open the database connection. | Below is the the instruction that describes the task:
### Input:
Open the database connection.
### Response:
def open( self ):
"""Open the database connection."""
if self._connection is None:
self._connection = sqlite3.connect(self._dbfile) |
def _send(self, key, value, metric_type):
"""Send the specified value to the statsd daemon via UDP without a
direct socket connection.
:param str key: The key name to send
:param int or float value: The value for the key
"""
try:
payload = self._build_payloa... | Send the specified value to the statsd daemon via UDP without a
direct socket connection.
:param str key: The key name to send
:param int or float value: The value for the key | Below is the the instruction that describes the task:
### Input:
Send the specified value to the statsd daemon via UDP without a
direct socket connection.
:param str key: The key name to send
:param int or float value: The value for the key
### Response:
def _send(self, key, value, metric_... |
def get_appliances(self, start=0, count=-1, filter='', fields='', query='', sort='', view=''):
"""
Gets a list of all the Image Streamer resources based on optional sorting and filtering, and constrained
by start and count parameters.
Args:
start:
The first i... | Gets a list of all the Image Streamer resources based on optional sorting and filtering, and constrained
by start and count parameters.
Args:
start:
The first item to return, using 0-based indexing.
If not specified, the default is 0 - start with the first av... | Below is the the instruction that describes the task:
### Input:
Gets a list of all the Image Streamer resources based on optional sorting and filtering, and constrained
by start and count parameters.
Args:
start:
The first item to return, using 0-based indexing.
... |
def getenv(name, **kwargs):
"""
Retrieves environment variable by name and casts the value to desired type.
If desired type is list or tuple - uses separator to split the value.
"""
default_value = kwargs.pop('default', None)
desired_type = kwargs.pop('type', str)
list_separator = kwargs.pop... | Retrieves environment variable by name and casts the value to desired type.
If desired type is list or tuple - uses separator to split the value. | Below is the the instruction that describes the task:
### Input:
Retrieves environment variable by name and casts the value to desired type.
If desired type is list or tuple - uses separator to split the value.
### Response:
def getenv(name, **kwargs):
"""
Retrieves environment variable by name and cas... |
def _normalize_django_header_name(header):
"""Unmunge header names modified by Django."""
# Remove HTTP_ prefix.
new_header = header.rpartition('HTTP_')[2]
# Camel case and replace _ with -
new_header = '-'.join(
x.capitalize() for x in new_header.split('_'))
... | Unmunge header names modified by Django. | Below is the the instruction that describes the task:
### Input:
Unmunge header names modified by Django.
### Response:
def _normalize_django_header_name(header):
"""Unmunge header names modified by Django."""
# Remove HTTP_ prefix.
new_header = header.rpartition('HTTP_')[2]
# Camel... |
def authenticate(self,
connection_certificate=None,
connection_info=None,
request_credentials=None):
"""
Query the configured SLUGS service with the provided credentials.
Args:
connection_certificate (cryptography.x509.C... | Query the configured SLUGS service with the provided credentials.
Args:
connection_certificate (cryptography.x509.Certificate): An X.509
certificate object obtained from the connection being
authenticated. Required for SLUGS authentication.
connection_inf... | Below is the the instruction that describes the task:
### Input:
Query the configured SLUGS service with the provided credentials.
Args:
connection_certificate (cryptography.x509.Certificate): An X.509
certificate object obtained from the connection being
authent... |
def request(device, response_queue, payload, timeout_s=None, poll=POLL_QUEUES):
'''
Send payload to serial device and wait for response.
Parameters
----------
device : serial.Serial
Serial instance.
response_queue : Queue.Queue
Queue to wait for response on.
payload : str or... | Send payload to serial device and wait for response.
Parameters
----------
device : serial.Serial
Serial instance.
response_queue : Queue.Queue
Queue to wait for response on.
payload : str or bytes
Payload to send.
timeout_s : float, optional
Maximum time to wait... | Below is the the instruction that describes the task:
### Input:
Send payload to serial device and wait for response.
Parameters
----------
device : serial.Serial
Serial instance.
response_queue : Queue.Queue
Queue to wait for response on.
payload : str or bytes
Payload ... |
def diffsp(self, col: str, serie: "iterable", name: str="Diff"):
"""
Add a diff column in percentage from a serie. The serie is
an iterable of the same length than the dataframe
:param col: column to diff
:type col: str
:param serie: serie to diff from
:type ser... | Add a diff column in percentage from a serie. The serie is
an iterable of the same length than the dataframe
:param col: column to diff
:type col: str
:param serie: serie to diff from
:type serie: iterable
:param name: name of the diff col, defaults to "Diff"
:p... | Below is the the instruction that describes the task:
### Input:
Add a diff column in percentage from a serie. The serie is
an iterable of the same length than the dataframe
:param col: column to diff
:type col: str
:param serie: serie to diff from
:type serie: iterable
... |
def summary(self, background=False, sub_sketch_keys=None):
"""
Summary statistics that can be calculated with one pass over the SArray.
Returns a turicreate.Sketch object which can be further queried for many
descriptive statistics over this SArray. Many of the statistics are
ap... | Summary statistics that can be calculated with one pass over the SArray.
Returns a turicreate.Sketch object which can be further queried for many
descriptive statistics over this SArray. Many of the statistics are
approximate. See the :class:`~turicreate.Sketch` documentation for more
d... | Below is the the instruction that describes the task:
### Input:
Summary statistics that can be calculated with one pass over the SArray.
Returns a turicreate.Sketch object which can be further queried for many
descriptive statistics over this SArray. Many of the statistics are
approximate.... |
def on_first_registration(self):
"""Action to be performed on first plugin registration"""
self.main.tabify_plugins(self.main.help, self)
self.dockwidget.hide() | Action to be performed on first plugin registration | Below is the the instruction that describes the task:
### Input:
Action to be performed on first plugin registration
### Response:
def on_first_registration(self):
"""Action to be performed on first plugin registration"""
self.main.tabify_plugins(self.main.help, self)
self.dockwidget.hide() |
def find_package_data(
where='.', package='',
exclude=standard_exclude,
exclude_directories=standard_exclude_directories,
only_in_packages=True,
show_ignored=False,
):
"""
Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary l... | Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks like::
{'package': [files]}
Where ``files`` is a list of all the files in that package that
don't match anything in ``exclude``.
If ``only_in_packages`` is true, then top-level... | Below is the the instruction that describes the task:
### Input:
Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks like::
{'package': [files]}
Where ``files`` is a list of all the files in that package that
don't match anything... |
def V_total(self):
'''
Compute the input voltage (i.e., ``V1``) based on the measured
high-voltage feedback values for ``V2``, using the high-voltage
transfer function.
See also
--------
:meth:`V_actuation` for diagram with ``V1`` and ``V2`` labelled.
'''... | Compute the input voltage (i.e., ``V1``) based on the measured
high-voltage feedback values for ``V2``, using the high-voltage
transfer function.
See also
--------
:meth:`V_actuation` for diagram with ``V1`` and ``V2`` labelled. | Below is the the instruction that describes the task:
### Input:
Compute the input voltage (i.e., ``V1``) based on the measured
high-voltage feedback values for ``V2``, using the high-voltage
transfer function.
See also
--------
:meth:`V_actuation` for diagram with ``V1`` an... |
def unpack_utf8(self):
"""Decode a utf-8 string encoded as described in MQTT Version
3.1.1 section 1.5.3 line 177. This is a 16-bit unsigned length
followed by a utf-8 encoded string.
Raises
------
UnderflowDecodeError
Raised when a read failed to extract en... | Decode a utf-8 string encoded as described in MQTT Version
3.1.1 section 1.5.3 line 177. This is a 16-bit unsigned length
followed by a utf-8 encoded string.
Raises
------
UnderflowDecodeError
Raised when a read failed to extract enough bytes from the
un... | Below is the the instruction that describes the task:
### Input:
Decode a utf-8 string encoded as described in MQTT Version
3.1.1 section 1.5.3 line 177. This is a 16-bit unsigned length
followed by a utf-8 encoded string.
Raises
------
UnderflowDecodeError
Rais... |
def parse_options(cls, options):
"""Parse plug-in specific options."""
cls.known_modules = {
project2module(k): v.split(",")
for k, v in [
x.split(":[")
for x in re.split(r"],?", options.known_modules)[:-1]
]
} | Parse plug-in specific options. | Below is the the instruction that describes the task:
### Input:
Parse plug-in specific options.
### Response:
def parse_options(cls, options):
"""Parse plug-in specific options."""
cls.known_modules = {
project2module(k): v.split(",")
for k, v in [
x.split("... |
def _prepare_data_dir(self, data):
"""Prepare destination directory where the data will live.
:param data: The :class:`~resolwe.flow.models.Data` object for
which to prepare the private execution directory.
:return: The prepared data directory path.
:rtype: str
"""
... | Prepare destination directory where the data will live.
:param data: The :class:`~resolwe.flow.models.Data` object for
which to prepare the private execution directory.
:return: The prepared data directory path.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Prepare destination directory where the data will live.
:param data: The :class:`~resolwe.flow.models.Data` object for
which to prepare the private execution directory.
:return: The prepared data directory path.
:r... |
def feed(self, schemata: list) -> None:
"""
Take schemata from incoming list representation as schemata() returns, unless
cache already has schema for an incoming schema sequence number.
:param schemata: list of schema objects
"""
LOGGER.debug('SchemaCache.feed >>> sche... | Take schemata from incoming list representation as schemata() returns, unless
cache already has schema for an incoming schema sequence number.
:param schemata: list of schema objects | Below is the the instruction that describes the task:
### Input:
Take schemata from incoming list representation as schemata() returns, unless
cache already has schema for an incoming schema sequence number.
:param schemata: list of schema objects
### Response:
def feed(self, schemata: list) -> No... |
def update(self, table, columns, values, where):
"""
Update the values of a particular row where a value is met.
:param table: table name
:param columns: column(s) to update
:param values: updated values
:param where: tuple, (where_column, where_value)
"""
... | Update the values of a particular row where a value is met.
:param table: table name
:param columns: column(s) to update
:param values: updated values
:param where: tuple, (where_column, where_value) | Below is the the instruction that describes the task:
### Input:
Update the values of a particular row where a value is met.
:param table: table name
:param columns: column(s) to update
:param values: updated values
:param where: tuple, (where_column, where_value)
### Response:
def... |
def _cnv_prioritize(data):
"""Perform confidence interval based prioritization for CNVs.
"""
supported = {"cnvkit": {"inputs": ["call_file", "segmetrics"], "fn": _cnvkit_prioritize}}
pcall = None
priority_files = None
for call in data.get("sv", []):
if call["variantcaller"] in supported:... | Perform confidence interval based prioritization for CNVs. | Below is the the instruction that describes the task:
### Input:
Perform confidence interval based prioritization for CNVs.
### Response:
def _cnv_prioritize(data):
"""Perform confidence interval based prioritization for CNVs.
"""
supported = {"cnvkit": {"inputs": ["call_file", "segmetrics"], "fn": _cn... |
def dot(matrix, vector, matrix_ty, vector_ty):
"""
Computes the dot product between a matrix and a vector.
Args:
matrix (WeldObject / Numpy.ndarray): 2-d input matrix
vector (WeldObject / Numpy.ndarray): 1-d input vector
ty (WeldType): Type of each element in the input matrix and ve... | Computes the dot product between a matrix and a vector.
Args:
matrix (WeldObject / Numpy.ndarray): 2-d input matrix
vector (WeldObject / Numpy.ndarray): 1-d input vector
ty (WeldType): Type of each element in the input matrix and vector
Returns:
A WeldObject representing this c... | Below is the the instruction that describes the task:
### Input:
Computes the dot product between a matrix and a vector.
Args:
matrix (WeldObject / Numpy.ndarray): 2-d input matrix
vector (WeldObject / Numpy.ndarray): 1-d input vector
ty (WeldType): Type of each element in the input mat... |
def pin_post(self, post):
"""Pin post
:type post: dict|str|int
:param post: Either the post dict returned by another API method, or
the `cid` field of that post.
:returns: True if it is successful. False otherwise
"""
try:
cid = post['id']
... | Pin post
:type post: dict|str|int
:param post: Either the post dict returned by another API method, or
the `cid` field of that post.
:returns: True if it is successful. False otherwise | Below is the the instruction that describes the task:
### Input:
Pin post
:type post: dict|str|int
:param post: Either the post dict returned by another API method, or
the `cid` field of that post.
:returns: True if it is successful. False otherwise
### Response:
def pin_post(... |
def _get(auth, path, fmt, autobox=True, params=None):
'''
Issue a GET request to the XNAT REST API and box the response content.
Example:
>>> import yaxil
>>> from yaxil import Format
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.get(auth... | Issue a GET request to the XNAT REST API and box the response content.
Example:
>>> import yaxil
>>> from yaxil import Format
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.get(auth, '/data/experiments', Format.JSON)
:param auth: XNAT authent... | Below is the the instruction that describes the task:
### Input:
Issue a GET request to the XNAT REST API and box the response content.
Example:
>>> import yaxil
>>> from yaxil import Format
>>> auth = yaxil.XnatAuth(url='...', username='...', password='...')
>>> yaxil.get(a... |
def min(self, axis=None, skipna=True, *args, **kwargs):
"""
Return the minimum value of the Index or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Series.min : Return the minimum value in a Series.
"""
nv.validate_min(args, kwargs)
... | Return the minimum value of the Index or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Series.min : Return the minimum value in a Series. | Below is the the instruction that describes the task:
### Input:
Return the minimum value of the Index or minimum along
an axis.
See Also
--------
numpy.ndarray.min
Series.min : Return the minimum value in a Series.
### Response:
def min(self, axis=None, skipna=True, *args,... |
def parse_mail_date(datestr):
'''Helper method used by :meth:`Message.from_email_message` to
convert dates from rfc822 format to iso 8601.
:param datestr: string containing a date in rfc822 format
:returns: string with date in iso 8601 format
'''
time_tuple = email.utils.parsedate_tz(datestr)
... | Helper method used by :meth:`Message.from_email_message` to
convert dates from rfc822 format to iso 8601.
:param datestr: string containing a date in rfc822 format
:returns: string with date in iso 8601 format | Below is the the instruction that describes the task:
### Input:
Helper method used by :meth:`Message.from_email_message` to
convert dates from rfc822 format to iso 8601.
:param datestr: string containing a date in rfc822 format
:returns: string with date in iso 8601 format
### Response:
def parse_mai... |
def left(X, i):
"""Compute the orthogonal matrix Q_{\leq i} as defined in [1]."""
if i < 0:
return np.ones([1, 1])
answ = np.ones([1, 1])
cores = tt.tensor.to_list(X)
for dim in xrange(i+1):
answ = np.tensordot(answ, cores[dim], 1)
answ = reshape(answ, (-1, X.r[i+1]))
return ... | Compute the orthogonal matrix Q_{\leq i} as defined in [1]. | Below is the the instruction that describes the task:
### Input:
Compute the orthogonal matrix Q_{\leq i} as defined in [1].
### Response:
def left(X, i):
"""Compute the orthogonal matrix Q_{\leq i} as defined in [1]."""
if i < 0:
return np.ones([1, 1])
answ = np.ones([1, 1])
cores = tt.ten... |
def applymap(self, func, **kwargs):
"""Return a new PRDD by applying a function to each element of each
pandas DataFrame."""
return self.from_rdd(
self._rdd.map(lambda data: data.applymap(func), **kwargs)) | Return a new PRDD by applying a function to each element of each
pandas DataFrame. | Below is the the instruction that describes the task:
### Input:
Return a new PRDD by applying a function to each element of each
pandas DataFrame.
### Response:
def applymap(self, func, **kwargs):
"""Return a new PRDD by applying a function to each element of each
pandas DataFrame."""
... |
def render_sendmail(self):
"""
if we have smtp_host and smtp_from, configure sendmail plugin,
else remove it
"""
phase = 'exit_plugins'
plugin = 'sendmail'
if not self.dj.dock_json_has_plugin_conf(phase, plugin):
return
if self.spec.smtp_host.... | if we have smtp_host and smtp_from, configure sendmail plugin,
else remove it | Below is the the instruction that describes the task:
### Input:
if we have smtp_host and smtp_from, configure sendmail plugin,
else remove it
### Response:
def render_sendmail(self):
"""
if we have smtp_host and smtp_from, configure sendmail plugin,
else remove it
"""
... |
def _generate_notebook_header(notebook_object, notebook_type, notebook_title="Notebook Title",
tags="tags", difficulty_stars=1,
notebook_description="Notebook Description"):
"""
Internal function that is used for generation of the generic notebooks hea... | Internal function that is used for generation of the generic notebooks header.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the header will be created.
notebook_type : str
Notebook type: - "Main_Files_Signal_Samples"
... | Below is the the instruction that describes the task:
### Input:
Internal function that is used for generation of the generic notebooks header.
----------
Parameters
----------
notebook_object : notebook object
Object of "notebook" class where the header will be created.
notebook_type ... |
def _progress_update(self, numerator_increment, stage=0, show_eta=True, **kw):
""" Updates the progress. Will update progress bars or other progress output.
Parameters
----------
numerator : int
numerator of partial work done already in current stage
stage : int, non... | Updates the progress. Will update progress bars or other progress output.
Parameters
----------
numerator : int
numerator of partial work done already in current stage
stage : int, nonnegative, default=0
Current stage of the algorithm, 0 or greater | Below is the the instruction that describes the task:
### Input:
Updates the progress. Will update progress bars or other progress output.
Parameters
----------
numerator : int
numerator of partial work done already in current stage
stage : int, nonnegative, default=0
... |
def draw_edges(self):
"""Basic edge routing applied only for edges with dummy points.
Enhanced edge routing can be performed by using the apropriate
*route_with_xxx* functions from :ref:routing_ in the edges' view.
"""
for e in self.g.E():
if hasattr(e,'view'):
... | Basic edge routing applied only for edges with dummy points.
Enhanced edge routing can be performed by using the apropriate
*route_with_xxx* functions from :ref:routing_ in the edges' view. | Below is the the instruction that describes the task:
### Input:
Basic edge routing applied only for edges with dummy points.
Enhanced edge routing can be performed by using the apropriate
*route_with_xxx* functions from :ref:routing_ in the edges' view.
### Response:
def draw_edges(self):
... |
def iterate_specific_packet_range():
"""Count the number of packets in a specific range."""
now = datetime.utcnow()
start = now - timedelta(hours=1)
total = 0
for packet in archive.list_packets(start=start, stop=now):
total += 1
# print(packet)
print('Found', total, 'packets in ... | Count the number of packets in a specific range. | Below is the the instruction that describes the task:
### Input:
Count the number of packets in a specific range.
### Response:
def iterate_specific_packet_range():
"""Count the number of packets in a specific range."""
now = datetime.utcnow()
start = now - timedelta(hours=1)
total = 0
for pac... |
def _print_summary_map(strm, result_map, ftype):
"""Print summary of certain result map."""
if len(result_map) == 0:
return 0
npass = len([x for k, x in result_map.iteritems() if len(x) == 0])
strm.write('=====%d/%d %s files passed check=====\n' % (npass, len(result_map), fty... | Print summary of certain result map. | Below is the the instruction that describes the task:
### Input:
Print summary of certain result map.
### Response:
def _print_summary_map(strm, result_map, ftype):
"""Print summary of certain result map."""
if len(result_map) == 0:
return 0
npass = len([x for k, x in result_map... |
def csrf_token():
"""
Get csrf token or create new one
"""
from uliweb import request, settings
from uliweb.utils.common import safe_str
v = {}
token_name = settings.CSRF.cookie_token_name
if not request.session.deleted and request.session.get(token_name):
v = request.sessio... | Get csrf token or create new one | Below is the the instruction that describes the task:
### Input:
Get csrf token or create new one
### Response:
def csrf_token():
"""
Get csrf token or create new one
"""
from uliweb import request, settings
from uliweb.utils.common import safe_str
v = {}
token_name = settings.CSRF... |
def import_txt(filename, **kwargs):
"""Import Syscal measurements from a text file, exported as 'Spreadsheet'.
Parameters
----------
filename: string
input filename
x0: float, optional
position of first electrode. If not given, then use the smallest
x-position in the data as... | Import Syscal measurements from a text file, exported as 'Spreadsheet'.
Parameters
----------
filename: string
input filename
x0: float, optional
position of first electrode. If not given, then use the smallest
x-position in the data as the first electrode.
spacing: float
... | Below is the the instruction that describes the task:
### Input:
Import Syscal measurements from a text file, exported as 'Spreadsheet'.
Parameters
----------
filename: string
input filename
x0: float, optional
position of first electrode. If not given, then use the smallest
... |
def align(self):
'''
Every step we have 3 choices:
1) Move pointer witness a --> omission
2) Move pointer witness b --> addition
3) Move pointer of both witness a/b --> match
Note: a replacement is omission followed by an addition or the other way around
Choice ... | Every step we have 3 choices:
1) Move pointer witness a --> omission
2) Move pointer witness b --> addition
3) Move pointer of both witness a/b --> match
Note: a replacement is omission followed by an addition or the other way around
Choice 1 and 2 are only possible if token a ... | Below is the the instruction that describes the task:
### Input:
Every step we have 3 choices:
1) Move pointer witness a --> omission
2) Move pointer witness b --> addition
3) Move pointer of both witness a/b --> match
Note: a replacement is omission followed by an addition or the o... |
def file_change_rates(self, branch='master', limit=None, coverage=False, days=None, ignore_globs=None,
include_globs=None):
"""
This function will return a DataFrame containing some basic aggregations of the file change history data, and
optionally test coverage data fr... | This function will return a DataFrame containing some basic aggregations of the file change history data, and
optionally test coverage data from a coverage_data.py .coverage file. The aim here is to identify files in the
project which have abnormal edit rates, or the rate of changes without growing the... | Below is the the instruction that describes the task:
### Input:
This function will return a DataFrame containing some basic aggregations of the file change history data, and
optionally test coverage data from a coverage_data.py .coverage file. The aim here is to identify files in the
project which... |
def sparse_to_unmasked_sparse(self):
"""The 1D index mappings between the masked sparse-grid and unmasked sparse grid."""
return mapping_util.sparse_to_unmasked_sparse_from_mask_and_pixel_centres(
total_sparse_pixels=self.total_sparse_pixels, mask=self.regular_grid.mask,
unmasked... | The 1D index mappings between the masked sparse-grid and unmasked sparse grid. | Below is the the instruction that describes the task:
### Input:
The 1D index mappings between the masked sparse-grid and unmasked sparse grid.
### Response:
def sparse_to_unmasked_sparse(self):
"""The 1D index mappings between the masked sparse-grid and unmasked sparse grid."""
return mapping_util... |
def remove_all_handler(self):
"""
Unlink the file handler association.
"""
for handler in self.logger.handlers[:]:
self.logger.removeHandler(handler)
self._handler_cache.append(handler) | Unlink the file handler association. | Below is the the instruction that describes the task:
### Input:
Unlink the file handler association.
### Response:
def remove_all_handler(self):
"""
Unlink the file handler association.
"""
for handler in self.logger.handlers[:]:
self.logger.removeHandler(handler)
... |
def commercial_domains():
# type: () -> set
""" Return list of commercial email domains, which means:
- domain is not public
- domain is not university
- it is not personal (more than 1 person using this domain)
>>> "google.com" in commercial_domains()
True
>>> "microsoft.com" in commerc... | Return list of commercial email domains, which means:
- domain is not public
- domain is not university
- it is not personal (more than 1 person using this domain)
>>> "google.com" in commercial_domains()
True
>>> "microsoft.com" in commercial_domains()
True
>>> "isri.cs.cmu.edu" in comm... | Below is the the instruction that describes the task:
### Input:
Return list of commercial email domains, which means:
- domain is not public
- domain is not university
- it is not personal (more than 1 person using this domain)
>>> "google.com" in commercial_domains()
True
>>> "microsoft.co... |
def update_serviceprofile(self, host_id, vlan_id):
"""Top level method to update Service Profiles on UCS Manager.
Calls all the methods responsible for the individual tasks that
ultimately result in a vlan_id getting programed on a server's
ethernet ports and the Fabric Interconnect's n... | Top level method to update Service Profiles on UCS Manager.
Calls all the methods responsible for the individual tasks that
ultimately result in a vlan_id getting programed on a server's
ethernet ports and the Fabric Interconnect's network ports. | Below is the the instruction that describes the task:
### Input:
Top level method to update Service Profiles on UCS Manager.
Calls all the methods responsible for the individual tasks that
ultimately result in a vlan_id getting programed on a server's
ethernet ports and the Fabric Interconn... |
def group_dict(items, keyfunc):
"""Return a list defaultdict with ``items`` grouped by ``keyfunc``.
>>> sorted(group_dict('eggs', lambda x: x).items())
[('e', ['e']), ('g', ['g', 'g']), ('s', ['s'])]
"""
result = collections.defaultdict(list)
for i in items:
key = keyfunc(i)
res... | Return a list defaultdict with ``items`` grouped by ``keyfunc``.
>>> sorted(group_dict('eggs', lambda x: x).items())
[('e', ['e']), ('g', ['g', 'g']), ('s', ['s'])] | Below is the the instruction that describes the task:
### Input:
Return a list defaultdict with ``items`` grouped by ``keyfunc``.
>>> sorted(group_dict('eggs', lambda x: x).items())
[('e', ['e']), ('g', ['g', 'g']), ('s', ['s'])]
### Response:
def group_dict(items, keyfunc):
"""Return a list defaultdi... |
def qteNextWindow(self):
"""
Return next window in cyclic order.
|Args|
* **None**
|Returns|
* **QtmacsWindow**: the next window in the Qtmacs internal
window list.
|Raises|
* **None**
"""
# Get the currently active window... | Return next window in cyclic order.
|Args|
* **None**
|Returns|
* **QtmacsWindow**: the next window in the Qtmacs internal
window list.
|Raises|
* **None** | Below is the the instruction that describes the task:
### Input:
Return next window in cyclic order.
|Args|
* **None**
|Returns|
* **QtmacsWindow**: the next window in the Qtmacs internal
window list.
|Raises|
* **None**
### Response:
def qteNextWin... |
def _write_var_data_nonsparse(self, f, zVar, var, dataType, numElems,
recVary, compression, blockingfactor, indata):
'''
Creates VVRs and the corresponding VXRs full of "indata" data.
If there is no compression, creates exactly one VXR and VVR
If there i... | Creates VVRs and the corresponding VXRs full of "indata" data.
If there is no compression, creates exactly one VXR and VVR
If there is compression
Parameters:
f : file
The open CDF file
zVar : bool
True if this is z variable data
... | Below is the the instruction that describes the task:
### Input:
Creates VVRs and the corresponding VXRs full of "indata" data.
If there is no compression, creates exactly one VXR and VVR
If there is compression
Parameters:
f : file
The open CDF file
... |
def get_object_data(self, ref):
""" As get_object_header, but returns object data as well
:return: (hexsha, type_string, size_as_int,data_string)
:note: not threadsafe"""
hexsha, typename, size, stream = self.stream_object_data(ref)
data = stream.read(size)
del(stream)
... | As get_object_header, but returns object data as well
:return: (hexsha, type_string, size_as_int,data_string)
:note: not threadsafe | Below is the the instruction that describes the task:
### Input:
As get_object_header, but returns object data as well
:return: (hexsha, type_string, size_as_int,data_string)
:note: not threadsafe
### Response:
def get_object_data(self, ref):
""" As get_object_header, but returns object dat... |
def cmd_exec(self, cmd):
"""
Execute commands in automate namespace
"""
if not cmd:
return
ns = self.cmd_namespace
import copy
rval = True
nscopy = copy.copy(ns)
try:
r = eval(cmd, ns)
if isinstance(r, Syste... | Execute commands in automate namespace | Below is the the instruction that describes the task:
### Input:
Execute commands in automate namespace
### Response:
def cmd_exec(self, cmd):
"""
Execute commands in automate namespace
"""
if not cmd:
return
ns = self.cmd_namespace
import copy
... |
def _join(self, rows):
'''
Join multiple rows worth of data into a single result.
'''
rval = {}
for row in rows:
if row:
for value,count in row.items():
rval[ value ] = count + rval.get(value,0)
return rval | Join multiple rows worth of data into a single result. | Below is the the instruction that describes the task:
### Input:
Join multiple rows worth of data into a single result.
### Response:
def _join(self, rows):
'''
Join multiple rows worth of data into a single result.
'''
rval = {}
for row in rows:
if row:
for value,count in row.ite... |
def _stdout_raw(self, s):
"""Writes the string to stdout"""
print(s, end='', file=sys.stdout)
sys.stdout.flush() | Writes the string to stdout | Below is the the instruction that describes the task:
### Input:
Writes the string to stdout
### Response:
def _stdout_raw(self, s):
"""Writes the string to stdout"""
print(s, end='', file=sys.stdout)
sys.stdout.flush() |
def write_meta(self):
"""ucds, descriptions and units are written as attributes in the hdf5 file, instead of a seperate file as
the default :func:`Dataset.write_meta`.
"""
with h5py.File(self.filename, "r+") as h5file_output:
h5table_root = h5file_output[self.h5table_root_n... | ucds, descriptions and units are written as attributes in the hdf5 file, instead of a seperate file as
the default :func:`Dataset.write_meta`. | Below is the the instruction that describes the task:
### Input:
ucds, descriptions and units are written as attributes in the hdf5 file, instead of a seperate file as
the default :func:`Dataset.write_meta`.
### Response:
def write_meta(self):
"""ucds, descriptions and units are written as attribu... |
def disable_all_tokens(platform, user_id, on_error=None, on_success=None):
""" Disable ALL device tokens for the given user on the specified platform.
:param str platform The platform which to disable token on. One of either
Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service
(outb... | Disable ALL device tokens for the given user on the specified platform.
:param str platform The platform which to disable token on. One of either
Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service
(outbound.APNS).
:param str | number user_id: the id you use to identify a user. th... | Below is the the instruction that describes the task:
### Input:
Disable ALL device tokens for the given user on the specified platform.
:param str platform The platform which to disable token on. One of either
Google Cloud Messaging (outbound.GCM) or Apple Push Notification Service
(outbound.APNS).
... |
def put(self,
body: Body,
priority: int = DEFAULT_PRIORITY,
delay: int = DEFAULT_DELAY,
ttr: int = DEFAULT_TTR) -> int:
"""Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priori... | Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
:param delay: The number of seconds to delay the job for.
:param tt... | Below is the the instruction that describes the task:
### Input:
Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
:param... |
def _wrap(value):
"""
Wraps the passed value in a Sequence if it is not a primitive. If it is a string
argument it is expanded to a list of characters.
>>> _wrap(1)
1
>>> _wrap("abc")
['a', 'b', 'c']
>>> type(_wrap([1, 2]))
functional.pipeline.Sequence
:param value: value to ... | Wraps the passed value in a Sequence if it is not a primitive. If it is a string
argument it is expanded to a list of characters.
>>> _wrap(1)
1
>>> _wrap("abc")
['a', 'b', 'c']
>>> type(_wrap([1, 2]))
functional.pipeline.Sequence
:param value: value to wrap
:return: wrapped or n... | Below is the the instruction that describes the task:
### Input:
Wraps the passed value in a Sequence if it is not a primitive. If it is a string
argument it is expanded to a list of characters.
>>> _wrap(1)
1
>>> _wrap("abc")
['a', 'b', 'c']
>>> type(_wrap([1, 2]))
functional.pipelin... |
def set_mode_cb(self, mode, tf):
"""Called when one of the Move/Draw/Edit radio buttons is selected."""
if tf:
self.canvas.set_draw_mode(mode)
if mode == 'edit':
self.edit_select_mark()
return True | Called when one of the Move/Draw/Edit radio buttons is selected. | Below is the the instruction that describes the task:
### Input:
Called when one of the Move/Draw/Edit radio buttons is selected.
### Response:
def set_mode_cb(self, mode, tf):
"""Called when one of the Move/Draw/Edit radio buttons is selected."""
if tf:
self.canvas.set_draw_mode(mode)
... |
def wquantiles(W, x, alphas=(0.25, 0.50, 0.75)):
"""Quantiles for weighted data.
Parameters
----------
W: (N,) ndarray
normalised weights (weights are >=0 and sum to one)
x: (N,) or (N,d) ndarray
data
alphas: list-like of size k (default: (0.25, 0.50, 0.75))
probabilitie... | Quantiles for weighted data.
Parameters
----------
W: (N,) ndarray
normalised weights (weights are >=0 and sum to one)
x: (N,) or (N,d) ndarray
data
alphas: list-like of size k (default: (0.25, 0.50, 0.75))
probabilities (between 0. and 1.)
Returns
-------
a (k... | Below is the the instruction that describes the task:
### Input:
Quantiles for weighted data.
Parameters
----------
W: (N,) ndarray
normalised weights (weights are >=0 and sum to one)
x: (N,) or (N,d) ndarray
data
alphas: list-like of size k (default: (0.25, 0.50, 0.75))
... |
def cli(env, identifier, wait):
"""Check if a virtual server is ready."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
ready = vsi.wait_for_ready(vs_id, wait)
if ready:
env.fout("READY")
else:
raise exceptions.CLIAbort("Inst... | Check if a virtual server is ready. | Below is the the instruction that describes the task:
### Input:
Check if a virtual server is ready.
### Response:
def cli(env, identifier, wait):
"""Check if a virtual server is ready."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
ready = v... |
def get(cls, pid_value, pid_type=None, **kwargs):
"""Get a persistent identifier for this provider.
:param pid_type: Persistent identifier type. (Default: configured
:attr:`invenio_pidstore.providers.base.BaseProvider.pid_type`)
:param pid_value: Persistent identifier value.
... | Get a persistent identifier for this provider.
:param pid_type: Persistent identifier type. (Default: configured
:attr:`invenio_pidstore.providers.base.BaseProvider.pid_type`)
:param pid_value: Persistent identifier value.
:param kwargs: See
:meth:`invenio_pidstore.provi... | Below is the the instruction that describes the task:
### Input:
Get a persistent identifier for this provider.
:param pid_type: Persistent identifier type. (Default: configured
:attr:`invenio_pidstore.providers.base.BaseProvider.pid_type`)
:param pid_value: Persistent identifier value.... |
def parse(self, m, prefix=None):
"""Parse messages sent by the 'buildbot-cvs-mail' program.
"""
# The mail is sent from the person doing the checkin. Assume that the
# local username is enough to identify them (this assumes a one-server
# cvs-over-rsh environment rather than the ... | Parse messages sent by the 'buildbot-cvs-mail' program. | Below is the the instruction that describes the task:
### Input:
Parse messages sent by the 'buildbot-cvs-mail' program.
### Response:
def parse(self, m, prefix=None):
"""Parse messages sent by the 'buildbot-cvs-mail' program.
"""
# The mail is sent from the person doing the checkin. Assume... |
def get_lambda_function(lambda_function, flags=FLAGS.ALL, **conn):
"""Fully describes a lambda function.
Args:
lambda_function: Name, ARN, or dictionary of lambda function. If dictionary, should likely be the return value from list_functions. At a minimum, must contain a key titled 'FunctionName'.
... | Fully describes a lambda function.
Args:
lambda_function: Name, ARN, or dictionary of lambda function. If dictionary, should likely be the return value from list_functions. At a minimum, must contain a key titled 'FunctionName'.
flags: Flags describing which sections should be included in the r... | Below is the the instruction that describes the task:
### Input:
Fully describes a lambda function.
Args:
lambda_function: Name, ARN, or dictionary of lambda function. If dictionary, should likely be the return value from list_functions. At a minimum, must contain a key titled 'FunctionName'.
... |
def label_image(
self,
parent,
basic_config,
feature,
image_classification_config=None,
bounding_poly_config=None,
polyline_config=None,
segmentation_config=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_... | Starts a labeling task for image. The type of image labeling task is
configured by feature in the request.
Example:
>>> from google.cloud import datalabeling_v1beta1
>>> from google.cloud.datalabeling_v1beta1 import enums
>>>
>>> client = datalabeling_v1b... | Below is the the instruction that describes the task:
### Input:
Starts a labeling task for image. The type of image labeling task is
configured by feature in the request.
Example:
>>> from google.cloud import datalabeling_v1beta1
>>> from google.cloud.datalabeling_v1beta1 i... |
def comply(self, path):
"""Ensures the contents and the permissions of the file.
:param path: the path to correct
"""
dirname = os.path.dirname(path)
if not os.path.exists(dirname):
os.makedirs(dirname)
self.pre_write()
render_and_write(self.template... | Ensures the contents and the permissions of the file.
:param path: the path to correct | Below is the the instruction that describes the task:
### Input:
Ensures the contents and the permissions of the file.
:param path: the path to correct
### Response:
def comply(self, path):
"""Ensures the contents and the permissions of the file.
:param path: the path to correct
"... |
def confd_state_loaded_data_models_data_model_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring")
loaded_data_models = ET.SubElement(confd_state, "loaded... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def confd_state_loaded_data_models_data_model_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
confd_state = ET.SubElement(config, "confd-state", xmlns="h... |
def legendLabel(self):
"""
Provide a textual description of the feature and its qualifiers to be
used as a label in a plot legend.
@return: A C{str} description of the feature.
"""
excludedQualifiers = set((
'codon_start', 'db_xref', 'protein_id', 'region_nam... | Provide a textual description of the feature and its qualifiers to be
used as a label in a plot legend.
@return: A C{str} description of the feature. | Below is the the instruction that describes the task:
### Input:
Provide a textual description of the feature and its qualifiers to be
used as a label in a plot legend.
@return: A C{str} description of the feature.
### Response:
def legendLabel(self):
"""
Provide a textual descript... |
def run(self, target, payload, instance=None, hook_id=None, **kwargs):
"""
target: the url to receive the payload.
payload: a python primitive data structure
instance: a possibly null "trigger" instance
hook: the defining Hook object (useful for removing)
"... | target: the url to receive the payload.
payload: a python primitive data structure
instance: a possibly null "trigger" instance
hook: the defining Hook object (useful for removing) | Below is the the instruction that describes the task:
### Input:
target: the url to receive the payload.
payload: a python primitive data structure
instance: a possibly null "trigger" instance
hook: the defining Hook object (useful for removing)
### Response:
def run(self, ta... |
def create_action(parent, text, shortcut=None, icon=None, tip=None,
toggled=None, triggered=None, data=None, menurole=None,
context=Qt.WindowShortcut):
"""Create a QAction"""
action = SpyderAction(text, parent)
if triggered is not None:
action.triggered.conn... | Create a QAction | Below is the the instruction that describes the task:
### Input:
Create a QAction
### Response:
def create_action(parent, text, shortcut=None, icon=None, tip=None,
toggled=None, triggered=None, data=None, menurole=None,
context=Qt.WindowShortcut):
"""Create a QAction"""
... |
def reinstantiate_endpoints(self, endpoint=None):
"""
This will re-instantiate the endpoints with the connection this time
:param endpoint: Endpoint object to instantiate the sub endpoint in.
:return: None
"""
endpoint = endpoint or self
for k, v in endpoi... | This will re-instantiate the endpoints with the connection this time
:param endpoint: Endpoint object to instantiate the sub endpoint in.
:return: None | Below is the the instruction that describes the task:
### Input:
This will re-instantiate the endpoints with the connection this time
:param endpoint: Endpoint object to instantiate the sub endpoint in.
:return: None
### Response:
def reinstantiate_endpoints(self, endpoint=None):
""... |
def create(resource_path, previous_version=None, package='perch.migrations'):
"""Create a new migration"""
pkg, obj = resource_path.rsplit('.', 1)
module = importlib.import_module(pkg)
resource = getattr(module, obj)
version = uuid4().hex
target_module = importlib.import_module(package)
targ... | Create a new migration | Below is the the instruction that describes the task:
### Input:
Create a new migration
### Response:
def create(resource_path, previous_version=None, package='perch.migrations'):
"""Create a new migration"""
pkg, obj = resource_path.rsplit('.', 1)
module = importlib.import_module(pkg)
resource = g... |
def plot_axes(self):
"""axes"""
span = np.linspace(-1.0, 1.0, 2)
self.axes.plot(span, 0 * span, zs=0, zdir='z', label='X',
lw=self.frame_width, color=self.frame_color)
self.axes.plot(0 * span, span, zs=0, zdir='z', label='Y',
lw=self.frame_wi... | axes | Below is the the instruction that describes the task:
### Input:
axes
### Response:
def plot_axes(self):
"""axes"""
span = np.linspace(-1.0, 1.0, 2)
self.axes.plot(span, 0 * span, zs=0, zdir='z', label='X',
lw=self.frame_width, color=self.frame_color)
self.axe... |
def read(self):
''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) '''
warnings.warn("Document.read() is deprecated and will be removed in near future.", DeprecationWarning)
with TxtReader.from_doc(self) as reader:
reader.read(self)
return self | Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) | Below is the the instruction that describes the task:
### Input:
Read tagged doc from mutliple files (sents, tokens, concepts, links, tags)
### Response:
def read(self):
''' Read tagged doc from mutliple files (sents, tokens, concepts, links, tags) '''
warnings.warn("Document.read() is deprecated a... |
def import_doc(self, file_uris, docsearch, current_doc=None):
"""
Import the specified PDF files
"""
doc = None
docs = []
pages = []
file_uris = [self.fs.safe(uri) for uri in file_uris]
imported = []
for file_uri in file_uris:
logger.... | Import the specified PDF files | Below is the the instruction that describes the task:
### Input:
Import the specified PDF files
### Response:
def import_doc(self, file_uris, docsearch, current_doc=None):
"""
Import the specified PDF files
"""
doc = None
docs = []
pages = []
file_uris = [s... |
def read(self, symbol, as_of=None, date_range=None, from_version=None, allow_secondary=None, **kwargs):
"""
Read data for the named symbol. Returns a VersionedItem object with
a data and metdata element (as passed into write).
Parameters
----------
symbol : `str`
... | Read data for the named symbol. Returns a VersionedItem object with
a data and metdata element (as passed into write).
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or `int` or `datetime.datetime`
Return the data as it was a... | Below is the the instruction that describes the task:
### Input:
Read data for the named symbol. Returns a VersionedItem object with
a data and metdata element (as passed into write).
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or... |
def parse_bool(value):
""" Convert a string to a boolean
>>> parse_bool(None)
False
>>> parse_bool("true")
True
>>> parse_bool("TRUE")
True
>>> parse_bool("yes")
True
>>> parse_bool("1")
True
>>> parse_bool("false")
False
>>> parse_bool("sqdf")
False
... | Convert a string to a boolean
>>> parse_bool(None)
False
>>> parse_bool("true")
True
>>> parse_bool("TRUE")
True
>>> parse_bool("yes")
True
>>> parse_bool("1")
True
>>> parse_bool("false")
False
>>> parse_bool("sqdf")
False
>>> parse_bool(False)
False... | Below is the the instruction that describes the task:
### Input:
Convert a string to a boolean
>>> parse_bool(None)
False
>>> parse_bool("true")
True
>>> parse_bool("TRUE")
True
>>> parse_bool("yes")
True
>>> parse_bool("1")
True
>>> parse_bool("false")
False
... |
def get_fwhm_tag(expnum, ccd, prefix=None, version='p'):
"""
Get the FWHM from the VOSpace annotation.
@param expnum:
@param ccd:
@param prefix:
@param version:
@return:
"""
uri = get_uri(expnum, ccd, version, ext='fwhm', prefix=prefix)
if uri not in fwhm:
key = "fwhm_{:... | Get the FWHM from the VOSpace annotation.
@param expnum:
@param ccd:
@param prefix:
@param version:
@return: | Below is the the instruction that describes the task:
### Input:
Get the FWHM from the VOSpace annotation.
@param expnum:
@param ccd:
@param prefix:
@param version:
@return:
### Response:
def get_fwhm_tag(expnum, ccd, prefix=None, version='p'):
"""
Get the FWHM from the VOSpace annotat... |
def _get_upsert_sql(queryset, model_objs, unique_fields, update_fields, returning,
ignore_duplicate_updates=True, return_untouched=False):
"""
Generates the postgres specific sql necessary to perform an upsert (ON CONFLICT)
INSERT INTO table_name (field1, field2)
VALUES (1, 'two')
... | Generates the postgres specific sql necessary to perform an upsert (ON CONFLICT)
INSERT INTO table_name (field1, field2)
VALUES (1, 'two')
ON CONFLICT (unique_field) DO UPDATE SET field2 = EXCLUDED.field2; | Below is the the instruction that describes the task:
### Input:
Generates the postgres specific sql necessary to perform an upsert (ON CONFLICT)
INSERT INTO table_name (field1, field2)
VALUES (1, 'two')
ON CONFLICT (unique_field) DO UPDATE SET field2 = EXCLUDED.field2;
### Response:
def _get_upsert_sq... |
def _writeReplacementFiles(self, session, directory, name):
"""
Write the replacement files
"""
if self.replaceParamFile:
self.replaceParamFile.write(session=session, directory=directory,
name=name)
if self.replaceValFile:
... | Write the replacement files | Below is the the instruction that describes the task:
### Input:
Write the replacement files
### Response:
def _writeReplacementFiles(self, session, directory, name):
"""
Write the replacement files
"""
if self.replaceParamFile:
self.replaceParamFile.write(session=sessio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.