import gamelib

def interfaz_pokedex_completo(titulo):
    """ Muestra la interfaz de la pokedex generica y recibe por parametro el
    titulo que se le quiera poner a la sección. """
    return gamelib.draw_rectangle(50, 50, 900, 650, fill='red'), \
        gamelib.draw_oval(80, 70, 130, 120, outline='black', fill='#15E8E8'), \
        gamelib.draw_oval(150, 70, 170, 90, outline='black', fill='red'), \
        gamelib.draw_oval(180, 70, 200, 90, outline='black', fill='green'), \
        gamelib.draw_oval(210, 70, 230, 90, outline='black', fill='yellow'), \
        gamelib.draw_rectangle(80, 150, 870, 550, fill='grey'), \
        gamelib.draw_rectangle(90, 160, 860, 540, fill='white'), \
        gamelib.draw_oval(80, 560, 120, 600, fill='blue'), \
        gamelib.draw_oval(150, 560, 180, 590, fill='green', outline='green'), \
        gamelib.draw_rectangle(165, 560, 235, 590, fill='green', outline='green'), \
        gamelib.draw_oval(220, 560, 250, 590, fill='green', outline='green'), \
        gamelib.draw_oval(290, 560, 320, 590, fill='yellow', outline='yellow'), \
        gamelib.draw_rectangle(305, 560, 375, 590, fill='yellow', outline='yellow'), \
        gamelib.draw_oval(360, 560, 390, 590, fill='yellow', outline='yellow'), \
        gamelib.draw_text(titulo, 400, 110, fill='white', anchor='nw', bold=True, size=20), \
        gamelib.draw_text(
            "Presiona la h para ver los comandos disponibles", 690, 620, fill="white", size=14)


import pygame as pg
import random as rd
import datetime as dt

def plaay():
    pg.init()

    SCREEN_WIDTH = 1000
    SCREEN_HEIGHT  = 1000
    SCREEN = pg.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pg.display.set_caption("game")
    background = pg.image.load("image.png")
    clock = pg.time.Clock()

    class obj:
        def __init__(self):
            self.x = 0
            self.y = 0
            self.move = 0
        def put_img(self,address):
            self.img = pg.image.load(address)
            self.sx,self.sy = self.img.get_size()
        def change_size(self,sx,sy):
            self.img = pg.transform.scale(self.img,(sx,sy))
            self.sx,self.sy = self.img.get_size()
        def show(self):
            SCREEN.blit(self.img,(self.x,self.y))

    def crash(a,b):
        if (a.x - b.sx <= b.x) and (b.x <= a.x + a.sx):
            if (a.y - b.sy <= b.y) and (b.y - a.y + a.sy):
                return True
            else:
                return False
        else:
            return False

    durability = 100

    monster_spawn = 199

    over = False

    t1 = obj()
    t1.put_img("IMG_0381.png")
    t1.change_size(100,150)
    t1.x = SCREEN_WIDTH / 8 - t1.sx / 2
    t1.y =  (SCREEN_HEIGHT / 2 + 160) - t1.sy / 2

    t2 = obj()
    t2.put_img("IMG_0382.png")
    t2.change_size(100,150)
    t2.x = (SCREEN_WIDTH / 8 + 150) - t2.sx / 2
    t2.y =  (SCREEN_HEIGHT / 2 + 160) - t2.sy / 2

    t3 = obj()
    t3.put_img("IMG_0385.png")
    t3.change_size(100,150)
    t3.x = (SCREEN_WIDTH / 8 + 350) - t3.sx / 2
    t3.y =  (SCREEN_HEIGHT / 2 + 160) - t3.sy / 2

    t4 = obj()
    t4.put_img("IMG_0387.png")
    t4.change_size(100,150)
    t4.x = (SCREEN_WIDTH / 8 + 500) - t4.sx / 2
    t4.y =  (SCREEN_HEIGHT / 2 + 160) - t4.sy / 2

    m1_list = []
    m2_list = []
    m3_list = []
    m4_list = []

    r1_list = []
    r2_list = []
    r3_list = []
    r4_list = []

    k1 = 0
    k2 = 0
    k3 = 0
    k4 = 0

    at1 = 40
    at2 = 40
    at3 = 40
    at4 = 40

    coin = 0

    start_time = dt.datetime.now()

    play = True
    while play:
        clock.tick(60)
        for event in pg.event.get():
            if event.type == pg.QUIT:
                play = False

            if event.type == pg.KEYDOWN:
                if event.key == pg.K_LEFT:
                    if coin >= 100:
                        coin -= 100
                        r1 = rd.randrange(1,101)
                        if r1 <= 50:
                            at1 = 40
                        elif r1 > 50 and r1 <= 75:
                            at1 = 30
                        elif r1 >75 and r1 <= 88:
                            at1 = 20
                        elif r1 > 88 and r1 <= 96:
                            at1 = 10
                        elif r1 > 96 and r1 <= 100:
                            at1 = 5

                if event.key == pg.K_UP:
                    if coin >= 100:
                        coin -= 100
                        r1 = rd.randrange(1,101)
                        if r1 <= 50:
                            at2 = 40
                        elif r1 > 50 and r1 <= 75:
                            at2 = 30
                        elif r1 >75 and r1 <= 88:
                            at2 = 20
                        elif r1 > 88 and r1 <= 96:
                            at2 = 10
                        elif r1 > 96 and r1 <= 100:
                            at2 = 5

                if event.key == pg.K_DOWN:
                    if coin >= 100:
                        coin -= 100
                        r1 = rd.randrange(1,101)
                        if r1 <= 50:
                            at3 = 40
                        elif r1 > 50 and r1 <= 75:
                            at3 = 30
                        elif r1 >75 and r1 <= 88:
                            at3 = 20
                        elif r1 > 88 and r1 <= 96:
                            at3 = 10
                        elif r1 > 96 and r1 <= 100:
                            at3 = 5

                if event.key == pg.K_RIGHT:
                    if coin >= 100:
                        coin -= 100
                        r1 = rd.randrange(1,101)
                        if r1 <= 50:
                            at4 = 40
                        elif r1 > 50 and r1 <= 75:
                            at4 = 30
                        elif r1 >75 and r1 <= 88:
                            at4 = 20
                        elif r1 > 88 and r1 <= 96:
                            at4 = 10
                        elif r1 > 96 and r1 <= 100:
                            at4 = 5

        coin += 1

        now_time = dt.datetime.now()
        delta_time = round((now_time - start_time).total_seconds())

        if rd.randint(1,201) > monster_spawn:
            m1 = obj()
            m1.put_img("IMG_0337.png")
            m1.change_size(50,50)
            m1.x = SCREEN_WIDTH / 8 - m1.sx / 2
            m1.y = 0
            m1.move = 5
            m1_list.append(m1)

        d_list = []

        for i in range(len(m1_list)):
            mo1 = m1_list[i]
            mo1.y += mo1.move
            if mo1.y >= 560:
                d_list.append(i)

        d_list.reverse()

        for d in d_list:
            del m1_list[d]
            durability -= 1

        if rd.randint(1,201) > monster_spawn:
            m2 = obj()
            m2.put_img("IMG_0337.png")
            m2.change_size(50,50)
            m2.x = (SCREEN_WIDTH / 8 + 150) - m2.sx / 2
            m2.y = 0
            m2.move = 5
            m2_list.append(m2)

        d_list = []

        for i in range(len(m2_list)):
            mo2 = m2_list[i]
            mo2.y += mo2.move
            if mo2.y >= 560:
                d_list.append(i)

        d_list.reverse()

        for d in d_list:
            del m2_list[d]
            durability -= 1

        if rd.randint(1,201) > monster_spawn:
            m3 = obj()
            m3.put_img("IMG_0341.png")
            m3.change_size(50,50)
            m3.x = (SCREEN_WIDTH / 8 + 350) - m3.sx / 2
            m3.y = 0
            m3.move = 5
            m3_list.append(m3)

        d_list = []

        for i in range(len(m3_list)):
            mo3 = m3_list[i]
            mo3.y += mo3.move
            if mo3.y >= 560:
                d_list.append(i)

        d_list.reverse()

        for d in d_list:
            del m3_list[d]
            durability -= 1

        if rd.randint(1,201) > monster_spawn:
            m4 = obj()
            m4.put_img("IMG_0364.png")
            m4.change_size(50,50)
            m4.x = (SCREEN_WIDTH / 8 + 500) - m4.sx / 2
            m4.y = 0
            m4.move = 5
            m4_list.append(m4)

        d_list = []

        for i in range(len(m4_list)):
            mo4 = m4_list[i]
            mo4.y += mo4.move
            if mo4.y >= 560:
                d_list.append(i)

        d_list.reverse()

        for d in d_list:
            del m4_list[d]
            durability -= 1

        if k1 > at1:
            k1 = 0
            r1 = obj()
            r1.put_img("missle.png")
            r1.change_size(50,50)
            r1.x = (SCREEN_WIDTH / 8 - r1.sx / 2)
            r1.y = (SCREEN_HEIGHT / 2 + 80) - r1.sy
            r1.move = 10
            r1_list.append(r1)

        d_list = []
        k1 += 1
        k2 += 1
        k3 += 1
        k4 += 1
        for i in range(len(r1_list)):
            ro1 = r1_list[i]
            ro1.y -= ro1.move
            if ro1.y <= 0:
                d_list.append(i)

        d_list.reverse()

        for d in d_list:
            del r1_list[d]

        if k2 > at2:
            k2 = 0
            r2 = obj()
            r2.put_img("missle.png")
            r2.change_size(50,50)
            r2.x = ((SCREEN_WIDTH / 8 + 150) - r2.sx / 2)
            r2.y = (SCREEN_HEIGHT / 2 + 80) - r2.sy
            r2.move = 10
            r2_list.append(r2)

        d_list = []

        for i in range(len(r2_list)):
            ro2 = r2_list[i]
            ro2.y -= ro2.move
            if ro2.y <= 0:
                d_list.append(i)

        d_list.reverse()

        for d in d_list:
            del r2_list[d]

        if k3 > at3:
            k3 = 0
            r3 = obj()
            r3.put_img("missle.png")
            r3.change_size(50,50)
            r3.x = ((SCREEN_WIDTH / 8 + 350) - r3.sx / 2)
            r3.y = (SCREEN_HEIGHT / 2 + 80) - r3.sy
            r3.move = 10
            r3_list.append(r3)

        d_list = []

        for i in range(len(r3_list)):
            ro3 = r3_list[i]
            ro3.y -= ro3.move
            if ro3.y <= 0:
                d_list.append(i)

        d_list.reverse()

        for d in d_list:
            del r3_list[d]

        if k4 > at4:
            k4 = 0
            r4 = obj()
            r4.put_img("missle.png")
            r4.change_size(50,50)
            r4.x = ((SCREEN_WIDTH / 8 + 500) - r4.sx / 2)
            r4.y = (SCREEN_HEIGHT / 2 + 80) - r4.sy
            r4.move = 10
            r4_list.append(r4)

        d_list = []

        for i in range(len(r4_list)):
            ro4 = r4_list[i]
            ro4.y -= ro4.move
            if ro4.y <= 0:
                d_list.append(i)

        d_list.reverse()

        for d in d_list:
            del r4_list[d]

        dm_list = []
        dr_list = []

        for i in range(len(r1_list)):
            for j in range(len(m1_list)):
                mo1 = m1_list[j]
                ro1 = r1_list[i]
                if crash(ro1,mo1) == True:
                    dm_list.append(i)
                    dr_list.append(j)

        dm_list = list(set(dm_list))
        dr_list = list(set(dr_list))

        dm_list.reverse()
        dr_list.reverse()

        try:
            for dm in dm_list:
                del m1_list[dm]
            for dr in dr_list:
                del r1_list[dr]
        except:
            pass

        dm_list = []
        dr_list = []

        for i in range(len(r2_list)):
            for j in range(len(m2_list)):
                mo2 = m2_list[j]
                ro2 = r2_list[i]
                if crash(ro2,mo2) == True:
                    dm_list.append(i)
                    dr_list.append(j)

        dm_list = list(set(dm_list))
        dr_list = list(set(dr_list))

        dm_list.reverse()
        dr_list.reverse()

        try:
            for dm in dm_list:
                del m2_list[dm]
            for dr in dr_list:
                del r2_list[dr]
        except:
            pass

        dm_list = []
        dr_list = []

        for i in range(len(r3_list)):
            for j in range(len(m3_list)):
                mo3 = m3_list[j]
                ro3 = r3_list[i]
                if crash(ro3,mo3) == True:
                    dm_list.append(i)
                    dr_list.append(j)

        dm_list = list(set(dm_list))
        dr_list = list(set(dr_list))

        dm_list.reverse()
        dr_list.reverse()

        try:
            for dm in dm_list:
                del m3_list[dm]
            for dr in dr_list:
                del r3_list[dr]
        except:
            pass

        dm_list = []
        dr_list = []

        for i in range(len(r4_list)):
            for j in range(len(m4_list)):
                mo4 = m4_list[j]
                ro4 = r4_list[i]
                if crash(ro4,mo4) == True:
                    dm_list.append(i)
                    dr_list.append(j)

        dm_list = list(set(dm_list))
        dr_list = list(set(dr_list))

        dm_list.reverse()
        dr_list.reverse()

        try:
            for dm in dm_list:
                del m4_list[dm]
            for dr in dr_list:
                del r4_list[dr]
        except:
            pass

        SCREEN.blit(background,(0,0))
        for mo1 in m1_list:
            mo1.show()
        for mo2 in m2_list:
            mo2.show()
        for mo3 in m3_list:
            mo3.show()
        for mo4 in m4_list:
            mo4.show()
        t1.show()
        t2.show()
        t3.show()
        t4.show()
        for ro1 in r1_list:
            ro1.show()
        for ro2 in r2_list:
            ro2.show()
        for ro3 in r3_list:
            ro3.show()
        for ro4 in r4_list:
            ro4.show()

        font = pg.font.Font(None,30)
        text_durability = font.render("durability : {} / 100".format(durability),True, (0,0,0))
        SCREEN.blit(text_durability,(760,100))

        text_time = font.render("time : {} ".format(delta_time),True, (0,0,0))
        SCREEN.blit(text_time,(760,70))

        text_coin = font.render("coin : {} ".format(coin),True, (0,0,0))
        SCREEN.blit(text_coin,(760,130))

        monster_spawn -= 0.002

        if durability <= 0:
            play = False
            over = True

        pg.display.flip()

    while over == True:
        clock.tick(60)
        for event in pg.event.get():
            if event.type == pg.QUIT:
                over = False
        font = pg.font.Font(None,100)
        text = font.render("Game over",True,(0,0,0))
        SCREEN.blit(text,(350,350))

        font = pg.font.Font(None,50)
        teext = font.render("time : {}".format(delta_time),True,(0,0,0))
        SCREEN.blit(teext,(350,450))
        pg.display.flip()
    pg.quit()

