import random
from copy import deepcopy
from typing import List

class BattleshipGame:
    # Initial boards
    # The parameter @ships = {'A': 4, 'B': 5, 'S': 3, 'D': 3, 'P': 2}
    def __init__(self, ships):
        self.__userBoard = []             # Private @field __userBoard
        self.userShips = dict(ships)      # Each user ship point to -> the length remained of its self
        self.__computerBoard = []         # Private @field __computerBoard
        self.computerShips = dict(ships)  # Each user ship point to -> the length remained of its self
        self.rounds = 0
        for i in range(10):
            self.__userBoard.append([' '] * 10)
            self.__computerBoard.append([' '] * 10)
        self.computerTargeting = False      # Computer's targeting phase initially is False.
        self.hits = 0                       # Tracks computer hits and is used to determine whether or not to continue the targeting phase.
        self.targetStack = []               # Target stack for computer in targeting mode, containing all possible and valid moves following a hit by the computer.
        self.parityDictionary = dict(ships) # Dictionary used to determine the lowest hit points of remained ships to adjust parity in computer hunting phase.
        self.userShotList = [[int, int]]    # Each item is a list of coordinate [int x, int y]
        self.computerShotList = [[int, int]]# Each item is a list of coordinate [int x, int y]
        self.userSunkShips = []             # List of user's ship names that been destroyed.
        self.computerSunkShips = []         # List of computer's ship names that been destroyed.
        self.userPlacedShips = {}           # Dictionary of user's ship and its position {'Ship_Name': [int x, int y, str: orientation], ...}
        self.__computerPlacedShips = {}     # Dictionary of user's ship and its position {'Ship_Name' : [int x, int y, str: orientation], ...}
        pass

    def drawBoard(self, hide):
        # Draw boards
        # Aircraft is A, Destroyer is D, Submarine is S, Patrol boat is P, Battleship is B
        # Rows are denoted by characters from A to J
        # Columns are denoted by numbers from 1 to 10
        stats = [['Nbr. of hits  :', self.getHits(True), self.getHits(False)],
                 ['Nbr. of misses:', self.getMisses(True), self.getMisses(False)],
                 ['Ships sunk    :', len(self.getEnemyFleet(True)[1]), len(self.getEnemyFleet(False)[1])]]
        shipsSunkByComputer = list(self.getEnemyFleet(True)[1])
        shipsSunkByPlayer = list(self.getEnemyFleet(False)[1])
        statsIndex = 0
        computerIndex = 0
        playerIndex = 0
        if hide:
            computerBoard = deepcopy(self.__computerBoard)
            for row in range(10):
                for cell in range(10):
                    if computerBoard[row][cell] in 'ABCDSP':
                        computerBoard[row][cell] = ' '
        else:
            computerBoard = self.__computerBoard
        columnNumbers = '1 2 3 4 5 6 7 8 9 10 '
        print('%20s %21s %18s %s' % ('Computer\'s board: ', 'User\'s board: ', 'at round: ', self.rounds))
        print('%24s %25s %33s %15s' % (columnNumbers, columnNumbers, 'Computer Status: ', 'User Status: '))
        count = 65        # ASCII code of A is 65
        for row in range(len(self.__userBoard)):
            letter = chr(count)  # chr will return a string of one character whose ASCII code is count(65-74)
            print('%2s|%s|%5s|%s|' % (letter, '|'.join(computerBoard[row]), letter, '|'.join(self.__userBoard[row])), end='')
            if statsIndex < len(stats):
                print('%17s %3.2d %19.2d' % (stats[statsIndex][0], stats[statsIndex][1], stats[statsIndex][2]))
                statsIndex += 1
            elif len(shipsSunkByComputer) or len(shipsSunkByPlayer):
                if playerIndex < len(shipsSunkByPlayer):
                    playerSunkShip = shipsSunkByPlayer[playerIndex]
                    playerIndex += 1
                else:
                    playerSunkShip = ''
                if computerIndex < len(shipsSunkByComputer):
                    computerSunkShip = shipsSunkByComputer[computerIndex]
                    computerIndex += 1
                else:
                    computerSunkShip = ''
                print('                   %-16s    %s' % (computerSunkShip, playerSunkShip))
            else:
                print('')
            count += 1

    def makeA_Move(self, computer, x, y):
        # Return {' '} if it's a miss and return {'A', 'D', 'S', 'P', 'B'} if it's a hit
        if computer:
            board = self.__userBoard
        else:
            board = self.__computerBoard
        if board[x][y] in '* #'.split():
            return board[x][y]      # Return '*' or '#'
        elif board[x][y] == ' ':
            miss = board[x][y]
            board[x][y] = '*'
            return miss             # Return ' '
        else:
            hit = board[x][y]
            board[x][y] = '#'
            return hit              # Return one of {'A', 'D', 'S', 'P', 'B'}

    def validatePlacement(self, computer, ship, size, x, y, orientation):
        # Use the computer's or user's board depending on whether or not True has been passed into the method.
        # With the appropriate board, check if the caller has provided x and y coordinates of an empty cell.
        # If the orientation is vertical, check whether the x coordinate + the size of the ship exceeds the bounds of
        # the game board, if so, return False.
        # Otherwise, check if each x and y coordinate of the ship would fill an empty
        # cell, if so, return True, otherwise return False.
        # This process is identical for checking valid horizontal placement except that
        # the size of the ship is added to the y coordinate instead of the x coordinate to check if the ship is
        # within the bounds of the game board.
        if computer:
            board = self.__computerBoard
        else:
            board = self.__userBoard

        if board[x][y] == ' ':
            if orientation == 'v':
                if x + size - 1 > 9:
                    return False
                else:
                    for i in range(size):
                        if board[x + i][y] != ' ':
                            return False
                    for i in range(size):
                        board[x + i][y] = ship
                    return True
            elif orientation == 'h':
                if y + size - 1 > 9:
                    return False
                else:
                    for i in range(size):
                        if board[x][y + i] != ' ':
                            return False
                    for i in range(size):
                        board[x][y + i] = ship
                    return True
        else:
            return False

    def getEnemyFleet(self, computer):
        # Create empty lists for the entire fleet of all ships sunk
        # If the computer is calling this method, iterate through the users's board, otherwise iterate through the computers's board
        # For each ship in the ship dictionary defined in the init, if the hit points of the ship are greater than zero,
        # call the what ship private method to get the full name of the ship, and then append it to the ships to sink list.
        # Otherwise, if the hit points of the ship is 0, get the full name
        # of the ship as previously using the what ship method, and append it to the ships sunk list.
        # Finally, append both lists to the fleet list and return it.
        shipsToSink = []
        shipsSunk = []
        if computer:
            ships = self.userShips
        else:
            ships = self.computerShips
        for ship in ships:
            if ships[ship] > 0:
                ship = self.whatShip(ship)
                shipsToSink.append(ship)
            else:
                ship = self.whatShip(ship)
                shipsSunk.append(ship)
        return [shipsToSink, shipsSunk]

    def whatShip(self, symbol):
        # Take the first letter (symbol of the ship and return the full name of the ship)
        shipNames = {'A': 'Aircraft Carrier',
                     'B': 'Battleship',
                     'S': 'Submarine',
                     'D': 'Destroyer',
                     'P': 'Patrol Boat'}
        fullName = shipNames[symbol]
        return fullName

    def checkWinning(self, computer):
        # Pass true or false depending on whether the user or computer is calling the method.
        # To determine if the computer or user has won, check the length of the ships to sink list
        # generated by the get enemy fleet method. If there are still ships on the board that have
        # not yet been sunk, return False, otherwise return True since all ships have been sunk.
        if computer:
            computer = True
        else:
            computer = False
        if len(self.getEnemyFleet(computer)[0]) == 0:
            return True
        else:
            return False

    def checkIfSunk(self, computer, ship):
        # Check if all parts of the ship is hit
        if computer:
            self.userShips[ship] -= 1
            if self.userShips[ship] == 0:
                print('Computer sunk your %s!' % (self.whatShip(ship)))
                self.userSunkShips.append(self.whatShip(ship))
                return True
            return False
        else:
            self.computerShips[ship] -= 1
            if self.computerShips[ship] == 0:
                print('You sunk Computer\'s %s!' % (self.whatShip(ship)))
                self.computerSunkShips.append(self.whatShip(ship))
                return True
            return False

    def incrementRounds(self):
        # increment the instance variable rounds by one after both the player and computer have shot
        self.rounds += 1

    def getHits(self, computer):
        # Pass true if returning hits for computer or false if checking hits for the player.
        # Iterate through the game board and check for hits ('#'), if a hit is encountered, increment
        # the variable hits by one. After iterating, return hits.
        hits = 0
        if computer:
            board = self.__userBoard
        else:
            board = self.__computerBoard
        for row in range(10):
            for cell in range(10):
                if board[row][cell] == '#':
                    hits += 1
        return hits

    def getMisses(self, computer):
        # Pass true if returning misses for computer or false if checking misses for the player.
        # Iterate through the game board and check for misses ('#'), if a miss is encountered, increment
        # the variable misses by one. After iterating, return misses.
        misses = 0
        if computer:
            board = self.__userBoard
        else:
            board = self.__computerBoard
        for row in range(10):
            for cell in range(10):
                if board[row][cell] == '*':
                    misses += 1
        return misses

    def userPlaceShips(self, ship, size):
        # While ship placement is not valid, prompt the user to enter in x and y coordinates for their shot.
        # After valid input has been accepted, ask the user for the orientation they would like to place their ship and only accept either v or h.
        # After all input is validated, call the validate placement method to check
        # if the ship can be placed on the board, if not, alert the user and prompt them to enter a new set of coordinates and orientation.
        # If the ship can be placed on the board, alert the player that they have placed a ship and the type of ship placed.
        valid = False
        while not valid:
            print('Placing %s of size %s' % (ship, size))
            x, y = userInput()
            orientation = None
            while orientation not in 'v h'.split():
                orientation = input('Is this ship vertical or horizontal (v,h)? ').lower()
            valid = self.validatePlacement(False, ship[0], size, x, y, orientation)
            print('You placed a %s' % ship)
            self.drawBoard(True)
            print()
            if not valid:
                print('Cannot place a %s there. Stern is out of the board or collides with another ship.' % ship)
                print('Please take a look at the board and try again.')

    def computerPlaceShips(self, ship, size):
        # While a valid placement for a particular ship has not been randomly generated by the computer,
        # generate random x and y coordinates between 0 and 9 and a random orientation (either v or h).
        # Continue generating random coordinates until the ship can be placed on the board.
        valid = False
        while not valid:
            x, y = random.randint(0, 9), random.randint(0, 9)
            orientation = random.choice(['v', 'h'])
            valid = self.validatePlacement(True, ship[0], size, x, y, orientation)
            if valid:
                # self.__computerPlacedShips.update({ship: [x, y, orientation]})
                self.__computerPlacedShips.update({ship: [chr(x + 65), y + 1, orientation]})
        print('Computer has placed a %s' % ship)

    def computerMakesMove(self):
        # Pass the battleShip game object, the size of the ships, and whether or not the computer is in targeting mode.
        # Initialize parity variable as the minimum ship size still in play. If the computer is in targeting mode,
        # pop a move from the targetStack and play that move. Otherwise, choose a random x (letter) coordinate between 0 and 9
        # set the range of possible y coordinates (numbers) to the result of the modulo of the x coordinate and the parity(min ship size).
        # Generate a random y coordinate in the defined range and then play the resulting move.
        # If the computer has fired a shot in the same location previously, generate new x and y coordinates.
        # Otherwise, print a message informing the user that the computer has missed their ship,
        # or if the computer has hit the user's ship, check if it has sunk by calling the check if sunk method.
        # If the ship has not been sunk, push to targetStack moves to the left, right, top, and bottom of the hit and return True(True is targeting mode).

        parity = min(self.parityDictionary.values())  # Get smallest ship size still remaining in play.
        while True:
            if self.computerTargeting:
                x, y = self.targetStack.pop()
            else:
                x = random.randrange(0, 10)
                yRange = x % parity
                y = random.randrange(yRange, 10, parity)
            computerMove = self.makeA_Move(True, x, y)
            if computerMove in '* #'.split():
                continue
            elif computerMove == ' ':
                self.computerShotList.append([x, y])
                print('Computer missed your ship at %s %s.' % (chr(x + 65), y + 1))
                if self.computerTargeting:
                    self.computerTargeting = True
                    return True
                else:
                    self.computerTargeting = False
                    return False
            else:
                self.hits += 1
                self.computerShotList.append([x, y])
                print('Computer hit your ship at %s %s!' % (chr(x + 65), y + 1))
                if self.checkIfSunk(True, computerMove):
                    self.hits -= self.parityDictionary[computerMove]  # If hits - length of ship sunk = 0, no hits were registered to a different ship.
                    del self.parityDictionary[computerMove]  # If the ship has sunk, delete it from the dictionary to allow a new minimum ship size.
                    if self.hits == 0:  # To make sure all hit shots are on the latest Sunk Ship, else at least 1 shot hit another ship that not been sunk yet.
                        self.targetStack = []  # Empty the stack before changing computer to hunting mode
                        self.computerTargeting = False
                        return False  # Computer will be in hunting mode.
                    else:
                        self.computerTargeting = True
                        return True  # Computer remains in targeting mode.
                else:
                    # Append x and y coordinates above, below, to the left, and to the right
                    # of the hit to targetStack list if they are within the bounds of the game board.
                    # This initiates the target phase. Checking if this cell has already been played
                    # is not needed because this case is handled above.
                    if y - 1 >= 0:
                        self.targetStack.append([x, y - 1])
                    if y + 1 <= 9:
                        self.targetStack.append([x, y + 1])
                    if x - 1 >= 0:
                        self.targetStack.append([x - 1, y])
                    if x + 1 <= 9:
                        self.targetStack.append([x + 1, y])
                    self.computerTargeting = True
                    return True  # Computer will be in targeting mode.

    def userMakesMoveAtXY(self, x, y):
        userMove = self.makeA_Move(False, x, y)
        if userMove in '* #'.split():
            print('Sorry, %s %s was already played. Try again.' % (chr(x + 65), y + 1))
            return False
        elif userMove == ' ':
            self.userShotList.append([x, y])
            print('Your shot at %s %s missed.' % (chr(x + 65), y + 1))
            return False
        else:
            self.userShotList.append([x, y])
            print('You hit Computer\'s ship at %s %s!' % (chr(x + 65), y + 1))
            if self.checkIfSunk(False, userMove):
                raise ComputerShipSunkException
            return True

    def userMakesMove(self):
        # Until a valid move is played on the board, ask the user for coordinates for their shot.
        # If the a shot has already been taken at that location, alert the user and prompt them to enter another set of coordinates.
        # If the user has missed, print a message and return.
        # If the user has hit a ship, print a message indicating they hit a ship and then call the check if sunk method.
        while True:
            x, y = userInput()
            userMove = self.makeA_Move(False, x, y)
            if userMove in '* #'.split():
                print('Sorry, %s %s was already played. Try again.' % (chr(x + 65), y + 1))
            elif userMove == ' ':
                self.userShotList.append([x, y])
                print('Your shot at %s %s missed.' % (chr(x + 65), y + 1))
                return
            else:
                self.userShotList.append([x, y])
                print('You hit Computer\'s ship at %s %s!' % (chr(x + 65), y + 1))
                if self.checkIfSunk(False, userMove):
                    print("BOOM !")
                return

    def getLatestShot(self, isComputer):
        try:
            if isComputer:
                return self.computerShotList.__getitem__(self.computerShotList.__len__() - 1)
            else:
                return self.userShotList.__getitem__(self.userShotList.__len__() - 1)
        except IndexError:
            return None

    def getLatestSunkShipPosition(self, isComputer):
        try:
            if isComputer:
                return self.__computerPlacedShips.get(self.getLatestSunkShipName(True))
            else:
                return self.userPlacedShips.get(self.getLatestSunkShipName(False))
        except KeyError:
            return None

    def getLatestSunkShipName(self, isComputer):
        try:
            if isComputer:
                return self.computerSunkShips.__getitem__(self.computerSunkShips.__len__() - 1)
            else:
                return self.userSunkShips.__getitem__(self.userSunkShips.__len__() - 1)
        except IndexError:
            return None

    def getComputerPlacedShips(self):  # Get computer's ships name & position
        return self.__computerPlacedShips

    pass  # End BattleshipGame's constructor !

