code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_services_health(self) -> dict:
"""Get the health of all services.
Returns:
dict, services id and health status
"""
# Initialise
services_health = {}
# Get Service IDs
services_ids = self._get_services()
for service_id in services_id... | Get the health of all services.
Returns:
dict, services id and health status | Below is the the instruction that describes the task:
### Input:
Get the health of all services.
Returns:
dict, services id and health status
### Response:
def get_services_health(self) -> dict:
"""Get the health of all services.
Returns:
dict, services id and heal... |
def _bulk_history_create(self, model, batch_size):
"""Save a copy of all instances to the historical model.
:param model: Model you want to bulk create
:param batch_size: number of models to create at once.
:return:
"""
instances = []
history = utils.get_history... | Save a copy of all instances to the historical model.
:param model: Model you want to bulk create
:param batch_size: number of models to create at once.
:return: | Below is the the instruction that describes the task:
### Input:
Save a copy of all instances to the historical model.
:param model: Model you want to bulk create
:param batch_size: number of models to create at once.
:return:
### Response:
def _bulk_history_create(self, model, batch_size)... |
def spkopa(filename):
"""
Open an existing SPK file for subsequent write.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkopa_c.html
:param filename: The name of an existing SPK file.
:type filename: str
:return: A handle attached to the SPK file opened to append.
:rtype: int
... | Open an existing SPK file for subsequent write.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkopa_c.html
:param filename: The name of an existing SPK file.
:type filename: str
:return: A handle attached to the SPK file opened to append.
:rtype: int | Below is the the instruction that describes the task:
### Input:
Open an existing SPK file for subsequent write.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkopa_c.html
:param filename: The name of an existing SPK file.
:type filename: str
:return: A handle attached to the SPK file o... |
def modify_access(src, dst='any', port=None, proto=None, action='allow',
index=None):
"""
Grant access to an address or subnet
:param src: address (e.g. 192.168.1.234) or subnet
(e.g. 192.168.1.0/24).
:param dst: destiny of the connection, if the machine has multiple I... | Grant access to an address or subnet
:param src: address (e.g. 192.168.1.234) or subnet
(e.g. 192.168.1.0/24).
:param dst: destiny of the connection, if the machine has multiple IPs and
connections to only one of those have to accepted this is the
field has to be... | Below is the the instruction that describes the task:
### Input:
Grant access to an address or subnet
:param src: address (e.g. 192.168.1.234) or subnet
(e.g. 192.168.1.0/24).
:param dst: destiny of the connection, if the machine has multiple IPs and
connections to only one ... |
def respond(self,
content=EmptyValue,
content_type=EmptyValue,
always_hash_content=True,
ext=None):
"""
Respond to the request.
This generates the :attr:`mohawk.Receiver.response_header`
attribute.
:param content=E... | Respond to the request.
This generates the :attr:`mohawk.Receiver.response_header`
attribute.
:param content=EmptyValue: Byte string of response body that will be sent.
:type content=EmptyValue: str
:param content_type=EmptyValue: content-type header value for response.
... | Below is the the instruction that describes the task:
### Input:
Respond to the request.
This generates the :attr:`mohawk.Receiver.response_header`
attribute.
:param content=EmptyValue: Byte string of response body that will be sent.
:type content=EmptyValue: str
:param co... |
def printdir(self):
"""Print a table of contents for the zip file."""
print "%-46s %19s %12s" % ("File Name", "Modified ", "Size")
for zinfo in self.filelist:
date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
print "%-46s %s %12d" % (zinfo.filename, date, zinf... | Print a table of contents for the zip file. | Below is the the instruction that describes the task:
### Input:
Print a table of contents for the zip file.
### Response:
def printdir(self):
"""Print a table of contents for the zip file."""
print "%-46s %19s %12s" % ("File Name", "Modified ", "Size")
for zinfo in self.filelist:
... |
def addFeature(self, features,
gdbVersion=None,
rollbackOnFailure=True):
""" Adds a single feature to the service
Inputs:
feature - list of common.Feature object or a single
common.Feature Object, a FeatureSet object, or a
... | Adds a single feature to the service
Inputs:
feature - list of common.Feature object or a single
common.Feature Object, a FeatureSet object, or a
list of dictionary objects
gdbVersion - Geodatabase version to apply the edits
... | Below is the the instruction that describes the task:
### Input:
Adds a single feature to the service
Inputs:
feature - list of common.Feature object or a single
common.Feature Object, a FeatureSet object, or a
list of dictionary objects
... |
def ranked_in_list(self, members, **options):
'''
Retrieve a page of leaders from the leaderboard for a given list of members.
@param members [Array] Member names.
@param options [Hash] Options to be used when retrieving the page from the leaderboard.
@return a page of leaders f... | Retrieve a page of leaders from the leaderboard for a given list of members.
@param members [Array] Member names.
@param options [Hash] Options to be used when retrieving the page from the leaderboard.
@return a page of leaders from the leaderboard for a given list of members. | Below is the the instruction that describes the task:
### Input:
Retrieve a page of leaders from the leaderboard for a given list of members.
@param members [Array] Member names.
@param options [Hash] Options to be used when retrieving the page from the leaderboard.
@return a page of leader... |
def _synchronize_controls(self):
"""
Updates the gui based on button configs.
"""
# whether the script is visible
self.grid_script._widget.setVisible(self.button_script.get_value())
# whether we should be able to edit it.
if not self.combo_autoscript.get_index()... | Updates the gui based on button configs. | Below is the the instruction that describes the task:
### Input:
Updates the gui based on button configs.
### Response:
def _synchronize_controls(self):
"""
Updates the gui based on button configs.
"""
# whether the script is visible
self.grid_script._widget.setVisible(self... |
def add_dummy_scores(iteratable, score=0):
"""Add zero scores to all sequences"""
for seq in iteratable:
seq.letter_annotations["phred_quality"] = (score,)*len(seq)
yield seq | Add zero scores to all sequences | Below is the the instruction that describes the task:
### Input:
Add zero scores to all sequences
### Response:
def add_dummy_scores(iteratable, score=0):
"""Add zero scores to all sequences"""
for seq in iteratable:
seq.letter_annotations["phred_quality"] = (score,)*len(seq)
yield seq |
def _set_tx_queue(self, v, load=False):
"""
Setter method for tx_queue, mapped from YANG variable /qos/tx_queue (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tx_queue is considered as a private
method. Backends looking to populate this variable should
... | Setter method for tx_queue, mapped from YANG variable /qos/tx_queue (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tx_queue is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_tx_queue() directl... | Below is the the instruction that describes the task:
### Input:
Setter method for tx_queue, mapped from YANG variable /qos/tx_queue (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tx_queue is considered as a private
method. Backends looking to populate this ... |
def send_slack_message(message):
"""Send a message to the slack channel #coretools"""
if 'SLACK_WEB_HOOK' not in os.environ:
raise EnvironmentError("Could not find SLACK_WEB_HOOK environment variable")
webhook = os.environ['SLACK_WEB_HOOK']
r = requests.post(webhook, json={'text':message, 'us... | Send a message to the slack channel #coretools | Below is the the instruction that describes the task:
### Input:
Send a message to the slack channel #coretools
### Response:
def send_slack_message(message):
"""Send a message to the slack channel #coretools"""
if 'SLACK_WEB_HOOK' not in os.environ:
raise EnvironmentError("Could not find SLACK_WE... |
def process_paths(options, candidates=None, error=True):
"""Process files and log errors."""
errors = check_path(options, rootdir=CURDIR, candidates=candidates)
if options.format in ['pycodestyle', 'pep8']:
pattern = "%(filename)s:%(lnum)s:%(col)s: %(text)s"
elif options.format == 'pylint':
... | Process files and log errors. | Below is the the instruction that describes the task:
### Input:
Process files and log errors.
### Response:
def process_paths(options, candidates=None, error=True):
"""Process files and log errors."""
errors = check_path(options, rootdir=CURDIR, candidates=candidates)
if options.format in ['pycodesty... |
def _add_delta_tdi(self, other):
"""
Add a delta of a TimedeltaIndex
return the i8 result view
"""
if len(self) != len(other):
raise ValueError("cannot add indices of unequal length")
if isinstance(other, np.ndarray):
# ndarray[timedelta64]; wrap ... | Add a delta of a TimedeltaIndex
return the i8 result view | Below is the the instruction that describes the task:
### Input:
Add a delta of a TimedeltaIndex
return the i8 result view
### Response:
def _add_delta_tdi(self, other):
"""
Add a delta of a TimedeltaIndex
return the i8 result view
"""
if len(self) != len(other):
... |
def _consfcn(self, x):
""" Evaluates nonlinear constraints and their Jacobian for OPF.
"""
h, g = self._gh(x)
dh, dg = self._dgh(x)
return h, g, dh, dg | Evaluates nonlinear constraints and their Jacobian for OPF. | Below is the the instruction that describes the task:
### Input:
Evaluates nonlinear constraints and their Jacobian for OPF.
### Response:
def _consfcn(self, x):
""" Evaluates nonlinear constraints and their Jacobian for OPF.
"""
h, g = self._gh(x)
dh, dg = self._dgh(x)
ret... |
def bump_option_validator(ctx, param, value):
"""In case a value is provided checks that it is a valid version string. If
is not thrown :class:`click.UsageError`.
Return a :class:`~braulio.version.Version` object or **None**.
"""
if value:
try:
value = Version(value)
ex... | In case a value is provided checks that it is a valid version string. If
is not thrown :class:`click.UsageError`.
Return a :class:`~braulio.version.Version` object or **None**. | Below is the the instruction that describes the task:
### Input:
In case a value is provided checks that it is a valid version string. If
is not thrown :class:`click.UsageError`.
Return a :class:`~braulio.version.Version` object or **None**.
### Response:
def bump_option_validator(ctx, param, value):
... |
def get_days_since_last_modified(filename):
"""
:param filename: Absolute file path
:return: Number of days since filename's last modified time
"""
now = datetime.now()
last_modified = datetime.fromtimestamp(os.path.getmtime(filename))
return (now - last_modified)... | :param filename: Absolute file path
:return: Number of days since filename's last modified time | Below is the the instruction that describes the task:
### Input:
:param filename: Absolute file path
:return: Number of days since filename's last modified time
### Response:
def get_days_since_last_modified(filename):
"""
:param filename: Absolute file path
:return: Number of days ... |
def _vmomentdensity(self,R,z,n,m,o,nsigma=None,mc=False,nmc=10000,
_returnmc=False,_vrs=None,_vts=None,_vzs=None,
_rawgausssamples=False,
gl=False,ngl=_DEFAULTNGL,_returngl=False,_glqeval=None,
_return_actions=False,_jr=None,_lz... | Non-physical version of vmomentdensity, otherwise the same | Below is the the instruction that describes the task:
### Input:
Non-physical version of vmomentdensity, otherwise the same
### Response:
def _vmomentdensity(self,R,z,n,m,o,nsigma=None,mc=False,nmc=10000,
_returnmc=False,_vrs=None,_vts=None,_vzs=None,
_rawgausssamples=... |
def copy(
ctx,
opts,
owner_repo_package,
destination,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
):
"""
Copy a package to another repository.
This requires appropriate permissions for both the source
repository/package and the destination repository.
... | Copy a package to another repository.
This requires appropriate permissions for both the source
repository/package and the destination repository.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
pac... | Below is the the instruction that describes the task:
### Input:
Copy a package to another repository.
This requires appropriate permissions for both the source
repository/package and the destination repository.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name wh... |
def selected(self, interrupt=False):
"""This object has been selected."""
self.ao2.output(self.get_title(), interrupt=interrupt) | This object has been selected. | Below is the the instruction that describes the task:
### Input:
This object has been selected.
### Response:
def selected(self, interrupt=False):
"""This object has been selected."""
self.ao2.output(self.get_title(), interrupt=interrupt) |
def _log_error(self, request, error):
'''Log exceptions during a fetch.'''
_logger.error(
_('Fetching ‘{url}’ encountered an error: {error}'),
url=request.url, error=error
) | Log exceptions during a fetch. | Below is the the instruction that describes the task:
### Input:
Log exceptions during a fetch.
### Response:
def _log_error(self, request, error):
'''Log exceptions during a fetch.'''
_logger.error(
_('Fetching ‘{url}’ encountered an error: {error}'),
url=request.url, error... |
def verify_crl(cert, path, validation_context, use_deltas=True, cert_description=None, end_entity_name_override=None):
"""
Verifies a certificate against a list of CRLs, checking to make sure the
certificate has not been revoked. Uses the algorithm from
https://tools.ietf.org/html/rfc5280#section-6.3 as... | Verifies a certificate against a list of CRLs, checking to make sure the
certificate has not been revoked. Uses the algorithm from
https://tools.ietf.org/html/rfc5280#section-6.3 as a basis, but the
implementation differs to allow CRLs from unrecorded locations.
:param cert:
An asn1cyrpto.x509.... | Below is the the instruction that describes the task:
### Input:
Verifies a certificate against a list of CRLs, checking to make sure the
certificate has not been revoked. Uses the algorithm from
https://tools.ietf.org/html/rfc5280#section-6.3 as a basis, but the
implementation differs to allow CRLs fro... |
def zoom_motion(self, event=None):
"""motion event handler for zoom mode"""
try:
x, y = event.x, event.y
except:
return
self.report_motion(event=event)
if self.zoom_ini is None:
return
ini_x, ini_y, ini_xd, ini_yd = self.zoom_ini
... | motion event handler for zoom mode | Below is the the instruction that describes the task:
### Input:
motion event handler for zoom mode
### Response:
def zoom_motion(self, event=None):
"""motion event handler for zoom mode"""
try:
x, y = event.x, event.y
except:
return
self.report_motion(event... |
def variable(self):
"""
variable : variable
Feature Type Array adds:
variable : variable[expression]
Feature Type Func adds:
variable : variable(arg_list)
"""
var = Var(self.cur_token)
self.eat(TokenTypes.VAR)
if Features.TYPE_ARRA... | variable : variable
Feature Type Array adds:
variable : variable[expression]
Feature Type Func adds:
variable : variable(arg_list) | Below is the the instruction that describes the task:
### Input:
variable : variable
Feature Type Array adds:
variable : variable[expression]
Feature Type Func adds:
variable : variable(arg_list)
### Response:
def variable(self):
"""
variable : variable
... |
def merge_params(params, lparams):
"""Merge global ignore/select with linter local params."""
ignore = params.get('ignore', set())
if 'ignore' in lparams:
ignore = ignore | set(lparams['ignore'])
select = params.get('select', set())
if 'select' in lparams:
select = select | set(lpar... | Merge global ignore/select with linter local params. | Below is the the instruction that describes the task:
### Input:
Merge global ignore/select with linter local params.
### Response:
def merge_params(params, lparams):
"""Merge global ignore/select with linter local params."""
ignore = params.get('ignore', set())
if 'ignore' in lparams:
ignore =... |
def createNote(self, title=None, text=None):
"""Create a new managed note. Any changes to the note will be uploaded when :py:meth:`sync` is called.
Args:
title (str): The title of the note.
text (str): The text of the note.
Returns:
gkeepapi.node.List: The n... | Create a new managed note. Any changes to the note will be uploaded when :py:meth:`sync` is called.
Args:
title (str): The title of the note.
text (str): The text of the note.
Returns:
gkeepapi.node.List: The new note. | Below is the the instruction that describes the task:
### Input:
Create a new managed note. Any changes to the note will be uploaded when :py:meth:`sync` is called.
Args:
title (str): The title of the note.
text (str): The text of the note.
Returns:
gkeepapi.nod... |
def complete_irradiance(self, times=None, weather=None):
"""
Determine the missing irradiation columns. Only two of the
following data columns (dni, ghi, dhi) are needed to calculate
the missing data.
This function is not safe at the moment. Results can be too high
or ne... | Determine the missing irradiation columns. Only two of the
following data columns (dni, ghi, dhi) are needed to calculate
the missing data.
This function is not safe at the moment. Results can be too high
or negative. Please contribute and help to improve this function
on https:... | Below is the the instruction that describes the task:
### Input:
Determine the missing irradiation columns. Only two of the
following data columns (dni, ghi, dhi) are needed to calculate
the missing data.
This function is not safe at the moment. Results can be too high
or negative. ... |
def update(self, index, iterable, commit=True):
"""
Updates the index with current data.
:param index: The search_indexes.Index object
:param iterable: The queryset
:param commit: commit to the backend.
"""
parler = False
# setup here because self.existing... | Updates the index with current data.
:param index: The search_indexes.Index object
:param iterable: The queryset
:param commit: commit to the backend. | Below is the the instruction that describes the task:
### Input:
Updates the index with current data.
:param index: The search_indexes.Index object
:param iterable: The queryset
:param commit: commit to the backend.
### Response:
def update(self, index, iterable, commit=True):
"""
... |
def get_struct(name):
"""Get a struct by it's name.
Args:
name: The name of the struct
Returns:
The struct's id
Raises:
exceptions.SarkStructNotFound: is the struct does not exist.
"""
sid = idc.GetStrucIdByName(name)
if sid == idaapi.BADADDR:
raise excepti... | Get a struct by it's name.
Args:
name: The name of the struct
Returns:
The struct's id
Raises:
exceptions.SarkStructNotFound: is the struct does not exist. | Below is the the instruction that describes the task:
### Input:
Get a struct by it's name.
Args:
name: The name of the struct
Returns:
The struct's id
Raises:
exceptions.SarkStructNotFound: is the struct does not exist.
### Response:
def get_struct(name):
"""Get a struct... |
def _add_current_codedir(self, path):
"""Adds the directory of the file at the specified path as a base
path to find other files in.
"""
dirpath = self.tramp.dirname(path)
if dirpath not in self.basepaths:
self.basepaths.append(dirpath)
self.rescan() | Adds the directory of the file at the specified path as a base
path to find other files in. | Below is the the instruction that describes the task:
### Input:
Adds the directory of the file at the specified path as a base
path to find other files in.
### Response:
def _add_current_codedir(self, path):
"""Adds the directory of the file at the specified path as a base
path to find oth... |
def _on_permission_result(self, code, perms, results):
""" Handles a permission request result by passing it to the
handler with the given code.
"""
#: Get the handler for this request
handler = self._permission_requests.get(code, None)
if handler is not None:
... | Handles a permission request result by passing it to the
handler with the given code. | Below is the the instruction that describes the task:
### Input:
Handles a permission request result by passing it to the
handler with the given code.
### Response:
def _on_permission_result(self, code, perms, results):
""" Handles a permission request result by passing it to the
handler ... |
def _inertia_from_labels(X, centers, labels):
"""Compute inertia with cosine distance using known labels.
"""
n_examples, n_features = X.shape
inertia = np.zeros((n_examples,))
for ee in range(n_examples):
inertia[ee] = 1 - X[ee, :].dot(centers[int(labels[ee]), :].T)
return np.sum(inert... | Compute inertia with cosine distance using known labels. | Below is the the instruction that describes the task:
### Input:
Compute inertia with cosine distance using known labels.
### Response:
def _inertia_from_labels(X, centers, labels):
"""Compute inertia with cosine distance using known labels.
"""
n_examples, n_features = X.shape
inertia = np.zeros((... |
def stackscripts(self, *filters, **kwargs):
"""
Returns a list of :any:`StackScripts<StackScript>`, both public and
private. You may filter this query to return only
:any:`StackScripts<StackScript>` that match certain criteria. You may
also request only your own private :any:`S... | Returns a list of :any:`StackScripts<StackScript>`, both public and
private. You may filter this query to return only
:any:`StackScripts<StackScript>` that match certain criteria. You may
also request only your own private :any:`StackScripts<StackScript>`::
my_stackscripts = client... | Below is the the instruction that describes the task:
### Input:
Returns a list of :any:`StackScripts<StackScript>`, both public and
private. You may filter this query to return only
:any:`StackScripts<StackScript>` that match certain criteria. You may
also request only your own private :a... |
def make_compare(key, value, obj):
"Map a key name to a specific comparison function"
if '__' not in key:
# If no __ exists, default to doing an "exact" comparison
key, comp = key, 'exact'
else:
key, comp = key.rsplit('__', 1)
# Check if comp is valid
if hasattr(Compare, comp... | Map a key name to a specific comparison function | Below is the the instruction that describes the task:
### Input:
Map a key name to a specific comparison function
### Response:
def make_compare(key, value, obj):
"Map a key name to a specific comparison function"
if '__' not in key:
# If no __ exists, default to doing an "exact" comparison
... |
def add_gateway_to_diagram(self, process_id, gateway_type, gateway_name="", gateway_direction="Unspecified",
node_id=None):
"""
Adds an exclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_type: s... | Adds an exclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_type: string object. Type of gateway to be added.
:param gateway_name: string object. Name of exclusive gateway,
:param gateway_direction: string object. Accepted val... | Below is the the instruction that describes the task:
### Input:
Adds an exclusiveGateway element to BPMN diagram.
:param process_id: string object. ID of parent process,
:param gateway_type: string object. Type of gateway to be added.
:param gateway_name: string object. Name of exclusive g... |
def _to_operator(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Operator representation."""
if rep == 'Operator':
return data
if rep == 'Stinespring':
return _stinespring_to_operator(data, input_dim, output_dim)
# Convert via Kraus representation
if rep != 'K... | Transform a QuantumChannel to the Operator representation. | Below is the the instruction that describes the task:
### Input:
Transform a QuantumChannel to the Operator representation.
### Response:
def _to_operator(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Operator representation."""
if rep == 'Operator':
return data
if rep... |
def _cli_check_basis(name, data_dir):
'''Checks that a basis set exists and if not, raises a helpful exception'''
if name is None:
return None
name = misc.transform_basis_name(name)
metadata = api.get_metadata(data_dir)
if not name in metadata:
errstr = "Basis set '" + name + "' do... | Checks that a basis set exists and if not, raises a helpful exception | Below is the the instruction that describes the task:
### Input:
Checks that a basis set exists and if not, raises a helpful exception
### Response:
def _cli_check_basis(name, data_dir):
'''Checks that a basis set exists and if not, raises a helpful exception'''
if name is None:
return None
n... |
def discoverPoints(bacnetapp, address, devID):
"""
Discover the BACnet points in a BACnet device.
:param bacnetApp: The app itself so we can call read
:param address: address of the device as a string (ex. '2:5')
:param devID: device ID of the bacnet device as a string (ex. '1001')
:returns: a... | Discover the BACnet points in a BACnet device.
:param bacnetApp: The app itself so we can call read
:param address: address of the device as a string (ex. '2:5')
:param devID: device ID of the bacnet device as a string (ex. '1001')
:returns: a tuple with deviceName, pss, objList, df
* *device... | Below is the the instruction that describes the task:
### Input:
Discover the BACnet points in a BACnet device.
:param bacnetApp: The app itself so we can call read
:param address: address of the device as a string (ex. '2:5')
:param devID: device ID of the bacnet device as a string (ex. '1001')
:... |
def valid(self, cnpj):
"""Check if a CNPJ is valid.
We should avoid sending invalid CNPJ to the web service as we know
it is going to be a waste of bandwidth. Assumes CNPJ is a string.
"""
if len(cnpj) != 14:
return False
tam = 12
nums = cnpj[:tam]
... | Check if a CNPJ is valid.
We should avoid sending invalid CNPJ to the web service as we know
it is going to be a waste of bandwidth. Assumes CNPJ is a string. | Below is the the instruction that describes the task:
### Input:
Check if a CNPJ is valid.
We should avoid sending invalid CNPJ to the web service as we know
it is going to be a waste of bandwidth. Assumes CNPJ is a string.
### Response:
def valid(self, cnpj):
"""Check if a CNPJ is valid.
... |
def set_freq(self, fout, freq):
"""
Sets new output frequency, required parameters are real current frequency at output and new required frequency.
"""
hsdiv_tuple = (4, 5, 6, 7, 9, 11) # possible dividers
n1div_tuple = (1,) + tuple(range(2,129,2)) #
fdco_min =... | Sets new output frequency, required parameters are real current frequency at output and new required frequency. | Below is the the instruction that describes the task:
### Input:
Sets new output frequency, required parameters are real current frequency at output and new required frequency.
### Response:
def set_freq(self, fout, freq):
"""
Sets new output frequency, required parameters are real current frequenc... |
def main(argv=None, loop=SharedLoop, max_time=None):
"""Main entry point for iotile-gateway."""
should_raise = argv is not None
if argv is None:
argv = sys.argv[1:]
parser = build_parser()
cmd_args = parser.parse_args(argv)
configure_logging(cmd_args.verbose)
logger = logging.getL... | Main entry point for iotile-gateway. | Below is the the instruction that describes the task:
### Input:
Main entry point for iotile-gateway.
### Response:
def main(argv=None, loop=SharedLoop, max_time=None):
"""Main entry point for iotile-gateway."""
should_raise = argv is not None
if argv is None:
argv = sys.argv[1:]
parser =... |
def key_sign(rsakey, message, digest):
"""Sign the given message with the RSA key."""
padding = _asymmetric.padding.PKCS1v15()
signature = rsakey.sign(message, padding, digest)
return signature | Sign the given message with the RSA key. | Below is the the instruction that describes the task:
### Input:
Sign the given message with the RSA key.
### Response:
def key_sign(rsakey, message, digest):
"""Sign the given message with the RSA key."""
padding = _asymmetric.padding.PKCS1v15()
signature = rsakey.sign(message, padding, digest)
re... |
def hook_point(self, hook_name):
"""Generic function to call modules methods if such method is avalaible
:param hook_name: function name to call
:type hook_name: str
:return:None
"""
self.my_daemon.hook_point(hook_name=hook_name, handle=self) | Generic function to call modules methods if such method is avalaible
:param hook_name: function name to call
:type hook_name: str
:return:None | Below is the the instruction that describes the task:
### Input:
Generic function to call modules methods if such method is avalaible
:param hook_name: function name to call
:type hook_name: str
:return:None
### Response:
def hook_point(self, hook_name):
"""Generic function to call... |
def datetime(self):
"""
Returns a datetime object of the month, day, year, and time the game
was played.
"""
date_string = '%s %s' % (self._date, self._year)
date_string = re.sub(r' \(\d+\)', '', date_string)
return datetime.strptime(date_string, '%A, %b %d %Y') | Returns a datetime object of the month, day, year, and time the game
was played. | Below is the the instruction that describes the task:
### Input:
Returns a datetime object of the month, day, year, and time the game
was played.
### Response:
def datetime(self):
"""
Returns a datetime object of the month, day, year, and time the game
was played.
"""
... |
def exec_command(self, command):
"""
Execute a command on the server. If the server allows it, the channel
will then be directly connected to the stdin, stdout, and stderr of
the command being executed.
When the command finishes executing, the channel will be closed and
... | Execute a command on the server. If the server allows it, the channel
will then be directly connected to the stdin, stdout, and stderr of
the command being executed.
When the command finishes executing, the channel will be closed and
can't be reused. You must open a new channel if you... | Below is the the instruction that describes the task:
### Input:
Execute a command on the server. If the server allows it, the channel
will then be directly connected to the stdin, stdout, and stderr of
the command being executed.
When the command finishes executing, the channel will be cl... |
def _Bound_Ph(P, h):
"""Region definition for input P y h
Parameters
----------
P : float
Pressure, [MPa]
h : float
Specific enthalpy, [kJ/kg]
Returns
-------
region : float
IAPWS-97 region code
References
----------
Wagner, W; Kretzschmar, H-J: Int... | Region definition for input P y h
Parameters
----------
P : float
Pressure, [MPa]
h : float
Specific enthalpy, [kJ/kg]
Returns
-------
region : float
IAPWS-97 region code
References
----------
Wagner, W; Kretzschmar, H-J: International Steam Tables: Pro... | Below is the the instruction that describes the task:
### Input:
Region definition for input P y h
Parameters
----------
P : float
Pressure, [MPa]
h : float
Specific enthalpy, [kJ/kg]
Returns
-------
region : float
IAPWS-97 region code
References
------... |
def create(self, display_name, content=None):
""" Create a new user list :class:`collection <pypump.models.collection.Collection>`.
:param display_name: List title.
:param content: (optional) List description.
Example:
>>> pump.me.lists.create(display_name='Friends', conten... | Create a new user list :class:`collection <pypump.models.collection.Collection>`.
:param display_name: List title.
:param content: (optional) List description.
Example:
>>> pump.me.lists.create(display_name='Friends', content='List of friends')
>>> myfriends = pump.me.l... | Below is the the instruction that describes the task:
### Input:
Create a new user list :class:`collection <pypump.models.collection.Collection>`.
:param display_name: List title.
:param content: (optional) List description.
Example:
>>> pump.me.lists.create(display_name='Frien... |
def sections(self):
""" Returns a list of all media sections in this library. Library sections may be any of
:class:`~plexapi.library.MovieSection`, :class:`~plexapi.library.ShowSection`,
:class:`~plexapi.library.MusicSection`, :class:`~plexapi.library.PhotoSection`.
"""
... | Returns a list of all media sections in this library. Library sections may be any of
:class:`~plexapi.library.MovieSection`, :class:`~plexapi.library.ShowSection`,
:class:`~plexapi.library.MusicSection`, :class:`~plexapi.library.PhotoSection`. | Below is the the instruction that describes the task:
### Input:
Returns a list of all media sections in this library. Library sections may be any of
:class:`~plexapi.library.MovieSection`, :class:`~plexapi.library.ShowSection`,
:class:`~plexapi.library.MusicSection`, :class:`~plexapi.librar... |
def _bin(self, bin): # type: (str) -> str
"""
Return path to the given executable.
"""
bin_path = (self._bin_dir / bin).with_suffix(".exe" if self._is_windows else "")
if not bin_path.exists():
return bin
return str(bin_path) | Return path to the given executable. | Below is the the instruction that describes the task:
### Input:
Return path to the given executable.
### Response:
def _bin(self, bin): # type: (str) -> str
"""
Return path to the given executable.
"""
bin_path = (self._bin_dir / bin).with_suffix(".exe" if self._is_windows else ""... |
def _round_field(values, name, freq):
"""Indirectly access pandas rounding functions by wrapping data
as a Series and calling through `.dt` attribute.
Parameters
----------
values : np.ndarray or dask.array-like
Array-like container of datetime-like values
name : str (ceil, floor, round... | Indirectly access pandas rounding functions by wrapping data
as a Series and calling through `.dt` attribute.
Parameters
----------
values : np.ndarray or dask.array-like
Array-like container of datetime-like values
name : str (ceil, floor, round)
Name of rounding function
freq ... | Below is the the instruction that describes the task:
### Input:
Indirectly access pandas rounding functions by wrapping data
as a Series and calling through `.dt` attribute.
Parameters
----------
values : np.ndarray or dask.array-like
Array-like container of datetime-like values
name :... |
def _track_modify(self, cls, name, detail, keep, trace):
"""
Modify settings of a tracked class
"""
self._observers[cls].modify(name, detail, keep, trace) | Modify settings of a tracked class | Below is the the instruction that describes the task:
### Input:
Modify settings of a tracked class
### Response:
def _track_modify(self, cls, name, detail, keep, trace):
"""
Modify settings of a tracked class
"""
self._observers[cls].modify(name, detail, keep, trace) |
def pos_branch(incl, chi):
"""
Determines the effective [as defined in Stone, Loeb,
Berger, PRD 87, 084053 (2013)] aligned dimensionless
spin parameter of a NS-BH binary with tilted BH spin.
This means finding the root chi_eff of
ISCO_eq_chi_first(chi_eff, PG_ISSO_solver(chi,incl)).
The resu... | Determines the effective [as defined in Stone, Loeb,
Berger, PRD 87, 084053 (2013)] aligned dimensionless
spin parameter of a NS-BH binary with tilted BH spin.
This means finding the root chi_eff of
ISCO_eq_chi_first(chi_eff, PG_ISSO_solver(chi,incl)).
The result returned by this function belongs to... | Below is the the instruction that describes the task:
### Input:
Determines the effective [as defined in Stone, Loeb,
Berger, PRD 87, 084053 (2013)] aligned dimensionless
spin parameter of a NS-BH binary with tilted BH spin.
This means finding the root chi_eff of
ISCO_eq_chi_first(chi_eff, PG_ISSO_s... |
def get_observed_magnitude(self, centroid=True):
# NOTE: this import is only here so that we don't load up IRAF
# unnecessarily (ex: for candidates processing).
"""
Get the magnitude at the current pixel x/y location.
:return: Table
"""
max_count = float(self.as... | Get the magnitude at the current pixel x/y location.
:return: Table | Below is the the instruction that describes the task:
### Input:
Get the magnitude at the current pixel x/y location.
:return: Table
### Response:
def get_observed_magnitude(self, centroid=True):
# NOTE: this import is only here so that we don't load up IRAF
# unnecessarily (ex: for candid... |
def post_process_images(self, doctree):
"""Pick the best candidate for all image URIs."""
super(AbstractSlideBuilder, self).post_process_images(doctree)
# figure out where this doctree is in relation to the srcdir
relative_base = (
['..'] *
doctree.attributes.ge... | Pick the best candidate for all image URIs. | Below is the the instruction that describes the task:
### Input:
Pick the best candidate for all image URIs.
### Response:
def post_process_images(self, doctree):
"""Pick the best candidate for all image URIs."""
super(AbstractSlideBuilder, self).post_process_images(doctree)
# figure out ... |
def unique(cls, iterable, key=None):
"""
Yields unique items from *iterable* whilst preserving the original order.
"""
if key is None:
key = lambda x: x
def generator():
seen = set()
seen_add = seen.add
for item in iterable:
key_val = key(item)
if key_val not... | Yields unique items from *iterable* whilst preserving the original order. | Below is the the instruction that describes the task:
### Input:
Yields unique items from *iterable* whilst preserving the original order.
### Response:
def unique(cls, iterable, key=None):
"""
Yields unique items from *iterable* whilst preserving the original order.
"""
if key is None:
key ... |
def values(self, values):
"""The values for insert ,
it can be a dict row or list tuple row.
"""
if isinstance(values, dict):
l = []
for column in self._columns:
l.append(values[column])
self._values.append(tuple(l))
else:
... | The values for insert ,
it can be a dict row or list tuple row. | Below is the the instruction that describes the task:
### Input:
The values for insert ,
it can be a dict row or list tuple row.
### Response:
def values(self, values):
"""The values for insert ,
it can be a dict row or list tuple row.
"""
if isinstance(values, dic... |
def list_files(dirname, extension=None):
"""
List all files in directory `dirname`, option to filter on file extension
"""
f = []
for (dirpath, dirnames, filenames) in os.walk(dirname):
f.extend(filenames)
break
if extension is not None:
# Filter on extension
filt... | List all files in directory `dirname`, option to filter on file extension | Below is the the instruction that describes the task:
### Input:
List all files in directory `dirname`, option to filter on file extension
### Response:
def list_files(dirname, extension=None):
"""
List all files in directory `dirname`, option to filter on file extension
"""
f = []
for (dirpath... |
def _get_hit_nearest_ref_end(self, hits):
'''Returns the hit nearest to the end of the ref sequence from the input list of hits'''
nearest_to_end = hits[0]
for hit in hits[1:]:
if hit.ref_coords().end > nearest_to_end.ref_coords().end:
nearest_to_end = hit
ret... | Returns the hit nearest to the end of the ref sequence from the input list of hits | Below is the the instruction that describes the task:
### Input:
Returns the hit nearest to the end of the ref sequence from the input list of hits
### Response:
def _get_hit_nearest_ref_end(self, hits):
'''Returns the hit nearest to the end of the ref sequence from the input list of hits'''
neares... |
def randset(self):
""" -> a #set of random integers """
return {
self._map_type(int)
for x in range(self.random.randint(3, 10))} | -> a #set of random integers | Below is the the instruction that describes the task:
### Input:
-> a #set of random integers
### Response:
def randset(self):
""" -> a #set of random integers """
return {
self._map_type(int)
for x in range(self.random.randint(3, 10))} |
def cmd_guess_labels(*args):
"""
Arguments: <document id> [-- [--apply]]
Guess the labels that should be set on the document.
Example: paperwork-shell guess_labels -- 20161207_1144_00_8 --apply
Possible JSON replies:
--
{
"status": "error", "exception": "yyy",
... | Arguments: <document id> [-- [--apply]]
Guess the labels that should be set on the document.
Example: paperwork-shell guess_labels -- 20161207_1144_00_8 --apply
Possible JSON replies:
--
{
"status": "error", "exception": "yyy",
"reason": "xxxx", "args": "(xxxx, )"
... | Below is the the instruction that describes the task:
### Input:
Arguments: <document id> [-- [--apply]]
Guess the labels that should be set on the document.
Example: paperwork-shell guess_labels -- 20161207_1144_00_8 --apply
Possible JSON replies:
--
{
"status": "error", "... |
def simxAuxiliaryConsolePrint(clientID, consoleHandle, txt, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
if (sys.version_info[0] == 3) and (type(txt) is str):
txt=txt.encode('utf-8')
return c_AuxiliaryConsolePrint(clientID, co... | Please have a look at the function description/documentation in the V-REP user manual | Below is the the instruction that describes the task:
### Input:
Please have a look at the function description/documentation in the V-REP user manual
### Response:
def simxAuxiliaryConsolePrint(clientID, consoleHandle, txt, operationMode):
'''
Please have a look at the function description/documentation i... |
def email_address_to_list(email_address):
"""Convert an email address to a list."""
realname, address = email.utils.parseaddr(email_address)
return (
[address, realname] if realname and address else
[email_address, email_address]
) | Convert an email address to a list. | Below is the the instruction that describes the task:
### Input:
Convert an email address to a list.
### Response:
def email_address_to_list(email_address):
"""Convert an email address to a list."""
realname, address = email.utils.parseaddr(email_address)
return (
[address, realname] if realnam... |
def eval_interval(interval):
""" Evaluate an interval expression """
kwargs = {
"years": 0,
"months": 0,
"weeks": 0,
"days": 0,
"hours": 0,
"minutes": 0,
"seconds": 0,
"microseconds": 0,
}
for section in interval[1:]:
name = section... | Evaluate an interval expression | Below is the the instruction that describes the task:
### Input:
Evaluate an interval expression
### Response:
def eval_interval(interval):
""" Evaluate an interval expression """
kwargs = {
"years": 0,
"months": 0,
"weeks": 0,
"days": 0,
"hours": 0,
"minutes... |
def add_menu(self, name):
"""Add a top-level menu.
The menu manager only allows one menu of the same name. However, it does
not make sure that there are no pre-existing menus of that name.
"""
if name in self._menus:
raise exceptions.MenuAlreadyExists("Menu name {!r}... | Add a top-level menu.
The menu manager only allows one menu of the same name. However, it does
not make sure that there are no pre-existing menus of that name. | Below is the the instruction that describes the task:
### Input:
Add a top-level menu.
The menu manager only allows one menu of the same name. However, it does
not make sure that there are no pre-existing menus of that name.
### Response:
def add_menu(self, name):
"""Add a top-level menu.
... |
def form_valid(self, form):
"""
The user has provided valid credentials (this was checked in AuthenticationForm.is_valid()). So now we
can check the test cookie stuff and log him in.
"""
self.check_and_delete_test_cookie()
login(self.request, form.get_user())
retu... | The user has provided valid credentials (this was checked in AuthenticationForm.is_valid()). So now we
can check the test cookie stuff and log him in. | Below is the the instruction that describes the task:
### Input:
The user has provided valid credentials (this was checked in AuthenticationForm.is_valid()). So now we
can check the test cookie stuff and log him in.
### Response:
def form_valid(self, form):
"""
The user has provided valid c... |
def raised_funds_by_project(df):
"""
Raised funds organized by project.
"""
df['CaptacaoReal'] = df['CaptacaoReal'].apply(
pd.to_numeric
)
return (
df[['Pronac', 'CaptacaoReal']]
.groupby(['Pronac'])
.sum()
) | Raised funds organized by project. | Below is the the instruction that describes the task:
### Input:
Raised funds organized by project.
### Response:
def raised_funds_by_project(df):
"""
Raised funds organized by project.
"""
df['CaptacaoReal'] = df['CaptacaoReal'].apply(
pd.to_numeric
)
return (
df[['Pronac',... |
def on_event(self, evt, is_final):
""" this is invoked from in response to COM PumpWaitingMessages - different thread """
for msg in XmlHelper.message_iter(evt):
# Single security element in historical request
node = msg.GetElement('securityData')
if node.HasElement('... | this is invoked from in response to COM PumpWaitingMessages - different thread | Below is the the instruction that describes the task:
### Input:
this is invoked from in response to COM PumpWaitingMessages - different thread
### Response:
def on_event(self, evt, is_final):
""" this is invoked from in response to COM PumpWaitingMessages - different thread """
for msg in XmlHelpe... |
def is_stationary(self):
r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution
of the hidden transition matrix. """
# for disconnected matrices, the stationary distribution depends on the estimator, so we can't compute
# it directly. Th... | r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution
of the hidden transition matrix. | Below is the the instruction that describes the task:
### Input:
r""" Whether the MSM is stationary, i.e. whether the initial distribution is the stationary distribution
of the hidden transition matrix.
### Response:
def is_stationary(self):
r""" Whether the MSM is stationary, i.e. whether the ini... |
def start(self):
'''
Start the actual master.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
'''
super(SaltAPI, self).start()
if check_user(self.config['user']):
... | Start the actual master.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`. | Below is the the instruction that describes the task:
### Input:
Start the actual master.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
### Response:
def start(self):
'''
Start the... |
def arcovar_marple(x, order):
r"""Estimate AR model parameters using covariance method
This implementation is based on [Marple]_. This code is far more
complicated and slower than :func:`arcovar` function, which is now the official version.
See :func:`arcovar` for a detailed description of Covariance m... | r"""Estimate AR model parameters using covariance method
This implementation is based on [Marple]_. This code is far more
complicated and slower than :func:`arcovar` function, which is now the official version.
See :func:`arcovar` for a detailed description of Covariance method.
This function should b... | Below is the the instruction that describes the task:
### Input:
r"""Estimate AR model parameters using covariance method
This implementation is based on [Marple]_. This code is far more
complicated and slower than :func:`arcovar` function, which is now the official version.
See :func:`arcovar` for a d... |
def get_body_size(params, boundary):
"""Returns the number of bytes that the multipart/form-data encoding
of ``params`` will be."""
size = sum(p.get_size(boundary) for p in MultipartParam.from_params(params))
return size + len(boundary) + 6 | Returns the number of bytes that the multipart/form-data encoding
of ``params`` will be. | Below is the the instruction that describes the task:
### Input:
Returns the number of bytes that the multipart/form-data encoding
of ``params`` will be.
### Response:
def get_body_size(params, boundary):
"""Returns the number of bytes that the multipart/form-data encoding
of ``params`` will be."""
... |
def ParseOptions(cls, options, output_module):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object does not have the
SetCredentials ... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object does not have the
SetCredentials or SetDatabaseName methods. | Below is the the instruction that describes the task:
### Input:
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object does not have the
... |
def _compute_distance(self, rup, dists, C):
"""
equation 3 pag 1960:
``c31 * logR + c32 * (R-Rref)``
"""
rref = 1.0
c31 = -1.7
return (c31 * np.log10(dists.rhypo) + C['c32'] * (dists.rhypo - rref)) | equation 3 pag 1960:
``c31 * logR + c32 * (R-Rref)`` | Below is the the instruction that describes the task:
### Input:
equation 3 pag 1960:
``c31 * logR + c32 * (R-Rref)``
### Response:
def _compute_distance(self, rup, dists, C):
"""
equation 3 pag 1960:
``c31 * logR + c32 * (R-Rref)``
"""
rref = 1.0
c31 = -1.... |
def info_player_id(self,name):
'''Get id using name football player'''
number = 0
name=name.title().replace(" ", "+")
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/team_news.phtml',"User-Agent": user_agent}
... | Get id using name football player | Below is the the instruction that describes the task:
### Input:
Get id using name football player
### Response:
def info_player_id(self,name):
'''Get id using name football player'''
number = 0
name=name.title().replace(" ", "+")
headers = {"Content-type": "application/x-www-form-u... |
def fetch_access_token_by_client_credentials(self):
'''
There are three ways to let you start using KKBOX's Open/Partner
API. The first way among them is to generate a client
credential to fetch an access token to let KKBOX identify
you. It allows you to access public data from K... | There are three ways to let you start using KKBOX's Open/Partner
API. The first way among them is to generate a client
credential to fetch an access token to let KKBOX identify
you. It allows you to access public data from KKBOX such as
public albums, playlists and so on.
Howeve... | Below is the the instruction that describes the task:
### Input:
There are three ways to let you start using KKBOX's Open/Partner
API. The first way among them is to generate a client
credential to fetch an access token to let KKBOX identify
you. It allows you to access public data from KKBO... |
def service(ctx):
"""Install systemd service configuration"""
install_service(ctx.obj['instance'], ctx.obj['dbhost'], ctx.obj['dbname'], ctx.obj['port']) | Install systemd service configuration | Below is the the instruction that describes the task:
### Input:
Install systemd service configuration
### Response:
def service(ctx):
"""Install systemd service configuration"""
install_service(ctx.obj['instance'], ctx.obj['dbhost'], ctx.obj['dbname'], ctx.obj['port']) |
def _reset_em(self):
"""Resets self.em and the shared instances."""
self.em = _ExtendedManager(self.addr, self.authkey, mode=self.mode, start=False)
self.em.start()
self._set_shared_instances() | Resets self.em and the shared instances. | Below is the the instruction that describes the task:
### Input:
Resets self.em and the shared instances.
### Response:
def _reset_em(self):
"""Resets self.em and the shared instances."""
self.em = _ExtendedManager(self.addr, self.authkey, mode=self.mode, start=False)
self.em.start()
... |
def bruggeman_refractive(m, mix):
"""Bruggeman EMA for the refractive index.
For instructions, see mg_refractive in this module, except this routine
only works for two components.
"""
f1 = mix[0]/sum(mix)
f2 = mix[1]/sum(mix)
e1 = m[0]**2
e2 = m[1]**2
a = -2*(f1+f2)
b = (2*f1*e1... | Bruggeman EMA for the refractive index.
For instructions, see mg_refractive in this module, except this routine
only works for two components. | Below is the the instruction that describes the task:
### Input:
Bruggeman EMA for the refractive index.
For instructions, see mg_refractive in this module, except this routine
only works for two components.
### Response:
def bruggeman_refractive(m, mix):
"""Bruggeman EMA for the refractive index.
... |
def refreshUserMembership(self, users):
"""
This operation iterates over every enterprise group configured in
the portal and determines if the input user accounts belong to any
of the configured enterprise groups. If there is any change in
membership, the database and the indexes... | This operation iterates over every enterprise group configured in
the portal and determines if the input user accounts belong to any
of the configured enterprise groups. If there is any change in
membership, the database and the indexes are updated for each user
account. While portal aut... | Below is the the instruction that describes the task:
### Input:
This operation iterates over every enterprise group configured in
the portal and determines if the input user accounts belong to any
of the configured enterprise groups. If there is any change in
membership, the database and th... |
def _unlock(self):
"""Unlock the config DB."""
if self.locked:
try:
self.device.cu.unlock()
self.locked = False
except JnrpUnlockError as jue:
raise UnlockError(jue.messsage) | Unlock the config DB. | Below is the the instruction that describes the task:
### Input:
Unlock the config DB.
### Response:
def _unlock(self):
"""Unlock the config DB."""
if self.locked:
try:
self.device.cu.unlock()
self.locked = False
except JnrpUnlockError as jue:... |
def get_execution_details(self):
"""
Retrieves execution details for a task.
:return: Execution details instance.
"""
extra = {
'resource': self.__class__.__name__,
'query': {'id': self.id}
}
logger.info('Get execution details', extra=extra... | Retrieves execution details for a task.
:return: Execution details instance. | Below is the the instruction that describes the task:
### Input:
Retrieves execution details for a task.
:return: Execution details instance.
### Response:
def get_execution_details(self):
"""
Retrieves execution details for a task.
:return: Execution details instance.
"""
... |
def vqa_attention_base():
"""VQA attention baseline hparams."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 128
hparams.use_fixed_batch_size = True,
hparams.optimizer = "adam"
hparams.optimizer_adam_beta1 = 0.9
hparams.optimizer_adam_beta2 = 0.999
hparams.optimizer_adam_epsilon = 1e-8
... | VQA attention baseline hparams. | Below is the the instruction that describes the task:
### Input:
VQA attention baseline hparams.
### Response:
def vqa_attention_base():
"""VQA attention baseline hparams."""
hparams = common_hparams.basic_params1()
hparams.batch_size = 128
hparams.use_fixed_batch_size = True,
hparams.optimizer = "adam"
... |
def return_dat(self, chan, begsam, endsam):
"""Return the data as 2D numpy.ndarray.
Parameters
----------
chan : int or list
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last ... | Return the data as 2D numpy.ndarray.
Parameters
----------
chan : int or list
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Returns
-------
numpy.n... | Below is the the instruction that describes the task:
### Input:
Return the data as 2D numpy.ndarray.
Parameters
----------
chan : int or list
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
inde... |
def setup_requires():
"""
Return required packages
Plus any version tests and warnings
"""
from pkg_resources import parse_version
required = ['cython>=0.24.0']
numpy_requirement = 'numpy>=1.7.1'
try:
import numpy
except Exception:
required.append(numpy_requirement)... | Return required packages
Plus any version tests and warnings | Below is the the instruction that describes the task:
### Input:
Return required packages
Plus any version tests and warnings
### Response:
def setup_requires():
"""
Return required packages
Plus any version tests and warnings
"""
from pkg_resources import parse_version
required = ['c... |
def when_all_players_ready(self):
"""Initializes decisions based on ``player.initial_decision()``.
If :attr:`num_subperiods` is set, starts a timed task to run the
sub-periods.
"""
self.group_decisions = {}
self.subperiod_group_decisions = {}
for player in self.ge... | Initializes decisions based on ``player.initial_decision()``.
If :attr:`num_subperiods` is set, starts a timed task to run the
sub-periods. | Below is the the instruction that describes the task:
### Input:
Initializes decisions based on ``player.initial_decision()``.
If :attr:`num_subperiods` is set, starts a timed task to run the
sub-periods.
### Response:
def when_all_players_ready(self):
"""Initializes decisions based on ``pl... |
def _EnsureFileExists(self):
"""Touches a file; returns False on error, True on success."""
if not os.path.exists(self._filename):
old_umask = os.umask(0o177)
try:
open(self._filename, 'a+b').close()
except OSError:
return False
... | Touches a file; returns False on error, True on success. | Below is the the instruction that describes the task:
### Input:
Touches a file; returns False on error, True on success.
### Response:
def _EnsureFileExists(self):
"""Touches a file; returns False on error, True on success."""
if not os.path.exists(self._filename):
old_umask = os.umask... |
def nonzero(self):
""" property decorated method to get a new ObservationEnsemble
of only non-zero weighted observations
Returns
-------
ObservationEnsemble : ObservationEnsemble
"""
df = self.loc[:,self.pst.nnz_obs_names]
return ObservationEnsemble.from... | property decorated method to get a new ObservationEnsemble
of only non-zero weighted observations
Returns
-------
ObservationEnsemble : ObservationEnsemble | Below is the the instruction that describes the task:
### Input:
property decorated method to get a new ObservationEnsemble
of only non-zero weighted observations
Returns
-------
ObservationEnsemble : ObservationEnsemble
### Response:
def nonzero(self):
""" property decorat... |
def _generate_api_gateway_deployment(self):
"""
Generate the API Gateway Deployment/Stage, and add to self.tf_conf
"""
# finally, the deployment
# this resource MUST come last
dep_on = []
for rtype in sorted(self.tf_conf['resource'].keys()):
for rname ... | Generate the API Gateway Deployment/Stage, and add to self.tf_conf | Below is the the instruction that describes the task:
### Input:
Generate the API Gateway Deployment/Stage, and add to self.tf_conf
### Response:
def _generate_api_gateway_deployment(self):
"""
Generate the API Gateway Deployment/Stage, and add to self.tf_conf
"""
# finally, the dep... |
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in pt:
assert isinstance(i, float)
assert isinstance(shift, list)
l_sh = len(shift)
assert l_sh == l_pt
for ... | Return given point shifted in N dimensions. | Below is the the instruction that describes the task:
### Input:
Return given point shifted in N dimensions.
### Response:
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
'''Return given point shifted in N dimensions.
'''
assert isinstance(pt, tuple)
l_pt = len(pt)
assert l_pt > 1
for i in p... |
def _freeze(self, final_text, err=False):
"""Stop spinner, compose last frame and 'freeze' it."""
if not final_text:
final_text = ""
target = self.stderr if err else self.stdout
if target.closed:
target = sys.stderr if err else sys.stdout
text = to_text(fi... | Stop spinner, compose last frame and 'freeze' it. | Below is the the instruction that describes the task:
### Input:
Stop spinner, compose last frame and 'freeze' it.
### Response:
def _freeze(self, final_text, err=False):
"""Stop spinner, compose last frame and 'freeze' it."""
if not final_text:
final_text = ""
target = self.std... |
def entry_index(request, limit=0, template='djournal/entry_index.html'):
'''Returns a reponse of a fixed number of entries; all of them, by default. '''
entries = Entry.public.all()
if limit > 0:
entries = entries[:limit]
context = {
'entries': entries,
}
return render_to_res... | Returns a reponse of a fixed number of entries; all of them, by default. | Below is the the instruction that describes the task:
### Input:
Returns a reponse of a fixed number of entries; all of them, by default.
### Response:
def entry_index(request, limit=0, template='djournal/entry_index.html'):
'''Returns a reponse of a fixed number of entries; all of them, by default. '''
e... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'emotion') and self.emotion is not None:
_dict['emotion'] = self.emotion._to_dict()
return _dict | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'emotion') and self.emotion is not None:
_dict... |
def get_matrix_from_list(self, rows, columns, matrix_list, rowBased=True):
"""Create a new Matrix instance from a matrix_list.
:note: This method is used to create a Matrix instance using cpython.
:param integer rows: The height of the Matrix.
:param integer columns: The widt... | Create a new Matrix instance from a matrix_list.
:note: This method is used to create a Matrix instance using cpython.
:param integer rows: The height of the Matrix.
:param integer columns: The width of the Matrix.
:param matrix_list: A one dimensional list containing... | Below is the the instruction that describes the task:
### Input:
Create a new Matrix instance from a matrix_list.
:note: This method is used to create a Matrix instance using cpython.
:param integer rows: The height of the Matrix.
:param integer columns: The width of the Matrix.
... |
def _add_ps2q(self, throat, queue):
"""
Helper method to add pores to the cluster queue
"""
net = self.project.network
elem_type = 'pore'
# Find pores connected to newly invaded throat
Ps = net['throat.conns'][throat]
# Remove already invaded pores from Ps... | Helper method to add pores to the cluster queue | Below is the the instruction that describes the task:
### Input:
Helper method to add pores to the cluster queue
### Response:
def _add_ps2q(self, throat, queue):
"""
Helper method to add pores to the cluster queue
"""
net = self.project.network
elem_type = 'pore'
# ... |
def container_fs_usage_bytes(self, metric, scraper_config):
"""
Number of bytes that are consumed by the container on this filesystem.
"""
metric_name = scraper_config['namespace'] + '.filesystem.usage'
if metric.type not in METRIC_TYPES:
self.log.error("Metric type %... | Number of bytes that are consumed by the container on this filesystem. | Below is the the instruction that describes the task:
### Input:
Number of bytes that are consumed by the container on this filesystem.
### Response:
def container_fs_usage_bytes(self, metric, scraper_config):
"""
Number of bytes that are consumed by the container on this filesystem.
"""
... |
def find_train_knns(self, data_activations):
"""
Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data.
"""
knns_ind = {}
knns_labels = {}
for layer in self.layers:
# Pre-process representations of data to norma... | Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data. | Below is the the instruction that describes the task:
### Input:
Given a data_activation dictionary that contains a np array with activations for each layer,
find the knns in the training data.
### Response:
def find_train_knns(self, data_activations):
"""
Given a data_activation dictionary that contai... |
def generate_proto(source, require = True):
"""Invokes the Protocol Compiler to generate a _pb2.py from the given
.proto file. Does nothing if the output already exists and is newer than
the input."""
if not require and not os.path.exists(source):
return
output = source.replace(".proto", "_pb2.py").rep... | Invokes the Protocol Compiler to generate a _pb2.py from the given
.proto file. Does nothing if the output already exists and is newer than
the input. | Below is the the instruction that describes the task:
### Input:
Invokes the Protocol Compiler to generate a _pb2.py from the given
.proto file. Does nothing if the output already exists and is newer than
the input.
### Response:
def generate_proto(source, require = True):
"""Invokes the Protocol Compiler t... |
def enrich_citation_model(manager, citation, p) -> bool:
"""Enrich a citation model with the information from PubMed.
:param pybel.manager.Manager manager:
:param Citation citation: A citation model
:param dict p: The dictionary from PubMed E-Utils corresponding to d["result"][pmid]
"""
if 'err... | Enrich a citation model with the information from PubMed.
:param pybel.manager.Manager manager:
:param Citation citation: A citation model
:param dict p: The dictionary from PubMed E-Utils corresponding to d["result"][pmid] | Below is the the instruction that describes the task:
### Input:
Enrich a citation model with the information from PubMed.
:param pybel.manager.Manager manager:
:param Citation citation: A citation model
:param dict p: The dictionary from PubMed E-Utils corresponding to d["result"][pmid]
### Response: ... |
def remove_system(self, system):
'''
Removes system from world and kills system
'''
if system in self._systems:
self._systems.remove(system)
else:
raise UnmanagedSystemError(system) | Removes system from world and kills system | Below is the the instruction that describes the task:
### Input:
Removes system from world and kills system
### Response:
def remove_system(self, system):
'''
Removes system from world and kills system
'''
if system in self._systems:
self._systems.remove(system)
... |
def _readline_echo(self, char, echo):
"""Echo a recieved character, move cursor etc..."""
if self._readline_do_echo(echo):
self.write(char) | Echo a recieved character, move cursor etc... | Below is the the instruction that describes the task:
### Input:
Echo a recieved character, move cursor etc...
### Response:
def _readline_echo(self, char, echo):
"""Echo a recieved character, move cursor etc..."""
if self._readline_do_echo(echo):
self.write(char) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.