if __name__ == '__main__':
    plaay()


class Graph:
	def __init__(self,vertices):
		self.V     = vertices
		self.graph = []

	def addEdge(self,s,d,w):
		self.graph.append([s,d,w])

	def find(self,parent,node):
		if (parent[node] == node):
			print("parent",parent)
			return node
		return self.find(parent,parent[node])

	def union(self, parent, rank, x, y):
		xroot = self.find(parent, x)
		yroot = self.find(parent, y)

		print("XRoot::",x," " , "YRoot ",yroot)

		print("rankX::",rank[xroot]," ","ranky",rank[yroot])

		if rank[xroot] < rank[yroot]:
			parent[xroot] = yroot
		elif rank[xroot] > rank[yroot]:
			parent[yroot] = xroot

		else:
			parent[yroot] = xroot
			rank[xroot] += 1

	def KruskalMST(self):
		result       = []
		index_edges  = 0
		index_result = 0

		self.graph = sorted(self.graph,key=lambda item:item[2])

		parent = []
		rank   = []

		for node in range(self.V):
			parent.append(node)
			rank.append(0)

		while index_edges < self.V :
			s,d,w = self.graph[index_edges]

			index_edges += 1

			print("S::",s," ","D::",d)

			x = self.find(parent,s)
			y = self.find(parent,d)

			print("X::",x)
			print("Y::",y)

			if (x != y):
				index_result += 1
				result.append([s,d,w])
				print("Rank :: ",rank)
				self.union(parent,rank,x,y)

		minCost = 0
		print("edges in MST")

		for s,d,w in result:
			minCost += w

			print("%d --> %d == %d "%(s,d,w))

		print("Min Cost is :: ",minCost)

'''0 ->Alam
   1-> amina
   2-> hazrat
   3->gomti
'''
g = Graph(4)
g.addEdge(0, 1, 21)
g.addEdge(0, 2, 27)
g.addEdge(0, 3, 35)
g.addEdge(1, 3, 33)
g.addEdge(2, 3, 22)

# Function call
g.KruskalMST()


from __future__ import print_function

import argparse
import pprint
import sys
sys.path.append("../")
import grpc
from protobuf import dlserver_pb2
from protobuf import dlserver_pb2_grpc
from protobuf import pb2_Feature, pb2_Features, pb2_Int64List, pb2_Example, pb2_BytesList
from conf import config

import cv2
import numpy as np

def create_examples(images):

    def getImageByteString(imgInput):
        try:
            img_encode = cv2.imencode('.jpg', imgInput)[1]
            data_encode = np.array(img_encode)
            imageByteString = data_encode.tostring()
            return imageByteString
        except Exception:
            return None

    def getExample(imageName):
        try:
            # image_reader = ImageReader()
            # with tf.Session('') as sess:
            image = cv2.imread(imageName)  # 读入图片W
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # 将图片转换为RGB格式，因为cv2读入为BGRW
            height = 299
            width = 299
            image = cv2.resize(image, (height, width))
            imageByteString = getImageByteString(image)

            #多标签W
            # imageName = getImageName(imageName)  # 获取图像对应的名字，用于预测W
            example = pb2_Example(features=pb2_Features(feature={
                'image/encoded': pb2_Feature(bytes_list=pb2_BytesList(value=[imageByteString])),
                'image/format': pb2_Feature(bytes_list=pb2_BytesList(value=[b'jpg'])),
                'image/class/labelPP': pb2_Feature(int64_list=pb2_Int64List(value=[0])),
                'image/class/labelFood': pb2_Feature(int64_list=pb2_Int64List(value=[0])),
                'image/class/labelScene': pb2_Feature(int64_list=pb2_Int64List(value=[0]))
            }))

            return example
        except Exception as e:
            pass
        return None

    examples = list(filter(lambda x: x != None, map(getExample, images))) #将lines中的每一行转为TFRecordW

    print("request examples len: {}".format(len(examples)))
    example_list = dlserver_pb2.ExampleList(examples=examples) #生成一个list请求W

    return example_list

def getScores(stub, dl_request):
    feature = stub.GetOutputs(dl_request)
    return feature

# host_port = '10.126.106.160:50051' if config.debug_mode else '10.126.106.210:50051'
host_port = '10.126.106.210:50051'
channel = grpc.insecure_channel(host_port)
stub = dlserver_pb2_grpc.ExamplesDLServerStub(channel)

def requestDLServerLabels(images):
    print("-------------- GetScores --------------")
    example_list = create_examples(images) #自定义解码W
    dl_request = dlserver_pb2.DLRequest(task_id="803", example_list=example_list) #服务idW
    return getScores(stub, dl_request)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.register("type", "bool", lambda v: v.lower() == "true")
    parser.add_argument(
        "--debug_mode",
        type="bool",
        default=True,
        help="use debug mode")
    parser.add_argument(
        "--use_hdfs",
        type=bool,
        default=False,
        help="use hdfs file")
    parser.add_argument(
        "--partition_num",
        type=int,
        default=64,
        help="the number of the repartition num")

    FLAGS, unparsed = parser.parse_known_args()
    pp = pprint.PrettyPrinter().pprint
    pp(FLAGS)
    pp(unparsed)

    images = ['./tmp/image/WechatIMG{}.jpeg'.format(i) for i in range(17, 21)]

    for i in range(1):
        result = requestDLServerLabels(images)
        print(result)


