from AIs.TP1 import *

maze = {(0, 0): {(0, 1): 1, (1, 0): 1},
        (0, 1): {(0, 2): 1, (0, 0): 1, (1, 1): 1},
        (0, 2): {(0, 1): 1},
        (0, 3): {(1, 3): 4},
        (0, 4): {(0, 5): 5},
        (0, 5): {(0, 6): 1, (0, 4): 5, (1, 5): 1},
        (0, 6): {(0, 7): 1, (0, 5): 1},
        (0, 7): {(0, 6): 1},
        (0, 8): {(0, 9): 1, (1, 8): 1},
        (0, 9): {(0, 10): 1, (0, 8): 1},
        (0, 10): {(0, 9): 1, (1, 10): 1},
        (1, 0): {(1, 1): 2, (0, 0): 1},
        (1, 1): {(1, 0): 2, (0, 1): 1, (2, 1): 1},
        (1, 2): {(1, 3): 1, (2, 2): 1},
        (1, 3): {(1, 4): 1, (1, 2): 1, (0, 3): 4},
        (1, 4): {(1, 5): 8, (1, 3): 1},
        (1, 5): {(1, 6): 1, (1, 4): 8, (0, 5): 1},
        (1, 6): {(1, 7): 1, (1, 5): 1, (2, 6): 1},
        (1, 7): {(1, 6): 1},
        (1, 8): {(0, 8): 1},
        (1, 9): {(1, 10): 1},
        (1, 10): {(1, 9): 1, (0, 10): 1, (2, 10): 1},
        (2, 0): {(2, 1): 1, (3, 0): 1},
        (2, 1): {(2, 0): 1, (1, 1): 1},
        (2, 2): {(2, 3): 1, (1, 2): 1, (3, 2): 2},
        (2, 3): {(2, 4): 1, (2, 2): 1, (3, 3): 1},
        (2, 4): {(2, 5): 1, (2, 3): 1},
        (2, 5): {(2, 4): 1},
        (2, 6): {(2, 7): 1, (1, 6): 1},
        (2, 7): {(2, 6): 1},
        (2, 8): {(2, 9): 1},
        (2, 9): {(2, 8): 1, (3, 9): 1},
        (2, 10): {(1, 10): 1, (3, 10): 1},
        (3, 0): {(2, 0): 1, (4, 0): 1},
        (3, 1): {(4, 1): 2},
        (3, 2): {(2, 2): 2, (4, 2): 1},
        (3, 3): {(3, 4): 1, (2, 3): 1},
        (3, 4): {(3, 5): 1, (3, 3): 1, (4, 4): 1},
        (3, 5): {(3, 6): 1, (3, 4): 1},
        (3, 6): {(3, 5): 1},
        (3, 7): {(3, 8): 1, (4, 7): 1},
        (3, 8): {(3, 7): 1},
        (3, 9): {(2, 9): 1, (4, 9): 4},
        (3, 10): {(2, 10): 1, (4, 10): 9},
        (4, 0): {(3, 0): 1, (5, 0): 1},
        (4, 1): {(4, 2): 1, (3, 1): 2, (5, 1): 1},
        (4, 2): {(4, 1): 1, (3, 2): 1},
        (4, 3): {(4, 4): 1},
        (4, 4): {(4, 3): 1, (3, 4): 1, (5, 4): 6},
        (4, 5): {(4, 6): 1, (5, 5): 1},
        (4, 6): {(4, 5): 1, (5, 6): 1},
        (4, 7): {(3, 7): 1, (5, 7): 1},
        (4, 8): {(4, 9): 1},
        (4, 9): {(4, 10): 1, (4, 8): 1, (3, 9): 4},
        (4, 10): {(4, 9): 1, (3, 10): 9, (5, 10): 1},
        (5, 0): {(5, 1): 6, (4, 0): 1, (6, 0): 1},
        (5, 1): {(5, 2): 1, (5, 0): 6, (4, 1): 1},
        (5, 2): {(5, 1): 1},
        (5, 3): {(5, 4): 1, (6, 3): 1},
        (5, 4): {(5, 5): 1, (5, 3): 1, (4, 4): 6, (6, 4): 1},
        (5, 5): {(5, 6): 1, (5, 4): 1, (4, 5): 1, (6, 5): 1},
        (5, 6): {(5, 7): 1, (5, 5): 1, (4, 6): 1, (6, 6): 6},
        (5, 7): {(5, 6): 1, (4, 7): 1},
        (5, 8): {(5, 9): 1},
        (5, 9): {(5, 10): 6, (5, 8): 1, (6, 9): 1},
        (5, 10): {(5, 9): 6, (4, 10): 1, (6, 10): 1},
        (6, 0): {(6, 1): 1, (5, 0): 1, (7, 0): 9},
        (6, 1): {(6, 2): 1, (6, 0): 1, (7, 1): 4},
        (6, 2): {(6, 1): 1},
        (6, 3): {(5, 3): 1, (7, 3): 1},
        (6, 4): {(6, 5): 1, (5, 4): 1},
        (6, 5): {(6, 4): 1, (5, 5): 1},
        (6, 6): {(6, 7): 1, (5, 6): 6, (7, 6): 1},
        (6, 7): {(6, 6): 1},
        (6, 8): {(6, 9): 1, (7, 8): 1},
        (6, 9): {(6, 8): 1, (5, 9): 1, (7, 9): 2},
        (6, 10): {(5, 10): 1, (7, 10): 1},
        (7, 0): {(6, 0): 9, (8, 0): 1},
        (7, 1): {(6, 1): 4, (8, 1): 1},
        (7, 2): {(7, 3): 1},
        (7, 3): {(7, 2): 1, (6, 3): 1},
        (7, 4): {(7, 5): 1},
        (7, 5): {(7, 6): 1, (7, 4): 1},
        (7, 6): {(7, 7): 1, (7, 5): 1, (6, 6): 1},
        (7, 7): {(7, 6): 1, (8, 7): 1},
        (7, 8): {(6, 8): 1, (8, 8): 2},
        (7, 9): {(6, 9): 2},
        (7, 10): {(6, 10): 1, (8, 10): 1},
        (8, 0): {(7, 0): 1, (9, 0): 1},
        (8, 1): {(8, 2): 1, (7, 1): 1},
        (8, 2): {(8, 1): 1},
        (8, 3): {(8, 4): 1},
        (8, 4): {(8, 3): 1, (9, 4): 1},
        (8, 5): {(8, 6): 1},
        (8, 6): {(8, 7): 1, (8, 5): 1},
        (8, 7): {(8, 8): 1, (8, 6): 1, (7, 7): 1},
        (8, 8): {(8, 7): 1, (7, 8): 2, (9, 8): 1},
        (8, 9): {(8, 10): 1, (9, 9): 1},
        (8, 10): {(8, 9): 1, (7, 10): 1},
        (9, 0): {(9, 1): 1, (8, 0): 1, (10, 0): 1},
        (9, 1): {(9, 0): 1},
        (9, 2): {(10, 2): 1},
        (9, 3): {(9, 4): 1},
        (9, 4): {(9, 5): 1, (9, 3): 1, (8, 4): 1},
        (9, 5): {(9, 6): 8, (9, 4): 1, (10, 5): 1},
        (9, 6): {(9, 7): 1, (9, 5): 8},
        (9, 7): {(9, 8): 1, (9, 6): 1, (10, 7): 4},
        (9, 8): {(9, 7): 1, (8, 8): 1},
        (9, 9): {(9, 10): 2, (8, 9): 1, (10, 9): 1},
        (9, 10): {(9, 9): 2, (10, 10): 1},
        (10, 0): {(10, 1): 1, (9, 0): 1},
        (10, 1): {(10, 2): 1, (10, 0): 1},
        (10, 2): {(10, 1): 1, (9, 2): 1},
        (10, 3): {(10, 4): 1},
        (10, 4): {(10, 5): 1, (10, 3): 1},
        (10, 5): {(10, 6): 5, (10, 4): 1, (9, 5): 1},
        (10, 6): {(10, 5): 5},
        (10, 7): {(9, 7): 4},
        (10, 8): {(10, 9): 1},
        (10, 9): {(10, 10): 1, (10, 8): 1, (9, 9): 1},
        (10, 10): {(10, 9): 1, (9, 10): 1}}

def aboveOf_unitTest(loc, goodLocation):
    try:
        location = aboveOf(loc)
        if type(location) != tuple:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The result has to be a tuple. Your result is of the type "+str(type(location))+".\n"
            print(ans)
            return False

        if type(location[0]) != int or type(location[1]) != int:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The result has to be a tuple of int. Your result is a tuple of the type ("+str(type(location[0]))+","+str(type(location[1]))+".\n"
            print(ans)
            return False

        if location!=goodLocation:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The cell above (i,j) is (i,j+1).\n"
            print(ans)
            return False
        return True
    except:
        ans = "    Error -- Your function did not work. \n"
        ans += "    location : "+str(loc)+" \n"
        print(ans)
        return False

def functionAboveOfTest():
    print("TEST of the function 'aboveOf'")
    result = True
    result = result and aboveOf_unitTest((0,0),(0,1))
    result = result and aboveOf_unitTest((12,-7),(12,-6))

    return result

def belowOf_unitTest(loc, goodLocation):
    try:
        location = belowOf(loc)
        if type(location) != tuple:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The result has to be a tuple. Your result is of the type "+str(type(location))+".\n"
            print(ans)
            return False

        if type(location[0]) != int or type(location[1]) != int:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The result has to be a tuple of int. Your result is a tuple of the type ("+str(type(location[0]))+","+str(type(location[1]))+".\n"
            print(ans)
            return False

        if location!=goodLocation:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The cell below (i,j) is (i,j-1).\n"
            print(ans)
            return False
        return True
    except:
        ans = "    Error -- Your function did not work. \n"
        ans += "    location : "+str(loc)+" \n"
        print(ans)
        return False

def functionBelowOfTest():
    print("TEST of the function 'belowOf'")
    result = True

    result = result and belowOf_unitTest((0,0),(0,-1))
    result = result and belowOf_unitTest((12,-7),(12,-8))

    return result

def leftOf_unitTest(loc, goodLocation):
    try:
        location = leftOf(loc)
        if type(location) != tuple:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The result has to be a tuple. Your result is of the type "+str(type(location))+".\n"
            print(ans)
            return False

        if type(location[0]) != int or type(location[1]) != int:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The result has to be a tuple of int. Your result is a tuple of the type ("+str(type(location[0]))+","+str(type(location[1]))+".\n"
            print(ans)
            return False

        if location!=goodLocation:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The cell on the left of (i,j) is (i-1,j).\n"
            print(ans)
            return False
        return True
    except:
        ans = "    Error -- Your function did not work. \n"
        ans += "    location : "+str(loc)+" \n"
        print(ans)
        return False

def functionLeftOfTest():
    print("TEST of the function 'leftOf'")
    result = True

    result = result and leftOf_unitTest((0,0),(-1,0))
    result = result and leftOf_unitTest((-12,7),(-13,7))

    return result

def rightOf_unitTest(loc, goodLocation):
    try:
        location = rightOf(loc)
        if type(location) != tuple:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The result has to be a tuple. Your result is of the type "+str(type(location))+".\n"
            print(ans)
            return False

        if type(location[0]) != int or type(location[1]) != int:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The result has to be a tuple of int. Your result is a tuple of the type ("+str(type(location[0]))+","+str(type(location[1]))+".\n"
            print(ans)
            return False

        if location!=goodLocation:
            ans = "    Error -- The expected answer is "+str(goodLocation)+". Your answer is : "+str(location)+".\n"
            ans += "    location : "+str(loc)+" \n"
            ans += "    The cell on the right of (i,j) is (i+1,j).\n"
            print(ans)
            return False
        return True
    except:
        ans = "    Error -- Your function did not work. \n"
        ans += "    location : "+str(loc)+" \n"
        print(ans)
        return False

def functionRightOfTest():
    print("TEST of the function 'rightOf'")
    result = True

    result = result and rightOf_unitTest((0,0),(1,0))
    result = result and rightOf_unitTest((-12,7),(-11,7))

    return result

def canMove_unitTest(maze, start, end, goodAns):
    try:
        result = canMove(maze,start,end)
        if type(result) != bool:
            ans = "    Error -- The expected answer is "+str(goodAns)+". Your answer is : "+str(result)+".\n"
            ans += "    mazeMap : "+str(maze)+"\n"
            ans += "    fromLocation : "+str(start)+" \n"
            ans += "    toLocation : "+str(end)+" \n"
            ans += "    The result has to be a boolean. Your result is of the type "+str(type(result))+".\n"
            print(ans)
            return False

        if result != goodAns:
            ans = "    Error -- The expected answer is "+str(goodAns)+". Your answer is : "+str(result)+".\n"
            ans += "    mazeMap : "+str(maze)+"\n"
            ans += "    You can pass from location "+str(start)+" to location "+str(end)+".\n"
            print(ans)
            return False
        return True
    except:
        ans = "    Error -- Your function did not work. \n"
        ans += "    mazeMap : "+str(maze)+"\n"
        ans += "    fromLocation : "+str(start)+" \n"
        ans += "    toLocation : "+str(end)+" \n"
        print(ans)
        return False

def functionCanMoveTest():
    print("TEST of the function 'canMove'")
    result = True

    result = result and canMove_unitTest(maze,(0,0),(0,1),True)
    result = result and canMove_unitTest(maze,(0,1),(0,0),True)
    result = result and canMove_unitTest(maze,(0,0),(-1,0),False)
    result = result and canMove_unitTest(maze,(-1,0),(0,0),False)
    result = result and canMove_unitTest(maze,(1,4),(2,4),False)
    result = result and canMove_unitTest(maze,(2,4),(1,4),False)
    result = result and canMove_unitTest(maze,(0,5),(0,4),True)
    result = result and canMove_unitTest(maze,(10,10),(11,10),False)
    result = result and canMove_unitTest(maze,(10,11),(10,10),False)
    result = result and canMove_unitTest(maze,(15,15),(15,16),False)
    result = result and canMove_unitTest(maze,(0,0),(1,1),False)

    return result

def getMove_unitTest(maze,start,end,goodAns):
    try:
        result = getMove(maze,start,end)
        if type(result) != str:
            ans = "    Error -- The expected answer is '"+str(goodAns)+"'. Your answer is : "+str(result)+".\n"
            ans += "    mazeMap : "+str(maze)+" \n"
            ans += "    fromLocation : "+str(start)+" \n"
            ans += "    toLocation : "+str(end)+" \n"
            ans += "    The result has to be a string. Your result is of the type "+str(type(result))+".\n"
            print(ans)
            return False

        if not (result == 'D' or result == 'U' or result == 'L' or result == 'R' or result == 'None'):
            ans = "    Error -- The expected answer is '"+str(goodAns)+"'. Your answer is : "+str(result)+".\n"
            ans += "    mazeMap : "+str(maze)+"\n"
            ans += "    fromLocation : "+str(start)+" \n"
            ans += "    toLocation : "+str(end)+" \n"
            ans += "    The result has to be a string from this list : 'D' / 'U' / 'L' / 'R' / 'None'.\n"
            print(ans)
            return False

        if result != goodAns:
            ans = "    Error -- The expected answer is '"+str(goodAns)+"'. Your answer is : "+str(result)+".\n"
            ans += "    mazeMap : "+str(maze)+"\n"
            ans += "    You can pass from location "+str(start)+" to location "+str(end)+".\n"
            print(ans)
            return False
        return True
    except:
        ans = "    Error -- Your function did not work. \n"
        ans += "    mazeMap : "+str(maze)+"\n"
        ans += "    fromLocation : "+str(start)+" \n"
        ans += "    toLocation : "+str(end)+" \n"
        print(ans)
        return False

def functionGetMoveTest():
    print("TEST of the function 'getMove'")
    result = True

    result = result and getMove_unitTest(maze,(0,0),(0,1),"U")
    result = result and getMove_unitTest(maze,(0,1),(0,0),"D")
    result = result and getMove_unitTest(maze,(0,0),(-1,0),"None")
    result = result and getMove_unitTest(maze,(0,0),(1,0),"R")
    result = result and getMove_unitTest(maze,(1,5),(0,5),"L")

    return result

def giveResult(result):
    if result:
        print("----COMPLETE \n")
    else:
        print("----ERROR \n")

def main():
    testSuccess = 0
    result = functionAboveOfTest()
    giveResult(result)
    testSuccess += result

    result = functionBelowOfTest()
    giveResult(result)
    testSuccess += result

    result = functionLeftOfTest()
    giveResult(result)
    testSuccess += result

    result = functionRightOfTest()
    giveResult(result)
    testSuccess += result

    result = functionCanMoveTest()
    giveResult(result)
    testSuccess += result

    result = functionGetMoveTest()
    giveResult(result)
    testSuccess += result

    if testSuccess==6:
        print("----------TOTAL NUMBER OF TESTS : 6")
        print("----------COMPLETE SUCCESS")
    else:
        print("----------TOTAL NUMBER OF TESTS : 6")
        print("----------ERRORS : "+str(6-testSuccess))
        print("----------SUCCESS : "+str(testSuccess))

if __name__ == "__main__":
    main()


from __future__ import division

import torch
from torch.utils.data import Dataset
from torchvision.transforms import Normalize
import numpy as np
import cv2
from os.path import join

import config
import constants
from utils.imutils import crop, flip_img, flip_pose, flip_kp, transform, rot_aa
import glob
import pytorch3d
from pytorch3d import ops, io, transforms

class AtlasDataset(Dataset):
    """
    Base Dataset Class - Handles data loading and augmentation.
    Able to handle heterogeneous datasets (different annotations available for different datasets).
    You need to update the path to each dataset in utils/config.py.
    """

    def __init__(self, options, dataset, ignore_3d=False, use_augmentation=True, is_train=True):
        super(AtlasDataset, self).__init__()
        self.dataset = dataset
        self.is_train = is_train
        self.options = options
        self.img_dir = config.DATASET_FOLDERS[dataset]
        self.normalize_img = Normalize(mean=constants.IMG_NORM_MEAN, std=constants.IMG_NORM_STD)
        self.data = np.load(config.DATASET_FILES[is_train][dataset])
        self.imgname = self.data['imgname']
        self.mapname = self.data['mapname']
        self.simname = self.data['simname']

        # Get paths to gt masks, if available
        try:
            self.maskname = self.data['maskname']
        except KeyError:
            pass
        try:
            self.partname = self.data['partname']
        except KeyError:
            pass

        # Bounding boxes are assumed to be in the center and scale format
        self.scale = self.data['scale']
        self.center = self.data['center']

        # If False, do not do augmentation
        self.use_augmentation = use_augmentation

        # Get gt SMPL parameters, if available
        self.pose = self.data['pose'].astype(np.float)
        self.betas = self.data['shape'].astype(np.float)
        self.trans = self.data['trans'].astype(np.float)
        if 'has_smpl' in self.data:
            self.has_smpl = self.data['has_smpl']
        else:
            self.has_smpl = np.ones(len(self.imgname))
        if ignore_3d:
            self.has_smpl = np.zeros(len(self.imgname))

        # Get gt 3D pose, if available
        try:
            self.pose_3d = self.data['S']
            self.has_pose_3d = 1
        except KeyError:
            self.has_pose_3d = 0
        if ignore_3d:
            self.has_pose_3d = 0

        # Get 2D keypoints
        try:
            keypoints_gt = self.data['part']
        except KeyError:
            keypoints_gt = np.zeros((len(self.imgname), 24, 3))
        try:
            keypoints_openpose = self.data['openpose']
        except KeyError:
            keypoints_openpose = np.zeros((len(self.imgname), 25, 3))
        self.keypoints = np.concatenate([keypoints_openpose, keypoints_gt], axis=1)

        # Get gender data, if available
        try:
            gender = self.data['gender']
            self.gender = np.array([0 if str(g) == 'm' else 1 for g in gender]).astype(np.int32)
        except KeyError:
            self.gender = -1*np.ones(len(self.imgname)).astype(np.int32)

        self.length = self.scale.shape[0]

    def augm_params(self):
        """Get augmentation parameters."""
        flip = 0            # flipping
        pn = np.ones(3)  # per channel pixel-noise
        rot = 0            # rotation
        sc = 1            # scaling
        if self.is_train:
            # We flip with probability 1/2
            if np.random.uniform() <= 0.5:
                flip = 1

            # Each channel is multiplied with a number
            # in the area [1-opt.noiseFactor,1+opt.noiseFactor]
            pn = np.random.uniform(1-self.options.noise_factor, 1+self.options.noise_factor, 3)

            # The rotation is a number in the area [-2*rotFactor, 2*rotFactor]
            rot = min(2*self.options.rot_factor,
                    max(-2*self.options.rot_factor, np.random.randn()*self.options.rot_factor))

            # The scale is multiplied with a number
            # in the area [1-scaleFactor,1+scaleFactor]
            sc = min(1+self.options.scale_factor,
                    max(1-self.options.scale_factor, np.random.randn()*self.options.scale_factor+1))
            # but it is zero with probability 3/5
            if np.random.uniform() <= 0.6:
                rot = 0

        return flip, pn, 0, sc

    def load_points(self, path):
        lists = glob.glob(path)
        mesh = io.load_objs_as_meshes(lists)
        pts, nms = ops.sample_points_from_meshes(mesh, self.options.num_points // len(lists), return_normals=True)
        pts = pts.reshape([-1,3])
        return pts, nms.reshape([-1,3]) * 0.1

    def map_processing(self, map_img, center, scale, rot, flip, pn):
        """data aug for pytorch3d"""
        tr = pytorch3d.transforms.RotateAxisAngle(rot, axis='Z')
        pt = tr.transform_points(map_img)
        if flip:
            pt[:,0] = -pt[:,0]
        return pt

    def map_processing_legacy(self, map_img, center, scale, rot, flip, pn):
        """Process rgb image and do augmentation."""
        map_img = np.roll(map_img, 64, axis=1)
        rot_mat = np.eye(3)
        if not rot == 0:
            rot_rad = rot * np.pi / 180
            sn,cs = np.sin(rot_rad), np.cos(rot_rad)
            rot_mat[0,:2] = [cs, -sn]
            rot_mat[1,:2] = [sn, cs]
        map_img = np.reshape(map_img, [256*256,4])
        map_img[:,:3] = np.einsum('ij,kj->ki', rot_mat, map_img[:,:3])
        map_img = np.reshape(map_img, [256, 256, 4])
        # flip the image
        if flip:
            map_img = map_img[:,::-1,:]
            map_img[:,:,0] = -map_img[:,:,0]
        # (3,224,224),float,[0,1]
        map_img = np.transpose(map_img.astype('float32'),(2,0,1))
        return map_img

    def pose_processing(self, pose, r, f):
        """Process SMPL theta parameters  and apply all augmentation transforms."""
        # rotation or the pose parameters
        pose[:3] = rot_aa(pose[:3], r)
        # flip the pose parameters
        if f:
            pose = flip_pose(pose)
        # (72),float
        pose = pose.astype('float32')
        return pose

    def __getitem__(self, index):
        # index = 0
        item = {}
        scale = self.scale[index].copy()
        center = self.center[index].copy()

        # Get augmentation parameters
        flip, pn, rot, sc = self.augm_params()
        #print(rot)
        # Get SMPL parameters, if available
        if self.has_smpl[index]:
            pose = self.pose[index].copy()
            betas = self.betas[index].copy()
            trans = torch.from_numpy(self.trans[index].copy()).float()
        else:
            pose = np.zeros(72)
            betas = np.zeros(10)

        # Store image before normalization to use it in visualization
        clothmap, normmap = self.load_points(join(self.img_dir, self.simname[index]))
        clothmap = self.map_processing(clothmap - trans, center, sc*scale, rot, flip, pn)

        normmap = self.map_processing(normmap, center, sc*scale, rot, flip, pn)
        item['map'] = clothmap.float()
        item['normmap'] = normmap.float()
        item['pose'] = torch.from_numpy(self.pose_processing(pose, rot, flip)).float()
        item['betas'] = torch.from_numpy(betas).float()

        item['rot_angle'] = np.float32(rot)
        item['gender'] = self.gender[index]
        item['sample_index'] = index
        item['dataset_name'] = self.dataset
        item['dataname'] = self.imgname[index]

        return item

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


# http://planetpixelemporium.com/tutorialpages/light.html
import colorsys

kelvin_temperature_colors = {

    "candle": (255, 147, 41),
    "40w_tungsten": (255, 197, 143),
    "100w_tungsten": (255, 214, 170),
    "halogen": (255, 241, 224),
    "carbon_arc": (255, 250, 244),
    "high_noon_sun": (255, 255, 251),
    "direct_sunlight": (255, 255, 255),  # white
    "overcast_sky": (201, 226, 255),
    "clear_blue_sky": (64, 156, 255),
}
background_colors = {
    'black': (0, 0, 0),
    'gray': (127, 127, 127),
    'light_gray': (180, 180, 180),
    'blueberry': (127, 127, 255),
}
strip_colors = {
    # for top edge
    'high_th': (150, 65, 90),
    'mid_th': (65, 55, 90),
    'low_th': (48, 65, 95),
    'purple': (127, 0, 255),
    # for bottom edge
    'high_ca': (137, 64, 109),
    'mid_ca': (120, 75, 55),
    'low_ca': (150, 75, 10),
}

def color_distance(left, right):
    return sum((l - r) ** 2 for l, r in zip(left, right)) ** 0.5

def color_label(color):
    """convert a rgb to a color name"""

    key_colors = {**kelvin_temperature_colors, **background_colors, **strip_colors}
    nearest_color = lambda key_colors: color_distance(color, key_colors[1])

    label, key_color = min(key_colors.items(), key=nearest_color)
    is_backgound_color = label in background_colors or label in kelvin_temperature_colors
    return label, not is_backgound_color

def rgb_to_hsv(r, g, b):
    r, g, b = r / 255.0, g / 255.0, b / 255.0
    h,s,v = colorsys.rgb_to_hsv(r, g, b)
    h,s,v = round(h, 6), round(s, 6), round(v, 6)
    return h,s,v


from ninfo import PluginBase

class shodan_plug(PluginBase):
    """This plugin returns any information from Shodan"""
    name    =    'shodan'
    title   =    'Shodan'
    description   =  'Computer Search Engine'
    cache_timeout   =  60*60*2
    types   =    ['ip']
    remote = False

    def setup(self):
        from shodan import WebAPI
        self.api = WebAPI(self.plugin_config["api_key"])

    def get_info(self, arg):
        info = self.api.host(arg)
        return info

plugin_class = shodan_plug


"""
Keybindings
"""

from libqtile.config import Key, Click, Drag
from libqtile.lazy import lazy
from settings import MOD, TERMINAL, BROWSER

MOD_S = [MOD, "shift"]
MOD_C = [MOD, "control"]

keys = [
    # A list of available commands that can be bound to keys can be found
    # at https://docs.qtile.org/en/latest/manual/config/lazy.html
    # Switch between windows
    Key([MOD], "h", lazy.layout.left(), desc="Move focus to left"),
    Key([MOD], "l", lazy.layout.right(), desc="Move focus to right"),
    Key([MOD], "j", lazy.layout.down(), desc="Move focus down"),
    Key([MOD], "k", lazy.layout.up(), desc="Move focus up"),
    Key(["mod1"], "Tab", lazy.layout.next(), desc="Focus next window"),
    # Move windows between left/right columns or move up/down in current stack.
    # Moving out of range in Columns layout will create new column.
    Key(MOD_S, "h", lazy.layout.shuffle_left(), desc="Move window to the left"),
    Key(MOD_S, "l", lazy.layout.shuffle_right(), desc="Move window to the right"),
    Key(MOD_S, "j", lazy.layout.shuffle_down(), desc="Move window down"),
    Key(MOD_S, "k", lazy.layout.shuffle_up(), desc="Move window up"),
    # Grow windows. If current window is on the edge of screen and direction
    # will be to screen edge - window would shrink.
    Key(MOD_C, "h", lazy.layout.grow_left(), desc="Grow window to the left"),
    Key(MOD_C, "l", lazy.layout.grow_right(), desc="Grow window to the right"),
    Key(MOD_C, "j", lazy.layout.grow_down(), desc="Grow window down"),
    Key(MOD_C, "k", lazy.layout.grow_up(), desc="Grow window up"),
    Key([MOD], "n", lazy.layout.normalize(), desc="Reset all window sizes"),
    # Toggle between split and unsplit sides of stack.
    # Split = all windows displayed
    # Unsplit = 1 window displayed, like Max layout, but still with
    # multiple stack panes
    Key(MOD_S, "Return", lazy.layout.toggle_split(), desc="Toggle split/unsplit"),
    # Toggle between different layouts as defined below
    Key([MOD], "space", lazy.next_layout(), desc="Toggle between layouts"),
    # Misc
    Key([MOD], "w", lazy.window.kill(), desc="Kill focused window"),
    Key(MOD_C, "r", lazy.reload_config(), desc="Reload the config"),
    Key(MOD_C, "q", lazy.shutdown(), desc="Shutdown Qtile"),
    Key([MOD], "f", lazy.window.toggle_fullscreen(), desc="Toggle Fullscreen"),
    Key(MOD_C, "f", lazy.window.toggle_floating(), desc="Toggle Floating"),
    # Applaunch
    Key([MOD], "Return", lazy.spawn(TERMINAL), desc="Launch terminal"),
    Key([MOD], "b", lazy.spawn(BROWSER), desc=f"Launch {BROWSER}"),
    Key([MOD], "c", lazy.spawn(".config/qtile/scripts/lock.sh"), desc="Lock Screen"),
    Key(
        ["mod1"],
        "space",
        lazy.spawn(".config/rofi/launchers/misc/launcher.sh"),
        desc="Spawn a command using a prompt widget",
    ),
    # Media Keys
    Key([], "XF86AudioRaiseVolume", lazy.spawn("pactl set-sink-volume 0 +5%")),
    Key([], "XF86AudioLowerVolume", lazy.spawn("pactl set-sink-volume 0 -5%")),
    Key([], "XF86AudioMute", lazy.spawn("pactl set-sink-mute 0 toggle")),
    Key([], "XF86AudioMute", lazy.spawn("pactl set-sink-mute 0 toggle")),
    Key([], "XF86AudioMute", lazy.spawn("pactl set-sink-mute 0 toggle")),
    Key([], "XF86AudioPlay", lazy.spawn("playerctl play-pause")),
    Key([], "XF86AudioPrev", lazy.spawn("playerctl previous")),
    Key([], "XF86AudioNext", lazy.spawn("playerctl next")),
    # Brightness control
    Key([], "XF86MonBrightnessUp", lazy.spawn("xbacklight -inc 5%")),
    Key([], "XF86MonBrightnessDown", lazy.spawn("xbacklight -dec 10%")),
    Key([], "Print", lazy.spawn("flameshot gui")),
    Key([MOD], "Print", lazy.spawn("flameshot full")),
    # Notification Center
    Key([MOD], "y", lazy.spawn("sh .config/qtile/scripts/notification_toggle.sh")),
    Key([MOD], "v", lazy.spawn("sh .config/qtile/scripts/multi_monitor.sh")),
]

# Drag floating layouts.
mouse = [
    Drag(
        [MOD],
        "Button1",
        lazy.window.set_position_floating(),
        start=lazy.window.get_position(),
    ),
    Drag(
        [MOD], "Button3", lazy.window.set_size_floating(), start=lazy.window.get_size()
    ),
    Click([MOD], "Button2", lazy.window.bring_to_front()),
]


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   __init__.py
@Time    :   2019/04/12 16:35:09
@Author  :   jiegemena
@Version :   1.0
@Contact :   jiegemena@outlook.com
@License :   https://github.com/jiegemena
@Desc    :   None
'''

# here put the import lib
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   main.py
@Time    :   2019/04/12 16:33:48
@Author  :   jiegemena
@Version :   1.0
@Contact :   jiegemena@outlook.com
@License :   https://github.com/jiegemena
@Desc    :   None
'''

# here put the import lib
from flask import Flask, request
import os
from datetime import timedelta
from jgpycshare.LogTools import LogTools
import area
import json
import tools

basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

def create_app():

    app = Flask(__name__)
    app.config.from_object('config')
    if app.config['DEBUG']:
        app.config['SECRET_KEY'] = os.urandom(24)  # 设置为24位的字符,每次运行服务器都是不同的，所以服务器启动一次上次的session就清除。
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)  # 设置session的保存时间。

    app.secret_key = app.config['SECRET_KEY']

    flask_logging(app)
    flask_init(app)
    flask_blueprints(app)
    # register_commands(app)
    register_errors(app)
    # register_shell_context(app)
    flask_template_context(app)

    sql_intercept = app.config['REQUEST_INTERCEPT']
    sql_intercept = sql_intercept.split('|')
    flask_request_handlers(app, sql_intercept)
    return app

def flask_logging(app):
    log = tools.qxlog()
    app.config['log'] = log
    log.info("info")
    log.debug("debug")
    log.error("error")
    log.info("info")

# 初始化应用
def flask_init(app):
    if os.path.exists(app.config['SQL_INIT'] + '.lock') is False:
        file = open(app.config['SQL_INIT'] + '.lock', 'w')
        file.write('del it create new database!')
        file.close()

        db = tools.db_sqlite3(sql_conn_str=app.config['SQL_CONN'])
        with open(app.config['SQL_INIT'], 'r') as f:
            db.get_db().executescript(f.read())
            print("db init successfully")
    ### register consul
    tools.unregister()
    if app.config['CONSUL_STATE']:
        tools.register()

def flask_blueprints(app):
    # app.register_blueprint(area.api_bp, url_prefix='/api')
    # app.register_blueprint(area.admin_bp, url_prefix='/admin')
    app.register_blueprint(area.guest_bp, url_prefix='/')
    # app.register_blueprint(web_bp)

# def register_shell_context(app):
#     @app.shell_context_processor
#     def make_shell_context():
#         return dict(db='db')

# 可以在 模板处 : {{test}}
def flask_template_context(app):
    @app.context_processor
    def make_template_context():
        return dict(test='test')

def register_errors(app):
    @app.errorhandler(400)
    def bad_request(e):
        return '400 error'

    @app.errorhandler(404)
    def page_not_found(e):
        return '500 error'

    @app.errorhandler(500)
    def internal_server_error(e):
        return '500 error'

def flask_request_handlers(app, sql_intercept):
    @app.after_request
    def after_request(response):
        # token = 'asdfaasdf'
        # response.set_cookie('csrf_token', token)
        # print('request end')
        return response

    @app.before_request
    def print_request_info():
        log = app.config['log']
        log.info("请求地址:" + str(request.path))
        log.info("GET参数：" + str(request.args))
        log.info("POST参数：" + str(request.form))
        for key in request.args:
            for k in sql_intercept:
                if (request.args[key]).find(k) >= 0:
                    return 'have get sql_intercept par:' + k

        for key in request.form:
            for k in sql_intercept:
                if (request.form[key]).find(k) >= 0:
                    return 'have post sql_intercept par:' + k


'''
给定一个只包括 '('，')'，'{'，'}'，'['，']' 的字符串 s ，判断字符串是否有效。

有效字符串需满足：

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
'''

# date:2021-12-12
# author: cy-book

parenthesisMap = {
    '{': '}',
    '(': ')',
    '[': ']'
}

def isValid(s: str) -> bool:
    stack = list()
    for ch in s:
        if ch in '({[':
            stack.append(ch)
        else:
            if stack and parenthesisMap[stack.pop()] == ch:
                continue
            else:
                return False
    return True if not stack else False


class Solution(object):
    """ Solution for Leetcode problem 39: Combination Sum. """

    def combination_sum(self, nums, target):
        """Find all comb. of nums in a list that sum to a given target.

        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """

        def recursion(rem, so_far, cut_off):
            if rem == 0:
                self.result.append(so_far)
                return

            for i in range(cut_off, len(self.nums)):
                if rem - self.nums[i] >= 0:
                    recursion(rem - self.nums[i], so_far + [self.nums[i]], i)
                else: break

        self.nums = sorted(nums)
        self.result = []

        recursion(target, [], 0)
        return self.result

import unittest

class ProblemTest(unittest.TestCase):
    """ Tests for Leetcode problem 39: Combination Sum. """

    def sort_list(self, mylist):
        return sorted( [ sorted(x) for x in mylist ])

    def test(self):

        cases = [
            {'input': [[2,3,6,7], 7], 'exp': [[7], [2,2,3]] },
            {'input': [[2,3,4,5], 8],
                'exp': [[2,2,2,2], [2,2,4], [2,3,3], [3,5], [4,4]]}
        ]

        for each_case in cases:
            expect = self.sort_list( each_case['exp'])
            answer = self.sort_list( Solution().combination_sum( *each_case['input'] ))
            self.assertEqual(expect, answer)

if __name__ == '__main__':
    unittest.main()


import cv2

imageName = 'data/images/opening.png'

image = cv2.imread(imageName, 0)

cv2.imshow('original', image)

#Opening이란
openingSize = 3

element = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,
                                    (2*openingSize+1, 2*openingSize+1) )

#iterations= 파라미터로 반복되는 것 지정해줌
imageOpened = cv2.morphologyEx(image, cv2.MORPH_OPEN, element, iterations=2)

cv2.imshow('Opened Image', imageOpened)

cv2.waitKey()
cv2.destroyAllWindows()


"""
Train a QWOP agent.
"""

import argparse
import itertools
import logging
import os

from anyrl.algos import PPO
from anyrl.models import CNN
from anyrl.spaces import gym_space_distribution, gym_space_vectorizer
import gym
import tensorflow as tf

from qwop_master.conn import Conn
from qwop_master.roller import RemoteRoller

def main():
    args = arg_parser().parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    conn = Conn(args.redis_host, args.redis_port, args.channel, obs_size=args.obs_size)

    with tf.Session() as sess:
        model = create_model(args, sess)
        roller = RemoteRoller(model, conn,
                              min_timesteps=args.min_timesteps,
                              min_horizon=args.min_horizon,
                              min_step_batch=args.min_step_batch,
                              timeout=args.env_timeout)
        ppo = PPO(model, epsilon=args.ppo_epsilon, entropy_reg=args.ppo_entropy)
        optimize = ppo.optimize(learning_rate=args.ppo_lr)

        saver = tf.train.Saver()
        ckpt_file = os.path.join(args.checkpoint, 'model.ckpt')

        sess.run(tf.global_variables_initializer())
        if os.path.exists(args.checkpoint):
            saver.restore(sess, ckpt_file)

        for outer_iter in itertools.count():
            rollouts = roller.rollouts()
            logging.info('mean cumulative reward: %f',
                         sum(r.total_reward for r in rollouts) / len(rollouts))
            ppo.run_optimize(optimize, rollouts,
                             batch_size=args.ppo_batch,
                             num_iter=args.ppo_iter,
                             log_fn=lambda x: logging.info('%s', x))
            if outer_iter % args.save_interval == 0:
                saver.save(sess, os.path.join(args.checkpoint, 'model.ckpt'))

def create_model(args, sess):
    act_space = gym.spaces.MultiBinary(args.act_size)
    obs_space = gym.spaces.Box(low=0, high=0xff, shape=[args.obs_size] * 2 + [3], dtype='uint8')
    return CNN(sess, gym_space_distribution(act_space), gym_space_vectorizer(obs_space))

def arg_parser():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--verbose', help='Show debug logs', action='store_true')

    parser.add_argument('--redis-host', help='Redis host', default='qwop-redis')
    parser.add_argument('--redis-port', help='Redis port', default=6379, type=int)
    parser.add_argument('--channel', help='worker channel prefix', default='qwop-worker')
    parser.add_argument('--checkpoint', help='agent checkpoint directory', default='checkpoint')
    parser.add_argument('--save-interval', help='training iters per save', default=5, type=int)
    parser.add_argument('--obs-size', help='observation image size', default=84, type=int)
    parser.add_argument('--act-size', help='action vector size', default=4, type=int)

    parser.add_argument('--min-timesteps', help='minimum timesteps per batch', default=1024,
                        type=int)
    parser.add_argument('--min-horizon', help='minimum timesteps per rollout', default=16, type=int)
    parser.add_argument('--min-step-batch', help='minimum batch size per step', default=1, type=int)
    parser.add_argument('--env-timeout', help='the environment timeout', default=300, type=int)

    parser.add_argument('--ppo-epsilon', help='the PPO clipping factor', default=0.2, type=float)
    parser.add_argument('--ppo-entropy', help='the PPO entropy bonus', default=0.01, type=float)
    parser.add_argument('--ppo-lr', help='the PPO learning rate', default=1e-4, type=float)
    parser.add_argument('--ppo-batch', help='the PPO batch size', default=256, type=int)
    parser.add_argument('--ppo-iter', help='the PPO iteration count', default=16, type=int)

    return parser

if __name__ == '__main__':
    main()


import asyncio

# Создаем экземпляр Event
event = asyncio.Event()

async def waiter():
    print('waiter: ожидаем события')
    await event.wait()
    print('waiter: событие произошло')

async def setter():
    print('setter: засыпаем')
    await asyncio.sleep(1)
    print('setter: просыпаемся и устанавливаем событие')
    event.set()

async def main():
    # Запускаем waiter и setter параллельно
    await asyncio.gather(waiter(), setter())

asyncio.run(main())


#The part where the face data of the person is taken and recorded in the system
import cv2
# Camera Settings
cameraWidth = 1020
cameraHeight = 720

# Face Detect Class
classifierFolder = 'haarcascade_frontalface_default.xml'
face_detector = cv2.CascadeClassifier(classifierFolder)

# Face Data Folder
faceDataFolder = "Datas/FaceDatas"

# Create Camera
#camera = cv2.VideoCapture(1)
camera = cv2.VideoCapture(0,cv2.CAP_DSHOW).release()
camera=cv2.VideoCapture(0,cv2.CAP_DSHOW)

# Camera Settings Late
camera.set(3, cameraWidth)
camera.set(4, cameraHeight)

# region Face Scan Function
def FaceCapture():
    # Captured face count
    count = 0
    # Face capture process
    while True:
        ret, img = camera.read()
        img = cv2.flip(img, 1)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = face_detector.detectMultiScale(gray, 1.4, 5)
        for (x, y, w, h) in faces:
            cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
            count += 1
            # Save captured face to FaceData folder
            cv2.imwrite(f"{faceDataFolder}/user.{str(userToken)}.{str(count)}.jpg", gray[y:y + h, x:x + w])
            cv2.imshow('image', img)
        k = cv2.waitKey(100) & 0xff  # 'ESC' to stop capturing
        if k == 27:
            break
        elif count >= 50:  # Take 50 faces to stop capture
            break

# endregion

userID = input("User ID : ")

userToken = userID

print("Initializing face capture. Look the camera and wait..")
FaceCapture()
print("Face is captured.")

# Clean and close camera window
camera.release()
cv2.destroyAllWindows()


from aoc2020.common import testing
from aoc2020.common import puzzle_input
from . import solution

class Test(testing.TimedTestCase):
    def test_part1_example1(self):
        example_input1 = puzzle_input.from_example(__file__, 1)  # 2/4 fail
        entries = solution.partition_entries(example_input1)
        self.assertEqual(2, sum(map(solution.validate_entry1, entries)))

    def test_part2_example2(self):
        example_input2 = puzzle_input.from_example(__file__, 2)  # all fail
        entries = solution.partition_entries(example_input2)
        self.assertFalse(all(map(solution.validate_entry2, entries)))

    def test_part2_example3(self):
        example_input2 = puzzle_input.from_example(__file__, 3)  # all pass
        entries = solution.partition_entries(example_input2)
        self.assertTrue(all(map(solution.validate_entry2, entries)))


from abc import abstractmethod
from math import ceil

from PyQt5 import QtCore
from PyQt5.QtGui import QFont, QCursor
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QHBoxLayout, QScrollArea

class PageHelper:
    def __init__(self, UI, PageItemNum):
        self._UI = UI
        self._PageItemNum = PageItemNum
        self._currentPageNum = 0
        self._isFilter = False
        self._tempHL_List = []
        self._numBTN_List = []

        self._initClick()
    def _initClick(self):
        def leftClick(evt):
            if self._currentPageNum>0:
                self.toPage(self._currentPageNum-1)
        self._UI.leftBTN.clicked.connect(leftClick)
        def rightClick(evt):
            if self._currentPageNum<self.pageCount-1:
                self.toPage(self._currentPageNum+1)
        self._UI.rightBTN.clicked.connect(rightClick)
        def toFirst(evt):
            if self._currentPageNum!=0:
                self.toPage(0)
        self._UI.toFirstBtn.clicked.connect(toFirst)
    def _initScrollArea(self, scrollArea:QScrollArea):
        widget = QWidget()
        self._VL = QVBoxLayout()
        self._VL.setContentsMargins(0,0,0,0)
        self._scrollArea = scrollArea
        self._scrollArea.setWidget(widget)
        widget.setLayout(self._VL)

    @abstractmethod
    def _generatePage(self,newDataList):
        '''
        生成每个页面的布局
        :return:
        '''
        pass
    @abstractmethod
    def dataList(self):
        if not self._isFilter:
            return []
        else:
            return []
    @property
    def _currentPageDataList(self):
        # 生成卡牌列表
        oldDataList = self.dataList()
        endValue = (self._currentPageNum + 1) * self._PageItemNum
        if endValue>len(oldDataList):endValue=len(oldDataList)
        newDataList = oldDataList[self._currentPageNum * self._PageItemNum:endValue]
        return newDataList

    @property
    def pageCount(self):
        return ceil((len(self.dataList()) / self._PageItemNum))

    def _clearScroll(self):
        while len(self._tempHL_List)>0:
            tempHL = self._tempHL_List[0]           # type: QHBoxLayout
            self._tempHL_List.remove(tempHL)
            while tempHL.count()>0:
                child = tempHL.takeAt(0)
                if child.widget():
                    child.widget().setParent(None)
                    del child
            tempHL.deleteLater();del tempHL
    def _refreshBtnList(self):
        while len(self._numBTN_List)>0:
            numBTN = self._numBTN_List[0]           # type: QPushButton
            self._numBTN_List.remove(numBTN)
            numBTN.setParent(None)
            numBTN.deleteLater();del numBTN
        # 生成按钮列表
        font = QFont()
        font.setFamily("Adobe 黑体 Std R")
        font.setPointSize(12)
        count = 0;continueFlag = False
        start = self._currentPageNum
        if self.pageCount - start<5:
            start = self.pageCount - 5
        for i in range(start, self.pageCount):
            if i < 0 or i == self.pageCount:continue
            if continueFlag and i != self.pageCount-1:continue
            count += 1
            numBTN = QPushButton(None)
            self._UI.pageBTN_List.insertWidget(count, numBTN)
            self._numBTN_List.append(numBTN)
            numBTN.setMinimumSize(QtCore.QSize(28, 28));numBTN.setMaximumSize(QtCore.QSize(28, 28))
            numBTN.setFont(font)

            if count == 4 and self.pageCount-1-start>5:
                numBTN.setText("...")
                continueFlag=True;continue
            else:
                numBTN.setText(str(i + 1))
            def numBTNClick(index):
                def __numBTNClick():
                    self.toPage(index)
                return __numBTNClick
            numBTN.clicked.connect(numBTNClick(i))
            numBTN.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
            if i == self._currentPageNum:
                numBTN.setStyleSheet("background-color:rgb(69, 138, 202);")
            else:
                numBTN.setStyleSheet("")

        # 刷新指针状态
        if self._currentPageNum<=0: self._UI.leftBTN.setCursor(QCursor(QtCore.Qt.ForbiddenCursor))
        else:self._UI.leftBTN.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
        if self._currentPageNum>=self.pageCount-1: self._UI.rightBTN.setCursor(QCursor(QtCore.Qt.ForbiddenCursor))
        else:self._UI.rightBTN.setCursor(QCursor(QtCore.Qt.PointingHandCursor))
    def _refreshEle(self):
        self._clearScroll()
        self._generatePage(self._currentPageDataList)
        self._refreshBtnList()

    def filter(self,filterStr):
        self.filterStr = filterStr
        if self.filterStr == "":
            self._isFilter = False
        else:
            self._isFilter = True
        self._refreshEle()
    def toPage(self,pageNum:int=0):
        if pageNum<0: return
        self._currentPageNum = pageNum
        self._refreshEle()


import re
import cn2an

road_num_pattern = re.compile(r"^(\w+[(大道)路])(\d+号)")
zu_num_pattern = re.compile(r"(\d+组)(\d+号)$")
unsure_zu_num_pattern = re.compile(r"[村浜区片桥]\w*[第]*(\w+组)(\d+号)$")
num_pattern = re.compile(r"\d+")

# 获取道路和道路号
def GetRoadNumByRegex(addr):
	m = road_num_pattern.match(addr)
	if m:
		return m.group(1),m.group(2)
	return "",""

# 获取组和组号
def GetZuAndNum(addr):
	m = zu_num_pattern.search(addr)
	if m:
		num = m.group(1)[:-1]
		value = cn2an.an2cn(num)
		return str(value)+"组",m.group(2)

	return getZuAndNumLast(addr)

def getZuAndNumLast(addr):
	ta = addr
	zu,zu_num = "",""
	for i in range(1,10):
		i = 0
		um = unsure_zu_num_pattern.search(ta)
		if um:
			zu = um.group(1)
			zu_num = um.group(2)
			ta = zu+zu_num
		else:
			break

	# if zu!="" and zu_num!="":
	# 	zu_str = zu[:len(zu)-1]
	# 	try:
	# 		value = cn2an.cn2an(zu_str, "strict")
	# 		value = str(value)
	# 		if num_pattern.match(value):
	# 			return value+"组",zu_num
	# 	except ValueError:
	# 		print(zu_str)
	# 		print("get zu zu_num wrong 1:"+addr)
	# 		return "",""
	# 	except TypeError:
	# 		print(zu_str)
	# 		print("get zu zu_num wrong 2:"+addr)
	# 		return "",""

	return "",""


#!/usr/bin/python3
"""
This module defines the State class,
a sub class of the Base class
"""
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()

class State(Base):
    """This class is a sub class of the Base class"""
    __tablename__ = 'states'

    id = Column(Integer, primary_key=True, autoincrement=True, nullable=False)
    name = Column(String(128), nullable=False)


import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):
    """A class to manage bullets fired from the ship"""

    def __init__(self, configs, screen, ship):
        super().__init__()
        self.screen = screen

        self.rect = pygame.Rect(0, 0, configs.bullet_width,
          configs.bullet_height)

        self.rect.centerx = ship.rect.centerx
        self.rect.top = ship.rect.top

        self.y = float(self.rect.y)

        self.color = configs.bullet_color
        self.speed = configs.bullet_speed

    def update(self):

        self.y -= self.speed
        self.rect.y = self.y

    def draw_bullet(self):
        pygame.draw.rect(self.screen, self.color, self.rect)


#!/usr/bin/python3
"""add_integer: sum of two integers
"""

def add_integer(a, b=98):
    """sum of two integers

    Args:
        a (int): n
        b (int, 98): n. Defaults to 98.

    Returns:
        int: sum
    """
    if type(a) == float:
        a = int(a)
    elif type(b) == float:
        b = int(a)
    elif type(a) != int:
        raise TypeError("a must be an integer")
    elif type(b) != int:
        raise TypeError("b must be an integer")
    return a + b


import re
from wordcloud import WordCloud, STOPWORDS
import pandas as pd
import matplotlib.pyplot as plt

# Import pulled Tweets
data_pull = pd.read_csv('C:/Users/huffm/tweets.csv', header=None)
raw_tweets = data_pull.iloc[:,1]

# eliminate special characters, links, short words, and stopwords
raw_string = ''.join(raw_tweets)
no_links = re.sub(r'http\S+', '', raw_string)
no_unicode = re.sub(r"\\[a-z][a-z]?[0-9]+", '', no_links)
no_special_characters = re.sub('[^A-Za-z ]+', '', no_unicode)

words = no_special_characters.split(" ")
words = [w for w in words if len(w) > 2]
words = [w.lower() for w in words]
words = [w for w in words if w not in STOPWORDS]

#print(words)
wc = WordCloud(background_color='white',
        width=1600,
        height=800,
        random_state=21,
        colormap='jet',
        max_words=2000,
        max_font_size=200)

clean_string = ','.join(words)
wc.generate(clean_string)

plt.figure(figsize=(12, 10))
plt.axis('off')
plt.imshow(wc, interpolation="bilinear")
plt.title("Colorado Twitter Word Cloud")
plt.show()


#!/usr/bin/env python3
from sklearn import tree
import sys

data=sys.argv
wgt=int(data[1])
txtre=int(data[2])

#		   wgt txtre
features=[[110,0],[140,0],[120,0],[80,1],[90,1],[100,1]]

output=["Apple","Apple","Apple","Orange","Orange","Orange"]

algo=tree.DecisionTreeClassifier()
#train the algo for data set
trained=algo.fit(features,output)
#test the algo
output=trained.predict([[wgt,txtre]])

print(output)


from usm_rest_api.models import Host
from usm_rest_api.models import DiscoveredNode
from usm_wrappers import utils as usm_wrapper_utils

def check_minion_is_new(minion_id):
    new = True
    in_host_list = Host.objects.filter(node_name__exact=minion_id)
    in_free_pool = DiscoveredNode.objects.filter(node_name__exact=minion_id)
    if in_host_list or in_free_pool:
        new = False
    return new

def add_minion_to_free_pool(minion_id):
    node = DiscoveredNode(
        node_name=minion_id,
        management_ip=usm_wrapper_utils.resolve_hostname(minion_id)[0])
    node.save()


import torch
from fvcore.common.registry import Registry

META_ARCH_REGISTRY = Registry("META_ARCH")
META_ARCH_REGISTRY.__doc__ = """
Registry for meta-architectures, i.e. the whole model

The registered object will be called with `obj(cfg)`
and expected to return a `nn.Module` object.
"""
def build_model(cfg):
    """
        build the whole model architecture, defined by configs.MODEL.META_ARCHITECTURE
    """
    name = cfg.training.model.meta_arch
    model = META_ARCH_REGISTRY.get(name)(cfg)
    model.to(torch.device(cfg.training.model.device))

    return model


from modules.common.module import BotModule
import urllib.request

class MatrixModule(BotModule):
    async def matrix_message(self, bot, room, event):
        args = event.body.split()
        args.pop(0)
        day = 0
        hour = 12
        if len(args) >= 1:
            day = int(args[0]) - 1
        if len(args) == 2:
            hour = int(args[1])

        imgurl = 'http://ennuste.ilmailuliitto.fi/' + str(day) + '/wstar_bsratio.curr.' + str(hour) + '00lst.d2.png'
        await bot.upload_and_send_image(room, imgurl, f"RASP Day {day+1} at {hour}:00", no_cache=True)

    def help(self):
        return 'RASP Gliding Weather forecast, Finland only'


# upload to S3 bucket through S3 client

import boto3

bucket_name = 'demobucket250-e67018'
file_name = 'abc.txt'

# s3_resource = boto3.resource('s3')
# s3_client = s3_resource.meta.client
# s3_client.upload_file(Bucket=bucket_name, Filename=file_name, Key=file_name)

#OR

s3_client = boto3.client('s3')
s3_client.upload_file(Bucket=bucket_name, Filename=file_name, Key=file_name)

print(f'{file_name} has been uploaded to {bucket_name} bucket')


from io import StringIO

from .file_client import FileClient

def list_from_file(filename,
                   prefix='',
                   offset=0,
                   max_num=0,
                   encoding='utf-8',
                   file_client_args=None):
    """Load a text file and parse the content as a list of strings.

    Note:
        In v1.3.16 and later, ``list_from_file`` supports loading a text file
        which can be storaged in different backends and parsing the content as
        a list for strings.

    Args:
        filename (str): Filename.
        prefix (str): The prefix to be inserted to the beginning of each item.
        offset (int): The offset of lines.
        max_num (int): The maximum number of lines to be read,
            zeros and negatives mean no limitation.
        encoding (str): Encoding used to open the file. Default utf-8.
        file_client_args (dict, optional): Arguments to instantiate a
            FileClient. See :class:`mmcv.fileio.FileClient` for details.
            Default: None.

    Examples:
        >>> list_from_file('/path/of/your/file')  # disk
        ['hello', 'world']
        >>> list_from_file('s3://path/of/your/file')  # ceph or petrel
        ['hello', 'world']

    Returns:
        list[str]: A list of strings.
    """
    cnt = 0
    item_list = []
    file_client = FileClient.infer_client(file_client_args, filename)
    with StringIO(file_client.get_text(filename, encoding)) as f:
        for _ in range(offset):
            f.readline()
        for line in f:
            if 0 < max_num <= cnt:
                break
            item_list.append(prefix + line.rstrip('\n\r'))
            cnt += 1
    return item_list

def dict_from_file(filename,
                   key_type=str,
                   encoding='utf-8',
                   file_client_args=None):
    """Load a text file and parse the content as a dict.

    Each line of the text file will be two or more columns split by
    whitespaces or tabs. The first column will be parsed as dict keys, and
    the following columns will be parsed as dict values.

    Note:
        In v1.3.16 and later, ``dict_from_file`` supports loading a text file
        which can be storaged in different backends and parsing the content as
        a dict.

    Args:
        filename(str): Filename.
        key_type(type): Type of the dict keys. str is user by default and
            type conversion will be performed if specified.
        encoding (str): Encoding used to open the file. Default utf-8.
        file_client_args (dict, optional): Arguments to instantiate a
            FileClient. See :class:`mmcv.fileio.FileClient` for details.
            Default: None.

    Examples:
        >>> dict_from_file('/path/of/your/file')  # disk
        {'key1': 'value1', 'key2': 'value2'}
        >>> dict_from_file('s3://path/of/your/file')  # ceph or petrel
        {'key1': 'value1', 'key2': 'value2'}

    Returns:
        dict: The parsed contents.
    """
    mapping = {}
    file_client = FileClient.infer_client(file_client_args, filename)
    with StringIO(file_client.get_text(filename, encoding)) as f:
        for line in f:
            items = line.rstrip('\n').split()
            assert len(items) >= 2
            key = key_type(items[0])
            val = items[1:] if len(items) > 2 else items[1]
            mapping[key] = val
    return mapping


from torch import nn
from typing import Optional, Union
import logging
import numpy as np
import torch
import torch.nn.functional as F

from .modeling_utils import (
    find_pruneable_heads_and_indices,
    prune_linear_layer
)

from typing import Callable, Optional, Union

class PerformerAttentionConfig:
    r"""
    This is the configuration class to store the configuration of a :class:`~transformers.PerformerAttention` module. It is used
    to define the behavior of a Performer/FAVOR+ attention module when it is initialized.

    Args:
        attention_dropout (:obj:`float`, `optional`, defaults to 0.1):
            The dropout ratio for the attention probabilities.
        causal (:obj:`bool`, `optional`, defaults to False):
            Whether to apply causal attention, where positions are prevented from attending to positions to ahead
            of themselves in the sequence, using the prefix-sum method.
        kernel_type (:obj:`str`,  `optional`, defaults to :obj:`'exp'`):
            The type of kernel function to use for comparing the queries and keys. Possible options are :obj:`'exp'`,
            :obj:`'cosh'`, and :obj:`'relu'`. The :obj:`'cosh'` option approximates softmax attention with a smaller
            variance than :obj:`'exp'`, but at the cost of using twice as many random features. :obj:`'relu'` may result
            in better performance than :obj:`'exp'` and :obj:`'cosh'` in certain circumstances, but it is not an unbiased
            estimator of softmax attention and thus should not be used with pretrained models that were pretrained with
            softmax attention.
        short_sequence_behavior (:obj:`str`, or `Callable` `optional` defaults to :obj:`'never_use_softmax'`):
            This parameter determines if and when the module should fall back to regular softmax attention. Softmax attention
            is generally faster than FAVOR+ when the sequence length is not significantly larger than the number of random
            features used— which is equal to round(d*log(d)), where d is the number of dimensions per attention head. The
            default behavior is to use FAVOR+ regardless of sequence length while training, but to use softmax attention at
            test time when the sequence length is less than twice the number of random features. Note that this means that for
            BERT-based models, where :obj:`'d_model'` = 768 and :obj:`'num_heads'` = 12, PerformerAttention will use softmax
            attention at test time when sequences do not exceed the usual maximum sequence length of 512 tokens.
            Possible values for this parameter are :obj:`'use_softmax_eval_only'`, :obj:`'use_softmax_eval_and_train'`,
            :obj:`'never_use_softmax'`. The option :obj:`'use_softmax_eval_and_train'` should probably only be used if the
            training set has a significant number of long sequences; otherwise, the model may not learn to deal with the
            random noise inherent in the FAVOR+ algorithm.
        kernel_epsilon (:obj:`float`, `optional`, defaults to 1e-4):
            Stabilizer term added to the output of the kernel function to avoid dividing by very small numbers.
        normalize_output (:obj:`bool`, `optional`, defaults to True):
            Whether to ensure that the output vectors are convex combinations of the input vectors; that is, that the rows of
            the implicit attention map sum to 1.
        normalization_stabilizer (:obj:`float`, `optional`, defaults to 1e-6):
            Stabilizer term used when normalizing the output to avoid dividing by very small numbers.
        num_random_features (:obj:`int`, `optional`, defaults to None):
            The dimensionality of the random feature vectors to use. When None, the dimensionality is set to
            D * log(D), where D is the dimensionality of each attention head.
        use_thick_features (:obj:`bool`, `optional`, defaults to False):
            Whether to generate a random feature tensor that has a batch dimension.
        use_orthogonal_features (:obj:`bool`, `optional`, defaults to True):
            Whether to use strictly orthogonal random features, as opposed to features drawn from a standard Gaussian
            distribution. Orthogonal features result in outputs that more closely approximate softmax attention, but at
            the cost of doing QR decomposition on the CPU every time the features are redrawn. Best combined with a
            reasonably large value of :obj:`feature_redraw_interval` (1-5k).
        use_qkv_linear_layers (:obj:`bool`, `optional`, defaults to True):
            Whether to transform the Q, K, and V inputs with a Linear layer before applying attention. Setting this
            to False may be useful if you want to use PerformerAttention as one component of a more complex
            attention mechanism.
        regularize_feature_norms (:obj:`bool`, `optional`, defaults to False):
            Whether to ensure that the random feature vectors have a norm of sqrt(`d`), where `d` is the dimensionality of
            each attention head.
        feature_redraw_interval (:obj:`int`, `optional`, defaults to 1000):
            The number of forward passes after which the random feature matrix should be redrawn. If None, then the feature
            matrix is never redrawn. It is recommended to set this property to some value on the order of 1-5k while
            training in order to get the best model performance. When combined with :obj:`redraw_stochastically`, this parameter
            determines the expected value of the redraw interval, rather than the interval itself.
        redraw_stochastically (:obj:`bool`, `optional`, defaults to False):
            If true, PerformerAttention will redraw its random features each forward pass with a probability equal to
            (1 / :obj:`feature_redraw_interval`), instead of deterministically redrawing once every N passes. This could be
            desirable in large models to ensure that the attention layers don't all redraw their features at the same time.
        redraw_verbose (:obj:`bool`, `optional`, defaults to False):
            Whether to log a message when random features are redrawn during training.
        dim (:obj:`int`, `optional`):
            Dimensionality of the queries, keys, and values.
        num_heads (:obj:`int`, `optional`):
            Number of attention heads.
    """

    attention_dropout: float = 0.1
    causal: bool = False
    kernel_type: str = 'cosh'

    # Default determined in PerformerAttention.__init__()
    # FAVOR+ takes more time compared with softmax over short sequence?
    # check: https://github.com/huggingface/transformers/issues/7675#issuecomment-734534302
    # __init__() set the value based on length of seq, roughly:
    # short sequence(L < 2 * M): fall back to transformer;
    # long sequence(L > 2 * M):  follow perfomer;
    short_sequence_behavior: Optional[Union[str, Callable]] = 'never_use_softmax'

    kernel_epsilon: float = 1e-4
    normalize_output: bool = True
    normalization_stabilizer: float = 1e-6

    num_random_features: Optional[int] = None
    use_thick_features: bool = False
    use_orthogonal_features: bool = True
    use_qkv_linear_layers: bool = True
    regularize_feature_norms: bool = True

    feature_redraw_interval: int = 1000
    redraw_stochastically: bool = False
    redraw_verbose: bool = False

    # Optional here so the user doesn't have to set redundant parameters, but must be set by model before config is
    # passed to PerformerAttention.__init__()
    d_model: Optional[int] = None
    num_heads: Optional[int] = None

KERNEL_CALLABLES = {
    'cosh': lambda x, h: torch.cat((torch.exp(h + x), torch.exp(h - x)), dim=-1),
    'exp': lambda x, h: torch.exp(h + x), # Default
    'elu': lambda x: F.elu(x) + 1,
    'relu': F.relu
}

SHORT_SEQUENCE_BEHAVIOR_CALLABLES = {
    'use_softmax_eval_only': lambda L, M, training: False if training else L < 2.0 * M,
    'use_softmax_eval_and_train': lambda L, M, training: L < 2.0 * M,
    'never_use_softmax': lambda L, M, training: False
}

class PerformerAttention(nn.Module):
    def __init__(self, config: Optional[PerformerAttentionConfig] = None, **kwargs):
        super().__init__()

        config = config or PerformerAttentionConfig()

        # kwargs take precedence over the default values that might be stored in the config object
        for k, v in kwargs.items():
            if not hasattr(config, k):
                raise AttributeError(f"PerformerAttention: '{k}' is an invalid config parameter")

            setattr(config, k, v)

        self.__dict__.update(config.__dict__)

        if self.num_heads is None or self.d_model is None:
            raise ValueError("PerformerAttention: num_heads and d_model must be non-None")

        self.dropout = nn.Dropout(p=self.attention_dropout)
        self.calls_since_last_redraw = 0
        self.random_features = None

        behavior = self.short_sequence_behavior
        if not behavior:
            behavior = 'never_use_softmax' if self.kernel_type == 'relu' else 'use_softmax_eval_only'
            self.should_fallback_to_softmax = SHORT_SEQUENCE_BEHAVIOR_CALLABLES[behavior]

        # if kernel is `relu`, then softmax attention cannot be used
        elif self.kernel_type == 'relu' and behavior != 'never_use_softmax':
            raise ValueError(f"PerformerAttention: short_sequence_behavior = {behavior} cannot be combined with the relu "
                             "kernel type")

        elif isinstance(behavior, str):
            self.should_fallback_to_softmax = SHORT_SEQUENCE_BEHAVIOR_CALLABLES[behavior]
        elif callable(behavior):
            self.should_fallback_to_softmax = behavior
        else:
            raise ValueError("PerformerAttention: short_sequence_behavior must be either str or Callable")

        self.kernel_fn = KERNEL_CALLABLES[self.kernel_type]

        assert self.d_model % self.num_heads == 0

        if self.use_qkv_linear_layers:
            self.q_lin = nn.Linear(in_features=self.d_model, out_features=self.d_model)
            self.k_lin = nn.Linear(in_features=self.d_model, out_features=self.d_model)
            self.v_lin = nn.Linear(in_features=self.d_model, out_features=self.d_model)

        self.out_lin = nn.Linear(in_features=self.d_model, out_features=self.d_model)

        self.pruned_heads = set()

    def prune_heads(self, heads):
        attention_head_size = self.d_model // self.num_heads
        if len(heads) == 0:
            return
        heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, attention_head_size, self.pruned_heads)
        # Prune linear layers
        if self.use_qkv_linear_layers:
            self.q_lin = prune_linear_layer(self.q_lin, index)
            self.k_lin = prune_linear_layer(self.k_lin, index)
            self.v_lin = prune_linear_layer(self.v_lin, index)

        self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)
        # Update hyper params
        self.num_heads = self.num_heads - len(heads)
        self.d_model = attention_head_size * self.num_heads
        self.pruned_heads = self.pruned_heads.union(heads)

    def redraw_features_now(self):
        device = self.random_features.device
        batch = self.random_features.shape[0]
        self._generate_feature_matrix(batch, device)

        if self.training and self.redraw_verbose:
            logging.info("PerformerAttention: Just redrew random features.")

        self.calls_since_last_redraw = 0

    def forward(self, query, key, value, mask=None, head_mask=None, output_attentions=False):
        """
        Parameters:
            query: torch.tensor(bs, seq_length, dim)
            key: torch.tensor(bs, seq_length, dim)
            value: torch.tensor(bs, seq_length, dim)
            mask: torch.tensor(bs, seq_length)

        Returns:
            weights: torch.tensor(bs, num_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
            seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
        """
        bs, q_length, dim = query.size()
        k_length = key.size(1)
        # assert dim == self.d_model, 'Dimensions do not match: %s input vs %s configured' % (dim, self.d_model)
        # assert key.size() == value.size()

        dim_per_head = self.d_model // self.num_heads
        mask_reshp = (bs, 1, 1, k_length)

        def shape(x):
            """ separate heads """
            return x.view(bs, -1, self.num_heads, dim_per_head).transpose(1, 2)

        if self.use_qkv_linear_layers:
            q = self.q_lin(query)
            k = self.k_lin(key)
            v = self.v_lin(value)
        else:
            q, k, v = query, key, value

        # (bs, num_heads, q_length, dim_per_head)
        q, k, v = (shape(x) for x in (q, k, v))

        # If the sequence length is short enough that FAVOR+ would use considerably more time and/or memory(?) than just using softmax attention,
        # putative reason: https://github.com/huggingface/transformers/issues/7675#issuecomment-734534302
        # For short enough sequence (L < 2 * d*log(d), remain to be tested) use softmax. This works because FAVOR+ is an unbiased estimator of softmax attention.
        m = self.num_random_features or round(dim_per_head * np.log(dim_per_head)) # m is the number of random features
        if self.should_fallback_to_softmax(q_length, m, self.training):
            scores = q @ k.transpose(-2, -1) / (dim ** 0.5)

            if mask is not None:
                mask = (mask == 0).view(mask_reshp).expand_as(scores)  # (bs, num_heads, q_length, k_length)
                scores.masked_fill_(mask, -float("inf"))  # (bs, num_heads, q_length, k_length)

            attn_map = nn.Softmax(dim=-1)(scores)
            attn_map = self.dropout(attn_map)  # (bs, num_heads, q_length, k_length)
            return self._finalize_attention_output(attn_map @ v, head_mask, attn_map)

        # When we're using FAVOR+ we can't output the attention matrix.
        # Why cannot, q'*k'^T ?
        #if output_attentions:
        #    raise ValueError("PerformerAttention: Can't output attention maps when using FAVOR+ linear attention.")

        self._redraw_features_if_needed(bs, q.device)

        # Get the transformed values of Q and K
        q_prime, k_prime = self.get_projected_queries_and_keys(q, k)
        return self.compute_attention_with_projected_queries_and_keys(q_prime, k_prime, v, mask, head_mask)

    # Turns Q into Q', K into K'
    def get_projected_queries_and_keys(self, q, k):
        # Instead of dividing the product QK^T by sqrt(d), we divide Q and K by the 4th root of d.
        q = q / (self.d_model ** 0.25)
        k = k / (self.d_model ** 0.25)

        projected_q = q @ self.random_features
        projected_k = k @ self.random_features

        # Special logic for kernels that attempt to approximate softmax
        if self.kernel_type in ('cosh', 'exp'):
            # The h(x) function is defined in Lemma 1 in Choromanski et al. pg. 4 as exp(-||x||**2 / 2). For numerical
            # stability we leverage the fact that exp(x)*exp(y) = exp(x + y) here and delay computing the exp().
            h_of_q = -torch.sum(q ** 2, dim=-1, keepdim=True) / 2
            h_of_k = -torch.sum(k ** 2, dim=-1, keepdim=True) / 2

            ## Need to check again ##:
            # In this implementation, q,k_stabilizer is max of h(*), but in original google implementation, they use max of q/k @ W_t

            # Compute the numerical stabilizer that we subtract from the input to exp(). For some reason the original
            # Jax implementation uses different types of stabilizers for queries vs. keys, and we follow that here.
            ## This is a workaround for very slow performance of torch.max(dim=N) on PyTorch 1.4 and earlier;
            ## see this GitHub discussion: https://github.com/pytorch/pytorch/issues/36900
            q_indices = h_of_q.argmax(-1).unsqueeze(-1)
            q_stabilizer = h_of_q.gather(-1, q_indices) # Note this is a (d_model, 1) matrix that gets broadcasted

            # This is just a scalar
            k_stabilizer = torch.max(h_of_k)

            q_kernel_output = self.kernel_fn(projected_q - q_stabilizer, h_of_q)
            k_kernel_output = self.kernel_fn(projected_k - k_stabilizer, h_of_k)

            # By multiplying by 1/sqrt(m), we ensure the final matrix product will contain a factor of 1/m. This means
            # each row of Q'K'^T can be interpreted as an average over the exp(omega^T * q) * exp(omega^T * k) terms.
            normalizing_constant = (q_kernel_output.shape[-1] ** -0.5)

            q_prime = normalizing_constant * (q_kernel_output + self.kernel_epsilon)
            k_prime = normalizing_constant * (k_kernel_output + self.kernel_epsilon)
            return q_prime, k_prime

        # Generalized attention (ReLU, ELU...)
        else:
            return (self.kernel_fn(x) + self.kernel_epsilon for x in (projected_q, projected_k))

    def compute_attention_with_projected_queries_and_keys(self, q_prime, k_prime, v, mask = None, head_mask = None):
        # Apply the padding mask to K'. Also applying it to Q' would be redundant.
        if mask is not None:
            k_prime *= mask.unsqueeze(1).unsqueeze(-1).expand_as(k_prime)

        if self.causal:
            output = _headwise_causal_numerator(q_prime, k_prime, v)
        else:
            k_prime_t = k_prime.transpose(-2, -1)
            output = q_prime @ (k_prime_t @ v)

        # Ensure that the output vectors are convex combinations of input vectors; that is,
        # the implied attention scores sum to 1
        if self.normalize_output:
            if self.causal:
                sums = k_prime.cumsum(dim=-2)
                d = torch.einsum("bhlm,bhlm->bhl", q_prime, sums).unsqueeze(-1)
            else:
                # Equivalent to multiplying K'^T by a ones vector
                d = q_prime @ k_prime.sum(dim=-2).unsqueeze(-1)

            # Avoid dividing by very small numbers
            d += 2 * self.normalization_stabilizer * (torch.abs(d) <= self.normalization_stabilizer)
            output /= d

        # TODO: output attention map
        return self._finalize_attention_output(output, head_mask)

    def _finalize_attention_output(self, context, head_mask=None, att_map_to_output=None):
        def unshape(x):
            """ group heads """
            return x.transpose(1, 2).contiguous().view(x.shape[0], -1, x.shape[1] * x.shape[-1])

        # Mask heads if we want to
        if head_mask is not None:
            context = context * head_mask

        context = unshape(context)  # (bs, q_length, dim)
        context = self.out_lin(context)  # (bs, q_length, dim)

        if att_map_to_output:
            return context, att_map_to_output
        else:
            return context,

    def _generate_feature_matrix(self, batch_size, device):
        dim_per_head = self.d_model // self.num_heads
        num_rows = self.num_random_features or round(dim_per_head * math.log(dim_per_head))
        batch = batch_size if self.use_thick_features else 1

        if not self.use_orthogonal_features:
            return torch.randn(batch, num_rows, dim_per_head, device=device)

        # The Givens rotation algorithm currently only supports matrices with an even number of rows/columns.
        # This should be fine for all widely used Transformer models, but we can use QR decomposition as a backup.
        num_full_blocks = num_rows // dim_per_head
        orthog_func = _get_square_orthogonal_block_givens if dim_per_head % 2 == 0 else _get_square_orthogonal_block_qr
        block_list = [orthog_func(batch, dim_per_head, device) for _ in range(num_full_blocks)]

        remaining_rows = num_rows - num_full_blocks * dim_per_head
        if remaining_rows > 0:
            q = orthog_func(batch, dim_per_head, device)
            block_list.append(q[:, :remaining_rows])

        final_tensor = torch.cat(block_list, dim=1)

        # This option yields SMREG
        if self.regularize_feature_norms:
            final_tensor *= dim_per_head ** 0.5
        else:
            # Hack to make the matrix columns have the norm we would expect them to have if they were sampled straight
            # from a Gaussian, instead of being all norm 1 since they went through QR decomposition
            multiplier = torch.randn(batch, num_rows, dim_per_head, device=device).norm(dim=2)
            final_tensor = torch.diag(multiplier) @ final_tensor

        # Add an attention head dimension
        final_tensor.unsqueeze_(1)
        new_shape = list(final_tensor.shape)
        new_shape[0] = batch_size  # This is redundant if use_thick_features == True, but not otherwise
        new_shape[1] = self.num_heads
        self.random_features = final_tensor.expand(*new_shape).transpose(-2, -1)

    def _redraw_features_if_needed(self, batch, device):
        # We haven't created the projection matrix yet, let's create it
        if self.random_features is None:
            self._generate_feature_matrix(batch, device)

        elif self.feature_redraw_interval is not None:
            if self.redraw_stochastically:
                # random.random() returns a float between 0.0 and 1.0, so this expression
                # evaluates to True with probability 1. / self.feature_redraw_interval
                if random.random() < 1. / self.feature_redraw_interval:
                    self.redraw_features_now()

            # It's time to redraw the projection matrix
            elif self.calls_since_last_redraw >= self.feature_redraw_interval:
                self.redraw_features_now()

            # Keep track of how many forward passes we do before we redraw again
            else:
                self.calls_since_last_redraw += 1

