# https://leetcode.com/problems/3sum/submissions/

# sort nums
# iterate i and have L pointer R pointer
# If nums[i] + nums[l] + nums [r] == 0 found -> append
# Skip duplicates when found
# Else move left and right pointers

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        size = len(nums)
        res = []

        for i in range(size):
            l = i+1
            r = size-1

            # If duplicate skip
            if i and nums[i] == nums[i-1]: continue

            while (l<r):
                if not (nums[i] + nums[r] + nums[l]):
                    res.append([nums[i], nums[l], nums[r]])

                    # Move l forward and ignore the duplicates
                    while l<r and nums[l] == nums[l+1]:
                        l+=1
                    # Move r back and ignore duplicates
                    while l<r and nums[r] == nums[r-1]:
                        r-=1

                    l+=1
                    r-=1

                elif nums[i] + nums[r] + nums[l] < 0: l+=1
                else: r-=1

        return res


from PIL import Image, ImageTk, ImageDraw

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return '(' + str(self.x) + ', ' + str(self.y) + ')'

def cropping(startPoint, endPoint, bc, img):
    pixelList = []

    x0 = startPoint[0]
    y0 = startPoint[1]
    x1 = endPoint[0]
    y1 = endPoint[1]

    if y0 > y1:
        y0, y1 = y1, y0
    if x0 > x1:
        x0, x1 = x1, x0

    for j in range(y0, y1):
        for i in range(x0, x1):
            if img.getpixel((i, j)) != bc:
                color = img.getpixel((i, j))
                pixelObj = ((i, j), color)
                pixelList.append(pixelObj)
                img.putpixel((i, j), bc)

    return pixelList

def curve(p0, p1, p2, color, img):
    t = 0
    while t < 1:
        x = int(p0[0] * (1 - t) ** 2 + 2 * (1 - t) * t * p1[0] + p2[0] * t ** 2)
        y = int(p0[1] * (1 - t) ** 2 + 2 * (1 - t) * t * p1[1] + p2[1] * t ** 2)
        img.putpixel((x, y), color)
        t = t + 0.001
    curveImg = ImageTk.PhotoImage(img)
    return curveImg

def draw_eclipse(centerPoint, x, y, color, img):
    img.putpixel((centerPoint[0] + x, centerPoint[1] + y), color);
    img.putpixel((centerPoint[0] - x, centerPoint[1] + y), color);
    img.putpixel((centerPoint[0] + x, centerPoint[1] - y), color);
    img.putpixel((centerPoint[0] - x, centerPoint[1] - y), color);

def eclipse_mid_point(centerPoint, rx, ry, color, img):
    rxSq = rx ** 2
    rySq = ry ** 2
    x = 0
    y = ry
    px = 0
    py = 2 * rxSq * y
    draw_eclipse(centerPoint, x, y, color, img)
    p = rySq - (rxSq * ry) + (0.25 * rxSq)
    while px < py:
        x = x + 1
        px = px + 2 * rySq
        if p < 0:
            p = p + rySq + px
        else:
            y = y - 1
            py = py - 2 * rxSq
            p = p + rySq + px - py
        draw_eclipse(centerPoint, x, y, color, img)

    p = rySq * (x + 0.5) * (x + 0.5) + rxSq * (y - 1) * (y - 1) - rxSq * rySq
    while y > 0:
        y = y - 1
        py = py - 2 * rxSq;
        if p > 0:
            p = p + rxSq - py;
        else:
            x = x + 1
            px = px + 2 * rySq;
            p = p + rxSq - py + px;
        draw_eclipse(centerPoint, x, y, color, img);

    eclipseImg = ImageTk.PhotoImage(img)
    return eclipseImg

def move_transition(pixelList, newPoint, bc, img):
    deltaX = newPoint[0] - pixelList[0][0][0]
    deltaY = newPoint[1] - pixelList[0][0][1]

    for i in range(0, len(pixelList) - 1):
        pixel = pixelList[i]
        img.putpixel((pixel[0][0] + deltaX, pixel[0][1] + deltaY), pixel[1])

    transitImg = ImageTk.PhotoImage(img)
    return transitImg

def pencil(previousPoint, pointNow, color, img):
    draw = ImageDraw.Draw(img)
    draw.line((previousPoint, pointNow), color)

    pencilImg = ImageTk.PhotoImage(img)
    return pencilImg

def eraser(previousPoint, pointNow, color, img):
    draw = ImageDraw.Draw(img)
    draw.line((previousPoint, pointNow), fill=color, width=10)

    eraserImg = ImageTk.PhotoImage(img)
    return eraserImg

def triangle(startPoint, endPoint, color, img, defaultState):
    a = (endPoint[1] - startPoint[1]) / float(2)
    b = (endPoint[0] - startPoint[0]) / float(2)

    A = (int(startPoint[0]), int(endPoint[1]))
    B = (int(endPoint[0]), int(endPoint[1]))
    C = (int(startPoint[0] + b), int(startPoint[1]))

    draw = ImageDraw.Draw(img)

    draw.line((A, B), color)
    draw.line((B, C), color)
    draw.line((C, A), color)

    triangleImg = ImageTk.PhotoImage(img)
    return triangleImg

def rectangle(pointA, pointB, color, img, defaultState):
    draw = ImageDraw.Draw(img)
    if defaultState:  # draw square
        edge = abs(pointB[0] - pointA[0])
        if pointB[1] > pointA[1]:
            pointB = (pointB[0], edge + pointA[1])
        else:
            pointB = (pointB[0], abs(pointA[1] - edge))
        draw.rectangle([pointA, pointB], None, color)
    else:
        draw.rectangle([pointA, pointB], None, color)

    rectangleImg = ImageTk.PhotoImage(img)
    return rectangleImg

def fillColor(img, center, bc, newColor, paperWidth, paperHeight):
    print('center ', center)

    oldColor = img.getpixel(center)
    if oldColor == newColor:
        return

    listSeed = []
    listSeed.append(center)
    while listSeed:
        seed = listSeed.pop(0)
        try:
            seedColor = img.getpixel(seed)
        except IndexError:
            seedColor = None
        if seedColor == oldColor:
            img.putpixel(seed, newColor)
            x, y = seed[0], seed[1]
            listSeed.append((x + 1, y))
            listSeed.append((x - 1, y))
            listSeed.append((x, y + 1))
            listSeed.append((x, y - 1))

    filledImg = ImageTk.PhotoImage(img)
    return filledImg


import sys
sys.stdin = open('input.txt')

def quick_sort(arr):    # 퀵소트 함수
    if len(arr) <= 1:   # 모든 요소를 쪼개 크기 비교
        return arr
    # arr[0]을 기준으로 크기를 비교하여 왼쪽, 오른쪽 리스트 채우고
    # 재귀호출을 이용해 모든 요소에 대한 정렬 진행
    else:
        pivot = arr[0]
        left, right = [], []
        for i in range(1, len(arr)):
            if arr[i] < pivot:
                left.append(arr[i])
            else:
                right.append(arr[i])
        return [*quick_sort(left), pivot, *quick_sort(right)]

T = int(input())
for tc in range(1, T+1):
    N = int(input())
    num = list(map(int, input().split()))

    # 정렬한 새 배열 저장
    num = quick_sort(num)

    # 문제에서 요구한 요소 출력
    print(f'#{tc} {num[N // 2]}')


import json
import sys
import configparser

def json_to_csv(file):
    config = configparser.ConfigParser()

    with open(file) as f:
        data = json.load(f)

        for key in data:
            config[key] = data[key]

        with open('config.ini', 'w') as configfile:
            config.write(configfile)

json_to_csv(sys.argv[1])


# -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 23:30:55 2019

