text
stringlengths
81
112k
Returns either the topic component types or the rconfigration's component types. def get_component_types(topic_id, remoteci_id, db_conn=None): """Returns either the topic component types or the rconfigration's component types.""" db_conn = db_conn or flask.g.db_conn rconfiguration = remotecis.get_...
For each component type of a topic, get the last one. def get_last_components_by_type(component_types, topic_id, db_conn=None): """For each component type of a topic, get the last one.""" db_conn = db_conn or flask.g.db_conn schedule_components_ids = [] for ct in component_types: where_clause =...
Process some verifications of the provided components ids. def verify_and_get_components_ids(topic_id, components_ids, component_types, db_conn=None): """Process some verifications of the provided components ids.""" db_conn = db_conn or flask.g.db_conn if len(components_id...
Retrieve all tags attached to a component. def retrieve_tags_from_component(user, c_id): """Retrieve all tags attached to a component.""" JCT = models.JOIN_COMPONENTS_TAGS query = (sql.select([models.TAGS]) .select_from(JCT.join(models.TAGS)) .where(JCT.c.component_id == c_id)) ...
Add a tag on a specific component. def add_tag_for_component(user, c_id): """Add a tag on a specific component.""" v1_utils.verify_existence_and_get(c_id, _TABLE) values = { 'component_id': c_id } component_tagged = tags.add_tag_to_resource(values, ...
Delete a tag on a specific component. def delete_tag_for_component(user, c_id, tag_id): """Delete a tag on a specific component.""" # Todo : check c_id and tag_id exist in db query = _TABLE_TAGS.delete().where(_TABLE_TAGS.c.tag_id == tag_id and _TABLE_TAGS.c.componen...
Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error def should_be_hidden_as_cause(exc): """ Used everywhere to decide if some exception type should be displayed or hidden as the casue of an error """ # reduced traceback in case of HasWrongType (instance_of ch...
Helper function to determine if some exception is of some type, by also looking at its declared __cause__ :param exc: :param ref_type: :return: def is_error_of_type(exc, ref_type): """ Helper function to determine if some exception is of some type, by also looking at its declared __cause__ :p...
Wraps the provided validation function so that in case of failure it raises the given failure_type or a WrappingFailure with the given help message. :param validation_callable: :param failure_type: an optional subclass of `WrappingFailure` that should be raised in case of failure, instead of `WrappingF...
Wraps the given validation callable to accept None values silently. When a None value is received by the wrapper, it is not passed to the validation_callable and instead this function will return True. When any other value is received the validation_callable is called as usual. Note: the created wrapper ha...
Wraps the given validation callable to reject None values. When a None value is received by the wrapper, it is not passed to the validation_callable and instead this function will raise a WrappingFailure. When any other value is received the validation_callable is called as usual. :param validation_callabl...
The method used to get the formatted help message according to kwargs. By default it returns the 'help_msg' attribute, whether it is defined at the instance level or at the class level. The help message is formatted according to help_msg.format(**kwargs), and may be terminated with a dot and a ...
The function called to get the details appended to the help message when self.append_details is True def get_details(self): """ The function called to get the details appended to the help message when self.append_details is True """ strval = str(self.wrong_value) if len(strval) > self.__max_str...
Overrides the method in Failure so as to add a few details about the wrapped function and outcome def get_details(self): """ Overrides the method in Failure so as to add a few details about the wrapped function and outcome """ if isinstance(self.validation_outcome, Exception): if isinstanc...
We override this method from HelpMsgMixIn to replace wrapped_func with its name def get_context_for_help_msgs(self, context_dict): """ We override this method from HelpMsgMixIn to replace wrapped_func with its name """ context_dict = copy(context_dict) context_dict['wrapped_func'] = get_callabl...
A class decorator. It goes through all class variables and for all of those that are descriptors with a __set__, it wraps the descriptors' setter function with a `validate_arg` annotation :param field_name: :param validation_func: :param help_msg: :param error_type: :param none_policy: :par...
A function decorator to add input validation prior to the function execution. It should be called with named arguments: for each function arg name, provide a single validation function or a list of validation functions to apply. If validation fails, it will raise an InputValidationError with details about the f...
A decorator to apply function input validation for the given argument name, with the provided base validation function(s). You may use several such decorators on a given function as long as they are stacked on top of each other (no external decorator in the middle) :param arg_name: :param validation_fu...
A decorator to apply function output validation to this function's output, with the provided base validation function(s). You may use several such decorators on a given function as long as they are stacked on top of each other (no external decorator in the middle) :param validation_func: the base validatio...
This method is equivalent to decorating a class with the `@validate_field` decorator but can be used a posteriori. :param cls: the class to decorate :param field_name: the name of the argument to validate or _OUT_KEY for output validation :param validation_func: the validation function or list of v...
This method is equivalent to applying `decorate_with_validation` once for each of the provided arguments of the function `func` as well as output `_out_`. validation_funcs keyword arguments are validation functions for each arg name. Note that this method is less flexible than decorate_with_validation sinc...
This method is the inner method used in `@validate_io`, `@validate_arg` and `@validate_out`. It can be used if you with to perform decoration manually without a decorator. :param func: :param arg_name: the name of the argument to validate or _OUT_KEY for output validation :param validation_func: the va...
Depending on none_policy and of the fact that the target parameter is nonable or not, returns a corresponding NonePolicy :param is_nonable: :param none_policy: :return: def _get_final_none_policy_for_validator(is_nonable, # type: bool none_policy # type: No...
Utility method to decorate the provided function with the provided input and output Validator objects. Since this method takes Validator objects as argument, it is for advanced users. :param func: the function to decorate. It might already be decorated, this method will check it and wont create another wra...
Called by the `validating_wrapper` in the first step (a) `apply_on_each_func_args` for each function input before executing the function. It simply delegates to the validator. The signature of this function is hardcoded to correspond to `apply_on_each_func_args`'s behaviour and should therefore not be changed. ...
Overrides the base behaviour defined in ValidationError in order to add details about the function. :return: def get_what_txt(self): """ Overrides the base behaviour defined in ValidationError in order to add details about the function. :return: """ return 'input [{var}]...
Overrides the base behaviour defined in ValidationError in order to add details about the class field. :return: def get_what_txt(self): """ Overrides the base behaviour defined in ValidationError in order to add details about the class field. :return: """ return 'field [...
Generate unique nonce with counter, uuid and rng. def generate_nonce_timestamp(): """ Generate unique nonce with counter, uuid and rng.""" global count rng = botan.rng().get(30) uuid4 = uuid.uuid4().bytes # 16 byte tmpnonce = (bytes(str(count).encode('utf-8'))) + uuid4 + rng nonce = tmpnonce[:...
recursively merges dict's. not just simple a['key'] = b['key'], if both a and bhave a key who's value is a dict then dict_merge is called on both values and the result stored in the returned dictionary. def dict_merge(*dict_list): """recursively merges dict's. not just simple a['key'] = b['key'], if bo...
Dispatch jobs to remotecis. The remoteci can use this method to request a new job. Before a job is dispatched, the server will flag as 'killed' all the running jobs that were associated with the remoteci. This is because they will never be finished. def schedule_jobs(user): """Dispatch jobs to re...
Create a new job in the same topic as the job_id provided and associate the latest components of this topic. def create_new_update_job_from_an_existing_job(user, job_id): """Create a new job in the same topic as the job_id provided and associate the latest components of this topic.""" values = { ...
Create a new job in the 'next topic' of the topic of the provided job_id. def create_new_upgrade_job_from_an_existing_job(user): """Create a new job in the 'next topic' of the topic of the provided job_id.""" values = schemas.job_upgrade.post(flask.request.json) values.update({ 'id': utils...
Get all jobs. If topic_id is not None, then return all the jobs with a topic pointed by topic_id. def get_all_jobs(user, topic_id=None): """Get all jobs. If topic_id is not None, then return all the jobs with a topic pointed by topic_id. """ # get the diverse parameters args = schemas...
Update a job def update_job_by_id(user, job_id): """Update a job """ # get If-Match header if_match_etag = utils.check_and_get_etag(flask.request.headers) # get the diverse parameters values = schemas.job.put(flask.request.json) job = v1_utils.verify_existence_and_get(job_id, _TABLE) ...
Get all results from job. def get_all_results_from_jobs(user, j_id): """Get all results from job. """ job = v1_utils.verify_existence_and_get(j_id, _TABLE) if not user.is_in_team(job['team_id']) and not user.is_read_only_user(): raise dci_exc.Unauthorized() # get testscases from tests_re...
Retrieve all tags attached to a job. def get_tags_from_job(user, job_id): """Retrieve all tags attached to a job.""" job = v1_utils.verify_existence_and_get(job_id, _TABLE) if not user.is_in_team(job['team_id']) and not user.is_read_only_user(): raise dci_exc.Unauthorized() JTT = models.JOIN_...
Add a tag to a job. def add_tag_to_job(user, job_id): """Add a tag to a job.""" job = v1_utils.verify_existence_and_get(job_id, _TABLE) if not user.is_in_team(job['team_id']): raise dci_exc.Unauthorized() values = { 'job_id': job_id } job_tagged = tags.add_tag_to_resource(val...
Delete a tag from a job. def delete_tag_from_job(user, job_id, tag_id): """Delete a tag from a job.""" _JJT = models.JOIN_JOBS_TAGS job = v1_utils.verify_existence_and_get(job_id, _TABLE) if not user.is_in_team(job['team_id']): raise dci_exc.Unauthorized() v1_utils.verify_existence_and_get...
Return the parent of the given node, based on an internal dictionary mapping of child nodes to the child's parent required since ElementTree doesn't make info about node ancestry/parentage available. def _lookup_node_parent(self, node): """ Return the parent of the given node, based on ...
Return True if the given node is an ElementTree Element, a fact that can be tricky to determine if the cElementTree implementation is used. def _is_node_an_element(self, node): """ Return True if the given node is an ElementTree Element, a fact that can be tricky to determine if...
Return result of performing the given XPath query on the given node. All known namespace prefix-to-URI mappings in the document are automatically included in the XPath invocation. If an empty/default namespace (i.e. None) is defined, this is converted to the prefix name '_' so it can b...
List the entries to be purged from the database. def get_to_purge_archived_resources(user, table): """List the entries to be purged from the database. """ if user.is_not_super_admin(): raise dci_exc.Unauthorized() archived_resources = get_archived_resources(table) return flask.jsonify({table...
Remove the entries to be purged from the database. def purge_archived_resources(user, table): """Remove the entries to be purged from the database. """ if user.is_not_super_admin(): raise dci_exc.Unauthorized() where_clause = sql.and_( table.c.state == 'archived' ) query = table.d...
Refresh the resource API Secret. def refresh_api_secret(user, resource, table): """Refresh the resource API Secret. """ resource_name = table.name[0:-1] where_clause = sql.and_( table.c.etag == resource['etag'], table.c.id == resource['id'], ) values = { 'api_secret': sig...
Generate a package.json file. def npm(package_json, output_file, pinned_file): """Generate a package.json file.""" amd_build_deprecation_warning() try: version = get_distribution(current_app.name).version except DistributionNotFound: version = '' output = { 'name': current_...
Returns a list of the latest root cause analysis results for a specified check. Optional Parameters: * limit -- Limits the number of returned results to the specified quantity. Type: Integer Default: 100 * offset -- O...
Update check details, returns dictionary of details 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']
Modify settings for a check. The provided settings will overwrite previous values. Settings not provided will stay the same as before the update. To clear an existing value, provide an empty value. Please note that you cannot change the type of a check once it has been cr...
Get the average time / uptime value for a specified check and time period. Optional parameters: * time_from -- Start time of period. Format is UNIX timestamp Type: Integer Default: 0 * time_to -- End time of period. Format is UNIX ti...
Get a list of probes that performed tests for a specified check during a specified period. 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: ...
Activate public report for this check. Returns status message 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']
Deactivate public report for this check. Returns status message def removePublicReport(self): """Deactivate public report for this check. Returns status message""" response = self.pingdom.request('DELETE', 'reports.public/%s' % self.id) ...
Extract the dependencies from the bundle and its sub-bundles. 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.con...
Make a semantic version from Python PEP440 version. Semantic versions does not handle post-releases. 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.rel...
Calculate the max number of item that an option can stored in the pool at give time. This is to limit the pool size to POOL_SIZE Args: option_index (int): the index of the option to calculate the size for pool (dict): answer pool num_option (int): total number of options available for ...
submit a student answer to the answer pool The answer maybe selected to stay in the pool depending on the selection algorithm Args: pool (dict): answer pool Answer pool format: { option1_index: { 'student_id': { can store algorithm specific i...
The simple selection algorithm. This algorithm randomly select an answer from the pool to discard and add the new one when the pool reaches the limit def offer_simple(pool, answer, rationale, student_id, options): """ The simple selection algorithm. This algorithm randomly select an answer from t...
The random selection algorithm. The same as simple algorithm 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)
This validator checks if the answers includes all possible options Args: answers (str): the answers to be checked options (dict): all options that should exist in the answers algo (str): selection algorithm Returns: None if everything is good. Otherwise, the missing option erro...
Validate answers based on selection algorithm This is called when instructor setup the tool and providing seeded answers to the question. This function is trying to validate if instructor provided enough seeds for a give algorithm. e.g. we require 1 seed for each option in simple algorithm and at least 1 s...
Select other student's answers from answer pool or seeded answers based on the selection algorithm Args: pool (dict): answer pool, format: { option1_index: { student_id: { can store algorithm specific info here } }, option2_ind...
Get answers from others with simple algorithm, which picks one answer for each option. Args: see `get_other_answers` num_responses (int): the number of responses to be returned. This value may not be respected if there is not enough answers to return Returns: dict: answers ...
Get answers from others with random algorithm, which randomly select answer from the pool. Student may get three answers for option 1 or one answer for option 1 and two answers for option 2. Args: see `get_other_answers` num_responses (int): the number of responses to be returned. This value m...
Convert seeded answers into the format that can be merged into student answers. Args: answers (list): seeded answers Returns: dict: seeded answers with student answers format: { 0: { 'seeded0': 'rationaleA' } 1: { ...
Batch processors stopped polling at version 2, so they no longer needed the idleInterval attribute. They also gained a scheduled attribute which tracks their interaction with the scheduler. Since they stopped polling, we also set them up as a timed event here to make sure that they don't silently disa...
Create an Axiom Item type which is suitable to use as a batch processor for the given Axiom Item type. Processors created this way depend on a L{iaxiom.IScheduler} powerup on the on which store they are installed. @type forType: L{item.MetaItem} @param forType: The Axiom Item type for which to cre...
Adapt a L{Store} to L{IBatchService}. If C{st} is a substore, return a simple wrapper that delegates to the site store's L{IBatchService} powerup. Return C{None} if C{st} has no L{BatchProcessingControllerService}. def storeBatchServiceSpecialCase(st, pups): """ Adapt a L{Store} to L{IBatchServic...
Mark the unit of work as failed in the database and update the listener so as to skip it next time. 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() ...
Try to run one unit of work through one listener. If there are more listeners or more work, reschedule this item to be run again in C{self.busyInterval} milliseconds, otherwise unschedule it. @rtype: L{extime.Time} or C{None} @return: The next time at which to run this item, used by th...
Add the given Item to the set which will be notified of Items available for processing. Note: Each Item is processed synchronously. Adding too many listeners to a single batch processor will cause the L{step} method to block while it sends notification to each listener. @param...
Remove a previously added listener. def removeReliableListener(self, listener): """ Remove a previously added listener. """ self.store.query(_ReliableListener, attributes.AND(_ReliableListener.processor == self, _ReliableL...
Return an iterable of the listeners which have been added to this batch processor. def getReliableListeners(self): """ Return an iterable of the listeners which have been added to this batch processor. """ for rellist in self.store.query(_ReliableListener, _ReliableListe...
Return an iterable of two-tuples of listeners which raised an exception from C{processItem} and the item which was passed as the argument to that method. def getFailedItems(self): """ Return an iterable of two-tuples of listeners which raised an exception from C{processItem} and...
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 not already scheduled to run, this will schedule it. It will also start the batch process if it is not yet running and there are any registered remote l...
Invoke the given bound item method in the batch process. Return a Deferred which fires when the method has been invoked. 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. """...
Run tasks until stopService is called. 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: ...
find every column in every sheet and put it in a new sheet or book. 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...
Recursively upgrade C{store}. def upgradeStore(self, store): """ Recursively upgrade C{store}. """ self.upgradeEverything(store) upgradeExplicitOid(store) for substore in store.query(SubStore): print 'Upgrading: {!r}'.format(substore) self.upgrad...
Upgrade C{store} performing C{count} upgrades per transaction. Also, catch any exceptions and print out something useful. def perform(self, store, count): """ Upgrade C{store} performing C{count} upgrades per transaction. Also, catch any exceptions and print out something useful. ...
Override L{code.InteractiveConsole.runcode} to run the code in a transaction unless the local C{autocommit} is currently set to a true value. def runcode(self, code): """ Override L{code.InteractiveConsole.runcode} to run the code in a transaction unless the local C{autocommit} ...
Return a dictionary representing the namespace which should be available to the user. def namespace(self): """ Return a dictionary representing the namespace which should be available to the user. """ self._ns = { 'db': self.store, 'store': store,...
Create a new account in the given store. @param siteStore: A site Store to which login credentials will be added. @param username: Local part of the username for the credentials to add. @param domain: Domain part of the username for the credentials to add. @param password: Passw...
Create a new L{Item} subclass with L{numAttributes} integers in its schema. def itemTypeWithSomeAttributes(attributeTypes): """ Create a new L{Item} subclass with L{numAttributes} integers in its schema. """ class SomeItem(Item): typeName = 'someitem_' + str(typeNameCounter()) f...
Create some instances of a particular type in a store. def createSomeItems(store, itemType, values, counter): """ Create some instances of a particular type in a store. """ for i in counter: itemType(store=store, **values)
save the instance or create a new one.. 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)) ...
Return a callable which will invoke C{func} in a transaction using the C{store} attribute of the first parameter passed to it. Typically this is used to create Item methods which are automatically run in a transaction. The attributes of the returned callable will resemble those of C{func} as closely a...
Collect all the items that should be deleted when an item or items of a particular item type are deleted. @param tableClass: An L{Item} subclass. @param comparison: A one-argument callable taking an attribute and returning an L{iaxiom.IComparison} describing the items to collect. @return: An ...
Returns a C{bool} indicating whether deletion of an item or items of a particular item type should be allowed to proceed. @param tableClass: An L{Item} subclass. @param comparison: A one-argument callable taking an attribute and returning an L{iaxiom.IComparison} describing the items to collect. ...
Generate a dummy subclass of Item that will have the given attributes, and the base Item methods, but no methods of its own. This is for use with upgrading. @param typeName: a string, the Axiom TypeName to have attributes for. @param schemaVersion: an int, the (old) version of the schema this is a pro...
Class decorator for indicating a powerup's powerup interfaces. The class will also be declared as implementing the interface. @type iface: L{zope.interface.Interface} @param iface: The powerup interface. @type priority: int @param priority: The priority the powerup will be installed at. def empo...
Installs a powerup (e.g. plugin) on an item or store. Powerups will be returned in an iterator when queried for using the 'powerupsFor' method. Normally they will be returned in order of installation [this may change in future versions, so please don't depend on it]. Higher priorities...
Remove a powerup. If no interface is specified, and the type of the object being installed has a "powerupInterfaces" attribute (containing either a sequence of interfaces, or a sequence of (interface, priority) tuples), the target will be powered down with this object on those i...
Returns powerups installed using C{powerUp}, in order of descending priority. Powerups found to have been deleted, either during the course of this powerupsFor iteration, during an upgrader, or previously, will not be returned. def powerupsFor(self, interface): """ Retu...
Return an iterator of the interfaces for which the given powerup is installed on this object. This is not implemented for in-memory powerups. It will probably fail in an unpredictable, implementation-dependent way if used on one. def interfacesFor(self, powerup): """ Return an...
Collect powerup interfaces this object declares that it can be installed on. def _getPowerupInterfaces(self): """ Collect powerup interfaces this object declares that it can be installed on. """ powerupInterfaces = getattr(self.__class__, "powerupInterfaces", ()) ...
Is this object currently valid as a reference? Objects which will be deleted in this transaction, or objects which are not in the same store are not valid. See attributes.reference.__get__. def _currentlyValidAsReferentFor(self, store): """ Is this object currently valid as a referenc...
Prepare each attribute in my schema for insertion into a given store, either by upgrade or by creation. This makes sure all references point to this store and all relative paths point to this store's files directory. def _schemaPrepareInsert(self, store): """ Prepare each attri...
Create and return a new instance from a row from the store. 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, sto...
return all persistent class attributes 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, ...
Return a dictionary of all attributes which will be/have been/are being stored in the database. def persistentValues(self): """ Return a dictionary of all attributes which will be/have been/are being stored in the database. """ return dict((k, getattr(self, k)) for (k, a...