コード例 #1
0
    def get_question(self, question_id=None, question_map=None):
        if question_id is not None:
            question_map = self._get_question_map(
                question_id)  # Throws NotFound()
        real_question_id = Id(question_map['questionId'])
        display_elements = question_map['displayElements']
        item = self._get_item_lookup_session().get_item(real_question_id)
        question = item.get_question()

        # Try to set a new display name and label
        try:
            if len(display_elements) > 0:
                new_display_name = [str(e) for e in display_elements]
                question.set_display_label('.'.join(new_display_name))
        except AttributeError:
            pass

        # Claim authority over this question:
        question._authority = ASSESSMENT_AUTHORITY

        # Override Item Id of this question (this is the Id that Questions report)
        question._item_id = Id(namespace='assessment.Item',
                               identifier=str(question_map['_id']),
                               authority=ASSESSMENT_AUTHORITY)
        return question
コード例 #2
0
ファイル: multi_choice_records.py プロジェクト: UOC/dlkit
    def __init__(self, osid_object, **kwargs):
        super(edXMultiChoiceQuestionRecord, self).__init__(osid_object)

        # change my_map
        if ('rerandomize' in self.my_osid_object._my_map
                and self.my_osid_object._my_map['rerandomize'] == 'always'):
            shuffle(self.my_osid_object._my_map['choices'])
        # handle deprecated data...this should go away once Luwen re-loads
        # her data with newer assessmentsv2/views.py code
        try:
            am = self.my_osid_object._get_provider_manager('ASSESSMENT',
                                                           local=True)
            try:
                ils = am.get_item_lookup_session_for_bank(
                    Id(self.my_osid_object._my_map['assignedBankIds'][0]),
                    proxy=self.my_osid_object._proxy)
            except TypeError:  # not a proxy manager
                ils = am.get_item_lookup_session_for_bank(
                    Id(self.my_osid_object._my_map['assignedBankIds'][0]))
            item = ils.get_item(Id(self.my_osid_object._my_map['itemId']))
            if 'rerandomize' in item._my_map and item._my_map[
                    'rerandomize'] == 'always':
                shuffle(self.my_osid_object._my_map['choices'])
        except (KeyError, NotFound, IllegalState, AttributeError) as ex:
            import logging
            logging.info(ex.args[0])
コード例 #3
0
ファイル: vcb_records.py プロジェクト: UOC/dlkit
 def _init_metadata(self):
     """stub"""
     self._start_timestamp_metadata = {
         'element_id': Id(self.my_osid_object_form._authority,
                          self.my_osid_object_form._namespace,
                          'start_timestamp'),
         'element_label': 'start timestamp',
         'instructions': 'enter an integer number of seconds for the start time',
         'required': False,
         'read_only': False,
         'linked': False,
         'array': False,
         'syntax': 'INTEGER',
         'minimum_integer': 0,
         'maximum_integer': None,
         'integer_set': [],
         'default_integer_values': [0]
     }
     self._end_timestamp_metadata = {
         'element_id': Id(self.my_osid_object_form._authority,
                          self.my_osid_object_form._namespace,
                          'end_timestamp'),
         'element_label': 'end timestamp',
         'instructions': 'enter an integer number of seconds for the end time',
         'required': False,
         'read_only': False,
         'linked': False,
         'array': False,
         'syntax': 'INTEGER',
         'minimum_integer': 0,
         'maximum_integer': None,
         'integer_set': [],
         'default_integer_values': [0]
     }
コード例 #4
0
ファイル: objects.py プロジェクト: DurgaSwetha/ClixOER
 def _init_metadata(self):
     from . import mdata_conf
     from ..primitives import Id
     from ..osid.objects import OsidForm
     OsidForm._init_metadata(self)
     self._display_name_metadata = {
         'element_id':
         Id(authority=self._authority,
            namespace=self._namespace,
            identifier='display_name')
     }
     self._display_name_metadata.update(mdata_conf.display_name)
     self._display_label_metadata = {
         'element_id':
         Id(authority=self._authority,
            namespace=self._namespace,
            identifier='description')
     }
     self._display_label_metadata.update(mdata_conf.display_label)
     self._description_metadata = {
         'element_id':
         Id(authority=self._authority,
            namespace=self._namespace,
            identifier='description')
     }
     self._description_metadata.update(mdata_conf.description)
     self._domain_metadata = {
         'element_id':
         Id(authority=self._authority,
            namespace=self._namespace,
            identifier='description')
     }
     self._domain_metadata.update(mdata_conf.domain)
