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 is_resource_class_member_attribute(rc, attr_name): """ Checks if the given attribute name is a member attribute of the given registered resource. """
attr = get_resource_class_attribute(rc, attr_name) return attr.kind == RESOURCE_ATTRIBUTE_KINDS.MEMBER
<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_resource_class_collection_attribute(rc, attr_name): """ Checks if the given attribute name is a collection attribute of the given registered resource. """
attr = get_resource_class_attribute(rc, attr_name) return attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION
<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_joke(): """Return a Ron Swanson quote. Returns None if unable to retrieve a quote. """
page = requests.get("http://ron-swanson-quotes.herokuapp.com/v2/quotes") if page.status_code == 200: jokes = [] jokes = json.loads(page.content.decode(page.encoding)) return '"' + jokes[0] + '" - Ron Swanson' 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 window(iterable, n=2, cast=tuple): """ This function passes a running window along the length of the given iterable. By default, the return value is a tuple,...
it = iter(iterable) win = deque((next(it) for _ in repeat(None, n)), maxlen=n) if len(win) < n: raise ValueError('Window size was greater than iterable length') yield cast(win) append = win.append for e in it: append(e) yield cast(win)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(): """Command line interface for the ``update-dotdee`` program."""
# Initialize logging to the terminal and system log. coloredlogs.install(syslog=True) # Parse the command line arguments. context_opts = {} program_opts = {} try: options, arguments = getopt.getopt(sys.argv[1:], 'fur:vqh', [ 'force', 'use-sudo', 'remote-host=', '...
<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_months(self, value: int) -> datetime: """ Add a number of months to the given date """
self.value = self.value + relativedelta(months=value) return self.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 from_date(self, value: date) -> datetime: """ Initializes from the given date value """
assert isinstance(value, date) #self.value = datetime.combine(value, time.min) self.value = datetime(value.year, value.month, value.day) return self.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_day_name(self) -> str: """ Returns the day name """
weekday = self.value.isoweekday() - 1 return calendar.day_name[weekday]
<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_iso_string(self) -> str: """ Returns full ISO string for the given date """
assert isinstance(self.value, datetime) return datetime.isoformat(self.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 end_of_day(self) -> datetime: """ End of day """
self.value = datetime(self.value.year, self.value.month, self.value.day, 23, 59, 59) return self.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 end_of_month(self) -> datetime: """ Provides end of the month for the given date """
# Increase month by 1, result = self.value + relativedelta(months=1) # take the 1st day of the (next) month, result = result.replace(day=1) # subtract one day result = result - relativedelta(days=1) self.value = result return self.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 is_end_of_month(self) -> bool: """ Checks if the date is at the end of the month """
end_of_month = Datum() # get_end_of_month(value) end_of_month.end_of_month() return self.value == end_of_month.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 set_day(self, day: int) -> datetime: """ Sets the day value """
self.value = self.value.replace(day=day) return self.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 set_value(self, value: datetime): """ Sets the current value """
assert isinstance(value, datetime) self.value = 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 start_of_day(self) -> datetime: """ Returns start of day """
self.value = datetime(self.value.year, self.value.month, self.value.day) return self.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 subtract_days(self, days: int) -> datetime: """ Subtracts dates from the given value """
self.value = self.value - relativedelta(days=days) return self.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 subtract_weeks(self, weeks: int) -> datetime: """ Subtracts number of weeks from the current value """
self.value = self.value - timedelta(weeks=weeks) return self.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 subtract_months(self, months: int) -> datetime: """ Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months) return self.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 yesterday(self) -> datetime: """ Set the value to yesterday """
self.value = datetime.today() - timedelta(days=1) return self.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_uuid_string(low=None, high=None, **x): """This method parses a UUID protobuf message type from its component 'high' and 'low' longs into a standard forma...
if low is None or high is None: return None x = ''.join([parse_part(low), parse_part(high)]) return '-'.join([x[:8], x[8:12], x[12:16], x[16:20], x[20:32]])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, search): """search Zenodo record for string `search` :param search: string to search :return: Record[] results """
search = search.replace('/', ' ') # zenodo can't handle '/' in search query params = {'q': search} return self._get_records(params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def qdict_get_list(qdict, k): """ get list from QueryDict and remove blank date from list. """
pks = qdict.getlist(k) return [e for e in pks if 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 request_get_next(request, default_next): """ get next url form request order: POST.next GET.next HTTP_REFERER, default_next """
next_url = request.POST.get('next')\ or request.GET.get('next')\ or request.META.get('HTTP_REFERER')\ or default_next return next_url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_progress(request): """ AJAX view adapted from django-progressbarupload Return the upload progress and total length values """
if 'X-Progress-ID' in request.GET: progress_id = request.GET['X-Progress-ID'] elif 'X-Progress-ID' in request.META: progress_id = request.META['X-Progress-ID'] if 'logfilename' in request.GET: logfilename = request.GET['logfilename'] elif 'logfilename' in request.META: l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_color(self, fg=None, bg=None, intensify=False, target=sys.stdout): """Set foreground- and background colors and intensity."""
raise NotImplementedError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, entity): """ Adds the given entity to this cache. :param entity: Entity to add. :type entity: Object implementing :class:`everest.interfaces.IEntit...
do_append = self.__check_new(entity) if do_append: self.__entities.append(entity)
<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(self, entity): """ Removes the given entity from this cache. :param entity: Entity to remove. :type entity: Object implementing :class:`everest.interf...
self.__id_map.pop(entity.id, None) self.__slug_map.pop(entity.slug, None) self.__entities.remove(entity)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retrieve(self, filter_expression=None, order_expression=None, slice_key=None): """ Retrieve entities from this cache, possibly after filtering, ordering and ...
ents = iter(self.__entities) if not filter_expression is None: ents = filter_expression(ents) if not order_expression is None: # Ordering always involves a copy and conversion to a list, so # we have to wrap in an iterator. ents = iter(order_expre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_user_keywords_generator(twitter_lists_gen, lemmatizing="wordnet"): """ Based on the user-related lists I have downloaded, annotate the users. Inputs:...
#################################################################################################################### # Extract keywords serially. #################################################################################################################### for user_twitter_id, twitter_lists_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 form_user_label_matrix(user_twitter_list_keywords_gen, id_to_node, max_number_of_labels): """ Forms the user-label matrix to be used in multi-label classific...
user_label_matrix, annotated_nodes, label_to_lemma, node_to_lemma_tokeywordbag = form_user_term_matrix(user_twitter_list_keywords_gen, id_to_node, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def form_user_term_matrix(user_twitter_list_keywords_gen, id_to_node, lemma_set=None, keyword_to_topic_manual=None): """ Forms a user-term matrix. Input: - user_...
# Prepare for iteration. term_to_attribute = dict() user_term_matrix_row = list() user_term_matrix_col = list() user_term_matrix_data = list() append_user_term_matrix_row = user_term_matrix_row.append append_user_term_matrix_col = user_term_matrix_col.append append_user_term_matrix_da...
<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_twitter_lists_for_user_ids_generator(twitter_app_key, twitter_app_secret, user_id_list): """ Collects at most 500 Twitter lists for each user from an i...
#################################################################################################################### # Log into my application. #################################################################################################################### twitter = login(twitter_app_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 decide_which_users_to_annotate(centrality_vector, number_to_annotate, already_annotated, node_to_id): """ Sorts a centrality vector and returns the Twitter u...
# Sort the centrality vector according to decreasing centrality. centrality_vector = np.asarray(centrality_vector) ind = np.argsort(np.squeeze(centrality_vector)) if centrality_vector.size > 1: reversed_ind = ind[::-1] else: reversed_ind = list() reversed_ind = reversed_ind....
<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_demand_annotation(twitter_app_key, twitter_app_secret, user_twitter_id): """ A service that leverages twitter lists for on-demand annotation of popular us...
#################################################################################################################### # Log into my application #################################################################################################################### twitter = login(twitter_app_key, twitter_ap...
<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_member_class(resource): """ Returns the registered member class for the given resource. :param resource: registered resource :type resource: class implem...
reg = get_current_registry() if IInterface in provided_by(resource): member_class = reg.getUtility(resource, name='member-class') else: member_class = reg.getAdapter(resource, IMemberResource, name='member-class') return member_class
<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_collection_class(resource): """ Returns the registered collection resource class for the given marker interface or member resource class or instance. :pa...
reg = get_current_registry() if IInterface in provided_by(resource): coll_class = reg.getUtility(resource, name='collection-class') else: coll_class = reg.getAdapter(resource, ICollectionResource, name='collection-class') return coll_class
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_member(entity, parent=None): """ Adapts an object to a location aware member resource. :param entity: a domain object for which a resource adapter has bee...
reg = get_current_registry() rc = reg.getAdapter(entity, IMemberResource) if not parent is None: rc.__parent__ = parent # interface method pylint: disable=E1121 return rc
<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_resource_url(resource): """ Returns the URL for the given resource. """
path = model_path(resource) parsed = list(urlparse.urlparse(path)) parsed[1] = "" return urlparse.urlunparse(parsed)
<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_registered_collection_resources(): """ Returns a list of all registered collection resource classes. """
reg = get_current_registry() return [util.component for util in reg.registeredUtilities() if util.name == 'collection-class']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_to_url(resource, request=None, quote=False): """ Converts the given resource to a URL. :param request: Request object (required for the host name pa...
if request is None: request = get_current_request() # cnv = request.registry.getAdapter(request, IResourceUrlConverter) reg = get_current_registry() cnv = reg.getAdapter(request, IResourceUrlConverter) return cnv.resource_to_url(resource, quote=quote)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url_to_resource(url, request=None): """ Converts the given URL to a resource. :param request: Request object (required for the host name part of the URL). If...
if request is None: request = get_current_request() # cnv = request.registry.getAdapter(request, IResourceUrlConverter) reg = get_current_registry() cnv = reg.getAdapter(request, IResourceUrlConverter) return cnv.url_to_resource(url)
<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_entity_class(resource): """ Returns the entity class registered for the given registered resource. :param resource: registered resource :type collection:...
reg = get_current_registry() if IInterface in provided_by(resource): ent_cls = reg.getUtility(resource, name='entity-class') else: ent_cls = reg.getAdapter(resource, IEntity, name='entity-class') return ent_cls
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_board_with_programmer(mcu, programmer, f_cpu=16000000, core='arduino', replace_existing=False, ): """install board with programmer."""
bunch = AutoBunch() board_id = '{mcu}_{f_cpu}_{programmer}'.format(f_cpu=f_cpu, mcu=mcu, programmer=programmer, ) bunch.name = '{mcu}@{f} Prog:{programmer}'.format(f=strfre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logMsg(self, msg, printMsg=True): """ logs a message and prints it to the screen """
time = datetime.datetime.now().strftime('%I:%M %p') self.log = '{0}\n{1} | {2}'.format(self.log, time, msg) if printMsg: print msg if self.addLogsToArcpyMessages: from arcpy import AddMessage AddMessage(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 logGPMsg(self, printMsg=True): """ logs the arcpy messages and prints them to the screen """
from arcpy import GetMessages msgs = GetMessages() try: self.logMsg(msgs, printMsg) except: self.logMsg('error getting arcpy message', printMsg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def writeLogToFile(self): """ writes the log to a """
if not os.path.exists(self.logFolder): os.mkdir(self.logFolder) with open(self.logFile, mode='a') as f: f.write('\n\n' + self.log)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logError(self): """ gets traceback info and logs it """
# got from http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Error_handling_with_Python import traceback self.logMsg('ERROR!!!') errMsg = traceback.format_exc() self.logMsg(errMsg) return errMsg
<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_random_giphy(phrase): """Return the URL of a random GIF related to the phrase, if possible"""
with warnings.catch_warnings(): warnings.simplefilter('ignore') giphy = giphypop.Giphy() results = giphy.search_list(phrase=phrase, limit=100) if not results: raise ValueError('There were no results for that phrase') return random.choice(results).media_url
<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_command_line(): """Display an image for the phrase in sys.argv, if possible"""
phrase = ' '.join(sys.argv[1:]) or 'random' try: giphy = get_random_giphy(phrase) except ValueError: sys.stderr.write('Unable to find any GIFs for {!r}\n'.format(phrase)) sys.exit(1) display(fetch_image(giphy))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_required_folders(self): """Makes all folders declared in the config if they do not exist. """
for folder in [ self.pending_folder, self.usb_incoming_folder, self.outgoing_folder, self.incoming_folder, self.archive_folder, self.tmp_folder, self.log_folder, ]: if not os.path.exists(folder): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, filename, offset): """Loads HFS+ volume information"""
try: self.offset = offset self.fd = open(filename, 'rb') # 1024 - temporary, need to find out actual volume header size self.fd.seek(self.offset + VOLUME_HEADER_OFFSET) data = self.fd.read(1024) self.vol_header = VolumeHeader(data) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_interfaces(self): """ Return a list of sham.network.interfaces.NetworkInterface describing all the interfaces this VM has """
interfaces = self.xml.find('devices').iter('interface') iobjs = [] for interface in interfaces: _type = interface.attrib['type'] mac = interface.find('mac').attrib['address'] source = interface.find('source').attrib[_type] model = interface.find('...
<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_disks(self): """ Return a list of all the Disks attached to this VM The disks are returned in a sham.storage.volumes.Volume object """
disks = [disk for disk in self.xml.iter('disk')] disk_objs = [] for disk in disks: source = disk.find('source') if source is None: continue path = source.attrib['file'] diskobj = self.domain.connect().storageVolLookupByPath(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 delete(self): """ Delete this VM, and remove all its disks """
disks = self.get_disks() self.domain.undefine() for disk in disks: disk.wipe() disk.delete()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """ Return the values contained in this object as a dict """
return {'domain_type': self.domain_type, 'max_memory': self.max_memory, 'current_memory': self.current_memory, 'num_cpus': self.num_cpus, 'running': self.is_running(), 'name': self.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 guess_url_vcs(url): """ Given a url, try to guess what kind of VCS it's for. Return None if we can't make a good guess. """
parsed = urllib.parse.urlsplit(url) if parsed.scheme in ('git', 'svn'): return parsed.scheme elif parsed.path.endswith('.git'): return 'git' elif parsed.hostname == 'github.com': return 'git' # If it's an http url, we can try requesting it and guessing from the # conte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def guess_folder_vcs(folder): """ Given a path for a folder on the local filesystem, see what kind of vcs repo it is, if any. """
try: contents = os.listdir(folder) vcs_folders = ['.git', '.hg', '.svn'] found = next((x for x in vcs_folders if x in contents), None) # Chop off the dot if we got a string back return found[1:] if found else None except OSError: 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 basename(url): """ Return the name of the folder that you'd get if you cloned 'url' into the current working directory. """
# It's easy to accidentally have whitespace on the beginning or end of the # url. url = url.strip() url, _sep, _fragment = url.partition('#') # Remove trailing slash from url if present if url.endswith('/'): url = url[:-1] # Also strip .git from url if it ends in that. 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 get_url(self): """ Assuming that the repo has been cloned locally, get its default upstream URL. """
cmd = { 'hg': 'hg paths default', 'git': 'git config --local --get remote.origin.url', }[self.vcs_type] with chdir(self.folder): r = self.run(cmd) return r.output.replace('\n', '')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fburl(parser, token): """ Returns an absolute URL matching given view with its parameters. This is a way to define links that aren't tied to a particular URL...
bits = token.contents.split(' ') if len(bits) < 2: raise template.TemplateSyntaxError("'%s' takes at least one argument" " (path to a view)" % bits[0]) viewname = bits[1] args = [] kwargs = {} asvar = None if len(bits) > 2: bits = iter(bits...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chdir(method): """Decorator executing method in directory 'dir'. """
def wrapper(self, dir, *args, **kw): dirstack = ChdirStack() dirstack.push(dir) try: return method(self, dir, *args, **kw) finally: dirstack.pop() return functools.wraps(method)(wrapper)
<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, dir): """Push cwd on stack and change to 'dir'. """
self.stack.append(os.getcwd()) os.chdir(dir or os.getcwd())
<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): """Pop dir off stack and change to it. """
if len(self.stack): os.chdir(self.stack.pop())
<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_matching(self, source_id): """ Returns a matching target object for the given source ID. """
value = self._accessor.get_by_id(source_id) if not value is None: reg = get_current_registry() prx_fac = reg.getUtility(IDataTraversalProxyFactory) prx = prx_fac.make_proxy(value, self._accessor, ...
<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_attribute_value_items(self): """ Returns an iterator of items for an attribute value map to use for an UPDATE operation. The iterator ignores collecti...
for attr in self._attribute_iterator(): if attr.kind != RESOURCE_ATTRIBUTE_KINDS.COLLECTION: try: attr_val = self._get_proxied_attribute_value(attr) except AttributeError: continue else: yiel...
<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_entity(self): """ Returns the entity converted from the proxied data. """
if self._accessor is None: if self.__converted_entity is None: self.__converted_entity = self._convert_to_entity() else: # If we have an accessor, we can get the proxied entity by ID. # FIXME: This is a hack that is only used for REMOVE operations ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_traverser(cls, source_data, target_data, relation_operation, accessor=None, manage_back_references=True): """ Factory method to create a tree traverser ...
reg = get_current_registry() prx_fac = reg.getUtility(IDataTraversalProxyFactory) if relation_operation == RELATION_OPERATIONS.ADD \ or relation_operation == RELATION_OPERATIONS.UPDATE: if relation_operation == RELATION_OPERATIONS.ADD \ and not target_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 info(self, obj_id=None): '''Get info about object id |coro| Parameters ---------- obj_id : str, list if not provided, server info is retured(as a dict). Otherwise, an object with that id is returned (or objects if `obj_id` is a list). ''' if obj_id: try: ...
<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 search(self, query, sort_map = {'BoxSet':0,'Series':1,'Movie':2,'Audio':3,'Person':4}, strict_sort = False): '''Sends a search request to emby, returns results |coro| Parameters ---------- query : str the search string to send to emby sort_map : dict ...
<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 nextUp(self, userId=None): '''returns list of items marked as `next up` |coro| Parameters ---------- userId : str if provided, then the list returned is the one that that use will see. Returns ------- list the itmes that will appear as next up (for us...
<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 update(self): ''' reload all cached information |coro| Notes ----- This is a slow process, and will remove the cache before updating. Thus it is recomended to use the `*_force` properties, which will only update the cache after data is retrived. ''' keys = self.extras...
<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 create_playlist(self, name, *songs): '''create a new playlist |coro| Parameters ---------- name : str name of new playlist songs : array_like list of song ids to add to playlist ''' data = {'Name': name} ids = [i.id for i in (await self.process(songs))] 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 load_all(self, group): """ Loads all plugins advertising entry points with the given group name. The specified plugin needs to be a callable that accepts the...
for ep in iter_entry_points(group=group): plugin = ep.load() plugin(self.__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 gui(): """remove libraries by GUI."""
sel = psidialogs.multi_choice(libraries(), 'select libraries to remove from %s!' % libraries_dir(), title='remove boards') print('%s selected' % sel) if sel: if psidialogs.ask_yes_no('Do you really want to remove selected librari...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def src2ast(src: str) -> Expression: """Return ast.Expression created from source code given in `src`."""
try: return ast.parse(src, mode='eval') except SyntaxError: raise ValueError("Not a valid expression.") from 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 names(expr: AST) -> Set[str]: """Names of globals in `expr`."""
nodes = [node for node in ast.walk(expr) if isinstance(node, ast.Name)] loaded = {node.id for node in nodes if isinstance(node.ctx, ast.Load)} stored = {node.id for node in nodes if isinstance(node.ctx, ast.Store)} return loaded - stored
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_name(expr: AST, old_name: str, new_name: str) -> AST: """Replace all Name nodes named `old_name` with nodes named `new_name`."""
return _NameReplacer(old_name, new_name).visit(deepcopy(expr))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Negation(expr: Expression) -> Expression: """Return expression which is the negation of `expr`."""
expr = Expression(_negate(expr.body)) return ast.fix_missing_locations(expr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Conjunction(expr1: Expression, expr2: Expression) -> Expression: """Return expression which is the conjunction of `expr1` and `expr2`."""
expr = Expression(ast.BoolOp(ast.And(), [expr1.body, expr2.body])) return ast.fix_missing_locations(expr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Disjunction(expr1: Expression, expr2: Expression) -> Expression: """Return expression which is the disjunction of `expr1` and `expr2`."""
expr = Expression(ast.BoolOp(ast.Or(), [expr1.body, expr2.body])) return ast.fix_missing_locations(expr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Contradiction(expr1: Expression, expr2: Expression) -> Expression: """Return expression which is the contradiction of `expr1` and `expr2`."""
expr = Disjunction(Conjunction(expr1, Negation(expr2)), Conjunction(Negation(expr1), expr2)) return ast.fix_missing_locations(expr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diff_binding(self) -> int: """Return the difference betweens the binding levels of the current and the previous operator. """
try: prev_op, prev_op_binding = self.nested_ops[-2] except IndexError: prev_op, prev_op_binding = None, 0 try: curr_op, curr_op_binding = self.nested_ops[-1] except IndexError: curr_op, curr_op_binding = None, 0 # special case ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wrap_expr(self, src: str, dfltChaining: bool) -> str: """Wrap `src` in parentheses if neccessary."""
diff_binding = self.op_man.diff_binding() if diff_binding < 0 or diff_binding == 0 and not dfltChaining: return self.parenthesize(src) else: return src
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit(self, node: AST, dfltChaining: bool = True) -> str: """Process `node` by dispatching to a handler."""
# print(node.__class__.__name__) if node is None: return '' if isinstance(node, ast.Expression): return self.visit(node.body) # dispatch to specific or generic method method = 'visit_' + node.__class__.__name__ visitor = getattr(self, method, self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generic_visit(self, node: AST, dfltChaining: bool = True) -> str: """Default handler, called if no explicit visitor function exists for a node. """
for field, value in ast.iter_fields(node): if isinstance(value, list): for item in value: if isinstance(item, AST): self.visit(item) elif isinstance(value, AST): self.visit(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 visit_NameConstant(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s name as string."""
return str(node.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 visit_Num(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s number as string."""
return str(node.n)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_Str(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s string representation."""
return repr(node.s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_FormattedValue(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s value formatted according to its format spec."""
format_spec = node.format_spec return f"{{{self.visit(node.value)}" \ f"{self.CONV_MAP.get(node.conversion, '')}" \ f"{':'+self._nested_str(format_spec) if format_spec 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 visit_Tuple(self, node: AST, dfltChaining: bool = True) -> str: """Return tuple representation of `node`s elements."""
elems = (self.visit(elt) for elt in node.elts) return f"({', '.join(elems)}{')' if len(node.elts) != 1 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 visit_Set(self, node: AST, dfltChaining: bool = True) -> str: """Return set representation of `node`s elements."""
return '{' + ', '.join([self.visit(elt) for elt in node.elts]) + '}'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_Dict(self, node: AST, dfltChaining: bool = True) -> str: """Return dict representation of `node`s elements."""
items = (': '.join((self.visit(key), self.visit(value))) for key, value in zip(node.keys, node.values)) return f"{{{', '.join(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 visit_Name(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s id."""
return node.id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_Starred(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of starred expresssion."""
with self.op_man(node): return f"*{self.visit(node.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 visit_Expr(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of nested expression."""
return self.visit(node.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 visit_UnaryOp(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of `node`s operator and operand."""
op = node.op with self.op_man(op): return self.visit(op) + self.visit(node.operand)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_Div(self, node: AST, dfltChaining: bool = True) -> str: """Return division sign."""
return '/' if self.compact 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 visit_Compare(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s operators and operands as inlined expression."""
# all comparison operators have the same precedence, # we just take the first one as representative first_op = node.ops[0] with self.op_man(first_op): cmps = [' '.join((self.visit(op), self.visit(cmp, dfltChaining=False))) fo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_keyword(self, node: AST, dfltChaining: bool = True) -> str: """Return representation of `node` as keyword arg."""
arg = node.arg if arg is None: return f"**{self.visit(node.value)}" else: return f"{arg}={self.visit(node.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 visit_Call(self, node: AST, dfltChaining: bool = True) -> str: """Return `node`s representation as function call."""
args = node.args try: kwds = node.keywords except AttributeError: kwds = [] self.compact = True args_src = (self.visit(arg) for arg in args) kwds_src = (self.visit(kwd) for kwd in kwds) param_src = ', '.join(chain(args_src, kwds_src)) ...