INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Keyword scan for ids.
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. If ``query_fc`` is ``None``, then the query is retrieved automatically corresponding to ``query_id``. :param str query_id: Optional query id. :param query_fc: Optional query feature collection. :type query_fc: :class:`dossier.fc.FeatureCollection` :rtype: Iterable of ``content_id`` ''' it = self._keyword_scan(query_id, query_fc, feature_names=False) for hit in it: yield did(hit['_id'])
Low - level keyword index scan for ids.
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 value. :rtype: Iterable of ``content_id`` ''' disj = [] for fname2 in self.indexes[fname]['feature_names']: disj.append({'term': {fname_to_idx_name(fname2): val}}) query = { 'constant_score': { 'filter': {'or': disj}, }, } hits = scan(self.conn, index=self.index, doc_type=self.type, query={ '_source': False, 'query': query, }) for hit in hits: yield did(hit['_id'])
Maps feature names to ES s _source field.
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)
Creates ES filters for key ranges used in scanning.
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. # We need a valid codepoint, so use the max. e += u'\U0010FFFF' e = eid(e) if s == () and e == (): filters.append({'match_all': {}}) elif e == (): filters.append({'range': {'_id': {'gte': s}}}) elif s == (): filters.append({'range': {'_id': {'lte': e}}}) else: filters.append({'range': {'_id': {'gte': s, 'lte': e}}}) if len(filters) == 0: return [{'match_all': {}}] else: return filters
Create the index
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.replicas, }, }) except TransportError: # Hope that this is an "index already exists" error... logger.warn('index already exists? OK', exc_info=True) pass
Create the field type mapping.
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': [{ 'default_no_analyze_fc': { 'match': 'fc.*', 'mapping': {'index': 'no'}, }, }], '_all': { 'enabled': False, }, '_id': { 'index': 'not_analyzed', # allows range queries }, 'properties': self._get_index_mappings(), }, }) # It is possible to create an index and quickly launch a request # that will fail because the index hasn't been set up yet. Usually, # you'll get a "no active shards available" error. # # Since index creation is a very rare operation (it only happens # when the index doesn't already exist), we sit and wait for the # cluster to become healthy. self.conn.cluster.health(index=self.index, wait_for_status='yellow')
Retrieve the field mappings. Useful for debugging.
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('es_index_type', 'integer'), 'store': False, 'index': 'not_analyzed', } for fname in self.fulltext_indexed_features: maps[fname_to_full_idx_name(fname)] = { 'type': 'string', 'store': False, 'index': 'analyzed', } return maps
Retrieve the field types. Useful for debugging.
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']
Creates a disjunction for keyword scan queries.
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.append({'terms': {fname_to_idx_name(fname): terms}}) return disj
Take a feature collection in dict form and count its size in bytes.
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
Count bytes of all feature collections whose key satisfies one of the predicates in filter_preds. The byte counts are binned by filter predicate.
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_pred in filter_preds: if filter_pred(did(hit['_id'])): num_bytes[filter_pred] += self.fc_bytes( hit['_source']['fc']) return num_bytes
construct a nice looking string for an FC
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'\n\t'.join(feature) s.append(fname + u': ' + feature) return u'\n'.join(s)
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 )
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 package-specific shared library If you want to load a system-wide shared library, use get_lib_ffi_shared instead ''' lib = SharedLibWrapper(libpath, c_hdr, module_name=module_name) ffi = lib.ffi return (ffi, lib)
libpath -- > str: shared library filename with optional path c_hdr -- > str: C - style header definitions for functions to wrap Returns -- > ( ffi lib )
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)
Actual ( lazy ) dlopen () only when an attribute is accessed
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._module_name, p) self.lib = self.ffi.dlopen(libres) return except: continue # Try self._libpath if nothing in libpath_list worked - will work # only if self._module_name is set try: libres = resource_filename(self._module_name, self._libpath) self.lib = self.ffi.dlopen(libres) except: # If self._module_name is in sys.modules, try self._libpath # in the same dir as sys.modules[self._module_name].__file__ # This is allows get_lib_ffi_shared to work in REPL try: # We set _libloaded to indicate all options have been tried self._libloaded = True libdir = '' if self._module_name is not None: mod = sys.modules.get(self._module_name, None) if mod is not None: libdir = os.path.dirname(mod.__file__) or os.getcwd() libres = os.path.join(libdir, self._libpath) self.lib = self.ffi.dlopen(libres) except: return None
Computes libpath based on whether module_name is set or not Returns -- > list of str lib paths to try
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._multiarch() at the end (looks like 'x86_64-linux-gnu'), but neither py2 or py3 do Additionally, in older releases of pypy (e.g. build f3ad1e1e1d62 Aug-28-2015), sysconfig.get_config_var('SOABI') returns '' but shared library still has '.pypy-26' in the name! So for pypy we try this this variant anyway! _I_ think Py2 and Py3 _MAY_ start adding sys._multiarch at some time So, we generate three forms: 1. With sys._multiarch 2. Without sys._multiarch 3. libpath as-is - always tried by self.__openlib anyway For different versions we try in different order (for efficiency): Python2 Python3 Pypy 2 --> 1 --> 3 2 --> 1 --> 3 1 --> 2 --> 3 ''' if self._module_name is None: return [] ending = '.so' base = self._libpath.rsplit(ending, 1)[0] abi = sysconfig.get_config_var('SOABI') if abi is not None: abi = '.' + abi else: abi = '' multi_arch = sysconfig.get_config_var('MULTIARCH') if multi_arch is None: multi_arch = '' else: multi_arch = '-' + multi_arch if PYPY: n1 = base + abi + multi_arch + ending n2 = base + abi + ending else: n1 = base + abi + ending n2 = base + abi + multi_arch + ending if PYPY: n3 = base + '.pypy-26' + ending return [n1, n2, n3] else: return [n1, n2]
Take care of command line options
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 config files = arguments["--secrets"] searcher = Searcher(source=arguments["--source"], files=files) searcher.go()
Gets data from a postcode.: param request: The aiohttp request.
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: Optional[Postcode] = await coroutine except CachingError as e: return web.HTTPInternalServerError(body=e.status) except CircuitBreakerError as e: pass else: if postcode is not None: return str_json_response(postcode.serialize()) else: return web.HTTPNotFound(body="Invalid Postcode")
Gets wikipedia articles near a given postcode.: param request: The aiohttp request.
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.HTTPBadRequest(text="Invalid Limit") try: coroutine = get_postcode_random() if postcode == "random" else get_postcode(postcode) postcode: Optional[Postcode] = await coroutine except CachingError as e: raise web.HTTPInternalServerError(body=e.status) if postcode is None: raise web.HTTPNotFound(text="Invalid Postcode") try: nearby_items = await fetch_nearby(postcode.lat, postcode.long, limit) except ApiError: return web.HTTPInternalServerError(text=f"No nearby locations cached, and can't be retrieved.") if nearby_items is None: raise web.HTTPNotFound(text="No Results") else: return str_json_response(nearby_items)
Escape the error and wrap it in a span with class error - message
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)
Create a human - readable representation of a link on the TO - side
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) value = xtuml.serialize_value(value, ty) name = link.key_map[name] values += '%s%s=%s' % (prefix, name, value) prefix = ', ' return '%s(%s)' % (link.kind, values)
Create a human - readable representation a unique identifier.
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 = getattr(inst, name) value = xtuml.serialize_value(value, ty) values += '%s%s=%s' % (prefix, name, value) prefix = ', ' return '%s(%s)' % (identifier, values)
Check the model for uniqueness constraint violations.
def check_uniqueness_constraint(m, kind=None): ''' Check the model for uniqueness constraint violations. ''' if kind is None: metaclasses = m.metaclasses.values() else: metaclasses = [m.find_metaclass(kind)] res = 0 for metaclass in metaclasses: id_map = dict() for identifier in metaclass.indices: id_map[identifier] = dict() for inst in metaclass.select_many(): # Check for null-values for name, ty in metaclass.attributes: if name not in metaclass.identifying_attributes: continue value = getattr(inst, name) isnull = value is None isnull |= (ty == 'UNIQUE_ID' and not value) if isnull: res += 1 logger.warning('%s.%s is part of an identifier and is null' % (metaclass.kind, name)) # Check uniqueness for identifier in metaclass.indices: kwargs = dict() for name in metaclass.indices[identifier]: kwargs[name] = getattr(inst, name) index_key = frozenset(kwargs.items()) if index_key in id_map[identifier]: res += 1 id_string = pretty_unique_identifier(inst, identifier) logger.warning('uniqueness constraint violation in %s, %s' % (metaclass.kind, id_string)) id_map[identifier][index_key] = inst return res
Check the model for integrity violations on an association in a particular direction.
def check_link_integrity(m, link): ''' Check the model for integrity violations on an association in a particular direction. ''' res = 0 for inst in link.from_metaclass.select_many(): q_set = list(link.navigate(inst)) if(len(q_set) < 1 and not link.conditional) or ( (len(q_set) > 1 and not link.many)): res += 1 logger.warning('integrity violation in ' '%s --(%s)--> %s' % (pretty_from_link(inst, link), link.rel_id, pretty_to_link(inst, link))) return res
Check the model for integrity violations across a subtype association.
def check_subtype_integrity(m, super_kind, rel_id): ''' Check the model for integrity violations across a subtype association. ''' if isinstance(rel_id, int): rel_id = 'R%d' % rel_id res = 0 for inst in m.select_many(super_kind): if not xtuml.navigate_subtype(inst, rel_id): res += 1 logger.warning('integrity violation across ' '%s[%s]' % (super_kind, rel_id)) return res
Check the model for integrity violations on association ( s ).
def check_association_integrity(m, rel_id=None): ''' Check the model for integrity violations on association(s). ''' if isinstance(rel_id, int): rel_id = 'R%d' % rel_id res = 0 for ass in m.associations: if rel_id in [ass.rel_id, None]: res += check_link_integrity(m, ass.source_link) res += check_link_integrity(m, ass.target_link) return res
This will exclude all of the modules from the traceback: param modules: list of modules to exclude: return: None
def skip_module(*modules): """ This will exclude all of the "modules" from the traceback :param modules: list of modules to exclude :return: None """ modules = (modules and isinstance(modules[0], list)) and \ modules[0] or modules for module in modules: if not module in SKIPPED_MODULES: SKIPPED_MODULES.append(module) traceback.extract_tb = _new_extract_tb
This will exclude all modules from the traceback except these modules: param modules: list of modules to report in traceback: return: None
def only_module(*modules): """ This will exclude all modules from the traceback except these "modules" :param modules: list of modules to report in traceback :return: None """ modules = (modules and isinstance(modules[0], list)) and \ modules[0] or modules for module in modules: if not module in ONLY_MODULES: ONLY_MODULES.append(module) traceback.extract_tb = _new_extract_tb
This will exclude all modules that start from this path: param paths: list of str of the path of modules to exclude: return: None
def skip_path(*paths): """ This will exclude all modules that start from this path :param paths: list of str of the path of modules to exclude :return: None """ paths = (paths and isinstance(paths[0], list)) and paths[0] or paths for path in paths: if not path in SKIPPED_PATHS: SKIPPED_PATHS.append(path) traceback.extract_tb = _new_extract_tb
Returns a index creation function.
def feature_index(*feature_names): '''Returns a index creation function. Returns a valid index ``create`` function for the feature names given. This can be used with the :meth:`Store.define_index` method to create indexes on any combination of features in a feature collection. :type feature_names: list(unicode) :rtype: ``(val -> index val) -> (content_id, FeatureCollection) -> generator of [index val]`` ''' def _(trans, (cid, fc)): for fname in feature_names: feat = fc.get(fname) if feat is None: continue elif isinstance(feat, unicode): yield trans(feat) else: # string counter, sparse/dense vector for val in feat.iterkeys(): yield trans(val) return _
A basic transform for strings and integers.
def basic_transform(val): '''A basic transform for strings and integers.''' if isinstance(val, int): return struct.pack('>i', val) else: return safe_lower_utf8(val)
x. lower (). encode ( utf - 8 ) where x can be None str or unicode
def safe_lower_utf8(x): '''x.lower().encode('utf-8') where x can be None, str, or unicode''' if x is None: return None x = x.lower() if isinstance(x, unicode): return x.encode('utf-8') return x
Retrieve a feature collection from the store. This is the same as get_many ( [ content_id ] )
def get(self, content_id): '''Retrieve a feature collection from the store. This is the same as get_many([content_id]) If the feature collection does not exist ``None`` is returned. :type content_id: str :rtype: :class:`dossier.fc.FeatureCollection` ''' rows = list(self.kvl.get(self.TABLE, (content_id,))) assert len(rows) < 2, 'more than one FC with the same content id' if len(rows) == 0 or rows[0][1] is None: return None return fc_loads(rows[0][1])
Yield ( content_id data ) tuples for ids in list.
def get_many(self, content_id_list): '''Yield (content_id, data) tuples for ids in list. As with :meth:`get`, if a content_id in the list is missing, then it is yielded with a data value of `None`. :type content_id_list: list<str> :rtype: yields tuple(str, :class:`dossier.fc.FeatureCollection`) ''' content_id_keys = [tuplify(x) for x in content_id_list] for row in self.kvl.get(self.TABLE, *content_id_keys): content_id = row[0][0] data = row[1] if data is not None: data = fc_loads(data) yield (content_id, data)
Add feature collections to the store.
def put(self, items, indexes=True): '''Add feature collections to the store. Given an iterable of tuples of the form ``(content_id, feature collection)``, add each to the store and overwrite any that already exist. This method optionally accepts a keyword argument `indexes`, which by default is set to ``True``. When it is ``True``, it will *create* new indexes for each content object for all indexes defined on this store. Note that this will not update existing indexes. (There is currently no way to do this without running some sort of garbage collection process.) :param iterable items: iterable of ``(content_id, FeatureCollection)``. :type fc: :class:`dossier.fc.FeatureCollection` ''' # So why accept an iterable? Ideally, some day, `kvlayer.put` would # accept an iterable, so we should too. # # But we have to transform it to a list in order to update indexes # anyway. Well, if we don't have to update indexes, then we can avoid # loading everything into memory, which seems like an optimization # worth having even if it's only some of the time. # # N.B. If you're thinking, "Just use itertools.tee", then you should # heed this warning from Python docs: "This itertool may require # significant auxiliary storage (depending on how much temporary data # needs to be stored). In general, if one iterator uses most or all of # the data before another iterator starts, it is faster to use list() # instead of tee()." # # i.e., `tee` has to store everything into memory because `kvlayer` # will exhaust the first iterator before indexes get updated. items = list(items) self.kvl.put(self.TABLE, *imap(lambda (cid, fc): ((cid,), fc_dumps(fc)), items)) if indexes: for idx_name in self._indexes: self._index_put(idx_name, *items)
Deletes all storage.
def delete_all(self): '''Deletes all storage. This includes every content object and all index data. ''' self.kvl.clear_table(self.TABLE) self.kvl.clear_table(self.INDEX_TABLE)
Retrieve feature collections in a range of ids.
def scan(self, *key_ranges): '''Retrieve feature collections in a range of ids. Returns a generator of content objects corresponding to the content identifier ranges given. `key_ranges` can be a possibly empty list of 2-tuples, where the first element of the tuple is the beginning of a range and the second element is the end of a range. To specify the beginning or end of the table, use an empty tuple `()`. If the list is empty, then this yields all content objects in the storage. :param key_ranges: as described in :meth:`kvlayer._abstract_storage.AbstractStorage` :rtype: generator of (``content_id``, :class:`dossier.fc.FeatureCollection`). ''' # (id, id) -> ((id,), (id,)) key_ranges = [(tuplify(s), tuplify(e)) for s, e in key_ranges] return imap(lambda (cid, fc): (cid[0], fc_loads(fc)), self.kvl.scan(self.TABLE, *key_ranges))
Retrieve content ids in a range of ids.
def scan_ids(self, *key_ranges): '''Retrieve content ids in a range of ids. Returns a generator of ``content_id`` corresponding to the content identifier ranges given. `key_ranges` can be a possibly empty list of 2-tuples, where the first element of the tuple is the beginning of a range and the second element is the end of a range. To specify the beginning or end of the table, use an empty tuple `()`. If the list is empty, then this yields all content ids in the storage. :param key_ranges: as described in :meth:`kvlayer._abstract_storage.AbstractStorage` :rtype: generator of ``content_id`` ''' # (id, id) -> ((id,), (id,)) key_ranges = [(tuplify(s), tuplify(e)) for s, e in key_ranges] scanner = self.kvl.scan_keys(self.TABLE, *key_ranges) return imap(itemgetter(0), scanner)
Returns ids that match an indexed value.
def index_scan(self, idx_name, val): '''Returns ids that match an indexed value. Returns a generator of content identifiers that have an entry in the index ``idx_name`` with value ``val`` (after index transforms are applied). If the index named by ``idx_name`` is not registered, then a :exc:`~exceptions.KeyError` is raised. :param unicode idx_name: name of index :param val: the value to use to search the index :type val: unspecified (depends on the index, usually ``unicode``) :rtype: generator of ``content_id`` :raises: :exc:`~exceptions.KeyError` ''' idx = self._index(idx_name)['transform'] key = (idx(val), idx_name.encode('utf-8')) keys = self.kvl.scan_keys(self.INDEX_TABLE, (key, key)) return imap(lambda k: k[2], keys)
Returns ids that match a prefix of an indexed value.
def index_scan_prefix(self, idx_name, val_prefix): '''Returns ids that match a prefix of an indexed value. Returns a generator of content identifiers that have an entry in the index ``idx_name`` with prefix ``val_prefix`` (after index transforms are applied). If the index named by ``idx_name`` is not registered, then a :exc:`~exceptions.KeyError` is raised. :param unicode idx_name: name of index :param val_prefix: the value to use to search the index :type val: unspecified (depends on the index, usually ``unicode``) :rtype: generator of ``content_id`` :raises: :exc:`~exceptions.KeyError` ''' return self._index_scan_prefix_impl( idx_name, val_prefix, lambda k: k[2])
Returns ids that match a prefix of an indexed value and the specific key that matched the search prefix.
def index_scan_prefix_and_return_key(self, idx_name, val_prefix): '''Returns ids that match a prefix of an indexed value, and the specific key that matched the search prefix. Returns a generator of (index key, content identifier) that have an entry in the index ``idx_name`` with prefix ``val_prefix`` (after index transforms are applied). If the index named by ``idx_name`` is not registered, then a :exc:`~exceptions.KeyError` is raised. :param unicode idx_name: name of index :param val_prefix: the value to use to search the index :type val: unspecified (depends on the index, usually ``unicode``) :rtype: generator of (``index key``, ``content_id``) :raises: :exc:`~exceptions.KeyError` ''' return self._index_scan_prefix_impl( idx_name, val_prefix, lambda k: (k[0], k[2]))
Implementation for index_scan_prefix and index_scan_prefix_and_return_key parameterized on return value function.
def _index_scan_prefix_impl(self, idx_name, val_prefix, retfunc): '''Implementation for index_scan_prefix and index_scan_prefix_and_return_key, parameterized on return value function. retfunc gets passed a key tuple from the index: (index name, index value, content_id) ''' idx = self._index(idx_name)['transform'] val_prefix = idx(val_prefix) idx_name = idx_name.encode('utf-8') s = (val_prefix, idx_name) e = (val_prefix + '\xff', idx_name) keys = self.kvl.scan_keys(self.INDEX_TABLE, (s, e)) return imap(retfunc, keys)
Add an index to this store instance.
def define_index(self, idx_name, create, transform): '''Add an index to this store instance. Adds an index transform to the current FC store. Once an index with name ``idx_name`` is added, it will be available in all ``index_*`` methods. Additionally, the index will be automatically updated on calls to :meth:`~dossier.fc.store.Store.put`. If an index with name ``idx_name`` already exists, then it is overwritten. Note that indexes do *not* persist. They must be re-defined for each instance of :class:`Store`. For example, to add an index on the ``boNAME`` feature, you can use the ``feature_index`` helper function: .. code-block:: python store.define_index('boNAME', feature_index('boNAME'), lambda s: s.encode('utf-8')) Another example for creating an index on names: .. code-block:: python store.define_index('NAME', feature_index('canonical_name', 'NAME'), lambda s: s.lower().encode('utf-8')) :param idx_name: The name of the index. Must be UTF-8 encodable. :type idx_name: unicode :param create: A function that accepts the ``transform`` function and a pair of ``(content_id, fc)`` and produces a generator of index values from the pair given using ``transform``. :param transform: A function that accepts an arbitrary value and applies a transform to it. This transforms the *stored* value to the *index* value. This *must* produce a value with type `str` (or `bytes`). ''' assert isinstance(idx_name, (str, unicode)) idx_name = idx_name.decode('utf-8') self._indexes[idx_name] = {'create': create, 'transform': transform}
Add new index values.
def _index_put(self, idx_name, *ids_and_fcs): '''Add new index values. Adds new index values for index ``idx_name`` for the pairs given. Each pair should be a content identifier and a :class:`dossier.fc.FeatureCollection`. :type idx_name: unicode :type ids_and_fcs: ``[(content_id, FeatureCollection)]`` ''' keys = self._index_keys_for(idx_name, *ids_and_fcs) with_vals = map(lambda k: (k, '0'), keys) # TODO: use imap when kvl.put takes an iterable self.kvl.put(self.INDEX_TABLE, *with_vals)
Add new raw index values.
def _index_put_raw(self, idx_name, content_id, val): '''Add new raw index values. Adds a new index key corresponding to ``(idx_name, transform(val), content_id)``. This method bypasses the *creation* of indexes from content objects, but values are still transformed. :type idx_name: unicode :type content_id: str :type val: unspecified (depends on the index, usually ``unicode``) ''' idx = self._index(idx_name)['transform'] key = (idx(val), idx_name.encode('utf-8'), content_id) self.kvl.put(self.INDEX_TABLE, (key, '0'))
Returns a generator of index triples.
def _index_keys_for(self, idx_name, *ids_and_fcs): '''Returns a generator of index triples. Returns a generator of index keys for the ``ids_and_fcs`` pairs given. The index keys have the form ``(idx_name, idx_val, content_id)``. :type idx_name: unicode :type ids_and_fcs: ``[(content_id, FeatureCollection)]`` :rtype: generator of ``(str, str, str)`` ''' idx = self._index(idx_name) icreate, itrans = idx['create'], idx['transform'] if isinstance(idx_name, unicode): idx_name = idx_name.encode('utf-8') for cid_fc in ids_and_fcs: content_id = cid_fc[0] # Be sure to dedup index_values or else we may # suffer duplicate_pkey errors down the line. seen_values = set() for index_value in icreate(itrans, cid_fc): if index_value and index_value not in seen_values: yield (index_value, idx_name, content_id) seen_values.add(index_value)
Returns index transforms for name.
def _index(self, name): '''Returns index transforms for ``name``. :type name: unicode :rtype: ``{ create |--> function, transform |--> function }`` ''' name = name.decode('utf-8') try: return self._indexes[name] except KeyError: raise KeyError('Index "%s" has not been registered with ' 'this FC store.' % name)
Gets the twitter feed for a given handle.: param handle: The twitter handle.: return: A list of entries in a user s feed.: raises ApiError: When the api couldn t connect.: raises CircuitBreakerError: When the circuit breaker is open.
async def fetch_twitter(handle: str) -> List: """ Gets the twitter feed for a given handle. :param handle: The twitter handle. :return: A list of entries in a user's feed. :raises ApiError: When the api couldn't connect. :raises CircuitBreakerError: When the circuit breaker is open. """ async with ClientSession() as session: try: async with session.get(f"http://twitrss.me/twitter_user_to_rss/?user={handle}") as request: text = await request.text() except ClientConnectionError as con_err: logger.debug(f"Could not connect to {con_err.host}") raise ApiError(f"Could not connect to {con_err.host}") else: feed = parse(text) for x in feed.entries: x["image"] = feed.feed["image"]["href"] return feed.entries
Gets wikipedia articles near a given set of coordinates.: raise ApiError: When there was an error connecting to the API.
async def fetch_nearby(lat: float, long: float, limit: int = 10) -> Optional[List[Dict]]: """ Gets wikipedia articles near a given set of coordinates. :raise ApiError: When there was an error connecting to the API. todo cache """ request_url = f"https://en.wikipedia.org/w/api.php?action=query" \ f"&list=geosearch" \ f"&gscoord={lat}%7C{long}" \ f"&gsradius=10000" \ f"&gslimit={limit}" \ f"&format=json" async with ClientSession() as session: try: async with session.get(request_url) as request: if request.status == 404: return None data = (await request.json())["query"]["geosearch"] except ClientConnectionError as con_err: logger.debug(f"Could not connect to {con_err.host}") raise ApiError(f"Could not connect to {con_err.host}") except JSONDecodeError as dec_err: logger.error(f"Could not decode data: {dec_err}") raise ApiError(f"Could not decode data: {dec_err}") except KeyError: return None else: for location in data: location.pop("ns") location.pop("primary") return data
Execute shell command and return stdout txt: param command:: return:
def execute_get_text(command): # type: (str) ->str """ Execute shell command and return stdout txt :param command: :return: """ try: completed = subprocess.run( command, check=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) except subprocess.CalledProcessError as err: raise else: print(completed.stdout.decode('utf-8') + str(":") + completed.stderr.decode("utf-8")) return completed.stdout.decode('utf-8') + completed.stderr.decode("utf-8")
If a task succeeds & is re - run and didn t change we might not want to re - run it if it depends * only * on source code: return:
def has_source_code_tree_changed(self): """ If a task succeeds & is re-run and didn't change, we might not want to re-run it if it depends *only* on source code :return: """ global CURRENT_HASH directory = self.where # if CURRENT_HASH is None: # print("hashing " + directory) # print(os.listdir(directory)) CURRENT_HASH = dirhash(directory, 'md5', ignore_hidden=True, # changing these exclusions can cause dirhas to skip EVERYTHING excluded_files=[".coverage", "lint.txt"], excluded_extensions=[".pyc"] ) print("Searching " + self.state_file_name) if os.path.isfile(self.state_file_name): with open(self.state_file_name, "r+") as file: last_hash = file.read() if last_hash != CURRENT_HASH: file.seek(0) file.write(CURRENT_HASH) file.truncate() return True else: return False # no previous file, by definition not the same. with open(self.state_file_name, "w") as file: file.write(CURRENT_HASH) return True
Check if a package name exists on pypi.
def check_pypi_name(pypi_package_name, pypi_registry_host=None): """ Check if a package name exists on pypi. TODO: Document the Registry URL construction. It may not be obvious how pypi_package_name and pypi_registry_host are used I'm appending the simple HTTP API parts of the registry standard specification. It will return True if the package name, or any equivalent variation as defined by PEP 503 normalisation rules (https://www.python.org/dev/peps/pep-0503/#normalized-names) is registered in the PyPI registry. >>> check_pypi_name('pip') True >>> check_pypi_name('Pip') True It will return False if the package name, or any equivalent variation as defined by PEP 503 normalisation rules (https://www.python.org/dev/peps/pep-0503/#normalized-names) is not registered in the PyPI registry. >>> check_pypi_name('testy_mc-test_case-has.a.cousin_who_should_never_write_a_package') False :param pypi_package_name: :param pypi_registry_host: :return: """ if pypi_registry_host is None: pypi_registry_host = 'pypi.python.org' # Just a helpful reminder why this bytearray size was chosen. # HTTP/1.1 200 OK # HTTP/1.1 404 Not Found receive_buffer = bytearray(b'------------') context = ssl.create_default_context() ssl_http_socket = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=pypi_registry_host) ssl_http_socket.connect((pypi_registry_host, 443)) ssl_http_socket.send(b''.join([ b"HEAD /simple/", pypi_package_name.encode('ascii'), b"/ HTTP/1.0", b"\r\n", b"Host: ", pypi_registry_host.encode('ascii'), b"\r\n", b"\r\n\r\n" ])) ssl_http_socket.recv_into(receive_buffer) # Early return when possible. if b'HTTP/1.1 200' in receive_buffer: ssl_http_socket.shutdown(1) ssl_http_socket.close() return True elif b'HTTP/1.1 404' in receive_buffer: ssl_http_socket.shutdown(1) ssl_http_socket.close() return False remaining_bytes = ssl_http_socket.recv(2048) redirect_path_location_start = remaining_bytes.find(b'Location:') + 10 redirect_path_location_end = remaining_bytes.find(b'\r\n', redirect_path_location_start) # Append the trailing slash to avoid a needless extra redirect. redirect_path = remaining_bytes[redirect_path_location_start:redirect_path_location_end] + b'/' ssl_http_socket.shutdown(1) ssl_http_socket.close() # Reset the bytearray to empty # receive_buffer = bytearray(b'------------') ssl_http_socket = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=pypi_registry_host) ssl_http_socket.connect((pypi_registry_host, 443)) ssl_http_socket.send(b''.join([ b"HEAD ", redirect_path, b" HTTP/1.0", b"\r\n", b"Host: ", pypi_registry_host.encode('ascii'), b"\r\n", b"\r\n\r\n"])) ssl_http_socket.recv_into(receive_buffer) if b'HTTP/1.1 200' in receive_buffer: return True elif b'HTTP/1.1 404' in receive_buffer: return False else: NotImplementedError('A definitive answer was not found by primary or secondary lookups.')
Adds direction to the element
def add_direction(value, arg=u"rtl_only"): """Adds direction to the element :arguments: arg * rtl_only: Add the direction only in case of a right-to-left language (default) * both: add the direction in both case * ltr_only: Add the direction only in case of a left-to-right language {{image_name|add_direction}} when image_name is 'start_arrow.png' results in 'start_arrow_rtl.png' in case of RTL language, and 'start_arrow.png' or 'start_arrow_ltr.png' depends on `arg` value. """ if arg == u'rtl_only': directions = (u'', u'_rtl') elif arg == u'both': directions = (u'_ltr', u'_rtl') elif arg == u'ltr_only': directions = (u'_ltr', u'') else: raise template.TemplateSyntaxError('add_direction can use arg with one of ["rtl_only", "both", "ltr_only"]') parts = value.rsplit('.', 1) if not len(parts): return value elif len(parts) == 1: return value + directions[translation.get_language_bidi()] else: return '.'.join((parts[0]+directions[translation.get_language_bidi()],parts[1]))
Gets a postcode object from the lat and long.: param lat: The latitude to look up.: param long: The longitude to look up.: return: The mapping corresponding to the lat and long or none if the postcode does not exist.: raises ApiError: When there was an error connecting to the API.: raises CircuitBreakerError: When the circuit breaker is open.
async def fetch_postcodes_from_coordinates(lat: float, long: float) -> Optional[List[Postcode]]: """ Gets a postcode object from the lat and long. :param lat: The latitude to look up. :param long: The longitude to look up. :return: The mapping corresponding to the lat and long or none if the postcode does not exist. :raises ApiError: When there was an error connecting to the API. :raises CircuitBreakerError: When the circuit breaker is open. """ postcode_lookup = f"/postcodes?lat={lat}&lon={long}" return await _get_postcode_from_url(postcode_lookup)
get the xsd name of a S_DT
def get_type_name(s_dt): ''' get the xsd name of a S_DT ''' s_cdt = nav_one(s_dt).S_CDT[17]() if s_cdt and s_cdt.Core_Typ in range(1, 6): return s_dt.Name s_edt = nav_one(s_dt).S_EDT[17]() if s_edt: return s_dt.Name s_udt = nav_one(s_dt).S_UDT[17]() if s_udt: return s_dt.Name
Get the the referred attribute.
def get_refered_attribute(o_attr): ''' Get the the referred attribute. ''' o_attr_ref = nav_one(o_attr).O_RATTR[106].O_BATTR[113].O_ATTR[106]() if o_attr_ref: return get_refered_attribute(o_attr_ref) else: return o_attr
Build an xsd simpleType out of a S_CDT.
def build_core_type(s_cdt): ''' Build an xsd simpleType out of a S_CDT. ''' s_dt = nav_one(s_cdt).S_DT[17]() if s_dt.name == 'void': type_name = None elif s_dt.name == 'boolean': type_name = 'xs:boolean' elif s_dt.name == 'integer': type_name = 'xs:integer' elif s_dt.name == 'real': type_name = 'xs:decimal' elif s_dt.name == 'string': type_name = 'xs:string' elif s_dt.name == 'unique_id': type_name = 'xs:integer' else: type_name = None if type_name: mapped_type = ET.Element('xs:simpleType', name=s_dt.name) ET.SubElement(mapped_type, 'xs:restriction', base=type_name) return mapped_type
Build an xsd simpleType out of a S_EDT.
def build_enum_type(s_edt): ''' Build an xsd simpleType out of a S_EDT. ''' s_dt = nav_one(s_edt).S_DT[17]() enum = ET.Element('xs:simpleType', name=s_dt.name) enum_list = ET.SubElement(enum, 'xs:restriction', base='xs:string') first_filter = lambda selected: not nav_one(selected).S_ENUM[56, 'succeeds']() s_enum = nav_any(s_edt).S_ENUM[27](first_filter) while s_enum: ET.SubElement(enum_list, 'xs:enumeration', value=s_enum.name) s_enum = nav_one(s_enum).S_ENUM[56, 'precedes']() return enum
Build an xsd complexType out of a S_SDT.
def build_struct_type(s_sdt): ''' Build an xsd complexType out of a S_SDT. ''' s_dt = nav_one(s_sdt).S_DT[17]() struct = ET.Element('xs:complexType', name=s_dt.name) first_filter = lambda selected: not nav_one(selected).S_MBR[46, 'succeeds']() s_mbr = nav_any(s_sdt).S_MBR[44](first_filter) while s_mbr: s_dt = nav_one(s_mbr).S_DT[45]() type_name = get_type_name(s_dt) ET.SubElement(struct, 'xs:attribute', name=s_mbr.name, type=type_name) s_mbr = nav_one(s_mbr).S_MBR[46, 'precedes']() return struct
Build an xsd simpleType out of a S_UDT.
def build_user_type(s_udt): ''' Build an xsd simpleType out of a S_UDT. ''' s_dt_user = nav_one(s_udt).S_DT[17]() s_dt_base = nav_one(s_udt).S_DT[18]() base_name = get_type_name(s_dt_base) if base_name: user = ET.Element('xs:simpleType', name=s_dt_user.name) ET.SubElement(user, 'xs:restriction', base=base_name) return user
Build a partial xsd tree out of a S_DT and its sub types S_CDT S_EDT S_SDT and S_UDT.
def build_type(s_dt): ''' Build a partial xsd tree out of a S_DT and its sub types S_CDT, S_EDT, S_SDT and S_UDT. ''' s_cdt = nav_one(s_dt).S_CDT[17]() if s_cdt: return build_core_type(s_cdt) s_edt = nav_one(s_dt).S_EDT[17]() if s_edt: return build_enum_type(s_edt) s_udt = nav_one(s_dt).S_UDT[17]() if s_udt: return build_user_type(s_udt)
Build an xsd complex element out of a O_OBJ including its O_ATTR.
def build_class(o_obj): ''' Build an xsd complex element out of a O_OBJ, including its O_ATTR. ''' cls = ET.Element('xs:element', name=o_obj.key_lett, minOccurs='0', maxOccurs='unbounded') attributes = ET.SubElement(cls, 'xs:complexType') for o_attr in nav_many(o_obj).O_ATTR[102](): o_attr_ref = get_refered_attribute(o_attr) s_dt = nav_one(o_attr_ref).S_DT[114]() while nav_one(s_dt).S_UDT[17](): s_dt = nav_one(s_dt).S_UDT[17].S_DT[18]() type_name = get_type_name(s_dt) if type_name and not nav_one(o_attr).O_BATTR[106].O_DBATTR[107](): ET.SubElement(attributes, 'xs:attribute', name=o_attr.name, type=type_name) else: logger.warning('Omitting %s.%s' % (o_obj.key_lett, o_attr.Name)) return cls
Build an xsd complex element out of a C_C including its packaged S_DT and O_OBJ.
def build_component(m, c_c): ''' Build an xsd complex element out of a C_C, including its packaged S_DT and O_OBJ. ''' component = ET.Element('xs:element', name=c_c.name) classes = ET.SubElement(component, 'xs:complexType') classes = ET.SubElement(classes, 'xs:sequence') scope_filter = lambda selected: ooaofooa.is_contained_in(selected, c_c) for o_obj in m.select_many('O_OBJ', scope_filter): cls = build_class(o_obj) classes.append(cls) return component
Build an xsd schema from a bridgepoint component.
def build_schema(m, c_c): ''' Build an xsd schema from a bridgepoint component. ''' schema = ET.Element('xs:schema') schema.set('xmlns:xs', 'http://www.w3.org/2001/XMLSchema') global_filter = lambda selected: ooaofooa.is_global(selected) for s_dt in m.select_many('S_DT', global_filter): datatype = build_type(s_dt) if datatype is not None: schema.append(datatype) scope_filter = lambda selected: ooaofooa.is_contained_in(selected, c_c) for s_dt in m.select_many('S_DT', scope_filter): datatype = build_type(s_dt) if datatype is not None: schema.append(datatype) component = build_component(m, c_c) schema.append(component) return schema
Indent an xml string with four spaces and add an additional line break after each node.
def prettify(xml_string): ''' Indent an xml string with four spaces, and add an additional line break after each node. ''' reparsed = xml.dom.minidom.parseString(xml_string) return reparsed.toprettyxml(indent=" ")
Gets the full list of bikes from the bikeregister site. The data is hidden behind a form post request and so we need to extract an xsrf and session token with bs4.
async def fetch_bikes() -> List[dict]: """ Gets the full list of bikes from the bikeregister site. The data is hidden behind a form post request and so we need to extract an xsrf and session token with bs4. todo add pytest tests :return: All the currently registered bikes. :raise ApiError: When there was an error connecting to the API. """ async with ClientSession() as session: try: async with session.get('https://www.bikeregister.com/stolen-bikes') as request: document = document_fromstring(await request.text()) except ClientConnectionError as con_err: logger.debug(f"Could not connect to {con_err.host}") raise ApiError(f"Could not connect to {con_err.host}") token = document.xpath("//input[@name='_token']") if len(token) != 1: raise ApiError(f"Couldn't extract token from page.") else: token = token[0].value xsrf_token = request.cookies["XSRF-TOKEN"] laravel_session = request.cookies["laravel_session"] # get the bike data headers = { 'cookie': f'XSRF-TOKEN={xsrf_token}; laravel_session={laravel_session}', 'origin': 'https://www.bikeregister.com', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0', 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 'accept': '*/*', 'referer': 'https://www.bikeregister.com/stolen-bikes', 'authority': 'www.bikeregister.com', 'x-requested-with': 'XMLHttpRequest', } data = [ ('_token', token), ('make', ''), ('model', ''), ('colour', ''), ('reporting_period', '1'), ] try: async with session.post('https://www.bikeregister.com/stolen-bikes', headers=headers, data=data) as request: bikes = json.loads(await request.text()) except ClientConnectionError as con_err: logger.debug(f"Could not connect to {con_err.host}") raise ApiError(f"Could not connect to {con_err.host}") except json.JSONDecodeError as dec_err: logger.error(f"Could not decode data: {dec_err.msg}") raise ApiError(f"Could not decode data: {dec_err.msg}") return bikes # if cant open a session return []
set positional information on a node
def set_positional_info(node, p): ''' set positional information on a node ''' node.position = Position() node.position.label = p.lexer.label node.position.start_stream = p.lexpos(1) node.position.start_line = p.lineno(1) node.position.start_column = find_column(p.lexer.lexdata, node.position.start_stream) _, node.position.end_stream = p.lexspan(len(p) - 1) _, node.position.end_line = p.linespan(len(p) - 1) node.position.end_column = find_column(p.lexer.lexdata, node.position.end_stream) - 1 node.character_stream = p.lexer.lexdata[node.position.start_stream: node.position.end_stream]
decorator for adding positional information to returning nodes
def track_production(f): ''' decorator for adding positional information to returning nodes ''' @wraps(f) def wrapper(self, p): r = f(self, p) node = p[0] if isinstance(node, Node) and len(p) > 1: set_positional_info(node, p) return r return wrapper
r \/ \/. * \ n
def t_SL_STRING(self, t): r'\/\/.*\n' t.lexer.lineno += t.value.count('\n') t.endlexpos = t.lexpos + len(t.value)
r \ [ ^ \ ] * \
def t_TICKED_PHRASE(self, t): r"\'[^\']*\'" t.endlexpos = t.lexpos + len(t.value) return t
r [ ^ \ n ] *
def t_STRING(self, t): r'"[^"\n]*"' t.endlexpos = t.lexpos + len(t.value) return t
r ( ?i ) end [ \ s ] + for
def t_END_FOR(self, t): r"(?i)end[\s]+for" t.endlexpos = t.lexpos + len(t.value) return t
r ( ?i ) end [ \ s ] + if
def t_END_IF(self, t): r"(?i)end[\s]+if" t.endlexpos = t.lexpos + len(t.value) return t
r ( ?i ) end [ \ s ] + while
def t_END_WHILE(self, t): r"(?i)end[\s]+while" t.endlexpos = t.lexpos + len(t.value) return t
r ( [ 0 - 9a - zA - Z_ ] ) + ( ? =:: )
def t_NAMESPACE(self, t): r"([0-9a-zA-Z_])+(?=::)" t.endlexpos = t.lexpos + len(t.value) return t
r [ a - zA - Z_ ] [ 0 - 9a - zA - Z_ ] * | [ a - zA - Z ] [ 0 - 9a - zA - Z_ ] * [ 0 - 9a - zA - Z_ ] +
def t_ID(self, t): r"[a-zA-Z_][0-9a-zA-Z_]*|[a-zA-Z][0-9a-zA-Z_]*[0-9a-zA-Z_]+" t.endlexpos = t.lexpos + len(t.value) value = t.value.upper() if value in self.keywords: t.type = value return t
r::
def t_DOUBLECOLON(self, t): r"::" t.endlexpos = t.lexpos + len(t.value) return t
r \ = \ =
def t_DOUBLEEQUAL(self, t): r"\=\=" t.endlexpos = t.lexpos + len(t.value) return t
r ! \ =
def t_NOTEQUAL(self, t): r"!\=" t.endlexpos = t.lexpos + len(t.value) return t
r \ - \ >
def t_ARROW(self, t): r"\-\>" t.endlexpos = t.lexpos + len(t.value) return t
r \ < \ =
def t_LE(self, t): r"\<\=" t.endlexpos = t.lexpos + len(t.value) return t
r \ > \ =
def t_GE(self, t): r"\>\=" t.endlexpos = t.lexpos + len(t.value) return t
r \ =
def t_EQUAL(self, t): r"\=" t.endlexpos = t.lexpos + len(t.value) return t
r \.
def t_DOT(self, t): r"\." t.endlexpos = t.lexpos + len(t.value) return t
r \ *
def t_TIMES(self, t): r"\*" t.endlexpos = t.lexpos + len(t.value) return t
r:
def t_COLON(self, t): r":" t.endlexpos = t.lexpos + len(t.value) return t
r \ [
def t_LSQBR(self, t): r"\[" t.endlexpos = t.lexpos + len(t.value) return t
r \ ]
def t_RSQBR(self, t): r"\]" t.endlexpos = t.lexpos + len(t.value) return t
r \ ?
def t_QMARK(self, t): r"\?" t.endlexpos = t.lexpos + len(t.value) return t
r \ <
def t_LESSTHAN(self, t): r"\<" t.endlexpos = t.lexpos + len(t.value) return t
r \ >
def t_GT(self, t): r"\>" t.endlexpos = t.lexpos + len(t.value) return t
r \ +
def t_PLUS(self, t): r"\+" t.endlexpos = t.lexpos + len(t.value) return t
r/
def t_DIV(self, t): r"/" t.endlexpos = t.lexpos + len(t.value) return t
r %
def t_MOD(self, t): r"%" t.endlexpos = t.lexpos + len(t.value) return t
statement_list: statement SEMICOLON statement_list
def p_statement_list_1(self, p): '''statement_list : statement SEMICOLON statement_list''' p[0] = p[3] if p[1] is not None: p[0].children.insert(0, p[1])
statement_list: statement SEMICOLON
def p_statement_list_2(self, p): '''statement_list : statement SEMICOLON''' p[0] = StatementListNode() if p[1] is not None: p[0].children.insert(0, p[1])
statement: BRIDGE variable_access EQUAL implicit_invocation
def p_bridge_assignment_statement(self, p): '''statement : BRIDGE variable_access EQUAL implicit_invocation''' p[4].__class__ = BridgeInvocationNode p[0] = AssignmentNode(variable_access=p[2], expression=p[4])
statement: TRANSFORM variable_access EQUAL implicit_invocation
def p_class_invocation_assignment_statement(self, p): '''statement : TRANSFORM variable_access EQUAL implicit_invocation''' p[4].__class__ = ClassInvocationNode p[0] = AssignmentNode(variable_access=p[2], expression=p[4])
statement: SEND variable_access EQUAL implicit_invocation
def p_port_invocation_assignment_statement(self, p): '''statement : SEND variable_access EQUAL implicit_invocation''' p[4].__class__ = PortInvocationNode p[0] = AssignmentNode(variable_access=p[2], expression=p[4])
statement: SEND namespace DOUBLECOLON identifier LPAREN parameter_list RPAREN TO expression
def p_port_event_generation(self, p): '''statement : SEND namespace DOUBLECOLON identifier LPAREN parameter_list RPAREN TO expression''' p[0] = GeneratePortEventNode(port_name=p[2], action_name=p[4], parameter_list=p[6], expression=p[9])