code
stringlengths
1
18.2k
def assign_log_entry_to_log(self, log_entry_id, log_id): """Adds an existing ``LogEntry`` to a ``Log``. arg: log_entry_id (osid.id.Id): the ``Id`` of the ``LogEntry`` arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` raise: AlreadyExists - ``log_entry_id`` is already assigned to ``log_id`` raise: NotFound - ``log_ent...
def unassign_log_entry_from_log(self, log_entry_id, log_id): """Removes a ``LogEntry`` from a ``Log``. arg: log_entry_id (osid.id.Id): the ``Id`` of the ``LogEntry`` arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` raise: NotFound - ``log_entry_id`` or ``log_id`` not found or ``log_entry_id`` not assigned to ``log_i...
def reassign_log_entry_to_log(self, log_entry_id, from_log_id, to_log_id): """Moves a ``LogEntry`` from one ``Log`` to another. Mappings to other ``Logs`` are unaffected. arg: log_entry_id (osid.id.Id): the ``Id`` of the ``LogEntry`` arg: from_log_id (osid.id.Id): the ``Id`` of the current ``Log`` arg: to_log_id (osid....
def can_create_log_with_record_types(self, log_record_types): """Tests if this user can create a single ``Log`` using the desired record types. While ``LoggingManager.getLogRecordTypes()`` can be used to examine which records are supported, this method tests which record(s) are required for creating a specific ``Log``....
None: return self._catalog_session.can_create_catalog_with_record_types(catalog_record_types=log_record_types) return True
def update_log(self, log_form): """Updates an existing log. arg: log_form (osid.logging.LogForm): the form containing the elements to be updated raise: IllegalState - ``log_form`` already used in an update transaction raise: InvalidArgument - the form contains an invalid value raise: NullArgument - ``log_id`` or ``log_...
update transaction') except KeyError: raise errors.Unsupported('log_form did not originate from this session') if not log_form.is_valid(): raise errors.InvalidArgument('one or more of the form elements is invalid') collection.save(log_form._my_map) # save is deprecated - change to replace_one self._forms[log_form.get_i...
def alias_log(self, log_id, alias_id): """Adds an ``Id`` to a ``Log`` for the purpose of creating compatibility. The primary ``Id`` of the ``Log`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another log, it is reassigned to the given log ``Id``....
def get_log_hierarchy_id(self): """Gets the hierarchy ``Id`` associated with this session. return: (osid.id.Id) - the hierarchy ``Id`` associated with this session *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.BinHierarchySession.get_bin_hierarchy_id if ...
def get_log_hierarchy(self): """Gets the hierarchy associated with this session. return: (osid.hierarchy.Hierarchy) - the hierarchy associated with this session raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.*...
def get_root_logs(self): """Gets the root logs in the log hierarchy. A node with no parents is an orphan. While all log ``Ids`` are known to the hierarchy, an orphan does not appear in the hierarchy unless explicitly added as a root node or child of another node. return: (osid.logging.LogList) - the root logs raise: Op...
def has_parent_logs(self, log_id): """Tests if the ``Log`` has any parents. arg: log_id (osid.id.Id): the ``Id`` of a log return: (boolean) - ``true`` if the log has parents, ``false`` otherwise raise: NotFound - ``log_id`` is not found raise: NullArgument - ``log_id`` is ``null`` raise: OperationFailed - unable to com...
def is_parent_of_log(self, id_, log_id): """Tests if an ``Id`` is a direct parent of a log. arg: id (osid.id.Id): an ``Id`` arg: log_id (osid.id.Id): the ``Id`` of a log return: (boolean) - ``true`` if this ``id`` is a parent of ``log_id,`` ``false`` otherwise raise: NotFound - ``log_id`` is not found raise: NullArgume...
def get_parent_log_ids(self, log_id): """Gets the parent ``Ids`` of the given log. arg: log_id (osid.id.Id): the ``Id`` of a log return: (osid.id.IdList) - the parent ``Ids`` of the log raise: NotFound - ``log_id`` is not found raise: NullArgument - ``log_id`` is ``null`` raise: OperationFailed - unable to complete req...
def get_parent_logs(self, log_id): """Gets the parent logs of the given ``id``. arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` to query return: (osid.logging.LogList) - the parent logs of the ``id`` raise: NotFound - a ``Log`` identified by ``Id is`` not found raise: NullArgument - ``log_id`` is ``null`` raise: Op...
def is_ancestor_of_log(self, id_, log_id): """Tests if an ``Id`` is an ancestor of a log. arg: id (osid.id.Id): an ``Id`` arg: log_id (osid.id.Id): the ``Id`` of a log return: (boolean) - ``true`` if the ``id`` is an ancestor of the ``log_id,`` ``false`` otherwise raise: NotFound - ``log_id`` is not found raise: NullAr...
def has_child_logs(self, log_id): """Tests if a log has any children. arg: log_id (osid.id.Id): the ``Id`` of a log return: (boolean) - ``true`` if the ``log_id`` has children, ``false`` otherwise raise: NotFound - ``log_id`` is not found raise: NullArgument - ``log_id`` is ``null`` raise: OperationFailed - unable to c...
def is_child_of_log(self, id_, log_id): """Tests if an ``Id`` is a direct child of a log. arg: id (osid.id.Id): an ``Id`` arg: log_id (osid.id.Id): the ``Id`` of a log return: (boolean) - ``true`` if this ``id`` is a child of ``log_id,`` ``false`` otherwise raise: NotFound - ``log_id`` is not found raise: NullArgument ...
def get_child_log_ids(self, log_id): """Gets the child ``Ids`` of the given log. arg: log_id (osid.id.Id): the ``Id`` to query return: (osid.id.IdList) - the children of the depot raise: NotFound - ``log_id`` is not found raise: NullArgument - ``log_id`` is ``null`` raise: OperationFailed - unable to complete request r...
def get_child_logs(self, log_id): """Gets the child logs of the given ``id``. arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` to query return: (osid.logging.LogList) - the child logs of the ``id`` raise: NotFound - a ``Log`` identified by ``Id is`` not found raise: NullArgument - ``log_id`` is ``null`` raise: Opera...
def is_descendant_of_log(self, id_, log_id): """Tests if an ``Id`` is a descendant of a log. arg: id (osid.id.Id): an ``Id`` arg: log_id (osid.id.Id): the ``Id`` of a log return: (boolean) - ``true`` if the ``id`` is a descendant of the ``log_id,`` ``false`` otherwise raise: NotFound - ``log_id`` is not found raise: Nu...
def get_log_nodes(self, log_id, ancestor_levels, descendant_levels, include_siblings): """Gets a portion of the hierarchy for the given log. arg: log_id (osid.id.Id): the ``Id`` to query arg: ancestor_levels (cardinal): the maximum number of ancestor levels to include. A value of 0 returns no parents in the node. arg: ...
osid.resource.BinHierarchySession.get_bin_nodes return objects.LogNode(self.get_log_node_ids( log_id=log_id, ancestor_levels=ancestor_levels, descendant_levels=descendant_levels, include_siblings=include_siblings)._my_map, runtime=self._runtime, proxy=self._proxy)
def add_root_log(self, log_id): """Adds a root log. arg: log_id (osid.id.Id): the ``Id`` of a log raise: AlreadyExists - ``log_id`` is already in hierarchy raise: NotFound - ``log_id`` is not found raise: NullArgument - ``log_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied -...
def remove_root_log(self, log_id): """Removes a root log. arg: log_id (osid.id.Id): the ``Id`` of a log raise: NotFound - ``log_id`` is not a root raise: NullArgument - ``log_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- Th...
def add_child_log(self, log_id, child_id): """Adds a child to a log. arg: log_id (osid.id.Id): the ``Id`` of a log arg: child_id (osid.id.Id): the ``Id`` of the new child raise: AlreadyExists - ``log_id`` is already a parent of ``child_id`` raise: NotFound - ``log_id`` or ``child_id`` not found raise: NullArgument - ``...
def remove_child_log(self, log_id, child_id): """Removes a child from a log. arg: log_id (osid.id.Id): the ``Id`` of a log arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``log_id`` not a parent of ``child_id`` raise: NullArgument - ``log_id`` or ``child_id`` is ``null`` raise: OperationFailed...
def remove_child_logs(self, log_id): """Removes all children from a log. arg: log_id (osid.id.Id): the ``Id`` of a log raise: NotFound - ``log_id`` not in hierarchy raise: NullArgument - ``log_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *complianc...
def bar_chart(data, bar_char='=', width=80): """Return an horizontal bar chart >>> print bar_chart({ ... 'one': '1', ... 'two': '2', ... 'three': '3', ... 'four': '4', ... 'five': '5', ... }) five ===== four ==== one = three === two == >>> print bar_chart({ ... '1/1': 1/1.0, ... '1/2': 1/2.0, ... '1/3': 1/3.0, ... '1/4...
============================================================================= """ if type(data) is dict: output = [] max_len = len(max(data, key=len)) float_values = map(float, data.values()) max_value = max(float_values) min_value = min(float_values) all_integer = all(f.is_integer() for f in float_values) for key in s...
def security(name, *permissions): """ Decorator to add security definition. """ def inner(c): c.security = Security(name, *permissions) return c return inner
def action(callback=None, name=None, path=None, methods=Method.GET, resource=None, tags=None, summary=None, middleware=None): # type: (Callable, Path, Path, Methods, Type[Resource], Tags, str, List[Any]) -> Operation """ Decorator to apply an action to a resource. An action is applied to a `detail` operation. """ # Gen...
def listing(callback=None, path=None, method=Method.GET, resource=None, tags=None, summary="List resources", middleware=None, default_limit=50, max_limit=None, use_wrapper=True): # type: (Callable, Path, Methods, Resource, Tags, str, List[Any], int, int) -> Operation """ Decorator to configure an operation that returns...
def create(callback=None, path=None, method=Method.POST, resource=None, tags=None, summary="Create a new resource", middleware=None): # type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation """ Decorator to configure an operation that creates a resource. """ def inner(c): op = ResourceOperation(c...
def detail(callback=None, path=None, method=Method.GET, resource=None, tags=None, summary="Get specified resource.", middleware=None): # type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation """ Decorator to configure an operation that fetches a resource. """ def inner(c): op = Operation(c, path ...
def update(callback=None, path=None, method=Method.PUT, resource=None, tags=None, summary="Update specified resource.", middleware=None): # type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation """ Decorator to configure an operation that updates a resource. """ def inner(c): op = ResourceOperati...
def patch(callback=None, path=None, method=Method.PATCH, resource=None, tags=None, summary="Patch specified resource.", middleware=None): # type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation """ Decorator to configure an operation that patches a resource. """ def inner(c): op = ResourceOperati...
def delete(callback=None, path=None, method=Method.DELETE, tags=None, summary="Delete specified resource.", middleware=None): # type: (Callable, Path, Methods, Tags, str, List[Any]) -> Operation """ Decorator to configure an operation that deletes resource. """ def inner(c): op = Operation(c, path or PathParam('{key_fi...
def execute(self, request, *args, **path_args): # type: (BaseHttpRequest, tuple, Dict[Any]) -> Any """ Execute the callback (binding callback if required) """ binding = self.binding if binding: # Provide binding as decorators are executed prior to binding return self.callback(binding, request, *args, **path_args) else:...
def bind_to_instance(self, instance): """ Bind a ResourceApi instance to an operation. """ self.binding = instance self.middleware.append(instance)
def op_paths(self, path_prefix=None): # type: (Path) -> Generator[Tuple[UrlPath, Operation]] """ Yield operations paths stored in containers. """ url_path = self.path if path_prefix: url_path = path_prefix + url_path yield url_path, self
def resource(self): """ Resource associated with operation. """ if self._resource: return self._resource elif self.binding: return self.binding.resource
def key_field_name(self): """ Field identified as the key. """ name = 'resource_id' if self.resource: key_field = getmeta(self.resource).key_field if key_field: name = key_field.attname return name
def to_swagger(self): """ Generate a dictionary for documentation generation. """ return dict_filter( operationId=self.operation_id, description=(self.callback.__doc__ or '').strip() or None, summary=self.summary or None, tags=list(self.tags) or None, deprecated=self.deprecated or None, consumes=list(self.consumes) or ...
def tags(self): # type: () -> Set[str] """ Tags applied to operation. """ tags = set() if self._tags: tags.update(self._tags) if self.binding: binding_tags = getattr(self.binding, 'tags', None) if binding_tags: tags.update(binding_tags) return tags
def run_container(self, conf, images, **kwargs): """Run this image and all dependency images""" with self._run_container(conf, images, **kwargs): pass
def delete_deps(self, conf, images): """Delete any deleteable images""" for dependency_name, _ in conf.dependency_images(): image = images[dependency_name] if image.deleteable_image: log.info("Removing un-needed image {0}".format(image.image_name)) conf.harpoon.docker_api.remove_image(image.image_name)
def run_deps(self, conf, images): """Start containers for all our dependencies""" for dependency_name, detached in conf.dependency_images(for_running=True): try: self.run_container(images[dependency_name], images, detach=detached, dependency=True) except Exception as error: raise BadImage("Failed to start dependency co...
def stop_deps(self, conf, images): """Stop the containers for all our dependencies""" for dependency, _ in conf.dependency_images(): self.stop_deps(images[dependency], images) try: self.stop_container(images[dependency], fail_on_bad_exit=True, fail_reason="Failed to run dependency container") except BadImage: raise exc...
def wait_for_deps(self, conf, images): """Wait for all our dependencies""" from harpoon.option_spec.image_objs import WaitCondition api = conf.harpoon.docker_context_maker().api waited = set() last_attempt = {} dependencies = set(dep for dep, _ in conf.dependency_images()) # Wait conditions come from dependency_options...
time.time() elif done is WaitCondition.Timedout: log.warning("Stopping dependency because it timedout waiting\tcontainer_id=%s", image.container_id) self.stop_container(image) else: waited.add(dependency) if set(this_round) != set([WaitCondition.KeepWaiting]): if dependencies - waited == set(): log.info("Finished waiti...
hp.write_to(conf.harpoon.stdout, "=================== Logs for failed container {0} ({1})\n".format(container_id, container_name)) for line in conf.harpoon.docker_api.logs(container_id).split("\n"): hp.write_to(conf.harpoon.stdout, "{0}\n".format(line)) hp.write_to(conf.harpoon.stdout, "------------------- End logs for...
def wait_for_dep(self, api, conf, wait_condition, start, last_attempt): """Wait for this image""" from harpoon.option_spec.image_objs import WaitCondition conditions = list(wait_condition.conditions(start, last_attempt)) if conditions[0] in (WaitCondition.KeepWaiting, WaitCondition.Timedout): return conditions[0] log.i...
def create_container(self, conf, detach, tty): """Create a single container""" name = conf.name image_name = conf.image_name if conf.tag is not NotSpecified: image_name = conf.image_name_with_tag container_name = conf.container_name with conf.assumed_role(): env = dict(e.pair for e in conf.env) binds = conf.volumes.bin...
%s", volumes_from) host_config = conf.harpoon.docker_api.create_host_config( binds = binds , volumes_from = volumes_from , port_bindings = port_bindings , devices = conf.devices , lxc_conf = conf.lxc_conf , privileged = conf.privileged , restart_policy = conf.restart_policy , dns = conf.network.dns , dns_search = conf....
, stdin_open = tty , hostname = conf.network.hostname , domainname = conf.network.domainname , network_disabled = conf.network.disabled , host_config = host_config , **conf.other_options.create ) if isinstance(container_id, dict): if "errorDetail" in container_id: raise BadImage("Failed to create container", image=name...
def start_container(self, conf, tty=True, detach=False, is_dependency=False, no_intervention=False): """Start up a single container""" # Make sure we can bind to our specified ports! if not conf.harpoon.docker_api.base_url.startswith("http"): self.find_bound_ports(conf.ports) container_id = conf.container_id container_...
def start_tty(self, conf, interactive): """Startup a tty""" try: api = conf.harpoon.docker_context_maker().api container_id = conf.container_id stdin = conf.harpoon.tty_stdin stdout = conf.harpoon.tty_stdout stderr = conf.harpoon.tty_stderr if callable(stdin): stdin = stdin() if callable(stdout): stdout = stdout() if c...
def wait_till_stopped(self, conf, container_id, timeout=10, message=None, waiting=True): """Wait till a container is stopped""" stopped = False inspection = None for _ in until(timeout=timeout, action=message): try: inspection = conf.harpoon.docker_api.inspect_container(container_id) if not isinstance(inspection, dict)...
def is_stopped(self, *args, **kwargs): """Return whether this container is stopped""" kwargs["waiting"] = False return self.wait_till_stopped(*args, **kwargs)
def stop_container(self, conf, fail_on_bad_exit=False, fail_reason=None, tag=None, remove_volumes=False): """Stop some container""" stopped = False container_id = conf.container_id if not container_id: return container_name = conf.container_name stopped, exit_code = self.is_stopped(conf, container_id) if stopped: if ex...
container %s:%s", container_name, container_id) conf.harpoon.docker_api.kill(container_id, 9) except DockerAPIError: pass self.wait_till_stopped(conf, container_id, timeout=10, message="waiting for container to die\tcontainer_name={0}\tcontainer_id={1}".format(container_name, container_id)) if tag: log.info("Tagging a ...
volume\tvolume=%s\terror=%s", mount, error) conf.harpoon.network_manager.removed(container_name)
def get_exit_code(self, conf): """Determine how a container exited""" for _ in until(timeout=0.5, step=0.1, silent=True): try: inspection = conf.harpoon.docker_api.inspect_container(conf.container_id) if not isinstance(inspection, dict) or "State" not in inspection: raise BadResult("Expected inspect result to be a dict...
def find_bound_ports(self, ports): """Find any ports that are already bound and complain about them""" bound = [] for port in ports: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((port.ip if port.ip is not NotSpecified else "127.0.0.1", port.host_port)) except socket.error as error: bound.append(por...
def stage_run_intervention(self, conf, just_do_it=False): """Start an intervention!""" if not conf.harpoon.interactive or conf.harpoon.no_intervention: return if just_do_it: answer = 'y' else: hp.write_to(conf.harpoon.stdout, "!!!!\n") hp.write_to(conf.harpoon.stdout, "Failed to run the container!\n") hp.write_to(conf....
def intervention(self, commit, conf): """Ask the user if they want to commit this container and run sh in it""" if not conf.harpoon.interactive or conf.harpoon.no_intervention: yield return hp.write_to(conf.harpoon.stdout, "!!!!\n") hp.write_to(conf.harpoon.stdout, "It would appear building the image failed\n") hp.writ...
def commit_and_run(self, commit, conf, command="sh"): """Commit this container id and run the provided command in it and clean up afterwards""" image_hash = None try: image_hash = conf.harpoon.docker_api.commit(commit)["Id"] new_conf = conf.clone() new_conf.bash = NotSpecified new_conf.command = command new_conf.image_...
def initialize(self, runtime): """Initialize this listener. Finds most recent timestamp""" if self.is_alive(): raise IllegalState('notification thread is already initialized') if not JSON_CLIENT.is_json_client_set() and runtime is not None: JSON_CLIENT.set_json_client(runtime) try: cursor = JSON_CLIENT.json_client['loc...
def _notify_receiver(self, receiver, params, doc): """Send notification to the receiver""" verb = VMAP[doc['op']] ns = doc['ns'] notification_id = Id(ns + 'Notification:' + str(ObjectId()) + '@' + params['authority']) object_id = Id(ns + ':' + str(doc['o']['_id']) + '@' + params['authority']) try: getattr(receiver, '_'...
def _run_namespace(self, doc): """Run through all receivers related to the doc's namespace""" for receiver in self.receivers[doc['ns']]: params = self.receivers[doc['ns']][receiver] if params[doc['op']]: if params[doc['op']] is True or str(doc['o']['_id']) in params[doc['op']]: notification_id = self._notify_receiver(r...
def _retry(self): """Deal with unacknowledged notifications.""" notifications_to_delete = [] for notification_id in self.notifications: if datetime.datetime.utcnow() > self.notifications[notification_id]['ts'] + self._wait_period: self._notify_receiver( self.notifications[notification_id]['receiver'], self.notification...
def run(self): """main control loop for thread""" while True: try: cursor = JSON_CLIENT.json_client['local']['oplog.rs'].find( {'ts': {'$gt': self.last_timestamp}}) except TypeError: # filesystem, so .json_client is a bool and not iterable pass else: # http://stackoverflow.com/questions/30401063/pymongo-tailing-oplog c...
def range_return(request, items): """ Determine what range of objects to return. Will check fot both `Range` and `X-Range` headers in the request and set both `Content-Range` and 'X-Content-Range' headers. :rtype: list """ if ('Range' in request.headers): range = parse_range_header(request.headers['Range']) elif 'X-Ran...
def set_http_caching(request, gateway='crab', region='permanent'): """ Set an HTTP Cache Control header on a request. :param pyramid.request.Request request: Request to set headers on. :param str gateway: What gateway are we caching for? Defaults to `crab`. :param str region: What caching region to use? Defaults to `pe...
def get_type_data(self, name): """Return dictionary representation of type.""" return { 'authority': 'birdland.mit.edu', 'namespace': 'Genus Types', 'identifier': name, 'domain': 'Generic Types', 'display_name': self.generic_types[name] + ' Generic Type', 'display_label': self.generic_types[name], 'description': ('The ...
def _initialize_part_map(self): """Sets up assessmentPartMap with as much information as is initially available.""" self._my_map['assessmentParts'] = [] self._my_map['questions'] = [] item_ids = self._assessment_part.get_item_ids() if item_ids.available(): # This is a simple section: self._load_simple_section_questions...
def _get_part_map(self, part_id): """ from self._my_map['assessmentParts'], return the one part map with ID that matches the one passed in""" return [p for p in self._my_map['assessmentParts'] if p['assessmentPartId'] == str(part_id)][0]
def _insert_part_map(self, part_map, index=-1): """ add a part map to self._my_map['assessmentParts']""" if index == -1: self._my_map['assessmentParts'].append(part_map) else: self._my_map['assessmentParts'].insert(index, part_map)
def _load_simple_section_questions(self, item_ids): """For loading the simple section case (common) just load the questions for the section, and insert the one part into assessment part map. """ self._insert_part_map( get_default_part_map(self._assessment_part_id, 0, self._assessment_part.are_items_sequential())) looku...
def _save(self): """Saves the current state of this AssessmentSection to database. Should be called every time the question map changes. """ collection = JSONClientValidated('assessment', collection='AssessmentSection', runtime=self._runtime) if '_id' in self._my_map: # This is the first time: collection.save(self._my_...
def _delete(self): """Deletes this AssessmentSection from database. Will be called by AssessmentTaken._delete() for clean-up purposes. """ collection = JSONClientValidated('assessment', collection='AssessmentSection', runtime=self._runtime) collection.delete_one({'_id': ObjectId(self.get_id().get_identifier())})
def is_simple_section(self): """Tests if this section is simple (ie, items assigned directly to Section Part).""" item_ids = self._get_assessment_part(self._assessment_part_id).get_item_ids() if item_ids.available(): return True return False
def _get_assessment_part(self, part_id=None): """Gets an AssessmentPart given a part_id. Returns this Section's own part if part_id is None. Make this a private part, so that it doesn't collide with the AssessmentPart.get_assessment_part method, which does not expect any arguments... """ if part_id is None: return self...
def _update_from_database(self): """Updates map to latest state in database. Should be called prior to major object events to assure that an assessment being taken on multiple devices are reasonably synchronized. """ collection = JSONClientValidated('assessment', collection='AssessmentSection', runtime=self._runtime) s...
def _update_questions(self): """Updates questions known to this Section""" if self.is_simple_section(): return # we don't need to go through any this for simple sections # ideally, we would update the parts map and questions list # at the same time as _get_parts(), to not run into the # issue where magic parts are init...
def _update_assessment_parts_map(self, part_list): """Updates the part map. Called before question list gets updated if it is determined that the sections assessmentPart map is out of date with the current part list. """ for part in part_list: # perhaps look for a "level offset"? level = part._level_in_section # plus o...
def _get_question_map(self, question_id): """get question map from questions matching question_id This can make sense of both Section assigned Ids or normal Question/Item Ids """ if question_id.get_authority() == ASSESSMENT_AUTHORITY: key = '_id' match_value = ObjectId(question_id.get_identifier()) else: key = 'questio...
def get_question_ids_for_assessment_part(self, assessment_part_id): """convenience method returns unique question ids associated with an assessment_part_id""" question_ids = [] for question_map in self._my_map['questions']: if question_map['assessmentPartId'] == str(assessment_part_id): question_ids.append(self.get_que...
def get_item_ids_for_assessment_part(self, assessment_part_id): """convenience method returns item ids associated with an assessment_part_id""" item_ids = [] for question_map in self._my_map['questions']: if question_map['assessmentPartId'] == str(assessment_part_id): item_ids.append(Id(question_map['itemId'])) return ...
def _get_item(self, question_id): """we need a middle-man method to convert the unique "assessment-session" authority question_ids into "real" itemIds BUT this also has to return the "magic" item, so we can't rely on question = self.get_question(question_id) ils = self._get_item_lookup_session() return ils.get_item(Id(...
def get_questions(self, answered=None, honor_sequential=True, update=True): """gets all available questions for this section if answered == False: only return next unanswered question if answered == True: only return next answered question if answered in None: return next question whether answered or not if honor_seque...
prev_question_answered: prev_question_answered = update_question_list() else: update_question_list() if self._my_map['actualStartTime'] is None: self._my_map['actualStartTime'] = DateTime.utcnow() return QuestionList(question_list, runtime=self._runtime, proxy=self._proxy)
def get_next_question(self, question_id, answered=None, reverse=False, honor_sequential=True): """Inspects question map to return the next available question. if answered == False: only return next unanswered question if answered == True: only return next answered question if answered in None: return next question whet...
+ ' questions available') index = questions.index(question_map) + 1 for question_map in questions[index:]: latest_question_response = question_map['responses'][0] question_answered = False # take missingResponse == UNANSWERED or NULL_RESPONSE as an unanswered question if 'missingResponse' not in latest_question_respons...
def submit_response(self, question_id, answer_form=None): """Updates assessmentParts map to insert an item response. answer_form is None indicates that the current response is to be cleared """ if answer_form is None: response = {'missingResponse': NULL_RESPONSE, 'itemId': str(question_id)} else: response = dict(answer...
def get_response(self, question_id): """Gets the response for question_id""" question_map = self._get_question_map(question_id) # will raise NotFound() return self._get_response_from_question_map(question_map)
def get_responses(self): """Gets list of the latest responses""" response_list = [] for question_map in self._my_map['questions']: response_list.append(self._get_response_from_question_map(question_map)) return ResponseList(response_list)
def is_question_answered(self, question_id): """has the question matching item_id been answered and not skipped""" question_map = self._get_question_map(question_id) # will raise NotFound() if 'missingResponse' in question_map['responses'][0]: return False else: return True
def is_feedback_available(self, question_id): """is feedback available for item""" response = self.get_response(question_id) item = self._get_item(question_id) if response.is_answered(): return item.is_feedback_available_for_response(response) return item.is_feedback_available()