from copy import deepcopy

class Real_Backgammon_Board:

    """
    self.Black_Pos is a list of black positions
    self.White_Pos is a list of white positions
    self.color: 'white' | 'black'
    self.dice: [die, die] | [die, die, die, die]
        die: 1 | 2 | 3 | 4 | 5 | 6
    self.turns: [[cpos, cpos], ...]
    self.validState is True | False
    self.init(self, board, turnInfo) initializes the self.Black_Pos, self.White_Pos, and self.listofTurnInfo
    self.moving(self) uses the self.listofTurnInfo to move checkers and if a move is illegal, self.solution = False
    self.getSolution(self) returns the solution (if self.solution is true, then self.returning_board() is called.
    self.returning_board(self) returns either False or a Board

    """

    ### In order to initialize the Backgammon Board, pass in a dictionary (board) that has "white" and "black" keys
    ### which are attached to the value of a list with which squares hold checkers, and then a 3-item list
    ### with the color (string), dice (list of numbers 1-6), and turn (list of 2-item list of cpos)

    def __init__(self, board, turnInfo):
        ## Filling up the different player lists with the appropriate piece positions
        self.Black_Pos = [0 for i in range(26)]
        self.White_Pos = [0 for i in range(26)]
        self.source = turnInfo #The iHateTeamFifteen function uses the original die to backtrack/figure smth out
        self.color = turnInfo[0]
        self.dice = turnInfo[1]
        self.turns = turnInfo[2]

        ### These next steps are essentially cleaning up the board
        ### We reorder the Black moves since they're in descending order
        ### We also change the strings of the positions to their integral equivalents according to color

        for entry in (board["black"]):
            if entry == "bar":
                entry = 25
            elif entry == "home":
                entry = 0
            totalBlackCheckers = self.Black_Pos[entry] + 1
            self.Black_Pos[entry] = totalBlackCheckers
        for entry in (board["white"]):
            if entry == "bar":
                entry = 0
            elif entry == "home":
                entry = 25
            totalWhiteCheckers = self.White_Pos[entry] + 1
            self.White_Pos[entry] = totalWhiteCheckers
        newTurns = self.turnsCleanUp(self.turns)
        self.turns = newTurns
        self.validState = True
        self.moving()

    ### Turning position strings ('home' | 'bar') into ints within the listofTurns

    def turnsCleanUp(self, listofTurns):
        for turn in listofTurns:
            for turnNo in list(range(len(turn))):
                if self.color == 'white':
                    if turn[turnNo] == "bar":
                        turn[turnNo] = 0
                    elif turn[turnNo] == "home":
                        turn[turnNo] = 25
                elif self.color == 'black':
                    if turn[turnNo] == "bar":
                        turn[turnNo] = 25
                    elif turn[turnNo] == "home":
                        turn[turnNo] = 0
        return (listofTurns)

    ### Through the listofTurns, we move around pieces until we finally reach the end of the action set
    ### returns nothing
    def moving(self):
        while (len(self.turns) != 0) and (self.validState is True):
            newTurn = self.turns.pop(0)
            oldPos = newTurn[0]
            newPos = newTurn[1]
            if self.valid_move(oldPos, newPos):
                pass
            else:
                self.validState = False
            self.move(oldPos, newPos)
            ### If Victory Condition is met, then stop moving and end turn, returning the board
            if self.color == "black":
                if self.Black_Pos[0] == 15:
                    self.dice = []
                    self.turns = []
                    self.validState = True
            elif self.color == "white":
                if self.White_Pos[25] == 15:
                    self.dice = []
                    self.turns = []
                    self.validState = True
        ### This is a post moving check basically to see if all die have been used.
        ### If not, then we check if there's any moves left. If there are, then we change validState to False
        ### Cause that means that the user didn't input the remaining available move.
        if len(self.dice) != 0 and self.validState == True:
            movesLeft = False
            for die in self.dice:
                if self.color == "white":
                    for x in range(len(self.White_Pos)):
                        if self.White_Pos[x] != 0:
                            oldPos = x
                            newPos = oldPos + die
                            if newPos > 25:
                                newPos = 25
                            movesLeft = (movesLeft or self.valid_move(oldPos, newPos))
                elif self.color == "black":
                    for x in range(len(self.Black_Pos)):
                        if self.Black_Pos[x] != 0:
                            oldPos = x
                            newPos = oldPos - die
                            if newPos < 0:
                                newPos = 0
                            print("This is oldPos: " + str(oldPos))
                            print("This is newPos: " + str(newPos))
                            print("This is movesLeft: " + str(movesLeft))
                            print("This is self.valid_move: " + str(self.valid_move(oldPos, newPos)))
                            movesLeft = (movesLeft or self.valid_move(oldPos, newPos))
            if movesLeft == False:
                print("case hit")
                self.validState = True
            else:
                self.validState = False

    """
    ### I won't lie to you. This function is in direct response to Team 15's awful awful edge case. I hate it. I HATE IT.
    ### Essentially this is an optimization function, called after victory is achieved. It basically double checks if
    ### all the die were used in the last move to victory. If so, then great. If not, then it checks if the last die
    ### used was less than the distance between final position and victory. If so, then it sets validState to False.
    ### Confused? Me too.
    ### God, iHateTeamFifteen().
    def iHateTeamFifteen(self):
        iHateColor = self.source[0]
        iHateDice = self.source[1]
        iHateTurns = self.source[2]
        for x in range(len(iHateTurns)):
            if x == len(self.turns) - 1:
                pass
            else:
                distance = abs(iHateTurns[x][1] - iHateTurns[x][0])

    """

    ## So far, this function checks whether
    ## 1. Checkers are moved off the bar first
    ## 2. All checkers are in pos 1-6 before going home
    ## 3. Whether the checkers are moving in the right direction.
    ## 4. Whether a checker is moved from a valid position.
    ## 5. Whether the space moved to is a valid spot.
    ## 6. If valid moves are being made with dice

    def valid_move(self, oldPos, newPos):
        if self.color == "black":
            home = 0
            bar = 25
            otherpos = self.White_Pos
            pos = self.Black_Pos
            homeBoard = [0, 1, 2, 3, 4, 5, 6]
        elif self.color == "white":
            home = 25
            bar = 0
            otherpos = self.Black_Pos
            pos = self.White_Pos
            homeBoard = [19, 20, 21, 22, 23, 24, 25]
        # 1.Checkers are moved off the bar first
        if oldPos != bar:
            if pos[bar] == 0:
                pass
            else:
                return False

        # 2. All checkers are in homeboard before going home
        if newPos == home:
            sum = 0
            for space in homeBoard:
                sum = pos[space] + sum
            if sum != 15:
                return False

        # 3. If directionality is correct
        if self.color == "black":
            spaceDiff = newPos - oldPos
            if spaceDiff > 0:
                return False
            else:
                pass
        elif self.color == "white":
            spaceDiff = newPos - oldPos
            if spaceDiff < 0:
                return False
            else:
                pass

        # 4. Whether a checker is moved from a valid position.
        if pos[oldPos] <= 0:
            return False
        # 5. Whether the space moved to is a valid spot.
        if newPos == bar or newPos == home:
            pass
        else:
            if otherpos[newPos] >= 2:
                return False
        ## 6. If valid moves are being made with dice
        spacesMoved = abs(newPos - oldPos)
        dicePoppedCond = False
        ### 6a. Checking for movement that is not to home
        for dieNo in range(len(self.dice)):
            if spacesMoved == self.dice[dieNo]:
                dicePopped = spacesMoved
                dicePoppedCond = True
        if dicePoppedCond:
            self.dice.remove(dicePopped)
        else:
        ### 6b. Checking for movement that is to home if the distance is not the same
        ###     if newPos is not home, then return False. Special board rules don't apply.
            if newPos == home:
                sumDice = 0
                biggestDice = 0
                for die in self.dice:
                    sumDice = sumDice + die
                    if die > biggestDice:
                        biggestDice = die
                ### Checking now for if value of die is larger than distance for
                ### any remaining checker to imaginary point, and checking for furthest away point
                mostDist = 0
                farthestSpace = 26
                for x in range(len(pos)):
                    if pos[x] != 0:
                        distance = abs(x - home)
                        if mostDist < distance and distance != 0:
                            mostDist = distance
                            if self.color == "white":
                                farthestSpace = x
                            elif self.color == "black":
                                farthestSpace = x
                if (mostDist <= sumDice) and (oldPos == farthestSpace):
                    self.dice.remove(biggestDice)
                    return True
                else:
                    return False
            else:
                return False
        return True

    def move(self, oldPos, newPos):
        ### Moving black's pieces
        if self.color == "black":
            newPosValue = self.Black_Pos[newPos] + 1
            self.Black_Pos[newPos] = newPosValue
            oldPosValue = self.Black_Pos[oldPos] - 1
            self.Black_Pos[oldPos] = oldPosValue

            # Removing Blots back to bar
            if self.White_Pos[newPos] == 1:
                self.White_Pos[newPos] -= 1
                self.White_Pos[0] += 1

        ### Moving white's pieces
        elif self.color == "white":
            newPosValue = self.White_Pos[newPos] + 1
            self.White_Pos[newPos] = newPosValue
            oldPosValue = self.White_Pos[oldPos] - 1
            self.White_Pos[oldPos] = oldPosValue

            # Removing Blots back to bar
            if (self.Black_Pos[newPos]) == 1:
                self.Black_Pos[newPos] -= 1
                self.Black_Pos[25] += 1

    ### Returns the solution as either False or a Board (returns Board if the solution is True)
    def getSolution(self):
        if self.validState:
            return(self.returning_board())
        else:
            return(False)

    ### Uses the self.Black_Pos and self.White_Pos to create the board in the JSON format, and then returns that board
    def returning_board(self):
        BlackList = []
        WhiteList = []
        blackHomeCount = 0
        ### Reformatting the list of black checkers into the JSON list format...
        for x in range(len(self.Black_Pos)):
            if self.Black_Pos[x] == 0:
                pass
            else:
                if x == 25:
                    checkerPos = "bar"
                elif x == 0:
                    checkerPos = "home"
                else:
                    checkerPos = x
                for checkerCount in range(self.Black_Pos[x]):
                    if checkerPos == "bar":
                        BlackList.insert(0, checkerPos)
                    elif checkerPos == "home":
                        blackHomeCount = blackHomeCount + 1
                    else:
                        BlackList.append(checkerPos)
        ### Adding in the "home" for black checkers at the end
        for x in range(blackHomeCount):
            BlackList.append('home')
        ### Reformatting the list of white checkers into the JSON list format...
        for x in range(len(self.White_Pos)):
            if self.White_Pos[x] == 0:
                pass
            else:
                if x == 0:
                    checkerPos = "bar"
                elif x == 25:
                    checkerPos = "home"
                else:
                    checkerPos = x
                for checkerCount in range(self.White_Pos[x]):
                    WhiteList.append(checkerPos)
        ## Constructing final dictionary to be returned
        currBoard = {}
        currBoard["black"] = BlackList
        currBoard["white"] = WhiteList
        return(currBoard)

class Proxy_Backgammon_Board:

    """
    self.Real_Board holds the Real_Backgammon_Board initialization
    self.validSpaces is a list of valid spaces for the checkers to be on
    """

    ### In order to initialize the Real Backgammon Board, pass in a dictionary (board) that has "white" and "black" keys
    ### which are attached to the value of a list with which squares hold checkers, and then a 3-item list
    ### with the color (string), dice (list of numbers 1-6), and turn (list of 2-item list of cpos)

    ### This proxy initialization checks if the arguments being passed into the real board are correct. Also creates
    ### a list of valid checker-spaces to test the boards against for self.validSpaces

    def __init__(self, board, turnInfo):
        turnInfo = deepcopy(turnInfo)
        self.validSpaces = list(range(26))
        self.validSpaces[0] = "bar"
        self.validSpaces[25] = "home"
        self.counterColors = ["white", "black"]
        if self.Board_Check(board):
            pass
        else:
            raise("initialization input for board is not correct!")
        if self.Turn_Check(turnInfo):
            pass
        else:
            raise("turn_check is incorrect!")
        self.Real_Board = Real_Backgammon_Board(board, turnInfo)

    ### Returns the solution as either False or a Board (returns Board if the solution is True)
    def getSolution(self):
        board = self.Real_Board
        proxySolution = board.getSolution()
        if proxySolution == False:
            return(proxySolution)
        elif self.Board_Check(proxySolution):
            return(proxySolution)
        else:
            raise("getSolution is not returning the right data type")

    ### Checks if the input is a board (dictionary with 'white' and 'black' keys to a list of length 15),
    ### then returns True | False depending on if it matches the format
    def Board_Check(self, checkingBoard):
        if isinstance(checkingBoard, dict):
            whiteList = checkingBoard.get('white')
            blackList = checkingBoard.get('black')
            if (whiteList is None) or (blackList is None):
                raise("either white or black was missing as a key in the board dictionary")
            elif (len(whiteList) != 15) or (len(blackList) != 15):
                raise("the length of the list of cpos within the board was not 15")
            else:
                for entry in whiteList:
                    if entry not in self.validSpaces:
                        raise("invalid cpos in the list of white checkers")
                for entry in blackList:
                    if entry not in self.validSpaces:
                        raise("invalid cpos in the list of black checkers")
                return(True)
        else:
            raise("board is not a dictionary data type")

    ### Checks if the input is a 3-item list of turn based information [color, dice, turn], which:
        #color: 'white' | 'black'
        #dice: [die, die] | [die, die, die, die]
        #die: 1 | 2 | 3 | 4 | 5 | 6
        #turn: [[cpos, cpos], ...]
    ### then returns True | False depending on if it matches the format
    def Turn_Check(self, checkingTurnInfo):

        if len(checkingTurnInfo) != 3:
            raise("the turnInfo has an incorrect number of elements in the list!")
        # checking if the color arguments are correct
        color = checkingTurnInfo[0]
        if (not isinstance(color, str)):
            raise("the color argument of the turnInfo is an incorrect data type")
        else:
            if color not in self.counterColors:
                raise("the color argument of the turnInfo is an invalid color")
        # checking if the dice arguments are correct
        dice = checkingTurnInfo[1]
        if (len(dice) != 2) and (len(dice) != 4):
            raise("invalid number of die in game!")
        else:
            for die in dice:
                if isinstance(die, int):
                    if (die > 6) or (die < 1):
                        raise("one of the dice is an invalid integer value")
                    else:
                        pass
                else:
                    raise("one of the dice is an invalid data type")
        # checking if the turn arguments are correct
        turns = checkingTurnInfo[2]
        for turn in turns:
            if len(turn) != 2:
                raise("invalid number of cpos in one of the turns")
            else:
                for cpos in turn:
                    if cpos not in self.validSpaces:
                        raise("invalid cpos within one of the turns")

        return(True)


from collections import OrderedDict

import numpy as np
import pandas as pd
import pytest
from numpy.testing import assert_equal

try:
    import xarray as xr
    MISSING_XARRAY = False
except ImportError:
    MISSING_XARRAY = True

from linearmodels.compat.pandas import assert_frame_equal, assert_series_equal
from linearmodels.iv.data import IVData

class TestDataHandler(object):
    def test_numpy_2d(self):
        x = np.empty((10, 2))
        xdh = IVData(x)
        assert xdh.ndim == x.ndim
        assert xdh.cols == ['x.0', 'x.1']
        assert xdh.rows == list(np.arange(10))
        assert_equal(xdh.ndarray, x)
        df = pd.DataFrame(x, columns=xdh.cols, index=xdh.rows)
        assert_frame_equal(xdh.pandas, df)
        assert xdh.shape == (10, 2)
        assert xdh.labels == {0: xdh.rows, 1: xdh.cols}

    def test_numpy_1d(self):
        x = np.empty(10)
        xdh = IVData(x)
        assert xdh.ndim == 2
        assert xdh.cols == ['x']
        assert xdh.rows == list(np.arange(10))
        assert_equal(xdh.ndarray, x[:, None])
        df = pd.DataFrame(x[:, None], columns=xdh.cols, index=xdh.rows)
        assert_frame_equal(xdh.pandas, df)
        assert xdh.shape == (10, 1)

    def test_pandas_df_numeric(self):
        x = np.empty((10, 2))
        index = pd.date_range('2017-01-01', periods=10)
        xdf = pd.DataFrame(x, columns=['a', 'b'], index=index)
        xdh = IVData(xdf)
        assert xdh.ndim == 2
        assert xdh.cols == list(xdf.columns)
        assert xdh.rows == list(xdf.index)
        assert_equal(xdh.ndarray, x)
        df = pd.DataFrame(x, columns=xdh.cols, index=xdh.rows)
        assert_frame_equal(xdh.pandas, df)
        assert xdh.shape == (10, 2)

    def test_pandas_series_numeric(self):
        x = np.empty(10)
        index = pd.date_range('2017-01-01', periods=10)
        xs = pd.Series(x, name='charlie', index=index)
        xdh = IVData(xs)
        assert xdh.ndim == 2
        assert xdh.cols == [xs.name]
        assert xdh.rows == list(xs.index)
        assert_equal(xdh.ndarray, x[:, None])
        df = pd.DataFrame(x[:, None], columns=xdh.cols, index=xdh.rows)
        assert_frame_equal(xdh.pandas, df)
        assert xdh.shape == (10, 1)

    @pytest.mark.skipif(MISSING_XARRAY, reason='xarray not installed')
    def test_xarray_1d(self):
        x_np = np.random.randn(10)
        x = xr.DataArray(x_np)
        dh = IVData(x, 'some_variable')
        assert_equal(dh.ndarray, x_np[:, None])
        assert dh.rows == list(np.arange(10))
        assert dh.cols == ['some_variable.0']
        expected = pd.DataFrame(x_np, columns=dh.cols, index=dh.rows)
        assert_frame_equal(expected, dh.pandas)

        index = pd.date_range('2017-01-01', periods=10)
        x = xr.DataArray(x_np,
                         [('time', index)])
        dh = IVData(x, 'some_variable')
        assert_equal(dh.ndarray, x_np[:, None])
        assert_series_equal(pd.Series(dh.rows), pd.Series(list(index)))
        assert dh.cols == ['some_variable.0']
        expected = pd.DataFrame(x_np[:, None], columns=dh.cols, index=dh.rows)
        assert_frame_equal(expected, dh.pandas)

    @pytest.mark.skipif(MISSING_XARRAY, reason='xarray not installed')
    def test_xarray_2d(self):
        x_np = np.random.randn(10, 2)
        x = xr.DataArray(x_np)
        dh = IVData(x)
        assert_equal(dh.ndarray, x_np)
        assert dh.rows == list(np.arange(10))
        assert dh.cols == ['x.0', 'x.1']
        expected = pd.DataFrame(x_np, columns=dh.cols, index=dh.rows)
        assert_frame_equal(expected, dh.pandas)

        index = pd.date_range('2017-01-01', periods=10)
        x = xr.DataArray(x_np,
                         [('time', index),
                          ('variables', ['apple', 'banana'])])
        dh = IVData(x)
        assert_equal(dh.ndarray, x_np)
        assert_series_equal(pd.Series(dh.rows), pd.Series(list(index)))
        assert dh.cols == ['apple', 'banana']
        expected = pd.DataFrame(x_np, columns=dh.cols, index=dh.rows)
        assert_frame_equal(expected, dh.pandas)

    def test_invalid_types(self):
        with pytest.raises(ValueError):
            IVData(np.empty((1, 1, 1)))
        with pytest.raises(ValueError):
            IVData(np.empty((10, 2, 2)))
        with pytest.raises(TypeError):
            class AnotherClass(object):
                @property
                def ndim(self):
                    return 2

            IVData(AnotherClass())

    def test_string_cat_equiv(self):
        s1 = pd.Series(['a', 'b', 'a', 'b', 'c', 'd', 'a', 'b'])
        s2 = pd.Series(np.arange(8.0))
        s3 = pd.Series(['apple', 'banana', 'apple', 'banana',
                        'cherry', 'date', 'apple', 'banana'])
        df = pd.DataFrame({'string': s1, 'number': s2, 'other_string': s3})
        dh = IVData(df)
        df_cat = df.copy()
        df_cat['string'] = df_cat['string'].astype('category')
        dh_cat = IVData(df_cat)
        assert_frame_equal(dh.pandas, dh_cat.pandas)

    def test_existing_datahandler(self):
        x = np.empty((10, 2))
        index = pd.date_range('2017-01-01', periods=10)
        xdf = pd.DataFrame(x, columns=['a', 'b'], index=index)
        xdh = IVData(xdf)
        xdh2 = IVData(xdh)
        assert xdh is not xdh2
        assert xdh.cols == xdh2.cols
        assert xdh.rows == xdh2.rows
        assert_equal(xdh.ndarray, xdh2.ndarray)
        assert xdh.ndim == xdh2.ndim
        assert_frame_equal(xdh.pandas, xdh2.pandas)

    def test_categorical(self):
        index = pd.date_range('2017-01-01', periods=10)
        cat = pd.Categorical(['a', 'b', 'a', 'b', 'a', 'a', 'b', 'c', 'c', 'a'])
        num = np.empty(10)
        df = pd.DataFrame(OrderedDict(cat=cat, num=num), index=index)
        dh = IVData(df)
        assert dh.ndim == 2
        assert dh.shape == (10, 3)
        assert sorted(dh.cols) == sorted(['cat.b', 'cat.c', 'num'])
        assert dh.rows == list(index)
        assert_equal(dh.pandas['num'].values, num)
        assert_equal(dh.pandas['cat.b'].values, (cat == 'b').astype(np.float))
        assert_equal(dh.pandas['cat.c'].values, (cat == 'c').astype(np.float))

    def test_categorical_series(self):
        index = pd.date_range('2017-01-01', periods=10)
        cat = pd.Categorical(['a', 'b', 'a', 'b', 'a', 'a', 'b', 'c', 'c', 'a'])
        s = pd.Series(cat, name='cat', index=index)
        dh = IVData(s)
        assert dh.ndim == 2
        assert dh.shape == (10, 2)
        assert sorted(dh.cols) == sorted(['cat.b', 'cat.c'])
        assert dh.rows == list(index)
        assert_equal(dh.pandas['cat.b'].values, (cat == 'b').astype(np.float))
        assert_equal(dh.pandas['cat.c'].values, (cat == 'c').astype(np.float))

    def test_categorical_no_conversion(self):
        index = pd.date_range('2017-01-01', periods=10)
        cat = pd.Categorical(['a', 'b', 'a', 'b', 'a', 'a', 'b', 'c', 'c', 'a'])
        s = pd.Series({'cat': cat}, index=index, name='cat')
        dh = IVData(s, convert_dummies=False)
        assert dh.ndim == 2
        assert dh.shape == (10, 1)
        assert dh.cols == ['cat']
        assert dh.rows == list(index)
        df = pd.DataFrame(s)
        assert_frame_equal(dh.pandas, df)

    def test_categorical_keep_first(self):
        index = pd.date_range('2017-01-01', periods=10)
        cat = pd.Categorical(['a', 'b', 'a', 'b', 'a', 'a', 'b', 'c', 'c', 'a'])
        num = np.empty(10)
        df = pd.DataFrame(OrderedDict(cat=cat, num=num), index=index)
        dh = IVData(df, drop_first=False)
        assert dh.ndim == 2
        assert dh.shape == (10, 4)
        assert sorted(dh.cols) == sorted(['cat.a', 'cat.b', 'cat.c', 'num'])
        assert dh.rows == list(index)
        assert_equal(dh.pandas['num'].values, num)
        assert_equal(dh.pandas['cat.a'].values, (cat == 'a').astype(np.float))
        assert_equal(dh.pandas['cat.b'].values, (cat == 'b').astype(np.float))
        assert_equal(dh.pandas['cat.c'].values, (cat == 'c').astype(np.float))

    def test_nobs_missing_error(self):
        with pytest.raises(ValueError):
            IVData(None)

    def test_incorrect_nobs(self):
        x = np.empty((10, 1))
        with pytest.raises(ValueError):
            IVData(x, nobs=100)

    def test_mixed_data(self):
        s = pd.Series([1, 2, 'a', -3.0])
        with pytest.raises(ValueError):
            IVData(s)


#!/opt/anaconda3/bin/python3
import configparser
import sys
import time
import logging
import GoogleFinance
from PyQt4 import QtCore
from PyQt4 import QtGui
import UI

if __name__ == "__main__":
    """
    This program reads the configuration file stocks.cfg, logs
    the information about the working of the program in file
    default.log or lab4.log and uses GoogleFinance class to
    download the google stock information into a .csv file.
    """
    # Open and read the info in stocks.cfg file; If not display a error message
    try:
        config = configparser.RawConfigParser()
        config.read("stocks.cfg")
    except:
        print("Unable to read configuration file")
        sys.exit()

    # Check if the stocks.cfg file has section 'LOGGING' and option 'LOG_FILE'; if so then create a
    # log file using this name; else use default.log as log file name.
    # If unable to create a log file; then display a error message and exit
    try:
        # Creating log file with level of logging, time and date
        if config.has_section('LOGGING') == True:
            logging.basicConfig(filename=str(config['LOGGING']['LOG_FILE']),level=logging.DEBUG,
                            format='%(asctime)s,%(message)s',
                            datefmt=
                            '%m/%d/%Y %I:%M:%S %p')
        else:
            logging.basicConfig(filename='default.log',level=logging.DEBUG,
                            format='%(asctime)s,%(message)s',
                            datefmt=
                            '%m/%d/%Y %I:%M:%S %p')
    except:
        print("Unable to create a log file")
        sys.exit()
    # logging an info saying program has started
    logging.info("Program started")
    # Creating a QtGui app, UI instance and exceuting
    app = QtGui.QApplication(sys.argv)
    UserInterface = UI.UI(None,config)
    UserInterface.show()
    app.exec_()


import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import mean_absolute_error as mae

# sources https://stackoverflow.com/questions/22239691/code-for-best-fit-straight-line-of-a-scatter-plot-in-python
# https://stackoverflow.com/questions/6148207/linear-regression-with-matplotlib-numpy
# https://stackoverflow.com/questions/18767523/fitting-data-with-numpy
# https://www.geeksforgeeks.org/python-map-function/
# https://stackoverflow.com/questions/24943991/change-grid-interval-and-specify-tick-labels-in-matplotlib
# https://www.kite.com/python/answers/how-to-set-point-size-in-a-matplotlib-plot-in-python

class Walmart:
    def __init__(self):
        self.population = []
        self.profit = []

    def loadData(self, filename):
        # store the data of cities from filename into the library
        raw_data = open(filename, "r")
        list_data = raw_data.readlines()
        raw_data.close()
        # parse list_data, create city objects, add cities to self.cityArray
        for line in list_data:
            dataArray = line.split(',')
            self.population.append(float(dataArray[0]))
            self.profit.append(float(dataArray[1]))

        # model profit as a function of population
        self.predict = np.poly1d(np.polyfit(self.population, self.profit, 1)) # part b
        # self.predict(x) => y

    def plotData(self): # part a
        font = {'family': 'DejaVu Sans', 'weight': 'bold', 'size': 15}
        pointSize = 15*np.ones(len(self.population))

        fig = plt.figure()
        ax = fig.add_subplot()
        plt.scatter(self.population, self.profit, pointSize, 'r') # scatter of population vs profit

        # grid details
        major_ticks = np.arange(0, 26, 5) # major ticks every 5
        minor_ticks = np.arange(-5, 26, 1) # minor ticks every 1
        ax.set_xticks(major_ticks)
        ax.set_xticks(minor_ticks, minor=True)
        ax.set_yticks(major_ticks)
        ax.set_yticks(minor_ticks, minor=True)
        ax.grid(which='both')
        ax.grid(which='minor', alpha=0.2) # line transparency
        ax.grid(which='major', alpha=0.5)
        plt.setp(ax.get_xticklabels(), fontsize=12) # label font size
        plt.setp(ax.get_yticklabels(), fontsize=12)

        # plot details
        plt.ylabel('Profit $ (x10,000)', fontdict=font)
        plt.xlabel('Population (x10,000)', fontdict=font)
        plt.xlim(min(self.population)-1, 25)
        plt.title("Walmart's Locations' Profit vs Population", fontdict=font)
        plt.show()

    def plotData_with_model(self): # part c
        font = {'family': 'DejaVu Sans', 'weight': 'bold', 'size': 15}
        x = sorted(self.population)  # sort since population is unordered
        pointSize = 15 * np.ones(len(self.population))

        fig = plt.figure()
        ax = fig.add_subplot()
        plt.scatter(self.population, self.profit, pointSize, 'r')  # scatter of population vs profit
        plt.plot(x, self.predict(x), '--k')  # best fit line part b

        # accuracy of the model
        self.accuracy = mae(self.profit, self.predict(self.population)) # part f

        # grid details
        major_ticks = np.arange(0, 26, 5)  # major ticks every 5
        minor_ticks = np.arange(-5, 26, 1)  # minor ticks every 1
        ax.set_xticks(major_ticks)
        ax.set_xticks(minor_ticks, minor=True)
        ax.set_yticks(major_ticks)
        ax.set_yticks(minor_ticks, minor=True)
        ax.grid(which='both')
        ax.grid(which='minor', alpha=0.2)  # line transparency
        ax.grid(which='major', alpha=0.5)
        plt.setp(ax.get_xticklabels(), fontsize=12)  # label font size
        plt.setp(ax.get_yticklabels(), fontsize=12)

        # plot details
        plt.ylabel('Profit $ (x10,000)', fontdict=font)
        plt.xlabel('Population (x10,000)', fontdict=font)
        plt.xlim(min(self.population) - 1, 25)
        plt.title("Walmart's Locations' Profit vs Population\n(MAE = %.2f)" % self.accuracy, fontdict=font)
        plt.show()

    def future_store_predictions(self): # part e
        future_stores = {}
        future_stores["A"] = self.predict(7.8)
        future_stores["B"] = self.predict(4.4)
        future_stores["C"] = self.predict(4.7)
        future_stores["D"] = self.predict(6.12)
        future_stores["E"] = self.predict(8.55)
        future_stores["F"] = self.predict(6.7)
        future_stores["G"] = self.predict(9.8)
        future_stores["H"] = self.predict(7.01)

        future_stores_ordered = dict(sorted(future_stores.items(), key=lambda item: item[1], reverse=True))
        print("Future stores in descending order of profit:")
        for k in future_stores_ordered:
            print("Store", k, "expects $%.2f (x10,000) of profit" % future_stores_ordered[k])

if __name__ == '__main__':
    W = Walmart()
    W.loadData("walmart_data.txt")
    W.plotData()
    W.plotData_with_model()
    W.future_store_predictions()


from django.urls import path, re_path
from .views import VacanciesListView, vacancy_new, layout
from .models import Vacancy

vacancies_list_view = VacanciesListView.as_view(
    queryset=Vacancy.objects.order_by('author'),
    context_object_name="vacancy_list",
    template_name="vacancy/vacancylist.html",

)

urlpatterns = [
    re_path("new", vacancy_new, name="vacancy_new"),
    re_path("ies", vacancies_list_view, name="vacancylist"),
    # path("", layout, name="layout"),
]


from model.config import *
from model.network import *
from model.utils import *
from model.evaluator import Evaluator
from keras import backend as K
import matplotlib.pyplot as plt
import warnings
import os
import pandas as pd

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
warnings.filterwarnings("ignore")
K.clear_session()

lstm_conf = LSTM_Config()
lstm_conf.update(use_previous_model=0,
                 load_file_name='lstm_next_mid_price_delta.h5',
                 label_name=['next_mid_price'],
                 feature_name=['mid_price', 'bc1', 'sc1'],
                 time_step=1,
)

# step 1: Get dataset (csv)
data = pd.read_csv(lstm_conf['data_file_path'], encoding='gbk')

# step 2: Select Feature
data = extract_feature_and_label(data, lstm_conf['feature_name'], lstm_conf['label_name'])

# step 3: Preprocess
data = normalize(data)
train, test = divide_train_and_test(data, lstm_conf['training_set_proportion'])
train_x, train_y = data_transform_lstm(train, lstm_conf['time_step'])
test_x, test_y = data_transform_lstm(test, lstm_conf['time_step'])

# step 4: Create and train model_weight
network = LSTMs(lstm_conf)
if lstm_conf['use_previous_model']:
    network.load(lstm_conf['load_file_name'])
else:
    network.train(train_x, train_y)
    network.save(lstm_conf['save_file_name'])

