code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def equivalence_transform(compound, from_positions, to_positions, add_bond=True):
"""Computes an affine transformation that maps the from_positions to the
respective to_positions, and applies this transformation to the compound.
Parameters
----------
compound : mb.Compound
The Compound to b... | Computes an affine transformation that maps the from_positions to the
respective to_positions, and applies this transformation to the compound.
Parameters
----------
compound : mb.Compound
The Compound to be transformed.
from_positions : np.ndarray, shape=(n, 3), dtype=float
Origina... | Below is the the instruction that describes the task:
### Input:
Computes an affine transformation that maps the from_positions to the
respective to_positions, and applies this transformation to the compound.
Parameters
----------
compound : mb.Compound
The Compound to be transformed.
f... |
def copy(self, site_properties=None, sanitize=False):
"""
Convenience method to get a copy of the structure, with options to add
site properties.
Args:
site_properties (dict): Properties to add or override. The
properties are specified in the same way as the ... | Convenience method to get a copy of the structure, with options to add
site properties.
Args:
site_properties (dict): Properties to add or override. The
properties are specified in the same way as the constructor,
i.e., as a dict of the form {property: [value... | Below is the the instruction that describes the task:
### Input:
Convenience method to get a copy of the structure, with options to add
site properties.
Args:
site_properties (dict): Properties to add or override. The
properties are specified in the same way as the const... |
def get_key_to_last_completed_course_block(user, course_key):
"""
Returns the last block a "user" completed in a course (stated as "course_key").
raises UnavailableCompletionData when the user has not completed blocks in
the course.
raises UnavailableCompletionData when the visual progress waffle ... | Returns the last block a "user" completed in a course (stated as "course_key").
raises UnavailableCompletionData when the user has not completed blocks in
the course.
raises UnavailableCompletionData when the visual progress waffle flag is
disabled. | Below is the the instruction that describes the task:
### Input:
Returns the last block a "user" completed in a course (stated as "course_key").
raises UnavailableCompletionData when the user has not completed blocks in
the course.
raises UnavailableCompletionData when the visual progress waffle flag ... |
def process_presence(self, stanza):
"""Process presence stanza.
Pass it to a handler of the stanza's type and payload namespace.
:Parameters:
- `stanza`: presence stanza to be handled
"""
stanza_type = stanza.stanza_type
return self.__try_handlers(self._pre... | Process presence stanza.
Pass it to a handler of the stanza's type and payload namespace.
:Parameters:
- `stanza`: presence stanza to be handled | Below is the the instruction that describes the task:
### Input:
Process presence stanza.
Pass it to a handler of the stanza's type and payload namespace.
:Parameters:
- `stanza`: presence stanza to be handled
### Response:
def process_presence(self, stanza):
"""Process presen... |
def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
"""Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
"""
update_ldict = []
same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict))
for same_ke... | Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict | Below is the the instruction that describes the task:
### Input:
Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
### Response:
def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
"""Return a list dict of the ch... |
def append(self, items):
""" Add some items to this ItemList and save the changes to the server
:param items: the items to add, either as a List of Item objects, an
ItemList, a List of item URLs as Strings, a single item URL as a
String, or a single Item object
:rtype: ... | Add some items to this ItemList and save the changes to the server
:param items: the items to add, either as a List of Item objects, an
ItemList, a List of item URLs as Strings, a single item URL as a
String, or a single Item object
:rtype: String
:returns: the server s... | Below is the the instruction that describes the task:
### Input:
Add some items to this ItemList and save the changes to the server
:param items: the items to add, either as a List of Item objects, an
ItemList, a List of item URLs as Strings, a single item URL as a
String, or a sing... |
def psffunc(self, *args, **kwargs):
"""Calculates a linescan psf"""
if self.polychromatic:
func = psfcalc.calculate_polychrome_linescan_psf
else:
func = psfcalc.calculate_linescan_psf
return func(*args, **kwargs) | Calculates a linescan psf | Below is the the instruction that describes the task:
### Input:
Calculates a linescan psf
### Response:
def psffunc(self, *args, **kwargs):
"""Calculates a linescan psf"""
if self.polychromatic:
func = psfcalc.calculate_polychrome_linescan_psf
else:
func = psfcalc.c... |
def get_interface_switchport_output_switchport_fcoe_port_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interf... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_interface_switchport_output_switchport_fcoe_port_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_in... |
def getBestMatchingCell(self, c, activeState):
"""Find weakly activated cell in column. Returns index and segment of most
activated segment above minThreshold.
"""
# Collect all cells in column c that have at least minThreshold in the most
# activated segment
bestActivityInCol = self.minThreshol... | Find weakly activated cell in column. Returns index and segment of most
activated segment above minThreshold. | Below is the the instruction that describes the task:
### Input:
Find weakly activated cell in column. Returns index and segment of most
activated segment above minThreshold.
### Response:
def getBestMatchingCell(self, c, activeState):
"""Find weakly activated cell in column. Returns index and segment of m... |
def update_entries(entries: Entries, data: dict) -> None:
"""Update each entry in the list with some data."""
# TODO: Is mutating the list okay, making copies is such a pain in the ass
for entry in entries:
entry.update(data) | Update each entry in the list with some data. | Below is the the instruction that describes the task:
### Input:
Update each entry in the list with some data.
### Response:
def update_entries(entries: Entries, data: dict) -> None:
"""Update each entry in the list with some data."""
# TODO: Is mutating the list okay, making copies is such a pain ... |
def fillna(data, other, join="left", dataset_join="left"):
"""Fill missing values in this object with data from the other object.
Follows normal broadcasting and alignment rules.
Parameters
----------
join : {'outer', 'inner', 'left', 'right'}, optional
Method for joining the indexes of the... | Fill missing values in this object with data from the other object.
Follows normal broadcasting and alignment rules.
Parameters
----------
join : {'outer', 'inner', 'left', 'right'}, optional
Method for joining the indexes of the passed objects along each
dimension
- 'outer': us... | Below is the the instruction that describes the task:
### Input:
Fill missing values in this object with data from the other object.
Follows normal broadcasting and alignment rules.
Parameters
----------
join : {'outer', 'inner', 'left', 'right'}, optional
Method for joining the indexes of ... |
async def copy_from_query(self, query, *args, output,
timeout=None, format=None, oids=None,
delimiter=None, null=None, header=None,
quote=None, escape=None, force_quote=None,
encoding=None):
"... | Copy the results of a query to a file or file-like object.
:param str query:
The query to copy the results of.
:param args:
Query arguments.
:param output:
A :term:`path-like object <python:path-like object>`,
or a :term:`file-like object <pytho... | Below is the the instruction that describes the task:
### Input:
Copy the results of a query to a file or file-like object.
:param str query:
The query to copy the results of.
:param args:
Query arguments.
:param output:
A :term:`path-like object <pytho... |
def sample_path(alpha, A, pobs, T=None):
""" Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations )
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
A : ndarra... | Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations )
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of time t.
A : ndarray((N,N), dtype = float)
transition matrix... | Below is the the instruction that describes the task:
### Input:
Sample the hidden pathway S from the conditional distribution P ( S | Parameters, Observations )
Parameters
----------
alpha : ndarray((T,N), dtype = float), optional, default = None
alpha[t,i] is the ith forward coefficient of ti... |
def clone(self, clone_member):
"""
- initialize the replica from an existing member (master or replica)
- initialize the replica using the replica creation method that
works without the replication connection (i.e. restore from on-disk
base backup)
... | - initialize the replica from an existing member (master or replica)
- initialize the replica using the replica creation method that
works without the replication connection (i.e. restore from on-disk
base backup) | Below is the the instruction that describes the task:
### Input:
- initialize the replica from an existing member (master or replica)
- initialize the replica using the replica creation method that
works without the replication connection (i.e. restore from on-disk
base ba... |
def getShocks(self):
'''
Gets new Markov states and permanent and transitory income shocks for this period. Samples
from IncomeDstn for each period-state in the cycle.
Parameters
----------
None
Returns
-------
None
'''
# Get new... | Gets new Markov states and permanent and transitory income shocks for this period. Samples
from IncomeDstn for each period-state in the cycle.
Parameters
----------
None
Returns
-------
None | Below is the the instruction that describes the task:
### Input:
Gets new Markov states and permanent and transitory income shocks for this period. Samples
from IncomeDstn for each period-state in the cycle.
Parameters
----------
None
Returns
-------
None
#... |
def convert_adc(value, output_type, max_volts):
"""
Converts the output from the ADC into the desired type.
"""
return {
const.ADC_RAW: lambda x: x,
const.ADC_PERCENTAGE: adc_to_percentage,
const.ADC_VOLTS: adc_to_volts,
const.ADC_MILLIVOLTS: adc_to_millivolts
}[outpu... | Converts the output from the ADC into the desired type. | Below is the the instruction that describes the task:
### Input:
Converts the output from the ADC into the desired type.
### Response:
def convert_adc(value, output_type, max_volts):
"""
Converts the output from the ADC into the desired type.
"""
return {
const.ADC_RAW: lambda x: x,
... |
def batch_results(self, results):
"""Push a batch of output results to the Spark output RDD of ``TFCluster.inference()``.
Note: this currently expects a one-to-one mapping of input to output data, so the length of the ``results`` array should match the length of
the previously retrieved batch of input data... | Push a batch of output results to the Spark output RDD of ``TFCluster.inference()``.
Note: this currently expects a one-to-one mapping of input to output data, so the length of the ``results`` array should match the length of
the previously retrieved batch of input data.
Args:
:results: array of out... | Below is the the instruction that describes the task:
### Input:
Push a batch of output results to the Spark output RDD of ``TFCluster.inference()``.
Note: this currently expects a one-to-one mapping of input to output data, so the length of the ``results`` array should match the length of
the previously r... |
def finalize(self, **kwargs):
"""
Finalize the drawing setting labels and title.
"""
# Set the title
self.set_title('Feature Importances of {} Features using {}'.format(
len(self.features_), self.name))
# Set the xlabel
self.ax.set_xlabel(self._ge... | Finalize the drawing setting labels and title. | Below is the the instruction that describes the task:
### Input:
Finalize the drawing setting labels and title.
### Response:
def finalize(self, **kwargs):
"""
Finalize the drawing setting labels and title.
"""
# Set the title
self.set_title('Feature Importances of {} Featur... |
def is_mixed_script(string, allowed_aliases=['COMMON']):
"""Checks if ``string`` contains mixed-scripts content, excluding script
blocks aliases in ``allowed_aliases``.
E.g. ``B. C`` is not considered mixed-scripts by default: it contains characters
from **Latin** and **Common**, but **Common** is excl... | Checks if ``string`` contains mixed-scripts content, excluding script
blocks aliases in ``allowed_aliases``.
E.g. ``B. C`` is not considered mixed-scripts by default: it contains characters
from **Latin** and **Common**, but **Common** is excluded by default.
>>> confusables.is_mixed_script('Abç')
... | Below is the the instruction that describes the task:
### Input:
Checks if ``string`` contains mixed-scripts content, excluding script
blocks aliases in ``allowed_aliases``.
E.g. ``B. C`` is not considered mixed-scripts by default: it contains characters
from **Latin** and **Common**, but **Common** is... |
def calculate_connvectivity_radius(self, amount_clusters, maximum_iterations = 100):
"""!
@brief Calculates connectivity radius of allocation specified amount of clusters using ordering diagram and marks borders of clusters using indexes of values of ordering diagram.
@details Parameter 'maxi... | !
@brief Calculates connectivity radius of allocation specified amount of clusters using ordering diagram and marks borders of clusters using indexes of values of ordering diagram.
@details Parameter 'maximum_iterations' is used to protect from hanging when it is impossible to allocate specified numbe... | Below is the the instruction that describes the task:
### Input:
!
@brief Calculates connectivity radius of allocation specified amount of clusters using ordering diagram and marks borders of clusters using indexes of values of ordering diagram.
@details Parameter 'maximum_iterations' is used to p... |
def parse(self, data):
"""
Split and iterate through the datafile to extract genres, tags
and points.
"""
categories = data.split("\n\n")
reference = {}
reference_points = {}
genre_index = []
tag_index = []
for category in categories:
... | Split and iterate through the datafile to extract genres, tags
and points. | Below is the the instruction that describes the task:
### Input:
Split and iterate through the datafile to extract genres, tags
and points.
### Response:
def parse(self, data):
"""
Split and iterate through the datafile to extract genres, tags
and points.
"""
catego... |
def _prepare_args_with_initial_simplex(objective_function,
initial_simplex,
objective_at_initial_simplex,
batch_evaluate_objective):
"""Evaluates the objective function at the specified initial simplex... | Evaluates the objective function at the specified initial simplex. | Below is the the instruction that describes the task:
### Input:
Evaluates the objective function at the specified initial simplex.
### Response:
def _prepare_args_with_initial_simplex(objective_function,
initial_simplex,
objective_at_in... |
def cast_to_list(position):
"""Cast the positional argument at given position into a list if not already a list."""
@wrapt.decorator
def wrapper(function, instance, args, kwargs):
if not isinstance(args[position], list):
args = list(args)
args[position] = [args[position]]
args = tuple(args)
return fun... | Cast the positional argument at given position into a list if not already a list. | Below is the the instruction that describes the task:
### Input:
Cast the positional argument at given position into a list if not already a list.
### Response:
def cast_to_list(position):
"""Cast the positional argument at given position into a list if not already a list."""
@wrapt.decorator
def wrapper(funct... |
def findSequenceOnDisk(cls, pattern, strictPadding=False):
"""
Search for a specific sequence on disk.
The padding characters used in the `pattern` are used to filter the
frame values of the files on disk (if `strictPadding` is True).
Examples:
Find sequence matchin... | Search for a specific sequence on disk.
The padding characters used in the `pattern` are used to filter the
frame values of the files on disk (if `strictPadding` is True).
Examples:
Find sequence matching basename and extension, and a wildcard for
any frame.
... | Below is the the instruction that describes the task:
### Input:
Search for a specific sequence on disk.
The padding characters used in the `pattern` are used to filter the
frame values of the files on disk (if `strictPadding` is True).
Examples:
Find sequence matching basename... |
def do_GET(self):
"""Handles a GET request."""
thread_local.clock_start = get_time()
thread_local.status_code = 200
thread_local.message = None
thread_local.headers = []
thread_local.end_headers = []
thread_local.size = -1
thread_local.method = 'GET'
... | Handles a GET request. | Below is the the instruction that describes the task:
### Input:
Handles a GET request.
### Response:
def do_GET(self):
"""Handles a GET request."""
thread_local.clock_start = get_time()
thread_local.status_code = 200
thread_local.message = None
thread_local.headers = []
... |
def get_header_guard_dmlc(filename):
"""Get Header Guard Convention for DMLC Projects.
For headers in include, directly use the path
For headers in src, use project name plus path
Examples: with project-name = dmlc
include/dmlc/timer.h -> DMLC_TIMTER_H_
src/io/libsvm_parser.h -> DMLC_IO_... | Get Header Guard Convention for DMLC Projects.
For headers in include, directly use the path
For headers in src, use project name plus path
Examples: with project-name = dmlc
include/dmlc/timer.h -> DMLC_TIMTER_H_
src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_ | Below is the the instruction that describes the task:
### Input:
Get Header Guard Convention for DMLC Projects.
For headers in include, directly use the path
For headers in src, use project name plus path
Examples: with project-name = dmlc
include/dmlc/timer.h -> DMLC_TIMTER_H_
src/io/li... |
def login():
"""View function for login view"""
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_class(request.form)
if form.validate_on_submit():
login_user(form.user, remember=form.remember.data)
... | View function for login view | Below is the the instruction that describes the task:
### Input:
View function for login view
### Response:
def login():
"""View function for login view"""
form_class = _security.login_form
if request.is_json:
form = form_class(MultiDict(request.get_json()))
else:
form = form_clas... |
def declare_queue(self, queue_name):
"""Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue.
"""
if queue_name not in self.queues:
self.emit_before("declare_queue",... | Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue. | Below is the the instruction that describes the task:
### Input:
Declare a queue. Has no effect if a queue with the given
name has already been declared.
Parameters:
queue_name(str): The name of the new queue.
### Response:
def declare_queue(self, queue_name):
"""Declare a queue... |
def scramble_mutation(random, candidate, args):
"""Return the mutants created by scramble mutation on the candidates.
This function performs scramble mutation. It randomly chooses two
locations along the candidate and scrambles the values within that
slice.
.. Arguments:
random -- the rand... | Return the mutants created by scramble mutation on the candidates.
This function performs scramble mutation. It randomly chooses two
locations along the candidate and scrambles the values within that
slice.
.. Arguments:
random -- the random number generator object
candidate -- the cand... | Below is the the instruction that describes the task:
### Input:
Return the mutants created by scramble mutation on the candidates.
This function performs scramble mutation. It randomly chooses two
locations along the candidate and scrambles the values within that
slice.
.. Arguments:
rand... |
def find_blocked_biomass_precursors(reaction, model):
"""
Return a list of all biomass precursors that cannot be produced.
Parameters
----------
reaction : cobra.core.reaction.Reaction
The biomass reaction of the model under investigation.
model : cobra.Model
The metabolic model... | Return a list of all biomass precursors that cannot be produced.
Parameters
----------
reaction : cobra.core.reaction.Reaction
The biomass reaction of the model under investigation.
model : cobra.Model
The metabolic model under investigation.
Returns
-------
list
Me... | Below is the the instruction that describes the task:
### Input:
Return a list of all biomass precursors that cannot be produced.
Parameters
----------
reaction : cobra.core.reaction.Reaction
The biomass reaction of the model under investigation.
model : cobra.Model
The metabolic mo... |
def console_print_rect(
con: tcod.console.Console, x: int, y: int, w: int, h: int, fmt: str
) -> int:
"""Print a string constrained to a rectangle.
If h > 0 and the bottom of the rectangle is reached,
the string is truncated. If h = 0,
the string is only truncated if it reaches the bottom of the co... | Print a string constrained to a rectangle.
If h > 0 and the bottom of the rectangle is reached,
the string is truncated. If h = 0,
the string is only truncated if it reaches the bottom of the console.
Returns:
int: The number of lines of text once word-wrapped.
.. deprecated:: 8.5
... | Below is the the instruction that describes the task:
### Input:
Print a string constrained to a rectangle.
If h > 0 and the bottom of the rectangle is reached,
the string is truncated. If h = 0,
the string is only truncated if it reaches the bottom of the console.
Returns:
int: The numb... |
def list_to_json(source_list):
"""
Serialise all the items in source_list to json
"""
result = []
for item in source_list:
result.append(item.to_json())
return result | Serialise all the items in source_list to json | Below is the the instruction that describes the task:
### Input:
Serialise all the items in source_list to json
### Response:
def list_to_json(source_list):
"""
Serialise all the items in source_list to json
"""
result = []
for item in source_list:
result.append(item.to_json())
retu... |
def plot(self, overlay=True, **labels): # pragma: no cover
'''Plot all time series in the group.'''
pylab = LazyImport.pylab()
colours = list('rgbymc')
colours_len = len(colours)
colours_pos = 0
plots = len(self.groups)
for name, series in self.groups.iteritems():... | Plot all time series in the group. | Below is the the instruction that describes the task:
### Input:
Plot all time series in the group.
### Response:
def plot(self, overlay=True, **labels): # pragma: no cover
'''Plot all time series in the group.'''
pylab = LazyImport.pylab()
colours = list('rgbymc')
colours_len = len... |
def _update_mean_coords(self, dig, N, centers_sum, **paircoords):
"""
Update the mean coordinate sums
"""
if N is None or centers_sum is None: return
N.flat[:] += utils.bincount(dig, 1., minlength=N.size)
for i, dim in enumerate(self.dims):
size = centers_sum... | Update the mean coordinate sums | Below is the the instruction that describes the task:
### Input:
Update the mean coordinate sums
### Response:
def _update_mean_coords(self, dig, N, centers_sum, **paircoords):
"""
Update the mean coordinate sums
"""
if N is None or centers_sum is None: return
N.flat[:] += ... |
def on_stop(self):
"""
stop requester
"""
LOGGER.debug("natsd.Requester.on_stop")
self.is_started = False
try:
LOGGER.debug("natsd.Requester.on_stop - unsubscribe from " + str(self.responseQS))
next(self.nc.unsubscribe(self.responseQS))
exc... | stop requester | Below is the the instruction that describes the task:
### Input:
stop requester
### Response:
def on_stop(self):
"""
stop requester
"""
LOGGER.debug("natsd.Requester.on_stop")
self.is_started = False
try:
LOGGER.debug("natsd.Requester.on_stop - unsubscrib... |
def wait_displayed(element, timeout=None, fail_on_timeout=None):
"""
Wait until element becomes visible or time out.
Returns true is element became visible, otherwise false.
If timeout is not specified or 0, then uses specific element wait timeout.
:param element:
:param timeout:
:param fail... | Wait until element becomes visible or time out.
Returns true is element became visible, otherwise false.
If timeout is not specified or 0, then uses specific element wait timeout.
:param element:
:param timeout:
:param fail_on_timeout:
:return: | Below is the the instruction that describes the task:
### Input:
Wait until element becomes visible or time out.
Returns true is element became visible, otherwise false.
If timeout is not specified or 0, then uses specific element wait timeout.
:param element:
:param timeout:
:param fail_on_time... |
def read_inquiry_scan_activity(sock):
"""returns the current inquiry scan interval and window,
or -1 on failure"""
# save current filter
old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
# Setup socket filter to receive only events related to the
# read_inquiry_mode command
... | returns the current inquiry scan interval and window,
or -1 on failure | Below is the the instruction that describes the task:
### Input:
returns the current inquiry scan interval and window,
or -1 on failure
### Response:
def read_inquiry_scan_activity(sock):
"""returns the current inquiry scan interval and window,
or -1 on failure"""
# save current filter
old_fi... |
def remap_snps(self, individual, target_assembly, complement_bases=True):
""" Remap the SNP coordinates of an individual from one assembly to another.
This method uses the assembly map endpoint of the Ensembl REST API service (via
``Resources``'s ``EnsemblRestClient``) to convert SNP coordinate... | Remap the SNP coordinates of an individual from one assembly to another.
This method uses the assembly map endpoint of the Ensembl REST API service (via
``Resources``'s ``EnsemblRestClient``) to convert SNP coordinates / positions from one
assembly to another. After remapping, the coordinates /... | Below is the the instruction that describes the task:
### Input:
Remap the SNP coordinates of an individual from one assembly to another.
This method uses the assembly map endpoint of the Ensembl REST API service (via
``Resources``'s ``EnsemblRestClient``) to convert SNP coordinates / positions fro... |
def check_candidate(a, d, n, s):
"""Part of the Miller-Rabin primality test in is_prime()."""
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
return True | Part of the Miller-Rabin primality test in is_prime(). | Below is the the instruction that describes the task:
### Input:
Part of the Miller-Rabin primality test in is_prime().
### Response:
def check_candidate(a, d, n, s):
"""Part of the Miller-Rabin primality test in is_prime()."""
if pow(a, d, n) == 1:
return False
for i in range(s):
if po... |
def index(self, key, start=None, stop=None):
"""
Return the smallest *k* such that `itemssview[k] == key` and `start <= k
< end`. Raises `KeyError` if *key* is not present. *stop* defaults
to the end of the set. *start* defaults to the beginning. Negative
indexes are supporte... | Return the smallest *k* such that `itemssview[k] == key` and `start <= k
< end`. Raises `KeyError` if *key* is not present. *stop* defaults
to the end of the set. *start* defaults to the beginning. Negative
indexes are supported, as for slice indices. | Below is the the instruction that describes the task:
### Input:
Return the smallest *k* such that `itemssview[k] == key` and `start <= k
< end`. Raises `KeyError` if *key* is not present. *stop* defaults
to the end of the set. *start* defaults to the beginning. Negative
indexes are supp... |
def keep_alive(self):
'''
Keep current transaction alive, updates self.expires
Args:
None
Return:
None: sets new self.expires
'''
# keep transaction alive
txn_response = self.api.http_request('POST','%sfcr:tx' % self.root, data=None, headers=None)
# if 204, transaction kept alive
if txn_res... | Keep current transaction alive, updates self.expires
Args:
None
Return:
None: sets new self.expires | Below is the the instruction that describes the task:
### Input:
Keep current transaction alive, updates self.expires
Args:
None
Return:
None: sets new self.expires
### Response:
def keep_alive(self):
'''
Keep current transaction alive, updates self.expires
Args:
None
Return:
None: set... |
def _set_openflow_controller(self, v, load=False):
"""
Setter method for openflow_controller, mapped from YANG variable /openflow_controller (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_openflow_controller is considered as a private
method. Backends looking... | Setter method for openflow_controller, mapped from YANG variable /openflow_controller (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_openflow_controller is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj... | Below is the the instruction that describes the task:
### Input:
Setter method for openflow_controller, mapped from YANG variable /openflow_controller (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_openflow_controller is considered as a private
method. Backends l... |
def notify(self, value):
"""Add a new observation to the metric"""
with self.lock:
#TODO: this could slow down slow-rate incoming updates
# since the number of ticks depends on the actual time
# passed since the latest notification. Consider using
# a rea... | Add a new observation to the metric | Below is the the instruction that describes the task:
### Input:
Add a new observation to the metric
### Response:
def notify(self, value):
"""Add a new observation to the metric"""
with self.lock:
#TODO: this could slow down slow-rate incoming updates
# since the number of... |
def step_amp(self):
"""
Change the amplitude according to the change rate and drift target.
Returns: None
"""
difference = self.drift_target - self._raw_value
if abs(difference) < self.change_rate:
self.value = self.drift_target
else:
delt... | Change the amplitude according to the change rate and drift target.
Returns: None | Below is the the instruction that describes the task:
### Input:
Change the amplitude according to the change rate and drift target.
Returns: None
### Response:
def step_amp(self):
"""
Change the amplitude according to the change rate and drift target.
Returns: None
"""
... |
def expand_variables(self):
"""
Expand variables in the task code.
Only variables who use the $[<variable name>] format are expanded.
Variables using the $<variable name> and ${<variable name>} formats
are expanded by the shell (in the cases where bash is the interpreter.
... | Expand variables in the task code.
Only variables who use the $[<variable name>] format are expanded.
Variables using the $<variable name> and ${<variable name>} formats
are expanded by the shell (in the cases where bash is the interpreter. | Below is the the instruction that describes the task:
### Input:
Expand variables in the task code.
Only variables who use the $[<variable name>] format are expanded.
Variables using the $<variable name> and ${<variable name>} formats
are expanded by the shell (in the cases where bash is the... |
def get_file_from_iso(self, local_path, **kwargs):
# type: (str, Any) -> None
'''
A method to fetch a single file from the ISO and write it out
to a local file.
Parameters:
local_path - The local file to write to.
blocksize - The number of bytes in each transfe... | A method to fetch a single file from the ISO and write it out
to a local file.
Parameters:
local_path - The local file to write to.
blocksize - The number of bytes in each transfer.
iso_path - The absolute ISO9660 path to lookup on the ISO (exclusive
with ... | Below is the the instruction that describes the task:
### Input:
A method to fetch a single file from the ISO and write it out
to a local file.
Parameters:
local_path - The local file to write to.
blocksize - The number of bytes in each transfer.
iso_path - The absolute I... |
def datetime_is_iso(date_str):
"""Attempts to parse a date formatted in ISO 8601 format"""
try:
if len(date_str) > 10:
dt = isodate.parse_datetime(date_str)
else:
dt = isodate.parse_date(date_str)
return True, []
except: # Any error qualifies as not ISO forma... | Attempts to parse a date formatted in ISO 8601 format | Below is the the instruction that describes the task:
### Input:
Attempts to parse a date formatted in ISO 8601 format
### Response:
def datetime_is_iso(date_str):
"""Attempts to parse a date formatted in ISO 8601 format"""
try:
if len(date_str) > 10:
dt = isodate.parse_datetime(date_st... |
def calcontime(data, inds=None):
""" Given indices of good times, calculate total time per scan with indices. """
if not inds:
inds = range(len(data['time']))
logger.info('No indices provided. Assuming all are valid.')
scans = set([data['scan'][i] for i in inds])
total = 0.
for sca... | Given indices of good times, calculate total time per scan with indices. | Below is the the instruction that describes the task:
### Input:
Given indices of good times, calculate total time per scan with indices.
### Response:
def calcontime(data, inds=None):
""" Given indices of good times, calculate total time per scan with indices. """
if not inds:
inds = range(len(da... |
def _set_bundle_message(self, v, load=False):
"""
Setter method for bundle_message, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/interface_refresh_reduction/bundle_message (container)
If this variable is read-only (config: false) in the
source YANG file, then _... | Setter method for bundle_message, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/interface_refresh_reduction/bundle_message (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_bundle_message is considered as a private
method. ... | Below is the the instruction that describes the task:
### Input:
Setter method for bundle_message, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/rsvp/interface_refresh_reduction/bundle_message (container)
If this variable is read-only (config: false) in the
source YANG f... |
def warm_night_frequency(tasmin, thresh='22 degC', freq='YS'):
r"""Frequency of extreme warm nights
Return the number of days with tasmin > thresh per period
Parameters
----------
tasmin : xarray.DataArray
Minimum daily temperature [℃] or [K]
thresh : str
Threshold temperature on w... | r"""Frequency of extreme warm nights
Return the number of days with tasmin > thresh per period
Parameters
----------
tasmin : xarray.DataArray
Minimum daily temperature [℃] or [K]
thresh : str
Threshold temperature on which to base evaluation [℃] or [K]. Default : '22 degC'
freq : ... | Below is the the instruction that describes the task:
### Input:
r"""Frequency of extreme warm nights
Return the number of days with tasmin > thresh per period
Parameters
----------
tasmin : xarray.DataArray
Minimum daily temperature [℃] or [K]
thresh : str
Threshold temperature on... |
def store_hash_configuration(self, lshash):
"""
Stores hash configuration
"""
self.mongo_object.insert_one(
{'hash_conf_name': lshash.hash_name+'_conf',
'hash_configuration': pickle.dumps(lshash.get_config())
}
) | Stores hash configuration | Below is the the instruction that describes the task:
### Input:
Stores hash configuration
### Response:
def store_hash_configuration(self, lshash):
"""
Stores hash configuration
"""
self.mongo_object.insert_one(
{'hash_conf_name': lshash.hash_name+'_conf',
... |
def switch(template, version):
"""
Switch a project's template to a different template.
"""
temple.update.update(new_template=template, new_version=version) | Switch a project's template to a different template. | Below is the the instruction that describes the task:
### Input:
Switch a project's template to a different template.
### Response:
def switch(template, version):
"""
Switch a project's template to a different template.
"""
temple.update.update(new_template=template, new_version=version) |
def compose_projects_json(projects, data):
""" Compose projects.json with all data sources
:param projects: projects.json
:param data: eclipse JSON
:return: projects.json with all data sources
"""
projects = compose_git(projects, data)
projects = compose_mailing_lists(projects, data)
pr... | Compose projects.json with all data sources
:param projects: projects.json
:param data: eclipse JSON
:return: projects.json with all data sources | Below is the the instruction that describes the task:
### Input:
Compose projects.json with all data sources
:param projects: projects.json
:param data: eclipse JSON
:return: projects.json with all data sources
### Response:
def compose_projects_json(projects, data):
""" Compose projects.json with... |
def sink(self, name, filter_=None, destination=None):
"""Creates a sink bound to the current client.
:type name: str
:param name: the name of the sink to be constructed.
:type filter_: str
:param filter_: (optional) the advanced logs filter expression
de... | Creates a sink bound to the current client.
:type name: str
:param name: the name of the sink to be constructed.
:type filter_: str
:param filter_: (optional) the advanced logs filter expression
defining the entries exported by the sink. If not
... | Below is the the instruction that describes the task:
### Input:
Creates a sink bound to the current client.
:type name: str
:param name: the name of the sink to be constructed.
:type filter_: str
:param filter_: (optional) the advanced logs filter expression
... |
def bind(self, database):
"""Associate the pool with a database.
:type database: :class:`~google.cloud.spanner_v1.database.Database`
:param database: database used by the pool: used to create sessions
when needed.
"""
self._database = database
... | Associate the pool with a database.
:type database: :class:`~google.cloud.spanner_v1.database.Database`
:param database: database used by the pool: used to create sessions
when needed. | Below is the the instruction that describes the task:
### Input:
Associate the pool with a database.
:type database: :class:`~google.cloud.spanner_v1.database.Database`
:param database: database used by the pool: used to create sessions
when needed.
### Response:
def bind... |
def unlock(self):
"""
Unlock the table(s)
"""
cursor = connection.cursor()
cursor.execute("UNLOCK TABLES")
logger.debug('Unlocked tables')
row = cursor.fetchone()
return row | Unlock the table(s) | Below is the the instruction that describes the task:
### Input:
Unlock the table(s)
### Response:
def unlock(self):
"""
Unlock the table(s)
"""
cursor = connection.cursor()
cursor.execute("UNLOCK TABLES")
logger.debug('Unlocked tables')
row = cursor.fetchone... |
def dump_file(self, value, relativePath,
description=None,
dump=None, pull=None,
replace=False, raiseError=True, ntrials=3):
"""
Dump a file using its value to the system and creates its
attribute in the Repository with utc ... | Dump a file using its value to the system and creates its
attribute in the Repository with utc timestamp.
:Parameters:
#. value (object): The value of a file to dump and add to the
repository. It is any python object or file.
#. relativePath (str): The relative to... | Below is the the instruction that describes the task:
### Input:
Dump a file using its value to the system and creates its
attribute in the Repository with utc timestamp.
:Parameters:
#. value (object): The value of a file to dump and add to the
repository. It is any pyth... |
def stop(cls):
"""Change back the normal stdout after the end"""
if any(cls.streams):
sys.stdout = cls.streams.pop(-1)
else:
sys.stdout = sys.__stdout__ | Change back the normal stdout after the end | Below is the the instruction that describes the task:
### Input:
Change back the normal stdout after the end
### Response:
def stop(cls):
"""Change back the normal stdout after the end"""
if any(cls.streams):
sys.stdout = cls.streams.pop(-1)
else:
sys.stdout = sys.__... |
def connectdown(np, p, acc, outlet, wtsd=None, workingdir=None, mpiexedir=None,
exedir=None, log_file=None, runtime_file=None, hostfile=None):
"""Reads an ad8 contributing area file,
identifies the location of the largest ad8 value as the outlet of the largest watershed"""
# ... | Reads an ad8 contributing area file,
identifies the location of the largest ad8 value as the outlet of the largest watershed | Below is the the instruction that describes the task:
### Input:
Reads an ad8 contributing area file,
identifies the location of the largest ad8 value as the outlet of the largest watershed
### Response:
def connectdown(np, p, acc, outlet, wtsd=None, workingdir=None, mpiexedir=None,
exe... |
def query_nds2(cls, name, host=None, port=None, connection=None,
type=None):
"""Query an NDS server for channel information
Parameters
----------
name : `str`
name of requested channel
host : `str`, optional
name of NDS2 server.
... | Query an NDS server for channel information
Parameters
----------
name : `str`
name of requested channel
host : `str`, optional
name of NDS2 server.
port : `int`, optional
port number for NDS2 connection
connection : `nds2.connection`
... | Below is the the instruction that describes the task:
### Input:
Query an NDS server for channel information
Parameters
----------
name : `str`
name of requested channel
host : `str`, optional
name of NDS2 server.
port : `int`, optional
po... |
def shift(self, h=0, m=0, s=0, ms=0, frames=None, fps=None):
"""
Shift start and end times.
See :meth:`SSAFile.shift()` for full description.
"""
delta = make_time(h=h, m=m, s=s, ms=ms, frames=frames, fps=fps)
self.start += delta
self.end += delta | Shift start and end times.
See :meth:`SSAFile.shift()` for full description. | Below is the the instruction that describes the task:
### Input:
Shift start and end times.
See :meth:`SSAFile.shift()` for full description.
### Response:
def shift(self, h=0, m=0, s=0, ms=0, frames=None, fps=None):
"""
Shift start and end times.
See :meth:`SSAFile.shift()` for f... |
def _write_weight_histograms(self, iteration:int)->None:
"Writes model weight histograms to Tensorboard."
self.hist_writer.write(model=self.learn.model, iteration=iteration, tbwriter=self.tbwriter) | Writes model weight histograms to Tensorboard. | Below is the the instruction that describes the task:
### Input:
Writes model weight histograms to Tensorboard.
### Response:
def _write_weight_histograms(self, iteration:int)->None:
"Writes model weight histograms to Tensorboard."
self.hist_writer.write(model=self.learn.model, iteration=iteration,... |
def exit_code_from_run_infos(run_infos: t.List[RunInfo]) -> int:
"""Generate a single exit code from a list of RunInfo objects.
Takes a list of RunInfos and returns the exit code that is furthest away
from 0.
Args:
run_infos (t.List[RunInfo]): [description]
Returns:
int: [descript... | Generate a single exit code from a list of RunInfo objects.
Takes a list of RunInfos and returns the exit code that is furthest away
from 0.
Args:
run_infos (t.List[RunInfo]): [description]
Returns:
int: [description] | Below is the the instruction that describes the task:
### Input:
Generate a single exit code from a list of RunInfo objects.
Takes a list of RunInfos and returns the exit code that is furthest away
from 0.
Args:
run_infos (t.List[RunInfo]): [description]
Returns:
int: [description... |
def insert(self, table_name, rows, fields=None, delimiter=None, null='NULL', parse_dates=False, quotechar='"'):
"""
Load a text file into the specified :code:`table_name` or Insert Python :code:`list` rows into the specified :code:`table_name`
:param str table_name: The name of the destination ... | Load a text file into the specified :code:`table_name` or Insert Python :code:`list` rows into the specified :code:`table_name`
:param str table_name: The name of the destination table
:param list/str rows: A list of rows **or** the name of an input file. Each row
must be a :code:`list` of ... | Below is the the instruction that describes the task:
### Input:
Load a text file into the specified :code:`table_name` or Insert Python :code:`list` rows into the specified :code:`table_name`
:param str table_name: The name of the destination table
:param list/str rows: A list of rows **or** the n... |
def purge_metadata(self, force=False):
"""Instance-based version of ProcessMetadataManager.purge_metadata_by_name() that checks
for process liveness before purging metadata.
:param bool force: If True, skip process liveness check before purging metadata.
:raises: `ProcessManager.MetadataError` when OSE... | Instance-based version of ProcessMetadataManager.purge_metadata_by_name() that checks
for process liveness before purging metadata.
:param bool force: If True, skip process liveness check before purging metadata.
:raises: `ProcessManager.MetadataError` when OSError is encountered on metadata dir removal. | Below is the the instruction that describes the task:
### Input:
Instance-based version of ProcessMetadataManager.purge_metadata_by_name() that checks
for process liveness before purging metadata.
:param bool force: If True, skip process liveness check before purging metadata.
:raises: `ProcessManager.... |
def xstep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`.
"""
ngsit = 0
gsrrs = np.inf
while gsrrs > self.opt['GSTol'] and ngsit < self.opt['MaxGSIter']:
self.X = self.GaussSeidelStep(self.S, self.X,
... | r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`. | Below is the the instruction that describes the task:
### Input:
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`.
### Response:
def xstep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{x}`.
"""
ngsit = 0
gsrrs = np.inf
... |
def detect_lang(path):
"""Detect the language used in the given file."""
blob = FileBlob(path, os.getcwd())
if blob.is_text:
print('Programming language of the file detected: {0}'.format(blob.language.name))
return blob.language.name
else:#images, binary and what-have-you won't be pasted
print('File not a tex... | Detect the language used in the given file. | Below is the the instruction that describes the task:
### Input:
Detect the language used in the given file.
### Response:
def detect_lang(path):
"""Detect the language used in the given file."""
blob = FileBlob(path, os.getcwd())
if blob.is_text:
print('Programming language of the file detected: {0}'.format(... |
def geodetic_to_ecef(latitude, longitude, altitude):
"""Convert WGS84 geodetic coordinates into ECEF
Parameters
----------
latitude : float or array_like
Geodetic latitude (degrees)
longitude : float or array_like
Geodetic longitude (degrees)
altitude : float or array_like
... | Convert WGS84 geodetic coordinates into ECEF
Parameters
----------
latitude : float or array_like
Geodetic latitude (degrees)
longitude : float or array_like
Geodetic longitude (degrees)
altitude : float or array_like
Geodetic Height (km) above WGS84 reference ellipsoid.... | Below is the the instruction that describes the task:
### Input:
Convert WGS84 geodetic coordinates into ECEF
Parameters
----------
latitude : float or array_like
Geodetic latitude (degrees)
longitude : float or array_like
Geodetic longitude (degrees)
altitude : float or arr... |
def clean_comment_body(body):
"""Returns given comment HTML as plaintext.
Converts all HTML tags and entities within 4chan comments
into human-readable text equivalents.
"""
body = _parser.unescape(body)
body = re.sub(r'<a [^>]+>(.+?)</a>', r'\1', body)
body = body.replace('<br>', '\n')
... | Returns given comment HTML as plaintext.
Converts all HTML tags and entities within 4chan comments
into human-readable text equivalents. | Below is the the instruction that describes the task:
### Input:
Returns given comment HTML as plaintext.
Converts all HTML tags and entities within 4chan comments
into human-readable text equivalents.
### Response:
def clean_comment_body(body):
"""Returns given comment HTML as plaintext.
Convert... |
async def activate_scene(self, scene_id: int):
"""Activate a scene
:param scene_id: Scene id.
:return:
"""
_scene = await self.get_scene(scene_id)
await _scene.activate() | Activate a scene
:param scene_id: Scene id.
:return: | Below is the the instruction that describes the task:
### Input:
Activate a scene
:param scene_id: Scene id.
:return:
### Response:
async def activate_scene(self, scene_id: int):
"""Activate a scene
:param scene_id: Scene id.
:return:
"""
_scene = await se... |
def add_route(self, route):
''' Add a route object, but do not change the :data:`Route.app`
attribute.'''
self.routes.append(route)
self.router.add(route.rule, route.method, route, name=route.name)
if DEBUG: route.prepare() | Add a route object, but do not change the :data:`Route.app`
attribute. | Below is the the instruction that describes the task:
### Input:
Add a route object, but do not change the :data:`Route.app`
attribute.
### Response:
def add_route(self, route):
''' Add a route object, but do not change the :data:`Route.app`
attribute.'''
self.routes.append(... |
def set_traindata(self, training_rdd, batch_size):
"""
Set new training dataset, for optimizer reuse
:param training_rdd: the training dataset
:param batch_size: training batch size
:return:
"""
callBigDlFunc(self.bigdl_type, "setTrainData", self.value,
... | Set new training dataset, for optimizer reuse
:param training_rdd: the training dataset
:param batch_size: training batch size
:return: | Below is the the instruction that describes the task:
### Input:
Set new training dataset, for optimizer reuse
:param training_rdd: the training dataset
:param batch_size: training batch size
:return:
### Response:
def set_traindata(self, training_rdd, batch_size):
"""
Set ... |
def _deserialize_encrypted_data_keys(stream):
# type: (IO) -> Set[EncryptedDataKey]
"""Deserialize some encrypted data keys from a stream.
:param stream: Stream from which to read encrypted data keys
:return: Loaded encrypted data keys
:rtype: set of :class:`EncryptedDataKey`
"""
(encrypted... | Deserialize some encrypted data keys from a stream.
:param stream: Stream from which to read encrypted data keys
:return: Loaded encrypted data keys
:rtype: set of :class:`EncryptedDataKey` | Below is the the instruction that describes the task:
### Input:
Deserialize some encrypted data keys from a stream.
:param stream: Stream from which to read encrypted data keys
:return: Loaded encrypted data keys
:rtype: set of :class:`EncryptedDataKey`
### Response:
def _deserialize_encrypted_data_k... |
def visit_BoolOp(self, node):
'''
Resulting node may alias to either operands:
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a or b')
>>> result = pm.gather(Aliases, module)
>>> Aliases.... | Resulting node may alias to either operands:
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a or b')
>>> result = pm.gather(Aliases, module)
>>> Aliases.dump(result, filter=ast.BoolOp)
(a or b) =... | Below is the the instruction that describes the task:
### Input:
Resulting node may alias to either operands:
>>> from pythran import passmanager
>>> pm = passmanager.PassManager('demo')
>>> module = ast.parse('def foo(a, b): return a or b')
>>> result = pm.gather(Aliases, module)
... |
def checkerboard(img_spec1=None,
img_spec2=None,
patch_size=10,
view_set=(0, 1, 2),
num_slices=(10,),
num_rows=2,
rescale_method='global',
background_threshold=0.05,
annot=None,
... | Checkerboard mixer.
Parameters
----------
img_spec1 : str or nibabel image-like object
MR image (or path to one) to be visualized
img_spec2 : str or nibabel image-like object
MR image (or path to one) to be visualized
patch_size : int or list or (int, int) or None
size of ... | Below is the the instruction that describes the task:
### Input:
Checkerboard mixer.
Parameters
----------
img_spec1 : str or nibabel image-like object
MR image (or path to one) to be visualized
img_spec2 : str or nibabel image-like object
MR image (or path to one) to be visualized... |
def index(request, template_name="tagging_ext/index.html", min_size=0,limit=10):
"""
min_size: Smallest size count accepted for a tag
order_by: asc or desc by count
limit: maximum number of tags to display
TODO: convert the hand-written query to an ORM call. Right now I kno... | min_size: Smallest size count accepted for a tag
order_by: asc or desc by count
limit: maximum number of tags to display
TODO: convert the hand-written query to an ORM call. Right now I know
this works with Sqlite3 and PostGreSQL. | Below is the the instruction that describes the task:
### Input:
min_size: Smallest size count accepted for a tag
order_by: asc or desc by count
limit: maximum number of tags to display
TODO: convert the hand-written query to an ORM call. Right now I know
this works... |
def episodes(self):
"""Return a flat episode iterator.
:returns: Iterator :code:`((season_num, episode_num), Episode)`
:rtype: iterator
"""
for sk, season in iteritems(self.seasons):
# Yield each episode in season
for ek, episode in iteritems(season.epis... | Return a flat episode iterator.
:returns: Iterator :code:`((season_num, episode_num), Episode)`
:rtype: iterator | Below is the the instruction that describes the task:
### Input:
Return a flat episode iterator.
:returns: Iterator :code:`((season_num, episode_num), Episode)`
:rtype: iterator
### Response:
def episodes(self):
"""Return a flat episode iterator.
:returns: Iterator :code:`((season... |
def get(cls, attachment_public_uuid, custom_headers=None):
"""
Get a specific attachment's metadata through its UUID. The Content-Type
header of the response will describe the MIME type of the attachment
file.
:type api_context: context.ApiContext
:type attachment_public... | Get a specific attachment's metadata through its UUID. The Content-Type
header of the response will describe the MIME type of the attachment
file.
:type api_context: context.ApiContext
:type attachment_public_uuid: str
:type custom_headers: dict[str, str]|None
:rtype: B... | Below is the the instruction that describes the task:
### Input:
Get a specific attachment's metadata through its UUID. The Content-Type
header of the response will describe the MIME type of the attachment
file.
:type api_context: context.ApiContext
:type attachment_public_uuid: str... |
def _addupdate_hdxobject(self, hdxobjects, id_field, new_hdxobject):
# type: (List[HDXObjectUpperBound], str, HDXObjectUpperBound) -> HDXObjectUpperBound
"""Helper function to add a new HDX object to a supplied list of HDX objects or update existing metadata if the object
already exists in the l... | Helper function to add a new HDX object to a supplied list of HDX objects or update existing metadata if the object
already exists in the list
Args:
hdxobjects (List[T <= HDXObject]): list of HDX objects to which to add new objects or update existing ones
id_field (str): Field o... | Below is the the instruction that describes the task:
### Input:
Helper function to add a new HDX object to a supplied list of HDX objects or update existing metadata if the object
already exists in the list
Args:
hdxobjects (List[T <= HDXObject]): list of HDX objects to which to add ne... |
def make_repr(obj, params=None, keywords=None, data=None, name=None,
reprs=None):
"""Generates a string of object initialization code style. It is useful
for custom __repr__ methods::
class Example(object):
def __init__(self, param, keyword=None):
self.param = p... | Generates a string of object initialization code style. It is useful
for custom __repr__ methods::
class Example(object):
def __init__(self, param, keyword=None):
self.param = param
self.keyword = keyword
def __repr__(self):
return make_r... | Below is the the instruction that describes the task:
### Input:
Generates a string of object initialization code style. It is useful
for custom __repr__ methods::
class Example(object):
def __init__(self, param, keyword=None):
self.param = param
self.keyword =... |
def transmit_metrics(self):
"""
Keep metrics updated about how long time ago each filetype was successfully uploaded.
Transmits max once per ten seconds, regardless of how many threads are running.
"""
global _last_stats_transmit_time # pylint: disable=global-statement
w... | Keep metrics updated about how long time ago each filetype was successfully uploaded.
Transmits max once per ten seconds, regardless of how many threads are running. | Below is the the instruction that describes the task:
### Input:
Keep metrics updated about how long time ago each filetype was successfully uploaded.
Transmits max once per ten seconds, regardless of how many threads are running.
### Response:
def transmit_metrics(self):
"""
Keep metrics u... |
def dens_floc(ConcAl, ConcClay, DIM_FRACTAL, DiamTarget, coag, material, Temp):
"""Calculate floc density as a function of size."""
WaterDensity = pc.density_water(Temp).magnitude
return ((dens_floc_init(ConcAl, ConcClay, coag, material).magnitude
- WaterDensity
)
* (ma... | Calculate floc density as a function of size. | Below is the the instruction that describes the task:
### Input:
Calculate floc density as a function of size.
### Response:
def dens_floc(ConcAl, ConcClay, DIM_FRACTAL, DiamTarget, coag, material, Temp):
"""Calculate floc density as a function of size."""
WaterDensity = pc.density_water(Temp).magnitude
... |
def new(self, platform_id):
# type: (int) -> None
'''
A method to create a new El Torito Validation Entry.
Parameters:
platform_id - The platform ID to set for this validation entry.
Returns:
Nothing.
'''
if self._initialized:
raise ... | A method to create a new El Torito Validation Entry.
Parameters:
platform_id - The platform ID to set for this validation entry.
Returns:
Nothing. | Below is the the instruction that describes the task:
### Input:
A method to create a new El Torito Validation Entry.
Parameters:
platform_id - The platform ID to set for this validation entry.
Returns:
Nothing.
### Response:
def new(self, platform_id):
# type: (int) -> N... |
def compress_ranges_to_lists(self):
'''
Converts the internal dimension ranges on lists into
list of the restricted size. Thus all dimension rules
are applied to all dimensions of the list wrapper
and returned as a list (of lists).
'''
clist = []
for elem ... | Converts the internal dimension ranges on lists into
list of the restricted size. Thus all dimension rules
are applied to all dimensions of the list wrapper
and returned as a list (of lists). | Below is the the instruction that describes the task:
### Input:
Converts the internal dimension ranges on lists into
list of the restricted size. Thus all dimension rules
are applied to all dimensions of the list wrapper
and returned as a list (of lists).
### Response:
def compress_ranges_... |
def info(name, m, p, b, w, **kwargs):
"""
Show information about cocaine runtime.
Return json-like string with information about cocaine-runtime.
If the name option is not specified, shows information about all applications. Flags can be
specified for fine-grained control of the output verbosity.
... | Show information about cocaine runtime.
Return json-like string with information about cocaine-runtime.
If the name option is not specified, shows information about all applications. Flags can be
specified for fine-grained control of the output verbosity. | Below is the the instruction that describes the task:
### Input:
Show information about cocaine runtime.
Return json-like string with information about cocaine-runtime.
If the name option is not specified, shows information about all applications. Flags can be
specified for fine-grained control of the... |
def replace(self, year=None, month=None, day=None):
"""
Returns a new datetime.date or asn1crypto.util.extended_date
object with the specified components replaced
:return:
A datetime.date or asn1crypto.util.extended_date object
"""
if year is None:
... | Returns a new datetime.date or asn1crypto.util.extended_date
object with the specified components replaced
:return:
A datetime.date or asn1crypto.util.extended_date object | Below is the the instruction that describes the task:
### Input:
Returns a new datetime.date or asn1crypto.util.extended_date
object with the specified components replaced
:return:
A datetime.date or asn1crypto.util.extended_date object
### Response:
def replace(self, year=None, month=... |
def ds2p(self):
"""Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2)
"""
idx = [(x[0] + 2, x[1]) for x in self.df.index]
values = self.s2p.values - self.s2p.loc[idx].values
return Table(df=pd.Series(values, index=self.df.inde... | Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2) | Below is the the instruction that describes the task:
### Input:
Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2)
### Response:
def ds2p(self):
"""Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2)... |
def _do_request(
self, method, url, headers, data, target_object
): # pylint: disable=unused-argument
"""Low-level helper: perform the actual API request over HTTP.
Allows batch context managers to override and defer a request.
:type method: str
:param method: The HTTP me... | Low-level helper: perform the actual API request over HTTP.
Allows batch context managers to override and defer a request.
:type method: str
:param method: The HTTP method to use in the request.
:type url: str
:param url: The URL to send the request to.
:type headers... | Below is the the instruction that describes the task:
### Input:
Low-level helper: perform the actual API request over HTTP.
Allows batch context managers to override and defer a request.
:type method: str
:param method: The HTTP method to use in the request.
:type url: str
... |
def count(self, name=None, **attrs):
r"""Number of descendants matching criteria.
:param Union[None,str] name: name of LaTeX expression
:param attrs: LaTeX expression attributes, such as item text.
:return: number of matching expressions
:rtype: int
>>> from TexSoup imp... | r"""Number of descendants matching criteria.
:param Union[None,str] name: name of LaTeX expression
:param attrs: LaTeX expression attributes, such as item text.
:return: number of matching expressions
:rtype: int
>>> from TexSoup import TexSoup
>>> soup = TexSoup(r'''
... | Below is the the instruction that describes the task:
### Input:
r"""Number of descendants matching criteria.
:param Union[None,str] name: name of LaTeX expression
:param attrs: LaTeX expression attributes, such as item text.
:return: number of matching expressions
:rtype: int
... |
def decorator(cls, candidate, *exp_args, **exp_kwargs):
'''
Decorate a control function in order to conduct an experiment when called.
:param callable candidate: your candidate function
:param iterable exp_args: positional arguments passed to :class:`Experiment`
:param dict exp_... | Decorate a control function in order to conduct an experiment when called.
:param callable candidate: your candidate function
:param iterable exp_args: positional arguments passed to :class:`Experiment`
:param dict exp_kwargs: keyword arguments passed to :class:`Experiment`
Usage::
... | Below is the the instruction that describes the task:
### Input:
Decorate a control function in order to conduct an experiment when called.
:param callable candidate: your candidate function
:param iterable exp_args: positional arguments passed to :class:`Experiment`
:param dict exp_kwargs:... |
def send_command(self, *args, **kwargs):
"""Palo Alto requires an extra delay"""
kwargs["delay_factor"] = kwargs.get("delay_factor", 2.5)
return super(PaloAltoPanosBase, self).send_command(*args, **kwargs) | Palo Alto requires an extra delay | Below is the the instruction that describes the task:
### Input:
Palo Alto requires an extra delay
### Response:
def send_command(self, *args, **kwargs):
"""Palo Alto requires an extra delay"""
kwargs["delay_factor"] = kwargs.get("delay_factor", 2.5)
return super(PaloAltoPanosBase, self).se... |
def edit(self, id):
""" Edit a pool.
"""
c.pool = Pool.get(int(id))
c.prefix_list = Prefix.list({ 'pool_id': c.pool.id })
c.prefix = ''
# save changes to NIPAP
if request.method == 'POST':
c.pool.name = request.params['name']
c.pool.descr... | Edit a pool. | Below is the the instruction that describes the task:
### Input:
Edit a pool.
### Response:
def edit(self, id):
""" Edit a pool.
"""
c.pool = Pool.get(int(id))
c.prefix_list = Prefix.list({ 'pool_id': c.pool.id })
c.prefix = ''
# save changes to NIPAP
if re... |
def add_attachment(self, issue_id_or_key, temp_attachment_id, public=True, comment=None):
"""
Adds temporary attachment that were created using attach_temporary_file function to a customer request
:param issue_id_or_key: str
:param temp_attachment_id: str, ID from result attach_temporar... | Adds temporary attachment that were created using attach_temporary_file function to a customer request
:param issue_id_or_key: str
:param temp_attachment_id: str, ID from result attach_temporary_file function
:param public: bool (default is True)
:param comment: str (default is None)
... | Below is the the instruction that describes the task:
### Input:
Adds temporary attachment that were created using attach_temporary_file function to a customer request
:param issue_id_or_key: str
:param temp_attachment_id: str, ID from result attach_temporary_file function
:param public: bo... |
def combine(self, expert_out, multiply_by_gates=True):
"""Sum together the expert output, weighted by the gates.
The slice corresponding to a particular batch element `b` is computed
as the sum over all experts `i` of the expert output, weighted by the
corresponding gate values. If `multiply_by_gates`... | Sum together the expert output, weighted by the gates.
The slice corresponding to a particular batch element `b` is computed
as the sum over all experts `i` of the expert output, weighted by the
corresponding gate values. If `multiply_by_gates` is set to False, the
gate values are ignored.
Args:
... | Below is the the instruction that describes the task:
### Input:
Sum together the expert output, weighted by the gates.
The slice corresponding to a particular batch element `b` is computed
as the sum over all experts `i` of the expert output, weighted by the
corresponding gate values. If `multiply_by... |
def update_one(cls, filter, update, upsert=False):
"""
Updates a document that passes the filter with the update value
Will upsert a new document if upsert=True and no document is filtered
"""
return cls.collection.update_one(filter, update, upsert).raw_result | Updates a document that passes the filter with the update value
Will upsert a new document if upsert=True and no document is filtered | Below is the the instruction that describes the task:
### Input:
Updates a document that passes the filter with the update value
Will upsert a new document if upsert=True and no document is filtered
### Response:
def update_one(cls, filter, update, upsert=False):
"""
Updates a document that... |
def eval_policy(eval_positions):
"""Evaluate all positions with all models save the policy heatmaps as CSVs
CSV name is "heatmap-<position_name>-<model-index>.csv"
CSV format is: model number, value network output, policy network outputs
position_name is taken from the SGF file
Policy network outp... | Evaluate all positions with all models save the policy heatmaps as CSVs
CSV name is "heatmap-<position_name>-<model-index>.csv"
CSV format is: model number, value network output, policy network outputs
position_name is taken from the SGF file
Policy network outputs (19x19) are saved in flat order (see... | Below is the the instruction that describes the task:
### Input:
Evaluate all positions with all models save the policy heatmaps as CSVs
CSV name is "heatmap-<position_name>-<model-index>.csv"
CSV format is: model number, value network output, policy network outputs
position_name is taken from the SGF... |
def setup_consumers(self):
"""Iterate through each consumer in the configuration and kick off the
minimal amount of processes, setting up the runtime data as well.
"""
if not self.consumer_cfg:
LOGGER.warning('No consumers are configured')
for name in self.consumer_c... | Iterate through each consumer in the configuration and kick off the
minimal amount of processes, setting up the runtime data as well. | Below is the the instruction that describes the task:
### Input:
Iterate through each consumer in the configuration and kick off the
minimal amount of processes, setting up the runtime data as well.
### Response:
def setup_consumers(self):
"""Iterate through each consumer in the configuration and k... |
def get_enumeration(rq, v, endpoint, metadata={}, auth=None):
"""
Returns a list of enumerated values for variable 'v' in query 'rq'
"""
# glogger.debug("Metadata before processing enums: {}".format(metadata))
# We only fire the enum filling queries if indicated by the query metadata
if 'enumera... | Returns a list of enumerated values for variable 'v' in query 'rq' | Below is the the instruction that describes the task:
### Input:
Returns a list of enumerated values for variable 'v' in query 'rq'
### Response:
def get_enumeration(rq, v, endpoint, metadata={}, auth=None):
"""
Returns a list of enumerated values for variable 'v' in query 'rq'
"""
# glogger.debug(... |
def upload(cls, file_obj, store=None):
"""Uploads a file and returns ``File`` instance.
Args:
- file_obj: file object to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None.
- False - do not st... | Uploads a file and returns ``File`` instance.
Args:
- file_obj: file object to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None.
- False - do not store file
- True - store file (can ... | Below is the the instruction that describes the task:
### Input:
Uploads a file and returns ``File`` instance.
Args:
- file_obj: file object to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None.
... |
def line(self, *args):
"""
Called one at a time for each dataset
args are of the form::
<data set n line thickness>,
<length of line segment>,
<length of blank segment>
APIPARAM: chls
"""
self.lines.append(','.join(['%.1f'%x for x in ma... | Called one at a time for each dataset
args are of the form::
<data set n line thickness>,
<length of line segment>,
<length of blank segment>
APIPARAM: chls | Below is the the instruction that describes the task:
### Input:
Called one at a time for each dataset
args are of the form::
<data set n line thickness>,
<length of line segment>,
<length of blank segment>
APIPARAM: chls
### Response:
def line(self, *args):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.