Best Python code snippet using avocado_python
parser.py
Source:parser.py  
...4    def __init__(self, database):5        self.parseCypher = _ParseCypher(database)6    def parse(self, cypher_query):7        node = pycypher.parse(cypher_query)8        return self.parseCypher.process_node(node)9class _ParseCypher:10    def __init__(self, database):11        self.database = database12    def process_node(self, node):13        errors = node['errors']14        name = node['name']15        result = node['result']16        if len(errors) > 0:17            print(f"There are errors in the query:")18            print(errors)19            raise RuntimeError20        if name == 'Cypher':21            for r in result:22                try:23                    if r['children']['name'] == 'Statement':24                        return self.process_node(r['children'])25                except KeyError:26                    continue27        elif name == 'Statement':28            return self.process_node(result[0]['children'])29        elif name == 'Query':30            return self.process_node(result[0]['children'])31        elif name == 'StandaloneQuery':32            raise RuntimeError("We don not support StandaloneQuery queries (yet).")33        elif name == 'RegularQuery':34            out = ''35            for r in result:36                if r['node'] == r['children']:37                    continue38                if len(out) > 0:39                    out += ' '40                if r['children']['name'] == 'SingleQuery':41                    out += _ParseSingleQuery(self.database).process_node(r['children'])42                else:43                    out += self.process_node(r['children'])44            return out45        elif name == 'Union':46            union = ''47            for r in result[:-1]:48                union += r['node']['text']49            union = union.strip()50            return union + ' ' + _ParseSingleQuery(self.database).process_node(result[-1]['children'])51        else:52            raise RuntimeError(f'Queries that make use of >>{name}<< are not supported (yet).')53class _ParseSingleQuery:54    def __init__(self, database):55        self.output_params = {56            "Order": '',57            "Skip": '',58            "Limit": ''59        }60        self.additional_wheres = list()61        self.metadata = Metadata(database)62    def build_select_statement(self, pattern):63        output = ''64        # First the start node65        s_node = pattern['NodePattern'][0]66        try:67            s_variable = s_node['Variable']68        except KeyError:69            s_variable = 'start_node'70        try:71            s_label = s_node['NodeLabels']72        except KeyError:73            raise RuntimeError('The type of a node needs to be know for know')74        try:75            s_properties = s_node['Properties']76            for key, value in s_properties.items():77                self.additional_wheres.append(f"""{s_variable}.{key} = {value.replace('"', "'")}""")78        except KeyError:79            pass80        output += f'{s_label} AS {s_variable}'81        # Then the chain82        try:83            chain = pattern['PatternElementChain']84        except KeyError:85            return output86        p_label = s_label87        p_variable = s_variable88        for i, chain_part in enumerate(chain):89            to_node = chain_part['node']90            try:91                to_node_variable = to_node['Variable']92            except KeyError:93                to_node_variable = f'Xtn{i}X'94            try:95                to_node_type = to_node['NodeLabels']96            except KeyError:97                raise RuntimeError("The node type needs to be known for now.")98            try:99                to_node_properties = to_node['Properties']100                for key, value in to_node_properties.items():101                    self.additional_wheres.append(f"""{to_node_variable}.{key} = {value.replace('"', "'")}""")102            except KeyError:103                pass104            relationship = chain_part['relationship']105            try:106                rel_variable = relationship['Variable']107            except KeyError:108                rel_variable = f'Xrel{i}X'109            try:110                rel_type = relationship['RelationshipTypes'][0]111            except KeyError:112                rel_type = self.metadata.get_default_join_info(p_label, to_node_type)[0]113            try:114                rel_properties = relationship['Properties']115                for key, value in rel_properties.items():116                    self.additional_wheres.append(f"""{rel_variable}.{key} = {value.replace('"', "'")}""")117            except KeyError:118                pass119            meta = self.metadata.get_all_join_info(p_label, to_node_type)120            if not meta:121                raise RuntimeError(f"There are no edges between these node types known: {p_label} and {to_node_type}")122            meta = meta[0] # TODO unless join table is specified123            join_table, from_node_jk, join_table_fnk, join_table_tnk, to_node_jk = meta124            # Add relationship join and then the node join125            join = f' JOIN {join_table} AS {rel_variable} ON {p_variable}.{from_node_jk} = {rel_variable}.{join_table_fnk}' + \126                   f' JOIN {to_node_type} AS {to_node_variable} ON {rel_variable}.{join_table_tnk} = {to_node_variable}.{to_node_jk}'127            output += join128            p_variable = to_node_variable129            p_label = to_node_type130        return output131    def process_node(self, node):132        name = node['name']133        result = node['result']134        if name == 'SingleQuery':135            return self.process_node(result[0]['children'])136        elif name == 'SinglePartQuery':137            read_part = ''138            return_part = ''139            for r in result:140                if r['node'] == r['children']:141                    continue142                elif r['children']['name'] == 'UpdatingClause':143                    raise RuntimeError('Updates are not supported yet')144                elif r['children']['name'] == 'ReadingClause':145                    if len(read_part) > 0:146                        raise RuntimeError('Only one reading clause per query is supported')147                    read_part = self.process_node(r['children'])148                else:149                    return_part = self.process_node(r['children'])150            return return_part + ' ' + read_part \151                   + self.output_params['Order'] \152                   + self.output_params['Skip'] \153                   + self.output_params['Limit']154        elif name == 'ReadingClause':155            return self.process_node(result[0]['children'])156        elif name == 'Match':157            match_text = ''158            where = ''159            result_generator = (r for r in result)160            r = next(result_generator)161            while r['node'] == r['children']:162                match_text += r['node']['text']163                r = next(result_generator)164            if match_text.strip().upper().startswith('OPTIONAL'):165                raise RuntimeError('For now we do not support OPTIONAL matches yet.')166            pattern = self.process_node(r['children'])167            while True:168                try:169                    r = next(result_generator)170                    if r['node'] == r['children']:171                        continue172                    if r['children']['name'] == 'Where':173                        where = self.process_node(r['children'])174                except StopIteration:175                    break176            match_statement = f'FROM {pattern}'177            if len(where) == 0 and len(self.additional_wheres) > 0:178                where = ' WHERE ' + ' AND '.join(self.additional_wheres)179            elif len(self.additional_wheres) > 0:180                additional_and = ' AND ' + ' AND '.join(self.additional_wheres)181                where += additional_and182            if len(where) > 0:183                match_statement += where184            return match_statement185        elif name == 'Pattern':186            return_expression = ''187            for r in result:188                if r['node'] == r['children']:189                    return_expression += r['node']['text']190                else:191                    return_expression += self.process_node(r['children'])192            return return_expression193        elif name == 'PatternPart':194            return_expression = ''195            for r in result:196                if r['node'] == r['children']:197                    return_expression += r['node']['text']198                elif r['children']['name'] == 'Variable':199                    raise RuntimeError('Variable assignment of patterns is not supported yet.')200                else:201                    return_expression += self.process_node(r['children'])202            return return_expression203        elif name == 'AnonymousPatternPart':204            return ''.join([self.process_node(r['children']) for r in result])205        elif name == 'PatternElement':206            # Get processed chain data207            pattern = dict()208            for r in result:209                if r['node'] == r['children']:210                    continue211                else:212                    try:213                        pattern[r['children']['name']].append(self.process_node(r['children']))214                    except KeyError:215                        pattern[r['children']['name']] = [self.process_node(r['children'])]216            return self.build_select_statement(pattern)217        elif name == 'NodePattern':218            node = dict()219            for r in result:220                if r['node'] == r['children']:221                    continue222                else:223                    node[r['children']['name']] = self.process_node(r['children'])224            return node225        elif name == 'NodeLabels':226            if len(result) > 1:227                raise RuntimeError("Only one node label at a time is supported")228            return self.process_node(result[0]['children'])229        elif name == 'NodeLabel':230            node_label = ''231            for r in result:232                if r['node'] == r['children']:233                    continue234                else:235                    node_label = self.process_node(r['children'])236            return node_label237        elif name == 'LabelName':238            return self.process_node(result[0]['children'])239        elif name == 'Properties':240            return self.process_node(result[0]['children'])241        elif name == 'MapLiteral':242            map_literal = dict()243            key = None244            for r in result:245                if r['node'] == r['children']:246                    continue247                elif r['children']['name'] == 'PropertyKeyName':248                    key = self.process_node(r['children'])249                elif r['children']['name'] == 'Expression':250                    map_literal[key] = self.process_node(r['children'])251                    key = None252            return map_literal253        elif name == 'PatternElementChain':254            relationship = None255            node = None256            for r in result:257                if r['node'] == r['children']:258                    continue259                elif r['children']['name'] == 'RelationshipPattern':260                    relationship = self.process_node(r['children'])261                else:262                    node = self.process_node(r['children'])263            return {'relationship': relationship, 'node': node}264        elif name == 'RelationshipPattern':265            for r in result:266                if r['children']['name'] == 'Dash':267                    continue268                elif r['children']['name'] in {'LeftArrowHead', 'RightArrowHead'}:269                    raise RuntimeError('Directed edges are not supported yet.')270                else:271                    return self.process_node(r['children'])272            raise RuntimeError("RelationshipPattern should return a pattern")273        elif name == 'RelationshipDetail':274            relation = dict()275            for r in result:276                if r['node'] == r['children']:277                    continue278                else:279                    relation[r['children']['name']] = self.process_node(r['children'])280            return relation281        elif name == 'RelationshipTypes':282            relationship_types = []283            for r in result:284                if r['node'] == r['children']:285                    continue286                else:287                    relationship_types.append(self.process_node(r['children']))288            if len(relationship_types) > 1:289                raise RuntimeError("We only support one join table at a time for now.")290            return relationship_types291        elif name == 'RelTypeName':292            return self.process_node(result[0]['children'])293        elif name == 'Where':294            where_statement = ' '295            for r in result:296                if r['node'] == r['children']:297                    where_statement += r['node']['text']298                else:299                    where_statement += self.process_node(r['children'])300            return where_statement301        elif name == 'Return':302            out = ''303            for r in result[1:]:304                if r['node'] == r['children']:305                    if len(r['node']['text'].strip()) == 0:306                        continue307                    out += r['node']['text'].strip() + ' '308                else:309                    out += self.process_node(r['children'])310            return 'SELECT ' + out311        elif name == 'ReturnBody':312            out = ''313            for r in result:314                if r['node'] == r['children']:315                    continue316                elif r['children']['name'] == 'ReturnItems':317                    out = self.process_node(r['children'])318                elif r['children']['name'] in {'Order', 'Skip', 'Limit'}:319                    self.output_params[r['children']['name']] = ' ' + r['node']['text']320                else:321                    n = r['children']['name']322                    raise RuntimeError(f'Queries that make use of >>{n}<< are not supported (yet).')323            return out324        elif name == 'ReturnItems':325            return_items = ''326            for r in result:327                return_items += r['node']['text']328            # TODO329            # For now we just assume the ReturnItems is already correct, should make it better such330            # that e.g. nodes can be selected directly (now specific attributes have to be specified).331            return return_items332        elif name == 'Expression':333            return self.process_node(result[0]['children'])334        elif name in {'OrExpression', 'AndExpression', 'XorExpression', 'NotExpression'}:335            keyword = name[:-10]336            expressions = []337            for r in result:338                if r['node'] == r['children']:339                    continue340                else:341                    expressions.append(self.process_node(r['children']))342            if len(expressions) == 1:343                return expressions[0]344            else:345                return f' {keyword.upper()} '.join(expressions)346        elif name == 'ComparisonExpression':347            possible_comparisons = {'=', '<>', '<', '>', '<=', '>='}348            comparisons = []349            for r in result:350                if r['node'] == r['children']:351                    continue352                else:353                    comparisons.append(self.process_node(r['children']))354            if len(comparisons) == 1:355                return comparisons[0]356            elif len(comparisons) == 2:357                return comparisons[0]  + ' ' + comparisons[1]358            else:359                comparison_expressions_unprocessed = []360                comparison_expressions = []361                for i in range(len(comparisons)-1):362                    comparison_expressions_unprocessed.append([comparisons[i], comparisons[i+1]])363                for expression_duo in comparison_expressions_unprocessed:364                    p1, p2 = expression_duo365                    for p in possible_comparisons:366                        p1 = p1.replace(p, '')367                    comparison_expressions.append(p1.strip() + ' ' + p2.strip())368                return ' AND '.join(comparison_expressions)369        elif name == 'PartialComparisonExpression':370            partial_comparison = ''371            for r in result:372                if r['node'] == r['children']:373                    partial_comparison += r['node']['text']374                else:375                    partial_comparison += self.process_node(r['children'])376            return partial_comparison377        elif name in {'AddOrSubtractExpression', 'MultiplyDivideModuloExpression',378                      'PowerOfExpression', 'UnaryAddOrSubtractExpression'}:379            return_expression= ''380            for r in result:381                if r['node'] == r['children']:382                    return_expression += r['node']['text']383                else:384                    return_expression += self.process_node(r['children'])385            return return_expression386        elif name == 'StringListNullOperatorExpression':387            return ' '.join([self.process_node(r['children']) for r in result])388        elif name == 'NullOperatorExpression':389            return ''.join([r['node']['text'] for r in result]).strip()390        elif name == 'PropertyOrLabelsExpression':391            return ''.join([self.process_node(r['children']) for r in result])392        elif name == 'PropertyLookup':393            return_expression = ''394            for r in result:395                if r['node'] == r['children']:396                    return_expression += r['node']['text']397                else:398                    return_expression += self.process_node(r['children'])399            return return_expression400        elif name == 'SchemaName':401            return_expression = ''402            for r in result:403                if r['node'] == r['children']:404                    return_expression += r['node']['text']405                else:406                    return_expression += self.process_node(r['children'])407            return return_expression408        elif name == 'PropertyKeyName':409            return_expression = ''410            for r in result:411                if r['node'] == r['children']:412                    return_expression += r['node']['text']413                else:414                    return_expression += self.process_node(r['children'])415            return return_expression416        elif name == 'Atom':417            return_expression = ''418            for r in result:419                if r['node'] == r['children']:420                    return_expression += r['node']['text']421                else:422                    return_expression += self.process_node(r['children'])423            return return_expression424        elif name == 'FunctionInvocation':425            return_expression = ''426            for r in result:427                if r['node'] == r['children']:428                    return_expression += r['node']['text']429                elif r['children']['name'] == 'FunctionName':430                    return_expression += r['node']['text']431                else:432                    return_expression += self.process_node(r['children'])433            return return_expression434        elif name == 'Literal':435            return_expression = ''436            for r in result:437                if r['node'] == r['children']:438                    return_expression += r['node']['text'].replace('"', "'")439                else:440                    return_expression += self.process_node(r['children'])441            return return_expression442        elif name == 'NumberLiteral':443            return self.process_node(result[0]['children'])444        elif name == 'DoubleLiteral':445            return ''.join([r['node']['text'] for r in result]).strip()446        elif name == 'IntegerLiteral':447            return ''.join([r['node']['text'] for r in result]).strip()448        elif name == 'Variable':449            return self.process_node(result[0]['children'])450        elif name == 'SymbolicName':451            return ''.join([r['node']['text'] for r in result]).strip()452        elif name == 'ParenthesizedExpression':453            return_expression = ''454            for r in result:455                if r['node'] == r['children']:456                    return_expression += r['node']['text']457                else:458                    return_expression += self.process_node(r['children'])459            return return_expression460        elif name == 'MultiPartQueries':461            raise RuntimeError('The keyword WITH is not supported (yet).')462        else:...3. Поиск неиспользованных переменных (old).py
Source:3. Поиск неиспользованных переменных (old).py  
1# обÑ
од в глÑбинÑ, Ñ ÑиÑÑемой деÑекÑии иÑполÑÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ Ð¿ÐµÑеменной2# def find_unused_vars(code):3#     def process_node(node, using):4#         if isinstance(node, (list, tuple)):5#             for _node in node:6#                 process_node(_node, using)7#         elif isinstance(node, ast.Name):  # именованнÑй обÑекÑ8#             # print(ast.dump(node), using)9#             if using:10#                 used.add(node.id)11#                 if node.id in used:  # еÑли пеÑÐµÐ¼ÐµÐ½Ð½Ð°Ñ Ð±Ñла опÑеделена Ñанее12#                     used.remove(node.id)13#             else:14#                 declared.add(node.id)15#         elif isinstance(node, ast.Expr):  # вÑÑажение16#             # print(ast.dump(node))17#             process_node(node.value, True)18#         elif isinstance(node, ast.Assign):  # пÑиÑваивание19#             process_node(node.targets, False)20#             process_node(node.value, True)21#         elif isinstance(node, ast.UnaryOp):  # ÑнаÑÐ½Ð°Ñ Ð¾Ð¿ÐµÑаÑиÑ22#             process_node(node.operand, using)23#         elif isinstance(node, ast.BinOp):  # бинаÑÐ½Ð°Ñ Ð¾Ð¿ÐµÑаÑиÑ24#             process_node(node.left, True)25#             process_node(node.right, True)26#         elif isinstance(node, ast.BoolOp):  # логиÑеÑÐºÐ°Ñ Ð¾Ð¿ÐµÑаÑиÑ27#             for _node in node.values:28#                 process_node(_node, False)29#         elif isinstance(node, ast.AugAssign):  # ÑоÑÑавное пÑиÑваивание30#             process_node(node.target, False)  # TODO: можеÑ, и Ð½ÐµÑ ÑмÑÑла обÑабаÑÑваÑÑ31#             process_node(node.value, True)32#         elif isinstance(node, ast.Compare):  # опеÑаÑÐ¸Ñ ÑÑавнениÑ33#             process_node(node.left, True)34#             for _node in node.comparators:35#                 process_node(_node, True)36#         elif isinstance(node, ast.Delete):  # Ñдаление37#             for _node in node.targets:38#                 process_node(_node, True)39#         elif isinstance(node, ast.Call):  # вÑзов (ÑÑнкÑии, клаÑÑа)40#             process_node(node.func, True)41#             for _node in node.args:42#                 process_node(_node, True)43#             for _node in node.keywords:44#                 process_node(_node, True)45#         elif isinstance(node, ast.Attribute):  # доÑÑÑп к ÑвойÑÑÐ²Ñ Ð¸Ð»Ð¸ меÑодÑ46#             process_node(node.value, True)47#         elif isinstance(node, ast.keyword):  # именованнÑй аÑгÑменÑ48#             process_node(node.value, True)49#         elif isinstance(node, (ast.Tuple, ast.List, ast.Set)):  # ÑпиÑок/коÑÑеж/множеÑÑво50#             for _node in node.elts:51#                 process_node(_node, using)52#             # TODO keywords53#         elif isinstance(node, ast.Dict):  # ÑловаÑÑ54#             for _node in node.keys:55#                 process_node(_node, True)56#             for _node in node.values:57#                 process_node(_node, True)58#         elif isinstance(node, ast.If):  # ÑÑловие59#             process_node(node.test, True)60#             if hasattr(node, 'comparators'):61#                 for _node in node.comparators:62#                     process_node(_node, True)63#             for _node in node.body:64#                 process_node(_node, False)65#             for _node in node.orelse:66#                 process_node(_node, False)67#         elif isinstance(node, ast.IfExp):  # ÑеÑнаÑнÑй опеÑаÑоÑ68#             process_node(node.test, True)69#             process_node(node.body, using)70#             process_node(node.orelse, using)71#         elif isinstance(node, ast.Subscript):  # взÑÑие по индекÑÑ Ð¸Ð»Ð¸ ÑÑезÑ72#             process_node(node.value, True)73#             process_node(node.slice, True)74#         elif isinstance(node, ast.Index):  # индекÑ75#             process_node(node.value, True)76#         elif isinstance(node, ast.Slice):  # ÑÑез77#             process_node(node.lower, True)78#             process_node(node.upper, True)79#             if node.step is not None:80#                 process_node(node.step, True)81#         elif isinstance(node, ast.For):  # Ñикл for82#             process_node(node.target, False)83#             process_node(node.iter, True)84#             for _node in node.body:85#                 process_node(_node, False)86#             for _node in node.orelse:87#                 process_node(_node, False)88#         elif isinstance(node, ast.While):  # Ñикл while89#             process_node(node.test, True)90#             for _node in node.body:91#                 process_node(_node, False)92#             for _node in node.orelse:93#                 process_node(_node, False)94#         elif isinstance(node, ast.With):  # опеÑаÑÐ¾Ñ with95#             for _node in node.items:  # withitem96#                 process_node(_node.context_expr, True)97#                 process_node(_node.optional_vars, False)98#             for _node in node.body:99#                 process_node(_node, False)100#         else:101#             try:  # Ð´Ð»Ñ ÑовмеÑÑимоÑÑи Ñ Python < 3.6102#                 if isinstance(node, ast.FormattedValue):  # ÑоÑмаÑиÑÐ¾Ð²Ð°Ð½Ð½Ð°Ñ ÑÑÑока103#                     process_node(node.value, True)104#                     return105#             except AttributeError:106#                 pass107#             # print(ast.dump(node))108#109#     declared = set()  # обÑÑвленнÑе пеÑеменнÑе110#     used = set()  # иÑполÑзованнÑе пеÑеменнÑе111#     tree = ast.parse(code)112#     for subtree in tree.body:113#         process_node(subtree, False)114#     # print(declared, used, declared - used)115#     return tuple(declared - used)116# обÑ
од в ÑиÑинÑ, Ñ Ð¸ÑполÑзованием меÑаданнÑÑ
117# def find_unused_vars(code):118#     declared = set()  # имена обÑÑвленнÑÑ
 обÑекÑов119#     used = set()  # имена иÑполÑзованнÑÑ
 обÑекÑов120#     for node in ast.walk(ast.parse(code)):  # ÑекÑÑÑивно пÑоÑ
