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://subdomain.example.com.au and length 16 the following would be returned. """
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) else: shortened = u'%s' % ext.domain if ext.tld: shortened = u'%s.%s' % (shortened, ext.tld) if not strip_path: if parsed_url.path: shortened += parsed_url.path if len(shortened) <= length: return shortened else: domain = shortened i = length + 1 - 3 left = right = int(i/2) if not i % 2: right -= 1 if ellipsis: shortened = u"%s\u2026%s" % (domain[:left], domain[-right:]) else: shortened = '%s...%s' % (domain[:left], domain[-right:]) return shortened
<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.set(res) def eb(res): result.set_exception(res) d.addCallbacks(cb, eb) try: return result.get() except failure.Failure, ex: ex.raiseException()
<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.callFromGreenlet(task) value = result.get() if isinstance(value, defer.Deferred): return waitForDeferred(value) else: 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 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 delay -= now else: self._wake = now + 300 delay = 300 try: self._wait = 1 try: self._threadCallNotification.get(timeout=delay if delay > 0 else 0) except Empty: pass else: raise Reschedule self._wait = 0 except Reschedule: if self.threadCallQueue: total = len(self.threadCallQueue) count = 0 for fn, args, kwargs in self.threadCallQueue: try: fn(*args, **kwargs) except: log.err() count += 1 if count == total: break del self.threadCallQueue[:count] if self.threadCallQueue: self.wakeUp() continue now = seconds() while 1: try: c = callqueue[0] except IndexError: break if c.time <= now: del callqueue[0] try: c() except GreenletExit: raise except: log.msg('Unexpected error in main loop.') log.err() else: break except (GreenletExit, KeyboardInterrupt): pass log.msg('Main loop terminated.') self.fireSystemEvent('shutdown')
<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 first search result. :returns: The track dictionary from the SoundCloud API """
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 by url: {}'.format(str(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 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='Downloading...') as chunks: for chunk in chunks: out.write(chunk)
<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(track_data.artwork_url, stream=True).raw.read() mp3.tags.add(mutagen.id3.APIC(encoding=3, mime='image/jpeg', type=3, desc='Front cover', data=cover_bytes)) mp3.save()
<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 with N observations X : ndarray The <N x C> design matrix with C independent variables, features, factors, etc. algorithm : str Optional. The algorithm used in scipy.optimize.minimize and 'L-BFGS-B' (Limited BFGS) as default. Eligible algorithms are 'CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', and 'SLSQP' as these use the supplied gradient function. This is an unconstrained optimization problem. Thus, the 'L-BFGS-B', 'TNC' and 'SLSQP' options does not make use of constraints. 'TNC' (Truncated Newton) seems to be suited to for larger datasets and 'L-BFGS-B' (Limited BFGS) if computing powever becomes an issue. debug : bool Optional. Returns: -------- beta : ndarray Estimated regression coefficients. results : scipy.optimize.optimize.OptimizeResult Optional. If debug=True then only scipy's optimization result variable is returned. """
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 algorithm if algorithm not in ('CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP'): raise Exception('Optimization Algorithm not supported.') # set start values theta0 = np.ones((X.shape[1],)) # run solver results = sopt.minimize( objective_pssr, theta0, jac=gradient_pssr, args=(y, X, lam), method=algorithm, options={'disp': False}) # debug? if debug: return results # done return results.x
<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. Returns the processed image as a PIL Image object. The image can be given as anything suitable for passing to `Image.open` (ie, the path to an image or as a file-like object containing image data). If tile_size is 0, the tile size will be guessed based on the image size. It will also be adjusted to be divisible by 2 if it is not already. """
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(image) if tile_size % 2 != 0: tile_size = (tile_size / 2) * 2 logging.info('Input image size: %r', image.size) logging.info('Tile size: %r', tile_size) # Preprocess image to make sure it's at a size we can handle image = prep_image(image, tile_size) logging.info('Prepped image size: %r', image.size) # Get pixmap (for direct pixel access) and draw objects for the image. pix = image.load() draw = ImageDraw.Draw(image) # Process the image, tile by tile for x, y in iter_tiles(image, tile_size): process_tile(x, y, tile_size, pix, draw, image) return image
<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 = get_color_dist(s, e) d_sw = get_color_dist(s, w) # Figure out which pair is the closest, which will determine the direction # we'll split this tile into triangles. A 'right' split runs from top left # to bottom right. A 'left' split runs bottom left to top right. closest = sorted([d_ne, d_nw, d_se, d_sw])[0] if closest in (d_ne, d_sw): split = 'right' elif closest in (d_nw, d_se): split = 'left' # Figure out the average color for each side of the "split" if split == 'right': top_color = get_average_color([n, e]) bottom_color = get_average_color([s, w]) else: top_color = get_average_color([n, w]) bottom_color = get_average_color([s, e]) draw_triangles(tile_x, tile_y, tile_size, split, top_color, bottom_color, draw)
<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 size. """
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, se, top_color, draw) # bottom left triangle draw_triangle(nw, sw, se, bottom_color, draw) else: # top left triangle draw_triangle(sw, nw, ne, top_color, draw) # bottom right triangle draw_triangle(sw, se, ne, bottom_color, draw)
<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 difference between each component of the input colors. """
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 dimensions by the tile size. """
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 connection * Initializing Template Lookups * Collecting installed applications * Creating apps for serving static files and will create/return Uiro application. """
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_matching + matching setup_lookup(apps) initdb(settings) return make_wsgi_app(matching)
<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 if the request is not permitted. """
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-standard queryset lookups. Eg if parent objects are referenced using multiple keyword arguments in the url conf. """
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'" % self.__class__.__name__ ) if self.parent_lookup_field is None: raise ImproperlyConfigured( "'%s' must define 'parent_lookup_field'" % self.__class__.__name__ # noqa ) lookup_url_kwarg = '_'.join([ self.parent_model_name or self.parent_model._meta.model_name, self.parent_lookup_field ]) lookup = self.kwargs.get(lookup_url_kwarg, None) if lookup is not None: filter_kwargs = {self.parent_lookup_field: lookup} else: raise ImproperlyConfigured( 'Expected view %s to be called with a URL keyword argument ' 'named "%s". Fix your URL conf, or set the ' '`parent_lookup_field` attribute on the view correctly.' % (self.__class__.__name__, lookup_url_kwarg) ) obj = get_object_or_404(parent_queryset, **filter_kwargs) self.check_parent_object_permissions(self.request, obj) self._parent_object_cache = obj return obj
<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_parser() method. This behaviour is for convenience, because I mostly use the sequence: If you want to configure your sub_parsers, you can do it with: help = "cmd help" subcommands = dict( title = "title" description = "subcommands description" ) ) """
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, kwargs = tuple(), dict() if subcommands is not None: kwargs = subcommands child = CommandDecorator( argparser = self.argparser, commands = cmd.add_subparsers(*args, **kwargs), parent = self, name = command, ) self.children.append(child) return child
<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 dest name ("all" in this case), then this function will return "index.ls.all" as configuration name for this option. ''' _name = None if name is None: if '.' in action: action, name = action.rsplit('.', 1) else: _name = '' name = action if _name is None: if isinstance(action, basestring): action = self.get_action(action) _name = action.argdeco_name logger.debug("_name=%s", _name) config_name = Undefined while True: logger.debug("check _name=%s, name=%s", repr(_name), repr(name)) if _name in self.config_map: if name in self.config_map[_name]: config_name = self.config_map[_name][name] if config_name is not None: if config_name.startswith('.'): config_name = _name + config_name break if _name == '': break if '.' not in _name: _name = '' continue _name = _name.rsplit('.', 1)[0] assert config_name is not Undefined, "could not determine config name for %s" % name return config_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 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 compile: - None, pass args as keyword args to function - True, pass args as single dictionary - function, get args from parse_args() and return a pair of tuple and dict to be passed as args and kwargs to function """
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 setting that can be edited via the admin. This mostly equates to storing the given args as a dict in the ``registry`` dict by name. """
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 True.") # append is True when called from an app (typically external) # after the setting has already been registered, with the # intention of appending to its default value. if append and name in registry: registry[name]["default"] += default return # If an editable setting has a value defined in the # project's settings.py module, it can't be editable, since # these lead to a lot of confusion once its value gets # defined in the db. if hasattr(django_settings, name): editable = False if label is None: label = name.replace("_", " ").title() # Python 2/3 compatibility. isinstance() is overridden by future # on Python 2 to behave as Python 3 in conjunction with either # Python 2's native types or the future.builtins types. if isinstance(default, bool): # Prevent bools treated as ints setting_type = bool elif isinstance(default, int): # An int or long or subclass on Py2 setting_type = int elif isinstance(default, (str, Promise)): # A unicode or subclass on Py2 setting_type = str elif isinstance(default, bytes): # A byte-string or subclass on Py2 setting_type = bytes else: setting_type = type(default) registry[name] = {"name": name, "label": label, "editable": editable, "description": description, "default": default, "choices": choices, "type": setting_type, "translatable": translatable}
<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 then stored in ``_editable_caches``, a WeakKeyDictionary that will automatically discard each entry when no more references to the request exist. """
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 emit a warning if there are settings that are defined in both settings.py and the database. """
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_setting()``. If not, add # it to a list of items to be deleted from the database later. try: setting = registry[setting_obj.name] except KeyError: removed_settings.append(setting_obj.name) continue # Convert a string from the database to the correct Python type. setting_value = self._to_python(setting, setting_obj.value) # If a setting is defined both in the database and in settings.py, # raise a warning and use the value defined in settings.py. if hasattr(django_settings, setting["name"]): if setting_value != setting["default"]: conflicting_settings.append(setting_obj.name) continue # If nothing went wrong, use the value from the database! new_cache[setting["name"]] = setting_value if removed_settings: Setting.objects.filter(name__in=removed_settings).delete() if conflicting_settings: warn("These settings are defined in both settings.py and " "the database: %s. The settings.py values will be used." % ", ".join(conflicting_settings)) return new_cache
<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' exists, check that file matches the md5sum. If not, re-download. """
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.config), 'proc.sh') rendered = get_template('proc.sh') % context with open(sh_path, 'w') as f: f.write(rendered) st = os.stat(sh_path) os.chmod( sh_path, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
<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 command for self.config.proc_name. """
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', '>', '/dev/null', '2>&1', ] os.system(' '.join(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 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 untar. self.untar()
<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, which is a read-only dictionary, the return value of the function called with context properties as its parameter. If not, the value itself. """
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['LoadBalancer Ingress'] print(f' - Name: {hub_name}') print(f' Url: {url}') else: hub = Hub(namespace=name) hub.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 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 like the script name stripped. That is, if there are no args provided, this should be an empty list. """
# 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 handle strand, names, and whether to collapse only regions with # exactly matching genomic loci? stranded = ui.optionIsSet("stranded") names = ui.optionIsSet("accumulate_names") exact = ui.optionIsSet("exact") # get output handle out_fh = sys.stdout if ui.optionIsSet("output"): out_fh = open(ui.getValue("output"), "w") # get input file-handle in_fh = sys.stdin if ui.hasArgument(0): in_fh = open(ui.getArgument(0)) # load data -- TODO at the moment we load everying; need to think about # whether it is possible to do this using a single pass of the data, but not # loading it all first. regions = [x for x in BEDIterator(in_fh, verbose)] if exact: collapse_exact(regions, stranded, names, out_fh) else: for x in collapseRegions(regions, stranded, names, verbose): out_fh.write(str(x) + "\n")
<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_checker(name) version = n.split(' ')[1] name = n.split(' ')[0] if name_max < len(name): name_max = len(name) link = elements[1].find('a')['href'] link = urlparse.urljoin(BASE_URL,link) desc = elements[2].string li = (name,desc,link,date,version) l.append(li) print u"\n\033[1m\033[1m\033[4m PACKAGES \033[0m\n" if command == 'ls': for li in l: print u"\033[1m \u25E6 %s \033[0m \033[93m%s \033[0m"%(li[0],li[4]) if command == 'list': for li in l: name = li[0] + "".join(" " for i in range(name_max-len(li[0]))) desc = li[1] if len(li[1]) > 56: desc = desc[:56] + " .." print u"\033[1m \u25D8 %s \033[0m \033[93m%s \033[0m"%(name,desc)
<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_for_release = release_point['downloads'] download_size_for_release = _sizeof_fmt(int(release_point['size'])) print """ \033[1m\033[1m \033[4mPACKAGE VERSION INFO\033[0m \033[1m md5 :\033[0m \033[93m%s \033[0m \033[1m python version :\033[0m \033[93m%s \033[0m \033[1m download url :\033[0m \033[93m%s \033[0m \033[1m download number :\033[0m \033[93m%s \033[0m \033[1m size :\033[0m \033[93m%s \033[0m \033[1m filename :\033[0m \033[93m%s \033[0m """%(md5,python_version,download_url_for_release,\ download_num_for_release,download_size_for_release,filename)
<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']['downloads']['last_day'] classifiers = jsn['info']['classifiers'] license = jsn['info']['license'] summary = jsn['info']['summary'] home_page = jsn['info']['home_page'] releases = reversed(jsn['releases'].keys()) releases = ' | '.join(releases)[:56] download_url = jsn['urls'][0]['url'] filename = jsn['urls'][0]['filename'] size = _sizeof_fmt(int(jsn['urls'][0]['size'])) if VERSION: try: _release_info(jsn,VERSION) except IndexError: print "\033[91m\033[1mError: Try the Command:\n\033[1m\033[0m\033[1m$ cheesy <PACKAGE> <VERSION>" return None print """ \n\033[1m\033[4mDESCRIPTION\n\n\033[0m\033[93m%s \033[0m \033[1m\033[1m \033[4mPACKAGE INFO\033[0m \n \033[1m package url :\033[0m \033[93m%s \033[0m \033[1m author name :\033[0m \033[93m%s \033[0m \033[1m author email :\033[0m \033[93m%s \033[0m \033[1m downloads last month :\033[0m \033[93m%s \033[0m \033[1m downloads last week :\033[0m \033[93m%s \033[0m \033[1m downloads last day :\033[0m \033[93m%s \033[0m \033[1m homepage :\033[0m \033[93m%s \033[0m \033[1m releases :\033[0m \033[93m%s \033[0m \033[1m download url :\033[0m \033[93m%s \033[0m \033[1m filename :\033[0m \033[93m%s \033[0m \033[1m size :\033[0m \033[93m%s \033[0m """%(description,package_url,author,author_email,last_month,last_week,\ last_day,home_page,releases,download_url,filename,size)
<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>']: _construct(arguments['<PACKAGE>'],arguments['<VERSION>']) else: _construct(arguments['<PACKAGE>'],None) except ValueError: print "\033[91m\033[1mError: package not found try.. \033[0m\033[1m\n$ cheese ls \nto view pacakages" else: print(__doc__)
<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: stdout_message(subprocess.getoutput(cmd)) return True elif 'Amazon' in family and '2' in release: stdout_message('Identified Amazon Linux 2 os distro') commands = [ 'sudo yum -y update', 'sudo yum -y groupinstall "Development tools"' ] for cmd in commands: stdout_message(subprocess.getoutput(cmd)) return True elif 'Redhat' in family: stdout_message('Identified Redhat Enterprise Linux os distro') commands = [ 'sudo yum -y update', 'sudo yum -y groupinstall "Development tools"' ] for cmd in commands: stdout_message(subprocess.getoutput(cmd)) elif 'Ubuntu' or 'Mint' in family: stdout_message('Identified Ubuntu Linux os distro') commands = [ 'sudo apt -y update', 'sudo apt -y upgrade', 'sudo yum -y groupinstall "Development tools"' ] for cmd in commands: stdout_message(subprocess.getoutput(cmd)) 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 stdout_message(message, prefix='INFO', quiet=False, multiline=False, tabspaces=4, severity=''): """ Prints message to cli stdout while indicating type and severity Args: :message (str): text characters to be printed to stdout :prefix (str): 4-letter string message type identifier. :quiet (bool): Flag to suppress all output :multiline (bool): indicates multiline message; removes blank lines on either side of printed message :tabspaces (int): left justified number of spaces :severity (str): header msg determined color instead of prefix .. code-block:: python # Examples: - INFO (default) - ERROR (error, problem occurred) - WARN (warning) - NOTE (important to know) Returns: TYPE: bool, Success (printed) | Failure (no output) """
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.upper() == 'CRITICAL': header = (Colors.YELLOW + '\t[ ' + Colors.RED + prefix + Colors.YELLOW + ' ]' + Colors.RESET + ': ') elif severity.upper() == 'WARNING': header = (Colors.YELLOW + '\t[ ' + Colors.ORANGE + prefix + Colors.YELLOW + ' ]' + Colors.RESET + ': ') else: # default color scheme header = (Colors.YELLOW + '\t[ ' + Colors.DARKCYAN + prefix + Colors.YELLOW + ' ]' + Colors.RESET + ': ') if multiline: print(header.expandtabs(tabspaces) + str(message)) else: print('\n' + header.expandtabs(tabspaces) + str(message) + '\n') 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 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_checksum') valid_checksum(tar_file, chksum) return compile_binary(tar_file) logger.warning('%s: Pre-run dependency check fail - Exit' % inspect.stack()[0][3]) 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 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 += 1 remove_results(vcs, signature) click.echo('Removed {} saved results.'.format(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 either 4 or 6. """
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 publish %s' % release_name) 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 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, local_file_path) run('rm ' + file_path) return local_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 bucket directory with CMS data between environments. Operations are done on server. """
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, src_bucket_secret_key, src_bucket_access_key), user=env.remote_user) sudo('s3cmd --recursive put %s/ s3://%s/upload/ --secret_key=%s --access_key=%s' % ( tmp_dir, dst_bucket_name, dst_bucket_secret_key, dst_bucket_access_key), user=env.remote_user) sudo('s3cmd setacl s3://%s/upload --acl-public --recursive --secret_key=%s --access_key=%s' % ( dst_bucket_name, dst_bucket_secret_key, dst_bucket_access_key), user=env.remote_user) # cleanup sudo('rm -rf %s' % tmp_dir, warn_only=True, 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 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, []) # get additional info event, path = additional.get((site, content_id), (None, None)) # append the point bodies[site].append([content_id, event, path, count]) for site, points in bodies.items(): # send payload to influxdb try: data = [{ "name": site, "columns": ["content_id", "event", "path", "value"], "points": points, }] INFLUXDB_CLIENT.write_points(data) except Exception as e: LOGGER.exception(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 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_REGEX, content_id): continue # add point bodies.setdefault(site, []) bodies[site].append([content_id, count]) for site, points in bodies.items(): # create name name = "{}_trending".format(site) # send payload to influxdb try: data = [{ "name": name, "columns": ["content_id", "value"], "points": points, }] INFLUXDB_CLIENT.write_points(data) except Exception as e: LOGGER.exception(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 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_QUEUE.get_nowait() events[(site, content_id)] += 1 if event and path: additional[(site, content_id)] = (event, path) except queue.Empty: break except Exception as e: LOGGER.exception(e) break # after tabulating, spawn a new thread to send the data to influxdb if len(events): gevent.spawn(send_point_data, events, additional) gevent.spawn(send_trending_data, 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 passed as query params - note, this load can be a little heavy and could take a minute """
# 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("group_by", [DEFAULT_GROUP_BY])[0] ids = params.get("content_id", []) except Exception as e: LOGGER.exception(e) return json.dumps({"error": e.message}), "500 Internal Error" # check the cache cache_key = "{}:{}:{}:{}:{}:{}:{}".format( memcached_prefix, "contentids.json", series, from_date, to_date, group_by, ids) try: data = MEMCACHED_CLIENT.get(cache_key) if data: return data, "200 OK" except Exception as e: LOGGER.exception(e) # enforce content ids if not len(ids): return json.dumps({"error": "you must pass at least one content id'"}), "400 Bad Request" # parse from date from_date = parse_datetime(from_date) if from_date is None: LOGGER.error("could not parse 'from'") return json.dumps({"error": "could not parse 'from'"}), "400 Bad Request" # parse to date to_date = parse_datetime(to_date) if to_date is None: LOGGER.error("could not parse 'to'") return json.dumps({"error": "could not parse 'to'"}), "400 Bad Request" # influx will only keep non-aggregated data for a day, so if the from param is beyond that point # we need to update the series name to use the rolled up values if from_date < yesterday: series = update_series(series, "pageviews", "content_id") # format times from_date = format_datetime(from_date) to_date = format_datetime(to_date) # start building the query query = "SELECT content_id, sum(value) as value " \ "FROM {series} " \ "WHERE time > '{from_date}' AND time < '{to_date}' " \ "GROUP BY content_id, time({group_by}) " \ "fill(0);" args = {"series": series, "from_date": from_date, "to_date": to_date, "group_by": group_by} # send the request try: res = INFLUXDB_CLIENT.query(query.format(**args)) # capture errors and send them back along with the query (for inspection/debugging) except Exception as e: LOGGER.exception(e) return json.dumps({"error": e.message, "query": query.format(**args)}), "500 Internal Error" # build the response object response = flatten_response(res) # filter by content ids if len(ids): for site, points in response.items(): filtered = filter(lambda p: p["content_id"] in ids, points) response[site] = filtered res = json.dumps(response) # cache the response try: MEMCACHED_CLIENT.set(cache_key, res, time=MEMCACHED_EXPIRATION) except Exception as e: LOGGER.exception(e) return res, "200 OK"