Search is not available for this dataset
text
stringlengths
75
104k
def get_defining_component(pe_pe): ''' Get the BridgePoint component (C_C) that defines the packeable element *pe_pe*. ''' if pe_pe is None: return None if type(pe_pe).__name__ != 'PE_PE': pe_pe = one(pe_pe).PE_PE[8001]() ep_pkg = one(pe_pe).EP_PKG[8000]() if ep...
def get_attribute_type(o_attr): ''' Get the base data type (S_DT) associated with a BridgePoint attribute. ''' ref_o_attr = one(o_attr).O_RATTR[106].O_BATTR[113].O_ATTR[106]() if ref_o_attr: return get_attribute_type(ref_o_attr) else: return one(o_attr).S_DT[114]()
def _get_data_type_name(s_dt): ''' Convert a BridgePoint data type to a pyxtuml meta model type. ''' s_cdt = one(s_dt).S_CDT[17]() if s_cdt and s_cdt.Core_Typ in range(1, 6): return s_dt.Name.upper() if one(s_dt).S_EDT[17](): return 'INTEGER' s_dt = one(s_dt).S_UDT[...
def _get_related_attributes(r_rgo, r_rto): ''' The two lists of attributes which relates two classes in an association. ''' l1 = list() l2 = list() ref_filter = lambda ref: ref.OIR_ID == r_rgo.OIR_ID for o_ref in many(r_rto).O_RTIDA[110].O_REF[111](ref_filter): o_attr = one(o_re...
def mk_enum(s_edt): ''' Create a named tuple from a BridgePoint enumeration. ''' s_dt = one(s_edt).S_DT[17]() enums = list() kwlist =['False', 'None', 'True'] + keyword.kwlist for enum in many(s_edt).S_ENUM[27](): if enum.Name in kwlist: enums.append(enum.Name + '_') ...
def mk_bridge(metamodel, s_brg): ''' Create a python function from a BridgePoint bridge. ''' action = s_brg.Action_Semantics_internal label = s_brg.Name return lambda **kwargs: interpret.run_function(metamodel, label, action, kwargs)
def mk_external_entity(metamodel, s_ee): ''' Create a python object from a BridgePoint external entity with bridges realized as python member functions. ''' bridges = many(s_ee).S_BRG[19]() names = [brg.Name for brg in bridges] EE = collections.namedtuple(s_ee.Key_Lett, names) funcs = l...
def mk_function(metamodel, s_sync): ''' Create a python function from a BridgePoint function. ''' action = s_sync.Action_Semantics_internal label = s_sync.Name return lambda **kwargs: interpret.run_function(metamodel, label, action, kwargs)
def mk_constant(cnst_syc): ''' Create a python value from a BridgePoint constant. ''' s_dt = one(cnst_syc).S_DT[1500]() cnst_lsc = one(cnst_syc).CNST_LFSC[1502].CNST_LSC[1503]() if s_dt.Name == 'boolean': return cnst_lsc.Value.lower() == 'true' if s_dt.Name == 'integer': ...
def mk_operation(metaclass, o_tfr): ''' Create a python function that interprets that action of a BridgePoint class operation. ''' o_obj = one(o_tfr).O_OBJ[115]() action = o_tfr.Action_Semantics_internal label = '%s::%s' % (o_obj.Name, o_tfr.Name) run = interpret.run_operation i...
def mk_derived_attribute(metaclass, o_dbattr): ''' Create a python property that interprets that action of a BridgePoint derived attribute. ''' o_attr = one(o_dbattr).O_BATTR[107].O_ATTR[106]() o_obj = one(o_attr).O_OBJ[102]() action = o_dbattr.Action_Semantics_internal label = '%s::%s' ...
def mk_class(m, o_obj, derived_attributes=False): ''' Create a pyxtuml class from a BridgePoint class. ''' first_filter = lambda selected: not one(selected).O_ATTR[103, 'succeeds']() o_attr = one(o_obj).O_ATTR[102](first_filter) attributes = list() while o_attr: s_dt = get_a...
def mk_simple_association(m, r_simp): ''' Create a pyxtuml association from a simple association in BridgePoint. ''' r_rel = one(r_simp).R_REL[206]() r_form = one(r_simp).R_FORM[208]() r_part = one(r_simp).R_PART[207]() r_rgo = one(r_form).R_RGO[205]() r_rto = one(r_part).R_RTO[204...
def mk_linked_association(m, r_assoc): ''' Create pyxtuml associations from a linked association in BridgePoint. ''' r_rel = one(r_assoc).R_REL[206]() r_rgo = one(r_assoc).R_ASSR[211].R_RGO[205]() source_o_obj = one(r_rgo).R_OIR[203].O_OBJ[201]() def _mk_assoc(side1, side2): r_r...
def mk_subsuper_association(m, r_subsup): ''' Create pyxtuml associations from a sub/super association in BridgePoint. ''' r_rel = one(r_subsup).R_REL[206]() r_rto = one(r_subsup).R_SUPER[212].R_RTO[204]() target_o_obj = one(r_rto).R_OIR[203].O_OBJ[201]() for r_sub in many(r_subsup).R_S...
def mk_association(m, r_rel): ''' Create a pyxtuml association from a R_REL in ooaofooa. ''' handler = { 'R_SIMP': mk_simple_association, 'R_ASSOC': mk_linked_association, 'R_SUBSUP': mk_subsuper_association, 'R_COMP': mk_derived_association, } inst = subtype(r_re...
def mk_component(bp_model, c_c=None, derived_attributes=False): ''' Create a pyxtuml meta model from a BridgePoint model. Optionally, restrict to classes and associations contained in the component c_c. ''' target = Domain() c_c_filt = lambda sel: c_c is None or is_contained_in(sel, c_c) ...
def load_metamodel(resource=None, load_globals=True): ''' Load and return a metamodel expressed in ooaofooa from a *resource*. The resource may be either a filename, a path, or a list of filenames and/or paths. ''' loader = _mk_loader(resource, load_globals) return loader.build_metamodel()
def load_component(resource, name=None, load_globals=True): ''' Load and return a model from a *resource*. The resource may be either a filename, a path, or a list of filenames and/or paths. ''' loader = _mk_loader(resource, load_globals) return loader.build_component()
def delete_globals(m, disconnect=False): ''' Remove global instances, e.g. the core data type integer. ''' filt = lambda sel: (247728914420827907967735776184937480192 <= sel.DT_ID <= 247728914420827907967735776184937480208) for s_dt in m.select_many...
def filename_input(self, path_or_filename): ''' Open and read input from a *path or filename*, and parse its content. If the filename is a directory, files that ends with .xtuml located somewhere in the directory or sub directories will be loaded as well. ''' if ...
def build_component(self, name=None, derived_attributes=False): ''' Instantiate and build a component from ooaofooa named *name* as a pyxtuml model. Classes, associations, attributes and unique identifers, i.e. O_OBJ, R_REL, O_ATTR in ooaofooa, are defined in the resulting pyxtum...
def default_malformed_message_handler(worker, exc_info, message_parts): """The default malformed message handler for :class:`Worker`. It warns as a :exc:`MalformedMessage`. """ exc_type, exc, tb = exc_info exc_strs = traceback.format_exception_only(exc_type, exc) exc_str = exc_strs[0].strip() ...
def work(self, socket, call, args, kwargs, topics=()): """Calls a function and send results to the collector. It supports all of function actions. A function could return, yield, raise any packable objects. """ task_id = uuid4_bytes() reply_socket, topics = self.replier...
def accept(self, reply_socket, channel): """Sends ACCEPT reply.""" info = self.info or b'' self.send_raw(reply_socket, ACCEPT, info, *channel)
def reject(self, reply_socket, call_id, topics=()): """Sends REJECT reply.""" info = self.info or b'' self.send_raw(reply_socket, REJECT, info, call_id, b'', topics)
def raise_(self, reply_socket, channel, exc_info=None): """Sends RAISE reply.""" if not reply_socket: return if exc_info is None: exc_info = sys.exc_info() exc_type, exc, tb = exc_info while tb.tb_next is not None: tb = tb.tb_next if is...
def _call_wait(self, hints, name, args, kwargs, topics=(), raw=False, limit=None, retry=False, max_retries=None): """Allocates a call id and emit.""" col = self.collector if not col.is_running(): col.start() call_id = uuid4_bytes() reply_to = (DUPLE...
def establish(self, call_id, timeout, limit=None, retry=None, max_retries=None): """Waits for the call is accepted by workers and starts to collect the results. """ rejected = 0 retried = 0 results = [] result_queue = self.result_queues[call_id] ...
def dispatch_reply(self, reply, value): """Dispatches the reply to the proper queue.""" method = reply.method call_id = reply.call_id task_id = reply.task_id if method & ACK: try: result_queue = self.result_queues[call_id] except KeyError: ...
def guess_type_name(value): ''' Guess the type name of a serialized value. ''' value = str(value) if value.upper() in ['TRUE', 'FALSE']: return 'BOOLEAN' elif re.match(r'(-)?(\d+)(\.\d+)', value): return 'REAL' elif re.match(r'(-)?(\d+)', value): return...
def deserialize_value(ty, value): ''' Deserialize a value of some type ''' uty = ty.upper() if uty == 'BOOLEAN': if value.isdigit(): return bool(int(value)) elif value.upper() == 'FALSE': return False elif value.upper() == 'TRUE': retu...
def load_metamodel(resource): ''' Load and return a metamodel from a *resource*. The *resource* may be either a filename, or a list of filenames. Usage example: >>> metamodel = xtuml.load_metamodel(['schema.sql', 'data.sql']) ''' if isinstance(resource, str): resource = [re...
def input(self, data, name='<string>'): ''' Parse *data* directly from a string. The *name* is used when reporting positional information if the parser encounter syntax errors. ''' lexer = lex.lex(debuglog=logger, errorlog=logger, o...
def file_input(self, file_object): ''' Read and parse data from a *file object*, i.e. the type of object returned by the builtin python function *open()*. ''' return self.input(file_object.read(), name=file_object.name)
def populate_classes(self, metamodel): ''' Populate a *metamodel* with classes previously encountered from input. ''' for stmt in self.statements: if isinstance(stmt, CreateClassStmt): metamodel.define_class(stmt.kind, stmt.attributes)
def populate_associations(self, metamodel): ''' Populate a *metamodel* with associations previously encountered from input. ''' for stmt in self.statements: if not isinstance(stmt, CreateAssociationStmt): continue ass = metamod...
def populate_unique_identifiers(self, metamodel): ''' Populate a *metamodel* with class unique identifiers previously encountered from input. ''' for stmt in self.statements: if isinstance(stmt, CreateUniqueStmt): metamodel.define_unique_identifier(stm...
def _populate_matching_class(metamodel, kind, names, values): ''' Populate a *metamodel* with a class that matches the given *insert statement*. ''' attributes = list() for name, value in zip(names, values): ty = guess_type_name(value) attr = (name...
def _populate_instance_with_positional_arguments(metamodel, stmt): ''' Populate a *metamodel* with an instance previously encountered from input that was defined using positional arguments. ''' if stmt.kind.upper() not in metamodel.metaclasses: names = ['_%s' % idx f...
def _populate_instance_with_named_arguments(metamodel, stmt): ''' Populate a *metamodel* with an instance previously encountered from input that was defined using named arguments. ''' if stmt.kind.upper() not in metamodel.metaclasses: ModelLoader._populate_matching_c...
def populate_instances(self, metamodel): ''' Populate a *metamodel* with instances previously encountered from input. ''' for stmt in self.statements: if not isinstance(stmt, CreateInstanceStmt): continue if stmt.names: ...
def populate_connections(self, metamodel): ''' Populate links in a *metamodel* with connections between them. ''' storage = dict() for ass in metamodel.associations: source_class = ass.source_link.to_metaclass target_class = ass.target_link.to_metaclass ...
def populate(self, metamodel): ''' Populate a *metamodel* with entities previously encountered from input. ''' self.populate_classes(metamodel) self.populate_unique_identifiers(metamodel) self.populate_associations(metamodel) self.populate_instances(metamodel) ...
def build_metamodel(self, id_generator=None): ''' Build and return a *xtuml.MetaModel* containing previously loaded input. ''' m = xtuml.MetaModel(id_generator) self.populate(m) return m
def t_COMMA(self, t): r',' t.endlexpos = t.lexpos + len(t.value) return t
def t_FRACTION(self, t): r'(\d+)(\.\d+)' t.endlexpos = t.lexpos + len(t.value) return t
def t_RELID(self, t): r'R[0-9]+' t.endlexpos = t.lexpos + len(t.value) return t
def t_CARDINALITY(self, t): r'(1C)' t.endlexpos = t.lexpos + len(t.value) return t
def t_ID(self, t): r'[A-Za-z_][\w_]*' vup = t.value.upper() if vup in self.reserved: t.type = vup t.endlexpos = t.lexpos + len(t.value) return t
def t_LPAREN(self, t): r'\(' t.endlexpos = t.lexpos + len(t.value) return t
def t_MINUS(self, t): r'-' t.endlexpos = t.lexpos + len(t.value) return t
def t_NUMBER(self, t): r'[0-9]+' t.endlexpos = t.lexpos + len(t.value) return t
def t_RPAREN(self, t): r'\)' t.endlexpos = t.lexpos + len(t.value) return t
def t_SEMICOLON(self, t): r';' t.endlexpos = t.lexpos + len(t.value) return t
def t_GUID(self, t): r'\"([^\\\n]|(\\.))*?\"' t.endlexpos = t.lexpos + len(t.value) return t
def t_newline(self, t): r'\n+' t.lexer.lineno += len(t.value) t.endlexpos = t.lexpos + len(t.value)
def p_statement(self, p): ''' statement : create_table_statement SEMICOLON | insert_into_statement SEMICOLON | create_rop_statement SEMICOLON | create_index_statement SEMICOLON ''' p[0] = p[1] p[0].offset = p.lexpos(1) ...
def p_create_rop_statement(self, p): '''create_rop_statement : CREATE ROP REF_ID RELID FROM association_end TO association_end''' args = [p[4]] args.extend(p[6]) args.extend(p[8]) p[0] = CreateAssociationStmt(*args)
def p_cardinality_1(self, p): '''cardinality : NUMBER''' if p[1] != '1': raise ParsingException("illegal cardinality (%s) at %s:%d" % (p[1], p.lexer.filename, p.lineno(1))) p[0] = p[1]
def p_cardinality_many(self, p): '''cardinality : ID''' if p[1] not in ['M', 'MC']: raise ParsingException("illegal cardinality (%s) at %s:%d" % (p[1], p.lexer.filename, p.lineno(1))) p[0] = p[1]
def append_known_secrets(self): # type: () -> None """ Read key-value pair files with secrets. For example, .conf and .ini files. :return: """ for file_name in self.files: if "~" in file_name: file_name = os.path.expanduser(file_name) if n...
def search_known_secrets(self): # type: () -> None """ Search a path for known secrets, outputing text and file when found :return: """ count = 0 here = os.path.abspath(self.source) # python 3 only! # for file in glob.glob(here + "/" + "**/*.*", recursive...
def eid(s): '''Encode id (bytes) as a Unicode string. The encoding is done such that lexicographic order is preserved. No concern is given to wasting space. The inverse of ``eid`` is ``did``. ''' if isinstance(s, unicode): s = s.encode('utf-8') return u''.join('{:02x}'.format(ord(b...
def did(s): '''Decode id (Unicode string) as a bytes. The inverse of ``did`` is ``eid``. ''' return ''.join(chr(int(s[i:i+2], base=16)) for i in xrange(0, len(s), 2))
def get(self, content_id, feature_names=None): '''Retrieve a feature collection. If a feature collection with the given id does not exist, then ``None`` is returned. :param str content_id: Content identifier. :param [str] feature_names: A list of feature names to retr...
def get_many(self, content_ids, feature_names=None): '''Returns an iterable of feature collections. This efficiently retrieves multiple FCs corresponding to the list of ids given. Tuples of identifier and feature collection are yielded. If the feature collection for a given id does not ...
def put(self, items, indexes=True): '''Adds feature collections to the store. This efficiently adds multiple FCs to the store. The iterable of ``items`` given should yield tuples of ``(content_id, FC)``. :param items: Iterable of ``(content_id, FC)``. :param [str] feature_names...
def delete(self, content_id): '''Deletes the corresponding feature collection. If the FC does not exist, then this is a no-op. ''' try: self.conn.delete(index=self.index, doc_type=self.type, id=eid(content_id)) except NotFoundError: ...
def delete_all(self): '''Deletes all feature collections. This does not destroy the ES index, but instead only deletes all FCs with the configured document type (defaults to ``fc``). ''' try: self.conn.indices.delete_mapping( index=self.index,...
def delete_index(self): '''Deletes the underlying ES index. Only use this if you know what you're doing. This destroys the entire underlying ES index, which could be shared by multiple distinct ElasticStore instances. ''' if self.conn.indices.exists(index=self.index): ...
def scan(self, *key_ranges, **kwargs): '''Scan for FCs in the given id ranges. :param key_ranges: ``key_ranges`` should be a list of pairs of ranges. The first value is the lower bound id and the second value is the upper bound id. Use ``()`` in either position to leave it...
def scan_ids(self, *key_ranges, **kwargs): '''Scan for ids only in the given id ranges. :param key_ranges: ``key_ranges`` should be a list of pairs of ranges. The first value is the lower bound id and the second value is the upper bound id. Use ``()`` in either position to...
def scan_prefix(self, prefix, feature_names=None): '''Scan for FCs with a given prefix. :param str prefix: Identifier prefix. :param [str] feature_names: A list of feature names to retrieve. When ``None``, all features are retrieved. Wildcards are allowed. :rtype: It...
def scan_prefix_ids(self, prefix): '''Scan for ids with a given prefix. :param str prefix: Identifier prefix. :param [str] feature_names: A list of feature names to retrieve. When ``None``, all features are retrieved. Wildcards are allowed. :rtype: Iterable of ``cont...
def fulltext_scan(self, query_id=None, query_fc=None, feature_names=None, preserve_order=True, indexes=None): '''Fulltext search. Yields an iterable of triples (score, identifier, FC) corresponding to the search results of the fulltext search in ``query``. This wil...
def fulltext_scan_ids(self, query_id=None, query_fc=None, preserve_order=True, indexes=None): '''Fulltext search for identifiers. Yields an iterable of triples (score, identifier) corresponding to the search results of the fulltext search in ``query``. This wil...
def keyword_scan(self, query_id=None, query_fc=None, feature_names=None): '''Keyword scan for feature collections. This performs a keyword scan using the query given. A keyword scan searches for FCs with terms in each of the query's indexed fields. At least one of ``query_id`` ...
def keyword_scan_ids(self, query_id=None, query_fc=None): '''Keyword scan for ids. This performs a keyword scan using the query given. A keyword scan searches for FCs with terms in each of the query's indexed fields. At least one of ``query_id`` or ``query_fc`` must be provided...
def index_scan_ids(self, fname, val): '''Low-level keyword index scan for ids. Retrieves identifiers of FCs that have a feature value ``val`` in the feature named ``fname``. Note that ``fname`` must be indexed. :param str fname: Feature name. :param str val: Feature val...
def _source(self, feature_names): '''Maps feature names to ES's "_source" field.''' if feature_names is None: return True elif isinstance(feature_names, bool): return feature_names else: return map(lambda n: 'fc.' + n, feature_names)
def _range_filters(self, *key_ranges): 'Creates ES filters for key ranges used in scanning.' filters = [] for s, e in key_ranges: if isinstance(s, basestring): s = eid(s) if isinstance(e, basestring): # Make the range inclusive. ...
def _create_index(self): 'Create the index' try: self.conn.indices.create( index=self.index, timeout=60, request_timeout=60, body={ 'settings': { 'number_of_shards': self.shards, 'number_of_replicas': self.re...
def _create_mappings(self): 'Create the field type mapping.' self.conn.indices.put_mapping( index=self.index, doc_type=self.type, timeout=60, request_timeout=60, body={ self.type: { 'dynamic_templates': [{ 'd...
def _get_index_mappings(self): 'Retrieve the field mappings. Useful for debugging.' maps = {} for fname in self.indexed_features: config = self.indexes.get(fname, {}) print(fname, config) maps[fname_to_idx_name(fname)] = { 'type': config.get('e...
def _get_field_types(self): 'Retrieve the field types. Useful for debugging.' mapping = self.conn.indices.get_mapping( index=self.index, doc_type=self.type) return mapping[self.index]['mappings'][self.type]['properties']
def _fc_index_disjunction_from_query(self, query_fc, fname): 'Creates a disjunction for keyword scan queries.' if len(query_fc.get(fname, [])) == 0: return [] terms = query_fc[fname].keys() disj = [] for fname in self.indexes[fname]['feature_names']: disj...
def fc_bytes(self, fc_dict): '''Take a feature collection in dict form and count its size in bytes. ''' num_bytes = 0 for _, feat in fc_dict.iteritems(): num_bytes += len(feat) return num_bytes
def count_bytes(self, filter_preds): '''Count bytes of all feature collections whose key satisfies one of the predicates in ``filter_preds``. The byte counts are binned by filter predicate. ''' num_bytes = defaultdict(int) for hit in self._scan(): for filter_p...
def pretty_string(fc): '''construct a nice looking string for an FC ''' s = [] for fname, feature in sorted(fc.items()): if isinstance(feature, StringCounter): feature = [u'%s: %d' % (k, v) for (k,v) in feature.most_common()] feature = u'\n\t' + u'\...
def get_lib_ffi_resource(module_name, libpath, c_hdr): ''' module_name-->str: module name to retrieve resource libpath-->str: shared library filename with optional path c_hdr-->str: C-style header definitions for functions to wrap Returns-->(ffi, lib) Use this method when you are loading a pack...
def get_lib_ffi_shared(libpath, c_hdr): ''' libpath-->str: shared library filename with optional path c_hdr-->str: C-style header definitions for functions to wrap Returns-->(ffi, lib) ''' lib = SharedLibWrapper(libpath, c_hdr) ffi = lib.ffi return (ffi, lib)
def __openlib(self): ''' Actual (lazy) dlopen() only when an attribute is accessed ''' if self.__getattribute__('_libloaded'): return libpath_list = self.__get_libres() for p in libpath_list: try: libres = resource_filename(self._mo...
def __get_libres(self): ''' Computes libpath based on whether module_name is set or not Returns-->list of str lib paths to try PEP3140: ABI version tagged .so files: https://www.python.org/dev/peps/pep-3149/ There's still one unexplained bit: pypy adds '-' + sys._mu...
def process_docopts(): # type: ()->None """ Take care of command line options """ arguments = docopt(__doc__, version="Find Known Secrets {0}".format(__version__)) logger.debug(arguments) # print(arguments) if arguments["here"]: # all default go() else: # user ...
async def api_postcode(request): """ Gets data from a postcode. :param request: The aiohttp request. """ postcode: Optional[str] = request.match_info.get('postcode', None) try: coroutine = get_postcode_random() if postcode == "random" else get_postcode(postcode) postcode: Option...
async def api_nearby(request): """ Gets wikipedia articles near a given postcode. :param request: The aiohttp request. """ postcode: Optional[str] = request.match_info.get('postcode', None) try: limit = int(request.match_info.get('limit', 10)) except ValueError: raise web.HT...
def default_formatter(error): """Escape the error, and wrap it in a span with class ``error-message``""" quoted = formencode.htmlfill.escape_formatter(error) return u'<span class="error-message">{0}</span>'.format(quoted)
def pretty_to_link(inst, link): ''' Create a human-readable representation of a link on the 'TO'-side ''' values = '' prefix = '' metaclass = xtuml.get_metaclass(inst) for name, ty in metaclass.attributes: if name in link.key_map: value = getattr(inst, name) ...
def pretty_unique_identifier(inst, identifier): ''' Create a human-readable representation a unique identifier. ''' values = '' prefix = '' metaclass = xtuml.get_metaclass(inst) for name, ty in metaclass.attributes: if name in metaclass.identifying_attributes: value ...