コード例 #5
0
ファイル: utilities.py プロジェクト: UOC/dlkit_builders
    def __init__(self, db, collection=None, runtime=None):
        if not MONGO_CLIENT.is_mongo_client_set() and runtime is not None:
            set_mongo_client(runtime)
        db_prefix = ''
        try:
            db_prefix_param_id = Id('parameter:mongoDBNamePrefix@mongo')
            db_prefix = runtime.get_configuration().get_value_by_parameter(
                db_prefix_param_id).get_string_value()
        except (AttributeError, KeyError, NotFound):
            pass

        if collection is None:
            self._mc = MONGO_CLIENT.mongo_client[db_prefix + db]
        else:
            self._mc = MONGO_CLIENT.mongo_client[db_prefix + db][collection]
            # add the collection index, if available in the configs
            try:
                mongo_indexes_param_id = Id('parameter:indexes@mongo')
                mongo_indexes = runtime.get_configuration(
                ).get_value_by_parameter(
                    mongo_indexes_param_id).get_object_value()
                namespace = '{0}.{1}'.format(db, collection)
                if namespace in mongo_indexes:
                    for field in mongo_indexes[namespace]:
                        self._mc.create_index(field)
            except (AttributeError, KeyError, NotFound):
                pass
コード例 #6
0
ファイル: compositions.py プロジェクト: UOC/dlkit
 def assets(self):
     resources = []
     try:
         rm = self.my_osid_object._get_provider_manager('REPOSITORY')
         if self.my_osid_object._proxy is None:
             acs = rm.get_asset_composition_session_for_repository(
                 Id(self.my_osid_object._my_map['assignedRepositoryIds'][0]))
         else:
             acs = rm.get_asset_composition_session_for_repository(
                 Id(self.my_osid_object._my_map['assignedRepositoryIds'][0]),
                 proxy=self.my_osid_object._proxy)
         for asset in acs.get_composition_assets(self.my_osid_object.ident):
             asset_map = asset.object_map
             if 'enclosedObjectId' in asset_map:
                 enclosed_object = asset.get_enclosed_object()
                 if isinstance(enclosed_object, Assessment):
                     am = self.my_osid_object._get_provider_manager('ASSESSMENT')
                     if self.my_osid_object._proxy is None:
                         abas = am.get_assessment_basic_authoring_session_for_bank(
                             Id(enclosed_object.object_map['assignedBankIds'][0]))
                     else:
                         abas = am.get_assessment_basic_authoring_session_for_bank(
                             Id(enclosed_object.object_map['assignedBankIds'][0]),
                             proxy=self.my_osid_object._proxy)
                     for item in abas.get_items(enclosed_object.ident):
                         resources.append(item)
                 elif isinstance(enclosed_object, Item):
                     resources.append(enclosed_object)
             else:
                 resources.append(asset)
     except NotFound:
         # no assets
         pass
     return resources
コード例 #7
0
 def _init_metadata(self):
     """stub"""
     super(TextsAnswerFormRecord, self)._init_metadata()
     self._min_string_length_metadata = {
         'element_id': Id(self.my_osid_object_form._authority,
                          self.my_osid_object_form._namespace,
                          'min-string-length'),
         'element_label': 'min string length',
         'instructions': 'enter minimum string length',
         'required': False,
         'read_only': False,
         'linked': False,
         'array': False,
         'default_cardinal_values': [self._min_string_length],
         'syntax': 'CARDINAL',
         'minimum_cardinal': None,
         'maximum_cardinal': None,
         'cardinal_set': []
     }
     self._max_string_length_metadata = {
         'element_id': Id(self.my_osid_object_form._authority,
                          self.my_osid_object_form._namespace,
                          'max-string-length'),
         'element_label': 'max string length',
         'instructions': 'enter maximum string length',
         'required': False,
         'read_only': False,
         'linked': False,
         'array': False,
         'default_cardinal_values': [self._max_string_length],
         'syntax': 'CARDINAL',
         'minimum_cardinal': None,
         'maximum_cardinal': None,
         'cardinal_set': []
     }
コード例 #8
0
 def _init_metadata(self):
     """stub"""
     self._min_string_length = None
     self._max_string_length = None
     self._confused_learning_objectives_metadata = {
         'element_id':
         Id(self.my_osid_object_form._authority,
            self.my_osid_object_form._namespace,
            'confusedLearningObjectiveIds'),
         'element_label':
         'Confused Learning Objectives',
         'instructions':
         'List of IDs',
         'required':
         False,
         'read_only':
         False,
         'linked':
         False,
         'array':
         False,
         'default_list_values': [[]],
         'syntax':
         'LIST'
     }
     self._feedback_metadata = {
         'element_id':
         Id(self.my_osid_object_form._authority,
            self.my_osid_object_form._namespace, 'feedback'),
         'element_label':
         'Feedback',
         'instructions':
         'enter a feedback string',
         'required':
         False,
         'read_only':
         False,
         'linked':
         False,
         'array':
         False,
         'default_string_values': [{
             'text':
             '',
             'languageTypeId':
             str(DEFAULT_LANGUAGE_TYPE),
             'scriptTypeId':
             str(DEFAULT_SCRIPT_TYPE),
             'formatTypeId':
             str(DEFAULT_FORMAT_TYPE),
         }],
         'syntax':
         'STRING',
         'minimum_string_length':
         self._min_string_length,
         'maximum_string_length':
         self._max_string_length,
         'string_set': []
     }
コード例 #9
0
ファイル: utilities.py プロジェクト: UOC/dlkit
    def __init__(self, db, collection=None, runtime=None):
        if not JSON_CLIENT.is_json_client_set() and runtime is not None:
            set_json_client(runtime)

        self._json_impl = 'mongo'
        try:
            use_filesystem_param_id = Id('parameter:useFilesystem@json')
            use_filesystem = runtime.get_configuration().get_value_by_parameter(use_filesystem_param_id).get_boolean_value()
            if not use_filesystem:
                raise AttributeError()
        except (AttributeError, KeyError, NotFound):
            pass
        else:
            self._json_impl = 'filesystem'

        if self._impl('filesystem'):
            host_path = PROJECT_PATH
            try:
                host_path_param_id = Id('parameter:dataStorePath@json')
                if BOOTLOADER:
                    host_path = '{0}/{1}'.format(host_path,
                                                 runtime.get_configuration().get_value_by_parameter(host_path_param_id).get_string_value())
                else:
                    host_path = runtime.get_configuration().get_value_by_parameter(host_path_param_id).get_string_value()
            except (AttributeError, KeyError, NotFound):
                pass
            if collection is None:
                self._cursor = '{}/{}'.format(host_path, db)
            else:
                self._cursor = '{}/{}/{}'.format(host_path, db, collection)

            if not os.path.isdir(self._cursor):
                os.makedirs(self._cursor)
        else:
            # use MongoDB as default
            db_prefix = ''
            try:
                db_prefix_param_id = Id('parameter:mongoDBNamePrefix@json')
                db_prefix = runtime.get_configuration().get_value_by_parameter(db_prefix_param_id).get_string_value()
            except (AttributeError, KeyError, NotFound):
                pass

            if collection is None:
                self._mc = JSON_CLIENT.json_client[db_prefix + db]
            else:
                self._mc = JSON_CLIENT.json_client[db_prefix + db][collection]
                # add the collection index, if available in the configs
                try:
                    mongo_indexes_param_id = Id('parameter:indexes@json')
                    mongo_indexes = runtime.get_configuration().get_value_by_parameter(mongo_indexes_param_id).get_object_value()
                    namespace = '{0}.{1}'.format(db, collection)
                    if namespace in mongo_indexes:
                        for field in mongo_indexes[namespace]:
                            self._mc.create_index(field)
                except (AttributeError, KeyError, NotFound):
                    pass
