from typing_extensions import Final
import wx
from wx.core import RED
import wx.xrc
import os
import result_gui as gui
import ctsi_gui
import bnd_gui
import APP1
import test
import sys
import time
import final_r
import cv2 as cv
from os import mkdir
import shutil
import xml.etree.ElementTree as ET

i = 0
case_number = "100783334"
detection_type = ""
jpg_file = ""
Nowpath = os.getcwd()
app_logo = "./logo/logo.ico"
bk_color = "#a7b1c0"

def OnClick_pancreas_menu(self, event):
    global detection_type
    global i
    i = 0
    detection_type = "pancreas"
    find_jpg_file()
    self.Close(True)
    app = wx.App()
    frm = Bnd_Frame(None)
    frm.Show()
    app.MainLoop()
def OnClick_effusion_menu(self, event):
    global detection_type
    global i
    i = 0
    detection_type = "effusion"
    find_jpg_file()
    self.Close(True)
    app = wx.App()
    frm = Bnd_Frame(None)
    frm.Show()
    app.MainLoop()
def find_jpg_file():
    global jpg_file
    path = os.getcwd() + "/../../Data/" + case_number + "/" + detection_type
    for fn in os.listdir(path):
            if fn.endswith("_jpg"):
                jpg_file = fn
def OnClick_pancreas_compara_menu(self, event):
    global detection_type
    global i
    i = 0
    detection_type = "pancreas"
    find_jpg_file()
    self.Close(True)
    app = wx.App()
    frm = MyFrame(None)
    frm.Show()
    app.MainLoop()
def OnClick_effusion_compara_menu(self, event):
    global detection_type
    global i
    i = 0
    detection_type = "effusion"
    find_jpg_file()
    self.Close(True)
    app = wx.App()
    frm = MyFrame(None)
    frm.Show()
    app.MainLoop()
def OnClick_cut_pancreas_menu(self, event):
    global detection_type
    detection_type = "pancreas"
    find_jpg_file()
    self.Close(True)
    app = wx.App()
    frm = Segmentation_Analysis(None)
    frm.Show()
    app.MainLoop()
def OnClick_cut_effusion_menu(self, event):
    global detection_type
    detection_type = "effusion"
    find_jpg_file()
    self.Close(True)
    app = wx.App()
    frm = Segmentation_Analysis(None)
    frm.Show()
    app.MainLoop()
def CTSI_Score_menu(self, event):
    global i
    i = 0
    self.Close(True)
    app = wx.App()
    frm = CTSI_Analysis(None)
    frm.Show()
    app.MainLoop()
def Start_menu(self, event):
    sys.path.append("../3D")
    import test_main
    test_main.test_main(0,case_number)
def FReport_menu(self, event):
    self.Close(True)
    app = wx.App()
    frm = FinalReport(None)
    frm.Show()
    app.MainLoop()
def Home_menu(self, event):
    self.Close(True)
    app = wx.App()
    frm = StartFrame(None)
    frm.Show()
    app.MainLoop()
def scale_bitmap(bitmap, width, height):
    image = wx.ImageFromBitmap(bitmap)
    image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)
    result = wx.BitmapFromImage(image)
    return result
def creat_xml(anchor,num,case_number):
    """
    新建xml文件
    :param xml_file: second_check bounding box 4座標
    """
    root = ET.Element("annotation")
    child1 = ET.SubElement(root, "casenumber")
    child1.text = case_number
    object = ET.SubElement(root, "object")
    namen = ET.SubElement(object, "name")
    namen.text = 'pancreas'
    bndbox = ET.SubElement(object, "bndbox")
    xminn = ET.SubElement(bndbox, "xmin")
    xminn.text = str(anchor[0][0])
    yminn = ET.SubElement(bndbox, "ymin")
    yminn.text = str(anchor[0][1])
    xmaxn = ET.SubElement(bndbox, "xmax")
    xmaxn.text = str(anchor[0][2])
    ymaxn = ET.SubElement(bndbox, "ymax")
    ymaxn.text = str(anchor[0][3])
    tree = ET.ElementTree(root)
    path = '../../Data/'+ case_number + "/" + detection_type +'/pancreas_xml'
    img_name = str(num).split(".")[0]
    writepath = '../../Data/'+ case_number + '/' + detection_type +'/' + detection_type + '_xml/' + img_name +'.xml'
    if detection_type == "effusion":
        path.replace("pancreas_xml","effusion_xml")
        writepath.replace("pancreas_xml","effusion_xml")
    if not os.path.exists(path):
        os.makedirs(path)

    tree.write(writepath,  encoding='utf-8')
    if len(anchor) >1:
        for i in range(len(anchor)-1,0,-1):
            edit_xml(anchor[len(anchor)-i],img_name)

def edit_xml(anchor,img_name):
    """
    修改xml文件
    :param xml_file:xml文件的路径
    :return:
    """
    #print(second_check[0])
    #print('../../Data/'+ case_number + "/" + detection_type +'/pancreas_xml/' + second_check[0] +'.xml')
    treepath = '../../Data/'+ case_number + '/' + detection_type +'/' + detection_type + '_xml/' + img_name +'.xml'
    if detection_type == "effusion":
        treepath.replace("pancreas_xml","effusion_xml")
    tree = ET.parse(treepath)
    root = tree.getroot()
    objs = ET.Element("object")
    root.append(objs)
    bndbox = ET.SubElement(objs, "bndbox")
    #print('error1')
    xminn = ET.SubElement(bndbox, "xmin")
    xminn.text = str(anchor[0])
    #print('error2')
    yminn = ET.SubElement(bndbox, "ymin")
    yminn.text = str(anchor[1])
    #print('error3')
    xmaxn = ET.SubElement(bndbox, "xmax")
    xmaxn.text = str(anchor[2])
    #print('error4')
    ymaxn = ET.SubElement(bndbox, "ymax")
    ymaxn.text = str(anchor[3])
    #print('error5')
    tree.write(treepath,method='xml',encoding='utf-8')
def enhence_show(anchors,img_name):
    JPG='../../Data/'+ case_number + "/" + detection_type +'/testmodel/' + case_number + "/" + img_name
    only_number = img_name.split('-00')[2].split('.')[0]
    img = cv.imread(JPG)
    for anchor in anchors:
        cv.rectangle(img,(anchor[0],anchor[1]),(anchor[2],anchor[3]),(0,0,255),thickness=2)
    PATH = '../../Data/'+ case_number + "/" + detection_type +'/pancreas_bnd/'
    if not os.path.exists(PATH):
        os.makedirs(PATH)
    cv.imwrite(PATH + img_name, img)

class First_Fram (gui.First_Fram):
    def __init__(self, parent):
        gui.First_Fram.__init__( self, parent)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
    def OnEraseBack( self, event):
        dc = event.GetDC()
        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("./logo/first_bkg4.png")
        bitmap = scale_bitmap(bmp, 500, 350)
        dc.DrawBitmap(bitmap, 0, 0)

    def Onclick_StartFrame( self, parent ):
        self.Close(True)
        frm = StartFrame(None)
        frm.Show()
        app.MainLoop()

class StartFrame (gui.StartFrame):

    def __init__(self, parent):
        gui.StartFrame.__init__( self, parent)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
    def Onclick_Item(self, event):
        col_index = self.list.GetFirstSelected()
        msg = self.list.GetItem(col_index, col=0)
        #print(msg.GetText())
        msg_text = msg.GetText()
        self.Item_choose.SetLabel(msg_text)
        self.Item_choose.SetForegroundColour('black')
    def Onclick_Result( self, event ):
        msg = self.Item_choose.GetLabelText()
        global case_number
        case_number = msg
        # 判斷路徑是否存在
        file_path = "../../Data"
        files = os.listdir(file_path)
        for file in files:
            if file == case_number:
            # 判斷路徑是否存在
                file_result_path = file_path + "/" +case_number + "/path"
                result_files = os.listdir(file_result_path)
                check_f = 0
                for f in result_files:
                    if f == "3_line_dcm":
                        check_f = 1
                        self.Close(True)
                        frm = Result_Frame(None)
                        frm.Show()
                        app.MainLoop()
                if check_f == 0:
                    msg_hint = "此案例尚未分析"
                    self.Item_choose.SetLabel(msg_hint)
                    self.Item_choose.SetForegroundColour('red')

    def Onclick_run_code( self, event ):
        msg = self.Item_choose.GetLabelText()
        global case_number
        case_number = msg
        # 判斷路徑是否存在
        file_path = "../../Data"
        files = os.listdir(file_path)
        for file in files:
            if file == case_number:
            # 判斷路徑是否存在
                self.Close(True)
                frm = WaitFrame(None)
                frm.Show()
                app.MainLoop()
    def Onclick_import_file( self, event):
        target_paths = '../../Data/'
        check_dlg_dcm = 0

        dlg_dcm = wx.DirDialog(
            self, message="Choose the DICOM file",
            style=wx.DD_DEFAULT_STYLE  |
                    wx.DD_DIR_MUST_EXIST
            )

        if dlg_dcm.ShowModal() == wx.ID_OK:
            check_dlg_dcm = 1
            paths_dcm = dlg_dcm.GetPath()
            list_case_number = paths_dcm.split('\\')
            str_case_number = list_case_number[len(list_case_number)-1]

            #print('path:' + paths_dcm)
            check_file = 0
            for fn in os.listdir(target_paths):
                if fn == str_case_number:
                    check_file = 1
                    break
            target_file_paths = target_paths + str_case_number
            if check_file == 0:
                mkdir(target_file_paths)
                mkdir(target_file_paths + '\\effusion')
                mkdir(target_file_paths + '\\pancreas')
                mkdir(target_file_paths + '\\path')

            shutil.move(paths_dcm, target_file_paths)

        dlg_dcm.Destroy()

        if check_dlg_dcm == 1:
            dlg_eff = wx.DirDialog(
                self, message="Choose the Effusion jpg file",
                style=wx.DD_DEFAULT_STYLE  |
                        wx.DD_DIR_MUST_EXIST
                )

            if dlg_eff.ShowModal() == wx.ID_OK:
                paths_eff = dlg_eff.GetPath()
                shutil.move(paths_eff, target_file_paths + '\\effusion')

            dlg_eff.Destroy()

            dlg_pan = wx.DirDialog(
                self, message="Choose the Pancreas jpg file",
                style=wx.DD_DEFAULT_STYLE  |
                        wx.DD_DIR_MUST_EXIST
                )

            if dlg_pan.ShowModal() == wx.ID_OK:
                paths_pan = dlg_pan.GetPath()
                shutil.move(paths_pan, target_file_paths + '\\pancreas')

            dlg_pan.Destroy()

        self.Close(True)
        app = wx.App()
        frm = StartFrame(None)
        frm.Show()
        app.MainLoop()
    def OnEraseBack( self, event):
        dc = event.GetDC()
        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("./logo/blue_bkg3.jpg")
        bitmap = scale_bitmap(bmp, 500, 350)
        dc.DrawBitmap(bitmap, 0, 0)

class Result_Frame( gui.Result_Frame ):
    def __init__( self, parent ):
        gui.Result_Frame.__init__ ( self, parent, case_number)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
    def OnClick_pancreas(self, event):
        OnClick_pancreas_menu(self, event)
    def OnClick_effusion(self, event):
        OnClick_effusion_menu(self, event)
    def OnClick_pancreas_compara(self, event):
        OnClick_pancreas_compara_menu(self, event)
    def OnClick_effusion_compara(self, event):
        OnClick_effusion_compara_menu(self, event)
    def OnClick_cut_pancreas(self, event):
        OnClick_cut_pancreas_menu(self, event)
    def OnClick_cut_effusion(self, event):
        OnClick_cut_effusion_menu(self, event)
    def CTSI_Score(self, event):
        CTSI_Score_menu(self, event)
    def Start_page(self, event):
        Start_menu(self, event)
    def FReport_page(self, event):
        FReport_menu(self, event)
    def Home_page(self, event):
        Home_menu(self, event)
    def OnEraseBack( self, event):
        dc = event.GetDC()
        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap(".\\button_bmp\\PNG\\background.png")
        bitmap = scale_bitmap(bmp, 1300, 800)
        dc.DrawBitmap(bitmap, 0, 0)

class MyFrame ( ctsi_gui.MyFrame ):

    def __init__( self, parent ):
        img_num = []
        ctsi_gui.MyFrame.__init__ ( self, parent, case_number, detection_type, jpg_file)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

    def imgs(self,img_num):
        path1 = "../../Data/" + case_number+ "/" + detection_type + "/" + detection_type + "_ove/"
        for fn in os.listdir(path1):
            if fn != '@eaDir' and fn.split('.')[1] == 'jpg':
                img_num.append(fn)
        img_num.sort()
    def txt_list(self,txt_num):
        path2 = "../../Data/" + case_number+ "/" + detection_type + "/" + detection_type + "_txt/"
        for fn in os.listdir(path2):
            if fn.endswith('.txt'):
                txt_num.append(fn)
        txt_num.sort()
    def next_picture(self, event,num,txt):
        global i
        if i ==len(num)-1:
            i = -1
        image1 = wx.Image("../../Data/" + case_number + "/" + detection_type + "/" + jpg_file +  "/" + str(num[i+1]))
        image2 = wx.Image("../../Data/" + case_number + "/" + detection_type + "/" + detection_type + "_ove/" + str(num[i+1]))
        #更新GridBagSizer()的self.bmp2
        image1.Rescale(300,300)
        image2.Rescale(300,300)

        mypic1 = image1.ConvertToBitmap()
        self.bitmap_no.SetBitmap(wx.BitmapFromImage(mypic1))
        mypic2 = image2.ConvertToBitmap()
        self.bitmap_yes.SetBitmap(wx.BitmapFromImage(mypic2))

        self.ctsi_list_Box.Clear()
        paths = '../../Data/' + case_number + '/' + detection_type + '/' + detection_type + '_txt/' + str(txt[i+1])
        fopen =  open(paths, 'r', encoding="ANSI")
        for line in fopen.readlines():
            self.ctsi_list_Box.Append(line)
        i = i + 1
    def last_picture(self, event,num,txt):
        global i
        if i ==0:
            i = len(num)
        image1 = wx.Image("../../Data/" + case_number + "/" + detection_type + "/" + jpg_file +  "/" + str(num[i-1]))
        image2 = wx.Image("../../Data/" + case_number + "/" + detection_type + "/" + detection_type + "_ove/" + str(num[i-1]))
        #更新GridBagSizer()的self.bmp2
        image1.Rescale(300,300)
        image2.Rescale(300,300)

        mypic1 = image1.ConvertToBitmap()
        self.bitmap_no.SetBitmap(wx.BitmapFromImage(mypic1))
        mypic2 = image2.ConvertToBitmap()
        self.bitmap_yes.SetBitmap(wx.BitmapFromImage(mypic2))
        #def Onclick_back( self, event ):
        #	self.Close(True)
        #	frm = Bounding_Box_Show_Frame(None)
        #	frm.Show()
        #	app.MainLoop()
        self.ctsi_list_Box.Clear()
        paths = '../../Data/' + case_number + '/' + detection_type + '/' + detection_type + '_txt/' + str(txt[i-1])
        fopen =  open(paths, 'r', encoding="ANSI")
        for line in fopen.readlines():
            self.ctsi_list_Box.Append(line)
        i = i - 1
    def OnClick_pancreas(self, event):
        OnClick_pancreas_menu(self, event)
    def OnClick_effusion(self, event):
        OnClick_effusion_menu(self, event)
    def OnClick_pancreas_compara(self, event):
        OnClick_pancreas_compara_menu(self, event)
    def OnClick_effusion_compara(self, event):
        OnClick_effusion_compara_menu(self, event)
    def OnClick_cut_pancreas(self, event):
        OnClick_cut_pancreas_menu(self, event)
    def OnClick_cut_effusion(self, event):
        OnClick_cut_effusion_menu(self, event)
    def CTSI_Score(self, event):
        CTSI_Score_menu(self, event)
    def Start_page(self, event):
        Start_menu(self, event)
    def FReport_page(self, event):
        FReport_menu(self, event)
    def Home_page(self, event):
        Home_menu(self, event)
    def OnEraseBack( self, event):
        dc = event.GetDC()
        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap(".\\button_bmp\\PNG\\background.png")
        bitmap = scale_bitmap(bmp, 1300, 800)
        dc.DrawBitmap(bitmap, 0, 0)
    def __del__( self ):
        pass

minx=0
miny=0
maxx=100
maxy=100

class Bnd_editFrame ( bnd_gui.Bnd_edit ):
    def __init__( self, parent ):
        bnd_gui.Bnd_edit.__init__ ( self, parent, case_number, detection_type)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
    def imgs(self,img_num):
        path = "../../Data/" + case_number + "/" + detection_type + "/" + detection_type +"_bnd/"
        for fn in os.listdir(path):
            if fn != '@eaDir' and fn.split('.')[1] == 'jpg':
                img_num.append(fn)
        img_num.sort()
    def next_picture(self, event,num):
        self.staticText_case_img_num.SetBackgroundColour(bk_color)
        global i
        if i ==len(num)-1:
            i = -1
        image = wx.Image("../../Data/" + case_number + "/" + detection_type + "/testmodel/" + "/" + case_number + "/" + str(num[i+1]))
        self.staticText_case_img_num.SetLabel("案例號碼:"+case_number+"  圖片代號:"+ num[i+1])
        #更新GridBagSizer()的self.bmp2
        i = i + 1
        mypic = image.ConvertToBitmap()
        self.bitmap_middle.SetBitmap(wx.BitmapFromImage(mypic))
    def last_picture(self, event,num):
        self.staticText_case_img_num.SetBackgroundColour(bk_color)
        global i
        if i ==0:
            i = len(num)
        image = wx.Image("../../Data/" + case_number + "/" + detection_type + "/testmodel/" + "/" + case_number + "/" + str(num[i-1]))
        self.staticText_case_img_num.SetLabel("案例號碼:"+case_number+"  圖片代號:"+ num[i-1])
        #更新GridBagSizer()的self.bmp2
        i = i - 1
        mypic = image.ConvertToBitmap()
        self.bitmap_middle.SetBitmap(wx.BitmapFromImage(mypic))
    def Onsavebtn(self, event, num, anchor):
        global i
        global case_number
        if len(anchor)>0:
            creat_xml(anchor,num[i],case_number)
            enhence_show(anchor,num[i])
        self.Close(True)
        app = wx.App()
        frm = Bnd_Frame(None)
        frm.Show()
        app.MainLoop()

    def OnClick_pancreas(self, event):
        OnClick_pancreas_menu(self, event)
    def OnClick_effusion(self, event):
        OnClick_effusion_menu(self, event)
    def OnClick_pancreas_compara(self, event):
        OnClick_pancreas_compara_menu(self, event)
    def OnClick_effusion_compara(self, event):
        OnClick_effusion_compara_menu(self, event)
    def OnClick_cut_pancreas(self, event):
        OnClick_cut_pancreas_menu(self, event)
    def OnClick_cut_effusion(self, event):
        OnClick_cut_effusion_menu(self, event)
    def CTSI_Score(self, event):
        CTSI_Score_menu(self, event)
    def Start_page(self, event):
        Start_menu(self, event)
    def FReport_page(self, event):
        FReport_menu(self, event)
    def Home_page(self, event):
        Home_menu(self, event)
    def OnClick_show_bnd(self, event):
        self.staticText_case_img_num.SetBackgroundColour(bk_color)
        global i
        selName = self.ctsi_list_Box.GetStringSelection()
        selName = selName.replace("xml", "jpg")
        image = wx.Image("../../Data/" + case_number + "/" + detection_type  + "/testmodel/" + "/" + case_number + "/" + selName)
        self.staticText_case_img_num.SetLabel("案例號碼:"+case_number+"  圖片代號:"+ selName)
        #更新GridBagSizer()的self.bmp2
        mypic = image.ConvertToBitmap()
        self.bitmap_middle.SetBitmap(wx.BitmapFromImage(mypic))
        i = int(selName.split("-00")[2].split(".jpg")[0])-1
    def OnPaint(self, event,anchor_position):#畫修改框
        dc = wx.ClientDC(self.bitmap_middle)
        brush = wx.Brush("white")
        dc.SetBackground(brush)
        #dc.Clear()

        pen = wx.Pen(wx.Colour(255,0,0) ,style=wx.SOLID)
        dc.SetPen(pen)
        dc.DrawLine(minx,miny,maxx,miny)
        dc.DrawLine(maxx,miny,maxx,maxy)
        dc.DrawLine(maxx,maxy,minx,maxy)
        dc.DrawLine(minx,maxy,minx,miny)
        anchor_position.append([minx,miny,maxx,maxy])
        print(anchor_position)
    def Onminpoint(self, event):#左鍵按下事件
        global minx,miny
        pos=event.GetPosition()
        minx = pos.x
        miny = pos.y
    def Onmaxpoint(self, event,anchor):#左鍵放開事件
        pos=event.GetPosition()
        global maxx,maxy,minx,miny
        maxx = pos.x
        maxy = pos.y
        self.OnPaint( event,anchor)

class Bnd_Frame ( bnd_gui.Bnd ):

    def __init__( self, parent ):
        bnd_gui.Bnd.__init__ ( self, parent, case_number, detection_type)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

    def imgs(self,img_num):
        path = "../../Data/" + case_number + "/" + detection_type + "/" + detection_type +"_bnd/"
        for fn in os.listdir(path):
            if fn != '@eaDir' and fn.split('.')[1] == 'jpg':
                img_num.append(fn)
        img_num.sort()
    def next_picture(self, event,num):
        self.staticText_case_img_num.SetBackgroundColour(bk_color)

        global i
        if i ==len(num)-1:
            i = -1
        image = wx.Image('../../Data/' + case_number +'/' + detection_type + '/' + detection_type + '_bnd/' + str(num[i+1]))
        self.staticText_case_img_num.SetLabel("案例號碼:"+case_number+"  圖片代號:"+ num[i+1])
        #更新GridBagSizer()的self.bmp2
        i = i + 1
        mypic = image.ConvertToBitmap()
        self.bitmap_middle.SetBitmap(wx.BitmapFromImage(mypic))
    def last_picture(self, event,num):
        self.staticText_case_img_num.SetBackgroundColour(bk_color)

        global i
        if i ==0:
            i = len(num)
        image = wx.Image("../../Data/" + case_number + "/" + detection_type + "/" + detection_type +"_bnd/" + str(num[i-1]))
        self.staticText_case_img_num.SetLabel("案例號碼:"+case_number+"  圖片代號:"+ num[i-1])
        #更新GridBagSizer()的self.bmp2
        i = i - 1
        mypic = image.ConvertToBitmap()
        self.bitmap_middle.SetBitmap(wx.BitmapFromImage(mypic))
    def Oneditbtn(self, event, num):
        import editimg
        editimg.edit_main(num,case_number,detection_type,i)
    def OnClick_pancreas(self, event):
        OnClick_pancreas_menu(self, event)
    def OnClick_effusion(self, event):
        OnClick_effusion_menu(self, event)
    def OnClick_pancreas_compara(self, event):
        OnClick_pancreas_compara_menu(self, event)
    def OnClick_effusion_compara(self, event):
        OnClick_effusion_compara_menu(self, event)
    def OnClick_cut_pancreas(self, event):
        OnClick_cut_pancreas_menu(self, event)
    def OnClick_cut_effusion(self, event):
        OnClick_cut_effusion_menu(self, event)
    def CTSI_Score(self, event):
        CTSI_Score_menu(self, event)
    def Start_page(self, event):
        Start_menu(self, event)
    def FReport_page(self, event):
        FReport_menu(self, event)
    def Home_page(self, event):
        Home_menu(self, event)
    def OnClick_show_bnd(self, event):
        self.staticText_case_img_num.SetBackgroundColour(bk_color)
        global i
        selName = self.ctsi_list_Box.GetStringSelection()
        selName = selName.replace("xml", "jpg")
        image = wx.Image('../../Data/' + case_number +'/' + detection_type + '/' + detection_type + '_bnd/' + selName)
        self.staticText_case_img_num.SetLabel("案例號碼:"+case_number+"  圖片代號:"+ selName)
        #更新GridBagSizer()的self.bmp2
        mypic = image.ConvertToBitmap()
        self.bitmap_middle.SetBitmap(wx.BitmapFromImage(mypic))
        i = int(selName.split("-00")[2].split(".jpg")[0])-1

###########################################################################
## Class Segmentation_Analysis
###########################################################################
class Segmentation_Analysis ( APP1.Segmentation_Analysis ):

    def __init__( self, parent ):
        APP1.Segmentation_Analysis.__init__ ( self, parent, case_number, detection_type)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

    def OnClick_pancreas(self, event):
        OnClick_pancreas_menu(self, event)
    def OnClick_effusion(self, event):
        OnClick_effusion_menu(self, event)
    def OnClick_pancreas_compara(self, event):
        OnClick_pancreas_compara_menu(self, event)
    def OnClick_effusion_compara(self, event):
        OnClick_effusion_compara_menu(self, event)
    def OnClick_cut_pancreas(self, event):
        OnClick_cut_pancreas_menu(self, event)
    def OnClick_cut_effusion(self, event):
        OnClick_cut_effusion_menu(self, event)
    def CTSI_Score(self, event):
        CTSI_Score_menu(self, event)
    def Start_page(self, event):
        Start_menu(self, event)
    def FReport_page(self, event):
        FReport_menu(self, event)
    def Home_page(self, event):
        Home_menu(self, event)
    def __del__( self ):
        pass