# Not currently used unless dim_per_head is odd
def _get_square_orthogonal_block_qr(batch, size, device=None):
    unstructured_block = torch.randn(batch, size, size, device=device)
    q, r = torch.qr(unstructured_block, some=True)
    return q.transpose(-2, -1)

# Not ideal but all we can do until https://github.com/pytorch/pytorch/issues/42502 gets implemented
def _batch_randperm(batch, n, dtype=torch.int64, device=None):
    out_tensor = torch.empty(batch, n, dtype=dtype, device=device)
    for i in range(batch):
        torch.randperm(n, out=out_tensor[i], dtype=dtype, device=device)

    return out_tensor

# Fast parallelizable way of making random orthogonal matrices- O(n log(n)) vs. O(n^3) for QR
def _get_square_orthogonal_block_givens(batch, num_rows, device=None):
    r"""Constructs a 2D-tensor which is a product of Givens random rotations.
    Constructs a 2D-tensor of the form G_1 * ... * G_k, where G_i is a Givens
    random rotation. The resulting tensor mimics a matrix taken uniformly at
    random form the orthogonal group.
    Args:
      num_rows: number of rows/columns of the resulting 2D-tensor.
    Returns:
      The product of Givens random rotations.
    """
    q = torch.eye(num_rows, device=device)  # Start with identity matrix
    q = q.expand(batch, num_rows, num_rows)

    # Compute the cosines and sines of the rotations up front
    num_iterations = 2 * int(math.ceil(math.log(num_rows)))
    angles = math.pi * torch.rand(batch, num_iterations, num_rows // 2, 1, device=device)
    cosines, sines = torch.cos(angles), torch.sin(angles)
    q.unsqueeze_(2)

    # Group the matrix into random, non-overlapping pairs of rows. Because these pairs are non-overlapping, we can
    # perform each set of rotations in parallel.
    for n in range(num_iterations):
        shuffled_rows = _batch_randperm(batch, num_rows, device=device).view(batch, -1, 1, 1)
        random_row_pairs = q.gather(1, shuffled_rows.expand_as(q)).view(batch, -1, 2, num_rows)

        rows1, rows2 = random_row_pairs[:, :, 0], random_row_pairs[:, :, 1]
        new_rows1 = cosines[:, n] * rows1 + sines[:, n] * rows2
        new_rows2 = -sines[:, n] * rows1 + cosines[:, n] * rows2

        random_row_pairs[:, :, 0], random_row_pairs[:, :, 1] = new_rows1, new_rows2

        q = random_row_pairs.view(batch, -1, 1, num_rows)  # Ungroup all the rows again

    return q.squeeze(-2)

def _headwise_causal_numerator(q_prime, k_prime, v):
    results = []

    # Iterate over the attention heads to avoid allocating a very large tensor
    for head in range(q_prime.shape[1]):
        # Outer products- a sorta biggish tensor
        outer_prods = torch.einsum('blm,bld->blmd', k_prime[:, head], v[:, head])
        prefix_sums = outer_prods.cumsum(dim=1)

        query_prods = torch.einsum('blmd,blm->bld', prefix_sums, q_prime[:, head])
        results.append(query_prods.unsqueeze(1))

    return torch.cat(results, dim=1)

# Not currently used
def _lengthwise_causal_numerator(q_prime, k_prime, v):
    batch_size, num_heads, seq_len, num_features = k_prime.shape
    d_model = v.shape[-1]

    # Merge the batch and attention head dimensions so we can use baddbmm_()
    prefix_sums = torch.zeros(batch_size * num_heads, num_features, d_model, device=v.device)
    q_prime = q_prime.view(-1, seq_len, num_features)
    k_prime = k_prime.view(-1, seq_len, num_features, 1)  # Add singleton dimension for outer product
    v = v.reshape(-1, seq_len, 1, d_model)  # Add singleton dimension for outer product

    result = []
    for pos in range(seq_len):
        prefix_sums.baddbmm_(k_prime[:, pos], v[:, pos])  # Fused in-place addition of outer products
        result.append(torch.einsum("bmd,bm->bd", prefix_sums, q_prime[:, pos]).unsqueeze(-2))

    # Unmerge the attention head and batch size dimensions
    return torch.cat(result, dim=-2).view(batch_size, num_heads, seq_len, d_model)


import sqlite3

def main():
    conn = sqlite3.connect('Data/chocolate.db')
    cur = conn.cursor()

    pid = int(input('Enter product ID: '))

    cur.execute('''SELECT Description, RetailPrice FROM Products
                    WHERE ProductID == ?''', (pid,))
    results = cur.fetchone()

    if results != None:
        print(f'The current price for "{results[0]}" is: '
              f'${results[1]:.2f}')

        new_price = float(input('Enter the new price: '))

        cur.execute('''UPDATE Products
                    SET RetailPrice = ?
                    WHERE ProductID == ?''',
                    (new_price, pid))

        conn.commit()
        print('The price was changed.')
    else:
        print(f'The "{pid}" ID wasnt found.')

    print(cur.rowcount)
    conn.close()

if __name__ == '__main__':
    main()


import json

# Demander le nom du fichier JSON à modifier
filename = input("Entrez le nom du fichier JSON à modifier : ")

# Vérifier si le fichier existe ou pas
try:
    with open(filename, "r") as f:
        data = json.load(f)
except FileNotFoundError:
    data = {}

# Afficher le contenu actuel du fichier JSON
print("Contenu actuel :")
print(json.dumps(data, indent=4))

# Demander à l'utilisateur les modifications à apporter
while True:
    print("Que voulez-vous faire ?")
    print("1. Ajouter ou modifier une entrée")
    print("2. Supprimer une entrée")
    print("3. Quitter")

    choice = input("Entrez votre choix (1-3) : ")

    if choice == "1":
        key = input("Entrez le nom de la clé : ")
        value = input("Entrez la valeur de la clé : ")
        data[key] = value
    elif choice == "2":
        key = input("Entrez le nom de la clé à supprimer : ")
        if key in data:
            del data[key]
        else:
            print(f"La clé '{key}' n'existe pas dans le fichier.")
    elif choice == "3":
        break
    else:
        print("Choix invalide. Veuillez entrer 1, 2 ou 3.")

# Enregistrer les modifications dans le fichier JSON
with open(filename, "w") as f:
    json.dump(data, f, indent=4)

print("Modifications enregistrées dans le fichier.")


# find the area of an equilateral triangle by using function
import math
def area(a):
 res=(math.sqrt(3)/4)*(a*a)
 res1=round(res,2)
 return res1
# get the area value from the user
a=float(input())
res2=area(a)
print(res2)


import os.path
import numpy as np
import itertools
import Tools
from pyquaternion import Quaternion

# mult, multvec, inverse, conjugate, normalize rot2quat, quat2rot , norm
def flattenQuat(l):
    return(np.array([list(x) for x in l]).reshape(4*len(l)))

def flattenRot(l):
    return(np.array([list(x) for x in l]).reshape(9*len(l)))

# q and -q are representing the same rotation.
# So there is an ambiguity for the tests.
# We force the real part of be positive.
def mkQuaternion(mat):
    q=Quaternion(matrix=mat)
    if q.scalar < 0:
        return(-q)
    else:
        return(q)

def writeTests(config,format):
    NBSAMPLES=128

    a=[Quaternion.random() for x in range(NBSAMPLES)]
    b=[Quaternion.random() for x in range(NBSAMPLES)]

    config.writeInput(1, flattenQuat(a))
    config.writeInput(2, flattenQuat(b))

    normTest = [x.norm for x in a]
    config.writeReference(1, normTest)

    inverseTest = [x.inverse for x in a]
    config.writeReference(2, flattenQuat(inverseTest))

    conjugateTest = [x.conjugate for x in a]
    config.writeReference(3, flattenQuat(conjugateTest))

    normalizeTest = [x.normalised for x in a]
    config.writeReference(4, flattenQuat(normalizeTest))

    multTest = [a[i] * b[i] for i in range(NBSAMPLES)]
    config.writeReference(5, flattenQuat(multTest))

    quat2RotTest = [x.rotation_matrix for x in a]
    config.writeReference(6, flattenRot(quat2RotTest))

    config.writeInput(7, flattenRot(quat2RotTest))
    rot2QuatTest = [mkQuaternion(x) for x in quat2RotTest]
    config.writeReference(7, flattenQuat(rot2QuatTest))

def generatePatterns():
    PATTERNDIR = os.path.join("Patterns","DSP","QuaternionMaths","QuaternionMaths")
    PARAMDIR = os.path.join("Parameters","DSP","QuaternionMaths","QuaternionMaths")

    configf32=Tools.Config(PATTERNDIR,PARAMDIR,"f32")
    configf16=Tools.Config(PATTERNDIR,PARAMDIR,"f16")

    writeTests(configf32,0)
    writeTests(configf16,16)

    # Params just as example
    someLists=[[1,3,5],[1,3,5],[1,3,5]]

    r=np.array([element for element in itertools.product(*someLists)])
    configf32.writeParam(1, r.reshape(81))

if __name__ == '__main__':
  generatePatterns()