コード例 #10
0
 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'])
     getattr(receiver,
             '_'.join([verb, params['obj_name_plural']]))(notification_id,
                                                          [object_id])
     return notification_id
コード例 #11
0
ファイル: compositions.py プロジェクト: UOC/dlkit
    def get_group_id_to_child(self):
        """ At a minimum need a course composition parent and two children to the split test

            course composition
                    |
            split_test composition
                |           |
            vertical     vertical

        And the expected output is a URL-safe (" instead of ") JSON string, of this object
            {
                0: "i4x://<org>/<course-name-slug>/<child-tag>/<child-name-slug>,
                1: "i4x://<org>/<course-name-slug>/<tag>/<child-name-slug>
            }
        """
        # get the children compositions, then construct
        # the escaped-JSON structure for this split_test
        group_ids = {}
        # also need the course name...so go up the composition tree
        course_node = None
        found_course = False
        rm = self.my_osid_object._get_provider_manager('REPOSITORY')
        if self.my_osid_object._proxy is not None:
            cqs = rm.get_composition_query_session_for_repository(Id(self.my_osid_object._my_map['assignedRepositoryIds'][0]),
                                                                  proxy=self.my_osid_object._proxy)
        else:
            cqs = rm.get_composition_query_session_for_repository(
                Id(self.my_osid_object._my_map['assignedRepositoryIds'][0]))
        search_node = self.my_osid_object
        while not found_course:
            querier = cqs.get_composition_query()
            cqs.use_unsequestered_composition_view()
            querier.match_contained_composition_id(search_node.ident, True)
            parents = cqs.get_compositions_by_query(querier)
            if parents.available() == 0:
                found_course = True
            else:
                parent = next(parents)
                if parent.genus_type.identifier == 'course':
                    found_course = True
                    course_node = parent
                else:
                    search_node = parent

        if course_node is None:
            return ''
        else:
            for index, child in enumerate(self.my_osid_object.get_children()):
                group_ids[index] = 'i4x://{0}/{1}/{2}/{3}'.format(course_node.org.text,
                                                                  re.sub('[^\w\s-]', '', course_node.display_name.text),
                                                                  child.genus_type.identifier,
                                                                  child.url)
            return json.dumps(group_ids).replace('"', '&quot;')
コード例 #12
0
ファイル: compositions.py プロジェクト: UOC/dlkit
 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.')
コード例 #13
0
ファイル: compositions.py プロジェクト: UOC/dlkit
    def _init_metadata(self):
        """stub"""
        super(EdXCompositionFormRecord, self)._init_metadata()
        TextsFormRecord._init_metadata(self)  # because the OsidForm breaks the MRO chain for super, in TemporalFormRecord
        ProvenanceFormRecord._init_metadata(self)  # because the OsidForm breaks the MRO chain for super, in TemporalFormRecord
        self._visible_to_students_metadata = {
            'element_id': Id(self.my_osid_object_form._authority,
                             self.my_osid_object_form._namespace,
                             'visible_to_students'),
            'element_label': 'Visible to students',
            'instructions': 'enter a boolean value',
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_boolean_values': [True],
            'syntax': 'BOOLEAN'
        }
        self._draft_metadata = {
            'element_id': Id(self.my_osid_object_form._authority,
                             self.my_osid_object_form._namespace,
                             'draft'),
            'element_label': 'Draft',
            'instructions': 'enter a boolean value',
            'required': False,
            'read_only': False,
            'linked': False,
            'array': False,
            'default_boolean_values': [False],
            'syntax': 'BOOLEAN'
        }

        # ideally this would be type LIST?
        self._learning_objective_ids_metadata = {
            'element_id': Id(self.my_osid_object_form._authority,
                             self.my_osid_object_form._namespace,
                             'learning_objectives'),
            'element_label': 'learning_objectives',
            'instructions': 'enter a list of strings',
            'required': False,
            'read_only': False,
            'linked': False,
            'array': True,
            'default_string_values': [[]],
            'syntax': 'STRING',
            'minimum_string_length': self._min_string_length,
            'maximum_string_length': self._max_string_length,
            'string_set': []
        }