import argparse

def bool_string(input_string):
    if input_string not in {"True","False"}:
        raise ValueError("Please Enter a valid Ture/False choice")
    else:
        return (input_string == "True")

def parse_args():
    """ Parse command line arguments.
    """
    parser = argparse.ArgumentParser(description="Deep SORT with detection")
    parser.add_argument(
        "--sequence_dir", help="Path to sequence directory, either image file or whole video",
        default=r"/media/msis_dasol/1TB/dataset/test/MOT16-06", required=True)
    parser.add_argument(
        "--running_name", help="Name of this running session to custom detections.",
        default="default", required=False)
    parser.add_argument(
        "--running_cfg", help="Running configuration: from_detect, from_encoded and track",
        default="track")
    parser.add_argument(
        "--gpu", help="GPU id to running the detection and encoder",
        default=0, type=int
    )
    parser.add_argument(
        "--sequence", help="specify the sequence or the video file name to run or leave empty to run all",
        default=""
    )
    parser.add_argument(
        "--bind_port", help="address to bind Embedding server",
        default=0, type=int
    )
    parser.add_argument(
        "--server_addr", help="address to connect to Embedding server",
        default=""
    )

    parser.add_argument(
        "--mc_mode", help="multiple camera tracker mode: 0: async, 1: sync master, 2: sync slave",
        default=2, type=int
    )

    parser.add_argument(
        "--min_confidence", help="Detection confidence threshold. Disregard "
        "all detections that have a confidence lower than this value.",
        default=0.3, type=float)
    parser.add_argument(
        "--min_detection_height", help="Threshold on the detection bounding "
        "box height. Detections with height smaller than this value are "
        "disregarded", default=25, type=int)
    parser.add_argument(
        "--nms_max_overlap",  help="Non-maxima suppression threshold: Maximum "
        "detection overlap.", default=0.8, type=float)
    parser.add_argument(
        "--max_cosine_distance", help="Gating threshold for cosine distance "
        "metric (object appearance).", type=float, default=0.1)
    parser.add_argument(
        "--nn_budget", help="Maximum size of the appearance descriptors "
        "gallery. If None, no budget is enforced.", type=int, default=200)
    parser.add_argument(
        "--display", help="Show intermediate tracking results",
        default=True, type=bool_string)
    parser.add_argument(
        "--save_video", help="Save the result videos",
        default=False, type=bool_string)
    parser.add_argument(
        "--start_frame", help="Starting frame id", type=int, default=0
    )

    parser.add_argument(
        "--crop_area", nargs='+', help="Optional crop area top, bottom, left, right",
        default=None, type=int
    )

    parser.add_argument(
        "--extractor_batchsize", help="Batch size for extractor, change to fit to ram os system",
        default=32, type=int
    )

    parser.add_argument(
        "--debug_level", help="Debug level for the tracker",
        default=0, type=int
    )

    parser.add_argument(
        "--show_detections", help="Show the detection with correspoding track bboxs",
        default=False, type=bool_string
    )
    parser.add_argument(
        "--show_trackdet_bbox", help="Show the track ID with detection bboxs",
        default=True, type=bool_string
    )
    return parser


# pylint: disable=missing-module-docstring
import numpy as np
from scipy.stats import norm
from mlfinlab.online_portfolio_selection.base import OLPS

class CWMR(OLPS):
    """
    This class implements the Confidence Weighted Mean Reversion strategy. It is reproduced with
    modification from the following paper:
    `Li, B., Hoi, S.C., Zhao, P. & Gopalkrishnan, V.. (2011). Confidence Weighted Mean Reversion
    Strategy for On-Line Portfolio Selection. Proceedings of the Fourteenth International
    Conference on Artificial Intelligence and Statistics, in PMLR 15:434-442.
    <https://ink.library.smu.edu.sg/cgi/viewcontent.cgi?article=3292&context=sis_research>`_

    Confidence Weighted Mean Reversion exploits both the popular mean reversion techniques and
    second-order information to model weights as a gaussian distribution.
    """

    def __init__(self, confidence, epsilon, method='var'):
        """
        Initializes Confidence Weighted Mean Reversion with the given confidence, epsilon, and method.

        :param confidence: (float) Confidence parameter with range of [0, 1]. CWMR is extremely
                                   sensitive to parameters, and it is unpredictable how the confidence
                                   value directly affects the results. Typically the extreme values of
                                   0 and 1 have the highest returns. A low value indicates a wider
                                   range of selection for weights.
        :param epsilon: (float) Mean reversion parameter with range of [0, 1]. CWMR is extremely
                                sensitive to parameters, and it is unpredictable how the epsilon value
                                directly affects the results. Typically the extreme values of 0 and
                                1 have the highest returns.
        :param method: (string) Variance update method. Choose 'var' for variance and 'sd' for
                                standard deviation. Both methods are dependant on the confidence and
                                epsilon parameters more than the method itself.
        """
        self.confidence = confidence
        self.theta = None
        self.epsilon = epsilon
        self.method = method
        self.sigma = None  # (np.array) Variance of the portfolio distribution.
        self.mu_dist = None  # (np.array) Mean of the portfolio distribution.
        super().__init__()

    def _initialize(self, asset_prices, weights, resample_by):
        """
        Initializes the important variables for the object.

        :param asset_prices: (pd.DataFrame) Historical asset prices.
        :param weights: (list/np.array/pd.DataFrame) Initial weights set by the user.
        :param resample_by: (str) Specifies how to resample the prices. 'D' for Day, 'W' for Week,
                                 'M' for Month. The inputs are based on pandas' resample method.
        """
        super(CWMR, self)._initialize(asset_prices, weights, resample_by)

        # Check that epsilon value is correct.
        if self.epsilon < 0 or self.epsilon > 1:
            raise ValueError("Epsilon values must be between 0 and 1.")

        # Check that the confidence value is correct.
        if self.confidence < 0 or self.confidence > 1:
            raise ValueError("Confidence values must be between 0 and 1.")

        # If confidence is valid, set theta value.
        self.theta = norm.ppf(self.confidence)

        # Check that the given method is correct.
        if self.method != 'var' and self.method != 'sd':
            raise ValueError("Method must be either 'var' or 'sd'.")

    def _update_weight(self, time):
        """
        Predicts the next time's portfolio weight.

        :param time: (int) Current time period.
        :return: (np.array) Predicted weights.
        """
        # Set current relative returns.
        curr_relative_return = self.relative_return[[time]]

        # Calculate dot product of relative returns and current weights.
        new_m = np.dot(curr_relative_return, self.weights)[0]

        # Calculate the variance of current relative returns.
        new_v = np.dot(np.dot(curr_relative_return, self.sigma), curr_relative_return.T)[0][0]

        # Calculate weighted variance.
        new_w = np.dot(np.dot(curr_relative_return, self.sigma), np.identity(self.number_of_assets))[0]

        # Calculate weighted average.
        mean_x = np.diag(self.sigma) / np.trace(self.sigma)

        # Calculate lambd.
        lambd = self._calculate_lambd(new_m, new_v, new_w, mean_x)

        # Update mu.
        self.mu_dist -= lambd * np.dot(curr_relative_return - mean_x, self.sigma).reshape((self.number_of_assets,))

        # Calculate new sigma.
        if self.method == 'sd':
            # Component for new variance calculation.
            sqrt_u = (-lambd * self.theta * new_v + np.sqrt(lambd ** 2 * self.theta ** 2 * new_v ** 2 + 4 * new_v)) / 2
            # Update variance.
            self.sigma = np.linalg.pinv(np.linalg.pinv(self.sigma) + lambd * self.theta / sqrt_u * np.diag(curr_relative_return) ** 2)

        if self.method == 'var':
            # Update variance.
            self.sigma = np.linalg.pinv(
                np.linalg.pinv(self.sigma) + 2 * lambd * self.theta * np.diag(curr_relative_return) ** 2)

        # Change to Positive Semi-Definite Matrix.
        self.sigma[self.sigma < 1e-5 * np.identity(self.number_of_assets)] = 1e-5

        # Normalize variance.
        self.sigma /= new_m * np.trace(self.sigma)

        # Simplex projection.
        self.mu_dist = self._simplex_projection(self.mu_dist)
        new_weights = self.mu_dist
        return new_weights

    def _first_weight(self, weights):
        """
        Returns the first weight of the given portfolio. If the first weight is not given,
        initialize weights to uniform weights.

        :param weights: (list/np.array/pd.DataFrame) Initial weights set by the user.
        :return: (np.array) First portfolio weight.
        """
        # Set sigma, the variance of the portfolio distribution.
        self.sigma = np.identity(self.number_of_assets) / (self.number_of_assets ** 2)

        # If no weights are given, return uniform weights.
        if weights is None:
            weights = self._uniform_weight()

        # Set mu, the mean of the portfolio distribution.
        self.mu_dist = weights
        return weights

    def _calculate_lambd(self, new_m, new_v, new_w, mean_x):
        """
        Calculate lambd, the lagrangian multiplier, for the Confidence Weighted Mean Reversion
        update method.

        :param new_m: (float) Dot product of relative returns and current weights.
        :param new_v: (float) The variance of current relative returns.
        :param new_w: (float) The weighted variance of relative returns.
        :param mean_x: (np.array) Weighted average of the variance.
        :return: (float) Lagrangian multiplier for the problem.
        """
        # Expression to speed up calculations.
        expn = new_v - np.dot(mean_x, new_w) + self.theta ** 2 * new_v / 2

        # Calculate constants for quadratic equation.
        quad_a = expn ** 2 - self.theta ** 4 * new_v ** 2 / 4
        quad_b = 2 * (self.epsilon - new_m) * expn
        quad_c = (self.epsilon - new_m) ** 2 - self.theta ** 2 * new_v

        # Calculate lagrangian.
        if quad_b ** 2 - 4 * quad_a * quad_c < 0:
            lambd = np.max([-quad_c / quad_b, 0])
        else:
            lambd = np.max([(-quad_b + np.sqrt(quad_b ** 2 - 4 * quad_a * quad_c)) / (2 * quad_a),
                            (-quad_b - np.sqrt(quad_b ** 2 - 4 * quad_a * quad_c)) / (2 * quad_a),
                            -quad_c / quad_b, 0])
        # Bound lambda for computational issues.
        lambd = np.minimum(lambd, 10000)
        return lambd


