def set_choice_ids(self, choice_ids, inline_region): if not isinstance(choice_ids, list): raise IllegalState() if inline_region in self.my_osid_object_form._my_map['inlineRegions']: self.my_osid_object_form._my_map['inlineRegions'][inline_region]['choiceIds'] = choice_ids else: raise IllegalState('that inline region is invalid')
def clear_choice(self, choice): """stub""" if len(self.my_osid_object_form._my_map['choices']) == 0: raise IllegalState( 'there are currently no choices defined for this question') if (len(self.my_osid_object_form._my_map['choices']) == 1 and choice in self.my_osid_object_form._my_map['choices']): raise IllegalState() self.my_osid_object_form._my_map['choices'] = \ [c for c in self.my_osid_object_form._my_map['choices'] if c != choice]
def get_item_ids(self): """get item ids associated with this assessment part""" if self.has_item_ids(): return IdList(self.my_osid_object._my_map['itemIds'], runtime=self.my_osid_object._runtime, proxy=self.my_osid_object._proxy) raise IllegalState()
def get_solution_for_question(self, question_id, section=None): try: if section is None: section = self._get_section_for_question(question_id) if self.can_review_solution(question_id): item = section._get_item(question_id) item_map = item.object_map answers = [a.object_map for a in item.get_answers()] try: answers = answers + [a.object_map for a in item.get_wrong_answers()] except AttributeError: # no wrong answers pass try: if 'solution' in item_map: return { 'answers': answers, 'explanation': item_map['solution'] # fbw items } else: return { 'answers': answers, 'explanation': item_map['texts']['solution'] # edX items } except KeyError: pass except KeyError: pass raise IllegalState()
def get_children(self): """return the current child parts of this assessment part""" if self.has_magic_children(): if self._child_parts is None: self.generate_children() return self._child_parts raise IllegalState()
def get_provenance_id(self): """to handle deprecated mecqbank data""" if self.has_provenance(): if 'provenanceId' in self.my_osid_object._my_map: return self.my_osid_object._my_map['provenanceId'] else: return self.my_osid_object._my_map['provenanceItemId'] raise IllegalState()
def add_inline_region(self, inline_region): if inline_region not in self.my_osid_object_form._my_map['inlineRegions']: self.my_osid_object_form._my_map['inlineRegions'][inline_region] = \ { "choiceIds": deepcopy(self._choice_ids_metadata['default_object_values'][0]) } else: raise IllegalState('that inline region already exists')
def get_confused_learning_objective_ids_for_response(self, response): try: answer = self.get_answer_for_response(response) except NotFound: raise IllegalState('no answer matching response was found') try: return answer.get_confused_learning_objective_ids() except AttributeError: return IdList([])
def clear_choice_ids(self, inline_region): """stub""" if (self.get_choice_ids_metadata().is_read_only() or self.get_choice_ids_metadata().is_required()): raise NoAccess() if inline_region in self.my_osid_object_form._my_map['inlineRegions']: self.my_osid_object_form._my_map['inlineRegions'][inline_region]['choiceIds'] = \ deepcopy(self._choice_ids_metadata['default_object_values'][0]) else: raise IllegalState('that inline region is invalid')
def edit_choice(self, choice_id, text, inline_region, name=''): """edit an existing choice, to keep the ID the same""" if inline_region not in self.my_osid_object_form._my_map['choices']: raise IllegalState('that inline region does not exist') for choice in self.my_osid_object_form._my_map['choices'][inline_region]: if choice['id'] == choice_id: if choice['text'] != text: choice['text'] = text if choice['name'] != name and name != '': choice['name'] = name break
def initialize(self, runtime): """Initialize this listener. Finds most recent timestamp""" if self.is_alive(): raise IllegalState('notification thread is already initialized') if not MONGO_CLIENT.is_mongo_client_set() and runtime is not None: MONGO_CLIENT.set_mongo_client(runtime) cursor = MONGO_CLIENT.mongo_client['local']['oplog.rs'].find().sort( 'ts', DESCENDING).limit(-1) try: self.last_timestamp = cursor.next()['ts'] except StopIteration: self.last_timestamp = Timestamp(0, 0)
def get_provenance_children(self): if self.has_provenance_children(): collection = JSONClientValidated( 'repository', collection='Composition', runtime=self.my_osid_object._runtime) result = collection.find( {'provenanceId': self.my_osid_object.object_map['id']}) return AssetList(result, runtime=self.my_osid_object._runtime, proxy=self.my_osid_object._proxy) raise IllegalState('No provenance children.')
def get_child_ids(self): """gets the ids for the child parts""" if self.has_magic_children(): if self._child_parts is None: self.generate_children() child_ids = list() for part in self._child_parts: child_ids.append(part.get_id()) return IdList(child_ids, runtime=self.my_osid_object._runtime, proxy=self.my_osid_object._runtime) raise IllegalState()
def get_solution(self, parameters=None): """stub""" if not self.has_solution(): raise IllegalState() try: if not self.get_text('python_script'): return self.get_text('solution').text if not parameters: parameters = self.get_parameters() return self._get_parameterized_text(parameters) except Exception: return self.get_text('solution').text
def wrapper(*args, **kwargs): if ('assessment_section_id' in kwargs or args and 'Section' in args[1].get_identifier_namespace()): try: assessment_section_id = kwargs['assessment_section_id'] except KeyError: assessment_section_id = args[1] if (not args[0].has_assessment_section_begun(assessment_section_id) or args[0].is_assessment_section_over(assessment_section_id)): raise IllegalState() else: if 'assessment_taken_id' in kwargs: assessment_taken_id = kwargs['assessment_taken_id'] else: assessment_taken_id = args[1] assessment_taken = args[0]._get_assessment_taken( assessment_taken_id) if not assessment_taken.has_started( ) or assessment_taken.has_ended(): raise IllegalState() return func(*args, **kwargs)
def get_provenance_children(self): """stub""" if self.has_provenance_children(): collection = JSONClientValidated( 'assessment', collection='AssessmentTaken', runtime=self.my_osid_object._runtime) result = collection.find( {'provenanceId': self.my_osid_object.object_map['id']}) return AssessmentTakenList(result, runtime=self.my_osid_object._runtime, proxy=self.my_osid_object._proxy) raise IllegalState('No provenance children.')
def set_expression(self, expression): # list of possible problems from # http://code.activestate.com/recipes/496746-restricted-safe-eval/ if any(t in expression for t in ['import', 'os.', '__class__', 'raise', 'from', 'exec', 'eval', 'try', 'except', 'finally', 'dir', 'compile', 'delattr', 'getattr', 'file', 'locals', 'globals', 'open', 'setattr', 'vars', 'input', 'raw_input', 'execFile', 'reload', 'im_class', 'im_func', 'im_self', 'func_code', 'func_defaults', 'func_globals', 'func_name', 'tb_frame', 'tb_next', 'f_back', 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_locals']): raise IllegalState('bad expression') self.my_osid_object_form._my_map['expression'] = str(expression)
def wrapper(self, *args): valid_item = False try: if Id(self.my_osid_object_form._my_map['genusTypeId']).identifier in whitelist: valid_item = True except AttributeError: if Id(self.my_osid_object._my_map['genusTypeId']).identifier in whitelist: valid_item = True finally: if valid_item: return func(self, *args) else: raise IllegalState('Method not allowed for this object.')
def get_provenance_parent(self): if self.has_provenance(): collection = JSONClientValidated( 'repository', collection='Composition', runtime=self.my_osid_object._runtime) result = collection.find_one({ '_id': ObjectId(Id(self.get_provenance_id()).get_identifier()) }) return Asset(osid_object_map=result, runtime=self.my_osid_object._runtime, proxy=self.my_osid_object._proxy) raise IllegalState("Composition has no provenance parent.")
def get_provenance_parent(self): """stub""" if self.has_provenance(): collection = JSONClientValidated( 'assessment', collection='Item', runtime=self.my_osid_object._runtime) result = collection.find_one({ '_id': ObjectId(Id(self.get_provenance_id()).get_identifier()) }) return Item(osid_object_map=result, runtime=self.my_osid_object._runtime, proxy=self.my_osid_object._proxy) raise IllegalState("Item has no provenance parent.")
def __init__(self, osid_object): self.my_osid_object = osid_object self.my_osid_object._authority = MAGIC_AUTHORITY super(MultiLanguageCalculationInteractionQuestionRecord, self).__init__(osid_object) # evaluate the randomly assigned variables and put values into the _my_map? self._vars = {} self._orig_question_text = list(self.my_osid_object._my_map['texts']) # get a copy, not a pointer for variable, params in self.my_osid_object._my_map['variables'].items(): if params['type'] == 'integer': self._vars[variable] = randint(int(params['min_value']), int(params['max_value'])) elif params['type'] == 'float': self._vars[variable] = uniform(float(params['min_value']), float(params['max_value'])) else: raise IllegalState('that type not supported') self._set_variable_value(variable, self._vars[variable])
def set_item_ids(self, item_ids): '''the target Item This can only be set if there is no learning objective set ''' if self.get_item_ids_metadata().is_read_only(): raise NoAccess() for item_id in item_ids: if not self.my_osid_object_form._is_valid_id(item_id): raise InvalidArgument() if self.my_osid_object_form._my_map['learningObjectiveIds'][0]: raise IllegalState() self.my_osid_object_form._my_map['itemIds'] = [ str(i) for i in item_ids ]
def remove_choice_language(self, language_type, choice_id, inline_region): """stub""" if len(self.my_osid_object_form._my_map['choices'][inline_region]) == 0: raise IllegalState('there are currently no choices defined for this region') if self.get_choices_metadata().is_read_only(): raise NoAccess() choices = [c for c in self.my_osid_object_form._my_map['choices'][inline_region] if c['id'] == choice_id] if len(choices) == 0: raise InvalidArgument('invalid choice_id') for current_choice in self.my_osid_object_form._my_map['choices'][inline_region]: if choice_id == current_choice['id']: self.remove_field_by_language('texts', language_type, current_choice)
def add_choice(self, text, inline_region, name='', identifier=None): """stub""" choice_display_text = self._choice_text_metadata['default_string_values'][0] choice_display_text['text'] = text if identifier is None: identifier = str(ObjectId()) choice = { 'id': identifier, 'text': text, 'name': name } if inline_region in self.my_osid_object_form._my_map['choices']: self.my_osid_object_form._my_map['choices'][inline_region].append(choice) else: raise IllegalState('that inline region does not exist') return choice
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['local']['oplog.rs'].find().sort( 'ts', DESCENDING).limit(-1) except TypeError: # filesystem, so .json_client is a bool and not iterable pass else: try: self.last_timestamp = cursor.next()['ts'] except StopIteration: self.last_timestamp = Timestamp(0, 0)
def set_learning_objective_ids(self, learning_objective_ids): """the learning objective to find related items for This can only be set if there are no items specifically set """ if self.get_learning_objective_ids_metadata().is_read_only(): raise NoAccess() for learning_objective_id in learning_objective_ids: if not self.my_osid_object_form._is_valid_id( learning_objective_id): raise InvalidArgument() if self.my_osid_object_form._my_map['itemIds'][0]: raise IllegalState() self.my_osid_object_form._my_map['learningObjectiveIds'] = [ str(lo) for lo in learning_objective_ids ]
def set_choice_order(self, choice_ids, inline_region): """ reorder choices per the passed in list :param choice_ids: :return: """ reordered_choices = [] current_choice_ids = [c['id'] for c in self.my_osid_object_form._my_map['choices'][inline_region]] if set(choice_ids) != set(current_choice_ids): raise IllegalState('missing choices for choice order') for choice_id in choice_ids: for current_choice in self.my_osid_object_form._my_map['choices'][inline_region]: if choice_id == current_choice['id']: reordered_choices.append(current_choice) break self.my_osid_object_form._my_map['choices'][inline_region] = reordered_choices
def edit_choice(self, new_choice, choice_id, inline_region): """edit an existing choice, to keep the ID the same""" if inline_region not in self.my_osid_object_form._my_map['choices']: raise IllegalState('that inline region does not exist') if not isinstance(new_choice, DisplayText): raise InvalidArgument('new choice is not a DisplayText object') choices = [c for c in self.my_osid_object_form._my_map['choices'][inline_region] if c['id'] == choice_id] if len(choices) == 0: raise InvalidArgument('invalid choice_id for that region') for current_choice in self.my_osid_object_form._my_map['choices'][inline_region]: if choice_id == current_choice['id']: index = self.get_index_of_language_type('texts', new_choice.language_type, dictionary=current_choice) current_choice['texts'][index] = self._dict_display_text(new_choice)
def add_variable(self, variable_name, variable_type, var_min, var_max, var_step=1, format=''): if variable_name in self.my_osid_object_form._my_map['variables']: raise IllegalState('variable already exists') if variable_type == 'integer': self.my_osid_object_form._my_map['variables'][variable_name] = { 'type': variable_type, 'min_value': int(var_min), 'max_value': int(var_max), 'step': int(var_step) } elif variable_type == 'float': self.my_osid_object_form._my_map['variables'][variable_name] = { 'type': variable_type, 'format': format, 'min_value': float(var_min), 'max_value': float(var_max) }
def get_parameters(self): """stub""" if not self.is_parameterized(): raise IllegalState() if not self.get_text('python_script'): return dict() import imp from types import ModuleType, FunctionType script_module = imp.new_module('script_module') exec(self.get_text('python_script').text, script_module.__dict__) params = dict() for attr in dir(script_module): if (not isinstance(getattr(script_module, attr), ModuleType) and not isinstance(getattr(script_module, attr), FunctionType) and not attr.startswith('__')): params[attr] = getattr(script_module, attr) return params