text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lasts(iterable, items=1, default=None):
# type: (Iterable[T], int, T) -> Iterable[T] """ Lazily return the last x items from this iterable or default. """ |
last_items = deque(iterable, maxlen=items)
for _ in range(items - len(last_items)):
yield default
for y in last_items:
yield y |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def is_legacy_server():
'''Determine execution mode.
Legacy mode: <= v4.20181215
'''
with Session() as session:
ret = session.Kernel.hello()
bai_version = ret['version']
legacy = True if bai_version <= 'v4.20181215' else False
return legacy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def clear(self):
'''
claar all the cache, and release memory
'''
for node in self.dli():
node.empty = True
node.key = None
node.value = None
self.head = _dlnode()
self.head.next = self.head
self.head.prev = self.head
self.listSize = 1
self.table.clear()
# status var
self.hit_cnt ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pop(self, key, default = None):
"""Delete the item""" |
node = self.get(key, None)
if node == None:
value = default
else:
value = node
try:
del self[key]
except:
return value
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def complete(self, code: str, opts: dict = None) -> Iterable[str]:
'''
Gets the auto-completion candidates from the given code string,
as if a user has pressed the tab key just after the code in
IDEs.
Depending on the language of the compute session, this feature
m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def get_info(self):
'''
Retrieves a brief information about the compute session.
'''
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
rqst = Request(self.session,
'GET', '/kernel/{}'.format(s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def upload(self, files: Sequence[Union[str, Path]],
basedir: Union[str, Path] = None,
show_progress: bool = False):
'''
Uploads the given list of files to the compute session.
You may refer them in the batch-mode execution or from the code
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def download(self, files: Sequence[Union[str, Path]],
dest: Union[str, Path] = '.',
show_progress: bool = False):
'''
Downloads the given list of files from the compute session.
:param files: The list of file paths in the compute session.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def list_files(self, path: Union[str, Path] = '.'):
'''
Gets the list of files in the given path inside the compute session
container.
:param path: The directory path in the compute session.
'''
params = {}
if self.owner_access_key:
params['owne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _message(self, mqttc, userdata, msg):
""" The callback for when a PUBLISH message is received from the server. :param mqttc: The client instance for this cal... |
try:
inputCmds = ['query', 'command', 'result', 'status', 'shortPoll', 'longPoll', 'delete']
parsed_msg = json.loads(msg.payload.decode('utf-8'))
if 'node' in parsed_msg:
if parsed_msg['node'] != 'polyglot':
return
del pars... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _disconnect(self, mqttc, userdata, rc):
""" The callback for when a DISCONNECT occurs. :param mqttc: The client instance for this callback :param userdata: T... |
self.connected = False
if rc != 0:
LOGGER.info("MQTT Unexpected disconnection. Trying reconnect.")
try:
self._mqttc.reconnect()
except Exception as ex:
template = "An exception of type {0} occured. Arguments:\n{1!r}"
me... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _startMqtt(self):
""" The client start method. Starts the thread for the MQTT Client and publishes the connected message. """ |
LOGGER.info('Connecting to MQTT... {}:{}'.format(self._server, self._port))
try:
# self._mqttc.connect_async(str(self._server), int(self._port), 10)
self._mqttc.connect_async('{}'.format(self._server), int(self._port), 10)
self._mqttc.loop_forever()
except Ex... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
""" The client stop method. If the client is currently connected stop the thread and disconnect. Publish the disconnected message if clean shutdo... |
# self.loop.call_soon_threadsafe(self.loop.stop)
# self.loop.stop()
# self._longPoll.cancel()
# self._shortPoll.cancel()
if self.connected:
LOGGER.info('Disconnecting from MQTT... {}:{}'.format(self._server, self._port))
self._mqttc.publish(self.topicSelf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addNode(self, node):
""" Add a node to the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are re... |
LOGGER.info('Adding node {}({})'.format(node.name, node.address))
message = {
'addnode': {
'nodes': [{
'address': node.address,
'name': node.name,
'node_def_id': node.id,
'primary': node.primary,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delNode(self, address):
""" Delete a node from the NodeServer :param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and driver... |
LOGGER.info('Removing node {}'.format(address))
message = {
'removenode': {
'address': address
}
}
self.send(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getNode(self, address):
""" Get Node by Address of existing nodes. """ |
try:
for node in self.config['nodes']:
if node['address'] == address:
return node
return False
except KeyError:
LOGGER.error('Usually means we have not received the config yet.', exc_info=True)
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inConfig(self, config):
""" Save incoming config received from Polyglot to Interface.config and then do any functions that are waiting on the config to be re... |
self.config = config
self.isyVersion = config['isyVersion']
try:
for watcher in self.__configObservers:
watcher(config)
self.send_custom_config_docs()
except KeyError as e:
LOGGER.error('KeyError in gotConfig: {}'.format(e), exc_info... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delNode(self, address):
""" Just send it along if requested, should be able to delete the node even if it isn't in our config anywhere. Usually used for norm... |
if address in self.nodes:
del self.nodes[address]
self.poly.delNode(address) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def query(cls, query: str,
variables: Optional[Mapping[str, Any]] = None,
) -> Any:
'''
Sends the GraphQL query and returns the response.
:param query: The GraphQL query string.
:param variables: An optional key-value dictionary
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_readable_time_string(seconds):
"""Returns human readable string from number of seconds""" |
seconds = int(seconds)
minutes = seconds // 60
seconds = seconds % 60
hours = minutes // 60
minutes = minutes % 60
days = hours // 24
hours = hours % 24
result = ""
if days > 0:
result += "%d %s " % (days, "Day" if (days == 1) else "Days")
if hours > 0:
result +... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_rate_limits(response):
"""Returns a list of rate limit information from a given response's headers.""" |
periods = response.headers['X-RateLimit-Period']
if not periods:
return []
rate_limits = []
periods = periods.split(',')
limits = response.headers['X-RateLimit-Limit'].split(',')
remaining = response.headers['X-RateLimit-Remaining'].split(',')
reset = response.headers['X-RateLimit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def swap(self):
# type: () -> DictWrapper """Swap key and value /!\ Be carreful, if there are duplicate values, only one will survive /!\ Example: {2: 2, 3: 3} "... |
return self.__class__((v, k) for k, v in self.items()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromkeys(cls, iterable, value=None):
# TODO : type: (Iterable, Union[Any, Callable]) -> DictWrapper # https://github.com/python/mypy/issues/2254 """Create a ... |
if not callable(value):
return cls(dict.fromkeys(iterable, value))
return cls((key, value(key)) for key in iterable) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_excel_workbook(api_data, result_info_key, identifier_keys):
"""Generates an Excel workbook object given api_data returned by the Analytics API Args: api_... |
cleaned_data = []
for item_data in api_data:
result_info = item_data.pop(result_info_key, {})
cleaned_item_data = {}
if 'meta' in item_data:
meta = item_data.pop('meta')
cleaned_item_data['meta'] = meta
for key in item_data:
cleaned_item_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_worksheets(workbook, data_list, result_info_key, identifier_keys):
"""Writes rest of the worksheets to workbook. Args: workbook: workbook to write into... |
# we can use the first item to figure out the worksheet keys
worksheet_keys = get_worksheet_keys(data_list[0], result_info_key)
for key in worksheet_keys:
title = key.split('/')[1]
title = utilities.convert_snake_to_title_case(title)
title = KEY_TO_WORKSHEET_MAP.get(title, titl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_keys(data_list, leading_columns=LEADING_COLUMNS):
"""Gets all possible keys from a list of dicts, sorting by leading_columns first Args: data_list: list ... |
all_keys = set().union(*(list(d.keys()) for d in data_list))
leading_keys = []
for key in leading_columns:
if key not in all_keys:
continue
leading_keys.append(key)
all_keys.remove(key)
return leading_keys + sorted(all_keys) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_data(worksheet, data):
"""Writes data into worksheet. Args: worksheet: worksheet to write into data: data to be written """ |
if not data:
return
if isinstance(data, list):
rows = data
else:
rows = [data]
if isinstance(rows[0], dict):
keys = get_keys(rows)
worksheet.append([utilities.convert_snake_to_title_case(key) for key in keys])
for row in rows:
values = [get_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_data(key, data_list, result_info_key, identifier_keys):
""" Given a key as the endpoint name, pulls the data for that endpoint out of the data_list f... |
master_data = []
for item_data in data_list:
data = item_data[key]
if data is None:
current_item_data = {}
else:
if key == 'property/value':
current_item_data = data['value']
elif key == 'property/details':
top_level... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_database_connected(app_configs, **kwargs):
""" A Django check to see if connecting to the configured default database backend succeeds. """ |
errors = []
try:
connection.ensure_connection()
except OperationalError as e:
msg = 'Could not connect to database: {!s}'.format(e)
errors.append(checks.Error(msg,
id=health.ERROR_CANNOT_CONNECT_DATABASE))
except ImproperlyConfigured as e:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_migrations_applied(app_configs, **kwargs):
""" A Django check to see if all migrations have been applied correctly. """ |
from django.db.migrations.loader import MigrationLoader
errors = []
# Load migrations from disk/DB
try:
loader = MigrationLoader(connection, ignore_no_migrations=True)
except (ImproperlyConfigured, ProgrammingError, OperationalError):
msg = "Can't connect to database to check migra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_redis_connected(app_configs, **kwargs):
""" A Django check to connect to the default redis connection using ``django_redis.get_redis_connection`` and s... |
import redis
from django_redis import get_redis_connection
errors = []
try:
connection = get_redis_connection('default')
except redis.ConnectionError as e:
msg = 'Could not connect to redis: {!s}'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_REDI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dev_alarms(auth, url, devid=None, devip=None):
""" function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for ... |
# checks to see if the imc credentials are already available
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
f_url = url + "/imcrs/fault/alarm?operatorName=admin&deviceId=" + \
str(devid) + "&desc=false"
response = requests.get(f_url, auth=auth, hea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list():
'''List virtual folders that belongs to the current user.'''
fields = [
('Name', 'name'),
('ID', 'id'),
('Owner', 'is_owner'),
('Permission', 'permission'),
]
with Session() as session:
try:
resp = session.VFolder.list()
if not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_hosts():
'''List the hosts of virtual folders that is accessible to the current user.'''
with Session() as session:
try:
resp = session.VFolder.list_hosts()
print(f"Default vfolder host: {resp['default']}")
print(f"Usable hosts: {', '.join(resp['allowed'])}")... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create(name, host):
'''Create a new virtual folder.
\b
NAME: Name of a virtual folder.
HOST: Name of a virtual folder host in which the virtual folder will be created.
'''
with Session() as session:
try:
result = session.VFolder.create(name, host)
print('Virt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def delete(name):
'''Delete the given virtual folder. This operation is irreversible!
NAME: Name of a virtual folder.
'''
with Session() as session:
try:
session.VFolder(name).delete()
print_done('Deleted.')
except Exception as e:
print_error(e)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def rename(old_name, new_name):
'''Rename the given virtual folder. This operation is irreversible!
You cannot change the vfolders that are shared by other users,
and the new name must be unique among all your accessible vfolders
including the shared ones.
OLD_NAME: The current name of a virtual fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def info(name):
'''Show the information of the given virtual folder.
NAME: Name of a virtual folder.
'''
with Session() as session:
try:
result = session.VFolder(name).info()
print('Virtual folder "{0}" (ID: {1})'
.format(result['name'], result['id']))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def download(name, filenames):
'''
Download a file from the virtual folder to the current working directory.
The files with the same names will be overwirtten.
\b
NAME: Name of a virtual folder.
FILENAMES: Paths of the files to be uploaded.
'''
with Session() as session:
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def mkdir(name, path):
'''Create an empty directory in the virtual folder.
\b
NAME: Name of a virtual folder.
PATH: The name or path of directory. Parent directories are created automatically
if they do not exist.
'''
with Session() as session:
try:
session.VFolder... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def rm(name, filenames, recursive):
'''
Delete files in a virtual folder.
If one of the given paths is a directory and the recursive option is enabled,
all its content and the directory itself are recursively deleted.
This operation is irreversible!
\b
NAME: Name of a virtual folder.
F... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ls(name, path):
""" List files in a path of a virtual folder. \b NAME: Name of a virtual folder. PATH: Path inside vfolder. """ |
with Session() as session:
try:
print_wait('Retrieving list of files in "{}"...'.format(path))
result = session.VFolder(name).list_files(path)
if 'error_msg' in result and result['error_msg']:
print_fail(result['error_msg'])
return
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invite(name, emails, perm):
"""Invite other users to access the virtual folder. \b NAME: Name of a virtual folder. EMAIL: Emails to invite. """ |
with Session() as session:
try:
assert perm in ['rw', 'ro'], \
'Invalid permission: {}'.format(perm)
result = session.VFolder(name).invite(perm, emails)
invited_ids = result.get('invited_ids', [])
if len(invited_ids) > 0:
pr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def invitations():
"""List and manage received invitations. """ |
with Session() as session:
try:
result = session.VFolder.invitations()
invitations = result.get('invitations', [])
if len(invitations) < 1:
print('No invitations.')
return
print('List of invitations (inviter, vfolder id, permis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_check(self, check, obj):
""" Adds a given check callback with the provided object to the list of checks. Useful for built-ins but also advanced custom c... |
self.logger.info('Adding extension check %s' % check.__name__)
check = functools.wraps(check)(functools.partial(check, obj))
self.check(func=check) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app):
""" Initializes the extension with the given app, registers the built-in views with an own blueprint and hooks up our signal callbacks. ... |
# If no version path was provided in the init of the Dockerflow
# class we'll use the parent directory of the app root path.
if self.version_path is None:
self.version_path = os.path.dirname(app.root_path)
for view in (
('/__version__', 'version', self._version_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _before_request(self):
""" The before_request callback. """ |
g._request_id = str(uuid.uuid4())
g._start_timestamp = time.time() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _after_request(self, response):
""" The signal handler for the request_finished signal. """ |
if not getattr(g, '_has_exception', False):
extra = self.summary_extra()
self.summary_logger.info('', extra=extra)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _got_request_exception(self, sender, exception, **extra):
""" The signal handler for the got_request_exception signal. """ |
extra = self.summary_extra()
extra['errno'] = 500
self.summary_logger.error(str(exception), extra=extra)
g._has_exception = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user_id(self):
""" Return the ID of the current request's user """ |
# This needs flask-login to be installed
if not has_flask_login:
return
# and the actual login manager installed
if not hasattr(current_app, 'login_manager'):
return
# fail if no current_user was attached to the request context
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summary_extra(self):
""" Build the extra data for the summary logger. """ |
out = {
'errno': 0,
'agent': request.headers.get('User-Agent', ''),
'lang': request.headers.get('Accept-Language', ''),
'method': request.method,
'path': request.path,
}
# set the uid value to the current user ID
user_id = sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _version_view(self):
""" View that returns the contents of version.json or a 404. """ |
version_json = self._version_callback(self.version_path)
if version_json is None:
return 'version.json not found', 404
else:
return jsonify(version_json) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _heartbeat_view(self):
""" Runs all the registered checks and returns a JSON response with either a status code of 200 or 500 depending on the results of the... |
details = {}
statuses = {}
level = 0
for name, check in self.checks.items():
detail = self._heartbeat_check_detail(check)
statuses[name] = detail['status']
level = max(level, detail['level'])
if detail['level'] > 0:
detail... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def drange(start: Decimal, stop: Decimal, num: int):
'''
A simplified version of numpy.linspace with default options
'''
delta = stop - start
step = delta / (num - 1)
yield from (start + step * Decimal(tick) for tick in range(0, num)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def range_expr(arg):
'''
Accepts a range expression which generates a range of values for a variable.
Linear space range: "linspace:1,2,10" (start, stop, num) as in numpy.linspace
Pythonic range: "range:1,10,2" (start, stop[, step]) as in Python's range
Case range: "case:a,b,c" (comma-separated str... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def exec_loop(stdout, stderr, kernel, mode, code, *, opts=None,
vprint_done=print_done, is_multi=False):
'''
Fully streamed asynchronous version of the execute loop.
'''
async with kernel.stream_execute(code, mode=mode, opts=opts) as stream:
async for result in stream:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def exec_loop_sync(stdout, stderr, kernel, mode, code, *, opts=None,
vprint_done=print_done):
'''
Old synchronous polling version of the execute loop.
'''
opts = opts if opts else {}
run_id = None # use server-assigned run ID
while True:
result = kernel.execute(run_id... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def start(lang, session_id, owner, env, mount, tag, resources, cluster_size):
'''
Prepare and start a single compute session without executing codes.
You may use the created session to execute codes using the "run" command
or connect to an application service provided by the session using the "app"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def terminate(sess_id_or_alias, owner, stats):
'''
Terminate the given session.
SESSID: session ID or its alias given when creating the session.
'''
print_wait('Terminating the session(s)...')
with Session() as session:
has_failure = False
for sess in sess_id_or_alias:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_devs_custom_views(custom_view_name, dev_list, auth, url):
""" function takes a list of devIDs from devices discovered in the HPE IMC platform and and iss... |
view_id = get_custom_views(auth, url, name=custom_view_name)[0]['symbolId']
add_devs_custom_views_url = '/imcrs/plat/res/view/custom/'+str(view_id)
payload = '''{"device" : '''+ json.dumps(dev_list) + '''}'''
f_url = url + add_devs_custom_views_url
r = requests.put(f_url, data = payload, auth=auth,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def status():
'''Show the manager's current status.'''
with Session() as session:
resp = session.Manager.status()
print(tabulate([('Status', 'Active Sessions'),
(resp['status'], resp['active_sessions'])],
headers='firstrow')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def freeze(wait, force_kill):
'''Freeze manager.'''
if wait and force_kill:
print('You cannot use both --wait and --force-kill options '
'at the same time.', file=sys.stderr)
return
with Session() as session:
if wait:
while True:
resp = sess... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dev_vlans(auth, url, devid=None, devip=None):
"""Function takes input of devID to issue RESTUL call to HP IMC :param auth: requests auth object #usually ... |
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
get_dev_vlans_url = "/imcrs/vlan?devId=" + str(devid) + "&start=0&size=5000&total=false"
f_url = url + get_dev_vlans_url
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 2... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_trunk_interfaces(auth, url, devid=None, devip=None):
"""Function takes devId as input to RESTFULL call to HP IMC platform :param auth: requests auth obje... |
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
get_trunk_interfaces_url = "/imcrs/vlan/trunk?devId=" + str(devid) + \
"&start=1&size=5000&total=false"
f_url = url + get_trunk_interfaces_url
response = requests.get(f_url, auth=auth, headers=H... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_device_access_interfaces(auth, url, devid=None, devip=None):
""" Function takes devid pr devip as input to RESTFUL call to HP IMC platform :param auth: r... |
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
get_access_interface_vlan_url = "/imcrs/vlan/access?devId=" + str(devid) + \
"&start=1&size=500&total=false"
f_url = url + get_access_interface_vlan_url
response = requests.get(f_url, auth=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_device_hybrid_interfaces(auth, url, devid=None, devip=None):
""" Function takes devId as input to RESTFUL call to HP IMC platform :param auth: requests a... |
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
get_hybrid_interface_vlan_url = "/imcrs/vlan/hybrid?devId=" + str(devid) + \
"&start=1&size=500&total=false"
f_url = url + get_hybrid_interface_vlan_url
response = requests.get(f_url, auth=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_results_from_api(identifiers, endpoints, api_key, api_secret):
"""Use the HouseCanary API Python Client to access the API""" |
if api_key is not None and api_secret is not None:
client = housecanary.ApiClient(api_key, api_secret)
else:
client = housecanary.ApiClient()
wrapper = getattr(client, endpoints[0].split('/')[0])
if len(endpoints) > 1:
# use component_mget to request multiple endpoints in one... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def images():
'''
Show the list of registered images in this cluster.
'''
fields = [
('Name', 'name'),
('Registry', 'registry'),
('Tag', 'tag'),
('Digest', 'digest'),
('Size', 'size_bytes'),
('Aliases', 'aliases'),
]
with Session() as session:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def rescan_images(registry):
'''Update the kernel image metadata from all configured docker registries.'''
with Session() as session:
try:
result = session.Image.rescanImages(registry)
except Exception as e:
print_error(e)
sys.exit(1)
if result['ok']:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def alias_image(alias, target):
'''Add an image alias.'''
with Session() as session:
try:
result = session.Image.aliasImage(alias, target)
except Exception as e:
print_error(e)
sys.exit(1)
if result['ok']:
print("alias {0} created for targe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dealias_image(alias):
'''Remove an image alias.'''
with Session() as session:
try:
result = session.Image.dealiasImage(alias)
except Exception as e:
print_error(e)
sys.exit(1)
if result['ok']:
print("alias {0} removed.".format(alias))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_alias():
""" Quick aliases for run command. """ |
mode = Path(sys.argv[0]).stem
help = True if len(sys.argv) <= 1 else False
if mode == 'lcc':
sys.argv.insert(1, 'c')
elif mode == 'lpython':
sys.argv.insert(1, 'python')
sys.argv.insert(1, 'run')
if help:
sys.argv.append('--help')
main.main(prog_name='backend.ai') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rate_limits(self):
"""Returns list of rate limit information from the response""" |
if not self._rate_limits:
self._rate_limits = utilities.get_rate_limits(self._response)
return self._rate_limits |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_custom_views(auth, url, name=None, upperview=None):
""" function takes no input and issues a RESTFUL call to get a list of custom views from HPE IMC. ... |
create_custom_views_url = '/imcrs/plat/res/view/custom?resPrivilegeFilter=false&desc=false' \
'&total=false'
f_url = url + create_custom_views_url
if upperview is None:
payload = '''{ "name": "''' + name + '''",
"upLevelSymbolId" : ""}'''
else:
pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_devs_custom_views(custom_view_name, dev_list, auth, url):
""" function takes a list of devIDs from devices discovered in the HPE IMC platform and issues ... |
view_id = get_custom_views(auth, url, name=custom_view_name)
if view_id is None:
print("View " + custom_view_name + " doesn't exist")
return view_id
view_id = get_custom_views(auth, url, name=custom_view_name)[0]['symbolId']
add_devs_custom_views_url = '/imcrs/plat/res/view/custom/' + s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_format_oauth(self):
"""
Format and encode dict for make authentication on microsoft
servers.
""" |
format_oauth = urllib.parse.urlencode({
'client_id': self._client_id,
'client_secret': self._client_secret,
'scope': self._url_request,
'grant_type': self._grant_type
}).encode("utf-8")
return format_oauth |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_request(self, params, translation_url, headers):
"""
This is the final step, where the request is made, the data is
retrieved and returned.
""" |
resp = requests.get(translation_url, params=params, headers=headers)
resp.encoding = "UTF-8-sig"
result = resp.json()
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def status(cls):
'''
Returns the current status of the configured API server.
'''
rqst = Request(cls.session, 'GET', '/manager/status')
rqst.set_json({
'status': 'running',
})
async with rqst.fetch() as resp:
return await resp.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(sess_id_or_alias, files):
""" Upload files to user's home folder. \b SESSID: Session ID or its alias given when creating the session. FILES: Path to u... |
if len(files) < 1:
return
with Session() as session:
try:
print_wait('Uploading files...')
kernel = session.Kernel(sess_id_or_alias)
kernel.upload(files, show_progress=True)
print_done('Uploaded.')
except Exception as e:
print_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(sess_id_or_alias, files, dest):
""" Download files from a running container. \b SESSID: Session ID or its alias given when creating the session. FIL... |
if len(files) < 1:
return
with Session() as session:
try:
print_wait('Downloading file(s) from {}...'
.format(sess_id_or_alias))
kernel = session.Kernel(sess_id_or_alias)
kernel.download(files, dest, show_progress=True)
prin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ls(sess_id_or_alias, path):
""" List files in a path of a running container. \b SESSID: Session ID or its alias given when creating the session. PATH: Path i... |
with Session() as session:
try:
print_wait('Retrieving list of files in "{}"...'.format(path))
kernel = session.Kernel(sess_id_or_alias)
result = kernel.list_files(path)
if 'errors' in result and result['errors']:
print_fail(result['errors'])... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_operator_password(operator, password, auth, url):
""" Function to set the password of an existing operator :param operator: str Name of the operator acco... |
if operator is None:
operator = input(
'''\n What is the username you wish to change the password?''')
oper_id = ''
authtype = None
plat_oper_list = get_plat_operator(auth, url)
for i in plat_oper_list:
if i['name'] == operator:
oper_id = i['id']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_plat_operator(auth, url):
""" Funtion takes no inputs and returns a list of dictionaties of all of the operators currently configured on the HPE IMC syst... |
f_url = url + '/imcrs/plat/operator?start=0&size=1000&orderBy=id&desc=false&total=false'
try:
response = requests.get(f_url, auth=auth, headers=HEADERS)
plat_oper_list = json.loads(response.text)['operator']
if isinstance(plat_oper_list, dict):
oper_list = [plat_oper_list]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_request(self, url, http_method, query_params, post_data):
"""Makes a request to the specified url endpoint with the specified http method, params and... |
response = requests.request(http_method, url, params=query_params,
auth=self._auth, json=post_data,
headers={'User-Agent': USER_AGENT})
if isinstance(self._output_generator, str) and self._output_generator.lower() == "json":
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post(self, url, post_data, query_params=None):
"""Makes a POST request to the specified url endpoint. Args: url (string):
The url to the API without query p... |
if query_params is None:
query_params = {}
return self.execute_request(url, "POST", query_params, post_data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_ip_scope(auth, url, scopeid=None, ):
""" function requires no inputs and returns all IP address scopes currently configured on the HPE IMC server. If the... |
if scopeid is None:
get_ip_scope_url = "/imcrs/res/access/assignedIpScope"
else:
get_ip_scope_url = "/imcrs/res/access/assignedIpScope/ip?ipScopeId=" + str(scopeid)
f_url = url + get_ip_scope_url
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_database_connected(db):
""" A built-in check to see if connecting to the configured default database backend succeeds. It's automatically added to the ... |
from sqlalchemy.exc import DBAPIError, SQLAlchemyError
errors = []
try:
with db.engine.connect() as connection:
connection.execute('SELECT 1;')
except DBAPIError as e:
msg = 'DB-API error: {!s}'.format(e)
errors.append(Error(msg, id=health.ERROR_DB_API_EXCEPTION))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_migrations_applied(migrate):
""" A built-in check to see if all migrations have been applied correctly. It's automatically added to the list of Dockerf... |
errors = []
from alembic.migration import MigrationContext
from alembic.script import ScriptDirectory
from sqlalchemy.exc import DBAPIError, SQLAlchemyError
# pass in Migrate.directory here explicitly to be compatible with
# older versions of Flask-Migrate that required the directory to be pa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_redis_connected(client):
""" A built-in check to connect to Redis using the given client and see if it responds to the ``PING`` command. It's automatic... |
import redis
errors = []
try:
result = client.ping()
except redis.ConnectionError as e:
msg = 'Could not connect to redis: {!s}'.format(e)
errors.append(Error(msg, id=health.ERROR_CANNOT_CONNECT_REDIS))
except redis.RedisError as e:
errors.append(Error('Redis error:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def vfolders(access_key):
'''
List and manage virtual folders.
'''
fields = [
('Name', 'name'),
('Created At', 'created_at'),
('Last Used', 'last_used'),
('Max Files', 'max_files'),
('Max Size', 'max_size'),
]
if access_key is None:
q = 'query { vf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def config():
'''
Shows the current configuration.
'''
config = get_config()
print('Client version: {0}'.format(click.style(__version__, bold=True)))
print('API endpoint: {0}'.format(click.style(str(config.endpoint), bold=True)))
print('API version: {0}'.format(click.style(config.version, bo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def create(cls, name: str, default_for_unspecified: int, total_resource_slots: int, max_concurrent_sessions: int, max_containers_per_session: int, max_vfold... |
if fields is None:
fields = ('name',)
q = 'mutation($name: String!, $input: CreateKeyPairResourcePolicyInput!) {' \
+ \
' create_keypair_resource_policy(name: $name, props: $input) {' \
' ok msg resource_policy { $fields }' \
' }' \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| async def list(cls, fields: Iterable[str] = None) -> Sequence[dict]:
'''
Lists the keypair resource policies.
You need an admin privilege for this operation.
'''
if fields is None:
fields = (
'name', 'created_at',
'total_resource_slots'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def keypair():
'''
Show the server-side information of the currently configured access key.
'''
fields = [
('User ID', 'user_id'),
('Access Key', 'access_key'),
('Secret Key', 'secret_key'),
('Active?', 'is_active'),
('Admin?', 'is_admin'),
('Created At', ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add(user_id, resource_policy, admin, inactive, rate_limit):
'''
Add a new keypair.
USER_ID: User ID of a new key pair.
RESOURCE_POLICY: resource policy for new key pair.
'''
try:
user_id = int(user_id)
except ValueError:
pass # string-based user ID for Backend.AI v1.4+... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def update(access_key, resource_policy, is_admin, is_active, rate_limit):
'''
Update an existing keypair.
ACCESS_KEY: Access key of an existing key pair.
'''
with Session() as session:
try:
data = session.KeyPair.update(
access_key,
is_active=is_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(access_key):
""" Delete an existing keypair. ACCESSKEY: ACCESSKEY for a keypair to delete. """ |
with Session() as session:
try:
data = session.KeyPair.delete(access_key)
except Exception as e:
print_error(e)
sys.exit(1)
if not data['ok']:
print_fail('KeyPair deletion has failed: {0}'.format(data['msg']))
sys.exit(1)
p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self):
""" perform API auth test returning user and team """ |
log.debug('performing auth test')
test = self._get(urls['test'])
user = User({ 'name': test['user'], 'id': test['user_id'] })
self._refresh()
return test['team'], user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user(self, match):
""" Return User object for a given Slack ID or name """ |
if len(match) == 9 and match[0] == 'U':
return self._lookup(User, 'id', match)
return self._lookup(User, 'name', match) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channel(self, match):
""" Return Channel object for a given Slack ID or name """ |
if len(match) == 9 and match[0] in ('C','G','D'):
return self._lookup(Channel, 'id', match)
return self._lookup(Channel, 'name', match) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.