code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS):
"""
Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logg... | Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logging(SentryHandler(client))
Within Django:
>>> from raven.contri... | Below is the the instruction that describes the task:
### Input:
Configures logging to pipe to Sentry.
- ``exclude`` is a list of loggers that shouldn't go to Sentry.
For a typical Python install:
>>> from raven.handlers.logging import SentryHandler
>>> client = Sentry(...)
>>> setup_logging(... |
def getThroughput(self, instId: int) -> float:
"""
Return the throughput of the specified instance.
:param instId: the id of the protocol instance
"""
# We are using the instanceStarted time in the denominator instead of
# a time interval. This is alright for now as all ... | Return the throughput of the specified instance.
:param instId: the id of the protocol instance | Below is the the instruction that describes the task:
### Input:
Return the throughput of the specified instance.
:param instId: the id of the protocol instance
### Response:
def getThroughput(self, instId: int) -> float:
"""
Return the throughput of the specified instance.
:param... |
def str_presenter(dmpr, data):
"""Return correct str_presenter to write multiple lines to a yaml field.
Source: http://stackoverflow.com/a/33300001
"""
if is_multiline(data):
return dmpr.represent_scalar('tag:yaml.org,2002:str', data, style='|')
return dmpr.represent_scalar('tag:yaml.org,2... | Return correct str_presenter to write multiple lines to a yaml field.
Source: http://stackoverflow.com/a/33300001 | Below is the the instruction that describes the task:
### Input:
Return correct str_presenter to write multiple lines to a yaml field.
Source: http://stackoverflow.com/a/33300001
### Response:
def str_presenter(dmpr, data):
"""Return correct str_presenter to write multiple lines to a yaml field.
So... |
def to_internal_value(self, value):
"""Convert to integer id."""
natural_key = value.split("_")
content_type = ContentType.objects.get_by_natural_key(*natural_key)
return content_type.id | Convert to integer id. | Below is the the instruction that describes the task:
### Input:
Convert to integer id.
### Response:
def to_internal_value(self, value):
"""Convert to integer id."""
natural_key = value.split("_")
content_type = ContentType.objects.get_by_natural_key(*natural_key)
return content_ty... |
def make_signer(self, salt=None):
"""A method that creates a new instance of the signer to be used.
The default implementation uses the :class:`Signer` baseclass.
"""
if salt is None:
salt = self.salt
return self.signer(self.secret_key, salt=salt, **self.signer_kwargs... | A method that creates a new instance of the signer to be used.
The default implementation uses the :class:`Signer` baseclass. | Below is the the instruction that describes the task:
### Input:
A method that creates a new instance of the signer to be used.
The default implementation uses the :class:`Signer` baseclass.
### Response:
def make_signer(self, salt=None):
"""A method that creates a new instance of the signer to be ... |
def print_tools(self, pattern=None, buf=sys.stdout):
"""Print a list of visible tools.
Args:
pattern (str): Only list tools that match this glob pattern.
"""
seen = set()
rows = []
context = self.context
if context:
data = context.get_too... | Print a list of visible tools.
Args:
pattern (str): Only list tools that match this glob pattern. | Below is the the instruction that describes the task:
### Input:
Print a list of visible tools.
Args:
pattern (str): Only list tools that match this glob pattern.
### Response:
def print_tools(self, pattern=None, buf=sys.stdout):
"""Print a list of visible tools.
Args:
... |
def cleanup_temporary_directories(self):
"""Delete the build directories and any temporary directories created by pip."""
while self.build_directories:
shutil.rmtree(self.build_directories.pop())
for requirement in self.reported_requirements:
requirement.remove_temporary_... | Delete the build directories and any temporary directories created by pip. | Below is the the instruction that describes the task:
### Input:
Delete the build directories and any temporary directories created by pip.
### Response:
def cleanup_temporary_directories(self):
"""Delete the build directories and any temporary directories created by pip."""
while self.build_direct... |
def compute_error(self, **args):
"""
Computes error for all non-output layers backwards through all
projections.
"""
for key in args:
layer = self.getLayer(key)
if layer.kind == 'Output':
self.copyTargets(layer, args[key])
self.veri... | Computes error for all non-output layers backwards through all
projections. | Below is the the instruction that describes the task:
### Input:
Computes error for all non-output layers backwards through all
projections.
### Response:
def compute_error(self, **args):
"""
Computes error for all non-output layers backwards through all
projections.
"""
... |
def IsHuntStarted(self):
"""Is this hunt considered started?
This method is used to check if new clients should be processed by
this hunt. Note that child flow responses are always processed but
new clients are not allowed to be scheduled unless the hunt is
started.
Returns:
If a new cli... | Is this hunt considered started?
This method is used to check if new clients should be processed by
this hunt. Note that child flow responses are always processed but
new clients are not allowed to be scheduled unless the hunt is
started.
Returns:
If a new client is allowed to be scheduled o... | Below is the the instruction that describes the task:
### Input:
Is this hunt considered started?
This method is used to check if new clients should be processed by
this hunt. Note that child flow responses are always processed but
new clients are not allowed to be scheduled unless the hunt is
star... |
def create_transaction(self, *args: Any, **kwargs: Any) -> BaseTransaction:
"""
Passthrough helper to the current VM class.
"""
return self.get_vm().create_transaction(*args, **kwargs) | Passthrough helper to the current VM class. | Below is the the instruction that describes the task:
### Input:
Passthrough helper to the current VM class.
### Response:
def create_transaction(self, *args: Any, **kwargs: Any) -> BaseTransaction:
"""
Passthrough helper to the current VM class.
"""
return self.get_vm().create_tran... |
def RingToneStatus(self, Id=1, Set=None):
"""Enables/disables a ringtone.
:Parameters:
Id : int
Ringtone Id
Set : bool
True/False if the ringtone should be enabled/disabled or None if the current status
should be queried.
:return: Current... | Enables/disables a ringtone.
:Parameters:
Id : int
Ringtone Id
Set : bool
True/False if the ringtone should be enabled/disabled or None if the current status
should be queried.
:return: Current status if Set=None, None otherwise.
:rtype: ... | Below is the the instruction that describes the task:
### Input:
Enables/disables a ringtone.
:Parameters:
Id : int
Ringtone Id
Set : bool
True/False if the ringtone should be enabled/disabled or None if the current status
should be queried.
... |
def poll(self):
"""
Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but we
don't know how. These ... | Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but we
don't know how. These are the return values JupyterHub exp... | Below is the the instruction that describes the task:
### Input:
Check if the pod is still running.
Uses the same interface as subprocess.Popen.poll(): if the pod is
still running, returns None. If the pod has exited, return the
exit code if we can determine it, or 1 if it has exited but w... |
def chi2_adaptive_binning(features_0,features_1,number_of_splits_list,systematics_fraction=0.0,title = "title", name="name", PLOT = True, DEBUG = False, transform='StandardScalar'):
"""This function takes in two 2D arrays with all features being columns"""
max_number_of_splits = np.max(number_of_splits_list)
#deter... | This function takes in two 2D arrays with all features being columns | Below is the the instruction that describes the task:
### Input:
This function takes in two 2D arrays with all features being columns
### Response:
def chi2_adaptive_binning(features_0,features_1,number_of_splits_list,systematics_fraction=0.0,title = "title", name="name", PLOT = True, DEBUG = False, transform='Sta... |
def wc(name_mode="_", head=None, args=None, kwargs=None, *, conditions=None) \
-> Pattern:
"""Constructor for a wildcard-:class:`Pattern`
Helper function to create a Pattern object with an emphasis on wildcard
patterns, if we don't care about the arguments of the matched expressions
(otherwise,... | Constructor for a wildcard-:class:`Pattern`
Helper function to create a Pattern object with an emphasis on wildcard
patterns, if we don't care about the arguments of the matched expressions
(otherwise, use :func:`pattern`)
Args:
name_mode (str): Combined `wc_name` and `mode` for :class:`Patter... | Below is the the instruction that describes the task:
### Input:
Constructor for a wildcard-:class:`Pattern`
Helper function to create a Pattern object with an emphasis on wildcard
patterns, if we don't care about the arguments of the matched expressions
(otherwise, use :func:`pattern`)
Args:
... |
def paginate(self, request, collection):
""" Paginate collection.
:return object: Collection or paginator
"""
p = Paginator(request, self, collection)
return p.paginator and p or UpdatedList(collection) | Paginate collection.
:return object: Collection or paginator | Below is the the instruction that describes the task:
### Input:
Paginate collection.
:return object: Collection or paginator
### Response:
def paginate(self, request, collection):
""" Paginate collection.
:return object: Collection or paginator
"""
p = Paginator(request,... |
def load_module(self, loader):
'''
Load the module. Required for the Python meta-loading mechanism.
'''
modfile, pathname, description = loader.info
module = imp.load_module(
loader.fullname,
modfile,
pathname,
description
... | Load the module. Required for the Python meta-loading mechanism. | Below is the the instruction that describes the task:
### Input:
Load the module. Required for the Python meta-loading mechanism.
### Response:
def load_module(self, loader):
'''
Load the module. Required for the Python meta-loading mechanism.
'''
modfile, pathname, description = l... |
def check_exports(mod, specs, renamings):
'''
Does nothing but raising PythranSyntaxError if specs
references an undefined global
'''
functions = {renamings.get(k, k): v for k, v in specs.functions.items()}
mod_functions = {node.name: node for node in mod.body
if isinstance... | Does nothing but raising PythranSyntaxError if specs
references an undefined global | Below is the the instruction that describes the task:
### Input:
Does nothing but raising PythranSyntaxError if specs
references an undefined global
### Response:
def check_exports(mod, specs, renamings):
'''
Does nothing but raising PythranSyntaxError if specs
references an undefined global
''... |
def _apply_workspaces(self, combination, mode):
"""
Allows user to force move a comma separated list of workspaces to the
given output when it's activated.
Example:
- DP1_workspaces = "1,2,3"
"""
if len(combination) > 1 and mode == "extend":
sleep... | Allows user to force move a comma separated list of workspaces to the
given output when it's activated.
Example:
- DP1_workspaces = "1,2,3" | Below is the the instruction that describes the task:
### Input:
Allows user to force move a comma separated list of workspaces to the
given output when it's activated.
Example:
- DP1_workspaces = "1,2,3"
### Response:
def _apply_workspaces(self, combination, mode):
"""
... |
def construct_survival_curves(hazard_rates, timelines):
"""
Given hazard rates, reconstruct the survival curves
Parameters
----------
hazard_rates: (n,t) array
timelines: (t,) the observational times
Returns
-------
t: survial curves, (n,t) array
"""
cumulative_hazards = cu... | Given hazard rates, reconstruct the survival curves
Parameters
----------
hazard_rates: (n,t) array
timelines: (t,) the observational times
Returns
-------
t: survial curves, (n,t) array | Below is the the instruction that describes the task:
### Input:
Given hazard rates, reconstruct the survival curves
Parameters
----------
hazard_rates: (n,t) array
timelines: (t,) the observational times
Returns
-------
t: survial curves, (n,t) array
### Response:
def construct_survi... |
def get_segmentation(X, rank, R, rank_labels, R_labels, niter=300,
bound_idxs=None, in_labels=None):
"""
Gets the segmentation (boundaries and labels) from the factorization
matrices.
Parameters
----------
X: np.array()
Features matrix (e.g. chromagram)
rank: in... | Gets the segmentation (boundaries and labels) from the factorization
matrices.
Parameters
----------
X: np.array()
Features matrix (e.g. chromagram)
rank: int
Rank of decomposition
R: int
Size of the median filter for activation matrix
niter: int
Number of it... | Below is the the instruction that describes the task:
### Input:
Gets the segmentation (boundaries and labels) from the factorization
matrices.
Parameters
----------
X: np.array()
Features matrix (e.g. chromagram)
rank: int
Rank of decomposition
R: int
Size of the me... |
def navactive(request, urls):
"""
{% navactive request "view_name another_view_name" %}
"""
url_list = set(urls.split())
resolved = resolve(request.path)
resolved_urls = set()
if resolved.url_name:
resolved_urls.add(resolved.url_name)
if resolved.namespaces:
resolved_url... | {% navactive request "view_name another_view_name" %} | Below is the the instruction that describes the task:
### Input:
{% navactive request "view_name another_view_name" %}
### Response:
def navactive(request, urls):
"""
{% navactive request "view_name another_view_name" %}
"""
url_list = set(urls.split())
resolved = resolve(request.path)
res... |
def unlink(self):
"""
Unregisters the Link
"""
links = self.registry.get(self.source)
if self in links:
links.pop(links.index(self)) | Unregisters the Link | Below is the the instruction that describes the task:
### Input:
Unregisters the Link
### Response:
def unlink(self):
"""
Unregisters the Link
"""
links = self.registry.get(self.source)
if self in links:
links.pop(links.index(self)) |
def get(self):
"""
Get a JSON-ready representation of this Attachment.
:returns: This Attachment, ready for use in a request body.
:rtype: dict
"""
attachment = {}
if self.file_content is not None:
attachment["content"] = self.file_content.get()
... | Get a JSON-ready representation of this Attachment.
:returns: This Attachment, ready for use in a request body.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Get a JSON-ready representation of this Attachment.
:returns: This Attachment, ready for use in a request body.
:rtype: dict
### Response:
def get(self):
"""
Get a JSON-ready representation of this Attachment.
... |
def rotate_left(self):
"""
Left rotation
"""
new_root = self.node.right.node
new_left_sub = new_root.left.node
old_root = self.node
self.node = new_root
old_root.right.node = new_left_sub
new_root.left.node = old_root | Left rotation | Below is the the instruction that describes the task:
### Input:
Left rotation
### Response:
def rotate_left(self):
"""
Left rotation
"""
new_root = self.node.right.node
new_left_sub = new_root.left.node
old_root = self.node
self.node = new_root
old_... |
def execute_command(self, command, **kwargs):
"""Execute a command on the node
Args:
command (str)
Kwargs:
username (str)
"""
self.info_log("executing command: %s" % command)
try:
ssh = paramiko.SSHClient()
ssh.set_missi... | Execute a command on the node
Args:
command (str)
Kwargs:
username (str) | Below is the the instruction that describes the task:
### Input:
Execute a command on the node
Args:
command (str)
Kwargs:
username (str)
### Response:
def execute_command(self, command, **kwargs):
"""Execute a command on the node
Args:
command... |
def _get_filename(request, item):
""" Creates a filename
"""
if request.keep_image_names:
filename = OgcImageService.finalize_filename(item['niceName'].replace(' ', '_'))
else:
filename = OgcImageService.finalize_filename(
'_'.join([str(GeopediaSer... | Creates a filename | Below is the the instruction that describes the task:
### Input:
Creates a filename
### Response:
def _get_filename(request, item):
""" Creates a filename
"""
if request.keep_image_names:
filename = OgcImageService.finalize_filename(item['niceName'].replace(' ', '_'))
el... |
def bind(self, **bindings):
"""Creates a new template with the given unbound variables bound.
Args:
**bindings: Arguments for every deferred parameter.
Returns:
A new template with the given bindings.
Raises:
ValueError: If any of the bindings do not correspond to unbound variables.
... | Creates a new template with the given unbound variables bound.
Args:
**bindings: Arguments for every deferred parameter.
Returns:
A new template with the given bindings.
Raises:
ValueError: If any of the bindings do not correspond to unbound variables. | Below is the the instruction that describes the task:
### Input:
Creates a new template with the given unbound variables bound.
Args:
**bindings: Arguments for every deferred parameter.
Returns:
A new template with the given bindings.
Raises:
ValueError: If any of the bindings do not ... |
def submission_status(self, link):
"""
Given the unique link of a submission, returns its current
status.
Keyword Arguments
-----------------
* link: the unique id string of a submission
Returns
-------
A dictionary of the error, the result cod... | Given the unique link of a submission, returns its current
status.
Keyword Arguments
-----------------
* link: the unique id string of a submission
Returns
-------
A dictionary of the error, the result code and the status
code.
Notes
-... | Below is the the instruction that describes the task:
### Input:
Given the unique link of a submission, returns its current
status.
Keyword Arguments
-----------------
* link: the unique id string of a submission
Returns
-------
A dictionary of the error, ... |
def setFont(self, font):
""" Sets the font that will be returned when data() is called with the Qt.FontRole.
Can be a QFont or None if no font is set.
"""
check_class(font, QtGui.QFont, allow_none=True)
self._font = font | Sets the font that will be returned when data() is called with the Qt.FontRole.
Can be a QFont or None if no font is set. | Below is the the instruction that describes the task:
### Input:
Sets the font that will be returned when data() is called with the Qt.FontRole.
Can be a QFont or None if no font is set.
### Response:
def setFont(self, font):
""" Sets the font that will be returned when data() is called with th... |
def get_ports(device_owners=None, vnic_type=None, port_id=None, active=True):
"""Returns list of all ports in neutron the db"""
session = db.get_reader_session()
with session.begin():
port_model = models_v2.Port
ports = (session
.query(port_model)
.filter_un... | Returns list of all ports in neutron the db | Below is the the instruction that describes the task:
### Input:
Returns list of all ports in neutron the db
### Response:
def get_ports(device_owners=None, vnic_type=None, port_id=None, active=True):
"""Returns list of all ports in neutron the db"""
session = db.get_reader_session()
with session.begin... |
def capture_update_records(records):
"""Writes all updated configuration info to DynamoDB"""
for rec in records:
data = cloudwatch.get_historical_base_info(rec)
group = describe_group(rec, cloudwatch.get_region(rec))
if len(group) > 1:
raise Exception(f'[X] Multiple groups f... | Writes all updated configuration info to DynamoDB | Below is the the instruction that describes the task:
### Input:
Writes all updated configuration info to DynamoDB
### Response:
def capture_update_records(records):
"""Writes all updated configuration info to DynamoDB"""
for rec in records:
data = cloudwatch.get_historical_base_info(rec)
g... |
def alias_symbol(self,
alias_symbol=None,
is_previous_symbol=None,
hgnc_symbol=None,
hgnc_identifier=None,
limit=None,
as_df=False):
"""Method to query :class:`.models.AliasSymbol` objec... | Method to query :class:`.models.AliasSymbol` objects in database
:param alias_symbol: alias symbol(s)
:type alias_symbol: str or tuple(str) or None
:param is_previous_symbol: flag for 'is previous'
:type is_previous_symbol: bool or tuple(bool) or None
:param hgnc_symbol: HGNC ... | Below is the the instruction that describes the task:
### Input:
Method to query :class:`.models.AliasSymbol` objects in database
:param alias_symbol: alias symbol(s)
:type alias_symbol: str or tuple(str) or None
:param is_previous_symbol: flag for 'is previous'
:type is_previous_s... |
def add_monitor(self, pattern, callback, limit=80):
"""
Calls the given function whenever the given pattern matches the
incoming data.
.. HINT::
If you want to catch all incoming data regardless of a
pattern, use the Protocol.data_received_event event instead.
... | Calls the given function whenever the given pattern matches the
incoming data.
.. HINT::
If you want to catch all incoming data regardless of a
pattern, use the Protocol.data_received_event event instead.
Arguments passed to the callback are the protocol instance, the
... | Below is the the instruction that describes the task:
### Input:
Calls the given function whenever the given pattern matches the
incoming data.
.. HINT::
If you want to catch all incoming data regardless of a
pattern, use the Protocol.data_received_event event instead.
... |
def backwards(self, orm):
"Write your backwards methods here."
orm['avocado.DataConcept'].objects.filter(name='Sample')\
.update(queryable=True) | Write your backwards methods here. | Below is the the instruction that describes the task:
### Input:
Write your backwards methods here.
### Response:
def backwards(self, orm):
"Write your backwards methods here."
orm['avocado.DataConcept'].objects.filter(name='Sample')\
.update(queryable=True) |
def _set_routing_system(self, v, load=False):
"""
Setter method for routing_system, mapped from YANG variable /routing_system (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_routing_system is considered as a private
method. Backends looking to populate th... | Setter method for routing_system, mapped from YANG variable /routing_system (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_routing_system is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_rout... | Below is the the instruction that describes the task:
### Input:
Setter method for routing_system, mapped from YANG variable /routing_system (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_routing_system is considered as a private
method. Backends looking to ... |
def _initialize(self):
"""Read the SharQ configuration and set appropriate
variables. Open a redis connection pool and load all
the Lua scripts.
"""
self._key_prefix = self._config.get('redis', 'key_prefix')
self._job_expire_interval = int(
self._config.get('s... | Read the SharQ configuration and set appropriate
variables. Open a redis connection pool and load all
the Lua scripts. | Below is the the instruction that describes the task:
### Input:
Read the SharQ configuration and set appropriate
variables. Open a redis connection pool and load all
the Lua scripts.
### Response:
def _initialize(self):
"""Read the SharQ configuration and set appropriate
variables.... |
def unpack(self, unpacker):
"""
Unpacks the constant pool from an unpacker stream
"""
(count, ) = unpacker.unpack_struct(_H)
# first item is never present in the actual data buffer, but
# the count number acts like it would be.
items = [(None, None), ]
c... | Unpacks the constant pool from an unpacker stream | Below is the the instruction that describes the task:
### Input:
Unpacks the constant pool from an unpacker stream
### Response:
def unpack(self, unpacker):
"""
Unpacks the constant pool from an unpacker stream
"""
(count, ) = unpacker.unpack_struct(_H)
# first item is nev... |
def comments(case_id):
"""Upload a new comment."""
text = request.form['text']
variant_id = request.form.get('variant_id')
username = request.form.get('username')
case_obj = app.db.case(case_id)
app.db.add_comment(case_obj, text, variant_id=variant_id, username=username)
return redirect(requ... | Upload a new comment. | Below is the the instruction that describes the task:
### Input:
Upload a new comment.
### Response:
def comments(case_id):
"""Upload a new comment."""
text = request.form['text']
variant_id = request.form.get('variant_id')
username = request.form.get('username')
case_obj = app.db.case(case_id)... |
def build(self):
'''
Returns
-------
Corpus
'''
constructor_kwargs = self._get_build_kwargs()
if type(self.raw_texts) == list:
constructor_kwargs['raw_texts'] = np.array(self.raw_texts)
else:
constructor_kwargs['raw_texts'] = self.raw_texts
return Corpus(**constructor_kwargs) | Returns
-------
Corpus | Below is the the instruction that describes the task:
### Input:
Returns
-------
Corpus
### Response:
def build(self):
'''
Returns
-------
Corpus
'''
constructor_kwargs = self._get_build_kwargs()
if type(self.raw_texts) == list:
constructor_kwargs['raw_texts'] = np.array(self.raw_texts)
else... |
def order_by(self, *field_names):
"""
Mark the filter as being ordered if search has occurred.
"""
if not self._search_ordered:
self._search_ordered = len(self._search_terms) > 0
return super(SearchableQuerySet, self).order_by(*field_names) | Mark the filter as being ordered if search has occurred. | Below is the the instruction that describes the task:
### Input:
Mark the filter as being ordered if search has occurred.
### Response:
def order_by(self, *field_names):
"""
Mark the filter as being ordered if search has occurred.
"""
if not self._search_ordered:
self._s... |
def extract_source(bundle_path, source_path):
"""
Extract the source bundle
:param bundle_path: path to the aource bundle *.tar.gz
:param source_path: path to location where to extractall
"""
with tarfile.open(bundle_path, 'r:gz') as tf:
tf.extractall(path=source_path)
logger.debug("... | Extract the source bundle
:param bundle_path: path to the aource bundle *.tar.gz
:param source_path: path to location where to extractall | Below is the the instruction that describes the task:
### Input:
Extract the source bundle
:param bundle_path: path to the aource bundle *.tar.gz
:param source_path: path to location where to extractall
### Response:
def extract_source(bundle_path, source_path):
"""
Extract the source bundle
:p... |
def delete(self):
"""
Destructor.
"""
if self.glucose:
pysolvers.glucose41_del(self.glucose)
self.glucose = None
if self.prfile:
self.prfile.close() | Destructor. | Below is the the instruction that describes the task:
### Input:
Destructor.
### Response:
def delete(self):
"""
Destructor.
"""
if self.glucose:
pysolvers.glucose41_del(self.glucose)
self.glucose = None
if self.prfile:
self.... |
def metabolite_summary(met, solution=None, threshold=0.01, fva=False,
names=False, floatfmt='.3g'):
"""
Print a summary of the production and consumption fluxes.
This method requires the model for which this metabolite is a part
to be solved.
Parameters
----------
so... | Print a summary of the production and consumption fluxes.
This method requires the model for which this metabolite is a part
to be solved.
Parameters
----------
solution : cobra.Solution, optional
A previously solved model solution to use for generating the
summary. If none provide... | Below is the the instruction that describes the task:
### Input:
Print a summary of the production and consumption fluxes.
This method requires the model for which this metabolite is a part
to be solved.
Parameters
----------
solution : cobra.Solution, optional
A previously solved mode... |
def getAllText(cls, where=None, SEPERATOR=' ', orderBy=None):
"""Retrieve a list of of all possible instances of this class.
The list is composed of tuples in the format (id, description) -
where description is a string composed by the fields from
cls._shortView, joint with SEPERATOR.
... | Retrieve a list of of all possible instances of this class.
The list is composed of tuples in the format (id, description) -
where description is a string composed by the fields from
cls._shortView, joint with SEPERATOR. | Below is the the instruction that describes the task:
### Input:
Retrieve a list of of all possible instances of this class.
The list is composed of tuples in the format (id, description) -
where description is a string composed by the fields from
cls._shortView, joint with SEPERATOR.
### R... |
def get_body(self, component):
"""
TODO: add documentation
"""
if component in self._bodies.keys():
return self._bodies[component]
else:
# then hopefully we're a child star of an contact_binary envelope
parent_component = self._parent_envelope_... | TODO: add documentation | Below is the the instruction that describes the task:
### Input:
TODO: add documentation
### Response:
def get_body(self, component):
"""
TODO: add documentation
"""
if component in self._bodies.keys():
return self._bodies[component]
else:
# then hope... |
def nested_genobject(self, metadata, attr, datastore):
"""
Allow for the printing of nested GenObjects
:param metadata: Nested dictionary containing the metadata. Will be further populated by this method
:param attr: Current attribute being evaluated. Must be a GenObject e.g. sample.gene... | Allow for the printing of nested GenObjects
:param metadata: Nested dictionary containing the metadata. Will be further populated by this method
:param attr: Current attribute being evaluated. Must be a GenObject e.g. sample.general
:param datastore: The dictionary of the current attribute. Will... | Below is the the instruction that describes the task:
### Input:
Allow for the printing of nested GenObjects
:param metadata: Nested dictionary containing the metadata. Will be further populated by this method
:param attr: Current attribute being evaluated. Must be a GenObject e.g. sample.general
... |
def addRecordsFromThread(self, records):
"""
Adds the given record to the system.
:param records | [<orb.Table>, ..]
"""
label_mapper = self.labelMapper()
icon_mapper = self.iconMapper()
tree = None
if self.showTreeP... | Adds the given record to the system.
:param records | [<orb.Table>, ..] | Below is the the instruction that describes the task:
### Input:
Adds the given record to the system.
:param records | [<orb.Table>, ..]
### Response:
def addRecordsFromThread(self, records):
"""
Adds the given record to the system.
:param records |... |
def _add_info(self, msg, **kwargs):
"""
Add information to a SAML message. If the attribute is not part of
what's defined in the SAML standard add it as an extension.
:param msg:
:param kwargs:
:return:
"""
args, extensions = self._filter_args(msg, **kwa... | Add information to a SAML message. If the attribute is not part of
what's defined in the SAML standard add it as an extension.
:param msg:
:param kwargs:
:return: | Below is the the instruction that describes the task:
### Input:
Add information to a SAML message. If the attribute is not part of
what's defined in the SAML standard add it as an extension.
:param msg:
:param kwargs:
:return:
### Response:
def _add_info(self, msg, **kwargs):
... |
def _set_ingress(self, v, load=False):
"""
Setter method for ingress, mapped from YANG variable /interface/fortygigabitethernet/storm_control/ingress (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ingress is considered as a private
method. Backends looking to... | Setter method for ingress, mapped from YANG variable /interface/fortygigabitethernet/storm_control/ingress (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ingress is considered as a private
method. Backends looking to populate this variable should
do so via callin... | Below is the the instruction that describes the task:
### Input:
Setter method for ingress, mapped from YANG variable /interface/fortygigabitethernet/storm_control/ingress (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ingress is considered as a private
method. B... |
def window_taylor(N, nbar=4, sll=-30):
"""Taylor tapering window
Taylor windows allows you to make tradeoffs between the
mainlobe width and sidelobe level (sll).
Implemented as described by Carrara, Goodman, and Majewski
in 'Spotlight Synthetic Aperture Radar: Signal Processing Algorithms'
Pa... | Taylor tapering window
Taylor windows allows you to make tradeoffs between the
mainlobe width and sidelobe level (sll).
Implemented as described by Carrara, Goodman, and Majewski
in 'Spotlight Synthetic Aperture Radar: Signal Processing Algorithms'
Pages 512-513
:param N: window length
:... | Below is the the instruction that describes the task:
### Input:
Taylor tapering window
Taylor windows allows you to make tradeoffs between the
mainlobe width and sidelobe level (sll).
Implemented as described by Carrara, Goodman, and Majewski
in 'Spotlight Synthetic Aperture Radar: Signal Proces... |
def _publish(tgt,
fun,
arg=None,
tgt_type='glob',
returner='',
timeout=None,
form='clean',
roster=None):
'''
Publish a command "from the minion out to other minions". In reality, the
minion does not execute this funct... | Publish a command "from the minion out to other minions". In reality, the
minion does not execute this function, it is executed by the master. Thus,
no access control is enabled, as minions cannot initiate publishes
themselves.
Salt-ssh publishes will default to whichever roster was used for the
in... | Below is the the instruction that describes the task:
### Input:
Publish a command "from the minion out to other minions". In reality, the
minion does not execute this function, it is executed by the master. Thus,
no access control is enabled, as minions cannot initiate publishes
themselves.
Salt-s... |
def properties(self):
"""Return various properties of the binary tree.
:return: Binary tree properties.
:rtype: dict
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
... | Return various properties of the binary tree.
:return: Binary tree properties.
:rtype: dict
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
>>> root.left = Node(2)
>>> root.right = Node(3)
... | Below is the the instruction that describes the task:
### Input:
Return various properties of the binary tree.
:return: Binary tree properties.
:rtype: dict
**Example**:
.. doctest::
>>> from binarytree import Node
>>>
>>> root = Node(1)
... |
def parse_header(file_obj):
"""
Read the ASCII header of a PLY file, and leave the file object
at the position of the start of data but past the header.
Parameters
-----------
file_obj : open file object
Positioned at the start of the file
Returns
-----------
elements : colle... | Read the ASCII header of a PLY file, and leave the file object
at the position of the start of data but past the header.
Parameters
-----------
file_obj : open file object
Positioned at the start of the file
Returns
-----------
elements : collections.OrderedDict
Fields and data... | Below is the the instruction that describes the task:
### Input:
Read the ASCII header of a PLY file, and leave the file object
at the position of the start of data but past the header.
Parameters
-----------
file_obj : open file object
Positioned at the start of the file
Returns
---... |
def last_written_resolver(riak_object):
"""
A conflict-resolution function that resolves by selecting the most
recently-modified sibling by timestamp.
:param riak_object: an object-in-conflict that will be resolved
:type riak_object: :class:`RiakObject <riak.riak_object.RiakObject>`
"""
ria... | A conflict-resolution function that resolves by selecting the most
recently-modified sibling by timestamp.
:param riak_object: an object-in-conflict that will be resolved
:type riak_object: :class:`RiakObject <riak.riak_object.RiakObject>` | Below is the the instruction that describes the task:
### Input:
A conflict-resolution function that resolves by selecting the most
recently-modified sibling by timestamp.
:param riak_object: an object-in-conflict that will be resolved
:type riak_object: :class:`RiakObject <riak.riak_object.RiakObject>... |
def first_n_three_layer_P(reference_patterns, estimated_patterns, n=5):
"""First n three-layer precision.
This metric is basically the same as the three-layer FPR but it is only
applied to the first n estimated patterns, and it only returns the
precision. In MIREX and typically, n = 5.
Examples
... | First n three-layer precision.
This metric is basically the same as the three-layer FPR but it is only
applied to the first n estimated patterns, and it only returns the
precision. In MIREX and typically, n = 5.
Examples
--------
>>> ref_patterns = mir_eval.io.load_patterns("ref_pattern.txt")
... | Below is the the instruction that describes the task:
### Input:
First n three-layer precision.
This metric is basically the same as the three-layer FPR but it is only
applied to the first n estimated patterns, and it only returns the
precision. In MIREX and typically, n = 5.
Examples
--------... |
def get_files(*bases):
"""
List all files in a data directory.
"""
for base in bases:
basedir, _ = base.split(".", 1)
base = os.path.join(os.path.dirname(__file__), *base.split("."))
rem = len(os.path.dirname(base)) + len(basedir) + 2
for... | List all files in a data directory. | Below is the the instruction that describes the task:
### Input:
List all files in a data directory.
### Response:
def get_files(*bases):
"""
List all files in a data directory.
"""
for base in bases:
basedir, _ = base.split(".", 1)
base = os.path.join(os.pat... |
def rebalance(self, weight, child, base=np.nan, update=True):
"""
Rebalance a child to a given weight.
This is a helper method to simplify code logic. This method is used
when we want to se the weight of a particular child to a set amount.
It is similar to allocate, but it calcu... | Rebalance a child to a given weight.
This is a helper method to simplify code logic. This method is used
when we want to se the weight of a particular child to a set amount.
It is similar to allocate, but it calculates the appropriate allocation
based on the current weight.
Arg... | Below is the the instruction that describes the task:
### Input:
Rebalance a child to a given weight.
This is a helper method to simplify code logic. This method is used
when we want to se the weight of a particular child to a set amount.
It is similar to allocate, but it calculates the app... |
def get_sub_doc(self, subpage):
"""Returns PyQuery object for a given subpage URL.
:subpage: The subpage of the season, e.g. 'per_game'.
:returns: PyQuery object.
"""
html = sportsref.utils.get_html(self._subpage_url(subpage))
return pq(html) | Returns PyQuery object for a given subpage URL.
:subpage: The subpage of the season, e.g. 'per_game'.
:returns: PyQuery object. | Below is the the instruction that describes the task:
### Input:
Returns PyQuery object for a given subpage URL.
:subpage: The subpage of the season, e.g. 'per_game'.
:returns: PyQuery object.
### Response:
def get_sub_doc(self, subpage):
"""Returns PyQuery object for a given subpage URL.
... |
def filter_by_transcript_expression(
self,
transcript_expression_dict,
min_expression_value=0.0):
"""
Filters variants down to those which have overlap a transcript whose
expression value in the transcript_expression_dict argument is greater
than min_e... | Filters variants down to those which have overlap a transcript whose
expression value in the transcript_expression_dict argument is greater
than min_expression_value.
Parameters
----------
transcript_expression_dict : dict
Dictionary mapping Ensembl transcript IDs to... | Below is the the instruction that describes the task:
### Input:
Filters variants down to those which have overlap a transcript whose
expression value in the transcript_expression_dict argument is greater
than min_expression_value.
Parameters
----------
transcript_expression... |
def populate_requirement_set(requirement_set, # type: RequirementSet
args, # type: List[str]
options, # type: Values
finder, # type: PackageFinder
session, ... | Marshal cmd line args into a requirement set. | Below is the the instruction that describes the task:
### Input:
Marshal cmd line args into a requirement set.
### Response:
def populate_requirement_set(requirement_set, # type: RequirementSet
args, # type: List[str]
options, ... |
def _start_queue_management_thread(self):
""" TODO: docstring """
if self._queue_management_thread is None:
logger.debug("Starting queue management thread")
self._queue_management_thread = threading.Thread(
target=self._queue_management_worker)
self._q... | TODO: docstring | Below is the the instruction that describes the task:
### Input:
TODO: docstring
### Response:
def _start_queue_management_thread(self):
""" TODO: docstring """
if self._queue_management_thread is None:
logger.debug("Starting queue management thread")
self._queue_management_... |
def _in_range(self, start_time, end_time, time):
"""Indicate if the given time falls inside of the given range.
Parameters
----------
start_time : int
The unix time for the start of the range
end_time : int
The unix time for the end of the range
t... | Indicate if the given time falls inside of the given range.
Parameters
----------
start_time : int
The unix time for the start of the range
end_time : int
The unix time for the end of the range
time : int
The unix time to check
Return... | Below is the the instruction that describes the task:
### Input:
Indicate if the given time falls inside of the given range.
Parameters
----------
start_time : int
The unix time for the start of the range
end_time : int
The unix time for the end of the range
... |
def toggleAttributesDOM(isEnabled):
'''
toggleAttributesDOM - Toggle if the old DOM tag.attributes NamedNodeMap model should be used for the .attributes method, versus
a more sane direct dict implementation.
The DOM version is always accessable as AdvancedTag.attributesDOM
... | toggleAttributesDOM - Toggle if the old DOM tag.attributes NamedNodeMap model should be used for the .attributes method, versus
a more sane direct dict implementation.
The DOM version is always accessable as AdvancedTag.attributesDOM
The dict version is always accessable as Advanced... | Below is the the instruction that describes the task:
### Input:
toggleAttributesDOM - Toggle if the old DOM tag.attributes NamedNodeMap model should be used for the .attributes method, versus
a more sane direct dict implementation.
The DOM version is always accessable as AdvancedTag.attrib... |
def add_child(self, node):
"""Add a child node to the current node instance.
:param node: the child node instance.
:type node: Node
:returns: The new child node instance.
:rtype: Node
"""
if not issubclass(node.__class__, Node):
raise TypeError("{... | Add a child node to the current node instance.
:param node: the child node instance.
:type node: Node
:returns: The new child node instance.
:rtype: Node | Below is the the instruction that describes the task:
### Input:
Add a child node to the current node instance.
:param node: the child node instance.
:type node: Node
:returns: The new child node instance.
:rtype: Node
### Response:
def add_child(self, node):
"""Add a ch... |
def get_values(self, dtype=None):
"""
return object dtype as boxed values, such as Timestamps/Timedelta
"""
if is_object_dtype(dtype):
values = self.values.ravel()
result = self._holder(values).astype(object)
return result.reshape(self.values.shape)
... | return object dtype as boxed values, such as Timestamps/Timedelta | Below is the the instruction that describes the task:
### Input:
return object dtype as boxed values, such as Timestamps/Timedelta
### Response:
def get_values(self, dtype=None):
"""
return object dtype as boxed values, such as Timestamps/Timedelta
"""
if is_object_dtype(dtype):
... |
def set_rule(self, name, properties):
"""
Set a rules as object attribute.
Arguments:
name (string): Rule name to set as attribute name.
properties (dict): Dictionnary of properties.
"""
self._rule_attrs.append(name)
setattr(self, name, properties... | Set a rules as object attribute.
Arguments:
name (string): Rule name to set as attribute name.
properties (dict): Dictionnary of properties. | Below is the the instruction that describes the task:
### Input:
Set a rules as object attribute.
Arguments:
name (string): Rule name to set as attribute name.
properties (dict): Dictionnary of properties.
### Response:
def set_rule(self, name, properties):
"""
Set ... |
def evaluate(self):
"""Evaluate functional value of previous iteration."""
if self.opt['AccurateDFid']:
DX = self.reconstruct()
S = self.xstep.S
dfd = (np.linalg.norm(self.xstep.W * (DX - S))**2) / 2.0
if self.xmethod == 'fista':
X = self.... | Evaluate functional value of previous iteration. | Below is the the instruction that describes the task:
### Input:
Evaluate functional value of previous iteration.
### Response:
def evaluate(self):
"""Evaluate functional value of previous iteration."""
if self.opt['AccurateDFid']:
DX = self.reconstruct()
S = self.xstep.S
... |
def rename_object(self, old, new):
"""Replace the name of an object by a new one."""
self._objects.replace(old, new)
pairs = self._pairs
pairs |= {(new, p) for p in self._properties
if (old, p) in pairs and not pairs.remove((old, p))} | Replace the name of an object by a new one. | Below is the the instruction that describes the task:
### Input:
Replace the name of an object by a new one.
### Response:
def rename_object(self, old, new):
"""Replace the name of an object by a new one."""
self._objects.replace(old, new)
pairs = self._pairs
pairs |= {(new, p) for ... |
def _complete_path(self, cmd_param_text, full_cmd, *_):
""" completes paths """
if full_cmd.endswith(" "):
cmd_param, path = " ", " "
else:
pieces = shlex.split(full_cmd)
if len(pieces) > 1:
cmd_param = pieces[-1]
else:
... | completes paths | Below is the the instruction that describes the task:
### Input:
completes paths
### Response:
def _complete_path(self, cmd_param_text, full_cmd, *_):
""" completes paths """
if full_cmd.endswith(" "):
cmd_param, path = " ", " "
else:
pieces = shlex.split(full_cmd)
... |
def deduplicate(s, ch):
"""
From http://stackoverflow.com/q/42216559/610569
s = 'this is an irritating string with random spacing .'
deduplicate(s)
'this is an irritating string with random spacing .'
"""
return ch.join([substring for substring in s.strip().split(ch) if su... | From http://stackoverflow.com/q/42216559/610569
s = 'this is an irritating string with random spacing .'
deduplicate(s)
'this is an irritating string with random spacing .' | Below is the the instruction that describes the task:
### Input:
From http://stackoverflow.com/q/42216559/610569
s = 'this is an irritating string with random spacing .'
deduplicate(s)
'this is an irritating string with random spacing .'
### Response:
def deduplicate(s, ch):
"""
... |
def maybe_run_for_org(org, task_func, task_key, lock_timeout):
"""
Runs the given task function for the specified org provided it's not already running
:param org: the org
:param task_func: the task function
:param task_key: the task key
:param lock_timeout: the lock timeout in seconds
"""
... | Runs the given task function for the specified org provided it's not already running
:param org: the org
:param task_func: the task function
:param task_key: the task key
:param lock_timeout: the lock timeout in seconds | Below is the the instruction that describes the task:
### Input:
Runs the given task function for the specified org provided it's not already running
:param org: the org
:param task_func: the task function
:param task_key: the task key
:param lock_timeout: the lock timeout in seconds
### Response:
... |
def parse_time(time):
"""
Parse a date/time string and return a corresponding datetime object.
Args:
time (str): A ``string` of one of the following formats: ``%H:%M``, ``%Y-%m-%d`` or
``%Y-%m-%d %H:%M``.
Returns:
datetime.datetime: Depending on input string either returns ... | Parse a date/time string and return a corresponding datetime object.
Args:
time (str): A ``string` of one of the following formats: ``%H:%M``, ``%Y-%m-%d`` or
``%Y-%m-%d %H:%M``.
Returns:
datetime.datetime: Depending on input string either returns ``datetime.date``,
``d... | Below is the the instruction that describes the task:
### Input:
Parse a date/time string and return a corresponding datetime object.
Args:
time (str): A ``string` of one of the following formats: ``%H:%M``, ``%Y-%m-%d`` or
``%Y-%m-%d %H:%M``.
Returns:
datetime.datetime: Depend... |
def add_data_item(self, data_item: DataItem) -> None:
"""Add a data item to the group.
:param data_item: The :py:class:`nion.swift.Facade.DataItem` object to add.
.. versionadded:: 1.0
Scriptable: Yes
"""
display_item = data_item._data_item.container.get_display_item_f... | Add a data item to the group.
:param data_item: The :py:class:`nion.swift.Facade.DataItem` object to add.
.. versionadded:: 1.0
Scriptable: Yes | Below is the the instruction that describes the task:
### Input:
Add a data item to the group.
:param data_item: The :py:class:`nion.swift.Facade.DataItem` object to add.
.. versionadded:: 1.0
Scriptable: Yes
### Response:
def add_data_item(self, data_item: DataItem) -> None:
"""... |
def batch_step(self, batch_idx=None):
"""Updates the learning rate for the batch index: ``batch_idx``.
If ``batch_idx`` is None, ``CyclicLR`` will use an internal
batch index to keep track of the index.
"""
if batch_idx is None:
batch_idx = self.last_batch_idx + 1
... | Updates the learning rate for the batch index: ``batch_idx``.
If ``batch_idx`` is None, ``CyclicLR`` will use an internal
batch index to keep track of the index. | Below is the the instruction that describes the task:
### Input:
Updates the learning rate for the batch index: ``batch_idx``.
If ``batch_idx`` is None, ``CyclicLR`` will use an internal
batch index to keep track of the index.
### Response:
def batch_step(self, batch_idx=None):
"""Updates t... |
def send_mail(subject, body_text, addr_from, recipient_list,
fail_silently=False, auth_user=None, auth_password=None,
attachments=None, body_html=None, html_message=None,
connection=None, headers=None):
"""
Sends a multipart email containing text and html versions ... | Sends a multipart email containing text and html versions which
are encrypted for each recipient that has a valid gpg key
installed. | Below is the the instruction that describes the task:
### Input:
Sends a multipart email containing text and html versions which
are encrypted for each recipient that has a valid gpg key
installed.
### Response:
def send_mail(subject, body_text, addr_from, recipient_list,
fail_silently=Fal... |
def _target_chroms_and_header(bam_file, data):
"""Get a list of chromosomes to target and new updated ref_file header.
Could potentially handle remapping from chr1 -> 1 but currently disabled due
to speed issues.
"""
special_remaps = {"chrM": "MT", "MT": "chrM"}
target_chroms = dict([(x.name, i... | Get a list of chromosomes to target and new updated ref_file header.
Could potentially handle remapping from chr1 -> 1 but currently disabled due
to speed issues. | Below is the the instruction that describes the task:
### Input:
Get a list of chromosomes to target and new updated ref_file header.
Could potentially handle remapping from chr1 -> 1 but currently disabled due
to speed issues.
### Response:
def _target_chroms_and_header(bam_file, data):
"""Get a list... |
def _get_namespace2go2term(go2terms):
"""Group GO IDs by namespace."""
namespace2go2term = cx.defaultdict(dict)
for goid, goterm in go2terms.items():
namespace2go2term[goterm.namespace][goid] = goterm
return namespace2go2term | Group GO IDs by namespace. | Below is the the instruction that describes the task:
### Input:
Group GO IDs by namespace.
### Response:
def _get_namespace2go2term(go2terms):
"""Group GO IDs by namespace."""
namespace2go2term = cx.defaultdict(dict)
for goid, goterm in go2terms.items():
namespace2go2term[goter... |
def getSortedTrackedDeviceIndicesOfClass(self, eTrackedDeviceClass, unTrackedDeviceIndexArrayCount, unRelativeToTrackedDeviceIndex):
"""
Get a sorted array of device indices of a given class of tracked devices (e.g. controllers). Devices are sorted right to left
relative to the specified tracke... | Get a sorted array of device indices of a given class of tracked devices (e.g. controllers). Devices are sorted right to left
relative to the specified tracked device (default: hmd -- pass in -1 for absolute tracking space). Returns the number of devices
in the list, or the size of the array needed if... | Below is the the instruction that describes the task:
### Input:
Get a sorted array of device indices of a given class of tracked devices (e.g. controllers). Devices are sorted right to left
relative to the specified tracked device (default: hmd -- pass in -1 for absolute tracking space). Returns the numb... |
def main():
"""
Install a package from pypi or gemfury
:return:
"""
pypitools.common.setup_main()
config = pypitools.common.ConfigData()
module_name = os.path.basename(os.getcwd())
args = []
if config.use_sudo:
args.extend([
'sudo',
'-H',
])
... | Install a package from pypi or gemfury
:return: | Below is the the instruction that describes the task:
### Input:
Install a package from pypi or gemfury
:return:
### Response:
def main():
"""
Install a package from pypi or gemfury
:return:
"""
pypitools.common.setup_main()
config = pypitools.common.ConfigData()
module_name = os.pa... |
def build_base_parameters(request):
"""Build the list of parameters to forward from the post and get parameters"""
getParameters = {}
postParameters = {}
files = {}
# Copy GET parameters, excluding ebuio_*
for v in request.GET:
if v[:6] != 'ebuio_':
val = request.GET.getlis... | Build the list of parameters to forward from the post and get parameters | Below is the the instruction that describes the task:
### Input:
Build the list of parameters to forward from the post and get parameters
### Response:
def build_base_parameters(request):
"""Build the list of parameters to forward from the post and get parameters"""
getParameters = {}
postParameters =... |
def int_to_base(n, base):
"""
:type n: int
:type base: int
:rtype: str
"""
is_negative = False
if n == 0:
return '0'
elif n < 0:
is_negative = True
n *= -1
digit = string.digits + string.ascii_uppercase
res = ''
while n > 0:
res += ... | :type n: int
:type base: int
:rtype: str | Below is the the instruction that describes the task:
### Input:
:type n: int
:type base: int
:rtype: str
### Response:
def int_to_base(n, base):
"""
:type n: int
:type base: int
:rtype: str
"""
is_negative = False
if n == 0:
return '0'
elif n < 0... |
def alphanum(columns, name=None, extended=False, isLast=False):
"""
Creates the grammar for an Alphanumeric (A) field, accepting only the
specified number of characters.
By default Alphanumeric fields accept only ASCII characters, excluding
lowercases. If the extended flag is set to True, then non-... | Creates the grammar for an Alphanumeric (A) field, accepting only the
specified number of characters.
By default Alphanumeric fields accept only ASCII characters, excluding
lowercases. If the extended flag is set to True, then non-ASCII characters
are allowed, but the no ASCII lowercase constraint is k... | Below is the the instruction that describes the task:
### Input:
Creates the grammar for an Alphanumeric (A) field, accepting only the
specified number of characters.
By default Alphanumeric fields accept only ASCII characters, excluding
lowercases. If the extended flag is set to True, then non-ASCII c... |
def _add_value_enum(self, var, tag):
"""
supports adding variables to the xml
Parameters
---------------
var: The SubElement variable
tag: The SubElement tag to which enum value is to be added
Return
---------------
None
"""
if va... | supports adding variables to the xml
Parameters
---------------
var: The SubElement variable
tag: The SubElement tag to which enum value is to be added
Return
---------------
None | Below is the the instruction that describes the task:
### Input:
supports adding variables to the xml
Parameters
---------------
var: The SubElement variable
tag: The SubElement tag to which enum value is to be added
Return
---------------
None
### Response:... |
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in e... | Read in the __exclude__ list and remove all excluded objects from the
high data | Below is the the instruction that describes the task:
### Input:
Read in the __exclude__ list and remove all excluded objects from the
high data
### Response:
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'... |
def validate(self, document):
"""
Check input for Python syntax errors.
"""
# When the input starts with Ctrl-Z, always accept. This means EOF in a
# Python REPL.
if document.text.startswith('\x1a'):
return
try:
if self.get_compiler_flags:... | Check input for Python syntax errors. | Below is the the instruction that describes the task:
### Input:
Check input for Python syntax errors.
### Response:
def validate(self, document):
"""
Check input for Python syntax errors.
"""
# When the input starts with Ctrl-Z, always accept. This means EOF in a
# Python R... |
def edit(
self,
text: str,
parse_mode: str = "",
disable_web_page_preview: bool = None,
reply_markup: Union[
"pyrogram.InlineKeyboardMarkup",
"pyrogram.ReplyKeyboardMarkup",
"pyrogram.ReplyKeyboardRemove",
"pyrogram.ForceReply"
... | Bound method *edit* of :obj:`Message <pyrogram.Message>`
Use as a shortcut for:
.. code-block:: python
client.edit_message_text(
chat_id=message.chat.id,
message_id=message.message_id,
text="hello"
)
Example:
... | Below is the the instruction that describes the task:
### Input:
Bound method *edit* of :obj:`Message <pyrogram.Message>`
Use as a shortcut for:
.. code-block:: python
client.edit_message_text(
chat_id=message.chat.id,
message_id=message.message_id,
... |
async def parse_vn_results(soup):
"""
Parse Visual Novel search pages.
:param soup: The BS4 class object
:return: A list of dictionaries containing a name and id.
"""
soup = soup.find_all('td', class_='tc1')
vns = []
for item in soup[1:]:
vns.append({'name': item.string, 'id': ... | Parse Visual Novel search pages.
:param soup: The BS4 class object
:return: A list of dictionaries containing a name and id. | Below is the the instruction that describes the task:
### Input:
Parse Visual Novel search pages.
:param soup: The BS4 class object
:return: A list of dictionaries containing a name and id.
### Response:
async def parse_vn_results(soup):
"""
Parse Visual Novel search pages.
:param soup: The ... |
def main(): # pylint: disable=too-many-statements
"""Main entry point"""
parser = argparse.ArgumentParser(prog='mediafire-cli',
description=__doc__)
parser.add_argument('--debug', dest='debug', action='store_true',
default=False, help='Enable de... | Main entry point | Below is the the instruction that describes the task:
### Input:
Main entry point
### Response:
def main(): # pylint: disable=too-many-statements
"""Main entry point"""
parser = argparse.ArgumentParser(prog='mediafire-cli',
description=__doc__)
parser.add_argument... |
def check(schema, rev_id, page_id=None, radius=defaults.RADIUS,
before=None, window=None):
"""
Checks the revert status of a revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another edit.
:Para... | Checks the revert status of a revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another edit.
:Parameters:
session : :class:`mwapi.Session`
An API session to make use of
rev_id : int
... | Below is the the instruction that describes the task:
### Input:
Checks the revert status of a revision. With this method, you can
determine whether an edit is a 'reverting' edit, was 'reverted' by another
edit and/or was 'reverted_to' by another edit.
:Parameters:
session : :class:`mwapi.Sess... |
def list_courses(args):
"""
List enrolled courses.
@param args: Command-line arguments.
@type args: namedtuple
"""
session = get_session()
login(session, args.username, args.password)
extractor = CourseraExtractor(session)
courses = extractor.list_courses()
logging.info('Found %... | List enrolled courses.
@param args: Command-line arguments.
@type args: namedtuple | Below is the the instruction that describes the task:
### Input:
List enrolled courses.
@param args: Command-line arguments.
@type args: namedtuple
### Response:
def list_courses(args):
"""
List enrolled courses.
@param args: Command-line arguments.
@type args: namedtuple
"""
sess... |
def settle_deferred_messages(self, settlement, messages, **kwargs):
"""Settle messages that have been previously deferred.
:param settlement: How the messages are to be settled. This must be a string
of one of the following values: 'completed', 'suspended', 'abandoned'.
:type settlemen... | Settle messages that have been previously deferred.
:param settlement: How the messages are to be settled. This must be a string
of one of the following values: 'completed', 'suspended', 'abandoned'.
:type settlement: str
:param messages: A list of deferred messages to be settled.
... | Below is the the instruction that describes the task:
### Input:
Settle messages that have been previously deferred.
:param settlement: How the messages are to be settled. This must be a string
of one of the following values: 'completed', 'suspended', 'abandoned'.
:type settlement: str
... |
def check_edge(self, name1, name2):
'''
API: check_edge(self, name1, name2)
Description:
Return True if edge exists, False otherwise.
Input:
name1: name of the source node.
name2: name of the sink node.
Return:
Returns True if edge exis... | API: check_edge(self, name1, name2)
Description:
Return True if edge exists, False otherwise.
Input:
name1: name of the source node.
name2: name of the sink node.
Return:
Returns True if edge exists, False otherwise. | Below is the the instruction that describes the task:
### Input:
API: check_edge(self, name1, name2)
Description:
Return True if edge exists, False otherwise.
Input:
name1: name of the source node.
name2: name of the sink node.
Return:
Returns True... |
def generate_table(self, rows):
"""
Generates from a list of rows a PrettyTable object.
"""
table = PrettyTable(**self.kwargs)
for row in self.rows:
if len(row[0]) < self.max_row_width:
appends = self.max_row_width - len(row[0])
for i i... | Generates from a list of rows a PrettyTable object. | Below is the the instruction that describes the task:
### Input:
Generates from a list of rows a PrettyTable object.
### Response:
def generate_table(self, rows):
"""
Generates from a list of rows a PrettyTable object.
"""
table = PrettyTable(**self.kwargs)
for row in self.r... |
def create_payload(self):
"""Remove ``smart_class_parameter_id`` or ``smart_variable_id``"""
payload = super(OverrideValue, self).create_payload()
if hasattr(self, 'smart_class_parameter'):
del payload['smart_class_parameter_id']
if hasattr(self, 'smart_variable'):
... | Remove ``smart_class_parameter_id`` or ``smart_variable_id`` | Below is the the instruction that describes the task:
### Input:
Remove ``smart_class_parameter_id`` or ``smart_variable_id``
### Response:
def create_payload(self):
"""Remove ``smart_class_parameter_id`` or ``smart_variable_id``"""
payload = super(OverrideValue, self).create_payload()
if h... |
def parse_tagInfo_data(self):
"""parses and plots taginfo files"""
# Find and parse homer taginfo reports
for f in self.find_log_files('homer/tagInfo', filehandles=True):
s_name = os.path.basename(f['root'])
s_name = self.clean_s_name(s_name, f['root'])
parsed... | parses and plots taginfo files | Below is the the instruction that describes the task:
### Input:
parses and plots taginfo files
### Response:
def parse_tagInfo_data(self):
"""parses and plots taginfo files"""
# Find and parse homer taginfo reports
for f in self.find_log_files('homer/tagInfo', filehandles=True):
... |
def add(self, *args):
"""
This function adds strings to the keyboard, while not exceeding row_width.
E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]}
when row_width is set to 1.
When row_width is set to 2, the following is the r... | This function adds strings to the keyboard, while not exceeding row_width.
E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]}
when row_width is set to 1.
When row_width is set to 2, the following is the result of this function: {keyboard: [["A", ... | Below is the the instruction that describes the task:
### Input:
This function adds strings to the keyboard, while not exceeding row_width.
E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]}
when row_width is set to 1.
When row_width is set t... |
def delete_account_invitation(self, account_id, invitation_id, **kwargs): # noqa: E501
"""Delete a user invitation. # noqa: E501
An endpoint for deleting an active user invitation which has been sent for a new or an existing user to join the account. **Example usage:** `curl -X DELETE https://api.u... | Delete a user invitation. # noqa: E501
An endpoint for deleting an active user invitation which has been sent for a new or an existing user to join the account. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/accounts/{account-id}/user-invitations/{invitation-id} -H 'Authorization:... | Below is the the instruction that describes the task:
### Input:
Delete a user invitation. # noqa: E501
An endpoint for deleting an active user invitation which has been sent for a new or an existing user to join the account. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/acco... |
def process_request(self, request):
"""Check if user is logged in"""
assert hasattr(request, 'user')
if not request.user.is_authenticated():
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
return HttpResponseRedirect(re... | Check if user is logged in | Below is the the instruction that describes the task:
### Input:
Check if user is logged in
### Response:
def process_request(self, request):
"""Check if user is logged in"""
assert hasattr(request, 'user')
if not request.user.is_authenticated():
path = request.path_info.lstrip(... |
def rebuild( self ):
"""
Rebuilds the current item in the scene.
"""
self.markForRebuild(False)
self._textData = []
if ( self.rebuildBlocked() ):
return
scene = self.scene()
if ( not scene ):
... | Rebuilds the current item in the scene. | Below is the the instruction that describes the task:
### Input:
Rebuilds the current item in the scene.
### Response:
def rebuild( self ):
"""
Rebuilds the current item in the scene.
"""
self.markForRebuild(False)
self._textData = []
if ( s... |
def apply_op(input_layer, operation, *op_args, **op_kwargs):
"""Applies the given operation to this before without adding any summaries.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_k... | Applies the given operation to this before without adding any summaries.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**op_kwargs: Keyword arguments for the operation.
Returns:
A new l... | Below is the the instruction that describes the task:
### Input:
Applies the given operation to this before without adding any summaries.
Args:
input_layer: The input layer for this op.
operation: An operation that takes a tensor and the supplied args.
*op_args: Extra arguments for operation.
**o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.