code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def ParseOptions(cls, options, analysis_plugin):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
Ba... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption: when unable to connect to Viper instance. | Below is the the instruction that describes the task:
### Input:
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
analysis_plugin (ViperAnalysisPlugin): analysis plugin to configure.
Raises:
BadConfigObject: when the output module object is of the wrong t... |
def main():
"""
Sets up our command line options, prints the usage/help (if warranted), and
runs :py:func:`pyminifier.pyminify` with the given command line options.
"""
usage = '%prog [options] "<input file>"'
if '__main__.py' in sys.argv[0]: # python -m pyminifier
usage = 'pyminifier [o... | Sets up our command line options, prints the usage/help (if warranted), and
runs :py:func:`pyminifier.pyminify` with the given command line options. | Below is the the instruction that describes the task:
### Input:
Sets up our command line options, prints the usage/help (if warranted), and
runs :py:func:`pyminifier.pyminify` with the given command line options.
### Response:
def main():
"""
Sets up our command line options, prints the usage/help (if... |
def get_default_lab_path(self, config):
"""Generate a default laboratory path based on user environment."""
# Default path settings
# Append project name if present (NCI-specific)
default_project = os.environ.get('PROJECT', '')
default_short_path = os.path.join('/short', default... | Generate a default laboratory path based on user environment. | Below is the the instruction that describes the task:
### Input:
Generate a default laboratory path based on user environment.
### Response:
def get_default_lab_path(self, config):
"""Generate a default laboratory path based on user environment."""
# Default path settings
# Append project ... |
def add_formatter(self, sqla_col_type, formatter, key_specific=None):
"""
Add a formatter to the registry
if key_specific is provided, this formatter will only be used for some
specific exports
"""
self.add_item(sqla_col_type, formatter, key_specific) | Add a formatter to the registry
if key_specific is provided, this formatter will only be used for some
specific exports | Below is the the instruction that describes the task:
### Input:
Add a formatter to the registry
if key_specific is provided, this formatter will only be used for some
specific exports
### Response:
def add_formatter(self, sqla_col_type, formatter, key_specific=None):
"""
Add a form... |
def __levenshteinDistance(s, t):
'''
Find the Levenshtein distance between two Strings.
Python version of Levenshtein distance method implemented in Java at
U{http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm}.
This is the number of chang... | Find the Levenshtein distance between two Strings.
Python version of Levenshtein distance method implemented in Java at
U{http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm}.
This is the number of changes needed to change one String into
another, ... | Below is the the instruction that describes the task:
### Input:
Find the Levenshtein distance between two Strings.
Python version of Levenshtein distance method implemented in Java at
U{http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm}.
This is the... |
def from_parts(cls, parts):
"""
Return content types XML mapping each part in *parts* to the
appropriate content type and suitable for storage as
``[Content_Types].xml`` in an OPC package.
"""
cti = cls()
cti._defaults['rels'] = CT.OPC_RELATIONSHIPS
cti._d... | Return content types XML mapping each part in *parts* to the
appropriate content type and suitable for storage as
``[Content_Types].xml`` in an OPC package. | Below is the the instruction that describes the task:
### Input:
Return content types XML mapping each part in *parts* to the
appropriate content type and suitable for storage as
``[Content_Types].xml`` in an OPC package.
### Response:
def from_parts(cls, parts):
"""
Return content ... |
def list_themes(cls, path=THEMES):
"""
Compile all of the themes configuration files in the search path.
"""
themes, errors = [], OrderedDict()
def load_themes(path, source):
"""
Load all themes in the given path.
"""
if os.path.is... | Compile all of the themes configuration files in the search path. | Below is the the instruction that describes the task:
### Input:
Compile all of the themes configuration files in the search path.
### Response:
def list_themes(cls, path=THEMES):
"""
Compile all of the themes configuration files in the search path.
"""
themes, errors = [], OrderedD... |
def get_date_less_query(days, date_field):
"""
Query for if date_field is within number of "days" from now.
"""
query = None
days = get_integer(days)
if days:
future = get_days_from_now(days)
query = Q(**{"%s__lte" % date_field: future.isoformat()})
return query | Query for if date_field is within number of "days" from now. | Below is the the instruction that describes the task:
### Input:
Query for if date_field is within number of "days" from now.
### Response:
def get_date_less_query(days, date_field):
"""
Query for if date_field is within number of "days" from now.
"""
query = None
days = get_integer(days)
i... |
def _load_form_data(self):
"""Method used internally to retrieve submitted data. After calling
this sets `form` and `files` on the request object to multi dicts
filled with the incoming form data. As a matter of fact the input
stream will be empty afterwards. You can also call this me... | Method used internally to retrieve submitted data. After calling
this sets `form` and `files` on the request object to multi dicts
filled with the incoming form data. As a matter of fact the input
stream will be empty afterwards. You can also call this method to
force the parsing of t... | Below is the the instruction that describes the task:
### Input:
Method used internally to retrieve submitted data. After calling
this sets `form` and `files` on the request object to multi dicts
filled with the incoming form data. As a matter of fact the input
stream will be empty afterwa... |
def on_import1(self, event):
"""
initialize window to import an arbitrary file into the working directory
"""
pmag_menu_dialogs.MoveFileIntoWD(self.parent, self.parent.WD) | initialize window to import an arbitrary file into the working directory | Below is the the instruction that describes the task:
### Input:
initialize window to import an arbitrary file into the working directory
### Response:
def on_import1(self, event):
"""
initialize window to import an arbitrary file into the working directory
"""
pmag_menu_dialogs.Mov... |
def acos(x, context=None):
"""
Return the inverse cosine of ``x``.
The mathematically exact result lies in the range [0, π]. However, note
that as a result of rounding to the current context, it's possible for the
actual value returned to be fractionally larger than π::
>>> from bigfloat ... | Return the inverse cosine of ``x``.
The mathematically exact result lies in the range [0, π]. However, note
that as a result of rounding to the current context, it's possible for the
actual value returned to be fractionally larger than π::
>>> from bigfloat import precision
>>> with preci... | Below is the the instruction that describes the task:
### Input:
Return the inverse cosine of ``x``.
The mathematically exact result lies in the range [0, π]. However, note
that as a result of rounding to the current context, it's possible for the
actual value returned to be fractionally larger than π... |
def mount(self, identifier):
"""
Mounts a container or image referred to by identifier to
the host filesystem.
"""
driver = self.client.info()['Driver']
driver_mount_fn = getattr(self, "_mount_" + driver,
self._unsupported_backend)
... | Mounts a container or image referred to by identifier to
the host filesystem. | Below is the the instruction that describes the task:
### Input:
Mounts a container or image referred to by identifier to
the host filesystem.
### Response:
def mount(self, identifier):
"""
Mounts a container or image referred to by identifier to
the host filesystem.
"""
... |
def put(index_name, doc_type, identifier, body, force, verbose):
"""Index input data."""
result = current_search_client.index(
index=index_name,
doc_type=doc_type or index_name,
id=identifier,
body=json.load(body),
op_type='index' if force or identifier is None else 'crea... | Index input data. | Below is the the instruction that describes the task:
### Input:
Index input data.
### Response:
def put(index_name, doc_type, identifier, body, force, verbose):
"""Index input data."""
result = current_search_client.index(
index=index_name,
doc_type=doc_type or index_name,
id=ident... |
def convert_tstamp(response):
"""
Convert a Stripe API timestamp response (unix epoch) to a native datetime.
:rtype: datetime
"""
if response is None:
# Allow passing None to convert_tstamp()
return response
# Overrides the set timezone to UTC - I think...
tz = timezone.utc if settings.USE_TZ else None
r... | Convert a Stripe API timestamp response (unix epoch) to a native datetime.
:rtype: datetime | Below is the the instruction that describes the task:
### Input:
Convert a Stripe API timestamp response (unix epoch) to a native datetime.
:rtype: datetime
### Response:
def convert_tstamp(response):
"""
Convert a Stripe API timestamp response (unix epoch) to a native datetime.
:rtype: datetime
"""
if res... |
def distance(x0, x1, y0, y1):
"""
Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of point 1
Returns
-----... | Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of point 1
Returns
------
distance : float
square ... | Below is the the instruction that describes the task:
### Input:
Function that calculates the square of the distance between two points.
Parameters
-----
x0: x - coordinate of point 0
x1: x - coordinate of point 1
y0: y - coordinate of point 0
y1: y - coordinate of poin... |
def find_file(path, filename, max_depth=5):
"""Returns full filepath if the file is in path or a subdirectory."""
for root, dirs, files in os.walk(path):
if filename in files:
return os.path.join(root, filename)
# Don't search past max_depth
depth = root[len(path) + 1:].count(os.sep)
if depth... | Returns full filepath if the file is in path or a subdirectory. | Below is the the instruction that describes the task:
### Input:
Returns full filepath if the file is in path or a subdirectory.
### Response:
def find_file(path, filename, max_depth=5):
"""Returns full filepath if the file is in path or a subdirectory."""
for root, dirs, files in os.walk(path):
if filenam... |
def get_removes(self, profile=None):
"""Get filtered list of Remove objects in this Feature
:param str profile: Return Remove objects with this profile or None
to return all Remove objects.
:return: list of Remove objects
"""
out = []
for rem ... | Get filtered list of Remove objects in this Feature
:param str profile: Return Remove objects with this profile or None
to return all Remove objects.
:return: list of Remove objects | Below is the the instruction that describes the task:
### Input:
Get filtered list of Remove objects in this Feature
:param str profile: Return Remove objects with this profile or None
to return all Remove objects.
:return: list of Remove objects
### Response:
def get_r... |
def add_runnable(self, runnable):
"""
Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable
"""
if runnable.id in self.runnables:
raise SimErr... | Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable | Below is the the instruction that describes the task:
### Input:
Adds a runnable component to the list of runnable components in
this simulation.
@param runnable: A runnable component
@type runnable: lems.sim.runnable.Runnable
### Response:
def add_runnable(self, runnable):
"""
... |
def get_params_from_list(params_list):
"""Transform params list to dictionary.
"""
params = {}
for i in range(0, len(params_list)):
if '=' not in params_list[i]:
try:
if not isinstance(params[key], list): params[key] = [params[key]]
params[key] += [par... | Transform params list to dictionary. | Below is the the instruction that describes the task:
### Input:
Transform params list to dictionary.
### Response:
def get_params_from_list(params_list):
"""Transform params list to dictionary.
"""
params = {}
for i in range(0, len(params_list)):
if '=' not in params_list[i]:
t... |
def _get_banks_to_remove(redis_server, bank, path=''):
'''
A simple tree tarversal algorithm that builds the list of banks to remove,
starting from an arbitrary node in the tree.
'''
current_path = bank if not path else '{path}/{bank}'.format(path=path, bank=bank)
bank_paths_to_remove = [current... | A simple tree tarversal algorithm that builds the list of banks to remove,
starting from an arbitrary node in the tree. | Below is the the instruction that describes the task:
### Input:
A simple tree tarversal algorithm that builds the list of banks to remove,
starting from an arbitrary node in the tree.
### Response:
def _get_banks_to_remove(redis_server, bank, path=''):
'''
A simple tree tarversal algorithm that builds... |
def cancel(self, consumer_tag):
"""Cancel a channel by consumer tag."""
if not self.channel.conn:
return
self.channel.basic_cancel(consumer_tag) | Cancel a channel by consumer tag. | Below is the the instruction that describes the task:
### Input:
Cancel a channel by consumer tag.
### Response:
def cancel(self, consumer_tag):
"""Cancel a channel by consumer tag."""
if not self.channel.conn:
return
self.channel.basic_cancel(consumer_tag) |
def update(*args, **kwargs):
'''
Update installed plugin package(s).
Each plugin package must have a directory (**NOT** a link) containing a
``properties.yml`` file with a ``package_name`` value in the following
directory:
<conda prefix>/share/microdrop/plugins/available/
Parameters
... | Update installed plugin package(s).
Each plugin package must have a directory (**NOT** a link) containing a
``properties.yml`` file with a ``package_name`` value in the following
directory:
<conda prefix>/share/microdrop/plugins/available/
Parameters
----------
*args
Extra arg... | Below is the the instruction that describes the task:
### Input:
Update installed plugin package(s).
Each plugin package must have a directory (**NOT** a link) containing a
``properties.yml`` file with a ``package_name`` value in the following
directory:
<conda prefix>/share/microdrop/plugins/... |
def supports_proxies(*proxy_types):
'''
Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies
'''
def _supports_proxies(fn):
@wraps(fn)
def __supports_proxies(*args, **kwargs):
... | Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies | Below is the the instruction that describes the task:
### Input:
Decorator to specify which proxy types are supported by a function
proxy_types:
Arbitrary list of strings with the supported types of proxies
### Response:
def supports_proxies(*proxy_types):
'''
Decorator to specify which proxy ... |
def serialize(data, measurement=None, tag_columns=None, **extra_tags):
"""Converts input data into line protocol format"""
if isinstance(data, bytes):
return data
elif isinstance(data, str):
return data.encode('utf-8')
elif hasattr(data, 'to_lineprotocol'):
return data.to_linepro... | Converts input data into line protocol format | Below is the the instruction that describes the task:
### Input:
Converts input data into line protocol format
### Response:
def serialize(data, measurement=None, tag_columns=None, **extra_tags):
"""Converts input data into line protocol format"""
if isinstance(data, bytes):
return data
elif is... |
def apply_color_scheme(self, color_scheme):
"""
Apply a pygments color scheme to the console.
As there is not a 1 to 1 mapping between color scheme formats and
console formats, we decided to make the following mapping (it usually
looks good for most of the available pygments sty... | Apply a pygments color scheme to the console.
As there is not a 1 to 1 mapping between color scheme formats and
console formats, we decided to make the following mapping (it usually
looks good for most of the available pygments styles):
- stdout_color = normal color
- s... | Below is the the instruction that describes the task:
### Input:
Apply a pygments color scheme to the console.
As there is not a 1 to 1 mapping between color scheme formats and
console formats, we decided to make the following mapping (it usually
looks good for most of the available pygment... |
def default_output_format(content_type='application/json', apply_globally=False, api=None, cli=False, http=True):
"""A decorator that allows you to override the default output format for an API"""
def decorator(formatter):
formatter = hug.output_format.content_type(content_type)(formatter)
if ap... | A decorator that allows you to override the default output format for an API | Below is the the instruction that describes the task:
### Input:
A decorator that allows you to override the default output format for an API
### Response:
def default_output_format(content_type='application/json', apply_globally=False, api=None, cli=False, http=True):
"""A decorator that allows you to overrid... |
def restore_image_options(cli, image, options):
""" Restores CMD and ENTRYPOINT values of the image
This is needed because we force the overwrite of ENTRYPOINT and CMD in the
`run_code_in_container` function, to be able to run the code in the
container, through /bin/bash.
"""
dockerfile = io.St... | Restores CMD and ENTRYPOINT values of the image
This is needed because we force the overwrite of ENTRYPOINT and CMD in the
`run_code_in_container` function, to be able to run the code in the
container, through /bin/bash. | Below is the the instruction that describes the task:
### Input:
Restores CMD and ENTRYPOINT values of the image
This is needed because we force the overwrite of ENTRYPOINT and CMD in the
`run_code_in_container` function, to be able to run the code in the
container, through /bin/bash.
### Response:
de... |
def _enforce_width(text, width, unicode_aware=True):
"""
Enforce a displayed piece of text to be a certain number of cells wide. This takes into
account double-width characters used in CJK languages.
:param text: The text to be truncated
:param width: The screen cell width to enforce
:return: ... | Enforce a displayed piece of text to be a certain number of cells wide. This takes into
account double-width characters used in CJK languages.
:param text: The text to be truncated
:param width: The screen cell width to enforce
:return: The resulting truncated text | Below is the the instruction that describes the task:
### Input:
Enforce a displayed piece of text to be a certain number of cells wide. This takes into
account double-width characters used in CJK languages.
:param text: The text to be truncated
:param width: The screen cell width to enforce
:retu... |
def create(host, port):
"""
Prepare server to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperServer], callable | None
"""
wrapper = WrapperServer({
'server': None
})
d = {
'listen_port': port,
'changer': wrapper
}
if host:
... | Prepare server to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperServer], callable | None | Below is the the instruction that describes the task:
### Input:
Prepare server to execute
:return: Modules to execute, cmd line function
:rtype: list[WrapperServer], callable | None
### Response:
def create(host, port):
"""
Prepare server to execute
:return: Modules to execute, cmd line func... |
def gauss(x,m_y,sigma):
'''returns the gaussian with mean m_y and std. dev. sigma,
calculated at the points of x.'''
e_y = [np.exp((1.0/(2*float(sigma)**2)*-(n-m_y)**2)) for n in np.array(x)]
y = [1.0/(float(sigma) * np.sqrt(2 * np.pi)) * e for e in e_y]
return np.array(y) | returns the gaussian with mean m_y and std. dev. sigma,
calculated at the points of x. | Below is the the instruction that describes the task:
### Input:
returns the gaussian with mean m_y and std. dev. sigma,
calculated at the points of x.
### Response:
def gauss(x,m_y,sigma):
'''returns the gaussian with mean m_y and std. dev. sigma,
calculated at the points of x.'''
e_y = [np.exp((1.0/(2*f... |
def update(self, data):
""" Update meta of one document."""
self.debug(data)
self._check(data)
wg_uuid = data.get('workGroup')
self.log.debug("wg_uuid : %s ", wg_uuid)
uuid = data.get('uuid')
url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % {
'base': self... | Update meta of one document. | Below is the the instruction that describes the task:
### Input:
Update meta of one document.
### Response:
def update(self, data):
""" Update meta of one document."""
self.debug(data)
self._check(data)
wg_uuid = data.get('workGroup')
self.log.debug("wg_uuid : %s ", wg_uuid)... |
def evaluator(evaluate):
"""Return an inspyred evaluator function based on the given function.
This function generator takes a function that evaluates only one
candidate. The generator handles the iteration over each candidate
to be evaluated.
The given function ``evaluate`` must have the fol... | Return an inspyred evaluator function based on the given function.
This function generator takes a function that evaluates only one
candidate. The generator handles the iteration over each candidate
to be evaluated.
The given function ``evaluate`` must have the following signature::
... | Below is the the instruction that describes the task:
### Input:
Return an inspyred evaluator function based on the given function.
This function generator takes a function that evaluates only one
candidate. The generator handles the iteration over each candidate
to be evaluated.
The given fu... |
def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
"""
ins = inspect(table)
return ((k, c.name) for k, c in ins.mapper.c.items()) | Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table. | Below is the the instruction that describes the task:
### Input:
Return a generator of tuples k, c such that k is the name of the python attribute for
the column and c is the name of the column in the sql table.
### Response:
def get_column_keys_and_names(table):
"""
Return a generator of tuples k, c s... |
def get_ratetimestamp(self, base, code):
"""Return rate timestamp as a datetime/date or None"""
self.get_latestcurrencyrates(base)
try:
return datetime.fromtimestamp(self.rates["timestamp"])
except KeyError:
return None | Return rate timestamp as a datetime/date or None | Below is the the instruction that describes the task:
### Input:
Return rate timestamp as a datetime/date or None
### Response:
def get_ratetimestamp(self, base, code):
"""Return rate timestamp as a datetime/date or None"""
self.get_latestcurrencyrates(base)
try:
return datetime... |
def list_pages_ajax(request, invalid_move=False):
"""Render pages table for ajax function."""
language = get_language_from_request(request)
pages = Page.objects.root()
context = {
'can_publish': request.user.has_perm('pages.can_publish'),
'invalid_move': invalid_move,
'language':... | Render pages table for ajax function. | Below is the the instruction that describes the task:
### Input:
Render pages table for ajax function.
### Response:
def list_pages_ajax(request, invalid_move=False):
"""Render pages table for ajax function."""
language = get_language_from_request(request)
pages = Page.objects.root()
context = {
... |
def toc(tt, return_msg=False, write_msg=True, verbose=None):
"""
similar to matlab toc
SeeAlso:
ut.tic
"""
if verbose is not None:
write_msg = verbose
(msg, start_time) = tt
ellapsed = (default_timer() - start_time)
if (not return_msg) and write_msg and msg is not None:
... | similar to matlab toc
SeeAlso:
ut.tic | Below is the the instruction that describes the task:
### Input:
similar to matlab toc
SeeAlso:
ut.tic
### Response:
def toc(tt, return_msg=False, write_msg=True, verbose=None):
"""
similar to matlab toc
SeeAlso:
ut.tic
"""
if verbose is not None:
write_msg = verbo... |
def add_to_bar_plot(ax, x, number, name = '', color = '0.'):
''' This function takes an axes and adds one bar to it '''
plt.sca(ax)
plt.setp(ax,xticks=np.append(ax.get_xticks(),np.array([x]))\
,xticklabels=[item.get_text() for item in ax.get_xticklabels()] +[name])
plt.bar([x],number , colo... | This function takes an axes and adds one bar to it | Below is the the instruction that describes the task:
### Input:
This function takes an axes and adds one bar to it
### Response:
def add_to_bar_plot(ax, x, number, name = '', color = '0.'):
''' This function takes an axes and adds one bar to it '''
plt.sca(ax)
plt.setp(ax,xticks=np.append(ax.get_xtick... |
def get_sections(self, gradebook_id='', simple=False):
"""Get the sections for a gradebook.
Return a dictionary of types of sections containing a list of that
type for a given gradebook. Specified by a gradebookid.
If simple=True, a list of dictionaries is provided for each
se... | Get the sections for a gradebook.
Return a dictionary of types of sections containing a list of that
type for a given gradebook. Specified by a gradebookid.
If simple=True, a list of dictionaries is provided for each
section regardless of type. The dictionary only contains one
... | Below is the the instruction that describes the task:
### Input:
Get the sections for a gradebook.
Return a dictionary of types of sections containing a list of that
type for a given gradebook. Specified by a gradebookid.
If simple=True, a list of dictionaries is provided for each
... |
def percent_covered(self, src_path):
"""
Return a float percent of lines covered for the source
in `src_path`.
If we have no coverage information for `src_path`, returns None
"""
diff_violations = self._diff_violations().get(src_path)
if diff_violations is None:... | Return a float percent of lines covered for the source
in `src_path`.
If we have no coverage information for `src_path`, returns None | Below is the the instruction that describes the task:
### Input:
Return a float percent of lines covered for the source
in `src_path`.
If we have no coverage information for `src_path`, returns None
### Response:
def percent_covered(self, src_path):
"""
Return a float percent of li... |
def _export_single_project(self):
""" A single project export """
expanded_dic = self.workspace.copy()
self._fix_paths(expanded_dic)
# generic tool template specified or project
if expanded_dic['template']:
template_ewp = False
template_ewd = False
... | A single project export | Below is the the instruction that describes the task:
### Input:
A single project export
### Response:
def _export_single_project(self):
""" A single project export """
expanded_dic = self.workspace.copy()
self._fix_paths(expanded_dic)
# generic tool template specified or project
... |
def outstanding(self):
"""Returns whether or not this barrier has pending work."""
# Allow the same WorkItem to be yielded multiple times but not
# count towards blocking the barrier.
done_count = 0
for item in self:
if not self.wait_any and item.fire_and_forget:
... | Returns whether or not this barrier has pending work. | Below is the the instruction that describes the task:
### Input:
Returns whether or not this barrier has pending work.
### Response:
def outstanding(self):
"""Returns whether or not this barrier has pending work."""
# Allow the same WorkItem to be yielded multiple times but not
# count towa... |
def bcrop(v, dsz, dimN=2):
"""Crop specified number of initial spatial dimensions of dictionary
array to specified size. Parameter `dsz` must be a tuple having one
of the following forms (the examples assume two spatial/temporal
dimensions). If all filters are of the same size, then
::
(flt_... | Crop specified number of initial spatial dimensions of dictionary
array to specified size. Parameter `dsz` must be a tuple having one
of the following forms (the examples assume two spatial/temporal
dimensions). If all filters are of the same size, then
::
(flt_rows, filt_cols, num_filt)
ma... | Below is the the instruction that describes the task:
### Input:
Crop specified number of initial spatial dimensions of dictionary
array to specified size. Parameter `dsz` must be a tuple having one
of the following forms (the examples assume two spatial/temporal
dimensions). If all filters are of the s... |
def geometries(self):
"""Return an iterator of (shapely) geometries for this feature."""
# Ensure that the associated files are in the cache
fname = '{}_{}'.format(self.name, self.scale)
for extension in ['.dbf', '.shx']:
get_test_data(fname + extension)
path = get_te... | Return an iterator of (shapely) geometries for this feature. | Below is the the instruction that describes the task:
### Input:
Return an iterator of (shapely) geometries for this feature.
### Response:
def geometries(self):
"""Return an iterator of (shapely) geometries for this feature."""
# Ensure that the associated files are in the cache
fname = '{... |
def gtd7d(Input, flags, output): # pragma: no cover
'''A separate subroutine (GTD7D) computes the ‘‘effec-
tive’’ mass density by summing the thermospheric mass
density and the mass density of the anomalous oxygen
component. Below 500 km, the effective mass density is
equivalent to the thermospheric... | A separate subroutine (GTD7D) computes the ‘‘effec-
tive’’ mass density by summing the thermospheric mass
density and the mass density of the anomalous oxygen
component. Below 500 km, the effective mass density is
equivalent to the thermospheric mass density, and we drop
the distinction. | Below is the the instruction that describes the task:
### Input:
A separate subroutine (GTD7D) computes the ‘‘effec-
tive’’ mass density by summing the thermospheric mass
density and the mass density of the anomalous oxygen
component. Below 500 km, the effective mass density is
equivalent to the the... |
def DiffArrayObjects(self, oldObj, newObj, isElementLinks=False):
"""Method which deligates the diffing of arrays based on the type"""
if oldObj == newObj:
return True
if not oldObj or not newObj:
return False
if len(oldObj) != len(newObj):
__Log__.debug('DiffArrayObje... | Method which deligates the diffing of arrays based on the type | Below is the the instruction that describes the task:
### Input:
Method which deligates the diffing of arrays based on the type
### Response:
def DiffArrayObjects(self, oldObj, newObj, isElementLinks=False):
"""Method which deligates the diffing of arrays based on the type"""
if oldObj == newObj:
... |
def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:
"""
Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object.
"""
return {k: v for k, v in obj.items() if v is not None} | Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object. | Below is the the instruction that describes the task:
### Input:
Return a new copied dictionary without the keys with ``None`` values from
the given Mapping object.
### Response:
def clean_map(obj: Mapping[Any, Any]) -> Mapping[Any, Any]:
"""
Return a new copied dictionary without the keys with ``None`... |
def minmax(self, constraints, x, iters=10000):
"""Returns the min and max possible values for x within given constraints"""
if issymbolic(x):
m = self.min(constraints, x, iters)
M = self.max(constraints, x, iters)
return m, M
else:
return x, x | Returns the min and max possible values for x within given constraints | Below is the the instruction that describes the task:
### Input:
Returns the min and max possible values for x within given constraints
### Response:
def minmax(self, constraints, x, iters=10000):
"""Returns the min and max possible values for x within given constraints"""
if issymbolic(x):
... |
def generate_dims_coords(shape, var_name, dims=None, coords=None, default_dims=None):
"""Generate default dimensions and coordinates for a variable.
Parameters
----------
shape : tuple[int]
Shape of the variable
var_name : str
Name of the variable. Used in the default name, if neces... | Generate default dimensions and coordinates for a variable.
Parameters
----------
shape : tuple[int]
Shape of the variable
var_name : str
Name of the variable. Used in the default name, if necessary
dims : list
List of dimensions for the variable
coords : dict[str] -> li... | Below is the the instruction that describes the task:
### Input:
Generate default dimensions and coordinates for a variable.
Parameters
----------
shape : tuple[int]
Shape of the variable
var_name : str
Name of the variable. Used in the default name, if necessary
dims : list
... |
def predictionExtent(inputs, resets, outputs, minOverlapPct=100.0):
"""
Computes the predictive ability of a temporal memory (TM). This routine returns
a value which is the average number of time steps of prediction provided
by the TM. It accepts as input the inputs, outputs, and resets provided to
the TM as ... | Computes the predictive ability of a temporal memory (TM). This routine returns
a value which is the average number of time steps of prediction provided
by the TM. It accepts as input the inputs, outputs, and resets provided to
the TM as well as a 'minOverlapPct' used to evalulate whether or not a
prediction is... | Below is the the instruction that describes the task:
### Input:
Computes the predictive ability of a temporal memory (TM). This routine returns
a value which is the average number of time steps of prediction provided
by the TM. It accepts as input the inputs, outputs, and resets provided to
the TM as well as... |
def resume_transfer_operation(self, operation_name):
"""
Resumes an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None
"""
self.get_conn().transferOperati... | Resumes an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None | Below is the the instruction that describes the task:
### Input:
Resumes an transfer operation in Google Storage Transfer Service.
:param operation_name: (Required) Name of the transfer operation.
:type operation_name: str
:rtype: None
### Response:
def resume_transfer_operation(self, oper... |
def create_comment(self, comment_form):
"""Creates a new ``Comment``.
arg: comment_form (osid.commenting.CommentForm): the form for
this ``Comment``
return: (osid.commenting.Comment) - the new ``Comment``
raise: IllegalState - ``comment_form`` already used in a creat... | Creates a new ``Comment``.
arg: comment_form (osid.commenting.CommentForm): the form for
this ``Comment``
return: (osid.commenting.Comment) - the new ``Comment``
raise: IllegalState - ``comment_form`` already used in a create
transaction
raise: Inval... | Below is the the instruction that describes the task:
### Input:
Creates a new ``Comment``.
arg: comment_form (osid.commenting.CommentForm): the form for
this ``Comment``
return: (osid.commenting.Comment) - the new ``Comment``
raise: IllegalState - ``comment_form`` alrea... |
def show(self, n=10, headers=(), tablefmt="simple", floatfmt="g", numalign="decimal",
stralign="left", missingval=""):
"""
Pretty print first n rows of sequence as a table. See
https://bitbucket.org/astanin/python-tabulate for details on tabulate parameters
:param n: Number... | Pretty print first n rows of sequence as a table. See
https://bitbucket.org/astanin/python-tabulate for details on tabulate parameters
:param n: Number of rows to show
:param headers: Passed to tabulate
:param tablefmt: Passed to tabulate
:param floatfmt: Passed to tabulate
... | Below is the the instruction that describes the task:
### Input:
Pretty print first n rows of sequence as a table. See
https://bitbucket.org/astanin/python-tabulate for details on tabulate parameters
:param n: Number of rows to show
:param headers: Passed to tabulate
:param tablefmt... |
def get_parent_book_nodes(self):
"""Gets the parents of this book.
return: (osid.commenting.BookNodeList) - the parents of this
book
*compliance: mandatory -- This method must be implemented.*
"""
parent_book_nodes = []
for node in self._my_map['parentNo... | Gets the parents of this book.
return: (osid.commenting.BookNodeList) - the parents of this
book
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Gets the parents of this book.
return: (osid.commenting.BookNodeList) - the parents of this
book
*compliance: mandatory -- This method must be implemented.*
### Response:
def get_parent_book_nodes(self):
"""Ge... |
def register_language(self, language):
"""
Registers given language in the :obj:`LanguagesModel.languages` class property.
:param language: Language to register.
:type language: Language
:return: Method success.
:rtype: bool
"""
if self.get_language(lang... | Registers given language in the :obj:`LanguagesModel.languages` class property.
:param language: Language to register.
:type language: Language
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Registers given language in the :obj:`LanguagesModel.languages` class property.
:param language: Language to register.
:type language: Language
:return: Method success.
:rtype: bool
### Response:
def register_language... |
def list(cls, rc_file='~/.odoorpcrc'):
"""Return a list of all stored sessions available in the
`rc_file` file:
.. doctest::
:options: +SKIP
>>> import odoorpc
>>> odoorpc.ODOO.list()
['foo', 'bar']
Use the :func:`save <odoorpc.ODOO.save... | Return a list of all stored sessions available in the
`rc_file` file:
.. doctest::
:options: +SKIP
>>> import odoorpc
>>> odoorpc.ODOO.list()
['foo', 'bar']
Use the :func:`save <odoorpc.ODOO.save>` and
:func:`load <odoorpc.ODOO.load>` me... | Below is the the instruction that describes the task:
### Input:
Return a list of all stored sessions available in the
`rc_file` file:
.. doctest::
:options: +SKIP
>>> import odoorpc
>>> odoorpc.ODOO.list()
['foo', 'bar']
Use the :func:`save... |
def setChargingStationStop(self, vehID, stopID, duration=2**31 - 1, until=-1, flags=tc.STOP_DEFAULT):
"""setChargingStationStop(string, string, integer, integer, integer) -> None
Adds or modifies a stop at a chargingStation with the given parameters. The duration and the until attribute are
in ... | setChargingStationStop(string, string, integer, integer, integer) -> None
Adds or modifies a stop at a chargingStation with the given parameters. The duration and the until attribute are
in milliseconds. | Below is the the instruction that describes the task:
### Input:
setChargingStationStop(string, string, integer, integer, integer) -> None
Adds or modifies a stop at a chargingStation with the given parameters. The duration and the until attribute are
in milliseconds.
### Response:
def setCharging... |
def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args):
"""
:type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration
:type terminal_controller: fake_switches.terminal.TerminalController
:type logger: logging.Logger
:ty... | :type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration
:type terminal_controller: fake_switches.terminal.TerminalController
:type logger: logging.Logger
:type piping_processor: fake_switches.command_processing.piping_processor_base.PipingProcessorBase | Below is the the instruction that describes the task:
### Input:
:type switch_configuration: fake_switches.switch_configuration.SwitchConfiguration
:type terminal_controller: fake_switches.terminal.TerminalController
:type logger: logging.Logger
:type piping_processor: fake_switches.command_... |
def rotate_y(self, angle):
"""
Rotates mesh about the y-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis.
"""
axis_rotation(self.points, angle, inplace=True, axis='y') | Rotates mesh about the y-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis. | Below is the the instruction that describes the task:
### Input:
Rotates mesh about the y-axis.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis.
### Response:
def rotate_y(self, angle):
"""
Rotates mesh about the y-axis.
... |
def deduplication_backup(self, process_bar):
"""
Backup the current file and compare the content.
:param process_bar: tqdm process bar
"""
self.fast_backup = False # Was a fast backup used?
src_path = self.dir_path.resolved_path
log.debug("*** deduplication bac... | Backup the current file and compare the content.
:param process_bar: tqdm process bar | Below is the the instruction that describes the task:
### Input:
Backup the current file and compare the content.
:param process_bar: tqdm process bar
### Response:
def deduplication_backup(self, process_bar):
"""
Backup the current file and compare the content.
:param process_bar... |
def run_kernel(self, func, c_args, threads, grid):
"""runs the kernel once, returns whatever the kernel returns
:param func: A C function compiled for this specific configuration
:type func: ctypes._FuncPtr
:param c_args: A list of arguments to the function, order should match the
... | runs the kernel once, returns whatever the kernel returns
:param func: A C function compiled for this specific configuration
:type func: ctypes._FuncPtr
:param c_args: A list of arguments to the function, order should match the
order in the code. The list should be prepared using
... | Below is the the instruction that describes the task:
### Input:
runs the kernel once, returns whatever the kernel returns
:param func: A C function compiled for this specific configuration
:type func: ctypes._FuncPtr
:param c_args: A list of arguments to the function, order should match t... |
def _clear_block_deco(self):
"""Clear the folded block decorations."""
for deco in self._block_decos:
self.editor.decorations.remove(deco)
self._block_decos[:] = [] | Clear the folded block decorations. | Below is the the instruction that describes the task:
### Input:
Clear the folded block decorations.
### Response:
def _clear_block_deco(self):
"""Clear the folded block decorations."""
for deco in self._block_decos:
self.editor.decorations.remove(deco)
self._block_decos[:] = [] |
def set_published(self, value=None):
"""stub"""
if value is None:
raise NullArgument()
if self.get_published_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_object_form._is_valid_boolean(value):
raise InvalidArgument()
self.my_o... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def set_published(self, value=None):
"""stub"""
if value is None:
raise NullArgument()
if self.get_published_metadata().is_read_only():
raise NoAccess()
if not self.my_osid_ob... |
def event(from_states=None, to_state=None):
""" a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only. """
from_states_tuple = (from_states, ) if isinstance(from_states, State) else tuple(from_states or [])
if not len(from_states_tup... | a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only. | Below is the the instruction that describes the task:
### Input:
a decorator for transitioning from certain states to a target state. must be used on bound methods of a class
instance, only.
### Response:
def event(from_states=None, to_state=None):
""" a decorator for transitioning from certain states to a... |
def _derive_log_path(self):
"""Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
u... | Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a nondeterministic way,
using the current time. We return the l... | Below is the the instruction that describes the task:
### Input:
Guess logfile path produced by Mothur
This method checks the working directory for log files
generated by Mothur. It will raise an ApplicationError if no
log file can be found.
Mothur generates log files named in a n... |
def pkcs7_unpad(buf):
# type: (bytes) -> bytes
"""Removes PKCS7 padding a decrypted object
:param bytes buf: buffer to remove padding
:rtype: bytes
:return: buffer without PKCS7_PADDING
"""
unpadder = cryptography.hazmat.primitives.padding.PKCS7(
cryptography.hazmat.primitives.cipher... | Removes PKCS7 padding a decrypted object
:param bytes buf: buffer to remove padding
:rtype: bytes
:return: buffer without PKCS7_PADDING | Below is the the instruction that describes the task:
### Input:
Removes PKCS7 padding a decrypted object
:param bytes buf: buffer to remove padding
:rtype: bytes
:return: buffer without PKCS7_PADDING
### Response:
def pkcs7_unpad(buf):
# type: (bytes) -> bytes
"""Removes PKCS7 padding a decryp... |
def group_objects_by(self, list, attr, valueLabel="value", childrenLabel="children"):
"""
Generates a group object based on the attribute value on of the given attr value that is passed in.
:param list list: A list of dictionary objects
:param str attr: The attribute that the dictionari... | Generates a group object based on the attribute value on of the given attr value that is passed in.
:param list list: A list of dictionary objects
:param str attr: The attribute that the dictionaries should be sorted upon
:param str valueLabel: What to call the key of the field we're sorting up... | Below is the the instruction that describes the task:
### Input:
Generates a group object based on the attribute value on of the given attr value that is passed in.
:param list list: A list of dictionary objects
:param str attr: The attribute that the dictionaries should be sorted upon
:par... |
def load(self):
"""
Loads the state of a previously saved CallStack to this instance.
"""
s = load_stack(self)
if s:
self.hooks = s.hooks
self.calls = s.calls | Loads the state of a previously saved CallStack to this instance. | Below is the the instruction that describes the task:
### Input:
Loads the state of a previously saved CallStack to this instance.
### Response:
def load(self):
"""
Loads the state of a previously saved CallStack to this instance.
"""
s = load_stack(self)
if s:
... |
def _tag_and_field_maker(self, event):
'''
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = {u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... ... | >>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = {u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... u'ln': 8,
... ... | Below is the the instruction that describes the task:
### Input:
>>> idbf = InfluxDBForwarder('no_host', '8086', 'deadpool',
... 'chimichanga', 'logs', 'collection')
>>> log = {u'data': {u'_': {u'file': u'log.py',
... u'fn': u'start',
... |
def qos_queue_scheduler_strict_priority_dwrr_traffic_class4(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
queue = ET.SubElement(qos, "queue")
scheduler = ET.SubElement... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def qos_queue_scheduler_strict_priority_dwrr_traffic_class4(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:broc... |
def unassign_log_entry_from_log(self, log_entry_id, log_id):
"""Removes a ``LogEntry`` from a ``Log``.
arg: log_entry_id (osid.id.Id): the ``Id`` of the
``LogEntry``
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
raise: NotFound - ``log_entry_id`` or ``log_id... | Removes a ``LogEntry`` from a ``Log``.
arg: log_entry_id (osid.id.Id): the ``Id`` of the
``LogEntry``
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
raise: NotFound - ``log_entry_id`` or ``log_id`` not found or
``log_entry_id`` not assigned to ``log_i... | Below is the the instruction that describes the task:
### Input:
Removes a ``LogEntry`` from a ``Log``.
arg: log_entry_id (osid.id.Id): the ``Id`` of the
``LogEntry``
arg: log_id (osid.id.Id): the ``Id`` of the ``Log``
raise: NotFound - ``log_entry_id`` or ``log_id`` ... |
def p_scalar__doublequote(self, p):
"""
scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END
"""
scalar = re.sub('\n\s+', ' ', str(p[2]))
p[0] = Str(scalar.replace('\\"', '"')) | scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END | Below is the the instruction that describes the task:
### Input:
scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END
### Response:
def p_scalar__doublequote(self, p):
"""
scalar : DOUBLEQUOTE_START SCALAR DOUBLEQUOTE_END
"""
scalar = re.sub('\n\s+', ' ', str(p[2]))
p[0] = S... |
def suggest(self, index=None, body=None, params=None):
"""
The suggest feature suggests similar looking terms based on a provided
text by using a suggester.
`<http://elasticsearch.org/guide/reference/api/search/suggest/>`_
:arg index: A comma-separated list of index names to res... | The suggest feature suggests similar looking terms based on a provided
text by using a suggester.
`<http://elasticsearch.org/guide/reference/api/search/suggest/>`_
:arg index: A comma-separated list of index names to restrict the
operation; use `_all` or empty string to perform the ... | Below is the the instruction that describes the task:
### Input:
The suggest feature suggests similar looking terms based on a provided
text by using a suggester.
`<http://elasticsearch.org/guide/reference/api/search/suggest/>`_
:arg index: A comma-separated list of index names to restrict ... |
def run(self, timeout=-1):
"""
Run the subprocess.
Arguments:
timeout (optional) If a positive real value, then timout after
the given number of seconds.
Raises:
SubprocessError If subprocess has not completed after "timeout"
seco... | Run the subprocess.
Arguments:
timeout (optional) If a positive real value, then timout after
the given number of seconds.
Raises:
SubprocessError If subprocess has not completed after "timeout"
seconds. | Below is the the instruction that describes the task:
### Input:
Run the subprocess.
Arguments:
timeout (optional) If a positive real value, then timout after
the given number of seconds.
Raises:
SubprocessError If subprocess has not completed after "timeout... |
def route(app_or_blueprint, context=default_context, **kwargs):
""" attach a transmute route. """
def decorator(fn):
fn = describe(**kwargs)(fn)
transmute_func = TransmuteFunction(fn)
routes, handler = create_routes_and_handler(transmute_func, context)
for r in routes:
... | attach a transmute route. | Below is the the instruction that describes the task:
### Input:
attach a transmute route.
### Response:
def route(app_or_blueprint, context=default_context, **kwargs):
""" attach a transmute route. """
def decorator(fn):
fn = describe(**kwargs)(fn)
transmute_func = TransmuteFunction(fn)
... |
def __crawler_start(self):
"""Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:... | Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:
`__crawler_stop()` and `_... | Below is the the instruction that describes the task:
### Input:
Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11... |
def soviet_checksum(code):
"""Courtesy of Sir Vlad Lavrov."""
def sum_digits(code, offset=1):
total = 0
for digit, index in zip(code[:7], count(offset)):
total += int(digit) * index
summed = (total / 11 * 11)
return total - summed
check = sum_digits(code, 1)
... | Courtesy of Sir Vlad Lavrov. | Below is the the instruction that describes the task:
### Input:
Courtesy of Sir Vlad Lavrov.
### Response:
def soviet_checksum(code):
"""Courtesy of Sir Vlad Lavrov."""
def sum_digits(code, offset=1):
total = 0
for digit, index in zip(code[:7], count(offset)):
total += int(digi... |
def get_unique_fields(cls):
"""
Return a list of fields with "unique" attribute, which needs to
be augmented by the language.
"""
unique_fields = []
for fname, field in cls.__dict__.items():
if isinstance(field, models.fields.Field):
if getatt... | Return a list of fields with "unique" attribute, which needs to
be augmented by the language. | Below is the the instruction that describes the task:
### Input:
Return a list of fields with "unique" attribute, which needs to
be augmented by the language.
### Response:
def get_unique_fields(cls):
"""
Return a list of fields with "unique" attribute, which needs to
be augmented b... |
def _split(self, rect):
"""
Split all max_rects intersecting the rectangle rect into up to
4 new max_rects.
Arguments:
rect (Rectangle): Rectangle
Returns:
split (Rectangle list): List of rectangles resulting from the split
"""
ma... | Split all max_rects intersecting the rectangle rect into up to
4 new max_rects.
Arguments:
rect (Rectangle): Rectangle
Returns:
split (Rectangle list): List of rectangles resulting from the split | Below is the the instruction that describes the task:
### Input:
Split all max_rects intersecting the rectangle rect into up to
4 new max_rects.
Arguments:
rect (Rectangle): Rectangle
Returns:
split (Rectangle list): List of rectangles resulting from the spl... |
def init_with_context(self, context):
"""
Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class.
"""
from admin_tools.menu.models import Bookmark
for b in Bookmark.objects.fil... | Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class. | Below is the the instruction that describes the task:
### Input:
Please refer to
:meth:`~admin_tools.menu.items.MenuItem.init_with_context`
documentation from :class:`~admin_tools.menu.items.MenuItem` class.
### Response:
def init_with_context(self, context):
"""
Please refer to
... |
def get_word_from_data(self, data, offset):
"""Convert two bytes of data to a word (little endian)
'offset' is assumed to index into a word array. So setting it to
N will return a dword out of the data starting at offset N*2.
Returns None if the data can't be turned into a word.
... | Convert two bytes of data to a word (little endian)
'offset' is assumed to index into a word array. So setting it to
N will return a dword out of the data starting at offset N*2.
Returns None if the data can't be turned into a word. | Below is the the instruction that describes the task:
### Input:
Convert two bytes of data to a word (little endian)
'offset' is assumed to index into a word array. So setting it to
N will return a dword out of the data starting at offset N*2.
Returns None if the data can't be turned into ... |
def split_frame(self, ratios=None, destination_frames=None, seed=None):
"""
Split a frame into distinct subsets of size determined by the given ratios.
The number of subsets is always 1 more than the number of ratios given. Note that
this does not give an exact split. H2O is designed to... | Split a frame into distinct subsets of size determined by the given ratios.
The number of subsets is always 1 more than the number of ratios given. Note that
this does not give an exact split. H2O is designed to be efficient on big data
using a probabilistic splitting method rather than an exac... | Below is the the instruction that describes the task:
### Input:
Split a frame into distinct subsets of size determined by the given ratios.
The number of subsets is always 1 more than the number of ratios given. Note that
this does not give an exact split. H2O is designed to be efficient on big da... |
def calculate_eclipses(M1s, M2s, R1s, R2s, mag1s, mag2s,
u11s=0.394, u21s=0.296, u12s=0.394, u22s=0.296,
Ps=None, period=None, logperkde=RAGHAVAN_LOGPERKDE,
incs=None, eccs=None,
mininc=None, calc_mininc=True,
... | Returns random eclipse parameters for provided inputs
:param M1s, M2s, R1s, R2s, mag1s, mag2s: (array-like)
Primary and secondary properties (mass, radius, magnitude)
:param u11s, u21s, u12s, u22s: (optional)
Limb darkening parameters (u11 = u1 for star 1, u21 = u2 for star 1, etc.)
:par... | Below is the the instruction that describes the task:
### Input:
Returns random eclipse parameters for provided inputs
:param M1s, M2s, R1s, R2s, mag1s, mag2s: (array-like)
Primary and secondary properties (mass, radius, magnitude)
:param u11s, u21s, u12s, u22s: (optional)
Limb darkening ... |
def pathjoin(*args, **kwargs):
"""
Arguments:
args (list): *args list of paths
if len(args) == 1, args[0] is not a string, and args[0] is iterable,
set args to args[0].
Basically::
joined_path = u'/'.join(
[args[0].rstrip('/')] +
[a.strip('/'... | Arguments:
args (list): *args list of paths
if len(args) == 1, args[0] is not a string, and args[0] is iterable,
set args to args[0].
Basically::
joined_path = u'/'.join(
[args[0].rstrip('/')] +
[a.strip('/') for a in args[1:-1]] +
[args[... | Below is the the instruction that describes the task:
### Input:
Arguments:
args (list): *args list of paths
if len(args) == 1, args[0] is not a string, and args[0] is iterable,
set args to args[0].
Basically::
joined_path = u'/'.join(
[args[0].rstrip('/')] ... |
def sketch_fasta(fasta_path, outdir):
"""Create a Mash sketch from an input fasta file
Args:
fasta_path (str): input fasta file path. Genome name in fasta filename
outdir (str): output directory path to write Mash sketch file to
Returns:
str: output Mash sketch file path
"""
... | Create a Mash sketch from an input fasta file
Args:
fasta_path (str): input fasta file path. Genome name in fasta filename
outdir (str): output directory path to write Mash sketch file to
Returns:
str: output Mash sketch file path | Below is the the instruction that describes the task:
### Input:
Create a Mash sketch from an input fasta file
Args:
fasta_path (str): input fasta file path. Genome name in fasta filename
outdir (str): output directory path to write Mash sketch file to
Returns:
str: output Mash ske... |
def process_data(self, data, cloud_cover='total_clouds', **kwargs):
"""
Defines the steps needed to convert raw forecast data
into processed forecast data.
Parameters
----------
data: DataFrame
Raw forecast data
cloud_cover: str, default 'total_clouds... | Defines the steps needed to convert raw forecast data
into processed forecast data.
Parameters
----------
data: DataFrame
Raw forecast data
cloud_cover: str, default 'total_clouds'
The type of cloud cover used to infer the irradiance.
Returns
... | Below is the the instruction that describes the task:
### Input:
Defines the steps needed to convert raw forecast data
into processed forecast data.
Parameters
----------
data: DataFrame
Raw forecast data
cloud_cover: str, default 'total_clouds'
The t... |
def get_status(dom):
"""
Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict
"""
status = {}
status_entry = OneLogin_Saml2_Utils.query(dom, '/samlp... | Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Gets Status from a Response.
:param dom: The Response as XML
:type: Document
:returns: The Status, an array with the code and a message.
:rtype: dict
### Response:
def get_status(dom):
"""
Gets Status... |
def _attribute_definition(self, attrid):
""" Returns the attribute definition dict of a given attribute
ID, can be the name or the integer ID """
attrs = self._schema["attributes"]
try:
# Make a new dict to avoid side effects
return dict(attrs[attrid])
ex... | Returns the attribute definition dict of a given attribute
ID, can be the name or the integer ID | Below is the the instruction that describes the task:
### Input:
Returns the attribute definition dict of a given attribute
ID, can be the name or the integer ID
### Response:
def _attribute_definition(self, attrid):
""" Returns the attribute definition dict of a given attribute
ID, can be ... |
def add_job(cls, identifier, queue_name=None, priority=0, queue_model=None,
prepend=False, delayed_for=None, delayed_until=None,
**fields_if_new):
"""
Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new... | Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new one, don't touch it, else move the job to the wanted queue.
Before setting/moving the job to the queue, check for a `delayed_for`
(int/foat/timedelta) or `delayed_until` (datetime) a... | Below is the the instruction that describes the task:
### Input:
Add a job to a queue.
If this job already exists, check it's current priority. If its higher
than the new one, don't touch it, else move the job to the wanted queue.
Before setting/moving the job to the queue, check for a `dela... |
def evolve(self, profile, t, return_log=False):
"""
Compute the probability of the sequence state of the child
at time t later, given the parent profile.
Parameters
----------
profile : numpy.array
Sequence profile. Shape = (L, a),
where L - seq... | Compute the probability of the sequence state of the child
at time t later, given the parent profile.
Parameters
----------
profile : numpy.array
Sequence profile. Shape = (L, a),
where L - sequence length, a - alphabet size.
t : double
Ti... | Below is the the instruction that describes the task:
### Input:
Compute the probability of the sequence state of the child
at time t later, given the parent profile.
Parameters
----------
profile : numpy.array
Sequence profile. Shape = (L, a),
where L - se... |
def _persist(self):
"""Persist client data."""
with open(self.file, 'w') as f:
json.dump({
'client': self.client,
'creds': self.creds,
'config': self.config
}, f) | Persist client data. | Below is the the instruction that describes the task:
### Input:
Persist client data.
### Response:
def _persist(self):
"""Persist client data."""
with open(self.file, 'w') as f:
json.dump({
'client': self.client,
'creds': self.creds,
'con... |
def get_function_params(self, scope_path, pyfunc):
""":type pyfunc: rope.base.pyobjectsdef.PyFunction"""
pyclass = pyfunc.parent
scope_path = get_attribute_scope_path(pyclass)
glade_file = self.get_glade_file_for_class(scope_path, pyclass)
if glade_file:
self.proces... | :type pyfunc: rope.base.pyobjectsdef.PyFunction | Below is the the instruction that describes the task:
### Input:
:type pyfunc: rope.base.pyobjectsdef.PyFunction
### Response:
def get_function_params(self, scope_path, pyfunc):
""":type pyfunc: rope.base.pyobjectsdef.PyFunction"""
pyclass = pyfunc.parent
scope_path = get_attribute_scope_p... |
def shp2geom(shp_fn):
"""Extract geometries from input shapefile
Need to handle multi-part geom: http://osgeo-org.1560.x6.nabble.com/Multipart-to-singlepart-td3746767.html
"""
ds = ogr.Open(shp_fn)
lyr = ds.GetLayer()
srs = lyr.GetSpatialRef()
lyr.ResetReading()
geom_list = []
f... | Extract geometries from input shapefile
Need to handle multi-part geom: http://osgeo-org.1560.x6.nabble.com/Multipart-to-singlepart-td3746767.html | Below is the the instruction that describes the task:
### Input:
Extract geometries from input shapefile
Need to handle multi-part geom: http://osgeo-org.1560.x6.nabble.com/Multipart-to-singlepart-td3746767.html
### Response:
def shp2geom(shp_fn):
"""Extract geometries from input shapefile
Ne... |
def terminate(self):
""" Terminate Qutepart instance.
This method MUST be called before application stop to avoid crashes and
some other interesting effects
Call it on close to free memory and stop background highlighting
"""
self.text = ''
self._completer.termina... | Terminate Qutepart instance.
This method MUST be called before application stop to avoid crashes and
some other interesting effects
Call it on close to free memory and stop background highlighting | Below is the the instruction that describes the task:
### Input:
Terminate Qutepart instance.
This method MUST be called before application stop to avoid crashes and
some other interesting effects
Call it on close to free memory and stop background highlighting
### Response:
def terminate(s... |
def list_groups(self, scope_descriptor=None, subject_types=None, continuation_token=None):
"""ListGroups.
[Preview API] Gets a list of all groups in the current scope (usually organization or account).
:param str scope_descriptor: Specify a non-default scope (collection, project) to search for g... | ListGroups.
[Preview API] Gets a list of all groups in the current scope (usually organization or account).
:param str scope_descriptor: Specify a non-default scope (collection, project) to search for groups.
:param [str] subject_types: A comma separated list of user subject subtypes to reduce t... | Below is the the instruction that describes the task:
### Input:
ListGroups.
[Preview API] Gets a list of all groups in the current scope (usually organization or account).
:param str scope_descriptor: Specify a non-default scope (collection, project) to search for groups.
:param [str] subje... |
def create_vector_observation_encoder(observation_input, h_size, activation, num_layers, scope,
reuse):
"""
Builds a set of hidden state encoders.
:param reuse: Whether to re-use the weights within the same scope.
:param scope: Graph scope for th... | Builds a set of hidden state encoders.
:param reuse: Whether to re-use the weights within the same scope.
:param scope: Graph scope for the encoder ops.
:param observation_input: Input vector.
:param h_size: Hidden layer size.
:param activation: What type of activation function t... | Below is the the instruction that describes the task:
### Input:
Builds a set of hidden state encoders.
:param reuse: Whether to re-use the weights within the same scope.
:param scope: Graph scope for the encoder ops.
:param observation_input: Input vector.
:param h_size: Hidden laye... |
def import_module(self, name):
"""Import a module into the bridge."""
if name not in self._objects:
module = _import_module(name)
self._objects[name] = module
self._object_references[id(module)] = name
return self._objects[name] | Import a module into the bridge. | Below is the the instruction that describes the task:
### Input:
Import a module into the bridge.
### Response:
def import_module(self, name):
"""Import a module into the bridge."""
if name not in self._objects:
module = _import_module(name)
self._objects[name] = module
... |
def run(self, configurations):
""" Run all tests
Returns:
A dictionnary containing tests results.
"""
result = CourgetteResult()
for configuration in configurations:
runner = CourgetteTestsRunner(url=self.url,
... | Run all tests
Returns:
A dictionnary containing tests results. | Below is the the instruction that describes the task:
### Input:
Run all tests
Returns:
A dictionnary containing tests results.
### Response:
def run(self, configurations):
""" Run all tests
Returns:
A dictionnary containing tests results.
... |
def edit(self, name=None, description=None, **kwargs):
# type: (AnyStr, AnyStr, **Any) -> None
"""
Edit the details of a part (model or instance).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`... | Edit the details of a part (model or instance).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`Part.update()`.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
... | Below is the the instruction that describes the task:
### Input:
Edit the details of a part (model or instance).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`Part.update()`.
In order to prevent the backe... |
def velocity_kalman_model():
'''Return a KalmanState set up to model objects with constant velocity
The observation and measurement vectors are i,j.
The state vector is i,j,vi,vj
'''
om = np.array([[1,0,0,0], [0, 1, 0, 0]])
tm = np.array([[1,0,1,0],
[0,1,0,1],
... | Return a KalmanState set up to model objects with constant velocity
The observation and measurement vectors are i,j.
The state vector is i,j,vi,vj | Below is the the instruction that describes the task:
### Input:
Return a KalmanState set up to model objects with constant velocity
The observation and measurement vectors are i,j.
The state vector is i,j,vi,vj
### Response:
def velocity_kalman_model():
'''Return a KalmanState set up to model objects... |
def detectGamingHandheld(self):
"""Return detection of a gaming handheld with a modern iPhone-class browser
Detects if the current device is a handheld gaming device with
a touchscreen and modern iPhone-class browser. Includes the Playstation Vita.
"""
return UAgentInfo.devicePl... | Return detection of a gaming handheld with a modern iPhone-class browser
Detects if the current device is a handheld gaming device with
a touchscreen and modern iPhone-class browser. Includes the Playstation Vita. | Below is the the instruction that describes the task:
### Input:
Return detection of a gaming handheld with a modern iPhone-class browser
Detects if the current device is a handheld gaming device with
a touchscreen and modern iPhone-class browser. Includes the Playstation Vita.
### Response:
def d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.