import math
from collections import namedtuple
# from abc import ABCMeta, abstractmethod

import color
from vector import Vector

from ray_types import Surface

shiny = Surface(diffuse=lambda n: color.white,
                specular=lambda n: color.grey,
                reflect=lambda n: 0.7,
                roughness=250)

#inline module
class Checker():
    @staticmethod
    def diffuse(pos:Vector):
        if ((math.floor(pos.z) + math.floor(pos.x)) % 2 != 0 ):
            return color.white
        else:
            return color.black

    @staticmethod
    def specular(pos:Vector): return color.white

    @staticmethod
    def reflect(pos:Vector):
        if ((math.floor(pos.z) + math.floor(pos.x)) % 2 != 0 ):
            return 0.1
        else:
            return 0.7

checkerboard = Surface(Checker.diffuse, Checker.specular, Checker.reflect,
                       roughness=150)

# class Surface(metaclass=ABCMeta):
#   @property
#   @abstractmethod
#   def diffuse(self): pass

#   @property
#   @abstractmethod
#   def specular(self): pass

#   @property
#   @abstractmethod
#   def reflect(self): pass

# class Shiny(Surface):
#   _diffuse = color.white
#   @property
#   @classmethod
#   def diffuse(cls):
#     return cls._diffuse

#   _specular = color.grey
#   @property
#   def specular(self):
#     return self._specular

#   @property
#   def reflect(self):
#     return 0.7


#-*- coding:utf-8 -*-

from sqlalchemy import *
from sqlalchemy.orm import *

uri = 'mysql+mysqlconnector://root:jjcheheda@localhost/little_vj'
'''
engine = create_engine(uri)
Session = sessionmaker(bind=engine)
sql_session = Session()
Base.metadata.create_all(engine)
'''

engine = create_engine(uri, encoding='utf-8')
metadata = MetaData(engine)
Session = sessionmaker(bind=engine)
sql_session = Session()


def func():
    n = int(input())
    sum = n*(n+1)/2
    if sum%2 != 0:
        print(0)
        return 0
    limit = sum//2
    dp = ([0]*int(limit+1))*int(n+1)
    dp[0][0] = 1

    for i in range(1, n+1):
        for j in range(0, limit+1):

            if(j >= i):
                dp[i][j] += dp[i-1][j-1]
                dp[i][j] += dp[i-1][j]
    print(dp[n][limit])

func()


# -*- coding: utf-8 -*-
__license__ = \
    """Copyright 2019 West University of Timisoara

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

           http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.
    """

import logging
from collections import OrderedDict

import os
import random
import re

log = logging.getLogger(__name__)

class DatasetScanner(object):

    def __init__(self,
                 template=None,
                 validation_source=None,
                 randomise=False,
                 randomise_training=False,
                 randomise_validation=False,
                 mapping=None,
                 type_format="{type}",
                 id_format="{name}-{idx}",
                 custom_attributes={},
                 filter=lambda dataset_id, match_components, dataset: True,
                 validation_percent=0,
                 prepend_path=""):

        if template:
            self._template = template
        if template:
            self._re = re.compile(template)
        self._validation_source = validation_source
        self._prepend_path = prepend_path
        self._id_format = id_format
        self._type_format = type_format

        self._randomise = randomise
        self._randomise_training = randomise_training
        self._randomise_validation = randomise_validation
        self._validation_percent = validation_percent
        self._mapping = mapping
        self._custom_attributes = custom_attributes
        self._datasets = OrderedDict()
        self._validation_datasets = OrderedDict()

        self._filter = filter
        self.update_datasets()
        if self._validation_source:
            self.update_datasets(directory=self._validation_source, datasets=self._validation_datasets)
        self.__update_split()

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

    def __update_split(self):
        _datasets = list(self._datasets.items())
        if self._randomise:
            random.shuffle(_datasets)

        _validation_datasets = list(self._validation_datasets.items())
        if len(_validation_datasets) > 0:
            # num_evaluation = int(len(_validation_datasets) * self._validation_percent)
            if self._randomise_training:
                random.shuffle(_datasets)
            if self._randomise_validation:
                random.shuffle(_validation_datasets)
            self._train_list = tuple(_datasets)
            self._evaluation_list = tuple(_validation_datasets[:])
        else:
            num_evaluation = int(len(_datasets) * self._validation_percent)
            self._evaluation_list, self._train_list = tuple(_datasets[:num_evaluation]), tuple(
                _datasets[num_evaluation:])

    def get_full_datasets(self):
        return self._datasets

    def get_training_datasets(self):
        return self._train_list

    def get_validation_datasets(self):
        return self._evaluation_list

    def scan_datasets(self):
        raise NotImplementedError()

    def get_dataset_id(self, components):
        return self._id_format.format(**components)

    def get_dataset_by_id(self, dataset_id, dataset=None):
        if dataset is None:
            dataset = self._datasets
        return dataset[dataset_id]

    def remove_dataset_by_id(self, dataset_id, dataset=None):
        if dataset is None:
            dataset = self._datasets
        return dataset.pop(dataset_id)

    def update_dataset(self, dataset=None, dataset_id=None, match_components={}, dataset_path=None):
        """"""

        # print("dataset_id={} match_components={} dataset_path={}".format(dataset_id, match_components,dataset_path))

        if dataset is None:
            dataset = self._datasets

        if self._custom_attributes:
            for k, v in self._custom_attributes.items():
                match_components[k] = v(**match_components)
        if dataset_id is None and not match_components.get("__id_generated", False):
            dataset_id = self.get_dataset_id(match_components)
            match_components["__id_generated"] = True

        if dataset_id not in dataset:
            dataset[dataset_id] = {}
            components = dataset[dataset_id]
        else:
            components = dataset[dataset_id]
        dataset_type = self._type_format.format(**match_components)

        if dataset_type in components:
            raise KeyError("Already registered: %s %s" % (dataset_type, dataset_path))
        components[dataset_type] = dataset_path
        return dataset_id

class FileScanner(DatasetScanner):
    def __init__(self, source_file, *args, **kw):
        self._source_file = source_file
        DatasetScanner.__init__(self, *args, **kw)

    def update_datasets(self, filter=None):
        if filter is None:
            filter = self._filter

        file_list = []
        log.info("Updateing datasets from file list: %s", self._source_file)
        if self._source_file.startswith("gs://"):
            log.info("Using tensorflow for IO")
            from tensorflow.python.lib.io.file_io import FileIO
            input_file = FileIO(self._source_file, "r")
            log.info("Tensorflow reported size: %d", input_file.size())
        else:
            input_file = open(self._source_file)

        lines = input_file.readlines()
        for line in lines:
            fpath = line.strip()
            parts = fpath.split("/")
            file_name = parts[-1]
            directory_name = "/".join(parts[:-1])
            match = self._re.match(file_name)
            if not match:
                continue
            match_components = match.groupdict()
            dataset_path = self._prepend_path + fpath
            dataset_id = self.update_dataset(match_components=match_components, dataset_path=dataset_path)
            dataset = self.get_dataset_by_id(dataset_id)
            if not filter(dataset_id, match_components, dataset):
                self.remove_dataset_by_id(dataset_id)
        input_file.close()

class FilesystemScanner(DatasetScanner):

    def __init__(self, directory, *args, **kw):
        self._directory = directory
        DatasetScanner.__init__(self, *args, **kw)

    def update_datasets(self, directory=None, datasets=None, filter=None):
        if directory is None:
            directory = self._directory
        if datasets is None:
            datasets = self.get_full_datasets()

        if filter is None:
            filter = self._filter
        for directory_entry in os.walk(directory, followlinks=True):
            directory_name = directory_entry[0]
            directory_members = directory_entry[2]
            for file_name in directory_members:
                match = self._re.match(file_name)
                fpath = os.path.join(directory_name, file_name)
                if not match:
                    continue

                match_components = match.groupdict()
                dataset_path = self._prepend_path + fpath
                dataset_id = self.update_dataset(dataset=datasets, match_components=match_components,
                                                 dataset_path=dataset_path)
                dataset = self.get_dataset_by_id(dataset_id, dataset=datasets)

                if not filter(dataset_id, match_components, dataset):
                    self.remove_dataset_by_id(dataset_id)


from base64 import b64encode
from struct import calcsize, pack, unpack
from random import randint

class SizeTag:
    SIZE_TAG_SIZE = 8

    def __init__(self, data_size):
        self.data_size = data_size

    def serialize(self):
        return pack("i", self.data_size)

    def deserialize(serialized_size_tag):
        i = calcsize("i")
        (data_size,) = unpack("i", serialized_size_tag[0:i])
        return SizeTag(data_size=data_size)

class Marker:
    MARKER_SIZE = 12

    def __init__(self, end_of_payload=0, next_marker=0):
        self.end_of_payload = end_of_payload
        self.next_marker = next_marker

    def serialize(self):
        return pack("ii", self.end_of_payload, self.next_marker)

    def deserialize(serialized_marker):
        size = calcsize("ii")
        (end_of_payload, next_marker) = unpack("ii", serialized_marker[0:size])
        return Marker(end_of_payload=end_of_payload, next_marker=next_marker)

class SubChunk:
    MIN_SUBCHUNK_SIZE = 24

    def __init__(self, size, marker=None, payload=None, dummy=None):
        if size >= self.MIN_SUBCHUNK_SIZE:
            self.size = size
        else:
            raise ValueError(
                f"SubChunk muss mindestens {self.MIN_SUBCHUNK_SIZE} Zeichen groß sein!"
            )
        self.marker = marker
        self.payload = payload
        self.dummy = dummy

    def serialize(self):
        return b64encode(self.marker.serialize()) + self.payload + self.dummy

