code stringlengths 1 18.2k |
|---|
def _set_fields(self, positional, options): """ _parse_arguments """ dictionary = {} if positional is not None and options is not None: self.positional = positional.copy() self.options = options.copy() dictionary = positional.copy() dictionary.update(options.copy()) self.m_reprdict = {"positional": positional.copy(), "... |
def set_reprdict_from_attributes(self): """ set_reprdict_from_attributes """ reprcopy = self.m_reprdict.copy() for kd, d in reprcopy.items(): for k in d.keys(): if hasattr(self, k): self.m_reprdict[kd][k] = getattr(self, k) |
def as_yaml(self): """ as_yaml """ self.set_reprdict_from_attributes() return "---\n" + yaml.dump(self.m_reprdict, default_flow_style=False) |
def code(self): """ code """ def uniq(seq): """ @type seq: str @return: None """ seen = set() seen_add = seen.add return [x for x in seq if x not in seen and not seen_add(x)] # noinspection PyTypeChecker a = uniq(i for i in self.autos if i is not None) # noinspection PyTypeChecker e = uniq(i for i in self.errors if i i... |
def make_map(): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('error/:action/:id... |
def django_admin(request): ''' Adds additional information to the context: ``django_admin`` - boolean variable indicating whether the current page is part of the django admin or not. ``ADMIN_URL`` - normalized version of settings.ADMIN_URL; starts with a slash, ends without a slash NOTE: do not set ADMIN_URL='/' in cas... |
def document(self): """Render the error document""" resp = request.environ.get('pylons.original_response') page = error_document_template % \ dict(prefix=request.environ.get('SCRIPT_NAME', ''), code=request.params.get('code', resp.status_int), message=request.params.get('message', resp.body)) return page |
def img(self, id): """Serve Pylons' stock images""" return self._serve_file(os.path.join(media_path, 'img', id)) |
def style(self, id): """Serve Pylons' stock stylesheets""" return self._serve_file(os.path.join(media_path, 'style', id)) |
def _serve_file(self, path): """Call Paste's FileApp (a WSGI application) to serve the file at the specified path """ fapp = paste.fileapp.FileApp(path) return fapp(request.environ, self.start_response) |
def rcfile(appname, args={}, strip_dashes=True, module_name=None): """ Read environment variables and config files and return them merged with predefined list of arguments. Arguments: appname - application name, used for config files and environemnt variable names. args - arguments from command line (optparse, docopt, ... |
strip_dashes: for k in args.keys(): args[k.lstrip('-')] = args.pop(k) environ = get_environment(appname) if not module_name: module_name = appname config = get_config(appname, module_name, args.get('config', '')) return merge(merge(args, config), environ) |
def color_parts(parts): """Adds colors to each part of the citation""" return parts._replace( title=Fore.GREEN + parts.title + Style.RESET_ALL, doi=Fore.CYAN + parts.doi + Style.RESET_ALL ) |
def get_common_parts(r): """Gets citation parts which are common to all types of citation""" title = format_title(r.get('title')) author_list = format_author_list(r.get('author')) container = format_container(r.get('container-title')) date = format_date(r.get('issued')) doi = r.get('DOI') return Parts(type='Unknown', t... |
def safeReadJSON(url, logger, max_check=6, waittime=30): '''Return JSON object from URL''' counter = 0 # try, try and try again .... while counter < max_check: try: with contextlib.closing(urllib.request.urlopen(url)) as f: res = json.loads(f.read().decode('utf8')) return res except Exception as errmsg: logger.info('--... |
def search(self, terms, prelim=True): """Search terms against GNR. If prelim = False, search other datasources \ for alternative names (i.e. synonyms) with which to search main datasource.\ Return JSON object.""" # TODO: There are now lots of additional data sources, make additional # searching optional (11/01/2017) if... |
# search the main source again with alt_terms # replace names in json terms = [each[1] for each in alt_terms] # unzip res = self._resolve(terms, self.Id) self._write(res) alt_res = self._replaceSupStrNames(res, alt_terms) return alt_res |
def theano_compiler(model): """Take a triflow model and return optimized theano routines. Parameters ---------- model: triflow.Model: Model to compile Returns ------- (theano function, theano_function): Optimized routine that compute the evolution equations and their jacobian matrix. """ from theano import tensor as T ... |
= x_th[-1] - x_th[0] dx = L / (N - 1) to_feed['dx'] = dx periodic = T.scalar("periodic", dtype="int32") middle_point = int((model._window_range - 1) / 2) th_args = [mapargs[key] for key in [*model._indep_vars, *model._dep_vars, *model._help_funcs, *model._pars]] + [periodic] map_extended = {} for (varname, discretisati... |
in model._args] ) F = T.concatenate(F, axis=0).reshape((model._nvar, N)).T F = T.stack(F).flatten() J = lambdify((model._symbolic_args), expr=model.J_array.tolist(), modules=[T, {"Max": th_Max, "Min": th_Min, "Heaviside": th_Heaviside}])( *[to_feed[key] for key in model._args] ) J = [j if j != 0 else T.constant(0.) for... |
= rows[:, model._sparse_indices].reshape(J.shape).flatten() cols = extended_idx[cols][:, model._sparse_indices] \ .reshape(J.shape).flatten() permutation = T.argsort(cols) J = J.flatten()[permutation] rows = rows[permutation] cols = cols[permutation] count = T.zeros((N * model._nvar + 1,), dtype=int) uq, cnt = T.extra_... |
def numpy_compiler(model): """Take a triflow model and return optimized numpy routines. Parameters ---------- model: triflow.Model: Model to compile Returns ------- (numpy function, numpy function): Optimized routine that compute the evolution equations and their jacobian matrix. """ def np_Min(args): a, b = args retur... |
def update(self, content): """Enumerates the bytes of the supplied bytearray and updates the CRC-64. No return value. """ for byte in content: self._crc64 = (self._crc64 >> 8) ^ self._lookup_table[(self._crc64 & 0xff) ^ byte] |
def _construct_lookup_table(self, polynomial): """Precomputes a CRC-64 lookup table seeded from the supplied polynomial. No return value. """ self._lookup_table = [] for i in range(0, 256): lookup_value = i for _ in range(0, 8): if lookup_value & 0x1 == 0x1: lookup_value = (lookup_value >> 1) ^ polynomial else: lookup_... |
def makefile(self, mode='r', bufsize=-1): """ Returns a special fileobject that has corutines instead of the usual read/readline/write methods. Will work in the same manner though. """ return _fileobject(Socket( _sock=self._fd._sock, _timeout=self._timeout, _proactor_added=self._proactor_added ), mode, bufsize) |
def send(self, data, **kws): """Send data to the socket. The socket must be connected to a remote socket. Ammount sent may be less than the data provided.""" return yield_(Send(self, data, timeout=self._timeout, **kws)) |
def accept(self, **kws): """Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the co... |
def connect(self, address, **kws): """Connect to a remote socket at _address_. """ return yield_(Connect(self, address, timeout=self._timeout, **kws)) |
def authenticate(identity=None, provider=None): " Authenticate user by net identity. " if not identity: return None try: netid = NetID.objects.get(identity=identity, provider=provider) return netid.user except NetID.DoesNotExist: return None |
def check(ty, val): "Checks that `val` adheres to type `ty`" if isinstance(ty, basestring): ty = Parser().parse(ty) return ty.enforce(val) |
def get_id(self, natural_key, enhancement=None): """ Returns the technical ID for a natural key or None if the given natural key is not valid. :param T natural_key: The natural key. :param T enhancement: Enhancement data of the dimension row. :rtype: int|None """ # If the natural key is known return the technical ID im... |
def get(cls, object_id): """ Get all parties (people and companies) associated with a given tag. :param object_id: the primary id of the model :type object_id: integer :return: the parties :rtype: list """ from highton.models.party import Party return fields.ListField(name=Party.ENDPOINT, init_class=Party).decode( cls.... |
def compute(dvd_path): """Computes a Windows API IDvdInfo2::GetDiscID-compatible 64-bit Cyclic Redundancy Check checksum from the DVD .vob, .ifo and .bup files found in the supplied DVD path. """ _check_dvd_path_exists(dvd_path) _check_video_ts_path_exists(dvd_path) # the polynomial used for this CRC-64 checksum is: # ... |
def _get_video_ts_file_paths(dvd_path): """Returns a sorted list of paths for files contained in th VIDEO_TS folder of the specified DVD path. """ video_ts_folder_path = join(dvd_path, "VIDEO_TS") video_ts_file_paths = [] for video_ts_folder_content_name in listdir(video_ts_folder_path): video_ts_folder_content_path = ... |
def _get_file_creation_time(file_path): """Returns the creation time of the file at the specified file path in Microsoft FILETIME structure format (https://msdn.microsoft.com/en-us/library/windows/desktop/ms724284.aspx), formatted as a 8-byte unsigned integer bytearray. """ ctime = getctime(file_path) if ctime < -11644... |
def _convert_timedelta_to_seconds(timedelta): """Returns the total seconds calculated from the supplied timedelta. (Function provided to enable running on Python 2.6 which lacks timedelta.total_seconds()). """ days_in_seconds = timedelta.days * 24 * 3600 return int((timedelta.microseconds + (timedelta.seconds + days_in... |
def _get_file_size(file_path): """Returns the size of the file at the specified file path, formatted as a 4-byte unsigned integer bytearray. """ size = getsize(file_path) file_size = bytearray(4) pack_into(b"I", file_size, 0, size) return file_size |
def _get_file_name(file_path): """Returns the name of the file at the specified file path, formatted as a UTF-8 bytearray terminated with a null character. """ file_name = basename(file_path) utf8_file_name = bytearray(file_name, "utf8") utf8_file_name.append(0) return utf8_file_name |
def _get_first_64k_content(file_path): """Returns the first 65536 (or the file size, whichever is smaller) bytes of the file at the specified file path, as a bytearray. """ if not isfile(file_path): raise PathDoesNotExistException(file_path) file_size = getsize(file_path) content_size = min(file_size, 0x10000) content ... |
def parseArgs(): """Read arguments""" parser = argparse.ArgumentParser() parser.add_argument("-names", "-n", help=".txt file of taxonomic names") parser.add_argument("-datasource", "-d", help="taxonomic datasource by \ which names will be resolved (default NCBI)") parser.add_argument("-taxonid", "-t", help="parent taxo... |
def logSysInfo(): """Write system info to log file""" logger.info('#' * 70) logger.info(datetime.today().strftime("%A, %d %B %Y %I:%M%p")) logger.info('Running on [{0}] [{1}]'.format(platform.node(), platform.platform())) logger.info('Python [{0}]'.format(sys.version)) logger.info('#' * 70 + '\n') |
def logEndTime(): """Write end info to log""" logger.info('\n' + '#' * 70) logger.info('Complete') logger.info(datetime.today().strftime("%A, %d %B %Y %I:%M%p")) logger.info('#' * 70 + '\n') |
def get_config(section, option, allow_empty_option=True, default=""): ''' Get data from configs ''' try: value = config.get(section, option) if value is None or len(value) == 0: if allow_empty_option: return "" else: return default else: return value except ConfigParser.NoSectionError: return default |
def getboolean_config(section, option, default=False): ''' Get data from configs which store boolean records ''' try: return config.getboolean(section, option) or default except ConfigParser.NoSectionError: return default |
def populate_values(self, rows, field): """ Populates the filter values of this filter using list of rows. :param list[dict[str,T]] rows: The row set. :param str field: The field name. """ self._values.clear() for row in rows: condition = SimpleConditionFactory.create_condition(self._field, row[field]) if condition.sch... |
def match(self, row): """ Returns True if the field is in the list of conditions. Returns False otherwise. :param dict row: The row. :rtype: bool """ if row[self._field] in self._values: return True for condition in self._conditions: if condition.match(row): return True return False |
def solveAndNotify(proto, exercise): """The user at the given AMP protocol has solved the given exercise. This will log the solution and notify the user. """ exercise.solvedBy(proto.user) proto.callRemote(ce.NotifySolved, identifier=exercise.identifier, title=exercise.title) |
def solvedBy(self, user): """Stores that this user has just solved this exercise. You probably want to notify the user when this happens. For that, see ``solveAndNotify``. """ _Solution(store=self.store, who=user, what=self) |
def wasSolvedBy(self, user): """Checks if this exercise has previously been solved by the user. """ thisExercise = _Solution.what == self byThisUser = _Solution.who == user condition = q.AND(thisExercise, byThisUser) return self.store.query(_Solution, condition, limit=1).count() == 1 |
def getExerciseDetails(self, identifier): """Gets the details for a particular exercise. """ exercise = self._getExercise(identifier) response = { b"identifier": exercise.identifier, b"title": exercise.title, b"description": exercise.description, b"solved": exercise.wasSolvedBy(self.user) } return response |
def solveAndNotify(self, request): """Notifies the owner of the current request (so, the user doing the exercise) that they've solved the exercise, and mark it as solved in the database. """ remote = request.transport.remote withThisIdentifier = Exercise.identifier == self.exerciseIdentifier exercise = self.store.findU... |
def split(s): """ Split a string into a list, respecting any quoted strings inside Uses ``shelx.split`` which has a bad habbit of inserting null bytes where they are not wanted """ return map(lambda w: filter(lambda c: c != '\x00', w), lexsplit(s)) |
def lookup(parser, var, context, resolve=True, apply_filters=True): """ Try to resolve the varialbe in a context If ``resolve`` is ``False``, only string variables are returned """ if resolve: try: return Variable(var).resolve(context) except VariableDoesNotExist: if apply_filters and var.find('|') > -1: return parser.... |
def get_cache_key(bucket, name, args, kwargs): """ Gets a unique SHA1 cache key for any call to a native tag. Use args and kwargs in hash so that the same arguments use the same key """ u = ''.join(map(str, (bucket, name, args, kwargs))) return 'native_tags.%s' % sha_constructor(u).hexdigest() |
def get_signature(token, contextable=False, comparison=False): """ Gets the signature tuple for any native tag contextable searchs for ``as`` variable to update context comparison if true uses ``negate`` (p) to ``not`` the result (~p) returns (``tag_name``, ``args``, ``kwargs``) """ bits = split(token.contents) args, k... |
def do_comparison(parser, token): """ Compares passed arguments. Attached functions should return boolean ``True`` or ``False``. If the attached function returns ``True``, the first node list is rendered. If the attached function returns ``False``, the second optional node list is rendered (part after the ``{% else %}`... |
an id less than 3. {% endif_less %} {% if_match request.path '^/$' %} Welcome home {% endif_match %} """ name, args, kwargs = get_signature(token, comparison=True) name = name.replace('if_if', 'if') end_tag = 'end' + name kwargs['nodelist_true'] = parser.parse(('else', end_tag)) token = parser.next_token() if token.con... |
def do_function(parser, token): """ Performs a defined function on the passed arguments. Normally this returns the output of the function into the template. If the second to last argument is ``as``, the result of the function is stored in the context and is named whatever the last argument is. Syntax:: {% [function] [v... |
def do_block(parser, token): """ Process several nodes inside a single block Block functions take ``context``, ``nodelist`` as first arguments If the second to last argument is ``as``, the rendered result is stored in the context and is named whatever the last argument is. Syntax:: {% [block] [var args...] [name=value ... |
def process_attributes_of_node(attrs, node_name, class_type): """ prepare the model fields, nodes and relations Args: node_name (str): name of the node we are currently processing attrs (dict): attribute dict class_type (str): Type of class. Can be one of these: 'ListNode', 'Model', 'Node' """ # print("Node: %s" % node... |
attrs['_nodes'][key] = attrs[key] else: # otherwise it should be a field or linked model attr_type = getattr(attr, '_TYPE', '') if attr_type == 'Model': attrs['%s_id' % key] = '' # lnk_mdl_ins = attrs.pop(key) lnk_mdl_ins = attrs[key] lnk = { 'null': lnk_mdl_ins.null or class_type == 'ListNode', 'link_source': True, 'm... |
def process_models(attrs, base_model_class): """ Attach default fields and meta options to models """ attrs.update(base_model_class._DEFAULT_BASE_FIELDS) attrs['_instance_registry'] = set() attrs['_is_unpermitted_fields_set'] = False attrs['save_meta_data'] = None attrs['_pre_save_hook_called'] = False attrs['_post_sav... |
def process_objects(kls): """ Applies default Meta properties. """ # first add a Meta object if not exists if 'Meta' not in kls.__dict__: kls.Meta = type('Meta', (object,), {}) if 'unique_together' not in kls.Meta.__dict__: kls.Meta.unique_together = [] # set verbose_name(s) if not already set if 'verbose_name' not in ... |
async def get_user(username: str, api_key: str, **kwargs) -> User: """ Creates a new user, validate its credentials and returns it |funccoro| Args: username: username as specified on the challonge website api_key: key as found on the challonge `settings <https://challonge.com/settings/developer>`_ Returns: User: a logg... |
async def get_tournament(self, t_id: int = None, url: str = None, subdomain: str = None, force_update=False) -> Tournament: """ gets a tournament with its id or url or url+subdomain Note: from the API, it can't be known if the retrieved tournament was made from this user. Thus, any tournament is added to the local list... |
of t_id or url must not be None') found_t = self._find_tournament_by_id(t_id) if t_id is not None else self._find_tournament_by_url(url, subdomain) if force_update or found_t is None: param = t_id if param is None: if subdomain is not None: param = '{}-{}'.format(subdomain, url) else: param = url res = await self.conne... |
async def get_tournaments(self, subdomain: str = None, force_update: bool = False) -> list: """ gets all user's tournaments |methcoro| Args: subdomain: *optional* subdomain needs to be given explicitely to get tournaments in a subdomain force_update: *optional* set to True to force the data update from Challonge Return... |
'tournaments', **params) if len(res) == 0: self.tournaments = [] else: for t_data in res: self._refresh_tournament_from_json(t_data) return self.tournaments |
async def create_tournament(self, name: str, url: str, tournament_type: TournamentType = TournamentType.single_elimination, **params) -> Tournament: """ creates a simple tournament with basic options |methcoro| Args: name: name of the new tournament url: url of the new tournament (http://challonge.com/url) tournament_t... |
async def destroy_tournament(self, t: Tournament): """ completely removes a tournament from Challonge |methcoro| Note: |from_api| Deletes a tournament along with all its associated records. There is no undo, so use with care! Raises: APIException """ await self.connection('DELETE', 'tournaments/{}'.format(t.id)) if t i... |
def ub_to_str(string): """ converts py2 unicode / py3 bytestring into str Args: string (unicode, byte_string): string to be converted Returns: (str) """ if not isinstance(string, str): if six.PY2: return str(string) else: return string.decode() return string |
def to_camel(s): """ :param string s: under_scored string to be CamelCased :return: CamelCase version of input :rtype: str """ # r'(?!^)_([a-zA-Z]) original regex wasn't process first groups return re.sub(r'_([a-zA-Z])', lambda m: m.group(1).upper(), '_' + s) |
def get_object_from_path(path): """ Import's object from given Python path. """ try: return sys.IMPORT_CACHE[path] except KeyError: _path = path.split('.') module_path = '.'.join(_path[:-1]) class_name = _path[-1] module = importlib.import_module(module_path) sys.IMPORT_CACHE[path] = getattr(module, class_name) return ... |
def pprnt(input, return_data=False): """ Prettier print for nested data Args: input: Input data return_data (bool): Default False. Print outs if False, returns if True. Returns: None | Pretty formatted text representation of input data. """ HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[32m' WARNING = '\033[93... |
def wrapped_sendfile(act, offset, length): """ Calls the sendfile system call or simulate with file read and socket send if unavailable. """ if sendfile: offset, sent = sendfile.sendfile( act.sock.fileno(), act.file_handle.fileno(), offset, length ) else: act.file_handle.seek(offset) sent = act.sock._fd.send(act.file_h... |
def set_options(self, multiplex_first=True, **bogus_options): "Takes implementation specific options. To be overriden in a subclass." self.multiplex_first = multiplex_first self._warn_bogus_options(**bogus_options) |
def _warn_bogus_options(self, **opts): """ Shows a warning for unsupported options for the current implementation. Called form set_options with remainig unsupported options. """ if opts: import warnings for i in opts: warnings.warn("Unsupported option %s for %s" % (i, self), stacklevel=2) |
def request_connect(self, act, coro): "Requests a connect for `coro` corutine with parameters and completion \ passed via `act`" result = self.try_run_act(act, perform_connect) if result: return result, coro else: self.add_token(act, coro, perform_connect) |
def request_generic(self, act, coro, perform): """ Requests an socket operation (in the form of a callable `perform` that does the actual socket system call) for `coro` corutine with parameters and completion passed via `act`. The socket operation request parameters are passed in `act`. When request is completed the re... |
def add_token(self, act, coro, performer): """ Adds a completion token `act` in the proactor with associated `coro` corutine and perform callable. """ assert act not in self.tokens act.coro = coro self.tokens[act] = performer self.register_fd(act, performer) |
def remove_token(self, act): """ Remove a token from the proactor. If removal succeeds (the token is in the proactor) return True. """ if act in self.tokens: self.unregister_fd(act) del self.tokens[act] return True else: import warnings warnings.warn("%s isn't a registered token." % act) |
def handle_event(self, act): """ Handle completion for a request. Calls the scheduler to run or schedule the associated coroutine. """ scheduler = self.scheduler if act in self.tokens: coro = act.coro op = self.try_run_act(act, self.tokens[act]) if op: del self.tokens[act] if scheduler.ops_greedy: while True: op, coro ... |
def yield_event(self, act): """ Hande completion for a request and return an (op, coro) to be passed to the scheduler on the last completion loop of a proactor. """ if act in self.tokens: coro = act.coro op = self.try_run_act(act, self.tokens[act]) if op: del self.tokens[act] return op, coro |
def handle_error_event(self, act, detail, exc=SocketError): """ Handle an errored event. Calls the scheduler to schedule the associated coroutine. """ del self.tokens[act] self.scheduler.active.append(( CoroutineException(exc, exc(detail)), act.coro )) |
def add_to_dumper(dumper: Type, classes: List[Type]) -> None: """Register user-defined classes with the Dumper. This enables the Dumper to write objects of your classes to a \ YAML file. Note that all the arguments are types, not instances! Args: dumper: Your dumper class(!), derived from yatiml.Dumper classes: One or ... |
def sparql(self, stringa): """ wrapper around a sparql query """ qres = self.rdfgraph.query(stringa) return list(qres) |
def _scan(self, verbose=False, hide_base_schemas=True): """ scan a source of RDF triples build all the objects to deal with the ontology/ies pythonically """ if verbose: printDebug("Scanning entities...", "green") printDebug("----------", "comment") self.__extractOntologies() if verbose: printDebug("Ontologies............ |
def stats(self): """ shotcut to pull out useful info for a graph 2016-08-18 the try/except is a dirty solution to a problem emerging with counting graph lenght on cached Graph objects.. TODO: investigate what's going on.. """ out = [] try: out += [("Triples", len(self.rdfgraph))] except: pass out += [("Classes", len(se... |
def __extractOntologies(self, exclude_BNodes = False, return_string=False): """ returns Ontology class instances [ a owl:Ontology ; vann:preferredNamespacePrefix "bsym" ; vann:preferredNamespaceUri "http://bsym.bloomberg.com/sym/" ], """ out = [] qres = self.queryHelper.getOntology() if qres: # NOTE: SPARQL returns a l... |
def __extractClasses(self, hide_base_schemas=True): """ 2015-06-04: removed sparql 1.1 queries 2015-05-25: optimized via sparql queries in order to remove BNodes 2015-05-09: new attempt Note: queryHelper.getAllClasses() returns a list of tuples, (class, classRDFtype) so in some cases there are duplicates if a class is ... |
mini graph aClass.queryHelper = self.queryHelper # attach to an ontology for uri in aClass.getValuesForProperty(rdflib.RDFS.isDefinedBy): onto = self.getOntology(uri) if onto: onto.classes += [aClass] aClass.ontology = onto # add direct Supers directSupers = self.queryHelper.getClassDirectSupers(aClass.uri) for x in di... |
def __extractProperties(self): """ 2015-06-04: removed sparql 1.1 queries 2015-06-03: analogous to get classes # instantiate properties making sure duplicates are pruned # but the most specific rdftype is kept # eg OWL:ObjectProperty over RDF:property """ self.properties = [] # @todo: keep adding? self.annotationProper... |
an ontology [2015-06-15: no property type distinction yet] for uri in aProp.getValuesForProperty(rdflib.RDFS.isDefinedBy): onto = self.getOntology(str(uri)) if onto: onto.properties += [aProp] aProp.ontology = onto self.__buildDomainRanges(aProp) # add direct Supers directSupers = self.queryHelper.getPropDirectSupers(a... |
def __buildDomainRanges(self, aProp): """ extract domain/range details and add to Python objects """ domains = aProp.rdfgraph.objects(None, rdflib.RDFS.domain) ranges = aProp.rdfgraph.objects(None, rdflib.RDFS.range) for x in domains: if not isBlankNode(x): aClass = self.getClass(uri=str(x)) if aClass: aProp.domains +=... |
def __extractSkosConcepts(self): """ 2015-08-19: first draft """ self.skosConcepts = [] # @todo: keep adding? qres = self.queryHelper.getSKOSInstances() for candidate in qres: test_existing_cl = self.getSkosConcept(uri=candidate[0]) if not test_existing_cl: # create it self.skosConcepts += [OntoSKOSConcept(candidate[0]... |
def getInferredPropertiesForClass(self, aClass, rel="domain_of"): """ returns all properties valid for a class (as they have it in their domain) recursively ie traveling up the descendants tree Note: results in a list of dicts including itself Note [2]: all properties with no domain info are added at the top as [None, ... |
for p in self.properties if p.ranges == []] if topLevelProps: _list.append({self.OWLTHING: topLevelProps}) return _list |
def getClass(self, id=None, uri=None, match=None): """ get the saved-class with given ID or via other methods... Note: it tries to guess what is being passed.. In [1]: g.getClass(uri='http://www.w3.org/2000/01/rdf-schema#Resource') Out[1]: <Class *http://www.w3.org/2000/01/rdf-schema#Resource*> In [2]: g.getClass(10) O... |
x.id == id: return x if uri and x.uri.lower() == uri.lower(): return x return None |
def getProperty(self, id=None, uri=None, match=None): """ get the saved-class with given ID or via other methods... Note: analogous to getClass method """ if not id and not uri and not match: return None if type(id) == type("string"): uri = id id = None if not uri.startswith("http://"): match = uri uri = None if match:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.