###########################################################################
## Class CTSI_Analysis
###########################################################################

class CTSI_Analysis ( APP1.CTSI_Analysis ):

    def __init__( self, parent ):
        APP1.CTSI_Analysis.__init__ ( self, parent, case_number)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)
    def img_set( self, img_num, jpg_save , case_number , jpg_save_file):
        tmp_path = "../../Data/" + case_number + "/effusion"
        path_eff = tmp_path + "/effusion_ove/"
        eff_num = os.listdir(path_eff)
        for fn in eff_num:
            if fn.endswith('.jpg'):
                img_num.append(fn)

        if len(img_num) == 0:
            tmp_list = os.listdir(tmp_path)
            for fn in tmp_list:
                if fn.endswith('_jpg'):
                    jpg_save_file.append(fn)

            path_N_eff = tmp_path + '/' + jpg_save_file[0]

            eff_jpg = os.listdir(path_N_eff)
            for fn in eff_jpg:
                if fn.endswith('.jpg'):
                    jpg_save.append(fn)

    def read_txt( self, content_list, case_number):
        obj_file = "../../Data/" + case_number + "/CTSI/Effusion_count.txt"
        f =  open(obj_file,'r')
        line = f.readlines()
        for fn in line:
            content_list.append(fn)

    def Onclick_btn_next(self, event, num, jpg, j_file, content):
        self.txt_img_num.SetBackgroundColour(bk_color)
        self.txt_content_1.SetBackgroundColour(bk_color)
        self.txt_content_2.SetBackgroundColour(bk_color)
        global i
        if len(num) == 0:
            if i == len(jpg)-1:
                i = -1
            image1 = wx.Image("../../Data/" + case_number + "/effusion/" + j_file[0]  +  "/" + str(jpg[i+1]))
            self.txt_img_num.SetLabel(jpg[i+1])
            self.txt_content_1.SetLabel(content[0])
            self.txt_content_2.SetLabel(label=content[1])

        else:
            if i ==len(num)-1:
                i = -1
            image1 = wx.Image("../../Data/" + case_number + "/effusion/effusion_ove" +  "/" + str(num[i+1]))
            j = (i+1)*2
            self.txt_img_num.SetLabel(num[i+1])
            self.txt_content_1.SetLabel(content[j])
            self.txt_content_2.SetLabel(content[j+1])

        #更新GridBagSizer()的self.bmp2
        i = i + 1
        image1.Rescale(255,255)
        mypic1 = image1.ConvertToBitmap()
        self.bitmap_no.SetBitmap(wx.BitmapFromImage(mypic1))

    def Onclick_btn_last(self, event, num, jpg, j_file, content):
        self.txt_img_num.SetBackgroundColour(bk_color)
        self.txt_content_1.SetBackgroundColour(bk_color)
        self.txt_content_2.SetBackgroundColour(bk_color)
        global i
        if len(num) == 0:
            if i ==0:
                i = len(jpg)
            image = wx.Image("../../Data/" + case_number + "/effusion/" + j_file[0]  +  "/" + str(jpg[i-1]))
            self.txt_img_num.SetLabel(jpg[i-1])
            self.txt_content_1.SetLabel(content[0])
            self.txt_content_2.SetLabel(content[1])
        else:
            if i ==0:
                i = len(num)
            image = wx.Image("../../Data/" + case_number + "/effusion/effusion_ove"  +  "/" + str(num[i-1]))
            j = (i-1)*2
            self.txt_img_num.SetLabel(num[i-1])
            self.txt_content_1.SetLabel(content[j])
            self.txt_content_2.SetLabel(content[j+1])
        #更新GridBagSizer()的self.bmp2
        i = i - 1
        image.Rescale(255,255)
        mypic1 = image.ConvertToBitmap()
        self.bitmap_no.SetBitmap(wx.BitmapFromImage(mypic1))

    def OnClick_pancreas(self, event):
        OnClick_pancreas_menu(self, event)
    def OnClick_effusion(self, event):
        OnClick_effusion_menu(self, event)
    def OnClick_pancreas_compara(self, event):
        OnClick_pancreas_compara_menu(self, event)
    def OnClick_effusion_compara(self, event):
        OnClick_effusion_compara_menu(self, event)
    def OnClick_cut_pancreas(self, event):
        OnClick_cut_pancreas_menu(self, event)
    def OnClick_cut_effusion(self, event):
        OnClick_cut_effusion_menu(self, event)
    def CTSI_Score(self, event):
        CTSI_Score_menu(self, event)
    def Start_page(self, event):
        Start_menu(self, event)
    def FReport_page(self, event):
        FReport_menu(self, event)
    def Home_page(self, event):
        Home_menu(self, event)

    def __del__( self ):

        pass

class Second_Frame ( test.Second_Frame ):

    def __init__( self, parent ):
        test.Second_Frame.__init__ ( self, parent, case_number)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

    def __del__( self ):
        pass

	# Virtual event handlers, overide them in your derived class
    def Onclick_processing( self, event):
        self.Close(True)
        frm = WaitFrame(None)	#放空白的Frame
        frm.Show()
        #這裡我不確定app.MainLoop()需不需要放最後面，它的功能是讓Application的主事件循環
    #	self.Close(True)
    #	frm = run_yards(None) 	#放讀條的Frame
    #	frm.Show()
    #	app.MainLoop()

        #AI
        #sys.path.append(Nowpath + '\\..\\AI')
        #import AI
        #PATH_TO_DICOM_FILE= Nowpath + '\\..\\..\\Data\\'+ case_number + "\\" + detection_type + "\\testmodel\\" + case_number
        #print(PATH_TO_DICOM_FILE)
        #AI.convert2jpg(PATH_TO_DICOM_FILE)

        #AI.image_inference()

        print('Inference Done... ', end='\n')

        #Deal
        #sys.path.append(Nowpath + '\\..\\Deal')

        import Img_processing_def
        #Img_processing_def.Img_processing_def(case_number,'pancreas')
        #Img_processing_def.Img_processing_def(case_number,'effusion')

        print('Img processing Done... \n')

        #sys.path.append(Nowpath + '\\..\\Deal')
        #import CTSI_def
        #CTSI_def.CTSI_def(case_number)
        #print('CTSI Done...\n')

        #Path
        #sys.path.append(Nowpath + '\\..\\Path')

        #import straightLine
        #straightLine.straightLine(case_number)
        print('The Best Path Done... \n')

        app.MainLoop()

    def Onclick_result( self, event):
        self.Close(True)
        frm = Result_Frame(None)	#放空白的Frame
        frm.Show()
        app.MainLoop()

class WaitFrame (wx.Frame):

    def __init__(self, parent):
        gui.init2(self, parent)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

        self.SetSizeHints( wx.DefaultSize, wx.DefaultSize )

        WaitbSizer = wx.BoxSizer( wx.VERTICAL )

        self.Waitpanel = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
        WaitbSizer_bg_panel = wx.BoxSizer( wx.VERTICAL )

        self.m_staticText = wx.StaticText( self.Waitpanel, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
        self.m_staticText.Wrap( -1 )

        WaitbSizer_bg_panel.Add( self.m_staticText, 0, wx.ALIGN_CENTER|wx.TOP, 3 )

        self.first_staticText = TransparentText( self.Waitpanel, wx.ID_ANY, label="AI辨識 . . . . . . .")
        self.first_staticText.Wrap( -1 )

        WaitbSizer_bg_panel.Add( self.first_staticText, 0, wx.ALIGN_CENTER|wx.ALL, 5 )

        self.second_staticText = TransparentText( self.Waitpanel, wx.ID_ANY, label="影像處理 . . . . . ." )
        self.second_staticText.Wrap( -1 )

        WaitbSizer_bg_panel.Add( self.second_staticText, 0, wx.ALIGN_CENTER|wx.ALL, 5 )

        self.third_staticText = TransparentText( self.Waitpanel, wx.ID_ANY, label="CTSI計算 . . . . ." )
        self.third_staticText.Wrap( -1 )

        WaitbSizer_bg_panel.Add( self.third_staticText, 0, wx.ALIGN_CENTER|wx.ALL, 5 )

        self.forth_staticText = TransparentText( self.Waitpanel, wx.ID_ANY, label="最佳路徑演算 . ." )
        self.forth_staticText.Wrap( -1 )

        WaitbSizer_bg_panel.Add( self.forth_staticText, 0, wx.ALIGN_CENTER|wx.ALL, 5 )

        self.Waitpanel.SetSizer( WaitbSizer_bg_panel )
        self.Waitpanel.Layout()
        WaitbSizer_bg_panel.Fit( self.Waitpanel )
        WaitbSizer.Add( self.Waitpanel, 1, wx.ALL|wx.EXPAND, 0 )

        self.gauge_count = 0
        self.panel_Gauge = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
        gauge_Sizer = wx.BoxSizer( wx.VERTICAL )

        self.gauge = wx.Gauge(self.panel_Gauge, range = 20, size = (250, 25), style =  wx.GA_HORIZONTAL)
        gauge_Sizer.Add( self.gauge, 0, wx.ALIGN_CENTER|wx.ALL, 5 )

        self.panel_Gauge.SetSizer( gauge_Sizer )
        self.panel_Gauge.Layout()
        gauge_Sizer.Fit( self.panel_Gauge )
        WaitbSizer.Add( self.panel_Gauge, 1, wx.ALL|wx.EXPAND, 0 )

        self.panel_button = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
        bSizer17 = wx.BoxSizer( wx.HORIZONTAL )

        AI_pic = wx.Image('.\\button_bmp\\PNG\\AI.png',wx.BITMAP_TYPE_PNG ).ConvertToBitmap()
        bmp_AI = scale_bitmap(AI_pic, 85, 35)
        self.AI_button = wx.BitmapButton( self.panel_button, wx.ID_ANY, bmp_AI, wx.DefaultPosition, wx.Size( 85,35 ), 0 )
        bSizer17.Add( self.AI_button, 0, wx.ALIGN_CENTER|wx.ALL, 18 )

        img_deal_pic = wx.Image('.\\button_bmp\\PNG\\img_deal.png',wx.BITMAP_TYPE_PNG ).ConvertToBitmap()
        bmp_img_deal = scale_bitmap(img_deal_pic, 85, 35)
        self.imgp_button = wx.BitmapButton( self.panel_button, wx.ID_ANY, bmp_img_deal, wx.DefaultPosition, wx.Size( 85,35 ), 0 )
        bSizer17.Add( self.imgp_button, 0, wx.ALIGN_CENTER|wx.ALL, 18 )

        CTSI_pic = wx.Image('.\\button_bmp\\PNG\\CTSI.png',wx.BITMAP_TYPE_PNG ).ConvertToBitmap()
        bmp_CTSI = scale_bitmap(CTSI_pic, 85, 38)
        self.CTSI_button = wx.BitmapButton( self.panel_button, wx.ID_ANY, bmp_CTSI, wx.DefaultPosition, wx.Size( 85,35 ), 0 )
        bSizer17.Add( self.CTSI_button, 0, wx.ALIGN_CENTER|wx.ALL, 18 )

        BP_pic = wx.Image('.\\button_bmp\\PNG\\best_paths.png',wx.BITMAP_TYPE_PNG ).ConvertToBitmap()
        bmp_BP = scale_bitmap(BP_pic, 85, 35)
        self.BP_button = wx.BitmapButton( self.panel_button, wx.ID_ANY, bmp_BP, wx.DefaultPosition, wx.Size( 85,35 ), 0 )
        bSizer17.Add( self.BP_button, 0, wx.ALIGN_CENTER|wx.ALL, 18 )
        '''
        self.AI_button = wx.Button( self.panel_button, wx.ID_ANY, u"AI", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer17.Add( self.AI_button, 0, wx.ALIGN_CENTER|wx.ALL, 22 )

        self.imgp_button = wx.Button( self.panel_button, wx.ID_ANY, u"影像分析", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer17.Add( self.imgp_button, 0, wx.ALIGN_CENTER|wx.ALL, 22 )

        self.CTSI_button = wx.Button( self.panel_button, wx.ID_ANY, u"CTSI", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer17.Add( self.CTSI_button, 0, wx.ALIGN_CENTER|wx.ALL, 22 )

        self.BP_button = wx.Button( self.panel_button, wx.ID_ANY, u"最佳路徑", wx.DefaultPosition, wx.DefaultSize, 0 )
        bSizer17.Add( self.BP_button, 0, wx.ALIGN_CENTER|wx.ALL, 22 )
        '''
        self.panel_button.SetSizer( bSizer17 )
        self.panel_button.Layout()
        bSizer17.Fit( self.panel_button )
        WaitbSizer.Add( self.panel_button, 1, wx.EXPAND |wx.ALL, 0 )

        self.SetSizer( WaitbSizer )
        self.Layout()

        self.Centre( wx.BOTH )

        #self.m_gauge4 = wx.Gauge(self.m_panel2, wx.ID_ANY, 1000,
        #                         (1000, 1000), wx.Size(1800, 20), wx.GA_HORIZONTAL)
        #if self.count >= 0:
        #    self.count = self.count + 1
        #    if self.count >= 50:
        #        self.count = 0

        # self.m_gauge4.SetValue(self.count)
        #self.m_gauge4.Pulse()
        #bSizer31.Add(self.m_gauge4, 0, wx.ALL, 5)

        self.Centre(wx.BOTH)

        self.AI_button.Bind( wx.EVT_BUTTON, self.Onclick_ai )
        self.imgp_button.Bind( wx.EVT_BUTTON, self.Onclick_imgp )
        self.CTSI_button.Bind( wx.EVT_BUTTON, self.Onclick_ctsi )
        self.BP_button.Bind( wx.EVT_BUTTON, self.Onclick_bp )
        self.Waitpanel.Bind(wx.EVT_ERASE_BACKGROUND,self.OnEraseBack)
        self.panel_Gauge.Bind(wx.EVT_ERASE_BACKGROUND,self.OnEraseBack)
        self.panel_button.Bind(wx.EVT_ERASE_BACKGROUND,self.OnEraseBack)

    def OnEraseBack( self, event):
        dc = event.GetDC()
        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap("./logo/blue_bkg3.jpg")
        bitmap = scale_bitmap(bmp, 500, 300)
        dc.DrawBitmap(bitmap, 0, 0)

    def __del__(self):
        pass
    def OnClick_pancreas(self, event):
        OnClick_pancreas_menu(self, event)
    def OnClick_effusion(self, event):
        OnClick_effusion_menu(self, event)
    def OnClick_pancreas_compara(self, event):
        OnClick_pancreas_compara_menu(self, event)
    def OnClick_effusion_compara(self, event):
        OnClick_effusion_compara_menu(self, event)
    def OnClick_cut_pancreas(self, event):
        OnClick_cut_pancreas_menu(self, event)
    def OnClick_cut_effusion(self, event):
        OnClick_cut_effusion_menu(self, event)
    def CTSI_Score(self, event):
        CTSI_Score_menu(self, event)
    def Start_page(self, event):
        Start_menu(self, event)
    def FReport_page(self, event):
        FReport_menu(self, event)
    def Home_page(self, event):
        Home_menu(self, event)
    def Onclick_ai(self, event):
        #AI
        sys.path.append(Nowpath + '\\..\\AI')
        import AI
        PATH_TO_DICOM_FILE= Nowpath + '\\..\\..\\Data\\'+ case_number + "\\" + case_number
        #print(PATH_TO_DICOM_FILE)

        AI.init_para(case_number,"pancreas")
        self.gauge.SetValue(0)
        AI.convert2jpg(PATH_TO_DICOM_FILE)
        self.gauge_count = self.gauge_count + 1
        self.gauge.SetValue(self.gauge_count)
        AI.image_inference(self.gauge_count, self.gauge)
        print('Inference Done... ', end='\n')
        AI.init_para(case_number,"effusion")
        self.gauge.SetValue(0)
        AI.convert2jpg(PATH_TO_DICOM_FILE)
        self.gauge_count = self.gauge_count + 1
        self.gauge.SetValue(self.gauge_count)
        AI.image_inference(self.gauge_count, self.gauge)
        print('Inference Done... ', end='\n')
        self.first_staticText.SetForegroundColour(RED)
        self.first_staticText.SetLabel("AI辨識完畢!")
    def Onclick_imgp(self, event):
        #Deal
        sys.path.append(Nowpath + '\\..\\Deal')

        import Img_processing_def

        self.gauge.SetValue(0)
        Img_processing_def.Img_processing_def(case_number,'pancreas', self.gauge_count, self.gauge)
        Img_processing_def.Img_processing_def(case_number,'effusion', self.gauge_count, self.gauge)

        #print('Img processing Done... \n')
        self.second_staticText.SetForegroundColour(RED)
        self.second_staticText.SetLabel("影像處理完畢!")
    def Onclick_ctsi(self, event):
        sys.path.append(Nowpath + '\\..\\Deal')
        import CTSI_def
        CTSI_def.CTSI_def(case_number)

        self.gauge.SetValue(0)
        self.gauge_count = self.gauge_count + 1
        self.gauge.SetValue(self.gauge_count)
        #print('CTSI Done...\n')
        self.third_staticText.SetForegroundColour(RED)
        self.third_staticText.SetLabel("CTSI計算完畢!")

    def Onclick_bp(self, event):
        #Path
        sys.path.append(Nowpath + '\\..\\Path')

        import straightLine

        self.gauge.SetValue(0)
        straightLine.straightLine(case_number, self.gauge_count, self.gauge)
        #print('The Best Path Done... \n')
        self.forth_staticText.SetForegroundColour(RED)
        self.forth_staticText.SetLabel("最佳路徑演算完畢!")

class FinalReport (gui.StartFrame):

    def __init__(self, parent):
        final_r.FinalReport.__init__( self, parent)
        icon = wx.Icon(app_logo, wx.BITMAP_TYPE_ICO)
        self.SetIcon(icon)

    def OnEraseBack_pic( self, event , pic_path, W, H):
        dc = event.GetDC()
        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap(pic_path)
        bitmap = scale_bitmap(bmp, W, H)
        dc.DrawBitmap(bitmap, 0, 0)

    def OnEraseBack( self, event):
        dc = event.GetDC()
        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()
        bmp = wx.Bitmap(".\\button_bmp\\PNG\\background.png")
        bitmap = scale_bitmap(bmp, 1300, 800)
        dc.DrawBitmap(bitmap, 0, 0)

    def on_resize(self, event):
        self.panel_size = list(self.GetSize())
        # 设置表格的大小
        if self.panel_size[1] > len(self.report_list) * 50 + 50:
            # 设置列的宽度:面板大小减去第一列的固定长度/一共的列数
            grid_column_size = (self.panel_size[0] - 120) // len(self.col_label_list)
            grid_height = len(self.report_list) * 50 + 50
        else:
            # 行数超过面板的的大小需要上下滚动，列宽需要设置小一点
            grid_column_size = (self.panel_size[0] - 135) // len(self.col_label_list)
            grid_height = self.panel_size[1] - 120
        self.gridTable.SetColSizes(wx.grid.GridSizesInfo(grid_column_size, []))
        self.gridTable.SetSize((self.panel_size[0] - 30, grid_height))
        event.Skip()

    def left_click_function(self, event):
        # 表格当前点击的行和列
        click_col_index = event.GetCol()
        click_row_index = event.GetRow()
        if click_col_index == 1:
            # 点击表格的选择时的处理事件，模拟表格中的按钮
            if click_row_index == 0:
                img = cv.imread('../../Data/'+case_number+'/F1Score/F1_Score_pancreas.jpg')
                cv.imshow('AI_pan Result', img)
            elif click_row_index == 1:
                img = cv.imread('../../Data/'+case_number+'/F1Score/F1_Score_effusion.jpg')
                cv.imshow('AI_eff Result', img)
            elif click_row_index == 2:
                img = cv.imread("../../Data/"+case_number+"/pancreas/pancreas_seg/segementation_chart.png")
                cv.imshow('Seg_pan Result', img)
            elif click_row_index == 3:
                img = cv.imread("../../Data/"+case_number+"/effusion/effusion_seg/segementation_chart.png")
                cv.imshow('Seg_eff Result', img)
            elif click_row_index == 4:
                img = cv.imread("../../Data/"+case_number+"/CTSI/CTSI_chart.png")
                cv.imshow('CTSI Score', img)
            elif click_row_index == 5:
                img = cv.imread("../../Data/"+case_number+"/path/score/path_img.png")
                cv.imshow('Path Score', img)

    '''
        #elif click_col_index == 0:
        #    self._handle_click_check_box(click_row_index)
            # 点击第0列的选中的操作

    def _handle_click_check_box(self, click_row_index):
        if int(self.gridTable.GetCellValue(click_row_index, 0)):
            self.gridTable.SetCellValue(click_row_index, 0, '0')
        else:
            self.gridTable.SetCellValue(click_row_index, 0, '1')
    '''

    def get_report_list(self, start_index, show_count):
        # 清空表格數據重新顯示
        self.gridTable.ClearGrid()
        # 獲取表格的行数
        #grid_row_number = self.gridTable.GetNumberRows() - 1
        # 清除表格的行
        #self.gridTable.DeleteRows(0, grid_row_number)
        # 設置表格的最大大小
        #self.gridTable.SetMaxSize((1200, (grid_row_number + 2) * 50))
        # 數據(暫時寫mock數據)
        data = []
        f1_pan = open("../../Data/"+case_number+"/F1Score/f1out_pancreas.txt","r")
        data.append(f1_pan.read())
        f1_pan.close()
        f1_eff = open("../../Data/"+case_number+"/F1Score/f1out_effusion.txt","r")
        data.append(f1_eff.read())
        f1_eff.close()
        seg_pan = open("../../Data/"+case_number+"/pancreas/"+"pancreas_seg/Output_chart.txt")
        data.append(seg_pan.read())
        seg_pan.close()
        seg_eff = open("../../Data/"+case_number+"/effusion/"+"effusion_seg/Output_chart.txt")
        data.append(seg_eff.read())
        seg_eff.close()
        ctsi = open("../../Data/"+case_number+"/"+"CTSI/Output_chart.txt")
        data.append(ctsi.read())
        ctsi.close()
        path = open("../../Data/"+case_number+"/path/score/score.txt","r")
        data.append(path.read())
        path.close()

        self.report_list = [{"score": data[0], "graph": "點擊查看", "notes": "F1 Score越接近1,代表AI辨識越準確"},
                            {"score": data[1], "graph": "點擊查看", "notes": ""},
                            {"score": data[2], "graph": "點擊查看", "notes": "DICE:預測值重和關係。該值越接近1，表示重和度越高。\nVOE:體積誤差。越接近0，表示分割結果越準確。\nRVD:相對體積誤差。越接近0，表示分割效果越好。"},
                            {"score": data[3], "graph": "點擊查看", "notes": ""},
                            {"score": data[4], "graph": "點擊查看", "notes": "CTSI值高表示病情嚴重，反之亦然"},
                            {"score": data[5], "graph": "點擊查看", "notes": "長度:規畫路徑長度\n通過率:路徑上無障礙物的比例"}]
        #self.gridTable.AppendRows(len(self.report_list) - 1)
        for row in range(0, len(self.report_list)):
            for column in range(0, len(self.col_label_list)):
                report_list_item = self.report_list[row]
                # 處理從數據庫獲取的數據
                report_grid_dict = {
                    '0': report_list_item["score"],
                    '1': report_list_item["graph"],
                    '2': report_list_item["notes"]
                }
                # 將數據插入到第row行第column列
                self.gridTable.SetCellValue(row, column, str(report_grid_dict[str(column)]))
                # 根據结果修改表格的顯示颜色
                if report_list_item["notes"] == "最佳路徑評分":
                    self.gridTable.SetCellTextColour(row, 5, wx.Colour('#237804'))
                else:
                    self.gridTable.SetCellTextColour(row, 5, wx.Colour('#f5222d'))
                self.gridTable.SetCellTextColour(row, 6, wx.Colour('#2395f1'))
                self.gridTable.SetCellFont(row, 6, wx.Font(10, wx.FONTFAMILY_DEFAULT,
                                                           wx.FONTSTYLE_NORMAL,
                                                           wx.FONTWEIGHT_NORMAL, True))
                self.gridTable.SetCellValue(row, column, str(report_grid_dict[str(column)]))
    def OnClick_pancreas(self, event):
        OnClick_pancreas_menu(self, event)
    def OnClick_effusion(self, event):
        OnClick_effusion_menu(self, event)
    def OnClick_pancreas_compara(self, event):
        OnClick_pancreas_compara_menu(self, event)
    def OnClick_effusion_compara(self, event):
        OnClick_effusion_compara_menu(self, event)
    def OnClick_cut_pancreas(self, event):
        OnClick_cut_pancreas_menu(self, event)
    def OnClick_cut_effusion(self, event):
        OnClick_cut_effusion_menu(self, event)
    def CTSI_Score(self, event):
        CTSI_Score_menu(self, event)
    def Start_page(self, event):
        Start_menu(self, event)
    def FReport_page(self, event):
        FReport_menu(self, event)
    def Home_page(self, event):
        Home_menu(self, event)

class TransparentText(wx.StaticText):#繼承了wx.Statictext的類，並對相應的方法進行重寫;
    def __init__(self, parent, id=wx.ID_ANY, label='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TRANSPARENT_WINDOW, name='transparenttext'):
        wx.StaticText.__init__(self, parent, id, label, pos, size, style, name)
        self.Bind(wx.EVT_PAINT, self.on_paint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None)
        self.Bind(wx.EVT_SIZE, self.on_size)
    def on_paint(self, event):#重寫on_paint可以對控件進行重寫重新構造形狀
        bdc = wx.PaintDC(self)
        dc = wx.GCDC(bdc)
        font_face = self.GetFont()
        font_color = self.GetForegroundColour()
        dc.SetFont(font_face)
        dc.SetTextForeground(font_color)
        dc.DrawText(self.GetLabel(), 0, 0)
    def on_size(self, event):
        self.Refresh()
        event.Skip()

if __name__ == '__main__':
    # When this module is run (not imported) then create the app, the
    # frame, show it, and start the event loop.
    app = wx.App()
    frm = First_Fram(None)
    frm.Show()
    app.MainLoop()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import tempfile

from scilpy.io.fetcher import get_testing_files_dict, fetch_data, get_home

# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['others.zip', 'commit_amico.zip'])
tmp_dir = tempfile.TemporaryDirectory()

def test_help_option(script_runner):
    ret = script_runner.run('scil_reshape_to_reference.py', '--help')
    assert ret.success

def test_execution_others(script_runner):
    os.chdir(os.path.expanduser(tmp_dir.name))
    in_img = os.path.join(get_home(), 'others', 't1_crop.nii.gz')
    in_ref = os.path.join(get_home(), 'others', 't1.nii.gz')
    ret = script_runner.run('scil_reshape_to_reference.py', in_img,
                            in_ref, 't1_reshape.nii.gz',
                            '--interpolation', 'nearest')
    assert ret.success

def test_execution_4D(script_runner):
    os.chdir(os.path.expanduser(tmp_dir.name))
    in_img = os.path.join(get_home(), 'commit_amico', 'dwi.nii.gz')
    in_ref = os.path.join(get_home(), 'others', 't1.nii.gz')
    ret = script_runner.run('scil_reshape_to_reference.py', in_img,
                            in_ref, 'dwi_reshape.nii.gz',
                            '--interpolation', 'nearest')
    assert ret.success


from multiprocessing import Process

import numpy as np
import os

import glob

from config import year, month, company_blacklist, title_key_blacklist, zhinengleibies
year_month=f'{year}{month:02}'

provinces=['北京','上海','广东','深圳','天津','重庆','江苏','浙江','四川','海南','福建','山东','江西','广西','安徽','河北','河南','湖北','湖南','陕西','山西','黑龙江','辽宁','吉林','云南','贵州','甘肃','内蒙古','宁夏','西藏','新疆','青海']
data_folder = '../../data/51jobs_{}/'.format(year_month)
back_folder = '../../data/51jobs_{}_b/'.format(year_month)

d = {}

counts = []
for zhinengleibie in list(zhinengleibies.values())[::-1]:
    count=0
    for province in provinces:
        files=glob.glob(f'{data_folder}{zhinengleibie}/{province}/*.*')
        count+=len(files)
    d[zhinengleibie]=count
    counts.append(count)
    #forglob(data_folder+"*")

orders = np.argsort(counts)

zhineng_splitters=[]
zhineng_splitters=[]

n_splitters = 4

for splitter_index in range(4):
    zhineng_splitters.append([])

for i in range(len(orders)):
    for splitter_index in range(4):
        if i % n_splitters == splitter_index:
            zhineng_splitters[splitter_index].append(znlbs[orders[i]])

znlbs=zhinengleibies.values()
znlbs = list(znlbs)


import blackjack_art as art
import random
import os

############### Our Blackjack House Rules #####################

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10 ,10]

def game():
    play_switch = input("\nDo you want to play a game of Blackjack? Type 'y' or 'n': ").lower()
    if play_switch == 'y':
        os.system('cls||clear')
        print(art.logo)
        deal_cards()
        game()
    elif play_switch == 'n':
        print("\nSee you another time! 💕")
        return
    else:
        print("\nPlease enter a valid input.")
        game()

def deal_cards(cards = cards):

    your_cards = [random.choice(cards), random.choice(cards)]
    computer_cards = [random.choice(cards), random.choice(cards)]

    print(f"\nYour cards: {your_cards}, current score: {sum(your_cards)}")
    print(f"Computer's 🖥 first card: {computer_cards[0]}")

    while sum(your_cards) < 21:
        redeal = input("\nType 'y' to get another card, type 'n' to pass: ").lower()

        if redeal == 'y':
            your_cards.append(random.choice(cards))
            print(f"\nYour cards: {your_cards}, current score: {sum(your_cards)}")
            print(f"Computer's 🖥 first card: {computer_cards[0]}")

        else:
            break

    while sum(computer_cards) < 17:
        computer_cards.append(random.choice(cards))
    final_hands(your_cards, computer_cards)

def final_hands(y_cards, c_cards):
        print(f"\nYour final hand: {y_cards}, final score: {sum(y_cards)}")
        print(f"Computer's final hand: {c_cards}, final score: {sum(c_cards)}")

        if (sum(c_cards) < 21 and sum(y_cards) < 21):
            if sum(c_cards) > sum(y_cards):
                print("Computer wins. 👿")
            elif sum(c_cards) < sum(y_cards):
                print("You win 😁")
            else:
                print("It's a draw. ⚔")

        elif (sum(y_cards) == 21):
            print("Win with a Blackjack 😎")

        elif (sum(y_cards) > 21):
            print("You overshot! You lose 👿")

        elif(sum(c_cards) > 21):
            print("Opponent went over. You win 😁")

        else:
            print("Computer wins with a Blackjack 👿")

### main body
game()
# deal_cards()


#文件的写入跟读取
'''
f=open('D:/文件写入.txt','w')
f.write('彭伟是真的帅')
f.write('\npeng')
f.write('\nwei')
f.write('\nzhen')
f.write('\nshuai')
#写入了之后必须要关闭

f.close()'''

def savefiles(myself,youself,count):
    boy_name = 'D:/boy' + str(count) + '.txt'
    boy_list = open(boy_name, 'w')
    boy_list.writelines(myself)
    gril_name = 'D:/gril' + str(count) + '.txt'
    gril_list = open(gril_name, 'w', encoding='UTF-8')
    gril_list.writelines(youself)
    boy_list.close()
    gril_list.close()

f=open('D:/文件写入.txt','r',encoding='UTF-8')
myself=[]
youself=[]
count=1
for each in f:
    if each[:6]!='======':
        (role,each_line)=each.split('：',1)
        if role=='彭伟':
            myself.append(each_line)
        if role=='王祝':
            youself.append(each_line)
    else:
        #创建文件，分别保存
        savefiles(myself, youself, count)
        count += 1
        myself = []
        youself = []

savefiles(myself,youself,count)

#0代表从哪开始截取到10字符，seek（）这个方法表示在文件中移动文件指针
#print(f.seek(20,0))
#read（）读取，不设置读取到哪默认读取全部，然后再使用read（）读取将读取空，因为第一个read（）
#已经读取到最后了。所以第二个只能读取空
#print(f.read())
#print(f.seek(0,0))
#print(f.read())


from selenium import webdriver
from skimage import io
import cairosvg
import os

option = webdriver.ChromeOptions()
option.add_argument('--headless')
#将下面的executable_path改为服务器上chrome的driver的地址
chrome_driver = webdriver.Chrome(executable_path=r"/home/painist/webdriver/chromedriver",options=option)
print("Chrome driver ready")

def cut(path : str) :
    img = io.imread(path)
    img2=img.sum(axis=2)
    (row,col)=img2.shape
    tempr0=0
    tempr1=0

    for r in range(0,row):
        if img2.sum(axis=1)[r]!=0:
            tempr0=r
            break

    for r in range(row-1,0,-1):
        if img2.sum(axis=1)[r]!=0:
            tempr1=r
            break

    new_img=img[tempr0:tempr1+1,:,0:4]
    io.imsave(path,new_img)

def getSVGStr(file_path:str) -> str:
    global chrome_driver
    chrome_driver.get(r"file://"+file_path)
    svg_text = chrome_driver.find_element_by_tag_name("SVG").get_attribute("outerHTML")
    svg_text = svg_text[0:5] + "xmlns=\"http://www.w3.org/2000/svg\" " + svg_text[5:]
    return svg_text

def SaveAsPng(file_path : str) -> str:
    print("Start process picture")
    file_name_no_root = file_path.split('/')[-1]
    save_path = os.path.join(os.getcwd(),'media/SVG',file_name_no_root)
    with open(save_path+".svg","wt", encoding='utf-8') as f:
        f.write(getSVGStr(file_path))
    cairosvg.svg2png(url=save_path+".svg",write_to=save_path+".png",scale=2.0)
    cut(save_path+".png")
    return "SVG/" + file_name_no_root + ".png"

if __name__ == "__main__":
    SaveAsPng(r"/home/painist/Test_Network/test_net/html/trans1.txt.html.res.html")


import requests

# Define the filename that contains the list of subdomains
filename = "subdomains.txt"

# List of common TLDs to check
tlds = ["com", "net", "org", "edu", "gov"]

# Open the file and read each subdomain
with open(filename) as file:
    for subdomain in file:
        # Remove any whitespace and newlines from the subdomain
        subdomain = subdomain.strip()

        # Make a request to each possible subdomain and TLD combination
        for tld in tlds:
            # Construct the URL using the subdomain and TLD
            url = f"http://{subdomain}.{tld}"
            # Make a request to the URL and print the response code
            response = requests.get(url)
            print(f"{url} - Response Code: {response.status_code}")


import logging
import sys
from random import shuffle

from gensim import utils
from gensim.models import Doc2Vec
from gensim.models.doc2vec import TaggedDocument

from preprocessor import ParseTweets

log = logging.getLogger()
log.setLevel(logging.DEBUG)

ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)
import numpy as np

class TaggedLineSentence(object):
    def __init__(self, sources):
        self.sources = sources

        flipped = {}

        # make sure that keys are unique
        for key, value in sources.items():
            if value not in flipped:
                flipped[value] = [key]
            else:
                raise Exception('Non-unique prefix encountered')

    def __iter__(self):
        for source, prefix in self.sources.items():
            with utils.smart_open(source) as fin:
                for item_no, line in enumerate(fin):
                    yield TaggedDocument(utils.to_unicode(line).split(), [prefix + '_%s' % item_no])

    def to_array(self):
        self.sentences = []
        for source, prefix in self.sources.items():
            with utils.smart_open(source) as fin:
                for item_no, line in enumerate(fin):
                    self.sentences.append(TaggedDocument(utils.to_unicode(line).split(), [prefix + '_%s' % item_no]))
        return self.sentences

    def sentences_perm(self):
        shuffle(self.sentences)
        return self.sentences

class Doc2vecLearner:
    """
    Učenje doc2vec modela
    """
    def __init__(self):
        self.model = None
        self.pt = ParseTweets()

    def learn_doc2vec(self, sources=None, model_save='model/twitter1.d2v', epoch=1, **kwargs):
        if sources is None:
            sources = {'data/corpus/all_english1.txt': 'DATA'}
        print(model_save)
        sentences = TaggedLineSentence(sources)
        model = Doc2Vec(workers=16, **kwargs)
        model.build_vocab(sentences.to_array())
        for num in range(epoch):
            print("EPOCH " + str(num))
            model.train(sentences.sentences_perm())

        print("Model save")
        model.save(model_save)
        self.model = model

    def load_model(self, model_file='model/twitter1.d2v'):
        self.model = Doc2Vec.load(model_file)

    def doctext_to_vec(self, doc):
        """
        Vrni vektorsko predstavitev dokumenta
        """
        return None if self.model is None else self.model.infer_vector(self.pt.tokenize_one_line(doc))

    def doctext_to_word2vec(self, doc):
        """
        Vrni povprečno vektrosko predstavitev besede v dokumentu
        """
        words, _ = self.pt.tokenize_one_line(doc, True)
        return np.mean(np.array([self.model[word] for word in words if word in self.model]), axis=0)

