Exemplo n.º 1
0
def get_top_words(wc, train_sample_size, top_num = 10):
	top_words = {}
	for word in wc:
		if not word in stopwords.words():
			for decade in wc[word]:
				p = P2.p_x_given_y(wc, word, decade, train_sample_size)
				p_min = 1

				for n_decade in wc[word]:
					if not n_decade == decade:
						p_min = min(P2.p_x_given_y(wc, word, n_decade, train_sample_size), p_min)

				ratio = p/p_min
				# ratio = wc[word][decade]/min(wc[word].values())

				if decade in top_words:
					w = top_words[decade]
					if len(w) < top_num:
						top_words[decade][word] = ratio
					else:
						mw = min(w, key=w.get)
						if ratio > w[mw]:
							del top_words[decade][mw]
							top_words[decade][word] = ratio
				else:
					top_words[decade] = {}
					top_words[decade][word] = wc[word][decade]
	return top_words
Exemplo n.º 2
0
def main():
    print(
        "1. View total votes in the U.S. for every election year from 2000 to 2016."
    )
    print(
        "2. Compares the number of votes and percentages for Republicans and Democrats for any state from 2000-2016"
    )
    print(
        "3. View the top 5 Republican states in either the 2012 or 2016 elections"
    )
    print(
        "4. View the top 5 Democrat states in either the 2012 or 2016 elections"
    )
    print("5. View Florida's Republican votes from 1976-2016")
    print("6. View Florida's Democrat votes from 1976-2016")
    print(
        "7. View a color-coded map of the 2016 U.S. Presidential Election results"
    )
    print("8. View third party votes in the U.S. from 1976-2016")

    choice = int(input("Choose one option (ex: 1) "))

    if choice == 1:
        print(P1.total_votes())
        P1.total_votes_map()
    elif choice == 2:
        state_input = input("Type in a state (ex: District of Columbia) ")
        print(P2.compare_votes(state_input))
        P2.compare_votes_map(state_input)
    elif choice == 3:
        year = int(
            input("Choose an election year. Type in either 2012 or 2016: "))
        if year == 2012:
            print(P3.rep_states2012())
            P3.rep_states_2012_plot()
        elif year == 2016:
            print(P3.rep_states2016())
            P3.rep_states_2016_plot()
    elif choice == 4:
        year = int(
            input("Choose an election year. Type in either 2012 or 2016: "))
        if year == 2012:
            print(P3.dem_states2012())
            P3.dem_states_2012_plot()
        elif year == 2016:
            print(P3.dem_states2016())
            P3.dem_states_2016_plot()
    elif choice == 5:
        print(P4.fl_repvotes())
        P4.florida_rep_votes_plot()
    elif choice == 6:
        print(P4.fl_demvotes())
        P4.florida_dem_votes_plot()
    elif choice == 7:
        print(P6.us_map_2016())
    elif choice == 8:
        print(P7.total_non_rd())
        P7.total_non_rd_map()
    else:
        main()
Exemplo n.º 3
0
def main():
    #water jug problem
    print("Water jug problem:")
    water_jug = P1.WaterJug((0, 0), (2, 0))
    t1 = time.time()
    print(breadth_first_tree_search(water_jug).solution())
    t2 = time.time()
    exe_time = t2 - t1
    print("Realizat in : %.8f secunde folosind breadth_first_tree_search" %
          exe_time)
    print("Rezultat: ", breadth_first_tree_search(water_jug).state)

    #15 puzzle problem
    print("\n\n15 Puzzle problem:")

    puzzle_15 = P2.Puzzle15(
        (5, 1, 7, 3, 9, 2, 11, 4, 13, 6, 15, 8, 0, 10, 14, 12),
        (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0))
    puzzle_15_mis_dist = P2.Puzzle15MisDist(
        (5, 1, 7, 3, 9, 2, 11, 4, 13, 6, 15, 8, 0, 10, 14, 12),
        (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0))
    puzzle_15_mis_col_row = P2.Puzzle15MisColRow(
        (5, 1, 7, 3, 9, 2, 11, 4, 13, 6, 15, 8, 0, 10, 14, 12),
        (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0))

    print("\nInitial : ", puzzle_15_mis_dist.initial)
    t1 = time.time()
    print(astar_search(puzzle_15_mis_dist).solution())
    t2 = time.time()
    exe_time = t2 - t1
    print(
        "Realizat in : %.8f secunde folosind A* cu heuristica care calculeaza suma elementelor misplaced si distanta dintre acestea"
        % exe_time)
    print("Rezultat : ", astar_search(puzzle_15_mis_dist).state)

    print("\nInitial : ", puzzle_15_mis_col_row.initial)
    t1 = time.time()
    print(astar_search(puzzle_15_mis_col_row).solution())
    t2 = time.time()
    exe_time = t2 - t1
    print(
        "Realizat in : %.8f secunde folosind A* cu heuristica care calculeaza suma elementelor misplaced de pe fiecare coloana si linie"
        % exe_time)
    print("Rezultat : ", astar_search(puzzle_15_mis_col_row).state)

    print("\nInitial : ", puzzle_15.initial)
    t1 = time.time()
    print(astar_search(puzzle_15).solution())
    t2 = time.time()
    exe_time = t2 - t1
    print("Realizat in : %.8f secunde folosind A* cu heuristica initiala" %
          exe_time)
    print("Rezultat : ", astar_search(puzzle_15).state)
Exemplo n.º 4
0
def checkers():
    t, wn, board = setupBoard()
    gameName = input(
        "Press enter to start a new game, otherwise, type in the name of an old game => "
    )
    if gameName != "":
        currentPlayer, opposingPlayer, currentPlayerTokens, opposingPlayerTokens, forwardRowInc = oldGame(
            t, wn, board, gameName)
    else:
        currentPlayer, opposingPlayer, currentPlayerTokens, opposingPlayerTokens, forwardRowInc = newGame(
            t, wn, board)
    if currentPlayer == "red":
        move = P2.getValidPlayerAction(currentPlayer, currentPlayerTokens,
                                       opposingPlayerTokens, board,
                                       forwardRowInc)
    else:
        move = P1.getValidPlayerAction(currentPlayer, currentPlayerTokens,
                                       opposingPlayerTokens, board,
                                       forwardRowInc)
    while move != "QUIT" and not win(board)[0]:
        while len(move) >= 5:
            move, fromRow, fromCol, toRow, toCol = parseValidMove(move)
            if board[fromRow][fromCol] in ['R', 'B']:
                isKing = True
            else:
                isKing = False
            removeChecker(t, wn, fromRow, fromCol, board)
            drawChecker(t, wn, toRow, toCol, currentPlayer, "gray", board,
                        isKing)
            if abs(fromRow - toRow) > 1:  #Jump is occuring
                removeChecker(t, wn, (fromRow + toRow) // 2,
                              (fromCol + toCol) // 2, board)
        currentPlayer, currentPlayerTokens, opposingPlayer, opposingPlayerTokens, forwardRowInc = switchPlayer(
            currentPlayer)
        if currentPlayer == "red":
            move = P2.getValidPlayerAction(currentPlayer, currentPlayerTokens,
                                           opposingPlayerTokens, board,
                                           forwardRowInc)
        else:
            move = P1.getValidPlayerAction(currentPlayer, currentPlayerTokens,
                                           opposingPlayerTokens, board,
                                           forwardRowInc)
    if move == "QUIT":
        saveGame(board, currentPlayer)
Exemplo n.º 5
0
def checkers(CB, bob, PlayerB, PlayerR, Bwin, Rwin, totalPlayed):
    #junk=input("Hey hey hey")
    imp.reload(P1)
    imp.reload(P2)
    player = readCheckerFile(CB)
    print(player, "goes first")
    SIZE = 60
    if VISIBLE:
        fillCheckerBoard(bob, SIZE, CB)
        labelGameStats(bob, SIZE, PlayerB, PlayerR, Bwin, Rwin, totalPlayed)
    move = ''
    numChecks = [0, 0, 0]
    while move != 'exit' and not win(CB, numChecks)[0]:
        possibles = getPossibles(CB, player)
        if player == "red":
            oppPlayer = "black"
            move = P2.automatedMove(CB, player)
        else:
            oppPlayer = "red"
            move = P1.automatedMove(CB, player)
        countBadMoves = 1
        #Until a valid move or exceeds allowed number of bad move trys
        while ((move != "exit") and
               (not (validMove(CB, move, player)))) and (countBadMoves != 3):
            countBadMoves += 1
            if player == "red":
                oppPlayer = "black"
                move = P2.automatedMove(CB, player)
            else:
                oppPlayer = "red"
                move = P1.automatedMove(CB, player)
        #terminate due to bad moves or exit entered (and save state)
        if countBadMoves == 3 or move == "exit":
            if countBadMoves == 3:
                print("Game terminated because player ", player,
                      " refused to make a valid move!")
            else:
                writeGameState(CB, player)
            return oppPlayer
        #All good - make move!
        makeMove(bob, CB, move, player, SIZE, possibles)
        #showBoard(CB)
        player = switchPlayers(player)
    return win(CB, numChecks)[1]
Exemplo n.º 6
0
 def get(self):
     # get should remove and return the root element of the heap (heappop)
     # raise an IndexError if called on an empty priority queue
     if len(self) > 0:
         minheap = P2.MinHeap(self.elements)
         min_elem = minheap.heappop()
         return (min_elem)
     else:
         raise IndexError(
             'Queue is empty, cannot perform get on an empty queue.')
Exemplo n.º 7
0
 def put(self, val):
     # put should push the element to the heap (heappush)
     # raise an IndexError if called after max_size is reached. Nothing should be returned
     if len(self) < self.max_size:
         minheap = P2.MinHeap(self.elements)
         minheap.heappush(val)
     else:
         raise IndexError(
             'Queue is already at maximum length, cannot put another element.'
         )
Exemplo n.º 8
0
 def peek(self):
     # peek should return the smallest value in the queue.
     # raise an IndexError if called on an empty priority queue
     if len(self) > 0:
         minheap = P2.MinHeap(self.elements)
         min_elem = minheap.heappop()
         minheap.heappush(min_elem)
         return (min_elem)
     else:
         raise IndexError(
             'Queue is empty, cannot perform peek from an empty queue.')
Exemplo n.º 9
0
class main:
    rows = 8
    columns = 7
    planeloc = [[0 for x in range(columns)] for y in range(rows)]
    planeloc[0][0] = 'X'
    planeloc[0][2] = 'Y'
    planeloc[3][6] = 'Z'
    bufferA = [[0 for x in range(columns)] for y in range(rows)]
    bufferA[0][0] = 'X'
    bufferA[0][2] = 'Y'
    bufferA[3][6] = 'Z'

    bufferB = [[0 for x in range(columns)] for y in range(rows)]
    bufferC = [[0 for x in range(3)] for y in range(3)]
    bufferD = [[0 for x in range(3)] for y in range(3)]
    bufferC[0][0] = 'X'
    bufferC[0][1] = 'Y'
    bufferC[0][2] = 'Z'
    bufferD[0][0] = 'X'
    bufferD[0][1] = 'Y'
    bufferD[0][2] = 'Z'
    # print (bufferA)

    plane_X = planeX.planeX(0, 0)
    plane_Y = planeY.planeY(0, 2)
    plane_Z = planeZ.planeZ(3, 6)
    p1 = P1.P1(0, plane_X, plane_Y, plane_Z, bufferA, bufferB)
    p2 = P2.P2(0, bufferC, bufferD)
    p3 = P3.P3(bufferC, bufferD)

    for i in range(0, 20):
        print("")
        #  print("")
        #  print("")
        #  print("TIME ", i+1)
        #   print("")

        time.sleep(1)
        #Process 1 work
        p1.proc1(i, plane_X, plane_Y, plane_Z, bufferA, bufferB)

        #Process 2 Work
        if i % 2 is 0:
            p2.proc2AC(i, bufferA, bufferC)
        else:
            p2.proc2BD(i, bufferB, bufferD)

        #Process 3 Work
        if i % 2 is 0:
            p3.checkC(i, bufferC)
        else:
            p3.checkD(i, bufferD)
Exemplo n.º 10
0
def main():
    # ----------------------------------- Water Jug Problem -------------------------------------- #

    water_jug_prob = P1.WaterJugProblem((0, 0), (2, 0), (4, 3))

    t0 = time.time()
    src1 = search.breadth_first_tree_search(water_jug_prob)

    t1 = time.time()
    src2 = search.astar_search(water_jug_prob)

    dt2 = time.time() - t1
    dt1 = t1 - t0

    print(src1.solution())
    print(src2.solution())

    print(
        "Uninformed search time: {0:.4f} seconds\nInformed search time: {1:.4f} seconds"
        .format(dt1, dt2))

    # -------------------------------------------------------------------------------------------- #

    # ----------------------------------- N-Puzzle Problem: -------------------------------------- #

    puzzle_prob = P2.NPuzzleProblem((5, 1, 2, 4, 7, 6, 3, 8, 9, 14, 10, 12, 13, 0, 11, 15), \
        (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0), 4)

    t0 = time.time()
    src1 = search.astar_search(puzzle_prob, puzzle_prob.h1)

    t1 = time.time()
    src2 = search.astar_search(puzzle_prob, puzzle_prob.h2)

    dt2 = time.time() - t1
    dt1 = t1 - t0

    print(src1.solution())
    print(src2.solution())

    print(
        "Heuristic 1 search time: {0:.4f} seconds\nHeuristic 2 search time: {1:.4f} seconds"
        .format(dt1, dt2))
Exemplo n.º 11
0
def main():
    polinomios = []
    while True:
        print("a.	Agregar términos a un polinomio")
        print("b.	Imprimir el polinomio generado hasta el momento")
        print("c.	Imprimir la integral del polinomio generado hasta el momento")
        print("d.	Evaluar la expresión para un valor específico de x")
        print("e.	Salir del menú")
        opcion = input("Digite opcion: ").lower().strip()
        if opcion == 'a':
            a = float(input("Digite a: "))
            n = float(input("Digite n: "))
            t = (a, n)
            polinomios.append(t)
        elif opcion == 'b':
            print(P3.conv_str(polinomios))
        elif opcion == 'c':
            print(P3.conv_str(P2.integra_polinomio(polinomios)))
        elif opcion == 'd':
            x = float(input("Digite x: "))
            print(evalua_pol(polinomios, x))
        elif opcion == 'e':
            break
Exemplo n.º 12
0
def mandelbrot_wrapper(row, col):
    x = col/(num_pixels/4.) - 2.
    y = row/(num_pixels/4.) - 2.

    return ((row, col), P2.mandelbrot(x, y))

mandelbrot_rdd = indices.map(lambda a: mandelbrot_wrapper(*a))

# Now collect the data & plot
mandelbrot_result = mandelbrot_rdd.collect()

plt.grid(False)
# I slightly redefined the draw image function as the original
# implementation annoyed me...I did not want to collect in a draw function!
P2.draw_image(data=mandelbrot_result)

plt.savefig('P2a_mandelbrot.png', dpi=200, bbox_inches='tight')

plt.clf()

# Now create the histogram...I recognize that mandelbrot is computed twice
# but it is for my sanity
summed_rdd = P2.sum_values_for_partitions(mandelbrot_rdd)
summed_result = summed_rdd.collect()

plt.hist(summed_result, bins=np.logspace(3, 8, 20))
sns.rugplot(summed_result, color='red')
plt.gca().set_xscale('log')
plt.xlabel('Total Number of Iterations on Partition')
plt.ylabel('Partition Count')
Exemplo n.º 13
0
def mandelbrot_wrapper(row, col):
    x = col / (num_pixels / 4.) - 2.
    y = row / (num_pixels / 4.) - 2.

    return ((row, col), P2.mandelbrot(x, y))
Exemplo n.º 14
0
def mandelbrot_wrapper(row, col):
    x = col / (num_pixels / 4.) - 2.
    y = row / (num_pixels / 4.) - 2.

    return ((row, col), P2.mandelbrot(x, y))


mandelbrot_rdd = indices.map(lambda a: mandelbrot_wrapper(*a))

# Now collect the data & plot
mandelbrot_result = mandelbrot_rdd.collect()

plt.grid(False)
# I slightly redefined the draw image function as the original
# implementation annoyed me...I did not want to collect in a draw function!
P2.draw_image(data=mandelbrot_result)

plt.savefig('P2a_mandelbrot.png', dpi=200, bbox_inches='tight')

plt.clf()

# Now create the histogram...I recognize that mandelbrot is computed twice
# but it is for my sanity
summed_rdd = P2.sum_values_for_partitions(mandelbrot_rdd)
summed_result = summed_rdd.collect()

plt.hist(summed_result, bins=np.logspace(3, 8, 20))
sns.rugplot(summed_result, color='red')
plt.gca().set_xscale('log')
plt.xlabel('Total Number of Iterations on Partition')
plt.ylabel('Partition Count')
Exemplo n.º 15
0
 def Openclick2(self):
     P2.p2()
Exemplo n.º 16
0
    def run(self):
        """
        @summary: The main function of this app, the driver for the whole game
        
        """
        #setup our stat counters
        stat1 = {}
        stat2 = {}
        stats = [stat1, stat2]

        #load bot 1
        ticks = time.time()
        p1 = P1()
        elapsed = time.time() - ticks
        stats[0]['Bot Loading Time'] = elapsed
        stats[0]['Number of Wins'] = 0
        stats[0]['Game Fails'] = 0
        stats[0]['Number of Draws'] = 0
        stats[0]['Player'] = p1
        stats[0]['Average Move Time'] = None
        stats[0]['Best Move Time'] = None
        stats[0]['Worst Move Time'] = None

        #load bot 2
        ticks = time.time()
        p2 = P2()
        elapsed = time.time() - ticks
        stats[1]['Bot Loading Time'] = elapsed
        stats[1]['Number of Wins'] = 0
        stats[1]['Game Fails'] = 0
        stats[1]['Number of Draws'] = 0
        stats[1]['Player'] = p2
        stats[1]['Average Move Time'] = None
        stats[1]['Best Move Time'] = None
        stats[1]['Worst Move Time'] = None

        #main runs start here
        thisRound = 1
        timeToRunInWarnings = 0

        totalGameTime = time.time()
        for i in range(self.numberOfGames):
            #check that the whole process isn't taking too long
            if time.time() - totalGameTime > self.startWarnings:
                if timeToRunInWarnings == 0:
                    timeToRunInWarnings = i
                if i % timeToRunInWarnings == 0:
                    secs = int((self.numberOfGames - i) / float(
                        (timeToRunInWarnings / float(self.startWarnings))))
                    hours, minutes, seconds = self.convertTime(secs)
                    print "Taking a while.... %i games have been calculated so far" % (
                        i)
                    if secs > self.maxGameTime:
                        ch, cm, cs = self.convertTime(self.maxGameTime -
                                                      (time.time() -
                                                       totalGameTime))
                        print "At this rate it would take a further %ih:%im:%is to finish. We will be cut off in %ih:%im:%is\n" % (
                            hours, minutes, seconds, ch, cm, cs)
                    else:
                        print "At this rate it will take a further %ih:%im:%is to finish\n" % (
                            hours, minutes, seconds)

            if time.time() - totalGameTime > self.maxGameTime:
                print "Too long, game %i is the last to be calculated\n" % (i)
                break

            #setup the board and player markers
            p1Map = thisRound
            board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

            #switch the round for the next game
            thisRound = self.switchPlayer(thisRound)

            #setup this games variables
            running = True
            winner = 0
            failed = False

            #randomly place the first piece
            board[randint(0, 2)][randint(0, 2)] = p1Map

            #switch player
            p1Map = self.switchPlayer(p1Map)

            while (running):
                #if there are no more moves, crash out
                if self.boardFull(board):
                    running = False
                else:
                    #time the players move
                    ticks = time.time()
                    move = stats[p1Map - 1]['Player'].move(board)
                    elapsed = time.time() - ticks

                    #save the players timings
                    if not stats[p1Map - 1]['Average Move Time']:
                        stats[p1Map - 1]['Average Move Time'] = elapsed
                    else:
                        stats[p1Map - 1]['Average Move Time'] = (
                            stats[p1Map - 1]['Average Move Time'] +
                            elapsed) / float(2)

                    #Best move Time
                    if not stats[p1Map - 1]['Best Move Time']:
                        stats[p1Map - 1]['Best Move Time'] = elapsed
                    elif stats[p1Map - 1]['Best Move Time'] > elapsed:
                        stats[p1Map - 1]['Best Move Time'] = elapsed

                    #Worst move Time
                    if not stats[p1Map - 1]['Worst Move Time']:
                        stats[p1Map - 1]['Worst Move Time'] = elapsed
                    elif stats[p1Map - 1]['Worst Move Time'] < elapsed:
                        stats[p1Map - 1]['Worst Move Time'] = elapsed

                    #see if the player took too long
                    if elapsed > self.gameFailThreshold:
                        stats[p1Map - 1]['Game Fails'] += 1
                        stats[self.switchPlayer(p1Map) -
                              1]['Number of Wins'] += 1
                        running = False
                        failed = True

                    #check the move and if its valid, enter it into the board, otherwise chalk up a fail to the player
                    if self.validateMove(move, board):
                        board[move[1]][move[0]] = p1Map
                    else:
                        #game over player forfeits
                        stats[p1Map - 1]['Game Fails'] += 1
                        running = False

                    #check for winner
                    winner = self.findWinner(board)
                    if not winner == 0:
                        #someone won!
                        running = False

                    #switch player for next move
                    p1Map = self.switchPlayer(p1Map)

            #game over, add up stats
            if not winner == 0:
                stats[winner - 1]['Number of Wins'] += 1
            elif failed:
                failed = False
            else:
                for stat in stats:
                    stat['Number of Draws'] += 1

        #print the game results
        self.printStatsToConsole(stats)
Exemplo n.º 17
0
 def setZero():
     OpenCaseV1.caseId = 0
     test()
     P2.HOAX()
     menuV1.Homepage.set_Opencase_True(self)
Exemplo n.º 18
0
 def test_a(self):
     polinomio = [(1, 1), (8, 4), (8.8, 3)]
     resultado = [(0.5, 2), (1.6, 5), (2.2, 4)]
     self.assertEqual(resultado, P2.integra_polinomio(polinomio))
Exemplo n.º 19
0
class main:
    rows = 8
    columns = 7
    bufferA = [[0 for x in range(7)] for y in range(8)]

    # Coordinates for X Y Z randomly generated
    x_xCoor = random.randint(0, rows - 1)
    x_yCoor = random.randint(0, columns - 1)
    y_xCoor = random.randint(0, rows - 1)
    y_yCoor = random.randint(0, columns - 1)
    z_xCoor = random.randint(0, rows - 1)
    z_yCoor = random.randint(0, columns - 1)
    # generate coordinates again if same coordinates
    if ((x_xCoor == y_xCoor or x_xCoor == z_xCoor or y_xCoor == z_xCoor) and
        (x_yCoor == y_yCoor or x_yCoor == z_yCoor or y_xCoor == z_xCoor)):
        x_xCoor = random.randint(0, rows - 1)
        x_yCoor = random.randint(0, columns - 1)
        y_xCoor = random.randint(0, rows - 1)
        y_yCoor = random.randint(0, columns - 1)
        z_xCoor = random.randint(0, rows - 1)
        z_yCoor = random.randint(0, columns - 1)

    bufferA[x_xCoor][x_yCoor] = 'X'
    bufferA[y_xCoor][y_yCoor] = 'Y'
    bufferA[z_xCoor][z_yCoor] = 'Z'

    bufferB = [[0 for x in range(7)] for y in range(8)]
    bufferC = [[0 for x in range(3)] for y in range(3)]
    bufferD = [[0 for x in range(3)] for y in range(3)]
    bufferC[0][0] = 'X'
    bufferC[0][1] = 'Y'
    bufferC[0][2] = 'Z'
    bufferD[0][0] = 'X'
    bufferD[0][1] = 'Y'
    bufferD[0][2] = 'Z'
    time_interval = 1
    iterations = 20
    semA = threading.Semaphore()
    semB = threading.Semaphore()
    semC = threading.Semaphore()
    semD = threading.Semaphore()

    plane_X = planeX.planeX(x_xCoor, x_yCoor)
    plane_Y = planeY.planeY(y_xCoor, y_yCoor)
    plane_Z = planeZ.planeZ(z_xCoor, z_yCoor)

    p1 = P1.P1(0, plane_X, plane_Y, plane_Z, bufferA, bufferB, semA, semB)
    p2 = P2.P2(0, bufferC, bufferD, semA, semB, semC, semD)
    p3 = P3.P3(bufferC, bufferD, plane_X, plane_Y, plane_Z, z_xCoor, y_yCoor)

    #thread class declarations
    i = 0
    t1 = threading.Thread(target=p1.proc1,
                          args=(i, plane_X, plane_Y, plane_Z, bufferA, bufferB,
                                semA, semB, semC, semD, time_interval,
                                iterations))
    t2 = threading.Thread(target=p2.proc,
                          args=(i, bufferA, bufferB, bufferC, bufferD, semA,
                                semB, semC, semD, time_interval, iterations))
    t3 = threading.Thread(target=p3.check,
                          args=(i, bufferC, bufferD, semC, semD, plane_X,
                                plane_Y, plane_Z, semA, semB, time_interval,
                                iterations))

    t1.start()

    t2.start()

    t3.start()
Exemplo n.º 20
0
def mandelbrot_wrapper(row, col):
    x = col/(num_pixels/4.) - 2.
    y = row/(num_pixels/4.) - 2.

    return ((row, col), P2.mandelbrot(x, y))
Exemplo n.º 21
0
    def run(self):
        menu = 0
        running = True
        screen = self.screen
        hvbOpponent = None
        opponents = {}
        p1 = P1()
        p2 = P2()
        opponents[p1.name] = p1
        opponents[p2.name] = p2
        scores = [0, 0]
        # QUIT           none
        # ACTIVEEVENT      gain, state
        # KEYDOWN           unicode, key, mod
        # KEYUP           key, mod
        # MOUSEMOTION      pos, rel, buttons
        # MOUSEBUTTONUP    pos, button
        # MOUSEBUTTONDOWN  pos, button
        # JOYAXISMOTION    joy, axis, value
        # JOYBALLMOTION    joy, ball, rel
        # JOYHATMOTION     joy, hat, value
        # JOYBUTTONUP      joy, button
        # JOYBUTTONDOWN    joy, button
        # VIDEORESIZE      size, w, h
        # VIDEOEXPOSE      none
        # USEREVENT        code

        while running:
            menuActive = True
            if menu == 0:
                #draw the main menu
                screen.fill((0, 0, 0))
                rects = {}
                rects['heading'] = pygame.Rect(120, 120, 560, 140)
                rects['hvh'] = pygame.Rect(120, 280, 560, 120)
                rects['hvb'] = pygame.Rect(120, 420, 560, 120)
                rects['bvb'] = pygame.Rect(120, 560, 560, 120)
                rects['quit'] = pygame.Rect(500, 720, 280, 60)

                screen.fill((0, 0, 255), (100, 100, 600, 600))
                screen.fill((127, 127, 127), rects['heading'])
                screen.fill((127, 127, 127), rects['hvh'])
                screen.fill((127, 127, 127), rects['hvb'])
                screen.fill((127, 127, 127), rects['bvb'])
                screen.fill((0, 0, 255),
                            (rects['quit'][0] - 3, rects['quit'][1] - 3,
                             rects['quit'][2] + 6, rects['quit'][3] + 6))
                screen.fill((127, 127, 127), rects['quit'])

                self.write(rects['quit'], 'quit', (200, 200, 200), 75)
                self.write(rects['heading'], "Game Mode", (255, 255, 0), 100)
                self.write(rects['hvh'], "Human Vs Human", (255, 0, 0), 65)
                self.write(rects['hvb'], "Human Vs Bot", (255, 0, 0), 65)
                self.write(rects['bvb'], "Bot Vs Bot", (255, 0, 0), 65)

                pygame.display.flip()

                selected = False
                while menuActive:
                    #assess mouse clicks n shit
                    for event in pygame.event.get():
                        if event.type == pygame.QUIT:
                            running = False
                            menu = 0
                            menuActive = False

                        #capture mouse clicks
                        if event.type == pygame.MOUSEBUTTONDOWN:
                            for key in rects.keys():
                                if rects[key].collidepoint(event.pos):
                                    selected = key

                        #capture key strokes
                        if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                            running = False
                            menuActive = False
                            menu = 0

                    #logic for menu from the button clicks
                    if selected:
                        if not selected == "heading":
                            menuActive = False
                            if selected == "hvh":
                                menu = 1
                            if selected == "hvb":
                                menu = 2
                            if selected == "bvb":
                                menu = 4
                            if selected == "quit":
                                menu = 0
                                running = False
                                menuActive = False

            menuActive = True
            if menu == 1:
                scores = [0, 0]
                #draw the human vs human menu and play accordingly
                #draw the main screen
                board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
                screen.fill((0, 0, 0))
                rects = {}
                rects['1'] = pygame.Rect(103, 501, 196, 196)
                rects['2'] = pygame.Rect(302, 501, 196, 196)
                rects['3'] = pygame.Rect(501, 501, 196, 196)
                rects['4'] = pygame.Rect(103, 302, 196, 196)
                rects['5'] = pygame.Rect(302, 302, 196, 196)
                rects['6'] = pygame.Rect(501, 302, 196, 196)
                rects['7'] = pygame.Rect(103, 103, 196, 196)
                rects['8'] = pygame.Rect(302, 103, 196, 196)
                rects['9'] = pygame.Rect(501, 103, 196, 196)
                rects['quit'] = pygame.Rect(500, 720, 280, 60)

                screen.fill((0, 0, 255), (100, 100, 600, 600))
                for key in rects.keys():
                    if key == "quit":
                        screen.fill((0, 0, 255),
                                    (rects[key][0] - 3, rects[key][1] - 3,
                                     rects[key][2] + 6, rects[key][3] + 6))
                        screen.fill((127, 127, 127), rects[key])
                        self.write(rects[key], key, (200, 200, 200), 75)
                    else:
                        screen.fill((127, 127, 127), rects[key])
                        self.write(rects[key], key, (200, 200, 200), 100)

                #draw the player names
                self.drawPlayers(0)
                self.drawScores(scores)

                pygame.display.flip()
                player = 1
                self.drawPlayers(player)
                winner = 0
                selected = False
                while menuActive:
                    #assess mouse clicks n shit
                    for event in pygame.event.get():

                        #quit events
                        if event.type == pygame.QUIT or (
                                event.type == pygame.KEYDOWN
                                and event.key == pygame.K_ESCAPE):
                            running = False
                            menu = 0
                            menuActive = False

                        #capture mouse clicks
                        if event.type == pygame.MOUSEBUTTONDOWN:
                            for key in rects.keys():
                                if rects[key].collidepoint(event.pos):
                                    selected = key

                        #capture key strokes
                        if event.type == pygame.KEYDOWN:
                            validKeys = '123456789'
                            if event.unicode in validKeys:
                                selected = event.unicode

                    #logic for menu from the button clicks
                    if selected:
                        if selected == "quit":
                            menuActive = False
                            menu = 0
                        else:
                            pos = self.convertIndexToPos(int(selected))
                            #print pos,selected,rects[selected]
                            if self.validateMove(pos, board):
                                board[pos[1]][pos[0]] = player
                                self.drawMove(selected, player, rects)
                                pygame.display.update(rects[selected])
                                if self.findWinner(board):
                                    winner = player
                                else:
                                    player = self.switchPlayer(player)
                                    if not self.boardFull(board):
                                        self.drawPlayers(player)
                            selected = False

                    if (not winner == 0) or self.boardFull(board):
                        if not winner == 0:
                            self.drawPlayers(winner + 2)
                            scores[winner - 1] += 1
                            self.drawScores(scores)
                        else:
                            #draw
                            self.drawPlayers(5)
                            winner = 1

                        #reset game
                        player = winner
                        screen.fill((0, 0, 255), (100, 100, 600, 600))
                        for key in rects.keys():
                            if key == "quit":
                                screen.fill(
                                    (0, 0, 255),
                                    (rects[key][0] - 3, rects[key][1] - 3,
                                     rects[key][2] + 6, rects[key][3] + 6))
                                screen.fill((127, 127, 127), rects[key])
                                self.write(rects[key], key, (200, 200, 200),
                                           75)
                            else:
                                screen.fill((127, 127, 127), rects[key])
                                self.write(rects[key], key, (200, 200, 200),
                                           100)
                        pygame.display.flip()
                        winner = 0
                        board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
                        self.drawPlayers(player)
                        selected = False

            menuActive = True
            if menu == 2:
                #draw the choose bot for human to play against menu
                #define the rects
                rects = {}
                cursor = 420
                for key in opponents.keys():
                    rects[key] = pygame.Rect(120, cursor, 560, 120)
                    cursor += 140

                #draw the elements
                screen.fill((0, 0, 0))
                self.write((100, 100, 600, 150), "Choose Your",
                           (255, 255, 255), 80)
                self.write((100, 250, 600, 150), "Opponent", (255, 255, 255),
                           80)
                screen.fill((0, 0, 255), (100, 400, 600, 300))
                for key in rects.keys():
                    screen.fill((120, 120, 120), rects[key])
                    self.write(rects[key], key, (255, 255, 255), 45)
                pygame.display.flip()
                selected = False
                #process user input
                while menuActive:
                    for event in pygame.event.get():

                        #quit events
                        if event.type == pygame.QUIT or (
                                event.type == pygame.KEYDOWN
                                and event.key == pygame.K_ESCAPE):
                            running = False
                            menu = 0
                            menuActive = False

                        #capture mouse clicks
                        if event.type == pygame.MOUSEBUTTONDOWN:
                            for key in rects.keys():
                                if rects[key].collidepoint(event.pos):
                                    selected = key

                    #logic for menu from the button clicks
                    if selected:
                        hvbOpponent = opponents[selected]
                        menuActive = False
                        menu = 3

            menuActive = True
            if menu == 3:
                scores = [0, 0]
                #draw the bot vs human play
                #draw the main screen
                board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
                screen.fill((0, 0, 0))
                rects = {}
                rects['1'] = pygame.Rect(103, 501, 196, 196)
                rects['2'] = pygame.Rect(302, 501, 196, 196)
                rects['3'] = pygame.Rect(501, 501, 196, 196)
                rects['4'] = pygame.Rect(103, 302, 196, 196)
                rects['5'] = pygame.Rect(302, 302, 196, 196)
                rects['6'] = pygame.Rect(501, 302, 196, 196)
                rects['7'] = pygame.Rect(103, 103, 196, 196)
                rects['8'] = pygame.Rect(302, 103, 196, 196)
                rects['9'] = pygame.Rect(501, 103, 196, 196)
                rects['quit'] = pygame.Rect(500, 720, 280, 60)

                screen.fill((0, 0, 255), (100, 100, 600, 600))
                for key in rects.keys():
                    if key == "quit":
                        screen.fill((0, 0, 255),
                                    (rects[key][0] - 3, rects[key][1] - 3,
                                     rects[key][2] + 6, rects[key][3] + 6))
                        screen.fill((127, 127, 127), rects[key])
                        self.write(rects[key], key, (200, 200, 200), 75)
                    else:
                        screen.fill((127, 127, 127), rects[key])
                        self.write(rects[key], key, (200, 200, 200), 100)

                #draw the player names
                self.drawPlayers(0, hvbOpponent.name)
                self.drawScores(scores)

                pygame.display.flip()
                player = 1
                self.drawPlayers(player, hvbOpponent.name)
                winner = 0
                selected = False

                while menuActive:
                    #assess mouse clicks n shit
                    for event in pygame.event.get():

                        #quit events
                        if event.type == pygame.QUIT or (
                                event.type == pygame.KEYDOWN
                                and event.key == pygame.K_ESCAPE):
                            running = False
                            menu = 0
                            menuActive = False

                        if player == 1:
                            #capture mouse clicks
                            if event.type == pygame.MOUSEBUTTONDOWN:
                                for key in rects.keys():
                                    if rects[key].collidepoint(event.pos):
                                        selected = key

                            #capture key strokes
                            if event.type == pygame.KEYDOWN:
                                validKeys = '123456789'
                                if event.unicode in validKeys:
                                    selected = event.unicode

                    #logic for menu from the button clicks
                    if player == 2:
                        selected = str(
                            self.pos2Selected(hvbOpponent.move(board)))
                    if selected:
                        if selected == "quit":
                            menuActive = False
                            menu = 0
                        else:
                            pos = self.convertIndexToPos(int(selected))
                            #print pos,selected,rects[selected]
                            if self.validateMove(pos, board):
                                board[pos[1]][pos[0]] = player
                                self.drawMove(selected, player, rects)
                                pygame.display.update(rects[selected])
                                if self.findWinner(board):
                                    winner = player
                                else:
                                    player = self.switchPlayer(player)
                                    if not self.boardFull(board):
                                        self.drawPlayers(
                                            player, hvbOpponent.name)
                            selected = False

                    if (not winner == 0) or self.boardFull(board):
                        if not winner == 0:
                            self.drawPlayers(winner + 2, hvbOpponent.name)
                            scores[winner - 1] += 1
                            self.drawScores(scores)
                        else:
                            #draw
                            self.drawPlayers(5, hvbOpponent.name)
                            winner = 1

                        #reset game
                        player = winner
                        screen.fill((0, 0, 255), (100, 100, 600, 600))
                        for key in rects.keys():
                            if key == "quit":
                                screen.fill(
                                    (0, 0, 255),
                                    (rects[key][0] - 3, rects[key][1] - 3,
                                     rects[key][2] + 6, rects[key][3] + 6))
                                screen.fill((127, 127, 127), rects[key])
                                self.write(rects[key], key, (200, 200, 200),
                                           75)
                            else:
                                screen.fill((127, 127, 127), rects[key])
                                self.write(rects[key], key, (200, 200, 200),
                                           100)
                        pygame.display.flip()
                        winner = 0
                        board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
                        self.drawPlayers(player, hvbOpponent.name)
                        selected = False

            menuActive = True
            if menu == 4:
                scores = [0, 0]
                #draw the bot vs bot game
                #draw the main screen
                board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
                screen.fill((0, 0, 0))
                rects = {}
                rects['1'] = pygame.Rect(103, 501, 196, 196)
                rects['2'] = pygame.Rect(302, 501, 196, 196)
                rects['3'] = pygame.Rect(501, 501, 196, 196)
                rects['4'] = pygame.Rect(103, 302, 196, 196)
                rects['5'] = pygame.Rect(302, 302, 196, 196)
                rects['6'] = pygame.Rect(501, 302, 196, 196)
                rects['7'] = pygame.Rect(103, 103, 196, 196)
                rects['8'] = pygame.Rect(302, 103, 196, 196)
                rects['9'] = pygame.Rect(501, 103, 196, 196)
                rects['quit'] = pygame.Rect(500, 720, 280, 60)

                screen.fill((0, 0, 255), (100, 100, 600, 600))
                for key in rects.keys():
                    if key == "quit":
                        screen.fill((0, 0, 255),
                                    (rects[key][0] - 3, rects[key][1] - 3,
                                     rects[key][2] + 6, rects[key][3] + 6))
                        screen.fill((127, 127, 127), rects[key])
                        self.write(rects[key], key, (200, 200, 200), 75)
                    else:
                        screen.fill((127, 127, 127), rects[key])
                        self.write(rects[key], key, (200, 200, 200), 100)

                #draw the player names
                opponentNames = []
                for key in opponents.keys():
                    opponentNames.append(key)
                #self.drawPlayers(0,hvbOpponent.name)
                self.drawBots(0, opponentNames)
                self.drawScores(scores)

                pygame.display.flip()
                player = 1
                self.drawBots(player, opponentNames, 1)
                winner = 0
                selected = False
                move = 0

                while menuActive:
                    #assess mouse clicks n shit
                    for event in pygame.event.get():

                        #quit events
                        if event.type == pygame.QUIT or (
                                event.type == pygame.KEYDOWN
                                and event.key == pygame.K_ESCAPE):
                            running = False
                            menu = 0
                            menuActive = False

                        #capture mouse clicks
                        if event.type == pygame.MOUSEBUTTONDOWN:
                            if rects['quit'].collidepoint(event.pos):
                                selected = 'quit'

                    #logic for menu from the button clicks
                    if selected == "quit":
                        menuActive = False
                        menu = 0

                    if move == 0:
                        selected = str(randint(1, 9))
                    else:
                        selected = str(
                            self.pos2Selected(
                                opponents[opponentNames[player -
                                                        1]].move(board)))
                    move += 1
                    pos = self.convertIndexToPos(int(selected))
                    if self.validateMove(pos, board):
                        board[pos[1]][pos[0]] = player
                        self.drawMove(selected, player, rects)
                        pygame.display.update(rects[selected])
                        if self.findWinner(board):
                            winner = player
                        else:
                            player = self.switchPlayer(player)
                            if not self.boardFull(board):
                                self.drawBots(player, opponentNames, 1)
                    selected = False

                    if (not winner == 0) or self.boardFull(board):
                        if not winner == 0:
                            self.drawBots(winner + 2, opponentNames, 500)
                            scores[winner - 1] += 1
                            self.drawScores(scores)
                        else:
                            #draw
                            self.drawBots(5, opponentNames, 500)
                            winner = 1

                        #reset game
                        player = winner
                        screen.fill((0, 0, 255), (100, 100, 600, 600))
                        for key in rects.keys():
                            if key == "quit":
                                screen.fill(
                                    (0, 0, 255),
                                    (rects[key][0] - 3, rects[key][1] - 3,
                                     rects[key][2] + 6, rects[key][3] + 6))
                                screen.fill((127, 127, 127), rects[key])
                                self.write(rects[key], key, (200, 200, 200),
                                           75)
                            else:
                                screen.fill((127, 127, 127), rects[key])
                                self.write(rects[key], key, (200, 200, 200),
                                           100)
                        pygame.display.flip()
                        winner = 0
                        board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
                        move = 0
                        self.drawBots(player, opponentNames, 1)
                        selected = False
Exemplo n.º 22
0
			correct_count += 1.
	return correct_count/len(plots_test)

if __name__ == '__main__':

	# Get set of all movies
	all_movies = list(load_all_movies("plot.list.gz"))
	random.shuffle(all_movies)
	years, plots, titles = [], [], []

	for movie in all_movies:
		years.append(movie['year'])
		plots.append(movie['summary'])
		titles.append(movie['title'])

	min_year, max_year, bin_num = P2.year_stats(years)

	# Get uniform subset of movies
	years_train, plots_train, titles_train = [], [], []
	years_test, plots_test, titles_test = [], [], []
	year_count_train = [0]*bin_num
	year_count_test = [0]*bin_num
	train_sample_size = 5000
	test_sample_size = 1000

	# Create uniformly distributed training and test sets
	for i, year in enumerate(years):
		bin = int((year - min_year)/10)
		if year_count_train[bin] < train_sample_size: 
			year_count_train[bin] += 1
			years_train.append(year)
Exemplo n.º 23
0
def main(numSquares, oldGameFileName):
    #Set up graphical and logical game boards
    t, scrn = drawBoard(numSquares)
    row = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
    board = []
    for i in range(15):
        board.append(row[:])
    #If old game specified, read and set it
    if oldGameFileName != "":
        inFile = open(oldGameFileName, "r")
        fileNextPlayer = inFile.readline()  #Read next player
        fileNextPlayer = fileNextPlayer.strip()  #Remove \n
        row = 0
        for line in inFile:
            line = line[:-1]
            for col in range(len(line)):
                if line[col] != 'e':
                    board[row][col] = line[col]
                    drawPlayer(t, col, row, {
                        'b': 'blue',
                        'g': 'green'
                    }[line[col]])
                else:
                    board[row][col] = ''
            row += 1
        inFile.close()
    #Pick the starting player
    if oldGameFileName != "":
        player = fileNextPlayer
    else:
        player = ["blue", "green"][random.randint(0, 1)]

    #Play game
    move = ""
    while move not in ["QUIT", "Quit", "quit"] and not win(t, scrn, board)[0]:
        if player == "blue":
            move = P1.getValidMove(t, scrn, board, player)
            print(player, move)
        else:
            move = P2.getValidMove(t, scrn, board, player)
            print(player, move)
        if move not in ["QUIT", "Quit", "quit"]:
            row = (ord(move[0])) - 65
            col = int(move[1:])
            drawPlayer(t, col, row, player)
            board[row][col] = player[0]
            if player == "blue":
                player = "green"
            else:
                player = "blue"

    #Display the winner or save the partial game
    d = {"g": "green", "b": "blue"}
    if win(t, scrn, board)[0]:
        print("Winner is", d[win(t, scrn, board)[1]])
    elif move in ["QUIT", "Quit", "quit"]:
        saveFileName = input(
            "Enter a name for the game file, or just hit enter for no save => "
        )
        if saveFileName != "":
            print("Saving game")
            outFile = open(saveFileName, "w")
            outFile.write(player + '\n')
            for row in board:
                outString = ""
                for col in row:
                    if col == "":
                        outString = outString + 'e'
                    else:
                        outString = outString + col
                outFile.write(outString + '\n')
            outFile.close()
            print("Game saved")
        else:
            print("Game abandoned")
    scrn.clearscreen()
    return win(t, scrn, board)[1]
Exemplo n.º 24
0
num_pixels = 2000
rows = sc.range(num_pixels, numSlices=10)
cols = sc.range(num_pixels, numSlices=10)

indices = rows.cartesian(cols)

def mandelbrot_wrapper(row, col):
    x = col/(num_pixels/4.) - 2.
    y = row/(num_pixels/4.) - 2.

    return ((row, col), P2.mandelbrot(x, y))

########### Different from part A: load balancing! ########
new_indices = indices.repartition(100) # Randomly throw jobs between partitions

mandelbrot_load_balanced = new_indices.map(lambda a: mandelbrot_wrapper(*a))

summed_rdd = P2.sum_values_for_partitions(mandelbrot_load_balanced)
summed_result = summed_rdd.collect()

# Now collect the data & plot
plt.hist(summed_result, bins=np.logspace(3, 8, 20))
sns.rugplot(summed_result, color='red')
plt.gca().set_xscale('log')
plt.xlabel('Total Number of Iterations on Partition')
plt.ylabel('Partition Count')
plt.title('Number of Iterations on each Partition')

plt.savefig('P2b_alternative_hist.png', dpi=200, bbox_inches='tight')
Exemplo n.º 25
0
    return correct_count / len(plots_test)


if __name__ == '__main__':

    # Get set of all movies
    all_movies = list(load_all_movies("plot.list.gz"))
    random.shuffle(all_movies)
    years, plots, titles = [], [], []

    for movie in all_movies:
        years.append(movie['year'])
        plots.append(movie['summary'])
        titles.append(movie['title'])

    min_year, max_year, bin_num = P2.year_stats(years)

    # Get uniform subset of movies
    years_train, plots_train, titles_train = [], [], []
    years_test, plots_test, titles_test = [], [], []
    year_count_train = [0] * bin_num
    year_count_test = [0] * bin_num
    train_sample_size = 5000
    test_sample_size = 1000

    # Create uniformly distributed training and test sets
    for i, year in enumerate(years):
        bin = int((year - min_year) / 10)
        if year_count_train[bin] < train_sample_size:
            year_count_train[bin] += 1
            years_train.append(year)
Exemplo n.º 26
0
while (run):

    print("\n1. New Vehicle Registration")
    print("2. Auto Transaction")
    print("3. Driver License Registration")
    print("4. Violation Record")
    print("5. Search Engine")
    selection = input("Please select your program number or 'exit':\n")

    try:
        digit = int(selection)
        if digit == 1:
            P1.regV(conString)
        elif digit == 2:
            P2.AutoTransaction(conString)
        elif digit == 3:
            P3.DriverLiRegis(conString)
        elif digit == 4:
            P4.violation(conString)
        elif digit == 5:
            P5.search_engine(conString)
        else:
            print("Must be between 1 and 5")

    except ValueError:
        if selection == 'exit':
            run = False
        else:
            print("Please enter a digit or 'exit'")
Exemplo n.º 27
0
    def logoutwindow(self):
        gui = self
        gui.geometry("400x250")
        gui.title("HOAX")

        logout_label = Label(gui, text="Log out", width=6, font=("bold", 15))
        logout_label.place(x=160, y=53)

        a = Label(gui, text="Are you sure you want to log out as the current user?", width=64)
        a.place(x=-10, y=110)

        e = ttk.Button(gui, text="YES", width=10, command=lambda: [self.destroy(), test(), P2.HOAX()])#[P2.HOAX(), self.destroy()])
        e.place(x=205, y=175)

        f = ttk.Button(gui, text="NO", width=10, command=lambda: [self.destroy(), menuV1.Homepage()]) #, test(), menuV1.Homepage()]) #, menuV1.Homepage()) #, menuV1.Homepage.delete, menuV1.Homepage()])
        f.place(x=120, y=175)
Exemplo n.º 28
0
def checkersMain(inFileName, redWinCount, blackWinCount):
    wn, bob, board, player = setupGame(inFileName)
    gameOver = False
    if player == "b":
        move = THE_PLAYER.getValidMove(copy.deepcopy(board),
                                       player)  #get the first move
    else:
        move = P2.getValidMove(copy.deepcopy(board),
                               player)  #get the first move
    while move.lower() != "quit" and not gameOver:  #Start alternate play
        if player == "b":
            playerColor = "black"
        else:
            playerColor = "red"
        if GRAPHICS: wn.tracer(False)
        if STEP:
            input("Press return to watch the selected move for " +
                  playerColor + " ")
        FROMRow, FROMCol, TORow, TOCol = parseMove(
            move)  #parse move into locations
        if abs(FROMRow - TORow) == 1:  #move, not a jump
            if SLOW_DOWN: time.sleep(1)
            playerToken = board[FROMRow][
                FROMCol]  #save the player form current location (regular checker or king)
            removeCheckerGraphicalAndLogical(
                bob, FROMCol, FROMRow, board)  #remove the checker to be moved
            if SLOW_DOWN: time.sleep(.5)
            placeCheckerGraphicalAndLogical(
                bob, TOCol, TORow, board,
                playerToken)  #place the moved checker in its new location
        else:  #jump, not a move
            reps = move.count(":")
            for i in range(reps):
                FROMRow, FROMCol, TORow, TOCol = parseMove(move)
                playerToken = board[FROMRow][
                    FROMCol]  #save the player form current location (regular checker or king)
                if GRAPHICS: wn.tracer(False)
                if SLOW_DOWN:
                    time.sleep(1)
                removeCheckerGraphicalAndLogical(
                    bob, FROMCol, FROMRow,
                    board)  #remove the checker to be moved
                if SLOW_DOWN:
                    time.sleep(.5)
                placeCheckerGraphicalAndLogical(
                    bob, TOCol, TORow, board, playerToken
                )  #place the jumping checker in its new location
                if SLOW_DOWN:
                    wn.tracer(True)
                    time.sleep(1)
                    wn.tracer(False)
                removeCheckerGraphicalAndLogical(
                    bob, (FROMCol + TOCol) // 2, (FROMRow + TORow) // 2,
                    board)  #remove the jumped checker
                if SLOW_DOWN:
                    time.sleep(.5)
                if GRAPHICS: wn.tracer(True)
                move = move[3:]
        if GRAPHICS: wn.tracer(True)
        #printBoard(board)
        player, playerColor = swapPlayer(player)
        gameOver, winningPlayer = win(board)
        if not gameOver:
            if player == "b":
                start = time.time()
                move = THE_PLAYER.getValidMove(copy.deepcopy(board),
                                               player)  #get the first move
                stop = time.time()
            else:
                start = time.time()
                move = P2.getValidMove(copy.deepcopy(board),
                                       player)  #get the first move
                stop = time.time()
        if stop - start > 1.0:
            print("Match forfeited by", playerColor)
            return redWinCount, blackWinCount
    if move.lower() != "quit":
        #print(winningPlayer +" won the game in a smashing victory!")
        if winningPlayer == "red":
            redWinCount += 1
        else:
            blackWinCount += 1
        return redWinCount, blackWinCount
    else:
        fileName = input(
            "Enter a file name to save the current state of the game, or just hit enter to quit without saving the game => "
        )
        if fileName != "":
            saveGame(fileName, board, player)
Exemplo n.º 29
0
    ([['16%', '*****@*****.**', None, 'true', 'true', '22.11.2001'],
      ['29%', '*****@*****.**', None, 'false', 'false', '04.09.2002'],
      ['47%', '*****@*****.**', None, 'true', 'true', '06.11.2004'],
      ['47%', '*****@*****.**', None, 'true', 'true',
       '06.11.2004']], [['0.2', '0.3', '0.5'],
                        ['aleksej17', 'zituvev90', 'zolatic7'],
                        ['Выполнено', 'Не выполнено', 'Выполнено'],
                        ['22/11/01', '04/09/02', '06/11/04']]),
    ([['62%', '*****@*****.**', None, 'false', 'false', '07.11.2004'],
      ['56%', '*****@*****.**', None, 'true', 'true', '09.08.1999'],
      ['51%', '*****@*****.**', None, 'false', 'false', '23.08.2001'],
      ['15%', '*****@*****.**', None, 'false', 'false', '23.01.2004'],
      ['15%', '*****@*****.**', None, 'false', 'false', '23.01.2004']],
     [['0.6', '0.6', '0.5', '0.1'],
      ['arsenij73', 'fomomberg97', 'devomanz57', 'gordej84'],
      ['Не выполнено', 'Выполнено', 'Не выполнено', 'Не выполнено'],
      ['07/11/04', '09/08/99', '23/08/01', '23/01/04']]),
    ([['54%', '*****@*****.**', None, 'true', 'true', '15.02.2004'],
      ['93%', '*****@*****.**', None, 'false', 'false', '21.01.1999'],
      ['86%', '*****@*****.**', None, 'true', 'true', '27.05.2002'],
      ['86%', '*****@*****.**', None, 'true', 'true', '27.05.2002'],
      ['72%', '*****@*****.**', None, 'false', 'false', '21.08.2003']],
     [['0.5', '0.9', '0.9', '0.7'],
      ['vadim8', 'betefuk48', 'anatolij24', 'musodic24'],
      ['Выполнено', 'Не выполнено', 'Выполнено', 'Не выполнено'],
      ['15/02/04', '21/01/99', '27/05/02', '21/08/03']])
]

