INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return the unique internal name
def internal_name(self): """ Return the unique internal name """ unq = super().internal_name() if self.tret is not None: unq += "_" + self.tret return unq
Deletes the specified file from the local filesystem.
def _delete_local(self, filename): """Deletes the specified file from the local filesystem.""" if os.path.exists(filename): os.remove(filename)
Deletes the specified file from the given S3 bucket.
def _delete_s3(self, filename, bucket_name): """Deletes the specified file from the given S3 bucket.""" conn = S3Connection(self.access_key_id, self.access_key_secret) bucket = conn.get_bucket(bucket_name) if type(filename).__name__ == 'Key': filename = '/' + filename.name ...
Deletes the specified file either locally or from S3 depending on the file s storage type.
def delete(self, filename, storage_type=None, bucket_name=None): """Deletes the specified file, either locally or from S3, depending on the file's storage type.""" if not (storage_type and bucket_name): self._delete_local(filename) else: if storage_type != 's3': ...
Saves the specified file to the local file system.
def _save_local(self, temp_file, filename, obj): """Saves the specified file to the local file system.""" path = self._get_path(filename) if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path), self.permission | 0o111) fd = open(path, 'wb') ...
Saves the specified file to the configured S3 bucket.
def _save_s3(self, temp_file, filename, obj): """Saves the specified file to the configured S3 bucket.""" conn = S3Connection(self.access_key_id, self.access_key_secret) bucket = conn.get_bucket(self.bucket_name) path = self._get_s3_path(filename) k = bucket.new_key(path) ...
Saves the specified file to either S3 or the local filesystem depending on the currently enabled storage type.
def save(self, temp_file, filename, obj): """Saves the specified file to either S3 or the local filesystem, depending on the currently enabled storage type.""" if not (self.storage_type and self.bucket_name): ret = self._save_local(temp_file, filename, obj) else: if self...
Finds files by licking an S3 bucket s contents by prefix.
def _find_by_path_s3(self, path, bucket_name): """Finds files by licking an S3 bucket's contents by prefix.""" conn = S3Connection(self.access_key_id, self.access_key_secret) bucket = conn.get_bucket(bucket_name) s3_path = self._get_s3_path(path) return bucket.list(prefix=s3_p...
Finds files at the specified path/ prefix either on S3 or on the local filesystem.
def find_by_path(self, path, storage_type=None, bucket_name=None): """Finds files at the specified path / prefix, either on S3 or on the local filesystem.""" if not (storage_type and bucket_name): return self._find_by_path_local(path) else: if storage_type != 's3': ...
Build an enum statement
def enum(*sequential, **named): """ Build an enum statement """ #: build enums from parameter enums = dict(zip(sequential, range(len(sequential))), **named) enums['map'] = copy.copy(enums) #: build reverse mapping enums['rmap'] = {} for key, value in enums.items(): if type(va...
Decorator to verify arguments and return types.
def checktypes(func): """Decorator to verify arguments and return types.""" sig = inspect.signature(func) types = {} for param in sig.parameters.values(): # Iterate through function's parameters and build the list of # arguments types param_type = param.annotation if par...
Add a mapping with key thing_name for callobject in chainmap with namespace handling.
def set_one(chainmap, thing_name, callobject): """ Add a mapping with key thing_name for callobject in chainmap with namespace handling. """ namespaces = reversed(thing_name.split(".")) lstname = [] for name in namespaces: lstname.insert(0, name) strname = '.'.join(lstname) ...
Attach a method to a class.
def add_method(cls): """Attach a method to a class.""" def wrapper(f): #if hasattr(cls, f.__name__): # raise AttributeError("{} already has a '{}' attribute".format( # cls.__name__, f.__name__)) setattr(cls, f.__name__, f) return f return wrapper
Attach a method to a parsing class and register it as a parser hook.
def hook(cls, hookname=None, erase=False): """Attach a method to a parsing class and register it as a parser hook. The method is registered with its name unless hookname is provided. """ if not hasattr(cls, '_hooks'): raise TypeError( "%s didn't seems to be a BasicParser subsclas...
Attach a method to a parsing class and register it as a parser rule.
def rule(cls, rulename=None, erase=False): """Attach a method to a parsing class and register it as a parser rule. The method is registered with its name unless rulename is provided. """ if not hasattr(cls, '_rules'): raise TypeError( "%s didn't seems to be a BasicParser subsclas...
Attach a class to a parsing class and register it as a parser directive.
def directive(directname=None): """Attach a class to a parsing class and register it as a parser directive. The class is registered with its name unless directname is provided. """ global _directives class_dir_list = _directives def wrapper(f): nonlocal directname if direct...
Attach a class to a parsing decorator and register it to the global decorator list. The class is registered with its name unless directname is provided
def decorator(directname=None): """ Attach a class to a parsing decorator and register it to the global decorator list. The class is registered with its name unless directname is provided """ global _decorators class_deco_list = _decorators def wrapper(f): nonlocal d...
Allow to alias a node to another name.
def bind(self, dst: str, src: Node) -> bool: """Allow to alias a node to another name. Useful to bind a node to _ as return of Rule:: R = [ __scope__:L [item:I #add_item(L, I]* #bind('_', L) ] It's also the default behaviour of ':>' """ for m in self.rule_nodes.maps:...
Return True if the parser can consume an EOL byte sequence.
def read_eol(self) -> bool: """Return True if the parser can consume an EOL byte sequence.""" if self.read_eof(): return False self._stream.save_context() self.read_char('\r') if self.read_char('\n'): return self._stream.validate_context() return self._stream.restore_context()
read a hexadecimal number Read the following BNF rule else return False::
def read_hex_integer(self) -> bool: """ read a hexadecimal number Read the following BNF rule else return False:: readHexInteger = [ [ '0'..'9' | 'a'..'f' | 'A'..'F' ]+ ] """ if self.read_eof(): return False self._stream.save_context() c = self._stream.pe...
read a double quoted string Read following BNF rule else return False::
def read_cstring(self) -> bool: """ read a double quoted string Read following BNF rule else return False:: '"' -> ['\\' #char | ~'\\'] '"' """ self._stream.save_context() idx = self._stream.index if self.read_char("\"") and self.read_until("\"", "\\"): txt = self._stream[i...
Push context variable to store rule nodes.
def push_rule_nodes(self) -> bool: """Push context variable to store rule nodes.""" if self.rule_nodes is None: self.rule_nodes = collections.ChainMap() self.tag_cache = collections.ChainMap() self.id_cache = collections.ChainMap() else: self.rule_...
Pop context variable that store rule nodes
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
Return the text value of the node
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...
Push a new Stream into the parser. All subsequent called functions will parse this new stream until the popStream function is called.
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))
Save the current index under the given 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
Extract the string between saved and current index.
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
Merge internal rules set with the given rules
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__ \ + '.' ...
Merge internal hooks set with the given hooks
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__ \ + '.' ...
Merge internal directives set with the given directives. For working directives attach it only in the dsl. Parser class
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(): ...
Evaluate a rule by name.
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: ...
Evaluate the hook by its name
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 ...
Same as readText but doesn t consume the stream.
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
Read one byte in stream
def one_char(self) -> bool: """Read one byte in stream""" if self.read_eof(): return False self._stream.incpos() return True
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.
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._...
Consume the stream while the c byte is not read else return false ex: if stream is abcdef read_until ( d ) ; consume abcd.
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() ...
Consume all the stream. Same as EOF in BNF.
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()
Consume a strlen ( text ) text at current position in the stream else return False. Same as in BNF ex: read_text ( ls ) ;.
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...
Consume head byte if it is > = begin and < = end else return false Same as a.. z in BNF
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...
Consume whitespace characters.
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...
The Decorator call is the one that actually pushes/ pops the decorator in the active decorators list ( parsing. _decorators )
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...
Return the unique internal name
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
Tell the clusterizer the meaning of the field names.
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...
Tell the clusterizer the meaning of the field names.
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_...
Set the data type of the hits.
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: ----------...
Set the data type of the cluster.
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([]) ...
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 )
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: ...
Adding function to module. This is maybe the only way to make the clusterizer to work with multiprocessing.
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
Adding function to module. This is maybe the only way to make the clusterizer to work with multiprocessing.
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
Cluster given hit array.
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 ...
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.
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: ...
Create a tree. { Complement LookAhead Neg Until }
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 == '!': ...
Create a tree. Rule
def add_ruleclause_name(self, ns_name, rid) -> bool: """Create a tree.Rule""" ns_name.parser_tree = parsing.Rule(self.value(rid)) return True
Attach a parser tree to the dict of rules
def add_rules(self, bnf, r) -> bool: """Attach a parser tree to the dict of rules""" bnf[r.rulename] = r.parser_tree return True
Add the rule name
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
Create a tree. Seq
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): ...
Create a tree. Alt
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...
Add a read_char/ read_text primitive from simple quote string
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
Add a read_range primitive
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
Add a repeater to the previous sequence
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...
Create a tree. Capture
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
Create a tree. Bind
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
Create a tree. Hook
def add_hook(self, sequence, h): """Create a tree.Hook""" sequence.parser_tree = parsing.Hook(h.name, h.listparam) return True
Parse a int in parameter list
def param_num(self, param, n): """Parse a int in parameter list""" param.pair = (int(self.value(n)), int) return True
Parse a str in parameter list
def param_str(self, param, s): """Parse a str in parameter list""" param.pair = (self.value(s).strip('"'), str) return True
Parse a char in parameter list
def param_char(self, param, c): """Parse a char in parameter list""" param.pair = (self.value(c).strip("'"), str) return True
Parse a node name in parameter list
def param_id(self, param, i): """Parse a node name in parameter list""" param.pair = (self.value(i), parsing.Node) return True
Parse a hook name
def hook_name(self, hook, n): """Parse a hook name""" hook.name = self.value(n) hook.listparam = [] return True
Parse a hook parameter
def hook_param(self, hook, p): """Parse a hook parameter""" hook.listparam.append(p.pair) return True
Add a directive in the sequence
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
Add a directive in the sequence
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...
Parse the DSL and provide a dictionnaries of all resulting rules. Call by the MetaGrammar class.
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...
Allow to get the YML string representation of a Node.::
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)
Consume comments and whitespace characters.
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...
all state in the register have a uid
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)
Provide a. dot representation of all State in the register.
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=...
write a. dot file.
def to_dot_file(self, fname: str): """ write a '.dot' file. """ with open(fname, 'w') as f: f.write(self.to_dot())
write a. png file.
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())
Provide a useful representation of the register.
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...
Manage transition of state.
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): ...
the str () of Values are stored internally for convenience
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
Only one Living State on the S0 of each StateRegister
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): ...
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.
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...
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.
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...
Infer type on block is to type each of is sub - element
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...
Infer type on the subexpr
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)
Infer type from an ID! - check if ID is declarated in the scope - if no ID is polymorphic type
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...
Infer type from an LITERAL! Type of literal depend of language. We adopt a basic convention
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...
Dump tag rule id and value cache. For debug.
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)) ...
Return list containing URIs with base URI.
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...
Return absolute path at which item content can be accessed.
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...
Return list of overlay names.
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] ...
Store the given key: value pair for the item associated with handle.
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 """ ...
Return iterator over item handles.
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
Return dictionary containing all metadata associated with handle.
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 ...
Generates code for a rule.
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...
Create the appropriate scope exiting statement.
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. """ ...
Normalize a test expression into a statements list.
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 ...
Generates python code calling the function.
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()), [...
Generates python code calling the function and returning True.
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...