class UserShipSunkException(Exception):
    """ Raised when a new ship of user been sunk !"""
    pass  # End UserShipSunkException constructor !

class ComputerShipSunkException(Exception):
    """ Raised when a new ship of computer been sunk !"""
    pass  # End ComputerShipSunkException constructor !

def userInput():
    # Until the user enters in valid input, prompt them to enter a letter and number for the x and y coordinate respectively.
    # To do this, check if the user's input consists of two elements separated by a space,
    # if so check if the x coordinate consists of a letter and the y coordinate consists of a number.
    # Next convert the y coordinate to an integer and check if it is within 1 and 10.
    # Next check if the x coordinate is between the letters a and j.
    # Finally return the x and y coordinates as integers between 0 and 9.
    while True:
        move = input('Enter coordinates x y (x in [A..J]) and y in [1..10]): ').lower()
        move = move.split()
        if len(move) != 2:
            continue
        if move[0].isalpha() and move[1].isnumeric():
            if len(move[0]) > 1:
                continue
            if 'a' <= move[0] <= 'j' and 1 <= int(move[1]) <= 10:
                return int(ord(move[0]) - 97), int(int(move[1]) - 1)
            else:
                continue
        else:
            continue

def main():
    playing = True
    fleetDictionary = {'Aircraft Carrier': 4,
                       'Battleship': 5,
                       'Submarine': 3,
                       'Destroyer': 3,
                       'Patrol Boat': 2}
    ships = {key[0]: fleetDictionary.get(key) for key in fleetDictionary}  # The dictionary key is 1st letter of ship and associated values are ship hit points.
    battleShip = BattleshipGame(ships)
    for computerShip in fleetDictionary:
        battleShip.computerPlaceShips(computerShip, fleetDictionary[computerShip])
    battleShip.drawBoard(True)
    print('Welcome to Battleship! Please place your ships.')
    for userShip in fleetDictionary:
        battleShip.userPlaceShips(userShip, fleetDictionary[userShip])
    battleShip.incrementRounds()
    battleShip.drawBoard(True)
    input('You have placed all of your ships. Please press ENTER to continue.')
    print('Fire at the enemy fleet...')
    while playing:
        battleShip.userMakesMove()
        userWin = battleShip.checkWinning(False)
        if userWin:
            battleShip.drawBoard(True)
            print('Congratulations! You have won against the computer.')
            playing = False
            break
        battleShip.computerMakesMove()
        computerWin = battleShip.checkWinning(True)
        if computerWin:
            print('Sorry! You have lost against the computer.')
            print('Remaining Computer Ships:')
            battleShip.drawBoard(False)
            playing = False
            input('Press any key to exit.')
            break
        battleShip.incrementRounds()
        battleShip.drawBoard(True)

if __name__ == "__main__":
    main()


import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from ComplexNN import *

class AlexNet(nn.Module):

    def __init__(self, num_classes=100):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(64, 192, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2)
        )

        self.conv2 = nn.Sequential(
            nn.Conv2d(64, 192, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2)
        )
        self.conv3 = nn.Sequential(
            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True)
        )
        self.conv4 = nn.Sequential(
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True)
        )
        self.conv5 = nn.Sequential(
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2)
        )

        self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
        self.classifier = nn.Sequential(
            nn.Dropout(),
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes),
        )

    def forward(self, x):
        # x = self.features(x)
        print(x.shape)
        x = self.conv1(x)
        print(x.shape)
        x = self.conv2(x)
        print(x.shape)
        x = self.conv3(x)
        print(x.shape)
        x = self.conv4(x)
        print(x.shape)
        x = self.conv5(x)
        print(x.shape)
        # x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x
