# module
# autor: MolokovAlex
# lisence: GPL
# coding: utf-8
# from sys import getsizeof
import os
from datetime import datetime
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import END, N, NSEW, Menu
import tkinter.messagebox as mb
import sqlite3 as sqlite
import pandas as pd
import numpy as np
import sqlite3 as sql3

import moduleDBClass as mdbc
import moduleImport as mi
import skladConfig as scfg
import moduleSQLite as msql

import modulеIncomeExpenditureGUI as mieGUI
import modulеEditGUI as meGUI
import moduleExport as me
import moduleSpecification as ms

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.protocol("WM_DELETE_WINDOW", self.confirm_delete)
        self.widthscreen = self.winfo_screenwidth()#-30    # размеры экрана
        self.heigthscreen = 640 #window.winfo_screenheight()-30
        self.geometry('{}x{}+5+5'.format(self.widthscreen, self.heigthscreen))

        self.frame_Logger = tk.LabelFrame(master=self, text="Log", relief=tk.SUNKEN, borderwidth=3, height=20)
        self.frame_Logger.pack(fill=tk.X, side=tk.TOP, ipadx=5, ipady=5, padx=10, pady=5)
        self.scroll_logger_x = tk.Scrollbar(self.frame_Logger, orient=tk.HORIZONTAL)
        self.scroll_logger_y = tk.Scrollbar(self.frame_Logger, orient=tk.VERTICAL)
        self.text_box = tk.Text(master=self.frame_Logger, xscrollcommand=self.scroll_logger_x.set, yscrollcommand=self.scroll_logger_y.set, height= 20)
        self.scroll_logger_x.config(command=self.text_box.xview)
        self.scroll_logger_y.config(command=self.text_box.yview)
        self.text_box.grid(row=0, column=0, sticky=tk.W + tk.E)
        self.scroll_logger_x.grid(row=1, column=0, sticky=tk.W + tk.E)
        self.scroll_logger_y.grid(row=0, column=1) #, sticky=tk.N + tk.S)
        self.frame_Logger.columnconfigure(0, weight=1)
        self.frame_Logger.rowconfigure(0, weight=0)

    def confirm_delete(self) -> None:
    #     message = "Вы уверены, что хотите закрыть это окно?"
    #     if mb.askyesno(message=message, parent=self):
        # сохраняем изменненный DataFame в файл перед закрытием основного окна
        # me.Save_DataFrame_in_PickleFile(df=scfg.df1, namefile=scfg.nameFile_DBC_pickle)
        # me.Save_DataFrame_in_ExcelFile(df=scfg.df1, namefile=scfg.nameFile_DBC_excel)
        me.Save_DataFrame_in_PickleFile()
        self.destroy()
        return None

    def createMainMenu(self) -> None:
        self.mainmenu = Menu(self)
        self.config(menu=self.mainmenu)

        self.db_import_menu = Menu(self.mainmenu, tearoff=0)
        self.mainmenu.add_cascade(label='Импорт из xls', menu=self.db_import_menu)

        self.db_import_menu.add_command(label='Импорт Components', command=lambda modeWind='import', viewWind = 'DBC': self.open_Window_Import_Component(modeWindow = modeWind, viewWindow = viewWind))
        self.db_import_menu.add_command(label='Импорт спецификаций', command=lambda modeWind='import', viewWind = 'DBS': self.open_Window_Import_Component(modeWindow = modeWind, viewWindow = viewWind))

        self.db_export_menu = Menu(self.mainmenu, tearoff=0)
        self.mainmenu.add_cascade(label='Экспорт в xls', menu=self.db_export_menu)
        self.db_export_menu.add_command(label='Экспорт Components', command=self.open_Window_Export)
        self.db_export_menu.add_command(label='Экспорт спецификаций', command=self.open_Window_Export)

        self.editmenu = Menu(self.mainmenu, tearoff=0)
        self.mainmenu.add_cascade(label='Правка БД', menu=self.editmenu)
        self.editmenu.add_command(label='Редактирование Components', command=self.open_Window_Edit_Component)
        self.editmenu.add_command(label='Редактирование спецификаций', command=self.open_Window_Edit_Specification)

        self.arrivalmenu = Menu(self.mainmenu, tearoff=0)
        self.mainmenu.add_cascade(label='Приход на склад', menu= self.arrivalmenu)
        self.arrivalmenu.add_command(label='Приход', command=self.open_Window_income_Component)
        self.arrivalmenu.add_command(label='История приходов', command=self.clicked)

        self.expensemenu = Menu(self.mainmenu, tearoff=0)
        self.mainmenu.add_cascade(label='Расход из склада', menu= self.expensemenu)
        self.expensemenu.add_command(label='Расход', command=self.open_Window_expenditure_Component)
        self.expensemenu.add_command(label='История расходов', command=self.clicked)

        self.specmenu = Menu(self.mainmenu, tearoff=0)
        self.mainmenu.add_cascade(label='Спецификации', menu=self.specmenu)
        self.specmenu.add_command(label='Новая', command=self.clicked)
        self.specmenu.add_command(label='Редактирование', command=self.clicked)
        self.specmenu.add_command(label='Удаление', command=self.clicked)
        self.specmenu.add_command(label='Проводка спецификации', command=self.clicked)

        self.helpmenu = Menu(self.mainmenu, tearoff=0)
        self.mainmenu.add_cascade(label="Справка", menu=self.helpmenu)
        self.helpmenu.add_command(label="Помощь")
        self.helpmenu.add_command(label="О программе")

        return None

    def open_Window_Export(self) -> None:
        """
        открытие окна экспорта
        """
        we = me.WindowExport(self)
        we.grab_set()                      #  чтобы окно получало все события
        return None

    def open_Window_expenditure_Component(self) -> None:
        """
        открытие окна для операции расхода компонента на различные цели
        """
        # viewDB - отображение в окне БД:
        # 'DBC' = DataBaseComponents
        # 'DBS' = DataBaseSpecification
        # 'DBE' - DataBaseExpenditure - БД расхода компонентов (expenditure)
        # modeWindow - внешний вид и расположени кнопок окна в режимах:
        # modeWindow = 'edit'
        # modeWindow = 'comp_in_spec'
        # modeWindow = 'expenditure'  - режим окна Расход компонента
        # modeWindow = 'income'  - режим окна Приход компонента
        we = mieGUI.WindowExpenditure(self, viewDB = 'DBE', modeWindow = 'expenditure')
        we.grab_set()                      #  чтобы окно получало все события
        # self.text_box.insert(tk.END, "open_WindowExpenditure"+"\n")

        return None

    def open_Window_income_Component(self) -> None:
        """
        открытие окна для операции расхода компонента на различные цели
        """
        # viewDB - отображение в окне БД:
        # 'DBC' = DataBaseComponents
        # 'DBS' = DataBaseSpecification
        # 'DBE' - DataBaseExpenditure - БД расхода компонентов (expenditure)
        # modeWindow - внешний вид и расположени кнопок окна в режимах:
        # modeWindow = 'edit'
        # modeWindow = 'comp_in_spec'
        # modeWindow = 'expenditure'  - режим окна Расход компонента
        # modeWindow = 'income'  - режим окна Приход компонента
        we = mieGUI.WindowExpenditure(self, viewDB = 'DBI', modeWindow = 'income')
        we.grab_set()                      #  чтобы окно получало все события
        # self.text_box.insert(tk.END, "open_WindowExpenditure"+"\n")

        return None

    def open_Window_Edit_Specification(self) -> None:
        # viewWindow = 'DBC' = DataBaseComponents
        # 'DBS' = DataBaseSpecification
        # modeWindow = 'edit'
        # modeWindow = 'comp_in_spec'
        # wec = meGUI.WindowEditComponent(self, modeWindow = 'edit', viewDB='DBS')
        # wec.grab_set()                      #  чтобы окно получало все события
        wior = ms.Window_Choice_Specification(self)
        select = wior.open()
        wes = ms.Window_Edit_Specification(self, id_select=select)
        self.text_box.insert(tk.END, "open_WindowEdit_Specification"+"\n")
        return None

    def open_Window_Edit_Component(self):
        # viewWindow = 'DBC' = DataBaseComponents
        # 'DBS' = DataBaseSpecification
        # modeWindow = 'edit'
        # modeWindow = 'comp_in_spec'
        wec = meGUI.WindowEditComponent(self, modeWindow = 'edit', viewDB='DBC')
        wec.grab_set()                      #  чтобы окно получало все события
        self.text_box.insert(tk.END, "open_WindowEdit_Component"+"\n")
        return None

    def open_Window_Import_Component(self, modeWindow, viewWindow) -> None:
        """
        сюда приходим из меню 'Импорт Components'
        Функция открытия универсального окна Импрта или Перемещния
        Вход:
        # визуальное отображение окна для БД компонентов или БД спецификаций :
        # viewWindow = DBC = DataBaseComponents
        # viewWindow = DBS = DataBaseSpecification
        # режим работы окна - или "перемещнние " или "импорт"
        # modeWindow = 'remove'
        # modeWindow == 'import

        """
        mW = modeWindow
        vW = viewWindow
        wior = mi.Window_Import_OR_Remove(self, modeWindow = mW, viewWindow = vW)
        # wig.grab_set()                      #  чтобы окно получало все события
        self.text_box.insert(tk.END, "open_Window_Import_Group"+"\n")
        return None

    def clicked(self):
        return None

def Unpack_String_DataFrame(DataFrameTree: pd.DataFrame, index: str) -> None:
    """
    Универсальная Распаковка строки таблцицы DataFrama на поля(столбцы), т.е. SerialFrame
    список полей- какие найдутся в DataFrame
    плюс поля:
    'UnitsName' - наименование ед изм - возмем по коду 'id_code_item' из DBCU
    'index'
    # 'PathDistanation' - путь списания компонента в спецификацию - возмем по коду 'id_code_parent' из DBS

    Выход:
    словарь типа {'название поля/столбца': содержимое}

    """
    # будущий результат работы функции - словать типа {'название поля/столбца': содержимое}
    upsdf = {}
    # список названий всех полей/столбцов в DataFrame
    # в pandas
    nameColunms = DataFrameTree.columns.values.tolist()

    #  для каждого наименования столбца извлекаем содержимое  value и помещаем в выходной словарь
    for itemNameColunm in nameColunms:
        value = DataFrameTree.loc[index, itemNameColunm]
        upsdf[itemNameColunm] = value

        if (itemNameColunm == 'id_code_item') | (itemNameColunm == 'amount'):
            if isinstance(value, str) :
                if (value == ''):
                    upsdf[itemNameColunm] = '0'
            else:
                if value.empty:
                    upsdf[itemNameColunm] = '0'
    # поле индекса тоже должно быть
    upsdf['index'] = DataFrameTree.index

    # извлекем наименование ед изм - возмем по коду 'id_code_item' из DBCU
    a = scfg.df_DBCU
    unitsCodeSF = scfg.df_DBCU[scfg.df_DBCU['id_code_item'] == upsdf['id_code_item']]['code_units']
    # если такой компонент ('id_code_item') отсутствет в БД ед изм - проверим это
    if unitsCodeSF.empty: unitsCode = '1699'
    else : unitsCode = unitsCodeSF.item()
    upsdf['UnitsName'] = scfg.UnitsCodeName[unitsCode]

    # # извлекем путь списания компонента в спецификацию - возмем по коду 'id_code_parent' из DBS
    # if (upsdf['id_code_parent'] !=''):
    #     # self.idCodeDistanation = id_item_group
    #     nameGroup = scfg.df_DB_Specification[scfg.df_DB_Specification['id_code_e']==upsdf['id_code_parent']]['name']
    #     ValuePathDistanation= nameGroup.item()
    #     id_code_parent = scfg.df_DB_Specification[scfg.df_DB_Specification['id_code_e']==upsdf['id_code_parent']]['id_code_parent']
    #     while (id_code_parent.item() != '10000'):
    #         id_item = id_code_parent.item()
    #         nextNameGroup = scfg.df_DB_Specification[scfg.df_DB_Specification['id_code_e']==id_item]['name']
    #         a= nextNameGroup.item()
    #         ValuePathDistanation = a + '/' + ValuePathDistanation
    #         #  перейдем к слудущему родителю
    #         id_code_parent = scfg.df_DB_Specification[scfg.df_DB_Specification['id_code_e']==id_item]['id_code_parent']
    # upsdf['PathDistanation'] = ValuePathDistanation

    return upsdf

# def viewTreeComponents(treeComp:ttk.Treeview, DataFrameTree: pd.DataFrame, id_parent):
def viewTreeComponents(treeComp:ttk.Treeview, id_parent: int) -> None:
    """
    отображение ветки в дереве Компонентов
    Вход:
    treeF:ttk.Treeview - объект дерева из формы
    DataFrameTree: pd.DataFrame - БД которую надо отобразить
    parent - id_code_item группы(ветки) дерева
    """
    stringDF = {}
    # очистим все дерево компонентов
    for i in treeComp.get_children(): treeComp.delete(i)

    # заполним дерево TreeComponent названиями данными из DBC у которых родителем является группа id_parent из DBG
    connectionDBFile = sql3.connect(scfg.DBSqlite)
    cursorDB = connectionDBFile.cursor()
    with connectionDBFile:
        # вычисли максимальное значение id в таблице DBС
        # cursorDB.execute("""SELECT MAX(id) FROM DBC;""")
        # maxxx3 = cursorDB.fetchone()
        # maxx2 = maxxx3[0]

         # получим названия столбцов БД
        cursorDB.execute('PRAGMA table_info("DBC")')
        column_names = [i[1] for i in cursorDB.fetchall()]
        column_names.append('name_unit')

        # вытащим строки - получим из DBC у которых id_parent =id_parent
        cursorDB.execute("""SELECT DBC.*, DBU.name FROM DBC JOIN DBU ON DBU.id = DBC.id_unit WHERE DBC.id_parent=? ;""", (id_parent,))
        # cursorDB.execute("""SELECT DBC.name, DBC.amount, DBU.name FROM DBC, DBU WHERE DBU.id = DBC.id_unit ;""")#, (id_parent,))
        # cursorDB.execute("""SELECT DBC.*, DBU.name FROM DBC, DBU WHERE DBU.id = DBC.id_unit AND DBC.id_parent=? ;""", (id_parent,))
        rows_from_DBС = cursorDB.fetchall()

    if(connectionDBFile):
            connectionDBFile.close()

        # сделаем словарь {ключ_название_столбца_таблицы: содержимое_ячейки_столбца} и заполняем элемент дерева
    for item_tupple in rows_from_DBС:
        stringDF = {}
        stringDF = { k:v for k,v in zip (column_names,item_tupple )}
        # print(stringDF)    # {'id': 1, 'name': 'Склад'}
        if stringDF['id_parent'] ==0:
            index_code_parent=''
        else:
            index_code_parent = str(stringDF['id_parent'])
        treeComp.insert('', 'end',  stringDF['id'], text=stringDF['name'], values=[stringDF['id'], stringDF['amount'], stringDF['name_unit'], stringDF['min_rezerve'], stringDF['articul_1C'], stringDF['code_1C'], stringDF['name_1C'], stringDF['id_parent'], 0])

    return None

def viewTreeGroupSpec(treeF:ttk.Treeview, DataFrameTree: pd.DataFrame) -> None:

    a=0
    stringDF = {}
    # очищаем дерево
    for i in treeF.get_children(): treeF.delete(i)
    for lvl in scfg.listOfLevel:
        # выдать всех у кого в родителях код lvl
        df2 = DataFrameTree[DataFrameTree['id_code_lvl'] == lvl]
        if not(df2.empty):
            for indx in df2.index:
                stringDF = Unpack_String_DataFrame(DataFrameTree, indx)
                if lvl == 'lvl01':
                    id_code_parent = ''
                else:
                    id_code_parent = DataFrameTree.loc[indx, 'id_code_parent']
                index_code_parent = id_code_parent
                id_code_e = int(stringDF['id_code_e'])
                # treeF.insert(index_code_parent, 'end',  id_code_item, text=name, values=[id_code_item, amount, code_units, min_rezerve, articul_1C, code_1C, name_1C, id_code_parent, id_code_lvl])
                treeF.insert(index_code_parent, 'end',  id_code_e, text=stringDF['name'], values=[stringDF['id_code_item'], stringDF['amount'],  stringDF['id_code_parent'], stringDF['id_code_lvl']])

def viewTreeGroupDBGC(treeF:ttk.Treeview):#, DataFrameTree: pd.DataFrame):

    stringDF = {}
    # очищаем дерево
    for i in treeF.get_children(): treeF.delete(i)

    # заполним дерево TreeGroup названиями групп из DBG

    connectionDBFile = sql3.connect(scfg.DBSqlite)
    cursorDB = connectionDBFile.cursor()
    with connectionDBFile:
        # вычисли максимальное значение id родителя в таблице DBG
        # cursorDB.execute("""SELECT MAX(id_parent) FROM DBG;""")
        # maxxx = cursorDB.fetchone()
        # maxx = maxxx[0]

        # вычисли максимальное значение id в таблице DBG
        # cursorDB.execute("""SELECT MAX(id) FROM DBG;""")
        # maxxx3 = cursorDB.fetchone()
        # maxx2 = maxxx3[0]

        # получим названия столбцов БД
        cursorDB.execute('PRAGMA table_info("DBG")')
        column_names = [i[1] for i in cursorDB.fetchall()]
        # print(column_names)
        # ['id', 'name', 'id_parent']

        # пройдемся по всем индексам БД и
        # for item_id in range (1, maxx2+1, 1):
        #     # вытащим строку - получим из DBG названия у которых id =item_id
        #     cursorDB.execute("""SELECT * FROM DBG WHERE id=?;""", (item_id,))
        #     row_from_DBG = cursorDB.fetchall()
            # print(row_from_DBG)    # [(1, 'Склад', 0)]
        cursorDB.execute("""SELECT * FROM DBG ORDER BY id_parent;""")
        rows_from_DBG = cursorDB.fetchall()
            # if row_from_DBG:
                # сделаем словарь {ключ_название_столбца_таблицы: содержимое_ячейки_столбца} и заполняем элемент дерева
        for item_tupple in rows_from_DBG:
            stringDF = {}
            stringDF = { k:v for k,v in zip (column_names,item_tupple )}
            # print(stringDF)    # {'id': 1, 'name': 'Склад'}
            if stringDF['id_parent'] ==0:
                index_code_parent=''
            else:
                index_code_parent = str(stringDF['id_parent'])
            # treeF.insert(index_code_parent, 'end',  id_code_item, text=stringDF['name'], values=[stringDF['id_code_item'], stringDF['amount'], UnitsName, stringDF['min_rezerve'], stringDF['articul_1C'], stringDF['code_1C'], stringDF['name_1C'], stringDF['id_code_parent'], stringDF['id_code_lvl']])
            treeF.insert(index_code_parent, 'end',  stringDF['id'], text=stringDF['name'], values=[stringDF['id'], 0, '', 0, '', '', '', stringDF['id_parent'], 0])

        # item_id_parent = 1
        # cursorDB.execute("""SELECT * FROM DBG WHERE id_parent=?;""", (item_id_parent,))
        # row_from_DBG = cursorDB.fetchall()
        # print(row_from_DBG)
        # # [(1, 'Склад', 0)]
        # # сделаем словарь и заполняем дерево
        # for item_tupple in row_from_DBG:
        #     stringDF = {}
        #     stringDF[column_names[0]] = item_tupple[0]
        #     stringDF[column_names[1]] = item_tupple[1]
        #     stringDF[column_names[2]] = item_tupple[2]
        #     print(stringDF)
        #     # {'id': 1, 'name': 'Склад'}
        #     if stringDF['id_parent'] ==0:
        #         index_code_parent=''
        #     else:
        #         index_code_parent = str(stringDF['id_parent'])
        #     # treeF.insert(index_code_parent, 'end',  id_code_item, text=stringDF['name'], values=[stringDF['id_code_item'], stringDF['amount'], UnitsName, stringDF['min_rezerve'], stringDF['articul_1C'], stringDF['code_1C'], stringDF['name_1C'], stringDF['id_code_parent'], stringDF['id_code_lvl']])
        #     treeF.insert(index_code_parent, 'end',  stringDF['id'], text=stringDF['name'], values=[stringDF['id'], 0, '', 0, '', '', '', stringDF['id_parent'], 0])

    if(connectionDBFile):
            connectionDBFile.close()

def viewTreeGroupDBGS(treeF:ttk.Treeview)-> None:
    """
    отображение таблицы DBGS в форме на компоненте Treeview
    """
    # очищаем дерево
    for i in treeF.get_children(): treeF.delete(i)

    # заполним дерево TreeGroup названиями групп из DBGS
    connectionDB = sql3.connect(scfg.DBSqlite)
    cursorDB = connectionDB.cursor()
    with connectionDB:
        cursorDB.execute("""SELECT * FROM DBGS ORDER BY id_parent;""")
        rows_from_DBGS = cursorDB.fetchall()
            # if row_from_DBG:
        for item_tupple in rows_from_DBGS:
            id, name, id_parent = item_tupple
            if id_parent == 0: index_code_parent=''
            else: index_code_parent = id_parent
            # stringDF = {}
            # stringDF = { k:v for k,v in zip (column_names,item_tupple )}
            # print(stringDF)    # {'id': 1, 'name': 'Склад'}
            # if stringDF['id_parent'] ==0:
            #     index_code_parent=''
            # else:
            #     index_code_parent = str(stringDF['id_parent'])
            # treeF.insert(index_code_parent, 'end',  id_code_item, text=stringDF['name'], values=[stringDF['id_code_item'], stringDF['amount'], UnitsName, stringDF['min_rezerve'], stringDF['articul_1C'], stringDF['code_1C'], stringDF['name_1C'], stringDF['id_code_parent'], stringDF['id_code_lvl']])
            # treeF.insert(index_code_parent, 'end',  stringDF['id'], text=stringDF['name'], values=[stringDF['id'], 0, '', 0, '', '', '', stringDF['id_parent'], 0])
            treeF.insert(index_code_parent, 'end',  id, text=name, values=[id, 0, '', 0, '', '', '', id_parent, 0])

    if(connectionDB):
            connectionDB.close()

def Setting_TreeView(treeF:ttk.Treeview, form):
    """
    Установка и настройка столбцов компонента TreeView
    Визуальная настройка

    """

    col = scfg.columns_DB_components.copy()
    col.remove('name')
    treeF["columns"]=col

    # treeF.heading('#0', text='NameID')
    # treeF.heading('#1', text='id_code_item')
    # treeF.heading('#2', text='amount')
    # treeF.heading('#3', text='code_units')
    # treeF.heading('#4', text='min_rezerve')
    # treeF.heading('#5', text='articul_1C')
    # treeF.heading('#6', text='code_1C')
    # treeF.heading('#7', text='name_1C')
    # treeF.heading('#8', text='id_code_parent')
    # treeF.heading('#9', text='id_code_lvl')
            # Specify attributes of the columns
    # treeF.column('#0', width=200,stretch=tk.YES)
    # treeF.column('#1', width=60,stretch=tk.YES)
    # treeF.column('#2', width=60,stretch=tk.YES)
    # treeF.column('#3', width=60,stretch=tk.YES)
    # treeF.column('#4', width=60, stretch=tk.YES)
    # treeF.column('#5', width=60, stretch=tk.YES)
    # treeF.column('#6', width=60, stretch=tk.YES)
    # treeF.column('#7', width=60, stretch=tk.YES)
    # treeF.column('#8', width=60, stretch=tk.YES)
    # treeF.column('#9', width=60, stretch=tk.YES)

    # treeF["columns"]=scfg.columns_DB_components.copy()
    # a = scfg.columns_DB_components.copy()

    for i in col:
            treeF.heading(i, text=i)
            treeF.column(i, width=scfg.widthColunmsTreeWindowEditComponent[i], stretch=True)
    treeF.heading('#0', text='NameID')
    # treeF.column('#0', width=300,stretch=tk.YES)

    if form == 'short':
        # отобразим визуально только те столбцы, которые заложены в конфигуоационный модуль
        treeF["displaycolumns"]=scfg.displayColumnsShort
        treeF.column('#0', width=200,stretch=tk.YES)
    elif form == 'full':
        treeF["displaycolumns"]=scfg.displayColumnsFull
        treeF.column('#0', width=400,stretch=tk.YES)
    elif form =="choice_specification":
        treeF["displaycolumns"]=scfg.displayColumnsShort
        treeF.column('#0', width=400,stretch=tk.YES)
    else :
        treeF["displaycolumns"]=scfg.displayColumnsE
    return None

    # mask = (scfg.df1['id_code_lvl'] != 'lvl01') & (scfg.df1['id_code_lvl'] != 'lvl02') & (scfg.df1['id_code_lvl'] != 'lvl03') & (scfg.df1['id_code_lvl'] != 'lvl04') & (scfg.df1['id_code_lvl'] != 'lvl05') & (scfg.df1['id_code_lvl'] != 'lvl06')
    # df2 = scfg.df1.loc[mask]     # выдать всех у кого в родителях
    # if not(df2.empty):
    #         for indx in df2.index:
    #             id_group =  int(scfg.df1.loc[indx, 'id_code_item'])
    #             name_group = scfg.df1.loc[indx, 'name']
    #             id_code_parent = scfg.df1.loc[indx, 'id_code_parent']
    #             id_code_lvl = scfg.df1.loc[indx, 'id_code_lvl']
    #             amount = scfg.df1.loc[indx, 'amount']
    #             treeF.insert(id_code_parent, 'end',  id_group, text=name_group, values=[id_group, id_code_parent, id_code_lvl, amount])

        # self.tree.insert('', 'end', 10, text='Разъемы', values=0)
        # self.tree.insert('', 'end', 11, text='Наконечники НКИ', values=0)
        # self.tree.insert(10, 'end', 1001, text='DIN', values=0)
        # self.tree.insert(10, 'end', 1002, text='DВ', values=0)
        # self.tree.insert(11, 'end', 1101, text='НКИ', values=0)
        # self.tree.insert(11, 'end', 1102, text='НВИ', values=0)

    return None

# class WindowTree(tk.Toplevel):
#     def __init__(self, parent, modeWindow, viewDB):
#         # визуальное отображение универсального окна дерева групп для БД компонентов или БД спецификаций :
#         # viewDB = DBC = DataBaseComponents
#         # viewDB = DBS = DataBaseSpecification
#         # режим работы окна - или "перемещнние " или "импорт"
#         # modeWindow = 'remove'
#         # modeWindow == 'import
#         # modeWindow = 'expenditure'  - режим окна Расход компонента

#         super().__init__(parent)
#         # self.geometry("1024x600")
#         opts = { 'ipadx': 3, 'ipady': 3 , 'sticky': 'nswe' }

#         if  (viewDB == 'DBS') and (modeWindow == 'expenditure'):
#             self.label_to = tk.Label(self, text="В какую спецфикацию переместить ? ")
#         self.label_to.grid(row=0, column=0, **opts)

#         self.frame_tableTreeGroup = tk.LabelFrame(master=self, text="Группы", relief=tk.SUNKEN, borderwidth=3)   #, height=50)
#         self.frame_tableTreeGroup.grid(row=1, column=0,columnspan=2, **opts)

#         if  (viewDB == 'DBS') and (modeWindow == 'expenditure'):
#             self.btn_Remove = tk.Button(master=self, height=3, text="Сюда", command=self.fn_removComponent)
#         self.btn_Remove.grid(row=2, column=0, **opts)
#         self.btn_Cansel = tk.Button(master=self, height=3, text="Отмена", command=self.destroy)
#         self.btn_Cansel.grid(row=2, column=1, **opts)

#         self.treeGroup = ttk.Treeview(self.frame_tableTreeGroup, show="tree headings", height= 15)#, columns=col) #self.columns)
#         self.treeGroup.grid(row=0, column=1, rowspan=4, **opts)

#         Setting_TreeView(self.treeGroup, form = 'short')

#         self.ysb = ttk.Scrollbar(self.frame_tableTreeGroup, orient=tk.VERTICAL, command=self.treeGroup.yview)
#         self.treeGroup.configure(yscroll=self.ysb.set)
#         self.ysb.grid(row=0, column=2, rowspan=4, **opts)

#         self.treeGroup.bind('<<TreeviewSelect>>', self.on_select)

#         self.new_parent = 0
#         self.sel = 0

#         # DBC = DataBaseComponents
#         # DBS = DataBaseSpecification
#         if viewDB == 'DBC':
#             dataFrame_in = scfg.df_DBC
#             if not(dataFrame_in.empty):
#                 viewTreeGroup(self.treeGroup, dataFrame_in)       # отобразим данные из памяти DataFrame в TreeGroup с родителями

#         elif viewDB == 'DBS':
#             dataFrame_in = scfg.df_DBS
#             if not(dataFrame_in.empty):
#                 viewTreeGroupSpec(self.treeGroup, dataFrame_in)       # отобразим данные из памяти DataFrame в TreeGroup с родителями
#         return None

#     def open(self):
#         self.grab_set()
#         self.wait_window()
#         usr = self.new_parent
#         return usr

#     def fn_removComponent(self):
#         self.new_parent = self.sel[0]
#         self.destroy()
#         return None

#     def on_select(self, event):
#         self.sel = self.treeGroup.selection()

    # def fn_add_groupComponents(self):
    #     sql_insert_data_in_tableDBGroupComponent = 'INSERT INTO DBGroupComponent (code_group, name_group) values(?, ?)'
    #     if self.flagSelection:
    #         name_group=self.ent_NameComponent.get()
    #         data = []
    #         connectionDBFile = sqlite.connect(scfg.nameFile_DB)
    #         cursorDB = connectionDBFile.cursor()
    #         with connectionDBFile:
    #             sel = self.tree.selection()
    #             id_item=int(sel[0])
    #             code_group, flag_oversize_number_child = self.next_code_in_parent(id_item)
    #             if not(flag_oversize_number_child):
    #                 data.append(code_group)
    #                 data.append(name_group)
    #                 cursorDB.execute(sql_insert_data_in_tableDBGroupComponent, data)
    #                 connectionDBFile.commit()
    #             else:
    #                 msg = "Число подгрупп в родительской группе не должно быть больше 15"
    #                 mb.showerror("Ошибка", msg)
    #     return None

    # def next_code_in_parent(self, id_itemf):
    #     """
    #     генерация нового кода для элемета в родительской группе
    #     """
    #     #Считаем таблицы из файла БД и положим их в памятть
    #     # DBGroupF, flag_copyTableInMemory = dbcm.copy_FileDBGroupComponent_In_ListDBGroup(scfg.nameFile_DB)
    #     # for j in range (0, len(DBGroupF), 1):
    #     #         if DBGroupF[j].code_group ==
    #     flag_oversize_number_child_f = False
    #     next_id_item = id_itemf
    #     while next_id_item != '':
    #         id_itemf = next_id_item
    #         next_id_item = self.tree.next(id_itemf)
    #         print (id_itemf, ' - ', next_id_item)

    #     cg = []
    #     cg = mdbc.Unpack_codegroup(int(id_itemf))
    #     if cg[0]>=0x10 and cg[1]==0 and cg[2]==0 and cg[3]==0 and cg[4]==0: # если это группа верхнего уровня
    #         increment_item_in_parent = 0x010000
    #     elif cg[1]!=0 and cg[2]==0 and cg[3]==0 and cg[4]==0: # если это группа второго уровня
    #         increment_item_in_parent = 0x001000
    #     elif cg[2]!=0 and cg[3]==0 and cg[4]==0: # если это группа третьего уровня
    #         increment_item_in_parent = 0x000100
    #     elif cg[3]!=0 and cg[4]==0: # если это группа четвертого уровня
    #         increment_item_in_parent = 0x000010
    #     elif cg[4]!=0: # если это группа пятого уровня
    #         increment_item_in_parent = 0x000001
    #     new_code = int(id_itemf)+increment_item_in_parent
    #     flag_oversize_number_child_f = False
    #     # число детей в родительской группе не должно быть больше 15 (номер 0 - родитель)
    #     if (increment_item_in_parent == 0x010000) and (new_code >= 0xFA0000):
    #         new_code = id_itemf
    #         flag_oversize_number_child_f = True
    #     # elif (increment_item_in_parent == 0x001000) and (new_code >= 0x00E000)
    #     #     new_code = id_itemf
    #     #     flag_oversize_number_child_f = True
    #     return new_code, flag_oversize_number_child_f

    # def fn_edit_groupComponent(self):
    #     sql_update_query_in_tableDBGroupComponent = 'UPDATE DBGroupComponent SET name_group = ? WHERE code_group = ?'
    #     if self.flagSelection:
    #         var=self.ent_NameComponent.get()
    #         connectionDBFile = sqlite.connect(scfg.nameFile_DB)
    #         cursorDB = connectionDBFile.cursor()
    #         with connectionDBFile:
    #             sel = self.tree.selection()
    #             data = []
    #             #dic = self.tree.item(sel[0])
    #             name_group=var          #dic['text']
    #             code_group=int(sel[0])
    #             data.append(name_group)
    #             data.append(code_group)
    #             cursorDB.execute(sql_update_query_in_tableDBGroupComponent, data)
    #             connectionDBFile.commit()
    #         self.ent_NameComponent.delete(0, END)
    #         for i in self.tree.get_children(): self.tree.delete(i)      # очистим все дерево
    #         viewTreeGroup(self.tree)       # отобразим данные из памяти DBGroup в Tree
    #     else:
    #         mb.showinfo('Ошибка', 'Вы ничего не выделили!!!')
    #     self.flagSelection = False
    #     return None

    # def fn_delete_groupComponents(self):
    #     sql_delete_single_data_in_tableDBGroupComponent = 'DELETE FROM DBGroupComponent WHERE code_group = ?;'
    #     if self.flagSelection:
    #         connectionDBFile = sqlite.connect(scfg.nameFile_DB)
    #         cursorDB = connectionDBFile.cursor()
    #         with connectionDBFile:
    #             sel = self.tree.selection()
    #             data = int(sel[0])
    #             print(data)
    #             print(type(data))
    #             cursorDB.execute(sql_delete_single_data_in_tableDBGroupComponent, (data,))
    #             connectionDBFile.commit()
    #         for i in self.tree.get_children(): self.tree.delete(i)      # очистим все дерево
    #         viewTreeGroup(self.tree)       # отобразим данные из памяти DBGroup в Tree
    #     else:
    #         mb.showinfo('Ошибка', 'Вы ничего не выделили!!!')
    #     self.flagSelection = False
    #     self.ent_NameComponent.delete(0, END)
    #     return None

    # def on_select(self, event):
    #     #print(event)
    #     sel = self.tree.selection()
    #     print(sel)
    #     print(sel[0])
    #     # self.tree.see(sel[0])                 # не работает- не понято !!!!!!!!!
    #     dic = self.tree.item(sel[0])
    #     print(dic['text'])
    #     self.ent_NameComponent.delete(0, END)
    #     self.ent_NameComponent.insert(0, dic['text'])
    #     self.flagSelection = True

    #     return None

    # def confirm_delete(self):
    #     message = "Вы уверены, что хотите закрыть это окно?"
    #     if mb.askyesno(message=message, parent=self):
    #         self.destroy()

# class WindowImportComponent(tk.Toplevel):
#     def __init__(self, parent):
#         super().__init__(parent)
#         #self.protocol("WM_DELETE_WINDOW", self.confirm_delete)
#         self.frame_wig = tk.LabelFrame (master=self, text="Импорт групп", relief=tk.SUNKEN, borderwidth=3, height=50)
#         self.frame_wig.pack(fill=tk.X, side=tk.TOP, ipadx=5, ipady=5, padx=10, pady=10)
#         self.btn_wig = tk.Button(master=self.frame_wig, text="Импорт групп", command=self.press_Button_ImportGroup)
#         self.btn_wig.pack(fill=tk.X, expand=0, side=tk.TOP, ipadx=5, ipady=5)

#         self.frame_tableTree = tk.Frame(master=self, relief=tk.SUNKEN, borderwidth=3, height=50)
#         self.frame_tableTree.pack(fill=tk.X, side=tk.TOP, ipadx=5, ipady=5, padx=10, pady=5)
#         # Set the treeview
#         self.columns = ('NameID', 'id_code_item',  'id_code_parent',   'id_code_lvl', 'amount')

#         self.tree = ttk.Treeview(self.frame_tableTree, show="tree headings", columns=self.columns)
#             # Set the heading (Attribute Names)
#         self.tree.heading('#0', text='NameID')
#         self.tree.heading('#1', text='id_code_item')
#         self.tree.heading('#2', text='id_code_parent')
#         self.tree.heading('#3', text='id_code_group')
#         self.tree.heading('#4', text='amount')

#         self.ysb = ttk.Scrollbar(self.frame_tableTree, orient=tk.VERTICAL, command=self.tree.yview)
#         self.tree.configure(yscroll=self.ysb.set)
#             # Specify attributes of the columns (We want to stretch it!)
#         self.tree.column('#0', stretch=tk.YES)
#         self.tree.column('#1', stretch=tk.YES)
#         self.tree.column('#2', stretch=tk.YES)
#         self.tree.column('#3', stretch=tk.YES)
#         self.tree.column('#4', stretch=tk.YES)

#         self.tree.grid(row=0, column=0, sticky=tk.W + tk.E)
#         self.ysb.grid(row=0, column=1, sticky=tk.N + tk.S)

#         self.frame_tableTree.columnconfigure(0, weight=1)
#         self.tree.bind('<<TreeviewSelect>>', self.on_select)

#         if not(scfg.df1.empty):
#             viewTreeGroup(self.tree, scfg.df1)        # отобразим данные из памяти DataFrame в Tree

#     def on_select(self, event):
#         print(event)
#         print(self.tree.selection())
#         return None

#     def press_Button_ImportGroup(self):
#         mi.Load_DBGroup_From_XLS_pandas(scfg.nameFile_pu)
#         viewTreeGroup(self.tree, scfg.df1)       # отобразим данные из памяти DBGroup в Tree
#         return None

    # def confirm_delete(self):
    #     message = "Вы уверены, что хотите закрыть это окно?"
    #     if mb.askyesno(message=message, parent=self):
    #         self.destroy()

    # def fn_addGroup_Components(self):
    #     # запомним 'id_code_item' элемента из treeGroup
    #     id_code_item = self.treeGroup.selection()
    #     # получим от родителя  строку 'id_code_parent'
    #     df2 = scfg.df1[scfg.df1['id_code_item'] == id_code_item[0]]['id_code_parent']
    #     id_code_parent = df2.item()
    #     # получаем новое наименование из self.ent_NameComponent
    #     newNameComponent = self.ent_NameComponent.get()
    #     # сгенерим для него уникальный код
    #     codeItem = mdbc.getCode()
    #     # получим от родителя  строку 'id_code_lvl'
    #     df2 = scfg.df1[scfg.df1['id_code_item'] == id_code_item[0]]['id_code_lvl']
    #     id_lvl = df2.item()

    #     # сформируем строку для DataFrame
    #     new_row = {'name':newNameComponent, 'id_code_lvl': id_lvl, 'id_code_item': codeItem, 'id_code_parent':id_code_parent, 'amount':0} #append row to the dataframe
    #     # scfg.df1 = scfg.df1.append(new_row, ignore_index=True)
    #     # пересоздадим добавление строки в DataFrame  как рекомендует Pandas 1.4.0. 22jan2022
    #     df_new_row = pd.DataFrame(new_row , index=[0])
    #     scfg.df1 = pd.concat([scfg.df1, df_new_row])
    #     #  переиндексируем DataFrame
    #     scfg.df1 = scfg.df1.reset_index(drop=True)
    #     # очищаем дерево
    #     for i in self.tree2.get_children(): self.tree2.delete(i)
    #     # и выводим его заново
    #     viewTreeGroup(self.treeGroup, scfg.df1)
    #     # сохраняем изменненный DataFame в файл
    #     mi.Save_DataFrame_in_PickleFile()
    #     mi.Save_DataFrame_in_ExcelFile()

    #     return None

# def fn_renameGroup_Component(self):
    #     # запомним 'id_code_item' элемента из treeGroup
    #     id_code_item = self.treeGroup.selection()[0]
    #     # получаем выделенный элемент
    #     # sel = self.tree2.selection()
    #     # получаем индекс и 'id_code_item' выделенного элемента
    #     df2 = scfg.df1[scfg.df1['id_code_item'] == id_code_item]
    #     indx = df2.index
    #     # получаем измененное наименование из self.ent_NameComponent
    #     newNameComponent = self.ent_NameComponent.get()
    #     # изменяем наименоевание в DataFrame по индексу
    #     scfg.df1.loc[indx, 'name'] = newNameComponent
    #     # и выводим его заново
    #     viewTreeGroup(self.treeGroup, scfg.df1)
    #     self.treeGroup.see(id_code_item)
    #     self.treeGroup.selection_set(id_code_item)
    #     viewTreeComponents(self.tree2, scfg.df1, id_code_item)
    #     # сохраняем изменненный DataFame в файл
    #     mi.Save_DataFrame_in_PickleFile()
    #     mi.Save_DataFrame_in_ExcelFile()
    #     return None

# def fn_deleteGroup_Components(self):
    #     # запомним id_code_item выделенной строки в treeGroup
    #     id_code_item = self.treeGroup.selection()
    #     # постмотрим, есть ли у выделенного родителя потомки
    #     df2 = scfg.df1[scfg.df1['id_code_parent'] == id_code_item[0]]
    #     # пустая ли таблица df2?
    #     if df2.empty:
    #         df2 = scfg.df1[scfg.df1['id_code_item'] == id_code_item[0]]
    #         indx = df2.index
    #         # удаляем его из DataFrame по индексу
    #         scfg.df1 = scfg.df1.drop(index=indx)
    #         #  переиндексируем DataFrame
    #         scfg.df1 = scfg.df1.reset_index(drop=True)
    #         # очищаем дерево
    #         for i in self.tree2.get_children(): self.tree2.delete(i)
    #         # for i in self.treeGroup.get_children(): self.treeGroup.delete(i)
    #         # и выводим его заново
    #         viewTreeGroup(self.treeGroup, scfg.df1)
    #         # сохраняем изменненный DataFame в файл
    #         mi.Save_DataFrame_in_PickleFile()
    #         mi.Save_DataFrame_in_ExcelFile()
    #     else:
    #         message = "Группа компонентов не пуста!"
    #         mb.askyesno(message=message, parent=self)
    #         self.destroy()
    #     return None

# def fn_removeGroup_Components(self):
    #     # запомним 'id_code_item' элемента из treeGroup
    #     id_code_item = self.treeGroup.selection()
    #     # получаем индекс по 'id_code_item' выделенного элемента
    #     df2 = scfg.df1[scfg.df1['id_code_item'] == id_code_item[0]]
    #     indx = df2.index
    #     # выводим окно в котором спрашваем куда в дереве переместить
    #     # в ответ получаем  'id_code_parent' нового родителя
    #     new_id_code_parent = self.open_Window_Remove_Component()
    #     # проверим - если этот код родителя тот же самый selTreeGroup - ничего не делаем
    #     if (new_id_code_parent != id_code_item[0]) and (new_id_code_parent != 0):
    #         # изменяем код родителя компонента в DataFrame по индексу
    #         scfg.df1.loc[indx, 'id_code_parent'] = new_id_code_parent
    #         # очищаем дерево
    #         for i in self.tree2.get_children(): self.tree2.delete(i)
    #         # for i in self.treeGroup.get_children(): self.treeGroup.delete(i)
    #         # и выводим его заново
    #         viewTreeGroup(self.treeGroup, scfg.df1)
    #         # сохраняем изменненный DataFame в файл
    #         mi.Save_DataFrame_in_PickleFile()
    #         mi.Save_DataFrame_in_ExcelFile()
    #     return None


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from caffe2.python import core
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import hypothesis.strategies as st
import numpy as np

class TestClipTensorByScalingOp(hu.HypothesisTestCase):

    @given(n=st.integers(5, 8), d=st.integers(2, 4),
           threshold=st.floats(0.1, 10),
           inplace=st.booleans(),
           **hu.gcs_cpu_only)
    def test_clip_tensor_by_scaling(self, n, d, threshold, inplace, gc, dc):

        tensor = np.random.rand(n, d).astype(np.float32)
        val = np.array(np.linalg.norm(tensor))

        def clip_tensor_by_scaling_ref(tensor_data, val_data):
            if val_data > threshold:
                ratio = threshold / float(val_data)
                tensor_data = tensor_data * ratio

            return [tensor_data]

        op = core.CreateOperator(
            "ClipTensorByScaling",
            ["tensor", "val"],
            ['Y'] if not inplace else ["tensor"],
            threshold=threshold,
        )

        self.assertReferenceChecks(
            device_option=gc,
            op=op,
            inputs=[tensor, val],
            reference=clip_tensor_by_scaling_ref,
        )

if __name__ == "__main__":
    import unittest
    unittest.main()


def strings_to_table(str1, str2):
    table = [[]]
    table[0].append(0)
    for letter in str1:
        table[0].append(letter)
    for letter in str2:
        table.append([letter])
    return table

def find_max_substring(str1, str2):
    table = strings_to_table(str1, str2)
    max_len_substring = 0
    for y in range(1, len(table)):
        for x in range(1, len(table[0])):
            if y == x and table[y][0] == table[0][x]:
                new_cost = int(table[y-1][x-1]) + 1
                table[y].append(new_cost)
                if new_cost > max_len_substring:
                    max_len_substring = new_cost
            else:
                table[y].append(0)
    return max_len_substring

print(find_max_substring("hish", "fish"))


#coding=utf-8

from socket import *

# 创建Socket
serverSocket = socket(AF_INET, SOCK_STREAM)

# 绑定
serverSocket.bind((("", 8899)))

# listen,数字"5"表示已建立和未建立的队列总长度
serverSocket.listen(5)

# clientSocket表示新的客户端, clientInfo表示新的客户端的ip以及短裤
clientSocket, clientInfo = serverSocket.accept()

# 接受数据,最大字节数为1024
recvData = clientSocket.recv(1024)

# 打印
print("%s:%s"%(str(clientInfo), recvData))

# 关闭套接字
clientSocket.close()
serverSocket.close()


import logging

# ============ mapping helpers start ============
# The mapping here are for ad hoc testing. The real mappings will be different
# from project to project and will be added in future CLs.

def FindBuganizerComponentId(monorail_component):
  # temp. will have real mapping.
  del monorail_component
  return 1325852

def FindBuganizerComponents(monorail_project_name):
  """return a list of components in buganizer based on the monorail project

  The current implementation is ad hoc as the component mappings are not
  fully set up on buganizer yet.
  """
  if monorail_project_name == 'MigratedProject':
    return ['1325852']
  return []

def FindMonorailProject(buganizer_component_id):
  if buganizer_component_id == '1325852':
    return 'MigratedProject'
  return ''

def FindBuganizerHotlists(monorail_labels):
  hotlists = []
  for label in monorail_labels:
    hotlist = _FindBuganizerHotlist(label)
    if hotlist:
      hotlists.append(hotlist)
  logging.debug(
    '[PerfIssueService] labels (%s) -> hotlists (%s)',
    monorail_labels, hotlists)
  return hotlists

def _FindBuganizerHotlist(monorail_label):
  if monorail_label == 'chromeperf-test':
    return '5141966'
  elif monorail_label == 'chromeperf-test-2':
    return '5142065'
  return None

def _FindMonorailLabel(buganizer_hotlist):
  if buganizer_hotlist == '5141966':
    return 'chromeperf-test'
  elif buganizer_hotlist == '5142065':
    return 'chromeperf-test-2'
  return None

def _FindMonorailStatus(buganizer_status):
  if buganizer_status == 'NEW':
    return 'Unconfirmed'
  elif buganizer_status == 'ASSIGNED':
    return "Assigned"
  elif buganizer_status == 'ACCEPTED':
    return 'Started'
  elif buganizer_status == 'FIXED':
    return 'Fixed'
  elif buganizer_status == 'VERIFIED':
    return 'Verified'
  return 'Untriaged'

def FindBuganizerStatus(monorail_status):
  if monorail_status == 'Unconfirmed':
    return 'NEW'
  elif monorail_status == 'Assigned':
    return "ASSIGNED"
  elif monorail_status == 'Started':
    return 'ACCEPTED'
  elif monorail_status == 'Fixed':
    return 'FIXED'
  elif monorail_status == 'Verified':
    return 'VERIFIED'
  return 'STATUS_UNSPECIFIED'

# ============ mapping helpers end ============

def GetBuganizerStatusUpdate(issue_update, status_enum):
  ''' Get the status from an issue update

  In Buganizer, each update event is saved in an issueUpdate struct like:
    {
      "author": {
        "emailAddress": "wenbinzhang@google.com"
      },
      "timestamp": "2023-07-28T22: 17: 34.721Z",
      ...
      "fieldUpdates": [
        {
          "field": "status",
          "singleValueUpdate": {
            "oldValue": {
              "@type": "type.googleapis.com/google.protobuf.Int32Value",
              "value": 2
            },
            "newValue": {
              "@type": "type.googleapis.com/google.protobuf.Int32Value",
              "value": 4
            }
          }
        }
      ],
      ...
      "version": 5,
      "issueId": "285172796"
    }
  Noticed that each update on the UI can have multiple operations, but each of
  operations is a single issue update. So far we only use the 'status' value,
  thus the other updates like priority change are not returned here.
  '''
  for field_update in issue_update.get('fieldUpdates', []):
    if field_update.get('field') == 'status':
      new_status = field_update.get('singleValueUpdate').get('newValue').get('value')

      # The current status returned from issueUpdate is integer, which is
      # different from the definition in the discovery doc.
      # I'm using  service._schema.get() to load the schema in JSON.
      if isinstance(new_status, int):
        new_status = status_enum[new_status]

      status_update = {
        'status': _FindMonorailStatus(new_status)
      }
      return status_update
  return None

def LoadPriorityFromMonorailLabels(monorail_labels):
  ''' Load the priority from monorail labels if it is set

  In Monorail, a label like 'Pri-X' is used set the issue's priority to X.
  X can be range from 0 to 4. Currently Monorail scan the labels in order
  and set the priority as it sees any. Thus, the last X will be kept. Here
  we changed the logic to keep the highest level (lowest value.)

  Args:
    monorail_labels: a list of labels in monorail fashion.

  Returns:
    the priority from the label if any, otherwise 2 by default.
  '''
  priority = 99
  for label in monorail_labels:
    if label.startswith('Pri-'):
      label_priority = int(label[4])
      priority = min(priority, label_priority)
  if priority == 99:
    return 2
  return priority

def ReconcileBuganizerIssue(buganizer_issue):
  '''Reconcile a Buganizer issue into the Monorail format

  During the Buganizer migration, we try to minimize the changes on the
  consumers of the issues. Thus, we will reconcile the results into the
  exising Monorail format before returning the results.
  '''
  monorail_issue = {}
  issue_state = buganizer_issue.get('issueState')

  monorail_issue['projectId'] = FindMonorailProject(issue_state['componentId'])

  monorail_issue['id'] = buganizer_issue['issueId']

  buganizer_status = issue_state['status']
  if buganizer_status in ('NEW', 'ASSIGNED', 'ACCEPTED'):
    monorail_issue['state'] = 'open'
  else:
    monorail_issue['state'] = 'closed'

  monorail_issue['status'] = _FindMonorailStatus(buganizer_status)

  monorail_author = {
    'name': issue_state['reporter']
  }
  monorail_issue['author'] = monorail_author

  monorail_issue['summary'] = issue_state['title']

  monorail_issue['owner'] = issue_state.get('assignee', None)

  hotlist_ids = buganizer_issue.get('hotlistIds', [])
  label_names = [_FindMonorailLabel(hotlist_id) for hotlist_id in hotlist_ids]
  monorail_issue['labels'] = [label for label in label_names if label]

  return monorail_issue


import sys
import time
import win32api
import win32con
import aircv as ac
from math import fabs
from PIL import ImageGrab
from win32gui import *
import atexit
import datetime
import os
from PIL import Image, ImageDraw, ImageFile
import numpy
import pytesseract
import cv2
import imagehash
import collections

windowHandleGame = 0
gameSize = ""
shuaXinCount = 0  # 刷新次数
useJewel = 0  # 使用钻石
useMoney = 0  # 使用金钱
shenmiCount = 0  # 神秘次数
shengyueCount = 0  # 圣约次数
sleepSize = 1.2  # 程序等待多长时间(秒)
threshold = 0.7  # 比较图片的阈值，影响精准度，取值在0到1之间
windowHandleName = "BlueStacks App Player"  # 模拟器窗口的名称
windowChilHandleName = "BlueStacks Android PluginAndroid"

def compare_image_with_hash(self, image_file1="images/desktop.jpg",
                            image_file2="images/desktopCompare.jpg", max_dif=7):
    ImageFile.LOAD_TRUNCATED_IMAGES = True
    hash_1 = None
    hash_2 = None
    with open(image_file1, 'rb') as fp:
        hash_1 = imagehash.average_hash(Image.open(fp))
        print(hash_1)
    with open(image_file2, 'rb') as fp:
        hash_2 = imagehash.average_hash(Image.open(fp))
        print(hash_2)
    dif = hash_1 - hash_2
    print(dif)
    if dif < 0:
        dif = -dif
    if dif <= max_dif:
        return True
    else:
        return False

def winfun(hwnd, lparam):
    global windowHandleGame
    s = GetWindowText(hwnd)
    if windowChilHandleName == s:
        windowHandleGame = hwnd
    return 1

@atexit.register
def endGame():
    f1 = open('res.txt', 'w')
    f1.write("时间:" + str(datetime.datetime.now()) + "\n")
    f1.write("刷新次数:" + str(shuaXinCount) + "\n")
    f1.write("使用钻石:" + str(useJewel) + "\n")
    f1.write("使用金钱:" + str(useMoney) + "\n")
    f1.write("神秘次数:" + str(shenmiCount) + "\n")
    f1.write("圣约次数:" + str(shengyueCount) + "\n")
    f1.write("...by Konvite")
    f1.close()

def compareShengyue(desktop, picture):
    yigoumaishengyue = ac.imread("images/yigoumaishengyue.png")
    useRes = ac.find_template(desktop, yigoumaishengyue, threshold)
    if useRes == None:
        return True
    res = ac.find_template(desktop, picture, threshold)
    if res == None:
        return False
    if useRes['confidence'] > res['confidence']:
        return False
    return True

def compareShenmi(desktop, picture):
    yigoumaishenmi = ac.imread("images/yishiyongshenmi.png")
    useRes = ac.find_template(desktop, yigoumaishenmi, threshold)
    if useRes == None:
        return True
    res = ac.find_template(desktop, picture, threshold)
    if res == None:
        return False
    if useRes['confidence'] > res['confidence']:
        return False
    return True

def comparePicture(desktop, picture):
    res = ac.find_template(desktop, picture, threshold)
    if res == None:
        return None
    clickSize = res['result']
    return [int(clickSize[0]), int(clickSize[1])]

def gameAutoStart():
    goumai = ac.imread("images/goumai.png")
    shenmi = ac.imread("images/shenmi.png")
    shengyue = ac.imread("images/shengyue.png")
    shuaxin = ac.imread("images/shuaxin.png")
    queren = ac.imread("images/queren.png")

    global shuaXinCount
    global useJewel
    global windowHandleName
    game = FindWindow(0, windowHandleName)
    ShowWindow(game, win32con.SW_SHOWNOACTIVATE)
    SetWindowPos(game, win32con.HWND_TOPMOST, 0, 0, 300, 300, win32con.SWP_SHOWWINDOW)
    time.sleep(sleepSize)
    game = FindWindow(0, windowHandleName)
    EnumChildWindows(game, winfun, None)
    global gameSize
    gameSize = GetWindowRect(windowHandleGame)

    jiequ_DeskTop(gameSize)

    desktop = ac.imread("images/desktop.jpg")

    autoBuy(desktop, goumai, shengyue, shenmi)
    endGame()

    while True:
        time.sleep(0.5)
        res = comparePicture(desktop, shuaxin)
        if res != None:
            windowClick(res)
            time.sleep(sleepSize)
            jiequ_DeskTopCompare(gameSize)
            while True:
                if compare_image_with_hash(None):
                    windowClick(res)
                    time.sleep(sleepSize)
                    jiequ_DeskTopCompare(gameSize)
                else:
                    break

            jiequ_DeskTop(gameSize)
            desktop = ac.imread("images/desktop.jpg")
            res = comparePicture(desktop, queren)
            if res != None:
                windowClick(res)
                time.sleep(sleepSize + 0.2)
                jiequ_DeskTopCompare(gameSize)
                while True:
                    if compare_image_with_hash(None):
                        windowClick(res)
                        time.sleep(sleepSize + 0.2)
                        jiequ_DeskTopCompare(gameSize)
                    else:
                        break
                shuaXinCount = shuaXinCount + 1
                useJewel = useJewel + 3
        jiequ_DeskTop(gameSize)
        desktop = ac.imread("images/desktop.jpg")
        autoBuy(desktop, goumai, shengyue, shenmi)
        endGame()

def windowClick(res):
    zzzs = win32api.MAKELONG(res[0], res[1])
    SendMessage(windowHandleGame, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    SendMessage(windowHandleGame, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, zzzs)
    time.sleep(0.05)
    SendMessage(windowHandleGame, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, zzzs)

def jiequ_DeskTop(gameSize):
    ImageGrab.grab([gameSize[0], gameSize[1], gameSize[2], gameSize[3]]).save("images/desktop.jpg")

def jiequ_DeskTopCompare(gameSize):
    ImageGrab.grab([gameSize[0], gameSize[1], gameSize[2], gameSize[3]]).save("images/desktopCompare.jpg")

def autoBuy(desktop, goumai, shengyue, shenmi):
    clickMouse(desktop, shengyue, shenmi, goumai, 4)
    time.sleep(sleepSize)
    point = win32api.MAKELONG(int(gameSize[2] / 2), -int(gameSize[3] / 1.3))
    pointEnd = win32api.MAKELONG(int(gameSize[2] / 1.5), 0)
    PostMessage(windowHandleGame, win32con.WM_MOUSEWHEEL, point, pointEnd)
    time.sleep(sleepSize + 0.5)
    jiequ_DeskTop(gameSize)
    desktop = ac.imread("images/desktop.jpg")
    clickMouse(desktop, shengyue, shenmi, goumai, 5)

def clickMouse(desktop, shengyue, shenmi, goumai, maxCount):
    global useMoney
    global shenmiCount
    global shengyueCount

    res = comparePicture(desktop, shenmi)
    if res != None:
        if compareShenmi(desktop, shenmi):
            shenmiCount = shenmiCount + 1
            useMoney = useMoney + 280000
            allRes = ac.find_all_template(desktop, goumai)
            clickMouse_GouMai(allRes, res, desktop, goumai, maxCount)
    res = comparePicture(desktop, shengyue)
    if res != None:
        if compareShengyue(desktop, shengyue):
            shengyueCount = shengyueCount + 1
            useMoney = useMoney + 184000
            allRes = ac.find_all_template(desktop, goumai)
            clickMouse_GouMai(allRes, res, desktop, goumai, maxCount)

def clickMouse_GouMai(allRes, res, desktop, goumai, maxCount):
    finalClickSize = []
    finalClickVal = 0
    allList = []
    if allRes != None:
        for index in range(len(allRes)):
            if index == maxCount:
                break
            if index == 0:
                clickSize = allRes[index]['result']
                finalClickSize = [int(clickSize[0]), int(clickSize[1])]
                finalClickVal = fabs(finalClickSize[1] - res[1])
                continue
            clickSize = allRes[index]['result']
            allList.append([int(clickSize[0]), int(clickSize[1])])
    for re in allList:
        val = fabs(re[1] - res[1])
        if val < finalClickVal:
            finalClickVal = val
            finalClickSize = re
    windowClick(finalClickSize)
    time.sleep(sleepSize)
    jiequ_DeskTopCompare(gameSize)
    while True:
        if compare_image_with_hash(None):
            windowClick(finalClickSize)
            time.sleep(sleepSize)
            jiequ_DeskTopCompare(gameSize)
        else:
            break

    jiequ_DeskTop(gameSize)
    desktop = ac.imread("images/desktop.jpg")
    res = ac.find_template(desktop, goumai, 0.7)
    clickSize = res['result']

    windowClick([int(clickSize[0]), int(clickSize[1])])
    time.sleep(sleepSize)
    jiequ_DeskTopCompare(gameSize)
    while True:
        if compare_image_with_hash(None):
            windowClick([int(clickSize[0]), int(clickSize[1])])
            time.sleep(sleepSize)
            jiequ_DeskTopCompare(gameSize)
        else:
            break

if __name__ == '__main__':
    gameAutoStart()


# 2775번 부녀회장이 될테야
# https://www.acmicpc.net/problem/2775
import sys

input = sys.stdin.readline

def dp(x, y):
    if ls[x][y] != 0:
        return ls[x][y]
    if y == 0:
        return 1
    return dp(x-1, y) + dp(x, y-1)

t = int(input())
while t != 0:
    k, n = [int(input()) for _ in range(2)]
    ls = [[i+1 for i in range(n)]] + [[0 for _ in range(n)] for _ in range(k)]
    for j in range(1, k+1):
        for l in range(n):
            ls[j][l] = dp(j, l)
    print(ls[k][n-1])
    t -= 1


# 초기 주사위 상태
dice = [[0,0,0],
        [0,0,0],
        [0,0,0],
        [0,0,0]]

dir = [[1,0],[-1,0],[0,-1],[0,1]]

# 방향 별 움직임에 따른 주사위 전개도 변화
def move(d):
    tmp = dice[3][1]
    # 동쪽 이동
    if d == 0:
        dice[3][1] = dice[1].pop(-1)
        dice[1].insert(0,tmp)
    # 남쪽 이동
    elif d == 3:
        tmp = dice[3][1]
        for i in range(2,-1,-1):
            dice[i+1][1] = dice[i][1]
        dice[0][1] = tmp
    # 서쪽 이동
    elif d == 1:
        dice[3][1] = dice[1].pop(0)
        dice[1].append(tmp)
    # 북쪽 이동
    elif d == 2:
        tmp = dice[0][1]
        for i in range(3):
            dice[i][1] = dice[i+1][1]
        dice[3][1] = tmp

n,m,y,x,k = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(n)]
dirList = list(map(int, input().split()))
px,py = x,y
for d in dirList:
    dx,dy = dir[d-1]
    # 일단 다음 칸으로 이동한 후에
    x,y = x+dx,y+dy
    # 범위를 벗어났을 시 원래대로 돌려줌
    if not (0 <= x < m and 0 <= y < n):
        x,y = x-dx,y-dy
        continue
    move(d-1)
    # 현재 위치 타일이 0이라면
    if arr[y][x] == 0:
        # 해당 타일에 주사위 밑면의 숫자를 넣음
        arr[y][x] = dice[3][1]
    # 타일이 0이 아니라면
    else:
        # 다이스의 밑면을 타일의 숫자로 만들고 타일을 0으로 만듦
        dice[3][1] = arr[y][x]
        arr[y][x] = 0
    # 다이스 윗면 출력
    print(dice[1][1])