コード例 #14
0
ファイル: edx_assets.py プロジェクト: UOC/dlkit
    def _init_metadata(self):
        ProvenanceFormRecord._init_metadata(self)
        TextsFormRecord._init_metadata(self)
        super(edXAssetFormRecord, self)._init_metadata()

        # ideally this would be type LIST?
        self._learning_objective_ids_metadata = {
            'element_id':
            Id(self.my_osid_object_form._authority,
               self.my_osid_object_form._namespace, 'learning_objectives'),
            'element_label':
            'learning_objectives',
            'instructions':
            'enter a list of strings',
            'required':
            False,
            'read_only':
            False,
            'linked':
            False,
            'array':
            False,
            'default_string_values': [[]],
            'syntax':
            'STRING',
            'minimum_string_length':
            self._min_string_length,
            'maximum_string_length':
            self._max_string_length,
            'string_set': []
        }
コード例 #15
0
ファイル: assessment_utilities.py プロジェクト: UOC/dlkit
def create_first_assessment_section(assessment_id, runtime, proxy, bank_id):
    assessment_admin_session, part_admin_session, rule_admin_session = get_admin_sessions(
        runtime, proxy, bank_id)
    mgr = get_provider_manager('ASSESSMENT',
                               runtime=runtime,
                               proxy=proxy,
                               local=True)
    assessment_lookup_session = mgr.get_assessment_lookup_session(proxy=proxy)
    assessment_lookup_session.use_federated_bank_view()
    assessment = assessment_lookup_session.get_assessment(assessment_id)
    part_form = part_admin_session.get_assessment_part_form_for_create_for_assessment(
        assessment_id, [SIMPLE_SEQUENCE_RECORD_TYPE])
    part_form.set_display_name(assessment.get_display_name().get_text() +
                               ' First Part')
    part_form.set_sequestered(
        False
    )  # Any Part of an Assessment must be a Section (i.e. non sequestered)
    # part_form.set_weight(100) # Uncomment this line when set_weight is implemented
    # Should we set allocated time?
    part_id = part_admin_session.create_assessment_part_for_assessment(
        part_form).get_id()
    if assessment._supports_simple_sequencing():
        child_ids = list(assessment.get_child_ids())
        child_ids.insert(0, str(part_id))
        update_form = assessment_admin_session.get_assessment_form_for_update(
            assessment.get_id())
        update_form.set_children([Id(i) for i in child_ids])
        assessment_admin_session.update_assessment(update_form)
    else:
        rule_form = rule_admin_session.get_sequence_rule_form_for_create(
            assessment.get_id(), part_id, [])
        rule_form.set_display_name('First Part Rule')
        rule_admin_session.create_sequence_rule(rule_form)
    return part_id
コード例 #16
0
ファイル: multi_choice_records.py プロジェクト: UOC/dlkit
    def get_choices_file_urls_map(self):
        """stub"""
        file_urls_map = []
        for choice in self.get_choices():
            choice = dict(choice)
            small_asset_content = self._get_asset_content(
                Id(choice['assetId']), OV_SET_SMALL_ASSET_CONTENT_TYPE)
            choice['smallOrthoViewSet'] = small_asset_content.get_url()

            small_asset_content = self._get_asset_content(
                Id(choice['assetId']), OV_SET_LARGE_ASSET_CONTENT_TYPE)
            choice['largeOrthoViewSet'] = small_asset_content.get_url()

            del choice['assetId']
            file_urls_map.append(choice)
        return file_urls_map
コード例 #17
0
ファイル: multi_choice_records.py プロジェクト: UOC/dlkit
 def get_choices_files_map(self):
     """stub"""
     files_map = []
     for choice in self.get_choices():
         choice = dict(choice)
         choice['smallOrthoViewSet'] = base64.b64encode(
             self._get_asset_content(Id(choice['assetId']),
                                     OV_SET_SMALL_ASSET_CONTENT_TYPE
                                     ).get_data().read())
         choice['largeOrthoViewSet'] = base64.b64encode(
             self._get_asset_content(Id(choice['assetId']),
                                     OV_SET_LARGE_ASSET_CONTENT_TYPE
                                     ).get_data().read())
         del choice['assetId']
         files_map.append(choice)
     return files_map
