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 list_dscp_marking_rules(self, policy_id, retrieve_all=True, **_params):
"""Fetches a list of all DSCP marking rules for the given policy.""" |
return self.list('dscp_marking_rules',
self.qos_dscp_marking_rules_path % policy_id,
retrieve_all, **_params) |
<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_dscp_marking_rule(self, rule, policy, body=None):
"""Shows information of a certain DSCP marking rule.""" |
return self.get(self.qos_dscp_marking_rule_path %
(policy, rule), body=body) |
<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_dscp_marking_rule(self, policy, body=None):
"""Creates a new DSCP marking rule.""" |
return self.post(self.qos_dscp_marking_rules_path % policy,
body=body) |
<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_dscp_marking_rule(self, rule, policy, body=None):
"""Updates a DSCP marking rule.""" |
return self.put(self.qos_dscp_marking_rule_path %
(policy, rule), body=body) |
<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_dscp_marking_rule(self, rule, policy):
"""Deletes a DSCP marking rule.""" |
return self.delete(self.qos_dscp_marking_rule_path %
(policy, rule)) |
<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_flavors(self, retrieve_all=True, **_params):
"""Fetches a list of all Neutron service flavors for a project.""" |
return self.list('flavors', self.flavors_path, retrieve_all,
**_params) |
<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_flavor(self, flavor, **_params):
"""Fetches information for a certain Neutron service flavor.""" |
return self.get(self.flavor_path % (flavor), params=_params) |
<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_flavor(self, flavor, body):
"""Update a Neutron service flavor.""" |
return self.put(self.flavor_path % (flavor), body=body) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def associate_flavor(self, flavor, body):
"""Associate a Neutron service flavor with a profile.""" |
return self.post(self.flavor_profile_bindings_path %
(flavor), body=body) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disassociate_flavor(self, flavor, flavor_profile):
"""Disassociate a Neutron service flavor with a profile.""" |
return self.delete(self.flavor_profile_binding_path %
(flavor, flavor_profile)) |
<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_service_profiles(self, retrieve_all=True, **_params):
"""Fetches a list of all Neutron service flavor profiles.""" |
return self.list('service_profiles', self.service_profiles_path,
retrieve_all, **_params) |
<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_service_profile(self, flavor_profile, **_params):
"""Fetches information for a certain Neutron service flavor profile.""" |
return self.get(self.service_profile_path % (flavor_profile),
params=_params) |
<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_service_profile(self, service_profile, body):
"""Update a Neutron service profile.""" |
return self.put(self.service_profile_path % (service_profile),
body=body) |
<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_availability_zones(self, retrieve_all=True, **_params):
"""Fetches a list of all availability zones.""" |
return self.list('availability_zones', self.availability_zones_path,
retrieve_all, **_params) |
<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_auto_allocated_topology(self, project_id, **_params):
"""Fetch information about a project's auto-allocated topology.""" |
return self.get(
self.auto_allocated_topology_path % project_id,
params=_params) |
<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_bgp_speakers(self, retrieve_all=True, **_params):
"""Fetches a list of all BGP speakers for a project.""" |
return self.list('bgp_speakers', self.bgp_speakers_path, retrieve_all,
**_params) |
<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_bgp_speaker(self, bgp_speaker_id, **_params):
"""Fetches information of a certain BGP speaker.""" |
return self.get(self.bgp_speaker_path % (bgp_speaker_id),
params=_params) |
<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_bgp_speaker(self, bgp_speaker_id, body=None):
"""Update a BGP speaker.""" |
return self.put(self.bgp_speaker_path % bgp_speaker_id, body=body) |
<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_peer_to_bgp_speaker(self, speaker_id, body=None):
"""Adds a peer to BGP speaker.""" |
return self.put((self.bgp_speaker_path % speaker_id) +
"/add_bgp_peer", body=body) |
<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_peer_from_bgp_speaker(self, speaker_id, body=None):
"""Removes a peer from BGP speaker.""" |
return self.put((self.bgp_speaker_path % speaker_id) +
"/remove_bgp_peer", body=body) |
<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_network_to_bgp_speaker(self, speaker_id, body=None):
"""Adds a network to BGP speaker.""" |
return self.put((self.bgp_speaker_path % speaker_id) +
"/add_gateway_network", body=body) |
<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_network_from_bgp_speaker(self, speaker_id, body=None):
"""Removes a network from BGP speaker.""" |
return self.put((self.bgp_speaker_path % speaker_id) +
"/remove_gateway_network", body=body) |
<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_route_advertised_from_bgp_speaker(self, speaker_id, **_params):
"""Fetches a list of all routes advertised by BGP speaker.""" |
return self.get((self.bgp_speaker_path % speaker_id) +
"/get_advertised_routes", params=_params) |
<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_bgp_peer(self, peer_id, **_params):
"""Fetches information of a certain BGP peer.""" |
return self.get(self.bgp_peer_path % peer_id,
params=_params) |
<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_bgp_peer(self, bgp_peer_id, body=None):
"""Update a BGP peer.""" |
return self.put(self.bgp_peer_path % bgp_peer_id, body=body) |
<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_network_ip_availabilities(self, retrieve_all=True, **_params):
"""Fetches IP availibility information for all networks""" |
return self.list('network_ip_availabilities',
self.network_ip_availabilities_path,
retrieve_all, **_params) |
<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_network_ip_availability(self, network, **_params):
"""Fetches IP availability information for a specified network""" |
return self.get(self.network_ip_availability_path % (network),
params=_params) |
<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_tag(self, resource_type, resource_id, tag, **_params):
"""Add a tag on the resource.""" |
return self.put(self.tag_path % (resource_type, resource_id, 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 replace_tag(self, resource_type, resource_id, body, **_params):
"""Replace tags on the resource.""" |
return self.put(self.tags_path % (resource_type, resource_id), body) |
<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_tag(self, resource_type, resource_id, tag, **_params):
"""Remove a tag on the resource.""" |
return self.delete(self.tag_path % (resource_type, resource_id, 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_tag_all(self, resource_type, resource_id, **_params):
"""Remove all tags on the resource.""" |
return self.delete(self.tags_path % (resource_type, resource_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 shorten_url(url, length=32, strip_www=True, strip_path=True, ellipsis=False):
""" Shorten a URL by chopping out the middle. For example if supplied with http... |
if '://' not in url:
# Ensure we have a protocol
url = 'http://%s' % url
parsed_url = urlparse(url)
ext = tldextract.extract(parsed_url.netloc)
if ext.subdomain and (not strip_www or (strip_www and ext.subdomain != 'www')):
shortened = u'%s.%s' % (ext.subdomain, ext.domain)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def netloc_no_www(url):
""" For a given URL return the netloc with any www. striped. """ |
ext = tldextract.extract(url)
if ext.subdomain and ext.subdomain != 'www':
return '%s.%s.%s' % (ext.subdomain, ext.domain, ext.tld)
else:
return '%s.%s' % (ext.domain, ext.tld) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deferToGreenletPool(*args, **kwargs):
"""Call function using a greenlet from the given pool and return the result as a Deferred""" |
reactor = args[0]
pool = args[1]
func = args[2]
d = defer.Deferred()
def task():
try:
reactor.callFromGreenlet(d.callback, func(*args[3:], **kwargs))
except:
reactor.callFromGreenlet(d.errback, failure.Failure())
pool.add(spawn(task))
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deferToGreenlet(*args, **kwargs):
"""Call function using a greenlet and return the result as a Deferred""" |
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
return deferToGreenletPool(reactor, reactor.getGreenletPool(), *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def callMultipleInGreenlet(tupleList):
"""Call a list of functions in the same thread""" |
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
reactor.callInGreenlet(_runMultiple, tupleList) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def waitForGreenlet(g):
"""Link greenlet completion to Deferred""" |
from twisted.internet import reactor
assert reactor.greenlet == getcurrent(), "must invoke this in the reactor greenlet"
d = defer.Deferred()
def cb(g):
try:
d.callback(g.get())
except:
d.errback(failure.Failure())
g.link(d)
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def waitForDeferred(d, result=None):
"""Block current greenlet for Deferred, waiting until result is not a Deferred or a failure is encountered""" |
from twisted.internet import reactor
assert reactor.greenlet != getcurrent(), "can't invoke this in the reactor greenlet"
if result is None:
result = AsyncResult()
def cb(res):
if isinstance(res, defer.Deferred):
waitForDeferred(res, result)
else:
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 blockingCallFromGreenlet(*args, **kwargs):
"""Call function in reactor greenlet and block current greenlet waiting for the result""" |
reactor = args[0]
assert reactor.greenlet != getcurrent(), "can't invoke this in the reactor greenlet"
func = args[1]
result = AsyncResult()
def task():
try:
result.set(func(*args[2:], **kwargs))
except Exception, ex:
result.set_exception(ex)
reactor.ca... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mainLoop(self):
"""This main loop yields to gevent until the end, handling function calls along the way.""" |
self.greenlet = gevent.getcurrent()
callqueue = self._callqueue
seconds = self.seconds
try:
while 1:
self._wait = 0
now = seconds()
if len(callqueue) > 0:
self._wake = delay = callqueue[0].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 removeReader(self, selectable):
"""Remove a FileDescriptor for notification of data available to read.""" |
try:
if selectable.disconnected:
self._reads[selectable].kill(block=False)
del self._reads[selectable]
else:
self._reads[selectable].pause()
except KeyError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeWriter(self, selectable):
"""Remove a FileDescriptor for notification of data available to write.""" |
try:
if selectable.disconnected:
self._writes[selectable].kill(block=False)
del self._writes[selectable]
else:
self._writes[selectable].pause()
except KeyError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(track_url):
""" Resolves the URL to an actual track from the SoundCloud API. If the track resolves to more than one possible track, it takes the firs... |
try:
path = urlparse.urlparse(track_url).path
tracks = client.get('/tracks', q=path)
if tracks:
return tracks[0]
else:
raise ValueError('Track not found for URL {}'.format(track_url))
except Exception as e:
raise ValueError('Error obtaining track... |
<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(url, target_file, chunk_size=4096):
""" Simple requests downloader """ |
r = requests.get(url, stream=True)
with open(target_file, 'w+') as out:
# And this is why I love Armin Ronacher:
with click.progressbar(r.iter_content(chunk_size=chunk_size),
int(r.headers['Content-Length'])/chunk_size,
label='Downl... |
<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_metadata(track_file, track_data):
""" Adds artist and title from the track data, and downloads the cover and embeds it in the MP3 tags. """ |
# This needs some exception handling!
# We don't always know what type the cover is!
mp3 = mutagen.mp3.MP3(track_file)
mp3['TPE1'] = mutagen.id3.TPE1(encoding=3, text=track_data.user['username'])
mp3['TIT2'] = mutagen.id3.TIT2(encoding=3, text=track_data.title)
cover_bytes = requests.get(trac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def linreg_ridge_gd(y, X, lam, algorithm='L-BFGS-B', debug=False):
"""Ridge Regression with Gradient Optimization methods Parameters: y : ndarray target variable... |
import numpy as np
import scipy.optimize as sopt
def objective_pssr(theta, y, X, lam):
return np.sum((y - np.dot(X, theta))**2) + lam * np.sum(theta**2)
def gradient_pssr(theta, y, X, lam):
return -2.0 * np.dot(X.T, (y - np.dot(X, theta))) + 2.0 * lam * theta
# check eligible alg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def triangulize(image, tile_size):
"""Processes the given image by breaking it down into tiles of the given size and applying a triangular effect to each tile. R... |
if isinstance(image, basestring) or hasattr(image, 'read'):
image = Image.open(image)
assert isinstance(tile_size, int)
# Make sure we have a usable tile size, by guessing based on image size
# and making sure it's a multiple of two.
if tile_size == 0:
tile_size = guess_tile_size(i... |
<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_tile(tile_x, tile_y, tile_size, pix, draw, image):
"""Process a tile whose top left corner is at the given x and y coordinates. """ |
logging.debug('Processing tile (%d, %d)', tile_x, tile_y)
# Calculate average color for each "triangle" in the given tile
n, e, s, w = triangle_colors(tile_x, tile_y, tile_size, pix)
# Calculate distance between triangle pairs
d_ne = get_color_dist(n, e)
d_nw = get_color_dist(n, w)
d_se =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_triangles(tile_x, tile_y, tile_size, split, top_color, bottom_color, draw):
"""Draws a triangle on each half of the tile with the given coordinates and ... |
assert split in ('right', 'left')
# The four corners of this tile
nw = (tile_x, tile_y)
ne = (tile_x + tile_size - 1, tile_y)
se = (tile_x + tile_size - 1, tile_y + tile_size)
sw = (tile_x, tile_y + tile_size)
if split == 'left':
# top right triangle
draw_triangle(nw, ne, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_triangle(a, b, c, color, draw):
"""Draws a triangle with the given vertices in the given color.""" |
draw.polygon([a, b, c], fill=color) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def color_reducer(c1, c2):
"""Helper function used to add two colors together when averaging.""" |
return tuple(v1 + v2 for v1, v2 in itertools.izip(c1, c2)) |
<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_color_dist(c1, c2):
"""Calculates the "distance" between two colors, where the distance is another color whose components are the absolute values of the ... |
return tuple(abs(v1 - v2) for v1, v2 in itertools.izip(c1, c2)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prep_image(image, tile_size):
"""Takes an image and a tile size and returns a possibly cropped version of the image that is evenly divisible in both dimensio... |
w, h = image.size
x_tiles = w / tile_size # floor division
y_tiles = h / tile_size
new_w = x_tiles * tile_size
new_h = y_tiles * tile_size
if new_w == w and new_h == h:
return image
else:
crop_bounds = (0, 0, new_w, new_h)
return image.crop(crop_bounds) |
<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(global_conf, root, **settings):
""" Entry point to create Uiro application. Setup all of necessary things: * Getting root matching * Initializing DB con... |
matching = import_module_attribute(settings['uiro.root_matching'])
apps = [import_module(app_name)
for app_name in settings['uiro.installed_apps'].split('\n')
if app_name != '']
static_matching = get_static_app_matching(apps)
if static_matching:
matching = static_matchi... |
<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_parent_object_permissions(self, request, obj):
""" Check if the request should be permitted for a given parent object. Raises an appropriate exception ... |
for permission in self.get_parent_permissions():
if not permission.has_object_permission(request, self, obj):
self.permission_denied(request) |
<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_parent_object(self, parent_queryset=None):
""" Returns the parent object the view is displaying. You may want to override this if you need to provide non... |
if self._parent_object_cache is not None:
return self._parent_object_cache
if parent_queryset is None:
parent_queryset = self.get_parent_queryset()
if self.parent_model is None:
raise ImproperlyConfigured(
"'%s' must define 'parent_model'" %... |
<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_subcommands(self, command, *args, **kwargs):
"""add subcommands. If command already defined, pass args and kwargs to add_subparsers() method, else to add... |
subcommands = kwargs.pop('subcommands', None)
try:
cmd = self[command]
except KeyError:
if 'formatter_class' not in kwargs:
kwargs['formatter_class'] = self.formatter_class
cmd = self.add_parser(command, *args, **kwargs)
args, kwa... |
<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(self, command=None, **kwargs):
"""update data, which is usually passed in ArgumentParser initialization e.g. command.update(prog="foo") """ |
if command is None:
argparser = self.argparser
else:
argparser = self[command]
for k,v in kwargs.items():
setattr(argparser, k, v) |
<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_config_name(self, action, name=None):
'''get the name for configuration
This returns a name respecting commands and subcommands. So if you
have a command name "index" with subcommand "ls", which has option
"--all", you will pass the action for subcommand "ls" and the options'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 add_command(self, command, *args, **kwargs):
"""add a command. This is basically a wrapper for add_parser() """ |
cmd = self.add_parser(command, *args, **kwargs) |
<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(self, argv=None, compile=None, preprocessor=None, compiler_factory=None):
"""Parse arguments and execute decorated function argv: list of arguments c... |
action, args, kwargs = self.compile_args(argv=argv, compile=compile, preprocessor=preprocessor, compiler_factory=compiler_factory)
return action(*args, **kwargs) |
<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(self, typ, id, **kwargs):
""" update just fields sent by keyword args """ |
return self._load(self._request(typ, id=id, method='PUT', data=kwargs)) |
<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(self, typ, id):
""" remove typ by id """ |
return self._load(self._request(typ, id=id, method='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 _merge_fields(a, b):
"""Merge two lists of fields. Fields in `b` override fields in `a`. Fields in `a` are output first. """ |
a_names = set(x[0] for x in a)
b_names = set(x[0] for x in b)
a_keep = a_names - b_names
fields = []
for name, field in a:
if name in a_keep:
fields.append((name, field))
fields.extend(b)
return fields |
<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_setting(name=None, label=None, editable=False, description=None, default=None, choices=None, append=False, translatable=False):
""" Registers a sett... |
if name is None:
raise TypeError("yacms.conf.register_setting requires the "
"'name' keyword argument.")
if editable and default is None:
raise TypeError("yacms.conf.register_setting requires the "
"'default' keyword argument when 'editable' is Tr... |
<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_editable(self, request):
""" Get the dictionary of editable settings for a given request. Settings are fetched from the database once per request and th... |
try:
editable_settings = self._editable_caches[request]
except KeyError:
editable_settings = self._editable_caches[request] = self._load()
return editable_settings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load(self):
""" Load editable settings from the database and return them as a dict. Delete any settings from the database that are no longer registered, and... |
from yacms.conf.models import Setting
removed_settings = []
conflicting_settings = []
new_cache = {}
for setting_obj in Setting.objects.all():
# Check that the Setting object corresponds to a setting that has
# been declared in code using ``register_se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_file(url, path, md5sum=None):
""" If file is not already at 'path', then download from 'url' and put it there. If md5sum is provided, and 'path' exist... |
if not os.path.isfile(path) or (md5sum and md5sum != file_md5(path)):
download_file(url, path) |
<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_proc_sh(self):
""" Write the script that is the first thing called inside the container. It sets env vars and then calls the real program. """ |
print("Writing proc.sh")
context = {
'tmp': '/tmp',
'home': '/app',
'settings': '/settings.yaml',
'envsh': '/env.sh',
'port': self.config.port,
'cmd': self.get_cmd(),
}
sh_path = os.path.join(get_container_path(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_cmd(self):
""" If self.config.cmd is not None, return that. Otherwise, read the Procfile inside the build code, parse it (as yaml), and pull out the comm... |
if self.config.cmd is not None:
return self.config.cmd
procfile_path = os.path.join(get_app_path(self.config), 'Procfile')
with open(procfile_path, 'r') as f:
procs = yaml.safe_load(f)
return procs[self.config.proc_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 ensure_container(self, name=None):
"""Make sure container exists. It's only needed on newer versions of LXC.""" |
if get_lxc_version() < pkg_resources.parse_version('2.0.0'):
# Nothing to do for old versions of LXC
return
if name is None:
name = self.container_name
args = [
'lxc-create',
'--name', name,
'--template', '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 ensure_build(self):
""" If self.config.build_url is set, ensure it's been downloaded to the builds folder. """ |
if self.config.build_url:
path = get_buildfile_path(self.config)
# Ensure that builds_root has been created.
mkdir(BUILDS_ROOT)
build_md5 = getattr(self.config, 'build_md5', None)
ensure_file(self.config.build_url, path, build_md5)
# Now... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def teardown(self):
""" Delete the proc path where everything has been put. The build will be cleaned up elsewhere. """ |
proc_path = get_proc_path(self.config)
if os.path.isdir(proc_path):
shutil.rmtree(proc_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve(self, value):
""" Resolve contextual value. :param value: Contextual value. :return: If value is a function with a single parameter, ... |
if isinstance(value, collections.Callable):
return value({
"base_dir": self.__base_dir,
"profile_dir": self.__prof_dir,
"profile_name": self.__prof_name
})
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:
def get(self, name=None):
"""Print a list of all jupyterHubs.""" |
# Print a list of hubs.
if name is None:
hubs = self.get_hubs()
print("Running Jupyterhub Deployments (by name):")
for hub_name in hubs:
hub = Hub(namespace=hub_name)
data = hub.get_description()
url = data['LoadBalance... |
<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(args, prog_name):
""" main entry point for the script. :param args: the arguments for this script, as a list of string. Should already have had things l... |
# get options and arguments
ui = getUI(args, prog_name)
if ui.optionIsSet("test"):
# just run unit tests
unittest.main(argv=[sys.argv[0]])
elif ui.optionIsSet("help"):
# just show help
ui.usage()
else:
verbose = (ui.optionIsSet("verbose") is True) or DEFAULT_VERBOSITY
# how to handl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pull_all(command):
"""Website scraper for the info from table content""" |
page = requests.get(BASE_URL,verify=False)
soup = BeautifulSoup(page.text,"lxml")
table = soup.find('table',{'class':'list'})
rows = table.findAll("tr")
rows = rows[1:-1]
l = []
name_max = 0
for row in rows:
elements = row.findAll('td')
date = elements[0].string
name = elements[1].string
n = _ascii_ch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _release_info(jsn,VERSION):
"""Gives information about a particular package version.""" |
try:
release_point = jsn['releases'][VERSION][0]
except KeyError:
print "\033[91m\033[1mError: Release not found."
exit(1)
python_version = release_point['python_version']
filename = release_point['filename']
md5 = release_point['md5_digest']
download_url_for_release = release_point['url']
download_num_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 _construct(PACKAGE,VERSION):
"""Construct the information part from the API.""" |
jsn = _get_info(PACKAGE)
package_url = jsn['info']['package_url']
author = jsn['info']['author']
author_email = jsn['info']['author_email']
description = jsn['info']['description']
last_month = jsn['info']['downloads']['last_month']
last_week = jsn['info']['downloads']['last_week']
last_day = jsn['info']['do... |
<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():
'''cheesy gives you the news for today's cheese pipy factory from command line'''
arguments = docopt(__doc__, version=__version__)
if arguments['ls']:
_pull_all('ls')
elif arguments['list']:
_pull_all('list')
elif arguments['<PACKAGE>']:
try:
if arguments['<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 os_packages(metadata):
""" Installs operating system dependent packages """ |
family = metadata[0]
release = metadata[1]
#
if 'Amazon' in family and '2' not in release:
stdout_message('Identified Amazon Linux 1 os distro')
commands = [
'sudo yum -y update', 'sudo yum -y groupinstall "Development tools"'
]
for cmd in commands:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stdout_message(message, prefix='INFO', quiet=False, multiline=False, tabspaces=4, severity=''):
""" Prints message to cli stdout while indicating type and se... |
prefix = prefix.upper()
tabspaces = int(tabspaces)
# prefix color handling
choices = ('RED', 'BLUE', 'WHITE', 'GREEN', 'ORANGE')
critical_status = ('ERROR', 'FAIL', 'WTF', 'STOP', 'HALT', 'EXIT', 'F*CK')
if quiet:
return False
else:
if prefix in critical_status or severity.... |
<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():
""" Check Dependencies, download files, integrity check """ |
# vars
tar_file = TMPDIR + '/' + BINARY_URL.split('/')[-1]
chksum = TMPDIR + '/' + MD5_URL.split('/')[-1]
# pre-run validation + execution
if precheck() and os_packages(distro.linux_distribution()):
stdout_message('begin download')
download()
stdout_message('begin valid_chec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gc(ctx):
"""Runs housekeeping tasks to free up space. For now, this only removes saved but unused (unreachable) test results. """ |
vcs = ctx.obj['vcs']
count = 0
with locking.lock(vcs, locking.Lock.tests_history):
known_signatures = set(get_committed_signatures(vcs) + get_staged_signatures(vcs))
for signature in get_signatures_with_results(vcs):
if signature not in known_signatures:
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 clone_repo(pkg_name, repo_url):
"""Create a new cloned repo with the given parameters.""" |
new_repo = ClonedRepo(name=pkg_name, origin=repo_url)
new_repo.save()
return new_repo |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pull_repo(repo_name):
"""Pull from origin for repo_name.""" |
repo = ClonedRepo.objects.get(pk=repo_name)
repo.pull() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pull_all_repos():
"""Pull origin updates for all repos with origins.""" |
repos = ClonedRepo.objects.all()
for repo in repos:
if repo.origin is not None:
pull_repo.delay(repo_name=repo.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 _get_ipv4_addrs(self):
""" Returns the IPv4 addresses associated with this NIC. If no IPv4 addresses are used, then empty dictionary is returned. """ |
addrs = self._get_addrs()
ipv4addrs = addrs.get(netifaces.AF_INET)
if not ipv4addrs:
return {}
return ipv4addrs[0] |
<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_ipv6addrs(self):
""" Returns the IPv6 addresses associated with this NIC. If no IPv6 addresses are used, empty dict is returned. """ |
addrs = self._get_addrs()
ipv6addrs = addrs.get(netifaces.AF_INET6)
if not ipv6addrs:
return {}
return ipv6addrs[0] |
<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_default_gateway(self, ip=4):
""" Returns the default gateway for given IP version. The ``ip`` argument is used to specify the IP version, and can be eit... |
net_type = netifaces.AF_INET if ip == 4 else netifaces.AF_INET6
gw = netifaces.gateways()['default'].get(net_type, (None, None))
if gw[1] == self.name:
return gw[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def release_qa(quietly=False):
""" Release code to QA server """ |
name = prompt(red('Sprint name?'), default='Sprint 1').lower().replace(' ', "_")
release_date = prompt(red('Sprint start date (Y-m-d)?'), default='2013-01-20').replace('-', '')
release_name = '%s_%s' % (release_date, name)
local('git flow release start %s' % release_name)
local('git flow release pu... |
<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_qa(quietly=False):
""" Merge code from develop to qa """ |
switch('dev')
switch('qa')
local('git merge --no-edit develop')
local('git push')
if not quietly:
print(red('PLEASE DEPLOY CODE: fab deploy:all')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def backup_db():
""" Backup local database """ |
if not os.path.exists('backups'):
os.makedirs('backups')
local('python manage.py dump_database | gzip > backups/' + _sql_paths('local', datetime.now())) |
<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_db():
""" Get database from server """ |
with cd(env.remote_path):
file_path = '/tmp/' + _sql_paths('remote', str(base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', ''))
run(env.python + ' manage.py dump_database | gzip > ' + file_path)
local_file_path = './backups/' + _sql_paths('remote', datetime.now())
get(file_path... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def command(command):
""" Run custom Django management command """ |
with cd(env.remote_path):
sudo(env.python + ' manage.py %s' % command, user=env.remote_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 copy_s3_bucket(src_bucket_name, src_bucket_secret_key, src_bucket_access_key, dst_bucket_name, dst_bucket_secret_key, dst_bucket_access_key):
""" Copy S3 buc... |
with cd(env.remote_path):
tmp_dir = "s3_tmp"
sudo('rm -rf %s' % tmp_dir, warn_only=True, user=env.remote_user)
sudo('mkdir %s' % tmp_dir, user=env.remote_user)
sudo('s3cmd --recursive get s3://%s/upload/ %s --secret_key=%s --access_key=%s' % (
src_bucket_name, tmp_dir, 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 send_point_data(events, additional):
"""creates data point payloads and sends them to influxdb """ |
bodies = {}
for (site, content_id), count in events.items():
if not len(site) or not len(content_id):
continue
# influxdb will take an array of arrays of values, cutting down on the number of requests
# needed to be sent to it wo write data
bodies.setdefault(site, [... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_trending_data(events):
"""creates data point payloads for trending data to influxdb """ |
bodies = {}
# sort the values
top_hits = sorted(
[(key, count) for key, count in events.items()],
key=lambda x: x[1],
reverse=True
)[:100]
# build up points to be written
for (site, content_id), count in top_hits:
if not len(site) or not re.match(CONTENT_ID_REG... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_events():
"""pulls data from the queue, tabulates it and spawns a send event """ |
# wait loop
while 1:
# sleep and let the queue build up
gevent.sleep(FLUSH_INTERVAL)
# init the data points containers
events = Counter()
additional = {}
# flush the queue
while 1:
try:
site, content_id, event, path = EVENTS_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def content_ids(params):
"""does the same this as `pageviews`, except it includes content ids and then optionally filters the response by a list of content ids p... |
# set up default values
default_from, default_to, yesterday, _ = make_default_times()
# get params
try:
series = params.get("site", [DEFAULT_SERIES])[0]
from_date = params.get("from", [default_from])[0]
to_date = params.get("to", [default_to])[0]
group_by = params.get("... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.