def load_data(self): try: with open('votechain-{}.txt'.format(self.node_id), mode='r') as f: # file_content = pickle.loads(f.read()) file_content = f.readlines() # blockchain = file_content['chain'] # open_transactions = file_content['ot'] votechain = json.loads(file_content[0][:-1]) # We need to convert the loaded data because Transactions should use OrderedDict updated_blockchain = [] for block in votechain: converted_tx = [ Vote(tx['sender'], tx['recipient'], tx['signature']) for tx in block['votes'] ] updated_block = Vote_Block(block['index'], block['previous_hash'], converted_tx, block['proof'], block['timestamp']) updated_blockchain.append(updated_block) self.votechain = updated_blockchain open_transactions = json.loads(file_content[1][:-1]) # We need to convert the loaded data because Transactions should use OrderedDict updated_transactions = [] for tx in open_transactions: updated_transaction = Vote(tx['voter'], tx['vote_to'], tx['signature']) updated_transactions.append(updated_transaction) self.__open_transactions = updated_transactions peer_nodes = json.loads(file_content[2]) self.__peer_nodes = set(peer_nodes) except (IOError, IndexError): pass finally: print('Cleanup!')
def createVote(self, voter, voted_for, zoneSection, privateKey): if (voter == "" or voted_for == ""): return False # Forneça todos os campos! Sua chave, em quem vota e suas Zona e Seção # Pega a chave pública associada à chave privada fornecida publicKey = keys.get_public_key(privateKey, curve.secp256k1) if (voter != publicKey.__str__()): return False # Chave inválida for vote in self.pendingVotes: if (publicKey == vote.voter): return False # Voto já adicionado (pendente) for block in self.chain: if (block.vote.voter.__str__() == publicKey.__str__()): return False # Voto já realizado # Cria uma nova cédula de votação vote = Vote(publicKey, voted_for, zoneSection) # Assina a cédula vote.signVote(privateKey) # Verifica se a assinatura é válida if (not vote.verifyVote(privateKey)): return False # Assinatura inválida. Voto não computado # Caso tudo ocorra com sucesso, adiciona ao array de votos pendentes de mineração self.pendingVotes.append(vote) return True
async def parseVote(ctx): cmdBase = botPrefix + "vote " author = ctx.author.name message = ctx.message.content[len(cmdBase):] if Vote.doesUserVoteExist(author): await Vote.closeVote(ctx, Vote.popVote(author)) else: await Vote.createVote(ctx, author, message)
def Conspiracy(self, input, toBeat, toWin): retVotes = [] for vote in input: retVotes.append(Vote(vote)) for vote in retVotes: foundFirst = False i = 0 while i < len(vote.getList()): j = 0 toWinFound = False toBeatFound = False rank = vote.getList()[i] while j < len(rank): if toWin == rank[j]: toWinFound = True if toBeat == rank[j]: toBeatFound = True j += 1 if not foundFirst and toWinFound: break if toBeatFound: foundFirst = True rank.remove(toBeat) if toWinFound: rank.remove(toWin) break i += 1 if foundFirst == True: vote.getList().insert(0, [toWin]) vote.getList().append([toBeat]) return retVotes
def readMy(self): inputFile = open("test.txt", "r") input = [] for line in inputFile: next = line.strip('\n').split(" ") input.append(next) votes = [] for voter in input: thisRank = [] added = 0 previous = 0 while added < len(input[0]): minChoice = 10000 for vote in voter: if int(vote) < minChoice and int(vote) > previous: minChoice = int(vote) tied = [] i = 0 for vote in voter: if int(vote) == minChoice: tied.append(i) i += 1 thisRank.append(tied) previous = minChoice added += len(tied) thisVote = Vote(thisRank) votes.append(thisVote) return votes
def forest_vote(forest, data): truth = data[-1] no_trees = len(forest) votes = [] for x in range(no_trees): temp = forest[x] temp_tree = temp.inside_tree votes.append(decide(data, temp_tree)) decision = Vote(votes) return decision, truth
def readSwitzerland(path: str, country: str) -> List[Representative]: fileNames = listdir(path) cleanFileNames = [] for file in fileNames: fullFileNames = join(path, file) cleanFileNames.append(fullFileNames) allReps = {} for voteFile in cleanFileNames: with open(voteFile) as f: print(voteFile) try: voteXML = xmltodict.parse(f.read()) except: continue metaData = voteXML["feed"]["entry"][0]["content"]["m:properties"] voteNumber = int(metaData["d:IdVote"]["#text"]) try: voteSession = metaData["d:IdSession"]["#text"] except: continue sessionNumber = int(voteSession[2:4]) parNumber = int(voteSession[0:2]) metaDataTuple = (parNumber, sessionNumber, voteNumber) voteSummary = analyzeVotes(voteXML["feed"]["entry"]) voteOb = Vote(metaDataTuple, voteSummary) for repXML in voteXML["feed"]["entry"]: rep = repXML["content"]["m:properties"] name = int(rep["d:PersonNumber"]["#text"]) party = rep["d:ParlGroupName"] voteContent = int(rep["d:Decision"]["#text"]) if voteContent == 1: vote = 1 elif voteContent == 2: vote = 0 else: continue if not name in allReps: realName = rep["d:FirstName"] + " " + rep["d:LastName"] canton = rep["d:CantonName"] country = "Switzerland" newRep = Representative(realName, canton, canton, country) allReps[name] = newRep rep = allReps[name] rep.addVote(voteOb, vote, party) return allReps
def vote(self, post, voter, votee, power=None): result = False voter_elector = self.get_elector(post, voter) votee_elector = self.get_elector(post, votee) if (not voter_elector) or (not votee_elector): # Couldn't resolve one of the two players; might implement something for this later raise NotImplementedError if (not voter_elector.get_modifier(post, 'can_vote')) or ( not votee_elector.get_modifier(post, 'can_be_voted')): # Either the voter can't vote or the votee can't be voted; return return result if power is None: # Power wasn't specified, so use the voter's power power = voter_elector.get_modifier(post, 'vote_power') current_votes = self.active_votes_by_voter(post, voter_elector) if self._is_voting_for(post, voter_elector, votee_elector): if not voter_elector.get_modifier( post, 'multiple_simultaneous_votes_on_one_player'): # We can't vote the same target multiple times; return return result if len(current_votes) >= voter_elector.get_modifier( post, 'maximum_simultaneous_votes'): # We are at our vote cap; see if we can unvote if voter_elector.get_modifier(post, 'automatically_unvote'): unvote_result = self.unvote(post, voter, avoid_removing=votee_elector) if unvote_result: # Place the vote if the unvote succeeded. self.votes.append( Vote(voter_elector, votee_elector, post, power=power)) result = True else: # We are not at our vote cap; just place the vote self.votes.append( Vote(voter_elector, votee_elector, post, power=power)) result = True return result
def add_vote(self, vote_to, sender, signature): if self.hosting_node == None: return False self.vote_to = vote_to self.sender = sender vote = Vote(sender, vote_to, signature) if Verification.verify_vote(vote, self.get_balance): self.__open_transactions.append(vote) self.save_data() self.save_database() if len(self.__open_transactions) == 3: self.mine_block() return True return False
def testVoteScore(self): players = [fixName(x) for x in ['p1', 'p2', 'p3', 'p4', 'p5']] game = MafiaGame(players=players, mafia=1) game.recordVote( Vote(on=players[0], voters=['p2 ', 'p3 '], alive=players, day=1)) if (len(game.votes) == 0): return False vote = game.votes[0] print(game.getVoteGoodness(vote, 'p1 ')) print(game.getVoteGoodness(vote, 'p2 ')) print(game.getVoteGoodness(vote, 'p4 ')) print(game.players) return True
def ReinforcingTest(self, votes, split): groups = [] thisCopy = [] #Change system here and lower down system = STV() for i in range(0, split): groups.append([]) for vote in votes: thisCopy.append(Vote(vote)) for vote in thisCopy: groups[random.randint(0, split - 1)].append(vote) groupsOutcomes = [] for list in groups: ## To change system also have to check this line and lower down result = system.runWithRemoval(list) if isinstance(result[0], int): groupsOutcomes.append(result[0]) else: groupsOutcomes.append(-1) totalPairs = 0 totalMatches = 0 for i in range(0, len(groups)): for j in range(0, len(groups)): if i != j: if groupsOutcomes[i] == groupsOutcomes[j]: totalPairs += 1 combinedList = [] for vote in groups[i]: combinedList.append(vote) for vote in groups[j]: combinedList.append(vote) #This is the last line to change result = system.runWithRemoval(combinedList) if isinstance(result[0], int): if result[0] == groupsOutcomes[i]: totalMatches += 1 print("Number of same pairs : " + str(totalPairs)) print("Number that failed reinforcement : " + str(totalPairs - totalMatches))
def run(self, input): self.votes = [] for vote in input: self.votes.append(Vote(vote)) i = 0 candidates = [] for tie in input[0].list: for option in tie: candidates.append(Candidate(i)) self.key.append([i, i]) i += 1 plur = Plurality() output = [] for person in candidates: val = 0 ranking = plur.run(self.votes) if isinstance(ranking[len(ranking) - 1], int): val = ranking[len(ranking) - 1] else: val = ranking[len(ranking) - 1][0] self.removeLowest(val) found = False for pair in self.key: if val == pair[1] and not found: val = pair[0] found = True for pair in self.key: if val < pair[0]: pair[1] -= 1 if val == pair[0]: pair[1] = -1 output.insert(0, val) return output
def readCanada(path: str, country: str) -> List[Representative]: """ retreive all of the relevant xml files. Generate all the relevant Vote objects as well as the relevant Representative objects Return a dictionary with keys of the representative's name, and values of Representative objects """ # get the full list of file names that contain the relevante xml files fileNames = listdir(path) cleanFileNames = [] for file in fileNames: fullFileNames = join(path, file) cleanFileNames.append(fullFileNames) allReps = {} for voteFile in cleanFileNames: with open(voteFile) as f: # open the file, and parse the xml in it print(voteFile) resultDict = xmltodict.parse(f.read()) allVotesList = resultDict["List"]["VoteParticipant"] voteMetaData = voteFile.split("/")[-1][:-4].split( "_") # gets the meta data of the vote from the file name voteMetaData = (int(voteMetaData[0]), int(voteMetaData[1]), int(voteMetaData[2])) # turn the xml into a summarized dictionary voteSummary = analyzeVotes(allVotesList) voteOb = Vote(voteMetaData, voteSummary) # for every representative in the vote, add the vote object to their list of votes for voterRecord in allVotesList: currentRepName = voterRecord["Name"] if not currentRepName in allReps: # if the representative isn't yet in the all reps dictionary, create it and then add it to the dictionary newRep = Representative(voterRecord["Name"], voterRecord["ConstituencyName"], voterRecord["Province"], country) allReps[currentRepName] = newRep rep = allReps[currentRepName] rep.addVote(voteOb, int(voterRecord["Yea"]), voterRecord["PartyName"]) return allReps
def run(self, input, seats): self.votes = [] for ballot in input: self.votes.append(Vote(ballot)) i = 0 for tie in input[0].list: for option in tie: self.candidates.append(Candidate(i)) i += 1 for rank in self.votes: self.distributeNewVotes(rank) self.meekSTV(seats) return self.output # for candidate in self.candidates: # print(candidate.getCount())
def load(self): try: self.load_base_data() with open(f'{self.save_dir}/data.json', 'r') as save: data = json.load(save) self.settings = data["settings"] self.settings["role"] = get(self.guild_obj.roles, id=self.settings["role"]) self.check_settings() self.blocked_users = data["blocked_users"] self.table_channel = data["table_channel"] self.table_channel = self.guild_obj.get_channel(self.table_channel) self.default_channel = data["default_channel"] self.default_channel = self.guild_obj.get_channel( self.default_channel) self.table_id = data["table_id"] self.votes = { v: Vote.from_dict(data["votes"][v]) for v in data["votes"] } if self.table_channel == None or self.default_channel == None: asyncio.run_coroutine_threadsafe( self.create_discord_channels(), asyncio.get_event_loop()) new_blocked_list = {} self.blocked_users = new_blocked_list self.log('Successfully loaded saved data!') except Exception as e: print(e) asyncio.run_coroutine_threadsafe(self.repair(), asyncio.get_event_loop())
def removeCandidate(self, input, person): retVotes = [] for vote in input: retVotes.append(Vote(vote)) for vote in retVotes: i = 0 while i < len(vote.getList()): j = 0 rank = vote.getList()[i] while j < len(rank): if rank[j] == person: rank.remove(person) j -= 1 if len(rank) == 0: vote.getList().pop(i) i -= 1 elif rank[j] > person: rank[j] -= 1 j += 1 i += 1 return retVotes
def readUS(path: str, country: str) -> List[Representative]: """ retreive all of the relevant xml files. Generate all the relevant Vote objects as well as the relevant Representative objects Return a dictionary with keys of the representative's name, and values of Representative objects """ fileNames = listdir(path) cleanFileNames = [] for file in fileNames: fullFileNames = join(path, file) cleanFileNames.append(fullFileNames) allReps = {} for voteFile in cleanFileNames: with open(voteFile) as f: print(voteFile) fullXML = parse(f.read()) metaData = fullXML["rollcall-vote"]["vote-metadata"] metaDataTuple = (int(metaData["congress"]), int(metaData["session"][0]), int(metaData["rollcall-num"])) try: # for a small amount of votes they don't keep track of totals for this. # keeping track of these votes would add uneeded complexity so we instead choose to ignore them partyData = metaData["vote-totals"]["totals-by-party"] except: continue voteResult = {} for partyResult in partyData: voteResult[partyResult["party"]] = (int(partyResult["yea-total"]), int(partyResult["nay-total"])) voteOb = Vote(metaDataTuple, voteResult) try: # there is a single vote where this line causes a problem fullResult = fullXML["rollcall-vote"]["vote-data"]["recorded-vote"] except: continue for representative in fullResult: repID = representative["legislator"] if representative["vote"] == "Yea" or representative[ "vote"] == "Aye": vote = 1 elif representative["vote"] == "Nay" or representative[ "vote"] == "No": vote = 0 elif representative["vote"] == "Not Voting" or representative[ "vote"] == "Present": continue else: print(representative["vote"]) name = repID["#text"] + " " + repID["@state"] if not name in allReps: newRep = Representative(repID["#text"], repID["@state"], repID["@state"], "USA") allReps[name] = newRep if repID["@party"] == "R": party = "Republican" elif repID["@party"] == "D": party = "Democratic" elif repID["@party"] == "I": party = "Independent" repOb = allReps[name] repOb.addVote(voteOb, vote, party) return allReps
def generateGenBlock(self): vote = Vote("Easter", "Egg", "007") genBlock = Block(vote) return genBlock
def runWithRemoval(self, input): self.votes = [] key = [] for vote in input: self.votes.append(Vote(vote)) i = 0 for tie in input[0].list: for option in tie: key.append(i) i += 1 stv = STV() outcome = stv.run(self.votes) del (stv) output = [] if (isinstance(outcome[0], int)): self.removeFirst(outcome[0]) output.append(outcome[0]) for i in range(0, len(key)): if i > outcome[0]: key[i] -= 1 elif i == outcome[0]: key[i] = -1 else: for person in outcome[0]: self.removeFirst(person) for i in range(0, len(key)): if i > person: key[i] -= 1 elif i == person: key[i] = -1 output.append(outcome[0]) while (len(outcome) > 1): stv = STV() outcome = stv.run(self.votes) del (stv) if (isinstance(outcome[0], int)): self.removeFirst(outcome[0]) for i in range(0, len(key)): if (outcome[0] < key[i]): key[i] -= 1 elif (outcome[0] == key[i]): key[i] = -1 output.append(i) else: tie = [] for person in outcome[0]: for i in range(0, len(key)): if (person == key[i]): key[i] = -1 tie.append(i) for person in outcome[0]: for i in range(0, len(key)): if person < key[i]: key[i] -= 1 for person in outcome[0]: self.removeFirst(person) output.append(tie) for i in range(0, len(key)): if key[i] != -1: output.append(i) return output
def parseGameFromFile(game, file): while True: input_line = file.readline().strip().split(" ") print(input_line) ret = 0 if (input_line[0] == "end"): return 0 # Submit votes to game if (input_line[0] == "vote"): on = fixName(input_line[1]) yes_votes = [ fixName(x) for x in file.readline().strip().split(" ") ] if (re.match("all ", yes_votes[0])): yes_votes = [x for x in game.alive if x not in yes_votes] if (re.match("none", yes_votes[0])): yes_votes = [] ret = game.recordVote( Vote(on=on.lower(), voters=yes_votes, alive=game.alive, day=game.vote_weight)) # Submit confirmed info elif (input_line[0] == "died"): playerName = fixName(input_line[1]) ret = game.playerDied(playerName) if (len(input_line) > 2): if re.match("t.*", input_line[2]): game.confirmTown(playerName) elif re.match("m.*", input_line[2]): game.confirmMafia(playerName) elif (input_line[0] == "town"): ret = game.confirmTown(fixName(input_line[1])) elif (re.match("maf*", input_line[0])): ret = game.confirmMafia(fixName(input_line[1])) elif (input_line[0] == "formal"): if (len(input_line) < 3): print(f"Not enough names in formal declaration") return 1 ret = game.recordFormal( Formal(on=fixName(input_line[1]), first=fixName(input_line[2]), second=None if len(input_line) < 4 else fixName(input_line[3]))) # Set day/night cycle elif (re.match("[dn]\d+", input_line[0])): ret = game.setDay(input_line[0]) # Game is over. elif (re.match("reveal", input_line[0])): for i in range(1, len(input_line)): pass # Reveal mafia team print(ret) if ret == 1: return 1 return 0
def readBallotImage(self, contestRequest): inputFile = open("BallotImage11315.txt", "r") input = [] for line in inputFile: next = line.strip('\n') input.append(next) i = 0 candidateArrayKey = [] candidateCount = 0 output = [] for j in range(0, 100): candidateArrayKey.append(-1) while (i < len(input)): # if i % 30000 == 0: # print(i) firstPick = input[i] secondPick = input[i + 1] thirdPick = input[i + 2] # print(firstPick) # print(secondPick) # print(thirdPick) contest = int(firstPick[0:7]) voter = int(firstPick[7:16]) precinct = int(firstPick[26:33]) if contest != contestRequest: i += 3 continue firstRank = int(firstPick[33:36]) firstCand = int(firstPick[36:43]) firstOver = int(firstPick[43]) firstUnder = int(firstPick[44]) secondRank = int(secondPick[33:36]) secondCand = int(secondPick[36:43]) secondOver = int(secondPick[43]) secondUnder = int(secondPick[44]) thirdRank = int(thirdPick[33:36]) thirdCand = int(thirdPick[36:43]) thirdOver = int(thirdPick[43]) thirdUnder = int(thirdPick[44]) if firstOver == 1 or secondOver == 1 or thirdOver == 1: i += 3 continue vote = [] placedInVote = [] for j in range(0, candidateCount): placedInVote.append(False) if firstUnder != 1: if candidateArrayKey[firstCand] == -1: candidateArrayKey[firstCand] = candidateCount placedInVote.append(False) for prevVote in output: prevVote.getList()[len(prevVote.getList()) - 1].append(candidateCount) candidateCount += 1 if not placedInVote[candidateArrayKey[firstCand]]: vote.append([candidateArrayKey[firstCand]]) placedInVote[candidateArrayKey[firstCand]] = True if secondUnder != 1: if candidateArrayKey[secondCand] == -1: candidateArrayKey[secondCand] = candidateCount placedInVote.append(False) for prevVote in output: prevVote.getList()[len(prevVote.getList()) - 1].append(candidateCount) candidateCount += 1 if not placedInVote[candidateArrayKey[secondCand]]: vote.append([candidateArrayKey[secondCand]]) placedInVote[candidateArrayKey[secondCand]] = True if thirdUnder != 1: if candidateArrayKey[thirdCand] == -1: candidateArrayKey[thirdCand] = candidateCount placedInVote.append(False) for prevVote in output: prevVote.getList()[len(prevVote.getList()) - 1].append(candidateCount) candidateCount += 1 if not placedInVote[candidateArrayKey[thirdCand]]: vote.append([candidateArrayKey[thirdCand]]) placedInVote[candidateArrayKey[thirdCand]] = True end = [] j = 0 for placed in placedInVote: if not placed: end.append(j) j += 1 vote.append(end) output.append(Vote(vote)) i += 3 for vote in output: if len(vote.getList()[len(vote.getList()) - 1]) == 0: pop(vote.getList()[len(vote.getList()) - 1]) print(candidateArrayKey) return output
print( "3) Edit Post\n4) Give Badge\n5) Add Tag\n6) Exit" ) choice = input( "Please select which action to take: ") #reply to post if choice == '1': terminal.clear() PostScreen(terminal, uid).printAnswerScreen(post[4]) #upvote post. Checks to see if user has voted on the post before adding vote #this simplifies error handling by not allowing errors elif choice == '2': v = Vote(terminal.getDBName()) if v.check_vote(post[4], uid) == False: v.vote(post[4], uid) input( "Vote placed. Press enter to continue:" ) else: input( "You have already voted on this post. Press enter to continue:" ) #TODO: edits posts (needs fix) elif choice == '3': newPost = PostEditScreen(terminal, post).printScreen() if newPost is not None: