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 start_process(self, key):
"""Start a specific processes.""" |
if key in self.processes and key in self.paused:
os.killpg(os.getpgid(self.processes[key].pid), signal.SIGCONT)
self.queue[key]['status'] = 'running'
self.paused.remove(key)
return True
elif key not in self.processes:
if self.queue[key]['statu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pause_process(self, key):
"""Pause a specific processes.""" |
if key in self.processes and key not in self.paused:
os.killpg(os.getpgid(self.processes[key].pid), signal.SIGSTOP)
self.queue[key]['status'] = 'paused'
self.paused.append(key)
return 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 daemon_factory(path):
"""Create a closure which creates a running daemon. We need to create a closure that contains the correct path the daemon should be sta... |
def start_daemon():
root_dir = path
config_dir = os.path.join(root_dir, '.config/pueue')
try:
daemon = Daemon(root_dir=root_dir)
daemon.main()
except KeyboardInterrupt:
print('Keyboard interrupt. Shutting down')
daemon.stop_daemon()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Execute entry function.""" |
args = parser.parse_args()
args_dict = vars(args)
root_dir = args_dict['root'] if 'root' in args else None
# If a root directory is specified, get the absolute path and
# check if it exists. Abort if it doesn't exist!
if root_dir:
root_dir = os.path.abspath(root_dir)
if not os.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(host=DFLT_ADDRESS[0], port=DFLT_ADDRESS[1], signum=signal.SIGUSR1):
"""Register a pdb handler for signal 'signum'. The handler sets pdb to listen on... |
_pdbhandler._register(host, port, signum) |
<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_handler():
"""Return the handler as a named tuple. The named tuple attributes are 'host', 'port', 'signum'. Return None when no handler has been register... |
host, port, signum = _pdbhandler._registered()
if signum:
return Handler(host if host else DFLT_ADDRESS[0].encode(),
port if port else DFLT_ADDRESS[1], signum) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def wait(self, timeout):
'''Wait for the provided time to elapse'''
logger.debug('Waiting for %fs', timeout)
return self._event.wait(timeout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def delay(self):
'''How long to wait before the next check'''
if self._last_checked:
return self._interval - (time.time() - self._last_checked)
return self._interval |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def callback(self):
'''Run the callback'''
self._callback(*self._args, **self._kwargs)
self._last_checked = 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 run(self):
'''Run the callback periodically'''
while not self.wait(self.delay()):
try:
logger.info('Invoking callback %s', self.callback)
self.callback()
except StandardError:
logger.exception('Callback failed') |
<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, email=None, password=None, app_id=None, api_key=None):
"""Login to MediaFire account. Keyword arguments: email -- account email password -- accou... |
session_token = self.api.user_get_session_token(
app_id=app_id, email=email, password=password, api_key=api_key)
# install session token back into api client
self.api.session = session_token |
<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_resource_by_uri(self, uri):
"""Return resource described by MediaFire URI. uri -- MediaFire URI Examples: Folder (using folderkey):
mf:r5g3p2z0sqs3j mf:... |
location = self._parse_uri(uri)
if location.startswith("/"):
# Use path lookup only, root=myfiles
result = self.get_resource_by_path(location)
elif "/" in location:
# mf:abcdefjhijklm/name
resource_key, path = location.split('/', 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_resource_by_path(self, path, folder_key=None):
"""Return resource by remote path. path -- remote path Keyword arguments: folder_key -- what to use as the... |
logger.debug("resolving %s", path)
# remove empty path components
path = posixpath.normpath(path)
components = [t for t in path.split(posixpath.sep) if t != '']
if not components:
# request for root
return Folder(
self.api.folder_get_inf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _folder_get_content_iter(self, folder_key=None):
"""Iterator for api.folder_get_content""" |
lookup_params = [
{'content_type': 'folders', 'node': 'folders'},
{'content_type': 'files', 'node': 'files'}
]
for param in lookup_params:
more_chunks = True
chunk = 0
while more_chunks:
chunk += 1
con... |
<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_folder_contents_iter(self, uri):
"""Return iterator for directory contents. uri -- mediafire URI Example: for item in get_folder_contents_iter('mf:///Doc... |
resource = self.get_resource_by_uri(uri)
if not isinstance(resource, Folder):
raise NotAFolderError(uri)
folder_key = resource['folderkey']
for item in self._folder_get_content_iter(folder_key):
if 'filename' in item:
# Work around https://medi... |
<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_folder(self, uri, recursive=False):
"""Create folder. uri -- MediaFire URI Keyword arguments: recursive -- set to True to create intermediate folders.... |
logger.info("Creating %s", uri)
# check that folder exists already
try:
resource = self.get_resource_by_uri(uri)
if isinstance(resource, Folder):
return resource
else:
raise NotAFolderError(uri)
except ResourceNotFoun... |
<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_folder(self, uri, purge=False):
"""Delete folder. uri -- MediaFire folder URI Keyword arguments: purge -- delete the folder without sending it to Tras... |
try:
resource = self.get_resource_by_uri(uri)
except ResourceNotFoundError:
# Nothing to remove
return None
if not isinstance(resource, Folder):
raise ValueError("Folder expected, got {}".format(type(resource)))
if purge:
fu... |
<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_file(self, uri, purge=False):
"""Delete file. uri -- MediaFire file URI Keyword arguments: purge -- delete the file without sending it to Trash. """ |
try:
resource = self.get_resource_by_uri(uri)
except ResourceNotFoundError:
# Nothing to remove
return None
if not isinstance(resource, File):
raise ValueError("File expected, got {}".format(type(resource)))
if purge:
func = ... |
<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_resource(self, uri, purge=False):
"""Delete file or folder uri -- mediafire URI Keyword arguments: purge -- delete the resource without sending it to ... |
try:
resource = self.get_resource_by_uri(uri)
except ResourceNotFoundError:
# Nothing to remove
return None
if isinstance(resource, File):
result = self.delete_file(uri, purge)
elif isinstance(resource, Folder):
result = self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_upload_info(self, source, dest_uri):
"""Prepare Upload object, resolve paths""" |
try:
dest_resource = self.get_resource_by_uri(dest_uri)
except ResourceNotFoundError:
dest_resource = None
is_fh = hasattr(source, 'read')
folder_key = None
name = None
if dest_resource:
if isinstance(dest_resource, File):
... |
<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_file(self, source, dest_uri):
"""Upload file to MediaFire. source -- path to the file or a file-like object (e.g. io.BytesIO) dest_uri -- MediaFire Re... |
folder_key, name = self._prepare_upload_info(source, dest_uri)
is_fh = hasattr(source, 'read')
fd = None
try:
if is_fh:
# Re-using filehandle
fd = source
else:
# Handling fs open/close
fd = open(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 download_file(self, src_uri, target):
"""Download file from MediaFire. src_uri -- MediaFire file URI to download target -- download path or file-like object ... |
resource = self.get_resource_by_uri(src_uri)
if not isinstance(resource, File):
raise MediaFireError("Only files can be downloaded")
quick_key = resource['quickkey']
result = self.api.file_get_links(quick_key=quick_key,
link_type='di... |
<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_file_metadata(self, uri, filename=None, description=None, mtime=None, privacy=None):
"""Update file metadata. uri -- MediaFire file URI Supplying the ... |
resource = self.get_resource_by_uri(uri)
if not isinstance(resource, File):
raise ValueError('Expected File, got {}'.format(type(resource)))
result = self.api.file_update(resource['quickkey'], filename=filename,
description=description,
... |
<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_folder_metadata(self, uri, foldername=None, description=None, mtime=None, privacy=None, privacy_recursive=None):
"""Update folder metadata. uri -- Med... |
resource = self.get_resource_by_uri(uri)
if not isinstance(resource, Folder):
raise ValueError('Expected Folder, got {}'.format(type(resource)))
result = self.api.folder_update(resource['folderkey'],
foldername=foldername,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_uri(uri):
"""Parse and validate MediaFire URI.""" |
tokens = urlparse(uri)
if tokens.netloc != '':
logger.error("Invalid URI: %s", uri)
raise ValueError("MediaFire URI format error: "
"host should be empty - mf:///path")
if tokens.scheme != '' and tokens.scheme != URI_SCHEME:
ra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def merged(self):
'''The clean stats from all the hosts reporting to this host.'''
stats = {}
for topic in self.client.topics()['topics']:
for producer in self.client.lookup(topic)['producers']:
hostname = producer['broadcast_address']
port = producer[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def stats(self):
'''Stats that have been aggregated appropriately.'''
data = Counter()
for name, value, aggregated in self.raw:
if aggregated:
data['%s.max' % name] = max(data['%s.max' % name], value)
data['%s.total' % name] += value
else:
... |
<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_curline():
"""Return the current python source line.""" |
if Frame:
frame = Frame.get_selected_python_frame()
if frame:
line = ''
f = frame.get_pyop()
if f and not f.is_optimized_out():
cwd = os.path.join(os.getcwd(), '')
fname = f.filename()
if cwd in fname:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reconnected(self, conn):
'''Subscribe connection and manipulate its RDY state'''
conn.sub(self._topic, self._channel)
conn.rdy(1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def distribute_ready(self):
'''Distribute the ready state across all of the connections'''
connections = [c for c in self.connections() if c.alive()]
if len(connections) > self._max_in_flight:
raise NotImplementedError(
'Max in flight must be greater than number of co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def needs_distribute_ready(self):
'''Determine whether or not we need to redistribute the ready state'''
# Try to pre-empty starvation by comparing current RDY against
# the last value sent.
alive = [c for c in self.connections() if c.alive()]
if any(c.ready <= (c.last_ready_sent... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def read(self):
'''Read some number of messages'''
found = Client.read(self)
# Redistribute our ready state if necessary
if self.needs_distribute_ready():
self.distribute_ready()
# Finally, return all the results we've read
return found |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def profiler():
'''Profile the block'''
import cProfile
import pstats
pr = cProfile.Profile()
pr.enable()
yield
pr.disable()
ps = pstats.Stats(pr).sort_stats('tottime')
ps.print_stats() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def messages(count, size):
'''Generator for count messages of the provided size'''
import string
# Make sure we have at least 'size' letters
letters = islice(cycle(chain(string.lowercase, string.uppercase)), size)
return islice(cycle(''.join(l) for l in permutations(letters, size)), count) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def stats():
'''Read a stream of floats and give summary statistics'''
import re
import sys
import math
values = []
for line in sys.stdin:
values.extend(map(float, re.findall(r'\d+\.?\d+', line)))
mean = sum(values) / len(values)
variance = sum((val - mean) ** 2 for val in value... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def ready(self):
'''Whether or not enough time has passed since the last failure'''
if self._last_failed:
delta = time.time() - self._last_failed
return delta >= self.backoff()
return 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 execute_log(args, root_dir):
"""Print the current log file. Args: args['keys'] (int):
If given, we only look at the specified processes. root_dir (string):
... |
# Print the logs of all specified processes
if args.get('keys'):
config_dir = os.path.join(root_dir, '.config/pueue')
queue_path = os.path.join(config_dir, 'queue')
if os.path.exists(queue_path):
queue_file = open(queue_path, 'rb')
try:
queue = pi... |
<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_show(args, root_dir):
"""Print stderr and stdout of the current running process. Args: args['watch'] (bool):
If True, we open a curses session and t... |
key = None
if args.get('key'):
key = args['key']
status = command_factory('status')({}, root_dir=root_dir)
if key not in status['data'] or status['data'][key]['status'] != 'running':
print('No running process with this key, use `log` to show finished processes.')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fetch_track(self, track_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches a song track by given ID.
:param track_id: the track ID.
:type track_id: str
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.1/reference#tracks-track_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 show(self, user, feed, id):
""" Show a specific indicator by id :param user: feed username :param feed: feed name :param id: indicator endpoint id [INT] :ret... |
uri = '/users/{}/feeds/{}/indicators/{}'.format(user, feed, id)
return self.client.get(uri) |
<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(self):
""" Submit action on the Indicator object :return: Indicator Object """ |
uri = '/users/{0}/feeds/{1}/indicators'\
.format(self.user, self.feed)
data = {
"indicator": json.loads(str(self.indicator)),
"comment": self.comment,
"content": self.content
}
if self.attachment:
attachment = self._file_to_a... |
<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_bulk(self, indicators, user, feed):
from .constants import API_VERSION if API_VERSION == '1': print("create_bulk currently un-avail with APIv1") raise... |
uri = '/users/{0}/feeds/{1}/indicators_bulk'.format(user, feed)
data = {
'indicators': [
{
'indicator': i.args.indicator,
'feed_id': i.args.feed,
'tag_list': i.args.tags,
"description": i.args.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_keystring(conn, key_string):
""" A utility function to turn strings like 'Mod1+Mod4+a' into a pair corresponding to its modifiers and keycode. :param k... |
# FIXME this code is temporary hack, requires better abstraction
from PyQt5.QtGui import QKeySequence
from PyQt5.QtCore import Qt
from .qt_keycodes import KeyTbl, ModsTbl
keysequence = QKeySequence(key_string)
ks = keysequence[0]
# Calculate the modifiers
mods = Qt.NoModifier
qtmo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_string(conn, kstr):
""" Finds the keycode associated with a string representation of a keysym. :param kstr: English representation of a keysym. :retur... |
if kstr in keysyms:
return get_keycode(conn, keysyms[kstr])
elif len(kstr) > 1 and kstr.capitalize() in keysyms:
return get_keycode(conn, keysyms[kstr.capitalize()])
return None |
<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_keyboard_mapping(conn):
""" Return a keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environment. :rtype: xcb.xpr... |
mn, mx = get_min_max_keycode(conn)
return conn.core.GetKeyboardMapping(mn, mx - mn + 1) |
<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_keyboard_mapping_unchecked(conn):
""" Return an unchecked keyboard mapping cookie that can be used to fetch the table of keysyms in the current X environ... |
mn, mx = get_min_max_keycode()
return conn.core.GetKeyboardMappingUnchecked(mn, mx - mn + 1) |
<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_keycode(conn, keysym):
""" Given a keysym, find the keycode mapped to it in the current X environment. It is necessary to search the keysym table in orde... |
mn, mx = get_min_max_keycode(conn)
cols = __kbmap.keysyms_per_keycode
for i in range(mn, mx + 1):
for j in range(0, cols):
ks = get_keysym(conn, i, col=j)
if ks == keysym:
return i
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ungrab_key(conn, wid, modifiers, key):
""" Ungrabs a key that was grabbed by ``grab_key``. Similarly, it will return True on success and False on failure. Wh... |
try:
for mod in TRIVIAL_MODS:
conn.core.UngrabKeyChecked(key, wid, modifiers | mod).check()
return True
except xproto.BadAccess:
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 update_keyboard_mapping(conn, e):
""" Whenever the keyboard mapping is changed, this function needs to be called to update xpybutil's internal representing o... |
global __kbmap, __keysmods
newmap = get_keyboard_mapping(conn).reply()
if e is None:
__kbmap = newmap
__keysmods = get_keys_to_mods(conn)
return
if e.request == xproto.Mapping.Keyboard:
changes = {}
for kc in range(*get_min_max_keycode(conn)):
knew... |
<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_storages(self, storage_type='normal'):
""" Return a list of Storage objects from the API. Storage types: public, private, normal, backup, cdrom, template... |
res = self.get_request('/storage/' + storage_type)
return Storage._create_storage_objs(res['storages'], cloud_manager=self) |
<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_storage(self, storage):
""" Return a Storage object from the API. """ |
res = self.get_request('/storage/' + str(storage))
return Storage(cloud_manager=self, **res['storage']) |
<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_storage(self, size=10, tier='maxiops', title='Storage disk', zone='fi-hel1', backup_rule={}):
""" Create a Storage object. Returns an object based on ... |
body = {
'storage': {
'size': size,
'tier': tier,
'title': title,
'zone': zone,
'backup_rule': backup_rule
}
}
res = self.post_request('/storage', body)
return Storage(cloud_manager=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 modify_storage(self, storage, size, title, backup_rule={}):
""" Modify a Storage object. Returns an object based on the API's response. """ |
res = self._modify_storage(str(storage), size, title, backup_rule)
return Storage(cloud_manager=self, **res['storage']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attach_storage(self, server, storage, storage_type, address):
""" Attach a Storage object to a Server. Return a list of the server's storages. """ |
body = {'storage_device': {}}
if storage:
body['storage_device']['storage'] = str(storage)
if storage_type:
body['storage_device']['type'] = storage_type
if address:
body['storage_device']['address'] = address
url = '/server/{0}/storage/att... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detach_storage(self, server, address):
""" Detach a Storage object to a Server. Return a list of the server's storages. """ |
body = {'storage_device': {'address': address}}
url = '/server/{0}/storage/detach'.format(server)
res = self.post_request(url, body)
return Storage._create_storage_objs(res['server']['storage_devices'], cloud_manager=self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reset(self, **kwargs):
""" Reset after repopulating from API. """ |
# there are some inconsistenciens in the API regarding these
# note: this could be written in fancier ways, but this way is simpler
if 'uuid' in kwargs:
self.uuid = kwargs['uuid']
elif 'storage' in kwargs: # let's never use storage.storage internally
self.uuid... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fetch_album(self, album_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches an album by given ID.
:param album_id: the album ID.
:type album_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
See `https://docs-en.kkbox.codes/v1.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup(self):
""" Prints name, author, size and age """ |
print "%s by %s, size: %s, uploaded %s ago" % (self.name, self.author,
self.size, self.age) |
<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_max_page(self, url):
""" Open url and return amount of pages """ |
html = requests.get(url).text
pq = PyQuery(html)
try:
tds = int(pq("h2").text().split()[-1])
if tds % 25:
return tds / 25 + 1
return tds / 25
except ValueError:
raise ValueError("No results found!") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(self, update=True):
""" Build and return url. Also update max_page. """ |
ret = self.base + self.query
page = "".join(("/", str(self.page), "/"))
if self.category:
category = " category:" + self.category
else:
category = ""
if self.order:
order = "".join(("?field=", self.order[0], "&sorder=", self.order[1]))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(self, update=True):
""" Build and return url. Also update max_page. URL structure for user torrent lists differs from other result lists as the page nu... |
query_str = "?page={}".format(self.page)
if self.order:
query_str += "".join(("&field=", self.order[0], "&sorder=",self.order[1]))
ret = "".join((self.base, self.user, "/uploads/", query_str))
if update:
self.max_page = self._get_max_page(ret)
return re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _items(self):
""" Parse url and yield namedtuple Torrent for every torrent on page """ |
torrents = map(self._get_torrent, self._get_rows())
for t in torrents:
yield t |
<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_torrent(self, row):
""" Parse row into namedtuple """ |
td = row("td")
name = td("a.cellMainLink").text()
name = name.replace(" . ", ".").replace(" .", ".")
author = td("a.plain").text()
verified_author = True if td(".lightgrey>.ka-verify") else False
category = td("span").find("strong").find("a").eq(0).text()
verifie... |
<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_rows(self):
""" Return all rows on page """ |
html = requests.get(self.url.build()).text
if re.search('did not match any documents', html):
return []
pq = PyQuery(html)
rows = pq("table.data").find("tr")
return map(rows.eq, range(rows.size()))[1:] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pages(self, page_from, page_to):
""" Yield torrents in range from page_from to page_to """ |
if not all([page_from < self.url.max_page, page_from > 0,
page_to <= self.url.max_page, page_to > page_from]):
raise IndexError("Invalid page numbers")
size = (page_to + 1) - page_from
threads = ret = []
page_list = range(page_from, page_to+1)
l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self):
""" Yield torrents in range from current page to last page """ |
return self.pages(self.url.page, self.url.max_page) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def order(self, field, order=None):
""" Set field and order set by arguments """ |
if not order:
order = ORDER.DESC
self.url.order = (field, order)
self.url.set_page(1)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def category(self, category):
""" Change category of current search and return self """ |
self.url.category = category
self.url.set_page(1)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def destroy(self):
""" Remove this FirewallRule from the API. This instance must be associated with a server for this method to work, which is done by instantiat... |
if not hasattr(self, 'server') or not self.server:
raise Exception(
"""FirewallRule not associated with server;
please use or server.get_firewall_rules() to get objects
that are associated with a server.
""")
return self.server... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fetch_new_release_category(self, category_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetches new release categories by given ID.
:param category_id: the station ID.
:type category_id: str
:param terr: the current territory.
:return: API response.
:rtype: 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 fetch_top_tracks_of_artist(self, artist_id, terr=KKBOXTerritory.TAIWAN):
'''
Fetcher top tracks belong to an artist by given ID.
:param artist_id: the artist ID.
:type artist_id: str
:param terr: the current territory.
:return: API response.
:rtype: dict
... |
<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_tags(self):
"""List all tags as Tag objects.""" |
res = self.get_request('/tag')
return [Tag(cloud_manager=self, **tag) for tag in res['tags']['tag']] |
<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_tag(self, name):
"""Return the tag as Tag object.""" |
res = self.get_request('/tag/' + name)
return Tag(cloud_manager=self, **res['tag']) |
<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_tag(self, name, description=None, servers=[]):
""" Create a new Tag. Only name is mandatory. Returns the created Tag object. """ |
servers = [str(server) for server in servers]
body = {'tag': Tag(name, description, servers).to_dict()}
res = self.request('POST', '/tag', body)
return Tag(cloud_manager=self, **res['tag']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_tags(self, server, tags):
""" Remove tags from a server. - server: Server object or UUID string - tags: list of Tag objects or strings """ |
uuid = str(server)
tags = [str(tag) for tag in tags]
url = '/server/{0}/untag/{1}'.format(uuid, ','.join(tags))
return self.post_request(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assignIfExists(opts, default=None, **kwargs):
""" Helper for assigning object attributes from API responses. """ |
for opt in opts:
if(opt in kwargs):
return kwargs[opt]
return default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def expand(self, info=b"", length=32):
'''
Generate output key material based on an `info` value
Arguments:
- info - context to generate the OKM
- length - length in bytes of the key to generate
See the HKDF draft RFC for guidance.
'''
return hkdf_expand(self._prk, info, length, self._hash) |
<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_user_block(username, ssh_keys, create_password=True):
""" Helper function for creating Server.login_user blocks. (see: https://www.upcloud.com/api/8-se... |
block = {
'create_password': 'yes' if create_password is True else 'no',
'ssh_keys': {
'ssh_key': ssh_keys
}
}
if username:
block['username'] = username
return block |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reset(self, server, **kwargs):
""" Reset the server object with new values given as params. - server: a dict representing the server. e.g the API response. ... |
if server:
# handle storage, ip_address dicts and tags if they exist
Server._handle_server_subobjs(server, kwargs.get('cloud_manager'))
for key in server:
object.__setattr__(self, key, server[key])
for key in kwargs:
object.__setattr__(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 populate(self):
""" Sync changes from the API to the local object. Note: syncs ip_addresses and storage_devices too (/server/uuid endpoint) """ |
server, IPAddresses, storages = self.cloud_manager.get_server_data(self.uuid)
self._reset(
server,
ip_addresses=IPAddresses,
storage_devices=storages,
populated=True
)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
""" Sync local changes in server's attributes to the API. Note: DOES NOT sync IPAddresses and storage_devices, use add_ip, add_storage, remove_ip... |
# dict comprehension that also works with 2.6
# http://stackoverflow.com/questions/21069668/alternative-to-dict-comprehension-prior-to-python-2-7
kwargs = dict(
(field, getattr(self, field))
for field in self.updateable_fields
if hasattr(self, field)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restart(self, hard=False, timeout=30, force=True):
""" Restart the server. By default, issue a soft restart with a timeout of 30s and a hard restart after th... |
body = dict()
body['restart_server'] = {
'stop_type': 'hard' if hard else 'soft',
'timeout': '{0}'.format(timeout),
'timeout_action': 'destroy' if force else 'ignore'
}
path = '/server/{0}/restart'.format(self.uuid)
self.cloud_manager.post_re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_ip(self, IPAddress):
""" Release the specified IP-address from the server. """ |
self.cloud_manager.release_ip(IPAddress.address)
self.ip_addresses.remove(IPAddress) |
<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_storage(self, storage=None, type='disk', address=None):
""" Attach the given storage to the Server. Default address is next available. """ |
self.cloud_manager.attach_storage(server=self.uuid,
storage=storage.uuid,
storage_type=type,
address=address)
storage.address = address
storage.type = type
self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_storage(self, storage):
""" Remove Storage from a Server. The Storage must be a reference to an object in Server.storage_devices or the method will th... |
if not hasattr(storage, 'address'):
raise Exception(
('Storage does not have an address. '
'Access the Storage via Server.storage_devices '
'so they include an address. '
'(This is due how the API handles Storages)')
)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_firewall(self, FirewallRules):
""" Helper function for automatically adding several FirewallRules in series. """ |
firewall_rule_bodies = [
FirewallRule.to_dict()
for FirewallRule in FirewallRules
]
return self.cloud_manager.configure_firewall(self, firewall_rule_bodies) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_post_body(self):
""" Prepare a JSON serializable dict from a Server instance with nested. Storage instances. """ |
body = dict()
# mandatory
body['server'] = {
'hostname': self.hostname,
'zone': self.zone,
'title': self.title,
'storage_devices': {}
}
# optional fields
for optional_field in self.optional_fields:
if hasattr(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self):
""" Prepare a JSON serializable dict for read-only purposes. Includes storages and IP-addresses. Use prepare_post_body for POST and .save() fo... |
fields = dict(vars(self).items())
if self.populated:
fields['ip_addresses'] = []
fields['storage_devices'] = []
for ip in self.ip_addresses:
fields['ip_addresses'].append({
'address': ip.address,
'access': ip.a... |
<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(self, access='public', addr_family=None, strict=None):
""" Return the server's IP address. Params: - addr_family: IPv4, IPv6 or None. None prefers IPv... |
if addr_family not in ['IPv4', 'IPv6', None]:
raise Exception("`addr_family` must be 'IPv4', 'IPv6' or None")
if access not in ['private', 'public']:
raise Exception("`access` must be 'public' or 'private'")
if not hasattr(self, 'ip_addresses'):
self.popula... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wait_for_state_change(self, target_states, update_interval=10):
""" Blocking wait until target_state reached. update_interval is in seconds. Warning: state ... |
while self.state not in target_states:
if self.state == 'error':
raise Exception('server is in error state')
# update server state every 10s
sleep(update_interval)
self.populate() |
<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_and_destroy(self, sync=True):
""" Destroy a server and its storages. Stops the server before destroying. Syncs the server state from the API, use sync=F... |
def _self_destruct():
"""destroy the server and all storages attached to it."""
# try_it_n_times util is used as a convenience because
# Servers and Storages can fluctuate between "maintenance" and their
# original state due to several different reasons especial... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revert(self):
"""Revert the state to the version stored on disc.""" |
if self.filepath:
if path.isfile(self.filepath):
serialised_file = open(self.filepath, "r")
try:
self.state = json.load(serialised_file)
except ValueError:
print("No JSON information could be read from the persi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync(self):
"""Synchronise and update the stored state to the in-memory state.""" |
if self.filepath:
serialised_file = open(self.filepath, "w")
json.dump(self.state, serialised_file)
serialised_file.close()
else:
print("Filepath to the persistence file is not set. State cannot be synced to disc.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _require_bucket(self, bucket_name):
""" Also try to create the bucket. """ |
if not self.exists(bucket_name) and not self.claim_bucket(bucket_name):
raise OFSException("Invalid bucket: %s" % bucket_name)
return self._get_bucket(bucket_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_stream(self, bucket, label):
""" Will fail if the bucket or label don't exist """ |
bucket = self._require_bucket(bucket)
key = self._require_key(bucket, label)
key.delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def authenticate_request(self, method, bucket='', key='', headers=None):
'''Authenticate a HTTP request by filling in Authorization field header.
:param method: HTTP method (e.g. GET, PUT, POST)
:param bucket: name of the bucket.
:param key: name of key within bucket.
:param 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 get_resources_to_check(client_site_url, apikey):
"""Return a list of resource IDs to check for broken links. Calls the client site's API to get a list of res... |
url = client_site_url + u"deadoralive/get_resources_to_check"
response = requests.get(url, headers=dict(Authorization=apikey))
if not response.ok:
raise CouldNotGetResourceIDsError(
u"Couldn't get resource IDs to check: {code} {reason}".format(
code=response.status_code,... |
<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_url_for_id(client_site_url, apikey, resource_id):
"""Return the URL for the given resource ID. Contacts the client site's API to get the URL for the ID a... |
# TODO: Handle invalid responses from the client site.
url = client_site_url + u"deadoralive/get_url_for_resource_id"
params = {"resource_id": resource_id}
response = requests.get(url, headers=dict(Authorization=apikey),
params=params)
if not response.ok:
raise C... |
<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_url(url):
"""Check whether the given URL is dead or alive. Returns a dict with four keys: "url": The URL that was checked (string) "alive": Whether the... |
result = {"url": url}
try:
response = requests.get(url)
result["status"] = response.status_code
result["reason"] = response.reason
response.raise_for_status() # Raise if status_code is not OK.
result["alive"] = True
except AttributeError as err:
if err.messa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upsert_result(client_site_url, apikey, resource_id, result):
"""Post the given link check result to the client site.""" |
# TODO: Handle exceptions and unexpected results.
url = client_site_url + u"deadoralive/upsert"
params = result.copy()
params["resource_id"] = resource_id
requests.post(url, headers=dict(Authorization=apikey), params=params) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.