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 loads(inputStr): """Takes a string and converts it into an internal hypercat object, with some checking"""
inCat = json.loads(inputStr) assert CATALOGUE_TYPE in _values(inCat[CATALOGUE_METADATA], ISCONTENTTYPE_RELATION) # Manually copy mandatory fields, to check that they are they, and exclude other garbage desc = _values(inCat[CATALOGUE_METADATA], DESCRIPTION_RELATION)[0] # TODO: We are ASSUMING just one description, which may not be true outCat = Hypercat(desc) for i in inCat[ITEMS]: href = i[HREF] contentType = _values(i[ITEM_METADATA], ISCONTENTTYPE_RELATION) [0] desc = _values(i[ITEM_METADATA], DESCRIPTION_RELATION) [0] if contentType == CATALOGUE_TYPE: r = Hypercat(desc) else: r = Resource(desc, contentType) outCat.addItem(r, href) return outCat
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rels(self): """Returns a LIST of all the metadata relations"""
r = [] for i in self.metadata: r = r + i[REL] return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prettyprint(self): """Return hypercat formatted prettily"""
return json.dumps(self.asJSON(), sort_keys=True, indent=4, separators=(',', ': '))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tailf( filepath, lastn=0, timeout=60, stopon=None, encoding="utf8", delay=0.1 ): """provide a `tail -f` like function :param filepath: file to tail -f, absolute path or relative path :param lastn: lastn line will also be yield :param timeout: (optional) stop tail -f when time's up [timeout <= 10min, default = 1min] :param stopon: (optional) stops when the stopon(output) returns True :param encoding: (optional) default encoding utf8 :param delay: (optional) sleep if no data is available, default is 0.1s Usage:: "bar" "barz" """
if not os.path.isfile(filepath): raise ShCmdError("[{0}] not exists".format(filepath)) if consts.TIMEOUT_MAX > timeout: timeout = consts.TIMEOUT_DEFAULT delay = delay if consts.DELAY_MAX > delay > 0 else consts.DELAY_DEFAULT if isinstance(stopon, types.FunctionType) is False: stopon = always_false logger.info("tail -f {0} begin".format(filepath)) with open(filepath, "rt", encoding=encoding) as file_obj: lastn_filter = deque(maxlen=lastn) logger.debug("tail last {0} lines".format(lastn)) for line in file_obj: lastn_filter.append(line.rstrip()) for line in lastn_filter: yield line start = time.time() while timeout < 0 or (time.time() - start) < timeout: line = file_obj.readline() where = file_obj.tell() if line: logger.debug("found line: [{0}]".format(line)) yield line if stopon(line): break else: file_obj.seek(0, os.SEEK_END) if file_obj.tell() < where: logger.info("file [{0}] rewinded!".format(filepath)) file_obj.seek(0) else: logger.debug("no data, waiting for [{0}]s".format(delay)) time.sleep(delay) logger.info("tail -f {0} end".format(filepath))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _execfile(filename, globals, locals=None): """ Python 3 implementation of execfile. """
mode = 'rb' # Python 2.6 compile requires LF for newlines, so use deprecated # Universal newlines support. if sys.version_info < (2, 7): mode += 'U' with open(filename, mode) as stream: script = stream.read() if locals is None: locals = globals code = compile(script, filename, 'exec') exec(code, globals, locals)
<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(self, value=None): """Send a single value to this element for processing"""
if self.chain_fork: return self._send_fork(value) return self._send_flat(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 read_interfaces(path: str) -> Interfaces: """Reads an Interfaces JSON file at the given path and returns it as a dictionary."""
with open(path, encoding='utf-8') as f: return json.load(f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def multiple(layer: int, limit: int) -> Set[str]: """Returns a set of strings to be used as Slots with Pabianas default Clock. Args: layer: The layer in the hierarchy this Area is placed in. Technically, the number specifies how many of the Clocks signals are relevant to the Area. Between 1 and limit. limit: The number of layers of the hierarchy. """
return {str(x).zfill(2) for x in [2**x for x in range(limit)] if x % 2**(layer - 1) == 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 print_change(self, symbol, typ, changes=None, document=None, **kwargs): """Print out a change"""
values = ", ".join("{0}={1}".format(key, val) for key, val in sorted(kwargs.items())) print("{0} {1}({2})".format(symbol, typ, values)) if changes: for change in changes: print("\n".join("\t{0}".format(line) for line in change.split('\n'))) elif document: print("\n".join("\t{0}".format(line) for line in document.split('\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 change(self, symbol, typ, **kwargs): """Print out a change and then do the change if not doing a dry run"""
self.print_change(symbol, typ, **kwargs) if not self.dry_run: try: yield except: raise else: self.amazon.changes = 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 urlopen(url, timeout=20, redirects=None): """A minimal urlopen replacement hack that supports timeouts for http. Note that this supports GET only."""
scheme, host, path, params, query, frag = urlparse(url) if not scheme in ('http', 'https'): return urllib.urlopen(url) if params: path = '%s;%s' % (path, params) if query: path = '%s?%s' % (path, query) if frag: path = '%s#%s' % (path, frag) if scheme == 'https': # If ssl is not compiled into Python, you will not get an exception # until a conn.endheaders() call. We need to know sooner, so use # getattr. try: import M2Crypto except ImportError: if not hasattr(socket, 'ssl'): raise RuntimeError, 'no built-in SSL Support' conn = TimeoutHTTPS(host, None, timeout) else: ctx = M2Crypto.SSL.Context() ctx.set_session_timeout(timeout) conn = M2Crypto.httpslib.HTTPSConnection(host, ssl_context=ctx) conn.set_debuglevel(1) else: conn = TimeoutHTTP(host, None, timeout) conn.putrequest('GET', path) conn.putheader('Connection', 'close') conn.endheaders() response = None while 1: response = conn.getresponse() if response.status != 100: break conn._HTTPConnection__state = httplib._CS_REQ_SENT conn._HTTPConnection__response = None status = response.status # If we get an HTTP redirect, we will follow it automatically. if status >= 300 and status < 400: location = response.msg.getheader('location') if location is not None: response.close() if redirects is not None and redirects.has_key(location): raise RecursionError( 'Circular HTTP redirection detected.' ) if redirects is None: redirects = {} redirects[location] = 1 return urlopen(location, timeout, redirects) raise HTTPResponse(response) if not (status >= 200 and status < 300): raise HTTPResponse(response) body = StringIO(response.read()) response.close() return 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 SOAPUriToVersion(self, uri): """Return the SOAP version related to an envelope uri."""
value = self._soap_uri_mapping.get(uri) if value is not None: return value raise ValueError( 'Unsupported SOAP envelope uri: %s' % uri )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def WSDLUriToVersion(self, uri): """Return the WSDL version related to a WSDL namespace uri."""
value = self._wsdl_uri_mapping.get(uri) if value is not None: return value raise ValueError( 'Unsupported SOAP envelope uri: %s' % uri )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isElement(self, node, name, nsuri=None): """Return true if the given node is an element with the given name and optional namespace uri."""
if node.nodeType != node.ELEMENT_NODE: return 0 return node.localName == name and \ (nsuri is None or self.nsUriMatch(node.namespaceURI, nsuri))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getElement(self, node, name, nsuri=None, default=join): """Return the first child of node with a matching name and namespace uri, or the default if one is provided."""
nsmatch = self.nsUriMatch ELEMENT_NODE = node.ELEMENT_NODE for child in node.childNodes: if child.nodeType == ELEMENT_NODE: if ((child.localName == name or name is None) and (nsuri is None or nsmatch(child.namespaceURI, nsuri)) ): return child if default is not join: return default raise KeyError, 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 getElementById(self, node, id, default=join): """Return the first child of node matching an id reference."""
attrget = self.getAttr ELEMENT_NODE = node.ELEMENT_NODE for child in node.childNodes: if child.nodeType == ELEMENT_NODE: if attrget(child, 'id') == id: return child if default is not join: return default raise KeyError, 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 getElements(self, node, name, nsuri=None): """Return a sequence of the child elements of the given node that match the given name and optional namespace uri."""
nsmatch = self.nsUriMatch result = [] ELEMENT_NODE = node.ELEMENT_NODE for child in node.childNodes: if child.nodeType == ELEMENT_NODE: if ((child.localName == name or name is None) and ( (nsuri is None) or nsmatch(child.namespaceURI, nsuri))): result.append(child) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hasAttr(self, node, name, nsuri=None): """Return true if element has attribute with the given name and optional nsuri. If nsuri is not specified, returns true if an attribute exists with the given name with any namespace."""
if nsuri is None: if node.hasAttribute(name): return True return False return node.hasAttributeNS(nsuri, 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 getAttr(self, node, name, nsuri=None, default=join): """Return the value of the attribute named 'name' with the optional nsuri, or the default if one is specified. If nsuri is not specified, an attribute that matches the given name will be returned regardless of namespace."""
if nsuri is None: result = node._attrs.get(name, None) if result is None: for item in node._attrsNS.keys(): if item[1] == name: result = node._attrsNS[item] break else: result = node._attrsNS.get((nsuri, name), None) if result is not None: return result.value if default is not join: return default return ''
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAttrs(self, node): """Return a Collection of all attributes """
attrs = {} for k,v in node._attrs.items(): attrs[k] = v.value return attrs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getElementText(self, node, preserve_ws=None): """Return the text value of an xml element node. Leading and trailing whitespace is stripped from the value unless the preserve_ws flag is passed with a true value."""
result = [] for child in node.childNodes: nodetype = child.nodeType if nodetype == child.TEXT_NODE or \ nodetype == child.CDATA_SECTION_NODE: result.append(child.nodeValue) value = join(result, '') if preserve_ws is None: value = strip(value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findNamespaceURI(self, prefix, node): """Find a namespace uri given a prefix and a context node."""
attrkey = (self.NS_XMLNS, prefix) DOCUMENT_NODE = node.DOCUMENT_NODE ELEMENT_NODE = node.ELEMENT_NODE while 1: if node is None: raise DOMException('Value for prefix %s not found.' % prefix) if node.nodeType != ELEMENT_NODE: node = node.parentNode continue result = node._attrsNS.get(attrkey, None) if result is not None: return result.value if hasattr(node, '__imported__'): raise DOMException('Value for prefix %s not found.' % prefix) node = node.parentNode if node.nodeType == DOCUMENT_NODE: raise DOMException('Value for prefix %s not found.' % prefix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findTargetNS(self, node): """Return the defined target namespace uri for the given node."""
attrget = self.getAttr attrkey = (self.NS_XMLNS, 'xmlns') DOCUMENT_NODE = node.DOCUMENT_NODE ELEMENT_NODE = node.ELEMENT_NODE while 1: if node.nodeType != ELEMENT_NODE: node = node.parentNode continue result = attrget(node, 'targetNamespace', default=None) if result is not None: return result node = node.parentNode if node.nodeType == DOCUMENT_NODE: raise DOMException('Cannot determine target namespace.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nsUriMatch(self, value, wanted, strict=0, tt=type(())): """Return a true value if two namespace uri values match."""
if value == wanted or (type(wanted) is tt) and value in wanted: return 1 if not strict and value is not None: wanted = type(wanted) is tt and wanted or (wanted,) value = value[-1:] != '/' and value or value[:-1] for item in wanted: if item == value or item[:-1] == value: return 1 return 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 createDocument(self, nsuri, qname, doctype=None): """Create a new writable DOM document object."""
impl = xml.dom.minidom.getDOMImplementation() return impl.createDocument(nsuri, qname, doctype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loadFromURL(self, url): """Load an xml file from a URL and return a DOM document."""
if isfile(url) is True: file = open(url, 'r') else: file = urlopen(url) try: result = self.loadDocument(file) except Exception, ex: file.close() raise ParseError(('Failed to load document %s' %url,) + ex.args) else: file.close() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _getUniquePrefix(self): '''I guess we need to resolve all potential prefixes because when the current node is attached it copies the namespaces into the parent node. ''' while 1: self._indx += 1 prefix = 'ns%d' %self._indx try: self._dom.findNamespaceURI(prefix, self._getNode()) except DOMException, ex: break return prefix
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def createDocument(self, namespaceURI, localName, doctype=None): '''If specified must be a SOAP envelope, else may contruct an empty document. ''' prefix = self._soap_env_prefix if namespaceURI == self.reserved_ns[prefix]: qualifiedName = '%s:%s' %(prefix,localName) elif namespaceURI is localName is None: self.node = self._dom.createDocument(None,None,None) return else: raise KeyError, 'only support creation of document in %s' %self.reserved_ns[prefix] document = self._dom.createDocument(nsuri=namespaceURI, qname=qualifiedName, doctype=doctype) self.node = document.childNodes[0] #set up reserved namespace attributes for prefix,nsuri in self.reserved_ns.items(): self._setAttributeNS(namespaceURI=self._xmlns_nsuri, qualifiedName='%s:%s' %(self._xmlns_prefix,prefix), value=nsuri)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def face_and_energy_detector(image_path, detect_faces=True): """ Finds faces and energy in an image """
source = Image.open(image_path) work_width = 800 if source.mode != 'RGB' or source.bits != 8: source24 = source.convert('RGB') else: source24 = source.copy() grayscaleRMY = source24.convert('L', (0.5, 0.419, 0.081, 0)) w = min(grayscaleRMY.size[0], work_width) h = w * grayscaleRMY.size[1] / grayscaleRMY.size[0] b = grayscaleRMY.resize((w, h), Image.BICUBIC) # b.save('step2.jpg') if detect_faces: info = do_face_detection(image_path) if info: return CropInfo(gravity=info) b = b.filter(ImageFilter.GaussianBlur(7)) # b.save('step3.jpg') sobelXfilter = ImageFilter.Kernel((3, 3), (1, 0, -1, 2, 0, -2, 1, 0, -1), -.5) sobelYfilter = ImageFilter.Kernel((3, 3), (1, 2, 1, 0, 0, 0, -1, -2, -1), -.5) b = ImageChops.lighter(b.filter(sobelXfilter), b.filter(sobelYfilter)) b = b.filter(ImageFilter.FIND_EDGES) # b.save('step4.jpg') ec = energy_center(b) return CropInfo(gravity=ec)
<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_crop_size(crop_w, crop_h, image_w, image_h): """ Determines the correct scale size for the image when img w == crop w and img h > crop h Use these dimensions when img h == crop h and img w > crop w Use these dimensions """
scale1 = float(crop_w) / float(image_w) scale2 = float(crop_h) / float(image_h) scale1_w = crop_w # int(round(img_w * scale1)) scale1_h = int(round(image_h * scale1)) scale2_w = int(round(image_w * scale2)) scale2_h = crop_h # int(round(img_h * scale2)) if scale1_h > crop_h: # scale1_w == crop_w # crop on vertical return (scale1_w, scale1_h) else: # scale2_h == crop_h and scale2_w > crop_w #crop on horizontal return (scale2_w, scale2_h)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_subrange(range_max, sub_amount, weight): """ return the start and stop points that are sub_amount distance apart and contain weight, without going outside the provided range """
if weight > range_max or sub_amount > range_max: raise ValueError("sub_amount and weight must be less than range_max. range_max %s, sub_amount %s, weight %s" % (range_max, sub_amount, weight)) half_amount = sub_amount / 2 bottom = weight - half_amount top = bottom + sub_amount if top <= range_max and bottom >= 0: return (bottom, top) elif weight > range_max / 2: # weight is on the upper half, start at the max and go down return (range_max - sub_amount, range_max) else: # weight is on the lower have, start at 0 and go up return (0, sub_amount)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def smart_crop(crop_w, crop_h, image_path): """ Return the scaled image size and crop rectangle """
cropping = face_and_energy_detector(image_path) img = Image.open(image_path) w, h = img.size scaled_size = get_crop_size(crop_w, crop_h, *img.size) gravity_x = int(round(scaled_size[0] * cropping.gravity[0])) gravity_y = int(round(scaled_size[1] * cropping.gravity[1])) if scaled_size[0] == crop_w: # find the top and bottom crops crop_top, crop_bot = calc_subrange(scaled_size[1], crop_h, gravity_y) return scaled_size, Rect(left=0, top=crop_top, right=crop_w, bottom=crop_bot) else: # find the right and left crops crop_left, crop_right = calc_subrange(scaled_size[0], crop_w, gravity_x) return scaled_size, Rect(left=crop_left, top=0, right=crop_right, bottom=crop_h)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expiration_time(self): """ Returns the time until this access attempt is forgotten. """
logging_forgotten_time = configuration.behavior.login_forgotten_seconds if logging_forgotten_time <= 0: return None now = timezone.now() delta = now - self.modified time_remaining = logging_forgotten_time - delta.seconds return time_remaining
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def bling(self, target, sender): "will print yo" if target.startswith("#"): self.message(target, "%s: yo" % sender) else: self.message(sender, "yo")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def repeat(self, target, sender, **kwargs): "will repeat whatever yo say" if target.startswith("#"): self.message(target, kwargs["msg"]) else: self.message(sender, kwargs["msg"])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stopword(self, target, sender, *args): """ will repeat 'lol', 'lmao, 'rofl' or 'roflmao' when seen in a message only applies to channel messages """
if target.startswith("#"): self.message(target, args[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 compare_dicts(dict1, dict2): """ Checks if dict1 equals dict2 """
for k, v in dict2.items(): if v != dict1[k]: return False 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 getItalianAccentedVocal(vocal, acc_type="g"): """ It returns given vocal with grave or acute accent """
vocals = {'a': {'g': u'\xe0', 'a': u'\xe1'}, 'e': {'g': u'\xe8', 'a': u'\xe9'}, 'i': {'g': u'\xec', 'a': u'\xed'}, 'o': {'g': u'\xf2', 'a': u'\xf3'}, 'u': {'g': u'\xf9', 'a': u'\xfa'}} return vocals[vocal][acc_type]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def read_certificate(self, certificate_name): ''' a method to retrieve the details about a server certificate :param certificate_name: string with name of server certificate :return: dictionary with certificate details ''' title = '%s.read_certificate' % self.__class__.__name__ # validate inputs input_fields = { 'certificate_name': certificate_name } for key, value in input_fields.items(): object_title = '%s(%s=%s)' % (title, key, str(value)) self.fields.validate(value, '.%s' % key, object_title) # verify existence of server certificate if not certificate_name in self.certificate_list: self.printer_on = False self.list_certificates() self.printer_on = True if not certificate_name in self.certificate_list: raise Exception('\nServer certificate %s does not exist.' % certificate_name) # send request for certificate details try: cert_kwargs = { 'ServerCertificateName': certificate_name } response = self.connection.get_server_certificate(**cert_kwargs) except: raise AWSConnectionError(title) # construct certificate details from response from labpack.records.time import labDT from labpack.parsing.conversion import camelcase_to_lowercase cert_dict = response['ServerCertificate'] cert_details = camelcase_to_lowercase(cert_dict) for key, value in cert_details['server_certificate_metadata'].item(): cert_details.update(**{key:value}) del cert_details['server_certificate_metadata'] date_time = cert_details['expiration'] epoch_time = labDT(date_time).epoch() cert_details['expiration'] = epoch_time return cert_details
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text_in_color(self, message, color_code): """ Print with a beautiful color. See codes at the top of this file. """
return self.term.color(color_code) + message + self.term.normal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def files(self): """files that will be add to tar file later should be tuple, list or generator that returns strings """
ios_names = [info.name for info in self._ios_to_add.keys()] return set(self.files_to_add + ios_names)
<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_fileobj(self, fname, fcontent): """add file like object, it will be add to tar file later :param fname: name in tar file :param fcontent: content. bytes, string, BytesIO or StringIO """
tar_info = tarfile.TarInfo(fname) if isinstance(fcontent, io.BytesIO): tar_info.size = len(fcontent.getvalue()) elif isinstance(fcontent, io.StringIO): tar_info.size = len(fcontent.getvalue()) fcontent = io.BytesIO(fcontent.getvalue().encode("utf8")) else: if hasattr(fcontent, "readable"): fcontent = fcontent tar_info.size = len(fcontent) if isinstance(fcontent, str): fcontent = fcontent.encode("utf8") fcontent = io.BytesIO(fcontent) self._ios_to_add[tar_info] = fcontent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate(self): """generate tar file ..Usage:: """
if self._tar_buffer.tell(): self._tar_buffer.seek(0, 0) yield self._tar_buffer.read() for fname in self._files_to_add: last = self._tar_buffer.tell() self._tar_obj.add(fname) self._tar_buffer.seek(last, os.SEEK_SET) data = self._tar_buffer.read() yield data for info, content in self._ios_to_add.items(): last = self._tar_buffer.tell() self._tar_obj.addfile(info, content) self._tar_buffer.seek(last, os.SEEK_SET) data = self._tar_buffer.read() yield data self._tar_obj.close() yield self._tar_buffer.read() self._generated = 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 tar(self): """tar in bytes format"""
if not self.generated: for data in self.generate(): pass return self._tar_buffer.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Starts the mongodb connection. Must be called before anything else will work. """
self.client = MongoClient(self.mongo_uri) self.db = self.client[self.db_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 find(self, collection, query): """ Search a collection for the query provided. Just a raw interface to mongo to do any query you want. Args: collection: The db collection. See main class documentation. query: A mongo find query. Returns: pymongo Cursor object with the results. """
obj = getattr(self.db, collection) result = obj.find(query) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_all(self, collection): """ Search a collection for all available items. Args: collection: The db collection. See main class documentation. Returns: List of all items in the collection. """
obj = getattr(self.db, collection) result = obj.find() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_one(self, collection, query): """ Search a collection for the query provided and return one result. Just a raw interface to mongo to do any query you want. Args: collection: The db collection. See main class documentation. query: A mongo find query. Returns: pymongo Cursor object with the results. """
obj = getattr(self.db, collection) result = obj.find_one(query) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_distinct(self, collection, key): """ Search a collection for the distinct key values provided. Args: collection: The db collection. See main class documentation. key: The name of the key to find distinct values. For example with the indicators collection, the key could be "type". Returns: List of distinct values. """
obj = getattr(self.db, collection) result = obj.distinct(key) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_embedded_campaign(self, id, collection, campaign, confidence, analyst, date, description): """ Adds an embedded campaign to the TLO. Args: id: the CRITs object id of the TLO collection: The db collection. See main class documentation. campaign: The campaign to assign. confidence: The campaign confidence analyst: The analyst making the assignment date: The date of the assignment description: A description Returns: The resulting mongo object """
if type(id) is not ObjectId: id = ObjectId(id) # TODO: Make sure the object does not already have the campaign # Return if it does. Add it if it doesn't obj = getattr(self.db, collection) result = obj.find({'_id': id, 'campaign.name': campaign}) if result.count() > 0: return else: log.debug('Adding campaign to set: {}'.format(campaign)) campaign_obj = { 'analyst': analyst, 'confidence': confidence, 'date': date, 'description': description, 'name': campaign } result = obj.update( {'_id': id}, {'$push': {'campaign': campaign_obj}} ) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_bucket_list_item(self, id, collection, item): """ Removes an item from the bucket list Args: id: the CRITs object id of the TLO collection: The db collection. See main class documentation. item: the bucket list item to remove Returns: The mongodb result """
if type(id) is not ObjectId: id = ObjectId(id) obj = getattr(self.db, collection) result = obj.update( {'_id': id}, {'$pull': {'bucket_list': item}} ) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_campaign_name_list(self): """ Returns a list of all valid campaign names Returns: List of strings containing all valid campaign names """
campaigns = self.find('campaigns', {}) campaign_names = [] for campaign in campaigns: if 'name' in campaign: campaign_names.append(campaign['name']) return campaign_names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deserialize(self): """ Invoke the RFC 7159 spec compliant parser :return: the parsed & vetted request body """
super(Deserializer, self).deserialize() try: return json.loads(self.req.get_body()) except TypeError: link = 'tools.ietf.org/html/rfc7159' self.fail('Typically, this error is due to a missing JSON ' 'payload in your request when one was required. ' 'Otherwise, it could be a bug in our API.', link) except UnicodeDecodeError: link = 'tools.ietf.org/html/rfc7159#section-8.1' self.fail('We failed to process your JSON payload & it is ' 'most likely due to non UTF-8 encoded characters ' 'in your JSON.', link) except ValueError as exc: link = 'tools.ietf.org/html/rfc7159' self.fail('The JSON payload appears to be malformed & we ' 'failed to process it. The error with line & column ' 'numbers is: %s' % exc.message, link)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quantize_without_scipy(self, image): """" This function can be used if no scipy is availabe. It's 7 times slower though. """
w, h = image.size px = np.asarray(image).copy() memo = {} for j in range(w): for i in range(h): key = (px[i, j, 0], px[i, j, 1], px[i, j, 2]) try: val = memo[key] except KeyError: val = self.convert(*key) memo[key] = val px[i, j, 0], px[i, j, 1], px[i, j, 2] = val return Image.fromarray(px).convert("RGB").quantize(palette=self.palette_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 get_installed_extjs_apps(): """ Get all installed extjs apps. :return: List of ``(appdir, module, appname)``. """
installed_apps = [] checked = set() for app in settings.INSTALLED_APPS: if not app.startswith('django.') and not app in checked: checked.add(app) try: installed_apps.append(get_appinfo(app)) except LookupError, e: pass return installed_apps
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createJsbConfig(self): """ Create JSB config file using ``sencha create jsb``. :return: The created jsb3 config as a string. """
tempdir = mkdtemp() tempfile = join(tempdir, 'app.jsb3') cmd = ['sencha', 'create', 'jsb', '-a', self.url, '-p', tempfile] log.debug('Running: %s', ' '.join(cmd)) call(cmd) jsb3 = open(tempfile).read() rmtree(tempdir) return jsb3
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cleanJsbConfig(self, jsbconfig): """ Clean up the JSB config. """
config = json.loads(jsbconfig) self._cleanJsbAllClassesSection(config) self._cleanJsbAppAllSection(config) return json.dumps(config, indent=4)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def buildFromJsbString(self, jsb, nocompressjs=False): """ Build from the given config file using ``sencha build``. :param jsb: The JSB config as a string. :param nocompressjs: Compress the javascript? If ``True``, run ``sencha build --nocompress``. """
tempconffile = 'temp-app.jsb3' cmd = ['sencha', 'build', '-p', tempconffile, '-d', self.outdir] if nocompressjs: cmd.append('--nocompress') open(tempconffile, 'w').write(jsb) log.info('Running: %s', ' '.join(cmd)) try: call(cmd) finally: remove(tempconffile)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def determine_actions(self, request, view): """ For generic class based views we return information about the fields that are accepted for 'PUT' and 'POST' methods. """
actions = {} for method in {'PUT', 'POST'} & set(view.allowed_methods): view.request = clone_request(request, method) try: # Test global permissions if hasattr(view, 'check_permissions'): view.check_permissions(view.request) # Test object permissions if method == 'PUT' and hasattr(view, 'get_object'): view.get_object() except (exceptions.APIException, PermissionDenied, Http404): pass else: # If user has appropriate permissions for the view, include # appropriate metadata about the fields that should be supplied. serializer = view.get_serializer() actions[method] = self.get_serializer_info(serializer) finally: view.request = request return actions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def music_search(self, entitiy_type, query, **kwargs): """ Search the music database Where ``entitiy_type`` is a comma separated list of: ``song`` songs ``album`` albums ``composition`` compositions ``artist`` people working in music """
return self.make_request('music', entitiy_type, query, 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 amg_video_search(self, entitiy_type, query, **kwargs): """ Search the Movies and TV database Where ``entitiy_type`` is a comma separated list of: ``movie`` Movies ``tvseries`` TV series ``credit`` people working in TV or movies """
return self.make_request('amgvideo', entitiy_type, query, 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 video_search(self, entitiy_type, query, **kwargs): """ Search the TV schedule database Where ``entitiy_type`` is a comma separated list of: ``movie`` Movie ``tvseries`` TV series ``episode`` Episode titles ``onetimeonly`` TV programs ``credit`` People working in TV or movies """
return self.make_request('video', entitiy_type, query, 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 structureOutput(fileUrl, fileName, searchFiles, format=True, space=40): """Formats the output of a list of packages"""
#First, remove the filename if format: splitUrls = fileUrl[1:].split('/') fileUrl = "" for splitUrl in splitUrls: # This is a gimmicky fix to make formatting consistent # Cemetech doesn't have /pub/ at the front of it's repo paths # Also, Omnimaga has a /files/ we need to get rid of similarly # This probably *should* be repo-dependent, but oh well if splitUrl != "" and (not "." in splitUrl) and (splitUrl != "pub" and splitUrl != "files"): fileUrl += splitUrl + '/' elif "." in splitUrl: archiveName = splitUrl #Now, format the output if searchFiles: fileName = archiveName pause = (space - len(fileUrl)) output = fileUrl output += (" " * pause) output += fileName return output
<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(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""): """Counts the number of ticalc.org files containing some search term, doesn't return them"""
fileData = {} nameData = {} #Search the index if searchFiles: fileData = self.searchNamesIndex(self.fileIndex, fileData, searchString, category, math, game, extension) else: nameData = self.searchNamesIndex(self.nameIndex, nameData, searchString) #Now search the other index if searchFiles: nameData, fileData = self.searchFilesIndex(fileData, nameData, self.nameIndex, searchString) else: fileData, nameData = self.searchFilesIndex(nameData, fileData, self.fileIndex, searchString, category, math, game, extension) # Bail out if we failed to do either of those things. if fileData is None or nameData is None: self.repo.printd("Error: failed to load one or more of the index files for this repo. Exiting.") self.repo.printd("Please run 'calcpkg update' and retry this command.") sys.exit(1) #Now obtain a count (exclude "none" elements) count = 0 for element in nameData: if not nameData[element] is None: count += 1 self.repo.printd("Search for '" + searchString + "' returned " + str(count) + " result(s) in " + self.repo.name) return 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 searchHierarchy(self, fparent): """Core function to search directory structure for child files and folders of a parent"""
data = [] returnData = [] parentslashes = fparent.count('/') filecount = 0 foldercount = 0 #open files for folder searching try: dirFile = open(self.dirIndex, 'rt') except IOError: self.repo.printd("Error: Unable to read index file " + self.dirIndex) return #search for folders for fldr in dirFile: fldr = fldr.split('|') fldr = fldr[0] if fparent in fldr and parentslashes+1 == fldr.count('/'): returnData.append([fldr, fldr[fldr.rfind('/',1,-1):-1], ResultType.FOLDER]) foldercount += 1 dirFile.close() #open files for file searching try: fileFile = open(self.fileIndex, 'rt') except IOError: self.repo.printd("Error: Unable to read index file " + self.fileIndex) return try: nameFile = open(self.nameIndex, 'rt') except IOError: self.repo.printd("Error: Unable to read index file " + self.nameIndex) return #search for files for (path,name) in zip(fileFile,nameFile): if fparent in path and parentslashes == path.count('/'): returnData.append([path.strip(), name, ResultType.FILE]) filecount += 1 fileFile.close() nameFile.close() return [returnData, foldercount, filecount]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""): """Core function to search the indexes and return data"""
data = [] nameData = {} fileData = {} #Search the name index if searchFiles: fileData = self.searchNamesIndex(self.fileIndex, fileData, searchString, category, math, game, extension, searchFiles) else: nameData = self.searchNamesIndex(self.nameIndex, nameData, searchString) #Now search the file index if searchFiles: nameData, fileData = self.searchFilesIndex(fileData, nameData, self.nameIndex, searchString) else: fileData, nameData = self.searchFilesIndex(nameData, fileData, self.fileIndex, searchString, category, math, game, extension) # Bail out if we failed to do either of those things. if fileData is None or nameData is None: self.repo.printd("Error: failed to load one or more of the index files for this repo. Exiting.") self.repo.printd("Please run 'calcpkg update' and retry this command.") sys.exit(1) # Prepare output to parse space = 0 longestFile = len("File Name:") for key, value in nameData.iteritems(): fileValue = fileData[key] data.append([fileValue, value]) if not fileValue is None: folder = fileValue.rpartition("/")[0] if space < len(folder): space = len(folder) if not value is None: if longestFile < len(value): longestFile = len(value) #Print output space += 5 if len(data) != 0: self.repo.printd("Results for repo: " + self.repo.name) self.repo.printd(structureOutput("File Category:", "File Name:", False, False, space)) self.repo.printd("-" * (space + longestFile)) else: self.repo.printd("No packages found") returnData = [] for datum in data: try: self.repo.printd(structureOutput(datum[0], datum[1], searchFiles, True, space)) returnData.append([datum[0], datum[1]]) except: pass self.repo.printd(" ") #Return data return returnData
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def searchFilesIndex(self, nameData, fileData, fileIndex, searchString, category="", math=False, game=False, extension=""): """Search the files index using the namedata and returns the filedata"""
try: fileFile = open(fileIndex, 'rt') except IOError: self.repo.printd("Error: Unable to read index file " + self.fileIndex) return None, None count = 1 for line in fileFile: count += 1 try: if nameData[count] != None: #category argument if category in line: fileData[count] = line[:len(line) - 1] else: nameData[count] = None fileData[count] = None #extension argument if extension in line: fileData[count] = line[:len(line) - 1] else: nameData[count] = None fileData[count] = None #Both game and math if (game and math): if ("/games/" in line or "/math/" in line or "/science" in line): nameData[count] = line[:len(line) - 1] else: nameData[count] = None #game option switch elif game: if "/games/" in line: fileData[count] = line[:len(line) - 1] else: nameData[count] = None fileData[count] = None #math option switch elif math: if ("/math/" in line or "/science/" in line): fileData[count] = line[:len(line) - 1] else: nameData[count] = None fileData[count] = None except: pass #Close the file and return fileFile.close() return fileData, nameData
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def searchNamesIndex(self, nameIndex, nameData, searchString, category="", math=False, game=False, extension="", searchFiles=False): """Search the names index for a string and returns the namedata"""
nameData = {} try: nameFile = open(nameIndex, 'rt') except IOError: self.repo.printd("Error: Unable to read index file " + self.fileIndex) return None count = 1 for line in nameFile: count += 1 if searchString.lower() in line.lower(): #Extension argument if extension in line: nameData[count] = line[:len(line) - 1] else: nameData[count] = None #category arg if category in line and extension in line: nameData[count] = line[:len(line) - 1] else: nameData[count] = None #Both game and math if (game and math): if ("/games/" in line or "/math/" in line or "/science" in line): nameData[count] = line[:len(line) - 1] else: nameData[count] = None #Game option switch elif game: if "/games/" in line: nameData[count] = line[:len(line) - 1] else: nameData[count] = None #Math option switch elif math: if ("/math/" in line or "/science/" in line): nameData[count] = line[:len(line) - 1] else: nameData[count] = None #Close the name index and return nameFile.close() return nameData
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_parser(self, request, parsers): """ Given a list of parsers and a media type, return the appropriate parser to handle the incoming request. """
for parser in parsers: if media_type_matches(parser.media_type, request.content_type): return parser return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter_renderers(self, renderers, format): """ If there is a '.json' style format suffix, filter the renderers so that we only negotiation against those that accept that format. """
renderers = [renderer for renderer in renderers if renderer.format == format] if not renderers: raise Http404 return renderers
<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_accept_list(self, request): """ Given the incoming request, return a tokenised list of media type strings. """
header = request.META.get('HTTP_ACCEPT', '*/*') return [token.strip() for token in header.split(',')]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unit_pos_to_spot(unit_pos) -> ParkingSpot: """ Translates a unit position to a known parking spot Args: unit_pos: unit position as Vec2 Returns: ParkingSpot object """
min_ = 50 res = None for airport in parkings: for spot in parkings[airport]: # type: ignore spot_pos = parkings[airport][spot] # type: ignore dist = math.hypot(unit_pos[0] - spot_pos[0], unit_pos[1] - spot_pos[1]) if dist < min_: min_ = dist # type: ignore res = ParkingSpot(airport=airport, spot=spot) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect(self): """ Select the best suited data of all available in the subclasses. In each subclass, the functions alphabetical order should correspond to their importance. Here, the first non null value is returned. """
class_functions = [] for key in self.__class__.__dict__.keys(): func = self.__class__.__dict__[key] if (inspect.isfunction(func)): class_functions.append(func) functions = sorted(class_functions, key=lambda func: func.__name__) for function in functions: value = function(self) if value: return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(self): """ Initialize a new password db store """
self.y = {"version": int(time.time())} recipient_email = raw_input("Enter Email ID: ") self.import_key(emailid=recipient_email) self.encrypt(emailid_list=[recipient_email])
<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_users(self): """ Get user list from the encrypted passdb file """
crypt = self._decrypt_file() self.logger.info(crypt.stderr) raw_userlist = crypt.stderr.split('\n') userlist = list() for index, line in enumerate(raw_userlist): if 'gpg: encrypted' in line: m = re.search('ID (\w+)', line) keyid = m.group(1).strip() userline = raw_userlist[index+1].strip() userlist.append((keyid, userline)) return userlist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_user(self, recipient_email): """ Add user to encryption """
self.import_key(emailid=recipient_email) emailid_list = self.list_user_emails() self.y = self.decrypt() emailid_list.append(recipient_email) self.encrypt(emailid_list=emailid_list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_user(self, recipient_email): """ Remove user from encryption """
emailid_list = self.list_user_emails() if recipient_email not in emailid_list: raise Exception("User {0} not present!".format(recipient_email)) else: emailid_list.remove(recipient_email) self.y = self.decrypt() self.encrypt(emailid_list=emailid_list)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_meta(filename, data): """ Parse `data` to EPublication. Args: filename (str): Used to choose right parser based at suffix. data (str): Content of the metadata file. Returns: EPublication: object. """
if "." not in filename: raise MetaParsingException( "Can't recognize type of your metadata ('%s')!" % filename ) suffix = filename.rsplit(".", 1)[1].lower() if suffix not in SUPPORTED_FILES: raise MetaParsingException("Can't parse file of type '%s'!" % suffix) fp = validator.FieldParser() for key, val in SUPPORTED_FILES[suffix](data).items(): fp.process(key, val) return fp.get_epublication()
<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_instance(page_to_consume): """Return an instance of ConsumeModel."""
global _instances if isinstance(page_to_consume, basestring): uri = page_to_consume page_to_consume = consumepage.get_instance(uri) elif isinstance(page_to_consume, consumepage.ConsumePage): uri = page_to_consume.uri else: raise TypeError( "get_instance() expects a parker.ConsumePage " "or basestring derivative." ) try: instance = _instances[uri] except KeyError: instance = ConsumeModel(page_to_consume) _instances[uri] = instance return instance
<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_dict(self): """Return a dictionary of the object primed for dumping."""
data = self.data_dict.copy() data.update({ "class": self.classification, "tags": self.tags, "key_value_data": self.key_value_dict, "crumbs": self.crumb_list if len(self.crumb_list) > 0 else None, "media": [ mediafile.filename if mediafile.filename is not None else mediafile.uri for mediafile in self.media_list ] if len(self.media_list) > 0 else None, "uri": self.uri, "dumped": datetime.utcnow().isoformat(), }) return data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, name, redirect_uri=None): """Create a new Device object. Devices tie Users and Applications together. For your Application to access and act on behalf of a User, the User must authorize a Device created by your Application. This function will return a `device_token` which you must store and use after the Device is approved in `client.authenticate_device(api_token, device_token)` The second value returned is an `mfa_uri` which is the location the User must visit to approve the new device. After this function completes, you should launch a new browser tab or webview with this value as the location. After the User approves the Device, they will be redirected to the redirect_uri you specify in this call. Args: name (str): Human-readable name for the device (e.g. "Suzanne's iPhone") redirect_uri (str, optional): A URI to which to redirect the User after they approve the new Device. Returns: A tuple of (device_token, mfa_uri) """
data = dict(name=name) if redirect_uri: data['redirect_uri'] = redirect_uri auth_request_resource = self.resource.create(data) return (auth_request_resource.attributes['metadata']['device_token'], auth_request_resource.attributes['mfa_uri'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_option_parser(parser): """Hook to add global options Called from openstackclient.shell.OpenStackShell.__init__() after the builtin parser has been initialized. This is where a plugin can add global options such as an API version setting. :param argparse.ArgumentParser parser: The parser object that has been initialized by OpenStackShell. """
parser.add_argument( '--os-rdomanager-oscplugin-api-version', metavar='<rdomanager-oscplugin-api-version>', default=utils.env( 'OS_RDOMANAGER_OSCPLUGIN_API_VERSION', default=DEFAULT_RDOMANAGER_OSCPLUGIN_API_VERSION), help='RDO Manager OSC Plugin API version, default=' + DEFAULT_RDOMANAGER_OSCPLUGIN_API_VERSION + ' (Env: OS_RDOMANAGER_OSCPLUGIN_API_VERSION)') return parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def baremetal(self): """Returns an baremetal service client"""
# TODO(d0ugal): When the ironicclient has it's own OSC plugin, the # following client handling code should be removed in favor of the # upstream version. if self._baremetal is not None: return self._baremetal endpoint = self._instance.get_endpoint_for_service_type( "baremetal", region_name=self._instance._region_name, ) token = self._instance.auth.get_token(self._instance.session) self._baremetal = ironic_client.get_client( 1, os_auth_token=token, ironic_url=endpoint, ca_file=self._instance._cli_options.os_cacert) return self._baremetal
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def orchestration(self): """Returns an orchestration service client"""
# TODO(d0ugal): This code is based on the upstream WIP implementation # and should be removed when it lands: # https://review.openstack.org/#/c/111786 if self._orchestration is not None: return self._orchestration API_VERSIONS = { '1': 'heatclient.v1.client.Client', } heat_client = utils.get_client_class( API_NAME, self._instance._api_version[API_NAME], API_VERSIONS) LOG.debug('Instantiating orchestration client: %s', heat_client) endpoint = self._instance.get_endpoint_for_service_type( 'orchestration') token = self._instance.auth.get_token(self._instance.session) client = heat_client( endpoint=endpoint, auth_url=self._instance._auth_url, token=token, username=self._instance._username, password=self._instance._password, region_name=self._instance._region_name, insecure=self._instance._insecure, ca_file=self._instance._cli_options.os_cacert, ) self._orchestration = client return self._orchestration
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def management(self): """Returns an management service client"""
endpoint = self._instance.get_endpoint_for_service_type( "management", region_name=self._instance._region_name, ) token = self._instance.auth.get_token(self._instance.session) self._management = tuskar_client.get_client( 2, os_auth_token=token, tuskar_url=endpoint) return self._management
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def media_type_matches(lhs, rhs): """ Returns ``True`` if the media type in the first argument <= the media type in the second argument. The media types are strings as described by the HTTP spec. Valid media type strings include: 'application/json; indent=4' 'application/json' 'text/*' '*/*' """
lhs = _MediaType(lhs) rhs = _MediaType(rhs) return lhs.match(rhs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def subclasses(cls, lst=None): '''Recursively gather subclasses of cls. ''' if lst is None: lst = [] for sc in cls.__subclasses__(): if sc not in lst: lst.append(sc) subclasses(sc, lst=lst) return lst
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def nearest_base(cls, bases): '''Returns the closest ancestor to cls in bases. ''' if cls in bases: return cls dists = {base: index(mro(cls), base) for base in bases} dists2 = {dist: base for base, dist in dists.items() if dist is not None} if not dists2: return None return dists2[min(dists2)]
<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_typename(x): '''Returns the name of the type of x, if x is an object. Otherwise, returns the name of x. ''' if isinstance(x, type): ret = x.__name__ else: ret = x.__class__.__name__ return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getfunc(obj, name=''): '''Get the function corresponding to name from obj, not the method.''' if name: obj = getattr(obj, name) return getattr(obj, '__func__', 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 get_mod(cls): '''Returns the string identifying the module that cls is defined in. ''' if isinstance(cls, (type, types.FunctionType)): ret = cls.__module__ else: ret = cls.__class__.__module__ return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def this_module(npop=1): '''Returns the module object of the module this function is called from ''' stack = inspect.stack() st = stack[npop] frame = st[0] return inspect.getmodule(frame)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assert_equivalent(o1, o2): '''Asserts that o1 and o2 are distinct, yet equivalent objects ''' if not (isinstance(o1, type) and isinstance(o2, type)): assert o1 is not o2 assert o1 == o2 assert o2 == o1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assert_inequivalent(o1, o2): '''Asserts that o1 and o2 are distinct and inequivalent objects ''' if not (isinstance(o1, type) and isinstance(o2, type)): assert o1 is not o2 assert not o1 == o2 and o1 != o2 assert not o2 == o1 and o2 != o1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assert_type_equivalent(o1, o2): '''Asserts that o1 and o2 are distinct, yet equivalent objects of the same type ''' assert o1 == o2 assert o2 == o1 assert type(o1) is type(o2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def elog(exc, func, args=None, kwargs=None, str=str, pretty=True, name=''): '''For logging exception-raising function invocations during randomized unit tests. ''' from .str import safe_str args = args if args else () kwargs = kwargs if kwargs else {} name = '{}.{}'.format(get_mod(func), name) if name else full_funcname(func) if pretty: invocation = ', '.join([safe_str(arg) for arg in args]) if kwargs: invocation += ', ' invocation += ', '.join(['{}={}'.format(key, safe_str(value)) for key, value in sorted(kwargs.items())]) else: invocation = 'args={}, kwargs={}'.format(safe_str(args), safe_str(kwargs)) msg = '***{}***: "{}" --- {}({})'.format(get_typename(exc), message(exc), name, invocation) elogger.error(msg)
<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_body(self): """Get the body of the email message"""
if self.is_multipart(): # get the plain text version only text_parts = [part for part in typed_subpart_iterator(self, 'text', 'plain')] body = [] for part in text_parts: charset = get_charset(part, get_charset(self)) body.append(unicode(part.get_payload(decode=True), charset, "replace")) return u"\n".join(body).strip() else: # if it is not multipart, the payload will be a string # representing the message body body = unicode(self.get_payload(decode=True), get_charset(self), "replace") return body.strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listen(self): """Blocking call on widgets. """
while self._listen: key = u'' key = self.term.inkey(timeout=0.2) try: if key.code == KEY_ENTER: self.on_enter(key=key) elif key.code in (KEY_DOWN, KEY_UP): self.on_key_arrow(key=key) elif key.code == KEY_ESCAPE or key == chr(3): self.on_exit(key=key) elif key != '': self.on_key(key=key) except KeyboardInterrupt: self.on_exit(key=key)
<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(self, widget, *args, **kwargs): """Insert new element. Usage: window.add(widget, **{ 'prop1': val, 'prop2': val2 }) """
ins_widget = widget(*args, **kwargs) self.__iadd__(ins_widget) return ins_widget
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def search_terms(q): '''Takes a search string and parses it into a list of keywords and phrases.''' tokens = parse_search_terms(q) # iterate through all the tokens and make a list of token values # (which are the actual words and phrases) values = [] for t in tokens: # word/phrase if t[0] is None: values.append(t[1]) # incomplete field elif t[1] is None: values.append('%s:' % t[0]) # anything else must be a field, value pair # - if value includes whitespace, wrap in quotes elif re.search('\s', t[1]): values.append('%s:"%s"' % t) # otherwise, leave unquoted else: values.append('%s:%s' % t) return values