# step 5: Predict
train_pred = network.predict(train_x)
test_pred = network.predict(test_x)

# step 6: Evaluate
evaluator = Evaluator()

# method1
train_acc = evaluator.evaluate_trend(y_true=train_y, y_pred=train_pred)
print('train=', train_acc)
test_acc = evaluator.evaluate_trend(y_true=test_y, y_pred=test_pred)
print('test=', test_acc)

# method 2
acc_train_list = evaluator.evaluate_divided_trend(train_y, train_pred)
acc_test_list = evaluator.evaluate_divided_trend(test_y, test_pred)
print('train=', acc_train_list)
print('test=', acc_test_list)

# method 3
train_acc = evaluator.evaluate_trend_simple(train_y, train_pred)
print('train=', train_acc)
test_acc = evaluator.evaluate_trend_simple(test_y, test_pred)
print('test=', test_acc)

# feature_list = lstm_conf['feature_name']
# save_feature_selection(feature_list, acc)

plt.figure(figsize=(200, 15))
plt.plot(train_y)
plt.plot(train_pred)
plt.legend(['train_label', 'train_predict'], loc='upper right')
plt.title('train_set plot')
plt.xlabel('time')
plt.ylabel('price')
plt.show()

plt.figure(figsize=(200, 15))
plt.plot(test_y)
plt.plot(test_pred)
# plt.plot(np.arange(len(test_mid_price)), test_mid_price-8.3)
plt.legend(['test_label', 'test_predict', 'test_mid_price - 8.3'], loc='upper right')
plt.title('test_set plot')
plt.xlabel('time')
plt.ylabel('price')
plt.show()


import pygame

pygame.init()

size = width,height = 1400, 900
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Missionaries and Cannibals Tree")
font = pygame.font.SysFont('Comic Sans MS', 18)

red = (0,0,255)
blue = (0,208,208)

clock = pygame.time.Clock()

class LeftBank:
    def __init__(self):
        self.mis = 3
        self.can = 3

class RightBank:
    def __init__(self):
        self.mis = 0
        self.can = 0

class Boat:
    def __init__(self):
        self.inLeft = True
        self.mis = 0
        self.can = 0

class State:
    def __init__(self,m_state,c_state,b_state):
        self.index = -1
        self.children = []
        self.m_state = m_state
        self.c_state = c_state
        self.boat_state = b_state
        self.isVisited = False
        self.tot_state = [self.m_state,self.c_state, self.boat_state]

    def setPos(self,x_pos,y_pos):
        self.x_pos = x_pos
        self.y_pos = y_pos

initial_state,final_state = [[3,3,True],[0,0,True]],[[0,0,False],[3,3,False]]

queue = [initial_state]

data = []

state = State(initial_state[0][0], initial_state[0][1], initial_state[0][2])
state.index = 0

leftBank = LeftBank()
rightBank = RightBank()
boat = Boat()

root_state = state
parent_state = state

state_queue = [parent_state]
nodes = [parent_state]

def set_original_value(leftBank,rightBank,boat,m,c):
    boat.inLeft = not boat.inLeft
    if boat.inLeft == True:
        leftBank.mis += m
        leftBank.can += c
        rightBank.mis -= m
        rightBank.can -= c
    else:
        rightBank.mis += m
        rightBank.can += c
        leftBank.mis -= m
        leftBank.can -= c

while True:
    current_state = queue.pop(0)
    current_parent_state = state_queue.pop(0)

    if (current_state[0][1] > current_state[0][0] and current_state[0][0] != 0) or (current_state[1][1] > current_state[1][0] and current_state[1][0] != 0):
        #print("Invalid Condition")
        continue
    if (current_state == final_state):
        done = True
        break

    leftBank.mis,leftBank.can = current_state[0][0],current_state[0][1]
    rightBank.mis, rightBank.can = current_state[1][0],current_state[1][1]
    boat.inLeft = current_state[0][2]

    mis_travel,can_travel = -1 ,-1

    #   Possible Number of missionaries or cannibals to travel
    if (boat.inLeft == True):
        mis_travel = (2 if leftBank.mis >2 else leftBank.mis)
        can_travel = (2 if leftBank.can >2 else leftBank.can)
    else:
        mis_travel = (2 if rightBank.mis >2 else rightBank.mis)
        can_travel = (2 if rightBank.can >2 else rightBank.can)

    for m in range(mis_travel + 1):
        for c in range(can_travel + 1):
            if (m+c >2 or m+c == 0):
                continue
            boat.mis = m
            boat.can = c

            if boat.inLeft == True:      # boat is in the left bank
                leftBank.mis -= m
                leftBank.can -= c
                rightBank.mis += m
                rightBank.can += c
            else:                        # boat is in the right bank
                leftBank.mis += m
                leftBank.can += c
                rightBank.mis -= m
                rightBank.can -= c
            boat.inLeft = not(boat.inLeft)
            this_state = [[leftBank.mis, leftBank.can, boat.inLeft],[rightBank.mis, rightBank.can, boat.inLeft]]

            if (this_state not in data):
                if (this_state not in queue):
                    queue.append(this_state)

                    temp_state = State(this_state[0][0],this_state[0][1],this_state[0][2])
                    temp_state.index = current_parent_state.index + 1
                    current_parent_state.children.append(temp_state)
                    state_queue.append(temp_state)
                    nodes.append(temp_state)
            set_original_value(leftBank,rightBank,boat,m,c)
    data.append(current_state)

#   To draw each node and its children in the screen
def draw(node):
    if len(node.children) > 0:
        for i in range(len(node.children)):
            x_pos, y_pos = node.x_pos + 90, (node.y_pos + i * 75 if node.y_pos + i * 75 < height else node.y_pos - i * 75)
            node.children[i].setPos(x_pos,y_pos)
            pygame.draw.line(screen,blue,(node.x_pos,node.y_pos),(x_pos,y_pos),1)
            pygame.draw.circle(screen,red,(x_pos,y_pos),5)
            textSurface = font.render(str(node.children[i].m_state) + "," + str(node.children[i].c_state) + "," + str(node.children[i].boat_state),False,(0,1,0))
            screen.blit(textSurface,(x_pos-textSurface.get_width()/2 , y_pos + textSurface.get_height()/2))
            draw(node.children[i])

while True:
    screen.fill((240,248,255))

    #   Draw root node in the screen
    nodes[0].setPos(75,20)
    pygame.draw.circle(screen,red,(nodes[0].x_pos,nodes[0].y_pos),5)
    textSurface = font.render(str(nodes[0].m_state) + "," + str(nodes[0].c_state) + "," + str(nodes[0].boat_state),False,(0,1,0))
    screen.blit(textSurface,(nodes[0].x_pos-textSurface.get_width()/2 , nodes[0].y_pos + textSurface.get_height()/2))
    draw(nodes[0])

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    clock.tick(50)
    pygame.display.update()


#!/usr/bin/python2
# coding: utf-8
#!/usr/bin/env python
'''
解析文件可以单独外置进行操作
target_speed可以设置成类似cx，cy的数组
1、确定车辆的位置：通过gps，惯导等设备，确定车辆的位置，航向角等实时状态信息；
2、找到离车最近的位置：在前视距离范围内，可能会有多个数据目标路径的点，应当选取一2个距离起点最接近前视距离的那个点，为了找到最满足要求的这个点，首先可以选取一个在路径上里此刻最近的点，以确定自己此刻在规划出的路径中的位置。
3、找到目标点：利用上一步获取的位置点，采取一定的计算方法，获取规划出的路径中，距离此点距离最接近前视距离的点，把这个点设为目标点。
4、利用pure pursuit算法的计算公式，计算出到达目标点所需的转向角δ。
5、根据单位时间内车辆的运动更新车辆的状态。
'''

import rospy
import numpy as np
import math
import time
import matplotlib.pyplot as plt
from std_msgs.msg import String
from std_msgs.msg import Float32
from std_msgs.msg import Int32
from control.msg import Motor_Feedback

k = 0.1                                #前向增益
Kp = 0.2                               #速度比例增益
dt = 0.1                               #[s]
L = 2.49                               #车辆轴距[m]
Lfc = 3                                #超前距离
bet = 1.0                              #缓冲距离
yaw = " "
sx = " "
sy = " "
angle = 0.0
rv = 0.0
zero_cord_x = 0.0
zero_cord_y = 0.0

old_nearest_point_index = None         #上次最近点
show_animation = True                  #显示动画

class State:
    #车辆运动学模型#
    def __init__(self, x=0.0, y=0.0, yaw=0.0, v=0.0):
        self.x = x
        self.y = y
        self.yaw = yaw
        self.v = v
        self.rear_x = self.x - ((L / 2) * math.cos(self.yaw))   #计算后轮位置X
        self.rear_y = self.y - ((L / 2) * math.sin(self.yaw))   #计算后轮位置Y

#######################################
#定义update(state, a, delta)
#输入：状态，GPS位置队列，
#返回：返回角度和当前预描点位置
#######################################
def update(state, a, delta):
    global yaw,sx,sy
    try:
        state.yaw=float(yaw)
        state.x=float(sx)
        state.y=float(sy)
    except:
        print("state updata error")
    state.x = state.x - zero_cord_x
    state.y  = state.y  - zero_cord_y
    state.yaw= 90 - state.yaw
    print("state.yaw:",state.yaw)
    state.yaw = (state.yaw * np.pi)/180
    '''
    while state.yaw > np.pi:
        state.yaw -= 2.0 * np.pi

    while state.yaw < -np.pi:
        state.yaw += 2.0 * np.pi
    '''
    print("state.yaw:",state.yaw)
    print("state.yaw:",math.sin(state.yaw))
    #state.v=float(rv)
    #state.v=state.v/3.6   # speed is m/s

    '''state.x = state.x + state.v * math.cos(state.yaw) * dt
    print("state.x:",state.x)
    print("state.x:",state.x)
    state.y = state.y + state.v * math.sin(state.yaw) * dt
    state.yaw = state.yaw + state.v / L * math.tan(delta) * dt'''
    state.v = rv#state.v + a * dt                                   #更新此时的速度
    state.rear_x = state.x #- ((L / 2) * math.cos(state.yaw))     #计算当前的后轮位置X
    state.rear_y = state.y #- ((L / 2) * math.sin(state.yaw))     #计算当前的后轮位置Y

    return state

#######################################
#函数：纵向PID
#输入：目标值，测量值
#返回：P_PIDControl
#######################################
def PIDControl(target, current):
    a = Kp * (target - current*1.5)

    return a