コード例 #18
0
def add_user_authz_to_settings(role,
                               username,
                               catalog_id=None,
                               authority='MIT-ODL'):
    from .testing import is_string
    if is_string(catalog_id):
        catalog_id = Id(catalog_id)
    agent = create_agent_id(username, authority=authority)

    if catalog_id is None:
        qualifiers = ('ROOT', 24 * '0')
        catalog_id = create_qualifier_id(24 * '0', 'authorization.Vault')
    else:
        qualifiers = (catalog_id, )

    # first, add the base authorizations to the user for the catalog_id and ROOT / '0' * 24
    req = get_super_authz_user_request()
    vault = get_vault(req)

    create_base_authorizations(vault, agent, qualifiers=qualifiers)

    # then, depending on role, add additional functions
    if role == 'instructor':
        authorization_iterator(vault, agent, qualifiers, INSTRUCTOR_FUNCTIONS)
    elif role == 'student':
        authorization_iterator(vault, agent, qualifiers, STUDENT_FUNCTIONS)
コード例 #19
0
def comment_class_fixture(request):
    request.cls.service_config = request.param
    request.cls.svc_mgr = Runtime().get_service_manager(
        'COMMENTING',
        proxy=PROXY,
        implementation=request.cls.service_config)
    if not is_never_authz(request.cls.service_config):
        create_form = request.cls.svc_mgr.get_book_form_for_create([])
        create_form.display_name = 'Test catalog'
        create_form.description = 'Test catalog description'
        request.cls.catalog = request.cls.svc_mgr.create_book(create_form)

        form = request.cls.catalog.get_comment_form_for_create(
            Id('resource.Resource%3A1%40ODL.MIT.EDU'),
            [])
        form.display_name = 'Test object'
        request.cls.object = request.cls.catalog.create_comment(form)

    def class_tear_down():
        if not is_never_authz(request.cls.service_config):
            for obj in request.cls.catalog.get_comments():
                request.cls.catalog.delete_comment(obj.ident)
            request.cls.svc_mgr.delete_book(request.cls.catalog.ident)

    request.addfinalizer(class_tear_down)
コード例 #20
0
 def _init_metadata(self):
     """stub"""
     super(MultiLanguageMultipleChoiceQuestionFormRecord,
           self)._init_metadata()
     self._choices_metadata = {
         'element_id':
         Id(self.my_osid_object_form._authority,
            self.my_osid_object_form._namespace, 'choices'),
         'element_label':
         'choices',
         'instructions':
         'Enter as many text choices as you wish',
         'required':
         True,
         'read_only':
         False,
         'linked':
         False,
         'array':
         True,
         'default_object_values': [[]],
         'syntax':
         'OBJECT',
         'object_set': []
     }
コード例 #21
0
ファイル: test_primitives.py プロジェクト: UOC/dlkit
 def test_can_create_id_with_kwargs(self):
     result = Id(authority='AUTHORITY',
                 namespace='package.Object',
                 identifier='identifier')
     assert result._authority == 'AUTHORITY'
     assert result._identifier == 'identifier'
     assert result._namespace == 'package.Object'
コード例 #22
0
ファイル: assessment_part_records.py プロジェクト: UOC/dlkit
    def get_id(self):
        """override get_id to generate our "magic" id that encodes scaffolding information"""
        waypoint_index = 0
        if 'waypointIndex' in self.my_osid_object._my_map:
            waypoint_index = self.my_osid_object._my_map['waypointIndex']
        # NOTE that the order of the dict **must** match the order in generate_children()
        #   when creating the child_part_id
        #   1) level
        #   2) objective_ids
        #   3) parent_id
        #   4) waypoint_index
        magic_identifier = OrderedDict({
            'level':
            self._level,
            'objective_ids':
            self.my_osid_object._my_map['learningObjectiveIds'],
        })
        if self._magic_parent_id is not None:
            magic_identifier['parent_id'] = str(self._magic_parent_id)
        magic_identifier['waypoint_index'] = waypoint_index

        identifier = quote('{0}?{1}'.format(
            str(self.my_osid_object._my_map['_id']),
            json.dumps(magic_identifier)))
        return Id(namespace='assessment_authoring.AssessmentPart',
                  identifier=identifier,
                  authority=MAGIC_PART_AUTHORITY)