from django.urls import path
from . import views

urlpatterns = [
 path('', views.index, name="index"), # /app
 path('registration/', views.register, name="register"), #/app/registration
 path('daily/', views.daily, name="daily"),
 path('models/', views.models, name="models"),
 path('keydates/', views.keydates, name="keydates"),
 path('about/', views.about, name="about")
]


import sys, re

rex = re.compile(
r'''\s*# t/s: (?P<preset>\d+)\s*
# sum: (?P<countsum>\d+)\s*
# mon: (?P<monitor>\d+)\s*
# A:   (?P<A>[0-9.]+)\s+\+/-\s+(?P<dA>[0-9.]+)
# B:   (?P<B>[0-9.]+)\s+\+/-\s+(?P<dB>[0-9.]+)
# phi: (?P<phi>[0-9.]+)\s+\+/-\s+(?P<dphi>[0-9.]+)
# C:   (?P<C>[0-9.]+)\s+\+/-\s+(?P<dC>[0-9.]+)\s*''')

settings = ['46_69', '72_108', '99_148p5', '138_207', '200_300']

outname = sys.argv[1]
varval = sys.argv[2]
setting = sys.argv[3]
if len(setting) == 1:
    setting = settings[int(setting)]
fname = '%05d' % int(sys.argv[4])

f = open(outname, 'a')

m = rex.match(sys.stdin.read())
values = m.groupdict().copy()
values['varval'] = varval
values['setting'] = setting
values['tau'] = '-'
values['fname'] = fname

fieldorder = ['varval', 'varval', 'setting', 'tau', 'preset', 'countsum',
              'monitor', 'A', 'B', 'phi', 'C', 'dA', 'dB', 'dphi', 'dC', 'fname']
f.write(' ' + ' '.join(values[field].rjust(10) for field in fieldorder) + '\n')


"""
Student facing code for Tantrix Solitaire
http://www.jaapsch.net/puzzles/tantrix.htm

Game is played on a grid of hexagonal tiles.
All ten tiles for Tantrix Solitaire and place in a corner of the grid.
Click on a tile to rotate it.  Cick and drag to move a tile.

Goal is to position the 10 provided tiles to form
a yellow, red or  blue loop of length 10
"""

# Core modeling idea - a triangular grid of hexagonal tiles are
# model by integer tuples of the form (i, j, k)
# where i + j + k == size and i, j, k >= 0.

# Each hexagon has a neighbor in one of six directions
# These directions are modeled by the differences between the
# tuples of these adjacent tiles

# Numbered directions for hexagonal grid, ordered clockwise at 60 degree intervals
DIRECTIONS = {0 : (-1, 0, 1), 1 : (-1, 1, 0), 2 : (0, 1, -1),
              3 : (1, 0, -1), 4 : (1, -1, 0), 5 : (0,  -1, 1)}

def reverse_direction(direction):
    """
    Helper function that returns opposite direction on hexagonal grid
    """
    num_directions = len(DIRECTIONS)
    return (direction + num_directions / 2) % num_directions

# Color codes for ten tiles in Tantrix Solitaire
# "B" denotes "Blue", "R" denotes "Red", "Y" denotes "Yellow"
SOLITAIRE_CODES = ["BBRRYY", "BBRYYR", "BBYRRY", "BRYBYR", "RBYRYB",
                "YBRYRB", "BBRYRY", "BBYRYR", "YYBRBR", "YYRBRB"]

# Minimal size of grid to allow placement of 10 tiles
MINIMAL_GRID_SIZE = 4

class Tantrix:
    """
    Basic Tantrix game class
    """

    def __init__(self, size, tile_value = None):
        """
        Create a triangular grid of hexagons with size + 1 tiles on each side.
        """
        assert size >= MINIMAL_GRID_SIZE, "Grid is too small!"
        # Initialize dictionary tile_value to contain codes for ten
        # tiles in Solitaire Tantrix in one 4x4 corner of grid
        self._size = size

        if tile_value == None:
            self._tile_value = {(0,size,0): "BBRRYY", (1,size-1,0): "BBRYYR", (2,size-2 ,0):"BBYRRY", (3,size-3,0): "BRYBYR",
                            (0,size-1,1):"RBYRYB", (1,size-2,1):"YBRYRB", (2,size-3,1): "BBRYRY",
                            (0,size-2,2):"BBYRYR", (1,size-3,2):"YYBRBR",
                            (0,size-3,3): "YYRBRB"}
        else:
            self._tile_value = tile_value

    def __str__(self):
        """
        Return string of dictionary of tile positions and values
        """
        s = "Tile positions and values: \n"
        for key, val in self._tile_value.items():
            s += str(key) +": "+ val +"\n"
        return s

    def get_tiling_size(self):
        """
        Return size of board for GUI
        """
        return self._size

    def tile_exists(self, index):
        """
        Return whether a tile with given index exists
        """
        for tile in self._tile_value.keys():
            if index == tile:
                return True
        return False

    def place_tile(self, index, code):
        """
        Play a tile with code at cell with given index
        """
        self._tile_value[index]=code

    def remove_tile(self, index):
        """
        Remove a tile at cell with given index
        and return the code value for that tile
        """
        code = self._tile_value[index]
        self._tile_value.pop(index)
        return code

    def rotate_tile(self, index):
        """
        Rotate a tile clockwise at cell with given index
        """
        code = self._tile_value[index]
        new_code = code[-1]+code[:-1]
        self._tile_value[index] = new_code

    def get_code(self, index):
        """
        Return the code of the tile at cell with given index
        """
        return self._tile_value[index]

    def get_neighbor(self, index, direction):
        """
        Return the index of the tile neighboring the tile with given index in given direction.
        Note that the returns postition may empty or outside the game board.
        """
        return (index[0] + direction[0], index[1] + direction[1], index[2] + direction[2])

    def is_legal(self):
        """
        Check whether a tile configuration obeys color matching rules for adjacent tiles
        """
        for index, code in self._tile_value.items():
            for direction_number, direction in DIRECTIONS.items():
                neighbor = self.get_neighbor(index, direction)
                if self.tile_exists(neighbor):
                    neighbor_code = self.get_code(neighbor)
                    if code[direction_number] != neighbor_code[(direction_number+3)%6]:
                        return False
        return True

    def get_outgoing_direction(self, index, color, ingoing_direction):
        """
        Returns an outgoing direction number corresponding to given index and color ("R", "B" or "Y")
        Ingoing_direction is relative to the tile in question
        """
        code = self.get_code(index)
        for direction_number in range(6):
            if code[direction_number] == color and direction_number != ingoing_direction:
                return direction_number

    def has_loop(self, color):
        """
        Check whether a tile configuration has a loop of size 10 of given color
        """
        if not self.is_legal():
            return False

        # choose arbitrary starting point
        first_index, first_code = self._tile_value.items()[0]
        investigation_number = 1
        index = first_index
        direction_number = self.get_outgoing_direction(first_index, color, None)

        # loop through neighboring tiles that match given color
        while index != first_index or investigation_number == 1:
            neighbor_index = self.get_neighbor(index, DIRECTIONS[direction_number])
            if not self.tile_exists(neighbor_index):
                return False
            neighbor_code = self.get_code(neighbor_index)
            neighbor_incomming_dir = (direction_number + 3 ) % 6
            if neighbor_code[neighbor_incomming_dir] != color:
                return False
            else:
                investigation_number += 1
                index = neighbor_index
                direction_number = self.get_outgoing_direction(index, color, neighbor_incomming_dir)

        if investigation_number == 10:
            return True
        return False

#t= Tantrix(6)
#print t.is_legal()

# run GUI for Tantrix
#import poc_tantrix_gui
#poc_tantrix_gui.TantrixGUI(Tantrix(6))


import random
import time

def merge(a,b):
    """ Function to merge two arrays """
    c = []
    while len(a) != 0 and len(b) != 0:
        if a[0] < b[0]:
            c.append(a[0])
            a.remove(a[0])
        else:
            c.append(b[0])
            b.remove(b[0])
    if len(a) == 0:
        c += b
    else:
        c += a
    return c

def mergesort(x):
    """ Function to sort an array using merge sort algorithm """
    if len(x) == 0 or len(x) == 1:
        return x
    else:
        middle = len(x)//2
        a = mergesort(x[:middle])
        b = mergesort(x[middle:])
        return merge(a,b)

def insert(x, num):
    for i in range(0,num):
        x.append(random.randrange(0,100000,1))

index = [1000, 5000, 10000, 20000, 25000, 50000, 100000, 1000000]
list1 = []

for i in index:
    print("\n\nFor Index : {}\n" .format(i))

    #average
    insert(list1, i)
    start = time .time()
    mergesort(list1)
    end = time.time()
    print("Average Case : {}\n" .format((end-start) * 1000))
    del list1
    list1 = []

    #best case
    insert(list1, i)
    list1.sort()
    start = time .time()
    mergesort(list1)
    end = time.time()
    print("Best Case : {}\n" .format((end-start) * 1000))
    del list1
    list1 = []

    #worst
    insert(list1, i)
    list1.reverse()
    start = time .time()
    mergesort(list1)
    end = time.time()
    print("Worst Case : {}\n" .format((end-start) * 1000))
    del list1
    list1 = []


import pymysql.cursors
import json
from DBConnector import DBConnector

# Connect to the database
dbconnector = DBConnector('localhost','root','','gerrit_test')

inline_comments = dbconnector.inline_comments()
patch_details = dbconnector.patch_details()
patches = dbconnector.patches()
# people = dbconnector.people()
requests = dbconnector.requests()
request_details = dbconnector.request_detail()
review_comments = dbconnector.review_comments()
reviews = dbconnector.reviews()

def getInlineComments(patch_id, req_id):
	I = {}
	for comment in inline_comments:
			if comment["patchset_id"] == patch_id and comment["request_id"] == req_id:
					I[comment["file_name"]] = {
						'comment_id': comment["comment_id"],
						'in_reply_to': comment["in_reply_to"],
						'line_number': comment["line_number"],
						'author_id': comment["author_id"],
						'written_on': comment["written_on"],
						'status': comment["status"],
						'side': comment["side"],
						'message': comment["message"],
						'start_line': comment["start_line"],
						'end_line': comment["end_line"],
						'start_character': comment["start_character"],
						'end_character': comment["end_character"],
						'sentiment_score': comment["sentiment_score"]
					}
	return I

def getReviews(req_id):
	R = {}
	for review in reviews:
		if review["request_id"] == req_id:
			R[review["id"]] = {
				'people_id': review["people_id"],
				'verified': review["verified"],
				'reviewed': review["reviewed"],
				'build': review["build"]
			}

	return R

def getPatchDetails(patch_id , req_id):
	D = {}
	for patch_detail in patch_details:
		if patch_detail["request_id"] == req_id and patch_detail["patchset_id"] == patch_id:
			D[patch_detail["file_name"]] = {
				'change_type': patch_detail["change_type"],
				'insertions': patch_detail["insertions"],
				'deletions': patch_detail["deletions"]
			}
			print(D[patch_detail["file_name"]])
	return D