одим по вÑем Ñзлам121#         if isinstance(node, ast.Name):  # еÑли именованнÑй обÑÐµÐºÑ (пеÑеменнÑе, ÑÑнкÑии, клаÑÑÑ)122#             # пÑиÑваиваеÑÑÑ Ð½Ð¾Ð²Ð¾Ðµ знаÑение123#             if isinstance(node.ctx, ast.Store):  # ctx = Store()124#                 declared.add(node.id)125#                 if node.id in used:  # еÑли пеÑÐµÐ¼ÐµÐ½Ð½Ð°Ñ Ð±Ñла опÑеделена Ñанее126#                     used.remove(node.id)127#             # загÑÑжаеÑÑÑ Ð¸Ð»Ð¸ ÑдалÑеÑÑÑ...day12.py
Source:day12.py  
...4    for line in f:5        lhs, rhs = line.strip().split("-")6        graph[lhs].add(rhs)7        graph[rhs].add(lhs)8def process_node(visited, current, second_visit_used):9    completed = 010    for child in graph[current]:11        if child == "start":12            continue13        if child == "end":14            completed += 115        elif child.islower():16            if child in visited and not second_visit_used:17                completed += process_node(visited | {child}, child, True)18            elif child not in visited:19                completed += process_node(visited | {child}, child, second_visit_used)20        else:21            completed += process_node(visited, child, second_visit_used)22    return completed23print("Part 1:", process_node(set(), "start", True))...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
