def __init__(self): SelectRuleset.__init__(self) Players.load() decorateWindow(self, m18n('Select four players')) self.names = None self.nameWidgets = [] for idx, wind in enumerate(Wind.all4): cbName = QComboBox() cbName.manualSelect = False # increase width, we want to see the full window title cbName.setMinimumWidth(350) # is this good for all platforms? cbName.addItems(list(Players.humanNames.values())) self.grid.addWidget(cbName, idx + 1, 1) self.nameWidgets.append(cbName) self.grid.addWidget(WindLabel(wind), idx + 1, 0) cbName.currentIndexChanged.connect(self.slotValidate) query = Query( "select p0,p1,p2,p3 from game where seed is null and game.id = (select max(id) from game)") if len(query.records): with BlockSignals(self.nameWidgets): for cbName, playerId in zip(self.nameWidgets, query.records[0]): try: playerName = Players.humanNames[playerId] playerIdx = cbName.findText(playerName) if playerIdx >= 0: cbName.setCurrentIndex(playerIdx) except KeyError: logError(u'database is inconsistent: player with id %d is in game but not in player' % playerId) self.slotValidate()
def execute(self, statement, parameters=None, silent=False, failSilent=False, mayFail=False): """logging wrapper, returning all selected data""" # pylint: disable=too-many-branches self.statement = statement self.parameters = parameters if not silent: logDebug(str(self)) try: for _ in range(10): try: with Duration(statement, 60.0 if Debug.neutral else 2.0): if isinstance(parameters, list): sqlite3.Cursor.executemany( self, statement, parameters) elif parameters: sqlite3.Cursor.execute(self, statement, parameters) else: sqlite3.Cursor.execute(self, statement) break except sqlite3.OperationalError as exc: logDebug( u'{} failed after {} tries:{}'.format(self, _, exc.message)) time.sleep(1) else: break else: raise sqlite3.OperationalError( 'Failed after 10 tries:{}'.format(self)) self.failure = None except sqlite3.Error as exc: self.failure = exc msg = u'ERROR in %s: %s for %s' % ( self.connection.path, exc.message if hasattr(exc, 'message') else '', self) if mayFail: if not failSilent: logDebug(msg) else: if not failSilent: logError(msg) raise QueryException(msg) return
from scoringdialog import ScoreTable, ExplainView from humanclient import HumanClient from rulesetselector import RulesetSelector from animation import afterQueuedAnimations, AnimationSpeed, ParallelAnimationGroup from chat import ChatWindow from scene import PlayingScene, ScoringScene from configdialog import ConfigDialog from statesaver import StateSaver from util import checkMemory except ImportError as importError: NOTFOUND.append('Kajongg is not correctly installed: modules: %s' % importError) if len(NOTFOUND): logError("\n".join(" * %s" % s for s in NOTFOUND), showStack=False) sys.exit(3) def cleanExit(*dummyArgs): """close sqlite3 files before quitting""" if isAlive(Internal.mainWindow): if Debug.quit: logDebug('cleanExit calling mainWindow.close') Internal.mainWindow.close() else: # this must be very early or very late if Debug.quit: logDebug('cleanExit calling sys.exit(0)') # sys.exit(0) MainWindow.aboutToQuit()
def loadFromDB(cls, gameid, client=None): """load game by game id and return a new Game instance""" Internal.logPrefix = 'S' if Internal.isServer else 'C' records = Query( "select p0,p1,p2,p3,ruleset,seed from game where id = ?", (gameid, )).records if not records: return None qGameRecord = records[0] rulesetId = qGameRecord[4] or 1 ruleset = Ruleset.cached(rulesetId) Players.load() # we want to make sure we have the current definitions records = Query( "select hand,rotated from score where game=? and hand=" "(select max(hand) from score where game=?)", (gameid, gameid)).records if records: qLastHandRecord = records[0] else: qLastHandRecord = tuple([0, 0]) qScoreRecords = Query( "select player, wind, balance, won, prevailing from score " "where game=? and hand=?", (gameid, qLastHandRecord[0])).records if not qScoreRecords: # this should normally not happen qScoreRecords = list([ tuple([qGameRecord[wind], wind.char, 0, False, East.char]) for wind in Wind.all4 ]) if len(qScoreRecords) != 4: logError('game %d inconsistent: There should be exactly ' '4 score records for the last hand' % gameid) # after loading SQL, prepare values. # default value. If the server saved a score entry but our client # did not, we get no record here. Should we try to fix this or # exclude such a game from the list of resumable games? if len(set(x[4] for x in qScoreRecords)) != 1: logError('game %d inconsistent: All score records for the same ' 'hand must have the same prevailing wind' % gameid) players = list( tuple([Wind(x[1]), Game.__getName(x[0])]) for x in qScoreRecords) # create the game instance. game = cls(players, ruleset, gameid=gameid, client=client, wantedGame=qGameRecord[5]) game.handctr, game.rotated = qLastHandRecord for record in qScoreRecords: playerid = record[0] player = game.players.byId(playerid) if not player: logError( 'game %d inconsistent: player %d missing in game table' % (gameid, playerid)) else: player.getsPayment(record[2]) if record[3]: game.winner = player game.roundsFinished = Wind(qScoreRecords[0][4]).__index__() game.handctr += 1 game.notRotated += 1 game.maybeRotateWinds() game.sortPlayers() with AnimationSpeed(Speeds.windMarker): animateAndDo(game.wall.decorate4) return game
from humanclient import HumanClient from rulesetselector import RulesetSelector from animation import afterQueuedAnimations, MoveImmediate from chat import ChatWindow from scene import PlayingScene, ScoringScene from configdialog import ConfigDialog from statesaver import StateSaver from util import checkMemory from twisted.internet.error import ReactorNotRunning # except ImportError as importError: # NOTFOUND.append('Kajongg is not correctly installed: modules: %s' % # importError) if len(NOTFOUND): logError("\n".join(" * %s" % s for s in NOTFOUND), showStack=False) sys.exit(3) def cleanExit(*dummyArgs): """close sqlite3 files before quitting""" if isAlive(Internal.mainWindow): if Debug.quit: logDebug(u'cleanExit calling mainWindow.close') Internal.mainWindow.close() else: # this must be very early or very late if Debug.quit: logDebug(u'cleanExit calling sys.exit(0)') # sys.exit(0) MainWindow.aboutToQuit()
def assemblerFromTestDir(jar, testDir, nasmDir, hackDir, nasmFile=None): error = 0 log = [] configFile = testDir + config.CONFIG_FILE # caminho do arquivo de configuracao pwd = os.path.dirname(configFile) + "/" # Verificando se é diretorio if not os.path.exists(configFile): logError("Favor passar como parametro um diretorio do tipo test") return (1) # verifica se exist arquivo de config try: f = open(configFile, 'r') except: logError("Arquivo {} não encontrado".format(CONFIG_FILE)) return (1) print(" 1/2 Removendo arquivos .hack") print(" - {}".format(hackDir)) clearbin(hackDir) os.makedirs(os.path.dirname(hackDir), exist_ok=True) print(" 2/2 Gerando arquivos .hack") print(" - {}".format(nasmDir)) for l in f: if len(l.strip()): if (l.strip()[0] != '#'): if (l.strip().find('.nasm') > 0) or (l.strip().find('.vm') > 0): # par[0] : Nome do teste (subpasta) # par[1] : quantidade de testes a serem executados # par[2] : tempo de simulação em ns par = l.rstrip().split() if (l.strip().find('.vm') > 0): name = par[0][:-3] else: name = par[0][:-5] hack = hackDir + name + '.hack' mif = hackDir + name + ".mif" found = False if isinstance(nasmDir, list): nasmDir = nasmDir else: nasmDir = [nasmDir, ''] for n in nasmDir: nasm = n + name + ".nasm" # verifica se é para executar compilar # apenas um arquivo da lista if nasmFile is not None: if name != nasmFile: continue if os.path.isfile(nasm): e, l = assemblerFile(jar, nasm, hack, mif) log.append(l) if e > 0: return config.ERRO_ASSEMBLER, log found = True if found is False: logError("Arquivo nasm não encontrado :") logError(" - {}".format(nasm)) log.append({'name': mif, 'status': 'false'}) return config.ERRO_ASSEMBLER_FILE, log return config.ERRO_NONE, log
def plotTopFlopHealthSpendingCoronaCases(topFlopCountryData, population): topAndFlopArray = [] topAndFlopArray.extend(topFlopCountryData["top"]) topAndFlopArray.extend(topFlopCountryData["flop"]) place = 0 for countryData in topAndFlopArray: x = [] totalCases = [] yCasesPer100kCitizens = [] totalDeaths = [] yDeathsPer100kCitizens = [] countryPopulation = population[countryData["alpha_2"]] * 1000 if countryPopulation > 0: sortedCasesCountryData = sorted( countryData["coronaCases"], key=lambda e: int(e["year"]) * 10000 + int(e[ "month"]) * 100 + int(e["day"])) for caseData in sortedCasesCountryData: x.append( datetime.date(int(caseData["year"]), int(caseData["month"]), int(caseData["day"]))) if len(totalCases) > 0: totalCases.append(totalCases[-1] + int(caseData["cases"])) else: totalCases.append(int(caseData["cases"])) if len(totalDeaths) > 0: totalDeaths.append(totalDeaths[-1] + int(caseData["deaths"])) else: totalDeaths.append(int(caseData["deaths"])) yCasesPer100kCitizens.append( (totalCases[-1] / countryPopulation) * 100000) yDeathsPer100kCitizens.append( (totalDeaths[-1] / countryPopulation) * 100000) red = hex(85 * place) green = hex(255) blue = hex(0) if (place > 2): red = hex(255) green = hex(85 * (place % 3)) blue = hex(0) colorString = "#" + str(red).replace( "0x", "").zfill(2) + str(green).replace( "0x", "").zfill(2) + str(blue).replace("0x", "").zfill(2) countryObj = pycountry.countries.get( alpha_2=countryData["alpha_2"]) plt.figure(1) plt.plot_date(x, yCasesPer100kCitizens, color=colorString, linestyle='solid', marker='None', label=countryObj.name) plt.figure(2) plt.plot_date(x, yDeathsPer100kCitizens, color=colorString, linestyle='solid', marker='None', label=countryObj.name) place += 1 else: log.logError("There is no countryPopulation data for " + countryData.alpha_2) plt.figure(1) figure = plt.gcf() figure.set_size_inches(19.2, 10.8) title = "cases per 100k of top and flop 3 per head spender" plt.title(title) plt.legend() plt.savefig("../out/healthSpending/cases.png", bbox_inches=Bbox(np.array([[0, 0], [19.2, 10.8]]))) plt.clf() plt.close() plt.figure(2) figure = plt.gcf() figure.set_size_inches(19.2, 10.8) title = "deaths per 100k of top and flop 3 per head spender" plt.title(title) plt.legend() plt.savefig("../out/healthSpending/deaths.png", bbox_inches=Bbox(np.array([[0, 0], [19.2, 10.8]]))) plt.clf() plt.close()
def processPlugin(self): # noinspection PyBroadException try: productId = tools.getIdByProduct(self.product) except: log.logError("Error getting the Id of the product specified:" + self.product) return False # noinspection PyBroadException try: results = tools.getTestSuites(self.name, self.branch) except: log.logError( "Error getting last TestSuites for the specified name + branch:" + self.name + " " + self.branch) return False productResults = [] # Results with the id we want. revisions = [] # A list with all the revisions numbers # We iterate through the response to get all the test-suites for our product for result in results: if str(result["product"]) == str(productId): productResults.append(result) if result['revision'] not in revisions: revisions.append(result['revision']) numTestSuitesByRevision = {} # Number of tests suites for a product testSuitesByRevision = {} n_tests = 0 # value to put on dict numTestSuitesByRevision testSuites_values = [] # value to put on dict IdListsClean for re in revisions: for Id in productResults: if Id['revision'] == re: n_tests = n_tests + 1 testSuites_values.append(Id) numTestSuitesByRevision[re] = n_tests testSuitesByRevision[re] = testSuites_values n_tests = 0 testSuites_values = [] countTests = 0 # Iterator to count number of tests finished inside a revision completedRevision = 0 for r, testSuites in testSuitesByRevision.items(): for testSuite in testSuites: if testSuite["revision"] == r and testSuite["status"] != "working": countTests += 1 else: break # If we found one testSuite working, we go for the next revision if countTests == numTestSuitesByRevision[r]: log.logDebug("The product has " + str(numTestSuitesByRevision[r]) + " for this revision.") completedRevision = r break # If we just found the completedRevision we go out of the loop else: countTests = 0 log.logDebug('The last completed revision for this Adict Product is ' + str(completedRevision)) allTestSuitesData = {} TestSuiteData = {} # refactor for result in productResults: if result['revision'] == completedRevision: TestSuiteData["percentage_test"] = result['success_tests_percentage'] TestSuiteData["status"] = result['status'] TestSuiteData["kind_type"] = str(result['kind']) + str(result['kind_level']) allTestSuitesData[result["name"]] = TestSuiteData TestSuiteData = {} # noinspection PyBroadException try: # Now that we have the completed revision, we get the last good build of a product productLastBuild = tools.getBuild(self.product, self.name, self.project, self.branch, completedRevision) except: log.logError( "Error getting the product (" + self.product + ") last build for the revision obtained as the last" + completedRevision) return False allProductBuildsData = {} for build in productLastBuild: allProductBuildsData[build['target']] = build['status'] self.globalResult = {"Revision": str(completedRevision), "TestSuites": allTestSuitesData, "ProductBuilds": allProductBuildsData} return self.globalResult
def main(): global expectingData, serialCom if len(sys.argv) != 2: logError('Please provide serial port as first argument') exit(1) try: serialCom = SerialCom(sys.argv[1]) except serial.serialutil.SerialException as e: logError('Could not open serial port: {}'.format(e.args[1])) exit(1) gui = GUI() gui.draw([], 'Looking for device') while serialCom.ping() != 0: gui.draw( [], 'Device is not responding to\nPING command\nCheck connection\n\nRetrying...' ) sleep(1) gui.draw([], 'Device is connected\n\nSending initial configuration') actions = [{ 'job': serialCom.setTriggerLevel, 'name': 'Setting trigger level', 'value': 1 }, { 'job': serialCom.setMode, 'name': 'Setting mode', 'value': 0 }, { 'job': serialCom.setNumberOfSamples, 'name': 'Setting number of samples', 'value': gui.graph.numberOfSamples }, { 'job': serialCom.setPrecision, 'name': 'Setting frequency', 'value': gui.graph.freq }] for action in actions: gui.draw([], 'Device is connected\n\nSending initial configuration\n\n' + action['name']) while action['job'](action['value']) != 0: sleep(3) gui.draw( [], 'Device is connected\n\nSending initial configuration\n\nRetrying: ' + action['name']) gui.draw([]) exData = [] while True: message = None while not (expectingData and serialCom.isDataAvail()) and not processUserInput( gui, serialCom): sleep(0.3) if expectingData and serialCom.isDataAvail(): (status, exData) = serialCom.downloadData() if status: expectingData = False else: message = 'Downloading samples failed\nCommunication error\noccurred\n\nPress any key' gui.draw(exData, message)
def processClientId(self, fileContent): clientId = fileContent.find(setting.clientIDLabel) if len(clientId) == 0: log.logError('Bad xml syntax: clientId missing') exit(1) return clientId.get_text()
def loadFromDB(cls, gameid, client=None): """load game by game id and return a new Game instance""" Internal.logPrefix = 'S' if Internal.isServer else 'C' records = Query( "select p0,p1,p2,p3,ruleset,seed from game where id = ?", (gameid,)).records if not records: return None qGameRecord = records[0] rulesetId = qGameRecord[4] or 1 ruleset = Ruleset.cached(rulesetId) Players.load() # we want to make sure we have the current definitions records = Query( "select hand,rotated from score where game=? and hand=" "(select max(hand) from score where game=?)", (gameid, gameid)).records if records: qLastHandRecord = records[0] else: qLastHandRecord = tuple([0, 0]) qScoreRecords = Query( "select player, wind, balance, won, prevailing from score " "where game=? and hand=?", (gameid, qLastHandRecord[0])).records if not qScoreRecords: # this should normally not happen qScoreRecords = list([ tuple([qGameRecord[wind], wind.char, 0, False, East.char]) for wind in Wind.all4]) if len(qScoreRecords) != 4: logError(u'game %d inconsistent: There should be exactly ' '4 score records for the last hand' % gameid) # after loading SQL, prepare values. # default value. If the server saved a score entry but our client # did not, we get no record here. Should we try to fix this or # exclude such a game from the list of resumable games? if len(set(x[4] for x in qScoreRecords)) != 1: logError(u'game %d inconsistent: All score records for the same ' 'hand must have the same prevailing wind' % gameid) players = list(tuple([Wind(x[1]), Game.__getName(x[0])]) for x in qScoreRecords) # create the game instance. game = cls(players, ruleset, gameid=gameid, client=client, wantedGame=qGameRecord[5]) game.handctr, game.rotated = qLastHandRecord for record in qScoreRecords: playerid = record[0] player = game.players.byId(playerid) if not player: logError( u'game %d inconsistent: player %d missing in game table' % (gameid, playerid)) else: player.getsPayment(record[2]) if record[3]: game.winner = player game.roundsFinished = Wind(qScoreRecords[0][4]).__index__() game.handctr += 1 game.notRotated += 1 game.maybeRotateWinds() game.sortPlayers() game.wall.decorate() return game
def simulateFromTestDir(testDir, hackDir, gui, verbose, nasmFile=None,rtlDir=config.PATH_SIMULATOR): error = 0 log = [] configFile = testDir+config.CONFIG_FILE # caminho do arquivo de configuracao pwd = os.path.dirname(configFile) + "/" f = util.openConfigFile(testDir) for l in f: if len(l.strip()): if ((l.strip()[0] != '#') and ( (l.strip().find('.nasm') > 0 ) or (l.strip().find('.vm') > 0) )): # pega parametros e atribui caminhos globais # par[0] : Nome do teste (subpasta) # par[1] : quantidade de testes a serem executados # par[2] : tempo de simulação em ns par = l.rstrip().split(); if(l.strip().find('.vm') > 0): name = par[0][:-3] else: name = par[0][:-5] sTime = int(par[2]) mif = hackDir+name+".mif" # verifica se é para executar compilar # apenas um arquivo da lista if nasmFile is not None: if name != nasmFile: continue # verifica se arquivo existe if os.path.isfile(mif): # simulate for i in range(0, int(par[1])): # usar join ? ramIn = pwd+config.TST_DIR+name+"/"+name+"{}".format(i) + config.RAM_INIT_FILE ramOut = pwd+config.TST_DIR+name+"/"+name+str(i) + config.RAM_END_SIMU_FILE lcdOut = hackDir + '../lcd/' +name+str(i) + config.LCD_PGM_FILE print(os.path.relpath(mif) + " teste : " + str(i)) if os.path.isfile(ramIn): tic = time.time() if verbose is True : print(ramIn) print(mif) print(ramOut) simulateCPU(ramIn, mif, ramOut, lcdOut, sTime, gui, verbose, rtlDir=rtlDir) toc = time.time() print(" ({0:.2f} seconds)".format(toc-tic)) else: logError("Arquivo de simulacao não encontrado :") logError(" - {}".format(ramIn)) log.append({'name': name, 'status': 'Simulacao Arquivo Fail'}) return -1, log else: logError("Arquivo hack não encontrado :") logError(" - {}".format(mif)) log.append({'name': mif, 'status': 'Simulacao Arquivo Fail'}) return -1, log return 0, log
def ignoreLostConnection(failure): """if the client went away correctly, do not dump error messages on stdout.""" msg = failure.getErrorMessage() if 'twisted.internet.error.ConnectionDone' not in msg: logError(msg) failure.trap(pb.PBConnectionLost)
def simulateFromTestDir(testDir, hackDir, gui, verbose, rtlDir=PATH_WORK): configFile = testDir + CONFIG_FILE # caminho do arquivo de configuracao pwd = os.path.dirname(configFile) + "/" os.path.abspath(hackDir) os.path.abspath(configFile) # file f = "" # Verificando se é diretorio if not os.path.exists(configFile): logError("Favor passar como parametro um diretorio do tipo test") return (1) # verifica se exist arquivo de config try: f = open(configFile, 'r') except: logError("Arquivo {} não encontrado".format(CONFIG_FILE)) return (1) for l in f: if (l.strip()[0] != '#') or (not l.strip()): # pega parametros e atribui caminhos globais # par[0] : Nome do teste (subpasta) # par[1] : quantidade de testes a serem executados # par[2] : tempo de simulação em ns par = l.rstrip().split() # nome do arquivo name = par[0] # tempo total de simulacao sTime = int(par[2]) # paths mif = hackDir + name + ".mif" # verifica se arquivo existe if os.path.isfile(mif): # simulate for i in range(0, int(par[1])): # usar join ? ramIn = pwd + TST_DIR + name + "/" + name + "{}".format( i) + RAM_INIT_FILE ramOut = pwd + TST_DIR + name + "/" + name + str( i) + RAM_END_SIMU_FILE print("Simulating " + os.path.relpath(mif) + " teste : " + str(i)) if os.path.isfile(ramIn): tic = time.time() if verbose is True: print(ramIn) print(mif) print(ramOut) simulateCPU(ramIn, mif, ramOut, sTime, gui, verbose, rtlDir=rtlDir) toc = time.time() print(" ( {0:.2f} seconds)".format(toc - tic)) else: logError("Arquivo de simulacao não encontrado :") logError(" - {}".format(ramIn)) return (1) else: logError("Arquivo hack não encontrado :") logError(" - {}".format(mif))
def simulateCPU(ramIn, romIn, ramOut, time, debug, verbose, rtlDir=PATH_WORK): global OUT_SIM_LST rtlDir = os.path.abspath(rtlDir) PATH_DO = os.path.join(rtlDir, "do", "sim.do") TEMP_IN_RAM_MIF = os.path.join(rtlDir, "tmpRAM.mif") TEMP_IN_ROM_MIF = os.path.join(rtlDir, "tmpROM.mif") OUT_RAM_MEM = os.path.join(rtlDir, "out", "RAM.mem") OUT_ROM_MEM = os.path.join(rtlDir, "out", "ROM.mem") # tosco, melhorar isso ! não pode ser global ! # mas o gui simulator usa, colocar como parametro ? # ou criar uma classe OUT_SIM_LST = os.path.join(rtlDir, "out", "SIM.lst") ramIn = os.path.abspath(ramIn) romIn = os.path.abspath(romIn) ramOut = os.path.abspath(ramOut) # try: # os.remove(OUT_RAM_MEM) # os.remove(OUT_ROM_MEM) # os.remove(OUT_SIM_LST) # print("removido") # except: # print("simulateCPU: Falha em remove arquivos") # pass # return(0) try: shutil.copyfile(ramIn, TEMP_IN_RAM_MIF) shutil.copyfile(romIn, TEMP_IN_ROM_MIF) except: logError("Arquivos não encontrados :") logError(" - {}".format(romIn)) logError(" - {}".format(ramIn)) return (1) if PATH_VSIM is None: logError("Configurar a variavel de ambiente : 'VUNIT_MODELSIM_PATH' ") return (1) setRuntimeDo(time, PATH_DO) v = "" if platform.system() == "Windows": if verbose is False: v = " > NUL " else: if verbose is False: v = " > /dev/null " c = "" if debug is False: c = " -c " # executa simulacao no modelsim owd = os.getcwd() os.chdir(rtlDir) os.system(PATH_VSIM + c + " -do " + PATH_DO + v) os.chdir(owd) shutil.copyfile(OUT_RAM_MEM, ramOut)