def doLogin(self, username, password): query = QSqlQuery() query.prepare("select id from qtapp_users where username = :username and password = :password") query.bindValue(":username", username) query.bindValue(":password", helper.computeHash(password)) query.exec_() if query.next(): return True return False
def preSupprVerification(self, index): u"""Vérification à effectuer avant d'autoriser à supprimer un item Renvoit False si la suppression est interdite """ sql = """ SELECT COUNT(*) FROM absence WHERE id_intervenant=""" + str(index.sibling(index.row(), 0).data()) req = QSqlQuery() if req.exec_(sql): req.next() nbAbsences = req.record().value(0) if nbAbsences != 0: pl = "" if nbAbsences != 1: pl = "s" QMessageBox.critical(self, "Impossible de suppprimer", u"L'intervenant a encore " + str(nbAbsences) + u" absence" + pl + u" enregistrée" + pl + "<br />" + u"Il faut les supprimer avant") # TODO trouver un moyen de setter l'onglet de l'application # self._ui.tabWidget.setCurrentIndex(1) return False # TODO gérer le else, au moins logger quelque chose return True
def __resulatEnvoi(self, errCode): u"""Slot notifié quand l'envoi du mail est fini errCode indique le succès, ou l'échec (avec la raison) de l'envoi du mail """ if errCode == MailSender.MAIL_ERROR_NONE: # Mail envoyé, mise à jour de la base self.notification.emit(u"Email envoyé", MailUI.DUREE_MESSAGE) index = self._ui.cbAbsence.currentIndex() sql = MailSQL.mailEnvoye(str(self.__absences[index]["id"])) req = QSqlQuery() if not req.exec_(sql): QMessageBox.critical(self, u"Erreur de base de données", u"Le mail a été envoyé mais impossible de <br />" + u"l'enregistrer dans la base.") # TODO logger print "SQL error" print str(req.lastError().text().toUtf8()) print req.lastQuery() else: self.majBdd.emit() elif (errCode == MailSender.MAIL_ERROR_TIMEOUT or errCode == MailSender.MAIL_ERROR_CONNECTION): message = u"Email non envoyé - " if errCode == MailSender.MAIL_ERROR_TIMEOUT: message += u"Durée dépassée" else: message += u"Erreur de connexion" self.notification.emit(message, MailUI.DUREE_MESSAGE) QMessageBox.critical(self, "Erreur de connection", u"Impossible de contacter le serveur.<br />" + u"Veuillez vérifier la connexion à internet, <br />" + u"ainsi que l'adresse du serveur de messagerie.") elif errCode == MailSender.MAIL_ERROR_AUTHENTICATION: message = u"Email non envoyé - Erreur d'authentification" self.notification.emit(message, MailUI.DUREE_MESSAGE) QMessageBox.critical(self, "Erreur d'authentification", "Indentifiants incorrects.<br />(login " + self.__conf["email"] + ")") del self.__password else: # MailSender.MAIL_ERROR_OTHER: message = u"Email non envoyé - Erreur inconnue" self.notification.emit(message, MailUI.DUREE_MESSAGE) QMessageBox.critical(self, "Erreur inconnue", "Une erreur inconnue s'est produite.<br />(login '" + self.__conf["email"] + "')") # TODO logger l'erreur réelle à la levée de l'exception self.majBdd.emit()
def getCurrentDomination(self): query = QSqlQuery(self.parent.db) query.prepare("SELECT dominant, slave FROM `domination` WHERE 1") query.exec_() if query.size() > 0: query.first() dominant = int(query.value(0)) slave = int(query.value(1)) if not slave in self.dominations: self.dominations[slave] = dominant
def getSelectedLadderMaps(self, playerId): query = QSqlQuery(self.db) query.prepare("SELECT idMap FROM ladder_map_selection WHERE idUser = ?") query.addBindValue(playerId) query.exec_() maps = [] if query.size() > 0: while query.next(): maps.append(int(query.value(0))) return maps
def check_barcode(self, txt): if len(txt) == self.edBarcode.maxLength(): db = Db_Instance("obook_barcode_search").get_instance() try: if db.open(): query = QSqlQuery(db) query.prepare("SELECT * FROM book WHERE barcode = :barcode") query.bindValue(":barcode", txt) query.exec_() if query.next(): self.add_book_from_record(query.record()) self.edBarcode.clear() else: raise RecordNotFoundException else: raise DbUnavailableException except RecordNotFoundException: message = unicode("Código de barra inválido!\n\n""" "O código informado não corresponde a nenhum livro cadastrado".decode('utf-8')) QMessageBox.critical(self, "Seareiros - Livraria", message) except DbUnavailableException: self.log.error(db.lastError().text()) message = unicode("Erro de conexão\n\n""Banco de dados indisponível".decode('utf-8')) QMessageBox.critical(self, "Seareiros - Livraria", message) self.edBarcode.setFocus()
def getPopularLadderMaps(self, count): query = QSqlQuery() query.prepare( "SELECT `idMap` FROM `ladder_map_selection` GROUP BY `idMap` ORDER BY count(`idUser`) DESC LIMIT %i" % count) query.exec_() maps = [] if query.size() > 0: while query.next(): maps.append(int(query.value(0))) return maps
def getPopularLadderMaps(self, count): query = QSqlQuery() query.prepare("SELECT `idMap` FROM `ladder_map_selection` GROUP BY `idMap` ORDER BY count(`idUser`) DESC LIMIT %i" % count) query.exec_() maps = [] if query.size() > 0: while query.next(): maps.append(int(query.value(0))) return maps
def _get_id_from_name(self, table, name): db = Db_Instance(table + "_fetch_" + name + "_id").get_instance() if not db.open(): return None else: query = QSqlQuery(db) query.prepare("SELECT id FROM %s WHERE name = :name" % table) query.bindValue(":name", name) query.exec_() if query.next(): return query.record().value("id") else: return None
def _get_name_from_id(self, table, id): db = Db_Instance(table + "_fetch_" + str(id) + "_name").get_instance() if not db.open(): return None else: query = QSqlQuery(db) query.prepare("SELECT name FROM %s WHERE id = :id" % table) query.bindValue(":name", id) query.exec_() if query.next(): return query.record().value("name") else: return None
def get_added_record(self): db = Db_Instance("added_book_record").get_instance() if db.open() and self._book_id: query = QSqlQuery(db) query.prepare("SELECT * FROM book WHERE id = :id") query.bindValue(":id", self._book_id) query.exec_() if query.next(): return query.record() else: return None else: return None
def update(self): '''Updating depots''' self.depots = {} query = QSqlQuery(self.parent.db) query.prepare("SELECT planetuid, influence, reinforcements, money FROM `planets_depots` WHERE 1") query.exec_() if query.size() > 0 : while query.next(): uid = int(query.value(0)) influence = int(query.value(1)) reinforcements = int(query.value(2)) money = int(query.value(3)) if not uid in self.depots: self.depots[uid] = Depot(uid, influence, reinforcements, money, self)
def setUndefended(self, planetuid): for uid in self.attacks: if self.attacks[uid].getPlanet() == planetuid: self.attacks[uid].defended = False query = QSqlQuery(self.parent.db) query.prepare( "UPDATE `attacks` SET `defended` = 0 WHERE id = ?") query.addBindValue(uid) query.exec_() return
def get_added_record(self): """ My workaround to get the last inserted id without any postgres specific queries """ db = Db_Instance("add_associate_last_id").get_instance() if not db.open(): return None else: query = QSqlQuery(db) query.prepare("SELECT * FROM associate WHERE fullname = :fullname") query.bindValue(":fullname", self.edFullName.text()) query.exec_() if query.next(): return query.record() else: return None
def last_id_from_sequence(table, db, id_field="id"): # db has to be passed as parameter as we have to capture the same session for this to work if not db.isOpen(): return None else: query = QSqlQuery(db) query.prepare("SELECT currval(pg_get_serial_sequence(:table,:id))") query.bindValue(":table", table) query.bindValue(":id", id_field) query.exec_() if query.next(): return query.record().value("currval") else: return None
def update(self): self.defenses = {} query = QSqlQuery(self.parent.db) query.prepare("SELECT planetuid, itemuid, amount, description, structure FROM planets_defense LEFT JOIN static_defenses ON static_defenses.id=planets_defense.itemuid WHERE amount != 0") if not query.exec_(): self.log.warning(query.lastError()) if query.size() > 0 : #query.first() while query.next() : planetuid = int(query.value(0)) itemuid = int(query.value(1)) amount = int(query.value(2)) description = str(query.value(3)) structure = str(query.value(4)) if not planetuid in self.defenses: self.defenses[planetuid] = defense(planetuid, self.parent) self.defenses[planetuid].addDefense(itemuid, amount, description, structure)
def setUndefended(self, planetuid): for uid in self.attacks : if self.attacks[uid].getPlanet() == planetuid : self.attacks[uid].defended = False query = QSqlQuery(self.parent.db) query.prepare("UPDATE `attacks` SET `defended` = 0 WHERE id = ?") query.addBindValue(uid) query.exec_() return
def preSupprVerification(self, index): u"""Vérification à effectuer avant d'autoriser à supprimer un item Renvoit False si la suppression est interdite """ sql = """ SELECT COUNT(*) FROM absence WHERE id_intervenant=""" + str(index.sibling(index.row(), 0).data()) req = QSqlQuery() if req.exec_(sql): req.next() nbAbsences = req.record().value(0) if nbAbsences != 0: pl = "" if nbAbsences != 1: pl = "s" QMessageBox.critical( self, "Impossible de suppprimer", u"L'intervenant a encore " + str(nbAbsences) + u" absence" + pl + u" enregistrée" + pl + "<br />" + u"Il faut les supprimer avant") # TODO trouver un moyen de setter l'onglet de l'application # self._ui.tabWidget.setCurrentIndex(1) return False # TODO gérer le else, au moins logger quelque chose return True
def slot_exec(self, query, params): records = [] sql = QSqlQuery(self.db) sql.prepare(query) if params: for p in params: self.set_value(sql, p) sql.exec_() # number of rows returned from query execution self.numRows.emit(sql.size()) while sql.next(): records.append(sql.record()) #sleep(1) # row read self.readRow.emit() self.result.emit(records, '') self.cleanup.emit(self.db.connectionName())
def deleteGroup(self, group, player): query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(player) query.exec_() if query.size() == 1: query.first() uid = int(query.value(0)) if not uid in self.deletedGroups: self.deletedGroups[uid] = [] if not group in self.deletedGroups[uid]: self.parent.lobby.sendJSON( dict(command="delete_group", group=group, playeruid=uid)) self.deletedGroups[uid].append(group)
def cancelAttack(self, planetuid): query = QSqlQuery(self.parent.db) query.prepare("DELETE FROM `attacks` WHERE `uid_planet` = ?") query.addBindValue(planetuid) query.exec_() self.update()
def update(self): query = QSqlQuery(self.parent.db) query.prepare("SELECT id, uid_player, uid_planet, attack_time, faction, defended, IFNULL(dominant,-1) FROM `attacks` LEFT JOIN accounts ON accounts.uid = uid_player LEFT JOIN domination on faction = domination.slave WHERE 1") query.exec_() if query.size() > 0 : allUids = [] while query.next() : uid = int(query.value(0)) playeruid = int(query.value(1)) planetuid = int(query.value(2)) attack = (time.time() - query.value(3).toTime_t()) faction = int(query.value(4)) if int(query.value(6)) != -1: faction = int(query.value(6)) defended = bool(query.value(5)) allUids.append(uid) if not uid in self.attacks : self.addAttack(uid, playeruid, faction, planetuid, attack, defended) else : self.updateAttack(uid, playeruid, attack, defended) toDelete = [] for uid in self.attacks : if not uid in allUids : toDelete.append(uid) for uid in toDelete : del self.attacks[uid] else : self.attacks = {}
def addResultPlayer(self, player, faresult, score): if faresult == "recall" : self.log.debug("%s recalled" % player ) if not player in self.recalled: self.recalled.append(player) self.gameResult[player] = -1 self.gameFaResult[player] = faresult if faresult == "autorecall" : self.gameResult[player] = -1 self.gameFaResult[player] = faresult self.log.debug("%s autorecalled" % player ) if not player in self.autorecalled: self.autorecalled.append(player) query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(player) query.exec_() if query.size() == 1 : query.first() playerUid = int(query.value(0)) self.log.debug(playerUid) self.parent.lobby.sendJSON(dict(command="autorecall", playeruid=playerUid)) if player in self.gameFaResult : self.log.debug("%s previous result : %s " % (player, self.gameFaResult[player])) self.log.debug("%s new result : %s " % (player, faresult)) if self.gameFaResult[player] == "score" : # the play got not decicive result yet, so we can apply it. self.gameFaResult[player] = faresult #self.gameResult[player] = score else : if faresult == "defeat": if player in self.recalled or player in self.autorecalled: self.log.debug("recalled to defeat -> invalid") self.wrongReport = True elif self.gameFaResult[player] == "victory" : if not player in self.invalidPlayers : self.log.debug("victory to defeat !?") #self.invalidPlayers.append(player) elif time.time() - self.startedAt < ((60*4) + 10) : self.log.debug("too soon to die...") self.setInvalid("Game is invalid : Play time was not long enough.") #if we try to set a defeat, but the player was victory.. We've got a disparity problem ! # else : if faresult != "score" : self.gameFaResult[player] = faresult if faresult == "defeat" : self.gameResult[player] = -1 elif faresult == "recall" or faresult == "autorecall": self.gameResult[player] = -1 elif faresult == "victory" : self.gameResult[player] = 1 elif faresult == "draw" : self.gameResult[player] = -1 else : self.log.debug("%s result : %s " % (player, faresult)) if faresult != "score" : self.gameFaResult[player] = faresult if faresult == "defeat" : self.gameResult[player] = -1 elif faresult == "recall" or faresult == "autorecall": self.gameResult[player] = -1 elif faresult == "victory" : self.gameResult[player] = 1 elif faresult == "draw" : self.gameResult[player] = -1
def getLeague(self, season, player): query = QSqlQuery(self.db) query.prepare("SELECT league FROM %s WHERE idUser = ?" % season) query.addBindValue(player.getId()) query.exec_() if query.size() > 0: query.first() return int(query.value(0)) # place the player in his league ! else: query.prepare( "INSERT INTO %s (`idUser` ,`league` ,`score`) VALUES (?, 1, 0)" % season) query.addBindValue(player.getId()) query.exec_() return 1
def load(layout): """"Loads the file and restores the saved state""" # Restore the first day of usage global_vars.DAYFIRST = datetime.date.fromordinal(int(open(paths.savePath).read().splitlines()[0])) filename = os.path.basename(paths.savePath)[:-8] database.setConnection(filename) layout.initTasks(database.getStatuses()) layout.tab.clearAll() # ### Loading main table # # weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] opened = False q = 'SELECT * FROM main' query = QSqlQuery(q) while query.next(): record = query.record() indexes = [] if not record.isEmpty(): for i in range(0, 44): if not record.isNull(i + 1): indexes.append(i) day = str(record.field('weekday').value()).split('_') weekday = day[0] weeknum = int(day[1]) values = {} for index in indexes: q = QSqlQuery("SELECT name FROM tasks WHERE rowid ='" + str(query.value(index + 1)) + "'") q.next() values[index] = q.value(0) if values: opened = True layout.tab.setValues(values, weekdays.index(weekday), weeknum) if not opened: layout.tab.openTab(1) # # ################ # Loading evaluation values # q = 'SELECT * from evaluation' query = QSqlQuery(q) while query.next(): record = query.record() if not record.isEmpty(): week = record.field('week').value() values = [] for day in global_vars.WEEKDAYS: values.append(record.field(day).value()) global_vars.EVAL_VALUES[week] = values database.dropConnection()
def trueSkillUpdate(self, tsresults, tsplayers, logger, db, players, playerFnc="setRating", table="global_rating", winner=False, sendScore=True): logger.debug("TS Results") noHumanResult = False if len(self.AIs) > 0: noHumanResult = True #sending to players for playerTS in tsplayers: name = playerTS.getPlayer() nameAI = None AI = False if str(name) in self.AIs: logger.debug("This is an AI") nameAI = str(name).rstrip(string.digits) AI = True logger.debug(name) logger.debug("original score") logger.debug(playerTS.getRating()) origScore = playerTS.getRating() # if we got a result... Something bad can happens if tsresults != 0: # if the player was really in a playing team if str(name) in tsresults.getAllPlayersNames(): logger.debug("player in game TrueSkill") mean = (tsresults.getRating(name).getMean() * self.partial) + (playerTS.getRating().getMean() * (1 - self.partial)) dev = (tsresults.getRating(name).getStandardDeviation() * self.partial) + ( playerTS.getRating().getStandardDeviation() * (1 - self.partial)) resPlayer = tsresults.getRating(name) resPlayer.setMean(mean) resPlayer.setStandardDeviation(dev) logger.debug(resPlayer) # Now we write the result in the DB. If player has already disconnect, it will update his score # no matter what. #db.open() query = QSqlQuery(db) if winner: if self.isWinner(name): queryStr = ( "UPDATE %s set mean =%f, deviation = %f, numGames = (numGames +1), winGames = (winGames +1) WHERE id = (SELECT id FROM login WHERE login.login = '******')" ) % (table, mean, dev, str(name)) query.exec_(queryStr) else: queryStr = ( "UPDATE %s set mean =%f, deviation = %f, numGames = (numGames +1) WHERE id = (SELECT id FROM login WHERE login.login = '******')" ) % (table, mean, dev, str(name)) query.exec_(queryStr) else: if AI: queryStr = ( "UPDATE AI_rating set mean =%f, deviation = %f, numGames = (numGames +1) WHERE id = (SELECT id FROM AI_names WHERE AI_names.login = '******')" ) % (mean, dev, nameAI) query.exec_(queryStr) gameId = self.getuuid() queryStr = ( "UPDATE game_player_stats set `after_mean` = %f, `after_deviation` = %f WHERE `gameId` = %s AND `playerId` = (SELECT id FROM AI_names WHERE login = '******' )" ) % (mean, dev, str(gameId), nameAI) logger.debug(queryStr) else: if noHumanResult == False: queryStr = ( "UPDATE %s set mean =%f, deviation = %f, numGames = (numGames +1) WHERE id = (SELECT id FROM login WHERE login.login = '******')" ) % (table, mean, dev, str(name)) query.exec_(queryStr) gameId = self.getuuid() queryStr = ( "UPDATE game_player_stats set `after_mean` = %f, `after_deviation` = %f WHERE `gameId` = %s AND `playerId` = (SELECT id FROM login WHERE login = '******' )" ) % (mean, dev, str(gameId), str(name)) logger.debug(queryStr) query.exec_(queryStr) #logger.debug(queryStr) #db.close() # if the player is still online, we update his rating if noHumanResult == False: for player in players.getAllPlayers(): if str(player.getLogin()) == str(name): logger.debug("found player online") function = getattr(player, playerFnc) function(resPlayer) break # and we send the score if sendScore: results = self.getAllResults() self.sendMessageToPlayers(players, name, results) else: if sendScore: self.sendMessageToPlayers( players, name, "AI detected in game - No rating for humans.") else: logger.debug("ERROR : No Valid TS results !")
def done(self): #writing file self.__logger.debug("writing the replay") self.__logger.debug(self.uid) if self.gw : self.getGWReplaysInfos() else: self.getReplaysInfos() # Construct the path where the replay is stored path = config['global']['content_path'] + "vault/replay_vault" if self.gw : path = config['global']['content_path'] + "gwreplays" dirsize = 100 depth = 5 i = depth dirname = path while i > 1: dirname = dirname + "/" + str((self.uid/(dirsize**(i-1)))%dirsize) i = i - 1 filename = dirname + "/" + str(self.uid) + ".fafreplay" self.__logger.debug("filename: " + filename) if not os.path.exists(dirname): os.makedirs(dirname) writeFile = QtCore.QFile(filename) if(writeFile.open(QtCore.QIODevice.WriteOnly)) : writeFile.write(json.dumps(self.replayInfo)) writeFile.write('\n') replayData = QtCore.QByteArray() replayDataQByte = QtCore.QByteArray() replayDataStream = QtCore.QDataStream(replayDataQByte, QtCore.QIODevice.WriteOnly) replayStream = QtCore.QDataStream(self.getReplayData(), QtCore.QIODevice.ReadOnly) replayStream.device().seek(0) while replayStream.atEnd() == False : timePacket = replayStream.readDouble() lenData = replayStream.readUInt32() datas = replayStream.readRawData(lenData) replayData.append(datas) replayDataStream.writeUInt32(replayData.size()) replayDataStream.writeRawData(zlib.compress(replayData.data(),9)) writeFile.write(replayDataQByte.toBase64()) writeFile.close() # We mention the existence of the replay inside the Database. self.parent.db.open() query = QSqlQuery(self.parent.db) if self.gw : query.prepare("INSERT INTO `galacticwar`.`game_replays`(`UID`) VALUES (?)") else : query.prepare("INSERT INTO `game_replays`(`UID`) VALUES (?)") query.addBindValue(self.uid) if not query.exec_(): self.__logger.debug("error adding replay to database") self.parent.db.close() self.__logger.debug("fafreplay written")
def add(self, winner, loser): query = QSqlQuery(self.parent.db) query.prepare( "INSERT INTO `domination`(`dominant`, `slave`) VALUES (?,?)") query.addBindValue(winner) query.addBindValue(loser) query.exec_() query.prepare( "UPDATE `domination` SET `dominant`=? WHERE dominant = ?") query.addBindValue(winner) query.addBindValue(loser) query.exec_() self.dominations[loser] = winner
def getMapName(self, mapId): query = QSqlQuery(self.db) query.prepare("SELECT filename FROM table_map WHERE id = ?") query.addBindValue(mapId) query.exec_() if query.size() > 0: query.first() return str(query.value(0)).split("/")[1].replace(".zip", "") else: return None
def update(self): query = QSqlQuery(self.parent.db) query.prepare( "SELECT id, uid_player, uid_planet, attack_time, faction, defended, IFNULL(dominant,-1) FROM `attacks` LEFT JOIN accounts ON accounts.uid = uid_player LEFT JOIN domination on faction = domination.slave WHERE 1" ) query.exec_() if query.size() > 0: allUids = [] while query.next(): uid = int(query.value(0)) playeruid = int(query.value(1)) planetuid = int(query.value(2)) attack = (time.time() - query.value(3).toTime_t()) faction = int(query.value(4)) if int(query.value(6)) != -1: faction = int(query.value(6)) defended = bool(query.value(5)) allUids.append(uid) if not uid in self.attacks: self.addAttack(uid, playeruid, faction, planetuid, attack, defended) else: self.updateAttack(uid, playeruid, attack, defended) toDelete = [] for uid in self.attacks: if not uid in allUids: toDelete.append(uid) for uid in toDelete: del self.attacks[uid] else: self.attacks = {}
def specialEnding(self, logger, db, players): try : self.log.debug("special ending.") if len(self.invalidPlayers) == self.numPlayers or self.wrongReport == True: if self.wrongReport: self.log.debug("Recalled player declared defeated.. Player recalled:") for p in self.recalled: self.log.debug(p) self.log.debug("Scores") self.log.debug(self.gameResult) self.log.debug("Recalled player declared defeated..") else: self.log.debug("Invalid : self.invalidPlayers == numPlayer") self.parent.lobby.sendJSON(dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) return False #computing winning team teams = self.finalTeams teamsResults = {} teamsResults[1] = {} teamsResults[2] = {} teamsResults[1]["players"] = {} teamsResults[2]["players"] = {} for teams in self.finalTeams : curScore = 0 for player in teams.getAllPlayers() : uid = player.getId() self.log.debug("searching") self.log.debug(uid) query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(uid) query.exec_() playerUid = 1 if query.size() == 1 : query.first() self.log.debug("found uid") playerUid = int(query.value(0)) self.log.debug(playerUid) if playerUid in self.attackers : i = 1 else : i = 2 if uid in str(self.gameResult) : resultPlayer = self.gameResult[uid] if resultPlayer <= -1 : if uid in self.recalled : teamsResults[i]["players"][playerUid] = 0 elif uid in self.autorecalled: teamsResults[i]["players"][playerUid] = -1 else : teamsResults[i]["players"][playerUid] = -2 else : teamsResults[i]["players"][playerUid] = 1 curScore = curScore + resultPlayer else : self.parent.lobby.sendJSON(dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) self.log.debug("score not found for %s" % str(uid)) return 0 teamsResults[i]["score"] = curScore if self.desync < 2: results = json.dumps(teamsResults) self.log.debug(teamsResults) self.parent.lobby.sendJSON(dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results=results)) else: self.log.debug(self.getInvalidReason()) self.parent.lobby.sendJSON(dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) except : self.log.exception("Something awful happened when finishing a gw game !")
def save(layout): """"Saves the state of the program and moves the save file to specified place""" # Create a file if there is no previous save # else move db to current folder to save if not os.path.isfile(paths.savePath): # Create txt and write down the first day of usage savefile = open(paths.savePath, mode='w') savefile.write(str(global_vars.DAYFIRST.toordinal())) savefile.close() filename = os.path.basename(paths.savePath)[:-8] # Saving tasks widget block database.setConnection(filename) database.truncate() groups = layout.taskwidget.getGroups() for group in groups: query = QSqlQuery() query.prepare("INSERT INTO status (name) VALUES (:name)") query.bindValue(":name", group.getName()) query.exec_() query = QSqlQuery("SELECT rowid FROM status WHERE name = '" + group.getName() + "' ") query.next() id_ = query.value(0) for task in group: query = QSqlQuery() query.prepare( "INSERT INTO tasks (name, status) VALUES (:name, :id)") query.bindValue(":name", task.getTask()) query.bindValue(":id", id_) query.exec_() # Saving maintable for weeknum in layout.tab.notsaved: table = layout.tab.getWidgetFromWeeknum(weeknum) weekdays = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] for weekday in weekdays: tasks = table.getTasks(weekday) if tasks: fields = '' values = '' for time in tasks: query = QSqlQuery("SELECT rowid FROM tasks WHERE name ='" + tasks[time] + "'") query.next() tasks[time] = query.value(0) fields += '"' + time + '"' + ',' values += str(tasks[time]) + ',' fields = 'weekday,' + fields[:-1] values = '"' + weekday + '_' + str( weeknum) + '"' + ', ' + values[:-1] request = 'INSERT INTO main (' + fields + ') VALUES (' + values + ')' query = QSqlQuery() query.exec_(request) layout.tab.notsaved = [] # Saving evaluation values for week in global_vars.EVAL_VALUES.keys(): val = str(week) + ', ' for value in global_vars.EVAL_VALUES[week]: val += str(value) + ', ' request = 'INSERT INTO evaluation VALUES(' + val[:-2] + ')' query = QSqlQuery() query.exec_(request) # Saving neural network weights parent = layout.parentWidget() exists = True try: parent.network except (AttributeError, NameError): exists = False if exists: hdw = parent.network.hiddenweights otpw = parent.network.outputweights request = 'INSERT INTO weights (input, output, value) ' for i in range(len(hdw)): for j in range(len(hdw[i])): if (i == 0) and (j == 0): request += 'SELECT ' + '"in_' + str( i) + '", "hidden_' + str(j) + '", ' + str(hdw[i][j]) else: request += ' UNION ALL' request += ' SELECT ' + '"in_' + str( i) + '", "hidden_' + str(j) + '", ' + str(hdw[i][j]) for i in range(len(otpw)): for j in range(len(otpw[i])): request += ' UNION ALL' request += ' SELECT ' + '"hidden_' + str(i) + '", "out_' + str( j) + '", ' + str(hdw[i][j]) print(request) query = QSqlQuery() query.exec_(request) print(query.lastError()) print('Saved') # Restoring the original state database.dropConnection()
def load(layout): """"Loads the file and restores the saved state""" # Restore the first day of usage global_vars.DAYFIRST = datetime.date.fromordinal( int(open(paths.savePath).read().splitlines()[0])) filename = os.path.basename(paths.savePath)[:-8] database.setConnection(filename) layout.initTasks(database.getStatuses()) layout.tab.clearAll() # ### Loading main table # # weekdays = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] opened = False q = 'SELECT * FROM main' query = QSqlQuery(q) while query.next(): record = query.record() indexes = [] if not record.isEmpty(): for i in range(0, 44): if not record.isNull(i + 1): indexes.append(i) day = str(record.field('weekday').value()).split('_') weekday = day[0] weeknum = int(day[1]) values = {} for index in indexes: q = QSqlQuery("SELECT name FROM tasks WHERE rowid ='" + str(query.value(index + 1)) + "'") q.next() values[index] = q.value(0) if values: opened = True layout.tab.setValues(values, weekdays.index(weekday), weeknum) if not opened: layout.tab.openTab(1) # # ################ # Loading evaluation values # q = 'SELECT * from evaluation' query = QSqlQuery(q) while query.next(): record = query.record() if not record.isEmpty(): week = record.field('week').value() values = [] for day in global_vars.WEEKDAYS: values.append(record.field(day).value()) global_vars.EVAL_VALUES[week] = values database.dropConnection()
def specialEnding(self, logger, db, players): if len(self.invalidPlayers) == 2 : self.setInvalid("Scores not validated. Possible reason : Disconnection between players.") if self.isValid() : if self.isDraw() : query = QSqlQuery(db) queryStr = ("SELECT id FROM table_map WHERE filename LIKE '%"+self.getGameMap()+"%'") query.exec_(queryStr) if query.size() == 1: query.first() mapId = query.value(0) queryStr = ("UPDATE table_map_features set num_draws = (num_draws +1) WHERE map_id LIKE " + str(mapId)) query.exec_(queryStr) # tsresults = self.computeResults() # tsplayers = self.getTrueSkillPlayers() # self.trueSkillUpdate(tsresults, tsplayers, logger, db, players) tsresults = self.computeResults1v1() tsplayers = self.getTrueSkill1v1Players() self.trueSkillUpdate(tsresults, tsplayers, logger, db, players, playerFnc="setladder1v1Rating" ,table="ladder1v1_rating", winner=True, sendScore=False) # and for the ladder ! evenLeague = True maxleague = max(self.leagues.iteritems(), key=operator.itemgetter(1))[1] if len(set(self.leagues.values())) != 1 : evenLeague = False if not self.isDraw() : query = QSqlQuery(db) for player in self.gameResult : if self.isWinner(player) : # if not even league: scoreToAdd = 1 if not evenLeague: if self.leagues[player] == maxleague: scoreToAdd = 0.5 else : scoreToAdd = 1.5 query.prepare("UPDATE %s SET score = (score + ?) WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(scoreToAdd) query.addBindValue(player) query.exec_() logger.debug(query.executedQuery()) else: # if not even league: scoreToRemove = 0.5 if not evenLeague : if self.leagues[player] == maxleague: scoreToRemove = 1 else : scoreToRemove = 0 query.prepare("UPDATE %s SET score = GREATEST(0,(score - ?)) WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(scoreToRemove) query.addBindValue(player) query.exec_() logger.debug(query.executedQuery()) #check if the user must be promoted query.prepare("SELECT league, score FROM %s WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() if query.size() != 0: update = False query.first() pleague = int(query.value(0)) pscore = float(query.value(1)) if pleague == 1 and pscore > 50: query.prepare("UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 2 and pscore > 75: query.prepare("UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 3 and pscore > 100: query.prepare("UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 4 and pscore > 150: query.prepare("UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True for p in players.getAllPlayers() : if str(p.getLogin()) == str(player) : query.prepare("SELECT score, league FROM %s WHERE idUser = ?" % self.parent.season) query.addBindValue(p.getId()) query.exec_() if query.size() > 0: query.first() score = float(query.value(0)) league = int(query.value(1)) query.prepare("SELECT name, `limit` FROM `ladder_division` WHERE `league` = ? AND `limit` >= ? ORDER BY `limit` ASC LIMIT 1") query.addBindValue(league) query.addBindValue(score) query.exec_() if query.size() > 0: query.first() p.setLeague(league) p.division = str(query.value(0)) else : tsplayers = self.getTrueSkillPlayers() for playerTS in tsplayers : name = playerTS.getPlayer() self.sendMessageToPlayers(players, name, self.getInvalidReason())
def save(layout): """"Saves the state of the program and moves the save file to specified place""" # Create a file if there is no previous save # else move db to current folder to save if not os.path.isfile(paths.savePath): # Create txt and write down the first day of usage savefile = open(paths.savePath, mode='w') savefile.write(str(global_vars.DAYFIRST.toordinal())) savefile.close() filename = os.path.basename(paths.savePath)[:-8] # Saving tasks widget block database.setConnection(filename) database.truncate() groups = layout.taskwidget.getGroups() for group in groups: query = QSqlQuery() query.prepare("INSERT INTO status (name) VALUES (:name)") query.bindValue(":name", group.getName()) query.exec_() query = QSqlQuery("SELECT rowid FROM status WHERE name = '" + group.getName() + "' ") query.next() id_ = query.value(0) for task in group: query = QSqlQuery() query.prepare("INSERT INTO tasks (name, status) VALUES (:name, :id)") query.bindValue(":name", task.getTask()) query.bindValue(":id", id_) query.exec_() # Saving maintable for weeknum in layout.tab.notsaved: table = layout.tab.getWidgetFromWeeknum(weeknum) weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] for weekday in weekdays: tasks = table.getTasks(weekday) if tasks: fields = '' values = '' for time in tasks: query = QSqlQuery("SELECT rowid FROM tasks WHERE name ='" + tasks[time] + "'") query.next() tasks[time] = query.value(0) fields += '"' + time + '"' + ',' values += str(tasks[time]) + ',' fields = 'weekday,' + fields[:-1] values = '"' + weekday + '_' + str(weeknum) + '"' + ', ' + values[:-1] request = 'INSERT INTO main (' + fields + ') VALUES (' + values + ')' query = QSqlQuery() query.exec_(request) layout.tab.notsaved = [] # Saving evaluation values for week in global_vars.EVAL_VALUES.keys(): val = str(week) + ', ' for value in global_vars.EVAL_VALUES[week]: val += str(value) + ', ' request = 'INSERT INTO evaluation VALUES(' + val[:-2] + ')' query = QSqlQuery() query.exec_(request) # Saving neural network weights parent = layout.parentWidget() exists = True try: parent.network except (AttributeError, NameError): exists = False if exists: hdw = parent.network.hiddenweights otpw = parent.network.outputweights request = 'INSERT INTO weights (input, output, value) ' for i in range(len(hdw)): for j in range(len(hdw[i])): if (i == 0) and (j == 0): request += 'SELECT ' + '"in_' + str(i) + '", "hidden_' + str(j) + '", ' + str(hdw[i][j]) else: request += ' UNION ALL' request += ' SELECT ' + '"in_' + str(i) + '", "hidden_' + str(j) + '", ' + str(hdw[i][j]) for i in range(len(otpw)): for j in range(len(otpw[i])): request += ' UNION ALL' request += ' SELECT ' + '"hidden_' + str(i) + '", "out_' + str(j) + '", ' + str(hdw[i][j]) print(request) query = QSqlQuery() query.exec_(request) print(query.lastError()) print('Saved') # Restoring the original state database.dropConnection()
def addResultPlayer(self, player, faresult, score): if faresult == "recall": self.log.debug("%s recalled" % player) if not player in self.recalled: self.recalled.append(player) self.gameResult[player] = -1 self.gameFaResult[player] = faresult if faresult == "autorecall": self.gameResult[player] = -1 self.gameFaResult[player] = faresult self.log.debug("%s autorecalled" % player) if not player in self.autorecalled: self.autorecalled.append(player) query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(player) query.exec_() if query.size() == 1: query.first() playerUid = int(query.value(0)) self.log.debug(playerUid) self.parent.lobby.sendJSON( dict(command="autorecall", playeruid=playerUid)) if player in self.gameFaResult: self.log.debug("%s previous result : %s " % (player, self.gameFaResult[player])) self.log.debug("%s new result : %s " % (player, faresult)) if self.gameFaResult[player] == "score": # the play got not decicive result yet, so we can apply it. self.gameFaResult[player] = faresult #self.gameResult[player] = score else: if faresult == "defeat": if player in self.recalled or player in self.autorecalled: self.log.debug("recalled to defeat -> invalid") self.wrongReport = True elif self.gameFaResult[player] == "victory": if not player in self.invalidPlayers: self.log.debug("victory to defeat !?") #self.invalidPlayers.append(player) elif time.time() - self.startedAt < ((60 * 4) + 10): self.log.debug("too soon to die...") self.setInvalid( "Game is invalid : Play time was not long enough.") #if we try to set a defeat, but the player was victory.. We've got a disparity problem ! # else: if faresult != "score": self.gameFaResult[player] = faresult if faresult == "defeat": self.gameResult[player] = -1 elif faresult == "recall" or faresult == "autorecall": self.gameResult[player] = -1 elif faresult == "victory": self.gameResult[player] = 1 elif faresult == "draw": self.gameResult[player] = -1 else: self.log.debug("%s result : %s " % (player, faresult)) if faresult != "score": self.gameFaResult[player] = faresult if faresult == "defeat": self.gameResult[player] = -1 elif faresult == "recall" or faresult == "autorecall": self.gameResult[player] = -1 elif faresult == "victory": self.gameResult[player] = 1 elif faresult == "draw": self.gameResult[player] = -1
def specialEnding(self, logger, db, players): if len(self.invalidPlayers) == 2: self.setInvalid( "Scores not validated. Possible reason : Disconnection between players." ) if self.isValid(): if self.isDraw(): query = QSqlQuery(db) queryStr = ("SELECT id FROM table_map WHERE filename LIKE '%" + self.getGameMap() + "%'") query.exec_(queryStr) if query.size() == 1: query.first() mapId = query.value(0) queryStr = ( "UPDATE table_map_features set num_draws = (num_draws +1) WHERE map_id LIKE " + str(mapId)) query.exec_(queryStr) # tsresults = self.computeResults() # tsplayers = self.getTrueSkillPlayers() # self.trueSkillUpdate(tsresults, tsplayers, logger, db, players) tsresults = self.computeResults1v1() tsplayers = self.getTrueSkill1v1Players() self.trueSkillUpdate(tsresults, tsplayers, logger, db, players, playerFnc="setladder1v1Rating", table="ladder1v1_rating", winner=True, sendScore=False) # and for the ladder ! evenLeague = True maxleague = max(self.leagues.iteritems(), key=operator.itemgetter(1))[1] if len(set(self.leagues.values())) != 1: evenLeague = False if not self.isDraw(): query = QSqlQuery(db) for player in self.gameResult: if self.isWinner(player): # if not even league: scoreToAdd = 1 if not evenLeague: if self.leagues[player] == maxleague: scoreToAdd = 0.5 else: scoreToAdd = 1.5 query.prepare( "UPDATE %s SET score = (score + ?) WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(scoreToAdd) query.addBindValue(player) query.exec_() logger.debug(query.executedQuery()) else: # if not even league: scoreToRemove = 0.5 if not evenLeague: if self.leagues[player] == maxleague: scoreToRemove = 1 else: scoreToRemove = 0 query.prepare( "UPDATE %s SET score = GREATEST(0,(score - ?)) WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(scoreToRemove) query.addBindValue(player) query.exec_() logger.debug(query.executedQuery()) #check if the user must be promoted query.prepare( "SELECT league, score FROM %s WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() if query.size() != 0: update = False query.first() pleague = int(query.value(0)) pscore = float(query.value(1)) if pleague == 1 and pscore > 50: query.prepare( "UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 2 and pscore > 75: query.prepare( "UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 3 and pscore > 100: query.prepare( "UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True elif pleague == 4 and pscore > 150: query.prepare( "UPDATE %s SET league = league+1, score = 0 WHERE `idUser` = (SELECT id FROM login WHERE login.login = ?)" % self.parent.season) query.addBindValue(player) query.exec_() update = True for p in players.getAllPlayers(): if str(p.getLogin()) == str(player): query.prepare( "SELECT score, league FROM %s WHERE idUser = ?" % self.parent.season) query.addBindValue(p.getId()) query.exec_() if query.size() > 0: query.first() score = float(query.value(0)) league = int(query.value(1)) query.prepare( "SELECT name, `limit` FROM `ladder_division` WHERE `league` = ? AND `limit` >= ? ORDER BY `limit` ASC LIMIT 1" ) query.addBindValue(league) query.addBindValue(score) query.exec_() if query.size() > 0: query.first() p.setLeague(league) p.division = str(query.value(0)) else: tsplayers = self.getTrueSkillPlayers() for playerTS in tsplayers: name = playerTS.getPlayer() self.sendMessageToPlayers(players, name, self.getInvalidReason())
def updateTrueskill(self): ''' Update all scores from the DB before updating the results''' self.log.debug("updating ratings") try: for team in self.finalTeams: for member in team.getAllPlayers(): query = QSqlQuery(self.parent.db) query.prepare( "SELECT mean, deviation FROM global_rating WHERE id = (SELECT id FROM login WHERE login = ?)" ) query.addBindValue(member.getId()) query.exec_() self.log.debug("updating a player") if query.size() > 0: query.first() team.getRating(member).setMean(query.value(0)) team.getRating(member).setStandardDeviation( query.value(1)) else: self.log.debug("error updating a player") self.log.debug(member.getId()) except: self.log.exception( "Something awful happened while updating trueskill!")
def __resulatEnvoi(self, errCode): u"""Slot notifié quand l'envoi du mail est fini errCode indique le succès, ou l'échec (avec la raison) de l'envoi du mail """ if errCode == MailSender.MAIL_ERROR_NONE: # Mail envoyé, mise à jour de la base self.notification.emit(u"Email envoyé", MailUI.DUREE_MESSAGE) index = self._ui.cbAbsence.currentIndex() sql = MailSQL.mailEnvoye(str(self.__absences[index]["id"])) req = QSqlQuery() if not req.exec_(sql): QMessageBox.critical( self, u"Erreur de base de données", u"Le mail a été envoyé mais impossible de <br />" + u"l'enregistrer dans la base.") # TODO logger print "SQL error" print str(req.lastError().text().toUtf8()) print req.lastQuery() else: self.majBdd.emit() elif (errCode == MailSender.MAIL_ERROR_TIMEOUT or errCode == MailSender.MAIL_ERROR_CONNECTION): message = u"Email non envoyé - " if errCode == MailSender.MAIL_ERROR_TIMEOUT: message += u"Durée dépassée" else: message += u"Erreur de connexion" self.notification.emit(message, MailUI.DUREE_MESSAGE) QMessageBox.critical( self, "Erreur de connection", u"Impossible de contacter le serveur.<br />" + u"Veuillez vérifier la connexion à internet, <br />" + u"ainsi que l'adresse du serveur de messagerie.") elif errCode == MailSender.MAIL_ERROR_AUTHENTICATION: message = u"Email non envoyé - Erreur d'authentification" self.notification.emit(message, MailUI.DUREE_MESSAGE) QMessageBox.critical( self, "Erreur d'authentification", "Indentifiants incorrects.<br />(login " + self.__conf["email"] + ")") del self.__password else: # MailSender.MAIL_ERROR_OTHER: message = u"Email non envoyé - Erreur inconnue" self.notification.emit(message, MailUI.DUREE_MESSAGE) QMessageBox.critical( self, "Erreur inconnue", "Une erreur inconnue s'est produite.<br />(login '" + self.__conf["email"] + "')") # TODO logger l'erreur réelle à la levée de l'exception self.majBdd.emit()
def updateTrueskillFor1v1(self): ''' Update all scores from the DB before updating the results''' try : for team in self.finalTeams1v1 : for member in team.getAllPlayers() : query = QSqlQuery(self.parent.db) query.prepare("SELECT mean, deviation FROM ladder1v1_rating WHERE id = (SELECT id FROM login WHERE login = ?)") query.addBindValue(member.getId()) query.exec_() self.log.debug("updating a player") if query.size() > 0: query.first() team.getRating(member).setMean(query.value(0)) team.getRating(member).setStandardDeviation(query.value(1)) else : self.log.debug("error updating a player") self.log.debug(member.getId()) except : self.log.exception("Something awful happened while updating trueskill!")
def getPlayerName(self, player): ''' Get the avatar name ''' try: if player.getLogin() in self.avatarNames: return self.avatarNames[player.getLogin()] self.log.debug("getting avatar name for %s (uid %i)" % (player.getLogin(), player.getId())) query = QSqlQuery(self.parent.db) uid = int(player.getId()) query.prepare( "SELECT name, id FROM galacticwar.`avatars` WHERE `uid` = ? AND `alive` = 1" ) query.addBindValue(uid) query.exec_() if query.size() == 1: query.first() name = str(query.value(0)) uid = int(query.value(1)) self.avatarNames[player.getLogin()] = name self.avatarIds[player.getLogin()] = uid self.log.debug("avatar name is %s (uid %i)" % (name, uid)) return name else: self.avatarNames[player.getLogin()] = player.getLogin() self.avatarIds[player.getLogin()] = player.getId() return player.getLogin() except: self.log.exception( "Something awful happened when getting a gw name !")
def getPlayerRealFaction(self, uid): query = QSqlQuery(self.parent.db) query.prepare( "SELECT faction FROM galacticwar.`accounts` WHERE `uid` = ?") query.addBindValue(uid) query.exec_() if query.size() == 1: query.first() return int(query.value(0)) return None
def specialEnding(self, logger, db, players): try: self.log.debug("special ending.") if len(self.invalidPlayers ) == self.numPlayers or self.wrongReport == True: if self.wrongReport: self.log.debug( "Recalled player declared defeated.. Player recalled:") for p in self.recalled: self.log.debug(p) self.log.debug("Scores") self.log.debug(self.gameResult) self.log.debug("Recalled player declared defeated..") else: self.log.debug( "Invalid : self.invalidPlayers == numPlayer") self.parent.lobby.sendJSON( dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) return False #computing winning team teams = self.finalTeams teamsResults = {} teamsResults[1] = {} teamsResults[2] = {} teamsResults[1]["players"] = {} teamsResults[2]["players"] = {} for teams in self.finalTeams: curScore = 0 for player in teams.getAllPlayers(): uid = player.getId() self.log.debug("searching") self.log.debug(uid) query = QSqlQuery(self.parent.db) query.prepare("SELECT id FROM login WHERE `login` = ?") query.addBindValue(uid) query.exec_() playerUid = 1 if query.size() == 1: query.first() self.log.debug("found uid") playerUid = int(query.value(0)) self.log.debug(playerUid) if playerUid in self.attackers: i = 1 else: i = 2 if uid in str(self.gameResult): resultPlayer = self.gameResult[uid] if resultPlayer <= -1: if uid in self.recalled: teamsResults[i]["players"][playerUid] = 0 elif uid in self.autorecalled: teamsResults[i]["players"][playerUid] = -1 else: teamsResults[i]["players"][playerUid] = -2 else: teamsResults[i]["players"][playerUid] = 1 curScore = curScore + resultPlayer else: self.parent.lobby.sendJSON( dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) self.log.debug("score not found for %s" % str(uid)) return 0 teamsResults[i]["score"] = curScore if self.desync < 2: results = json.dumps(teamsResults) self.log.debug(teamsResults) self.parent.lobby.sendJSON( dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results=results)) else: self.log.debug(self.getInvalidReason()) self.parent.lobby.sendJSON( dict(command="results", gameuid=self.uuid, planetuid=self.planetuid, results={})) except: self.log.exception( "Something awful happened when finishing a gw game !")
def getLeague(self, season, player): query = QSqlQuery(self.db) query.prepare("SELECT league FROM %s WHERE idUser = ?" % season) query.addBindValue(player.getId()) query.exec_() if query.size() > 0 : query.first() return int(query.value(0)) # place the player in his league ! else : query.prepare("INSERT INTO %s (`idUser` ,`league` ,`score`) VALUES (?, 1, 0)" % season) query.addBindValue(player.getId()) query.exec_() return 1
def create_tables(): qry = QSqlQuery() qry.exec_(''' CREATE TABLE employee ( id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE NOT NULL , department_id INTEGER NOT NULL , first_name VARCHAR(20) NOT NULL , last_name VARCHAR(20) , age INT , sex CHAR(1) , income FLOAT , last_update DATETIME DEFAULT CURRENT_TIMESTAMP , date_added DATETIME ) ''') qry.exec_(''' CREATE TABLE department ( id INTEGER PRIMARY KEY UNIQUE NOT NULL , name VARCHAR(40) NOT NULL ) ''' ) # populate department table with test values qry.exec_('''INSERT INTO department(id, name) VALUES (1, 'Shipping')''') qry.exec_('''INSERT INTO department(id, name) VALUES (2, 'Receiving')''') qry.exec_('''INSERT INTO department(id, name) VALUES (3, 'Accounts Payable')''') # Populate employee table with test values qry.exec_(''' INSERT INTO employee (department_id, first_name, last_name, age, sex, income) VALUES (1, 'Alice', 'A', 30, 'F', 5000.00) ''') qry.exec_(''' INSERT INTO employee (department_id, first_name, last_name, age, sex, income) VALUES (2,'Bob', 'B', 31, 'M', 5100.00) ''') qry.exec_(''' INSERT INTO employee (department_id, first_name, last_name, age, sex, income) VALUES (1, 'Caesar', 'C', 32, 'F', 5200.00) ''') qry.exec_(''' INSERT INTO employee (department_id, first_name, last_name, age, sex, income) VALUES (2, 'Danny', 'D', 34, 'M', 5300.00) ''') qry.exec_(''' INSERT INTO employee (department_id, first_name, last_name, age, sex, income) VALUES (1, 'Eziekel', 'E', 35, 'F', 5400.00) ''')
def getReplaysInfos(self): #general stats self.parent.db.open() self.replayInfo["game_end"] = time.time() query = QSqlQuery(self.parent.db) queryStr = ("SELECT game_featuredMods.gamemod, gameType, filename, gameName, host, login, playerId, AI, team FROM `game_stats` LEFT JOIN game_player_stats ON `game_player_stats`.`gameId` = game_stats.id LEFT JOIN table_map ON `game_stats`.`mapId` = table_map.id LEFT JOIN login ON login.id = `game_player_stats`.`playerId` LEFT JOIN game_featuredMods ON `game_stats`.`gameMod` = game_featuredMods.id WHERE game_stats.id = %i" % self.uid) query.exec_(queryStr) if query.size() != 0: self.replayInfo["num_players"] = query.size() query.first() self.replayInfo["featured_mod"] = str(query.value(0)) self.replayInfo["game_type"] = int(query.value(1) or 0) mapname = str(query.value(2)) self.replayInfo["title"] = str(query.value(3).encode('utf-8')) self.replayInfo["featured_mod_versions"] = {} # checking featured mod version tableMod = "updates_" + str(query.value(0)) tableModFiles = tableMod + "_files" query2 = QSqlQuery(self.parent.db) query2.prepare("SELECT fileId, MAX(version) FROM `%s` LEFT JOIN %s ON `fileId` = %s.id GROUP BY fileId" % (tableModFiles, tableMod, tableMod)) query2.exec_() if query2.size() != 0 : while query2.next() : self.replayInfo["featured_mod_versions"][int(query2.value(0))] = int(query2.value(1)) self.replayInfo["mapname"] = os.path.splitext(os.path.basename(mapname))[0] self.replayInfo["complete"] = True teams = {} while query.next() : team = int(query.value(8)) name = str(query.value(5)) isAi = int(query.value(7)) if int(query.value(4)) == int(query.value(6)) : self.replayInfo["host"] = name if isAi == 0 : if not team in teams : teams[team] = [] teams[team].append(name) self.replayInfo["teams"] = teams self.parent.db.close()
def miseAJour(self): u"""Liste les absences pouvant donner lieu à un email de rappel""" self._ui.cbAbsence.clear() # Vérification des mails à envoyer req = QSqlQuery() sql = MailSQL.construitRequeteComptage(self.__conf["duree"]) if req.exec_(sql): req.next() nbMails = req.record().value(0) else: # TODO log print req.lastError().text() print req.lastQuery() print "Erreur de requête" return label = str(nbMails) + " absence" if nbMails == 0: label += " :" self._ui.lAbsence.setText(label) self._ui.leSujet.setText("") self._ui.teCorps.setText("") self.__activerUi(False) self._ui.pbEnvoyer.setText("Envoyer") return else: self.__activerUi(True) if nbMails > 1: label += "s" label += " :" self._ui.lAbsence.setText(label) sql = MailSQL.construitRequeteListe(self.__conf["duree"]) if not req.exec_(sql): print req.lastError().text() print req.lastQuery() print "Erreur de requête" else: self.__absences = [] while (req.next()): absence = {} rec = req.record() absence = {} absence["id"] = rec.value(0) absence["date"] = QDate.fromString(rec.value(1), Qt.ISODate) absence["nom"] = rec.value(2) absence["adresse"] = rec.value(3) self.__absences.append(absence) item = absence["nom"] + " le " item += absence["date"].toString(Qt.SystemLocaleLongDate) self._ui.cbAbsence.addItem(item)
def getGWReplaysInfos(self): self.parent.db.open() self.replayInfo["game_end"] = time.time() query = QSqlQuery(self.parent.db) self.replayInfo["featured_mod"] = "gw" self.replayInfo["game_type"] = 0 query.prepare("SELECT filename, planets.name, avatars.name \ FROM galacticwar.game_stats \ LEFT JOIN galacticwar.game_player_stats ON galacticwar.game_player_stats.`gameId` = galacticwar.game_stats.id \ LEFT JOIN galacticwar.planets ON galacticwar.planets.id = galacticwar.game_stats.planetuid \ LEFT JOIN galacticwar.planet_maps ON galacticwar.planet_maps.planetuid = galacticwar.game_stats.planetuid \ LEFT JOIN faf_lobby.table_map ON galacticwar.planet_maps.`mapuid` = faf_lobby.table_map.id \ LEFT JOIN galacticwar.avatars ON galacticwar.avatars.id = galacticwar.game_player_stats.`avatarId` \ WHERE galacticwar.game_stats.id = ? ") query.addBindValue(self.uid) query.exec_() if query.size() != 0: self.replayInfo["num_players"] = query.size() query.first() mapname = str(query.value(0)) self.replayInfo["title"] = str("battle on " +query.value(1)) self.replayInfo["featured_mod_versions"] = {} tableMod = "updates_gw" tableModFiles = tableMod + "_files" query2 = QSqlQuery(self.parent.db) query2.prepare("SELECT fileId, MAX(version) FROM `%s` LEFT JOIN %s ON `fileId` = %s.id GROUP BY fileId" % (tableModFiles, tableMod, tableMod)) query2.exec_() if query2.size() != 0 : while query2.next() : self.replayInfo["featured_mod_versions"][int(query2.value(0))] = int(query2.value(1)) self.replayInfo["mapname"] = os.path.splitext(os.path.basename(mapname))[0] self.replayInfo["complete"] = True self.parent.db.close()
def getSelectedLadderMaps(self, playerId): query = QSqlQuery(self.db) query.prepare( "SELECT idMap FROM ladder_map_selection WHERE idUser = ?") query.addBindValue(playerId) query.exec_() maps = [] if query.size() > 0: while query.next(): maps.append(int(query.value(0))) return maps