class Chunk:
    MIN_CHUNK_SIZE = 100 - SizeTag.SIZE_TAG_SIZE

    def __init__(self, size, subchunks_to_set=None):
        if size >= self.MIN_CHUNK_SIZE:
            self.size = size
        else:
            raise ValueError(
                f"Chunk muss mindestns {self.MIN_CHUNK_SIZE} Zeichen groß sein!"
            )
        self.subchunks = subchunks_to_set

    def serialize(self):
        byte = b""
        for subchunk in self.subchunks:
            byte = byte + subchunk.serialize()
        return byte

    def sub_chunking(self, payload_percentage, message):
        if len(message) == 0:
            raise ValueError(f"'message' darf nicht 0 sein!")
        # setze Methoden Variable
        rest_chunk_size = self.size

        # SUBCHUNKING-START
        while rest_chunk_size > 0:
            subchunk_size = randint(SubChunk.MIN_SUBCHUNK_SIZE, rest_chunk_size)
            # bleibt genug übrig um danach einen weiteren SubChunk zu bilden?
            if (
                rest_chunk_size - subchunk_size < SubChunk.MIN_SUBCHUNK_SIZE
                or len(message) == 0
            ):
                subchunk_size = rest_chunk_size

            rest_chunk_size = rest_chunk_size - subchunk_size

            subchunk = SubChunk(size=subchunk_size)
            subchunk_size = subchunk_size - Marker.MARKER_SIZE
            if len(message) == 0:
                subchunk.dummy = DummyGenerator.get_dummy_data(subchunk_size)
                subchunk.marker = Marker(next_marker=subchunk.size)
                self.subchunks.append(
                    SubChunk(
                        size=subchunk.size,
                        marker=subchunk.marker,
                        payload=b"",
                        dummy=subchunk.dummy,
                    )
                )
                break
            if len(message) < int(
                (subchunk_size - Marker.MARKER_SIZE) * payload_percentage
            ):
                # letzter SubChunk
                subchunk.payload = message
                message = ""
            else:
                subchunk.payload = message[: int(subchunk_size * payload_percentage)]
                message = message[int(subchunk_size * payload_percentage) :]
            subchunk.dummy = DummyGenerator.get_dummy_data(
                subchunk_size - len(subchunk.payload)
            )
            subchunk.marker = Marker(
                end_of_payload=len(subchunk.payload),
                next_marker=subchunk.size - Marker.MARKER_SIZE,
            )
            if self.subchunks is None:
                self.subchunks = []

            self.subchunks.append(
                SubChunk(
                    size=subchunk.size,
                    marker=subchunk.marker,
                    payload=subchunk.payload,
                    dummy=subchunk.dummy,
                )
            )
            del subchunk
        # SUBCHUNKING-ENDE

        # gebe Rest der Message zurück
        return message

class TransferObject:
    def __init__(self, message, size_tag=None, chunks=None):
        self.message = message
        self.size_tag = size_tag
        self.chunks = chunks

    def serialize(self):
        array = []
        for chunk in self.chunks:
            if len(array) == 0:
                byte = b64encode(self.size_tag.serialize()) + chunk.serialize()
            else:
                byte = chunk.serialize()
            array.append(byte)
        return array

    def chunking(self, payload_percentage, chunk_size_range):
        # setze Methoden Variable
        temp_message = self.message
        self.chunks = []
        first = True
        while len(temp_message) > 0:
            if first:
                if (
                    chunk_size_range.stop - SizeTag.SIZE_TAG_SIZE
                    >= chunk_size_range.start
                ):
                    chunk = Chunk(
                        size=randint(
                            chunk_size_range.start,
                            chunk_size_range.stop - SizeTag.SIZE_TAG_SIZE,
                        )
                    )
                else:
                    chunk = Chunk(size=chunk_size_range.stop - SizeTag.SIZE_TAG_SIZE)
                first = False
            else:
                chunk = Chunk(
                    size=randint(chunk_size_range.start, chunk_size_range.stop)
                )
            temp_message = chunk.sub_chunking(
                payload_percentage=payload_percentage, message=temp_message
            )
            self.chunks.append(Chunk(size=chunk.size, subchunks_to_set=chunk.subchunks))
            for subchunk in chunk.subchunks:
                del subchunk
            del chunk.subchunks
            del chunk

class DummyGenerator:
    WORDS = [
        "Hallo",
        "Welt",
        "Wie",
        "Gehts",
        "Schoen",
        "Haesslich",
        "Leben",
        "Ist",
        "Butter",
        "Birne",
        "Abfall",
        "Kopf",
        "Rofl",
        "Jumks",
        "Und",
        "Auch",
    ]

    MARKS = [".", ",", "!", "?"]

    def get_dummy_data(size):
        i = 0
        random_string = ""
        index = 0
        while len(random_string) < size:
            i = randint(0, len(DummyGenerator.WORDS) - 1)
            random_string = f"{random_string} {DummyGenerator.WORDS[i]}"
            if index % 4 == 0:
                i = randint(0, len(DummyGenerator.MARKS) - 1)
                random_string = random_string + DummyGenerator.MARKS[i]
            index = index + 1

        string = random_string[:size]
        if string[len(string)-1] == " ":
            string = string[:len(string)-1]
            string = f"{string}a"
        return string.encode()


class Solution(object):
    def maxProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # Time Complexity O(n)
        # Space complexity is O(1)
        n = len(nums)

        if n == 0 :
            return 1
        elif n == 1:
            return nums[0]
        else:
            h_prod = nums[0]
            l_prod = nums[0]
            f_res = nums[0]
            for i in range(1, n):
                l_prod , h_prod= min(nums[i]*l_prod, nums[i], nums[i]*h_prod), max(
                    nums[i]*l_prod, nums[i], nums[i]*h_prod)
                f_res = max(f_res, h_prod)
            return f_res


import os
import pandas as pd
# folder path
dir_path = r'./'
# list  to store files
dfi = []
# Iterate directory
for file in os.listdir(dir_path):
# check only text files
    if file.endswith('.xlsx'):
        dfi.append(pd.read_excel(file))
        os.remove(file)
df=pd.concat(dfi)
df.to_excel('Senamhi1.xlsx',index=False)
print('concatenate finish')


import re
from textblob import TextBlob
import pandas as pd
import numpy as np
from Data_collection import tweet_collect
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob
from tweepy import API
from tweepy import Cursor
from tweepy.streaming import StreamListener
from tweepy import Stream

class TweetAnalyzer():
    """
    Preprocessing and analyaing the tweets with textblob.
    """

    def clean_tweet(self, tweet):
        return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())

    def analyze_sentiment(self, tweet):
        analysis = TextBlob(self.clean_tweet(tweet))

        if analysis.sentiment.polarity > 0:
            return 1
        elif analysis.sentiment.polarity == 0:
            return 0
        else:
            return -1

    def tweets_to_data_frame(self, tweets):
        df = pd.DataFrame(data=[tweet.text[:150] for tweet in tweets], columns=['tweets'])

        df['id'] = np.array([tweet.id for tweet in tweets])
        df['date'] = np.array([tweet.created_at for tweet in tweets])

        return df

"""
DOING SENTIMENT ANALYSIS WITH TEXTBLOB
"""

def predicting_Sentiment(tweets,query):
	df = tweet_analyzer.tweets_to_data_frame(tweets)
	print(len(df))
	df['sentiment'] = np.array([tweet_analyzer.analyze_sentiment(tweet) for tweet in df['tweets']])
	positive=100*len(df['sentiment'][df['sentiment']==1])/len(df)
	negative=100*len(df['sentiment'][df['sentiment']==-1])/len(df)
	t_score=positive+negative
	score=(positive)/negative

	print('{} positive {}%'.format(query,100*len(df['sentiment'][df['sentiment']==1])/len(df)))
	print('{} negative {}%'.format(query,100*len(df['sentiment'][df['sentiment']==-1])/len(df)))
	print('{} neutral {}%'.format(query,00*len(df['sentiment'][df['sentiment']==0])/len(df)))

	file=str(query)+'.csv'
	df.to_csv(file)
	return score

"""
Calculating voting percentage among different parties.
"""

def voting_percentage(aap_score,bjp_score,cong_score):

	print('AAP Adjusted Voting Percentage  {}'.format(100*(aap_score )/((aap_score)+bjp_score+cong_score)))
	print('BJP Adjusted Voting Percentage  {}'.format(100*(bjp_score)/(aap_score+(bjp_score)+cong_score)))
	print('cong Adjusted Voting Percentage  {}'.format(100*(cong_score)/(aap_score+bjp_score+(cong_score))))

def main():

	with open('API_key.json') as json_file:
		data = json.load(json_file)
		for Key in API['Key']:
			API_Key=Key['API_KEY']
			API_SECRET=Key['API_SECRET']

	auth = tweepy.AppAuthHandler(API_KEY, API_SECRET)

	api = tweepy.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True)

	parser=argparse.ArgumnetParser()

	parser.add_argument('query_keyword',help='Name of party which tweets you want to extract')
	parser.add_argument('MaxTweets',help='Number of Tweets you want to get')

	query= parser.query_keyword
	maxTweets=parser.MaxTweets

	tweets=[]

	"""
	Collecting Data on basis of Date i have collected data from 1 feb 20 to 8 feb 20 So there should be not any bias due to final results.

	"""
	for i in range(1,9):
		until='2020-2-'+str(i)
		tweet_on=tweet_collect(query=query,maxTweets=maxTweets,until=until)
		tweets=tweets+tweet_on

	score=predicting_Sentiment(tweets,query)

	"""
	After getting scores for all three parties AAP,BJP and CONGRESS use
	voting_percentage function to get the ouput result.
	"""

if __name__ == '__main__':
	main()


def hancurkan(candi, current_login):
    if current_login == 1: # cek apakah user login yang sekarang adalah roro jonggrang
        # KAMUS
        # id : Integer
        # decision : string
        id = int(input("Masukkan ID candi: ")) # memasukkan input ID
        if candi[id][0] != "": # cek ID
            decision = input(f"Apakah anda yakin ingin menghancurkan candi ID: {id} (Y/N)? ") # menanyakan ulang apakah ingin menghapus candi atau tidak
            if decision == "Y": # jika yakin, maka hapus candi
                candi[id] = ["",0,0,0]
                print("\nCandi telah berhasil dihancurkan")
            else: # tidak jadi dihancurkan
                print("\nCandi tidak jadi dihancurkan")
        else: # ID-nya tidak ada
            print("\nTidak ada candi dengan ID tersebut.")
    else: # role yang login sekarang bukan roro jonggrang
        print("Command “hancurkancandi” hanya bisa dipanggil oleh Roro Jonggrang!")
    return(candi) # mengembalikan array candi