#######################################
#函数：pure_pursuit_control
#输入：状态，GPS位置队列，
#返回：返回角度和当前预描点
#######################################
def pure_pursuit_control(state, cx, cy, pind):
    global angle
    ind = calc_target_index(state, cx, cy)

    if pind >= ind:
        ind = pind

    if ind < len(cx):
        tx = cx[ind]
        ty = cy[ind]
    else:
        tx = cx[-1]
        ty = cy[-1]
        ind = len(cx) - 1

    apl = (math.atan2(ty - state.rear_y, tx - state.rear_x))
    alpha = apl - state.yaw
    kx=tx-state.rear_x
    ky=ty-state.rear_y
    #L = math.sqrt(kx ** 2 + ky ** 2)
    Lf =Lfc # k * state.v + Lfc
    buf1 = math.sin(alpha)
    buf2 = 2.0 * L * math.sin(alpha) / Lf
    buf3 = (math.atan2(2.0 * L * math.sin(alpha) / Lf, 1.0))
    print("alpha_chuliqian_hudu",apl)
    print("alpha_chuliqian_jiaodu",apl/math.pi*180)
    print("alpha_chulihou_hudu",alpha)
    print("alpha_chulihou_jiaodu",alpha/math.pi*180)
    print("buf1",buf1)
    print("buf2",buf2)
    print("buf3",buf3)
    #bu = (math.atan2(ty - state.rear_y, tx - state.rear_x))
    #bu2 = (math.atan2(2.0 * L * math.sin(alpha) / Lf, 1.0))
    #bu3 = (math.atan2(2.0 * L * math.sin(alpha) / Lf, 1.0))/math.pi*180
    delta = -(math.atan2(2.0 * L * math.sin(alpha) / Lf, 1.0))/math.pi*180

    '''st_delta = (math.atan2(2.0 * L * math.sin(alpha) / Lf, 1.0))/math.pi*180
    #delta = p*(math.atan2(2.0 * L * math.sin(alpha) / Lf, 1.0))/math.pi*180
    delta = st_delta - angle
    angle = st_delta'''

    print("Lf:",Lf)
    print("delta:jiaodu:",delta)
    print("state.v::",state.v)

    return delta, ind

#######################################
#函数：calc_distance(state, point_x, point_y)
#输入：state, point_x, point_y
#返回：距离
#######################################
def calc_distance(state, point_x, point_y):
    dx = state.rear_x - point_x
    dy = state.rear_y - point_y
    return math.sqrt(dx ** 2 + dy ** 2)

#######################################
#函数：calc_target_index(state, cx, cy)
#功能：遍历全部cx，cy如果需要提高实时性
#功能：可以根据当前的ind来缩小计算的范围
#输入：state, point_x, point_y
#返回：距离
#######################################
def calc_target_index(state, cx, cy):

    dx = [state.x - icx for icx in cx]
    dy = [state.y - icy for icy in cy]
    d = [abs(math.sqrt(idx ** 2 + idy ** 2)) for (idx, idy) in zip(dx, dy)]
    ind = d.index(min(d))                                                           #最近的目标点的距离和索引号
    print("dddd:",min(d))
    print("ind:",ind)
    L = 0.0

    Lf = Lfc #k * state.v + Lfc

    while Lf > L and (ind + 1) < len(cx):
        #寻找前视距离内最远的路径点
        dx = cx[ind]-state.rear_x
        dy = cx[ind]-state.rear_y
        #dx = cx[ind + 1] - cx[ind]
        #dy = cx[ind + 1] - cx[ind]
        L = math.sqrt(dx ** 2 + dy ** 2)
        print("LLLL:",L)
        ind += 1

    return ind

#######################################
#函数：plot_arrow
#######################################
def plot_arrow(x, y, yaw, length=1.0, width=0.5, fc="r", ec="k"):
    """
    Plot arrow
    """

    if not isinstance(x, float):
        for (ix, iy, iyaw) in zip(x, y, yaw):
            plot_arrow(ix, iy, iyaw)
        print("xxxxxxxxxxxxxxx")
    else:
        plt.arrow(x, y, length * math.cos(yaw), length * math.sin(yaw),
                  fc=fc, ec=ec, head_width=width, head_length=width)
        plt.plot(x, y)

#######################################
#函数：RVcallback(data)
#功能：订阅当前车速
#data的数据类型与Subscriber接收的Topic对应的消息类型一致
#######################################
def RVcallback(Motor_Feedback):
    global rv
    rv = Motor_Feedback.Base_Vehspd
    #rospy.loginfo('I heard: %s', data.data)

#######################################
#函数：callback(msg)
#功能：订阅组合惯导纬度、经度、航向角
#data的数据类型与Subscriber接收的Topic对应的消息类型一致
#######################################
def callback(msg):

    global yaw,sx,sy
    sx,sy,yaw=msg.data.split(',')

    print("msg.data:",sx,sy,yaw)

    #state = update(state, ai, di,msg)
    #return yaw,sx,sy

def moving_average(interval, windowsize):
    window = np.ones(int(windowsize)) / float(windowsize)
    re = np.convolve(interval, window, 'same')
    return re

#######################################
#函数：main()
#######################################
def main():

    blank = []                                                                      #buffer
    white = []                                                                      #buffer
    yellow = []                                                                     #buffer
    cx = []                                                                         #所采集预描点的x
    cy = []                                                                         #所采集预描点的x
    rospy.init_node('pure_pursuit', anonymous = False)                              #初始化ROS节点 pure_pursuit
    simple_publisher = rospy.Publisher('delta', Float32, queue_size = 10)           #定义Publisher对象
    second_publisher = rospy.Publisher('c_a', Float32, queue_size = 10)
    rate = rospy.Rate(90)                                                           #设置Topic发布的频率（Hz）

    while not rospy.is_shutdown():
        sub = rospy.Subscriber('chatter', String, callback,queue_size = 10)                       #订阅GPS数据
        rospy.Subscriber("Motor_Feedback_mssage", Motor_Feedback,RVcallback,queue_size = 10)             #订阅车速

        #读取预描点
        nums, ber = np.loadtxt("/home/robot/Robot/SmartCar_WS/src/fuzzy_purepursuit/scripts/curve.txt", dtype=str, delimiter=',', unpack=True)
        for i in range(len(nums)):
            if not nums[i] in blank:                                                #去除重复点
                #blank.append(nums[i])
                yellow.append(float(nums[i]))
                white.append(float(ber[i]))
        bx = yellow[0]                                                              #起始点坐标
        by = white[0]

        for i in range(len(yellow)):
            dx = yellow[i] - bx
            dy = white[i] - by
            dis = math.sqrt(dx ** 2 + dy ** 2)
            if dis > bet:                                                           #选取大于设定的距离的点
                cx.append(yellow[i])                                                #使cx，cy中点均满足要求
                cy.append(white[i])
                bx = yellow[i]
                by = white[i]

        cx = np.array(cx)                                                           #将列表转换成数组
        cy = np.array(cy)
        #print("cx:",cx)
        #print("cy:",cy)
        global zero_cord_x,zero_cord_y
        zero_cord_x = cx[0]
        zero_cord_y = cy[0]
        cx = cx - cx[0]
        cy = cy - cy[0]
        cy = moving_average(cy, 10)
        plt.plot(cx,cy, "-r", label="ccc")
        plt.plot()
        plt.show()

        target_speed = 10.0                                                  # [m/s]

        T = 1000.0                                                                  # max simulation time

        # initial state
        state = State(x=cx[0], y=cy[0], yaw=0.0, v=0.0)                             #初始状态

        lastIndex = len(cx) - 1                                                     #定义最后一个点是第几个
        time = 0.0
        x = [state.x]
        y = [state.y]
        yaw = [state.yaw]
        v = [state.v]
        t = [0.0]
        print("state")
        target_ind = calc_target_index(state, cx, cy)                               #目标预描点是第几个

        print("state")
        print("target:",target_ind)
        print("target:",lastIndex)

        while T >= time and lastIndex > target_ind:
            ai = PIDControl(target_speed, rv)                                  #车的加速度
            di, target_ind = pure_pursuit_control(state, cx, cy, target_ind)        #返回角度和当前预描点
            state = update(state, ai, di)
            '''print("state:",state.x)
            print("state:",state.y)
            print("state:",state.yaw)'''
            print("target:",target_ind)

            time = time + dt

            x.append(state.x)
            y.append(state.y)
            #print(type(x))
            #print(y)
            yaw.append(state.yaw)
            v.append(state.v)
            t.append(time)
            simple_publisher.publish(di)
            second_publisher.publish(ai)
            #发布Topic
            rate.sleep()
            print("state_x:",x)
            print("state_y:",y)
            if show_animation:  # pragma: no cover
                plt.cla()
                plot_arrow(state.x, state.y, state.yaw)
                plt.plot(cx,cy, "-r", label="course")
                plt.plot(x, y, "-b", label="trajectory")
                plt.plot(cx[target_ind], cy[target_ind], "xg", label="target")
                #kx=cx(target_ind)-x
                #ky=cy(target_ind)-y
                #L = math.sqrt(kx ** 2 + ky ** 2)
                #print("Lf:",math.sqrt(kx ** 2 + ky ** 2))
                plt.axis("equal")
                #plt.axis([-270,110,-190,190])#北汽
                #plt.axis([-50, 250, -250, 250])#abc
                plt.grid(True)
                plt.title("Speed[km/h]:" + str(state.v * 3.6)[:4])
                plt.pause(0.001)

        # Test
        assert lastIndex >= target_ind, "Cannot goal"

        if show_animation:  # pragma: no cover
            plt.cla()
            plt.plot(cx, cy, ".r", label="course")
            plt.plot(x, y, "-b", label="trajectory")
            plt.legend()
            plt.xlabel("x[m]")
            plt.ylabel("y[m]")
            plt.axis("equal")
            plt.grid(True)

            plt.subplots(1)
            plt.plot(t, [iv * 3.6 for iv in v], "-r")
            plt.xlabel("Time[s]")
            plt.ylabel("Speed[km/h]")
            plt.grid(True)
            plt.show()

if __name__ == '__main__':
    print("Pure pursuit path tracking start")
    main()


import django
from django import forms
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS

class KeyResponseForm(forms.Form):
    response = forms.CharField()

    if django.get_version() < (1, 7):
        def add_error(self, field, error):
            """
            Update the content of `self._errors`.

            The `field` argument is the name of the field to which the errors
            should be added. If its value is None the errors will be treated as
            NON_FIELD_ERRORS.

            The `error` argument can be a single error, a list of errors, or a
            dictionary that maps field names to lists of errors. What we define as
            an "error" can be either a simple string or an instance of
            ValidationError with its message attribute set and what we define as
            list or dictionary can be an actual `list` or `dict` or an instance
            of ValidationError with its `error_list` or `error_dict` attribute set.

            If `error` is a dictionary, the `field` argument *must* be None and
            errors will be added to the fields that correspond to the keys of the
            dictionary.
            """
            if not isinstance(error, ValidationError):
                # Normalize to ValidationError and let its constructor
                # do the hard work of making sense of the input.
                error = ValidationError(error)

            if hasattr(error, 'error_dict'):
                if field is not None:
                    raise TypeError(
                        "The argument `field` must be `None` when the `error` "
                        "argument contains errors for multiple fields."
                    )
                else:
                    error = error.error_dict
            else:
                error = {field or NON_FIELD_ERRORS: error.error_list}

            for field, error_list in error.items():
                if field not in self.errors:
                    if field != NON_FIELD_ERRORS and field not in self.fields:
                        raise ValueError(
                            "'%s' has no field named '%s'." % (self.__class__.__name__, field))
                    self._errors[field] = self.error_class()
                self._errors[field].extend(error_list)
                if field in self.cleaned_data:
                    del self.cleaned_data[field]


