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 get_settings(self, section=None, defaults=None): """ Gets a named section from the configuration source. :param section: a :class:`str` representing the sect...
# This is a partial reimplementation of # ``paste.deploy.loadwsgi.ConfigLoader:get_context`` which supports # "set" and "get" options and filters out any other globals section = self._maybe_get_default_name(section) if self.filepath is None: return {} parser ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_wsgi_app(self, name=None, defaults=None): """ Reads the configuration source and finds and loads a WSGI application defined by the entry with name ``name...
name = self._maybe_get_default_name(name) defaults = self._get_defaults(defaults) return loadapp( self.pastedeploy_spec, name=name, relative_to=self.relative_to, global_conf=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 get_wsgi_server(self, name=None, defaults=None): """ Reads the configuration source and finds and loads a WSGI server defined by the server entry with the na...
name = self._maybe_get_default_name(name) defaults = self._get_defaults(defaults) return loadserver( self.pastedeploy_spec, name=name, relative_to=self.relative_to, global_conf=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 get_wsgi_filter(self, name=None, defaults=None): """Reads the configuration soruce and finds and loads a WSGI filter defined by the filter entry with the nam...
name = self._maybe_get_default_name(name) defaults = self._get_defaults(defaults) return loadfilter( self.pastedeploy_spec, name=name, relative_to=self.relative_to, global_conf=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 _maybe_get_default_name(self, name): """Checks a name and determines whether to use the default name. :param name: The current name to check. :return: Either...
if name is None and self.uri.fragment: name = self.uri.fragment return 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 set(self, hue): """Set cursor position on the color corresponding to the hue value."""
x = hue / 360. * self.winfo_width() self.coords('cursor', x, 0, x, self.winfo_height()) self._variable.set(hue)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPageType(name,number=False): """Returns the type of the page with that name. If that name doesn't exist, None is returned. Args: name (str): name of the ...
if not name in pageNames(): return None pageType=PyOrigin.Pages(name).GetType() if number: return str(pageType) if pageType==1: return "matrix" if pageType==2: return "book" if pageType==3: return "graph" if pageType==4: return "layout" if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listEverything(matching=False): """Prints every page in the project to the console. Args: matching (str, optional): if given, only return names with this st...
pages=pageNames() if matching: pages=[x for x in pages if matching in x] for i,page in enumerate(pages): pages[i]="%s%s (%s)"%(pageFolder(page),page,getPageType(page)) print("\n".join(sorted(pages)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sheetNames(book=None): """return sheet names of a book. Args: book (str, optional): If a book is given, pull names from that book. Otherwise, try the active...
if book: if not book.lower() in [x.lower() for x in bookNames()]: return False else: book=activeBook() if not book: return False poBook=PyOrigin.WorksheetPages(book) if not len(poBook): return None return [x.GetName() for x in poBook.Layers()]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getSheet(book=None,sheet=None): """returns the pyorigin object for a sheet."""
# figure out what book to use if book and not book.lower() in [x.lower() for x in bookNames()]: print("book %s doesn't exist"%book) return if book is None: book=activeBook().lower() if book is None: print("no book given or selected") return # figure out wha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sheetDelete(book=None,sheet=None): """ Delete a sheet from a book. If either isn't given, use the active one. """
if book is None: book=activeBook() if sheet in sheetNames(): PyOrigin.WorksheetPages(book).Layers(sheetNames().index(sheet)).Destroy()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sheetDeleteEmpty(bookName=None): """Delete all sheets which contain no data"""
if bookName is None: bookName = activeBook() if not bookName.lower() in [x.lower() for x in bookNames()]: print("can't clean up a book that doesn't exist:",bookName) return poBook=PyOrigin.WorksheetPages(bookName) namesToKill=[] for i,poSheet in enumerate([poSheet for poShee...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pickle_load(fname): """return the contents of a pickle file"""
assert type(fname) is str and os.path.exists(fname) print("loaded",fname) return pickle.load(open(fname,"rb"))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pickle_save(thing,fname=None): """save something to a pickle file"""
if fname is None: fname=os.path.expanduser("~")+"/%d.pkl"%time.time() assert type(fname) is str and os.path.isdir(os.path.dirname(fname)) pickle.dump(thing, open(fname,"wb"),pickle.HIGHEST_PROTOCOL) print("saved",fname)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getCodeBlocks(): """return a dict with the code for each function"""
raw=open("examples.py").read() d={} for block in raw.split("if __name__")[0].split("\ndef "): title=block.split("\n")[0].split("(")[0] if not title.startswith("demo_"): continue code=[x[4:] for x in block.split("\n")[1:] if x.startswith(" ")] d[title]="\n".joi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getOutputBlocks(): """return a dict with the output of each function"""
raw=open("output.txt").read() d={} for block in raw.split("\n####### ")[1:]: title=block.split("\n")[0].split("(")[0] block=block.split("\n",1)[1].strip() d[title]=block.split("\nfinished in ")[0] return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decodeCommandLine(self, cmdline): """Turn a byte string from the command line into a unicode string. """
codec = getattr(sys.stdin, 'encoding', None) or sys.getdefaultencoding() return unicode(cmdline, codec)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize(text): """ Yield tokens. Args: text (str): The original text. Yields: dict: The next token. """
stem = PorterStemmer().stem tokens = re.finditer('[a-z]+', text.lower()) for offset, match in enumerate(tokens): # Get the raw token. unstemmed = match.group(0) yield { # Emit the token. 'stemmed': stem(unstemmed), 'unstemmed': unstemmed, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_dict(d, desc=True): """ Sort an ordered dictionary by value, descending. Args: d (OrderedDict): An ordered dictionary. desc (bool): If true, sort desc...
sort = sorted(d.items(), key=lambda x: x[1], reverse=desc) return OrderedDict(sort)
<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(seq, n=2): """ Yield a sliding window over an iterable. Args: seq (iter): The sequence. n (int): The window width. Yields: tuple: The next window. "...
it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for token in it: result = result[1:] + (token,) yield result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insertUserStore(siteStore, userStorePath): """ Move the SubStore at the indicated location into the given site store's directory and then hook it up to the s...
# The following may, but does not need to be in a transaction, because it # is merely an attempt to guess a reasonable filesystem name to use for # this avatar. The user store being operated on is expected to be used # exclusively by this process. ls = siteStore.findUnique(LoginSystem) unattac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractUserStore(userAccount, extractionDestination, legacySiteAuthoritative=True): """ Move the SubStore for the given user account out of the given site st...
if legacySiteAuthoritative: # migrateDown() manages its own transactions, since it is copying items # between two different stores. userAccount.migrateDown() av = userAccount.avatars av.open().close() def _(): # We're separately deleting several Items from the site store...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getAccountNames(store, protocol=None): """ Retrieve account name information about the given database. @param store: An Axiom Store representing a user accou...
return ((meth.localpart, meth.domain) for meth in getLoginMethods(store, protocol))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDomainNames(store): """ Retrieve a list of all local domain names represented in the given store. """
domains = set() domains.update(store.query( LoginMethod, AND(LoginMethod.internal == True, LoginMethod.domain != None)).getColumn("domain").distinct()) return sorted(domains)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cloneInto(self, newStore, avatars): """ Create a copy of this LoginAccount and all associated LoginMethods in a different Store. Return the copied LoginAccou...
la = LoginAccount(store=newStore, password=self.password, avatars=avatars, disabled=self.disabled) for siteMethod in self.store.query(LoginMethod, LoginMethod.account == 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 addLoginMethod(self, localpart, domain, protocol=ANY_PROTOCOL, verified=False, internal=False): """ Add a login method to this account, propogating up or dow...
# Out takes you west or something if self.store.parent is None: # West takes you in otherStore = self.avatars.open() peer = otherStore.findUnique(LoginAccount) else: # In takes you east otherStore = self.store.parent subSto...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replacePassword(self, currentPassword, newPassword): """ Set this account's password if the current password matches. @param currentPassword: The password to...
if unicode(currentPassword) != self.password: return fail(BadCredentials()) return self.setPassword(newPassword)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addAccount(self, username, domain, password, avatars=None, protocol=u'email', disabled=0, internal=False, verified=True): """ Create a user account, add it t...
# unicode(None) == u'None', kids. if username is not None: username = unicode(username) if domain is not None: domain = unicode(domain) if password is not None: password = unicode(password) if self.accountByAddress(username, domain) is not 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 identifySQLError(self, sql, args, e): """ Identify an appropriate SQL error object for the given message for the supported versions of sqlite. @return: an SQ...
message = e.args[0] if message.startswith("table") and message.endswith("already exists"): return errors.TableAlreadyExists(sql, args, e) return errors.SQLError(sql, args, 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 createCacheRemoveCallback(cacheRef, key, finalizer): """ Construct a callable to be used as a weakref callback for cache entries. The callable will invoke th...
def remove(reference): # Weakref callbacks cannot raise exceptions or DOOM ensues try: finalizer() except: logErrorNoMatterWhat() try: cache = cacheRef() if cache is not None: if key in cache.data: 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 cache(self, key, value): """ Add an entry to the cache. A weakref to the value is stored, rather than a direct reference. The value must have a C{__finalizer...
fin = value.__finalizer__() try: # It's okay if there's already a cache entry for this key as long # as the weakref has already been broken. See the comment in # get() for an explanation of why this might happen. if self.data[key]() 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 get(self, key): """ Get an entry from the cache by key. @raise KeyError: if the given key is not present in the cache. @raise CacheFault: (a L{KeyError} subc...
o = self.data[key]() if o is None: # On CPython, the weakref callback will always(?) run before any # other code has a chance to observe that the weakref is broken; # and since the callback removes the item from the dict, this # branch of code should neve...
<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_from_xml(root): """ Update the UBCPI XBlock's content from an XML definition. We need to be strict about the XML we accept, to avoid setting the XBlock...
# Check that the root has the correct tag if root.tag != 'ubcpi': raise UpdateFromXmlError(_('Every peer instruction tool must contain an "ubcpi" element.')) display_name_el = root.find('display_name') if display_name_el is None: raise UpdateFromXmlError(_('Every peer instruction tool...
<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_options(options, block): """ Serialize the options in peer instruction XBlock to xml Args: options (lxml.etree.Element): The <options> XML element...
for index, option_dict in enumerate(block.options): option = etree.SubElement(options, 'option') # set correct option and rationale if index == block.correct_answer: option.set('correct', u'True') if hasattr(block, 'correct_rationale'): rationale = 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 serialize_seeds(seeds, block): """ Serialize the seeds in peer instruction XBlock to xml Args: seeds (lxml.etree.Element): The <seeds> XML element. block (P...
for seed_dict in block.seeds: seed = etree.SubElement(seeds, 'seed') # options in xml starts with 1 seed.set('option', unicode(seed_dict.get('answer', 0) + 1)) seed.text = seed_dict.get('rationale', '')
<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_to_xml(root, block): """ Serialize the Peer Instruction XBlock's content to XML. Args: block (PeerInstructionXBlock): The peer instruction block t...
root.tag = 'ubcpi' if block.rationale_size is not None: if block.rationale_size.get('min'): root.set('rationale_size_min', unicode(block.rationale_size.get('min'))) if block.rationale_size.get('max'): root.set('rationale_size_max', unicode(block.rationale_size['max'])) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """ Obtains the lvm and vg_t handle. Usually you would never need to use this method unless you are doing operations using the ctypes function wr...
if not self.handle: self.lvm.open() self.__vgh = lvm_vg_open(self.lvm.handle, self.name, self.mode) if not bool(self.__vgh): raise HandleError("Failed to initialize VG Handle.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Closes the lvm and vg_t handle. Usually you would never need to use this method unless you are doing operations using the ctypes function wr...
if self.handle: cl = lvm_vg_close(self.handle) if cl != 0: raise HandleError("Failed to close VG handle after init check.") self.__vgh = None self.lvm.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uuid(self): """ Returns the volume group uuid. """
self.open() uuid = lvm_vg_get_uuid(self.handle) self.close() return uuid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extent_count(self): """ Returns the volume group extent count. """
self.open() count = lvm_vg_get_extent_count(self.handle) self.close() return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def free_extent_count(self): """ Returns the volume group free extent count. """
self.open() count = lvm_vg_get_free_extent_count(self.handle) self.close() return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pv_count(self): """ Returns the physical volume count. """
self.open() count = lvm_vg_get_pv_count(self.handle) self.close() return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_pv_count(self): """ Returns the maximum allowed physical volume count. """
self.open() count = lvm_vg_get_max_pv(self.handle) self.close() return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_lv_count(self): """ Returns the maximum allowed logical volume count. """
self.open() count = lvm_vg_get_max_lv(self.handle) self.close() return count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_clustered(self): """ Returns True if the VG is clustered, False otherwise. """
self.open() clust = lvm_vg_is_clustered(self.handle) self.close() return bool(clust)
<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_exported(self): """ Returns True if the VG is exported, False otherwise. """
self.open() exp = lvm_vg_is_exported(self.handle) self.close() return bool(exp)
<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_partial(self): """ Returns True if the VG is partial, False otherwise. """
self.open() part = lvm_vg_is_partial(self.handle) self.close() return bool(part)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sequence(self): """ Returns the volume group sequence number. This number increases everytime the volume group is modified. """
self.open() seq = lvm_vg_get_seqno(self.handle) self.close() return seq
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(self, units="MiB"): """ Returns the volume group size in the given units. Default units are MiB. *Args:* """
self.open() size = lvm_vg_get_size(self.handle) self.close() return size_convert(size, units)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def free_size(self, units="MiB"): """ Returns the volume group free size in the given units. Default units are MiB. *Args:* """
self.open() size = lvm_vg_get_free_size(self.handle) self.close() return size_convert(size, units)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extent_size(self, units="MiB"): """ Returns the volume group extent size in the given units. Default units are MiB. *Args:* """
self.open() size = lvm_vg_get_extent_size(self.handle) self.close() return size_convert(size, units)
<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_all_lvs(self): """ Removes all logical volumes from the volume group. *Raises:* * HandleError, CommitError """
lvs = self.lvscan() for lv in lvs: self.remove_lv(lv)
<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_pair(self, term1, term2, value, **kwargs): """ Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed) """
key = self.key(term1, term2) self.keys.update([term1, term2]) self.pairs[key] = 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_pair(self, term1, term2): """ Get the value for a pair of terms. Args: term1 (str) term2 (str) Returns: The stored value. """
key = self.key(term1, term2) return self.pairs.get(key, 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 index(self, text, terms=None, **kwargs): """ Index all term pair distances. Args: text (Text): The source text. terms (list): Terms to index. """
self.clear() # By default, use all terms. terms = terms or text.terms.keys() pairs = combinations(terms, 2) count = comb(len(terms), 2) for t1, t2 in bar(pairs, expected_size=count, every=1000): # Set the Bray-Curtis distance. score = text.sc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def anchored_pairs(self, anchor): """ Get distances between an anchor term and all other terms. Args: anchor (str): The anchor term. Returns: OrderedDict: The d...
pairs = OrderedDict() for term in self.keys: score = self.get_pair(anchor, term) if score: pairs[term] = score return utils.sort_dict(pairs)
<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_rgb(r, g=None, b=None): """ Return the nearest xterm 256 color code from rgb input. """
c = r if isinstance(r, list) else [r, g, b] best = {} for index, item in enumerate(colors): d = __distance(item, c) if(not best or d <= best['distance']): best = {'distance': d, 'index': index} if 'index' in best: return best['index'] else: return 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def entry(): """Parse command line arguments and run utilities."""
parser = argparse.ArgumentParser() parser.add_argument( 'action', help='Action to take', choices=['from_hex', 'to_rgb', 'to_hex'], ) parser.add_argument( 'value', help='Value for the action', ) parsed = parser.parse_args() if parsed.action != "from_hex": try:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def makeSoftwareVersion(store, version, systemVersion): """ Return the SoftwareVersion object from store corresponding to the version object, creating it if it d...
return store.findOrCreate(SoftwareVersion, systemVersion=systemVersion, package=unicode(version.package), version=unicode(version.short()), major=version.major, mino...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def listVersionHistory(store): """ List the software package version history of store. """
q = store.query(SystemVersion, sort=SystemVersion.creation.descending) return [sv.longWindedRepr() for sv in q]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def checkSystemVersion(s, versions=None): """ Check if the current version is different from the previously recorded version. If it is, or if there is no previou...
if versions is None: versions = getSystemVersions() currentVersionMap = dict([(v.package, v) for v in versions]) mostRecentSystemVersion = s.findFirst(SystemVersion, sort=SystemVersion.creation.descending) mostRecentVersionMap = dict([(v.package, v.as...
<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(self): """clears all columns"""
self.colNames,self.colDesc,self.colUnits,self.colComments,\ self.colTypes,self.colData=[],[],[],[],[],[]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def colDelete(self,colI=-1): """delete a column at a single index. Negative numbers count from the end."""
# print("DELETING COLUMN: [%d] %s"%(colI,self.colDesc[colI])) self.colNames.pop(colI) self.colDesc.pop(colI) self.colUnits.pop(colI) self.colComments.pop(colI) self.colTypes.pop(colI) self.colData.pop(colI) return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def onex(self): """ delete all X columns except the first one. """
xCols=[i for i in range(self.nCols) if self.colTypes[i]==3] if len(xCols)>1: for colI in xCols[1:][::-1]: self.colDelete(colI)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wiggle(self,noiseLevel=.1): """Slightly changes value of every cell in the worksheet. Used for testing."""
noise=(np.random.rand(*self.data.shape))-.5 self.data=self.data+noise*noiseLevel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nRows(self): """returns maximum number of rows based on the longest colData"""
if self.nCols: return max([len(x) for x in self.colData]) else: return 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self): """return all of colData as a 2D numpy array."""
data=np.empty((self.nRows,self.nCols),dtype=np.float) data[:]=np.nan # make everything nan by default for colNum,colData in enumerate(self.colData): validIs=np.where([np.isreal(v) for v in colData])[0] validData=np.ones(len(colData))*np.nan validData[validIs]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self,data): """Given a 2D numpy array, fill colData with it."""
assert type(data) is np.ndarray assert data.shape[1] == self.nCols for i in range(self.nCols): self.colData[i]=data[:,i].tolist()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(self): """ Obtains the lvm handle. Usually you would never need to use this method unless you are trying to do operations using the ctypes function wrap...
if not self.handle: try: path = self.system_dir except AttributeError: path = '' self.__handle = lvm_init(path) if not bool(self.__handle): raise HandleError("Failed to initialize LVM handle.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Closes the lvm handle. Usually you would never need to use this method unless you are trying to do operations using the ctypes function wrap...
if self.handle: q = lvm_quit(self.handle) if q != 0: raise HandleError("Failed to close LVM handle.") self.__handle = 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 from_file(cls, path): """ Create a text from a file. Args: path (str): The file path. """
with open(path, 'r', errors='replace') as f: return cls(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 load_stopwords(self, path): """ Load a set of stopwords. Args: path (str): The stopwords file path. """
if path: with open(path) as f: self.stopwords = set(f.read().splitlines()) else: self.stopwords = set( pkgutil .get_data('textplot', 'data/stopwords.txt') .decode('utf8') .splitlines() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize(self): """ Tokenize the text. """
self.tokens = [] self.terms = OrderedDict() # Generate tokens. for token in utils.tokenize(self.text): # Ignore stopwords. if token['unstemmed'] in self.stopwords: self.tokens.append(None) else: # 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 most_frequent_terms(self, depth): """ Get the X most frequent terms in the text, and then probe down to get any other terms that have the same count as the l...
counts = self.term_counts() # Get the top X terms and the instance count of the last word. top_terms = set(list(counts.keys())[:depth]) end_count = list(counts.values())[:depth][-1] # Merge in all other words with that appear that number of times, so # that we don't t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unstem(self, term): """ Given a stemmed term, get the most common unstemmed variant. Args: term (str): A stemmed term. Returns: str: The unstemmed token. ""...
originals = [] for i in self.terms[term]: originals.append(self.tokens[i]['unstemmed']) mode = Counter(originals).most_common(1) return mode[0][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 kde(self, term, bandwidth=2000, samples=1000, kernel='gaussian'): """ Estimate the kernel density of the instances of term in the text. Args: term (str): A ...
# Get the offsets of the term instances. terms = np.array(self.terms[term])[:, np.newaxis] # Fit the density estimator on the terms. kde = KernelDensity(kernel=kernel, bandwidth=bandwidth).fit(terms) # Score an evely-spaced array of samples. x_axis = np.linspace(0, le...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def score_intersect(self, term1, term2, **kwargs): """ Compute the geometric area of the overlap between the kernel density estimates of two terms. Args: term1 (...
t1_kde = self.kde(term1, **kwargs) t2_kde = self.kde(term2, **kwargs) # Integrate the overlap. overlap = np.minimum(t1_kde, t2_kde) return np.trapz(overlap)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def score_cosine(self, term1, term2, **kwargs): """ Compute a weighting score based on the cosine distance between the kernel density estimates of two terms. Arg...
t1_kde = self.kde(term1, **kwargs) t2_kde = self.kde(term2, **kwargs) return 1-distance.cosine(t1_kde, t2_kde)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def score_braycurtis(self, term1, term2, **kwargs): """ Compute a weighting score based on the "City Block" distance between the kernel density estimates of two ...
t1_kde = self.kde(term1, **kwargs) t2_kde = self.kde(term2, **kwargs) return 1-distance.braycurtis(t1_kde, t2_kde)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_term_kdes(self, words, **kwargs): """ Plot kernel density estimates for multiple words. Args: words (list): A list of unstemmed terms. """
stem = PorterStemmer().stem for word in words: kde = self.kde(stem(word), **kwargs) plt.plot(kde) plt.show()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _tupleCompare(tuple1, ineq, tuple2, eq=lambda a,b: (a==b), ander=AND, orer=OR): """ Compare two 'in-database tuples'. Useful when sorting by a compound key a...
orholder = [] for limit in range(len(tuple1)): eqconstraint = [ eq(elem1, elem2) for elem1, elem2 in zip(tuple1, tuple2)[:limit]] ineqconstraint = ineq(tuple1[limit], tuple2[limit]) orholder.append(ander(*(eqconstraint + [ineqconstraint]))) return orer(*orholder)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def truncate_rationale(rationale, max_length=MAX_RATIONALE_SIZE_IN_EVENT): """ Truncates the rationale for analytics event emission if necessary Args: rationale ...
if isinstance(rationale, basestring) and max_length is not None and len(rationale) > max_length: return rationale[0:max_length], True else: return rationale, 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 validate_options(options): """ Validate the options that course author set up and return errors in a dict if there is any """
errors = [] if int(options['rationale_size']['min']) < 1: errors.append(_('Minimum Characters')) if int(options['rationale_size']['max']) < 0 or int(options['rationale_size']['max']) > MAX_RATIONALE_SIZE: errors.append(_('Maximum Characters')) if not any(error in [_('Minimum Characters...
<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_student_item_dict(self, anonymous_user_id=None): """Create a student_item_dict from our surrounding context. See also: submissions.api for details. Args:...
item_id = self._serialize_opaque_key(self.scope_ids.usage_id) # This is not the real way course_ids should work, but this is a # temporary expediency for LMS integration if hasattr(self, "xmodule_runtime"): course_id = self.get_course_id() # pylint:disable=E1101 ...
<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_answers_for_student(student_item): """ Retrieve answers from backend for a student and question Args: student_item (dict): The location of the problem t...
submissions = sub_api.get_submissions(student_item) if not submissions: return Answers() latest_submission = submissions[0] latest_answer_item = latest_submission.get('answer', {}) return Answers(latest_answer_item.get(ANSWER_LIST_KEY, []))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_answer_for_student(student_item, vote, rationale): """ Add an answer for a student to the backend Args: student_item (dict): The location of the problem...
answers = get_answers_for_student(student_item) answers.add_answer(vote, rationale) sub_api.create_submission(student_item, { ANSWER_LIST_KEY: answers.get_answers_as_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 add_answer(self, vote, rationale): """ Add an answer Args: vote (int): the option that student voted for rationale (str): the reason why the student vote f...
self.raw_answers.append({ VOTE_KEY: vote, RATIONALE_KEY: rationale, })
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createNew(cls, store, pathSegments): """ Create a new SubStore, allocating a new file space for it. """
if isinstance(pathSegments, basestring): raise ValueError( 'Received %r instead of a sequence' % (pathSegments,)) if store.dbdir is None: self = cls(store=store, storepath=None) else: storepath = store.newDirectory(*pathSegments) 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 createStore(self, debug, journalMode=None): """ Create the actual Store this Substore represents. """
if self.storepath is None: self.store._memorySubstores.append(self) # don't fall out of cache if self.store.filesdir is None: filesdir = None else: filesdir = (self.store.filesdir.child("_substore_files") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgradeCatalog1to2(oldCatalog): """ Create _TagName instances which version 2 of Catalog automatically creates for use in determining the tagNames result, bu...
newCatalog = oldCatalog.upgradeVersion('tag_catalog', 1, 2, tagCount=oldCatalog.tagCount) tags = newCatalog.store.query(Tag, Tag.catalog == newCatalog) tagNames = tags.getColumn("name").distinct() for t in tagNames: _TagName(store=newCatalog.store, cat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tagNames(self): """ Return an iterator of unicode strings - the unique tag names which have been applied objects in this catalog. """
return self.store.query(_TagName, _TagName.catalog == self).getColumn("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 tagsOf(self, obj): """ Return an iterator of unicode strings - the tag names which apply to the given object. """
return self.store.query( Tag, AND(Tag.catalog == self, Tag.object == obj)).getColumn("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 loaded(self, oself, dbval): """ This method is invoked when the item is loaded from the database, and when a transaction is reverted which restores this attr...
setattr(oself, self.dbunderlying, dbval) delattr(oself, self.underlying)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _convertPyval(self, oself, pyval): """ Convert a Python value to a value suitable for inserting into the database. @param oself: The object on which this des...
# convert to dbval later, I guess? if pyval is None and not self.allowNone: raise TypeError("attribute [%s.%s = %s()] must not be None" % ( self.classname, self.attrname, self.__class__.__name__)) return self.infilter(pyval, oself, oself.store)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _queryContainer(self, store): """ Generate and cache the subselect SQL and its arguments. Return the subselect SQL. """
if self._subselectSQL is None: sql, args = self.container._sqlAndArgs('SELECT', self.container._queryTarget) self._subselectSQL, self._subselectArgs = sql, args return self._subselectSQL
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sequenceContainer(self, store): """ Smash whatever we got into a list and save the result in case we are executed multiple times. This keeps us from trippin...
if self._sequence is None: self._sequence = list(self.container) self._clause = ', '.join(['?'] * len(self._sequence)) return self._clause
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _sequenceArgs(self, store): """ Filter each element of the data using the attribute type being tested for containment and hand back the resulting list. """
self._sequenceContainer(store) # Force _sequence to be valid return [self.attribute.infilter(pyval, None, store) for pyval in self._sequence]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepareInsert(self, oself, store): """ Prepare for insertion into the database by making the dbunderlying attribute of the item a relative pathname with resp...
if self.relative: fspath = self.__get__(oself) oself.__dirty__[self.attrname] = self, self.infilter(fspath, oself, store)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(self, time=None): """ Undeletes the object. Returns True if undeleted, False if it was already not deleted """
if self.deleted: time = time if time else self.deleted_at if time == self.deleted_at: self.deleted = False self.save() return True else: return False return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_restore(self, using=None): using = using or router.db_for_write(self.__class__, instance=self) restore_counter = Counter() if self.deleted: time = self....
self.collector = models.deletion.Collector(using=using) self.collector.collect([self], keep_parents=keep_parents)