コード例 #23
0
ファイル: assessment_part_records.py プロジェクト: UOC/dlkit
 def get_assessment_part(self, assessment_part_id):
     authority = assessment_part_id.get_authority()
     if assessment_part_id not in self._magic_parts:
         if authority == MAGIC_PART_AUTHORITY:
             magic_identifier = unquote(assessment_part_id.identifier)
             orig_identifier = magic_identifier.split('?')[0]
             assessment_part = super(
                 MagicAssessmentPartLookupSession,
                 self).get_assessment_part(assessment_part_id=Id(
                     authority=self._catalog.ident.authority,
                     namespace=assessment_part_id.get_identifier_namespace(
                     ),
                     identifier=orig_identifier))
             # should a magic assessment part's parent be the original part?
             # Or that original part's parent?
             assessment_part.initialize(assessment_part_id.identifier,
                                        self._my_assessment_section)
         else:
             assessment_part = super(
                 MagicAssessmentPartLookupSession,
                 self).get_assessment_part(assessment_part_id)
         self._magic_parts[assessment_part_id] = assessment_part
         return assessment_part
     else:
         return self._magic_parts[assessment_part_id]
コード例 #24
0
ファイル: numeric_response_records.py プロジェクト: UOC/dlkit
 def _init_metadata(self):
     """stub"""
     DecimalValuesFormRecord._init_metadata(self)
     IntegerValuesFormRecord._init_metadata(self)
     TextAnswerFormRecord._init_metadata(self)
     super(MultiLanguageCalculationInteractionFeedbackAndFilesAnswerFormRecord, self)._init_metadata()
     self._tolerance_mode_metadata = {
         'element_id': Id(self.my_osid_object_form._authority,
                          self.my_osid_object_form._namespace,
                          'tolerance_mode'),
         'element_label': 'tolerance_mode',
         'instructions': 'enter the tolerance mode',
         'required': True,
         'read_only': False,
         'linked': False,
         'array': False,
         'default_string_values': [{
             'text': '',
             'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
             'scriptTypeId': str(DEFAULT_SCRIPT_TYPE),
             'formatTypeId': str(DEFAULT_FORMAT_TYPE),
         }],
         'syntax': 'STRING',
         'minimum_string_length': 0,
         'maximum_string_length': 1024,
         'string_set': []
     }
コード例 #25
0
ファイル: numeric_response_records.py プロジェクト: UOC/dlkit
 def get_item(self, item_id):
     """ see if this is a magic item id (i.e. questionId).
     If so, grab the item and set the params.
     If not, just pass through to the original Mongo ItemLookupSession
     :param item_id:
     :return:
     """
     authority = item_id.authority
     mgr = self._get_provider_manager('ASSESSMENT', local=True)
     if self._proxy is not None:
         ils = mgr.get_item_lookup_session(proxy=self._proxy)
     else:
         ils = mgr.get_item_lookup_session()
     ils.use_federated_bank_view()
     if authority == MAGIC_AUTHORITY:
         magic_identifier = unquote(item_id.identifier)
         params = json.loads(magic_identifier.split('?')[-1])
         orig_identifier = magic_identifier.split('?')[0]
         original_item_id = Id(
             namespace=item_id.namespace,
             authority=self._catalog.ident.authority,
             identifier=orig_identifier
         )
         orig_item = ils.get_item(original_item_id)
         orig_item.set_params(params)
         return orig_item
     else:
         return ils.get_item(item_id)