file_name = 'test.txt'
try:
    with open(file_name, 'r') as f:
        lst = []
        for i in f:
            lst.append(i.strip('\n'))
except IOError as e:
    print(">>>",e)

print(f"Total Number of Lines In File {len(lst)}")
print("File Data :")
for line in lst:
    print(line)
word = []
for line in lst:
    words = line.split(' ')
    for w in words:
        word.append(w)

print(f"Total Number of words In File {len(word)}")
print()
print("Seprated Each Sentence In form of list: ")
print(lst)


#Ejercicio6_3 Menu para clientes

def agregar_cliente(clientes,nombre,apellido,dni):
    cliente={}
    cliente['nombre'] = nombre
    cliente['apellido'] = apellido
    cliente['dni'] = dni
    clientes.append(cliente)

def mostrar_clientes(clientes):
    for i in clientes:
        print(f"Nombre:{i['nombre']} \nApellido:{i['apellido']} \nDNI:{i['dni']}")

def mostrar_cliente(clientes, dni):
    for i in clientes:
        if i['dni'] == dni:
            print(f"Nombre:{i['nombre']} \nApellido:{i['apellido']} \nDNI:{i['dni']}")
            return True
    return False

def eliminar_cliente(clientes,dni):
    for i in clientes:
        if i['dni'] == dni:
            clientes.remove(i)
            return True
    return False

clientes = [] #Lista
while True:
    print("""\t.:MENU:.
1. Agregar nuevo cliente
2. Mostrar todos los clientes
3. Mostrar cliente por DNI
4. Eliminar Cliente
5. Salir""")
    opcion = int(input("Digite una opción: "))
    print()

    if opcion == 1:
        nombre = input("Nombre del cliente -> ")
        apellido = input("Apellido del cliente -> ")
        dni = input("DNI del cliente -> ")
        agregar_cliente(clientes,nombre,apellido,dni)
    elif opcion == 2:
        mostrar_clientes(clientes)
    elif opcion == 3:
        dni = input("DNI del cliente -> ")
        if mostrar_cliente(clientes,dni):
            print("Cliente encontrado")
        else:
            print("Cliente no encontrado")
    elif opcion == 4:
        dni = input("DNI del cliente -> ")
        if eliminar_cliente(clientes,dni):
            print("cliente eliminado")
        else:
            print("Cliente no encontrado")
    elif opcion == 5:
        break
    else:
        print("Error, Opcion no valida")
    print()


#!/usr/bin/env python3
# SAMPLE SQL FILE
# Will create a file in the current directory 'blockchain.db'

import sqlite3 as lite

create_table = """
CREATE TABLE IF NOT EXISTS Blockchain (
    ID              INTEGER PRIMARY KEY AUTOINCREMENT,
    PubKey          TEXT,
    Coins           INTEGER
);
"""

def CreateDataBase():
  con = lite.connect("blockchain.db")
  c = con.cursor()
  c.execute(create_table)
  print("Table Blockchain created.")

def DeleteDataBase():
  con = lite.connect("blockchain.db")
  with con:
    c = con.cursor()
    c.execute("DROP TABLE IF EXISTS Blockchain;")
    print("Table Blockchain deleted.")

def AddPubKey(key, coins):
  con = lite.connect("blockchain.db")
  with con:
    c = con.cursor()
    c.execute("INSERT INTO Blockchain (PubKey, Coins) VALUES (?, ?);", (key, coins))

def PrintPubKeys():
  con = lite.connect("blockchain.db")
  with con:
    c = con.cursor()
    c.execute("SELECT * FROM Blockchain;")
    row = c.fetchall()
    print(str(row))

def GetCoinsByKey(key):
  con = lite.connect("blockchain.db")
  with con:
    c = con.cursor()
    c.execute("SELECT * FROM Blockchain WHERE PubKey = '{k}';".format(k=key))
    row = c.fetchall()
    if not row:
      return None
    return row[0][2] # return the amount of coins

CreateDataBase()
AddPubKey("91298e9812eh81298he9h182e", 420)
PrintPubKeys()
print(GetCoinsByKey("91298e9812eh81298he9h182e")) # => 420
print(GetCoinsByKey("invalid_key"))               # => None

DeleteDataBase()


""" server.py

    Run the call center app.
"""

import argparse
import logging
import logging.config

import tornado.ioloop
import tornado.web

import handlers

LOGGING_CONFIG = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level': 'INFO',
            'formatter': 'standard',
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        '': {
            'handlers': ['default'],
            'level': 'INFO',
            'propagate': True
        },
    }
}

logging.config.dictConfig(LOGGING_CONFIG)

def make_app():
    return tornado.web.Application([
        (r'/', handlers.MainHandler),
        (r'/main-digit-handler', handlers.MainDigitHandler),
        (r'/recording-handler', handlers.RecordingHandler),
        (r'/recording-digit-handler', handlers.RecordingDigitHandler),
    ])

def get_args():
    parser = argparse.ArgumentParser(description='Run twilio voice server')
    parser.add_argument(
        '--port', type=int, default=8888,
        help='Port to listen on')
    return parser.parse_args()