def getPatches(patch_id , req_id):
	p = {}
	for patch in patches:
		if patch["request_id"] == req_id:
			p[patch["patch_id"]] = {
				'revision':  patch["revision"],
				'patchset_number':  patch["patchset_number"],
				'comment_count':  patch["comment_count"],
				'subject':  patch["subject"],
				'message':  patch["message"],
				'checkout':  patch["checkout"],
				'author':  patch["author"],
				'committer':  patch["committer"],
				'created':  patch["created"],
				'committed':  patch["committed"],
				'patch_file_details': getPatchDetails(patch_id , req_id),
				'inline_comments': getInlineComments(patch_id , req_id),
				'reviews': getReviews(req_id)
			}
	return p

def MakeRequestDict(req_id):
	for request_detail in request_details:
		if request_detail["request_id"] == req_id:
			return {
				'change_id': request_detail["change_id"],
				'gerrit_id': request_detail["gerrit_id"],
				'project': request_detail["project"],
				'branch': request_detail["branch"],
				'subject': request_detail["subject"],
				'status': request_detail["status"],
				'created': request_detail["created"],
				'updated': request_detail["updated"],
				'insertions': request_detail["insertions"],
				'deletions': request_detail["deletions"],
				'owner': request_detail["owner"],
				'number_patches': request_detail["number_patches"],
				'curent_patch_id': request_detail["curent_patch_id"],
				'revisions': getPatches(request_detail["curent_patch_id"] , req_id)
			}
	return {}

finalJSON = {}
## Here we will be getting list of 12k dict, which will be converted into JSON Array

# finalJSON[1] = MakeRequestDict(1)

for request in requests:
	finalJSON[request["request_id"]] = MakeRequestDict(request["request_id"])

	if len(finalJSON[request["request_id"]]) == 0:
		finalJSON.pop(request["request_id"])

with open('data.json', 'w') as outfile:
   json.dump(finalJSON, outfile)

# y = json.dumps(finalJSON)
# print(y)
# print(requests[0][0])


import pandas as pd
from nltk.tokenize import TweetTokenizer
import nltk
from nltk.stem import SnowballStemmer
from nltk.corpus import stopwords

data_path_training='../benchmark_system/SemEval2018-T3-train-taskA.txt'
trainingData = pd.read_csv(data_path_training, sep='\t')

data_path_test='../datasets/goldtest_TaskA/SemEval2018-T3_gold_test_taskA_emoji.txt'
testData = pd.read_csv(data_path_test, sep='\t')
trainingData.drop('Tweet index', axis=1, inplace=True)
testData.drop('Tweet index', axis=1, inplace=True)

arrayTraing = trainingData.values
X_training = arrayTraing[:, 1]
Y_training = arrayTraing[:, 0].astype(int)

arrayTest = testData.values
X_test = arrayTest[:, 1]
Y_test = arrayTest[:, 0].astype(int)


import random
import time

class TestCase(object):

    def __init__(self, serial, logger, input_window, button_window):
        self.serial = serial
        self.logger = logger
        self.input_window = input_window
        self.button_window = button_window

    def test(self):
        sleep_time = random.randint(1, 10)
        self.logger('测试程序等待 %d 秒！' % sleep_time)
        time.sleep(sleep_time)
        res = random.randint(0, 1)
        self.logger('测试结果 %d ！' % sleep_time)
        return res == 0


import json
import os
import pandas as pd
from services.db_service import engine
from dotenv import load_dotenv
from services.json_unpack_service import UnPackObj

file_path = os.path.join(os.path.dirname(__file__), "..")
load_dotenv(os.path.join(file_path, ".env"))

def _get_marketfact_exclusion(crop, spatial_hiearchy_type, spatial_hiearchy_value):
    exclude_definition_id = str(os.getenv("EXCLUDE_DEFINITION_ID", ""))
    if crop:
        crop_filter = f"and crop = '{crop}'"
    else:
        crop_filter = ""
    sql = f"select grid_id, product_dimension from datafactory.market_facts where definition_id = '{exclude_definition_id}' " \
           f"{crop_filter} and {spatial_hiearchy_type} = '{spatial_hiearchy_value}'"
    return pd.read_sql(sql, engine)

def _filter_productdimension(market_facts, product_dimension):
    market_facts_json = market_facts.to_json(orient="records")
    market_facts_data = json.loads(market_facts_json)
    market_facts_irrigation_types = []
    irrigation_types = []
    for fact in market_facts_data:
        if not isinstance(fact['product_dimension'], str):
            for dim in product_dimension:
                if dim['type'] in fact['product_dimension'].values():
                    prod_dim = UnPackObj().extract_obj(product_dimension).get(dim['type'], None)
                    if isinstance(prod_dim, list):
                        irrigation_types.extend(prod_dim)
                    else:
                        irrigation_types.append(prod_dim)
                    market_facts_irrigation_types.append(fact['product_dimension'].get('value',None))
        else:
            return True

    if set(irrigation_types) == set(market_facts_irrigation_types):
        return True

def exclude(gridcell, crop, product_dimension):
    # Check adminlevel1
    market_facts_level_1 = _get_marketfact_exclusion(crop, "adminlevel1_code", gridcell['country_code'])
    if not market_facts_level_1.empty and _filter_productdimension(market_facts_level_1, product_dimension):
        return True

    # Check grid_id
    market_facts_level_2 = _get_marketfact_exclusion(None, "grid_id", gridcell['grid_id'])
    if not market_facts_level_2.empty and _filter_productdimension(market_facts_level_2, product_dimension):
        return True
    else:
        return False


import sys

t = (19, 42, 21)
print('The {} numbers are: '.format(len(t)), end="")

j = 1
for i in t:
    print("{}".format(i), end="")
    if j < len(t):
        print(", ", end="")
    j += 1


from scapy.layers.inet import *
from scapy.layers.http import *

def ping_flood(packets: scapy.plist.PacketList):
    """Test for potential ping flood attacks"""
    num_packets = packets.__len__()
    threshold_percent = .5
    min_count = 1000
    if num_packets > min_count and num_packets / packets.filter(lambda p: ICMP in p).__len__() > threshold_percent:
        return ['Potential ICMP Flood attack', ]

def http_malicious_auth(packets: scapy.plist.PacketList):
    """Check for a large number of 400-series HTTP responses

    This could indicate a potential auth attack
    """
    counts = {}
    threshold = 3
    res = []
    http_packets = packets.filter(lambda p: HTTPResponse in p)
    for p in http_packets:
        if 400 <= int(p['HTTPResponse'].Status_Code) < 500:
            try:
                counts[p['IP'].dst] = counts[p['IP'].dst] + 1
            except:
                counts[p['IP'].dst] = 1
    for k in counts.keys():
        if counts[k] > threshold:
            res.append("Potential malicious auth attempts from {}".format(k))


import argparse
import os
import subprocess
import sys
import tempfile

from mopy.config import Config
from mopy.paths import Paths

def target(config):
  target_name = config.target_os + "-" + config.target_cpu
  if config.is_official_build:
    target_name += "-official"
  return target_name

def get_gsutil():
  paths = Paths()
  sys.path.insert(0, os.path.join(paths.src_root, "tools"))
  # pylint: disable=F0401
  import find_depot_tools

  depot_tools_path = find_depot_tools.add_depot_tools_to_path()
  return os.path.join(depot_tools_path, "third_party", "gsutil", "gsutil")

def upload(gsutil_exe, source, dest):
  subprocess.check_call([gsutil_exe, "cp", source, dest])

def write_file_to_gs(gsutil_exe, file_contents, dest):
  with tempfile.NamedTemporaryFile() as temp_version_file:
    temp_version_file.write(file_contents)
    temp_version_file.flush()
    upload(gsutil_exe, temp_version_file.name, dest)

def roll_version(gsutil_exe, config, version):
  service_dir = 'gs://mojo/services/%s/%s' % (target(config), version)
  services = subprocess.check_output(
      [gsutil_exe, 'ls', service_dir]).strip().split('\n')
  for service in services:
    service_binary_name = service.split('/')[-1]
    service_location_file = ("gs://mojo/services/" + target(config) + "/" +
        service_binary_name + "_location")
    service_location_in_gs = service[len('gs://'):]
    write_file_to_gs(gsutil_exe, service_location_in_gs, service_location_file)

def main():
  parser = argparse.ArgumentParser(description="Change the version of the mojo "
      "services on the cdn.")
  parser.add_argument("-v", "--verbose", help="Verbose mode",
      action="store_true")
  parser.add_argument("version",
                      help="New version of the mojo services.")
  args = parser.parse_args()

  gsutil_exe = get_gsutil()

  for target_os in [Config.OS_LINUX, Config.OS_ANDROID]:
    config = Config(target_os=target_os)
    roll_version(gsutil_exe, config, args.version)

  return 0

if __name__ == "__main__":
  sys.exit(main())


#!/usr/bin/python3

from attributes import Attributes, AttributeList
from job import Job
from skill import SkillList

JOB_LVL_REQS = {1:0, 2:10, 3:30, 4:100, 5:200, 6:400, 7:700, 8:1200, 9:1800}

JOB_LVL_BOOSTS = {1:(3,5), 2:(10,20), 3:(30,50), 4:(60,100), 5:(100,170), 6:(150,250), 7:(300,500), 8:(600,1000), 9:(1000,2000)}

class Character(object):

    def __init__(self, name, age, gender, race, job):
        self.name = name
        self.age = age
        self.gender = gender
        self.race = race
        assert(isinstance(job, Job))
        self.job = job
        self.base_stats = None
        self.stats_set = False
        self.skill_list = None
        self.skills_set = False
        self.unset_skills = 0

    def setBases(self, hp, mp, stre, end, agi, magic, intel, dex, luck):
        bases = {}
        bases[Attributes.HP] = hp
        bases[Attributes.MP] = mp
        bases[Attributes.STRENGTH] = stre
        bases[Attributes.ENDURANCE] = end
        bases[Attributes.AGILITY] = agi
        bases[Attributes.MAGIC] = magic
        bases[Attributes.INTELLIGENCE] = intel
        bases[Attributes.DEXTERITY] = dex
        bases[Attributes.LUCK] = luck
        self.base_stats = AttributeList(bases)
        self.stats_set = True

    def setSkillList(self, skills, empty_slots = 0):
        assert(isinstance(skills, SkillList))
        self.skill_list = skills
        self.skills_set = True
        self.unset_skills = empty_slots

    def isSetup(self):
        return self.stats_set and self.skills_set

    def getJobSkillTotal(self):
        return self.skill_list.getJobSkillTotal(self.job)

    def getJobLevel(self):
        assert(self.isSetup())
        jobSkillTotal = self.getJobSkillTotal()
        jobLevel = 1
        for (jLvl, sTotal) in JOB_LVL_REQS.items():
            if jobSkillTotal >= sTotal:
                if jLvl > jobLevel:
                    jobLevel = jLvl
        return jobLevel

    def getJobBoosts(self):
        jobLevel = self.getJobLevel()
        lvl_boosts = JOB_LVL_BOOSTS[jobLevel]
        jobBoosts = {}
        for attr in [self.job.getFirstAttr(), self.job.getSecondAttr()]:
            if attr in [Attributes.HP, Attributes.MP]:
                jobBoosts[attr] = lvl_boosts[1]
            else:
                jobBoosts[attr] = lvl_boosts[0]
        return AttributeList(jobBoosts)

    def getTotalStats(self):
        return self.base_stats + self.skill_list.getSkillStatBoosts() + self.getJobBoosts()

    def show_status(self):
        print("="*30)
        print()
        print(self.name,'|',self.age,'years old |',self.gender,'|',self.race)
        jobLevel = self.getJobLevel()
        print("Job:",self.job.getName(),"LV"+str(jobLevel))
        jobBoosts = self.getJobBoosts()
        stats = self.getTotalStats()
        assert(len(stats)==len(Attributes))
        for attr in Attributes:
            attrName = attr.name.title()
            if attr in jobBoosts:
                print(attrName+":",stats[attr],"(+"+str(jobBoosts[attr])+")")
            else:
                print(attrName+":",stats[attr])
        print()
        print("Skill Slots")
        self.skill_list.show_skills(self.job)
        if self.unset_skills > 0:
            for _ in range(self.unset_skills):
                print("o Not Set")
        print()
        print("="*30)
        jobSkillTotal = self.getJobSkillTotal()
        nextSkillTotal = "?"
        if jobLevel < 9:
            nextSkillTotal = str(JOB_LVL_REQS[jobLevel+1])
        print("Job skill total: (" + str(jobSkillTotal) + "/" + nextSkillTotal + ")")


from bs4 import BeautifulSoup
from selenium import webdriver
import pandas as pd
from webdriver_manager.chrome import ChromeDriverManager
import json

def get_url(name):
    return f"https://www.google.com/search?q={name.replace(' ', '+')}+isla+vista"

restaurants = pd.read_csv("restaurants2.csv", names=["name", "address"])
print(restaurants)
rest_list = [line.rstrip('\n') for line in restaurants.name]
print(rest_list)

'''
dict_order = {}
dict_order_now = {}
dict_times = {}
'''

output = []
for i in rest_list:
    rest = {}

    url = get_url(i)
    options = webdriver.ChromeOptions()
    # options.add_argument('headless') # uncommented for testing
    browser = webdriver.Chrome(
        ChromeDriverManager().install(), options=options)
    browser.get(url)

    soup = BeautifulSoup(browser.page_source, 'html.parser')

    order_string = soup.find(string="Order")
    order_now_string = soup.find(string="Order Now")
    order_string1 = soup.find(string="$")
    order_string2 = soup.find(string="$$")
    rest_closed = soup.find(string="Temporarily closed")
    stars = soup.find("span", {"class", "Aq14fc"})

    if order_string:
        # Find the word "Order inside a <b> tag, then get the parent div"
        try:
            order_area = order_string.find_parent("b").find_parent("div")
        except:
            order_area = order_string.find_parent("div")

        rest['order'] = []

        for anchor in order_area.find_all('a', {'class': 'xFAlBc'}):
            delivery_name = anchor.getText()
            delivery_url = anchor.get('href', '/')
            #dict_order[i].append([f'* {delivery_name}, {delivery_url}'])
            rest['order'].append({"name": delivery_name, "url": delivery_url})
            # = [f'* {delivery_name}, {delivery_url}']

    elif order_now_string:
        order_now_area = order_now_string.find_parent("a")
        # dict_order_now[i].append(order_now_area.prettify())
        # we might want to actually make this order_now
        rest['order_now'] = order_now_area.prettify()

    elif order_string1:
        rest['price range'] = order_string1

    elif order_string2:
        rest['price range'] = order_string2

    # else:
    #     rest['price range'] = "no price range found"

    # find Menu
    # try:
        # browser.find_element_by_xpath(
        #"//div//span[contains(text(), 'Menu') and @class='xFAlBc']"
        # ).click()

    # except:
        #print("couldn't find menu for restaurant", i)

    # find menu
    menu_area = soup.find("div", {"data-attrid": "kc:/local:menu"})

    try:
        try:
            menu_area1 = menu_area.find_parent("b").find_parent("div")
        except:
            menu_area1 = menu_area.find_parent("div")

        menu_link = menu_area1.find('a', {"class": "xFAlBc"})
        rest['Menu'] = {"url": menu_link['href']}
    except:
        print("no menu")

    phone_area = soup.find(
        'a', {'data-local-attribute': 'd3ph'}
    )
    if phone_area:
        rest['phone_number'] = phone_area.find("span").getText()
    # find
    try:
        # for hours:
        try:
            browser.find_element_by_xpath(
                "//div//span[contains(text(), 'More hours') and @class='XCdOnb']"
            ).click()
        except:
            browser.find_element_by_xpath(
                "//div//span[ @class='BTP3Ac']"
            ).click()

        # reset the beautiful soup - maybe change variable name
        souP = BeautifulSoup(browser.page_source, 'html.parser')

        #souP.find("div", {"class", "eRD3Mb"}).find("table")
        # find the table and go through all of the rows
        #hour_area = souP.find("div", {"class", "eRD3Mb"}).find("table")

        try:
            hour_area = soup.find("div", {"class", "eRD3Mb"}).find("table")
        except:
            hour_area = soup.find("table", {"class", "WgFkxc"})

        rest['hours'] = []
        for row in hour_area.find_all("tr"):
            day, times = row.find_all("td")
            #dict_times[i].append([day.getText(), times.getText()])
            rest['hours'].append(dict(day=day.getText(), time=times.getText()))

    except:
        print("couldn't find hours for restaurant", i)
    print(rest)

    '''
    try:
        # for $:
        browser.find_element_by_xpath(
            "//div//span[ @class='YhemCb' and @data-ved='2ahUKEwj46vzz5dvxAhVMoZ4KHddVDyMQxuQDKAAwFXoECD0QAQ' ]"
            ).click()
        # for $$:
        browser.find_element_by_xpath(
            "//div//span[ @class='YhemCb' and @data-ved='2ahUKEwjIhe2P5NvxAhWHZM0KHRKTCQ4QxuQDKAAwGHoECGAQAQ' ]"
            ).click()

    except:
        print("couldn't find price range for restaurant", i)
    '''
    if stars:
        # print(stars.getText())
        rest["stars"] = stars.getText()

    rest["closed"] = rest_closed
    rest["name"] = i
    # if rest_closed:
    #     print("temporarily closed")

    # print(json.dumps(rest))

    output.append(rest)

    # break
    browser.close()
    browser.quit()

# print(output)

with open("../../dist/data/status.json", "w") as outfile:
    json.dump(output, outfile)


from desktop.models import Document2, Document

def _save_pipeline(pipeline, user):
  pipeline_type = pipeline.get('type', 'pipeline')
  save_as = False

  if pipeline.get('parentSavedQueryUuid'): # We save into the original saved query, not into the query history
    pipeline_doc = Document2.objects.get_by_uuid(user=user, uuid=pipeline['parentSavedQueryUuid'])
  elif pipeline.get('id'):
    pipeline_doc = Document2.objects.get(id=pipeline['id'])
  else:
    pipeline_doc = Document2.objects.create(name=pipeline['name'], uuid=pipeline['uuid'], type=pipeline_type, owner=user)
    Document.objects.link(pipeline_doc, owner=pipeline_doc.owner, name=pipeline_doc.name, description=pipeline_doc.description, extra=pipeline_type)
    save_as = True

    if pipeline.get('directoryUuid'):
      pipeline_doc.parent_directory = Document2.objects.get_by_uuid(user=user, uuid=pipeline.get('directoryUuid'), perm_type='write')
    else:
      pipeline_doc.parent_directory = Document2.objects.get_home_directory(user)

  pipeline['isSaved'] = True
  pipeline['isHistory'] = False
  pipeline['id'] = pipeline_doc.id
  pipeline_doc1 = pipeline_doc._get_doc1(doc2_type=pipeline_type)
  pipeline_doc.update_data(pipeline)
  #pipeline_doc.search = _get_statement(pipeline)
  pipeline_doc.name = pipeline_doc1.name = pipeline['name']
  pipeline_doc.description = pipeline_doc1.description = pipeline['description']
  pipeline_doc.save()
  pipeline_doc1.save()

  return pipeline_doc, save_as

FIELD_TYPES = (
  "alphaOnlySort",
  "ancestor_path",
  "boolean",
  "currency",
  "date",
  "descendent_path",
  "double",
  "float",
  "int",
  "location",
  "location_rpt",
  "long",
  "lowercase",
  "pdate",
  "pdouble",
  "pfloat",
  "pint",
  "plong",
  "point",
  "random",
  "string",
  "text_ar",
  "text_bg",
  "text_ca",
  "text_char_norm",
  "text_cjk",
  "text_cz",
  "text_da",
  "text_de",
  "text_el",
  "text_en",
  "text_en_splitting",
  "text_en_splitting_tight",
  "text_es",
  "text_eu",
  "text_fa",
  "text_fi",
  "text_fr",
  "text_ga",
  "text_general",
  "text_general_rev",
  "text_gl",
  "text_greek",
  "text_hi",
  "text_hu",
  "text_hy",
  "text_id",
  "text_it",
  "text_ja",
  "text_lv",
  "text_nl",
  "text_no",
  "text_pt",
  "text_ro",
  "text_ru",
  "text_sv",
  "text_th",
  "text_tr",
  "text_ws"
)

TEXT_FIELD_TYPES = (
  "alphaOnlySort",
  "lowercase",
  "random",
  "string",
  "text_ar",
  "text_bg",
  "text_ca",
  "text_char_norm",
  "text_cjk",
  "text_cz",
  "text_da",
  "text_de",
  "text_el",
  "text_en",
  "text_en_splitting",
  "text_en_splitting_tight",
  "text_es",
  "text_eu",
  "text_fa",
  "text_fi",
  "text_fr",
  "text_ga",
  "text_general",
  "text_general_rev",
  "text_gl",
  "text_greek",
  "text_hi",
  "text_hu",
  "text_hy",
  "text_id",
  "text_it",
  "text_ja",
  "text_lv",
  "text_nl",
  "text_no",
  "text_pt",
  "text_ro",
  "text_ru",
  "text_sv",
  "text_th",
  "text_tr",
  "text_ws"
)

DATE_FIELD_TYPES = (
  "date",
  "pdate"
)

INTEGER_FIELD_TYPES = (
  "int",
  "pint",
  "long",
  "plong"
)

DECIMAL_FIELD_TYPES = (
  "float",
  "pfloat",
  "double",
  "pdouble",
  "currency"
)

BOOLEAN_FIELD_TYPES = (
  'boolean',
)


from flask import current_app
import time
from flask import session
from flask_caching import Cache
import pandas as pd

from application.utils.logger import configure_logger

logger = configure_logger()

from application import create_app

from .cache import cache

def update_csv_file(df_name: str, df: pd.DataFrame, session=session) -> None:
    """Store the DataFrame in cache and raise an error if not stored."""

    dataframe_name = f"{df_name}_{session['session_id']}"
    cache.set(dataframe_name, df)
    # session['timestamp']= time.time()  # Update the timestamp
    cache.set('timestamp',(time.time()))

    # Check if the DataFrame is stored in the cache
    if cache.get(dataframe_name) is None:
        raise ValueError("DataFrame not stored in cache. Failed to update.")

    # Add dataframe_name to dataframes_saved_in_cache list in the session if not already present
    if 'dataframes_saved_in_cache' not in session:
        session['dataframes_saved_in_cache'] = []

    if dataframe_name not in session['dataframes_saved_in_cache']:
        session['dataframes_saved_in_cache'].append(dataframe_name)

def getting_csv(df_name: str,session=session) -> pd.DataFrame:
    """Retrieve the DataFrame from cache and return it."""

    dataframe_name = f"{df_name}_{session['session_id']}"
    retrieved_df = cache.get(dataframe_name)

    if retrieved_df is None:
        raise ValueError(f"DataFrame '{dataframe_name}' not found in cache.")

    return retrieved_df

# View cached keys and values
def view_cache():
    cached_keys = cache.cache._cache.keys()  # Get all cached keys
    return cached_keys

def clear_inactive_cache():
    while True:
        time.sleep(100000)  # Sleep for 5 minutes
        current_time = time.time()
        timestamp = cache.get('timestamp')
        print('-----------------------------------------------------',timestamp)
        if timestamp is not None and current_time - timestamp > 100000:
            logger.info('files stored in cache before clearing the cache data {}'.format(view_cache()))
            cache.clear()
            # session.clear()
            logger.info('files stoed in cache after clearing the cache data {}'.format(view_cache()))
            print('-----------------------------------------------------',timestamp)

def clear_inactive_cache_immediate():
    logger.info('Currently running the clear_inactive_cache_immediate and clearing the cache and session')
    cache.clear()
    session.clear()


from django import forms
from django.forms import ModelForm, Textarea
from tally_ho.apps.tally.models.center import Center

disable_copy_input = {
    'onCopy': 'return false;',
    'onDrag': 'return false;',
    'onDrop': 'return false;',
    'onPaste': 'return false;',
    'autocomplete': 'off',
    'class': 'form-control'
}

class CreateCenterForm(ModelForm):
    class Meta:
        model = Center
        fields = localized_fields = [
            'center_type',
            'code',
            'latitude',
            'longitude',
            'mahalla',
            'name',
            'tally',
            'office',
            'region',
            'village',
        ]

        widgets = {
            "tally": forms.HiddenInput(),
            'mahalla': Textarea(attrs={'cols': 60, 'rows': 2}),
            'name': Textarea(attrs={'cols': 60, 'rows': 2}),
            'region': Textarea(attrs={'cols': 60, 'rows': 2}),
            'village': Textarea(attrs={'cols': 60, 'rows': 2}),
        }