code
stringlengths
1
18.2k
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 i...
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...
def remove_choice(self, choice_id, inline_region): """remove a choice, given the id""" if inline_region in self.my_osid_object_form._my_map['choices']: updated_choices = [] for choice in self.my_osid_object_form._my_map['choices'][inline_region]: if choice['id'] != choice_id: updated_choices.append(choice) self.my_osid...
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('m...
def set_values(self, choice_ids): """assume choice_ids is a dict of { region: choiceIds }, like: { "REGION_1": ["57978959cdfc5c42eefb36d1", "57978959cdfc5c42eefb36d0", "57978959cdfc5c42eefb36cf", "57978959cdfc5c42eefb36ce"] } """ # if not self.my_osid_object._my_map['choices']: # raise IllegalState() organized_regions ...
def _init_map(self): """stub""" FilesAnswerFormRecord._init_map(self) FeedbackAnswerFormRecord._init_map(self) self.my_osid_object_form._my_map['inlineRegions'] = \ self._inline_regions_metadata['default_object_values'][0]
def add_choice_id(self, choice_id, inline_region): """stub""" if inline_region in self.my_osid_object_form._my_map['inlineRegions']: self.my_osid_object_form._my_map['inlineRegions'][inline_region]['choiceIds'].append(choice_id) else: raise IllegalState('that inline region is invalid')
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'] ...
def get_inline_choice_ids(self): """stub""" return_data = {} for inline_region, data in self.my_osid_object._my_map['inlineRegions'].items(): return_data[inline_region] = { 'choiceIds': IdList(data['choiceIds']) } return return_data
def _init_map(self): """stub""" super(MultiLanguageInlineChoiceQuestionFormRecord, self)._init_map() self.my_osid_object_form._my_map['choices'] = \ self._choices_metadata['default_object_values'][0]
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 i...
def add_choice(self, choice, inline_region, identifier=None, name=''): """stub""" if inline_region not in self.my_osid_object_form._my_map['choices']: raise IllegalState('that inline region does not exist. Please call add_inline_region first') if identifier is None: identifier = str(ObjectId()) current_identifiers = [c...
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 i...
def get_choices(self): """stub""" # ideally would return a displayText object in text ... except for legacy # use cases like OEA, it expects a text string. choices = {} # for region_name, region_choices in self.my_osid_object.object_map['choices'].items(): for region_name, region_choices in self.my_osid_object._my_map[...
def _init_metadata(self): """stub""" self._inline_regions_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'inline_regions'), 'element_label': 'set of inline regions', 'instructions': 'submit correct choice for answer for each region', 'required': True, 'read_only'...
def parse_multiple(s, f, values=None): """Parse multiple comma-separated elements, each of which is parsed using function f.""" if values is None: values = [] values.append(f(s)) if s.pos < len(s) and s.cur == ',': s.pos += 1 return parse_multiple(s, f, values) else: return values
def string_to_state(s): """s is a string possibly preceded by > or @.""" s = lexer(s) attrs = {} while True: if s.cur == '>': attrs['start'] = True s.pos += 1 elif s.cur == '@': attrs['accept'] = True s.pos += 1 else: break x = parse_symbol(s) parse_end(s) return x, attrs
def string_to_config(s): """s is a comma-separated list of stores.""" from .machines import Configuration s = lexer(s) x = parse_multiple(s, parse_store) parse_end(s) return Configuration(x)
def string_to_configs(s): """s is a string in one of the following formats: - x,y - (x,y) - {x,y} - {(w,x),(y,z)} In any case, returns a set of tuples of stores. """ s = lexer(s) value = None if s.pos == len(s): value = set() elif s.cur == '{': value = parse_set(s) elif s.cur == '(': value = {parse_tuple(s)} else: valu...
def string_to_transition(s): """s is a string of the form a,b or a,b->c,d""" from .machines import Transition s = lexer(s) lhs = parse_multiple(s, parse_store) if s.pos < len(s) and s.cur == "->": s.pos += 1 rhs = parse_multiple(s, parse_store) else: rhs = () parse_end(s) return Transition(lhs, rhs)
def hypercube(number_of_samples, variables): """ This implements Latin Hypercube Sampling. See https://mathieu.fenniak.net/latin-hypercube-sampling/ for intuitive explanation of what it is :param number_of_samples: number of segments/samples :param variables: initial parameters and conditions (list of ranges, i.e. (70,...
regression tests as the values are shuffled in different order values = random.sample(values, len(values)) x.append(values) # at this point x is a list of lists containing a randomly-ordered list of random values # in each of the `possvalues` segments samples = [] for i in range(len(segment_ranges)): sample = [y[i] for...
def output_latex(self, filename_or_file_handle): """ Output the file to a latex document :param filename_or_file_handle: filename or already opened file handle to output to :return: """ if isinstance(filename_or_file_handle, basestring): file_handle = file(filename_or_file_handle, 'w') we_opened = True else: file_handl...
def _init_map(self): """stub""" self.my_osid_object_form._my_map['maxStrings'] = \ self._max_strings_metadata['default_integer_values'][0] self.my_osid_object_form._my_map['expectedLength'] = \ self._expected_length_metadata['default_integer_values'][0] self.my_osid_object_form._my_map['expectedLines'] = \ self._expect...
def _init_metadata(self): """stub""" self._max_strings_metadata = { 'element_id': Id(self.my_osid_object_form._authority, self.my_osid_object_form._namespace, 'maxStrings'), 'element_label': 'maxStrings', 'instructions': 'QTI maxStrings settings', 'required': False, 'read_only': False, 'linked': False, 'array': False, ...
def set_max_strings(self, max_strings): """stub""" if not self.my_osid_object_form._is_valid_integer( max_strings, self.get_max_strings_metadata()): raise InvalidArgument('maxStrings') self.my_osid_object_form._my_map['maxStrings'] = max_strings
def set_expected_length(self, expected_length): """stub""" if not self.my_osid_object_form._is_valid_integer( expected_length, self.get_expected_length_metadata()): raise InvalidArgument('expectedLength') self.my_osid_object_form._my_map['expectedLength'] = expected_length
def set_expected_lines(self, expected_lines): """stub""" if not self.my_osid_object_form._is_valid_integer( expected_lines, self.get_expected_lines_metadata()): raise InvalidArgument('expectedLines') self.my_osid_object_form._my_map['expectedLines'] = expected_lines
def run(self, collector, image, available_actions, tasks, **extras): """Run this task""" task_func = available_actions[self.action] configuration = collector.configuration.wrapped() if self.options: if image: configuration.update({"images": {image: self.options}}) else: configuration.update(self.options) # args like --...
def find_image(self, image, configuration): """Complain if we don't have an image""" images = configuration["images"] available = list(images.keys()) if not image: info = {} if available: info["available"] = available raise BadOption("Please use --image to specify an image", **info) if image not in images: raise BadOpt...
def replicate_global_dbs(cloud_url=None, local_url=None): """ Set up replication of the global databases from the cloud server to the local server. :param str cloud_url: Used to override the cloud url from the global configuration in case the calling function is in the process of initializing the cloud server :param st...
def cancel_global_db_replication(): """ Cancel replication of the global databases from the cloud server to the local server. """ local_url = config["local_server"]["url"] server = Server(local_url) for db_name in global_dbs: server.cancel_replication(db_name)
def replicate_per_farm_dbs(cloud_url=None, local_url=None, farm_name=None): """ Sete up replication of the per-farm databases from the local server to the cloud server. :param str cloud_url: Used to override the cloud url from the global configuration in case the calling function is in the process of initializing the c...
url parsed_cloud_url = urlparse(cloud_url) if not parsed_cloud_url.username: new_netloc = "{}:{}@{}".format( username, password, parsed_cloud_url.netloc ) cloud_url = ParseResult( parsed_cloud_url.scheme, new_netloc, parsed_cloud_url.path, parsed_cloud_url.params, parsed_cloud_url.query, parsed_cloud_url.fragment ).get...
def cancel_per_farm_db_replication(): """ Cancel replication of the per-farm databases from the local server to the cloud server. """ cloud_url = config["cloud_server"]["url"] local_url = config["local_server"]["url"] server = Server(local_url) for db_name in per_farm_dbs: server.cancel_replication(db_name)
def _register_options(self, api_interface): # type: (ApiInterfaceBase) -> None """ Register CORS options endpoints. """ op_paths = api_interface.op_paths(collate_methods=True) for path, operations in op_paths.items(): if api.Method.OPTIONS not in operations: self._options_operation(api_interface, path, operations.keys(...
def cors_options(self, request, **_): """ CORS options response method. Broken out if this needs to be customised. """ return create_response( request, headers=self.pre_flight_headers(request, request.supported_methods) )
def _options_operation(self, api_interface, path, methods): # type: (ApiInterfaceBase, UrlPath, List[api.Method]) -> None """ Generate an options operation for the specified path """ # Trim off path prefix. if path.startswith(api_interface.path_prefix): path = path[len(api_interface.path_prefix):] methods = set(methods...
def allow_origin(self, request): # type: (BaseHttpRequest) -> str """ Generate allow origin header """ origins = self.origins if origins is AnyOrigin: return '*' else: origin = request.origin return origin if origin in origins else ''
def pre_flight_headers(self, request, methods): # type: (BaseHttpRequest, Sequence[api.Method]) -> Dict[str, str] """ Generate pre-flight headers. """ methods = ', '.join(m.value for m in methods) headers = { 'Allow': methods, 'Cache-Control': 'no-cache, no-store' } allow_origin = self.allow_origin(request) if allow_or...
def request_headers(self, request): """ Generate standard request headers """ headers = {} allow_origin = self.allow_origin(request) if allow_origin: headers = dict_filter({ 'Access-Control-Allow-Origin': allow_origin, 'Access-Control-Allow-Credentials': {True: 'true', False: 'false'}.get(self.allow_credentials), 'Acce...
def post_request(self, request, response): # type: (BaseHttpRequest, HttpResponse) -> HttpResponse """ Post-request hook to allow CORS headers to responses. """ if request.method != api.Method.OPTIONS: response.headers.update(self.request_headers(request)) return response
def _muck_w_date(record): """muck with the date because EPW starts counting from 1 and goes to 24.""" # minute 60 is actually minute 0? temp_d = datetime.datetime(int(record['Year']), int(record['Month']), int(record['Day']), int(record['Hour']) % 24, int(record['Minute']) % 60) d_off = int(record['Hour'])//24 # hour 2...
def _station_info(station_code): """filename based meta data for a station code.""" url_file = open(env.SRC_PATH + '/eere.csv') for line in csv.DictReader(url_file): if line['station_code'] == station_code: return line raise KeyError('Station not found')
def _basename(station_code, fmt=None): """region, country, weather_station, station_code, data_format, url.""" info = _station_info(station_code) if not fmt: fmt = info['data_format'] basename = '%s.%s' % (info['url'].rsplit('/', 1)[1].rsplit('.', 1)[0], DATA_EXTENTIONS[fmt]) return basename
def twopercent(station_code): """Two percent high design temperature for a location. Degrees in Celcius Args: station_code (str): Weather Station Code Returns: float degrees Celcius """ # (DB=>MWB) 2%, MaxDB= temp = None try: fin = open('%s/%s' % (env.WEATHER_DATA_PATH, _basename(station_code, 'ddy'))) for line in fin:...
def minimum(station_code): """Extreme Minimum Design Temperature for a location. Degrees in Celcius Args: station_code (str): Weather Station Code Returns: float degrees Celcius """ temp = None fin = None try: fin = open('%s/%s' % (env.WEATHER_DATA_PATH, _basename(station_code, 'ddy'))) except IOError: logger.info("Fil...
def next(self): """Weather data record. Yields: dict """ record = self.epw_data.next() local_time = _muck_w_date(record) record['datetime'] = local_time # does this fix a specific data set or a general issue? if self.DST: localdt = self.local_tz.localize(record['datetime']) record['utc_datetime'] = localdt.astimezone(p...
def ensure_string(obj): """Return String and if Unicode convert to string. :param obj: ``str`` || ``unicode`` :return: ``str`` """ if sys.version_info < (3, 2, 0) and isinstance(obj, unicode): return str(obj.encode('utf8')) else: return obj
def dict_update(base_dict, update_dict): """Return an updated dictionary. If ``update_dict`` is a dictionary it will be used to update the ` `base_dict`` which is then returned. :param request_kwargs: ``dict`` :param kwargs: ``dict`` :return: ``dict`` """ if isinstance(update_dict, dict): base_dict.update(update_dict) ...
def op_paths(self, path_base): # type: (Union[str, UrlPath]) -> Generator[Tuple[UrlPath, Operation]] """ Return all operations stored in containers. """ path_base += self.path_prefix for operation in self._operations: for op_path in operation.op_paths(path_base): yield op_path
def operation(self, path, methods=Method.GET, resource=None, tags=None, summary=None, middleware=None): # type: (UrlPath, Union[Method, Tuple[Method]], Type[Resource], Tags, str, list) -> Operation """ :param path: A sub path that can be used as a action. :param methods: HTTP method(s) this function responses to. :para...
def op_paths(self, path_base=None): # type: (Union[str, UrlPath]) -> Generator[Tuple[UrlPath, Operation]] """ Return all operations stored in containers. """ if path_base: path_base += self.path_prefix else: path_base = self.path_prefix or UrlPath() for container in self.containers: for op_path in container.op_paths(pa...
def handle_500(self, request, exception): # type: (BaseHttpRequest, BaseException) -> Resource """ Handle an *un-handled* exception. """ # Let middleware attempt to handle exception try: for middleware in self.middleware.handle_500: resource = middleware(request, exception) if resource: return resource except Exception...
def dispatch_operation(self, operation, request, path_args): # type: (Operation, BaseHttpRequest, Dict[str, Any]) -> Tuple[Any, Optional[HTTPStatus], Optional[dict]] """ Dispatch and handle exceptions from operation. """ try: # path_args is passed by ref so changes can be made. for middleware in self.middleware.pre_dis...
if self.debug_enabled: # If debug is enabled then fallback to the frameworks default # error processing, this often provides convenience features # to aid in the debugging process. raise resource = None # Fallback to the default handler if resource is None: resource = self.handle_500(request, e) return resource, resour...
def _dispatch(self, operation, request, path_args): """ Wrapped dispatch method, prepare request and generate a HTTP Response. """ # Determine the request and response types. Ensure API supports the requested types request_type = resolve_content_type(self.request_type_resolvers, request) request_type = self.remap_codec...
def dispatch(self, operation, request, **path_args): """ Dispatch incoming request and capture top level exceptions. """ # Add current operation to the request (for convenience in middleware methods) request.current_operation = operation try: for middleware in self.middleware.pre_request: response = middleware(request,...
def op_paths(self, path_base=None, collate_methods=False): # type: (Union[str, UrlPath], bool) -> Union[Generator[Tuple[UrlPath, Operation]], Dict[UrlPath, Operation]] """ Return all operations stored in containers. Use the `collate_methods` option to collate methods by path. This is required for certain web frameworks...
def sector_size(self): """ Property with current sector size. CFB file can store normal sectors and smaller ones. """ header = self.source.header return header.mini_sector_size if self._is_mini else header.sector_size
def sector_shift(self): """ Property with current sector size shift. Actually sector size is 2 ** sector shift """ header = self.source.header return header.mini_sector_shift if self._is_mini \ else header.sector_shift
def left(self): """ Entry is left sibling of current directory entry """ return self.source.directory[self.left_sibling_id] \ if self.left_sibling_id != NOSTREAM else None
def right(self): """ Entry is right sibling of current directory entry """ return self.source.directory[self.right_sibling_id] \ if self.right_sibling_id != NOSTREAM else None
def read(self, size=None): """ Reads `size` bytes from current directory entry. If `size` is empty, it'll read all data till entry's end. """ if self._is_mini: self.seek(self._position) else: self.source.seek(self._source_position) if not size or size < 0: size = self.size - self.tell() data = b('') while len(data) < s...
def seek(self, offset, whence=SEEK_SET): """ Seeks to specified `offset` position in current directory entry stream. `Whence` can be SEEK_SET - from entry's start, SEEK_CUR - from current position and SEEK_END - from entry's end. Constants are same with same stored `os` module. """ if whence == SEEK_CUR: offset += self...
def child(self): """ Root entry object has only one child entry and no siblings. """ return self.stream.directory[self.child_id] \ if self.child_id != NOSTREAM else None
def apply_filter(objs, selector, mode): '''Apply selector to transform each object in objs. This operates in-place on objs. Empty objects are removed from the list. Args: mode: either KEEP (to keep selected items & their ancestors) or DELETE (to delete selected items and their children). ''' indices_to_delete = [] pres...
def apply_selector(objs, selector): '''Returns a list of objects which match the selector in any of objs.''' out = [] for obj in objs: timer.log('Applying selector: %s' % selector) out += list(jsonselect.match(selector, objs)) timer.log('done applying selector') return out
def log(self, statement): '''Write statement to stderr with timing info in DEBUG mode.''' global DEBUG time_ms = 1000 * time.time() if DEBUG: total_time_ms = time_ms - self._start_time_ms_ lap_time_ms = time_ms - self._last_time_ms_ sys.stderr.write('%6.f (%6.f ms) %s\n' % ( total_time_ms, lap_time_ms, statement)) self...
def get_data(self): """Gets the asset content data. return: (osid.transport.DataInputStream) - the length of the content data raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* # gets you a file-like object...not sure if it will behave exactly as expected... ...
def get_object_map(self): """stub""" obj_map = self._payload.get_object_map() obj_map.update({'url': self.get_url()}) obj_map['recordTypeIds'].append(str(AWS_ASSET_CONTENT_RECORD_TYPE)) return obj_map
def set_data(self, data=None): """Sets the content data. arg: data (osid.transport.DataInputStream): the content data raise: InvalidArgument - ``data`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``data`` is ``null`` *compliance: mandatory -- This method must be implemented....
= str(repository_id) + '/' + str(filename) url += '/' + remote_location data.seek(0) odl_repo.put_object( Body=data.read(), Bucket=self._config_map['s3_bucket'], Key=remote_location ) # odl_repo.key = remote_location # odl_repo.set_contents_from_file(data._my_data) # this should set the original S3 location, so we can ...
def clear_data(self): """Removes the content data. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # cjshaw@mit.edu, Jan 9, 2015 # Removes the item from AWS S3 and resets URL to '' odl_repo, url = get_aws_s3...
def get_next_asset_contents(self, n=None): """Gets the next set of ``AssetContents`` in this list which must be less than or equal to the return from ``available()``. arg: n (cardinal): the number of ``AssetContent`` elements requested which must be less than or equal to ``available()`` return: (osid.repository.AssetCo...
def resolve_content_type(type_resolvers, request): # type: (Iterable[Callable[[Any], str]], Any) -> Optional[str] """ Resolve content types from a request. """ for resolver in type_resolvers: content_type = parse_content_type(resolver(request)) if content_type: return content_type
def get_resource(request, resource, allow_multiple=False, full_clean=True, default_to_not_supplied=False): """ Get a resource instance from ``request.body``. Note error code 98 is returned in multiple places, this is to prevent leakage of details of defined resources. """ # Decode the request body. body = request.body ...
98, "Invalid resource type.") if not allow_multiple: raise HttpError(HTTPStatus.BAD_REQUEST, 97, "Expected a single resource not a list.") elif not isinstance(instance, resource): raise HttpError(HTTPStatus.BAD_REQUEST, 98, "Invalid resource type.") return instance
def create_response(request, body=None, status=None, headers=None): # type: (BaseHttpRequest, Any, HTTPStatus, dict) -> HttpResponse """ Generate a HttpResponse. :param request: Request object :param body: Body of the response :param status: HTTP status code :param headers: Any headers. """ if body is None: return Http...
def read(self): """ This module is lazy-loaded by default. You can read all internal structure by calling this method. """ stack = [self[0].child] while stack: current = stack.pop() if current.right: stack.append(current.right) if current.left: stack.append(current.left) self[0].seek(0)
def by_name(self, name): """ In many cases you want to access directory not by it's ID, but by it's name. This method implements red-black search method, which internally uses CFB format. Also this method has internal name cache to speed up 2nd+ named accesses. """ if name in self._name_cache: return self[self._name_ca...
def _compare(self, other, method): """see https://regebro.wordpress.com/2010/12/13/python-implementing-rich-comparison-the-correct-way/""" # This needs to be updated to take uncertainty into account: if isinstance(other, abc_mapping_primitives.Coordinate): if self.get_dimensions() != other.get_dimensions(): return Fals...
def _set_vault_view(self, session): """Sets the underlying vault view to match current view""" if self._vault_view == COMPARATIVE: try: session.use_comparative_vault_view() except AttributeError: pass else: try: session.use_plenary_vault_view() except AttributeError: pass
def use_comparative_vault_view(self): """Pass through to provider AuthorizationVaultSession.use_comparative_vault_view""" self._vault_view = COMPARATIVE # self._get_provider_session('authorization_vault_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_compar...
def use_plenary_vault_view(self): """Pass through to provider AuthorizationVaultSession.use_plenary_vault_view""" self._vault_view = PLENARY # self._get_provider_session('authorization_vault_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_plenary_vault_view...
def get_vaults_by_ids(self, *args, **kwargs): """Pass through to provider VaultLookupSession.get_vaults_by_ids""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_by_ids catalogs = self._get_provider_session('vault_lookup_session').get_vaults_by_ids(*args, **kwargs) cat_list = [] for ...
def get_vaults(self): """Pass through to provider VaultLookupSession.get_vaults""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_template catalogs = self._get_provider_session('vault_lookup_session').get_vaults() cat_list = [] for cat in catalogs: cat_list.append(Vault(self._provid...
def create_vault(self, *args, **kwargs): """Pass through to provider VaultAdminSession.create_vault""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.create_bin return Vault( self._provider_manager, self._get_provider_session('vault_admin_session').create_vault(*args, **kwargs), self._runtime...
def get_vault_form(self, *args, **kwargs): """Pass through to provider VaultAdminSession.get_vault_form_for_update""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.get_bin_form_for_update_template # This method might be a bit sketchy. Time will tell. if isinstance(args[-1], list) or 'vault_r...
def save_vault(self, vault_form, *args, **kwargs): """Pass through to provider VaultAdminSession.update_vault""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.update_bin if vault_form.is_for_update(): return self.update_vault(vault_form, *args, **kwargs) else: return self.create_vault(vault_...
def _set_vault_view(self, session): """Sets the underlying vault view to match current view""" if self._vault_view == FEDERATED: try: session.use_federated_vault_view() except AttributeError: pass else: try: session.use_isolated_vault_view() except AttributeError: pass
def use_comparative_authorization_view(self): """Pass through to provider AuthorizationLookupSession.use_comparative_authorization_view""" self._object_views['authorization'] = COMPARATIVE # self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked for session in self._get_provide...
def use_plenary_authorization_view(self): """Pass through to provider AuthorizationLookupSession.use_plenary_authorization_view""" self._object_views['authorization'] = PLENARY # self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions()...
def use_federated_vault_view(self): """Pass through to provider AuthorizationLookupSession.use_federated_vault_view""" self._vault_view = FEDERATED # self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_federated_...
def use_isolated_vault_view(self): """Pass through to provider AuthorizationLookupSession.use_isolated_vault_view""" self._vault_view = ISOLATED # self._get_provider_session('authorization_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_isolated_vaul...
def get_authorization_form(self, *args, **kwargs): """Pass through to provider AuthorizationAdminSession.get_authorization_form_for_update""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.get_resource_form_for_update # This method might be a bit sketchy. Time will tell. if isinstance(ar...
def save_authorization(self, authorization_form, *args, **kwargs): """Pass through to provider AuthorizationAdminSession.update_authorization""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if authorization_form.is_for_update(): return self.update_authorization(authoriz...
def get_grade_system_id(self): """Gets the ``GradeSystem Id`` in which this grade belongs. return: (osid.id.Id) - the grade system ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.Activity.get_objective_id if not bool(self._my_map['gradeSystemId']): ra...
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._output_score_default = self._mdata['output_score']['default_decimal_values'][0] self._input_score_end_range_default = self._mdata['input_score_end_range']['default_decimal_values'][0] self...
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map['outputScore'] = self._output_score_default self._my_map['gradeSystemId'] = str(kwargs['grade_system_id']) self._my_map['inputScoreEndRange'] = self._input_scor...