Search is not available for this dataset
text
stringlengths
75
104k
def pop_rule_nodes(self) -> bool: """Pop context variable that store rule nodes""" self.rule_nodes = self.rule_nodes.parents self.tag_cache = self.tag_cache.parents self.id_cache = self.id_cache.parents return True
def value(self, n: Node) -> str: """Return the text value of the node""" id_n = id(n) idcache = self.id_cache if id_n not in idcache: return "" name = idcache[id_n] tag_cache = self.tag_cache if name not in tag_cache: raise Exception("Incoh...
def parsed_stream(self, content: str, name: str=None): """Push a new Stream into the parser. All subsequent called functions will parse this new stream, until the 'popStream' function is called. """ self._streams.append(Stream(content, name))
def begin_tag(self, name: str) -> Node: """Save the current index under the given name.""" # Check if we could attach tag cache to current rule_nodes scope self.tag_cache[name] = Tag(self._stream, self._stream.index) return True
def end_tag(self, name: str) -> Node: """Extract the string between saved and current index.""" self.tag_cache[name].set_end(self._stream.index) return True
def set_rules(cls, rules: dict) -> bool: """ Merge internal rules set with the given rules """ cls._rules = cls._rules.new_child() for rule_name, rule_pt in rules.items(): if '.' not in rule_name: rule_name = cls.__module__ \ + '.' ...
def set_hooks(cls, hooks: dict) -> bool: """ Merge internal hooks set with the given hooks """ cls._hooks = cls._hooks.new_child() for hook_name, hook_pt in hooks.items(): if '.' not in hook_name: hook_name = cls.__module__ \ + '.' ...
def set_directives(cls, directives: dict) -> bool: """ Merge internal directives set with the given directives. For working directives, attach it only in the dsl.Parser class """ meta._directives = meta._directives.new_child() for dir_name, dir_pt in directives.items(): ...
def eval_rule(self, name: str) -> Node: """Evaluate a rule by name.""" # context created by caller n = Node() id_n = id(n) self.rule_nodes['_'] = n self.id_cache[id_n] = '_' # TODO: other behavior for empty rules? if name not in self.__class__._rules: ...
def eval_hook(self, name: str, ctx: list) -> Node: """Evaluate the hook by its name""" if name not in self.__class__._hooks: # TODO: don't always throw error, could have return True by default self.diagnostic.notify( error.Severity.ERROR, "Unknown ...
def peek_text(self, text: str) -> bool: """Same as readText but doesn't consume the stream.""" start = self._stream.index stop = start + len(text) if stop > self._stream.eos_index: return False return self._stream[self._stream.index:stop] == text
def one_char(self) -> bool: """Read one byte in stream""" if self.read_eof(): return False self._stream.incpos() return True
def read_char(self, c: str) -> bool: """ Consume the c head byte, increment current index and return True else return False. It use peekchar and it's the same as '' in BNF. """ if self.read_eof(): return False self._stream.save_context() if c == self._...
def read_until(self, c: str, inhibitor='\\') -> bool: """ Consume the stream while the c byte is not read, else return false ex : if stream is " abcdef ", read_until("d"); consume "abcd". """ if self.read_eof(): return False self._stream.save_context() ...
def read_until_eof(self) -> bool: """Consume all the stream. Same as EOF in BNF.""" if self.read_eof(): return True # TODO: read ALL self._stream.save_context() while not self.read_eof(): self._stream.incpos() return self._stream.validate_context()
def read_text(self, text: str) -> bool: """ Consume a strlen(text) text at current position in the stream else return False. Same as "" in BNF ex : read_text("ls");. """ if self.read_eof(): return False self._stream.save_context() if se...
def read_range(self, begin: str, end: str) -> int: """ Consume head byte if it is >= begin and <= end else return false Same as 'a'..'z' in BNF """ if self.read_eof(): return False c = self._stream.peek_char if begin <= c <= end: self._stre...
def ignore_blanks(self) -> bool: """Consume whitespace characters.""" self._stream.save_context() if not self.read_eof() and self._stream.peek_char in " \t\v\f\r\n": while (not self.read_eof() and self._stream.peek_char in " \t\v\f\r\n"): self._stre...
def do_call(self, parser: BasicParser) -> Node: """ The Decorator call is the one that actually pushes/pops the decorator in the active decorators list (parsing._decorators) """ valueparam = [] for v, t in self.param: if t is Node: valu...
def internal_name(self): """ Return the unique internal name """ unq = 'f_' + super().internal_name() if self.tparams is not None: unq += "_" + "_".join(self.tparams) if self.tret is not None: unq += "_" + self.tret return unq
def set_hit_fields(self, hit_fields): ''' Tell the clusterizer the meaning of the field names. The hit_fields parameter is a dict, e.g., {"new field name": "standard field name"}. If None default mapping is set. Example: -------- Internally, the clusterizer uses the hi...
def set_cluster_fields(self, cluster_fields): ''' Tell the clusterizer the meaning of the field names. The cluster_fields parameter is a dict, e.g., {"new filed name": "standard field name"}. ''' if not cluster_fields: cluster_fields_mapping_inverse = {} cluster_...
def set_hit_dtype(self, hit_dtype): ''' Set the data type of the hits. Fields that are not mentioned here are NOT copied into the clustered hits array. Clusterizer has to know the hit data type to produce the clustered hit result with the same data types. Parameters: ----------...
def set_cluster_dtype(self, cluster_dtype): ''' Set the data type of the cluster. Parameters: ----------- cluster_dtype : numpy.dtype or equivalent Defines the dtype of the cluster array. ''' if not cluster_dtype: cluster_dtype = np.dtype([]) ...
def add_cluster_field(self, description): ''' Adds a field or a list of fields to the cluster result array. Has to be defined as a numpy dtype entry, e.g.: ('parameter', '<i4') ''' if isinstance(description, list): for item in description: if len(item) != 2: ...
def set_end_of_cluster_function(self, function): ''' Adding function to module. This is maybe the only way to make the clusterizer to work with multiprocessing. ''' self.cluster_functions._end_of_cluster_function = self._jitted(function) self._end_of_cluster_function = function
def set_end_of_event_function(self, function): ''' Adding function to module. This is maybe the only way to make the clusterizer to work with multiprocessing. ''' self.cluster_functions._end_of_event_function = self._jitted(function) self._end_of_event_function = function
def cluster_hits(self, hits, noisy_pixels=None, disabled_pixels=None): ''' Cluster given hit array. The noisy_pixels and disabled_pixels parameters are iterables of column/row index pairs, e.g. [[column_1, row_1], [column_2, row_2], ...]. The noisy_pixels parameter allows for removing clusters ...
def _check_struct_compatibility(self, hits): ''' Takes the hit array and checks if the important data fields have the same data type than the hit clustered array and that the field names are correct.''' for key, _ in self._cluster_hits_descr: if key in self._hit_fields_mapping_inverse: ...
def add_mod(self, seq, mod): """Create a tree.{Complement, LookAhead, Neg, Until}""" modstr = self.value(mod) if modstr == '~': seq.parser_tree = parsing.Complement(seq.parser_tree) elif modstr == '!!': seq.parser_tree = parsing.LookAhead(seq.parser_tree) elif modstr == '!': ...
def add_ruleclause_name(self, ns_name, rid) -> bool: """Create a tree.Rule""" ns_name.parser_tree = parsing.Rule(self.value(rid)) return True
def add_rules(self, bnf, r) -> bool: """Attach a parser tree to the dict of rules""" bnf[r.rulename] = r.parser_tree return True
def add_rule(self, rule, rn, alts) -> bool: """Add the rule name""" rule.rulename = self.value(rn) rule.parser_tree = alts.parser_tree return True
def add_sequences(self, sequences, cla) -> bool: """Create a tree.Seq""" if not hasattr(sequences, 'parser_tree'): # forward sublevel of sequence as is sequences.parser_tree = cla.parser_tree else: oldnode = sequences if isinstance(oldnode.parser_tree, parsing.Seq): ...
def add_alt(self, alternatives, alt) -> bool: """Create a tree.Alt""" if not hasattr(alternatives, 'parser_tree'): # forward sublevel of alt as is if hasattr(alt, 'parser_tree'): alternatives.parser_tree = alt.parser_tree else: alternatives.parser_tree = alt e...
def add_read_sqstring(self, sequence, s): """Add a read_char/read_text primitive from simple quote string""" v = self.value(s).strip("'") if len(v) > 1: sequence.parser_tree = parsing.Text(v) return True sequence.parser_tree = parsing.Char(v) return True
def add_range(self, sequence, begin, end): """Add a read_range primitive""" sequence.parser_tree = parsing.Range(self.value(begin).strip("'"), self.value(end).strip("'")) return True
def add_rpt(self, sequence, mod, pt): """Add a repeater to the previous sequence""" modstr = self.value(mod) if modstr == '!!': # cursor on the REPEATER self._stream.restore_context() # log the error self.diagnostic.notify( error.Severity.ERROR, "Canno...
def add_capture(self, sequence, cpt): """Create a tree.Capture""" cpt_value = self.value(cpt) sequence.parser_tree = parsing.Capture(cpt_value, sequence.parser_tree) return True
def add_bind(self, sequence, cpt): """Create a tree.Bind""" cpt_value = self.value(cpt) sequence.parser_tree = parsing.Bind(cpt_value, sequence.parser_tree) return True
def add_hook(self, sequence, h): """Create a tree.Hook""" sequence.parser_tree = parsing.Hook(h.name, h.listparam) return True
def param_num(self, param, n): """Parse a int in parameter list""" param.pair = (int(self.value(n)), int) return True
def param_str(self, param, s): """Parse a str in parameter list""" param.pair = (self.value(s).strip('"'), str) return True
def param_char(self, param, c): """Parse a char in parameter list""" param.pair = (self.value(c).strip("'"), str) return True
def param_id(self, param, i): """Parse a node name in parameter list""" param.pair = (self.value(i), parsing.Node) return True
def hook_name(self, hook, n): """Parse a hook name""" hook.name = self.value(n) hook.listparam = [] return True
def hook_param(self, hook, p): """Parse a hook parameter""" hook.listparam.append(p.pair) return True
def add_directive2(self, sequence, d, s): """Add a directive in the sequence""" sequence.parser_tree = parsing.Directive2( d.name, d.listparam, s.parser_tree ) return True
def add_directive(self, sequence, d, s): """Add a directive in the sequence""" if d.name in meta._directives: the_class = meta._directives[d.name] sequence.parser_tree = parsing.Directive(the_class(), d.listparam, s.parser_tree) elif d.name in...
def get_rules(self) -> parsing.Node: """ Parse the DSL and provide a dictionnaries of all resulting rules. Call by the MetaGrammar class. TODO: could be done in the rules property of parsing.BasicParser??? """ res = None try: res = self.eval_rule('bnf...
def to_yml(self): """ Allow to get the YML string representation of a Node.:: from pyrser.passes import to_yml t = Node() ... print(str(t.to_yml())) """ pp = fmt.tab([]) to_yml_item(self, pp.lsdata, "") return str(pp)
def ignore_cxx(self) -> bool: """Consume comments and whitespace characters.""" self._stream.save_context() while not self.read_eof(): idxref = self._stream.index if self._stream.peek_char in " \t\v\f\r\n": while (not self.read_eof() and self._stream.peek_char...
def add_state(self, s: State): """ all state in the register have a uid """ ids = id(s) uid = len(self.states) if ids not in self.states: self.states[ids] = (uid, s)
def to_dot(self) -> str: """ Provide a '.dot' representation of all State in the register. """ txt = "" txt += "digraph S%d {\n" % id(self) if self.label is not None: txt += '\tlabel="%s";\n' % (self.label + '\l').replace('\n', '\l') txt += "\trankdir=...
def to_dot_file(self, fname: str): """ write a '.dot' file. """ with open(fname, 'w') as f: f.write(self.to_dot())
def to_png_file(self, fname: str): """ write a '.png' file. """ cmd = pipes.Template() cmd.append('dot -Tpng > %s' % fname, '-.') with cmd.open('pipefile', 'w') as f: f.write(self.to_dot())
def to_fmt(self) -> str: """ Provide a useful representation of the register. """ infos = fmt.end(";\n", []) s = fmt.sep(', ', []) for ids in sorted(self.states.keys()): s.lsdata.append(str(ids)) infos.lsdata.append(fmt.block('(', ')', [s])) in...
def nextstate(self, newstate, treenode=None, user_data=None): """ Manage transition of state. """ if newstate is None: return self if isinstance(newstate, State) and id(newstate) != id(self): return newstate elif isinstance(newstate, StateEvent): ...
def checkValue(self, v) -> State: """the str() of Values are stored internally for convenience""" if self.wild_value: return self.nextstate(self.values['*']) elif str(v) in self.values: return self.nextstate(self.values[str(v)]) return self
def resetLivingState(self): """Only one Living State on the S0 of each StateRegister""" # TODO: add some test to control number of instanciation of LivingState # clean all living state on S0 must_delete = [] l = len(self.ls) for idx, ls in zip(range(l), self.ls): ...
def infer_type(self, init_scope: Scope=None, diagnostic=None): """ Do inference. Write infos into diagnostic object, if this parameter is not provide and self is a AST (has is own diagnostic object), use the diagnostic of self. """ # create the first .infer_node i...
def feedback(self, diagnostic=None): """ Do feedback. Write infos into diagnostic object, if this parameter is not provide and self is a AST (has is own diagnostic object), use the diagnostic of self. """ # get algo type_algo = self.type_algos() if diagnos...
def infer_block(self, body, diagnostic=None): """ Infer type on block is to type each of is sub-element """ # RootBlockStmt has his own .infer_node (created via infer_type) for e in body: e.infer_node = InferNode(parent=self.infer_node) e.infer_type(diagno...
def infer_subexpr(self, expr, diagnostic=None): """ Infer type on the subexpr """ expr.infer_node = InferNode(parent=self.infer_node) expr.infer_type(diagnostic=diagnostic)
def infer_id(self, ident, diagnostic=None): """ Infer type from an ID! - check if ID is declarated in the scope - if no ID is polymorphic type """ # check if ID is declared #defined = self.type_node.get_by_symbol_name(ident) defined = self.infer_node.scope...
def infer_literal(self, args, diagnostic=None): """ Infer type from an LITERAL! Type of literal depend of language. We adopt a basic convention """ literal, t = args #self.type_node.add(EvalCtx.from_sig(Val(literal, t))) self.infer_node.scope_node.add(Eval...
def dump_nodes(self): """ Dump tag,rule,id and value cache. For debug. example:: R = [ #dump_nodes ] """ print("DUMP NODE LOCAL INFOS") try: print("map Id->node name") for k, v in self.id_cache.items(): print("[%d]=%s" % (k, v)) ...
def list_dataset_uris(cls, base_uri, config_path): """Return list containing URIs with base URI.""" uri_list = [] parse_result = generous_parse_uri(base_uri) bucket_name = parse_result.netloc bucket = boto3.resource('s3').Bucket(bucket_name) for obj in bucket.objects.fi...
def get_item_abspath(self, identifier): """Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed """ admin_metadata = self.get_admin_metadata() uuid = admin_metad...
def list_overlay_names(self): """Return list of overlay names.""" bucket = self.s3resource.Bucket(self.bucket) overlay_names = [] for obj in bucket.objects.filter( Prefix=self.overlays_key_prefix ).all(): overlay_file = obj.key.rsplit('/', 1)[-1] ...
def add_item_metadata(self, handle, key, value): """Store the given key:value pair for the item associated with handle. :param handle: handle for accessing an item before the dataset is frozen :param key: metadata key :param value: metadata value """ ...
def iter_item_handles(self): """Return iterator over item handles.""" bucket = self.s3resource.Bucket(self.bucket) for obj in bucket.objects.filter(Prefix=self.data_key_prefix).all(): relpath = obj.get()['Metadata']['handle'] yield relpath
def get_item_metadata(self, handle): """Return dictionary containing all metadata associated with handle. In other words all the metadata added using the ``add_item_metadata`` method. :param handle: handle for accessing an item before the dataset is frozen ...
def parserrule_topython(parser: parsing.BasicParser, rulename: str) -> ast.FunctionDef: """Generates code for a rule. def rulename(self): <code for the rule> return True """ visitor = RuleVisitor() rule = parser._rules[rulename] fn_args = ast.arguments([a...
def __exit_scope(self) -> ast.stmt: """Create the appropriate scope exiting statement. The documentation only shows one level and always uses 'return False' in examples. 'raise AltFalse()' within a try. 'break' within a loop. 'return False' otherwise. """ ...
def _clause(self, pt: parsing.ParserTree) -> [ast.stmt]: """Normalize a test expression into a statements list. Statements list are returned as-is. Expression is packaged as: if not expr: return False """ if isinstance(pt, list): return pt ...
def visit_Call(self, node: parsing.Call) -> ast.expr: """Generates python code calling the function. fn(*args) """ return ast.Call( ast.Attribute( ast.Name('self', ast.Load), node.callObject.__name__, ast.Load()), [...
def visit_CallTrue(self, node: parsing.CallTrue) -> ast.expr: """Generates python code calling the function and returning True. lambda: fn(*args) or True """ return ast.Lambda( ast.arguments([], None, None, [], None, None, [], []), ast.BoolOp( ast...
def visit_Hook(self, node: parsing.Hook) -> ast.expr: """Generates python code calling a hook. self.evalHook('hookname', self.ruleNodes[-1]) """ return ast.Call( ast.Attribute( ast.Name('self', ast.Load()), 'evalHook', ast.Load()), [ ...
def visit_Rule(self, node: parsing.Rule) -> ast.expr: """Generates python code calling a rule. self.evalRule('rulename') """ return ast.Call( ast.Attribute(ast.Name('self', ast.Load()), 'evalRule', ast.Load()), [ast.Str(node.name)], [], ...
def visit_Capture(self, node: parsing.Capture) -> [ast.stmt] or ast.expr: """Generates python code to capture text consumed by a clause. #If all clauses can be inlined self.beginTag('tagname') and clause and self.endTag('tagname') if not self.beginTag('tagname'): return Fal...
def visit_Scope(self, node: parsing.Capture) -> [ast.stmt] or ast.expr: """Generates python code for a scope. if not self.begin(): return False res = self.pt() if not self.end(): return False return res """ return ast.Name('scope_not_imple...
def visit_Alt(self, node: parsing.Alt) -> [ast.stmt]: """Generates python code for alternatives. try: try: <code for clause> #raise AltFalse when alternative is False raise AltTrue() except AltFalse: pass return False ...
def visit_Seq(self, node: parsing.Seq) -> [ast.stmt] or ast.expr: """Generates python code for clauses. #Continuous clauses which can can be inlined are combined with and clause and clause if not clause: return False if not clause: return False "...
def visit_RepOptional(self, node: parsing.RepOptional) -> ([ast.stmt] or ast.expr): """Generates python code for an optional clause. <code for the clause> """ cl_ast = self.visit(node.pt) if isinstance(cl_ast, ast.ex...
def visit_Rep0N(self, node: parsing.Rep0N) -> [ast.stmt]: """Generates python code for a clause repeated 0 or more times. #If all clauses can be inlined while clause: pass while True: <code for the clause> """ cl_ast = self.visit(node.pt) ...
def visit_Rep1N(self, node: parsing.Rep0N) -> [ast.stmt]: """Generates python code for a clause repeated 1 or more times. <code for the clause> while True: <code for the clause> """ clause = self.visit(node.pt) if isinstance(clause, ast.expr): ret...
def synthese(self, month=None): """ month format: YYYYMM """ if month is None and self.legislature == '2012-2017': raise AssertionError('Global Synthesis on legislature does not work, see https://github.com/regardscitoyens/nosdeputes.fr/issues/69') if month is None: ...
def catend(dst: str, src: str, indent) -> str: """cat two strings but handle \n for tabulation""" res = dst txtsrc = src if not isinstance(src, str): txtsrc = str(src) for c in list(txtsrc): if len(res) > 0 and res[-1] == '\n': res += (indentable.char_indent * indentable....
def list_set_indent(lst: list, indent: int=1): """recurs into list for indentation""" for i in lst: if isinstance(i, indentable): i.set_indent(indent) if isinstance(i, list): list_set_indent(i, indent)
def list_to_str(lst: list, content: str, indent: int=1): """recurs into list for string computing """ for i in lst: if isinstance(i, indentable): content = i.to_str(content, indent) elif isinstance(i, list): content = list_to_str(i, content, indent) elif isinstanc...
def echo_nodes(self, *rest): """ Print nodes. example:: R = [ In : node #echo("coucou", 12, node) ] """ txt = "" for thing in rest: if isinstance(thing, Node): txt += self.value(thing) else: txt += str(thing) print(txt) ...
def populate_from_sequence(seq: list, r: ref(Edge), sr: state.StateRegister): """ function that connect each other one sequence of MatchExpr. """ base_state = r # we need to detect the last state of the sequence idxlast = len(seq) - 1 idx = 0 for m in seq: # alternatives are represented ...
def populate_state_register(all_seq: [list], sr: state.StateRegister) -> Edge: """ function that create a state for all instance of MatchExpr in the given list and connect each others. """ # Basic State s0 = state.State(sr) # loop on himself s0.matchDefault(s0) # this is default ...
def build_state_tree(self, tree: list, sr: state.StateRegister): """ main function for creating a bottom-up tree automata for a block of matching statements. """ all_seq = [] # for all statements populate a list # from deeper to nearer of MatchExpr instances. ...
def pred_eq(self, n, val): """ Test if a node set with setint or setstr equal a certain value example:: R = [ __scope__:n ['a' #setint(n, 12) | 'b' #setint(n, 14)] C [#eq(n, 12) D] ] """ v1 = n.value v2 = val if hasattr(val, ...
def from_string(bnf: str, entry=None, *optional_inherit) -> Grammar: """ Create a Grammar from a string """ inherit = [Grammar] + list(optional_inherit) scope = {'grammar': bnf, 'entry': entry} return build_grammar(tuple(inherit), scope)
def from_file(fn: str, entry=None, *optional_inherit) -> Grammar: """ Create a Grammar from a file """ import os.path if os.path.exists(fn): f = open(fn, 'r') bnf = f.read() f.close() inherit = [Grammar] + list(optional_inherit) scope = {'grammar': bnf, 'entry...
def parse(self, source: str=None, entry: str=None) -> parsing.Node: """Parse source using the grammar""" self.from_string = True if source is not None: self.parsed_stream(source) if entry is None: entry = self.entry if entry is None: raise Valu...
def parse_file(self, filename: str, entry: str=None) -> parsing.Node: """Parse filename using the grammar""" self.from_string = False import os.path with open(filename, 'r') as f: self.parsed_stream(f.read(), os.path.abspath(filename)) if entry is None: en...