def main():
    args = get_args()

    app = make_app()

    logging.info('Starting app on port %d', args.port)

    app.listen(args.port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == '__main__':
    main()


#script to produce plots of G, logG from anacm. Will plot using matplotlib
#Ryan Bignell - a1627873 - 28/4/15

import sys
import os.path

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

inFile = sys.argv[1]     #getting into the correct folder

#to use latex in plots
plt.rc('text', usetex=True)
mpl.rcParams['text.latex.preamble'].append(r'\usepackage{amsmath}')
mpl.rcParams['text.latex.preamble'].append(r'\usepackage{amssymb}')

plt.figure(figsize=(8.3, 5.8), dpi=100)

#plotting logG
logG_data = np.loadtxt(inFile+".logG.txt",dtype=[('t',int),('logG',float),('error',float),('bias',float)])

#logG_data = logG_data[logG_data['t'] >= 17]    #these two lines remove data from points t<17 and t>40
#logG_data = logG_data[logG_data['t'] <= 40]

plt.ylabel("$logG$")
plt.xlabel("$t$")
plt.xlim([16,40])    #limits on axes
plt.ylim([logG_data['logG'][min(40-17, len(logG_data)-1)],0])
plt.errorbar(logG_data['t'], logG_data['logG'], yerr=logG_data['error'])    #plotting with error bars
#plt.show()
plt.savefig(inFile+".logG.png")

#plotting G
plt.figure(figsize=(8.3, 5.8), dpi=100)

G_data = np.loadtxt(inFile+".G.txt", dtype=[('t',int),('G',float),('error',float),('bias',float)])
#G_data = G_data[G_data['t'] >= 17]
#G_data = G_data[G_data['t'] <= 40]
#zeros = np.where(G_data['G'] - G_data['error'] <= 0)[0]
#if len(zeros) > 0:
#    G_data = G_data[:zeros[0]]

plt.errorbar(G_data['t'], G_data['G'], yerr=G_data['error'])
plt.ylabel("$G$")
plt.xlabel("$t$")
plt.xlim([16,40])
#plt.ylim([G_data['G'][min(40-17, len(G_data)-1)],0])
#plt.show()
plt.savefig(inFile+".G.png")

print("END OF FILE")


# -*- coding: utf-8 -*-
# =============================================================================
# MIT License
#
# Copyright (c) 2018 Charles Jekel
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# =============================================================================

#   Define a function that combines two vander matricies for use with least
#   Square polynomial regression fitting for three dimensional data
#   Useage A = doubleVander(X,Y,degree)
#   Where X, Y are your vectors
#   Degree = the order of the desired polynomial
#   A is the resulting double vander matrix

import numpy as np

def doubleVander(x,y,Degree):
    N = Degree + 1
    Ax = np.vander(x,Degree+1)
    Ay = np.vander(y,Degree+1)
    Aout = np.zeros((len(x),N*N))
    count = 0
    for i in range(0,N):
        for j in range(0,N):
            Aout[:,count] = Ax[:,i]*Ay[:,j]
            count = count +1
    return Aout;


#!/usr/local/bin/python
# example client that calls adding a song to the database

import socket
import sys

def create_sock():
	HOST, PORT = "localhost", 9999
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sock.connect((HOST, PORT))
	return sock

# 	Will Add a song to the database
##sock = create_sock()
#sock.sendall("1,mysong,myartist,myablum,rock,mypath2\n")
#sock.close()

#	Get next song to play
#sock = create_sock()
#sock.sendall("2")
#received = sock.recv(1024)
#print received
#if received == "0":
#	print "No Songs in Playlist"
#sock.close()

#Test delete fucntionality
sock = create_sock()
sock.sendall("3")
sock.close()


from django.test import TestCase
from swipe.models import Interaction
from rest_framework.test import force_authenticate, APIRequestFactory
from users.models import User
from chat.models import Match
from swipe.views import Smash, Skip, Top5

class InteractionManagerTests(TestCase):
    fixtures = ["tests/med_test_users.json"]

    def activate_all(self):
        """Activate all users"""
        for user in User.objects.all():
            user.status = User.ACTIVE
            user.save()

    def test_smash(self):
        """ Smashing """
        swiper = User.objects.get(pk=1)
        swiped_on = User.objects.get(pk=2)
        interaction = Interaction.objects.smash(swiper, swiped_on)

        self.assertEqual(interaction.swiper.id, 1)
        self.assertEqual(interaction.swiped_on.id, 2)

        self.assertEqual(interaction.skip_count, 0)
        self.assertTrue(interaction.smash)

    def test_skip(self):
        """ Skipping """
        swiper = User.objects.get(pk=1)
        swiped_on = User.objects.get(pk=2)
        interaction = Interaction.objects.skip(swiper, swiped_on)

        self.assertEqual(interaction.swiper.id, 1)
        self.assertEqual(interaction.swiped_on.id, 2)

        self.assertEqual(interaction.skip_count, 1)
        self.assertFalse(interaction.smash)

    def test_skip_then_smash(self):
        """ Smashing after a skip """
        swiper = User.objects.get(pk=1)
        swiped_on = User.objects.get(pk=2)
        _ = Interaction.objects.skip(swiper, swiped_on)
        interaction = Interaction.objects.smash(swiper, swiped_on)

        self.assertEqual(interaction.swiper.id, 1)
        self.assertEqual(interaction.swiped_on.id, 2)

        self.assertEqual(interaction.skip_count, 1)
        self.assertTrue(interaction.smash)

    def test_smash_then_skip(self):
        """ Smashing then skipping should not change interaction """
        swiper = User.objects.get(pk=1)
        swiped_on = User.objects.get(pk=2)
        _ = Interaction.objects.smash(swiper, swiped_on)

        with self.assertRaises(Exception):
            Interaction.objects.skip(swiper, swiped_on)

        interaction = Interaction.objects.get(swiper=swiper, swiped_on=swiped_on)

        self.assertEqual(interaction.skip_count, 0)
        self.assertTrue(interaction.smash)

    def test_smash_then_smash(self):
        """ Double smashing should trigger assertion """
        swiper = User.objects.get(pk=1)
        swiped_on = User.objects.get(pk=2)
        _ = Interaction.objects.smash(swiper, swiped_on)

        with self.assertRaises(Exception):
            Interaction.objects.smash(swiper, swiped_on)

        interaction = Interaction.objects.get(swiper=swiper, swiped_on=swiped_on)

        self.assertEqual(interaction.skip_count, 0)
        self.assertTrue(interaction.smash)

    def test_match_creation(self):
        """ A match is created by complementary smash swipes """
        swiper = User.objects.get(pk=1)
        swiped_on = User.objects.get(pk=2)
        _ = Interaction.objects.smash(swiper, swiped_on)
        _ = Interaction.objects.smash(swiped_on, swiper)
        # ideally this should probably be a mock not an actual call
        self.assertEqual(len(list(Match.objects.list_matches(swiper))), 1)

    def test_no_match_creation(self):
        """ A match is not created with smash + skip swipes"""
        swiper = User.objects.get(pk=1)
        swiped_on = User.objects.get(pk=2)
        _ = Interaction.objects.smash(swiper, swiped_on)
        _ = Interaction.objects.skip(swiped_on, swiper)

        self.assertEqual(len(list(Match.objects.list_matches(swiper))), 0)

    def test_top5_swipe(self):
        """ Top5 'swipe' """
        swiper = User.objects.get(pk=1)
        swiped_on = User.objects.get(pk=2)
        interaction = Interaction.objects.top5(swiper, swiped_on)

        self.assertTrue(interaction.top5)
        self.assertFalse(interaction.smash)

    def test_top5_swipe_invalid(self):
        """ Top5 cannot be applied to existing interaction """
        swiper = User.objects.get(pk=1)
        swiped_on = User.objects.get(pk=2)
        _ = Interaction.objects.smash(swiper, swiped_on)
        with self.assertRaises(Exception):
            _ = Interaction.objects.top5(swiper, swiped_on)

    def test_top5_match(self):
        """ Matching top5 swipes create match, mark both interactions smash"""
        swiper = User.objects.get(pk=1)
        swiped_on = User.objects.get(pk=2)
        _ = Interaction.objects.top5(swiper, swiped_on)
        interaction = Interaction.objects.top5(swiped_on, swiper)
        complement = Interaction.objects.get(swiper=swiper, swiped_on=swiped_on)

        self.assertTrue(interaction.top5)
        self.assertTrue(interaction.smash)

        self.assertTrue(complement.top5)
        self.assertTrue(complement.smash)

        matches = list(Match.objects.list_matches(swiper))

        self.assertEqual(len(matches), 1)
        self.assertTrue(matches[0].top5)

    def test_first_build(self):
        "First build of the deck - create all interactions, smash = null"
        # Activate all users before building Deck
        self.activate_all()
        active = User.objects.get(pk=1)
        Interaction.objects.build_deck(active)
        deck = Interaction.objects.filter(swiper=active, smash=None)

        self.assertEqual(len(deck), 99)
        # I shouldn't show up in my own deck
        with self.assertRaises(Interaction.DoesNotExist):
            _ = Interaction.objects.get(swiper=1, swiped_on=1)

    def test_skip_then_refresh(self):
        "Rebuild deck after skipping - user should reappear in deck"
        self.activate_all()
        active = User.objects.get(pk=1)
        Interaction.objects.build_deck(active)
        deck = Interaction.objects.filter(swiper=active, smash=None)

        # Left swipe on other user
        other_user = Interaction.objects.get(swiper=active, swiped_on=98)
        other_user.smash = False
        other_user.save()

        deck = Interaction.objects.filter(swiper=active, smash=None)
        self.assertEqual(len(deck), 98)

        # Refresh
        Interaction.objects.build_deck(active)
        deck = Interaction.objects.filter(swiper=active, smash=None)
        self.assertEqual(len(deck), 99)

    def test_smash_then_refresh(self):
        "Rebuild deck after smashing - user should not reappear in deck"
        self.activate_all()
        active = User.objects.get(pk=1)
        Interaction.objects.build_deck(active)
        deck = Interaction.objects.filter(swiper=active, smash=None)

        # Smash someone
        other_user = Interaction.objects.get(swiper=active, swiped_on=98)
        other_user.smash = True
        other_user.save()

        deck = Interaction.objects.filter(swiper=active, smash=None)
        self.assertEqual(len(deck), 98)

        # Refresh
        Interaction.objects.build_deck(active)
        deck = Interaction.objects.filter(swiper=active, smash=None)
        self.assertEqual(len(deck), 98)

    def test_get_next(self):
        "Test retrieve users to swipe, confirm no duplicates"
        self.activate_all()
        active = User.objects.get(pk=1)
        Interaction.objects.build_deck(active)
        already_seen = []

        cards = Interaction.objects.get_next(active)
        while len(cards) > 0:
            # feelin thirsty - swipe right on everyone
            for card in cards:
                card.smash = True
                card.save()
                self.assertFalse(card in already_seen)
                already_seen.append(card)
            cards = Interaction.objects.get_next(active)

        # I have smashed everyone -- refreshed, my deck is now empty
        Interaction.objects.build_deck(active)
        deck = Interaction.objects.filter(swiper=active, smash=None)
        self.assertEqual(len(deck), 0)

    def test_get_next_banned(self):
        "Banned users never appear in deck, even if they are banned after deck is built"
        self.activate_all()
        active = User.objects.get(pk=1)
        Interaction.objects.build_deck(active)

        ban = User.objects.get(pk=25)
        ban.status = User.BANNED
        ban.save()

        cards = Interaction.objects.get_next(active)
        while len(cards) > 0:
            # Picky picky - skip everyone
            for card in cards:
                card.smash = False
                card.save()
            cards = Interaction.objects.get_next(active)
            self.assertFalse(Interaction.objects.get(swiped_on=ban) in cards)

    def test_get_next_new_users(self):
        "New users activated while swiping should appear at the end of the deck"
        # Activate every other user
        index = 0
        for user in User.objects.all():
            if index % 2 == 1:
                user.status = User.ACTIVE
                user.save()
            index += 1

        active = User.objects.get(pk=1)
        Interaction.objects.build_deck(active)

        self.assertEqual(len(Interaction.objects.filter(swiper=active)), 50)
        cards = Interaction.objects.get_next(active)
        # After building deck, activate the rest of the users and ensure each user
        # appears only once in the deck
        self.activate_all()
        already_seen = []
        while len(cards) > 0:
            for card in cards:
                card.smash = True
                card.save()
                self.assertFalse(card in already_seen)  # check no duplicates
                already_seen.append(card)
            cards = Interaction.objects.get_next(active)
        self.assertEqual(len(already_seen), 99)

class InteractionsViewsTest(TestCase):
    fixtures = ["tests/dummy_users.json"]

    def test_smash_valid(self):
        """ Smash endpoint creates smash interaction """
        user = User.objects.get(pk=1)

        factory = APIRequestFactory()
        request = factory.post("swipe/smash/", {"user": 2}, format="json")
        force_authenticate(request, user=user)
        view = Smash.as_view()
        response = view(request)

        self.assertEqual(response.status_code, 201)

        smash = Interaction.objects.get(swiper=user, swiped_on=2)
        self.assertTrue(smash.smash)

    def test_skip_valid(self):
        """ Skip endpoint creates skip interaction """
        user = User.objects.get(pk=1)

        factory = APIRequestFactory()
        request = factory.post("swipe/skip/", {"user": 2}, format="json")
        force_authenticate(request, user=user)
        view = Skip.as_view()
        response = view(request)

        self.assertEqual(response.status_code, 201)

        smash = Interaction.objects.get(swiper=user, swiped_on=2)
        self.assertFalse(smash.smash)

    def test_top5_valid(self):
        """ Top5 endpoint creates top5 interaction """
        user = User.objects.get(pk=1)

        factory = APIRequestFactory()
        request = factory.post("swipe/top5/", [{"user": 2}, {"user": 3}], format="json")
        force_authenticate(request, user=user)
        view = Top5.as_view()
        response = view(request)

        self.assertEqual(response.status_code, 201)

        Interaction.objects.get(swiper=user, swiped_on=2, top5=True)
        Interaction.objects.get(swiper=user, swiped_on=3, top5=True)

    def test_top5_too_many(self):
        """ Top5 endpoint rejects lists of more than 5 users """
        user = User.objects.get(pk=1)

        factory = APIRequestFactory()
        request = factory.post(
            "swipe/top5/",
            [
                {"user": 2},
                {"user": 3},
                {"user": 3},
                {"user": 3},
                {"user": 3},
                {"user": 3},
            ],
            format="json",
        )
        force_authenticate(request, user=user)
        view = Top5.as_view()
        response = view(request)

        self.assertEqual(response.status_code, 400)

    def test_top5_repeats(self):
        """ Top5 endpoint ignores repeats"""
        user = User.objects.get(pk=1)

        factory = APIRequestFactory()
        request = factory.post(
            "swipe/top5/", [{"user": 2}, {"user": 2}], format="json",
        )
        force_authenticate(request, user=user)
        view = Top5.as_view()
        response = view(request)
        self.assertEqual(response.status_code, 201)

        Interaction.objects.get(swiper=user, swiped_on=2, top5=True)

    def test_top5_multiple_requests(self):
        """ Users can only submit one set of top5 requests """
        user = User.objects.get(pk=1)

        factory = APIRequestFactory()
        request = factory.post("swipe/top5/", [{"user": 2}], format="json")
        force_authenticate(request, user=user)
        view = Top5.as_view()
        response = view(request)

        request_2 = factory.post("swipe/top5/", [{"user": 3}], format="json")
        force_authenticate(request_2, user=user)
        response_2 = view(request_2)

        self.assertEqual(response_2.status_code, 400)

        Interaction.objects.get(swiper=user, swiped_on=2, top5=True)
        with self.assertRaises(Exception):
            Interaction.objects.get(swiper=user, swiped_on=3, top5=True)


import json
import os
from urllib.parse import urlencode
import aiohttp
import aiohttp_jinja2
import jinja2
from aiohttp import web

from raspi_alexa.device import DevicesConfiguration

_ROOT_URL = 'https://raspberry.alexa.mirko.io/production'
_LOGIN_URL = '{}/login'.format(_ROOT_URL)
_SUBSCRIBE_URL = '{}/subscribe'.format(_ROOT_URL)

VAR = {}

async def fetch(session, url):
    async with session.get(url, raise_for_status=True) as response:
        return await response.text()

async def get_amazon_user_id(access_token: str) -> str:
    async with aiohttp.ClientSession() as session:
        async with session.get(
                'https://api.amazon.com/user/profile',
                headers={'x-amz-access-token': access_token},
                raise_for_status=True) as response:
            response_text = await response.text()
            return json.loads(response_text)['user_id']

async def login(request):
    arguments = {
        'device_id': VAR['device_id'],
        'subscribe_url': 'http://{}/subscription'.format(request.headers.get('Host'))
    }
    login_url = '{login_url}?{arguments}'.format(
            login_url=_LOGIN_URL,
            arguments=urlencode(arguments)
    )
    raise web.HTTPFound(login_url)

@aiohttp_jinja2.template('logout.jinja2')
def logout(request):
    return {
        'device_id': request.rel_url.query['device_id']
    }

async def subscription(request):
    form_data = await request.post()
    device_id = form_data['device_id']
    if VAR['device_id'] != device_id:
        return web.Response(status=400)
    openid_token = json.loads(form_data['data'])['data']
    aws_user = await get_amazon_user_id(form_data['aws_token'])
    VAR['devices_configuration'].add_configuration(device_id, aws_user, openid_token)
    raise web.HTTPFound('/logout?{}'.format(urlencode({'device_id': device_id})))

def start_server(devices_configuration: DevicesConfiguration, device_id: str, http_port: int = 8080):
    VAR['device_id'] = device_id
    VAR['devices_configuration'] = devices_configuration

    app = web.Application()
    app.add_routes(
        [
            web.get('/', login),
            web.post('/subscription', subscription),
            web.get('/logout', logout)
        ]
    )
    aiohttp_jinja2.setup(
        app, loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '..', 'templates'))
    )

    web.run_app(app, port=http_port)


