text
stringlengths
81
112k
This is only a slot to store and get already initialized poco instance rather than initializing again. You can simply pass the ``current device instance`` provided by ``airtest`` to get the AndroidUiautomationPoco instance. If no such AndroidUiautomationPoco instance, a new instance will be created and ...
Automatically dismiss the target objects Args: targets (:obj:`list`): list of poco objects to be dropped exit_when: termination condition, default is None which means to automatically exit when list of ``targets`` is empty sleep_interval: time interval between e...
See Also: :py:meth:`select <poco.sdk.Selector.ISelector.select>` method in ``ISelector``. def select(self, cond, multiple=False): """ See Also: :py:meth:`select <poco.sdk.Selector.ISelector.select>` method in ``ISelector``. """ return self.selectImpl(cond, multiple, self.getRoot(), 999...
Selector internal implementation. TODO: add later. .. note:: This doc shows only the outline of the algorithm. Do not call this method in your code as this is an internal method. Args: cond (:obj:`tuple`): query expression multiple (:obj:`bool`): whether or no...
Get API key details. def find_by_id(key: str, user: str=None) -> Optional['ApiKey']: """ Get API key details. """ return ApiKey.from_db(db.get_key(key, user))
List all API keys. def find_all(query: Query=None) -> List['ApiKey']: """ List all API keys. """ return [ApiKey.from_db(key) for key in db.get_keys(query)]
List API keys for a user. def find_by_user(user: str) -> List['ApiKey']: """ List API keys for a user. """ return [ApiKey.from_db(key) for key in db.get_keys(qb.from_dict({'user': user}))]
Create an admin API key. def key(username, key, all): """Create an admin API key.""" if username and username not in current_app.config['ADMIN_USERS']: raise click.UsageError('User {} not an admin'.format(username)) def create_key(admin, key): key = ApiKey( user=admin, ...
List admin API keys. def keys(): """List admin API keys.""" for admin in current_app.config['ADMIN_USERS']: try: db.get_db() # init db on global app context keys = ApiKey.find_by_user(admin) except Exception as e: click.echo('ERROR: {}'.format(e)) el...
Create admin users (BasicAuth only). def user(username, password, all): """Create admin users (BasicAuth only).""" if current_app.config['AUTH_PROVIDER'] != 'basic': raise click.UsageError('Not required for {} admin users'.format(current_app.config['AUTH_PROVIDER'])) if username and username not in...
List admin users. def users(): """List admin users.""" for admin in current_app.config['ADMIN_USERS']: try: db.get_db() # init db on global app context user = User.find_by_username(admin) except Exception as e: click.echo('ERROR: {}'.format(e)) else:...
Get severity of correlated alert. Used to determine previous severity. def get_severity(self, alert): """ Get severity of correlated alert. Used to determine previous severity. """ query = { 'environment': alert.environment, 'resource': alert.resource, ...
Return true if alert severity has changed more than X times in Y seconds def is_flapping(self, alert, window=1800, count=2): """ Return true if alert severity has changed more than X times in Y seconds """ pipeline = [ {'$match': { 'environment': alert.enviro...
Update alert status, service, value, text, timeout and rawData, increment duplicate count and set repeat=True, and keep track of last receive id and time but don't append to history unless status changes. def dedup_alert(self, alert, history): """ Update alert status, service, value, text, time...
Update alert key attributes, reset duplicate count and set repeat=False, keep track of last receive id and time, appending all to history. Append to history again if status changes. def correlate_alert(self, alert, history): """ Update alert key attributes, reset duplicate count and set repeat=...
Set status and update history. def set_status(self, id, status, timeout, update_time, history=None): """ Set status and update history. """ query = {'_id': {'$regex': '^' + id}} update = { '$set': {'status': status, 'timeout': timeout, 'updateTime': update_time}, ...
Append tags to tag list. Don't add same tag more than once. def tag_alert(self, id, tags): """ Append tags to tag list. Don't add same tag more than once. """ response = self.get_db().alerts.update_one( {'_id': {'$regex': '^' + id}}, {'$addToSet': {'tags': {'$each': tags}}})...
Set all attributes and unset attributes by using a value of 'null'. def update_attributes(self, id, old_attrs, new_attrs): """ Set all attributes and unset attributes by using a value of 'null'. """ update = dict() set_value = {'attributes.' + k: v for k, v in new_attrs.items() ...
Return total number of alerts that meet the query filter. def get_count(self, query=None): """ Return total number of alerts that meet the query filter. """ query = query or Query() return self.get_db().alerts.find(query.where).count()
Set all attributes and unset attributes by using a value of 'null'. def update_user_attributes(self, id, old_attrs, new_attrs): """ Set all attributes and unset attributes by using a value of 'null'. """ from alerta.utils.collections import merge merge(old_attrs, new_attrs) ...
Does this alert match a blackout period? def is_blackout(self) -> bool: """Does this alert match a blackout period?""" if not current_app.config['NOTIFICATION_BLACKOUT']: if self.severity in current_app.config['BLACKOUT_ACCEPT']: return False return db.is_blackout_pe...
should return internal id of external system def take_action(self, alert, action, text, **kwargs): """should return internal id of external system""" BASE_URL = '{}/projects/{}'.format(GITLAB_URL, quote(GITLAB_PROJECT_ID, safe='')) if action == 'createIssue': if 'issue_iid' not in...
Wraps JSONified output for JSONP requests. def jsonp(func): """Wraps JSONified output for JSONP requests.""" @wraps(func) def decorated(*args, **kwargs): callback = request.args.get('callback', False) if callback: data = str(func(*args, **kwargs).data) content = str(...
Return true if alert severity has changed more than X times in Y seconds def is_flapping(self, alert, window=1800, count=2): """ Return true if alert severity has changed more than X times in Y seconds """ select = """ SELECT COUNT(*) FROM alerts, unnest(histor...
Update alert status, service, value, text, timeout and rawData, increment duplicate count and set repeat=True, and keep track of last receive id and time but don't append to history unless status changes. def dedup_alert(self, alert, history): """ Update alert status, service, value, text, time...
Insert, with return. def _insert(self, query, vars): """ Insert, with return. """ cursor = self.get_db().cursor() self._log(cursor, query, vars) cursor.execute(query, vars) self.get_db().commit() return cursor.fetchone()
Return none or one row. def _fetchone(self, query, vars): """ Return none or one row. """ cursor = self.get_db().cursor() self._log(cursor, query, vars) cursor.execute(query, vars) return cursor.fetchone()
Return multiple rows. def _fetchall(self, query, vars, limit=None, offset=0): """ Return multiple rows. """ if limit is None: limit = current_app.config['DEFAULT_PAGE_SIZE'] query += ' LIMIT %s OFFSET %s''' % (limit, offset) cursor = self.get_db().cursor() ...
Update, with optional return. def _updateone(self, query, vars, returning=False): """ Update, with optional return. """ cursor = self.get_db().cursor() self._log(cursor, query, vars) cursor.execute(query, vars) self.get_db().commit() return cursor.fetchon...
Update, with optional return. def _updateall(self, query, vars, returning=False): """ Update, with optional return. """ cursor = self.get_db().cursor() self._log(cursor, query, vars) cursor.execute(query, vars) self.get_db().commit() return cursor.fetchal...
Return True if wanted scope is in list of scopes or derived scopes. :param want_scope: scope wanted for permission to do something (str because could be invalid scope) :param have_scopes: list of valid scopes that user has been assigned def is_in_scope(cls, want_scope: str, have_scopes: List[Scope]) -...
Merge two dictionaries. :param dict1: :param dict2: :return: def merge(dict1, dict2): """ Merge two dictionaries. :param dict1: :param dict2: :return: """ for k in dict2: if k in dict1 and isinstance(dict1[k], dict) and isinstance(dict2[k], dict): merge(dict1...
Return a scope based on the supplied action and resource. :param action: the scope action eg. read, write or admin :param resource: the specific resource of the scope, if any eg. alerts, blackouts, heartbeats, users, perms, customers, keys, webhooks, oembed, management or userin...
ingests and deparses a given code block 'co'. If version is None, we will use the current Python interpreter version. def code_deparse(co, out=sys.stdout, version=None, debug_opts=DEFAULT_DEBUG_OPTS, code_objects={}, compile_mode='exec', is_pypy=IS_PYPY, walker=SourceWalker): """ ingests a...
Return the deparsed text for a Python code object. `out` is where any intermediate output for assembly or tree output will be sent. def deparse_code2str(code, out=sys.stdout, version=None, debug_opts=DEFAULT_DEBUG_OPTS, code_objects={}, compile_mode='exec', ...
Pretty print a tuple def pp_tuple(self, tup): """Pretty print a tuple""" last_line = self.f.getvalue().split("\n")[-1] l = len(last_line)+1 indent = ' ' * l self.write('(') sep = '' for item in tup: self.write(sep) l += len(sep) ...
exec_stmt ::= expr exprlist DUP_TOP EXEC_STMT exec_stmt ::= expr exprlist EXEC_STMT def n_exec_stmt(self, node): """ exec_stmt ::= expr exprlist DUP_TOP EXEC_STMT exec_stmt ::= expr exprlist EXEC_STMT """ self.write(self.indent, 'exec ') self.preorder(node[0]) ...
List comprehensions def n_list_comp(self, node): """List comprehensions""" p = self.prec self.prec = 100 if self.version >= 2.7: if self.is_pypy: self.n_list_comp_pypy27(node) return n = node[-1] elif node[-1] == 'del_stmt'...
List comprehensions in PYPY. def n_list_comp_pypy27(self, node): """List comprehensions in PYPY.""" p = self.prec self.prec = 27 if node[-1].kind == 'list_iter': n = node[-1] elif self.is_pypy and node[-1] == 'JUMP_BACK': n = node[-2] list_expr = ...
Non-closure-based comprehensions the way they are done in Python3 and some Python 2.7. Note: there are also other set comprehensions. def comprehension_walk_newer(self, node, iter_index, code_index=-5): """Non-closure-based comprehensions the way they are done in Python3 and some Python 2.7. No...
List comprehensions the way they are done in Python 2 and sometimes in Python 3. They're more other comprehensions, e.g. set comprehensions See if we can combine code. def listcomprehension_walk2(self, node): """List comprehensions the way they are done in Python 2 and sometimes...
Set comprehensions the way they are done in Python3. They're more other comprehensions, e.g. set comprehensions See if we can combine code. def setcomprehension_walk3(self, node, collection_index): """Set comprehensions the way they are done in Python3. They're more other comprehensions...
prettyprint a dict 'dict' is something like k = {'a': 1, 'b': 42}" We will source-code use line breaks to guide us when to break. def n_dict(self, node): """ prettyprint a dict 'dict' is something like k = {'a': 1, 'b': 42}" We will source-code use line breaks to guide u...
prettyprint a list or tuple def n_list(self, node): """ prettyprint a list or tuple """ p = self.prec self.prec = 100 lastnode = node.pop() lastnodetype = lastnode.kind # If this build list is inside a CALL_FUNCTION_VAR, # then the first * has al...
The format template interpetation engine. See the comment at the beginning of this module for the how we interpret format specifications such as %c, %C, and so on. def template_engine(self, entry, startnode): """The format template interpetation engine. See the comment at the beginnin...
Special handling for opcodes, such as those that take a variable number of arguments -- we add a new entry for each in TABLE_R. def customize(self, customize): """ Special handling for opcodes, such as those that take a variable number of arguments -- we add a new entry for each in TABL...
If the name of the formal parameter starts with dot, it's a tuple parameter, like this: # def MyFunc(xx, (a,b,c), yy): # print a, b*2, c*42 In byte-code, the whole tuple is assigned to parameter '.1' and then the tuple gets unpacked to 'a', 'b' and 'c'. ...
Dump class definition, doc string and class body. def build_class(self, code): """Dump class definition, doc string and class body.""" assert iscode(code) self.classes.append(self.currentclass) code = Code(code, self.scanner, self.currentclass) indent = self.indent # s...
convert SyntaxTree to Python source code def gen_source(self, ast, name, customize, is_lambda=False, returnNone=False): """convert SyntaxTree to Python source code""" rn = self.return_none self.return_none = returnNone old_name = self.name self.name = name # if code wou...
diassembles and deparses a given code block 'co' def disco(version, co, out=None, is_pypy=False): """ diassembles and deparses a given code block 'co' """ assert iscode(co) # store final output stream for case of error real_out = out or sys.stdout print('# Python %s' % version, file=real_...
disassemble Python byte-code file (.pyc) If given a Python source file (".py") file, we'll try to find the corresponding compiled object. def disassemble_file(filename, outstream=None): """ disassemble Python byte-code file (.pyc) If given a Python source file (".py") file, we'll try to find ...
The base grammar we start out for a Python version even with the subclassing is, well, is pretty base. And we want it that way: lean and mean so that parsing will go faster. Here, we add additional grammar rules based on specific instructions that are in the instruction/token stream. I...
ingests and deparses a given code block 'co' def code_deparse_align(co, out=sys.stderr, version=None, is_pypy=None, debug_opts=DEFAULT_DEBUG_OPTS, code_objects={}, compile_mode='exec'): """ ingests and deparses a given code block 'co' """ assert iscode(co)...
Show the asm based on the showasm flag (or file object), writing to the appropriate stream depending on the type of the flag. :param showasm: Flag which determines whether the ingested code is written to sys.stdout or not. (It is also to pass a file like object, into whi...
Show the ast based on the showast flag (or file object), writing to the appropriate stream depending on the type of the flag. :param show_tree: Flag which determines whether the parse tree is written to sys.stdout or not. (It is also to pass a file like object, into ...
Show a function parameter with default for an grammar-tree based on the show_tree flag (or file object), writing to the appropriate stream depending on the type of the flag. :param show_tree: Flag which determines whether the function parameter with default is written to sys.stdout or...
Pick out tokens from an uncompyle6 code object, and transform them, returning a list of uncompyle6 Token's. The transformations are made to assist the deparsing grammar. def ingest(self, co, classname=None, code_objects={}, show_asm=None): """ Pick out tokens from an uncompyle6 code ob...
Pick out tokens from an uncompyle6 code object, and transform them, returning a list of uncompyle6 Token's. The transformations are made to assist the deparsing grammar. Specificially: - various types of LOAD_CONST's are categorized in terms of what they load - COME_FROM...
Detect all offsets in a byte code which are jump targets where we might insert a COME_FROM instruction. Return the list of offsets. Return the list of offsets. An instruction can be jumped to in from multiple instructions. def find_jump_targets(self, debug): """ Detect...
Detect type of block structures and their boundaries to fix optimized jumps in python2.3+ def detect_control_flow(self, offset, targets, inst_index): """ Detect type of block structures and their boundaries to fix optimized jumps in python2.3+ """ code = self.code ...
Return True if the code at offset is some sort of jump back. That is, it is ether "JUMP_FORWARD" or an absolute jump that goes forward. def is_jump_back(self, offset, extended_arg): """ Return True if the code at offset is some sort of jump back. That is, it is ether "JUMP_FORWA...
Return the next jump that was generated by an except SomeException: construct in a try...except...else clause or None if not found. def next_except_jump(self, start): """ Return the next jump that was generated by an except SomeException: construct in a try...except...else clause or Non...
Find offsets of all requested <instr> between <start> and <end>, optionally <target>ing specified offset, and return list found <instr> offsets which are not within any POP_JUMP_IF_TRUE jumps. def rem_or(self, start, end, instr, target=None, include_beyond_target=False): """ Find offset...
Create a list of instructions (a structured object rather than an array of bytes) and store that in self.insts def build_instructions(self, co): """ Create a list of instructions (a structured object rather than an array of bytes) and store that in self.insts """ # FIXME...
Generate various line-related helper data. def build_lines_data(self, code_obj): """ Generate various line-related helper data. """ # Offset: lineno pairs, only for offsets which start line. # Locally we use list for more convenient iteration using indices if self.versi...
Compose 'list-map' which allows to jump to previous op, given offset of current op as index. def build_prev_op(self): """ Compose 'list-map' which allows to jump to previous op, given offset of current op as index. """ code = self.code codelen = len(code) ...
Return True if the code at offset is some sort of jump forward. That is, it is ether "JUMP_FORWARD" or an absolute jump that goes forward. def is_jump_forward(self, offset): """ Return True if the code at offset is some sort of jump forward. That is, it is ether "JUMP_FORWARD" o...
Get next instruction offset for op located at given <offset>. NOTE: extended_arg is no longer used def get_target(self, offset, extended_arg=0): """ Get next instruction offset for op located at given <offset>. NOTE: extended_arg is no longer used """ inst = self.get_ins...
Find the first <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be specified which must match precisely if exact is True, or if exact is False, the instruc...
Find the last <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be specified which must match precisely if exact is True, or if exact is False, the instruct...
Find all `instr` in the block from start to end. `instr` is a Python opcode or a list of opcodes If `instr` is an opcode with a target (like a jump), a target destination can be specified which must match precisely. Return a list with indexes to them or [] if none found. def inst_match...
Find all `instr` in the block from start to end. `instr` is any Python opcode or a list of opcodes If `instr` is an opcode with a target (like a jump), a target destination can be specified which must match precisely. Return a list with indexes to them or [] if none found. def all_inst...
Iterate through positions of opcodes, skipping arguments. def op_range(self, start, end): """ Iterate through positions of opcodes, skipping arguments. """ while start < end: yield start start += instruction_size(self.code[start], self.opc)
Go through instructions removing extended ARG. get_instruction_bytes previously adjusted the operand values to account for these def remove_extended_args(self, instructions): """Go through instructions removing extended ARG. get_instruction_bytes previously adjusted the operand values ...
Go through passed offsets, filtering ifs located somewhere mid-line. def remove_mid_line_ifs(self, ifs): """ Go through passed offsets, filtering ifs located somewhere mid-line. """ # FIXME: this doesn't work for Python 3.6+ filtered = [] for i in ifs: ...
Restrict target to parent structure boundaries. def restrict_to_parent(self, target, parent): """Restrict target to parent structure boundaries.""" if not (parent['start'] < target < parent['end']): target = parent['end'] return target
Returns parser object for Python version 2 or 3, 3.2, 3.5on, etc., depending on the parameters passed. *compile_mode* is either 'exec', 'eval', or 'single'. See https://docs.python.org/3.6/library/functions.html#compile for an explanation of the different modes. def get_python_parser( version,...
Parse a code object to an abstract syntax tree representation. :param version: The python version this code is from as a float, for example 2.6, 2.7, 3.2, 3.3, 3.4, 3.5 etc. :param co: The code object to parse. :param out: File like object to wri...
Add rule to grammar, but only if it hasn't been added previously opname and stack_count are used in the customize() semantic the actions to add the semantic action rule. Stack_count is used in custom opcodes like MAKE_FUNCTION to indicate how many arguments it has. Often it i...
Add rules (a list of string) to grammar. Note that the rules must not be those that set arg_count in the custom dictionary. def add_unique_rules(self, rules, customize): """Add rules (a list of string) to grammar. Note that the rules must not be those that set arg_count in the c...
Add rules (a docstring-like list of rules) to grammar. Note that the rules must not be those that set arg_count in the custom dictionary. def add_unique_doc_rules(self, rules_str, customize): """Add rules (a docstring-like list of rules) to grammar. Note that the rules must not be those...
Remove recursive references to allow garbage collector to collect this object. def cleanup(self): """ Remove recursive references to allow garbage collector to collect this object. """ for dict in (self.rule2func, self.rules, self.rule2name): for i in list(di...
Customized format and print for our kind of tokens which gets called in debugging grammar reduce rules def debug_reduce(self, rule, tokens, parent, last_token_pos): """Customized format and print for our kind of tokens which gets called in debugging grammar reduce rules """ def ...
Return then the number of positional parameters and represented by the attr field of token def get_pos_kw(self, token): """Return then the number of positional parameters and represented by the attr field of token""" # Low byte indicates number of positional paramters, # high by...
Remove __ from the end of _name_ if it starts with __classname__ return the "unmangled" name. def unmangle_name(name, classname): """Remove __ from the end of _name_ if it starts with __classname__ return the "unmangled" name. """ if name.startswith(classname) and name[-2:] != '...
Remove __ from the end of _name_ if it starts with __classname__ return the "unmangled" name. def unmangle_code_names(self, co, classname): """Remove __ from the end of _name_ if it starts with __classname__ return the "unmangled" name. """ if classname: classname = ...
Pick out tokens from an uncompyle6 code object, and transform them, returning a list of uncompyle6 Token's. The transformations are made to assist the deparsing grammar. Specificially: - various types of LOAD_CONST's are categorized in terms of what they load - COME_FROM...
Return the next jump that was generated by an except SomeException: construct in a try...except...else clause or None if not found. def next_except_jump(self, start): """ Return the next jump that was generated by an except SomeException: construct in a try...except...else clause or Non...
Detect type of block structures and their boundaries to fix optimized jumps in python2.3+ def detect_control_flow(self, offset, op, extended_arg): """ Detect type of block structures and their boundaries to fix optimized jumps in python2.3+ """ code = self.code ...
Detect all offsets in a byte code which are jump targets where we might insert a pseudo "COME_FROM" instruction. "COME_FROM" instructions are used in detecting overall control flow. The more detailed information about the control flow is captured in self.structs. Since this stuff...
Find all <instr> in the block from start to end. <instr> is any python bytecode instruction or a list of opcodes If <instr> is an opcode with a target (like a jump), a target destination can be specified which must match precisely. Return a list with indexes to them or [] if none found....
Customize CALL_FUNCTION to add the number of positional arguments def call_fn_name(token): """Customize CALL_FUNCTION to add the number of positional arguments""" if token.attr is not None: return '%s_%i' % (token.kind, token.attr) else: return '%s_0' % (token.kind)
# Should the first rule be somehow folded into the 2nd one? build_class ::= LOAD_BUILD_CLASS mkfunc LOAD_CLASSNAME {expr}^n-1 CALL_FUNCTION_n LOAD_CONST CALL_FUNCTION_n build_class ::= LOAD_BUILD_CLASS mkfunc expr ...
call ::= expr {expr}^n CALL_FUNCTION_n call ::= expr {expr}^n CALL_FUNCTION_VAR_n call ::= expr {expr}^n CALL_FUNCTION_VAR_KW_n call ::= expr {expr}^n CALL_FUNCTION_KW_n classdefdeco2 ::= LOAD_BUILD_CLASS mkfunc {expr}^n-1 CALL_FUNCTION_n def custom_classfunc_rule(self, opname, token, ...
Python 3.3 added a an addtional LOAD_CONST before MAKE_FUNCTION and this has an effect on many rules. def add_make_function_rule(self, rule, opname, attr, customize): """Python 3.3 added a an addtional LOAD_CONST before MAKE_FUNCTION and this has an effect on many rules. """ if ...
The base grammar we start out for a Python version even with the subclassing is, well, is pretty base. And we want it that way: lean and mean so that parsing will go faster. Here, we add additional grammar rules based on specific instructions that are in the instruction/token stream. I...
ingests and deparses a given code block 'co' if `bytecode_version` is None, use the current Python intepreter version. Caller is responsible for closing `out` and `mapstream` def decompile( bytecode_version, co, out=None, showasm=None, showast=False, timestamp=None, showgrammar=False, cod...
decompile Python byte-code file (.pyc). Return objects to all of the deparsed objects found in `filename`. def decompile_file(filename, outstream=None, showasm=None, showast=False, showgrammar=False, mapstream=None, do_fragments=False): """ decompile Python byte-code file (.pyc). Return ...
in_base base directory for input files out_base base directory for output files (ignored when files list of filenames to be uncompyled (relative to in_base) outfile write output to this filename (overwrites out_base) For redirecting output to - <filename> outfile=<filename> (out_base is ignored) ...
Dump function defintion, doc string, and function body. This code is specialized for Python 3 def make_function3_annotate(self, node, is_lambda, nested=1, code_node=None, annotate_last=-1): """ Dump function defintion, doc string, and function body. This code is specialized ...