for t in temp:
    print(P2.f23(t[0]) == t[1])
Exemplo n.º 30
0
 def test_empty(self):
     polinomio = []
     resultado = []
     self.assertEqual(resultado, P2.integra_polinomio(polinomio))
Exemplo n.º 31
0
partition_vs_expensive_task = labeled_expensive_tasks.map(
    lambda x: (x[1] % num_partitions, x[0]))

# Get cheap tasks ready to process
cheap_tasks = indices_vs_expensive.filter(lambda x: x[1] == 0)
cheap_tasks = cheap_tasks.map(lambda x: x[0])
labeled_cheap_tasks = cheap_tasks.zipWithIndex()
partition_vs_cheap_task = labeled_cheap_tasks.map(
    lambda x: (x[1] % num_partitions, x[0]))

# Combine cheap & expensive tasks, now designated to an appropriate partition
partition_vs_ij = partition_vs_expensive_task.union(partition_vs_cheap_task)
# Sort data into the correct partition...sorted by key!
sorted_by_partition = partition_vs_ij.sortByKey(numPartitions=100)

mandelbrot_load_balanced = sorted_by_partition.map(
    lambda a: mandelbrot_wrapper(*a[1]))

summed_rdd = P2.sum_values_for_partitions(mandelbrot_load_balanced)
summed_result = summed_rdd.collect()