import os
import cv2
import re

listOfVideoNames = os.listdir(os.path.dirname(os.path.abspath(__file__)) + '/real_celebs/')
totalNumberOfVideos = len(listOfVideoNames)
videoCount = 1

for videoName in listOfVideoNames:
    capturedVideo = cv2.VideoCapture(os.path.dirname(os.path.abspath(__file__)) + '/real_celebs/' + videoName)
    videoLength = int(capturedVideo.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
    currentFrameCount = 1

    fileNameWithoutMp4 = videoName.replace('_', '').replace(' ', '').replace('.mp4', '')

    while(currentFrameCount < videoLength):
        ret, frame = capturedVideo.read()

        newFramePath = os.path.dirname(os.path.abspath(__file__)) + '/real_celeb_frames/' + fileNameWithoutMp4 + '_' + str(currentFrameCount) + '.png'

        cv2.imwrite(newFramePath, frame)

        currentFrameCount += 1

        print('Total Video Length: ' + str(videoLength))
        print('Current Frame Count: ' + str(currentFrameCount))
        print('Current Video: ' + str(videoCount))
        print('Total Videos: ' + str(totalNumberOfVideos))

    capturedVideo.release()
    cv2.destroyAllWindows

    videoCount += 1


# -*- coding: utf-8 -*-
#
# タイムライン取得
#

from lib.config import OAConfig, PathConfig

from requests_oauthlib import OAuth1Session
from datetime import datetime
import re, json ,logging

class GetTL:

    def __init__(self):
        self.twitter = OAuth1Session(OAConfig.CONSUMER_KEY, OAConfig.CONSUMER_SECRET, OAConfig.ACCESS_TOKEN, OAConfig.ACCESS_TOKEN_SECRET)
        self.apistat = {"limit": -1, "remaining": -1, "reset": -1} #gettl api用のapistat
        self.intAPIStat = {"limit": -1, "remaining": -1, "reset": -1} #apistat更新用のapiのapistat
        self.reloadAPIStat()
        self.remlimit = 100 #残りリクエスト回数がこの数値を切ったらエラーを吐く

        logging.basicConfig(filename=PathConfig.PATH_LOGOUTPUT, level=logging.INFO) #ログの出力先とレベル

    #--paramをもとにツイートを取得
    def getTL(self, param):
        rst = {"stat": 0} #取得結果とステータス

        #--API的にリクエスト投げていい?
        self.getAPIStat()
        if(self.apistat['remaining'] <= self.remlimit):
            if(self.apistat['remaining'] > 0):
                logging.error(str(int(datetime.now().timestamp())) + ": [GetTL] API count limitation")
            else:
                logging.error(str(int(datetime.now().timestamp())) + ": [GetTL] can't get API limit status")
            rst['stat'] = 1
            return rst

        #--リクエストを投げ、ヘッダ経由でAPIstatを更新
        url_ustl = "https://api.twitter.com/1.1/statuses/user_timeline.json"
        request = self.twitter.get(url_ustl, params=param)
        for key in self.apistat.keys():
            #ヘッダ内のキー名とapistatのキー名を一致させる
            hdkey = {"limit" : "X-Rate-Limit-Limit","remaining" : "X-Rate-Limit-Remaining","reset" : "X-Rate-Limit-Reset"}
            self.apistat[key] = int(request.headers[hdkey[key]])

        rst['tweets'] = json.loads(request.text)
        return rst

    #--user_timeline APIの状態を更新
    def reloadAPIStat(self):
        try:
            #--rate-limit-statusを呼び出す
            apspath = "https://api.twitter.com/1.1/application/rate_limit_status.json"
            request = self.twitter.get(apspath)
            resp = json.loads(request.text)

            #--APIstatを更新
            for key in self.apistat.keys():
                self.intAPIStat[key] = int(resp['resources']['application']['/application/rate_limit_status'][key])
                self.apistat[key] = int(resp['resources']['statuses']['/statuses/user_timeline'][key])

            return 0
        except Exception as e:
            logging.error(str(int(datetime.now().timestamp())) + ": [GetTL(internal)] " + str(e))
            return 1

    #--APIの状態をローカルで取得
    def getAPIStat(self):
        #--データを取得した履歴がなければreload
        if(self.apistat['limit'] == -1):
            logging.debug(str(int(datetime.now().timestamp())) + ": [GetTL] Access to API-Limit-list endpoint")
            self.reloadAPIStat()
        return self.apistat


import tensorflow as tf
import numpy as np
import random
import gym
import math
import pickle
import hyperopt.pyll.stochastic

from stable_baselines.common.policies import MlpPolicy
from stable_baselines.common.vec_env import DummyVecEnv
from stable_baselines import TRPO
from hyperopt import hp

def get_space():
    """
        Defines the search space to sample from for each hyperparameter for the hyperparameter
        optimization. Define all parameters to tune in the given model here.

        Returns:
        --------
            dict-like expression graph consisting of nested function expressions for all
            hyperparameters to optimize.
    """
    space = {
            'timesteps_per_batch': hp.choice('timesteps_per_batch', [512, 1024, 2048, 4096, 8192]),
            'vf_stepsize': hp.loguniform('vf_stepsize', -5, -2),
            'max_kl' : hp.loguniform('max_kl', -2.5, -0.5),
            'gamma': hp.uniform('gamma', (1-(1/((10**(-1))*4))), (1-(1/((10**(1.5))*4)))), #4: Remember to change this if code is altered. -1:T/tau. tau=0.04=dt
            'lam': hp.uniform('lam', (1-(1/((10**(-1))*4))), (1-(1/((10**(1.5))*4)))) #4: Remember to change this if code is altered. -1:T/tau. tau=0.04=dt
            }
    return space

# Draw a specified number of configurations randomly from the search space
def sample(space, num_configs):
    """
        Returns a specified number of configurations drawn randomly from the search space

        Parameters:
        -----------
            space: dictionary containing function expressions for all hyperparameters to
                   optimize
            num_configs: number of sample configurations to draw from the search space

        Returns:
        --------
            samples: nested lists containing all sampled hyperparameter configurations and the
                     corresponding values of each hyperparameter.
    """
    samples = []
    for i in range(num_configs):
        samples.append(hyperopt.pyll.stochastic.sample(space))
    return samples

# Initialize the model to be trained
def get_model(env, samples, config_num=0):
    """
        Initializes the model to be evaluated, with specified hyperparameter values from a given
        configuration. In this case we want to run the cartpole environment using TRPO with a
        multilayer perceptron as the function approximator.

        Parameters:
        -----------
            samples: nested lists containing all sampled hyperparameter configurations and the
                     corresponding values of each hyperparameter.
            env: environment to evaluate model in
            config_num: number of the configuration sampled to evaluate

        Returns:
        --------
            model: initialized model with specified settings ready to be trained
    """
    model = TRPO(MlpPolicy, env,
              verbose=1,
              timesteps_per_batch=samples[config_num]['timesteps_per_batch'],
              vf_stepsize=samples[config_num]['vf_stepsize'],
              max_kl=samples[config_num]['max_kl'],
              gamma=samples[config_num]['gamma'],
              lam=samples[config_num]['lam']
            )
    return model

# Evaluation metric is calculated as the mean of the sum of episodic rewards for the given model.
def evaluate(env, model):
    """
        Computes evaluation metric. In this case, the metric chosen is the mean of
        the sum of episodic rewards obtained during training

        Parameters:
        -----------
            env: environment to evaluate model in
            model: current model in a given state during training

        Returns:
        --------
            mean of sum of episodic rewards for a full run of a given configuration
    """
    episode_rewards = []
    for _ in range(num_configs):
        reward_sum = 0
        done = False
        obs = env.reset()
        while not done:
            action, _states = model.predict(obs)
            obs, reward, done, info = env.step(action)
            reward_sum += reward
        episode_rewards.append(reward_sum)
    return np.mean(episode_rewards)

if __name__ == "__main__":

    num_configs = 3 #specify number of configurations to sample
    config_evals = [] #used to extract resulting metric after training of each config

    space = get_space()
    samples = sample(space, num_configs)

    for config_num in range(num_configs):
        # Fixed random state
        rand_state = np.random.RandomState(1).get_state()
        np.random.set_state(rand_state)
        seed = np.random.randint(1, 2**31 - 1)
        tf.set_random_seed(seed)
        random.seed(seed)

        env = gym.make('CartPole-v1') #initialize environment
        env = DummyVecEnv([lambda: env])

        model = get_model(env, samples, config_num)

        model.learn(total_timesteps=10000)
        model.save("trpo_cartpole_" + str(config_num))

        result = evaluate(env, model)
        config_evals.append([config_num, result])

        best = max(config_evals, key=lambda x: x[1])
    print("best: {} \n".format(best)) #configuration number best[0]

    model = TRPO.load(("trpo_cartpole_" + str(best[0])), env)
    obs = env.reset()
    print("Running best model...")
    for i in range(1000):
        action, _states = model.predict(obs)
        obs, rewards, dones, info = env.step(action)
        env.render()
    env.close()

    # See info on best model
    # model_info = pickle.load(open(("trpo_cartpole" + str(config_num) + ".pkl"), "rb"))

       # print("\n model info: {} \n".format(model_info))