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 well(self, well_x=1, well_y=1): """ScanWellData of specific well. Parameters well_x : int well_y : int Returns ------- lxml.objectify.ObjectifiedElement """
xpath = './ScanWellData' xpath += _xpath_attrib('WellX', well_x) xpath += _xpath_attrib('WellY', well_y) # assume we find only one return self.well_array.find(xpath)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def field(self, well_x=1, well_y=1, field_x=1, field_y=1): """ScanFieldData of specified field. Parameters well_x : int well_y : int field_x : int field_y : int Returns ------- lxml.objectify.ObjectifiedElement ScanFieldArray/ScanFieldData element. """
xpath = './ScanFieldArray/ScanFieldData' xpath += _xpath_attrib('WellX', well_x) xpath += _xpath_attrib('WellY', well_y) xpath += _xpath_attrib('FieldX', field_x) xpath += _xpath_attrib('FieldY', field_y) # assume we find only one return self.root.find(xpath)
<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_start_position(self): "Set start position of experiment to position of first field." x_start = self.field_array.ScanFieldData.FieldXCoordinate y_start = self.field_array.ScanFieldData.FieldYCoordinate # empty template have all fields positions set to zero # --> avoid overwriting start position if x_start != 0 and y_start != 0: self.properties.ScanFieldStageStartPositionX = int(x_start * 1e6) # in um self.properties.ScanFieldStageStartPositionY = int(y_start * 1e6)
<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_counts(self): "Update counts of fields and wells." # Properties.attrib['TotalCountOfFields'] fields = str(len(self.fields)) self.properties.attrib['TotalCountOfFields'] = fields # Properties.CountOfWellsX/Y wx, wy = (str(x) for x in self.count_of_wells) self.properties.CountOfWellsX = wx self.properties.CountOfWellsY = wy # Properties.attrib['TotalCountOfWells'] wells = str(len(self.wells)) self.properties.attrib['TotalCountOfWells'] = wells # Properties.attrib['TotalAssignedJobs'] self.properties.attrib['TotalAssignedJobs'] = str(self.count_of_assigned_jobs)
<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_well(self, well_x, well_y): """Remove well and associated scan fields. Parameters well_x : int well_y : int Raises ------ AttributeError If well not found. """
well = self.well(well_x, well_y) if well == None: raise AttributeError('Well not found') self.well_array.remove(well) # remove associated fields fields = self.well_fields(well_x, well_y) for f in fields: self.field_array.remove(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 field_exists(self, well_x, well_y, field_x, field_y): "Check if field exists ScanFieldArray." return self.field(well_x, well_y, field_x, field_y) != 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 write(self, filename=None): """Save template to xml. Before saving template will update date, start position, well positions, and counts. Parameters filename : str If not set, XML will be written to self.filename. """
if not filename: filename = self.filename # update time self.properties.CurrentDate = _current_time() # set rubber band to true self.properties.EnableRubberBand = 'true' # update start position self.update_start_position() # update well postions self.update_well_positions() # update counts self.update_counts() # remove py:pytype attributes objectify.deannotate(self.root) # remove namespaces added by lxml for child in self.root.iterchildren(): etree.cleanup_namespaces(child) xml = etree.tostring(self.root, encoding='utf8', xml_declaration=True, pretty_print=True) # fix format quirks # add carriage return character xml = u'\r\n'.join(l.decode(encoding='utf8') for l in xml.splitlines()) # add space at "end/>" --> "end />" xml = re.sub(r'(["a-z])/>', r'\1 />', xml) xml = xml.replace("version='1.0' encoding='utf8'", 'version="1.0"') with open(filename, 'wb') as f: f.write(xml.encode('utf8'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def preserve_attr_data(A, B): '''Preserve attr data for combining B into A. ''' for attr, B_data in B.items(): # defined object attrs if getattr(B_data, 'override_parent', True): continue if attr in A: A_data = A[attr] for _attr in getattr(A_data, '_attrs', []): # Attr attrs, like type, default, & doc if hasattr(A_data, _attr): if getattr(B_data, _attr, None) is not None: if _attr in getattr(B_data, '_set_by_default', []): setattr(B_data, _attr, getattr(A_data, _attr)) else: setattr(B_data, _attr, getattr(A_data, _attr))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def graft(coll, branch, index): '''Graft list branch into coll at index ''' pre = coll[:index] post = coll[index:] ret = pre + branch + post 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 metaclasses(bases): ''' Returns 'proper' metaclasses for the classes in bases ''' ret = [] metas = [type(base) for base in bases] for k,meta in enumerate(metas): if not any(issubclass(m, meta) for m in metas[k+1:]): ret.append(meta) if type in ret: ret.remove(type) 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 _combine_attr_fast_update(self, attr, typ): '''Avoids having to call _update for each intermediate base. Only works for class attr of type UpdateDict. ''' values = dict(getattr(self, attr, {})) for base in self._class_data.bases: vals = dict(getattr(base, attr, {})) preserve_attr_data(vals, values) values = combine(vals, values) setattr(self, attr, typ(values))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(ctx, collections, threads, debug): """ A configurable data and document processing tool. """
ctx.obj = { 'collections': collections, 'debug': debug, 'threads': threads } if debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_dependencies(nodes): """ Figure out which order the nodes in the graph can be executed in to satisfy all requirements. """
done = set() while True: if len(done) == len(nodes): break for node in nodes: if node.name not in done: match = done.intersection(node.requires) if len(match) == len(node.requires): done.add(node.name) yield node break else: raise ConfigException('Invalid requirements in pipeline!')
<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_yaml_configuration(filename): '''Parse configuration in YAML format into a Python dict :param filename: filename of a file with configuration in YAML format :return: unprocessed configuration object :rtype: dict ''' with open(filename, 'r') as f: config = yaml.load(f.read()) return config
<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_type(filename): '''Determine the file type and return it.''' ftype = magic.from_file(filename, mime=True).decode('utf8') if ftype == 'text/plain': ftype = 'text' elif ftype == 'image/svg+xml': ftype = 'svg' else: ftype = ftype.split('/')[1] return ftype
<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_configuration(orig, new): '''Update existing configuration with new values. Needed because dict.update is shallow and would overwrite nested dicts. Function updates sections commands, parameters and pipelines and adds any new items listed in updates. :param orig: configuration to update :type orig: dict :param new: new updated values :type orig: dict ''' dicts = ('commands', 'parameters', 'pipelines') for key in dicts: if key in new: orig[key].update(new[key]) for key in new: if key not in dicts: orig[key] = new[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 check_configuration(config): '''Check if configuration object is not malformed. :param config: configuration :type config: dict :return: is configuration correct? :rtype: bool ''' sections = ('commands', 'parameters', 'pipelines') # Check all sections are there and contain dicts for section in sections: if section not in config: error_msg = 'Error: Section {0} is missing.'.format(section) raise ConfigurationErrorDietException(error_msg) if not isinstance(config[section], dict): error_msg = 'Error: Section {0} is malformed.'.format(section) raise ConfigurationErrorDietException(error_msg) # Check every command has a corresponding parameters entry commands_cmds = set(list(config['commands'].keys())) parameters_cmds = set(list(config['parameters'].keys())) if commands_cmds != parameters_cmds: error_msg = ('Every command in commands and parameters section has to ' 'have a corresponding entry in the other section.') raise ConfigurationErrorDietException(error_msg) # Check pipelines section contains lists as values and each of them only # has entries listed in commands section for cmd in config['pipelines']: pipeline = config['pipelines'][cmd] if not isinstance(pipeline, list): error_msg = ('Error: Pipeline {0} is malformed. Values have to ' 'be a list of command names.').format(cmd) raise ConfigurationErrorDietException(error_msg) for tool in pipeline: if tool not in commands_cmds: error_msg = ('Error in pipeline {0}. "{1}" cannot be found ' 'among commands listed in commands ' 'section').format(cmd, tool) raise ConfigurationErrorDietException(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 diet(filename, configuration): ''' Squeeze files if there is a pipeline defined for them or leave them be otherwise. :param filename: filename of the file to process :param configuration: configuration dict describing commands and pipelines :type configuration: dict :return: has file changed :rtype: bool ''' changed = False if not isfile(filename): raise NotFileDietException('Passed filename does not point to a file') conf = copy.deepcopy(DEFAULT_CONFIG) if not configuration.get('parsed'): new_config = parse_configuration(configuration) else: new_config = configuration update_configuration(conf, new_config) filetype = determine_type(filename) squeeze_cmd = conf['pipelines'].get(filetype) if squeeze_cmd: tmpbackup_ext = 'diet_internal' ext = conf.get('backup', tmpbackup_ext) backup = backup_file(filename, ext) size = os.stat(filename).st_size new_size = squeeze(squeeze_cmd, filename, backup) if not conf.get('keep_processed', False) and new_size > size: copy_if_different(backup, filename) # Delete backup, if it was internal if not conf.get('backup'): os.remove(backup) changed = True return changed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auth_scheme(self): """ If an Authorization header is present get the scheme It is expected to be the first string in a space separated list & will always be returned lowercase. :return: str or None """
try: auth = getattr(self, 'auth') return naked(auth.split(' ')[0]).lower() except (AttributeError, IndexError): 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 _init_content_type_params(self): """ Return the Content-Type request header parameters Convert all of the semi-colon separated parameters into a dict of key/vals. If for some stupid reason duplicate & conflicting params are present then the last one wins. If a particular content-type param is non-compliant by not being a simple key=val pair then it is skipped. If no content-type header or params are present then return an empty dict. :return: dict """
ret = {} if self.content_type: params = self.content_type.split(';')[1:] for param in params: try: key, val = param.split('=') ret[naked(key)] = naked(val) except ValueError: continue 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 _handle_match(client, channel, nick, message, matches): """ Match stores all channel info. If helga is asked something to stimulate a markov response about channel data, then we shall graciously provide it. """
generate_interrogative = _CHANNEL_GENERATE_REGEX.match(message) if generate_interrogative: return generate(_DEFAULT_TOPIC, _ADD_PUNCTUATION) current_topic = db.markovify.find_one({'topic': _DEFAULT_TOPIC}) if current_topic: message = punctuate(current_topic['text'], message, _ADD_PUNCTUATION) try: ingest(_DEFAULT_TOPIC, message) except ValueError as e: # not good, but this is done every message so just move along print 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 require_root(fn): """ Decorator to make sure, that user is root. """
@wraps(fn) def xex(*args, **kwargs): assert os.geteuid() == 0, \ "You have to be root to run function '%s'." % fn.__name__ return fn(*args, **kwargs) return xex
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recursive_chmod(path, mode=0755): """ Recursively change ``mode`` for given ``path``. Same as ``chmod -R mode``. Args: path (str): Path of the directory/file. mode (octal int, default 0755): New mode of the file. Warning: Don't forget to add ``0`` at the beginning of the numbers of `mode`, or `Unspeakable hOrRoRs` will be awaken from their unholy sleep outside of the reality and they WILL eat your soul (and your files). """
passwd_reader.set_permissions(path, mode=mode) if os.path.isfile(path): return # recursively change mode of all subdirectories for root, dirs, files in os.walk(path): for fn in files + dirs: passwd_reader.set_permissions(os.path.join(root, fn), mode=mode)
<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(username, password): """ Adds record to passwd-like file for ProFTPD, creates home directory and sets permissions for important files. Args: username (str): User's name. password (str): User's password. """
assert _is_valid_username(username), \ "Invalid format of username '%s'!" % username assert username not in passwd_reader.load_users(), \ "User '%s' is already registered!" % username assert password, "Password is reqired!" # add new user to the proftpd's passwd file home_dir = settings.DATA_PATH + username sh.ftpasswd( passwd=True, # passwd file, not group file name=username, home=home_dir, # chroot in DATA_PATH shell="/bin/false", uid=settings.PROFTPD_USERS_GID, # TODO: parse dynamically? gid=settings.PROFTPD_USERS_GID, stdin=True, # tell ftpasswd to read password from stdin file=settings.LOGIN_FILE, _in=password ) # create home dir if not exists if not os.path.exists(home_dir): os.makedirs(home_dir, 0775) # I am using PROFTPD_USERS_GID (2000) for all our users - this GID # shouldn't be used by other than FTP users! passwd_reader.set_permissions(home_dir, gid=settings.PROFTPD_USERS_GID) passwd_reader.set_permissions(settings.LOGIN_FILE, mode=0600) create_lock_file(home_dir + "/" + settings.LOCK_FILENAME) reload_configuration()
<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_user(username): """ Remove user, his home directory and so on.. Args: username (str): User's name. """
users = passwd_reader.load_users() assert username in users, "Username '%s' not found!" % username # remove user from passwd file del users[username] passwd_reader.save_users(users) # remove home directory home_dir = settings.DATA_PATH + username if os.path.exists(home_dir): shutil.rmtree(home_dir) reload_configuration()
<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_password(username, new_password): """ Change password for given `username`. Args: username (str): User's name. new_password (str): User's new password. """
assert username in passwd_reader.load_users(),\ "Username '%s' not found!" % username sh.ftpasswd( "--change-password", passwd=True, # passwd file, not group file name=username, stdin=True, # tell ftpasswd to read password from stdin file=settings.LOGIN_FILE, _in=new_password ) reload_configuration()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDataPath(_system=thisSystem, _FilePath=FilePath): """Gets an appropriate path for storing some local data, such as TLS credentials. If the path doesn't exist, it is created. """
if _system == "Windows": pathName = "~/Crypto101/" else: pathName = "~/.crypto101/" path = _FilePath(expanduser(pathName)) if not path.exists(): path.makedirs() return 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 get_zoneID(self, headers, zone): """Get the zone id for the zone."""
zoneIDurl = self.BASE_URL + '?name=' + zone zoneIDrequest = requests.get(zoneIDurl, headers=headers) zoneID = zoneIDrequest.json()['result'][0]['id'] return zoneID
<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_recordInfo(self, headers, zoneID, zone, records): """Get the information of the records."""
if 'None' in records: #If ['None'] in record argument, query all. recordQueryEnpoint = '/' + zoneID + '/dns_records&per_page=100' recordUrl = self.BASE_URL + recordQueryEnpoint recordRequest = requests.get(recordUrl, headers=headers) recordResponse = recordRequest.json()['result'] dev = [] num = 0 for value in recordResponse: recordName = recordResponse[num]['name'] dev.append(recordName) num = num + 1 records = dev updateRecords = [] for record in records: if zone in record: recordFullname = record else: recordFullname = record + '.' + zone recordQuery = '/' + zoneID + '/dns_records?name=' + recordFullname recordUrl = self.BASE_URL + recordQuery recordInfoRequest = requests.get(recordUrl, headers=headers) recordInfoResponse = recordInfoRequest.json()['result'][0] recordID = recordInfoResponse['id'] recordType = recordInfoResponse['type'] recordProxy = str(recordInfoResponse['proxied']) recordContent = recordInfoResponse['content'] if recordProxy == 'True': recordProxied = True else: recordProxied = False updateRecords.append([recordID, recordFullname, recordType, recordContent, recordProxied]) return updateRecords
<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_records(self, headers, zoneID, updateRecords): """Update DNS records."""
IP = requests.get(self.GET_EXT_IP_URL).text message = True errorsRecords = [] sucessRecords = [] for record in updateRecords: updateEndpoint = '/' + zoneID + '/dns_records/' + record[0] updateUrl = self.BASE_URL + updateEndpoint data = json.dumps({ 'id': zoneID, 'type': record[2], 'name': record[1], 'content': IP, 'proxied': record[4] }) if record[3] != IP and record[2] == 'A': result = requests.put(updateUrl, headers=headers, data=data).json() if result['success'] == True: sucessRecords.append(record[1]) else: errorsRecords.append(record[1]) if errorsRecords != []: message = ("There was an error updating these records: " + str(errorsRecords) + " , the rest is OK.") else: message = ("These records got updated: " + str(sucessRecords)) return message
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_view(self, request, object_id, form_url='', extra_context={}): """ It adds ButtonLinks and ButtonForms to extra_context used in the change_form template """
extra_context['buttons_link'] = self.buttons_link extra_context['buttons_form'] = self.buttons_form extra_context['button_object_id'] = object_id return super(ButtonableModelAdmin, self).change_view(request, object_id, form_url, extra_context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def FaultFromException(ex, inheader, tb=None, actor=None): '''Return a Fault object created from a Python exception. <SOAP-ENV:Fault> <faultcode>SOAP-ENV:Server</faultcode> <faultstring>Processing Failure</faultstring> <detail> <ZSI:FaultDetail> <ZSI:string></ZSI:string> <ZSI:trace></ZSI:trace> </ZSI:FaultDetail> </detail> </SOAP-ENV:Fault> ''' tracetext = None if tb: try: lines = '\n'.join(['%s:%d:%s' % (name, line, func) for name, line, func, text in traceback.extract_tb(tb)]) except: pass else: tracetext = lines exceptionName = "" try: exceptionName = ":".join([ex.__module__, ex.__class__.__name__]) except: pass elt = ZSIFaultDetail(string=exceptionName + "\n" + str(ex), trace=tracetext) if inheader: detail, headerdetail = None, elt else: detail, headerdetail = elt, None return Fault(Fault.Server, 'Processing Failure', actor, detail, headerdetail)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def FaultFromFaultMessage(ps): '''Parse the message as a fault. ''' pyobj = ps.Parse(FaultType.typecode) if pyobj.detail == None: detailany = None else: detailany = pyobj.detail.any return Fault(pyobj.faultcode, pyobj.faultstring, pyobj.faultactor, detailany)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def serialize(self, sw): '''Serialize the object.''' detail = None if self.detail is not None: detail = Detail() detail.any = self.detail pyobj = FaultType(self.code, self.string, self.actor, detail) sw.serialize(pyobj, typed=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 parse(page_to_parse): """Return a parse of page.content. Wraps PyQuery."""
global _parsed if not isinstance(page_to_parse, page.Page): raise TypeError("parser.parse requires a parker.Page object.") if page_to_parse.content is None: raise ValueError("parser.parse requires a fetched parker.Page object.") try: parsed = _parsed[page_to_parse] except KeyError: parsed = parsedpage.ParsedPage( page=page_to_parse, parsed=PyQuery(page_to_parse.content, parser='html') ) _parsed[page_to_parse] = parsed return parsed
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def sort_data(self, data, sort_key, reverse=False): """Sort dataset."""
sorted_data = [] lines = sorted(data, key=lambda k: k[sort_key], reverse=reverse) for line in lines: sorted_data.append(line) return sorted_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def iso(self, source): """Convert to timestamp."""
from datetime import datetime unix_timestamp = int(source) return datetime.fromtimestamp(unix_timestamp).isoformat()
<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(api_key, query, offset=0, type='personal'): """Get a list of email addresses for the provided domain. The type of search executed will vary depending on the query provided. Currently this query is restricted to either domain searches, in which the email addresses (and other bits) for the domain are returned, or searches for an email address. The latter is primary meant for checking if an email address exists, although various other useful bits are also provided (for example, the domain where the address was found). :param api_key: Secret client API key. :param query: URL or email address on which to search. :param offset: Specifies the number of emails to skip. :param type: Specifies email type (i.e. generic or personal). """
if not isinstance(api_key, str): raise InvalidAPIKeyException('API key must be a string') if not api_key or len(api_key) < 40: raise InvalidAPIKeyException('Invalid API key.') url = get_endpoint(api_key, query, offset, type) try: return requests.get(url).json() except requests.exceptions.RequestException as err: raise PunterException(err)
<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_clinamen(self, input_word, list_of_dict_words, swerve): """ Generate a clinamen. Here we looks for words via the damerau levenshtein distance with a distance of 2. """
results = [] selected_list = [] for i in list_of_dict_words: #produce a subset for efficency if len(i) < len(input_word)+1 and len(i) > len(input_word)/2: if '_' not in i: selected_list.append(i) for i in selected_list: match = self.damerau_levenshtein_distance(input_word,i) if match == swerve: results.append(i) results = {'input' : input_word, 'results' : results, 'category' : 'clinamen'} return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tick(self): """ Advances time in the game. Use this once all "choices" have been submitted for the current game state using the other methods. """
if self.state == AuctionState.NOMINATE: # if no nominee submitted, exception if self.nominee is None: raise InvalidActionError("Tick was invoked during nomination but no nominee was selected.") self.state = AuctionState.BID # initialize bids array to hold each owner's bid # this holds the latest bids submitted for the current bidding phase self.bids = [self.bid if i == self.turn_index else 0 for i in range(len(self.owners))] # this holds the bids submitted on a given tick self.tickbids = [0] * len(self.owners) elif self.state == AuctionState.BID: # If no new bids submitted, we're done with this bid and the player gets what they bid for if not any(bid > 0 for bid in self.tickbids): winner = self._winning_owner() winner.buy(self.nominee, self.bid) self._player_ownership[self._nominee_index] = self.winning_owner_index() self.undrafted_players.remove(self.nominee) self.nominee = None self._nominee_index = -1 # check if we're done, or move to the next player who still has space done = True for i in range(len(self.owners)): next_turn = (self.turn_index + 1 + i) % len(self.owners) if self.owners[next_turn].remaining_picks() > 0: self.turn_index = next_turn done = False break # if we didn't move on, we're done if done: self.state = AuctionState.DONE else: self.state = AuctionState.NOMINATE else: # new bids have been submitted, # randomly pick the bid to accept from the highest, # then everyone gets a chance to submit more top_idxs = [i for i, bid in enumerate(self.tickbids) if bid == max(self.tickbids)] accept_idx = random.choice(top_idxs) # set this as the new bid self.bid = self.tickbids[accept_idx] # update the bids for this round self.bids[accept_idx] = self.bid # clear this for the next tick self.tickbids = [0] * len(self.owners)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nominate(self, owner_id, player_idx, bid): """ Nominates the player for auctioning. :param int owner_id: index of the owner who is nominating :param int player_idx: index of the player to nominate in the players list :param int bid: starting bid :raise InvalidActionError: if the action is not allowed according to the rules. See the error message for details. """
owner = self.owners[owner_id] nominated_player = self.players[player_idx] if self.state != AuctionState.NOMINATE: raise InvalidActionError("Owner " + str(owner_id) + " tried to nominate, but Auction state " "is not NOMINATE, so nomination is not allowed") elif self.turn_index != owner_id: raise InvalidActionError("Owner " + str(owner_id) + " tried to nominate, but it is currently " + str(self.turn_index) + "'s turn") elif nominated_player not in self.undrafted_players: raise InvalidActionError("Owner " + str(owner_id) + "tried to nominate the player with index " + str(player_idx) + ", named " + nominated_player.name + ", but they have already been purchased and cannot be nominated.") elif bid > owner.max_bid(): raise InvalidActionError("Bid amount was " + str(bid) + " but this owner (Owner " + str(owner_id) + " can only bid a maximum of " + str(owner.max_bid())) elif bid < 1: raise InvalidActionError("Owner " + str(owner_id) + "'s bid amount was " + str(bid) + " but must be greater than 1") elif not owner.can_buy(nominated_player, bid): raise InvalidActionError("Owner " + str(owner_id) + " cannot make this nomination for player with index " + str(player_idx) + ", named " + nominated_player.name + ", because they cannot slot or cannot" " afford the player for the specified bid amount") # nomination successful, bidding time self.nominee = nominated_player self._nominee_index = player_idx self.bid = bid self.tickbids[owner_id] = bid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on_post(self, req, resp): """ Validate the access token request for spec compliance The spec also dictates the JSON based error response on failure & is handled in this responder. """
grant_type = req.get_param('grant_type') password = req.get_param('password') username = req.get_param('username') # errors or not, disable client caching along the way # per the spec resp.disable_caching() if not grant_type or not password or not username: resp.status = falcon.HTTP_400 resp.serialize({ 'error': 'invalid_request', 'error_description': 'A grant_type, username, & password ' 'parameters are all required when ' 'requesting an OAuth access_token', 'error_uri': 'tools.ietf.org/html/rfc6749#section-4.3.2', }) elif grant_type != 'password': resp.status = falcon.HTTP_400 resp.serialize({ 'error': 'unsupported_grant_type', 'error_description': 'The grant_type parameter MUST be set ' 'to "password" not "%s"' % grant_type, 'error_uri': 'tools.ietf.org/html/rfc6749#section-4.3.2', }) else: try: token = self.auth_creds(username, password) resp.serialize({ 'access_token': token, 'token_type': 'Bearer', }) except AuthRejected as exc: resp.status = falcon.HTTP_401 resp.set_header('WWW-Authenticate', self._realm) resp.serialize({ 'error': 'invalid_client', 'error_description': exc.detail, })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generate_anomaly(self, input_word, list_of_dict_words, num): """ Generate an anomaly. This is done via a Psuedo-random number generator. """
results = [] for i in range(0,num): index = randint(0,len(list_of_dict_words)-1) name = list_of_dict_words[index] if name != input_word and name not in results: results.append(PataLib().strip_underscore(name)) else: i = i +1 results = {'input' : input_word, 'results' : results, 'category' : 'anomaly'} return results
<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_checkable_button(instance, prop, widget): """ Connect a boolean callback property with a Qt button widget. Parameters instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setChecked`` method and the ``toggled`` signal. """
add_callback(instance, prop, widget.setChecked) widget.toggled.connect(partial(setattr, instance, prop)) widget.setChecked(getattr(instance, prop) or 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 connect_text(instance, prop, widget): """ Connect a string callback property with a Qt widget containing text. Parameters instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. """
def update_prop(): val = widget.text() setattr(instance, prop, val) def update_widget(val): if hasattr(widget, 'editingFinished'): widget.blockSignals(True) widget.setText(val) widget.blockSignals(False) widget.editingFinished.emit() else: widget.setText(val) add_callback(instance, prop, update_widget) try: widget.editingFinished.connect(update_prop) except AttributeError: pass update_widget(getattr(instance, prop))
<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_combo_data(instance, prop, widget): """ Connect a callback property with a QComboBox widget based on the userData. Parameters instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QComboBox The combo box to connect. See Also -------- connect_combo_text: connect a callback property with a QComboBox widget based on the text. """
def update_widget(value): try: idx = _find_combo_data(widget, value) except ValueError: if value is None: idx = -1 else: raise widget.setCurrentIndex(idx) def update_prop(idx): if idx == -1: setattr(instance, prop, None) else: setattr(instance, prop, widget.itemData(idx)) add_callback(instance, prop, update_widget) widget.currentIndexChanged.connect(update_prop) update_widget(getattr(instance, prop))
<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_combo_text(instance, prop, widget): """ Connect a callback property with a QComboBox widget based on the text. Parameters instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QComboBox The combo box to connect. See Also -------- connect_combo_data: connect a callback property with a QComboBox widget based on the userData. """
def update_widget(value): try: idx = _find_combo_text(widget, value) except ValueError: if value is None: idx = -1 else: raise widget.setCurrentIndex(idx) def update_prop(idx): if idx == -1: setattr(instance, prop, None) else: setattr(instance, prop, widget.itemText(idx)) add_callback(instance, prop, update_widget) widget.currentIndexChanged.connect(update_prop) update_widget(getattr(instance, prop))
<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_float_text(instance, prop, widget, fmt="{:g}"): """ Connect a numerical callback property with a Qt widget containing text. Parameters instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. fmt : str or func This should be either a format string (in the ``{}`` notation), or a function that takes a number and returns a string. """
if callable(fmt): format_func = fmt else: def format_func(x): return fmt.format(x) def update_prop(): val = widget.text() try: setattr(instance, prop, float(val)) except ValueError: setattr(instance, prop, 0) def update_widget(val): if val is None: val = 0. widget.setText(format_func(val)) add_callback(instance, prop, update_widget) try: widget.editingFinished.connect(update_prop) except AttributeError: pass update_widget(getattr(instance, prop))
<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_value(instance, prop, widget, value_range=None, log=False): """ Connect a numerical callback property with a Qt widget representing a value. Parameters instance : object The class instance that the callback property is attached to prop : str The name of the callback property widget : QtWidget The Qt widget to connect. This should implement the ``setText`` and ``text`` methods as well optionally the ``editingFinished`` signal. value_range : iterable, optional A pair of two values representing the true range of values (since Qt widgets such as sliders can only have values in certain ranges). log : bool, optional Whether the Qt widget value should be mapped to the log of the callback property. """
if log: if value_range is None: raise ValueError("log option can only be set if value_range is given") else: value_range = math.log10(value_range[0]), math.log10(value_range[1]) def update_prop(): val = widget.value() if value_range is not None: imin, imax = widget.minimum(), widget.maximum() val = (val - imin) / (imax - imin) * (value_range[1] - value_range[0]) + value_range[0] if log: val = 10 ** val setattr(instance, prop, val) def update_widget(val): if val is None: widget.setValue(0) return if log: val = math.log10(val) if value_range is not None: imin, imax = widget.minimum(), widget.maximum() val = (val - value_range[0]) / (value_range[1] - value_range[0]) * (imax - imin) + imin widget.setValue(val) add_callback(instance, prop, update_widget) widget.valueChanged.connect(update_prop) update_widget(getattr(instance, prop))
<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_button(instance, prop, widget): """ Connect a button with a callback method Parameters instance : object The class instance that the callback method is attached to prop : str The name of the callback method widget : QtWidget The Qt widget to connect. This should implement the ``clicked`` method """
widget.clicked.connect(getattr(instance, prop))
<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_combo_data(widget, value): """ Returns the index in a combo box where itemData == value Raises a ValueError if data is not found """
# Here we check that the result is True, because some classes may overload # == and return other kinds of objects whether true or false. for idx in range(widget.count()): if widget.itemData(idx) is value or (widget.itemData(idx) == value) is True: return idx else: raise ValueError("%s not found in combo box" % (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 _find_combo_text(widget, value): """ Returns the index in a combo box where text == value Raises a ValueError if data is not found """
i = widget.findText(value) if i == -1: raise ValueError("%s not found in combo box" % value) else: return i
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def class_repr(value): """Returns a representation of the value class. Arguments --------- value A class or a class instance Returns ------- str The "module.name" representation of the value class. Example ------- 'datetime.date' 'datetime.date' """
klass = value if not isinstance(value, type): klass = klass.__class__ return '.'.join([klass.__module__, klass.__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 rand_unicode(min_char=MIN_UNICHR, max_char=MAX_UNICHR, min_len=MIN_STRLEN, max_len=MAX_STRLEN, **kwargs): '''For values in the unicode range, regardless of Python version. ''' from syn.five import unichr return unicode(rand_str(min_char, max_char, min_len, max_len, unichr))
<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, email, device_name, passphrase=None, api_token=None, redirect_uri=None, **kwargs): """Create a new User object and add it to this Users collection. In addition to creating a user, this call will create a device for that user, whose device_token will be returned from this call. Store the device_token, as it's required to complete Gem-Device authentication after the user approves the device at the end of their signup flow. If you lose the device_token returned from users.create, you'll have to create a new device for the user to gain access to their account again. Also, after this call, be sure to redirect the user to the location in `mfa_uri` (second return value of this function) to complete their account. If you get a 409 Conflict error, then the user already exists in the Gem system and you'll want to do a `client.user(email).devices.create(device_name)` Args: email (str) device_name (str): Human-readable name for the device through which your Application will be authorized to access the new User's account. passphrase (str, optional): A passphrase with which to encrypt a user wallet. If not provided, a default_wallet parameter must be passed in kwargs. api_token (str, optional): Your app's API token. This is optional if and only if the Client which will be calling this function already has Gem-Application or Gem-Identify authentication. redirect_uri (str, optional): A URI to which to redirect the User after they confirm their Gem account. **kwargs Returns: device_token """
if not passphrase and u'default_wallet' not in kwargs: raise ValueError("Usage: users.create(email, passphrase, device_name" ", api_token, redirect_uri)") elif passphrase: default_wallet = generate(passphrase, ['primary'])['primary'] else: default_wallet = kwargs['default_wallet'] default_wallet['name'] = 'default' default_wallet['primary_private_seed'] = default_wallet['encrypted_seed'] default_wallet['primary_public_seed'] = default_wallet['public_seed'] del default_wallet['encrypted_seed'] del default_wallet['public_seed'] del default_wallet['private_seed'] # If not supplied, we assume the client already has an api_token param. if api_token: self.client.authenticate_identify(api_token) user_data = dict(email=email, default_wallet=default_wallet, device_name=device_name) if redirect_uri: user_data['redirect_uri'] = redirect_uri if 'first_name' in kwargs: user_data['first_name'] = kwargs['first_name'] if 'last_name' in kwargs: user_data['last_name'] = kwargs['last_name'] try: resource = self.resource.create(user_data) except ResponseError as e: if "conflict" in e.message: raise ConflictError( "This user already exists. Use " "client.user(email).devices.create(name) to request " "authorization from the user.") raise e return resource.attributes['metadata']['device_token']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subscriptions(self): """Fetch and return Subscriptions associated with this user."""
if not hasattr(self, '_subscriptions'): subscriptions_resource = self.resource.subscriptions self._subscriptions = Subscriptions( subscriptions_resource, self.client) return self._subscriptions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify_mfa(self, mfa_token): """Verify an SMS or TOTP MFA token for this user. Args: mfa_token (str): An alphanumeric code from either a User's TOTP application or sent to them via SMS. Returns: True if the mfa_token is valid, False otherwise. """
response = self.resource.verify_mfa({'mfa_token': mfa_token}) return (response['valid'] == True or response['valid'] == '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 reset_sequence(app_label): """ Reset the primary key sequence for the tables in an application. This is necessary if any local edits have happened to the table. """
puts("Resetting primary key sequence for {0}".format(app_label)) cursor = connection.cursor() cmd = get_reset_command(app_label) cursor.execute(cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _validate_install(self): ''' a method to validate docker is installed ''' from subprocess import check_output, STDOUT sys_command = 'docker --help' try: check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8') # call(sys_command, stdout=open(devnull, 'wb')) except Exception as err: raise Exception('"docker" not installed. GoTo: https://www.docker.com') 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 _images(self, sys_output): ''' a helper method for parsing docker image output ''' import re gap_pattern = re.compile('\t|\s{2,}') image_list = [] output_lines = sys_output.split('\n') column_headers = gap_pattern.split(output_lines[0]) for i in range(1,len(output_lines)): columns = gap_pattern.split(output_lines[i]) if len(columns) == len(column_headers): image_details = {} for j in range(len(columns)): image_details[column_headers[j]] = columns[j] image_list.append(image_details) return image_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 _ps(self, sys_output): ''' a helper method for parsing docker ps output ''' import re gap_pattern = re.compile('\t|\s{2,}') container_list = [] output_lines = sys_output.split('\n') column_headers = gap_pattern.split(output_lines[0]) for i in range(1,len(output_lines)): columns = gap_pattern.split(output_lines[i]) container_details = {} if len(columns) > 1: for j in range(len(column_headers)): container_details[column_headers[j]] = '' if j <= len(columns) - 1: container_details[column_headers[j]] = columns[j] # stupid hack for possible empty port column if container_details['PORTS'] and not container_details['NAMES']: from copy import deepcopy container_details['NAMES'] = deepcopy(container_details['PORTS']) container_details['PORTS'] = '' container_list.append(container_details) return container_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 _synopsis(self, container_settings, container_status=''): ''' a helper method for summarizing container settings ''' # compose default response settings = { 'container_status': container_settings['State']['Status'], 'container_exit': container_settings['State']['ExitCode'], 'container_ip': container_settings['NetworkSettings']['IPAddress'], 'image_name': container_settings['Config']['Image'], 'container_alias': container_settings['Name'].replace('/',''), 'container_variables': {}, 'mapped_ports': {}, 'mounted_volumes': {}, 'container_networks': [] } # parse fields nested in container settings import re num_pattern = re.compile('\d+') if container_settings['NetworkSettings']['Ports']: for key, value in container_settings['NetworkSettings']['Ports'].items(): if value: port = num_pattern.findall(value[0]['HostPort'])[0] settings['mapped_ports'][port] = num_pattern.findall(key)[0] elif container_settings['HostConfig']['PortBindings']: for key, value in container_settings['HostConfig']['PortBindings'].items(): port = num_pattern.findall(value[0]['HostPort'])[0] settings['mapped_ports'][port] = num_pattern.findall(key)[0] if container_settings['Config']['Env']: for variable in container_settings['Config']['Env']: k, v = variable.split('=') settings['container_variables'][k] = v for volume in container_settings['Mounts']: system_path = volume['Source'] container_path = volume['Destination'] settings['mounted_volumes'][system_path] = container_path if container_settings['NetworkSettings']: if container_settings['NetworkSettings']['Networks']: for key in container_settings['NetworkSettings']['Networks'].keys(): settings['container_networks'].append(key) # determine stopped status if settings['container_status'] == 'exited': if not container_status: try: from subprocess import check_output, STDOUT sys_command = 'docker logs --tail 1 %s' % settings['container_alias'] check_output(sys_command, shell=True, stderr=STDOUT).decode('utf-8') settings['container_status'] = 'stopped' except: pass else: settings['container_status'] = container_status return 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 chunk_by(n, iterable, fillvalue=None): """ Iterate over a given ``iterable`` by ``n`` elements at a time. :param n: (int) a chunk size number :param iterable: (iterator) an input iterator :param fillvalue: (any) a value to be used to fit chunk size if there not enough values in input iterator :returns: (iterator) an output iterator that iterates over the input one by chunks of size ``n`` """
args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _parameterize(self, config, parameters): """ Parameterized configuration template given as string with dynamic parameters. :param config: a string with configuration template to be parameterized :param parameters: dynamic parameters to inject into the template :return: a parameterized configuration string. """
parameters = self._parameters.override(parameters) return pystache.render(config, parameters)
<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_backend(self, conn_string): """ Given a DSN, returns an instantiated backend class. Ex:: backend = gator.build_backend('locmem://') backend = gator.build_backend('redis://127.0.0.1:6379/0') :param conn_string: A DSN for connecting to the queue. Passed along to the backend. :type conn_string: string :returns: A backend ``Client`` instance """
backend_name, _ = conn_string.split(':', 1) backend_path = 'alligator.backends.{}_backend'.format(backend_name) client_class = import_attr(backend_path, 'Client') return client_class(conn_string)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(self, task, func, *args, **kwargs): """ Pushes a configured task onto the queue. Typically, you'll favor using the ``Gator.task`` method or ``Gator.options`` context manager for creating a task. Call this only if you have specific needs or know what you're doing. If the ``Task`` has the ``async = False`` option, the task will be run immediately (in-process). This is useful for development and in testing. Ex:: task = Task(async=False, retries=3) finished = gator.push(task, increment, incr_by=2) :param task: A mostly-configured task :type task: A ``Task`` instance :param func: The callable with business logic to execute :type func: callable :param args: Positional arguments to pass to the callable task :type args: list :param kwargs: Keyword arguments to pass to the callable task :type kwargs: dict :returns: The ``Task`` instance """
task.to_call(func, *args, **kwargs) data = task.serialize() if task.async: task.task_id = self.backend.push( self.queue_name, task.task_id, data ) else: self.execute(task) return task
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop(self): """ Pops a task off the front of the queue & runs it. Typically, you'll favor using a ``Worker`` to handle processing the queue (to constantly consume). However, if you need to custom-process the queue in-order, this method is useful. Ex:: # Tasks were previously added, maybe by a different process or finished_topmost_task = gator.pop() :returns: The completed ``Task`` instance """
data = self.backend.pop(self.queue_name) if data: task = self.task_class.deserialize(data) return self.execute(task)
<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, task_id): """ Gets a specific task, by ``task_id`` off the queue & runs it. Using this is not as performant (because it has to search the queue), but can be useful if you need to specifically handle a task *right now*. Ex:: # Tasks were previously added, maybe by a different process or finished_task = gator.get('a-specific-uuid-here') :param task_id: The identifier of the task to process :type task_id: string :returns: The completed ``Task`` instance """
data = self.backend.get(self.queue_name, task_id) if data: task = self.task_class.deserialize(data) return self.execute(task)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cancel(self, task_id): """ Takes an existing task & cancels it before it is processed. Returns the canceled task, as that could be useful in creating a new task. Ex:: task = gator.task(add, 18, 9) # Whoops, didn't mean to do that. gator.cancel(task.task_id) :param task_id: The identifier of the task to process :type task_id: string :returns: The canceled ``Task`` instance """
data = self.backend.get(self.queue_name, task_id) if data: task = self.task_class.deserialize(data) task.to_canceled() return task
<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, task): """ Given a task instance, this runs it. This includes handling retries & re-raising exceptions. Ex:: task = Task(async=False, retries=5) task.to_call(add, 101, 35) finished_task = gator.execute(task) :param task_id: The identifier of the task to process :type task_id: string :returns: The completed ``Task`` instance """
try: return task.run() except Exception: if task.retries > 0: task.retries -= 1 task.to_retrying() if task.async: # Place it back on the queue. data = task.serialize() task.task_id = self.backend.push( self.queue_name, task.task_id, data ) else: return self.execute(task) else: raise
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_simple_callable(obj): """ True if the object is a callable that takes no arguments. """
function = inspect.isfunction(obj) method = inspect.ismethod(obj) if not (function or method): return False args, _, _, defaults = inspect.getargspec(obj) len_args = len(args) if function else len(args) - 1 len_defaults = len(defaults) if defaults else 0 return len_args <= len_defaults
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flatten_choices_dict(choices): """ Convert a group choices dict into a flat dict of choices. flatten_choices({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'} flatten_choices({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'} """
ret = OrderedDict() for key, value in choices.items(): if isinstance(value, dict): # grouped choices (category, sub choices) for sub_key, sub_value in value.items(): ret[sub_key] = sub_value else: # choice (key, display value) ret[key] = value 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 iter_options(grouped_choices, cutoff=None, cutoff_text=None): """ Helper function for options and option groups in templates. """
class StartOptionGroup(object): start_option_group = True end_option_group = False def __init__(self, label): self.label = label class EndOptionGroup(object): start_option_group = False end_option_group = True class Option(object): start_option_group = False end_option_group = False def __init__(self, value, display_text, disabled=False): self.value = value self.display_text = display_text self.disabled = disabled count = 0 for key, value in grouped_choices.items(): if cutoff and count >= cutoff: break if isinstance(value, dict): yield StartOptionGroup(label=key) for sub_key, sub_value in value.items(): if cutoff and count >= cutoff: break yield Option(value=sub_key, display_text=sub_value) count += 1 yield EndOptionGroup() else: yield Option(value=key, display_text=value) count += 1 if cutoff and count >= cutoff and cutoff_text: cutoff_text = cutoff_text.format(count=cutoff) yield Option(value='n/a', display_text=cutoff_text, disabled=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 get_default(self): """ Return the default value to use when validating data if no input is provided for this field. If a default has not been set for this field then this will simply return `empty`, indicating that no value should be set in the validated data for this field. """
if self.default is empty: raise SkipField() if callable(self.default): if hasattr(self.default, 'set_context'): self.default.set_context(self) return self.default() return self.default
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_validators(self, value): """ Test the given value against all the validators on the field, and either raise a `ValidationError` or simply return. """
errors = [] for validator in self.validators: if hasattr(validator, 'set_context'): validator.set_context(self) try: validator(value) except ValidationError as exc: # If the validation error contains a mapping of fields to # errors then simply raise it immediately rather than # attempting to accumulate a list of errors. if isinstance(exc.detail, dict): raise errors.extend(exc.detail) except DjangoValidationError as exc: errors.extend(exc.messages) if errors: raise ValidationError(errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def root(self): """ Returns the top-level serializer for this field. """
root = self while root.parent is not None: root = root.parent return root
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_internal_value(self, data): """ Validate that the input is a decimal number and return a Decimal instance. """
data = smart_text(data).strip() if len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: value = decimal.Decimal(data) except decimal.DecimalException: self.fail('invalid') # Check for NaN. It is the only value that isn't equal to itself, # so we can use this to identify NaN values. if value != value: self.fail('invalid') # Check for infinity and negative infinity. if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')): self.fail('invalid') return self.validate_precision(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 validate_precision(self, value): """ Ensure that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. Override this method to disable the precision validation for input values or to enhance it in any way you need to. """
sign, digittuple, exponent = value.as_tuple() if exponent >= 0: # 1234500.0 total_digits = len(digittuple) + exponent whole_digits = total_digits decimal_places = 0 elif len(digittuple) > abs(exponent): # 123.45 total_digits = len(digittuple) whole_digits = total_digits - abs(exponent) decimal_places = abs(exponent) else: # 0.001234 total_digits = abs(exponent) whole_digits = 0 decimal_places = total_digits if self.max_digits is not None and total_digits > self.max_digits: self.fail('max_digits', max_digits=self.max_digits) if self.decimal_places is not None and decimal_places > self.decimal_places: self.fail('max_decimal_places', max_decimal_places=self.decimal_places) if self.max_whole_digits is not None and whole_digits > self.max_whole_digits: self.fail('max_whole_digits', max_whole_digits=self.max_whole_digits) 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 quantize(self, value): """ Quantize the decimal value to the configured precision. """
context = decimal.getcontext().copy() context.prec = self.max_digits return value.quantize( decimal.Decimal('.1') ** self.decimal_places, context=context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_representation(self, value): """ List of object instances -> List of dicts of primitive datatypes. """
return { six.text_type(key): self.child.to_representation(val) for key, val in value.items() }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _query_(self, path, method, params={}): """Used internally for requests. :param str path: The path to hit. :param str method: The method to use, either `'GET'` or `'POST.` :param dict data: The optional paramters to the `GET` or the data to `POST`. :returns: Requests object -- Requires you to handle the status codes yourself. """
if method == "POST": url = '{API_URL}{API_PATH}'.format(API_URL=self.api_url, API_PATH=path) r = requests.post(url, data=json.dumps(params), headers=self.headers) return r elif method == "GET": url = '{API_URL}{API_PATH}'.format(API_URL=self.api_url, API_PATH=path) r = requests.get(url, params=params, headers=self.headers) return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authenticate(self, username, password): """Authenticates your user and returns an auth token. :param str username: Hummingbird username. :param str password: Hummingbird password. :returns: str -- The Auth Token :raises: ValueError -- If the Authentication is wrong """
r = self._query_('/users/authenticate', 'POST', params={'username': username, 'password': password}) if r.status_code == 201: return r.text.strip('"') else: raise ValueError('Authentication invalid.')
<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_anime(self, anime_id, title_language='canonical'): """Fetches the Anime Object of the given id or slug. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str title_language: The PREFERED title language can be any of `'canonical'`, `'english'`, `'romanized'` :returns: Anime Object -- The Anime you requested. """
r = self._query_('/anime/%s' % anime_id, 'GET', params={'title_language_preference': title_language}) return Anime(r.json())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_anime(self, query): """Fuzzy searches the Anime Database for the query. :param str query: The text to fuzzy search. :returns: List of Anime Objects. This list can be empty. """
r = self._query_('/search/anime', 'GET', params={'query': query}) results = [Anime(item) for item in r.json()] return results
<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_library(self, username, status=None): """Fetches a users library. :param str username: The user to get the library from. :param str status: only return the items with the supplied status. Can be one of `currently-watching`, `plan-to-watch`, `completed`, `on-hold` or `dropped`. :returns: List of Library objects. """
r = self._query_('/users/%s/library' % username, 'GET', params={'status': status}) results = [LibraryEntry(item) for item in r.json()] return results
<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_feed(self, username): """Gets a user's feed. :param str username: User to fetch feed from. """
r = self._query_('/users/%s/feed' % username, 'GET') results = [Story(item) for item in r.json()] return results
<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_favorites(self, username): """Get a user's favorite anime. :param str username: User to get favorites from. """
r = self._query_('/users/%s/favorite_anime' % username, 'GET') results = [Favorite(item) for item in r.json()] return results
<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_entry(self, anime_id, status=None, privacy=None, rating=None, sane_rating_update=None, rewatched_times=None, notes=None, episodes_watched=None, increment_episodes=None): """Creates or updates the Library entry with the provided values. :param anime_id: The Anime ID or Slug. :type anime_id: int or str :param str auth_token: User authentication token. :param str status: Can be one of `'currently-watching'`, `'plan-to-watch'`, `'completed'`, `'on-hold'`, `'dropped'`. :param str privacy: Can be one of `'public'`, `'private'`. Making an entry private will hide it from public view. :param rating: Can be one of `0`, `0.5`, `1`, `1.5`, `2`, `2.5`, `3`, `3.5`, `4`, `4.5`, `5`. Setting it to the current value or 0 will remove the rating. :type rating: str, int or float :param sane_rating_update: Can be any one of the values for rating. Setting it to 0 will remove the rating. This should be used instead of rating if you don't want to unset the rating when setting it to its current value. :type sane_rating_update: str, int or float :param int rewatched_times: Number of rewatches. Can be 0 or above. :param str notes: The personal notes for the entry. :param int episodes_watched: Number of watched episodes. Can be between 0 and the total number of episodes. If equal to total number of episodes, status should be set to completed. :param bool increment_episodes: If set to true, increments watched episodes by one. If used along with episodes_watched, provided value will be incremented. :raises: ValueError -- if Authentication Token is invalid (it shouldn't be), or if there is a `500 Internal Server Error` or if the response is `Invalid JSON Object`. """
r = self._query_('/libraries/%s' % anime_id, 'POST', { 'auth_token': self.auth_token, 'status': status, 'privacy': privacy, 'rating': rating, 'sane_rating_update': sane_rating_update, 'rewatched_times': rewatched_times, 'notes': notes, 'episodes_watched': episodes_watched, 'increment_episodes': increment_episodes}) if not (r.status_code == 200 or r.status_code == 201): raise ValueError
<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_entry(self, anime_id): """Removes an entry from the user's library. :param anime_id: The Anime ID or slug. """
r = self._query_('libraries/%s/remove' % anime_id, 'POST') if not r.status_code == 200: raise ValueError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def terminal(self, confirmation=True): ''' method to open an SSH terminal inside AWS instance :param confirmation: [optional] boolean to prompt keypair confirmation :return: True ''' title = '%s.terminal' % self.__class__.__name__ # construct ssh command if confirmation: override_cmd = ' ' else: override_cmd = ' -o CheckHostIP=no ' sys_command = 'ssh -i %s%s%s@%s' % (self.pem_file, override_cmd, self.login_name, self.instance_ip) self.ec2.iam.printer(sys_command) # send shell script command to open up terminal if self.localhost.os.sysname in ('Windows'): raise Exception('%s is not supported on Windows. try using putty.exe') try: import os os.system(sys_command) # TODO: check into making sys_command OS independent except: raise AWSConnectionError(title) 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 responsive(self, port=80, timeout=600): ''' a method for waiting until web server on AWS instance has restarted :param port: integer with port number to check :param timeout: integer with number of seconds to continue to check :return: string with response code ''' title = '%s.wait' % self.__class__.__name__ from time import sleep # validate inputs input_fields = { 'port': port, 'timeout': timeout } for key, value in input_fields.items(): object_title = '%s(%s=%s)' % (title, key, str(value)) self.fields.validate(value, '.%s' % key, object_title) # construct parameters for request loop import requests waiting_msg = 'Waiting for http 200 response from %s' % self.instance_ip nonres_msg = 'Instance %s is not responding to requests at %s.' % ( self.instance_id, self.instance_ip) server_url = 'http://%s' % self.instance_ip if port: server_url += ':%s' % str(port) # initiate waiting loop self.ec2.iam.printer(waiting_msg, flush=True) t0 = timer() while True: t1 = timer() self.ec2.iam.printer('.', flush=True) try: response = requests.get(server_url, timeout=2) response_code = response.status_code if response_code >= 200 and response_code < 300: self.ec2.iam.printer(' done.') return response_code except: pass t2 = timer() if t2 - t0 > timeout: timeout_msg = 'Timeout [%ss]: %s' % (timeout, nonres_msg) raise TimeoutError(timeout_msg) response_time = t2 - t1 if 3 - response_time > 0: delay = 3 - response_time else: delay = 0 sleep(delay)
<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(uri): """Return an instance of MediaFile."""
global _instances try: instance = _instances[uri] except KeyError: instance = MediaFile( uri, client.get_instance() ) _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 fetch_to_file(self, filename): """Stream the MediaFile to the filesystem."""
self.filename = filename stream = self.client.get_iter_content(self.uri) content_type = self.client.response_headers['content-type'] if content_type in _content_type_map: self.fileext = _content_type_map[content_type] self.filename = "%s.%s" % (self.filename, self.fileext) with open(self.filename, 'wb') as file_handle: for chunk in stream: file_handle.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 is_unique(seq): '''Returns True if every item in the seq is unique, False otherwise.''' try: s = set(seq) return len(s) == len(seq) except TypeError: buf = [] for item in seq: if item in buf: return False buf.append(item) 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 indices_removed(lst, idxs): '''Returns a copy of lst with each index in idxs removed.''' ret = [item for k,item in enumerate(lst) if k not in idxs] return type(lst)(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 _deriv_hypot(x, y): """Derivative of numpy hypot function"""
r = np.hypot(x, y) df_dx = x / r df_dy = y / r return np.hstack([df_dx, df_dy])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _deriv_arctan2(y, x): """Derivative of the arctan2 function"""
r2 = x*x + y*y df_dy = x / r2 df_dx = -y / r2 return np.hstack([df_dy, df_dx])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_classify_function(data): """ A default classify_function which recieve `data` and return filename without characters just after the last underscore './foo/foo_bar.piyo' './foo/foo.piyo' './foo/foo.piyo' './foo/foo' """
# data[0] indicate the filename of the data rootname, basename = os.path.split(data[0]) filename, ext = os.path.splitext(basename) if '_' in filename: filename = filename.rsplit('_', 1)[0] filename = os.path.join(rootname, filename + ext) return 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 classify_dataset(dataset, fn): """ Classify dataset via fn Parameters dataset : list A list of data fn : function A function which recieve :attr:`data` and return classification string. It if is None, a function which return the first item of the :attr:`data` will be used (See ``with_filename`` parameter of :func:`maidenhair.load` function). Returns ------- dict A classified dataset """
if fn is None: fn = default_classify_function # classify dataset via classify_fn classified_dataset = OrderedDict() for data in dataset: classify_name = fn(data) if classify_name not in classified_dataset: classified_dataset[classify_name] = [] classified_dataset[classify_name].append(data) return classified_dataset
<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_apod(cls, date=None, hd=False): """ Returns Astronomy Picture of the Day Args: date: date instance (default = today) hd: bool if high resolution should be included Returns: json """
instance = cls('planetary/apod') filters = { 'date': date, 'hd': hd } return instance.get_resource(**filters)