@author: Margarida Viera
"""

import math
def hypotenuse(n):
    hypotenuse = math.sqrt(n**2 + n**2)
    return round(hypotenuse, 2)

n = float(input())
print(hypotenuse(n))


from socket import *
from ui import *
from PyQt5.QtCore import *
import re
import threading
import sys
import time

class Client(QObject):
    progress_update = pyqtSignal(int)
    transfer_complete = pyqtSignal(int)
    recv_msg = pyqtSignal(str)
    pwd_signal = pyqtSignal(str)
    insert_file = pyqtSignal(str, str, str, str)

    def __init__(self):
        super().__init__()
        self.socket_command = socket(AF_INET, SOCK_STREAM)
        self.socket_command.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.socket_data = socket(AF_INET, SOCK_STREAM)
        self.socket_data.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.ip = ''
        self.port = 0
        self.dataMode = 0
        self.transferMode = 0
        self.transferType = 0
        self.restPos = 0
        self.response = ''
        self.returnValue = True
        self.local_path = ''
        self.server_path = ''

    def dispatch(self, command, content):
        if hasattr(Client, command):
            if self.transferMode == 1:
                self.returnValue = True
                return
            self.returnValue = getattr(Client, command)(self, content)
        else:
            self.returnValue = False

    def sendCommand(self, command, content):
        if content != '':
            content = ' ' + content
        data = command + content + '\r\n'
        self.socket_command.send(data.encode())

    def recvRes(self):
        res = self.socket_command.recv(1024, MSG_PEEK).decode()
        pos = res.find('\r\n')
        if pos == -1:
            pos = 1024
        else:
            pos += 2
        res = self.socket_command.recv(pos + 2)
        self.recv_msg.emit(res.decode()[:-2])
        return res.decode()

    def recvData(self,socket, decode=True):
        if decode:
            res = socket.recv(1024, MSG_PEEK).decode()
            pos = res.find('\r\n')
        else:
            res = socket.recv(1024, MSG_PEEK)
            pos = res.find('\r\n'.encode())
        if pos == -1:
            pos = 1024
        else:
            pos += 2
        res = socket.recv(pos)
        if decode:
            return res.decode()
        else:
            return res

    def connect(self, content):
        self.socket_command = socket(AF_INET, SOCK_STREAM)
        self.socket_command.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.socket_data = socket(AF_INET, SOCK_STREAM)
        self.socket_data.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        content = content.split()
        if len(content) != 2:
            return False
        self.ip = content[0]
        self.port = content[1]
        try:
            self.port = int(self.port)
        except ValueError:
            return False
        if re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', self.ip) is None:
            return False
        try:
            self.socket_command.connect((self.ip, self.port))
        except Exception:
            return False
        self.recvRes()
        return True

    def user(self, content):
        self.sendCommand('user', content)
        res = self.recvRes()
        if not res.startswith('331'):
            return False
        return True

    def password(self, content):
        self.sendCommand('pass', content)
        res = self.recvRes()
        if not res.startswith('230'):
            return False
        return True

    def pasv(self, content):
        self.sendCommand('pasv', content)
        res = self.recvRes()
        if not res.startswith('227'):
            return False
        pattern = r'(\d{1,3},\d{1,3},\d{1,3},\d{1,3},\d{1,3},\d{1,3})'
        ip_port = re.search(pattern, res)
        if ip_port:
            ip_port = ip_port.group(1)
            ip_port = ip_port.split(',')
            if len(ip_port) == 6:
                self.ip = '.'.join(ip_port[:4])
                self.port = int(ip_port[4]) * 256 + int(ip_port[5])
                self.socket_data = socket(AF_INET, SOCK_STREAM)
                self.socket_data.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
                try:
                    self.socket_data.connect((self.ip, self.port))
                except:
                    return False
                self.dataMode = 1
        return True

    def port(self, content):
        ip_port = content.split()
        if len(ip_port) == 2:
            ip = ip_port[0]
            try:
                port = int(ip_port[1])
            except ValueError:
                return False
            self.socket_data = socket(AF_INET, SOCK_STREAM)
            self.socket_data.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            try:
                self.socket_data.bind((ip, port))
                self.socket_data.listen(1)
            except Exception as e:
                print(e)
                return False
            content = ip.replace('.', ',')+','
            content += str(int(port/256))+','
            content += str(port%256)
            self.sendCommand('port', content)
            res = self.recvRes()
            if not res.startswith('200'):
                self.socket_data.shutdown(SHUT_RDWR)
                self.socket_data.close()
                return False
            self.dataMode = 2
            return True
        return False

    def pwd(self, content):
        self.sendCommand('pwd', content)
        res = self.recvRes()
        if not res.startswith('257'):
            return False
        else:
            self.pwd_signal.emit(res.split()[1][1:-1])
            return True

    def cwd(self, content):
        self.sendCommand('cwd', content)
        res = self.recvRes()
        if not res.startswith('250'):
            return False
        return True

    def mkd(self, content):
        self.sendCommand('mkd', content)
        res = self.recvRes()
        if not res.startswith('257'):
            return False
        return True

    def rmd(self, content):
        self.sendCommand('rmd', content)
        res = self.recvRes()
        if not res.startswith('250'):
            return False
        return True

    def rnfr(self, content):
        self.sendCommand('rnfr', content)
        res = self.recvRes()
        if not res.startswith('350'):
            return False
        return True

    def rnto(self, content):
        self.sendCommand('rnto', content)
        res = self.recvRes()
        if not res.startswith('250'):
            return False
        return True

    def syst(self, content):
        self.sendCommand('syst', content)
        self.response = ' '.join(self.recvRes().split()[1:])
        return True

    def type(self, content):
        self.sendCommand('type', content)
        self.response = ' '.join(self.recvRes().split()[1:])
        return True

    def list(self, content):
        self.sendCommand('list', content)
        res = self.recvRes()
        if not res.startswith('150'):
            return False
        else:
            thread = threading.Thread(target=self.readList)
            thread.start()
            return True

    def rest(self, content):
        self.sendCommand('rest', content)
        res = self.recvRes()
        if not res.startswith('350'):
            return False
        self.restPos = int(content)
        return True

    def retr(self, content):
        self.sendCommand('retr', content)
        res = self.recvRes()
        if not res.startswith('150'):
            return False
        else:
            self.transferType = 1
            thread = threading.Thread(target=self.readFile)
            thread.start()
            return True

    def stor(self, content):
        self.sendCommand('stor',content)
        res = self.recvRes()
        if not res.startswith('150'):
            return False
        else:
            self.transferType = 2
            thread = threading.Thread(target=self.sendFile)
            thread.start()
            return True

    def quit(self, content):
        self.sendCommand('quit', content)
        self.recvRes()
        self.socket_command.close()
        self.socket_data.close()

    def sendFile(self):
        if self.dataMode == 0:
            return
        if self.dataMode == 1:
            self.transferMode = 1
            try:
                with open(self.local_path, "rb") as file:
                    file.seek(self.restPos)
                    while True:
                        time.sleep(0.00000000000001)
                        if self.transferMode == -1:
                            break
                        data = file.read(1024)
                        self.socket_data.send(data)
                        if len(data) == 0:
                            break
                        self.restPos += len(data)
                        self.progress_update.emit(self.restPos)
            except IOError as e:
                print(e)
            try:
                self.socket_data.shutdown(SHUT_RDWR)
                self.socket_data.close()
            except:
                print(1)
            self.dataMode = 0
        if self.dataMode == 2:
            conn_data, address = self.socket_data.accept()
            self.transferMode = 1
            try:
                with open(self.local_path, "rb") as file:
                    file.seek(self.restPos)
                    while True:
                        time.sleep(0.00000000000001)
                        if self.transferMode == -1:
                            break
                        data = file.read(1024)
                        conn_data.send(data)
                        if len(data) == 0:
                            break
                        self.restPos += len(data)
                        self.progress_update.emit(self.restPos)
            except IOError as e:
                print(e)
            try:
                conn_data.shutdown(SHUT_RDWR)
                conn_data.close()
                self.socket_data.shutdown(SHUT_RDWR)
                self.socket_data.close()
            except:
                pass
            self.dataMode = 0

        self.recvRes()
        if self.transferMode != -1:
            self.restPos = 0
            self.transferMode = 0
            self.transfer_complete.emit(1)
        self.transferMode = 0

    def readFile(self):
        if self.restPos:
            mode = 'ab'
        else:
            mode = 'wb'
        if self.dataMode == 0:
            return False
        if self.dataMode == 1:
            self.transferMode = 1
            try:
                with open(self.local_path, mode) as file:
                    while True:
                        data = self.recvData(socket=self.socket_data,decode=False)
                        if len(data) == 0:
                            break
                        file.write(data)
                        self.restPos += len(data)
                        self.progress_update.emit(self.restPos)
                        if self.transferMode == -1:
                            break
            except IOError as e:
                print(e)
            try:
                self.socket_data.shutdown(SHUT_RDWR)
                self.socket_data.close()
            except:
                pass
            self.dataMode = 0
        if self.dataMode == 2:
            conn_data, address = self.socket_data.accept()
            self.transferMode = 1
            try:
                with open(self.local_path, mode) as file:
                    while True:
                        data = self.recvData(socket=conn_data, decode=False)
                        if len(data) == 0:
                            break
                        file.write(data)
                        self.restPos += len(data)
                        self.progress_update.emit(self.restPos)
                        if self.transferMode == -1:
                            break
            except IOError as e:
                print(e)
            try:
                conn_data.shutdown(SHUT_RDWR)
                conn_data.close()
                self.socket_data.shutdown(SHUT_RDWR)
                self.socket_data.close()
            except:
                pass
            self.dataMode = 0

        self.recvRes()
        if self.transferMode != -1:
            self.transferMode = 0
            self.restPos = 0
            self.transfer_complete.emit(1)
        self.transferMode = 0

    def readList(self):
        if self.dataMode == 0:
            return False
        if self.dataMode == 1:
            while True:
                data = self.recvData(socket=self.socket_data, decode=False)
                if len(data) == 0:
                    break
                self.parseList(data.decode())
            try:
                self.socket_data.shutdown(SHUT_RDWR)
                self.socket_data.close()
            except:
                print(2)
            self.dataMode = 0
        if self.dataMode == 2:
            conn_data, address = self.socket_data.accept()
            while True:
                data = self.recvData(socket=conn_data, decode=False)
                if len(data) == 0:
                    break
                self.parseList(data.decode())
            try:
                conn_data.shutdown(SHUT_RDWR)
                conn_data.close()
                self.socket_data.shutdown(SHUT_RDWR)
                self.socket_data.close()
            except:
                pass
            self.dataMode = 0
        self.recvRes()

    def parseList(self, data):
        data = data.split()
        if data[0][0] == 'd':
            type = 'Directory'
        else:
            type = 'File'
        name = ''.join(data[8:])
        time = ' '.join(data[5:8])
        size = int(data[4])
        size = self.bytes(size)

        self.insert_file.emit(name, type, size, time)

    def bytes(self, byte):
        if byte < 1024:
            byte = str(round(byte, 2)) + ' B'
        elif byte < 1024 * 1024:
            byte = str(round(byte / 1024, 2)) + ' KB'
        elif byte < 1024 * 1024 * 1024:
            byte = str(round(byte / 1024 / 1024, 2)) + ' MB'
        elif byte < 1024 * 1024 * 1024 * 1024:
            byte = str(round(byte / 1024 / 1024 / 1024, 2)) + ' GB'
        else:
            byte = str(round(byte / 1024 / 1024 / 1024 / 1024, 2)) + ' TB'
        return byte


class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def majorityElement(self, nums):
        sorted(nums)
        numDict = {}
        for n in nums:
            numDict[n] = numDict.get(n,0) + 1
        return max(numDict.values())

test = Solution()
print(test.majorityElement([1,2,3,4,4,4,5,7,7,7,4,7]))


from abc import ABC, abstractmethod
import csv
from pprint import pprint
import pandas as pd
import uuid

class Cupcake(ABC):
    size = "regular"
    def __init__(self, name, price, flavor, frosting, filling):
        self.name = name
        self.price = price
        self.flavor = flavor
        self.frosting = frosting
        self.filling = filling
        self.sprinkles = []

    def add_sprinkles(self, *args):
        for sprinkle in args:
            self.sprinkles.append(sprinkle)

    # @abstractmethod
    def calculate_price(self, quantity):
        return quantity * self.price

class Mini(Cupcake):
    size = "mini"

    def __init__(self, name, price, flavor, frosting):
        self.name = name
        self.price = price
        self.flavor = flavor
        self.frosting = frosting
        self.sprinkles = []

cupcake_1 = Cupcake('Super Chocolate', 4.99, 'Chocolate', 'Chocolate', 'Chocolate Mousse')

cupcake_1.add_sprinkles('Chocolate', 'White Chocolate Shavings')

# print(cupcake_1.sprinkles)

cupcake_2 = Mini('Vanilla Swirl', 1.99, 'Marbled', 'Choco-Swirl')
# print(cupcake_2.name)
# print(cupcake_2.price)
# print(cupcake_2.size)

def read_csv(file):
    with open(file) as csvfile:
        reader = csv.DictReader(csvfile)

        for row in reader:
            pprint(row)

# read_csv("sample.csv")

def write_new_csv(file, cupcakes):
    with open(file, "w", newline="\n") as csvfile:
        fieldnames = ["size", "name", "price", "flavor", "frosting", "sprinkles", "filling"]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        writer.writeheader()

        for cupcake in cupcakes:
            if hasattr(cupcake, "filling"):
                writer.writerow({"size": cupcake.size, "name": cupcake.name, "price": cupcake.price, "flavor": cupcake.flavor, "frosting": cupcake.frosting, "filling": cupcake.filling, "sprinkles": cupcake.sprinkles})
            else:
                writer.writerow({"size": cupcake.size, "name": cupcake.name, "price": cupcake.price, "flavor": cupcake.flavor, "frosting": cupcake.frosting, "sprinkles": cupcake.sprinkles})

def append_to_csv(file, cupcake):
    with open(file, "a", newline="\n") as csvfile:
        fieldnames = ["size", "name", "price", "flavor", "frosting", "sprinkles", "filling"]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        if hasattr(cupcake, "filling"):
            writer.writerow({"size": cupcake.size, "name": cupcake.name, "price": cupcake.price, "flavor": cupcake.flavor, "frosting": cupcake.frosting, "filling": cupcake.filling, "sprinkles": cupcake.sprinkles})
        else:
            writer.writerow({"size": cupcake.size, "name": cupcake.name, "price": cupcake.price, "flavor": cupcake.flavor, "frosting": cupcake.frosting, "sprinkles": cupcake.sprinkles})

#testing functions

# append_to_csv('sample.csv', cupcake_1)
# read_csv('sample.csv')

def get_cupcakes(file):
    with open(file) as csvfile:
        reader = csv.DictReader(csvfile)
        reader = list(reader)
        return reader

def find_cupcake_by_name(file, name):
    for cupcake in get_cupcakes(file):
        if cupcake['name'] == name:
            return cupcake
    return None

def find_cupcake_by_id(file, id):
    for cupcake in get_cupcakes(file):
        if cupcake['id'] == id:
            return cupcake
    return None

def add_cupcake_dictionary(file, cupcake):
    with open(file, 'a', newline="\n") as csvfile:
        fieldnames = ['id', 'size', 'name', 'price', 'flavor', 'frosting', 'sprinkles', 'filling']
        cupcake['id'] = str(uuid.uuid4())
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow(cupcake)

def order_price(file):
    price = 0
    for cupcake in get_cupcakes(file):
        price += float(cupcake['price'])
    return round(price, 2)

def remove_cupcake(file, cupcake):
    df = pd.read_csv(file)
    print(cupcake['id'])
    df = df[df.name != cupcake['id']]
    df.to_csv(file, index=False)


from user import User

class Privilege:
    """This class models privilages of an admin"""

    def __init__(self, privilages=['can add post', 'can delete post', 'can ban user',
            'Create User', 'Update User', 'Display User\'s information ', 'Delete User', ]
            ):
        self.privilages = privilages

    def show_privileges(self):
        print("List of Admin Privileges are:")
        for privilege in self.privilages:
            print(f" - {privilege}")
        return ""

class Admin(User):
    """This an Admin model that inherit from the User class"""

    def __init__(self, first_name, last_name, *user_profile):
        super().__init__(first_name, last_name, *user_profile)
        self.privileges = Privilege()


from itertools import accumulate

def dice_results(dices, n):
    a1, b1, a2, b2 = dices
    results = [0] * (n + 1)
    for d1 in range(a1, b1 + 1):
        for d2 in range(a2, b2 + 1):
            results[d1 + d2] += 1
    return results

if __name__ == '__main__':
    dices_g = list(map(int, input().split()))
    dices_e = list(map(int, input().split()))
    number_max = max([dices_g[1] + dices_g[3], dices_e[1] + dices_e[3]])
    results_g = dice_results(dices_g, number_max)
    results_e = dice_results(dices_e, number_max)

    wins_g = 0
    cumulative_e = list(accumulate(results_e))
    for result, frequency in enumerate(results_g):
        wins_g += frequency * cumulative_e[result - 1]

    wins_e = 0
    cumulative_g = list(accumulate(results_g))
    for result, frequency in enumerate(results_e):
        wins_e += frequency * cumulative_g[result - 1]

    if wins_g > wins_e:
        print('Gunnar')
    elif wins_g < wins_e:
        print('Emma')
    else:
        print('Tie')


#!/bin/python3

import os
import sys

#
# Complete the truckTour function below.
#
def truckTour(petrolPumps):
    #
    # Write your code here.
    #
    req = 0
    total = 0
    i = 0

    while i<len(petrolPumps):
        total += petrolPumps[i][0]-petrolPumps[i][1]
        if total<0:
            req -= total
            total = 0
            start = i+1
        i+=1

    if total-req>=0:
        return start
    else:
        return -1

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    petrolpumps = []

    for _ in range(n):
        petrolpumps.append(list(map(int, input().rstrip().split())))

    result = truckTour(petrolpumps)

    fptr.write(str(result) + '\n')

    fptr.close()


import sys

N = int(sys.stdin.readline().rstrip()) #N번방 입력
T = 2 #T=T+6*i를 위한 초기값()
i = 0 #이동수 - 1
while True: #발견할떄 까지 무한 루프
    T += 6*i  #문제의 규칙
    if N < T: #N=1이면 어짜피 T=2이므로 작음
        print(i+1)
        break
    i += 1


# number of vehicles to include in the simulation
numVehicles = 200

simulation_start_date = '02/23/16'  # mm/dd/yy format

simulation_start_time = '04:00'	# start simulation at midnight

simulation_end_date = '02/23/16'  # mm/dd/yy format

simulation_end_time = '19:00'	# run simulation for an entire day

max_pwr = 260.0 # kW

data_filename = 'SampleData0.csv'


import uasyncio
import ulogging

import sensor
import store
import ds18x20
import machine
import onewire

global ds_sensor, roms
ds_pin = machine.Pin(0, machine.Pin.PULL_UP)

def init():
    ulogging.info("In init")
    global ds_sensor
    global roms
    try:
        ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))
        roms = ds_sensor.scan()
        ulogging.info('Found DS devices: ' + str(roms))
    except Exception as err:
        ulogging.error(str(err))

init()

def temperature():
    try:
        if len(roms) == 0:
            return -273
        ds_sensor.convert_temp()
        uasyncio.sleep_ms(750)
        return ds_sensor.read_temp(roms[0])
    except onewire.OneWireError as err:
        ulogging.error(str(err))
        return -273
    except Exception as err:
        ulogging.error(str(err))
        return -273

async def run():
    while True:
        try:
            store.ds_temperature = temperature()
            ulogging.debug('temperature= ' + str(store.ds_temperature))
            await uasyncio.sleep(30)
        except Exception as err:
            ulogging.debug(str(err))


#
# @author Felipe Serna
# @email damsog38@gmail.com
# @create date 2021-14-06 20:01:10
# @modify date 2022-02-13 14:19:39
# @desc API that serves Analytics Processes. Face Detection and Recognition for both
# single images as well as live processes. This app imports and calls a process object
# which loads the detection and recognition models on gpu memory and then can be used to initiate.
#

#*************************************************************************************************
#                                              Dependencies
#*************************************************************************************************

# Importing configurations & Global Variables
from dotenv import load_dotenv, find_dotenv

# API Server dependencies
from aiohttp import web
import asyncio
from av import VideoFrame
from aiortc import MediaStreamTrack, RTCPeerConnection, RTCSessionDescription
from aiortc.contrib.media import MediaBlackhole, MediaPlayer, MediaRecorder, MediaRelay
import ssl

# Other useful dependencies
import json
import os
import uuid

# Analytics personal Library
from videoAnalytics.processor import processor

# Logging, Terminal Styles & Colors Dependencies
import logging
import iridi
import pyfiglet
import colorful

#*************************************************************************************************
#                                              Definitions
#*************************************************************************************************
class VideoProcessorTrack(MediaStreamTrack):
    """
    A video stream track that transforms frames from an another track.
    """

    kind = "video"

    def __init__(self, track, process, processor, dataset_path=None):
        super().__init__()  # don't forget this!
        self.track = track
        self.process = process
        self.processor = processor
        if dataset_path:
            self.processor.set_analyzer_dataset(dataset_path)

    async def recv(self):
        frame = await self.track.recv()

        if self.process == "detection":
            img = frame.to_ndarray(format="bgr24")
            _,img = self.processor.detect_image(img, return_img=True)
            # rebuild a VideoFrame, preserving timing information
            new_frame = VideoFrame.from_ndarray(img, format="bgr24")
            new_frame.pts = frame.pts
            new_frame.time_base = frame.time_base
            return new_frame
        elif self.process == "recognition":
            #TODO: Dont load the dataset for each image. its making it laggy.
            img = frame.to_ndarray(format="bgr24")
            _,img = self.processor.analyze_image_2(img, return_img=True)
            # rebuild a VideoFrame, preserving timing information
            new_frame = VideoFrame.from_ndarray(img, format="bgr24")
            new_frame.pts = frame.pts
            new_frame.time_base = frame.time_base
            return new_frame
        else:
            return frame

#*************************************************************************************************
#                                              Main Function
#*************************************************************************************************
def main():
    #initializations
    load_dotenv(find_dotenv())

    # Some definitions
    NET = None
    METADATA = None
    MAX_SIMULTANEOUS_PROCESSES = 1
    NUM_SESSIONS = 0
    HOST = os.environ.get("SERVER_IP")
    PORT = os.environ.get("SERVER_PORT")
    SSL_CONTEXT = os.environ.get("SERVER_SSL_CONTEXT")
    SSL_KEYFILE = os.environ.get("SERVER_SSL_KEYFILE")
    ROOT = os.path.dirname(__file__)
    LOGGER_LEVEL = os.environ.get("LOGGER_LEVEL")

    # Server Api title definition
    serverTitle = pyfiglet.figlet_format("Gnosis", font="isometric2", width=200)
    serverSubtitle = pyfiglet.figlet_format("Face Analytics Server", font="alligator2", width=300)

    logger = logging.getLogger(__name__)
    logger_format = '%(asctime)s : : %(levelname)s : : %(name)s : : %(message)s'
    logger_date_format = '[%Y:%m:%d %H:%M:%S %Z]'

    if LOGGER_LEVEL == "DEBUG":
        logging.basicConfig(level=logging.DEBUG, format=logger_format, datefmt=logger_date_format)
    else:
        logging.basicConfig(level=logging.INFO,  format=logger_format, datefmt=logger_date_format)

    iridi.print(serverTitle, ["#8A2387", "#E94057", "#F27121"], bold=True)
    iridi.print(serverSubtitle, ["#8A2387", "#E94057", "#F27121"], bold=True)

    mProcessor = processor()
    pcs = set()
    relay = MediaRelay()
    #======================================================Requests============================================================

    async def encode_images(request):
        logger.info("Encode images Requested")
        datajson = await request.json()

        logger.debug(f'Data received: {datajson}')

        logger.debug(f'Processing images: {datajson["imgs"]}')
        result = mProcessor.encode_images( str(datajson).replace("'",'"') )

        return web.Response(
            content_type="application/json",
            text=str(result).replace("'",'"')
        )

    async def analyze_image(request):
        logger.info("Analyze image requested")

        datajson = await request.json()
        logger.debug(f'Information: {datajson}')

        return_img_json = True if datajson["return_img"]==1 else False
        logger.debug(f'Return img as b64: {return_img_json}')

        dataset_path = datajson["dataset_path"]
        logger.debug(f'Dataset : {dataset_path}')

        img_b64 =  datajson["img"]

        logger.debug('Processing Image')
        result = mProcessor.analyze_image(dataset_path,mProcessor.b642cv2( img_b64 ),return_img_json=return_img_json)

        return web.Response(
            content_type = "application/json",
            text = str(result)
        )

    async def detect_image(request):
        logger.info('Detect image requested')

        datajson = await request.json()
        logger.debug(f'Information: {datajson}')

        return_img_json = True if datajson["return_img"] == 1 else False
        logger.debug(f'Return img as b64: {return_img_json}')

        img_b64 = datajson["img"]

        logger.debug('Detecting Image')
        result = mProcessor.detect_image(mProcessor.b642cv2( img_b64 ), return_img_json=return_img_json )

        return web.Response(
            content_type = "application/json",
            text = str(result)
        )

    async def facedet_stream(request):
        params = await request.json()
        logger.info("Face detection stream requested")
        offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])

        pc = RTCPeerConnection()
        pc_id = "PeerConnection(%s)" % uuid.uuid4()
        pcs.add(pc)

        def log_info(msg, *args):
            logger.info( colorful.cyan( pc_id + " " + msg ), *args )

        log_info("Created for %s", request.remote)

        # prepare local media
        record = False
        if record:
            recorder = MediaRecorder("args.record_to")
        else:
            recorder = MediaBlackhole()

        @pc.on("connectionstatechange")
        async def on_connectionstatechange():
            log_info("Connection state is %s", pc.connectionState)
            if pc.connectionState == "failed":
                await pc.close()
                pcs.discard(pc)

        @pc.on("track")
        def on_track(track):
            log_info("Track %s received", track.kind)

            if track.kind == "video":
                pc.addTrack(
                    VideoProcessorTrack(
                        relay.subscribe(track), process="detection", processor=mProcessor
                    )
                )
                if record:
                    recorder.addTrack(relay.subscribe(track))

            @track.on("ended")
            async def on_ended():
                log_info("Track %s ended", track.kind)
                await recorder.stop()

        # handle offer
        await pc.setRemoteDescription(offer)
        await recorder.start()

        # send answer
        answer = await pc.createAnswer()
        await pc.setLocalDescription(answer)

        return web.Response(
            content_type="application/json",
            text=json.dumps(
                {"sdp": pc.localDescription.sdp, "type": pc.localDescription.type}
            ),
        )

    async def facerek_stream(request):
        params = await request.json()
        dataset_path = params["dataset_path"]
        logger.info(f'Face recognition stream requested. using group: {dataset_path}')
        offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])

        pc = RTCPeerConnection()
        pc_id = "PeerConnection(%s)" % uuid.uuid4()
        pcs.add(pc)

        def log_info(msg, *args):
            logger.info(pc_id + " " + msg, *args)

        log_info("Created for %s", request.remote)

        # prepare local media
        record = False
        if record:
            recorder = MediaRecorder("args.record_to")
        else:
            recorder = MediaBlackhole()

        @pc.on("connectionstatechange")
        async def on_connectionstatechange():
            log_info("Connection state is %s", pc.connectionState)
            if pc.connectionState == "failed":
                await pc.close()
                pcs.discard(pc)

        @pc.on("track")
        def on_track(track):
            log_info("Track %s received", track.kind)

            if track.kind == "video":
                pc.addTrack(
                    VideoProcessorTrack(
                        relay.subscribe(track), process="recognition", processor=mProcessor, dataset_path=dataset_path
                    )
                )
                if record:
                    recorder.addTrack(relay.subscribe(track))

            @track.on("ended")
            async def on_ended():
                log_info("Track %s ended", track.kind)
                await recorder.stop()

        # handle offer
        await pc.setRemoteDescription(offer)
        await recorder.start()

        # send answer
        answer = await pc.createAnswer()
        await pc.setLocalDescription(answer)

        return web.Response(
            content_type="application/json",
            text=json.dumps(
                {"sdp": pc.localDescription.sdp, "type": pc.localDescription.type}
            ),
        )

    async def on_shutdown(app):
        # close peer connections
        coros = [pc.close() for pc in pcs]
        await asyncio.gather(*coros)
        pcs.clear()

    if SSL_CONTEXT:
        ssl_context = ssl.SSLContext()
        ssl_context.load_cert_chain(SSL_CONTEXT, SSL_KEYFILE)
    else:
        ssl_context = None

    # Setting API Enpoints
    app = web.Application()
    app.on_shutdown.append(on_shutdown)
    app.router.add_post('/facedet_stream', facedet_stream)
    app.router.add_post('/facerek_stream', facerek_stream)
    app.router.add_post('/analyze_image', analyze_image)
    app.router.add_post('/detect_image', detect_image)
    app.router.add_post('/encode_images', encode_images)

    # Running the server
    web.run_app(
        app, access_log=None, host=HOST, port=PORT, ssl_context=ssl_context
    )

#*************************************************************************************************
#                                              Running
#*************************************************************************************************
if __name__=="__main__":
    main()


import sys
import json
import pysam
import truvari
from collections import Counter
from truvari.annotations.lcr import sequence_entropy
def filter_TR_entry(entry):
    """
    Returns True if this should be filtered
    """
    if "TRFdiff" not in entry.info or entry.info["TRFdiff"] == None:
        return True
    if entry.info["TRFperiod"] == 1:
        return True
    if len(entry.alts[0]) > len(entry.ref):
        seq = entry.alts[0][1:]
    else:
        seq = entry.ref[1:]
    if sequence_entropy(seq) < 0.25:
        return True
    return False

if __name__ == '__main__':
    v = pysam.VariantFile(sys.argv[1])
    #bed = sys.argv[2]
    header = v.header.copy()
    header.add_line('##FILTER=<ID=NONTR,Description="NonTR variant">')
    o = pysam.VariantFile('/dev/stdout', 'w', header=header)
    for entry in v:
        if truvari.entry_size(entry) < 5:
            o.write(entry)
            continue
        entry.translate(header)
        if filter_TR_entry(entry):
            entry.filter.clear()
            entry.filter.add('NONTR')
        o.write(entry)


import random
import json
import pandas as pd
import glob

def spawn_pokemon():
    df = pd.read_csv('pokemons.txt')
    elements = df.sample()
    moop = elements.to_string(index = False, header = False)
    moop2 = moop.lstrip()
    moop3 = moop2.upper()

    return(moop3)

def find_pokemon_sprite(text):
    lowercasestring = text.lower()
    dir = ("./mons/")
    wildcard = ("*.png")
    finalstring = dir+lowercasestring+wildcard
    files = glob.glob(finalstring)
    extractedstring = (files[0])
    s = list(extractedstring)
    s[6] = '/'
    x = "".join(s)

    return(x)

#find_pokemon_sprite()


def fazer_pizza(*coberturas):
    """--mostrar a lista de coberturas--"""

    print(' preparando a pizza com as seguintes coberturas:\n')
    for p in coberturas:
           print('-'+p)
    """função usando * , nesse caso vai mostrar as coberturas
        mesmo se na chamada da função, tivesse apenas 1 valor"""

fazer_pizza('tomate','queijo','calabresa','pimenta')


import sys
sys.stdin = open('input.txt')

# 보통의 정렬은 오름차순이나 내림차순으로 이루어지지만,
# 이번에는 특별한 정렬을 하려고 한다.

# N개의 정수가 주어지면 가장 큰 수, 가장 작은 수,
# 2번째 큰 수, 2번째 작은 수 식으로
# 큰 수와 작은 수를 번갈아 정렬하는 방법이다.

# 예를 들어 1부터 10까지 10개의 숫자가 주어지면 다음과 같이 정렬한다.
# 10 1 9 2 8 3 7 4 6 5

# 주어진 숫자에 대해 특별한 정렬을 한 결과를 10개까지 출력하시오

# 맨 첫줄에 주어진 테스트 케이스 만큼 반복을 진행한다.
# 테스트 케이스 아랫줄에는 정렬할 숫자의 개수를,
# 그 아랫줄에는 개수만큼의 정렬할 숫자들을 받아준다.
t = int(input())
for tc in range(1, t+1):
    n = int(input())
    num = list(map(int, input().split()))

    # 정렬을 위한 함수를 생성한다.
    # 이때, 인자로는 주어진 숫자들로 이루어진 리스트와
    # 리스트의 길이를 parameter로 집어넣는다.
    def select(num, n):

        # i와 i+1의 숫자를 비교할 것이므로,
        # i의 범위는 전체 길이에서 -1하여 설정하고
        # 최솟값과 최댓값을 i로 설정해준다.
        for i in range(n-1):
            mini = i
            maxi = i
            # 만약 i가 2로 나누어 떨어지지 않는 수라면,
            # 앞에서부터 최솟값을 찾아 바꾸어나가야 한다.
            # j의 범위는 i와 같은 이유로 시작 값을 i+1,
            # 마지막 값을 n으로 설정 한 뒤,
            # 최솟값을 찾아 i의 자리 숫자와 바꾼다.
            if i % 2:
                for j in range(i+1, n):
                    if num[mini] > num[j]:
                        mini = j
                num[i], num[mini] = num[mini], num[i]

            # 만약 i가 2로 나누어 떨어지는 수라면,
            # 앞에서부터 최댓값을 찾아 바꾸어나가야 한다.
            # i+1 부터 n까지의 범위 동안
            # 최댓값을 찾아 바꾸어 나간다.
            else:
                for j in range(i+1, n):
                    if num[maxi] < num[j]:
                        maxi = j
                num[i], num[maxi] = num[maxi], num[i]

        # 최종적으로 바꾼 num을 리턴한다.
        return num

    # 리턴 값을 담은 리스트 new를 생성하고
    # new 안에 있는 요소들을 10개까지
    # 주어진 양식에 맞게 출력한다.
    new = select(num, n)
    print(f'#{tc}', end= ' ')
    for i in range(10):
        print(new[i], end=' ')
    # 다음 케이스 결과를 출력할 때 줄을 바꾸기 위해
    # 프린트를 한 번 더 추가한다.
    print()


import _data_read as dr
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

def power_law(name):
   eta,gamma,tau,t=dr.Data_Read(name)
   func1 = lambda x,kappa,n: kappa*np.power(x,n-1)
   func=np.vectorize(func1)
   Xdata=gamma
   Ydata=eta
   plt.figure( num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k' )
   plt.plot( Xdata, Ydata, 'o', label='rownanie potegowe' )
   popt, pcov = curve_fit(func, Xdata, Ydata, p0=[1,1])
   print('Standardowe odchylenie dopasowania fit (eta) = ',dr.stdev(Xdata,Ydata,func,popt))
   plt.plot( Xdata, func(Xdata,*popt), 'b',
             label='dopasowanie: kappa = %5.3e, n = %5.3e' % tuple( popt ) )
   plt.xlabel('gamma')
   plt.ylabel('eta')
   plt.legend()
   plt.show()

power_law("wyniki.xls")


# download the casecase file from the CV2 git hub :
# https://github.com/opencv/opencv/tree/master/data/haarcascades

import cv2

face_Cascade = cv2.CascadeClassifier('c:\demo\haarcascade_frontalface_default.xml')

# you can use any video to capure the faces
cap = cv2.VideoCapture('C:\Python Code\FacialDetection\people.mp4')

while True:
    ret,img = cap.read()

    # convert to gray
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    # grab faces from the gray image

    faces = face_Cascade.detectMultiScale(gray,1.1,4)

    # draw a rectangle for each face (for each frame)
    for (x,y,w,h) in faces :
        cv2.rectangle(img,(x,y), (x+w,y+h),(255,0,0),3)

    # show each image
    cv2.imshow('img',img)

    # break if 'q' pressed

    if cv2.waitKey(1) & 0xff == ord('q'):
        break

cap.release()


from PyQt5 import QtWidgets,QtCore,QtGui
from PyQt5.QtWidgets import QTableView
from PyQt5.QtCore import QAbstractTableModel, Qt
from skip_frac import Ui_MainWindow
from run_desc import Ui_MainWindow2
from polymer_bounds import Ui_MainWindow3

import re
import sys
import pandas as pd
import numpy as np
import math
import os
from pathlib import Path

def filtered_data(name,time_underscore):
    # file_name = 'Burst on PThio DNA.txt'
    f = open(name, 'r')
    headers = ['Dye', 'Peak Number', 'Height', 'Time', 'Well', 'Area', 'Data Point']
    # data = pd.read_csv('Burst on PThio DNA.txt')
    f.readline()
    col_data = []
    count = 0
    # reads each line in the text file
    for test in f:
        # Splits column data based on header
        # Dye/Sample Peak,Sample File Name,Size, Height, Area,Data Point

        test_set = test.split()
        # Output: ['"B,1"', 'PT_100nM_0_TLD_4.2.19_1_2019-04-02_A05.fsa', '894', '11056', '2524']

        # print(test_set)
        # strips the underscore in long description
        desc_fix = test_set[1].split('_')
        # Output: ['PT', '100nM', '0', 'TLD', '4.2.19', '1', '2019-04-02', 'A05.fsa']

        # print(desc_fix)
        # removes long description name
        test_set.pop(1)
        # Output: ['"B,1"','894', '11056', '2524']
        # print(test_set)
        # print(test_set)

        # inserts time into test_set
        test_set.insert(2, desc_fix[time_underscore])

        # Output:['"B,1"', 'PT_100nM_0_TLD_4.2.19_1_2019-04-02_A05.fsa', '0', '894', '11056', '2524']

        # inserts Well number at the end of test_set
        test_set.insert(3, desc_fix[len(desc_fix) - 1])

        # Output: #['"B,1"', 'PT_100nM_0_TLD_4.2.19_1_2019-04-02_A05.fsa', '0', 'A05.fsa', '894', '11056', '2524']

        # print(test_set)

        # splits dye and peak number and puts them into separate columns
        dye_peak = test_set[0].strip('\"').replace(',', '')
        test_set.pop(0)
        i = 0
        while i < len(dye_peak):
            test_set.insert(i, dye_peak[i])
            i += 1
        # print(test_set)
        # adding all data to each column
        col_data.append(test_set)
        count += 1
    # pprint.pprint(col_data)
    df = pd.DataFrame(col_data, columns=headers)
    # print(col_data)

    # filters height above user input. Note that if filter height
    # is above internal standard height, then error will raise
    # have to add try/except block here for future use
    return df
    # df_int_all = df.loc[df['Dye'] == 'Y']
    # return df_int_all
    # print()
    # print("These are all the internal std. peaks\n")
    # print('---------------------------------------\n')
    # print(df_int_all)
    # print()
    #min_height = input("Please enter the minimum height (make sure bigger than int std desired): ")
    # while string_alpha_check(min_height):
    #     min_height = input("Not valid integer, please try again: ")

    # min_height = int(min_height)
    # df_hmin = df.loc[df['Height'].astype(int) > min_height]
    # return df_hmin

def int_std_all(df):
    df_int_all = df.loc[df['Dye'] == 'Y']
    return df_int_all

def all_peaks_filtered(df,min_height):
    df_hmin = df.loc[df['Height'].astype(int) > min_height]
    return df_hmin
def int_std_filtered(df):
    df_int_std_filtered = df.loc[df['Dye'] == 'Y']
    return df_int_std_filtered

class pandasModel(QAbstractTableModel):

    def __init__(self, data):
        QAbstractTableModel.__init__(self)
        self._data = data

    def rowCount(self, parent=None):
        return self._data.shape[0]

    def columnCount(self, parent=None):
        return self._data.shape[1]

    def data(self, index, role=Qt.DisplayRole):
        if index.isValid():
            if role == Qt.DisplayRole:
                return str(self._data.iloc[index.row(), index.column()])
        return None

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self._data.columns[col]
        return None

class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow,self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle('Skip Frac vs. Size')
        self.show()
        self.ui.pushButton.clicked.connect(self.on_push_yes)
        # self.ui.hide()
        self.ui.pushButton_2.clicked.connect(self.on_push_no)

    def on_push_yes(self):
        print('Hello')
    def on_push_no(self):
        self.close()
        self.RunDesc = RunDesc()
        #self.ui.close()
        # window_RunD = RunDesc()
        # window_RunD.show()

class RunDesc(QtWidgets.QMainWindow):
    def __init__(self):
        super(RunDesc,self).__init__()
        self.ui2 = Ui_MainWindow2()
        self.ui2.setupUi2(self)
        self.setWindowTitle('Run Description')
        self.show()
        #Gets the file run description from text file
        self.ui2.pushButton.clicked.connect(self.getTxt)
        #Gets the time underscore
        self.ui2.pushButton_2.clicked.connect(self.getTimeUnderscore) #Gets the time underscore
        self.ui2.pushButton_3.clicked.connect(self.pressBack) #Goes to the previous frame
        self.ui2.pushButton_8.clicked.connect(self.showAllPeaks) #Shows all the peaks before filtering
        self.ui2.pushButton_4.clicked.connect(self.showAllIntStdPeaks) #Shows all internal standard peaks
        self.ui2.pushButton_5.clicked.connect(self.getMinHeight) #Gets the minimum height filter
        self.ui2.pushButton_6.clicked.connect(self.showAllFilteredPeaks) #Shows all the filtered peaks
        self.ui2.pushButton_7.clicked.connect(self.showFilteredStd) #Shows all the filtered internal std. peaks
        self.ui2.pushButton_9.clicked.connect(self.showPolymerBounds)

#fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', QtCore.QDir.rootPath() , '*.xlsm')

    def getTxt(self):
        global fileName
        #options = QtGui.QFileDialog.Options()
        fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', QtCore.QDir.rootPath(), '*.txt')
        #self.ui2.lineEdit_2.setText(fileName)
        file = open(fileName,'r')
        file.readline()
        second_line = file.readline()
        split_second_line = second_line.split()
        txt_file_name = split_second_line[1]
        file.close()
        self.ui2.lineEdit_2.setText(fileName)
        self.ui2.RunDescLabel.setText(txt_file_name)
        # self.df = filtered_data(fileName,2)
        # model = pandasModel(self.df)
        # self.view = QTableView()
        # self.view.setModel(model)
        # self.view.setWindowTitle('Internal Standard Peaks')
        # self.view.resize(800, 600)
        # self.view.show()

    #Have to error check in case not an integer
    def getTimeUnderscore(self):
        global time_underscore
        time_underscore = int(self.ui2.lineEdit.text())

    def pressBack(self):
        self.close()
        self.backFrac = MyWindow()

    def getMinHeight(self):
        global min_height
        min_height = int(self.ui2.lineEdit_3.text())

    def showAllPeaks(self):
        self.df_all_peaks = filtered_data(fileName,time_underscore)
        #self.df_int_std_all = int_std_all(self.df_all_peaks)
        model = pandasModel(self.df_all_peaks)
        self.view = QTableView()
        self.view.setModel(model)
        self.view.setWindowTitle('All Peaks')
        self.view.resize(800, 600)
        #self.close()
        self.view.show()

    def showAllIntStdPeaks(self):
        self.df_all_int_std_peaks = int_std_all(self.df_all_peaks)
        model_all_int = pandasModel(self.df_all_int_std_peaks)
        self.view_int_std_all = QTableView()
        self.view_int_std_all.setModel(model_all_int)
        self.view_int_std_all.setWindowTitle('All Internal Std. Peaks')
        self.view_int_std_all.resize(800, 600)
        # self.close()
        self.view_int_std_all.show()

    def showAllFilteredPeaks(self):
        global df_global_peaks #For use in another class
        self.df_all_filtered_peaks = all_peaks_filtered(self.df_all_peaks,min_height)
        df_global_peaks = all_peaks_filtered(self.df_all_filtered_peaks,min_height)
        model_all_filtered = pandasModel(self.df_all_filtered_peaks)
        self.view_all_filtered = QTableView()
        self.view_all_filtered.setModel(model_all_filtered)
        self.view_all_filtered.setWindowTitle('All Filtered Peaks')
        self.view_all_filtered.resize(800,600)
        #self.close()
        self.view_all_filtered.show()

    def showFilteredStd(self):
        self.df_int_std_filter = int_std_filtered(self.df_all_filtered_peaks)
        model_int_std_filter = pandasModel(self.df_int_std_filter)
        self.view_int_std_filter = QTableView()
        self.view_int_std_filter.setModel(model_int_std_filter)
        self.view_int_std_filter.setWindowTitle('Filtered internal std. peaks')
        self.view_int_std_filter.resize(800,600)
        #self.close()
        self.view_int_std_filter.show()

    def showPolymerBounds(self):
        self.polymer = polymerBounds()
        #pass

def sample_distance(filtered_data):
    # gets peaks without internal standard
    df_no_int = filtered_data.loc[filtered_data['Dye'] == 'B']
    #print(df_no_int)

    # gets peaks with internal standard
    df_int_std = filtered_data.loc[filtered_data['Dye'] == 'Y']

    #Exports the internal standard data
    #export_int_std = df_int_std.to_csv('Export_data_int_std.csv',sep = ',')
    # print('These are the internal std. peaks after filtering')
    # print('------------------------------------------------')
    # print(df_int_std)
    # print()
    # makes list of int standard data points
    int_stdlist = df_int_std['Data Point'].tolist()

    # makes list of int standard time points
    int_stdtimelist = df_int_std['Time'].tolist()

    # makes list of sample data points
    sample_list = df_no_int['Data Point'].tolist()

    # makes list of sample time points
    sample_timelist = df_no_int['Time'].tolist()
    # print(sample_timelist)

    #zips the internal standard time points and data points into a dictionary
    # Ex: {1:2,3:4}
    int_std_dict = dict(zip(int_stdtimelist, int_stdlist))

    #zips the sample time points and data points into a nested list
    # Ex: [[1,2],[3,4]]
    sample_2d = [list(a) for a in zip(sample_timelist, sample_list)]

    #pprint.pprint(sample_2d)

    # if sample_2d[i][0] in int_std_dict:

    #Creates a column in the pandas dataframe for difference
    #(internal standard - sample) by using datapoint
    #For each time
    diff_list = []
    for i in range(len(sample_2d)):
        #Subtracts the internal std value by the sample datapoint
        #Method is inefficient, could probably use nested list
        # for the internal standards as well
        #diff = int(int_std_dict[sample_2d[i][0]]) - int(sample_2d[i][1])
        diff = round(float(int(int_std_dict[sample_2d[i][0]])/int(sample_2d[i][1])) * 100,2)
        diff_list.append(diff)

    #This is to prevent pandas SettingwithCopyWarning
    df_diff = df_no_int.copy()
    df_diff['Diff'] = diff_list

    # exports data with compared to internal standard
    #export_excel_difference = df_diff.to_csv('Export_data_intstd_Diff.csv',sep=',')

    #Returns a dataframe containing values with differences and
    #No intenal standard column
    return (df_diff)

def size(df,length,ranges_list):
    # Asks user input for template size
    # original = int(input('Please enter the template size: '))
    # Adjusts the peak number in relation to template size

    # Polymer length list. Ex: [27mer,28mer,29mer]
    #length = []

    # Nested list for the ranges of the difference ranges for each polymer.
    # Ex: For 27mer: [[300,400]]. Where 300 is lower bound and 400 is upper bound
    #ranges_list = []

    # Creates a dictionary for polymer length and difference ranges
    # Ex: {27mer:[300,400],28mer"[450,500]}
    ranges_dict = {}

    # Loop appends each polymer as the key and the range list as the value
    for i in range(len(ranges_list)):
        ranges_dict[length[i]] = ranges_list[i]
    # print(ranges_dict)

    # Takes difference values to list
    diff_list = df['Diff'].astype(float).tolist()

    # Gets the keys of the dictionary which are the polymer sizes
    ranges_keys = list(ranges_dict.keys())
    # print(ranges_keys)
    final_length_list = []
    # print(diff_list)

    # Parses the differences (internal std - sample) and checks to see
    # If within a certain range. If it is, then it is appends the key(size)
    # to final_length_list
    for j in diff_list:
        for i in range(len(ranges_keys)):
            # Gets the value of ranges. Ex: [300,400]
            width = ranges_dict[ranges_keys[i]]
            # print(ranges_dict[ranges_keys[i]])

            # Takes lower bound
            low = width[0]
            # Takes upper bound
            high = width[-1]
            # If the difference is in between these bounds, then
            # append the size to the final_length_list
            if j >= low and j < high:
                final_length_list.append(ranges_keys[i])

    # print(final_length_list)
    # Creates a new column in the dataframe for the size of each sample run
    df["Size"] = final_length_list

    return df

 # Function that creates the table containing area values for each polymer
def table(df):
    #Creates sorted set with time values (unique values only)
    df_time = list(set(df['Time'].tolist()))
    df_time.sort()

    #Creates sorted set with size values (unique values only)
    df_size = list(set(df['Size'].tolist()))
    df_size.sort(key=natural_keys)

    #print(df_size)
    #n = pd.DataFrame(columns = df_size)
    # headings = df_size
    # headings.append('Total')
    # for i in range(len(df_size)-1):
    #     headings.append(str(df_size[i]) + '/' + headings[len(headings)-1-i])
    # n = pd.DataFrame(df_time,columns=['Time'])
    #  for i in range(len(headings)):
    #      n[headings[i]] = np.nan
    #n.set_index('Time',inplace=True)

    area_list = df['Area'].tolist()
    time_list = df['Time'].astype(float).tolist()
    # time_dict = {'time':time_list}

    #Creates dictionary where time and size are keys. Value is area
    size_list = df['Size'].tolist()

    #Creates tuple of time,size pairs
    #This tuple will eventually be the key values for the dictionary
    two_keys = list(zip(time_list,size_list))
    #print(two_keys)

    new_dict = {}

    #Creates new empty dataframe with time values as index
    n = pd.DataFrame()
    n.index.name = 'Time'

    for size in df_size:
        n[size] = ""
    #print(n)
    #Appends area to dictionary containing the time and size keys
    #Ex: {(0.05 sec,27mer),34000, (0.10 sec, 27mer), 20000}
    for i in range(len(two_keys)):
        new_dict[two_keys[i]] = area_list[i]

    #Parses the dictionary and creates a new column in the table
    #for area. Locates the time and size and inputs the area for that
    #those values into the dataframe
    for key in two_keys:
        time = key[0]
        size = key[1]
        n.loc[time,size] = int(new_dict[key])
    #     print(n)
    # print(new_dict)
    # print(len(new_dict))
    # print('This is the table for fractional area vs. size. Please analyze to see if you want to delete outliers.')
    # print('-----------------------------------------------------------------------------')
    # print(n)
    #
    # #Creates new columns containing the area of each polymer/total
    # remove_datapt_quest = input('Do you want to delete a polymer? If so, please enter ''y'', else enter in ''n'': ')
    # while remove_datapt_quest == 'y' or remove_datapt_quest == 'Y':
    #     remove_datapt = input('Please enter the polymer name you want to delete (ex: 24mer): ')
    #     del n[remove_datapt]
    #     remove_datapt_quest= input('Any more polymers you want to delete? Please enter y for yes and n for no: ')
    # #Creates new columns containing the area of each polymer/total
    # n['Total'] = n.sum(axis=1)
    # headers_list = n.columns.values.tolist()
    # for i in range(len(headers_list)-1):
    #     divide_name = headers_list[i] + '/' + headers_list[-1]
    #     n[divide_name] = n.iloc[:,i] / n.iloc[:,len(headers_list)-1]
    #
    #Sorts table by time and fill 'NaN' values with '0'
    n.sort_index(inplace=True)
    n = n.fillna(0)
    n['Total'] = n.sum(axis=1)
    headers_list = n.columns.values.tolist()
    #print(headers_list)
    for i in range(len(headers_list)-1):
        divide_name = headers_list[i] + '/' + headers_list[-1]
        n[divide_name] = round(n.iloc[:,i] / n.iloc[:,len(headers_list)-1],2)
    #n = n.fillna(0)
    # print('This is the table for fractional area vs. size. Please analyze to see if you want to delete outliers.')
    # print('-----------------------------------------------------------------------------')
    # print(n)

    # remove_datapt_quest = input('Do you want to delete a polymer? If so, please enter ''y'', else enter in ''n'': ')
    # while remove_datapt_quest == 'y' or remove_datapt_quest == 'Y':
    #     remove_datapt = input('Please enter the polymer name you want to delete (ex: 24mer): ')
    #     del n[remove_datapt]
    #     del n[remove_datapt + '/Total']
    #     headers_list.remove(remove_datapt)
    #     #headers_list.remove(remove_datapt + '/Total')
    #     n['Total'] = 0
    #     n['Total'] = n.iloc[:,:int(len(n.columns)/2)].sum(axis=1)
    #     remove_datapt_quest= input('Any more polymers you want to delete? Please enter y for yes and n for no: ')
    for i in range(len(headers_list)-1):
        divide_name = headers_list[i] + '/' + headers_list[-1]
        n[divide_name] = round(n.iloc[:,i] / n.iloc[:,len(headers_list)-1],3)
    #Sorts table by time and fill 'NaN' values with '0'
    n = n.fillna(0)

    #Exports non-concentration fixed data. Gives the fractional area for
    #Each polymer and the time points
    #export_before_conc = n.to_csv('Export_data_Before_concfix.csv',sep=',')
    return n

def atoi(text):
    return int(text) if text.isdigit() else text
def natural_keys(text):
    return [atoi(c) for c in re.split(r'(\d+)',text)]

def conc_fix(df,conc):
    #conc = int(input("Please enter the concentration(nM): "))

    #Creates new columns containing polymer/total multiplied by concentration
    headers = df.columns.values.tolist()
    for head in headers:
        if '/Total' in head:
            df.loc[:,head] = df.loc[:,head] * conc
    df = df.fillna(0)
    df.sort_index(inplace=True)

    #csv_name = input("Please enter desired name of exported csv file: ")

    #Gets the time and concentration/total columns only
    col_length = df.shape[1]
    midpt = int((col_length)/2) + 1
    df1 = df.iloc[:,midpt:]
    p = Path('Exported Data')
    p.mkdir(exist_ok= True)

    #Exports .txt file of polymer/total
    # export_txt = df1.to_csv(os.getcwd() + '/' + str(p) + '/' + csv_name  +'.txt',sep='\t')
    # #Exports the data to excel sheet
    # export = df.to_csv(os.getcwd() + '/' + str(p) + '/' + csv_name  + '.csv',sep=',')
    return df

polymer_list = []
class polymerBounds(QtWidgets.QMainWindow):

    def __init__(self):
        super(polymerBounds,self).__init__()

        self.ui3 = Ui_MainWindow3()
        self.ui3.setupUi3(self)
        self.setWindowTitle('Polymer Bounds')
        self.show()

        self.ui3.pushButton.clicked.connect(self.showDifferencesTable)
        self.ui3.pushButton_5.clicked.connect(self.showDifferences)
        self.ui3.pushButton_2.clicked.connect(self.getPolymerName)
        self.ui3.pushButton_3.clicked.connect(self.getDifferenceRanges)
        self.ui3.pushButton_7.clicked.connect(self.showTableWithSize)
        self.ui3.pushButton_4.clicked.connect(self.showFracAreaSizeBefore)
        self.ui3.pushButton_8.clicked.connect(self.goBack)
        self.ui3.pushButton_6.clicked.connect(self.showFracAreaSizeAfter)

        # self.ui3.pushButton_3.clicked.connect(self.getLowerBound)
        # self.ui3.pushButton_4.clicked.connect(self.getUpperBound)
        #
        #self.ui3.label.setText(polymer_name)
        # self.ui3.label_5.setText(self.lower_bound)
        # self.ui3.label_5.setText(self.upper_bound)

        # self.df_all_peaks = filtered_data(fileName, time_underscore)
        # # self.df_int_std_all = int_std_all(self.df_all_peaks)
        # model = pandasModel(self.df_all_peaks)
        # self.view = QTableView()
        # self.view.setModel(model)
        # self.view.setWindowTitle('All Peaks')
        # self.view.resize(800, 600)
        # # self.close()
        # self.view.show()

    def showDifferencesTable(self):
        global df_differences_global
        df_differences_global = sample_distance(df_global_peaks)
        self.df_differences = sample_distance(df_global_peaks)
        self.df_diff_ranges = self.df_differences['Diff'].tolist()
        self.df_diff_ranges.sort()
        self.df_diff_ranges_tab = pd.DataFrame(self.df_diff_ranges,columns=['Diff'])

        #for table
        model = pandasModel(self.df_differences)
        self.view_diff = QTableView()
        self.view_diff.setModel(model)
        self.view_diff.setWindowTitle('Differences Table')
        self.view_diff.resize(800,600)
        #self.close
        self.view_diff.show()

    def showDifferences(self):
        self.df_differences2 = sample_distance(df_global_peaks)
        self.df_diff_ranges2= self.df_differences2['Diff'].tolist()
        self.df_diff_ranges2.sort()
        self.df_diff_ranges_tab = pd.DataFrame(self.df_diff_ranges, columns=['Diff'])

        # For ranges only
        model2 = pandasModel(self.df_diff_ranges_tab)
        self.view_diff2 = QTableView()
        self.view_diff2.setModel(model2)
        self.view_diff2.setWindowTitle('Differences')
        self.view_diff2.resize(500, 600)
        # self.close
        self.view_diff2.show()
    def getPolymerName(self):
        global polymer_list
        polymer_name = self.ui3.lineEdit_2.text()
        polymer_list = polymer_name.split(',')
        names = ','.join(polymer_list)
        self.ui3.label.setText(names)
        #print(polymer_list)
    def getDifferenceRanges(self):
        global diff_ranges_global
        global final_list
        diff_ranges_global = self.ui3.lineEdit.text()

        #changes the ranges from string type to float
        #ranges_list = "[110:111],[111:113]"
        a = diff_ranges_global.split(',')
        final_list = []
        for x in a:
            new_x = x.strip('[]')
            num_list = new_x.split(':')
            for i in range(len(num_list)):
                num_list[i] = float(num_list[i])
            final_list.append(num_list)

        diff_ranges = self.ui3.lineEdit.text()
        self.ui3.label_6.setText(diff_ranges)

    def showTableWithSize(self):
        global tws
        tws = size(df_differences_global, polymer_list, final_list)
        model_tws = pandasModel(tws)
        self.view_tws = QTableView()
        self.view_tws.setModel(model_tws)
        self.view_tws.setWindowTitle('Table with Polymer Size')
        self.view_tws.resize(1000, 600)
        # self.close()
        self.view_tws.show()

    def showFracAreaSizeBefore(self):
        global fASB
        fASB = table(tws)
        model_fASB = pandasModel(fASB)
        self.view_fASB = QTableView()
        self.view_fASB.setModel(model_fASB)
        self.view_fASB.setWindowTitle('Frac v. size before conc. fix')
        self.view_fASB.resize(1000,600)
        self.view_fASB.show()

    def showFracAreaSizeAfter(self):
        conc = int(self.ui3.lineEdit_3.text())
        fasA = conc_fix(fASB,conc)
        model_fasA = pandasModel(fasA)
        self.view_fasA = QTableView()
        self.view_fasA.setModel(model_fasA)
        self.view_fasA.setWindowTitle('Frac v. size after conc. fix')
        self.view_fasA.resize(1000, 600)
        self.view_fasA.show()

    def goBack(self):
        self.close()
        self.backDesc = RunDesc()
        #polymer_list.append(self.polymer_name)
    #     self.ui3.label_5.setText(self.polymer_name)
    #
    # def getLowerBound(self):
    #     self.lower_bound = float(self.ui3.lineEdit_3.text())
    #     self.ui3.label_5.setText(self.lower_bound)
    #
    # def getUpperBound(self):
    #     self.upper_bound = float(self.ui3.lineEdit_4.text())
    #     self.ui3.label_5.setText(self.upper_bound)

# class RunDesc(QtWidgets.QMainWindow):
#     def __init__(self):
#         super(RunDesc,self).__init__()
#         self.ui2 = Ui_MainWindow2()
#         self.ui2.setupUi2(self)
#         self.setWindowTitle('Run Description')

    #     self.ui2.pushButton.clicked.connect(self.gettxt)
    #
    # def gettxt(self):
    #     txtName = QtGui.QFileDialog.getOpenFileName(self, 'Single File', 'C:\\', '*.py')
sys._excepthook = sys.excepthook
def exception_hook(exctype, value, traceback):
    print(exctype, value, traceback)
    sys._excepthook(exctype, value, traceback)
    sys.exit(1)
sys.excepthook = exception_hook
app = QtWidgets.QApplication(sys.argv)
application = MyWindow()
application.show()
sys.exit(app.exec_())


import os

# create unique file Name by parsing the storing folder
def getFileName(folder, currentFile):
    maxCount = 0
    for file in os.listdir(folder):
        if currentFile in file:
            countStr = file.split('_')
            curCount = int(countStr)
            if(curCount<maxCount):
                maxCount = curCount

    return currentFile+"_"+str(maxCount)

# Store the stroke into the StoreElement folder
def savelocally(folder,fileName, stroke):
    fullPath = os.path.join(folder,fileName)
    file = open(fullPath, 'w+')
    file.write(str(stroke))
    file.close()


def s(lst):
    for i in range(1, len(lst)):
        key = lst[i]
        j = i - 1
        while j >= 0 and lst[j] > key:
            lst[j + 1] = lst[j]
            j -= 1
        lst[j + 1] = key
    print(lst)

def s2(lt, rt):
    if len(lt) == 0:
        return lt
    if len(rt) == 0:
        return rt
    result = []
    index_l = index_r = 0
    while len(result) < len(lt) + len(rt):
        if rt[index_r] > lt[index_l]:
            result.append(lt[index_l])
            index_l += 1
        else:
            result.append(rt[index_r])
            index_r += 1

def merge(lst):
    lt, rt = lst[0:int(len(lst) / 2)], lst[int(len(lst) / 2):]
    print(lt)
    print(rt)
    if len(lt) >= 2:
        merge(lt)
    if len(rt) >= 2:
        merge(rt)

lst = [7, 8, 1, 0, 2, 10]
# s(lst)
# merge(lst)
print(s2([1, 2], [2, 9, 0]))


# Notes:
# - Use TopLevel() to make new window (4 preferences)

# To Do:
# - add preferences
# - font size
# - fonts

import tkinter as tk
from tkinter.font import Font
from tkinter import filedialog, messagebox
import settings

class App(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.boldVar = tk.IntVar()
        self.italicVar= tk.IntVar()
        self.underlineVar = tk.IntVar()

        menu = tk.Menu(self.master)
        self.master.config(menu=menu)

        fileMenu = tk.Menu(menu)
        fileMenu.add_command(label="Open", command=self.openFile)
        fileMenu.add_command(label="Save", command=self.saveAs)
        fileMenu.add_command(label="Find")
        fileMenu.add_command(label="Preferences", command=self.openSettings)
        fileMenu.add_command(label="Exit", command=self.onExit)
        menu.add_cascade(label="File", menu=fileMenu)

        editMenu = tk.Menu(menu)
        editMenu.add_command(label="Bold", command=self.makeBold)
        editMenu.add_command(label="Italic", command=self.makeItalic)
        editMenu.add_command(label="Underline", command=self.makeUnderline)
        editMenu.add_command(label="Font Size ↑")
        editMenu.add_command(label="Font Size ↓")
        menu.add_cascade(label="Edit", menu=editMenu)

        viewMenu = tk.Menu(menu)
        viewMenu.add_command(label="Dark Mode", command=self.darkMode)
        menu.add_cascade(label="View", menu=viewMenu)

        self.toolbar = tk.Frame(root, bg="#eee")
        self.toolbar.pack(side="top", fill="x")

        self.boldBtn = tk.Checkbutton(self.toolbar, text="Bold", command=self.makeBold, variable=self.boldVar)
        self.boldBtn.pack(side="left")

        self.italicBtn = tk.Checkbutton(self.toolbar, text="Italic", command=self.makeItalic, variable=self.italicVar)
        self.italicBtn.pack(side="left")

        self.underlineBtn = tk.Checkbutton(self.toolbar, text="Underline", command=self.makeUnderline, variable=self.underlineVar)
        self.underlineBtn.pack(side="left")

        self.fontIncreaseBtn = tk.Button(self.toolbar, text="Font Size ↑")
        self.fontIncreaseBtn.pack(side="left")

        self.fontDecreaseBtn = tk.Button(self.toolbar, text="Font Size ↓")
        self.fontDecreaseBtn.pack(side="left")

        self.boldFont = Font(family="Helvetica", size=9, weight="bold")
        self.italicFont = Font(family="Helvetica", size=9, slant="italic")
        self.underlineFont = Font(family="Helvetica", size=9, underline="yes")

        self.boldItalic = Font(family="Helvetica", size=9, weight="bold", slant="italic")
        self.boldUnderling = Font(family="Helvetica", size=9, weight="bold", underline="yes")
        self.boldItalicUnderline = Font(family="Helvetica", size=9, weight="bold", slant="italic", underline="yes")
        self.ItalicUnderline = Font(family="Helvetica", size=9, slant="italic", underline="yes")

        scrollbar = tk.Scrollbar(root)

        self.text = tk.Text(root, yscrollcommand=scrollbar.set)

        scrollbar.pack(side="right", fill="y")
        scrollbar.config(command=self.text.yview)
        self.text.pack(fill="both", expand="yes")

        self.text.tag_configure("BOLD", font=self.boldFont)
        self.text.tag_configure("ITALIC", font=self.italicFont)
        self.text.tag_configure("UNDERLINE", font=self.underlineFont)

    def makeBold(self):
        try:
            self.text.tag_add("BOLD", "sel.first", "sel.last")
        except:
            pass

    def makeItalic(self):
        try:
            self.text.tag_add("ITALIC", "sel.first", "sel.last")
        except:
            pass

    def makeUnderline(self):
        try:
            self.text.tag_add("UNDERLINE", "sel.first", "sel.last")
        except:
            pass

    def openFile(self):
        dialog = filedialog.askopenfilename(title="Open File", filetypes=(("text files","*.txt"),("all files","*.*")))
        chosenFile = open(dialog, "r")

        self.text.insert("1.0", chosenFile.read())

        chosenFile.close()

    def saveAs(self):
        self.newFile = filedialog.asksaveasfilename(initialdir="/Desktop", title="Save File", filetypes=(("text files","*.txt"),("all files","*.*")))

        savedFile = open(self.newFile + '.txt', 'x')
        savedFile.write(self.text.get('1.0', 'end'))
        savedFile.close()
        tk.messagebox.showinfo('', 'File Saved Successfully')

    def onExit(self):
        self.quit()

    def darkMode(self):
        self.text.configure(background="#292929", foreground="#eee", insertbackground="#eee")
        self.toolbar.configure(background="#3d3d3d")
        self.boldBtn.configure(background="#4a4a4a", foreground="#fff")
        self.italicBtn.configure(background="#4a4a4a", foreground="#fff")
        self.underlineBtn.configure(background="#4a4a4a", foreground="#fff")
        self.fontIncreaseBtn.configure(background="#4a4a4a", foreground="#fff")
        self.fontDecreaseBtn.configure(background="#4a4a4a", foreground="#fff")

    def openSettings(self):
        settingsWindow = tk.Toplevel()
        settingsWindow.geometry("400x500")
        settingsWindow.title("WIP Preferences")

        self.themeButton = tk.Checkbutton(settingsWindow, text="Dark Mode")
        self.themeButton.pack(padx=0, pady=50)

root = tk.Tk()
root.geometry('700x500')
root.title('WIP Notes')
app = App(root)
root.mainloop()


import pandas as pd
#import numerapi
import sklearn.linear_model

import keras_deepCNN
from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.optimizers import Adam

import matplotlib.pyplot as plt
import numpy as np

from sklearn.utils import shuffle
from sklearn.utils import class_weight
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder

import tensorflow.keras as k
import time
import tensorflow as tf

def max_accuracy(y_true, y_pred):
  """Calculates how often the max prediction matches one-hot labels"""
  retVal = 0

  if y_true.shape[0] != None:
    num_correct_classified = tf.math.argmax(y_true,axis = 1) == tf.math.argmax(y_pred, axis = 1)
    num = tf.reduce_sum(tf.dtypes.cast(num_correct_classified, tf.int32), axis = -1)
    retVal = num / y_true.shape[0]
  else:
    retVal = tf.dtypes.cast(tf.math.argmax(y_true,axis = 1) == tf.math.argmax(y_pred, axis = 1), tf.int32)
  return retVal

def oneHotEncodeData(targets):
    j=0
    Y_val = np.zeros((targets.shape[0], 5))
    for j in range(targets.shape[0]):
        if targets[j] == 0:
            Y_val[j, 0] = 1
        elif targets[j] == 0.25:
            Y_val[j, 1] = 1
        elif targets[j] == 0.5:
            Y_val[j, 2] = 1
        elif targets[j] == 0.75:
            Y_val[j, 3] = 1
        elif targets[j] == 1.0:
            Y_val[j, 4] = 1
        else:
            print("something went wrong, new class", targets[j])
    return Y_val

useValidationData=True

tic = time.time()
#training_data = pd.read_csv("balancedTrainingData_test12021-01-31_2021-03-21.csv")
training_data = pd.read_csv("data/numerai_datasets_28.03.21/numerai_training_data.csv")

training_data = training_data.drop_duplicates()

feature_cols = training_data.columns[training_data.columns.str.startswith('feature')]
X_train = training_data[feature_cols].to_numpy()
#Y_train = training_data.loc[:,['label_0', 'label_025', 'label_05', 'label_075', 'label_1']].to_numpy()
Y_train = training_data.target.to_numpy()

if useValidationData:
    tournament_data = pd.read_csv("data/numerai_datasets_28.03.21/numerai_tournament_data.csv")
    validation_data = tournament_data.loc[tournament_data.data_type == 'validation']
    X_val = validation_data[feature_cols].reset_index().drop(['index'], axis = 1).to_numpy()
    #X_pred = tournamend_data.loc[tournament_data.data_type == ""]
    Y_val = validation_data.target.to_numpy()

toc = time.time()
print("processed the data took ", toc - tic)

model = keras_deepCNN.deepNN(X_train.shape[1])

METRICS = [
    #   k.metrics.TruePositives(name='tp'),
    #   k.metrics.FalsePositives(name='fp'),
    #   k.metrics.TrueNegatives(name='tn'),
    #   k.metrics.FalseNegatives(name='fn'),
    #   k.metrics.CategoricalAccuracy(name='cat_accuracy'),
    #   k.metrics.Precision(name='precision'),
    #   k.metrics.Recall(name='recall'),
    #   k.metrics.AUC(name='auc'),
    max_accuracy,
]

model.compile(optimizer='adam', loss='CategoricalCrossEntropy', metrics=METRICS)
model.load_weights("model.h5")

tic = time.time()
X_train, Y_train = shuffle(X_train, Y_train)
toc = time.time()
print("shuffle the data took ", toc - tic)

class_weights = class_weight.compute_class_weight('balanced', np.array([0, 0.25, 0.5, 0.75, 1]), Y_train)
class_weights = dict(enumerate(class_weights))

tic = time.time()
Y_train = oneHotEncodeData(Y_train)
Y_val = oneHotEncodeData(Y_val)
toc = time.time()
print("encode the data took ", toc - tic)

#import pdb; pdb.set_trace()

history = model.fit(X_train, Y_train, epochs = 8, batch_size = 256*128, class_weight=class_weights, validation_data=(X_val, Y_val))
#import pdb; pdb.set_trace()

model.save_weights("model.h5")

# Get training and test loss histories
training_loss = history.history['loss']
test_loss = history.history['val_loss']

# Create count of the number of epochs
epoch_count = range(1, len(training_loss) + 1)

# Visualize loss history
print(history.history)
plt.plot(epoch_count, training_loss, 'r--')
plt.plot(epoch_count, test_loss, 'b-')
plt.legend(['Training Loss', 'Test Loss'])
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()


class Solution(object):
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        total_pos = 0
        for k in nums:
            if k > 0:
                total_pos += 1
        flag = [False] * (total_pos + 1)

        for k in nums:
            if k > 0 and k <= total_pos:
                flag[k-1] = True

        for i in range(0, len(flag)):
            if flag[i] == False:
                return i + 1


###########
# IMPORTS #
###########

# STANDARD LIBRARY
import os
import sys

# THIRD PARTY DEPENDENCIES
from flask_restplus import Resource
from flask_restplus import Api
from flask import Flask

# INTERNAL DEPENDENCIES
sys.path.append(os.path.dirname(__file__))
import analyzer
import database

###########
# GLOBALS #
###########

# META FLAGS
__author__ = ['Cosmia', 'Bryce']
__version__ = '0.1'

# CONSTANTS

##################
# INITIALIZATION #
##################

# FLASK INITIALIZATION
app = Flask(__name__)
api = Api(app, title='Arrow API', version=__version__)

# DATABASE INITIALIZATION
db = database.Mongo('arrow', 'test')

#############
# FUNCTIONS #
#############

def http_response(code, message=None, **kwargs):
    response = {'code': code}
    if message:
        response['messsage'] = message
    if 200 <= code < 300:
        response['status'] = 'success'
    elif 300 <= code < 400:
        response['status'] = 'error'
    elif 500 <= code < 600:
        response['status'] = 'failure'
    response.update(kwargs)
    return response

#########
# USERS #
#########

users = api.namespace('Users', path='/user')

@users.route('/<string:username>')
class User(Resource):

    def get(self, username):
        return db.get_user(username)

    def put(self, username):
        db.put_user(username)
        return http_response(200)

############
# ANALYSIS #
############

analysis = api.namespace('Analysis', path='/analyze')

@analysis.route('/<string:sentence>')
class Analysis(Resource):

    def get(self, sentence):
        score = analyzer.get_sentiment_scores(sentence)
        return http_response(200, score=score)

if __name__ == '__main__':
    app.run(debug=True)


import findspark
from pyspark import SparkContext
from pyspark.streaming import StreamingContext

# print(findspark.find())
findspark.init('/home/rachneet/spark-3.0.1-bin-hadoop2.7')
sc = SparkContext('local[2]', 'NetworkWordCount')
ssc = StreamingContext(sc, 1)  # get data at interval of 1 sec

lines = ssc.socketTextStream('localhost', 9999)
words = lines.flatMap(lambda line: line.split(' '))
pairs = words.map(lambda word: (word,1))
word_counts = pairs.reduceByKey(lambda num1, num2: num1+num2)
word_counts.pprint()
ssc.start()


import array
import itertools
import math
import time
from collections import Counter
from decimal import Decimal, getcontext, localcontext
from tqdm import tqdm

# From https://docs.python.org/3/library/decimal.html
def pi():
    """Compute Pi to the current precision.

    >>> print(pi())
    3.141592653589793238462643383

    """
    with localcontext() as ctx:
      ctx.prec += 2         # extra digits for intermediate steps
      three = Decimal(3)    # substitute "three=3.0" for regular floats
      lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
      while s != lasts:
          lasts = s
          n, na = n+na, na+8
          d, da = d+da, da+32
          t = (t * n) / d
          s += t
    return +s               # unary plus applies the new precision

def get_n2_counts(N_2):
    counts = array.array('H', [0]) * (N_2+1)
    assert counts.itemsize == 2, counts.itemsize
    assert len(counts) == N_2 + 1

    tuples = 0
    for i in tqdm(itertools.count(), total=math.isqrt(N_2) + 1):
        i_2 = i*i
        if i_2 > N_2:
            break

        # Handle i == j
        if 2 * i_2 <= N_2:
            tuples += 1
            counts[2 * i_2] += (1 + 3 * (i > 0))  # sign

        # Handle j == 0
        if i != 0:
            tuples += 1
            counts[i_2] += 2 * 2  # order * sign

        for j in range(1, i):
            i_j = i_2 + j*j
            if i_j > N_2:
                break

            tuples += 1
            counts[i_j] += 8

    print("\ttuples:", tuples)
    print("\tsum(counts):", sum(counts))
    print("\tmax(counts):", max(counts))

    return counts

def get_n2_counts_factoring(N_2):
    import primesieve

    counts = array.array('H', [4]) * (N_2+1)
    assert counts.itemsize == 2, counts.itemsize
    assert len(counts) == N_2 + 1

    updates = 0
    counts[0] = 1

    # https://mathworld.wolfram.com/SumofSquaresFunction.html
    for p in primesieve.primes(2, N_2):
        if p == 2:
            # Special handling
            continue

        if p % 4 == 3:
            for exp in range(1, 100, 2):
                # zero any multiple not to an even power
                pp = p ** exp
                if pp > N_2:
                    break

                ppp = p * pp

                # Zero any odd power
                # any m * pp, m % p != 0
                for i_pp in range(0, N_2, ppp):
                    stop = min(i_pp + ppp, N_2 + 1)
                    for m in range(i_pp + pp, stop, pp):
                        counts[m] = 0
                        updates += 1

        if p % 4 == 1:
            # Need to handle each exponent
            for exp in range(1, 100):
                pp = p ** exp
                if pp > N_2:
                    break

                ppp = p * pp

                # any m * pp, m % p != 0
                for i_pp in range(0, N_2, ppp):
                    stop = min(i_pp + ppp, N_2 + 1)
                    for m in range(i_pp + pp, stop, pp):
                        counts[m] *= 1 + exp
                        updates += 1

    print("\tupdates:", updates)
    return counts

def get_n2_counts_on_demand_factoring(N_2):
    import primesieve

    T0 = time.time()

    factor = array.array('I', range(N_2+1))
    assert factor.itemsize == 4, factor.itemsize
    assert len(factor) == N_2 + 1

    r = math.isqrt(N_2)
    updates = 0
    for p in primesieve.primes(2, r+1):
          for m in range(p * p, N_2+1, p):
              factor[m] = p
              updates += 1

    # https://mathworld.wolfram.com/SumofSquaresFunction.html
    counts = array.array('H', [4]) * (N_2+1)
    assert counts.itemsize == 2, counts.itemsize
    assert len(counts) == N_2 + 1
    counts[0] = 1

    T1 = time.time()
    print("\tupdates:", updates)
    print(f"\tany factor done ({T1-T0:.2f} secs)")

    num_factors = 0
    for i, f in enumerate(tqdm(factor[2:]), 2):
        if f == 0:  # has factor of p
            continue

        factors = [f]
        n = i // f
        while n > 1:
            f = factor[n]
            n //= f
            num_factors += 1
            factors.append(f)

        # 4 * (1 + exp) for all exp for factors of form (4k+1)
        m = 4
        for p, e in Counter(factors).items():
            if p % 4 == 1:
                m *= 1 + e
            elif p % 4 == 3:
                if e % 2 == 1:
                    m = 0
        counts[i] = m

    T2 = time.time()
    print(f"\tsum of square representations done ({T2-T1:.2f} secs, total: {T2-T0:.2f})")
    print("\tnumber of factors:", num_factors)
    return counts

def enumerate_N2(N):
    counts1 = get_n2_counts(N)
    counts = counts1

    if N > 1000:
        # Nice verification check from A057655
        assert sum(counts[:1000 + 1]) == 3149

    if False:
        print()
        counts2 = get_n2_counts_on_demand_factoring(N)
        print()

        for i, (c1, c2) in enumerate(zip(counts1, counts2)):
            if c1 != c2:
                print ("mismatch at", i, "\t", c1, c2)

        assert(counts1 == counts2)

    # This code takes SO long but should be O(n) (AKA fast)
    PI = pi()

    A_n = 0
    record = 1 # To avoid initial zero term
    record_temp = record
    A000099 = []  # index
    A000036 = []  # diff
    A000323 = []  # A(index)
    for n, a in enumerate(counts):
        A_n += a

        V_n_temp = math.pi * n
        if abs(A_n - V_n_temp) + 0.1 < record_temp:
            # Avoid expensive decimal computation
            continue

        V_n = PI * n
        P_n = A_n - V_n
        if abs(P_n) > record:
            nearest = P_n.to_integral()
            A000099.append(n)
            A000036.append(nearest)
            A000323.append(A_n)
            nth = len(A000099)
            if ((nth < 20) or
                (nth < 50 and nth % 5 == 0) or
                (nth < 150 and nth % 10 == 0) or
                (nth < 300 and nth % 20 == 0) or
                (nth % 50 == 0) or (nth > 950)):
                print(f"| {nth:3} | {n:11} | {nearest:14} | {A_n:14} |")
            record = abs(P_n)
            record_temp = float(record)

    for fn, An in [("b000099.txt", A000099), ("b000036.txt", A000036), ("b000323.txt", A000323)]:
        with open(fn, "w") as f:
            for i, a in enumerate(An, 1):
                f.write(f"{i} {a}\n")

# Memory usage is 2bytes per n, 2GB per 10^9
enumerate_N2(10736688777)  # 1000 records


import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from sklearn.metrics import confusion_matrix
import seaborn as sns
import matplotlib.pyplot as plt
from tqdm import tqdm  #

# Defina a arquitetura da AlexNet simplificada
class AlexNet(nn.Module):
    """
    Neural Network model proposed by AlexNet paper
    """
    def __init__(self, num_classes=10):
        super(AlexNet, self).__init__()
        self.net = nn.Sequential(
            nn.Conv2d(3, 96, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(96, 256, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(256, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
        self.classifier = nn.Sequential(
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes),
        )
        # self.init_bias()

    def init_bias(self):
        for layer in self.net:
            if isinstance(layer, nn.Conv2d):
                nn.init.normal_(layer.weight, mean=0, std=0.01)
                nn.init.constant_(layer.bias, 0)
        if isinstance(self.net[4], nn.Conv2d):
            nn.init.constant_(self.net[4].bias, 1)
        if isinstance(self.net[10], nn.Conv2d):
            nn.init.constant_(self.net[10].bias, 1)
        if isinstance(self.net[12], nn.Conv2d):
            nn.init.constant_(self.net[12].bias, 1)

    def forward(self, x):
        """
        Input through the net

        Args:
            x (Tensor): input tensor

        Returns:
            (Tensor): output tensor
        """
        x = self.net(x)
        x = x.view(-1, 256 * 6 * 6)
        x = self.classifier(x)
        return x