コード例 #26
0
ファイル: test_objects.py プロジェクト: UOC/dlkit
def authorization_class_fixture(request):
    request.cls.service_config = request.param
    request.cls.authorization_list = list()
    request.cls.authorization_ids = list()
    request.cls.svc_mgr = Runtime().get_service_manager(
        'AUTHORIZATION',
        proxy=PROXY,
        implementation=request.cls.service_config)
    if not is_never_authz(request.cls.service_config):
        create_form = request.cls.svc_mgr.get_vault_form_for_create([])
        create_form.display_name = 'Test Vault'
        create_form.description = 'Test Vault for AuthorizationQuerySession tests'
        request.cls.catalog = request.cls.svc_mgr.create_vault(create_form)
        create_form = request.cls.catalog.get_authorization_form_for_create_for_agent(
            AGENT_ID, LOOKUP_RESOURCE_FUNCTION_ID,
            Id(
                **{
                    'identifier': str('foo'),
                    'namespace': 'resource.Resource',
                    'authority': 'ODL.MIT.EDU'
                }), [])
        create_form.display_name = 'Test Authorization'
        create_form.description = (
            'Test Authorization for Authorization tests')
        obj = request.cls.catalog.create_authorization(create_form)
        request.cls.object = obj

    def class_tear_down():
        if not is_never_authz(request.cls.service_config):
            for catalog in request.cls.svc_mgr.get_vaults():
                for obj in catalog.get_authorizations():
                    catalog.delete_authorization(obj.ident)
                request.cls.svc_mgr.delete_vault(catalog.ident)

    request.addfinalizer(class_tear_down)
コード例 #27
0
ファイル: markers.py プロジェクト: DurgaSwetha/ClixOER
 def _set_authority(self, runtime):
     try:
         authority_param_id = Id('parameter:authority@mongo')
         self._authority = runtime.get_configuration(
         ).get_value_by_parameter(authority_param_id).get_string_value()
     except (AttributeError, KeyError, errors.NotFound):
         self._authority = 'GSTUDIO'
コード例 #28
0
ファイル: markers.py プロジェクト: DurgaSwetha/ClixOER
    def get_id(self):
        """Gets the Id associated with this instance of this OSID object.

        Persisting any reference to this object is done by persisting
        the Id returned from this method. The Id returned may be
        different than the Id used to query this object. In this case,
        the new Id should be preferred over the old one for future
        queries.

        return: (osid.id.Id) - the ``Id``
        *compliance: mandatory -- This method must be implemented.*
        *implementation notes*: The ``Id`` is intended to be constant
        and persistent. A consumer may at any time persist the ``Id``
        for retrieval at any future time. Ideally, the Id should
        consistently resolve into the designated object and not be
        reused. In cases where objects are deactivated after a certain
        lifetime the provider should endeavor not to obliterate the
        object or its ``Id`` but instead should update the properties of
        the object including the deactiavted status and the elimination
        of any unwanted pieces of data. As such, there is no means for
        updating an ``Id`` and providers should consider carefully the
        identification scheme to implement.  ``Id`` assignments for
        objects are strictly in the realm of the provider and any errors
        should be fixed directly with the backend supporting system.
        Once an Id has been assigned in a production service it should
        be honored such that it may be necessary for the backend system
        to support Id aliasing to redirect the lookup to the current
        ``Id``. Use of an Id OSID may be helpful to accomplish this task
        in a modular manner.

        """
        identifier = 'None'  # re-implement to get real identifier for object
        return Id(identifier=str(self._gstudio_node['_id']),
                  namespace=self._namespace,
                  authority=self._authority)
コード例 #29
0
ファイル: multi_choice_records.py プロジェクト: UOC/dlkit
 def _init_metadata(self):
     """stub"""
     self._rerandomize_metadata = {
         'element_id':
         Id(self.my_osid_object_form._authority,
            self.my_osid_object_form._namespace, 'rerandomize'),
         'element_label':
         'Randomize',
         'instructions':
         'How to rerandomize the parameters',
         'required':
         False,
         'read_only':
         False,
         'linked':
         False,
         'array':
         False,
         'default_object_values': ['never'],
         'syntax':
         'STRING',
         'minimum_string_length':
         None,
         'maximum_string_length':
         None,
         'string_set': []
     }
     super(edXMultiChoiceQuestionFormRecord, self)._init_metadata()
コード例 #30
0
 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 item_ids