code stringlengths 1 18.2k |
|---|
def get_functions_by_search(self, function_query, function_search): """Pass through to provider FunctionSearchSession.get_functions_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDenied() return sel... |
def get_qualifiers_by_search(self, qualifier_query, qualifier_search): """Pass through to provider QualifierSearchSession.get_qualifiers_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise PermissionDenied() retur... |
def print_trace(self): """ Prints stack trace for current exceptions chain. """ traceback.print_exc() for tb in self.tracebacks: print tb, print '' |
def grep(rootdir, searched): "grep -l <searched>" to_inspect = [] for root, dirs, files in os.walk(rootdir): for _file in files: if _file.endswith('.rst'): to_inspect.append(join(root, _file)) to_check = ((_file, open(_file, 'r').read()) for _file in to_inspect) to_check = filter(lambda item: searched in item[1], to_ch... |
def c(source, libraries=[]): r""" >>> c('int add(int a, int b) {return a + b;}').add(40, 2) 42 >>> sqrt = c(''' ... #include <math.h> ... double _sqrt(double x) {return sqrt(x);} ... ''', ['m'])._sqrt >>> sqrt.restype = ctypes.c_double >>> sqrt(ctypes.c_double(400.0)) 20.0 """ path = _cc_build_shared_lib(source, '.c', ... |
def cxx(source, libraries=[]): r""" >>> cxx('extern "C" { int add(int a, int b) {return a + b;} }').add(40, 2) 42 """ path = _cc_build_shared_lib(source, '.cc', libraries) return ctypes.cdll.LoadLibrary(path) |
def python(source): r""" >>> python('def add(a, b): return a + b').add(40, 2) 42 """ obj = type('', (object,), {})() _exec(source, obj.__dict__, obj.__dict__) return obj |
def _exec(object, globals, locals): r""" >>> d = {} >>> exec('a = 0', d, d) >>> d['a'] 0 """ if sys.version_info < (3,): exec('exec object in globals, locals') else: exec(object, globals, locals) |
def get_type_lookup_session(self): """Gets the OsidSession associated with the type lookup service. return: (osid.type.TypeLookupSession) - a TypeLookupSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_type_lookup() is false compliance: optional - This method must be implemente... |
def get_type_admin_session(self): """Gets the OsidSession associated with the type admin service. return: (osid.type.TypeAdminSession) - a TypeAdminSession raise: OperationFailed - unable to complete request raise: Unimplemented - supports_type_admin() is false compliance: optional - This method must be implemented if ... |
def _line_to_entry(self,line): """parse the line into entries and keys""" f = line.rstrip().split("\t") """ 'chrom' 'chromStart' 'chromEnd' 'name' 'score' 'strand' 'thickStart' 'thickEnd' 'itemRgb' 'blockCount' 'blockSizes' 'blockStarts' """ return Bed12Fields( f[0], int(f[1]), int(f[2]), f[3], int(f[4]), f[5], int(f[6... |
def _to_swagger(base=None, description=None, resource=None, options=None): # type: (Dict[str, str], str, Resource, Dict[str, str]) -> Dict[str, str] """ Common to swagger definition. :param base: The base dict. :param description: An optional description. :param resource: An optional resource. :param options: Any addit... |
def from_object(cls, obj): # type: (Any) -> UrlPath """ Attempt to convert any object into a UrlPath. Raise a value error if this is not possible. """ if isinstance(obj, UrlPath): return obj if isinstance(obj, _compat.string_types): return UrlPath.parse(obj) if isinstance(obj, PathParam): return UrlPath(obj) if isinsta... |
def parse(cls, url_path): # type: (str) -> UrlPath """ Parse a string into a URL path (simple eg does not support typing of URL parameters) """ if not url_path: return cls() nodes = [] for node in url_path.rstrip('/').split('/'): # Identifies a PathNode if '{' in node or '}' in node: m = PATH_NODE_RE.match(node) if not... |
def startswith(self, other): # type: (UrlPath) -> bool """ Return True if this path starts with the other path. """ try: other = UrlPath.from_object(other) except ValueError: raise TypeError('startswith first arg must be UrlPath, str, PathParam, not {}'.format(type(other))) else: return self._nodes[:len(other._nodes)] ... |
def apply_args(self, **kwargs): # type: (**str) -> UrlPath """ Apply formatting to each path node. This is used to apply a name to nodes (used to apply key names) eg: >>> a = UrlPath("foo", PathParam('{key_field}'), "bar") >>> b = a.apply_args(id="item_id") >>> b.format() 'foo/{item_id}/bar' """ def apply_format(node):... |
def odinweb_node_formatter(path_node): # type: (PathParam) -> str """ Format a node to be consumable by the `UrlPath.parse`. """ args = [path_node.name] if path_node.type: args.append(path_node.type.name) if path_node.type_args: args.append(path_node.type_args) return "{{{}}}".format(':'.join(args)) |
def format(self, node_formatter=None, separator='/'): # type: (Optional[Callable[[PathParam], str]]) -> str """ Format a URL path. An optional `node_parser(PathNode)` can be supplied for converting a `PathNode` into a string to support the current web framework. """ if self._nodes == ('',): return separator else: node_... |
def path(cls, name, type_=Type.String, description=None, default=None, minimum=None, maximum=None, enum=None, **options): """ Define a path parameter """ if minimum is not None and maximum is not None and minimum > maximum: raise ValueError("Minimum must be less than or equal to the maximum.") return cls(name, In.Path,... |
def query(cls, name, type_=Type.String, description=None, required=None, default=None, minimum=None, maximum=None, enum=None, **options): """ Define a query parameter """ if minimum is not None and maximum is not None and minimum > maximum: raise ValueError("Minimum must be less than or equal to the maximum.") return c... |
def header(cls, name, type_=Type.String, description=None, default=None, required=None, **options): """ Define a header parameter. """ return cls(name, In.Header, type_, None, description, required=required, default=default, **options) |
def body(cls, description=None, default=None, resource=DefaultResource, **options): """ Define body parameter. """ return cls('body', In.Body, None, resource, description, required=True, default=default, **options) |
def form(cls, name, type_=Type.String, description=None, required=None, default=None, minimum=None, maximum=None, enum=None, **options): """ Define form parameter. """ if minimum is not None and maximum is not None and minimum > maximum: raise ValueError("Minimum must be less than or equal to the maximum.") return cls(... |
def to_swagger(self, bound_resource=None): """ Generate a swagger representation. """ return _to_swagger( { 'name': self.name, 'in': self.in_.value, 'type': str(self.type) if self.type else None, }, description=self.description, resource=bound_resource if self.resource is DefaultResource else self.resource, options=sel... |
def to_swagger(self, bound_resource=None): """ Generate a swagger representation. """ response_def = _to_swagger( description=self.description, resource=bound_resource if self.resource is DefaultResource else self.resource, ) status = self.status if self.status == 'default' else self.status.value return status, respons... |
def pre_request(self): """ List of pre-request methods from registered middleware. """ middleware = sort_by_priority(self) return tuple(m.pre_request for m in middleware if hasattr(m, 'pre_request')) |
def pre_dispatch(self): """ List of pre-dispatch methods from registered middleware. """ middleware = sort_by_priority(self) return tuple(m.pre_dispatch for m in middleware if hasattr(m, 'pre_dispatch')) |
def post_dispatch(self): """ List of post-dispatch methods from registered middleware. """ middleware = sort_by_priority(self, reverse=True) return tuple(m.post_dispatch for m in middleware if hasattr(m, 'post_dispatch')) |
def post_swagger(self): """ List of post-swagger methods from registered middleware. This is used to modify documentation (eg add/remove any extra information, provided by the middleware) """ middleware = sort_by_priority(self) return tuple(m.post_swagger for m in middleware if hasattr(m, 'post_swagger')) |
def add(self, key, value): # type: (Hashable, Any) -> None """ Adds a new value for the key. :param key: the key for the value. :param value: the value to add. """ dict.setdefault(self, key, []).append(value) |
def get(self, key, default=None, type_=None): """ Return the last data value for the passed key. If key doesn't exist or value is an empty list, return `default`. """ try: rv = self[key] except KeyError: return default if type_ is not None: try: rv = type_(rv) except ValueError: rv = default return rv |
def getlist(self, key, type_=None): # type: (Hashable, Callable) -> List[Any] """ Return the list of items for a given key. If that key is not in the `MultiDict`, the return value will be an empty list. Just as `get` `getlist` accepts a `type` parameter. All items will be converted with the callable defined there. :par... |
ValueError: pass return result |
def setlist(self, key, new_list): # type: (Hashable, List[Any]) -> None """ Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary. >>> d = MultiValueDict() >>> d.setlist('foo', ['1', '2']) >>> d['foo'] '1' >>> d.getlist... |
def setlistdefault(self, key, default_list=None): # type: (Hashable, List[Any]) -> List[Any] """ Like `setdefault` but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list: >>> d = MultiV... |
def items(self, multi=False): # type: (bool) -> Iterator[Tuple[Hashable, Any]] """ Return an iterator of ``(key, value)`` pairs. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the lasted added of each key. """ for key, values in... |
def sorteditems(self, multi=False): # type: (bool) -> Iterator[Tuple[Hashable, Any]] """ Return an iterator of ``(key, value)`` pairs, sorted by key. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the lasted added of each key. "... |
def values(self, multi=False): # type: (bool) -> Iterator[Any] """ Yield the last value on every key list. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the lasted added of each key. """ for values in itervalues(self): if multi... |
def to_dict(self, flat=True): """ Return the contents as regular dict. If `flat` is `True` the returned dict will only have the first item present, if `flat` is `False` all values will be returned as lists. :param flat: If set to `False` the dict returned will have lists with all the values in it. Otherwise it will onl... |
def pop(self, key, default=NotDefined): # type: (Hashable, Any) -> Any """ Pop the last item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded: >>> d = MultiValueDict({"foo": [1, 2, 3]}) >>> d.pop("foo") 1 >>> "foo" in d False :param key: the key to pop. :param defa... |
def get_proxy(self, input_): """Gets a proxy. arg: input (osid.proxy.ProxyCondition): a proxy condition return: (osid.proxy.Proxy) - a proxy raise: NullArgument - ``input`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure raise: Unsupported - ``input`` is n... |
def to_plain_text(str): ''' Return a plain-text version of a given string This is a dumb approach that tags and then removing entity markers but this is fine for the content from biocyc where entities are β etc. Stripping in this way turns these into plaintext 'beta' which is preferable to unicode ''' str = strip_... |
def get_from_cache(self, org_id, id): ''' Get an object from the cache Use all cache folders available (primary first, then secondary in order) and look for the ID in the dir if found unpickle and return the object, else return False FIXME: Check for expiry of object! Return false is expired (will auto-refetch and over... |
else continue if obj.created_at > current_time - self.expire_records_after: # If we're here it mustn't be in the memory cache self.memory_cache[org_id][id] = obj if len(self.memory_cache[org_id]) > self.max_memory_cache: self.memory_cache[org_id].popitem(last=False) return obj # Else continue looking # We found nothing... |
def cache(self, obj): ''' Store an object in the cache (this allows temporarily assigning a new cache for exploring the DB without affecting the stored version ''' # Check cache path exists for current obj write_path = os.path.join( self.cache_path, obj.org_id ) if not os.path.exists( write_path ): mkdir_p( write_path ... |
def get_for_org(self, org_id, ids, skip_cache=False): ''' Returns objects for the given identifiers If called with a list returns a list, else returns a single entity ''' t = type(ids) if t != list: ids = [ids] objs = [] for id in ids: if id == '' or type(id) is not str: # Empty string objs.append(None) continue if ski... |
def import_from_xml(self, xml): ''' Standard imports for all types of object These must fail gracefully, skip if not found ''' self._import_orgid(xml) self._import_parents_from_xml(xml) self._import_instances_from_xml(xml) self._import_common_name(xml) self._import_synonyms(xml) self._import_dblinks(xml) |
def _set_var_from_xml_text(self, xml, xmlpath, var): ''' Sets a object variable from the xml if it is there and passing it through a data conversion based on the variable datatype ''' xmle = xml.find(xmlpath) if xmle is not None: setattr(self, var, type_converter[ xmle.attrib.get('datatype', 'string') ]( xmle.text )) |
def _set_list_ids_from_xml_iter(self, xml, xmlpath, var): ''' Set a list variable from the frameids of matching xml entities ''' es = xml.iterfind(xmlpath) if es is not None: l = [] for e in es: l.append( e.attrib['frameid'] ) setattr(self, var, l) |
def _set_id_from_xml_frameid(self, xml, xmlpath, var): ''' Set a single variable with the frameids of matching entity ''' e = xml.find(xmlpath) if e is not None: setattr(self, var, e.attrib['frameid']) |
def get_avatar_id(self): """Gets the asset ``Id``. return: (osid.id.Id) - the asset ``Id`` raise: IllegalState - ``has_avatar()`` is ``false`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_template if not bool(self._my_map['avatarId'... |
def get_avatar(self): """Gets the asset. return: (osid.repository.Asset) - the asset raise: IllegalState - ``has_avatar()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_t... |
def _init_metadata(self, **kwargs): """Initialize form metadata""" osid_objects.OsidObjectForm._init_metadata(self, **kwargs) self._group_default = self._mdata['group']['default_boolean_values'][0] self._avatar_default = self._mdata['avatar']['default_id_values'][0] |
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map['assignedBinIds'] = [str(kwargs['bin_id'])] self._my_map['group'] = self._group_default self._my_map['avatarId'] = self._avatar_default |
def get_group_metadata(self): """Gets the metadata for a group. return: (osid.Metadata) - metadata for the group *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['group']) metadata.update({'... |
def set_group(self, group): """Sets the resource as a group. arg: group (boolean): ``true`` if this resource is a group, ``false`` otherwise raise: InvalidArgument - ``group`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented... |
def clear_group(self): """Clears the group designation. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_group_template if (self.get_group_metadata().is_re... |
def get_avatar_metadata(self): """Gets the metadata for an asset. return: (osid.Metadata) - metadata for the asset *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['avatar']) metadata.update... |
def set_avatar(self, asset_id): """Sets the avatar asset. arg: asset_id (osid.id.Id): an asset ``Id`` raise: InvalidArgument - ``asset_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Res... |
def clear_avatar(self): """Clears the asset. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.clear_avatar_template if (self.get_avatar_metadata().is_read_only()... |
def get_bin(self): """Gets the ``Bin`` at this node. return: (osid.resource.Bin) - the bin represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_provider_manager('RESOURCE', runtime=self._runtime, proxy=self._proxy) self._lookup_session = mgr... |
def get_parent_bin_nodes(self): """Gets the parents of this bin. return: (osid.resource.BinNodeList) - the parents of the ``id`` *compliance: mandatory -- This method must be implemented.* """ parent_bin_nodes = [] for node in self._my_map['parentNodes']: parent_bin_nodes.append(BinNode( node._my_map, runtime=self._run... |
def supports_coordinate_type(self, coordinate_type): """Tests if the given coordinate type is supported. arg: coordinate_type (osid.type.Type): a coordinate Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``COORDINATE`` raise: NullArgument - ``coordi... |
def supports_currency_type(self, currency_type): """Tests if the given currency type is supported. arg: currency_type (osid.type.Type): a currency Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``CURRENCY`` raise: NullArgument - ``currency_type`` is... |
def supports_calendar_type(self, calendar_type): """Tests if the given calendar type is supported. arg: calendar_type (osid.type.Type): a calendar Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``DATETIME`` or ``DURATION`` raise: NullArgument - ``ca... |
def supports_time_type(self, time_type): """Tests if the given time type is supported. arg: time_type (osid.type.Type): a time Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``DATETIME, DURATION,`` or ``TIME`` raise: NullArgument - ``time_type`` is ... |
def supports_heading_type(self, heading_type): """Tests if the given heading type is supported. arg: heading_type (osid.type.Type): a heading Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``HEADING`` raise: NullArgument - ``heading_type`` is ``null... |
def supports_object_type(self, object_type): """Tests if the given object type is supported. arg: object_type (osid.type.Type): an object Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not an ``OBJECT`` raise: NullArgument - ``object_type`` is ``null`` *c... |
def supports_spatial_unit_record_type(self, spatial_unit_record_type): """Tests if the given spatial unit record type is supported. arg: spatial_unit_record_type (osid.type.Type): a spatial unit record Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not an... |
def supports_string_match_type(self, string_match_type): """Tests if the given string match type is supported. arg: string_match_type (osid.type.Type): a string match type return: (boolean) - ``true`` if the given string match type Is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``STRING`` raise... |
def supports_version_type(self, version_type): """Tests if the given version type is supported. arg: version_type (osid.type.Type): a version Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``VERSION`` raise: NullArgument - ``version_type`` is ``null... |
def get(self, index1, index2=None): """Return the text from INDEX1 to INDEX2 (not included).""" returnvar = self.tk.call(self._w, 'get', index1, index2) return returnvar.strip() |
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() try: return { 'authority': 'okapia.net', 'namespace': 'TextFormats', 'identifier': name, 'domain': 'DisplayText Formats', 'display_name': FORMAT_TYPES[name] + ' Format ... |
def log_view(func): """ Helpful while debugging Selenium unittests. e.g.: server response an error in AJAX requests """ @functools.wraps(func) def view_logger(*args, **kwargs): log.debug("call view %r", func.__name__) try: response = func(*args, **kwargs) except Exception as err: log.error("view exception: %s", err) tr... |
def move_id_ahead(element_id, reference_id, idstr_list): """Moves element_id ahead of reference_id in the list""" if element_id == reference_id: return idstr_list idstr_list.remove(str(element_id)) reference_index = idstr_list.index(str(reference_id)) idstr_list.insert(reference_index, str(element_id)) return idstr_lis... |
def initialize_logging(args): """Configure the root logger with some sensible defaults.""" log_handler = logging.StreamHandler() log_formatter = logging.Formatter( "%(levelname)s %(asctime)s %(name)s:%(lineno)04d - %(message)s") log_handler.setFormatter(log_formatter) root_logger = logging.getLogger() root_logger.addHa... |
def main(): """Run the bot.""" args = parser.parse_args() initialize_logging(args) # Allow expansion of paths even if the shell doesn't do it config_path = os.path.abspath(os.path.expanduser(args.config)) client = kitnirc.client.Client() controller = kitnirc.modular.Controller(client, config_path) # Make sure the confi... |
= args.nick or config_or_none("server", "nick") if not nick: parser.error( "Nick must be specified if not in config file.") # KitnIRC's default client will use port 6667 if nothing else is specified, # but since we want to potentially specify something else, we add that # fallback here ourselves. port = args.port or co... |
def get_agent_id(self): """Gets the agent ``Id`` who created this entry. return: (osid.id.Id) - the agent ``Id`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_id_template if not bool(self._my_map['agentId']): raise errors.IllegalState('... |
def get_agent(self): """Gets the ``Agent`` who created this entry. return: (osid.authentication.Agent) - the ``Agent`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.Resource.get_avatar_template if not boo... |
def get_priority_metadata(self): """Gets the metadata for a priority type. return: (osid.Metadata) - metadata for the priority *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.logging.LogEntryForm.get_priority_metadata metadata = dict(self._mdata['priority']) metadata... |
def set_priority(self, priority): """Sets the priority. arg: priority (osid.type.Type): the new priority raise: InvalidArgument - ``priority`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``priority`` is ``null`` *compliance: mandatory -- This method must be implemented.* """... |
def clear_priority(self): """Removes the priority. raise: NoAccess - ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.logging.LogEntryForm.clear_priority_template if (self.get_priority_meta... |
def get_timestamp_metadata(self): """Gets the metadata for a timestamp. return: (osid.Metadata) - metadata for the timestamp *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['timestamp']) me... |
def set_timestamp(self, timestamp): """Sets the timestamp. arg: timestamp (osid.calendaring.DateTime): the new timestamp raise: InvalidArgument - ``timestamp`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``timestamp`` is ``null`` *compliance: mandatory -- This method must be... |
def get_agent_metadata(self): """Gets the metadata for the agent. return: (osid.Metadata) - metadata for the agent *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['agent']) metadata.update(... |
def set_agent(self, agent_id): """Sets the agent. arg: agent_id (osid.id.Id): the new agent raise: InvalidArgument - ``agent_id`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``agent_id`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ # Implemente... |
def get_log(self): """Gets the ``Log`` at this node. return: (osid.logging.Log) - the log represented by this node *compliance: mandatory -- This method must be implemented.* """ if self._lookup_session is None: mgr = get_provider_manager('LOGGING', runtime=self._runtime, proxy=self._proxy) self._lookup_session = mgr.g... |
def get_parent_log_nodes(self): """Gets the parents of this log. return: (osid.logging.LogNodeList) - the parents of this log *compliance: mandatory -- This method must be implemented.* """ parent_log_nodes = [] for node in self._my_map['parentNodes']: parent_log_nodes.append(LogNode( node._my_map, runtime=self._runtim... |
def _brace_key(self, key): """ key: 'x' -> '{x}' """ if isinstance(key, six.integer_types): t = str key = t(key) else: t = type(key) return t(u'{') + key + t(u'}') |
def _inject_conversion(self, value, conversion): """ value: '{x}', conversion: 's' -> '{x!s}' """ t = type(value) return value[:-1] + t(u'!') + conversion + t(u'}') |
def _inject_format_spec(self, value, format_spec): """ value: '{x}', format_spec: 'f' -> '{x:f}' """ t = type(value) return value[:-1] + t(u':') + format_spec + t(u'}') |
def _escape(self, bits): """ value: 'foobar {' -> 'foobar {{' value: 'x}' -> 'x}}' """ # for value, field_name, format_spec, conversion in bits: while True: try: value, field_name, format_spec, conversion = next(bits) if value: end = value[-1] if end in (u'{', u'}'): value += end yield value, field_name, format_spec, c... |
def GET(self): """ Show page """ todos = model.get_todos() form = self.form() return render.index(todos, form) |
def POST(self): """ Add new entry """ form = self.form() if not form.validates(): todos = model.get_todos() return render.index(todos, form) model.new_todo(form.d.title) raise web.seeother('/') |
def POST(self, id): """ Delete based on ID """ id = int(id) model.del_todo(id) raise web.seeother('/') |
def _can(self, func_name, qualifier_id=None): """Tests if the named function is authorized with agent and qualifier. Also, caches authz's in a dict. It is expected that this will not grow to big, as there are typically only a small number of qualifier + function combinations to store for the agent. However, if this bec... |
def _can_for_object(self, func_name, object_id, method_name): """Checks if agent can perform function for object""" can_for_session = self._can(func_name) if (can_for_session or self._object_catalog_session is None or self._override_lookup_session is None): return can_for_session override_auths = self._override_lookup_... |
def get_alt_texts_metadata(self): """Gets the metadata for all alt_texts. return: (osid.Metadata) - metadata for the alt_texts *compliance: mandatory -- This method must be implemented.* """ metadata = dict(self._alt_texts_metadata) metadata.update({'existing_string_values': [t['text'] for t in self.my_osid_object_form... |
def add_alt_text(self, alt_text): """Adds an alt_text. arg: alt_text (displayText): the new alt_text raise: InvalidArgument - ``alt_text`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``alt_text`` is ``null`` *compliance: mandatory -- This method must be implemented.* """ if ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.