Best Python code snippet using avocado_python
tournament.py
Source:tournament.py
1#! /usr/bin/env python32# coding: utf-83import re4class Tournament:5 """Le model pour le tournoi en cours."""6 tournament_in_progress = []7 def __init__(self, tournament_oontroller, index=int(), name="", place="",8 round=4, time_control=list, description="",9 status_participants=list):10 """Initialisation de la classe Tournament."""11 self.controller = tournament_oontroller12 self.index = index13 self.name = name14 self.place = place15 self.round = round16 self.time_control = time_control17 self.description = description18 self.status_participants = status_participants19 def unserial_tournament_in_progress(self, in_progress):20 """Désérialisation du tournoi en cours."""21 self.tournament_in_progress = []22 index = in_progress["index"]23 name = in_progress["name"]24 place = in_progress["place"]25 round = in_progress["round"]26 time_control = in_progress["time_control"]27 description = in_progress["description"]28 status_participants = in_progress["status_participants"]29 self.tournament_in_progress = Tournament("tournament_controller",30 index, name,31 place, round,32 time_control, description,33 status_participants)34 return self.tournament_in_progress35 def add_tournament(self, new_tournament):36 """Création du tournoi en cours à partir des input utilisateur."""37 count_finished = self.controller.get_len_tournaments_finished()38 if count_finished == 0:39 index = 140 else:41 index = count_finished + 142 name = new_tournament[0]43 place = new_tournament[1]44 round = new_tournament[3]45 time_control = new_tournament[4]46 description = new_tournament[5]47 status_participants = new_tournament[2]48 self.tournament_in_progress = Tournament("tournament_controller",49 index, name,50 place, round,51 time_control, description,52 status_participants)53 return self.tournament_in_progress54 @staticmethod55 def check_name(input_name):56 """Vérifie la validité de l'input_name."""57 if input_name == '':58 return "true"59 else:60 return input_name61 @staticmethod62 def check_place(input_place):63 """Vérifie la validité de l'input_place."""64 if input_place == '':65 return "true"66 else:67 return input_place68 def check_participant(self, input_participant):69 """Vérifie la validité de l'input_participant."""70 index_to_check = re.findall("[0-9]+", input_participant)71 if index_to_check == []:72 return "true"73 check = self.controller.get_player_exists(index_to_check)74 return check75 @staticmethod76 def check_round(input_round):77 """Vérifie la validité de l'input_round."""78 if input_round == '':79 return 480 elif input_round != '':81 if input_round.isdigit() is True:82 return int(input_round)83 else:84 return "true"85 @staticmethod86 def check_time_control(input_time_control):87 """Vérifie la validité de l'input_time_control."""88 while input_time_control != '0' \89 and input_time_control != '1' \90 and input_time_control != '2':91 return "true"92 else:93 return input_time_control94 @staticmethod95 def check_description(input_description):96 """Vérifie la lavalidité de l'input_description."""97 if input_description == '':98 return "true"99 else:100 return input_description101 def adding_score_round(self, matchs_round_to_close):102 """à la fin d'un round, ajout du score du round des participants,103 à leur score de tournoi (score cummulé)."""104 in_progress = self.controller.get_unserial_tournament_in_progress()105 for match in matchs_round_to_close:106 try:107 idx_a = match.participant_a["index"]108 score_a = match.participant_a["score"]109 short = "player_index_{}".format(idx_a)110 in_progress.status_participants[short]["score"] += score_a111 except Exception as e:112 osef = []113 osef.append(e)114 continue115 try:116 idx_b = match.participant_b["index"]117 score_b = match.participant_b["score"]118 short = "player_index_{}".format(idx_b)119 in_progress.status_participants[short]["score"] += score_b120 except Exception as e:121 osef = []122 osef.append(e)123 continue124 return self.controller.save_tournament(in_progress)125 def designate_winner_tournament(self):126 # tournament = self.controller.get_unserial_tournament_in_progress()127 # sorted_by_score = tournament.status_participants\128 # .sort(key=attrgetter("score"), reverse=True)129 #130 # winner = sorted_by_score[0]131 pass132class TournamentFinished:133 """Le model pour les tournois terminés."""134 list_finished_tournaments = []135 def __init__(self, finished_controller, len_participants=int(),136 index=list(), name=list(), place=list(), round=list(),137 time_control=list(), participants=list(), description=list()):138 """Initialisation de la classe TournamentFinished."""139 self.controller = finished_controller140 self.len_participants = len_participants141 self.index = index142 self.name = name143 self.place = place144 self.round = round145 self.time_control = time_control146 self.participants = participants147 self.description = description148 def get_data_player(self, index_participant):149 """demande les données d'un joueur selon son index."""150 return self.controller.get_data_player(index_participant)151 @staticmethod152 def unserial_index(tournament, len_participant):153 """Désérialisation de l'index du tournoi."""154 index = []155 index.append("| {:<5} |".format(tournament["tournament"]["index"]))156 for count in range(len_participant - 1):157 index.append("| {:<5} |".format(''))158 return index159 @staticmethod160 def unserial_name(tournament, len_participant):161 """Désérialisation du nom du tournoi."""162 name = []163 name.append(" {:<20} |".format(tournament["tournament"]["name"]))164 for count in range(len_participant - 1):165 name.append(" {:<20} |".format(''))166 return name167 @staticmethod168 def unserial_place(tournament, len_participant):169 """Désérialisation du lieu du tournoi."""170 place = []171 place.append(" {:<20} |".format(tournament["tournament"]["place"]))172 for count in range(len_participant - 1):173 place.append(" {:<20} |".format(''))174 return place175 @staticmethod176 def unserial_round(tournament, len_participants):177 """Désérialisation du nombre de rounds du tournoi."""178 round = []179 round.append(" {:<5} |".format(tournament["tournament"]["round"]))180 for count in range(len_participants - 1):181 round.append(" {:<5} |".format(''))182 return round183 @staticmethod184 def unserial_time_control(tournament, len_participants):185 """Désérialisation du time control du tournoi."""186 time_control = []187 t_c_string = ""188 if tournament["tournament"]["time_control"] == '0':189 t_c_string = "Bullet"190 elif tournament["tournament"]["time_control"] == '1':191 t_c_string = "Blitz"192 elif tournament["tournament"]["time_control"] == '2':193 t_c_string = "Quick"194 time_control.append(" {:<20} |".format(t_c_string))195 for count in range(len_participants - 1):196 time_control.append(" {:<20} |".format(''))197 return time_control198 def unserial_participants(self, tournament):199 """200 Désérialisation de l'index, nom de famille, prénom et score de chacun201 des participants.202 """203 participants = []204 for key in tournament["tournament"]["status_participants"]:205 index_participant = re.findall("[0-9]+", key)[0]206 score = \207 tournament["tournament"]["status_participants"][key]["score"]208 data_player = self.get_data_player(index_participant)[0]209 participants.append(" {:<30} |".format(str(data_player["index"]) +210 ' ' +211 data_player["last_name"] +212 ' ' +213 data_player["first_name"] +214 ' ' +215 str(score)216 ))217 return participants218 @staticmethod219 def unserial_description(tournament, len_participant):220 """Désérialisation de la desscription du tournoi."""221 description = []222 description.append(" {:<30} |"223 .format(tournament["tournament"]["description"]))224 for count in range(len_participant):225 description.append(" {:<30} |".format(''))226 return description227 def unserial_tournaments_finished(self, list_finished):228 """Désérialisation des tournois terminés."""229 self.list_finished_tournaments = []230 if list_finished == []:231 return "empty"232 for tournament in list_finished:233 len_participants = self.get_len_participants(tournament)234 index = self.unserial_index(tournament, len_participants)235 name = self.unserial_name(tournament, len_participants)236 place = self.unserial_place(tournament, len_participants)237 round = self.unserial_round(tournament, len_participants)238 time_control = \239 self.unserial_time_control(tournament, len_participants)240 participants = self.unserial_participants(tournament)241 description = \242 self.unserial_description(tournament, len_participants)243 self.list_finished_tournaments.append(244 TournamentFinished("finished_controller", len_participants,245 index, name, place, round, time_control,246 participants, description))247 return self.list_finished_tournaments248 @staticmethod249 def get_len_participants(tournament):250 """Demande le nombre de participants que le tournoi à eu."""...
gdbresultparser.py
Source:gdbresultparser.py
1# ricodebug - A GDB frontend which focuses on visually supported2# debugging using data structure graphs and SystemC features.3#4# Copyright (C) 2011 The ricodebug project team at the5# Upper Austrian University Of Applied Sciences Hagenberg,6# Department Embedded Systems Design7#8# This file is part of ricodebug.9#10# ricodebug is free software: you can redistribute it and/or modify11# it under the terms of the GNU General Public License as published by12# the Free Software Foundation, either version 3 of the License, or13# (at your option) any later version.14#15# This program is distributed in the hope that it will be useful,16# but WITHOUT ANY WARRANTY; without even the implied warranty of17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the18# GNU General Public License for more details.19#20# You should have received a copy of the GNU General Public License21# along with this program. If not, see <http://www.gnu.org/licenses/>.22#23# For further information see <http://syscdbg.hagenberg.servus.at/>.24"""Lexical parser for the gdb output25For futher information see the ply python module documentation.26"""27import re28import ply.lex as lex29import ply.yacc as yacc30from PyQt4.QtCore import QDir31from .gdboutput import GdbOutput32import helpers.excep33from .tools import unBackslashify34reserved = {35 x : x.upper().replace("-", "_") for x in [36 "done",37 "running",38 "connected",39 "error",40 "exit",41 "stopped",42 "thread-created",43 "thread-group-created",44 "thread-group-added",45 "thread-group-started",46 "thread-exited",47 "thread-group-exited",48 "thread-selected",49 "library-loaded",50 "library-unloaded",51 "breakpoint-modified",52 "breakpoint-created",53 "breakpoint-deleted",54 "record-started",55 "record-stopped",56 "cmd-param-changed"57 ]58}59tokens = [60 "ASSIGN",61 "COMMA",62 "LBRACE",63 "RBRACE",64 "LBRACKET",65 "RBRACKET",66 "HAT",67 "STAR",68 "PLUS",69 "TILDE",70 "AT",71 "AMP",72 "TOKEN",73 "C_STRING",74 "STRING",75] + list(reserved.values())76t_ASSIGN = r'='77t_COMMA = r','78t_LBRACE = r'{'79t_RBRACE = r'}'80t_LBRACKET = r'\['81t_RBRACKET = r'\]'82t_HAT = r'\^'83t_STAR = r'\*'84t_PLUS = r'\+'85t_TILDE = r'~'86t_AT = r'@'87t_AMP = r'&'88def t_TOKEN(t):89 r'\d+'90 return t91def t_STRING(t):92 r'[\w\d_-]+'93 t.type = reserved.get(t.value, "STRING")94 return t95def t_C_STRING(t):96 r'".*?(?<!\\)"(?=(,|\}|\]|$))'97 t.value = unBackslashify(t.value)98 t.value = t.value[1:-1] # strip the "99 return t100def t_error(t):101 raise TypeError("Unknown text '%s'" % (t.value,))102class Result:103 def __str__(self):104 return "RESULT(" + self.__dict__.__str__() + ")"105class Assignment:106 def __init__(self, dest, src):107 self.dest = dest108 self.src = src109 def __str__(self):110 return "ASSIGN(" + self.dest.__str__() + "," + self.src.__str__() + ")"111def p_result_record(p):112 '''result_record : result_class113 | result_class COMMA result_list'''114 p[0] = GdbOutput()115 p[0].class_ = p[1]116 if len(p) == 4:117 for a in p[3]:118 setattr(p[0], a.dest, a.src)119def p_async_output(p):120 '''async_output : async_class121 | async_class COMMA result_list'''122 p[0] = GdbOutput()123 p[0].class_ = p[1]124 if len(p) == 4:125 p[0].results = p[3]126def p_result_class(p):127 '''result_class : DONE128 | RUNNING129 | CONNECTED130 | ERROR131 | EXIT'''132 if p[1] == "done":133 p[0] = GdbOutput.DONE134 elif p[1] == "running":135 p[0] = GdbOutput.RUNNING136 elif p[1] == "connected":137 p[0] = GdbOutput.CONNECTED138 elif p[1] == "error":139 p[0] = GdbOutput.ERROR140 elif p[1] == "exit":141 p[0] = GdbOutput.EXIT142def p_async_class(p):143 '''async_class : STOPPED144 | RUNNING145 | THREAD_CREATED146 | THREAD_GROUP_CREATED147 | THREAD_GROUP_ADDED148 | THREAD_GROUP_STARTED149 | THREAD_EXITED150 | THREAD_GROUP_EXITED151 | THREAD_SELECTED152 | LIBRARY_LOADED153 | LIBRARY_UNLOADED154 | BREAKPOINT_MODIFIED155 | BREAKPOINT_CREATED156 | BREAKPOINT_DELETED157 | RECORD_STARTED158 | RECORD_STOPPED159 | CMD_PARAM_CHANGED'''160 if p[1] == "stopped":161 p[0] = GdbOutput.STOPPED162 elif p[1] == "running":163 p[0] = GdbOutput.RUNNING164 elif p[1] == "thread-created":165 p[0] = GdbOutput.THREAD_CREATED166 elif p[1] == "thread-group-created":167 p[0] = GdbOutput.THREAD_GROUP_CREATED168 elif p[1] == "thread-group-added":169 p[0] = GdbOutput.THREAD_GROUP_ADDED170 elif p[1] == "thread-group-started":171 p[0] = GdbOutput.THREAD_GROUP_STARTED172 elif p[1] == "thread-exited":173 p[0] = GdbOutput.THREAD_EXITED174 elif p[1] == "thread-group-exited":175 p[0] = GdbOutput.THREAD_GROUP_EXITED176 elif p[1] == "thread-selected":177 p[0] = GdbOutput.THREAD_SELECTED178 elif p[1] == "library-loaded":179 p[0] = GdbOutput.LIBRARY_LOADED180 elif p[1] == "library-unloaded":181 p[0] = GdbOutput.LIBRARY_UNLOADED182 elif p[1] == "breakpoint-modified":183 p[0] = GdbOutput.BREAKPOINT_MODIFIED184 elif p[1] == "breakpoint-created":185 p[0] = GdbOutput.BREAKPOINT_CREATED186 elif p[1] == "breakpoint-deleted":187 p[0] = GdbOutput.BREAKPOINT_DELETED188 elif p[1] == "record-started":189 p[0] = GdbOutput.RECORD_STARTED190 elif p[1] == "record-stopped":191 p[0] = GdbOutput.RECORD_STOPPED192 elif p[1] == "cmd-param-changed":193 p[0] = GdbOutput.CMD_PARAM_CHANGED194 else:195 raise helpers.excep.GdbError("Got " + p[1] + " which cannot occur here!")196def p_result(p):197 '''result : variable ASSIGN value'''198 p[0] = Assignment(p[1], p[3])199def p_variable(p):200 '''variable : STRING'''201 p[0] = p[1]202def p_value(p):203 '''value : const204 | tuple_205 | list_'''206 p[0] = p[1]207def p_const(p):208 '''const : C_STRING'''209 p[0] = p[1]210def p_tuple_(p):211 '''tuple_ : LBRACE RBRACE212 | LBRACE result_list RBRACE'''213 if len(p) > 3:214 p[0] = Result()215 for a in p[2]:216 setattr(p[0], a.dest, a.src)217 else:218 p[0] = []219def p_list_(p):220 '''list_ : LBRACKET RBRACKET221 | LBRACKET value_list RBRACKET222 | LBRACKET result_list RBRACKET'''223 if len(p) > 3:224 p[0] = p[2]225 else:226 p[0] = []227def p_stream_output(p):228 '''stream_output : C_STRING'''229 p[0] = GdbOutput()230 p[0].string = p[1]231def p_result_list(p):232 '''result_list : result233 | result COMMA result_list'''234 if len(p) > 2:235 p[0] = [p[1]] + p[3]236 else:237 p[0] = [p[1]]238def p_value_list(p):239 '''value_list : value240 | value COMMA value_list'''241 if len(p) > 2:242 p[0] = [p[1]] + p[3]243 else:244 p[0] = [p[1]]245def p_error(p):246 if p:247 raise helpers.excep.GdbError("Syntax error in input, line %d, col %d: %s" % (p.lineno, p.lexpos, p.type))248 else:249 raise helpers.excep.GdbError("Syntax error in input!")250def p_token(p):251 ''' token :252 | TOKEN'''253 p[0] = None if len(p) == 1 else p[1]254def p_top(p):255 '''top : token HAT result_record256 | token STAR async_output257 | token PLUS async_output258 | token ASSIGN async_output259 | TILDE stream_output260 | AT stream_output261 | AMP stream_output'''262 l = len(p)263 p[0] = p[l-1]264 if p[l-2] == '^':265 p[0].type_ = GdbOutput.RESULT_RECORD266 elif p[l-2] == '*':267 p[0].type_ = GdbOutput.EXEC_ASYN268 elif p[l-2] == '+':269 p[0].type_ = GdbOutput.STATUS_ASYN270 elif p[l-2] == '=':271 p[0].type_ = GdbOutput.NOTIFY_ASYN272 elif p[l-2] == '~':273 p[0].type_ = GdbOutput.CONSOLE_STREAM274 elif p[l-2] == '@':275 p[0].type_ = GdbOutput.TARGET_STREAM276 elif p[l-2] == '&':277 p[0].type_ = GdbOutput.LOG_STREAM278 if l == 4:279 p[0].token = p[1]280class GdbResultParser:281 @classmethod282 def parse(cls, lines):283 """Parse the lines with the above defined lexical rules284 """285 lex.lex(reflags=re.DOTALL)286 parser = yacc.yacc(start='top', debug=0, outputdir=str(QDir.homePath()) + "/.ricodebug")287 r = []288 for line in lines:289 line = line.strip()290 r.append(parser.parse(line))291 r[-1].raw = line...
scanner.py
Source:scanner.py
1import ply.lex as lex2import sys3reserved = {4 'Program': 'PROGRAM',5 'var': 'VAR',6 'module': 'MODULE',7 'main': 'MAIN',8 'int': 'INT',9 'float': 'FLOAT',10 'char': 'CHAR',11 'void':'VOID',12 'return': 'RETURN',13 'read': 'READ',14 'write': 'WRITE',15 'if': 'IF',16 'then': 'THEN',17 'else': 'ELSE',18 'do': 'DO',19 'while': 'WHILE',20 'from' : 'FROM',21 'to': 'TO',22 'Line': 'LINE',23 'Point': 'POINT',24 'Circle': 'CIRCLE',25 'Arc': 'ARC',26 'Penup': 'PENUP',27 'Pendown': 'PENDOWN',28 'Color': 'COLOR',29 'Size': 'SIZE',30 'Clear': 'CLEAR'31}32tokens = [33 'ID',34 'C_INT',35 'C_FLOAT',36 'C_STRING',37 'C_CHAR',38 'PLUS',39 'MINUS',40 'DIVIDE',41 'MULTIPLY',42 'EQUALS',43 'COMMA',44 'SEMICOLON',45 'COLON',46 'LPAREN',47 'RPAREN',48 'LBRACKET',49 'RBRACKET',50 'LSBRACKET',51 'RSBRACKET',52 'AND',53 'OR',54 'GREATER_THAN',55 'LESS_THAN',56 'IS_EQUAL',57 'NOT_EQUAL'58] + list(reserved.values())59t_PLUS = r'\+'60t_MINUS = r'\-'61t_DIVIDE = r'\/'62t_MULTIPLY = r'\*'63t_EQUALS = r'\='64t_COMMA = r'\,'65t_SEMICOLON = r'\;'66t_COLON = r'\:'67t_LPAREN = r'\('68t_RPAREN = r'\)'69t_LBRACKET = r'\{'70t_RBRACKET = r'\}'71t_LSBRACKET = r'\['72t_RSBRACKET = r'\]'73t_AND = r'\&'74t_OR = r'\|'75t_GREATER_THAN = r'\>'76t_LESS_THAN = r'\<'77t_IS_EQUAL = r'\=\='78t_NOT_EQUAL = r'\!\='79def t_ID(t):80 r'[a-zA-Z][a-zA-Z_0-9]*'81 t.type = reserved.get(t.value, 'ID')82 return t83def t_C_FLOAT(t):84 r'\d+\.\d+'85 t.value = float(t.value)86 return t87def t_C_INT(t):88 r'\d+'89 t.value = int(t.value)90 return t91def t_C_STRING(t):92 r'\"[^"]+\"'93 return t94def t_C_CHAR(t):95 r'\'.\''96 return t97t_ignore = " \t"98def t_newline(t):99 r'\n+'100 t.lexer.lineno += t.value.count("\n")101 102def t_error(t):103 print("Illegal characters:", t.value)104 t.lexer.skip(1)105lexer = lex.lex()106""" while True:107 try:108 s = input('')109 except EOFError:...
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!!