if __name__ == "__main__":
    a = Doc2vecLearner()
    a.learn_doc2vec(model_save='model/twitter2.d2v', epoch=10)


import pattern
import generator

if __name__ == '__main__':

    A = pattern.Checker(180, 30)
    b = A.draw()
    A.show()
#-------------------------------
    B=pattern.Circle(1000,100,(600,500))
    B.draw()
    B.show()
#-------------------------------
    A=pattern.Spectrum(100)
    A.draw()
    A.show()
#-------------------------------
    A = generator.ImageGenerator('data/exercise_data/', 'data/Labels.json', 5, [32, 32, 3], rotation=False, mirroring=False, shuffle=True)
    B = A.next()
    A.show(B)


import os.path
import sys

INTO_FILE = False
output = []

def fast_input(file_name):
    global INTO_FILE
    if os.path.isfile(file_name):
        INTO_FILE = True
        with open(file_name, 'r') as file:
            input_lines = file.readlines()
    else:
        INTO_FILE = False
        input_lines = sys.stdin.readlines()

    for line in input_lines:
        yield line

fast_input_reader = fast_input('input.txt')

def input():
    return fast_input_reader.__next__()

def print(line):
   output.append(str(line))

def solve():
    from collections import deque
    value1 = int(input().strip())
    value2 = int(input().strip())

    distances = [-1 for _ in range(10000)]

    def get_neighbors(value):
        neighbors = [int(str(value)[1:] + str(value)[0]), int(str(value)[-1] + str(value)[:-1])]
        if value % 10 > 1:
            neighbors.append(value - 1)
        if value // 1000 < 9:
            neighbors.append(value + 1000)
        return neighbors

    def get_inverted_neighbors(value):
        neighbors = [int(str(value)[1:] + str(value)[0]), int(str(value)[-1] + str(value)[:-1])]
        if value % 10 < 9:
            neighbors.append(value + 1)
        if value // 1000 > 1:
            neighbors.append(value - 1000)
        return neighbors

    queue = deque([(value1, 0)])

    while queue:
        value, d = queue.popleft()
        if distances[value] == -1:
            distances[value] = d
            for ngb in get_neighbors(value):
                queue.append((ngb, d+1))

    distance = distances[value2]
    cur_value = value2
    res = []
    while distance != -1:
        res.append(cur_value)
        distance -= 1
        for ngb in get_inverted_neighbors(cur_value):
            if distances[ngb] == distance:
                cur_value = ngb
    print(' '.join(map(str, res[::-1])))

def main():
    solve()
    answer = '\n'.join(output) + '\n'

    if INTO_FILE:
        with open('output.txt', 'w') as output_file:
            output_file.write(answer)
    else:
        sys.stdout.write(answer)

if __name__ == '__main__':
    main()


#encoding=utf8

import torch
from torch import nn

class Net(torch.nn.Module):
        def __init__(self, n_feature, nums_hidden, n_output):
            super(Net,self).__init__()

            self.backbone = self.make_layers(n_feature, nums_hidden)
            self.output_layer = torch.nn.Linear(nums_hidden[-1], n_output)
            self.output_act = nn.ReLU(True)
            self._init_params()

        def forward(self, x):
            x = self.backbone(x)
            out = self.output_layer(x)
            #out = self.output_act(out)
            return out

        def _init_params(self):
            for m in self.modules():
                if isinstance(m, nn.Linear):
                    nn.init.normal_(m.weight, mean=0.0, std=0.1)
                    if m.bias is not None:
                        nn.init.constant_(m.bias, 0)

        def make_layers(self, n_features, nums_hidden):
            layers = []
            for i, n_hidden in enumerate(nums_hidden):
                if i==0:
                    layers+=[torch.nn.Linear(n_features, n_hidden), nn.ReLU(inplace=True)]
                else:
                    layers+=[torch.nn.Linear(nums_hidden[i-1], n_hidden), nn.ReLU(inplace=True)]

            return nn.Sequential(*layers)

if __name__=="__main__":
    net = Net(5, [15,15], 1)
    x = torch.rand(3, 5)
    out = net(x)
    print(out.shape)
    print(out)


import socket
import logging
import time

logging.basicConfig(format = u'[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s]  %(message)s', level = logging.NOTSET)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto=socket.IPPROTO_TCP)

port = 10000
adresa = '198.10.0.2'
server_address = (adresa, port)
image = "poza_client.png"

try:
    logging.info('Handshake cu %s', str(server_address))
    sock.connect(server_address)
    file = open(image, 'rb')
    msg = file.read()

    while True:
        sock.sendall(msg)
        data = sock.recv(1000)

finally:
    logging.info('closing socket')
    sock.close()

2nd Year/RC - Computer Networks/Homework/Homework3/TCP_client.py


# Enter your code here. Read input from STDIN. Print output to STDOUT
T = int(input())
for i in range(T):
    n = int(input())
    blocks = list(map(int, input().split()))
    curblock = float('inf')
    s, e = 0 , len(blocks) - 1

    while e > s:
        blockleft = blocks[s]
        blockright = blocks[e]
        if blockleft >= blockright and blockleft <= curblock:
            s += 1
            curblock = blockleft
        elif blockleft < blockright and blockright <= curblock:
            e -= 1
            curblock = blockright

        else:
            print("No")
            break

    if s == e:
        print("Yes")


import discord, asyncpg, os, aiohttp, random
import core.utils.help as help
from discord.ext import commands

async def create_pool_postgres():
    bot.postgres = await asyncpg.create_pool(dsn=os.getenv("DATABASE_URL"))
    print("Successfully created to the Postgres Pool")

async def get_prefix(bot, message:discord.Message):
    prefix = bot.prefixes.get(message.guild.id)
    if prefix:
        return commands.when_mentioned_or(prefix)(bot, message)
    postgres = await bot.postgres.fetchval("SELECT prefix FROM prefixes WHERE guild_id=$1", message.guild.id)
    if postgres:
        prefix = bot.prefixes[message.guild.id] = postgres
    else:
        prefix = bot.prefixes[message.guild.id] = bot.default_prefix
    print(F"Cached {F'{prefix}/d' if not postgres else F'{postgres}/p'} | {message.guild.name} - {message.guild.id}")
    return commands.when_mentioned_or(prefix)(bot, message)

async def create_session_aiohttp():
    bot.session = aiohttp.ClientSession()
    print("Successfully created a AioHttp Session ")

class PemguBase(commands.AutoShardedBot):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.prefixes = {}
        self.default_prefix = ".m"
        self._commands = []
        for command in sorted(os.listdir("./core/commands/")):
            if command.endswith(".py"):
                self.load_extension(F"core.commands.{command[:-3]}")
                self._commands.append(command[:-3])
        self._events = []
        for event in sorted(os.listdir("./core/events/")):
            if event.endswith(".py"):
                self.load_extension(F"core.events.{event[:-3]}")
                self._events.append(event[:-3])
        self.load_extension("jishaku")
        os.environ["JISHAKU_NO_UNDERSCORE"] = "True"
        os.environ["JISHAKU_NO_DM_TRACEBACK"] = "True"
        self.afks = {}

    async def close(self):
        if not self.session.closed:
            await self.session.close()
        await super().close()

    @property
    def color(self):
        colors = [
            0x224585, 0x1D4E9A, 0x4879CE, 0x142966, 0x093C84,
            discord.Color.blue(),
            discord.Color.blurple(),
            discord.Color.brand_green(),
            discord.Color.brand_red(),
            discord.Color.dark_blue(),
            discord.Color.dark_gold(),
            discord.Color.dark_gray(),
            discord.Color.dark_green(),
            discord.Color.dark_grey(),
            discord.Color.dark_magenta(),
            discord.Color.dark_orange(),
            discord.Color.dark_purple(),
            discord.Color.dark_red(),
            discord.Color.dark_teal(),
            discord.Color.dark_theme(),
            discord.Color.darker_gray(),
            discord.Color.darker_grey(),
            discord.Color.default(),
            discord.Color.fuchsia(),
            discord.Color.gold(),
            discord.Color.green(),
            discord.Color.greyple(),
            discord.Color.light_gray(),
            discord.Color.light_grey(),
            discord.Color.lighter_gray(),
            discord.Color.lighter_grey(),
            discord.Color.magenta(),
            discord.Color.og_blurple(),
            discord.Color.orange(),
            discord.Color.purple(),
            discord.Color.random(),
            discord.Color.red(),
            discord.Color.teal(),
            discord.Color.yellow()
        ]
        color = random.choice(colors)
        return color

    @classmethod
    def trim(self, text: str, limit: int):
        text = text.strip()
        if len(text) > limit: return text[:limit-3] + "..."
        return text

bot = PemguBase(
    slash_commands=True,
    command_prefix=get_prefix,
    strip_after_prefix=True,
    case_insensitive=True,
    help_command=help.CustomHelp(),
    intents=discord.Intents.all(),
    allowed_mentions=discord.AllowedMentions.none()
)

@bot.check
async def blacklisted(ctx:commands.Context):
    blacklist = await bot.postgres.fetchval("SELECT user_id FROM blacklist WHERE user_id=$1", ctx.author.id)
    if not blacklist: return True
    raise commands.CheckAnyFailure

bot.loop.run_until_complete(create_pool_postgres())
bot.loop.create_task(create_session_aiohttp())
bot.run(os.getenv("TOKEN"))


import logging
import configparser
from pathlib import Path
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as bs
from .extractors import extract_products_information
from .utils import save_into_csv
from ...utils import set_query_string_parameter_from_url

config = configparser.RawConfigParser()
config.read('{}/scraper.properties'.format(Path().absolute()))
LIDER_SUPERMARKET = dict(config.items('LIDER_SUPERMARKET'))

MAX_PRODUCTS = int(LIDER_SUPERMARKET['max_products'])

def scrap(entries):
  print('Starting Líder supermarket')
  logging.info('Processing Líder supermarket')
  information = process_entries(entries)
  save_into_csv(information)
  print('Líder supermarket done...')
  logging.info('Ending Líder supermarket')

def process_entries(entries):
  result = list()
  for entry in entries:
    information = process_entry(entry)
    result.extend(information)
  return result

def process_entry(entry):
  result = list()
  url = set_query_string_parameter_from_url(entry, 'Nrpp', MAX_PRODUCTS)
  print('Processing: {}'.format(url))
  request = Request(url, headers = {'User-Agent': 'Mozilla/5.0'})
  try:
    response = urlopen(request).read()
    html = bs(response, 'html.parser')
    products_information = extract_products_information(html)
    result.extend(products_information)
  except Exception as e:
    logging.error('Failure processing: {}'.format(url))
    logging.error(e)
  return result


#!/usr/bin/env python3

"""
Directed Graph-Based Genome Assembler

This script reads FASTQ and PAF files, constructs a directed graph based on read sequences and alignment information,
and performs genome assembly to generate contigs (Small scale simplified example).

Usage:
    Modify the 'fastq_file_path' and 'paf_file_path' variables in the main function to specify the paths to your
    FASTQ and PAF files. Then, run the script to perform the genome assembly and obtain contigs.

Author: Lisan Eisinga
"""

import os
import networkx as nx
import pandas as pd
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqIO.QualityIO import FastqGeneralIterator
from Bio.SeqRecord import SeqRecord

def read_fastq_file(fastq_file):
    """
    Read a FASTQ file and return the read sequences as a dictionary with read IDs as keys.

    Parameters:
        fastq_file (str): Path to the FASTQ file.

    Returns:
        dict: A dictionary with read IDs as keys and read sequences as values.
    """
    if not os.path.exists(fastq_file):
        raise FileNotFoundError(f"FastQ data set {fastq_file} not found.")

    sequences = { }
    with open(fastq_file, "r", encoding="utf-8") as fastq:
        for title, seq, _ in FastqGeneralIterator(fastq):
            # Use the first element to avoid possible duplicated read_ids
            sequences[title.split()[0]] = seq

    return sequences

def parse_paf(paf_file):
    """
    Parse a PAF file and return the alignment information as a DataFrame.

    Parameters:
        paf_file (str): Path to the PAF file.

    Returns:
        pandas.DataFrame: DataFrame containing alignment information.
    """
    if not os.path.exists(paf_file):
        raise FileNotFoundError(f"PAF data set '{paf_file}' not found.")

    # Read the PAF data set into a DataFrame
    columns = [
        "query_id", "query_length", "query_start", "query_end", "strand",
        "target_id", "target_length", "target_start", "target_end",
        "alignment_block_length", "residue_matches", "mapping_quality"
    ]
    paf_df = pd.read_csv(paf_file, sep="\t", header=None, usecols=range(12), names=columns)
    return paf_df

