code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def new_game(self):
"""Creates a new game of 2048."""
self.game = self.game_class(self, self.screen)
self.save() | Creates a new game of 2048. | Below is the the instruction that describes the task:
### Input:
Creates a new game of 2048.
### Response:
def new_game(self):
"""Creates a new game of 2048."""
self.game = self.game_class(self, self.screen)
self.save() |
def asArcPyObject(self):
""" returns the Point as an ESRI arcpy.Point object """
if arcpyFound == False:
raise Exception("ArcPy is required to use this function")
return arcpy.AsShape(self.asDictionary, True) | returns the Point as an ESRI arcpy.Point object | Below is the the instruction that describes the task:
### Input:
returns the Point as an ESRI arcpy.Point object
### Response:
def asArcPyObject(self):
""" returns the Point as an ESRI arcpy.Point object """
if arcpyFound == False:
raise Exception("ArcPy is required to use this function... |
def get_by_id(self, id_networkv6):
"""Get IPv6 network
:param id_networkv4: ID for NetworkIPv6
:return: IPv6 Network
"""
uri = 'api/networkv4/%s/' % id_networkv6
return super(ApiNetworkIPv6, self).get(uri) | Get IPv6 network
:param id_networkv4: ID for NetworkIPv6
:return: IPv6 Network | Below is the the instruction that describes the task:
### Input:
Get IPv6 network
:param id_networkv4: ID for NetworkIPv6
:return: IPv6 Network
### Response:
def get_by_id(self, id_networkv6):
"""Get IPv6 network
:param id_networkv4: ID for NetworkIPv6
:return: IPv6 Netw... |
def get_corresponding_lineno(self, lineno):
"""Return the source line number of a line number in the
generated bytecode as they are not in sync.
"""
for template_line, code_line in reversed(self.debug_info):
if code_line <= lineno:
return template_line
... | Return the source line number of a line number in the
generated bytecode as they are not in sync. | Below is the the instruction that describes the task:
### Input:
Return the source line number of a line number in the
generated bytecode as they are not in sync.
### Response:
def get_corresponding_lineno(self, lineno):
"""Return the source line number of a line number in the
generated byt... |
def rover_yaw_rate(VFR_HUD, SERVO_OUTPUT_RAW):
'''return yaw rate in degrees/second given steering_angle and speed'''
max_wheel_turn=35
speed = VFR_HUD.groundspeed
# assume 1100 to 1900 PWM on steering
steering_angle = max_wheel_turn * (SERVO_OUTPUT_RAW.servo1_raw - 1500) / 400.0
if abs(steering... | return yaw rate in degrees/second given steering_angle and speed | Below is the the instruction that describes the task:
### Input:
return yaw rate in degrees/second given steering_angle and speed
### Response:
def rover_yaw_rate(VFR_HUD, SERVO_OUTPUT_RAW):
'''return yaw rate in degrees/second given steering_angle and speed'''
max_wheel_turn=35
speed = VFR_HUD.grounds... |
def load(self, filename=None, ignore_discard=False, ignore_expires=False):
"""Load cookies from a file."""
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename)
try:
... | Load cookies from a file. | Below is the the instruction that describes the task:
### Input:
Load cookies from a file.
### Response:
def load(self, filename=None, ignore_discard=False, ignore_expires=False):
"""Load cookies from a file."""
if filename is None:
if self.filename is not None: filename = self.filename... |
def _indentLines(str, indentLevels = 1, indentFirstLine=True):
""" Indent all lines in the given string
str: input string
indentLevels: number of levels of indentation to apply
indentFirstLine: if False, the 1st line will not be indented
Returns: The result string with all lines indented
"""... | Indent all lines in the given string
str: input string
indentLevels: number of levels of indentation to apply
indentFirstLine: if False, the 1st line will not be indented
Returns: The result string with all lines indented | Below is the the instruction that describes the task:
### Input:
Indent all lines in the given string
str: input string
indentLevels: number of levels of indentation to apply
indentFirstLine: if False, the 1st line will not be indented
Returns: The result string with all lines indented
### R... |
def register_halfmaxes(self, telescope, band, lower, upper):
"""Register precomputed half-max points."""
if (telescope, band) in self._halfmaxes:
raise AlreadyDefinedError('half-max points for %s/%s already '
'defined', telescope, band)
self._no... | Register precomputed half-max points. | Below is the the instruction that describes the task:
### Input:
Register precomputed half-max points.
### Response:
def register_halfmaxes(self, telescope, band, lower, upper):
"""Register precomputed half-max points."""
if (telescope, band) in self._halfmaxes:
raise AlreadyDefinedErr... |
def cp_files(self, source, target, delete_source=False):
'''Copy files
This function can handle multiple files if source S3 URL has wildcard
characters. It also handles recursive mode by copying all files and
keep the directory structure.
'''
pool = ThreadPool(ThreadUtil, self.opt)
... | Copy files
This function can handle multiple files if source S3 URL has wildcard
characters. It also handles recursive mode by copying all files and
keep the directory structure. | Below is the the instruction that describes the task:
### Input:
Copy files
This function can handle multiple files if source S3 URL has wildcard
characters. It also handles recursive mode by copying all files and
keep the directory structure.
### Response:
def cp_files(self, source, target, d... |
def plot_roc_curve(self, on, bootstrap_samples=100, ax=None, **kwargs):
"""Plot an ROC curve for benefit and a given variable
Parameters
----------
on : str or function or list or dict
See `cohort.load.as_dataframe`
bootstrap_samples : int, optional
Numbe... | Plot an ROC curve for benefit and a given variable
Parameters
----------
on : str or function or list or dict
See `cohort.load.as_dataframe`
bootstrap_samples : int, optional
Number of boostrap samples to use to compute the AUC
ax : Axes, default None
... | Below is the the instruction that describes the task:
### Input:
Plot an ROC curve for benefit and a given variable
Parameters
----------
on : str or function or list or dict
See `cohort.load.as_dataframe`
bootstrap_samples : int, optional
Number of boostrap ... |
def _get_headers(self):
"""Get all the headers we're going to need:
1. Authorization
2. Content-Type
3. User-agent
Note that the User-agent string contains the library name, the
libary version, and the python version. This will help us track
what people are usin... | Get all the headers we're going to need:
1. Authorization
2. Content-Type
3. User-agent
Note that the User-agent string contains the library name, the
libary version, and the python version. This will help us track
what people are using, and where we should concentrate ... | Below is the the instruction that describes the task:
### Input:
Get all the headers we're going to need:
1. Authorization
2. Content-Type
3. User-agent
Note that the User-agent string contains the library name, the
libary version, and the python version. This will help us ... |
def parsestr(self, argsstr, usedname, location):
"""Parse a string lexically and store the result.
ARGS:
argsstr <str>:
The string to parse.
usedname <str>:
The string used by the user to invoke the option.
location <str>:
A user friendly sring... | Parse a string lexically and store the result.
ARGS:
argsstr <str>:
The string to parse.
usedname <str>:
The string used by the user to invoke the option.
location <str>:
A user friendly sring describing where the parser got this
data from. | Below is the the instruction that describes the task:
### Input:
Parse a string lexically and store the result.
ARGS:
argsstr <str>:
The string to parse.
usedname <str>:
The string used by the user to invoke the option.
location <str>:
A user frien... |
def gzip_if_smaller(content_related, data):
"""Calls bytes(request), and based on a certain threshold,
optionally gzips the resulting data. If the gzipped data is
smaller than the original byte array, this is returned instead.
Note that this only applies to content related requ... | Calls bytes(request), and based on a certain threshold,
optionally gzips the resulting data. If the gzipped data is
smaller than the original byte array, this is returned instead.
Note that this only applies to content related requests. | Below is the the instruction that describes the task:
### Input:
Calls bytes(request), and based on a certain threshold,
optionally gzips the resulting data. If the gzipped data is
smaller than the original byte array, this is returned instead.
Note that this only applies to conten... |
def resolveport(self, definitions):
"""
Resolve port_type reference.
@param definitions: A definitions object.
@type definitions: L{Definitions}
"""
ref = qualify(self.type, self.root, definitions.tns)
port_type = definitions.port_types.get(ref)
if port_ty... | Resolve port_type reference.
@param definitions: A definitions object.
@type definitions: L{Definitions} | Below is the the instruction that describes the task:
### Input:
Resolve port_type reference.
@param definitions: A definitions object.
@type definitions: L{Definitions}
### Response:
def resolveport(self, definitions):
"""
Resolve port_type reference.
@param definitions: A ... |
def _extrac_qtl(peak, block, headers):
""" Given a row containing the peak of the QTL and all the rows of
the linkage group of the said QTL (splitted per trait), determine
the QTL interval and find the start and stop marker of the said
interval.
The interval is a LOD 2 interval.
The approach is ... | Given a row containing the peak of the QTL and all the rows of
the linkage group of the said QTL (splitted per trait), determine
the QTL interval and find the start and stop marker of the said
interval.
The interval is a LOD 2 interval.
The approach is conservative in the way it takes the first and ... | Below is the the instruction that describes the task:
### Input:
Given a row containing the peak of the QTL and all the rows of
the linkage group of the said QTL (splitted per trait), determine
the QTL interval and find the start and stop marker of the said
interval.
The interval is a LOD 2 interval... |
def get_min_max_mag(self):
"""
:returns: minumum and maximum magnitudes from the underlying MFDs
"""
m1s, m2s = [], []
for mfd in self:
m1, m2 = mfd.get_min_max_mag()
m1s.append(m1)
m2s.append(m2)
return min(m1s), max(m2s) | :returns: minumum and maximum magnitudes from the underlying MFDs | Below is the the instruction that describes the task:
### Input:
:returns: minumum and maximum magnitudes from the underlying MFDs
### Response:
def get_min_max_mag(self):
"""
:returns: minumum and maximum magnitudes from the underlying MFDs
"""
m1s, m2s = [], []
for mfd in ... |
def show(self):
"""write my output to sys.stdout/err as appropriate"""
sys.stdout.write(self.stdout)
sys.stderr.write(self.stderr)
sys.stdout.flush()
sys.stderr.flush() | write my output to sys.stdout/err as appropriate | Below is the the instruction that describes the task:
### Input:
write my output to sys.stdout/err as appropriate
### Response:
def show(self):
"""write my output to sys.stdout/err as appropriate"""
sys.stdout.write(self.stdout)
sys.stderr.write(self.stderr)
sys.stdout.flush()
... |
def upload_complete(self, path, url, quiet):
""" function to complete an upload to retrieve a path from a url
Parameters
==========
path: the path for the upload that is read in
url: the url to send the POST to
quiet: suppress verbose output (default ... | function to complete an upload to retrieve a path from a url
Parameters
==========
path: the path for the upload that is read in
url: the url to send the POST to
quiet: suppress verbose output (default is False) | Below is the the instruction that describes the task:
### Input:
function to complete an upload to retrieve a path from a url
Parameters
==========
path: the path for the upload that is read in
url: the url to send the POST to
quiet: suppress verbose outp... |
def diffusion_mds(means, weights, d, diffusion_rounds=10):
"""
Dimensionality reduction using MDS, while running diffusion on W.
Args:
means (array): genes x clusters
weights (array): clusters x cells
d (int): desired dimensionality
Returns:
W_reduced (array): array of ... | Dimensionality reduction using MDS, while running diffusion on W.
Args:
means (array): genes x clusters
weights (array): clusters x cells
d (int): desired dimensionality
Returns:
W_reduced (array): array of shape (d, cells) | Below is the the instruction that describes the task:
### Input:
Dimensionality reduction using MDS, while running diffusion on W.
Args:
means (array): genes x clusters
weights (array): clusters x cells
d (int): desired dimensionality
Returns:
W_reduced (array): array of sh... |
def unregister(self, cleanup_mode):
"""Unregisters a machine previously registered with
:py:func:`IVirtualBox.register_machine` and optionally do additional
cleanup before the machine is unregistered.
This method does not delete any files. It only changes the machine configurat... | Unregisters a machine previously registered with
:py:func:`IVirtualBox.register_machine` and optionally do additional
cleanup before the machine is unregistered.
This method does not delete any files. It only changes the machine configuration and
the list of registered machines... | Below is the the instruction that describes the task:
### Input:
Unregisters a machine previously registered with
:py:func:`IVirtualBox.register_machine` and optionally do additional
cleanup before the machine is unregistered.
This method does not delete any files. It only changes ... |
def removed_issues(self, board_id, sprint_id):
"""Return the completed issues for the sprint."""
r_json = self._get_json('rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s' % (board_id, sprint_id),
base=self.AGILE_BASE_URL)
issues = [Issue(self._options, self._... | Return the completed issues for the sprint. | Below is the the instruction that describes the task:
### Input:
Return the completed issues for the sprint.
### Response:
def removed_issues(self, board_id, sprint_id):
"""Return the completed issues for the sprint."""
r_json = self._get_json('rapid/charts/sprintreport?rapidViewId=%s&sprintId=%s' ... |
def get_column(self, column_name, column_type, index, verbose=True):
"""Summary
Args:
column_name (TYPE): Description
column_type (TYPE): Description
index (TYPE): Description
Returns:
TYPE: Description
"""
return LazyOpResult(
... | Summary
Args:
column_name (TYPE): Description
column_type (TYPE): Description
index (TYPE): Description
Returns:
TYPE: Description | Below is the the instruction that describes the task:
### Input:
Summary
Args:
column_name (TYPE): Description
column_type (TYPE): Description
index (TYPE): Description
Returns:
TYPE: Description
### Response:
def get_column(self, column_name, colum... |
def calcCodePageRanges(unicodes):
""" Given a set of Unicode codepoints (integers), calculate the
corresponding OS/2 CodePage range bits.
This is a direct translation of FontForge implementation:
https://github.com/fontforge/fontforge/blob/7b2c074/fontforge/tottf.c#L3158
"""
codepageRanges = set... | Given a set of Unicode codepoints (integers), calculate the
corresponding OS/2 CodePage range bits.
This is a direct translation of FontForge implementation:
https://github.com/fontforge/fontforge/blob/7b2c074/fontforge/tottf.c#L3158 | Below is the the instruction that describes the task:
### Input:
Given a set of Unicode codepoints (integers), calculate the
corresponding OS/2 CodePage range bits.
This is a direct translation of FontForge implementation:
https://github.com/fontforge/fontforge/blob/7b2c074/fontforge/tottf.c#L3158
### R... |
def chi2(g1, g2=None, svdcut=1e-12, nocorr=False):
""" Compute chi**2 of ``g1-g2``.
``chi**2`` is a measure of whether the multi-dimensional
Gaussian distributions ``g1`` and ``g2`` (dictionaries or arrays)
agree with each other --- that is, do their means agree
within errors for corresponding elem... | Compute chi**2 of ``g1-g2``.
``chi**2`` is a measure of whether the multi-dimensional
Gaussian distributions ``g1`` and ``g2`` (dictionaries or arrays)
agree with each other --- that is, do their means agree
within errors for corresponding elements. The probability is high
if ``chi2(g1,g2)/chi2.dof... | Below is the the instruction that describes the task:
### Input:
Compute chi**2 of ``g1-g2``.
``chi**2`` is a measure of whether the multi-dimensional
Gaussian distributions ``g1`` and ``g2`` (dictionaries or arrays)
agree with each other --- that is, do their means agree
within errors for correspo... |
def smart_search(cls, query_string, search_options=None, extra_query = None):
""" Perform a smart VRF search.
Maps to the function
:py:func:`nipap.backend.Nipap.smart_search_vrf` in the backend.
Please see the documentation for the backend function for
informatio... | Perform a smart VRF search.
Maps to the function
:py:func:`nipap.backend.Nipap.smart_search_vrf` in the backend.
Please see the documentation for the backend function for
information regarding input arguments and return values. | Below is the the instruction that describes the task:
### Input:
Perform a smart VRF search.
Maps to the function
:py:func:`nipap.backend.Nipap.smart_search_vrf` in the backend.
Please see the documentation for the backend function for
information regarding input arg... |
def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None:
"""
Send histograms of parameters to tensorboard.
"""
for name, param in model.named_parameters():
if name in histogram_parameters:
self.add_train_histogram("parameter_histogram/" ... | Send histograms of parameters to tensorboard. | Below is the the instruction that describes the task:
### Input:
Send histograms of parameters to tensorboard.
### Response:
def log_histograms(self, model: Model, histogram_parameters: Set[str]) -> None:
"""
Send histograms of parameters to tensorboard.
"""
for name, param in model... |
def _add_header_domains_xml(self, document):
"""
Generates the XML elements for allowed header domains.
"""
for domain, attrs in self.header_domains.items():
header_element = document.createElement(
'allow-http-request-headers-from'
)
... | Generates the XML elements for allowed header domains. | Below is the the instruction that describes the task:
### Input:
Generates the XML elements for allowed header domains.
### Response:
def _add_header_domains_xml(self, document):
"""
Generates the XML elements for allowed header domains.
"""
for domain, attrs in self.header_domains... |
def filter_useless_pass(source):
"""Yield code with useless "pass" lines removed."""
try:
marked_lines = frozenset(useless_pass_line_numbers(source))
except (SyntaxError, tokenize.TokenError):
marked_lines = frozenset()
sio = io.StringIO(source)
for line_number, line in enumerate(si... | Yield code with useless "pass" lines removed. | Below is the the instruction that describes the task:
### Input:
Yield code with useless "pass" lines removed.
### Response:
def filter_useless_pass(source):
"""Yield code with useless "pass" lines removed."""
try:
marked_lines = frozenset(useless_pass_line_numbers(source))
except (SyntaxError,... |
def parse(station: str, txt: str) -> (MetarData, Units): # type: ignore
"""
Returns MetarData and Units dataclasses with parsed data and their associated units
"""
core.valid_station(station)
return parse_na(txt) if core.uses_na_format(station[:2]) else parse_in(txt) | Returns MetarData and Units dataclasses with parsed data and their associated units | Below is the the instruction that describes the task:
### Input:
Returns MetarData and Units dataclasses with parsed data and their associated units
### Response:
def parse(station: str, txt: str) -> (MetarData, Units): # type: ignore
"""
Returns MetarData and Units dataclasses with parsed data and their ... |
def listdir(self, folder_id='0', offset=None, limit=None, fields=None):
'Get Box object, representing list of objects in a folder.'
if fields is not None\
and not isinstance(fields, types.StringTypes): fields = ','.join(fields)
return self(
join('folders', folder_id, 'items'),
dict(offset=offset, limit=l... | Get Box object, representing list of objects in a folder. | Below is the the instruction that describes the task:
### Input:
Get Box object, representing list of objects in a folder.
### Response:
def listdir(self, folder_id='0', offset=None, limit=None, fields=None):
'Get Box object, representing list of objects in a folder.'
if fields is not None\
and not isinstan... |
def get_single_submission_courses(self, user_id, course_id, assignment_id, include=None):
"""
Get a single submission.
Get a single submission, based on user id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID""... | Get a single submission.
Get a single submission, based on user id. | Below is the the instruction that describes the task:
### Input:
Get a single submission.
Get a single submission, based on user id.
### Response:
def get_single_submission_courses(self, user_id, course_id, assignment_id, include=None):
"""
Get a single submission.
Get a sin... |
def json(self):
"""Produce a JSON representation for the web interface"""
d = { 'id': self.id, 'format': self.formatclass.__name__,'label': self.label, 'mimetype': self.formatclass.mimetype, 'schema': self.formatclass.schema }
if self.unique:
d['unique'] = True
if self.filen... | Produce a JSON representation for the web interface | Below is the the instruction that describes the task:
### Input:
Produce a JSON representation for the web interface
### Response:
def json(self):
"""Produce a JSON representation for the web interface"""
d = { 'id': self.id, 'format': self.formatclass.__name__,'label': self.label, 'mimetype': self... |
def clean_path(p):
""" Clean a path by expanding user and environment variables and
ensuring absolute path.
"""
p = os.path.expanduser(p)
p = os.path.expandvars(p)
p = os.path.abspath(p)
return p | Clean a path by expanding user and environment variables and
ensuring absolute path. | Below is the the instruction that describes the task:
### Input:
Clean a path by expanding user and environment variables and
ensuring absolute path.
### Response:
def clean_path(p):
""" Clean a path by expanding user and environment variables and
ensuring absolute path.
"""
p = os.path... |
def move(self, x = None, y = None, width = None, height = None,
bRepaint = True):
"""
Moves and/or resizes the window.
@note: This is request is performed syncronously.
@type x: int
@param x: (Optional) New horizontal... | Moves and/or resizes the window.
@note: This is request is performed syncronously.
@type x: int
@param x: (Optional) New horizontal coordinate.
@type y: int
@param y: (Optional) New vertical coordinate.
@type width: int
@param width: (Optional) Desired wind... | Below is the the instruction that describes the task:
### Input:
Moves and/or resizes the window.
@note: This is request is performed syncronously.
@type x: int
@param x: (Optional) New horizontal coordinate.
@type y: int
@param y: (Optional) New vertical coordinate.
... |
def bandpass(data, freqmin, freqmax, df, corners=4, zerophase=True):
"""
Butterworth-Bandpass Filter.
Filter data from ``freqmin`` to ``freqmax`` using ``corners``
corners.
The filter uses :func:`scipy.signal.iirfilter` (for design)
and :func:`scipy.signal.sosfilt` (for applying the filter).
... | Butterworth-Bandpass Filter.
Filter data from ``freqmin`` to ``freqmax`` using ``corners``
corners.
The filter uses :func:`scipy.signal.iirfilter` (for design)
and :func:`scipy.signal.sosfilt` (for applying the filter).
:type data: numpy.ndarray
:param data: Data to filter.
:param freqmin:... | Below is the the instruction that describes the task:
### Input:
Butterworth-Bandpass Filter.
Filter data from ``freqmin`` to ``freqmax`` using ``corners``
corners.
The filter uses :func:`scipy.signal.iirfilter` (for design)
and :func:`scipy.signal.sosfilt` (for applying the filter).
:type dat... |
def alias(self, v, stat='dummy'):
"""Return a representation of a value suitable for use in historical queries.
It will behave much as if you assigned the value to some entity and then used its
``historical`` method to get a reference to the set of its past values, which
happens to cont... | Return a representation of a value suitable for use in historical queries.
It will behave much as if you assigned the value to some entity and then used its
``historical`` method to get a reference to the set of its past values, which
happens to contain only the value you've provided here, ``v`... | Below is the the instruction that describes the task:
### Input:
Return a representation of a value suitable for use in historical queries.
It will behave much as if you assigned the value to some entity and then used its
``historical`` method to get a reference to the set of its past values, which... |
def freqpoly_plot(data):
"""make freqpoly plot of merged read lengths"""
rel_data = OrderedDict()
for key, val in data.items():
tot = sum(val.values(), 0)
rel_data[key] = {k: v / tot for k, v in val.items()}
fplotconfig = {
'data_labels': [
... | make freqpoly plot of merged read lengths | Below is the the instruction that describes the task:
### Input:
make freqpoly plot of merged read lengths
### Response:
def freqpoly_plot(data):
"""make freqpoly plot of merged read lengths"""
rel_data = OrderedDict()
for key, val in data.items():
tot = sum(val.values(), 0)
... |
def _restore(self, value):
"""Restores the state copied with _copy()"""
items, subs = value
self.clear()
for key, value in items:
self[key] = value
if key in subs:
value.sub_frames._restore(subs[key]) | Restores the state copied with _copy() | Below is the the instruction that describes the task:
### Input:
Restores the state copied with _copy()
### Response:
def _restore(self, value):
"""Restores the state copied with _copy()"""
items, subs = value
self.clear()
for key, value in items:
self[key] = value
... |
def quaternion(vector, angle):
"""
Unit quaternion for a vector and an angle
"""
return N.cos(angle/2)+vector*N.sin(angle/2) | Unit quaternion for a vector and an angle | Below is the the instruction that describes the task:
### Input:
Unit quaternion for a vector and an angle
### Response:
def quaternion(vector, angle):
"""
Unit quaternion for a vector and an angle
"""
return N.cos(angle/2)+vector*N.sin(angle/2) |
def setup_callsite(self, state, ret_addr, args, stack_base=None, alloc_base=None, grow_like_stack=True):
"""
This function performs the actions of the caller getting ready to jump into a function.
:param state: The SimState to operate on
:param ret_addr: The address to ... | This function performs the actions of the caller getting ready to jump into a function.
:param state: The SimState to operate on
:param ret_addr: The address to return to when the called function finishes
:param args: The list of arguments that that the called functi... | Below is the the instruction that describes the task:
### Input:
This function performs the actions of the caller getting ready to jump into a function.
:param state: The SimState to operate on
:param ret_addr: The address to return to when the called function finishes
:par... |
def nse(sim=None, obs=None, node=None, skip_nan=False):
"""Calculate the efficiency criteria after Nash & Sutcliffe.
If the simulated values predict the observed values as well
as the average observed value (regarding the the mean square
error), the NSE value is zero:
>>> from hydpy import nse
... | Calculate the efficiency criteria after Nash & Sutcliffe.
If the simulated values predict the observed values as well
as the average observed value (regarding the the mean square
error), the NSE value is zero:
>>> from hydpy import nse
>>> nse(sim=[2.0, 2.0, 2.0], obs=[1.0, 2.0, 3.0])
0.0
... | Below is the the instruction that describes the task:
### Input:
Calculate the efficiency criteria after Nash & Sutcliffe.
If the simulated values predict the observed values as well
as the average observed value (regarding the the mean square
error), the NSE value is zero:
>>> from hydpy import n... |
def save_ipv6(self, ip6, id_equip, descricao, id_net):
"""
Save an IP6 and associate with equipment
:param ip6: An IP6 available to save in format xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx.
:param id_equip: Equipment identifier. Integer value and greater than zero.
:param descrica... | Save an IP6 and associate with equipment
:param ip6: An IP6 available to save in format xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx.
:param id_equip: Equipment identifier. Integer value and greater than zero.
:param descricao: IPv6 description.
:param id_net: Network identifier. Integer val... | Below is the the instruction that describes the task:
### Input:
Save an IP6 and associate with equipment
:param ip6: An IP6 available to save in format xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx.
:param id_equip: Equipment identifier. Integer value and greater than zero.
:param descricao: IPv... |
def digestSession(self, mecha=MechanismSHA1):
"""
C_DigestInit/C_DigestUpdate/C_DigestKey/C_DigestFinal
:param mecha: the digesting mechanism to be used
(use `MechanismSHA1` for `CKM_SHA_1`)
:type mecha: :class:`Mechanism`
:return: A :class:`DigestSession` object
... | C_DigestInit/C_DigestUpdate/C_DigestKey/C_DigestFinal
:param mecha: the digesting mechanism to be used
(use `MechanismSHA1` for `CKM_SHA_1`)
:type mecha: :class:`Mechanism`
:return: A :class:`DigestSession` object
:rtype: DigestSession | Below is the the instruction that describes the task:
### Input:
C_DigestInit/C_DigestUpdate/C_DigestKey/C_DigestFinal
:param mecha: the digesting mechanism to be used
(use `MechanismSHA1` for `CKM_SHA_1`)
:type mecha: :class:`Mechanism`
:return: A :class:`DigestSession` object
... |
def _push_writer(self):
"""push a capturing buffer onto this Context and return
the new writer function."""
buf = util.FastEncodingBuffer()
self._buffer_stack.append(buf)
return buf.write | push a capturing buffer onto this Context and return
the new writer function. | Below is the the instruction that describes the task:
### Input:
push a capturing buffer onto this Context and return
the new writer function.
### Response:
def _push_writer(self):
"""push a capturing buffer onto this Context and return
the new writer function."""
buf = util.FastEn... |
def prune(self):
"""
Remove anything which shouldn't be displayed.
"""
def to_include(obj):
inc = obj.permission in self.display
if self.settings['hide_undoc'].lower() == 'true' and not obj.doc:
inc = False
return inc
if self.o... | Remove anything which shouldn't be displayed. | Below is the the instruction that describes the task:
### Input:
Remove anything which shouldn't be displayed.
### Response:
def prune(self):
"""
Remove anything which shouldn't be displayed.
"""
def to_include(obj):
inc = obj.permission in self.display
if se... |
def open_file(path, grib_errors='warn', **kwargs):
"""Open a GRIB file as a ``cfgrib.Dataset``."""
if 'mode' in kwargs:
warnings.warn("the `mode` keyword argument is ignored and deprecated", FutureWarning)
kwargs.pop('mode')
stream = messages.FileStream(path, message_class=cfmessage.CfMessag... | Open a GRIB file as a ``cfgrib.Dataset``. | Below is the the instruction that describes the task:
### Input:
Open a GRIB file as a ``cfgrib.Dataset``.
### Response:
def open_file(path, grib_errors='warn', **kwargs):
"""Open a GRIB file as a ``cfgrib.Dataset``."""
if 'mode' in kwargs:
warnings.warn("the `mode` keyword argument is ignored and ... |
def initialize_concept_scheme(rdf, cs, label, language, set_modified):
"""Initialize a concept scheme: Optionally add a label if the concept
scheme doesn't have a label, and optionally add a dct:modified
timestamp."""
# check whether the concept scheme is unlabeled, and label it if possible
labels ... | Initialize a concept scheme: Optionally add a label if the concept
scheme doesn't have a label, and optionally add a dct:modified
timestamp. | Below is the the instruction that describes the task:
### Input:
Initialize a concept scheme: Optionally add a label if the concept
scheme doesn't have a label, and optionally add a dct:modified
timestamp.
### Response:
def initialize_concept_scheme(rdf, cs, label, language, set_modified):
"""Initializ... |
def _cache_morlist_raw(self, instance):
"""
Fill the Mor objects queue that will be asynchronously processed later.
Resolve the vCenter `rootFolder` and initiate hosts and virtual machines
discovery.
"""
i_key = self._instance_key(instance)
self.log.debug("Caching... | Fill the Mor objects queue that will be asynchronously processed later.
Resolve the vCenter `rootFolder` and initiate hosts and virtual machines
discovery. | Below is the the instruction that describes the task:
### Input:
Fill the Mor objects queue that will be asynchronously processed later.
Resolve the vCenter `rootFolder` and initiate hosts and virtual machines
discovery.
### Response:
def _cache_morlist_raw(self, instance):
"""
Fill... |
def int_flags(flags, mapper=const.PERM_STRING_MAP):
"""
Converts string permission flags into integer permission flags as
specified in const.PERM_STRING_MAP
Arguments:
- flags <str>: one or more flags
For example: "crud" or "ru" or "r"
- mapper <list=const.PERM_STRING_MAP>: a... | Converts string permission flags into integer permission flags as
specified in const.PERM_STRING_MAP
Arguments:
- flags <str>: one or more flags
For example: "crud" or "ru" or "r"
- mapper <list=const.PERM_STRING_MAP>: a list containing tuples mapping
int permission flag ... | Below is the the instruction that describes the task:
### Input:
Converts string permission flags into integer permission flags as
specified in const.PERM_STRING_MAP
Arguments:
- flags <str>: one or more flags
For example: "crud" or "ru" or "r"
- mapper <list=const.PERM_STRING_MA... |
def generate_primes():
"""
Generate an infinite sequence of prime numbers.
The algorithm was originally written by David Eppstein, UC Irvine. See:
http://code.activestate.com/recipes/117119/
Examples
--------
>>> g = generate_primes()
>>> next(g)
2
>>> next(g)
3
>>> nex... | Generate an infinite sequence of prime numbers.
The algorithm was originally written by David Eppstein, UC Irvine. See:
http://code.activestate.com/recipes/117119/
Examples
--------
>>> g = generate_primes()
>>> next(g)
2
>>> next(g)
3
>>> next(g)
5 | Below is the the instruction that describes the task:
### Input:
Generate an infinite sequence of prime numbers.
The algorithm was originally written by David Eppstein, UC Irvine. See:
http://code.activestate.com/recipes/117119/
Examples
--------
>>> g = generate_primes()
>>> next(g)
2... |
def remove_column(self, column_name, inplace=False):
"""
Returns an SFrame with a column removed.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
SFrame, ret... | Returns an SFrame with a column removed.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
SFrame, returning self.
Parameters
----------
column_name :... | Below is the the instruction that describes the task:
### Input:
Returns an SFrame with a column removed.
If inplace == False (default) this operation does not modify the
current SFrame, returning a new SFrame.
If inplace == True, this operation modifies the current
SFrame, returni... |
def generate_tile_coordinates(roi, num_tiles):
# type: (GeoVector, Tuple[int, int]) -> Iterator[GeoVector]
"""Yields N x M rectangular tiles for a region of interest.
Parameters
----------
roi : GeoVector
Region of interest
num_tiles : tuple
Tuple (horizontal_tiles, vertical_til... | Yields N x M rectangular tiles for a region of interest.
Parameters
----------
roi : GeoVector
Region of interest
num_tiles : tuple
Tuple (horizontal_tiles, vertical_tiles)
Yields
------
~telluric.vectors.GeoVector | Below is the the instruction that describes the task:
### Input:
Yields N x M rectangular tiles for a region of interest.
Parameters
----------
roi : GeoVector
Region of interest
num_tiles : tuple
Tuple (horizontal_tiles, vertical_tiles)
Yields
------
~telluric.vectors.... |
def findCaller(self, stack_info=False):
"""
Find the stack frame of the caller so that we can note the source
file name, line number and function name.
"""
f = logging.currentframe()
# On some versions of IronPython, currentframe() returns None if
# IronPython isn... | Find the stack frame of the caller so that we can note the source
file name, line number and function name. | Below is the the instruction that describes the task:
### Input:
Find the stack frame of the caller so that we can note the source
file name, line number and function name.
### Response:
def findCaller(self, stack_info=False):
"""
Find the stack frame of the caller so that we can note the s... |
def release(self, signal=True):
"""
Unlocks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the released_event signal.
"""
if not self.needs_lock:
r... | Unlocks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the released_event signal. | Below is the the instruction that describes the task:
### Input:
Unlocks the account.
Method has no effect if the constructor argument `needs_lock`
wsa set to False.
:type signal: bool
:param signal: Whether to emit the released_event signal.
### Response:
def release(self, signal=... |
def dt_str_to_posix(dt_str):
"""format str to posix.
datetime str is of format %Y-%m-%dT%H:%M:%S.%fZ,
e.g. 2013-04-12T00:22:27.978Z. According to ISO 8601, T is a separator
between date and time when they are on the same line.
Z indicates UTC (zero meridian).
A pointer: http://www.cl.cam.ac.uk/~mgk25/iso-... | format str to posix.
datetime str is of format %Y-%m-%dT%H:%M:%S.%fZ,
e.g. 2013-04-12T00:22:27.978Z. According to ISO 8601, T is a separator
between date and time when they are on the same line.
Z indicates UTC (zero meridian).
A pointer: http://www.cl.cam.ac.uk/~mgk25/iso-time.html
This is used to parse... | Below is the the instruction that describes the task:
### Input:
format str to posix.
datetime str is of format %Y-%m-%dT%H:%M:%S.%fZ,
e.g. 2013-04-12T00:22:27.978Z. According to ISO 8601, T is a separator
between date and time when they are on the same line.
Z indicates UTC (zero meridian).
A pointer: ... |
def _print_foreign_repetition_table(self, idset1, idset2):
"""
:param idset1:
:param idset2:
"""
assert(isinstance(idset1, idset_with_reference))
assert(isinstance(idset2, idset))
reps = idset2.get_repetitions()
if len(reps) < 1:
return
... | :param idset1:
:param idset2: | Below is the the instruction that describes the task:
### Input:
:param idset1:
:param idset2:
### Response:
def _print_foreign_repetition_table(self, idset1, idset2):
"""
:param idset1:
:param idset2:
"""
assert(isinstance(idset1, idset_with_reference))
ass... |
def get_query_indexes(self, raw_result=False):
"""
Retrieves query indexes from the remote database.
:param bool raw_result: If set to True then the raw JSON content for
the request is returned. Default is to return a list containing
:class:`~cloudant.index.Index`,
... | Retrieves query indexes from the remote database.
:param bool raw_result: If set to True then the raw JSON content for
the request is returned. Default is to return a list containing
:class:`~cloudant.index.Index`,
:class:`~cloudant.index.TextIndex`, and
:class:... | Below is the the instruction that describes the task:
### Input:
Retrieves query indexes from the remote database.
:param bool raw_result: If set to True then the raw JSON content for
the request is returned. Default is to return a list containing
:class:`~cloudant.index.Index`,
... |
def delete_document(self, doc_id, conn=None):
"""
Delete a document from index
Returns 1 if the document was deleted, 0 if not
"""
if conn is None:
conn = self.redis
return conn.execute_command(self.DEL_CMD, self.index_name, doc_id) | Delete a document from index
Returns 1 if the document was deleted, 0 if not | Below is the the instruction that describes the task:
### Input:
Delete a document from index
Returns 1 if the document was deleted, 0 if not
### Response:
def delete_document(self, doc_id, conn=None):
"""
Delete a document from index
Returns 1 if the document was deleted, 0 if not
... |
def is_solid(regex):
"""
Check the given regular expression is solid.
>>> is_solid(r'a')
True
>>> is_solid(r'[ab]')
True
>>> is_solid(r'(a|b|c)')
True
>>> is_solid(r'(a|b|c)?')
True
>>> is_solid(r'(a|b)(c)')
False
>>> is_solid(r'(a|b)(c)?')
False
"""
sha... | Check the given regular expression is solid.
>>> is_solid(r'a')
True
>>> is_solid(r'[ab]')
True
>>> is_solid(r'(a|b|c)')
True
>>> is_solid(r'(a|b|c)?')
True
>>> is_solid(r'(a|b)(c)')
False
>>> is_solid(r'(a|b)(c)?')
False | Below is the the instruction that describes the task:
### Input:
Check the given regular expression is solid.
>>> is_solid(r'a')
True
>>> is_solid(r'[ab]')
True
>>> is_solid(r'(a|b|c)')
True
>>> is_solid(r'(a|b|c)?')
True
>>> is_solid(r'(a|b)(c)')
False
>>> is_solid(r'(a... |
def from_jd(jd):
'''Calculate Indian Civil date from Julian day
Offset in years from Saka era to Gregorian epoch'''
start = 80
# Day offset between Saka and Gregorian
jd = trunc(jd) + 0.5
greg = gregorian.from_jd(jd) # Gregorian date for Julian day
leap = isleap(greg[0]) # Is this a leap... | Calculate Indian Civil date from Julian day
Offset in years from Saka era to Gregorian epoch | Below is the the instruction that describes the task:
### Input:
Calculate Indian Civil date from Julian day
Offset in years from Saka era to Gregorian epoch
### Response:
def from_jd(jd):
'''Calculate Indian Civil date from Julian day
Offset in years from Saka era to Gregorian epoch'''
start = 80... |
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
'''
if _service_is_upstart(name):
cmd = 'reload {0}'.format(name)
else:
cmd = '/sbin/service {0} reload'.format(name)
return not __salt__['c... | Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name> | Below is the the instruction that describes the task:
### Input:
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' service.reload <service name>
### Response:
def reload_(name):
'''
Reload the named service
CLI Example:
.. code-block:: bash
salt '*' s... |
def htmlize_paragraphs(text):
"""
Convert paragraphs delimited by blank lines into HTML text enclosed
in <p> tags.
"""
paragraphs = re.split('(\r?\n)\s*(\r?\n)', text)
return '\n'.join('<p>%s</p>' % paragraph for paragraph in paragraphs) | Convert paragraphs delimited by blank lines into HTML text enclosed
in <p> tags. | Below is the the instruction that describes the task:
### Input:
Convert paragraphs delimited by blank lines into HTML text enclosed
in <p> tags.
### Response:
def htmlize_paragraphs(text):
"""
Convert paragraphs delimited by blank lines into HTML text enclosed
in <p> tags.
"""
paragraphs =... |
def tag(self, text):
"""Retrieves list of keywords in text.
Parameters
----------
text: Text
The text to search for events.
Returns
-------
list of vents sorted by start, end
"""
if self.search_method == 'ahocorasick':
eve... | Retrieves list of keywords in text.
Parameters
----------
text: Text
The text to search for events.
Returns
-------
list of vents sorted by start, end | Below is the the instruction that describes the task:
### Input:
Retrieves list of keywords in text.
Parameters
----------
text: Text
The text to search for events.
Returns
-------
list of vents sorted by start, end
### Response:
def tag(self, text):
... |
def _presence_listener(self, event: Dict[str, Any]):
"""
Update cached user presence state from Matrix presence events.
Due to the possibility of nodes using accounts on multiple homeservers a composite
address state is synthesised from the cached individual user presence states.
... | Update cached user presence state from Matrix presence events.
Due to the possibility of nodes using accounts on multiple homeservers a composite
address state is synthesised from the cached individual user presence states. | Below is the the instruction that describes the task:
### Input:
Update cached user presence state from Matrix presence events.
Due to the possibility of nodes using accounts on multiple homeservers a composite
address state is synthesised from the cached individual user presence states.
### Respon... |
def process_agreement_events_publisher(publisher_account, agreement_id, did, service_agreement,
price, consumer_address, condition_ids):
"""
Process the agreement events during the register of the service agreement for the publisher side
:param publisher_account: Acco... | Process the agreement events during the register of the service agreement for the publisher side
:param publisher_account: Account instance of the publisher
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param price: Asset... | Below is the the instruction that describes the task:
### Input:
Process the agreement events during the register of the service agreement for the publisher side
:param publisher_account: Account instance of the publisher
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param... |
def top(self, topn=10):
"""
Get a list of the top ``topn`` features in this :class:`.Feature`\.
Examples
--------
.. code-block:: python
>>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])
>>> myFeature.top(1)
[('trapezoid', 5)]
... | Get a list of the top ``topn`` features in this :class:`.Feature`\.
Examples
--------
.. code-block:: python
>>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])
>>> myFeature.top(1)
[('trapezoid', 5)]
Parameters
----------
topn... | Below is the the instruction that describes the task:
### Input:
Get a list of the top ``topn`` features in this :class:`.Feature`\.
Examples
--------
.. code-block:: python
>>> myFeature = Feature([('the', 2), ('pine', 1), ('trapezoid', 5)])
>>> myFeature.top(1)
[... |
def success(self):
"""return True if a response status is Success or Follows:
.. code-block:: python
>>> resp = Message({'Response': 'Success'})
>>> print(resp.success)
True
>>> resp['Response'] = 'Failed'
>>> resp.success
False
... | return True if a response status is Success or Follows:
.. code-block:: python
>>> resp = Message({'Response': 'Success'})
>>> print(resp.success)
True
>>> resp['Response'] = 'Failed'
>>> resp.success
False | Below is the the instruction that describes the task:
### Input:
return True if a response status is Success or Follows:
.. code-block:: python
>>> resp = Message({'Response': 'Success'})
>>> print(resp.success)
True
>>> resp['Response'] = 'Failed'
... |
def make_pymol(pdb_file, cutoff=7.0, min_kihs=2, outfile=None):
""" Pymol script for viewing classic coiled-coil Socket output.
Notes
-----
For examples of these views, browse the CC+ database here: http://coiledcoils.chm.bris.ac.uk/ccplus/search/.
Parameters
----------
pdb_file: str
... | Pymol script for viewing classic coiled-coil Socket output.
Notes
-----
For examples of these views, browse the CC+ database here: http://coiledcoils.chm.bris.ac.uk/ccplus/search/.
Parameters
----------
pdb_file: str
Path to a pdb_file.
cutoff: float
Socket cutoff in Angstr... | Below is the the instruction that describes the task:
### Input:
Pymol script for viewing classic coiled-coil Socket output.
Notes
-----
For examples of these views, browse the CC+ database here: http://coiledcoils.chm.bris.ac.uk/ccplus/search/.
Parameters
----------
pdb_file: str
... |
def get_container_setting(name, container, settings):
'''
Get the value of the setting for the IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, S... | Get the value of the setting for the IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites, SslBindings
settings (dict): A dictionary of the setting na... | Below is the the instruction that describes the task:
### Input:
Get the value of the setting for the IIS container.
.. versionadded:: 2016.11.0
Args:
name (str): The name of the IIS container.
container (str): The type of IIS container. The container types are:
AppPools, Sites... |
def staticmap(ctx, mapid, output, features, lat, lon, zoom, size):
"""
Generate static map images from existing Mapbox map ids.
Optionally overlay with geojson features.
$ mapbox staticmap --features features.geojson mapbox.satellite out.png
$ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 m... | Generate static map images from existing Mapbox map ids.
Optionally overlay with geojson features.
$ mapbox staticmap --features features.geojson mapbox.satellite out.png
$ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 mapbox.satellite out2.png
An access token is required, see `mapbox --help`. | Below is the the instruction that describes the task:
### Input:
Generate static map images from existing Mapbox map ids.
Optionally overlay with geojson features.
$ mapbox staticmap --features features.geojson mapbox.satellite out.png
$ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 mapbox.sate... |
def _apply_rules(expr, rules):
"""Recursively re-instantiate the expression, while applying all of the
given `rules` to all encountered (sub-) expressions
Args:
expr: Any Expression or scalar object
rules (list, ~collections.OrderedDict): A list of rules dictionary
mapping name... | Recursively re-instantiate the expression, while applying all of the
given `rules` to all encountered (sub-) expressions
Args:
expr: Any Expression or scalar object
rules (list, ~collections.OrderedDict): A list of rules dictionary
mapping names to rules, where each rule is a tuple... | Below is the the instruction that describes the task:
### Input:
Recursively re-instantiate the expression, while applying all of the
given `rules` to all encountered (sub-) expressions
Args:
expr: Any Expression or scalar object
rules (list, ~collections.OrderedDict): A list of rules dict... |
def find_proc_date(header):
"""Search the HISTORY fields of a header looking for the FLIPS
processing date.
"""
import string, re
for h in header.ascardlist():
if h.key=="HISTORY":
g=h.value
if ( string.find(g,'FLIPS 1.0 -:') ):
result=re.search('imred... | Search the HISTORY fields of a header looking for the FLIPS
processing date. | Below is the the instruction that describes the task:
### Input:
Search the HISTORY fields of a header looking for the FLIPS
processing date.
### Response:
def find_proc_date(header):
"""Search the HISTORY fields of a header looking for the FLIPS
processing date.
"""
import string, re
for h... |
def phids(self, *phids):
"""Retrieve data about PHIDs.
:params phids: list of PHIDs
"""
params = {
self.PHIDS: phids
}
response = self._call(self.PHAB_PHIDS, params)
return response | Retrieve data about PHIDs.
:params phids: list of PHIDs | Below is the the instruction that describes the task:
### Input:
Retrieve data about PHIDs.
:params phids: list of PHIDs
### Response:
def phids(self, *phids):
"""Retrieve data about PHIDs.
:params phids: list of PHIDs
"""
params = {
self.PHIDS: phids
}... |
def create_project(self, name, client_id, budget = None, budget_by =
'none', notes = None, billable = True):
'''Creates a Project with the given information.'''
project = {'project':{
'name': name,
'client_id': client_id,
'budget_by': budget_by,
'budg... | Creates a Project with the given information. | Below is the the instruction that describes the task:
### Input:
Creates a Project with the given information.
### Response:
def create_project(self, name, client_id, budget = None, budget_by =
'none', notes = None, billable = True):
'''Creates a Project with the given information.'''
project ... |
def compcor_variance_plot(metadata_files, metadata_sources=None,
output_file=None, varexp_thresh=(0.5, 0.7, 0.9),
fig=None):
"""
Parameters
----------
metadata_files: list
List of paths to files containing component metadata. If more than one
... | Parameters
----------
metadata_files: list
List of paths to files containing component metadata. If more than one
decomposition has been performed (e.g., anatomical and temporal
CompCor decompositions), then all metadata files can be provided in
the list. However, each metadata f... | Below is the the instruction that describes the task:
### Input:
Parameters
----------
metadata_files: list
List of paths to files containing component metadata. If more than one
decomposition has been performed (e.g., anatomical and temporal
CompCor decompositions), then all metadat... |
def print_profile_info(org_vm, profile_instance):
"""
Print information on a profile defined by profile_instance.
Parameters:
org_vm: The value mapping for CIMRegisterdProfile and
RegisteredOrganization so that the value and not value mapping
is displayed.
profile_instance... | Print information on a profile defined by profile_instance.
Parameters:
org_vm: The value mapping for CIMRegisterdProfile and
RegisteredOrganization so that the value and not value mapping
is displayed.
profile_instance: instance of a profile to be printed | Below is the the instruction that describes the task:
### Input:
Print information on a profile defined by profile_instance.
Parameters:
org_vm: The value mapping for CIMRegisterdProfile and
RegisteredOrganization so that the value and not value mapping
is displayed.
profile_i... |
def load_exchange_word_vectors(
filename = "database.db",
maximum_number_of_events = None
):
"""
Load exchange data and return dataset.
"""
log.info("load word vectors of database {filename}".format(
filename = filename
))
# Ensure that the database exists.
... | Load exchange data and return dataset. | Below is the the instruction that describes the task:
### Input:
Load exchange data and return dataset.
### Response:
def load_exchange_word_vectors(
filename = "database.db",
maximum_number_of_events = None
):
"""
Load exchange data and return dataset.
"""
log.info("loa... |
def band_path(self, band_id, for_gdal=False, absolute=False):
"""Return paths of given band's jp2 files for all granules."""
band_id = str(band_id).zfill(2)
if not isinstance(band_id, str) or band_id not in BAND_IDS:
raise ValueError("band ID not valid: %s" % band_id)
if self... | Return paths of given band's jp2 files for all granules. | Below is the the instruction that describes the task:
### Input:
Return paths of given band's jp2 files for all granules.
### Response:
def band_path(self, band_id, for_gdal=False, absolute=False):
"""Return paths of given band's jp2 files for all granules."""
band_id = str(band_id).zfill(2)
... |
def _ctab_property_block(stream):
"""Process properties block of ``Ctab``.
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabPropertiesBlockLine`
"""
line = stream.popleft()
while lin... | Process properties block of ``Ctab``.
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabPropertiesBlockLine` | Below is the the instruction that describes the task:
### Input:
Process properties block of ``Ctab``.
:param stream: Queue containing lines of text.
:type stream: :py:class:`collections.deque`
:return: Tuples of data.
:rtype: :class:`~ctfile.tokenizer.CtabPropertiesBlockLine`
### Response:
def _c... |
def _check_command_result(self):
"""If command result exists run these checks."""
if self.commandResult.startswith('/bin/bash'):
raise UtilError('%s' % self.commandResult.split(' ', 1)[1])
if self.commandResult.startswith('/bin/mv'):
raise UtilError('%s' % self.commandRes... | If command result exists run these checks. | Below is the the instruction that describes the task:
### Input:
If command result exists run these checks.
### Response:
def _check_command_result(self):
"""If command result exists run these checks."""
if self.commandResult.startswith('/bin/bash'):
raise UtilError('%s' % self.commandR... |
def validate(self, vat_deets):
"""Validates an existing VAT identification number against VIES."""
request = self._get('validation', vat_deets)
return self.responder(request) | Validates an existing VAT identification number against VIES. | Below is the the instruction that describes the task:
### Input:
Validates an existing VAT identification number against VIES.
### Response:
def validate(self, vat_deets):
"""Validates an existing VAT identification number against VIES."""
request = self._get('validation', vat_deets)
return... |
def _style_text(text):
"""
Apply some HTML highlighting to the contents.
This can't be done in the
"""
# Escape text and apply some formatting.
# To have really good highlighting, pprint would have to be re-implemented.
text = escape(text)
text = text.replace(' <iterator object>', ... | Apply some HTML highlighting to the contents.
This can't be done in the | Below is the the instruction that describes the task:
### Input:
Apply some HTML highlighting to the contents.
This can't be done in the
### Response:
def _style_text(text):
"""
Apply some HTML highlighting to the contents.
This can't be done in the
"""
# Escape text and apply some formatti... |
def nvmlDeviceSetDefaultAutoBoostedClocksEnabled(handle, enabled, flags):
r"""
/**
* Try to set the default state of Auto Boosted clocks on a device. This is the default state that Auto Boosted clocks will
* return to when no compute running processes (e.g. CUDA application which have an active contex... | r"""
/**
* Try to set the default state of Auto Boosted clocks on a device. This is the default state that Auto Boosted clocks will
* return to when no compute running processes (e.g. CUDA application which have an active context) are running
*
* For Kepler &tm; or newer non-GeForce fully suppor... | Below is the the instruction that describes the task:
### Input:
r"""
/**
* Try to set the default state of Auto Boosted clocks on a device. This is the default state that Auto Boosted clocks will
* return to when no compute running processes (e.g. CUDA application which have an active context) are ru... |
def list_assignments(self, course_id, assignment_ids=None, bucket=None, include=None, needs_grading_count_by_section=None, override_assignment_dates=None, search_term=None):
"""
List assignments.
Returns the list of assignments for the current context.
"""
path = {}
... | List assignments.
Returns the list of assignments for the current context. | Below is the the instruction that describes the task:
### Input:
List assignments.
Returns the list of assignments for the current context.
### Response:
def list_assignments(self, course_id, assignment_ids=None, bucket=None, include=None, needs_grading_count_by_section=None, override_assignment_dates=N... |
def _probvec(r, out):
"""
Fill `out` with randomly sampled probability vectors as rows.
To be complied as a ufunc by guvectorize of Numba. The inputs must
have the same shape except the last axis; the length of the last
axis of `r` must be that of `out` minus 1, i.e., if out.shape[-1] is
k, the... | Fill `out` with randomly sampled probability vectors as rows.
To be complied as a ufunc by guvectorize of Numba. The inputs must
have the same shape except the last axis; the length of the last
axis of `r` must be that of `out` minus 1, i.e., if out.shape[-1] is
k, then r.shape[-1] must be k-1.
Pa... | Below is the the instruction that describes the task:
### Input:
Fill `out` with randomly sampled probability vectors as rows.
To be complied as a ufunc by guvectorize of Numba. The inputs must
have the same shape except the last axis; the length of the last
axis of `r` must be that of `out` minus 1, i... |
def require_dataset(self, name, shape, dtype=None, exact=False, **kwargs):
"""Obtain an array, creating if it doesn't exist. Other `kwargs` are
as per :func:`zarr.hierarchy.Group.create_dataset`.
Parameters
----------
name : string
Array name.
shape : int or ... | Obtain an array, creating if it doesn't exist. Other `kwargs` are
as per :func:`zarr.hierarchy.Group.create_dataset`.
Parameters
----------
name : string
Array name.
shape : int or tuple of ints
Array shape.
dtype : string or dtype, optional
... | Below is the the instruction that describes the task:
### Input:
Obtain an array, creating if it doesn't exist. Other `kwargs` are
as per :func:`zarr.hierarchy.Group.create_dataset`.
Parameters
----------
name : string
Array name.
shape : int or tuple of ints
... |
def append(self, event, force = False):
'''
Append an event to queue. The events are classified and appended to sub-queues
:param event: input event
:param force: if True, the event is appended even if the queue is full
:returns: None if appended succes... | Append an event to queue. The events are classified and appended to sub-queues
:param event: input event
:param force: if True, the event is appended even if the queue is full
:returns: None if appended successfully, or a matcher to match a QueueCanWriteEvent otherwise | Below is the the instruction that describes the task:
### Input:
Append an event to queue. The events are classified and appended to sub-queues
:param event: input event
:param force: if True, the event is appended even if the queue is full
:returns: None if append... |
def get_first_name_last_name(self):
"""
:rtype: str
"""
names = []
if self._get_first_names():
names += self._get_first_names()
if self._get_additional_names():
names += self._get_additional_names()
if self._get_last_names():
na... | :rtype: str | Below is the the instruction that describes the task:
### Input:
:rtype: str
### Response:
def get_first_name_last_name(self):
"""
:rtype: str
"""
names = []
if self._get_first_names():
names += self._get_first_names()
if self._get_additional_names():
... |
def softplus(X):
""" Pass X through a soft-plus function, , in a numerically
stable way (using the log-sum-exp trick).
The softplus transformation is:
.. math::
\log(1 + \exp\{X\})
Parameters
----------
X: ndarray
shape (N,) array or... | Pass X through a soft-plus function, , in a numerically
stable way (using the log-sum-exp trick).
The softplus transformation is:
.. math::
\log(1 + \exp\{X\})
Parameters
----------
X: ndarray
shape (N,) array or shape (N, D) array of da... | Below is the the instruction that describes the task:
### Input:
Pass X through a soft-plus function, , in a numerically
stable way (using the log-sum-exp trick).
The softplus transformation is:
.. math::
\log(1 + \exp\{X\})
Parameters
----------
X:... |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(Fil... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
### Response:
def fi... |
def save(self, commit=True):
""" Saves the instance. """
if not self.instance.pk:
# First, handle topic creation
if 'topic_type' in self.cleaned_data and len(self.cleaned_data['topic_type']):
topic_type = self.cleaned_data['topic_type']
else:
... | Saves the instance. | Below is the the instruction that describes the task:
### Input:
Saves the instance.
### Response:
def save(self, commit=True):
""" Saves the instance. """
if not self.instance.pk:
# First, handle topic creation
if 'topic_type' in self.cleaned_data and len(self.cleaned_data[... |
async def node(self, node, *, dc=None, watch=None, consistency=None):
"""Returns the health info of a node.
Parameters:
node (ObjectID): Node ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blo... | Returns the health info of a node.
Parameters:
node (ObjectID): Node ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a blocking query
consistency (Consistency): Force consiste... | Below is the the instruction that describes the task:
### Input:
Returns the health info of a node.
Parameters:
node (ObjectID): Node ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blocking): Do a... |
def documents(self, full=False):
'''Return list of documents owned by user.
If `full=True`, it'll download all pages returned by the HTTP server'''
url = self.base_url + self.DOCUMENTS_PAGE
class_ = Document
results = self._retrieve_resources(url, class_, full)
return re... | Return list of documents owned by user.
If `full=True`, it'll download all pages returned by the HTTP server | Below is the the instruction that describes the task:
### Input:
Return list of documents owned by user.
If `full=True`, it'll download all pages returned by the HTTP server
### Response:
def documents(self, full=False):
'''Return list of documents owned by user.
If `full=True`, it'll dow... |
def _get_string_and_set_width(self, combination, mode):
"""
Construct the string to be displayed and record the max width.
"""
show = "{}".format(self._separator(mode)).join(combination)
show = show.rstrip("{}".format(self._separator(mode)))
self.max_width = max([self.max... | Construct the string to be displayed and record the max width. | Below is the the instruction that describes the task:
### Input:
Construct the string to be displayed and record the max width.
### Response:
def _get_string_and_set_width(self, combination, mode):
"""
Construct the string to be displayed and record the max width.
"""
show = "{}".fo... |
def get(self, **params):
"""Performs get request to the biomart service.
Args:
**params (dict of str: any): Arbitrary keyword arguments, which
are added as parameters to the get request to biomart.
Returns:
requests.models.Response: Response from biomart... | Performs get request to the biomart service.
Args:
**params (dict of str: any): Arbitrary keyword arguments, which
are added as parameters to the get request to biomart.
Returns:
requests.models.Response: Response from biomart for the request. | Below is the the instruction that describes the task:
### Input:
Performs get request to the biomart service.
Args:
**params (dict of str: any): Arbitrary keyword arguments, which
are added as parameters to the get request to biomart.
Returns:
requests.model... |
def logp_gradient_of_set(variable_set, calculation_set=None):
"""
Calculates the gradient of the joint log posterior with respect to all the variables in variable_set.
Calculation of the log posterior is restricted to the variables in calculation_set.
Returns a dictionary of the gradients.
"""
... | Calculates the gradient of the joint log posterior with respect to all the variables in variable_set.
Calculation of the log posterior is restricted to the variables in calculation_set.
Returns a dictionary of the gradients. | Below is the the instruction that describes the task:
### Input:
Calculates the gradient of the joint log posterior with respect to all the variables in variable_set.
Calculation of the log posterior is restricted to the variables in calculation_set.
Returns a dictionary of the gradients.
### Response:
de... |
def delete_orderrun(backend, orderrun_id):
"""
Delete the orderrun specified by the argument.
"""
click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg='green')
check_and_print(DKCloudCommandRunner.delete_orderrun(backend.dki, orderrun_id.strip())) | Delete the orderrun specified by the argument. | Below is the the instruction that describes the task:
### Input:
Delete the orderrun specified by the argument.
### Response:
def delete_orderrun(backend, orderrun_id):
"""
Delete the orderrun specified by the argument.
"""
click.secho('%s - Deleting orderrun %s' % (get_datetime(), orderrun_id), fg... |
def _init_using_k_equivalence(self, given_graph, sfa=False):
"""
Args:
given_graph (DFA): The DFA states
sfa (boolean): A boolean for chosing SFA
Return:
list, list, list: sm_vector, smi_vector, em_vector initialization vectors
"""
graph = DFA(... | Args:
given_graph (DFA): The DFA states
sfa (boolean): A boolean for chosing SFA
Return:
list, list, list: sm_vector, smi_vector, em_vector initialization vectors | Below is the the instruction that describes the task:
### Input:
Args:
given_graph (DFA): The DFA states
sfa (boolean): A boolean for chosing SFA
Return:
list, list, list: sm_vector, smi_vector, em_vector initialization vectors
### Response:
def _init_using_k_equivalence... |
def get_thumbnails(self, size=None):
""" Returns this Item Thumbnails. Thumbnails are not supported on
SharePoint Server 2016.
:param size: request only the specified size: ej: "small",
Custom 300x400 px: "c300x400", Crop: "c300x400_Crop"
:return: Thumbnail Data
:rtype:... | Returns this Item Thumbnails. Thumbnails are not supported on
SharePoint Server 2016.
:param size: request only the specified size: ej: "small",
Custom 300x400 px: "c300x400", Crop: "c300x400_Crop"
:return: Thumbnail Data
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Returns this Item Thumbnails. Thumbnails are not supported on
SharePoint Server 2016.
:param size: request only the specified size: ej: "small",
Custom 300x400 px: "c300x400", Crop: "c300x400_Crop"
:return: Thumbnail ... |
def _check_configuration(self, *attrs):
"""Check that each named attr has been configured
"""
for attr in attrs:
if getattr(self, attr, None) is None:
raise ConfigurationError("{} not configured".format(attr)) | Check that each named attr has been configured | Below is the the instruction that describes the task:
### Input:
Check that each named attr has been configured
### Response:
def _check_configuration(self, *attrs):
"""Check that each named attr has been configured
"""
for attr in attrs:
if getattr(self, attr, None) is None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.