# net = AlexNet()
# x = torch.rand(64,3,32,32)
# net(x)
class preEncoder(nn.Module):
    def __init__(self):
        super(preEncoder, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(64, 192, kernel_size=5, stride=1, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(192, 384, kernel_size=5, stride=1, padding=1),
            nn.ReLU(inplace=True)
        )
    def forward(self, I):
        return self.features(I)

class Discriminator(nn.Module):
    def __init__(self):
        super(Discriminator, self).__init__()

        self.main = nn.Sequential(
            nn.Conv2d(384,192,3,1),
            nn.LeakyReLU(),
            nn.Conv2d(192,64,3,1),
            nn.LeakyReLU(),
            nn.Conv2d(64,32,3,1),
            nn.LeakyReLU(),
        )
        self.linear = nn.Linear(256,1)
        self.relu = nn.LeakyReLU()

    def forward(self, x):
        x = self.main(x) #[128, 32, 4, 2]
        # print(x.shape)
        x = x.view(x.shape[0], -1)  #[128, 256]
        # print(x.shape)
        x = self.linear(x)
        # print(x.shape)
        x = self.relu(x) #[128, 256]

        return x

class Net(nn.Module):
    def __init__(self, identities=10177):
        super(Net, self).__init__()
        self.conv4 = ComplexConv2d(384, 256, kernel_size=3, stride=1, padding=1)
        self.conv5 = ComplexConv2d(256, 256, kernel_size=3, stride=1, padding=1)
        self.Crelu = ComplexRelu()
        self.Cmax = ComplexMaxPool2d(3, 2)
        self.classifier = nn.Sequential(
            nn.Dropout(),
            nn.Linear(256 * 4 * 3, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, identities),
        )

    def forward(self, a, b, theta):
        x1, x2 = encode(a, b, theta)
        x1, x2 = self.conv4(x1, x2)
        x1, x2 = self.Crelu(x1, x2)
        x1, x2 = self.conv5(x1, x2)
        x1, x2 = self.Crelu(x1, x2)
        x1, x2 = self.Cmax(x1, x2)

        x1 = x1.view(x1.size()[0], -1)
        x2 = x2.view(x2.size()[0], -1)

        x = decode(x1, x2, theta)
        x = self.classifier(x)

        return x

g = preEncoder()
discriminator = Discriminator()
net = Net()
# model = AlexNet()
x = torch.rand(128, 3, 218, 178)
# b = g(torch.rand_like(x))
x = g(x)
print(x.shape)
# theta = torch.Tensor(1).uniform_(0,np.pi)
# x = net(x,b,theta)
x = discriminator(x)
print(x.shape)
# a = g(x)
# b = g(torch.rand_like(x))
# delta_theta = torch.Tensor(5).uniform_(0,np.pi)
# output = net(a, b, delta_theta[0])
# print(ED(a, b, delta_theta[0]).shape)
# print(discriminator(ED(a, b, delta_theta[0])))
# fake_imgs = torch.stack([discriminator(ED(a, b, dt)) for dt in delta_theta])
# loss_D = -torch.mean(discriminator(a)) + torch.mean(fake_imgs)
# print(x.shape)
# x = model(x)
# print(x.shape)
# x = d(x)
# print(x.shape)
#
# target = torch.ones([256, 40], dtype=torch.int64).float()  # 64 classes, batch size = 10
# output = torch.full([256, 40], 0.999)  # A prediction (logit)
# pos_weight = torch.ones([40])  # All weights are equal to 1
# criterion = torch.nn.BCEWithLogitsLoss(pos_weight=pos_weight)
# loss = criterion(output, target)  # -log(sigmoid(0.999))
# print(loss)
# def encode(a, b, theta):
#     x = torch.mul(a, torch.cos(theta)) - torch.mul(b, torch.sin(theta))
#     y = torch.mul(a, torch.sin(theta)) + torch.mul(b, torch.cos(theta))
#     # print(theta)
#     return x, y

# def decode(a, b, theta):
#     return torch.mul(a, torch.cos(-theta)) - torch.mul(b, torch.sin(-theta))

# print(x.shape[0])
# b = g(torch.rand_like(x))
# x = g(x)

# print(x.shape)

# theta = torch.Tensor(1).uniform_(0,2*np.pi)
# output = net(x, b, theta)
# print(output.shape)
# def encode1(a, b, theta):
#     x = a * torch.cos(theta) - b * torch.sin(theta)
#     y = a * torch.sin(theta) + b * torch.cos(theta)
#     # print(theta)
#     return x, y

# class preEncoder(nn.Module):
#     def __init__(self):
#         super(preEncoder, self).__init__()
#         self.features = nn.Sequential(
#             nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1),
#             nn.ReLU(inplace=True),
#             nn.MaxPool2d(kernel_size=3, stride=2),
#             nn.Conv2d(64, 192, kernel_size=3, stride=1, padding=1),
#             nn.ReLU(inplace=True),
#             nn.MaxPool2d(kernel_size=3, stride=2),
#             nn.Conv2d(192, 384, kernel_size=3, stride=1, padding=1),
#             nn.ReLU(inplace=True),
#         )
#     def forward(self, I):
#         return self.features(I)

# class Discriminator(nn.Module):
#     def __init__(self):
#         super(Discriminator, self).__init__()

#         self.main = nn.Sequential(
#             nn.Conv2d(384,192,3,1),
#             nn.LeakyReLU(),
#             nn.Conv2d(192,64,2,1),
#             nn.LeakyReLU(),
#         )
#         self.linear = nn.Linear(64, 1)
#         self.relu = nn.LeakyReLU()

#     def forward(self, x):
#         x = self.main(x)
#         x = x.view(x.shape[0], -1)
#         x = self.linear(x)
#         x = self.relu(x)

#         return x

# # g = preEncoder()
# d = Discriminator()
# x = torch.rand(10,384,4,4)
# # x = g(x)
# # print(x.shape)
# x = d(x)
# print(x.shape)

# print(3e-4)

# a = torch.tensor([2])
# b = torch.tensor([3])

# b = torch.rand(1, 6, 1, 2)
# # print(b)

# pool = nn.MaxPool2d(2, stride=2, return_indices=True)
# unpool = nn.MaxUnpool2d(2, stride=2)
# Input = torch.tensor([[[[ 1.,  2,  3,  4],
#                         [ 5,  6,  7,  8],
#                         [ 9, 10, 11, 12],
#                         [13, 14, 15, 16]],[[ 1.,  2,  3,  4],
#                         [ 5,  6,  7,  8],
#                         [ 9, 10, 11, 12],
#                         [13, 14, 15, 16]]],[[[ 0.,  0,  0,  0],
#                         [ 0,  1,  0,  1],
#                         [ 0,0,0,0],
#                         [3,4,0,1]],[[ 0.,  0,  0,  0],
#                         [ 0,  1,  0,  1],
#                         [ 0,0,0,0],
#                         [0,1,0,1]]]])
# output, indices = pool(Input)

# I = torch.tensor([[[[ 0.,  0,  0,  0],
#                         [ 0,  1,  0,  1],
#                         [ 0,0,0,0],
#                         [0,1,0,1]]]])
# def unravel_index(index, shape):
#     out = []
#     for dim in reversed(shape):
#         out.append(index % dim)
#         index = index // dim
#     return tuple(reversed(out))
# print(Input)
# print(torch.mean(Input,(0)))

# A  = torch.tensor([[ 0.,  1,  0,  1],[ 0,0,0,0],[0,1,0,1]])
# A[0,:] = 3
# print(A)
# print(torch.mean(A))

# print(unravel_index(1, Input.shape))
# print(Input[unravel_index(1, Input.shape)])
# # Input[15] = 100
# y = Input.view(16)
# indices[0,0,0,1] = y[indices[0,0,0,1]]

# theta = torch.Tensor(10).uniform_(0,2*np.pi)
# b = torch.rand(100, 6, 14, 14)
# print(b)

# G_DIM = 6
# G_SIZE = 14
# D_CHANNEL=256
# x = torch.rand(10,100,6,14,14)

# model = nn.Sequential(
#         nn.Linear(G_DIM*G_SIZE*G_SIZE, 256),
#         nn.LeakyReLU(0.2),
#         nn.Linear(256, 128),
#         nn.LeakyReLU(0.2),
#         nn.Linear(128, 1),
#     )

# x = x.view(x.shape[0],x.shape[1],G_DIM*G_SIZE*G_SIZE)
# x = torch.mean(model(x))
# print(x.shape)
# x = torch.rand(50)
# print(x.shape)
# for i in range(x.shape[0]):
#     print(i)

# def ED(a, b, theta):
#     x, y = encode(a, b, theta)
#     return decode(x, y, theta)
# a = torch.rand(100,3,14,14)
# b = torch.rand(100,3,14,14)
# theta = torch.Tensor(10).uniform_(0,2*np.pi)
# x = torch.stack([ED(a, b, dt) for dt in theta])

# print(x.shape)

# a = torch.tensor([[1.,2.],[3.,4.]])
# non_Linear = torch.clamp(a, max = 2)

# print(non_Linear)
# non_Linear = a / torch.clamp(a, max = 2)
# print(a)
# print(non_Linear)

# x1 = torch.rand([100, 3, 32, 32])
# x_norm_max, inds = F.max_pool2d(x1, 2, 2, return_indices = True)
# print(inds[1,1,:,:])
# print(a_max.shape, "\n")
# print(inds.shape, "\n")
# n,c,h,w = inds.shape
# b = a.view(100,3,32*32)
# inds_b = inds.view(n,c,h*w)
# b_max = torch.gather(b, 2, inds_b)
# print(b_max.shape, "\n")
# b_max = b_max.view(n,c,h,w)
# print(b_max.shape, "\n")

# x1 = torch.rand([100, 3, 32, 32])
# x2 = torch.rand([100, 3, 32, 32])
# x_norm = x1*x1 + x2*x2
# x_norm_max, inds = F.max_pool2d(x_norm, 2, 2, return_indices = True)

# x1 = torch.rand([100, 3, 32, 32])
# x2 = torch.rand([100, 3, 32, 32])
# x_norm = x1*x1 + x2*x2
# x_norm_max, inds = F.max_pool2d(x_norm, 2, 2, 0, 1, False, True)
# n,c,h1,w1 = x_norm.shape
# n,c,h2,w2 = x_norm_max.shape
# X1 = x1.view(n,c,h1*w1)
# X2 = x2.view(n,c,h1*w1)
# inds_X = inds.view(n,c,h2*w2)
# X1_max = X1.gather(2, inds_X).view(n,c,h2,w2)
# X2_max = X2.gather(2, inds_X).view(n,c,h2,w2)

# x1 = torch.rand([100, 3, 32, 32])
# x2 = torch.rand(x1.shape)
# print(x2.shape)

# import argparse
# parser = argparse.ArgumentParser()
# parser.add_argument("--n_epochs", type=int, default=10, help="number of epochs of training")
# parser.add_argument("--batch_size", type=int, default=100, help="size of the batches")
# parser.add_argument("--lr", type=float, default=0.00005, help="learning rate")
# # parser.add_argument("--n_cpu", type=int, default=8, help="number of cpu threads to use during batch generation")
# # parser.add_argument("--latent_dim", type=int, default=100, help="dimensionality of the latent space")
# parser.add_argument("--img_size", type=int, default=32, help="size of each image dimension")
# parser.add_argument("--channels", type=int, default=3, help="number of image channels")
# parser.add_argument("--n_critic", type=int, default=10, help="number of training steps for discriminator per iter")
# parser.add_argument("--clip_value", type=float, default=0.01, help="lower and upper clip value for disc. weights")
# # parser.add_argument("--sample_interval", type=int, default=400, help="interval betwen image samples")
# opt = parser.parse_args()
# opt.channels = 64
# img_shape = (opt.channels, opt.img_size, opt.img_size)
# print(img_shape)

# a = torch.rand(3,5,64,64)
# b = nn.Conv2d(5,6,5,1)
# # b = torch.rand_like(a)

# print(b)


#!/usr/bin/env python3
#
# This file is part of pySerial - Cross platform serial port support for Python
# (C) 2016 Chris Liechti <cliechti@gmx.net>
#
# SPDX-License-Identifier:	BSD-3-Clause

import sys
import os
import time
import getopt
from hexdump import hexdump
from print_color import print
from attenuator import *
from usbtty_geehy import *

def UnitTest(ser):
	print("Self unit test action...")
	ser.SetFull()
	time.sleep(3)
	ser.SetHalt()
	time.sleep(1)
	exit(0)

def usage():
	print("For example:")
	print("\t./geehy-io.py -D </dev/ttyUSB0> -v 103")
	exit(-1)

if __name__ == '__main__':
	argv=sys.argv[1:]

	try:
		opts, args = getopt.getopt(argv, "D:v:ut:s:i:w:")
	except:
		usage()

	atten=None
	unit_test=None
	intv_waitting=5
	init_atten=20
	step_lvl=5
	start_wait=3
	for opt, arg in opts:
		if opt in ['-D']:
			ttyX=arg
		if opt in ['-v']:
			atten=int(arg)
		if opt in ['-u']:
			unit_test = True
		if opt in ['-i']:
			intv_waitting = int(arg)
		if opt in ['-s']:
			init_atten = int(arg)
		if opt in ['-t']:
			step_lvl = int(arg)
		if opt in ['-w']:
			start_wait = int(arg)

	try:
		ttyX
	except:
		ttyX='/dev/ttyUSB0'

	Ser = tty_usb_geehy(ttyX)
	atten_sc = atten_unit(atten_unit.ATTEN_MODE_HP33321_SC)
	atten_sd = atten_unit(atten_unit.ATTEN_MODE_HP33321_SD)
	atten_sg = atten_unit(atten_unit.ATTEN_MODE_HP33321_SG)

	if unit_test == True:
		UnitTest(Ser)

	if atten == None:
		usage()
	# atten_grp = AttenGroup("SC-SG-SD", Ser, [atten_sc, atten_sg, atten_sd])
	# atten_grp.dump()
	# atten_grp.set_value(atten)

	atten_grp = atten_group("SC-SG", Ser, [atten_sc, atten_sg])
	# atten_grp = atten_group("SC-SD", Ser, [atten_sc, atten_sd])
	atten_grp.dump()
	atten_grp.set_value(init_atten)
	time.sleep(start_wait)

	print("\nTarget: {} cell to 5 * {} = {}".format(atten, int(atten/5), int(atten/5)*5), color = "yellow", background='gray', format='bold')
	sys.stdout.write(" serial port: {!r}, step:{:d} intv: {:d} sec.\n".format(ttyX, step_lvl, intv_waitting))
	for av in range(init_atten, atten + 5, step_lvl):
		atten_grp.set_value(av)
		time.sleep(intv_waitting)


# Small Exercise 7. Looping from 1 to 10

# Using a while loop, print out the numbers between 1 and 10 inclusive, one on a line.

STOP = 11
counter = 0

while counter < STOP:
     print(counter)
     counter += 1


from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import User

# Create your models here.
class QuizUser(AbstractUser):

    ROLE_CHOICE = [('Admin', 'Admin User'), ('Quizmaster', 'Quizmaster'),
                   ('StdUser', 'Standard User'), ('Guest', 'Guest')]

    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    role = models.CharField(
        max_length=20, choices=ROLE_CHOICE, default='StdUser')


from collections import OrderedDict

GAME_WORDS = ['ability', 'about', 'above', 'absolute', 'accessible',
              'accommodation', 'accounting', 'ambassador', 'anniversary',
              'appointment', 'awkward', 'bagpipes', 'beautiful', 'birthday',
              'bookstore', 'brand', 'calculator', 'circumstance', 'clever',
              'confused', 'congratulate', 'dangerous', 'decrease', 'development',
              'dictionary', 'dwarves', 'earthquake', 'engaged', 'engineer',
              'enough', 'entertainment', 'environment', 'environment', 'exhausted',
              'frequent', 'gypsy', 'handsome', 'haphazard', 'hyphen', 'impossible',
              'information', 'interested', 'ivory', 'jukebox', 'luggage',
              'mathematics', 'memento', 'mystify', 'necessary', 'opposite',
              'overweight', 'oxygen', 'perhaps', 'pixel', 'possible',
              'refrigerator', 'responsible', 'rhythmic', 'rogue', 'scissors',
              'sphinx', 'strawberry', 'temperature', 'twelfth', 'vacation', 'yacht',
              'xylophone', 'zealous', 'zombie']

MESSAGES = OrderedDict([
    ('NEXT', {
        'msg': "What's your next guess?",
    }),
    ('ALREADY_GUESSED', {
        'msg': "You can't guess a letter that you've guessed before. Try again.",
    }),
    ('INVALID', {
        'msg': "Invalid guess. Try again."
    }),
    ('CORRECT', {
        'msg': "Good guess!"
    }),
    ('INCORRECT', {
        'msg': "Oops... That letter isn't in this word."
    }),
    ('GAME_OVER', {
        'msg': "Oh no! You couldn't guess the word in time.\nGame over!"
    }),
    ('GAME_WON', {
        'msg': "You've guessed the word correctly.\nCongratulations!"
    })
])

IMG_PATH = {
    0: 'images/hangman-0.png',
    1: 'images/hangman-1.png',
    2: 'images/hangman-2.png',
    3: 'images/hangman-3.png',
    4: 'images/hangman-4.png',
    5: 'images/hangman-5.png',
    6: 'images/game-over.png'
}


class Solution:
    def sortColors(self, a: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i = 0
        for j in range(len(a)):
            if a[j] == 0:
                a[i], a[j] = a[j], a[i]
                i += 1
        for j in range(len(a)):
            if a[j] == 1:
                a[i], a[j] = a[j], a[i]
                i += 1
        return a


import random

words_file = open("input.txt", mode="r")

words = []

for word in words_file:
    words.append(word)

def getRandomWords(amount):
    random_words = []
    random.shuffle(words)
    for x in range(0, amount):
        random_words.append(words[x])
    return random_words

def writeFile(amount, file):
    e = open(file, mode="w")
    for word in getRandomWords(amount):
        e.write(word)

writeFile(100, "./export/100.txt")
writeFile(250, "./export/250.txt")
writeFile(500, "./export/500.txt")
writeFile(1000, "./export/1000.txt")
writeFile(5000, "./export/5000.txt")
writeFile(10000, "./export/10000.txt")


if __name__ == '__main__':
    param = [
    ('LZIKA',),
    ('0556979952',),
    ('110010',),
    ('kGaYfd',),
    ('413567670657',),
    ('01001',),
    ('EQPuFa',),
    ('48848378',),
    ('110',),
    ('PLehNeP',)
        ]
    n_success = 0
    print("class,mutant,test_index,result")
    for i, parameters_set in enumerate(param):
        try:
            print("COUNT_SUBSTRINGS_WITH_SAME_FIRST_AND_LAST_CHARACTERS," + sys.argv[1] + "," + str(i) + "," + str(f_gold(*parameters_set)))
        except:
            print("COUNT_SUBSTRINGS_WITH_SAME_FIRST_AND_LAST_CHARACTERS," + sys.argv[1] + "," + str(i) + ",EXCEPTION")


import os
import random
import torch
from torch.utils.data import Dataset

def news_sample(news, ratio):
    if ratio > len(news):
        return news + [0] * (ratio - len(news))
    else:
        return random.sample(news, ratio)

class MindDataset(Dataset):
    def __init__(self,
                 data_dir,
                 args,
                 news_index,
                 news_combined,
                 word_dict):
        super(MindDataset, self).__init__()
        self.data_dir = data_dir
        self.device = args.device_id
        self.npratio = args.npratio
        self.user_log_length = args.max_hist_len
        self.batch_size = args.batch_size
        # data loader only cares about the config after tokenization.
        self.sampler = None
        self.epoch = -1

        self.news_combined = news_combined
        self.news_index = news_index
        self.word_dict = word_dict
        self.behaviors = self._process()

    def trans_to_nindex(self, nids):
        return [self.news_index[i] if i in self.news_index else 0 for i in nids]

    def pad_to_fix_len(self, x, fix_length):
        pad_x = x[:fix_length] + [0] * (fix_length - len(x))
        mask = [1] * min(fix_length, len(x)) + [0] * max(0, fix_length - len(x))
        return pad_x, mask

    def parser_text(self, indices):
        title_text = self.news_combined['title_text'][indices]
        title_mask = self.news_combined['title_mask'][indices]
        body_text = self.news_combined['body_text'][indices]
        body_mask = self.news_combined['body_mask'][indices]
        category = self.news_combined['category'][indices]
        sub_category = self.news_combined['sub_category'][indices]

        title_text = torch.LongTensor(title_text).cuda(self.device)
        title_mask = torch.LongTensor(title_mask).cuda(self.device)
        body_text = torch.LongTensor(body_text).cuda(self.device)
        body_mask = torch.LongTensor(body_mask).cuda(self.device)
        category = torch.LongTensor(category).cuda(self.device)
        sub_category = torch.LongTensor(sub_category).cuda(self.device)

        return title_text, title_mask, body_text, body_mask, category, sub_category

    def _process(self):
        pass

    def __getitem__(self, item):
        pass

    def __len__(self):
        return len(self.behaviors)

class DatasetTrain(MindDataset):
    def __init__(self,
                 data_dir,
                 args,
                 news_index,
                 news_combined,
                 word_dict):
        super().__init__(data_dir, args, news_index, news_combined, word_dict)

    def _process(self):
        examples = []

        with open(os.path.join(self.data_dir, 'behaviors.tsv'), 'r', encoding='utf-8') as behavior_file:
            for behavior_index, line in enumerate(behavior_file):
                impression_ID, user_ID, time, history, impressions = line.split('\t')

                click_impressions = []
                non_click_impressions = []
                for impression in impressions.strip().split(' '):
                    if impression[-2:] == '-1':
                        click_impressions.append(impression[:-2])
                    else:
                        non_click_impressions.append(impression[:-2])

                if len(history) != 0:
                    history = history.strip().split(' ')
                    user_history = list((history[-self.user_log_length:]))

                    examples.append(
                        [user_ID, user_history, click_impressions, non_click_impressions])
            return examples

    def __getitem__(self, item):

        label = 0
        user_idx, user_history, click_impressions, non_click_impressions = self.behaviors[item]

        click_docs, log_mask = self.pad_to_fix_len(self.trans_to_nindex(user_history),
                                                   self.user_log_length)

        sess_pos = self.trans_to_nindex(click_impressions)
        sess_neg = self.trans_to_nindex(non_click_impressions)

        if len(sess_pos) > 0:
            sess_pos = random.choices(sess_pos, k=1)

        if len(sess_neg) > 0:
            neg_index = news_sample(list(range(len(sess_neg))), self.npratio)
            sam_negs = [sess_neg[i] for i in neg_index]
        else:
            sam_negs = [0] * self.npratio
        sample_news = sess_pos + sam_negs

        user_features = self.parser_text(click_docs)
        news_features = self.parser_text(sample_news)

        log_mask = torch.FloatTensor(log_mask).cuda(self.device)
        label = torch.tensor(0).cuda(self.device)
        # label = torch.zeros(1)
        return user_features, log_mask, news_features, label

class DatasetTest(MindDataset):
    def __init__(self,
                 data_dir,
                 args,
                 news_index,
                 news_combined,
                 word_dict,
                 mode='dev'):
        super().__init__(data_dir, args, news_index, news_combined, word_dict)
        self.mode = mode

    def _process(self):
        examples = []

        with open(os.path.join(self.data_dir, 'behaviors.tsv'), 'r', encoding='utf-8') as behavior_file:
            for behavior_index, line in enumerate(behavior_file):
                impression_ID, user_ID, time, history, impressions = line.split('\t')
                candidates = [article for article in impressions.strip().split(' ')]
                history = history.strip().split(' ')

                if len(history) != 0:
                    user_history = list((history[-self.user_log_length:]))
                    examples.append([user_ID, user_history, candidates])
                else:
                    user_history = [0] * self.user_log_length
                    examples.append([user_ID, user_history, candidates])

            return examples

    def __getitem__(self, item):

        user_idx, user_history, impressions = self.behaviors[item]

        sess = [i.split('-')[0] for i in impressions]
        if self.mode == 'dev':
            labels = [int(i.split('-')[1]) for i in impressions]
        else:
            labels = [0] * len(impressions)

        click_docs, log_mask = self.pad_to_fix_len(self.trans_to_nindex(user_history),
                                                   self.user_log_length)
        sample_news = self.trans_to_nindex(sess)

        user_features = self.parser_text(click_docs)
        news_features = self.parser_text(sample_news)

        log_mask = torch.FloatTensor(log_mask).cuda(self.device)

        label = torch.tensor(labels).cuda(self.device)
        # label = torch.zeros(1)
        return user_features, log_mask, news_features, label


import xlrd

def run_shortest_distance(d):
    # Source: https://www.geeksforgeeks.org/floyd-warshall-algorithm-dp-16/
    dist = d
    V = len(d)
    global nex

    for i in range(V):
        for j in range(V):
            nex[i][j] = j

    print("Started run.")
    for k in range(V):
        for i in range(V):
            for j in range(V):
                possible = dist[i][k]+ dist[k][j]
                if possible < dist[i][j]:
                    dist[i][j] = possible
                    nex[i][j] = nex[i][k]

    print("Finished run.")
    return nex, dist

def get_path(i, j):
    path = [i]
    while i!=j:
        print("->",i,j,path)
        i = nex[i][j]
        print("****",i,j,path)
        if i in path:
            if j not in path:
                path.append(j)
            break
        path.append(i)
    return path

def initialize_next(d):
    nex = []
    t = []
    for i in range(d):
        t.append([])
    for i in range(d):
        nex.append(t)
    return nex

if __name__ == "__main__":
    try:
        sheet = xlrd.open_workbook(".\Honors Research Data.xlsx").sheet_by_index(0)
        print("Sheet imported.")
    except:
        print("Error! Cannot open sheet.")

    d = []

    for i in range(1, sheet.nrows):
        row = []
        for j in range(1, sheet.ncols):
            val = sheet.cell_value(j,i)
            if val == '':
                val = 9999
            row.append(val)
        d.append(row)
    print("Data read.")

    nex = initialize_next(len(d))

    if len(d) == 0:
        print("Error! Dataset empty.")
    else:
        # shortest distance between points
        ans = run_shortest_distance(d)
        # shortest paths


##猜指定数字
##num=input('请输入数字')
##abc=int(num)
##while abc!=9:
##    num=input('猜错了，请重新输入吧：')
##    abc=int(num)
##    if abc>9:
##            print('哥，大了大了')
##    else:
##        if abc<9:
##                print('哥，小了小了')
##        else:
##                print('你是小甲鱼心里的蛔虫嘛');print('猜对了也没有奖励')
##print('游戏结束')

##随机猜数字
##import random
##num=random.randint(1,10) #输入随机函数
##num1=input('请输入数字吧：')
##guess=0
##while guess!=num :
##    num1=input('猜错啦，请重新输入吧：') #1
##    while not num1.isdigit(): #这个修改，可以提示如果输入的不是数字
##        num1=input('格式输入错误')
##    #num1=input('猜错啦，请重新输入吧：') #2
##    #注意#1 #2，这两个语句的位置。#2位置等于跳过了判断字母的过程，所以这里如果再出现字母，则会报错，而#1语句则不会出现问题
##    guess=int(num1)
##    if guess >num:
##        print('哥，太大了')
##    else:
##        if guess<num:
##            print('哥，小了小了')
##        else:
##            print('猜对了，哈哈')
##print('游戏结束')

##随机猜数字，且只给三次机会
import random
times=3
secret=random.randint(1,10)
print('猜数字')
print('猜猜我心里想的是什么数字？',end='')
guess=0
while (guess != secret) and (times>0):
    temp=input()
    while not temp.isdigit():
        temp=input('输入格式错误：')
    guess=int(temp)
    times=times-1 #每输入一次，可用机会减一
    if guess==secret:
        print('尼玛，真牛逼')
    else:
        if guess>secret:
            print('哥，大了大了')
        else:
            print('哥，小了小了')
        if times>0:   #之前失败的原因是，不知道时间也有一个判断语句
            print('再试一次吧：',end='')
        else:
            print('机会用完，退下吧')
print('game over')


import math

from PIL import ImageFont

def vrf(clv, dsc, dt):
	if clv not in dt:
		raise Exception(f"Se esperaba '{clv}' ({dsc}) en datos de entrada")
	return dt[clv]

def str_num(num):
	## convierte un numero en texto
	pdc, pen = math.modf(num)
	if pdc == 0:
		return str(int(pen))
	return str(num)

def wtxt(txt, px):
	h = math.ceil(px)
	return ImageFont.truetype('arialbd.ttf', h).getlength(txt)

def divgrf(ndiv, vmin, vmax):
	#
	# print(f"vmin = {vmin}  vmax = {vmax}")
	try:
		dim = vmax - vmin
		divx = dim / ndiv
		#
		mag = math.pow(10.0, math.floor(math.log10(divx)))
		Pmag = int(divx / mag + 0.5)
		#
		if Pmag > 5:
			Pmag = 10.0
		elif Pmag > 2.0:
			Pmag = 5.0
		elif Pmag > 1.0:
			Pmag = 2.0
		#
		dg = mag * Pmag
		vmn = round(dg * math.floor(vmin / dg), 5)
		vmx = round(dg * math.ceil(vmax / dg), 5)

		# return {'dg':dg, 'vmn':vmn, 'vmx':vmx}
		return {'dg': dg, 'vmng': vmn, 'vmxg': vmx, 'vmn': vmin, 'vmx': vmax}
	except Exception as e:
		err = f"ERROR(divgrf): {e} vmin = {vmin}  vmax = {vmax} ndiv = {ndiv}"
		print(err)
		raise Exception(err)

def g_marco(dt):
	# -- estilo de borde -->>
	e = 1
	cb = 'black'
	# -- estilo de fondo -->>
	cf = 'none'
	op = ''
	#
	if 'marco' in dt:
		jx = dt['marco']
		if 'borde' in jx:
			o = jx['borde']
			if 'e' in o:
				e = o['e']
			if 'c' in o:
				cb = o['c']
		if 'fondo' in jx:
			o = jx['fondo']
			if 'c' in o:
				cf = o['c']
			if 't' in o:
				op = f"opacity:{o['t']};"
	ebr = f"fill:none;stroke:{cb};stroke-width:{e}px;"
	efn = f"stroke:none;fill:{cf};{op}"
	return ebr, efn

def g_fondo(**cv):
	esp = 0
	# -- estilo de linea -- #
	eLn = ""
	k = 'borde'
	if k in cv:
		o = cv[k]
		# -- color de linea -->
		c = 'none'
		if 'c' in o:
			c = o['c']
		eLn += f"stroke:{c};"
		# -- espesor de linea -->
		e = 1
		if 'e' in o:
			e = o['e']
		eLn += f"stroke-width:{e}px;"
		esp = e
	# -- estilo de área -- #
	eAr = ""
	k = 'fondo'
	if k in cv:
		o = cv[k]
		# -- color del area -->
		c = 'none'
		if 'c' in o:
			c = o['c']
		eAr += f"fill:{c};"
		# -- transparencia -->
		if 't' in o:
			eAr += f"opacity:{o['t']}"
	#
	return esp, eLn, eAr

def g_rotulo(h, o):
	OK = True
	if 'ok' in o:
		OK = o['ok']
	# -- rótulo -->
	txt = ""
	if 'txt' in o:
		txt = o['txt']
	# -- estilo -->>
	sAl = "text-anchor:middle;dominant-baseline:middle;"
	stl = "stroke:none;"
	# -- color -->
	if 'c' in o:
		stl += f"fill:{o['c']};"
	# -- nombre tipo -->
	if 'f' in o:
		stl += f"font-family:{o['f']};"
	# -- tamaño tipo -->
	if 'h' in o:
		h = o['h']
	stl += f"font-size:{h}px;"
	# -- negrita -->
	if 'n' in o:
		if o['n']:
			stl += "font-weight:bold;"
	# -- itálica -->
	if 'i' in o:
		if o['i']:
			stl += "font-style:italic;"
	#
	stl += sAl
	#
	return {'ok': OK, 'h': h, 'txt': txt, 'stl': stl}

def grf_xy_limites(dt):
	lerr = []  # lista de errores
	"""| valores extremos a partir de series |"""
	jm = {'xmn': -1, 'xmx': 1, 'ymn': -1, 'ymx': 1}
	if 'series' in dt:
		lmnx = []
		lmxx = []
		lmny = []
		lmxy = []
		for i, jx in enumerate(dt['series']):
			if 'id' not in jx:
				jx['id'] = f"Serie {i + 1}"
			if 'vx' not in jx:
				lerr.append(f"No se ha indicado 'vx' (valores x)  en la serie#{i + 1}")
			if 'vy' not in jx:
				lerr.append(f"No se ha indicado 'vy' (valores y)  en la serie#{i + 1}")
			vx = jx['vx']
			vy = jx['vy']
			nx = len(vx)
			ny = len(vy)
			if nx != ny:
				id = jx['id']
				err = f"No coinciden las dimensiones de 'vx'({nx}) y 'vy'({ny}) en '{id}'"
				lerr.append(err)
			#
			jx['n'] = nx
			lmnx.append(min(vx))
			lmxx.append(max(vx))
			lmny.append(min(vy))
			lmxy.append(max(vy))
		#
		jm['xmn'] = min(lmnx)
		jm['xmx'] = max(lmxx)
		jm['ymn'] = min(lmny)
		jm['ymx'] = max(lmxy)
		#
		if jm['xmx'] == jm['xmn']:
			jm['xmx'] += 1.0
			jm['xmn'] -= 1.0
		if jm['ymx'] == jm['ymn']:
			jm['ymx'] += 1.0
			jm['ymn'] -= 1.0
	else:
		pass
	return jm, lerr

def grf_xy_stl(ls):
	clr = ['red', 'green', 'blue', 'gold', 'orange', 'magenta', 'purple']
	n = len(clr)
	for i, o in enumerate(ls):
		# -- nombre de serie -->>
		if 'id' not in o:
			o['id'] = f"Serie #{i+1}"
		# -- color de línea -->>
		c = clr[i % n]
		if 'c' in o:
			c = o['c']
		# -- espesor de línea -->>
		e = 1
		if 'e' in o:
			e = o['e']
		else:
			o['e'] = e
		# -- tipo de lineas -->>

		o['stl'] = f"fill:none;stroke-linejoin:round;stroke:{c};stroke-width:{e};"
		o['over'] = f"resaltar(this,{2 * o['e']})"
		o['out'] = f"resaltar(this,{o['e']})"
		# onmouseover="evt.target.setAttribute('stroke-width', '3');"
		# onmouseout="evt.target.setAttribute('stroke-width', '1');"

def stl_linea(js):
	# -- color de línea -->
	cl = 'black'
	k = 'cl'
	if k in js:
		cl = js[k]
	stl = f"stroke:{cl};"
	# -- espesor de línea -->
	e = 1
	k = 'e'
	if k in js:
		e = js[k]
		if e != 1:
			stl += f"stroke-width:{e}px;"
	# stroke-dasharray:
	k = 'pl'
	if k in js:
		pl = js[k]
		stl += f"stroke-dasharray:{pl};"
	#
	return stl

def stl_fondo(js):
	# -- color de fondo -->>
	cf = 'white'
	k = 'cf'
	if k in js:
		cf = js[k]
	stl = f"stroke:none;fill:{cf};"
	# - trasparencia -->>
	k = 't'
	if k in js:
		t = js[k]
		stl += f"opacity:{t};"

	return stl

def stl_divxy(js):
	# -- color de línea -->
	cl = 'black'
	k = 'c'
	if k in js:
		cl = js[k]
	stl = f"stroke:{cl};"
	# -- espesor de línea -->
	e = 1
	k = 'e'
	if k in js:
		e = js[k]
		if e != 1:
			stl += f"stroke-width:{e}px;"
	# stroke-dasharray:
	k = 'p'
	if k in js:
		pl = js[k]
		stl += f"stroke-dasharray:{pl};"
	#
	return stl


def divided_difference(x_data, y_data):
    """计算牛顿插值法中的差商"""
    n = len(x_data)
    f = []
    for i in range(n):
        f.append(y_data[i])
    for j in range(1, n):
        for i in range(n-1, j-1, -1):
            f[i] = (f[i] - f[i-1]) / (x_data[i] - x_data[i-j])
    return f

def newton_interpolation(x_data, y_data, x):
    """计算牛顿插值多项式在 x 处的值"""
    n = len(x_data)
    f = divided_difference(x_data, y_data)
    newton_poly = f[0]
    for i in range(1, n):
        term = f[i]
        for j in range(i):
            term *= (x - x_data[j])
        newton_poly += term
    return newton_poly

if __name__ == "main":
    x_data = [0, 0.1, 0.2, 0.3, 0.4]
    y_data = [0.5, 0.5398, 0.5793, 0.6179, 0.6554]

    # 待插值的 x 值
    x = 0.13

    # 调用牛顿插值函数计算插值结果
    result = newton_interpolation(x_data, y_data, x)
    print("在 x = {:.2f} 处的牛顿插值结果为: {:.4f}".format(x, result))

数值计算方法/牛顿插值法.py


# This is a script to run the data scraping process from the SEC API.

from datetime import datetime
import os

from sec_api import QueryApi, ExtractorApi
from dotenv import load_dotenv
import csv
from codes import CODES

load_dotenv()

# environment variables
SEC_API_KEY = os.environ.get('sec-api-key')
COMPANIES = []
SECTORS = []

def extract_meta():
    # the endpoints of the sec-api we will be using
    queryApi = QueryApi(api_key=SEC_API_KEY)

    # using CSV writer, open document for writing
    with open('metadata.csv', 'w', encoding='UTF8', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(['Ticker', 'Company Name', 'Sector', 'Date', 'Incorporation Region', 'Filing Link'])
        for i in range(len(COMPANIES)):
            query = {
                'query': {'query_string': {
                    'query': f'ticker:{COMPANIES[i]} AND formType:\"10-K\"'
                }},
                'from': '0',
                'size': '1',
                'sort': [{'filedAt': {'order': 'desc'}}]
            }
            filings = queryApi.get_filings(query)
            try:
                country = filings['filings'][0]['entities'][0]['stateOfIncorporation']
            except:
                country = "XX"
            date = datetime.fromisoformat(filings['filings'][0]['filedAt']).strftime('%Y-%m-%d')
            link = filings['filings'][0]['linkToFilingDetails']
            company_name = filings['filings'][0]['companyName']
            data = [COMPANIES[i], company_name, SECTORS[i], date, CODES[country], link]
            writer.writerow(data)
            print(f'extracted data for: {company_name}')

# Populates the list of companies using the file provided of company tickers
def populate_companies():
    tickers = open('../data-scripts/companies.txt', 'r')
    for line in tickers:
        comp_str = line.split(",")
        COMPANIES.append(comp_str[0].strip('"'))
        SECTORS.append(comp_str[4].strip('"'))

if __name__ == '__main__':
    populate_companies()
    extract_meta()


import csv
import datetime

def to_date_object(date_string): return datetime.datetime.strptime(
    date_string, '%d.%m.%Y')

def order_date(x): return x[1]

def parse_csv_into_rows(file_path):
    with open(file_path, 'r') as file:
        txt = file.read()
        rows_raw = txt.split('\n')
        rows_cleansed = [row.split(',') for row in rows_raw[1:-1]]
        return rows_cleansed

def extract_inserts(cleansed_rows):
    insert_rows = [row[0:-1] for row in cleansed_rows if row[3] == 'I']
    return insert_rows

def extract_updates(cleansed_rows):
    update_rows = [row[0:-1] for row in cleansed_rows if row[3] == 'U']
    return update_rows

def get_most_recent_updates(update_rows):
    ids = get_ids(update_rows)
    idsGrouped = {}
    for row in cleansed_rows:
        # check if the first element is in the dictionary
        if row[0] in idsGrouped:
            # if yes, append the second element to the list
            idsGrouped[row[0]].append((row))
        else:
            # if not, create a new list with the second element
            idsGrouped[row[0]] = [(row)]

    for id in idsGrouped:
        dts = []
        for row in idsGrouped[id]:
            date_dt = to_date_object(row[1])
            row[1] = date_dt

        idsGrouped[id] = sorted(
            idsGrouped[id], key=order_date, reverse=True)[0]

    return idsGrouped

def extract_deletes(cleansed_rows):
    delete_rows = [row[0:-1] for row in cleansed_rows if row[3] == 'D']
    return delete_rows

def append_insert_to_current_customers(file_path, insert_rows):
    with open(file_path, 'a') as file:
        writer = csv.writer(file)
        [writer.writerow(row) for row in insert_rows]

def get_ids(rows):
    ids = [row[0] for row in rows]
    return ids

def delete_row_from_customers_current(file_path, delete_rows_list):
    # open the csv file in read mode
    with open(file_path, 'r') as readFile:
        reader = csv.reader(readFile)
        lines = list(reader)

    # open the csv file in write mode
    with open(file_path, 'w') as writeFile:
        writer = csv.writer(writeFile)
        for line in lines:
            id = line[0]
            # check the condition and write to the file accordingly
            ids = get_ids(delete_rows_list)
            if id in ids:
                continue
            else:
                writer.writerow(line)

def transform_date_to_str(row):
    row[1] = row[1].strftime('%d.%m.%Y')
    return row

def update_row_from_customers_current(file_path, update_rows_dict):
    # open the csv file in read mode
    with open(file_path, 'r') as readFile:
        reader = csv.reader(readFile)
        lines = list(reader)

    # open the csv file in write mode
    with open(file_path, 'w') as writeFile:
        writer = csv.writer(writeFile)
        for index, line in enumerate(lines):
            if index == 0:
                writer.writerow(['CUSTOMER_ID', 'UPDATE_DATE', 'LOCATION'])
                continue
            id = line[0]
            # check the condition and write to the file accordingly
            if id in update_rows_dict:

                row = transform_date_to_str(update_rows_dict[id])[0:-1]
                curent_str_date = line[1]
                current_dt_date = to_date_object(curent_str_date)
                update_row_str_date = update_rows_dict[id][1]
                update_row_dt_date = to_date_object(update_row_str_date)
                if update_row_dt_date > current_dt_date:
                    writer.writerow(row)
                else:
                    writer.writerow(line)
            else:
                writer.writerow(line)

if __name__ == '__main__':
    cleansed_rows = parse_csv_into_rows('data/customers_update.csv')
    rows_to_insert = extract_inserts(cleansed_rows)
    rows_to_delete = extract_deletes(cleansed_rows)

    update_rows = extract_updates(cleansed_rows)
    most_recent_updates_by_id = get_most_recent_updates(update_rows)

    append_insert_to_current_customers(
        'data/customers_current.csv', rows_to_insert)
    update_row_from_customers_current(
        'data/customers_current.csv', most_recent_updates_by_id)
    delete_row_from_customers_current(
        'data/customers_current.csv', rows_to_delete)


#code for pressing of the “*” key:

from gpiozero import Button, LED, Buzzer
from time import sleep

col1 = Button(3)
col2 = Button(21)
col3 = Button(5)
row1 = LED(2)
row2 = LED(7)
row3 = LED(6)
row4 = LED(4)

def star_code():
    row1.on()
    row2.on()
    row3.on()
    row4.off()
    while True:
        if col1.is_pressed:
            print(" * key is pressed")


import spacy
import nltk

class NEREntityExtractor:

    def __init__(self, model_folder):
        self.model = spacy.load(model_folder)

    def find_ner_entities(self, articles_df, columns_to_process=["abstract"], column_name="column_with_ner", entity_labels=[]):
        articles_df[column_name] = ""
        for i in range(len(articles_df)):
            result_set = set()
            for column in columns_to_process:
                for sentence in nltk.sent_tokenize(articles_df[column].values[i]):
                    for r in self.model(sentence).ents:
                        if not entity_labels or r.label_ in entity_labels:
                            result_set.add(r.text.strip())
            articles_df[column_name].values[i] = list(result_set)
            if i % 3000 == 0:
                print("Processed %d rows" % i)
        return articles_df


"""
This problem was asked by Dropbox.

Given a list of words, determine whether the words can be chained to form a circle.
A word X can be placed in front of another word Y in a circle if the last character
of X is same as the first character of Y.

For example, the words ['chair', 'height', 'racket', 'touch', 'tunic'] can form the
following circle: chair --> racket --> touch --> height --> tunic --> chair.
"""

def build_word_graph(word_list):
    graph = {}
    for w in word_list:
        first = w[0]
        if first not in graph:
            graph[first] = set()
        graph[first].add(w)
    return graph

def is_valid(current_char, remaining_set, current_circle, word_graph):
    # Base cases
    if not remaining_set and current_char == current_circle[0][0]:
        return True

    if current_char not in word_graph or not word_graph[current_char]:
        return False

    # Recur over conditions of multiple valid word options
    for word in word_graph[current_char]:
        if word not in remaining_set:
            continue
        remaining_set.remove(word)
        current_circle.append(word)
        next_char = word[-1]
        if not is_valid(next_char, remaining_set, current_circle, word_graph):
            remaining_set.add(word)
            current_circle = current_circle[:-1]
        else:
            return True
    return False

def circular_words(word_list):
    graph = build_word_graph(word_list)
    word_set = set(word_list)
    for word in word_set:
        curr_char = word[-1]
        if is_valid(curr_char, word_set - {word}, [word], graph):
            return True

    return False

test_1 = ['chair', 'height', 'racket', 'touch', 'tunic']
test_2 = ['chair', 'height', 'racket', 'perfect', 'touch', 'tunic']
test_3 = ['abc', 'cb', 'bca']

assert circular_words(test_1)
assert not circular_words(test_2)
assert circular_words(test_3)


import os
import requests
import json
import time
from uuid import uuid4

license = 'GZEQhdOCI7a0VbikezFdz1WGlfhKZQKy4OrCLgsb'
authentication = 'Basic enJiaTl3N253eGhtdHZ3NXE5Y2RxcjZsY3NsY2pwMjQzcWRnMng4Y2w4OTJ2OXJwOkR7cjpqaypRSEgtMjpIZGRjNzUpJS19KTFHMF9fXCotIykzX0xoaF9+SFxmTjdQZQ=='

headers = {
   'Content-Type':'application/json',
   'x-spdra-license':license,
   'x-spdra-authentication':authentication
}

https_url = 'http://www.voiptroubleshooter.com/open_speech/american/OSR_us_000_0010_8k.wav'

def get_upload_destination():
	wflurl =  'https://spdra.deloitterisk.cloud/v1/upload-destination'
	resp = requests.post(wflurl, headers=headers)
	return resp.json()

def upload_file(filepath, url):
	file_size = os.path.getsize(filepath)
	with open(filepath, "rb") as f:
		data = f.read()
	headers = {
		'Content-Length': str(file_size),
	}
	resp = requests.put(url, data=data, headers=headers)
	return resp.status_code

def init_transcription(fileUri=https_url, protocol="https"):
	wflurl =  'https://spdra.deloitterisk.cloud/v1/job/workflow/transcription_only/'
	payload = {'correlationId': str(uuid4()),'location': {'fileUri': fileUri,'protocol': protocol}}
	data = json.dumps(payload)
	resp = requests.post(wflurl, data=data, headers=headers)
	return resp.json()

def upload_file_and_init_transcription(filepath):
	resp_urls = get_upload_destination()
	uploadUri = resp_urls['uploadUri']
	processingUri = resp_urls['processingUri']

	resp_upload = upload_file(filepath=filepath, url=uploadUri)
	assert resp_upload == 200

	return init_transcription(fileUri=processingUri, protocol="spdra")

def poll_transcription(jobID):
	url =  'https://spdra.deloitterisk.cloud/v1/job/'+jobID
	resp = requests.get(url, headers=headers)
	return resp.json()

if __name__ == "__main__":
	jobId = upload_file_and_init_transcription('/Users/rman/Documents/BEAT/audio/voice_recognition/OSR_us_000_0040_8k.wav')['jobId']
	time.sleep(2)
	result = poll_transcription(jobId)
	while result == {'statusCode': 202, 'message': 'Job not yet finished, try again later.'}:
		result = poll_transcription(jobId)
		print(result)
		time.sleep(30)


# -*- coding: utf-8 -*-
"""
Created on Fri May 15 17:54:55 2020

@author: bdwoo
"""

class Node:
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def __str__(self):
        return str(self.data)

    #accessors
    def getLeft(self):
        return self.left
    def getRight(self):
        return self.right
    def getData(self):
        return self.data

    #mutators
    def setLeft(self, left):
        self.left = left
    def setRight(self, right):
        self.right = right
    def setData(self, data):
        self.data = data

class BsTree:
    def __init__(self):
        self.root = None

    #Modified level order, insert None into queue as placeholder
    #Track number in row to know when to make a newline
    #If a row is all None, then it is the end of the tree
    #Still need number of levels to control spacing
    def __str__(self):
        q = []
        out = ''
        temp = ''
        n = 1   #Tracks how many to print on each level

        if self.root is not None:
            q.append(self.root)

        level = self.findLevels()

        while True:
            j = False #If a row is all None, then it is the end of the tree
            temp = '' #Temporary storage for this row. Used to avoid printing empty final row

            temp += ' '*level #Add spacing for each level

            for i in range(n):
                cur = q.pop(0)

                #Not a placeholder
                if cur is not None:
                    j = True    #Note this is not an empty row

                    temp += str(cur.data) + ' '*(level)

                    #Add children to queue
                    #We want None placeholders, so don't check for None
                    q.append(cur.left)
                    q.append(cur.right)

                else:
                    temp += ' ' + ' '*(level) #None is a placeholder, print a space

                    #If this is None, add two None children as placeholders
                    q.append(None)
                    q.append(None)

            temp += '\n'

            #If it is an empty row, we are at the end of the tree
            if j:
                out += temp
            else:
                break

            n*=2 #increase number of elements in row
            level-=1 #Decrement the level
        return out

    #Mutators
    def insert(self, data):
        if self.root is None:
            self.root = Node(data)
        else:
            self.insertR(self.root, data)
    def insertR(self, cur, data):
        if data < cur.data:
            if cur.left is None:
                cur.left = Node(data)
            else:
                self.insertR(cur.left, data)
        elif data > cur.data:
            if cur.right is None:
                cur.right = Node(data)
            else:
                self.insertR(cur.right, data)

    #Recursively search
    #def delete(self, data):

    #Accessors
    def search(self, data):
        return self.__searchR(self.root, data)
    def __searchR(self, cur, data):
        if data < cur.data and cur.left is not None:
            self.__searchR(cur.left, data)
        elif data > cur.data and cur.right is not None:
            self.__searchR(cur.right, data)
        elif data == cur.data:
            return cur

    def levelOrder(self):
        q = []

        if self.root is not None:
            q.append(self.root)

        while len(q) > 0:
            cur = q.pop(0)

            if cur.left is not None:
                q.append(cur.left)
            if cur.right is not None:
                q.append(cur.right)

            print(str(cur.data))

    def preOrder(self):
        self.__preOrderR(self.root)
    def __preOrderR(self, cur):
        print(cur.data)
        if cur.left is not None:
            self.__preOrderR(cur.left)
        if cur.right is not None:
            self.__preOrderR(cur.right)

    def inOrder(self):
        self.__inOrderR(self.root)
    def __inOrderR(self, cur):
        if cur.left is not None:
            self.__inOrderR(cur.left)
        print(cur.data)
        if cur.right is not None:
            self.__inOrderR(cur.right)

    def postOrder(self):
        self.__postOrderR(self.root)
    def __postOrderR(self, cur):
        if cur.left is not None:
            self.__postOrderR(cur.left)
        if cur.right is not None:
            self.__postOrderR(cur.right)
        print(cur.data)

    def findLevels(self):
        if self.root is not None:
            return self.__findLevelsR(self.root, 1)
        else:
            return 0
    def __findLevelsR(self, cur, level):
        maxLevel = level
        if cur.left is not None:
            maxLevel = max(maxLevel, self.__findLevelsR(cur.left, level+1))
        if cur.right is not None:
            maxLevel = max(maxLevel, self.__findLevelsR(cur.right, level+1))
        return maxLevel

tree = BsTree()
tree.insert(5)
tree.insert(1)
tree.insert(0)
tree.insert(2)
tree.insert(7)
tree.insert(6)
tree.insert(8)
print(tree)
print(tree.findLevels())
print(tree.inOrder())


from tkinter import*

class Plotter(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.pack()

        self.x, self.y = 50, 75

        self.canvas = Canvas(self, height = 100, width=150, relief=SUNKEN, borderwidth=3)
        self.canvas.pack(side=LEFT)

        bt1 = Button(self, text='up', command=lambda: self.move(0, -10))
        bt1.pack(side=TOP)

        bt2 = Button(self, text='left', command=lambda: self.move(-10, 0))
        bt2.pack(side=BOTTOM)

        bt3 = Button(self, text='right', command=lambda: self.move(10, 0))
        bt3.pack(side=BOTTOM)

        bt4 = Button(self, text='down', command=lambda: self.move(0, 10))
        bt4.pack(side=LEFT)

    def move(self, dx, dy):
        self.canvas.create_line(self.x, self.y, self.x+dx, self.y+dy)
        self.x += dx
        self.y += dy

top = Tk()
plot = Plotter(top)
plot.pack()

top.mainloop()


# -*- coding: utf-8 -*-
"""
Created on Thu Nov 18 22:04:00 2021

@author: MBo
"""

import os
from MoquiManager import MoquiManager
from NymphManager import NymphManager
from DijMatrix import DijMatrix
from RTArrays import DoseMap, Structure
from time import time

class PlanAdaptation(object):
    '''
    Initialize by passing an instance of the "DicomPlan" class as the argument.
    '''
    def __init__(self, plan):

        self.plan = plan
        self.rtplan_file = plan.rtplan_file
        self.time_dij   = 0
        self.time_nymph = 0
        self.time_dose  = 0
        self.time_total = 0

    def run(self, image_file, output_dir, mask_file=None, dose_file=None, structures=None):
        '''
        Runs plan adaptation.
        Provide "dose_file" to mimic dose distribution.
        Provide "structures" to apply objectives based on contours.

        Args:
            image_file --> path to input image file (str)
            output_dir --> path to output dicom directory (str)
            mask_file --> path to input Dij mask file (str)
            dose_file --> path to input dose file to mimic (str)
            structures --> dictionary containing structures with the corresponding file paths (dict)
                           dictionary format: {structure_name : file_path}
        '''
        t1 = time()

        # Load arrays
        mask = Structure(mask_file) if mask_file is not None else None
        dose = DoseMap(dose_file) if dose_file is not None else None

        # Run Dij calculation
        moqui_dij = MoquiManager(self.plan.machine_name)
        moqui_dij.run_simulation(output_dir, self.rtplan_file, 'dij',
                                 image_file = image_file,
                                 masks = [mask_file])
                                 # masks = None)

        # Load Dij matrix
        mask_indices = mask.voxel_indices if mask is not None else None
        dij_total = DijMatrix(npz_dir = output_dir, mask_indices = mask_indices)

        # Split Dij matrix based on beamlet subset
        self.plan.set_beamlet_subset(0.33, 1)
        self.plan.exclude_zero_weighted_beamlets()
        included_beamlets = self.plan.optimized_beamlets
        excluded_beamlets = self.plan.fixed_beamlets
        dij_included = DijMatrix(csr_matrix = dij_total.csr_matrix[included_beamlets])
        dij_excluded = DijMatrix(csr_matrix = dij_total.csr_matrix[excluded_beamlets])
        preexisting_dose = dij_excluded.get_dose_array_1D()

        # Set optimization parameters --> separate function
        self.nymph = NymphManager(dij_included, preexisting_dose)
        self.nymph_set_objectives(mask, dose, structures)
        self.nymph.run_optimization()

        # Adapt beamlets weights
        self.beamlet_scales = self.nymph.beamlet_scales
        self.plan.adapt_weights(self.beamlet_scales)
        self.plan.write_tramps(output_dir)

        # Run dose calculation
        moqui_dose = MoquiManager(self.plan.machine_name)
        moqui_dose.run_simulation(output_dir, self.rtplan_file, 'dose',
                                  image_file = image_file,
                                  tramps_dir = output_dir,
                                  random_seed = 500)
        t2 = time()

        self.time_dij   = moqui_dij.sim_time
        self.time_nymph = self.nymph.opt_time
        self.time_dose  = moqui_dose.sim_time
        self.time_total = t2-t1
        self.log_dij  = moqui_dij.log
        self.log_opt  = self.nymph.log
        self.log_dose = moqui_dose.log
        self.write_log_file(output_dir)

    def nymph_set_objectives(self, mask, dose, structures):
        '''
        Separate function to set Nymph's objectives.
        '''
        if dose is not None:
            self.nymph.mimic_dose(dose.get_array_in_mask(mask), weight = 1)

        if structures is not None:
            HR_CTV       = Structure(structures['HR_CTV']).get_indices_in_mask(mask)
            LR_CTV       = Structure(structures['LR_CTV_uniform']).get_indices_in_mask(mask)
            # larynx       = Structure(structures['Larynx']).get_indices_in_mask(mask)
            # parotid_L    = Structure(structures['Parotid_L']).get_indices_in_mask(mask)
            # parotid_R    = Structure(structures['Parotid_R']).get_indices_in_mask(mask)
            # constrictors = Structure(structures['Constrictors']).get_indices_in_mask(mask)
            # spinal_cord  = Structure(structures['SpinalCord']).get_indices_in_mask(mask)
            # brainstem    = Structure(structures['Brainstem']).get_indices_in_mask(mask)
            # shell        = Structure(structures['conformality_shell']).get_indices_in_mask(mask)
            #
            # Adding objectives
            self.nymph.set_mean_dose(HR_CTV, 70, label = 'HR_CTV', weight = 1/2)
            self.nymph.set_mean_dose(LR_CTV, 57, label = 'LR_CTV', weight = 1/2)
            # self.nymph.add_dose_function(3, 0, 0.01, None, 0, shell, label = 'conformality_shell')
            # self.nymph.add_dose_function(1, 0, 0.01, None, 0, shell, label = 'conformality_shell')

    def write_log_file(self, output_dir):
        separator = '-'*200
        self.log = 'Plan adaptation overview'
        self.log += '\ntime total = {} sec ≈ {} min'.format(self.time_total, round(self.time_total/60, 2))
        self.log += self.plan.beamlet_subset_info
        self.log += self.plan.adaptation_info
        self.log += '\n\n'+separator+'\n'
        self.log += '\n(1) Moqui dij calculation'
        self.log += '\ntime = {} sec ≈ {} min\n'.format(self.time_dij, round(self.time_dij/60, 2))
        self.log += self.log_dij
        self.log += '\n'+separator+'\n'
        self.log += '\n(2) Nymph optimization'
        self.log += '\ntime = {} sec ≈ {} min\n'.format(self.time_nymph, round(self.time_nymph/60, 2))
        self.log += self.log_opt
        self.log += '\n'+separator+'\n'
        self.log += '\n(3) Moqui dose calculation'
        self.log += '\ntime = {} sec ≈ {} min\n'.format(self.time_dose, round(self.time_dose/60, 2))
        self.log += self.log_dose
        log_path = os.path.join(output_dir, 'log.txt')
        with open(log_path, 'w') as f:
            f.write(self.log)


import re
def names():
    simple_string = """Amy is 5 years old, and her sister Mary is 2 years old.
    Ruth and Peter, their parents, have 3 kids."""

    # YOUR CODE HERE
#     raise NotImplementedError()
    pattern = "[A-Z][a-z]*"
    return re.findall(pattern, simple_string)

assert len(names()) == 4, "There are four names in the simple_string"


#########HW2
import requests
import folium
import json
import pandas as pd
import numpy as np
from pymongo import MongoClient
import folium
from IPython.display import HTML
from folium.plugins import HeatMap
import matplotlib.pyplot as plt

client = MongoClient('localhost', 27017)
db = client.LA
LA_collection = db.LA_collection

params = "TrafficID,IntersectionID,lat,lon,intersection,Shape,TOOLTIP"

type(params)
params == "TrafficID,IntersectionID,lat,lon,intersection,Shape,TOOLTIP"
QueryURL = "https://maps.lacity.org/lahub/rest/services/LADOT/MapServer/21/query?where=1%3D1&outFields="+params+"&outSR=4326&f=json"
response = requests.get(QueryURL)
data = response.json()

len(data)

for keys in data:
    print(type(data[keys]))
features = data['features']
len(data) #7
type(data) # dictionary
for collision in features:
    try:
        LA_collection.insert_one(collision)
    except:
        pass

find_coll = LA_collection.find()

array = list(find_coll)
array
df_list = []

for i in array:
    df_list.append(i['attributes'])
df_list

df = pd.DataFrame(df_list)
df.info()

df.size #size = number of total data points
df.shape #shape == observations then columns

df.columns #put the useful variables into the columns

df = df.drop(columns='TOOLTIP')

df = df.rename(columns = lambda col: col.replace(" ", ""))
df['intersection'] = df['intersection'].apply(lambda x: x.upper())
df.dtypes #change intersectionID to object/str

#df.IntersectionID = df.astype({'IntersectionID': 'float64'}).dtypes

df.isnull().sum(axis=0) # many intersection IDs missing
df1 = df.copy()
df1.replace(' ', np.nan, inplace=True)

df1.replace('', np.nan, inplace = True)

# shows all the blanks
df2.loc[df['intersection'] == ' ']

df2 = df.copy()

df2 = df2[df2.intersection != ' ']

#got rid of the blanks

df2.loc[df2['intersection'] == ' ']

print("These intersections have the most collisions \n")
print(df2['intersection'].value_counts()[df2['intersection'].value_counts()>2])
#find lat/lon where the 31 is?
calc = df2['intersection'].value_counts()[df2['intersection'].value_counts()>3].plot(kind='bar')
plt.xticks(rotation = 45)

lat_lon= df.groupby(['lat', 'lon']).size().reset_index(name='Freq')
print("These exact lats and lons have more than one collision \n")

print(lat_lon.loc[lat_lon['Freq'] > 1])

lat_lon_points = lat_lon[lat_lon['Freq'] > 1]
lat_lon_points = lat_lon_points[['lat', 'lon']] # two brackets access the data points

lat_lon_tuple = [tuple(x) for x in lat_lon_points.values]

#save in tuple for mapping later

lat.dtypes

lat = df.groupby(['lat']).size().reset_index(name='Freq')

#find the lattitudes with the most accidents
print("The lattitudes with more than 3 collisions \n")

print(lat[lat['Freq'] > 3])

lat_points = lat[lat['Freq'] > 3]

lat_lonMAP = folium.Map(location =(34.052235,-118.243683))

HeatMap(lat_lon_tuple, radius=13).add_to(lat_lonMAP)

lat_lonMAP.save('lat_lonMAP.html')

lon = df.groupby(['lon']).size().reset_index(name='Freq')

print("The longitudes with more than 3 collisions \n")
print(lon[lon['Freq'] > 3])

#next plotting these areas based on lat and lon.

# makea small sample to plot points on map. 9000 + is too many
sample_points = df2.sample(n = 200)

#lat and lon come from latlong.net to be accurate

sample_map1 = folium.Map(location =(34.052235,-118.243683))

for i in range(0, len(sample_points)):
    folium.Marker([sample_points.iloc[i]['lat'], sample_points.iloc[i]['lon']], popup= sample_points.iloc[i]['intersection']).add_to(sample_map1)

sample_map1.save('sample.html')

coord1 = [ ]

#put coordinates from API data into list
#create LA map
#create heat map of the data

#make a list of tuples

for i in range(len(df2)):
    coord.append((df2.iloc[i]['lat'],df2.iloc[i]['lon']))

LA_collision_map = folium.Map(location=(34.052235,-118.243683))

HeatMap(coord,radius=13).add_to(LA_collision_map)

LA_collision_map.save('LA_collision_map1.html')


#a sudoku solver python program
"""Given a incomplete sudoku to the program
   and it will give out the complete sudoku as a result"""
"""The given sudoku solver will be in int mode and
    the space or the incomplete value contains empty """

class Solution:
    def __init__(self,sudoku):
        self.sudoku = sudoku

    #Function for checking if the sudoku is valid or not!
    def isValidSudoku(self):
        #condition to check if the sudoku contains 9 rows and 9 columns!
        if len(self.sudoku) != 9 or len(self.sudoku[0]) != 9:
            return False

        #Creating the set arr for checking the unique values in the rows, columns and 3X3 sub boxes!
        arr = set()

        #for checking if the value is present in rows or not.
        #if not then it returns False
        for row in range(len(self.sudoku)):
            for col in range(len(self.sudoku[0])):
                if self.sudoku[row][col] != ".":
                    if self.sudoku[row][col] in arr:
                        return False
                    else:
                        arr.add(self.sudoku[row][col])
            arr.clear()

        #clear the arr set for use checking in row wise
        arr.clear()

        #for checking if the values are unique in columns or not
        for col in range(len(self.sudoku[0])):
            for row in range(len(self.sudoku)):
                if self.sudoku[row][col] != '.':
                    if self.sudoku[row][col] in arr:
                        return False
                    else:
                        arr.add(self.sudoku[row][col])
            arr.clear()

        #making this array, it'll help us to travel through the 3X3 sub-arrays
        threeXthree = [0,3,6]

        #again clear the arr set so that you can check the 3X3 sub boxes of the sudoku
        arr.clear()

        for subRow in threeXthree:
            for subCol in threeXthree:
                for row in range(3):
                    for col in range(3):
                        if self.sudoku[row+subRow][col+subCol] != ".":
                            if not self.sudoku[row+subRow][col+subCol] in arr:
                                arr.add(self.sudoku[row+subRow][col+subCol])
                            else:
                                return False
                arr.clear()
        return True

    #Function to print the three rows of the sudoku
    def printTheThreeRows(self,starting,ending):
        for row in range(starting, ending):
            for col in range(0,9):
                if col == 2 or col == 5:
                    print(self.sudoku[row][col],'|',end='')
                else:
                    print(' ',self.sudoku[row][col],',',sep='',end='')
            print()

    #Function for printing the complete sudoku
    def printTheSudoku(self):
        if len(self.sudoku) == 9 and len(self.sudoku[0]) == 9:
            self.printTheThreeRows(0,3)
            print("---------------------------")
            self.printTheThreeRows(3,6)
            print('---------------------------')
            self.printTheThreeRows(6,9)
        else:
            print('''Your entered sudoku is not valid.
                  i.e., it is not 9X9 sudoku.''')

    #function of solving the incomplete sudoku
    def solve(self,sudoku,i,j):
        if i==9:
            return True
        if j == 9:
            return self.solve(sudoku,i+1,0)
        if self.sudoku[i][j] != '.':
            return self.solve(sudoku,i,j+1)
        nums = "123456789"

        for num in nums:
            if self.check(sudoku,i,j,num) == True:
                self.sudoku[i][j] = num
                if self.solve(self.sudoku,i,j) == True:
                    return True
                self.sudoku[i][j] = "."
        return False

    def check(self,sudoku,i,j,val):
        row = i - i%3
        col = j - j%3
        for x in range(0,9):
            if self.sudoku[i][x] == val:
                return False
        for y in range(0,9):
            if self.sudoku[y][j] == val:
                return False
        for x in range(0,3):
            for y in range(0,3):
                if self.sudoku[x+row][y+col] == val:
                    return False
        return True

"""
    A sudoku given for practice!

    [['.','.','1', '8','.','.', '.','.','5'],
     ['.','.','.', '1','.','5', '3','.','7'],
     ['.','6','.', '.','.','.', '2','.','.'],

     ['9','8','.', '.','4','.', '.','.','.'],
     ['.','.','.', '.','.','.', '.','.','.'],
     ['.','.','.', '.','8','.', '.','7','3'],

     ['.','.','2', '.','.','.', '.','9','.'],
     ['5','.','4', '9','.','7', '.','.','.'],
     ['3','.','.', '.','.','2', '7','.','.']]
"""

if __name__ == '__main__':
    a = Solution([['.','.','1', '8','.','.', '.','.','5'],
     ['.','.','.', '1','.','5', '3','.','7'],
     ['.','6','.', '.','.','.', '2','.','.'],

     ['9','8','.', '.','4','.', '.','.','.'],
     ['.','.','.', '.','.','.', '.','.','.'],
     ['.','.','.', '.','8','.', '.','7','3'],

     ['.','.','2', '.','.','.', '.','9','.'],
     ['5','.','4', '9','.','7', '.','.','.'],
     ['3','.','.', '.','.','2', '7','.','.']])

    #print(a.isValidSudoku())
    #a.printTheSudoku()
    print(a.isValidSudoku())

    board = [['.','.','1', '8','.','.', '.','.','5'],
     ['.','.','.', '1','.','5', '3','.','7'],
     ['.','6','.', '.','.','.', '2','.','.'],

     ['9','8','.', '.','4','.', '.','.','.'],
     ['.','.','.', '.','.','.', '.','.','.'],
     ['.','.','.', '.','8','.', '.','7','3'],

     ['.','.','2', '.','.','.', '.','9','.'],
     ['5','.','4', '9','.','7', '.','.','.'],
     ['3','.','.', '.','.','2', '7','.','.']]
    a.solve(board,0,0)
    a.printTheSudoku()


#!/usr/bin/env python3
"""Task 4"""
import numpy as np

def dropout_forward_prop(X, weights, L, keep_prob):
    """Conducts forward propagation using Droupout:

    X: numpy.ndarray of shape (nx, m) containing input data for the network
        nx: is the number of input features
        m: is the number of data points
    weights: is a dictionary of the weights and biases of the neural network
    L: the number of layers in the network
    keep_prob: is the probability that a node will be kept

    All layers except the last should use the tanh activation function
    The last layer should use the softmax activation function

    Returns: a dictionary containing the outputs of each layer
        and the dropout mask used on each layer"""

    cache = {}
    cache["A0"] = X
    for lay in range(1, L + 1):
        W = weights["W{}".format(lay)]
        A = cache["A{}".format(lay - 1)]
        b = weights["b{}".format(lay)]
        z = np.matmul(W, A) + b

        if lay == L:
            softA = np.exp(z)/np.sum(np.exp(z), axis=0)
            cache["A{}".format(lay)] = softA

        else:
            newA = (np.exp(z) - np.exp(-z)) / (np.exp(z) + np.exp(-z))
            d = (np.random.rand(newA.shape[0], newA.shape[1]) < keep_prob)
            cache["D{}".format(lay)] = d.astype(int)
            newA *= d
            newA /= keep_prob
            cache["A{}".format(lay)] = newA

    return cache


from injector import inject

from vc.command.base import BaseCommand
from vc.service.abme import AbmeService, AbmeOptions

class AbmeCommand(BaseCommand):
    description = 'Runs abme on an input file'
    args = [
        {
            'dest': 'first_file',
            'type': str,
            'help': 'First file',
            'default': 'first.png',
            'nargs': '?',
        },
        {
            'dest': 'second_file',
            'type': str,
            'help': 'Second file',
            'default': 'second.png',
            'nargs': '?',
        },
        {
            'dest': 'output_file',
            'type': str,
            'help': 'Output file',
            'default': 'debug.png',
            'nargs': '?',
        },
    ]

    abme: AbmeService

    @inject
    def __init__(self, abme: AbmeService):
        self.abme = abme

    def handle(self, args):
        print('got %s %s %s' % (args.first_file, args.second_file, args.output_file))
        self.abme.handle(AbmeOptions(
            first_file=args.first_file,
            second_file=args.second_file,
            output_file=args.output_file,
        ))


#!/usr/bin/env python
# coding: utf-8

# In[7]:

import numpy as np
import pandas as pd

# In[8]:

print("\t\t\tWelcome to the Device Management System")

# print(" 1. View all devices \n 2. Add a device \n 3. Delete a device \n 4. Update a device \n 5. Exit the program")

# In[14]:

ch="Y"
while(ch=="Y"):
    n = int(input("Select one option from the list ( 1, 2, 3, 4 or 5 ):"))
    if(n==1):
        f=open("devices.txt","r")
        print(f.read())
        f.close()

    elif(n==2):
        f=open("devices.txt","r+")
        x=f.readlines()
        y=len(x)
        f.close()
        f=open("devices.txt","r")
        f.write("device "+(y+1))
        f.close()

    elif(n==3):
        f=open("devices.txt","r")
        x=f.readlines()
        f.close()
        x.pop()
        f=open("devices.txt","w")
        f.writelines(x)
        f.close()

    elif(n==4):
        k=input("Enter device code:")
        f=open("devices.txt","a")
        f.write(k)
        f.close()

    elif(n==5):
        exit()

    else:
        print("invalid input")
    ch=input("Do you want to continue?(y/n):")

#These Function is responsible for print the file
# def read(d):
#     for i in d:
#         print(i,d[i]) #These Function is responsible for add element in the file

# def add(d):
#     id1=input("Enter id")
#     name=input("Enter device name")
#     d[name]=id1
#     f = open("devices.txt", "w")
#     c=0
#     for i in d:
#         if c!=0:
#             s="\n"+i + " " +d[i]
#             f.write(s)
#         else:
#             s=i + " " +d[i]
#             f.write(s)
#             c+=1
#             f.close() #These Function is responsible for update element in the file

# def update(d):
#     name=input("Enter device name")
#     id1=input("Enter id")
#     f = open("devices.txt", "w")
#     c=0
#     d[name]=id1
#     print(d)
#     for i in d:
#         if c!=0:
#             s="\n"+i + " " +d[i]
#             f.write(s)
#         else:
#             s=i + " " +d[i]
#             f.write(s)
#             c+=1
#             f.close() #These Function is responsible for update element in the file

# def delete(d):
#     d1={}
#     name=input("Enter device name")
#     f = open("devices.txt", "w")
#     c=0
#     for i in d:
#         if i!=name:
#             d1[i]=d[i]
#     for i in d1:
#         if c!=0:
#             s="\n"+i + " " +d1[i]
#             f.write(s)
#         else:
#             s=i + " " +d1[i]
#             f.write(s)
#             c+=1
#     f.close()

# while(c<2):     #These below lines is resposible for read the file
#     f = open("devices.txt", "r")
#     s=f.read()
#     f.close()
#     s=s.split()
#     d={}
#     for i in range(len(s)):
#         if i%2==0:
#             s1=s[i]
#             s2=s[i+1]
#             d[s1]=s2
#         print("Press 1 for read")
#         print("Press 2 for add")
#         print("Press 3 for update")
#         print("Press 4 for Delete")
#         print("Press 5 for Exit")
#         try:
#             n=int(input("Enter your choice"))
#         except:
#             print("Wrong Input")
#         if(n==1):
#             read(d)  #call the read function and pass the dictionary which is loaded from file
#         elif(n==2):
#             d=add(d) #call the add function and pass the dictionary which is loaded from file
#         elif(n==3):
#             update(d) #call the update function and pass the dictionary which is loaded from file
#         elif(n==4):
#             delete(d) #call the delete function and pass the dictionary which is loaded from file
#         elif(n==5):
#             break;
#         else:
#             print("Wrong Input,Plz try Again")
#         c+=1

# In[ ]: