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 ...
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 ...
<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) ...
<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 f...
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...
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 po...
<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'...
<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(typ...
<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(bas...
<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) ...
<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()) ...
<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...
<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 ...
<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 ch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 ...
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/...
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 ...
<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 c...
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_PUNCTU...
<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/fil...
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: usernam...
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...
<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): ...
<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 passwo...
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=setti...
<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 ex...
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 = recordReques...
<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.du...
<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 templa...
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> ...
<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 ...
<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 ...
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 re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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...
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...
<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...
<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 play...
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 " ...
<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 hand...
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: ...
<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 ...
<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 ins...
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 instanc...
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() ...
<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 c...
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: setatt...
<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...
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: setatt...
<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 : obj...
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_widg...
<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. Paramete...
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: ...
<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 ...
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 Valu...
<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...
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 collecti...
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: ...
<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 applica...
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 tab...
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=o...
<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...
<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]) ...
<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...
<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...
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 confi...
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.bui...
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.opti...
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 con...
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), b...
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 t...
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...
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() ta...
<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_def...
<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'} fl...
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[...
<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...
<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 fi...
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 field...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 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 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 po...
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_digi...
<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...
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 == "...
<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:...
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 anim...
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. T...
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 t...
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, increme...
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...
<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 ...
<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 ...
<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, se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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) re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def 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 '...
# 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 r...
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_dat...
<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 b...
instance = cls('planetary/apod') filters = { 'date': date, 'hd': hd } return instance.get_resource(**filters)