code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def login(self):
"""Set http session."""
if self._session is None:
self._session = requests.session()
# adding fake user-agent header
self._session.headers.update({'User-agent': str(UserAgent().random)})
return self._post_login_page() | Set http session. | Below is the the instruction that describes the task:
### Input:
Set http session.
### Response:
def login(self):
"""Set http session."""
if self._session is None:
self._session = requests.session()
# adding fake user-agent header
self._session.headers.update({'U... |
def get_version():
""" str: The package version. """
global_vars = {}
# Compile and execute the individual file to prevent
# the package from being automatically loaded.
source = read(os.path.join("capybara", "version.py"))
code = compile(source, "version.py", "exec")
exec(code, global_var... | str: The package version. | Below is the the instruction that describes the task:
### Input:
str: The package version.
### Response:
def get_version():
""" str: The package version. """
global_vars = {}
# Compile and execute the individual file to prevent
# the package from being automatically loaded.
source = read(os.p... |
def unique_field(self, field_name):
"""set a unique field to be selected, this is automatically called when you do unique_FIELDNAME(...)"""
self.fields_set.options["unique"] = True
return self.select_field(field_name) | set a unique field to be selected, this is automatically called when you do unique_FIELDNAME(...) | Below is the the instruction that describes the task:
### Input:
set a unique field to be selected, this is automatically called when you do unique_FIELDNAME(...)
### Response:
def unique_field(self, field_name):
"""set a unique field to be selected, this is automatically called when you do unique_FIELDNAM... |
def _prepare_for_submission(self,tempfolder, inputdict):
"""
This is the routine to be called when you want to create
the input files and related stuff with a plugin.
:param tempfolder: a aiida.common.folders.Folder subclass where
the plugin sh... | This is the routine to be called when you want to create
the input files and related stuff with a plugin.
:param tempfolder: a aiida.common.folders.Folder subclass where
the plugin should put all its files.
:param inputdict: a dictionary with the input nodes, ... | Below is the the instruction that describes the task:
### Input:
This is the routine to be called when you want to create
the input files and related stuff with a plugin.
:param tempfolder: a aiida.common.folders.Folder subclass where
the plugin should put all its... |
def _router_request(router, method, data=None):
'''
Make a request to the Zenoss API router
'''
if router not in ROUTERS:
return False
req_data = salt.utils.json.dumps([dict(
action=router,
method=method,
data=data,
type='rpc',
tid=1)])
config = ... | Make a request to the Zenoss API router | Below is the the instruction that describes the task:
### Input:
Make a request to the Zenoss API router
### Response:
def _router_request(router, method, data=None):
'''
Make a request to the Zenoss API router
'''
if router not in ROUTERS:
return False
req_data = salt.utils.json.dumps... |
def _node_to_model(tree_or_item, metadata=None, parent=None,
lucent_id=cnxepub.TRANSLUCENT_BINDER_ID):
"""Given a tree, parse to a set of models"""
if 'contents' in tree_or_item:
# It is a binder.
tree = tree_or_item
binder = cnxepub.TranslucentBinder(metadata=tree)
... | Given a tree, parse to a set of models | Below is the the instruction that describes the task:
### Input:
Given a tree, parse to a set of models
### Response:
def _node_to_model(tree_or_item, metadata=None, parent=None,
lucent_id=cnxepub.TRANSLUCENT_BINDER_ID):
"""Given a tree, parse to a set of models"""
if 'contents' in tree_... |
def get_referenced_object_as_list(
prev_obj, obj, dot_separated_name, desired_type=None):
"""
Same as get_referenced_object, but always returns a list.
Args:
prev_obj: see get_referenced_object
obj: see get_referenced_object
dot_separated_name: see get_referenced_object
... | Same as get_referenced_object, but always returns a list.
Args:
prev_obj: see get_referenced_object
obj: see get_referenced_object
dot_separated_name: see get_referenced_object
desired_type: see get_referenced_object
Returns:
same as get_referenced_object, but always re... | Below is the the instruction that describes the task:
### Input:
Same as get_referenced_object, but always returns a list.
Args:
prev_obj: see get_referenced_object
obj: see get_referenced_object
dot_separated_name: see get_referenced_object
desired_type: see get_referenced_obje... |
def list_available_solvers():
"""Determine available solver interfaces (with python bindings).
Returns
-------
dict
A dict like {'GLPK': True, 'GUROBI': False, ...}
"""
solvers = dict(GUROBI=False, GLPK=False, MOSEK=False, CPLEX=False, SCIPY=False)
try:
import gurobipy
... | Determine available solver interfaces (with python bindings).
Returns
-------
dict
A dict like {'GLPK': True, 'GUROBI': False, ...} | Below is the the instruction that describes the task:
### Input:
Determine available solver interfaces (with python bindings).
Returns
-------
dict
A dict like {'GLPK': True, 'GUROBI': False, ...}
### Response:
def list_available_solvers():
"""Determine available solver interfaces (with py... |
def cee_map_priority_table_map_cos0_pgid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name_key = ET.SubElement(cee_map, "name")
name_key.text = kwargs.pop... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def cee_map_priority_table_map_cos0_pgid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgm... |
def _validate_param(rtype, fields):
""" Ensure the sparse fields exists on the models """
try:
# raises ValueError if not found
model = rtype_to_model(rtype)
model_fields = model.all_fields
except ValueError:
raise InvalidQueryParams(**{
'detail': 'The fields que... | Ensure the sparse fields exists on the models | Below is the the instruction that describes the task:
### Input:
Ensure the sparse fields exists on the models
### Response:
def _validate_param(rtype, fields):
""" Ensure the sparse fields exists on the models """
try:
# raises ValueError if not found
model = rtype_to_model(rtype)
... |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(Upd... | Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
### Response:
def fi... |
def _ssh_channel_read(ssh_channel_int, count, is_stderr):
"""Do a read on a channel."""
buffer_ = create_string_buffer(count)
while 1:
received_bytes = c_ssh_channel_read(ssh_channel_int,
cast(buffer_, c_void_p),
... | Do a read on a channel. | Below is the the instruction that describes the task:
### Input:
Do a read on a channel.
### Response:
def _ssh_channel_read(ssh_channel_int, count, is_stderr):
"""Do a read on a channel."""
buffer_ = create_string_buffer(count)
while 1:
received_bytes = c_ssh_channel_read(ssh_channel_int,
... |
def save_reg(data):
'''
Save the register to msgpack files
'''
reg_dir = _reg_dir()
regfile = os.path.join(reg_dir, 'register')
try:
if not os.path.exists(reg_dir):
os.makedirs(reg_dir)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
... | Save the register to msgpack files | Below is the the instruction that describes the task:
### Input:
Save the register to msgpack files
### Response:
def save_reg(data):
'''
Save the register to msgpack files
'''
reg_dir = _reg_dir()
regfile = os.path.join(reg_dir, 'register')
try:
if not os.path.exists(reg_dir):
... |
def fromString(cls, string):
"""
Convert a serialized Unicode string to a L{TaskLevel}.
@param string: Output of L{TaskLevel.toString}.
@return: L{TaskLevel} parsed from the string.
"""
return cls(level=[int(i) for i in string.split("/") if i]) | Convert a serialized Unicode string to a L{TaskLevel}.
@param string: Output of L{TaskLevel.toString}.
@return: L{TaskLevel} parsed from the string. | Below is the the instruction that describes the task:
### Input:
Convert a serialized Unicode string to a L{TaskLevel}.
@param string: Output of L{TaskLevel.toString}.
@return: L{TaskLevel} parsed from the string.
### Response:
def fromString(cls, string):
"""
Convert a serialized... |
def set_simulate(self, status):
"""Set the simulation status.
:param status: Value to set the simulation
:type status: bool
:returns: None
:raises: InvalidInput
"""
if type(status) != bool:
raise InvalidInput("Status value must be bool")
self.... | Set the simulation status.
:param status: Value to set the simulation
:type status: bool
:returns: None
:raises: InvalidInput | Below is the the instruction that describes the task:
### Input:
Set the simulation status.
:param status: Value to set the simulation
:type status: bool
:returns: None
:raises: InvalidInput
### Response:
def set_simulate(self, status):
"""Set the simulation status.
... |
def transactional_async(func, args, kwds, **options):
"""The async version of @ndb.transaction."""
options.setdefault('propagation', datastore_rpc.TransactionOptions.ALLOWED)
if args or kwds:
return transaction_async(lambda: func(*args, **kwds), **options)
return transaction_async(func, **options) | The async version of @ndb.transaction. | Below is the the instruction that describes the task:
### Input:
The async version of @ndb.transaction.
### Response:
def transactional_async(func, args, kwds, **options):
"""The async version of @ndb.transaction."""
options.setdefault('propagation', datastore_rpc.TransactionOptions.ALLOWED)
if args or kwds:... |
def _print_errs(self):
"""
Prints the errors trace with tracebacks
"""
i = 0
for error in self.errors:
print(self._errmsg(error, tb=True, i=i))
# for spacing
if self.errs_traceback is False:
print()
i += 1 | Prints the errors trace with tracebacks | Below is the the instruction that describes the task:
### Input:
Prints the errors trace with tracebacks
### Response:
def _print_errs(self):
"""
Prints the errors trace with tracebacks
"""
i = 0
for error in self.errors:
print(self._errmsg(error, tb=True, i=i))
... |
def _add_file(self, tar, name, contents, mode=DEFAULT_FILE_MODE):
"""
Adds a single file in tarfile instance.
:param tar: tarfile instance
:param name: string representing filename or path
:param contents: string representing file contents
:param mode: string representin... | Adds a single file in tarfile instance.
:param tar: tarfile instance
:param name: string representing filename or path
:param contents: string representing file contents
:param mode: string representing file mode, defaults to 644
:returns: None | Below is the the instruction that describes the task:
### Input:
Adds a single file in tarfile instance.
:param tar: tarfile instance
:param name: string representing filename or path
:param contents: string representing file contents
:param mode: string representing file mode, defa... |
def parent(self):
"""Return the parent of the name.
@rtype: dns.name.Name object
@raises NoParent: the name is either the root name or the empty name,
and thus has no parent.
"""
if self == root or self == empty:
raise NoParent
return Name(self.labels[... | Return the parent of the name.
@rtype: dns.name.Name object
@raises NoParent: the name is either the root name or the empty name,
and thus has no parent. | Below is the the instruction that describes the task:
### Input:
Return the parent of the name.
@rtype: dns.name.Name object
@raises NoParent: the name is either the root name or the empty name,
and thus has no parent.
### Response:
def parent(self):
"""Return the parent of the name... |
def _log_deprecation(self, deprecation_key):
"""
Logs a deprecation notice at most once per AgentCheck instance, for the pre-defined `deprecation_key`
"""
if not self._deprecations[deprecation_key][0]:
self.log.warning(self._deprecations[deprecation_key][1])
self.... | Logs a deprecation notice at most once per AgentCheck instance, for the pre-defined `deprecation_key` | Below is the the instruction that describes the task:
### Input:
Logs a deprecation notice at most once per AgentCheck instance, for the pre-defined `deprecation_key`
### Response:
def _log_deprecation(self, deprecation_key):
"""
Logs a deprecation notice at most once per AgentCheck instance, for t... |
def unescape(s, unicode_action="replace"):
"""
Unescape HTML strings, and convert & etc.
"""
import HTMLParser
hp = HTMLParser.HTMLParser()
s = hp.unescape(s)
s = s.encode('ascii', unicode_action)
s = s.replace("\n", "").strip()
return s | Unescape HTML strings, and convert & etc. | Below is the the instruction that describes the task:
### Input:
Unescape HTML strings, and convert & etc.
### Response:
def unescape(s, unicode_action="replace"):
"""
Unescape HTML strings, and convert & etc.
"""
import HTMLParser
hp = HTMLParser.HTMLParser()
s = hp.unescape(s)
... |
def typing(self, room: Room, timeout: int = 5000):
"""
Send typing event directly to api
Args:
room: room to send typing event to
timeout: timeout for the event, in ms
"""
path = f'/rooms/{quote(room.room_id)}/typing/{quote(self.user_id)}'
return ... | Send typing event directly to api
Args:
room: room to send typing event to
timeout: timeout for the event, in ms | Below is the the instruction that describes the task:
### Input:
Send typing event directly to api
Args:
room: room to send typing event to
timeout: timeout for the event, in ms
### Response:
def typing(self, room: Room, timeout: int = 5000):
"""
Send typing event d... |
def ignore_missing_email_protection_eku_cb(ok, ctx):
"""
For verifying PKCS7 signature, m2Crypto uses OpenSSL's PKCS7_verify().
The latter requires that ExtendedKeyUsage extension, if present,
contains 'emailProtection' OID. (Is it because S/MIME is/was the
primary use case for PKCS7?)
We do not... | For verifying PKCS7 signature, m2Crypto uses OpenSSL's PKCS7_verify().
The latter requires that ExtendedKeyUsage extension, if present,
contains 'emailProtection' OID. (Is it because S/MIME is/was the
primary use case for PKCS7?)
We do not want to fail the verification in this case. At present,
M2Cr... | Below is the the instruction that describes the task:
### Input:
For verifying PKCS7 signature, m2Crypto uses OpenSSL's PKCS7_verify().
The latter requires that ExtendedKeyUsage extension, if present,
contains 'emailProtection' OID. (Is it because S/MIME is/was the
primary use case for PKCS7?)
We do... |
def hash(self):
"""Return an hash string computed on the PSF data."""
hash_list = []
for key, value in sorted(self.__dict__.items()):
if not callable(value):
if isinstance(value, np.ndarray):
hash_list.append(value.tostring())
else:... | Return an hash string computed on the PSF data. | Below is the the instruction that describes the task:
### Input:
Return an hash string computed on the PSF data.
### Response:
def hash(self):
"""Return an hash string computed on the PSF data."""
hash_list = []
for key, value in sorted(self.__dict__.items()):
if not callable(va... |
def account(self, url):
"""
Return accounts references for the given account id.
:param account_id:
:param accounts_password: The password for decrypting the secret
:return:
"""
from sqlalchemy.orm.exc import NoResultFound
from ambry.orm.exc import NotFoun... | Return accounts references for the given account id.
:param account_id:
:param accounts_password: The password for decrypting the secret
:return: | Below is the the instruction that describes the task:
### Input:
Return accounts references for the given account id.
:param account_id:
:param accounts_password: The password for decrypting the secret
:return:
### Response:
def account(self, url):
"""
Return accounts refere... |
def store_sample_set(self, md5_list):
""" Store a sample set (which is just a list of md5s).
Note: All md5s must already be in the data store.
Args:
md5_list: a list of the md5s in this set (all must exist in data store)
Returns:
The md5 of ... | Store a sample set (which is just a list of md5s).
Note: All md5s must already be in the data store.
Args:
md5_list: a list of the md5s in this set (all must exist in data store)
Returns:
The md5 of the set (the actual md5 of the set) | Below is the the instruction that describes the task:
### Input:
Store a sample set (which is just a list of md5s).
Note: All md5s must already be in the data store.
Args:
md5_list: a list of the md5s in this set (all must exist in data store)
Returns:
... |
def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None):
"""Generate a new JWT token for this user_id. Default expiration date
is 1 year from creation time"""
assert user_id, "No user_id passed to generate_token()"
assert isinstance(data, dict), "generate_token(data=) should be a dic... | Generate a new JWT token for this user_id. Default expiration date
is 1 year from creation time | Below is the the instruction that describes the task:
### Input:
Generate a new JWT token for this user_id. Default expiration date
is 1 year from creation time
### Response:
def generate_token(user_id, expire_in=None, data={}, issuer=None, iat=None):
"""Generate a new JWT token for this user_id. Default e... |
def currentProfile(self):
"""
Returns the currently selected profile from the system.
:return <XViewProfile>
"""
index = self._profileCombo.currentIndex()
if 0 <= index and index < len(self._profiles):
return self._profiles[index]
... | Returns the currently selected profile from the system.
:return <XViewProfile> | Below is the the instruction that describes the task:
### Input:
Returns the currently selected profile from the system.
:return <XViewProfile>
### Response:
def currentProfile(self):
"""
Returns the currently selected profile from the system.
:return <XVie... |
def get_settings(self, site=None, role=None):
"""
Retrieves the Django settings dictionary.
"""
r = self.local_renderer
_stdout = sys.stdout
_stderr = sys.stderr
if not self.verbose:
sys.stdout = StringIO()
sys.stderr = StringIO()
t... | Retrieves the Django settings dictionary. | Below is the the instruction that describes the task:
### Input:
Retrieves the Django settings dictionary.
### Response:
def get_settings(self, site=None, role=None):
"""
Retrieves the Django settings dictionary.
"""
r = self.local_renderer
_stdout = sys.stdout
_stde... |
def printSegmentUpdates(self):
"""
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.printSegmentUpdates`.
"""
# TODO: need to add C++ accessors to implement this method
assert False
print "=== SEGMENT UPDATES ===, Num = ", len(self.segmentUpdates)
for key, updateList in self.... | Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.printSegmentUpdates`. | Below is the the instruction that describes the task:
### Input:
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.printSegmentUpdates`.
### Response:
def printSegmentUpdates(self):
"""
Overrides :meth:`nupic.algorithms.backtracking_tm.BacktrackingTM.printSegmentUpdates`.
"""
# TODO:... |
def print_profile(function):
'''
Decorator that prints memory and runtime information at each call of the function
'''
import memory_profiler
def wrapper(*args,**kwargs):
m=StringIO()
pr=cProfile.Profile()
pr.enable()
temp_func = memory_profiler.profile(func=function,... | Decorator that prints memory and runtime information at each call of the function | Below is the the instruction that describes the task:
### Input:
Decorator that prints memory and runtime information at each call of the function
### Response:
def print_profile(function):
'''
Decorator that prints memory and runtime information at each call of the function
'''
import memory_profi... |
def assign_from_subscribed(self, assignments):
"""Update the assignment to the specified partitions
This method is called by the coordinator to dynamically assign
partitions based on the consumer's topic subscription. This is different
from assign_from_user() which directly sets the ass... | Update the assignment to the specified partitions
This method is called by the coordinator to dynamically assign
partitions based on the consumer's topic subscription. This is different
from assign_from_user() which directly sets the assignment from a
user-supplied TopicPartition list.
... | Below is the the instruction that describes the task:
### Input:
Update the assignment to the specified partitions
This method is called by the coordinator to dynamically assign
partitions based on the consumer's topic subscription. This is different
from assign_from_user() which directly s... |
def index(self, row, col, parent=QtCore.QModelIndex()):
"""Creates an index. An item must exist for the given *row*
and *col*
:returns: :qtdoc:`QModelIndex`
"""
if row < self._stim.rowCount() and col < self._stim.columnCountForRow(row):
component = self._stim.compo... | Creates an index. An item must exist for the given *row*
and *col*
:returns: :qtdoc:`QModelIndex` | Below is the the instruction that describes the task:
### Input:
Creates an index. An item must exist for the given *row*
and *col*
:returns: :qtdoc:`QModelIndex`
### Response:
def index(self, row, col, parent=QtCore.QModelIndex()):
"""Creates an index. An item must exist for the given *r... |
def smart_search_vrf(self):
""" Perform a smart VRF search.
The "smart" search function tries extract a query from
a text string. This query is then passed to the search_vrf
function, which performs the search.
"""
search_options = {}
extra_query = N... | Perform a smart VRF search.
The "smart" search function tries extract a query from
a text string. This query is then passed to the search_vrf
function, which performs the search. | Below is the the instruction that describes the task:
### Input:
Perform a smart VRF search.
The "smart" search function tries extract a query from
a text string. This query is then passed to the search_vrf
function, which performs the search.
### Response:
def smart_search_vrf... |
def serveWeek(self, request, year=None, week=None):
"""Weekly calendar view."""
myurl = self.get_url(request)
def myUrl(urlYear, urlWeek):
if (urlYear < 1900 or
urlYear > 2099 or
urlYear == 2099 and urlWeek == 53):
return None
... | Weekly calendar view. | Below is the the instruction that describes the task:
### Input:
Weekly calendar view.
### Response:
def serveWeek(self, request, year=None, week=None):
"""Weekly calendar view."""
myurl = self.get_url(request)
def myUrl(urlYear, urlWeek):
if (urlYear < 1900 or
u... |
def _construct_as_path_attr(self, as_path_attr, as4_path_attr):
"""Marge AS_PATH and AS4_PATH attribute instances into
a single AS_PATH instance."""
def _listify(li):
"""Reconstruct AS_PATH list.
Example::
>>> _listify([[1, 2, 3], {4, 5}, [6, 7]])
... | Marge AS_PATH and AS4_PATH attribute instances into
a single AS_PATH instance. | Below is the the instruction that describes the task:
### Input:
Marge AS_PATH and AS4_PATH attribute instances into
a single AS_PATH instance.
### Response:
def _construct_as_path_attr(self, as_path_attr, as4_path_attr):
"""Marge AS_PATH and AS4_PATH attribute instances into
a single AS_PA... |
def encode(self, *values):
"""Builds a hash from the passed `values`.
:param values The values to transform into a hashid
>>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456')
>>> hashids.encode(1, 23, 456)
'1d6216i30h53elk3'
"""
if not (values and ... | Builds a hash from the passed `values`.
:param values The values to transform into a hashid
>>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456')
>>> hashids.encode(1, 23, 456)
'1d6216i30h53elk3' | Below is the the instruction that describes the task:
### Input:
Builds a hash from the passed `values`.
:param values The values to transform into a hashid
>>> hashids = Hashids('arbitrary salt', 16, 'abcdefghijkl0123456')
>>> hashids.encode(1, 23, 456)
'1d6216i30h53elk3'
### Resp... |
def epcr_report(self):
"""
Create a report of the ePCR-calculated toxin profiles
"""
logging.info('Creating {at} report'.format(at=self.analysistype))
with open(os.path.join(self.reportpath, '{at}.csv'.format(at=self.analysistype)), 'w') as report:
data = 'Strain,Toxi... | Create a report of the ePCR-calculated toxin profiles | Below is the the instruction that describes the task:
### Input:
Create a report of the ePCR-calculated toxin profiles
### Response:
def epcr_report(self):
"""
Create a report of the ePCR-calculated toxin profiles
"""
logging.info('Creating {at} report'.format(at=self.analysistype))... |
def find_by_uuid(self, uuid):
"""Find an entry by uuid.
:raise: EntryNotFoundError
"""
for entry in self.entries:
if entry.uuid == uuid:
return entry
raise EntryNotFoundError("Entry not found for uuid: %s" % uuid) | Find an entry by uuid.
:raise: EntryNotFoundError | Below is the the instruction that describes the task:
### Input:
Find an entry by uuid.
:raise: EntryNotFoundError
### Response:
def find_by_uuid(self, uuid):
"""Find an entry by uuid.
:raise: EntryNotFoundError
"""
for entry in self.entries:
if entry.uuid == u... |
def createLoadableModuleBuilder(env):
"""This is a utility function that creates the LoadableModule
Builder in an Environment if it is not there already.
If it is already there, we return the existing one.
"""
try:
ld_module = env['BUILDERS']['LoadableModule']
except KeyError:
... | This is a utility function that creates the LoadableModule
Builder in an Environment if it is not there already.
If it is already there, we return the existing one. | Below is the the instruction that describes the task:
### Input:
This is a utility function that creates the LoadableModule
Builder in an Environment if it is not there already.
If it is already there, we return the existing one.
### Response:
def createLoadableModuleBuilder(env):
"""This is a utility... |
def validate_unit(input_unit):
"""Validate unit.
To be compatible with existing SYNPHOT data files:
* 'angstroms' and 'inversemicrons' are accepted although
unrecognized by astropy units
* 'transmission', 'extinction', and 'emissivity' are
converted to astropy dimensionless... | Validate unit.
To be compatible with existing SYNPHOT data files:
* 'angstroms' and 'inversemicrons' are accepted although
unrecognized by astropy units
* 'transmission', 'extinction', and 'emissivity' are
converted to astropy dimensionless unit
Parameters
----------
... | Below is the the instruction that describes the task:
### Input:
Validate unit.
To be compatible with existing SYNPHOT data files:
* 'angstroms' and 'inversemicrons' are accepted although
unrecognized by astropy units
* 'transmission', 'extinction', and 'emissivity' are
con... |
def get(self, url, params=None, **kwargs):
""" Shorthand for self.oauth_request(url, 'get')
:param str url: url to send get oauth request to
:param dict params: request parameter to get the service data
:param kwargs: extra params to send to request api
:return: Response of the ... | Shorthand for self.oauth_request(url, 'get')
:param str url: url to send get oauth request to
:param dict params: request parameter to get the service data
:param kwargs: extra params to send to request api
:return: Response of the request
:rtype: requests.Response | Below is the the instruction that describes the task:
### Input:
Shorthand for self.oauth_request(url, 'get')
:param str url: url to send get oauth request to
:param dict params: request parameter to get the service data
:param kwargs: extra params to send to request api
:return: Re... |
def temporal_network(gtfs,
start_time_ut=None,
end_time_ut=None,
route_type=None):
"""
Compute the temporal network of the data, and return it as a pandas.DataFrame
Parameters
----------
gtfs : gtfspy.GTFS
start_time_ut: int | None
... | Compute the temporal network of the data, and return it as a pandas.DataFrame
Parameters
----------
gtfs : gtfspy.GTFS
start_time_ut: int | None
start time of the time span (in unix time)
end_time_ut: int | None
end time of the time span (in unix time)
route_type: int | None
... | Below is the the instruction that describes the task:
### Input:
Compute the temporal network of the data, and return it as a pandas.DataFrame
Parameters
----------
gtfs : gtfspy.GTFS
start_time_ut: int | None
start time of the time span (in unix time)
end_time_ut: int | None
en... |
def binom(n, k):
"""
Returns binomial coefficient (n choose k).
"""
# http://blog.plover.com/math/choose.html
if k > n:
return 0
if k == 0:
return 1
result = 1
for denom in range(1, k + 1):
result *= n
result /= denom
n -= 1
return result | Returns binomial coefficient (n choose k). | Below is the the instruction that describes the task:
### Input:
Returns binomial coefficient (n choose k).
### Response:
def binom(n, k):
"""
Returns binomial coefficient (n choose k).
"""
# http://blog.plover.com/math/choose.html
if k > n:
return 0
if k == 0:
return 1
... |
def from_inches(value, units):
"""
Convert value in inches to given units
Parameters
----------
value : float
Value to be converted
units : str
Units to convert value to. Must be one of
`['in', 'cm', 'mm']`.
"""
lookup = {'in': lambda x: x,
'cm': la... | Convert value in inches to given units
Parameters
----------
value : float
Value to be converted
units : str
Units to convert value to. Must be one of
`['in', 'cm', 'mm']`. | Below is the the instruction that describes the task:
### Input:
Convert value in inches to given units
Parameters
----------
value : float
Value to be converted
units : str
Units to convert value to. Must be one of
`['in', 'cm', 'mm']`.
### Response:
def from_inches(value,... |
def average_patterson_d(aca, acb, acc, acd, blen):
"""Estimate D(A, B; C, D) and standard error using the block-jackknife.
Parameters
----------
aca : array_like, int, shape (n_variants, 2),
Allele counts for population A.
acb : array_like, int, shape (n_variants, 2)
Allele counts f... | Estimate D(A, B; C, D) and standard error using the block-jackknife.
Parameters
----------
aca : array_like, int, shape (n_variants, 2),
Allele counts for population A.
acb : array_like, int, shape (n_variants, 2)
Allele counts for population B.
acc : array_like, int, shape (n_varia... | Below is the the instruction that describes the task:
### Input:
Estimate D(A, B; C, D) and standard error using the block-jackknife.
Parameters
----------
aca : array_like, int, shape (n_variants, 2),
Allele counts for population A.
acb : array_like, int, shape (n_variants, 2)
Alle... |
def CheckLanguage(filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error):
"""Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
... | Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum:... | Below is the the instruction that describes the task:
### Input:
Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
cl... |
def update_properties(self, properties):
"""
Update writeable properties of this NIC.
Authorization requirements:
* Object-access permission to the Partition containing this NIC.
* Object-access permission to the backing Adapter for this NIC.
* Task permission to the "P... | Update writeable properties of this NIC.
Authorization requirements:
* Object-access permission to the Partition containing this NIC.
* Object-access permission to the backing Adapter for this NIC.
* Task permission to the "Partition Details" task.
Parameters:
prope... | Below is the the instruction that describes the task:
### Input:
Update writeable properties of this NIC.
Authorization requirements:
* Object-access permission to the Partition containing this NIC.
* Object-access permission to the backing Adapter for this NIC.
* Task permission t... |
def estimation_required(func, *args, **kw):
"""
Decorator checking the self._estimated flag in an Estimator instance, raising a value error if the decorated
function is called before estimator.estimate() has been called.
If mixed with a property-annotation, this annotation needs to come first in the ch... | Decorator checking the self._estimated flag in an Estimator instance, raising a value error if the decorated
function is called before estimator.estimate() has been called.
If mixed with a property-annotation, this annotation needs to come first in the chain of function calls, i.e.,
@property
@estimat... | Below is the the instruction that describes the task:
### Input:
Decorator checking the self._estimated flag in an Estimator instance, raising a value error if the decorated
function is called before estimator.estimate() has been called.
If mixed with a property-annotation, this annotation needs to come fi... |
def total_energy_matrix(self):
"""
The total energy matrix. Each matrix element (i, j) corresponds to the
total interaction energy between site i and site j.
Note that this does not include the charged-cell energy, which is only important
when the simulation cell is not charge b... | The total energy matrix. Each matrix element (i, j) corresponds to the
total interaction energy between site i and site j.
Note that this does not include the charged-cell energy, which is only important
when the simulation cell is not charge balanced. | Below is the the instruction that describes the task:
### Input:
The total energy matrix. Each matrix element (i, j) corresponds to the
total interaction energy between site i and site j.
Note that this does not include the charged-cell energy, which is only important
when the simulation ce... |
def reward(self,
state: Sequence[tf.Tensor],
action: Sequence[tf.Tensor],
next_state: Sequence[tf.Tensor]) -> tf.Tensor:
'''Compiles the reward function given the current `state`, `action` and
`next_state`.
Args:
state (Sequence[tf.Tensor... | Compiles the reward function given the current `state`, `action` and
`next_state`.
Args:
state (Sequence[tf.Tensor]): A tuple of current state tensors.
action (Sequence[tf.Tensor]): A tuple of action tensors.
next_state (Sequence[tf.Tensor]): A tuple of next state te... | Below is the the instruction that describes the task:
### Input:
Compiles the reward function given the current `state`, `action` and
`next_state`.
Args:
state (Sequence[tf.Tensor]): A tuple of current state tensors.
action (Sequence[tf.Tensor]): A tuple of action tensors.
... |
def detach(gandi, resource, background, force):
"""Detach an ip from it's currently attached vm.
resource can be an ip id or ip.
"""
if not force:
proceed = click.confirm('Are you sure you want to detach ip %s?' %
resource)
if not proceed:
ret... | Detach an ip from it's currently attached vm.
resource can be an ip id or ip. | Below is the the instruction that describes the task:
### Input:
Detach an ip from it's currently attached vm.
resource can be an ip id or ip.
### Response:
def detach(gandi, resource, background, force):
"""Detach an ip from it's currently attached vm.
resource can be an ip id or ip.
"""
if ... |
def denoise_grid(self, val, expand=1):
"""
for every cell in the grid of 'val' fill all cells
around it to de noise the grid
"""
updated_grid = [[self.grd.get_tile(y,x) \
for x in range(self.grd.grid_width)] \
for y in rang... | for every cell in the grid of 'val' fill all cells
around it to de noise the grid | Below is the the instruction that describes the task:
### Input:
for every cell in the grid of 'val' fill all cells
around it to de noise the grid
### Response:
def denoise_grid(self, val, expand=1):
"""
for every cell in the grid of 'val' fill all cells
around it to de noise the gr... |
def res_set_to_phenotype(res_set, full_list):
"""
Converts a set of strings indicating resources to a binary string where
the positions of 1s indicate which resources are present.
Inputs: res_set - a set of strings indicating which resources are present
full_list - a list of strings indicat... | Converts a set of strings indicating resources to a binary string where
the positions of 1s indicate which resources are present.
Inputs: res_set - a set of strings indicating which resources are present
full_list - a list of strings indicating all resources which could
coul... | Below is the the instruction that describes the task:
### Input:
Converts a set of strings indicating resources to a binary string where
the positions of 1s indicate which resources are present.
Inputs: res_set - a set of strings indicating which resources are present
full_list - a list of stri... |
def callback(newstate):
"""Callback from modem, process based on new state"""
print('callback: ', newstate)
if newstate == modem.STATE_RING:
if state == modem.STATE_IDLE:
att = {"cid_time": modem.get_cidtime,
"cid_number": modem.get_cidnumber,
"cid_n... | Callback from modem, process based on new state | Below is the the instruction that describes the task:
### Input:
Callback from modem, process based on new state
### Response:
def callback(newstate):
"""Callback from modem, process based on new state"""
print('callback: ', newstate)
if newstate == modem.STATE_RING:
if state == modem.STATE_IDL... |
def p_importIdentifiers(self, p):
"""importIdentifiers : importIdentifiers ',' importIdentifier
| importIdentifier"""
n = len(p)
if n == 4:
p[0] = p[1] + [p[3]]
elif n == 2:
p[0] = [p[1]] | importIdentifiers : importIdentifiers ',' importIdentifier
| importIdentifier | Below is the the instruction that describes the task:
### Input:
importIdentifiers : importIdentifiers ',' importIdentifier
| importIdentifier
### Response:
def p_importIdentifiers(self, p):
"""importIdentifiers : importIdentifiers ',' importIdentifier
... |
def str_to_ipmask(ipmask):
'''
Converts a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255.255.0) to an hex mask
'''
v = ipmask.split("/")
if len(v) > 2: raise Exception("bad mask format")
mask_ip = ip2hex(v[0])
if mask_ip is None: raise Exception("bad mask format... | Converts a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255.255.0) to an hex mask | Below is the the instruction that describes the task:
### Input:
Converts a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255.255.0) to an hex mask
### Response:
def str_to_ipmask(ipmask):
'''
Converts a string with the notation ip/mask (e.g. 192.168.1.1/24 or 192.168.1.1/255.255... |
def plot_one_track(file_struct, est_times, est_labels, boundaries_id, labels_id,
title=None):
"""Plots the results of one track, with ground truth if it exists."""
import matplotlib.pyplot as plt
# Set up the boundaries id
bid_lid = boundaries_id
if labels_id is not None:
... | Plots the results of one track, with ground truth if it exists. | Below is the the instruction that describes the task:
### Input:
Plots the results of one track, with ground truth if it exists.
### Response:
def plot_one_track(file_struct, est_times, est_labels, boundaries_id, labels_id,
title=None):
"""Plots the results of one track, with ground truth if... |
def symbol_leading_char(self):
"""Return the symbol leading char attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.SYMBOL_LEADING_CHA... | Return the symbol leading char attribute of the BFD file being
processed. | Below is the the instruction that describes the task:
### Input:
Return the symbol leading char attribute of the BFD file being
processed.
### Response:
def symbol_leading_char(self):
"""Return the symbol leading char attribute of the BFD file being
processed.
"""
i... |
def _get_tables(self, ods):
"""Returns list of table nodes from ods object"""
childnodes = ods.spreadsheet.childNodes
qname_childnodes = [(s.qname[1], s) for s in childnodes]
return [node for name, node in qname_childnodes if name == u"table"] | Returns list of table nodes from ods object | Below is the the instruction that describes the task:
### Input:
Returns list of table nodes from ods object
### Response:
def _get_tables(self, ods):
"""Returns list of table nodes from ods object"""
childnodes = ods.spreadsheet.childNodes
qname_childnodes = [(s.qname[1], s) for s in chil... |
def set_state(self, state=None, **kwargs):
""" Set the view state of the camera
Should be a dict (or kwargs) as returned by get_state. It can
be an incomlete dict, in which case only the specified
properties are set.
Parameters
----------
state : dict
... | Set the view state of the camera
Should be a dict (or kwargs) as returned by get_state. It can
be an incomlete dict, in which case only the specified
properties are set.
Parameters
----------
state : dict
The camera state.
**kwargs : dict
... | Below is the the instruction that describes the task:
### Input:
Set the view state of the camera
Should be a dict (or kwargs) as returned by get_state. It can
be an incomlete dict, in which case only the specified
properties are set.
Parameters
----------
state : d... |
def _evaluate_objective_multiple(objective_function, arg_batch,
batch_evaluate_objective):
"""Evaluates the objective function on a batch of points.
If `batch_evaluate_objective` is True, returns
`objective function(arg_batch)` else it maps the `objective_function`
across the `... | Evaluates the objective function on a batch of points.
If `batch_evaluate_objective` is True, returns
`objective function(arg_batch)` else it maps the `objective_function`
across the `arg_batch`.
Args:
objective_function: A Python callable that accepts a single `Tensor` of
rank 'R > 1' and any shape... | Below is the the instruction that describes the task:
### Input:
Evaluates the objective function on a batch of points.
If `batch_evaluate_objective` is True, returns
`objective function(arg_batch)` else it maps the `objective_function`
across the `arg_batch`.
Args:
objective_function: A Python callab... |
def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False,
concat_softmax=False):
"""As described in https://arxiv.org/abs/1511.06581"""
with tf.variable_scope(scope, reuse=reuse):
out = img_in
with tf.variable_scope("convnet"):
# original architecture
out = layers... | As described in https://arxiv.org/abs/1511.06581 | Below is the the instruction that describes the task:
### Input:
As described in https://arxiv.org/abs/1511.06581
### Response:
def dueling_model(img_in, num_actions, scope, noisy=False, reuse=False,
concat_softmax=False):
"""As described in https://arxiv.org/abs/1511.06581"""
with tf.variabl... |
def set_hostname(hostname):
'''
Set the hostname of the windows minion, requires a restart before this will
be updated.
.. versionadded:: 2016.3.0
Args:
hostname (str): The hostname to set
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. cod... | Set the hostname of the windows minion, requires a restart before this will
be updated.
.. versionadded:: 2016.3.0
Args:
hostname (str): The hostname to set
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt 'minion-id'... | Below is the the instruction that describes the task:
### Input:
Set the hostname of the windows minion, requires a restart before this will
be updated.
.. versionadded:: 2016.3.0
Args:
hostname (str): The hostname to set
Returns:
bool: ``True`` if successful, otherwise ``False``
... |
def generate_filename(self, instance, filename):
"""
removes UTF chars from filename
"""
from unidecode import unidecode
return super().generate_filename(instance, unidecode(force_text(filename))) | removes UTF chars from filename | Below is the the instruction that describes the task:
### Input:
removes UTF chars from filename
### Response:
def generate_filename(self, instance, filename):
"""
removes UTF chars from filename
"""
from unidecode import unidecode
return super().generate_filename(instance,... |
def is_valid_resource_name(rname, exception_type=None):
"""Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_typ... | Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type exception_type: :class:`Exception`
:returns: A boolean describing whethe... | Below is the the instruction that describes the task:
### Input:
Validates the given resource name to ARM guidelines, individual services may be more restrictive.
:param rname: The resource name being validated.
:type rname: str
:param exception_type: Raises this Exception if invalid.
:type excepti... |
def login(self, username=None, password=None):
"""
登陆用户。如果用户名和密码正确,服务器会返回用户的 sessionToken 。
"""
if username:
self.set('username', username)
if password:
self.set('password', password)
response = client.post('/login', params=self.dump())
con... | 登陆用户。如果用户名和密码正确,服务器会返回用户的 sessionToken 。 | Below is the the instruction that describes the task:
### Input:
登陆用户。如果用户名和密码正确,服务器会返回用户的 sessionToken 。
### Response:
def login(self, username=None, password=None):
"""
登陆用户。如果用户名和密码正确,服务器会返回用户的 sessionToken 。
"""
if username:
self.set('username', username)
if ... |
def _map_to_memory(self, stride=1):
r"""Maps results to memory. Will be stored in attribute :attr:`_Y`."""
self._mapping_to_mem_active = True
try:
self._Y = self.get_output(stride=stride)
from pyemma.coordinates.data import DataInMemory
self._Y_source = DataIn... | r"""Maps results to memory. Will be stored in attribute :attr:`_Y`. | Below is the the instruction that describes the task:
### Input:
r"""Maps results to memory. Will be stored in attribute :attr:`_Y`.
### Response:
def _map_to_memory(self, stride=1):
r"""Maps results to memory. Will be stored in attribute :attr:`_Y`."""
self._mapping_to_mem_active = True
tr... |
def _emp_extra_options(options):
"""
Get special options patch, cols, and splits if analysis in emp module
"""
# Check that metadata is valid
metadata_path = os.path.normpath(os.path.join(options['param_dir'],
options['metadata']))
if not os.pat... | Get special options patch, cols, and splits if analysis in emp module | Below is the the instruction that describes the task:
### Input:
Get special options patch, cols, and splits if analysis in emp module
### Response:
def _emp_extra_options(options):
"""
Get special options patch, cols, and splits if analysis in emp module
"""
# Check that metadata is valid
met... |
def on_train_begin(self, **kwargs: Any) -> None:
"Prepare file with metric names."
self.path.parent.mkdir(parents=True, exist_ok=True)
self.file = self.path.open('a') if self.append else self.path.open('w')
self.file.write(','.join(self.learn.recorder.names[:(None if self.add_time ... | Prepare file with metric names. | Below is the the instruction that describes the task:
### Input:
Prepare file with metric names.
### Response:
def on_train_begin(self, **kwargs: Any) -> None:
"Prepare file with metric names."
self.path.parent.mkdir(parents=True, exist_ok=True)
self.file = self.path.open('a') if self... |
def filter_backends(backends, filters=None, **kwargs):
"""Return the backends matching the specified filtering.
Filter the `backends` list by their `configuration` or `status`
attributes, or from a boolean callable. The criteria for filtering can
be specified via `**kwargs` or as a callable via `filter... | Return the backends matching the specified filtering.
Filter the `backends` list by their `configuration` or `status`
attributes, or from a boolean callable. The criteria for filtering can
be specified via `**kwargs` or as a callable via `filters`, and the
backends must fulfill all specified conditions... | Below is the the instruction that describes the task:
### Input:
Return the backends matching the specified filtering.
Filter the `backends` list by their `configuration` or `status`
attributes, or from a boolean callable. The criteria for filtering can
be specified via `**kwargs` or as a callable via ... |
def read_namespaced_pod_disruption_budget(self, name, namespace, **kwargs):
"""
read the specified PodDisruptionBudget
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_di... | read the specified PodDisruptionBudget
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_disruption_budget(name, namespace, async_req=True)
>>> result = thread.get()
:par... | Below is the the instruction that describes the task:
### Input:
read the specified PodDisruptionBudget
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_disruption_budget(name, names... |
def downsync(section, map_files):
"""
For each section defined in the local config file, creates a folder inside the local config folder
named after the section. Downloads the environemnt file defined by the S3CONF variable for this section
to this folder.
"""
try:
settings = config.Sett... | For each section defined in the local config file, creates a folder inside the local config folder
named after the section. Downloads the environemnt file defined by the S3CONF variable for this section
to this folder. | Below is the the instruction that describes the task:
### Input:
For each section defined in the local config file, creates a folder inside the local config folder
named after the section. Downloads the environemnt file defined by the S3CONF variable for this section
to this folder.
### Response:
def downs... |
def get_templates(model):
""" Return a list of templates usable by a model. """
for template_name, template in templates.items():
if issubclass(template.model, model):
yield (template_name, template.layout._meta.verbose_name) | Return a list of templates usable by a model. | Below is the the instruction that describes the task:
### Input:
Return a list of templates usable by a model.
### Response:
def get_templates(model):
""" Return a list of templates usable by a model. """
for template_name, template in templates.items():
if issubclass(template.model, model):
... |
def to_tex(self, text_size='large', table_width=5, clear_pages = False):
"""
Write the program information to a .tex file, which can be
rendered to .pdf running pdflatex. The program can then be
printed and brought to the gym.
Parameters
----------
text_size
... | Write the program information to a .tex file, which can be
rendered to .pdf running pdflatex. The program can then be
printed and brought to the gym.
Parameters
----------
text_size
The tex text size, e.g. '\small', 'normalsize', 'large', 'Large'
or 'LARG... | Below is the the instruction that describes the task:
### Input:
Write the program information to a .tex file, which can be
rendered to .pdf running pdflatex. The program can then be
printed and brought to the gym.
Parameters
----------
text_size
The tex text siz... |
def install(apk, opts=[]):
"""
Install *.apk on target
:param apk: string path to apk on host to install
:param opts: list command options (e.g. ["-r", "-a"])
:return: result of _exec_command() execution
"""
adb_full_cmd = [v.ADB_COMMAND_PREFIX, v.ADB_COMMAND_INSTALL, _convert_opts(opts), ap... | Install *.apk on target
:param apk: string path to apk on host to install
:param opts: list command options (e.g. ["-r", "-a"])
:return: result of _exec_command() execution | Below is the the instruction that describes the task:
### Input:
Install *.apk on target
:param apk: string path to apk on host to install
:param opts: list command options (e.g. ["-r", "-a"])
:return: result of _exec_command() execution
### Response:
def install(apk, opts=[]):
"""
Install *.ap... |
def paintEvent(self, event):
"""
Reimplements the :meth:`*.paintEvent` method.
:param event: QEvent.
:type event: QEvent
"""
super(type(self), self).paintEvent(event)
show_message = True
model = self.model()
if issubclass(type(model), GraphModel... | Reimplements the :meth:`*.paintEvent` method.
:param event: QEvent.
:type event: QEvent | Below is the the instruction that describes the task:
### Input:
Reimplements the :meth:`*.paintEvent` method.
:param event: QEvent.
:type event: QEvent
### Response:
def paintEvent(self, event):
"""
Reimplements the :meth:`*.paintEvent` method.
:param event: QEvent.
... |
def create_exception(error_codec):
"""
Creates an exception with given error codec.
:param error_codec: (Error Codec), error codec which includes the class name, message and exception trace.
:return: (Exception), the created exception.
"""
if error_codec.error_code in ERROR_CODE_TO_ERROR:
... | Creates an exception with given error codec.
:param error_codec: (Error Codec), error codec which includes the class name, message and exception trace.
:return: (Exception), the created exception. | Below is the the instruction that describes the task:
### Input:
Creates an exception with given error codec.
:param error_codec: (Error Codec), error codec which includes the class name, message and exception trace.
:return: (Exception), the created exception.
### Response:
def create_exception(error_cod... |
def verify_request(self):
"""
Verify LTI request
:raises: LTIException if request validation failed
"""
request = self.lti_kwargs['app'].current_request
if request.method == 'POST':
# Chalice expects JSON and does not nativly support forms data in
... | Verify LTI request
:raises: LTIException if request validation failed | Below is the the instruction that describes the task:
### Input:
Verify LTI request
:raises: LTIException if request validation failed
### Response:
def verify_request(self):
"""
Verify LTI request
:raises: LTIException if request validation failed
"""
request = se... |
def threshold_monitor_hidden_threshold_monitor_Memory_limit(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "threshold-monitor-hidden", xmlns="urn:brocade.com:mgmt:brocade-threshold-monitor")
threshold_mon... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def threshold_monitor_hidden_threshold_monitor_Memory_limit(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
threshold_monitor_hidden = ET.SubElement(config, "... |
def find_best_frametype(channel, start, end,
frametype_match=None, allow_tape=True,
connection=None, host=None, port=None):
"""Intelligently select the best frametype from which to read this channel
Parameters
----------
channel : `str`, `~gwpy.detector.C... | Intelligently select the best frametype from which to read this channel
Parameters
----------
channel : `str`, `~gwpy.detector.Channel`
the channel to be found
start : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
GPS start time of period of interest,
any input parseable by `~gwpy.t... | Below is the the instruction that describes the task:
### Input:
Intelligently select the best frametype from which to read this channel
Parameters
----------
channel : `str`, `~gwpy.detector.Channel`
the channel to be found
start : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
GPS star... |
def add_files(self, files):
"""Add files and/or folders to transfer.
If :class:`Transfer.compress` attribute is set to ``True``, files
will get packed into a zip file before sending.
:param files: Files or folders to send
:type files: str, list
"""
if isinstance... | Add files and/or folders to transfer.
If :class:`Transfer.compress` attribute is set to ``True``, files
will get packed into a zip file before sending.
:param files: Files or folders to send
:type files: str, list | Below is the the instruction that describes the task:
### Input:
Add files and/or folders to transfer.
If :class:`Transfer.compress` attribute is set to ``True``, files
will get packed into a zip file before sending.
:param files: Files or folders to send
:type files: str, list
### ... |
def writemessage(self, text):
"""Put data in output queue, rebuild the prompt and entered data"""
# Need to grab the input queue lock to ensure the entered data doesn't change
# before we're done rebuilding it.
# Note that writemessage will eventually call writecooked
self.IQUEUE... | Put data in output queue, rebuild the prompt and entered data | Below is the the instruction that describes the task:
### Input:
Put data in output queue, rebuild the prompt and entered data
### Response:
def writemessage(self, text):
"""Put data in output queue, rebuild the prompt and entered data"""
# Need to grab the input queue lock to ensure the entered da... |
def decorate(self, func, limit, ttl, *anoop, **kwnoop):
"""make limit and ttl required"""
return super(ratelimit, self).decorate(func, limit, ttl, *anoop, **kwnoop) | make limit and ttl required | Below is the the instruction that describes the task:
### Input:
make limit and ttl required
### Response:
def decorate(self, func, limit, ttl, *anoop, **kwnoop):
"""make limit and ttl required"""
return super(ratelimit, self).decorate(func, limit, ttl, *anoop, **kwnoop) |
def text(self,text):
""" puts text in the entity. Whitespace and newlines are stripped to single spaces. """
if text:
text = utfstr(text)
text = text.strip()
text = re.sub('\s+',' ',text)
if text:
self.dirty = True
self.escp... | puts text in the entity. Whitespace and newlines are stripped to single spaces. | Below is the the instruction that describes the task:
### Input:
puts text in the entity. Whitespace and newlines are stripped to single spaces.
### Response:
def text(self,text):
""" puts text in the entity. Whitespace and newlines are stripped to single spaces. """
if text:
text = utf... |
def cache_url(url, model_dir=None, progress=True):
r"""Loads the Torch serialized object at the given URL.
If the object is already present in `model_dir`, it's deserialized and
returned. The filename part of the URL should follow the naming convention
``filename-<sha256>.ext`` where ``<sha256>`` is the... | r"""Loads the Torch serialized object at the given URL.
If the object is already present in `model_dir`, it's deserialized and
returned. The filename part of the URL should follow the naming convention
``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or more
digits of the SHA256 hash of t... | Below is the the instruction that describes the task:
### Input:
r"""Loads the Torch serialized object at the given URL.
If the object is already present in `model_dir`, it's deserialized and
returned. The filename part of the URL should follow the naming convention
``filename-<sha256>.ext`` where ``<sh... |
def unregister_callback(self, callback_url, **kwargs):
"""
Unregister a callback.
Unregisters a callback URL that was previously white-listed with a **Register a
callback** request for use with the asynchronous interface. Once unregistered, the
URL can no longer be used with asy... | Unregister a callback.
Unregisters a callback URL that was previously white-listed with a **Register a
callback** request for use with the asynchronous interface. Once unregistered, the
URL can no longer be used with asynchronous recognition requests.
**See also:** [Unregistering a call... | Below is the the instruction that describes the task:
### Input:
Unregister a callback.
Unregisters a callback URL that was previously white-listed with a **Register a
callback** request for use with the asynchronous interface. Once unregistered, the
URL can no longer be used with asynchron... |
def resume(self) -> None:
"""Resume recording after pause.
Thread safe and UI safe."""
with self.__state_lock:
if self.__state == DataChannelBuffer.State.paused:
self.__state = DataChannelBuffer.State.started | Resume recording after pause.
Thread safe and UI safe. | Below is the the instruction that describes the task:
### Input:
Resume recording after pause.
Thread safe and UI safe.
### Response:
def resume(self) -> None:
"""Resume recording after pause.
Thread safe and UI safe."""
with self.__state_lock:
if self.__state == DataC... |
def merge(*projects):
"""
Merge zero or more dictionaries representing projects with the default
project dictionary and return the result
"""
result = {}
for project in projects:
for name, section in (project or {}).items():
if name not in PROJECT_SECTIONS:
ra... | Merge zero or more dictionaries representing projects with the default
project dictionary and return the result | Below is the the instruction that describes the task:
### Input:
Merge zero or more dictionaries representing projects with the default
project dictionary and return the result
### Response:
def merge(*projects):
"""
Merge zero or more dictionaries representing projects with the default
project dic... |
def name_resolve(self, name=None, recursive=False,
nocache=False, **kwargs):
"""Gets the value currently published at an IPNS name.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In resolve, th... | Gets the value currently published at an IPNS name.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In resolve, the
default value of ``name`` is your own identity public key.
.. code-block:: python
... | Below is the the instruction that describes the task:
### Input:
Gets the value currently published at an IPNS name.
IPNS is a PKI namespace, where names are the hashes of public keys, and
the private key enables publishing new (signed) values. In resolve, the
default value of ``name`` is y... |
def apply(self):
"""Inherited from tkinter.simpledialog.Dialog"""
user_type = self.rb_choice.get()
if user_type == 'student' or user_type == 'tutor':
self.result = user_type | Inherited from tkinter.simpledialog.Dialog | Below is the the instruction that describes the task:
### Input:
Inherited from tkinter.simpledialog.Dialog
### Response:
def apply(self):
"""Inherited from tkinter.simpledialog.Dialog"""
user_type = self.rb_choice.get()
if user_type == 'student' or user_type == 'tutor':
self.re... |
def bind_key(pymux, variables):
"""
Bind a key sequence.
-n: Not necessary to use the prefix.
"""
key = variables['<key>']
command = variables['<command>']
arguments = variables['<arguments>']
needs_prefix = not variables['-n']
try:
pymux.key_bindings_manager.add_custom_bind... | Bind a key sequence.
-n: Not necessary to use the prefix. | Below is the the instruction that describes the task:
### Input:
Bind a key sequence.
-n: Not necessary to use the prefix.
### Response:
def bind_key(pymux, variables):
"""
Bind a key sequence.
-n: Not necessary to use the prefix.
"""
key = variables['<key>']
command = variables['<comma... |
def cull_nodes(self, stat, threshold=0.5, comparator=ge):
"""Delete nodes whose stat >= ``threshold`` (default 0.5).
Optional argument ``comparator`` will replace >= as the test
for whether to cull. You can use the name of a stored function.
"""
comparator = self._lookup_compar... | Delete nodes whose stat >= ``threshold`` (default 0.5).
Optional argument ``comparator`` will replace >= as the test
for whether to cull. You can use the name of a stored function. | Below is the the instruction that describes the task:
### Input:
Delete nodes whose stat >= ``threshold`` (default 0.5).
Optional argument ``comparator`` will replace >= as the test
for whether to cull. You can use the name of a stored function.
### Response:
def cull_nodes(self, stat, threshold=0... |
def publish(
self, resource_group_name, automation_account_name, runbook_name, custom_headers=None, raw=False, polling=True, **operation_config):
"""Publish runbook draft.
:param resource_group_name: Name of an Azure Resource group.
:type resource_group_name: str
:param auto... | Publish runbook draft.
:param resource_group_name: Name of an Azure Resource group.
:type resource_group_name: str
:param automation_account_name: The name of the automation account.
:type automation_account_name: str
:param runbook_name: The parameters supplied to the publish r... | Below is the the instruction that describes the task:
### Input:
Publish runbook draft.
:param resource_group_name: Name of an Azure Resource group.
:type resource_group_name: str
:param automation_account_name: The name of the automation account.
:type automation_account_name: str
... |
def update_refchip_with_shift(chip_wcs, wcslin, fitgeom='rscale',
rot=0.0, scale=1.0, xsh=0.0, ysh=0.0,
fit=None, xrms=None, yrms=None):
""" Compute the matrix for the scale and rotation correction
Parameters
----------
chip_wcs: wcs object
... | Compute the matrix for the scale and rotation correction
Parameters
----------
chip_wcs: wcs object
HST of the input image
wcslin: wcs object
Reference WCS from which the offsets/rotations are determined
fitgeom: str
NOT USED
rot : float
Amount of rotation measur... | Below is the the instruction that describes the task:
### Input:
Compute the matrix for the scale and rotation correction
Parameters
----------
chip_wcs: wcs object
HST of the input image
wcslin: wcs object
Reference WCS from which the offsets/rotations are determined
fitgeom: s... |
def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
if not self.upstream:
raise Exception("Must have an upstream")
# Must always propagate, since this is really just a filter.
self.upstream.remove(self._rename(rel_path), ... | Delete the file from the cache, and from the upstream | Below is the the instruction that describes the task:
### Input:
Delete the file from the cache, and from the upstream
### Response:
def remove(self, rel_path, propagate=False):
'''Delete the file from the cache, and from the upstream'''
if not self.upstream:
raise Exception("Must have... |
def create_distant_reference(self, ref_data):
"""Validate and create the reference in Zotero and return the created item."""
self.validate_reference_data(ref_data)
creation_status = self._zotero_lib.create_items([ref_data])
try:
created_item = creation_status["successful"]["0... | Validate and create the reference in Zotero and return the created item. | Below is the the instruction that describes the task:
### Input:
Validate and create the reference in Zotero and return the created item.
### Response:
def create_distant_reference(self, ref_data):
"""Validate and create the reference in Zotero and return the created item."""
self.validate_referenc... |
def _conf(cls, opts):
"""Setup logging via ini-file from logging_conf_file option."""
if not opts.logging_conf_file:
return False
if not os.path.exists(opts.logging_conf_file):
# FileNotFoundError added only in Python 3.3
# https://docs.python.org/3/whatsnew/... | Setup logging via ini-file from logging_conf_file option. | Below is the the instruction that describes the task:
### Input:
Setup logging via ini-file from logging_conf_file option.
### Response:
def _conf(cls, opts):
"""Setup logging via ini-file from logging_conf_file option."""
if not opts.logging_conf_file:
return False
if not os.p... |
def _closeResources(self):
""" Closes the root Dataset.
"""
logger.info("Closing: {}".format(self._fileName))
self._h5Group.close()
self._h5Group = None | Closes the root Dataset. | Below is the the instruction that describes the task:
### Input:
Closes the root Dataset.
### Response:
def _closeResources(self):
""" Closes the root Dataset.
"""
logger.info("Closing: {}".format(self._fileName))
self._h5Group.close()
self._h5Group = None |
def join(
self,
words,
sep=None,
sep_spaced=True,
final_sep=None,
conj="and",
conj_spaced=True,
):
"""
Join words into a list.
e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly'
options:
conj: replacement for... | Join words into a list.
e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly'
options:
conj: replacement for 'and'
sep: separator. default ',', unless ',' is in the list then ';'
final_sep: final separator. default ',', unless ',' is in the list then ';'
conj_spa... | Below is the the instruction that describes the task:
### Input:
Join words into a list.
e.g. join(['ant', 'bee', 'fly']) returns 'ant, bee, and fly'
options:
conj: replacement for 'and'
sep: separator. default ',', unless ',' is in the list then ';'
final_sep: final separa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.