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 getDetails(self): """Update check details, returns dictionary of details"""
response = self.pingdom.request('GET', 'checks/%s' % self.id) self.__addDetails__(response.json()['check']) return response.json()['check']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def modify(self, **kwargs): """Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as bef...
# Warn user about unhandled parameters for key in kwargs: if key not in ['paused', 'resolution', 'contactids', 'sendtoemail', 'sendtosms', 'sendtotwitter', 'sendtoiphone', 'sendnotificationwhendown', 'notifyagainevery', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def probes(self, fromtime, totime=None): """Get a list of probes that performed tests for a specified check during a specified period."""
args = {'from': fromtime} if totime: args['to'] = totime response = self.pingdom.request('GET', 'summary.probes/%s' % self.id, args) return response.json()['probes']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publishPublicReport(self): """Activate public report for this check. Returns status message"""
response = self.pingdom.request('PUT', 'reports.public/%s' % self.id) return response.json()['message']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removePublicReport(self): """Deactivate public report for this check. Returns status message"""
response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) return response.json()['message']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extract_deps(bundles, log=None): """Extract the dependencies from the bundle and its sub-bundles."""
def _flatten(bundle): deps = [] if hasattr(bundle, 'npm'): deps.append(bundle.npm) for content in bundle.contents: if isinstance(content, BundleBase): deps.extend(_flatten(content)) return deps flatten_deps = [] for bundle in bundles:...
<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_semver(version_str): """Make a semantic version from Python PEP440 version. Semantic versions does not handle post-releases. """
v = parse_version(version_str) major = v._version.release[0] try: minor = v._version.release[1] except IndexError: minor = 0 try: patch = v._version.release[2] except IndexError: patch = 0 prerelease = [] if v._version.pre: prerelease.append(''....
<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_max_size(pool, num_option, item_length): """ Calculate the max number of item that an option can stored in the pool at give time. This is to limit the po...
max_items = POOL_SIZE / item_length # existing items plus the reserved for min size. If there is an option has 1 item, POOL_OPTION_MIN_SIZE - 1 space # is reserved. existing = POOL_OPTION_MIN_SIZE * num_option + sum([max(0, len(pool.get(i, {})) - 5) for i in xrange(num_option)]) return int(max_item...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def offer_answer(pool, answer, rationale, student_id, algo, options): """ submit a student answer to the answer pool The answer maybe selected to stay in the poo...
if algo['name'] == 'simple': offer_simple(pool, answer, rationale, student_id, options) elif algo['name'] == 'random': offer_random(pool, answer, rationale, student_id, options) else: raise UnknownChooseAnswerAlgorithm()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def offer_simple(pool, answer, rationale, student_id, options): """ The simple selection algorithm. This algorithm randomly select an answer from the pool to dis...
existing = pool.setdefault(answer, {}) if len(existing) >= get_max_size(pool, len(options), POOL_ITEM_LENGTH_SIMPLE): student_id_to_remove = random.choice(existing.keys()) del existing[student_id_to_remove] existing[student_id] = {} pool[answer] = existing
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def offer_random(pool, answer, rationale, student_id, options): """ The random selection algorithm. The same as simple algorithm """
offer_simple(pool, answer, rationale, student_id, options)
<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_seeded_answers_simple(answers, options, algo): """ This validator checks if the answers includes all possible options Args: answers (str): the answ...
seen_options = {} for answer in answers: if answer: key = options[answer['answer']].get('text') if options[answer['answer']].get('image_url'): key += options[answer['answer']].get('image_url') seen_options.setdefault(key, 0) seen_options[k...
<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_seeded_answers(answers, options, algo): """ Validate answers based on selection algorithm This is called when instructor setup the tool and providin...
if algo['name'] == 'simple': return validate_seeded_answers_simple(answers, options, algo) elif algo['name'] == 'random': return validate_seeded_answers_random(answers) else: raise UnknownChooseAnswerAlgorithm()
<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_other_answers(pool, seeded_answers, get_student_item_dict, algo, options): """ Select other student's answers from answer pool or seeded answers based on...
# "#" means the number of responses returned should be the same as the number of options. num_responses = len(options) \ if 'num_responses' not in algo or algo['num_responses'] == "#" \ else int(algo['num_responses']) if algo['name'] == 'simple': return get_other_answers_simple(poo...
<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_other_answers_simple(pool, seeded_answers, get_student_item_dict, num_responses): """ Get answers from others with simple algorithm, which picks one answ...
ret = [] # clean up answers so that all keys are int pool = {int(k): v for k, v in pool.items()} total_in_pool = len(seeded_answers) merged_pool = convert_seeded_answers(seeded_answers) student_id = get_student_item_dict()['student_id'] # merge the dictionaries in the answer dictionary ...
<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_other_answers_random(pool, seeded_answers, get_student_item_dict, num_responses): """ Get answers from others with random algorithm, which randomly selec...
ret = [] # clean up answers so that all keys are int pool = {int(k): v for k, v in pool.items()} seeded = {'seeded'+str(index): answer for index, answer in enumerate(seeded_answers)} merged_pool = seeded.keys() for key in pool: merged_pool += pool[key].keys() # shuffle random....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_seeded_answers(answers): """ Convert seeded answers into the format that can be merged into student answers. Args: answers (list): seeded answers Re...
converted = {} for index, answer in enumerate(answers): converted.setdefault(answer['answer'], {}) converted[answer['answer']]['seeded' + str(index)] = answer['rationale'] return converted
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mark(self): """ Mark the unit of work as failed in the database and update the listener so as to skip it next time. """
self.reliableListener.lastRun = extime.Time() BatchProcessingError( store=self.reliableListener.store, processor=self.reliableListener.processor, listener=self.reliableListener.listener, item=self.workUnit, error=self.failure.getErrorMessage()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def addReliableListener(self, listener, style=iaxiom.LOCAL): """ Add the given Item to the set which will be notified of Items available for processing. Note: Ea...
existing = self.store.findUnique(_ReliableListener, attributes.AND(_ReliableListener.processor == self, _ReliableListener.listener == listener), default=None) if exi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeReliableListener(self, listener): """ Remove a previously added listener. """
self.store.query(_ReliableListener, attributes.AND(_ReliableListener.processor == self, _ReliableListener.listener == listener)).deleteFromStore() self.store.query(BatchProcessingError, attributes.AND(BatchProcess...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getReliableListeners(self): """ Return an iterable of the listeners which have been added to this batch processor. """
for rellist in self.store.query(_ReliableListener, _ReliableListener.processor == self): yield rellist.listener
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def itemAdded(self): """ Called to indicate that a new item of the type monitored by this batch processor is being added to the database. If this processor is no...
localCount = self.store.query( _ReliableListener, attributes.AND(_ReliableListener.processor == self, _ReliableListener.style == iaxiom.LOCAL), limit=1).count() remoteCount = self.store.query( _ReliableListener, att...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def call(self, itemMethod): """ Invoke the given bound item method in the batch process. Return a Deferred which fires when the method has been invoked. """
item = itemMethod.im_self method = itemMethod.im_func.func_name return self.batchController.getProcess().addCallback( CallItemMethod(storepath=item.store.dbdir, storeid=item.storeID, method=method).do)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def processWhileRunning(self): """ Run tasks until stopService is called. """
work = self.step() for result, more in work: yield result if not self.running: break if more: delay = 0.1 else: delay = 10.0 yield task.deferLater(reactor, delay, lambda: 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 getcols(sheetMatch=None,colMatch="Decay"): """find every column in every sheet and put it in a new sheet or book."""
book=BOOK() if sheetMatch is None: matchingSheets=book.sheetNames print('all %d sheets selected '%(len(matchingSheets))) else: matchingSheets=[x for x in book.sheetNames if sheetMatch in x] print('%d of %d sheets selected matching "%s"'%(len(matchingSheets),len(book.sheetNam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def namespace(self): """ Return a dictionary representing the namespace which should be available to the user. """
self._ns = { 'db': self.store, 'store': store, 'autocommit': False, } return self._ns
<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, siteStore, username, domain, password): """ Create a new account in the given store. @param siteStore: A site Store to which login credentia...
for ls in siteStore.query(userbase.LoginSystem): break else: ls = self.installOn(siteStore) try: acc = ls.addAccount(username, domain, password) except userbase.DuplicateUser: raise usage.UsageError("An account by that name already exists....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createSomeItems(store, itemType, values, counter): """ Create some instances of a particular type in a store. """
for i in counter: itemType(store=store, **values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, commit=True): """save the instance or create a new one.."""
# walk through the document fields for field_name, field in iter_valid_fields(self._meta): setattr(self.instance, field_name, self.cleaned_data.get(field_name)) if commit: self.instance.save() return self.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 dependentItems(store, tableClass, comparisonFactory): """ Collect all the items that should be deleted when an item or items of a particular item type are de...
for cascadingAttr in (_cascadingDeletes.get(tableClass, []) + _cascadingDeletes.get(None, [])): for cascadedItem in store.query(cascadingAttr.type, comparisonFactory(cascadingAttr)): yield cascadedItem
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def declareLegacyItem(typeName, schemaVersion, attributes, dummyBases=()): """ Generate a dummy subclass of Item that will have the given attributes, and the bas...
if (typeName, schemaVersion) in _legacyTypes: return _legacyTypes[typeName, schemaVersion] if dummyBases: realBases = [declareLegacyItem(*A) for A in dummyBases] else: realBases = (Item,) attributes = attributes.copy() attributes['__module__'] = 'item_dummy' attributes['...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def empowerment(iface, priority=0): """ Class decorator for indicating a powerup's powerup interfaces. The class will also be declared as implementing the interf...
def _deco(cls): cls.powerupInterfaces = ( tuple(getattr(cls, 'powerupInterfaces', ())) + ((iface, priority),)) implementer(iface)(cls) return cls return _deco
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def powerDown(self, powerup, interface=None): """ Remove a powerup. If no interface is specified, and the type of the object being installed has a "powerupInterf...
if interface is None: for interface, priority in powerup._getPowerupInterfaces(): self.powerDown(powerup, interface) else: for cable in self.store.query(_PowerupConnector, AND(_PowerupConnector.item == 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 interfacesFor(self, powerup): """ Return an iterator of the interfaces for which the given powerup is installed on this object. This is not implemented for i...
pc = _PowerupConnector for iface in self.store.query(pc, AND(pc.item == self, pc.powerup == powerup)).getColumn('interface'): yield namedAny(iface)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getPowerupInterfaces(self): """ Collect powerup interfaces this object declares that it can be installed on. """
powerupInterfaces = getattr(self.__class__, "powerupInterfaces", ()) pifs = [] for x in powerupInterfaces: if isinstance(x, type(Interface)): #just an interface pifs.append((x, 0)) else: #an interface and a priority ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _schemaPrepareInsert(self, store): """ Prepare each attribute in my schema for insertion into a given store, either by upgrade or by creation. This makes sur...
for name, atr in self.getSchema(): atr.prepareInsert(self, 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 existingInStore(cls, store, storeID, attrs): """Create and return a new instance from a row from the store."""
self = cls.__new__(cls) self.__justCreated = False self.__subinit__(__store=store, storeID=storeID, __everInserted=True) schema = self.getSchema() assert len(schema) == len(attrs), "invalid number of attributes" for 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 getSchema(cls): """ return all persistent class attributes """
schema = [] for name, atr in cls.__attributes__: atr = atr.__get__(None, cls) if isinstance(atr, SQLAttribute): schema.append((name, atr)) cls.getSchema = staticmethod(lambda schema=schema: schema) return schema
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def committed(self): """ Called after the database is brought into a consistent state with this object. """
if self.__deleting: self.deleted() if not self.__legacy__: self.store.objectCache.uncache(self.storeID, self) self.__store = None self.__justCreated = 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 registerUpgrader(upgrader, typeName, oldVersion, newVersion): """ Register a callable which can perform a schema upgrade between two particular versions. @pa...
# assert (typeName, oldVersion, newVersion) not in _upgradeRegistry, "duplicate upgrader" # ^ this makes the tests blow up so it's just disabled for now; perhaps we # should have a specific test mode # assert newVersion - oldVersion == 1, "read the doc string" assert isinstance(typeName, str), "rea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _hasExplicitOid(store, table): """ Does the given table have an explicit oid column? """
return any(info[1] == 'oid' for info in store.querySchemaSQL( 'PRAGMA *DATABASE*.table_info({})'.format(table)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _upgradeTableOid(store, table, createTable, postCreate=lambda: None): """ Upgrade a table to have an explicit oid. Must be called in a transaction to avoid c...
if _hasExplicitOid(store, table): return store.executeSchemaSQL( 'ALTER TABLE *DATABASE*.{0} RENAME TO {0}_temp'.format(table)) createTable() store.executeSchemaSQL( 'INSERT INTO *DATABASE*.{0} ' 'SELECT oid, * FROM *DATABASE*.{0}_temp'.format(table)) store.executeSc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgradeSystemOid(store): """ Upgrade the system tables to use explicit oid columns. """
store.transact( _upgradeTableOid, store, 'axiom_types', lambda: store.executeSchemaSQL(CREATE_TYPES)) store.transact( _upgradeTableOid, store, 'axiom_objects', lambda: store.executeSchemaSQL(CREATE_OBJECTS), lambda: store.executeSchemaSQL(CREATE_OBJECTS_IDX))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgradeExplicitOid(store): """ Upgrade a store to use explicit oid columns. This allows VACUUMing the database without corrupting it. This requires copying a...
upgradeSystemOid(store) for typename, version in store.querySchemaSQL(LATEST_TYPES): cls = _typeNameToMostRecentClass[typename] if cls.schemaVersion != version: remaining = store.querySQL( 'SELECT oid FROM {} LIMIT 1'.format( store._tableNameFor(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 checkUpgradePaths(self): """ Check that all of the accumulated old Item types have a way to get from their current version to the latest version. @raise axio...
cantUpgradeErrors = [] for oldVersion in self._oldTypesRemaining: # We have to be able to get from oldVersion.schemaVersion to # the most recent type. currentType = _typeNameToMostRecentClass.get( oldVersion.typeName, None) if currentTy...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgradeItem(self, thisItem): """ Upgrade a legacy item. @raise axiom.errors.UpgraderRecursion: If the given item is already in the process of being upgraded....
sid = thisItem.storeID if sid in self._currentlyUpgrading: raise UpgraderRecursion() self._currentlyUpgrading[sid] = thisItem try: return upgradeAllTheWay(thisItem) finally: self._currentlyUpgrading.pop(sid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgradeBatch(self, n): """ Upgrade the entire store in batches, yielding after each batch. @param n: Number of upgrades to perform per transaction @type n: C...
store = self.store def _doBatch(itemType): upgradedAnything = False for theItem in store.query(itemType, limit=n): upgradedAnything = True try: self.upgradeItem(theItem) except: f = Failure...
<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, vg_t and lv_t handle. Usually you would never need to use this method unless you are doing operations using the ctypes funct...
self.vg.open() self.__lvh = lvm_lv_from_uuid(self.vg.handle, self.uuid) if not bool(self.__lvh): raise HandleError("Failed to initialize LV 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 name(self): """ Returns the logical volume name. """
self.open() name = lvm_lv_get_name(self.__lvh) self.close() 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 is_active(self): """ Returns True if the logical volume is active, False otherwise. """
self.open() active = lvm_lv_is_active(self.__lvh) self.close() return bool(active)
<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_suspended(self): """ Returns True if the logical volume is suspended, False otherwise. """
self.open() susp = lvm_lv_is_suspended(self.__lvh) self.close() return bool(susp)
<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 logical volume size in the given units. Default units are MiB. *Args:* """
self.open() size = lvm_lv_get_size(self.__lvh) 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 activate(self): """ Activates the logical volume. *Raises:* * HandleError """
self.open() a = lvm_lv_activate(self.handle) self.close() if a != 0: raise CommitError("Failed to activate 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 deactivate(self): """ Deactivates the logical volume. *Raises:* * HandleError """
self.open() d = lvm_lv_deactivate(self.handle) self.close() if d != 0: raise CommitError("Failed to deactivate 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 open(self): """ Obtains the lvm, vg_t and pv_t handle. Usually you would never need to use this method unless you are doing operations using the ctypes funct...
self.vg.open() self.__pvh = lvm_pv_from_uuid(self.vg.handle, self.uuid) if not bool(self.__pvh): raise HandleError("Failed to initialize PV 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 name(self): """ Returns the physical volume device path. """
self.open() name = lvm_pv_get_name(self.handle) self.close() 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 mda_count(self): """ Returns the physical volume mda count. """
self.open() mda = lvm_pv_get_mda_count(self.handle) self.close() return mda
<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 physical volume size in the given units. Default units are MiB. *Args:* """
self.open() size = lvm_pv_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 dev_size(self, units="MiB"): """ Returns the device size in the given units. Default units are MiB. *Args:* """
self.open() size = lvm_pv_get_dev_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(self, units="MiB"): """ Returns the free size in the given units. Default units are MiB. *Args:* """
self.open() size = lvm_pv_get_free(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 mongoengine_validate_wrapper(old_clean, new_clean): """ A wrapper function to validate formdata against mongoengine-field validator and raise a proper django...
def inner_validate(value): value = old_clean(value) try: new_clean(value) return value except ValidationError, e: raise forms.ValidationError(e) return inner_validate
<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_valid_fields(meta): """walk through the available valid fields.."""
# fetch field configuration and always add the id_field as exclude meta_fields = getattr(meta, 'fields', ()) meta_exclude = getattr(meta, 'exclude', ()) meta_exclude += (meta.document._meta.get('id_field'),) # walk through meta_fields or through the document fields to keep # meta_fields order...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uninstallFrom(self, target): """ Remove this object from the target, as well as any dependencies that it automatically installed which were not explicitly "p...
#did this class powerup on any interfaces? powerdown if so. target.powerDown(self) for dc in self.store.query(_DependencyConnector, _DependencyConnector.target==target): if dc.installee is self: dc.deleteFromStore() for item in installedUniqueRequi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def installedOn(self): """ If this item is installed on another item, return the install target. Otherwise return None. """
try: return self.store.findUnique(_DependencyConnector, _DependencyConnector.installee == self ).target except ItemNotFound: 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 installedDependents(self, target): """ Return an iterable of things installed on the target that require this item. """
for dc in self.store.query(_DependencyConnector, _DependencyConnector.target == target): depends = dependentsOf(dc.installee.__class__) if self.__class__ in depends: yield dc.installee
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def installedUniqueRequirements(self, target): """ Return an iterable of things installed on the target that this item requires and are not required by anything ...
myDepends = dependentsOf(self.__class__) #XXX optimize? for dc in self.store.query(_DependencyConnector, _DependencyConnector.target==target): if dc.installee is self: #we're checking all the others not ourself continue depends = depen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def installedRequirements(self, target): """ Return an iterable of things installed on the target that this item requires. """
myDepends = dependentsOf(self.__class__) for dc in self.store.query(_DependencyConnector, _DependencyConnector.target == target): if dc.installee.__class__ in myDepends: yield dc.installee
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _diffSchema(diskSchema, memorySchema): """ Format a schema mismatch for human consumption. @param diskSchema: The on-disk schema. @param memorySchema: The in...
diskSchema = set(diskSchema) memorySchema = set(memorySchema) diskOnly = diskSchema - memorySchema memoryOnly = memorySchema - diskSchema diff = [] if diskOnly: diff.append('Only on disk:') diff.extend(map(repr, diskOnly)) if memoryOnly: diff.append('Only in memory:'...
<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): """ Close this file and commit it to its permanent location. @return: a Deferred which fires when the file has been moved (and backed up to tert...
now = time.time() try: file.close(self) _mkdirIfNotExists(self._destpath.dirname()) self.finalpath = self._destpath os.rename(self.name, self.finalpath.path) os.utime(self.finalpath.path, (now, now)) except: return defer.fa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _computeFromClause(self, tables): """ Generate the SQL string which follows the "FROM" string and before the "WHERE" string in the final SQL statement. """
tableAliases = [] self.fromClauseParts = [] for table in tables: # The indirect calls to store.getTableName() will create the tables # if needed. (XXX That's bad, actually. They should get created # some other way if necessary. -exarkun) tableN...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _selectStuff(self, verb='SELECT'): """ Return a generator which yields the massaged results of this query with a particular SQL verb. For an attribute query,...
sqlResults = self._runQuery(verb, self._queryTarget) for row in sqlResults: yield self._massageData(row)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def next(self): """ This method is deprecated, a holdover from when queries were iterators, rather than iterables. @return: one element of massaged data. """
if self._selfiter is None: warnings.warn( "Calling 'next' directly on a query is deprecated. " "Perhaps you want to use iter(query).next(), or something " "more expressive like store.findFirst or store.findOrCreate?", DeprecationWarnin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def paginate(self, pagesize=20): """ Split up the work of gathering a result set into multiple smaller 'pages', allowing very large queries to be iterated withou...
sort = self.sort oc = list(sort.orderColumns()) if not oc: # You can't have an unsorted pagination. sort = self.tableClass.storeID.ascending oc = list(sort.orderColumns()) if len(oc) != 1: raise RuntimeError("%d-column sorts not supported...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _massageData(self, row): """ Convert a row into an Item instance by loading cached items or creating new ones based on query results. @param row: an n-tuple,...
result = self.store._loadedItem(self.tableClass, row[0], row[1:]) assert result.store is not None, "result %r has funky store" % (result,) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deleteFromStore(self): """ Delete all the Items which are found by this query. """
if (self.limit is None and not isinstance(self.sort, attributes.UnspecifiedOrdering)): # The ORDER BY is pointless here, and SQLite complains about it. return self.cloneQuery(sort=None).deleteFromStore() #We can do this the fast way or the slow way. # If th...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _massageData(self, row): """ Convert a row into a tuple of Item instances, by slicing it according to the number of columns for each instance, and then proce...
offset = 0 resultBits = [] for i, tableClass in enumerate(self.tableClass): numAttrs = self.schemaLengths[i] result = self.store._loadedItem(self.tableClass[i], row[offset], row[off...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cloneQuery(self, limit=_noItem, sort=_noItem): """ Clone the original query which this distinct query wraps, and return a new wrapper around that clone. """
newq = self.query.cloneQuery(limit=limit, sort=sort) return self.__class__(newq)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count(self): """ Count the number of distinct results of the wrapped query. @return: an L{int} representing the number of distinct results. """
if not self.query.store.autocommit: self.query.store.checkpoint() target = ', '.join([ tableClass.storeID.getColumnName(self.query.store) for tableClass in self.query.tableClass ]) sql, args = self.query._sqlAndArgs( 'SELECT DISTINCT', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sum(self): """ Return the sum of all the values returned by this query. If no results are specified, return None. Note: for non-numeric column types the resu...
res = self._runQuery('SELECT', 'SUM(%s)' % (self._queryTarget,)) or [(0,)] assert len(res) == 1, "more than one result: %r" % (res,) dbval = res[0][0] or 0 return self.attribute.outfilter(dbval, _FakeItemForFilter(self.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 _attachChild(self, child): "attach a child database, returning an identifier for it" self._childCounter += 1 databaseName = 'child_db_%d' % (self._childCounter,) self._attachedChildren[databaseName] = child # ATTACH DATABASE statements can't use bind paramaters, blech. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def newFile(self, *path): """ Open a new file somewhere in this Store's file area. @param path: a sequence of path segments. @return: an L{AtomicFile}. """
assert len(path) > 0, "newFile requires a nonzero number of segments" if self.dbdir is None: if self.filesdir is None: raise RuntimeError("This in-memory store has no file directory") else: tmpbase = self.filesdir else: tmpbase...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepareOldVersionOf(self, typename, version, persistedSchema): """ Note that this database contains old versions of a particular type. Create the appropriat...
appropriateSchema = persistedSchema[typename, version] # create actual attribute objects dummyAttributes = {} for (attribute, sqlType, indexed, pythontype, docstring) in appropriateSchema: atr = pythontype(indexed=indexed, doc=docstring) dummyAttribu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batchInsert(self, itemType, itemAttributes, dataRows): """ Create multiple items in the store without loading corresponding Python objects into memory. the i...
class FakeItem: pass _NEEDS_DEFAULT = object() # token for lookup failure fakeOSelf = FakeItem() fakeOSelf.store = self sql = itemType._baseInsertSQL(self) indices = {} schema = [attr for (name, attr) in itemType.getSchema()] for i, attr in en...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getTableName(self, tableClass): """ Retrieve the fully qualified name of the table holding items of a particular class in this store. If the table does not e...
if not (isinstance(tableClass, type) and issubclass(tableClass, item.Item)): raise errors.ItemClassesOnly("Only subclasses of Item have table names.") if tableClass not in self.typeToTableNameCache: self.typeToTableNameCache[tableClass] = self._tableNameFor(tableClass.typeName,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getTypeID(self, tableClass): """ Retrieve the typeID associated with a particular table in the in-database schema for this Store. A typeID is an opaque integ...
key = (tableClass.typeName, tableClass.schemaVersion) if key in self.typenameAndVersionToID: return self.typenameAndVersionToID[key] return self.transact(self._maybeCreateTable, tableClass, 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 _justCreateTable(self, tableClass): """ Execute the table creation DDL for an Item subclass. Indexes are *not* created. @type tableClass: type @param tableCl...
sqlstr = [] sqlarg = [] # needs to be calculated including version tableName = self._tableNameFor(tableClass.typeName, tableClass.schemaVersion) sqlstr.append("CREATE TABLE %s (" % tableName) # The column is named "oid" instead 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 getItemByID(self, storeID, default=_noItem, autoUpgrade=True): """ Retrieve an item by its storeID, and return it. Note: most of the failure modes of this me...
if not isinstance(storeID, (int, long)): raise TypeError("storeID *must* be an int or long, not %r" % ( type(storeID).__name__,)) if storeID == STORE_SELF_ID: return self try: return self.objectCache.get(storeID) except KeyError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createSQL(self, sql, args=()): """ For use with auto-committing statements such as CREATE TABLE or CREATE INDEX. """
before = time.time() self._execSQL(sql, args) after = time.time() if after - before > 2.0: log.msg('Extremely long CREATE: %s' % (after - before,)) log.msg(sql)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def executeSQL(self, sql, args=()): """ For use with UPDATE or INSERT statements. """
sql = self._execSQL(sql, args) result = self.cursor.lastRowID() if self.executedThisTransaction is not None: self.executedThisTransaction.append((result, sql, args)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invokeRunnable(self): """ Run my runnable, and reschedule or delete myself based on its result. Must be run in a transaction. """
runnable = self.runnable if runnable is None: self.deleteFromStore() else: try: self.running = True newTime = runnable.run() finally: self.running = False self._rescheduleFromRun(newTime)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unscheduleFirst(self, runnable): """ Remove from given item from the schedule. If runnable is scheduled to run multiple times, only the temporally first is r...
for evt in self.store.query(TimedEvent, TimedEvent.runnable == runnable, sort=TimedEvent.time.ascending): evt.deleteFromStore() break
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scheduledTimes(self, runnable): """ Return an iterable of the times at which the given item is scheduled to run. """
events = self.store.query( TimedEvent, TimedEvent.runnable == runnable) return (event.time for event in events if not event.running)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def startService(self): """ Start calling persistent timed events whose time has come. """
super(_SiteScheduler, self).startService() self._transientSchedule(self.now(), self.now())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stopService(self): """ Stop calling persistent timed events. """
super(_SiteScheduler, self).stopService() if self.timer is not None: self.timer.cancel() self.timer = 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 _transientSchedule(self, when, now): """ If this service's store is attached to its parent, ask the parent to schedule this substore to tick at the given tim...
if self.store.parent is not None: subStore = self.store.parent.getItemByID(self.store.idInParent) hook = self.store.parent.findOrCreate( _SubSchedulerParentHook, subStore=subStore) hook._schedule(when)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def migrateDown(self): """ Remove the components in the site store for this SubScheduler. """
subStore = self.store.parent.getItemByID(self.store.idInParent) ssph = self.store.parent.findUnique( _SubSchedulerParentHook, _SubSchedulerParentHook.subStore == subStore, default=None) if ssph is not None: te = self.store.parent.findUnique(TimedE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def migrateUp(self): """ Recreate the hooks in the site store to trigger this SubScheduler. """
te = self.store.findFirst(TimedEvent, sort=TimedEvent.time.descending) if te is not None: self._transientSchedule(te.time, 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 build_graph(path, term_depth=1000, skim_depth=10, d_weights=False, **kwargs): """ Tokenize a text, index a term matrix, and build out a graph. Args: path (st...
# Tokenize text. click.echo('\nTokenizing text...') t = Text.from_file(path) click.echo('Extracted %d tokens' % len(t.tokens)) m = Matrix() # Index the term matrix. click.echo('\nIndexing terms:') m.index(t, t.most_frequent_terms(term_depth), **kwargs) g = Skimmer() # Const...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw_spring(self, **kwargs): """ Render a spring layout. """
nx.draw_spring( self.graph, with_labels=True, font_size=10, edge_color='#dddddd', node_size=0, **kwargs ) 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 build(self, text, matrix, skim_depth=10, d_weights=False): """ 1. For each term in the passed matrix, score its KDE similarity with all other indexed terms. ...
for anchor in bar(matrix.keys): n1 = text.unstem(anchor) # Heaviest pair scores: pairs = matrix.anchored_pairs(anchor).items() for term, weight in list(pairs)[:skim_depth]: # If edges represent distance, use the complement of the raw ...