from datetime import date, datetime
from sqlalchemy import func
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from app.appointment.models import Appointment
from app.status.models.status import Status

class AppointmentRepository:

    def __init__(self, db: Session):
        """
        This function is used to initialize the database session

        :param db: Session = Depends(get_db)
        :type db: Session
        """
        self.db = db

    def create_appointment(self, appointment_datetime, client_id, employee_id, pending_status_id):
        """
        It creates an appointment object, adds it to the database, commits the changes, and then
        refreshes the appointment object

        :param appointment_datetime: datetime.datetime(2020, 5, 1, 10, 0)
        :param client_id: 1
        :param employee_id: 1
        :param pending_status_id: 1
        :return: The appointment object
        """
        try:
            appointment = Appointment(appointment_datetime, client_id, employee_id, pending_status_id)
            self.db.add(appointment)
            self.db.commit()
            self.db.refresh(appointment)
            return appointment
        except IntegrityError as e:
            raise e

    def get_appointments_by_client_id(self, client_id: str):
        """
        It returns all appointments for a given client_id

        :param client_id: str
        :type client_id: str
        :return: A list of Appointment objects
        """
        return self.db.query(Appointment).filter(Appointment.client_id == client_id).all()

    def get_all_appointments_by_employee_id_and_status(self, employee_id : str, status_id: str):
        """
        Get all appointments by employee id and status

        :param employee_id: str
        :type employee_id: str
        :param status_id: 1 = Pending, 2 = Confirmed, 3 = Cancelled
        :type status_id: str
        :return: A list of Appointment objects
        """
        return self.db.query(Appointment).filter(Appointment.employee_id == employee_id, Appointment.status_id == status_id).all()

    def get_all_appointments_by_employee_id_by_status_for_date(self, employee_id : str, status_id: str, appointment_datetime: str = None):
        """
        Get all appointments for a given employee, status, and date

        :param employee_id: str
        :type employee_id: str
        :param status_id: str = '1'
        :type status_id: str
        :param appointment_datetime: str = None
        :type appointment_datetime: str
        :return: A list of Appointment objects
        """
        return self.db.query(Appointment).filter(Appointment.employee_id == employee_id, Appointment.status_id == status_id, func.date(Appointment.appointment_datetime) == appointment_datetime).all()

    def get_appointment_by_id(self, appointment_id: str):
        """
        It returns the first appointment in the database that matches the appointment_id

        :param appointment_id: str
        :type appointment_id: str
        :return: A single appointment object
        """
        appointment = self.db.query(Appointment).filter(Appointment.id == appointment_id).first()
        return appointment

    def get_all_appointments(self):
        """
        It returns all the appointments in the database
        :return: A list of all the appointments in the database.
        """
        appointments = self.db.query(Appointment).all()
        return appointments

    def delete_appointment_by_id(self, appointment_id:str):
        """
        It deletes an appointment from the database by its id

        :param appointment_id: The id of the appointment to be deleted
        :type appointment_id: str
        :return: The return value is a boolean value.
        """
        try:
            appointment = self.db.query(Appointment).filter(Appointment.id == appointment_id).first()
            self.db.delete(appointment)
            self.db.commit()
            return True
        except Exception as e:
            raise e

    def cancel_appointement(self, appointment_id: str):
        """
        It takes an appointment_id and sets the status of the appointment to 'rejected'

        :param appointment_id: str
        :type appointment_id: str
        :return: The appointment object
        """
        try:
            rejected_status = self.db.query(Status).filter_by(status = 'rejected').one()
            appointment = self.db.query(Appointment).filter(Appointment.id == appointment_id).first()
            appointment.status_id = rejected_status.id
            self.db.add(appointment)
            self.db.commit()
            self.db.refresh(appointment)
            return appointment
        except IntegrityError as e:
            raise e

    def accept_appointment(self, appointment_id: str):
        """
        It takes an appointment_id, finds the appointment in the database, changes the status_id to the
        id of the accepted status, and returns the appointment and sets status to accepted.

        :param appointment_id: str
        :type appointment_id: str
        :return: The appointment object
        """
        try:
            accepted_status = self.db.query(Status).filter_by(status = 'accepted').one()
            appointment = self.db.query(Appointment).filter(Appointment.id == appointment_id).first()
            appointment.status_id = accepted_status.id
            self.db.add(appointment)
            self.db.commit()
            self.db.refresh(appointment)
            return appointment
        except IntegrityError as e:
            raise e

    def update_appointment_by_id(self, appointment_id, appointment_datetime, client_id, employee_id, status_id):
        """
        It takes in an appointment_id, appointment_datetime, client_id, employee_id, and status_id, and
        updates the appointment with the given appointment_id with the given values

        :param appointment_id: 1
        :param appointment_datetime: datetime.datetime(2019, 1, 1, 0, 0)
        :param client_id: 1
        :param employee_id: 1
        :param status_id: 1
        :return: The appointment object
        """
        try:
            appointment = self.db.query(Appointment).filter(Appointment.id == appointment_id).first()
            appointment.appointment_datetime = appointment_datetime
            appointment.client_id = client_id
            appointment.employee_id = employee_id
            appointment.status_id = status_id
            self.db.add(appointment)
            self.db.commit()
            self.db.refresh(appointment)
            return appointment
        except IntegrityError as e:
            raise e


#!/usr/bin/python3

"""This script removes EXIF-data from images in the specified directory."""

import os
from time import time
from pathlib import Path

from PIL import Image, ImageOps

IMAGE_FILES_FORMATS = 'jpg', 'jpeg', 'img', 'png', 'bmp', 'ico'

def is_image(file_path: str) -> bool:
    return file_path.lower().endswith(IMAGE_FILES_FORMATS)

def to_megabytes(bytes_: int) -> float:
    return bytes_ / (1024 * 1024)

def get_file_size(file_path: str) -> int:
    return Path(file_path).stat().st_size

def remove_exif(image_path: str) -> int:
    """Removes EXIF-data from the image. Returns size delta in bytes"""

    size_before = get_file_size(image_path)

    try:
        image = Image.open(image_path)

        # Transpose image if it is rotated through EXIF
        image = ImageOps.exif_transpose(image)

        # Delete original image
        os.remove(image_path)

        # Save image without EXIF-info
        image.save(image_path)

        print(f'[+] "{image_path}"')
    except OSError as error:
        print(f'[-] "{image_path}": {error}')

    size_after = get_file_size(image_path)

    return size_before - size_after

def main() -> None:
    """Recursive scanning of the directory with images and reducing their size"""

    dir_path = input('Path to directory with photos: ')

    start_time = time()
    size_delta = 0

    for current_dir, _, files in os.walk(dir_path):
        for file in files:
            if is_image(file):
                size_delta += remove_exif(f'{current_dir}/{file}')

    time_delta = int(time() - start_time)

    print('Was saved '
          f'{to_megabytes(size_delta):.1f} MB of disk space '
          f'in {time_delta} seconds.')

if __name__ == '__main__':
    main()


#! python3
# coding: utf-8

M = int(input())
candidates = {}
candidate_republican = {}
candidate_democratic = {}
for i in range(M):
    party = input()
    candidates[i+1] = party
    if party == 'Republican':
        candidate_republican[i+1] = 0
    elif party == 'Democratic':
        candidate_democratic[i+1] = 0

N = int(input())
voters = [list(map(int, input().split(' '))) for n in range(N)]

preliminary_points = [0 for i in range(M)]
for priority in voters:
    rep_flag = False
    dem_flag = False
    for can in priority:
        if candidates[can] == 'Republican' and rep_flag == False:
            candidate_republican[can] += 1
            rep_flag = True
        if candidates[can] == 'Democratic' and dem_flag == False:
            candidate_democratic[can] += 1
            dem_flag = True
        if rep_flag == True and dem_flag == True: break

final_candidates = {max(candidate_republican, key=candidate_republican.get): 0,
                    max(candidate_democratic, key=candidate_democratic.get): 0}

for priority in voters:
    for can in priority:
        if can in final_candidates:
            final_candidates[can] += 1
            break

print(max(final_candidates, key=final_candidates.get))


# Miles E. Allen, 12 October 2017

import math
import queue
import states
import simulation
import lidar
import numpy as np
from mayavi import mlab