# Now collect the data & plot
plt.hist(summed_result, bins=np.logspace(3, 8, 20))
sns.rugplot(summed_result, color='red')
plt.gca().set_xscale('log')
plt.xlabel('Total Number of Iterations on Partition')
plt.ylabel('Partition Count')
plt.title('Number of Iterations on each Partition')

plt.savefig('P2b_hist.png', dpi=200, bbox_inches='tight')
Exemplo n.º 32
0
 def Openclick(self):
     P2.p1()
Exemplo n.º 33
0

# Main Function
if __name__ == '__main__':

		# Get set of all movies
	all_movies = list(load_all_movies("plot.list.gz"))
	random.shuffle(all_movies)
	years, plots, titles = [], [], []

	for movie in all_movies:
		years.append(movie['year'])
		plots.append(movie['summary'])
		titles.append(movie['title'])

	min_year, max_year, bin_num = P2.year_stats(years)

	# Get uniform subset of movies
	years_train, plots_train, titles_train = [], [], []
	years_test, plots_test, titles_test = [], [], []
	year_count_train = [0]*bin_num
	year_count_test = [0]*bin_num
	train_sample_size = 5000
	test_sample_size = 1000

	# Create uniformly distributed training and test sets
	for i, year in enumerate(years):
		bin = int((year - min_year)/10)
		if year_count_train[bin] < train_sample_size: 
			year_count_train[bin] += 1
			years_train.append(year)
Exemplo n.º 34
0
 def Openclick3(self):
     P2.p3()
Exemplo n.º 35
0
Arquivo: P12.py Projeto: cosminm/test
def main():
    print d
    result = P1.dict_to_list(d)
    print 'P1: ', result
    print 'P2: ', P2.find_index_optimized(result)