def construct_directed_graph(sequences, paf_df):
    """
    Construct a directed graph based on read sequences and alignment information.

    Parameters:
        sequences (dict): Dictionary of read sequences with read IDs as keys.
        paf_df (pandas.DataFrame): DataFrame containing alignment information.

    Returns:
        networkx.DiGraph: Directed graph with reads as nodes and alignments as edges.
    """
    # Create an empty directed graph
    graph = nx.DiGraph()

    # Add nodes to the graph (each read sequence will be a node)
    for read_id, sequence in sequences.items():
        graph.add_node(read_id, sequence=sequence)

    # Add directed edges to the graph based on the PAF alignment data
    for _, row in paf_df.iterrows():
        query_id = row["query_id"]
        target_id = row["target_id"]

        # Add an edge from the query read to the target read
        graph.add_edge(query_id, target_id)

    return graph

def genome_assembly(directed_graph):
    """
    Perform genome assembly using the directed graph.

    Parameters:
        directed_graph: Directed graph for traversal.
    Returns:
        list: List of contigs (assembled sequences).
    """
    contigs = []

    def dfs(node, current_contig):
        if directed_graph.out_degree(node) == 0:
            # Reached the end of the contig, add it to the list of contigs
            contigs.append(current_contig + directed_graph.nodes[node]["sequence"])
        else:
            # Continue traversing the graph
            current_contig += directed_graph.nodes[node]["sequence"]
            for neighbor in directed_graph.successors(node):
                dfs(neighbor, current_contig)

    for start_node in directed_graph.nodes():
        if directed_graph.in_degree(start_node) > 0 and directed_graph.out_degree(start_node) == 0:
            # Start a new contig from this start node
            dfs(start_node, "")

    return contigs

def write_to_file(contigs, output_file):
    """
    Write contigs to a FASTA file.

    Parameters:
        contigs (list): List of contigs (assembled sequences).
        output_file (str): Path to the output FASTA file.
    """
    with open(output_file, "w") as fasta_file:
        for i, contig_sequence in enumerate(contigs, start=1):
            seq_record = SeqRecord(Seq(contig_sequence), id=f"Contig_{i}", description="")
            SeqIO.write(seq_record, fasta_file, "fasta")

def main():
    # Example usage:
    fastq_file_path = "../../Test_data/foo-reads.fq"
    paf_file_path = "../../Test_data/foo.paf"
    output_file_path = "../../Test_data/foo_directed_contigs.fq"

    sequences = read_fastq_file(fastq_file_path)
    paf_df = parse_paf(paf_file_path)
    directed_graph = construct_directed_graph(sequences, paf_df)
    assembled_contigs = genome_assembly(directed_graph)

    # Write contigs to a FASTA file
    write_to_file(assembled_contigs, output_file_path)

if __name__ == "__main__":
    main()


import os
import librosa
from matplotlib import pyplot as plt
import tqdm
import uuid

from preprocess import get_melspectrogram_db, transform_audio

def display_audio(filename, sr=48000):
  """display spectogram of a audio file in notebook"""
  s = get_melspectrogram_db(filename)
  plt.figure()
  plt.imshow(s)
  plt.show()

def generate_duplicate_wav(filepath, label, sr=48000, augmented=True, num_of_duplicates=300):
  """generate duplicates of input audio with the option to randomly augment/transform the audio"""
  for i in tqdm(range(num_of_duplicates), f"Generating wav duplicates of wavfile({filepath})..."):
    if augmented:
      audio = transform_audio(filepath)
    else:
      audio, _ = librosa.load(filepath, sr=sr)

    new_filename = f"{label}_{uuid.uuid4().hex}"
    new_filepath = os.path.join('data', label, new_filename)
    wavfile.write(new_filepath, sr, audio)


from collections import deque
from packet import Packet

class Link(object):
    # Conversion constants from Mbps to bytes per milisecond
    MBPS_TO_B_PER_MS = 131.072
    KB_TO_B = 1024

    def __init__(self, env, id, link_rate, link_delay,
                 buffer_size, end_points=None):
        """ Attributes:
                env:
                    SimPy environment in which everything resides.
                id:
                    id for this link
                link_rate:
                    link rate converted to bytes per milisecond
                link_delay:
                    link delay in ms
                buffer_size:
                    buffer size in bytes
                end_points:
                    a tuple of objects that the link connects to
                buffer:
                    a deque object which models the buffer queue
                buffer_used:
                    total size of the packets in the buffer
                transmitted_size:
                    size of packets transmitted since the last
                    statictics collection in Bytes
                busy:
                    event that indicates whether link is busy
        """
        self.env = env
        self.id = id
        # Link rate in bytes per milisecond
        self.link_rate =  Link.MBPS_TO_B_PER_MS * link_rate
        self.link_delay = link_delay
        # Buffer size in Bytes
        self.buffer_size = Link.KB_TO_B * buffer_size

        self.buffer = {}
        self.buffer_used = {}
        self.end_points = end_points
        if end_points:
            self.add_end_points(end_points)

        # Statistics collection
        self.packet_drop = 0
        self.transmitted_size = 0

        # reactive event and processes
        self.busy = env.event()
        env.process(self.transmit(env))

    def add_end_points(self, end_points):
        """ Mutator funciton to add end points to link """
        # ids of endpoints
        self.device_ids = [end_points[0].get_id(), end_points[1].get_id()]
        # Buffer on both sides
        self.buffer[self.device_ids[0]] = deque()
        self.buffer[self.device_ids[1]] = deque()
        # Buffer occupied on both sides
        self.buffer_used[self.device_ids[0]] = 0
        self.buffer_used[self.device_ids[1]] = 0

    def get_id(self):
        """ Function that returns link id. """
        return self.id

    def enqueue(self, packet, src_id):
        """ Function to handle incoming packets: drop the
            packet if buffer is full, otherwise enqueue the packet
            and wake up process()
        """
        size = packet.get_length()
        # Drop the packet if buffer is full
        if self.buffer_used[src_id] + size > self.buffer_size:
            self.packet_drop += 1
        else:
            self.buffer[src_id].append((packet, self.env.now))
            self.buffer_used[src_id] += size
            if not self.busy.triggered:
                # Wake up link
                self.busy.succeed()

    def buffer_empty(self):
        """ Helper function to check whether both buffers
            are empty.
        """
        return len(self.buffer[self.device_ids[0]]) + \
               len(self.buffer[self.device_ids[1]]) == 0

    def find_next_packet(self):
        """ Helper function that returns the index of the buffer from
            which the next packet should be transmitted
        """
        if len(self.buffer[self.device_ids[0]]) == 0:
            return 1
        elif len(self.buffer[self.device_ids[1]]) == 0:
            return 0
        else:
            # Peek the leftmost packets on both buffers
            packet_1, ts_1 = self.buffer[self.device_ids[0]][0]
            packet_2, ts_2 = self.buffer[self.device_ids[1]][0]
            if ts_1 <= ts_2:
                return 0
            else:
                return 1

    def transmit(self, env):
        """ Processs to transmit packets from both buffers.
            The transmit is done by always sending the packet
            that arrived first in the buffer.
        """
        while True:
            yield self.busy

            while not self.buffer_empty():
                idx = self.find_next_packet()
                # peek at leftmost packet
                packet, ts = self.buffer[self.device_ids[idx]][0]
                size = packet.get_length()
                # size / self.link_rate is in ms
                yield env.timeout(size / self.link_rate)
                self.buffer_used[self.device_ids[idx]] -= size
                self.buffer[self.device_ids[idx]].popleft()
                # Schedule event after link_delay
                env.process(self.send_packet(idx, packet))
                self.transmitted_size += size

            self.busy = self.env.event()

    def send_packet(self, idx, packet):
        ''' Independent process to schedule receive packet event for host. '''
        yield self.env.timeout(self.link_delay)
        self.end_points[1 - idx].receive_packet(packet)

    def get_buffer_size(self):
        """Returns the buffer size of the link in bytes."""
        return self.buffer_size

    def get_buffer_occupancy(self):
        """ Helper function that calculates the total buffer occupancy
            for link
        """
        return (self.buffer_used[self.device_ids[0]] + \
               self.buffer_used[self.device_ids[1]]) / (self.buffer_size * 2.0)

    def get_weight(self):
        """ Link weight for dynamic routing. """
        return (self.buffer_used[self.device_ids[0]] +
                self.buffer_used[self.device_ids[1]]) / \
                self.link_rate + self.link_delay

    def get_link_rate(self):
        """Returns the link rate."""
        return self.link_rate

    def get_flow_rate(self):
        """ Helper function that calculates average flow rate since we
            last called the report function
        """
        # Convert B/ms to Mbps
        return self.transmitted_size / \
               (Link.MBPS_TO_B_PER_MS * self.env.interval)

    def report(self):
        """ Function that reports link statictics to environment """
        # Convert buffer occupancy to percentage
        buffer_occ = 100 * self.get_buffer_occupancy()
        flow_rate = self.get_flow_rate()
        packet_drop = self.packet_drop
        # Clear transmitted_size and packet drop for the next round
        self.transmitted_size = 0
        self.packet_drop = 0
        return {'packet_loss' : packet_drop,
                'buffer_occupancy' : buffer_occ,
                'link_rate' : flow_rate}


from typing import OrderedDict

a = int(input())
selled = dict()
for _ in range(a):
    book = input()
    if book not in selled.keys():
        selled[book] = 1
    else:
        selled[book] += 1

max = max(selled.values())
max_list = list()
for k, v in selled.items():
    if v == max:
        max_list.append(k)
max_list.sort()
print(max_list[0])


# Advent of Code 2018 - Day 2

# Author:   Rachael Judy
# Date:     12/15/2020
# Purpose:  Compute checksum (number of ids with exactly two or exactly three multiplied)
#           Find id off by one letter

import os
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import parseMod

boxes = parseMod.readCSV_row('data/2boxes.csv', '\n')

# part 1
twos_overall, threes_overall = 0, 0
for box in boxes:
    twos, threes = 0, 0
    for letter in range(ord('a'), ord('z')+1):
        if box.sea_monster_count(chr(letter)) == 2:
            twos += 1
        if box.sea_monster_count(chr(letter)) == 3:
            threes += 1
    twos_overall += (twos > 0)
    threes_overall += (threes > 0)

print("Part 1: ", twos_overall*threes_overall)

# part 2
for box1 in boxes:
    for box2 in boxes:  # look at each combo
        ans = []
        if box1 != box2:
            # sea_monster_count mismatch and mismatch character
            mismatch = 0
            mismatch_c = ''
            for char_1, char_2 in zip(box1, box2):
                if char_1 != char_2:
                    mismatch += 1
                    mismatch_c = char_1
            if mismatch == 1: # found it
                ans = [box1, box2]
                break

    if len(ans): break

# bit of a cheat, if not the first occurrence of the mismatch, won't replace the right one
# should display the ans instead and then remove the different character
print("Part 2: ", ans[0].replace(mismatch_c, '', 1))


import pymongo as pm
import gridfs
import cPickle

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

from scipy import misc
import os, sys
import time

import sklearn.linear_model
from sklearn import (manifold, datasets, decomposition, ensemble,
                     discriminant_analysis, random_projection)
from sklearn.cluster import KMeans

import math
from matplotlib.backends.backend_pdf import PdfPages

import PIL.Image
import IPython.display as ip_disp
from cStringIO import StringIO

DEFAULT_BATCHSIZE = 128
CACHE_DICT = {}

# Add parent directory to the system path so we can import from there.
parent, _ = os.path.split(os.getcwd())
if parent not in sys.path:
    sys.path.append(parent)

from tfutils_reader import (
    TfutilsReader, load_model,
    load_validation_results,
    load_loss_results,
    )
from embedding_stats import MemoryBank
import image_utils
from instance_stats import analysis

def display_img_array(*img_arrays, **kwargs):
    fmt = kwargs['fmt'] if 'fmt' in kwargs else 'jpeg'
    imgs = []
    for img_array in img_arrays:
        img_array = np.uint8(img_array)
        f = StringIO()
        PIL.Image.fromarray(img_array).save(f, fmt)
        img = ip_disp.Image(data=f.getvalue())
        imgs.append(img)
    ip_disp.display(*imgs)

def color_sequence(rgb, n):
    color_seq = np.stack([
        (rgb[c] * np.array(range(n)) / float(n)) for c in [0,1,2]
    ], axis=1)
    return np.array([tuple(c) for c in color_seq])