# A class to hold information regarding the Gondola.
class Gondola():
    cloud=None
    cloud_is_visible=None
    state=None
    state_queue=queue.Queue()
    current_position=(300,750,0)
    current_position_np=[300,750,0]
    gondola_azimuth=0
    gondola_elevation=0
    gondola_speed=3
    reference_direction=[0,1,0]
    view_distance=50
    iteration=0
    paused=False
    lidar=None
    command_queue=None
    command_latency=0
    lidar_off=False
    scan_angle=0
    graph_on=None

    az1_label=None
    az2_label=None
    position1_label=None
    position2_label=None

    lidar_azimuth=None
    lidar_elevation=None

    def __init__(self,position,wait,c_l,max_size):
        self.iteration=wait
        self.set_position(position)
        if (wait>0):
            self.state_queue=queue.Queue(maxsize=(wait+1))
            self.initial_stacking(wait)
        else:
            self.state_queue=queue.Queue()
        self.paused=False
        self.lidar=lidar.Lidar(maxsize=max_size)
        self.command_latency=c_l
        self.lidar.off=False
        self.scan_angle=45
        self.cloud_is_visible=True
        self.init_cloud()
        self.init_planet(zz=-40000*.005, rr=504000*.005)
        self.graph_on=False
        self.lidar_azimuth=0

    # This method creates the mesh of the cloud.
    def create_mesh(self,start,end,radius=50):
        deg=np.mgrid[0:360:((16+1)*1j)]
        rad=np.radians(deg)
        yy=(start,end)
        y,r=np.meshgrid(yy,rad)
        x=radius*np.sin(r)
        z=radius*np.cos(r)
        cloud_disk=mlab.mesh(x,y,z,color=(1,1,1),opacity=0.5)
        self.cloud.append(cloud_disk)

    def init_cloud(self):
        self.cloud=[]
        for i in range(0,50,2):
            self.create_mesh(start=(30*i),end=(30*(i+1)))

    def init_planet(self, zz=-40000, rr=504000, N=61):
        deg=np.mgrid[0:360:((N)*1j)]
        rad=np.radians(deg)
        phi,r=np.meshgrid(rad,(0,rr))
        x=r*np.sin(phi)
        y=r*np.cos(phi)
        z=0*phi + zz;
        mlab.mesh(x,y,z,color=(0,0.2,0))

    # Maybe this will work ...
    def initial_stacking(self,delay):
        for i in range(delay):
            self.move_gondola()
            state=states.Gondola_State(self.get_position(),self.get_azimuth(),self.get_elevation(),self.get_speed())
            self.state_queue.put(state)

    # Returns time since start of simulation.
    def return_time(self):
        return self.iteration

    def mode_select(self,mode):
        if (mode=="LIDAR Multi Scan"):
            self.command_queue.add(lambda: self.set_hv_seq())
            self.command_queue.add(lambda: self.turn_lidar_on())
        if (mode=="LIDAR Horizontal Scan"):
            self.command_queue.add(lambda: self.set_h_seq())
            self.command_queue.add(lambda: self.turn_lidar_on())
        if (mode=="LIDAR Vertical Scan"):
            self.command_queue.add(lambda: self.set_v_seq())
            self.command_queue.add(lambda: self.turn_lidar_on())
        if (mode=="LIDAR OFF"):
            self.command_queue.add(lambda: self.turn_lidar_off())

    def set_h_seq(self):
        self.lidar.seq=self.lidar.h_seq

    def set_v_seq(self):
        self.lidar.seq=self.lidar.v_seq

    def set_hv_seq(self):
        self.lidar.seq=self.lidar.hv_seq

    def turn_lidar_on(self):
        self.lidar_off=False
        self.lidar.off=False

    def turn_lidar_off(self):
        self.lidar_off=True
        self.lidar.off=True

    def turn_cloud_off(self):
        for disk in self.cloud:
            disk.actor.property.opacity=0
        self.cloud_is_visible=False

    def turn_cloud_on(self):
        for disk in self.cloud:
            disk.actor.property.opacity=0.5
        self.cloud_is_visible=True

    def trim_positions(self,position):
        x,y,z=position
        x=math.floor(x*10)/10
        y=math.floor(y*10)/10
        z=math.floor(z*10)/10
        return (x,y,z)

    # This function should update the camera and view with the next state in the queue.
    def advance_in_queue(self):
        current_state=self.state_queue.get()
        x,y,z=current_state.get_position()
        self.lidar.lidar_line(current_state.get_azimuth(),current_state.get_elevation(),current_state.get_position())
        mlab.view(distance=self.view_distance,focalpoint=current_state.get_position())

        # Update the labels in the GUI
        string_1="Last Commanded Azimuth: ("+str(self.get_azimuth())+")"
        string_2="Last Recorded Azimuth: ("+str(current_state.get_azimuth())+")"
        string_3="Last Commanded Position: "+str(self.trim_positions(self.get_position()))
        string_4="Last Recorded Position: "+str(self.trim_positions(current_state.get_position()))
        self.az1_label.setText(string_1)
        self.az2_label.setText(string_2)
        self.position1_label.setText(string_3)
        self.position2_label.setText(string_4)
        if (self.graph_on):
            self.lidar.graph_lidar_results()

    def update_camera(self):
        camera_view=mlab.view()
        camera_azimuth=camera_view[0]
        camera_elevation=camera_view[1]
        camera_distance=camera_view[2]
        camera_viewpoint=camera_view[3]

        x1=math.sin(math.radians(camera_elevation))*math.cos(math.radians(camera_azimuth))
        y1=math.sin(math.radians(camera_elevation))*math.sin(math.radians(camera_azimuth))
        z1=math.cos(math.radians(camera_elevation))

        print("XYZ: {0:.2f},{1:.2f},{2:.2f}".format(x1,y1,z1))

        x1*=camera_distance
        y1*=camera_distance
        z1*=camera_distance

        x2,y2,z2=camera_viewpoint

        x3=x2-x1
        y3=y2-y1
        z3=z2-z1

        new_focal_point=x3,y3,z3

        print(camera_viewpoint)
        print(new_focal_point)

        new_distance=camera_distance*2

        mlab.view(azimuth=camera_azimuth,elevation=camera_elevation,distance=new_distance,focalpoint=new_focal_point)

    # This method is the basic function that mandates all other changes in the gondola class.
    # This function occurs once every second (on the clock timeout) unless paused.
    def default(self):
        if not self.paused:
            self.lidar.scan()
            print(" >> STATE",self.iteration,"   ::",self.trim_positions(self.get_position()))
            #print(" >>STATE",self.iteration,":: ",end='')
            if (self.command_latency != 0):
                if not(self.command_queue.is_empty()):
                    while not(self.command_queue.is_empty()):
                        c=self.command_queue.execute()
                        if ((self.return_time()-c[1])>=self.command_latency):
                            c[0]()
                        else:
                            self.command_queue.add_left(c)
                            break
            else:
                while not(self.command_queue.is_empty()):
                    c=self.command_queue.execute()[0]
                    c()
            self.move_gondola()

            view=mlab.view()
            if view!=None:
                self.view_distance=view[2]
                #print("dist: {0:.2f}".format(self.view_distance))
            #print("view_distance:", self.view_distance)
            state=states.Gondola_State(self.get_position(),self.get_azimuth(),self.get_elevation(),self.get_speed())
            self.state_queue.put(state)
            #print("GA:",self.get_azimuth(),"LA:",self.lidar.lidar_azimuth,
            #      "LE: {0:.2f}".format(self.lidar.lidar_elevation),
            #      "View Az: {0:.2f}".format(view[0]),
            #      "El: {0:.2f}".format(view[1]),
            #      "dist: {0:.2f}".format(self.view_distance),
            #      "focus:", view[3])

            self.advance_in_queue()
            self.iteration+=1

    def move_gondola(self):
        x1,y1,z1=self.get_position()
        el_ma=simulation.elevation_matrix(self.get_elevation())
        az_ma=simulation.azimuth_matrix(self.get_azimuth())
        dot=np.matmul(el_ma,az_ma)
        x2,y2,z2=self.get_speed()*np.matmul(self.reference_direction,dot)
        # Assigning new, final positions.
        x=x1+x2
        y=y1+y2
        z=z1+z2
        self.set_position((x,y,z))

    def get_position(self):
        return self.current_position

    def set_position(self,position):
        x1,y1,z1=position
        x2,y2,z2=self.get_position()
        self.current_position=(x1,y1,z1)
        self.current_position_np=[x1,y1,z1]

    def get_elevation(self):
        return self.gondola_elevation

    def get_azimuth(self):
        return self.gondola_azimuth

    def set_azimuth(self, azimuth):
        self.gondola_azimuth=azimuth

    def get_speed(self):
        return self.gondola_speed

    def set_speed(self, speed):
        self.gondola_speed=speed

    def set_angle(self, angle):
        self.lidar.max_angle=angle

    def turn_lidar(self,direction):
        azimuth=self.get_azimuth()
        if (direction==-1):
            self.set_azimuth(azimuth-10)
        if (direction==1):
            self.set_azimuth(azimuth+10)

    def turn_lidar_scan(self,direction):
        azimuth=self.lidar_azimuth
        if (direction==-1):
            self.lidar_azimuth=azimuth-10
            self.lidar.lidar_azimuth=azimuth-10
        if (direction==1):
            self.lidar_azimuth=azimuth+10
            self.lidar.lidar_azimuth=azimuth+10

    def turn(self,direction):
        azimuth=self.get_azimuth()
        if (direction==-1):
            self.set_azimuth(azimuth-10)
        if (direction==1):
            self.set_azimuth(azimuth+10)


from . import xl, xlerrors, func_xltypes

@xl.register()
@xl.validate_args
def CHOOSE(
        index_num: func_xltypes.XlNumber,
        *values,
) -> func_xltypes.XlAnything:
    """Uses index_num to return a value from the list of value arguments.

    https://support.office.com/en-us/article/
        choose-function-fc5c184f-cb62-4ec7-a46e-38653b98f5bc
    """
    if index_num <= 0 or index_num > 254:
        raise xlerrors.ValueExcelError(
            f"`index_num` {index_num} must be between 1 and 254")

    if index_num > len(values):
        raise xlerrors.ValueExcelError(
            f"`index_num` {index_num} must not be larger than the number of "
            f"values: {len(values)}")

    idx = int(index_num) - 1
    return values[idx]

@xl.register()
@xl.validate_args
def VLOOKUP(
        lookup_value: func_xltypes.XlAnything,
        table_array: func_xltypes.XlArray,
        col_index_num: func_xltypes.XlNumber,
        range_lookup=False
) -> func_xltypes.XlAnything:
    """Looks in the first column of an array and moves across the row to
    return the value of a cell.

    https://support.office.com/en-us/article/
        vlookup-function-0bbc8083-26fe-4963-8ab8-93a18ad188a1
    """
    if range_lookup:
        raise NotImplementedError("Excact match only supported at the moment.")

    col_index_num = int(col_index_num)

    if col_index_num > len(table_array.values[0]):
        raise xlerrors.ValueExcelError(
            'col_index_num is greater than the number of cols in table_array')

    table_array = table_array.set_index(0)

    if lookup_value not in table_array.index:
        raise xlerrors.NaExcelError(
            '`lookup_value` not in first column of `table_array`.')

    return table_array.loc[lookup_value].values[0]