def plot_trajectory(traj, plot, components=(0,1),
                    projection_vecs=None,
                    color=(1, 0, 0), smoothed=True):
    if smoothed:
        traj = np.apply_along_axis(
            lambda x: analysis.smooth(x, conv_len=10),
            axis=0, arr=traj)
    if projection_vecs is None:
        top, _, projection_vecs = analysis.pca_analysis(traj)
        #print top

    projected_pts = []
    comp1, comp2 = components
    for pt in traj:
        coord1 = np.dot(pt, projection_vecs[comp1])
        coord2 = np.dot(pt, projection_vecs[comp2])
        projected_pts.append((coord1, coord2))

    xs, ys = zip(*projected_pts)
    plot.scatter(xs, ys, c=color_sequence(color, len(xs)))

def plot_tsne(data, **kwargs):
    tsne = manifold.TSNE(n_components=2, init='pca', random_state=0)
    X_tsne = tsne.fit_transform(data)
    plt.scatter(X_tsne[:,0], X_tsne[:,1], **kwargs)

def plot_mds(data, **kwargs):
    clf = manifold.MDS(n_components=2, n_init=1, max_iter=100)
    X_mds = clf.fit_transform(data)
    plt.scatter(X_mds[:,0], X_mds[:,1], **kwargs)

class ValidationPlot(object):
    def __init__(self, xlabel="Epoch", ylabel="Validation Performance"):
        self.fig, self.ax = plt.subplots()
        self.ax.set(xlabel=xlabel, ylabel=ylabel)
        self.data = {}

    def add(self, label, xy_pairs):
        self.data[label] = xy_pairs

    def plot(self, start=None, end=None):
        start = start if start is not None else 0
        end = end if end is not None else float('inf')
        for label, xy_pairs in self.data.iteritems():
            xy_pairs = [(x,y) for x,y in xy_pairs if x >= start and x <= end]
            if len(xy_pairs) == 0:
                continue
            xs, ys = zip(*xy_pairs)
            self.ax.plot(xs, ys, label=label)
        self.ax.legend(loc='lower right')

class LossPlot(object):
    def __init__(self, xlabel="Epoch", ylabel="Loss Value", steps_per_epoch=10009):
        self.fig, self.ax = plt.subplots()
        self.ax.set(xlabel=xlabel, ylabel=ylabel)
        self.steps_per_epoch = steps_per_epoch
        self.data = {}

    def add(self, label, values, start_epoch=0):
        self.data[label] = (values, start_epoch)

    def plot(self, start=None, end=None):
        start = start if start is not None else 0
        end = end if end is not None else float('inf')
        for label, (values, start_epoch) in self.data.iteritems():
            s = max(start - start_epoch, 0) * self.steps_per_epoch
            e = max(end - start_epoch, 0) * self.steps_per_epoch
            if s >= e:
                continue
            values = values[s:e]
            idxs = [i / float(self.steps_per_epoch) for i in range(len(values))]
            self.ax.plot(idxs, values, label=label)
        self.ax.legend(loc='upper right')

def show_train_learnrate(
        curr_expid,
        conn,
        dbname='combinet-test',
        colname='combinet',
        start_N=50,
        with_dataset=None,
        batch_watch_start=0,
        batch_watch_end=None,
        do_conv=False,
        conv_len=100,
        new_figure=True,
        batch_size=DEFAULT_BATCHSIZE,
        batch_offset=0,
        max_step=None,
        label_now=None,
        loss_key='loss',
        big_loss_thres=50,
        ):

    # Weird setting in tfutils, the records are stored in colname + .files
    colname = colname + '.files'

    # Used for legend
    if label_now is None:
        label_now = curr_expid

    # Get the query through exp_id
    find_res = conn[dbname][colname].find(
                {'exp_id': curr_expid, 'train_results': {'$exists': True}})

    # Sort the results based on steps, for overlapped steps, use the last record
    find_res = sorted(find_res, key = lambda x: x['step'])
    new_find_res = []
    for curr_indx in xrange(len(find_res)-1):
        if find_res[curr_indx]['step'] == find_res[curr_indx+1]['step']:
            continue
        new_find_res.append(find_res[curr_indx])
    new_find_res.append(find_res[len(find_res)-1])
    find_res = new_find_res

    # Only use the steps
    if max_step:
        find_res = filter(lambda x: x['step']<max_step, find_res)
    train_vec = np.concatenate(
            [
                [(_r[loss_key], _r['learning_rate'])
                    for _r in r['train_results']]
                for r in find_res])

    # Build a new figure if needed
    if new_figure:
        fig = plt.figure(figsize=(12, 5))

    # For loss plotting
    plt.subplot(1, 2, 1)
    ## Throw away first start_N losses
    ## (as they might be huge, which influences the visualizations)
    _N = start_N
    inter_list = train_vec[_N:, 0]
    inter_list = np.asarray(inter_list)
    ## Filter out the spikes, which can influence the visualizations
    inter_list = inter_list[inter_list < big_loss_thres]
    ## Smooth the loss values
    if do_conv:
        conv_list = np.ones([conv_len])/conv_len
        inter_list = np.convolve(inter_list, conv_list, mode='valid')

    ## The x axis will be per 10k steps
    temp_x_list = np.asarray(range(len(inter_list)))\
            * 1.0 * batch_size / (10000*DEFAULT_BATCHSIZE) + batch_offset
    new_indx_list = temp_x_list > batch_watch_start
    if batch_watch_end:
        new_indx_list = (temp_x_list>batch_watch_start) \
                & (temp_x_list<batch_watch_end)
    ## Do the plotting
    plt.plot(
            temp_x_list[new_indx_list],
            inter_list[new_indx_list],
            label=label_now)
    plt.title('Training loss')
    plt.legend(loc = 'best')

    # For learning rate plot
    plt.subplot(1, 2, 2)
    temp_y_list = train_vec[_N:, 1]
    # This x_list is slightly different from that in losses (convolution)
    temp_x_list_lr = np.asarray(range(len(temp_y_list)))\
            * 1.0 * batch_size / (10000*DEFAULT_BATCHSIZE) + batch_offset
    new_indx_list_lr = temp_x_list_lr > batch_watch_start
    if batch_watch_end:
        new_indx_list_lr = (temp_x_list_lr>batch_watch_start) \
                & (temp_x_list_lr<batch_watch_end)
    plt.plot(
            temp_x_list_lr[new_indx_list_lr],
            temp_y_list[new_indx_list_lr],
            label=label_now)
    plt.title('Learning Rate')

def show_val(
        curr_expid,
        conn,
        dbname='combinet-test',
        colname='combinet',
        gridfs_name='combinet',
        key='loss',
        valid_key='topn',
        big_dict=CACHE_DICT,
        batch_watch_start=0,
        batch_watch_end=None,
        new_figure=True,
        val_N=0,
        batch_size=DEFAULT_BATCHSIZE,
        label_now=None,
        val_step=1.0,
        batch_offset=0,
        do_plot=True,
        ):

    colname = colname + '.files'
    if not label_now:
        label_now = curr_expid

    # Get the query
    find_res = conn[dbname][colname].find(
            {'exp_id': curr_expid,
             'validation_results': {'$exists': True}})
    # Sort using step
    find_res = sorted(find_res, key = lambda x: x['step'])
    if len(find_res)==0:
        return None
    # Remove the duplicate steps
    new_find_res = []
    for curr_indx in xrange(len(find_res)-1):
        if find_res[curr_indx]['step'] == find_res[curr_indx+1]['step'] \
                and find_res[curr_indx]['step']:
            continue
        new_find_res.append(find_res[curr_indx])
    new_find_res.append(find_res[len(find_res)-1])
    find_res = new_find_res

    # Get the validation results
    if len(find_res)==0:
        return
    list_res = filter(lambda x: valid_key in x['validation_results'], find_res)

    test_vec = [r['validation_results'][valid_key][key] for r in list_res]
    x_range = range(len(test_vec))
    _N = val_N
    if new_figure and do_plot:
        plt.figure(figsize=(9, 5))
    x_range = np.asarray(x_range) * val_step * (batch_size)/(DEFAULT_BATCHSIZE)\
            + batch_offset
    x_range = np.asarray(x_range[_N:])
    test_vec = np.asarray(test_vec[_N:])

    choose_indx = x_range > batch_watch_start
    if batch_watch_end is not None:
        choose_indx = choose_indx & (x_range < batch_watch_end)

    if do_plot:
        plt.plot(x_range[choose_indx], test_vec[choose_indx], label = label_now)
    if 'top' in key and  do_plot:
        print(
                curr_expid, key,
                np.max(test_vec[choose_indx]), np.argmax(test_vec))
    if do_plot:
        plt.title('Validation Performance, %s' % key)

    if do_plot:
        return test_vec[_N:]
    else:
        return x_range[choose_indx], test_vec[choose_indx]

def show_instance_perf(
        txt_path='/home/chengxuz/previous_logs/instance_task.log',
        perf_detail_str='50000/50000',
        perf_str='Top1: ',
        mult_num=1,
        offset_epoch=0,
        epoch_range=None,
        ):

    with open(txt_path, 'r') as f:
        data = f.readlines()
    all_perfes = []
    for each_line in data:
        if perf_str in each_line \
                and perf_detail_str in each_line \
                and 'Top5' not in each_line:
            perf_plc = each_line.find(perf_str)
            curr_perf = float(each_line[perf_plc+len(perf_str):]) * mult_num
            all_perfes.append(curr_perf)

    start, end = epoch_range or (0, len(all_perfes))
    end = min(end, len(all_perfes))
    x_perf = range(start, end)
    plt.plot([x + offset_epoch for x in x_perf], [all_perfes[x] for x in x_perf])

def show_tf_inst_loss(
        which_loss='total',
        txt_path='/home/chengxuz/previous_logs/'\
                + 'log_performance_instance_18_fxcp_2.txt',
        end_N=None,
        start_N=None,
        label_now=None,
        offset_N=0,
        color=None
        ):
    with open(txt_path, 'r') as f:
        data = f.readlines()

    mapping_dict = {
            'total': 'Loss:',
            'model': 'Loss model:',
            'noise': 'Loss noise:',
            }

    all_losses = []
    loss_str = mapping_dict[which_loss]
    for each_line in data:
        if loss_str in each_line:
            loss_plc = each_line.find(loss_str)
            curr_loss_str = each_line[loss_plc+len(loss_str):]
            curr_loss_str = curr_loss_str.split(',')[0]
            if which_loss=='total':
                which_one = 0
            elif which_loss=='model':
                which_one = 1
            else:
                which_one = 2
            curr_loss = float(curr_loss_str)
            all_losses.append(curr_loss)
    all_losses = all_losses[::10]
    if end_N is not None:
        all_losses = all_losses[:end_N]
    if start_N is not None:
        all_losses = all_losses[start_N:]
    # Smooth the loss curve
    conv_len = 100
    conv_list = np.ones([conv_len])/conv_len
    all_losses = np.convolve(all_losses, conv_list, mode='valid')

    if not label_now:
        search_str = 'log_performance_instance_'
        label_now = txt_path[txt_path.find(search_str) + len(search_str):]
        label_now = label_now[:-4]
    plot_kwargs = {}
    if color:
        plot_kwargs['color'] = color
    x_indx = np.arange(len(all_losses)) + offset_N
    plt.plot(x_indx, all_losses, label=label_now, **plot_kwargs)
    plt.legend(loc = 'lower left')


import h5py
import numpy as np

def build_flipped_dataset(db, new_db, partition):
    ids = db['ids_{}'.format(partition)]
    classes = db['classes_{}'.format(partition)]
    impos = db['impos_{}'.format(partition)]
    ims = db['ims_{}'.format(partition)]
    numims = db['numims_{}'.format(partition)]

    new_ims = [np.rollaxis(img, 0, 3) for img in ims]

    print(new_ims[0].shape)

    new_db.create_dataset('ids_{}'.format(partition), data=ids)
    new_db.create_dataset('classes_{}'.format(partition), data=classes)
    new_db.create_dataset('numims_{}'.format(partition), data=numims)
    new_db.create_dataset('impos_{}'.format(partition), data=impos)

    new_db.create_dataset('ims_{}'.format(partition), data=new_ims)

db_path = 'data/subset_train_val.h5'
new_db_path = 'data/flipped_subset.h5'

db = h5py.File(db_path, 'r')
new_db = h5py.File(new_db_path, 'w')

build_flipped_dataset(db, new_db, "train")
build_flipped_dataset(db, new_db, "val")

new_db.flush()
new_db.close()
db.close()