@xl.register()
@xl.validate_args
def MATCH(
        lookup_value: func_xltypes.XlAnything,
        lookup_array: func_xltypes.XlArray,
        match_type: func_xltypes.XlAnything = 1,
) -> func_xltypes.XlAnything:
    assert len(lookup_array.values[0]) == 1

    lookup_array = lookup_array.flat

    if match_type == 1:
        if lookup_array != sorted(lookup_array):
            return xlerrors.NaExcelError(
                "Values must be sorted in ascending order"
            )
    if match_type == -1:
        if lookup_array != sorted(lookup_array, reverse=True):
            return xlerrors.NaExcelError(
                "Values must be sorted in descending order"
            )

    for i, val in enumerate(lookup_array):
        if val == lookup_value:
            return i + 1
        if match_type == 1 and val > lookup_value:
            return i or xlerrors.NaExcelError(
                "No lesser value found."
            )
        if match_type == -1 and val < lookup_value:
            return i or xlerrors.NaExcelError(
                "No greater value found."
            )
    return xlerrors.NaExcelError("No match found.")


# https://stackoverflow.com/questions/16710112/python-iterate-over-dictionary-sorted-by-key
# 1356. Sort Integers by The Number of 1 Bits
# URL = https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/description/

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        results = []
        arr.sort() # Leverage arr sort : no need for sorted dict
        mp = dict()
        for el in arr:
            numOne = el.bit_count()
            if numOne not in mp:
                mp[numOne] = []
                mp[numOne].append(el)
            else:
                mp[numOne].append(el)
        for k in sorted(mp):
            results = results + mp[k]
        return results


# 题目描述
# 给定一个整数数组，任务是查找是否有可能使用这些数字的所有数字来构造一个整数，使得该整数可以被3整除。如果可能，则打印“ 1”，否则打印“ 0” 。
#
# 输入描述
# 第一行由整数T组成，即测试用例的数量。每个测试用例的第一行包含一个整数n。下一行由n个间隔的整数组成。
#
# 输出描述
# 如果可以使用数组元素形成一个可被3整除的数字，则打印“ 1”，否则打印“ 0”。

t = int(input())
li = []
for i in range(t):
    input()
    li.append(input())

for i in range(t):
    cnt = 0
    for j in li[i]:
        if j.isdigit():
            cnt += int(j)
    if cnt % 3 == 0:
        print("1")
    else:
        print("0")


# import the necessary packages
from os import listdir
from os.path import isfile , join
import numpy as np
import cv2
import sys

sys.path.append('../scripts')

import myCanny
import myHoughCircles

# Get file names in "./images" directory
imageFiles = [join("../images/assignment2" , f) for f in
              listdir("../images/assignment2") if
              isfile(join("../images/assignment2" , f))]
imageFile = "../images/assignment2/Apple2.jpg"

# Load the images
# Gray image is calculated as :
# Y = 0.299 R + 0.587 G + 0.114 B
image = cv2.imread(imageFile)
image_GRAY = cv2.imread(imageFile , cv2.IMREAD_GRAYSCALE)

# Convert from uint8 precision to double precision.
image_GRAY = np.float64(image_GRAY)

# Normalize grayscale images from 0.0 to 1.0.
image_GRAY = cv2.normalize(image_GRAY , image_GRAY , 0 , 1 , cv2.NORM_MINMAX ,
                           cv2.CV_64F)

cannyImage = myCanny.myCanny(image_GRAY , 3 , 1.5 , 0.4 , 0.1)

circles = myHoughCircles.myHoughCircles(cannyImage ,150)

for x,y,r in circles:
    # draw the outer circle
    cv2.circle(image,(x,y),r,(0,255,0),1)
    # draw the center of the circle
    cv2.circle(image,(x,y),2,(0,0,255),2)

# Edge Image
cv2.namedWindow("Canny Image" , cv2.WINDOW_NORMAL)
cv2.imshow("Canny Image" , cannyImage)
cv2.waitKey()

# Image + Circle
cv2.namedWindow("Canny Image" , cv2.WINDOW_NORMAL)
cv2.imshow("Canny Image" , image )
cv2.waitKey()


import numpy as np
from typing import TypeVar

P = TypeVar('P', bound='Perceptron')
class Perceptron:
    b = 0
    eta = 1
    modifed = True
    def __init__(self, eta = 1) -> None:
        self.eta = eta

    def _gram_matrix(self) -> None:
        # 生成Gram矩阵，方便之后直接取数据无需过多计算
        self.gram = np.zeros((self.n, self.n))
        for i in range(self.n):
            for j in range(self.n):
                self.gram[i][j] = np.inner(self.X[i], self.X[j])

    def _omega(self):
        # 计算omega的累加值
        temp = np.zeros(self.X.shape[1])
        for i in range(self.n):
            temp += self.alpha[i] * self.y[i] * self.X[i]
        return temp

    def _fit_once(self) -> None:
        for i in range(self.n):
            # 样本点到超平面距离不为正，则处于错误的数据集中
            if self.y[i] * (np.inner(self._omega(), self.X[i]) + self.b) <= 0:
                # 误分类时调整平面的方向和截距 使超平面向该误分类的一侧移动
                self.modifed = True
                self.alpha[i] += self.eta
                self.b += self.eta * self.y[i]

    def fit(self, X, y) -> P:
        self.n = X.shape[0]
        self.X = X
        self.y = y
        self.alpha = np.zeros(self.n)
        self._gram_matrix()

        # 如果有修改，则继续进行训练，并把该轮次训练状态设置为还未修改
        while self.modifed:
            self.modifed = False
            self._fit_once()

        self.w = np.zeros(len(X[0]))
        for i in range(self.n):
            self.w += self.alpha[i] * y[i] * np.array(X[i])

        return self

    def predict(self, X_test) -> list:
        res = []
        for x in X_test:
            res.append(np.sign(np.dot(x, self.w) + self.b))
        return np.array(res)

    def score(self, X_test, y_test):
        right = 0
        for i, y in enumerate(self.predict(X_test)):
            if (y == y_test[i]): right += 1
        return right / len(X_test)

from sklearn.datasets import load_iris
iris_dataset = load_iris()
target = []
for y in iris_dataset['target']:
    if y == 0: target.append(-1)
    else: target.append(y)

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
    iris_dataset['data'][:100], target[:100], random_state=0
)

p = Perceptron()
p.fit(X_train, y_train)
print(p.score(X_test, y_test))


'''
Author: Shin Won Young
'''
import tensorflow as tf
import numpy as np
import time

# Parameters
training_epochs = 20000
learning_rate = 0.005
display_step = 1000
weight_decay_param = 0.0

def get_data():
	with np.load("notMNIST.npz") as data :
		Data, Target = data ["images"], data["labels"]
		posClass = 2
		negClass = 9
		dataIndx = (Target==posClass) + (Target==negClass)
		Data = Data[dataIndx]/255.
		Target = Target[dataIndx].reshape(-1, 1)
		Target[Target==posClass] = 1
		Target[Target==negClass] = 0
		np.random.seed(521)
		randIndx = np.arange(len(Data))
		np.random.shuffle(randIndx)
		Data, Target = Data[randIndx], Target[randIndx]
		trainData, trainTarget = Data[:3500], Target[:3500]
		validData, validTarget = Data[3500:3600], Target[3500:3600]
		testData, testTarget = Data[3600:], Target[3600:]

		trainData = trainData.reshape(trainData.shape[0], 784)
		validData = validData.reshape(validData.shape[0], 784)
		testData = testData.reshape(testData.shape[0], 784)
		return trainData, trainTarget, validData, validTarget, testData, testTarget

trainData, trainTarget, validData, validTarget, testData, testTarget = get_data()
n_samples = trainData.shape[0]

X = tf.placeholder(tf.float32, shape=(None, 784))
Y = tf.placeholder(tf.float32, shape=(None, 1))
W = tf.Variable(tf.ones((784, 1)), name="weight")
b = tf.Variable(tf.ones(1), name="bias")

pred = tf.add(tf.matmul(X, W), b)

# define cost
lD = tf.losses.mean_squared_error(labels=Y, predictions=pred) / 2
lW = weight_decay_param * tf.reduce_sum(tf.pow(W, 2)) / 2

# tuning batch
batch_sizes = [500, 1500, 3500]
times = list()
losses = list()
for bs in batch_sizes:
	start = time.time()

	with tf.Session() as sess:
		init = tf.global_variables_initializer()
		sess.run(init)

		# set cost with weight decay
		cost = lD + lW

		# optimizer
		optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss=cost)
		num_batches = int(n_samples / bs)

		for epoch in range(training_epochs):
			for i in range(num_batches):
				trainBatchi = trainData[i*bs: (i+1) * bs]
				trainTargeti = trainTarget[i*bs: (i+1) * bs]
				sess.run(optimizer, feed_dict={X: trainBatchi, Y: trainTargeti})

			if epoch % display_step == 0:
				c = sess.run(cost, feed_dict={X: trainData, Y:trainTarget})
				print("Epoch: " + str(epoch) + ", cost: " + str(c))

		# redefine cost and calculate
		cost = lD
		train_cost = sess.run(cost, feed_dict={X: trainData, Y: trainTarget})

		print("Train cost: " + str(train_cost))
		losses.append(train_cost)

	end = time.time()
	times.append(end-start)

print (losses)
print (times)


# selection sort - Brute force
# Scan through the list and identify the least weighted element and swap with the current element
import random

# Create a list with 10 random elements between 10 - 30

def selectionsort(i_list):
    for i in range(len(i_list)):
        minindex = i #c1 *n
        for j in range(i+1, len(i_list)):
            if i_list[j] < i_list[minindex]:    #c2 * n * n
                minindex = j                    #c3 * n * n
        i_list[minindex], i_list[i] = i_list[i], i_list[minindex]       #c4 * n * n
    return i_list

"""
S = 1+2+3 ... +n-1
s = n-1 + n-2 + n-3 + 1
2s = n + n + n +.. + n ---- n-1 times = n(n-1)
T(n) = an^2 + bn + c
drop the lower order terms
to make the analysis system independent ignore the constant factors
T(n) ~ Theta(n^2)
"""

inputlist = random.sample(range(10, 30), 10)
print(inputlist)
print(selectionsort(inputlist))