#  -*- coding:utf-8 -*-
import clr
import sys
import os
import json
import logging
import time
import xml.etree.ElementTree as ET
import shutil
from ctypes import *
base_dir = os.path.abspath(os.path.join(os.getcwd()))
sys.path.append(base_dir +'\\Python3\\Server\\Dll\\')
clr.FindAssembly('TexttoXls.dll')
from TexttoXls import *
import tornado.ioloop
from tornado.options import define,options, parse_command_line
from tornado.web import RequestHandler
import uuid
define("port", default=8005, help="run on the given port", type=int)
dll = ConvertXls()
openxls = dll.openxls
GetSheetNums = dll.GetSheetNums
GetCell = dll.GetCell
InsertCell = dll.InsertCell
RemoveOneCol = dll.RemoveOneCol
RemoveOneRow = dll.RemoveOneRow
InsertRow = dll.InsertRow
closexls = dll.closexls
InsertNumCell = dll.InsertNumCell
InsertPicture = dll.InsertPicture
ChangeSheetName = dll.ChangeSheetName#void changesheetname(int sheetnum, string sheetname)
HideCol = dll.HideCol  #增加隐藏某一列功能， 不隐藏某一列。

SetCellRangeAddress = dll.SetCellRangeAddress
GetPathByXlsToHTML = dll.GetPathByXlsToHTML
# 20200227增加单元格行高和列宽
# 设置单元格颜色
#
#
SetColor = dll.SetColor    #设置单元格颜色
SetCellRowHeight = dll.SetCellRowHeight    #设置单元格行高
SetCellColumnWidth = dll.SetCellColumnWidth     #设置单元格列宽
CreateSheet = dll.CreateSheet

SetCellStyle = dll.SetCellStyle
ExcelToHtml = dll.ExcelToHtml
# 20200409
XlsToJson = dll.XlsToJson
Getbase64Picture = dll.Getbase64Picture
Insertbase64Picture = dll.Insertbase64Picture
Getbase64PictureTest = dll.Getbase64PictureTest
SetPrintArea = dll.SetPrintArea

mMaxRow = 4096
mMaxCol = 100
mRow = 4096
mCol = 100

cellcolor = {
    'Black': 8,
    'Brown': 60,
    'Olive_Green': 59,
    'Dark_Green': 58,
    'Dark_Teal': 56,
    'Dark_Blue': 18,
    'Indigo': 62,
    'Grey_80_PERCENT': 63,
    'Dark_Red': 16,
    'Orange': 53,
    'DARK_YELLOW': 19,
    'Green': 17,
    'Teal':	21,
    'Blue':	12,
    'Blue_Grey': 54,
    'Grey_50_PERCENT': 23,
    'Red': 10,
    'LIGHT_ORANGE':	52,
    'LIME':	50,
    'SEA_GREEN': 57,
    'AQUA':	49,
    'LIGHT_BLUE': 48,
    'VIOLET': 20,
    'GREY_40_PERCENT': 55,
    'Pink':	14,
    'Gold':	51,
    'Yellow': 13,
    'BRIGHT_GREEN':	11,
    'TURQUOISE': 15,
    'SKY_BLUE':	40,
    'Plum':	61,
    'GREY_25_PERCENT': 22,
    'Rose':	45,
    'Tan': 47,
    'LIGHT_YELLOW': 43,
    'LIGHT_GREEN': 42,
    'LIGHT_TURQUOISE': 41,
    'PALE_BLUE': 44,
    'LAVENDER': 46,
    'White': 9,
    'CORNFLOWER_BLUE': 24,
    'LEMON_CHIFFON': 26,
    'MAROON': 25,
    'ORCHID': 28,
    'CORAL': 29,
    'ROYAL_BLUE': 30,
    'LIGHT_CORNFLOWER_BLUE': 31,
    'AUTOMATIC': 64

}

def CopyFile(srcfile, dstfile):
    if not os.path.isfile(srcfile):

        return False
        # print "%s not exist!"%(srcfile)
    else:
        fpath, fname = os.path.split(dstfile)  # 分离文件名和路径
        if not os.path.exists(fpath):
            os.makedirs(fpath)  # 创建路径
        if os.path.isfile(dstfile):
            os.remove(dstfile)
        shutil.copyfile(srcfile, dstfile)  # 复制文件
        return True

#日志的配置文件
def outputlog():
    # main_log_handler = logging.FileHandler(log_path +
    #                                        "/JsonToPrice_%s.log" % time.strftime("%Y-%m-%d_%H-%M-%S",
    #                                                                     time.localtime(time.time())), mode="w+",
    #                                        encoding="utf-8")
    # main_log_handler.setLevel(logging.DEBUG)
    # formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    # main_log_handler.setFormatter(formatter)
    # logger.addHandler(main_log_handler)

    # 控制台打印输出日志
    console = logging.StreamHandler()  # 定义一个StreamHandler，将INFO级别或更高的日志信息打印到标准错误，并将其添加到当前的日志处理对象
    console.setLevel(logging.DEBUG)  # 设置要打印日志的等级，低于这一等级，不会打印
    formatter = logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)
    # 进程号
    pid = os.getpid()
    # 本文件名（不含后缀.py）
    myfilename = os.path.split(__file__)[-1].split(".")[0]
    # 生成关闭进程的脚本文件
    #produce_stop_bat(pid, myfilename)

# 退出程序操作
class ExitSystem(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        try:
            pass
        except:
            pass
        finally:
            print("***服务器退出***")
            os._exit(0)  # 退出程序

class ProduceExcel(tornado.web.RequestHandler):
    def post(self, *args, **kwargs):
        datacontent = self.get_argument('pricedata')
        guid = str(uuid.uuid1())  # 唯一标识符guid
        guid = ''.join(guid.split('-'))
        ToPrice = JsonToPrice(datacontent, guid)
        state = ToPrice.ToSrc()
        if state:
            self.set_header('Content-Type', 'application/x-xls')
            self.set_header('Content-Disposition', 'attachment; filename=NetPrice.xls')
            with open(state, 'rb') as f:
                while True:
                    data = f.read(1024)
                    if not data:
                        break
                    self.write(data)
                # # 记得有finish哦
                # self.write('1')
            self.finish()

        else:
            self.write(json.dumps({'result':'0'}).encode('utf8'))

class JsonToPrice(object):
    def __init__(self, datacontent, guid):
        self.datacontent = datacontent
        self.guid = guid
        self.excelname = ''
    def ToSrc(self):
        sheetsobj = json.loads(self.datacontent)
        self.excelname = sheetsobj['fileName']
        filename = self.producedatasheet(sheetsobj)
        if filename and os.path.exists(filename):
            return filename,self.excelname
        return False, ''

    def ToRGBColor(self, value):
        digit = list(map(str, range(10))) + list("ABCDEF")
        print(digit)
        if isinstance(value, tuple):
            string = '#'
            for i in value:
                a1 = i // 16
                a2 = i % 16
                string += digit[a1] + digit[a2]
            return string
        elif isinstance(value, str):
            a1 = digit.index(value[1]) * 16 + digit.index(value[2])
            a2 = digit.index(value[3]) * 16 + digit.index(value[4])
            a3 = digit.index(value[5]) * 16 + digit.index(value[6])
            return (a1, a2, a3)

    def producedatasheet(self, sheetsobj):
        if sheetsobj['type'] !='xls':
            sheetsobj['type'] = 'xls'

        excel = excelPath + sheetsobj['fileName'] + '_' + self.guid + '.' + sheetsobj['type']

        if not os.path.exists(excel):
            CopyFile(srcexcelfile, excel)
        else:
            os.remove(excel)
            CopyFile(srcexcelfile, excel)
        print(excel)
        openxls(excel)
        sheetnum = len(sheetsobj['sheets'])
        if sheetnum - 1 != 0: CreateSheet(sheetnum - 1)
        for k in range(len(sheetsobj['sheets'])):
            sheet = sheetsobj['sheets'][k]
            sheetname = sheet['sheetName']
            if sheetname !='':
                ChangeSheetName(k+1, sheetname)

            if 'RowHeight' in sheet:
                rowobj = sheet['RowHeight']
                for row, height in rowobj.items():
                    rownum = int(row[1:]) + 1
                    logger.info(str(rownum) + '行高:' + str(height))
                    SetCellRowHeight(k+1, rownum, height)

            if 'ColumnWidth' in sheet:
                print(sheet['ColumnWidth'])
                colobj = sheet['ColumnWidth']
                for col, width in colobj.items():
                    colnum = int(col[1:]) + 1
                    logger.info(str(colnum) + '列宽:' + str(width))
                    SetCellColumnWidth(k+1, colnum, width)

            dataobj = sheet['data']  #data数据

            for key in sorted(dataobj.keys()):

                colobj = dataobj[key] # key 为 row number, colobj 为col对象
                i = int(key[1:])+1  # i 代表第几行
                collist = list(colobj.keys())
                print(collist)
                for col in range(0, len(collist)):
                    onecolobj = collist[col]    #列元素
                    j = int(onecolobj[1:]) +1 # j 代表第几列
                    cellobj = colobj[onecolobj] #单元格元素
                    print(k+1, i, j, str(cellobj['Text']))
                    InsertCell(k+1, i, j, str(cellobj['Text']))
                    if '_mergeCount' in cellobj:
                        addcol = cellobj['_mergeCount']
                        SetCellRangeAddress(k+1, i, i, j, j+addcol)   #int k, int rowstart, int rowend, int colstart, int colend

                    #必须存在单元格，改变颜色才有效
                    if 'style' in cellobj:
                        style = cellobj['style']
                        # thin 代表框的上横线一条细线， medium 中等线 dashed 虚线 hair 点线
                        # thick 厚 double 俩条线 medium_dashed 中厚虚线，
                        if style:
                            #print(k+1, i, j, style)
                            SetCellStyle(k+1, i, j, style)

        #print(GetPathByXlsToHTML(excel))
            string = ExcelToHtml(k)
            htmlpath = ServerPath+'\\ExcelHtml\\'+str(k)+'_'+sheetsobj['fileName'] + '_' + self.guid+'.html'
            if not os.path.exists(os.path.dirname(htmlpath)):
                os.makedirs(os.path.dirname(htmlpath))
            with open(htmlpath, 'w+', encoding='utf8') as f:
                f.write(string)

            picturelistobj = sheet['pictures']
            picturelist = json.loads(picturelistobj)
            print('len of picturelist=',len(picturelist))
            for picture in picturelist:
                # print(picture)
                # print(1, picture['startrow'], picture['startcol'], picture['endrow'], picture['endcol'],
                # picture['picturedata'])
                # print(type(picture['picturedata']))

                Insertbase64Picture(1, picture['startrow'], picture['startcol'], picture['endrow'] + 1,
                                    picture['endcol'] + 1,picture['AnchorType'],
                                    picture['picturedata'])
        closexls()
        # openxls(excel)
        # # with open('s.txt', 'r', encoding='utf8') as f:
        # #     picturelist = json.loads(f.read())
        # #     for picture in picturelist:
        # #         print(picture)
        # #         print(1, picture['startrow'], picture['startcol'], picture['endrow'], picture['endcol'],
        # #               picture['picturedata'])
        # #         print(type(picture['picturedata']))
        # #
        # #         Insertbase64Picture(1, picture['startrow'], picture['startcol'], picture['endrow'], picture['endcol'] + 1,
        # #                             picture['picturedata'])
        # for k in range(len(sheetsobj['sheets'])):
        #     sheet = sheetsobj['sheets'][k]
        #
        # # SetCellStyle(1, 3, 1, "font-weight:normal;font-name:宋体;font-size:12;text-align:CENTER;border-type:THIN None THIN MEDIUM;WrapText:True")
        #
        #
        #
        #
        #
        # closexls()
        return excel

application = tornado.web.Application([
    (r"/exit_localserver", ExitSystem),  # 退出程序
    (r"/Excel/ConAndDown/", ProduceExcel),
],autoreload=True)
template_path='templates'
static_path='static'

def jsontoexcel():
    srcexcelfile = base_dir + '\\reports\\pricesource.xls'
    excel = base_dir + '\\reports\\pricesourceTest.xls'
    if not os.path.exists(excel):
        CopyFile(srcexcelfile, excel)
    else:
        os.remove(excel)
        CopyFile(srcexcelfile, excel)

    # SetCellRowHeight(1, 1, 40)
    # InsertCell(1, 1, 1, '')
    # SetColor(1, 1, 1, 0, 0, 0)
    # #CreateSheet(2)
    # InsertCell(1, 3, 1, '李涛')
    # SetCellStyle(1, 3, 1, "color:red;font-weight:bold;font-size:11;font-name:宋体;border-type:thin;")
    # SetCellRangeAddress(1, 1, 1, 1, 3)

    # print (cellcolor.get('Black1'))
    excelPath = base_dir + '\\Python3\\Server\\Dll\\exceltojson\\json.txt'
    with open(excelPath, 'r', encoding='utf8') as f:
        datacontent = f.read()
    print(type(datacontent))

    guid = str(uuid.uuid1())  # 唯一标识符guid
    guid = ''.join(guid.split('-'))
    ToPrice = JsonToPrice(datacontent, guid)
    state, excelname = ToPrice.ToSrc()
    # print(state, excelname)
    print('excel=', state)

def ExtractFileExt(filename):
    '''
        :param filename: '123.txt'
        :return: .txt
        '''
    if '.' not in filename:
        return ''
    for i in range(len(filename)-1, -1, -1):
        if filename[i] == '.' and (i != 0):
            return filename[:i]
    return ''
def exceltojson():
    srcexcelfile = base_dir + '\\reports\\经销商订货表.xls'
    #excel = base_dir + '\\Python3\\Server\\Dll\\exceltojson\\经销商订货表.xls'
    excel = base_dir + '\\reports\\price.xls'
    if not os.path.exists(excel):
        state = CopyFile(srcexcelfile, excel)
        print(state)

    print(123)
    jsontext = XlsToJson(excel)
    jsonobj = json.loads(jsontext)

    jsonobj['fileName'] = ExtractFileExt(os.path.basename(excel))
    with open(os.path.join(os.path.dirname(excel),'json.txt'), 'w+', encoding='utf8') as f:
        f.write(json.dumps(jsonobj, ensure_ascii=False))
    print('456')
    # srcexcelfile = base_dir + '\\reports\\pricesource.xls'
    # excel = base_dir + '\\reports\\pricesourceTest.xls'
    # if not os.path.exists(excel):
    #     CopyFile(srcexcelfile, excel)
    # else:
    #     os.remove(excel)
    #     CopyFile(srcexcelfile, excel)
    # openxls(excel)
    # for k in range(len(jsonobj['sheets'])):
    #     sheet = jsonobj['sheets'][k]
    #     picturelistobj = sheet['pictures']
    #     picturelist = json.loads(picturelistobj)
    #     for picture in picturelist:
    #         print(picture)
    #         print(1, picture['startrow'], picture['startcol'], picture['endrow'], picture['endcol'],
    #               picture['picturedata'])
    #         print(type(picture['picturedata']))
    #
    #         Insertbase64Picture(1, picture['startrow'], picture['startcol'], picture['endrow']+1, picture['endcol'] + 1,
    #                             picture['picturedata'])
    # closexls()
#测试插入图片接口
def TestInterface():
    srcexcelfile = base_dir + '\\reports\\零售订货表.xls'
    excel = base_dir + '\\reports\\经销商订货表.xls'
    if not os.path.exists(excel):
        CopyFile(srcexcelfile, excel)
    else:
        os.remove(excel)
        CopyFile(srcexcelfile, excel)
    openxls(excel)
    pngfile = base_dir + '\\reports\\图片1.png'

    # 测试插入图片文件
    #InsertPicture(1,1,1,1,12,pngfile)startrow, int startcol, int lastrow, int lastcol
    #测试获取图片信息
    pictureliststring = Getbase64PictureTest(1)
    print(pictureliststring)
    closexls()
    #picturelist = json.loads(pictureliststring)

#     excel = base_dir + '\\reports\\转换前.xls'    #转换前010
#     openxls(excel)
#     printarea = {
#   "PrintArea": "A单生产表!$A$1:$M$13",
#   "Scale": 80,
#   "PaperSize": 9,
#   "HL": "",
#   "HC": "",
#   "HR": "",
#   "FL": "拆单:[$登陆用户]      审核：",
#   "FC": "业务：         批次：",
#   "FR": "&D &T  \n第 &P 页，共 &N 页"
# }
#     SetPrintArea(1, json.dumps(printarea, ensure_ascii=False))
    # print(picturelist)
    # with open('s.txt', 'w+', encoding='utf8') as f:
    #     f.write(json.dumps(picturelist, ensure_ascii=False))
    # with open('s.txt', 'r', encoding='utf8') as f:
    #     picturelist = json.loads(f.read())
    #
    # for picture in picturelist:
    #     print(1, picture['startrow'], picture['startcol'], picture['endrow'], picture['endcol'],  picture['picturedata'])
    #     print(type(picture['picturedata']))
    #
    #     Insertbase64Picture(1, picture['startrow'], picture['startcol'], picture['endrow'], picture['endcol']+1, picture['picturedata'])

    #SetCellStyle(1, 3, 1, "font-weight:normal;font-name:宋体;font-size:12;text-align:CENTER;border-type:THIN None THIN MEDIUM;WrapText:True")
    #closexls()

def exceltohtml():
    jsontoexcel()
    excelfile = base_dir + '\\Python3\\Server\\Dll\\excel\\网络报价.xls'
    if not os.path.exists(excelfile):
        print(' No excel!!!')
    import pandas as pd
    import codecs
    xd = pd.ExcelFile(excelfile)
    df = xd.parse()
    print(os.path.dirname(excelfile)+'1.html')
    with codecs.open(os.path.dirname(excelfile)+'1.html', 'w', 'utf-8') as html_file:
        html_file.write(df.to_html(header=True, index=False))

if __name__=='__main__':
    # 如果日志文件夹不存在，则创建
    log_dir = "PriceLog"  # 日志存放文件夹名称
    log_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), log_dir)
    if not os.path.isdir(log_path):
        os.makedirs(log_path)
    print(log_path)
    # 设置logging
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    outputlog()
    excelPath = base_dir + '\\Python3\\Server\\Dll\\excel\\'
    srcexcelfile = base_dir + '\\reports\\pricesource.xls'
    excel = base_dir + '\\reports\\pricesourceTest.xls'
    ServerPath = os.path.abspath(os.path.join(os.getcwd(), '..')) + '\\nginx-1.0.11\\nginx-1.0.11\\html\\'
    print(ServerPath)
    #TestInterface()
    #jsontoexcel()
    #TestInterface()
    exceltojson()
    #jsontoexcel()
    # excelPath = base_dir + '\\Python3\\Server\\Dll\\excel\\'
    # if not os.path.exists(excelPath):
    #     os.makedirs(excelPath)

    # # with open(file, 'r', encoding='utf8') as f:
    # #     datacontent = f.read()
    # # ToPrice = JsonToPrice(datacontent, excel)
    # # ToPrice.ToSrc()
    # tornado.options.parse_command_line()
    # http_server = tornado.httpserver.HTTPServer(application)
    # http_server.listen(options.port)
    # try:
    #     tornado.ioloop.IOLoop.instance().start()
    # except:
    #     pass


import numpy as np
import matplotlib.pyplot as plt
import random
import pickle
import os

def sin_cos_creator(num_points=512, number_basis_functions=7):
    time = np.arange(num_points)
    cos_signal = np.zeros(num_points)
    for i in range(number_basis_functions):
        amplitude  = random.uniform(0.5, 1)
        frequence = random.uniform(3, 3.1)
        phase = random.uniform(-0.01, 0.01)
        cos_wave = amplitude * np.cos(2 * np.pi * (time + phase) * frequence)  # Cosine pattern
        cos_signal = cos_signal + cos_wave
    cos_signal[0] = 0
    #trend = [(0.0001 * x**2 - 0.000001*x**3) for x in range(num_points)]
    return (cos_signal) / np.sqrt(number_basis_functions)

def grapfical_print():
    # Generate synthetic time series data
    synthetic_data = sin_cos_creator()

    # Plot the synthetic time series data
    plt.figure(figsize=(10, 6))
    plt.plot(synthetic_data)
    plt.title('Synthetic Time Series Data with Sinusoidal and Cosine Patterns')
    plt.xlabel('Time')
    plt.ylabel('Value')
    plt.savefig('sample_plot1.png')

def create_sample(n, name):
    """
    Create a sample of data using the sin_cos_creator function and save it to a file.

    Args:
        n (int): Number of data points to generate in the sample.
        name (str): Name of the file (without extension) to save the sample.

    Returns:
        None

    """
    sample = []
    for i in range(n):
        sample.append(sin_cos_creator())
        if i % 1000 == 0:
            print(i)

    # Get the current directory
    current_directory = os.path.dirname(os.path.realpath(__file__))

    # Construct the full path for the file
    file_path = os.path.join(current_directory, name + '.pkl')

    # Save data to a file using pickle
    with open(file_path, 'wb') as file:
        pickle.dump(sample, file)

if __name__=="__main__":
    create_sample(9999, "9999_test_sample_sin_cos_creator")
    #grapfical_print()


from .pedal import BasePedal
from enum import IntEnum

class DelayType(IntEnum):
    DEFAULT = 0
    DIGITAL = 0
    SINGLE = 0
    PAN = 1
    STEREO = 2
    DUAL_SERIES = 3
    DUAL_PARALLEL = 4
    DUAL_LR = 5
    REVERSE = 6
    ANALOG = 7
    TAPE_ECHO = 8
    MODULATE = 9
    SDE_3000 = 10

class Delay(BasePedal):

    CHAIN_POS = [7, 8, 8]

    def __init__(self,
                _type: DelayType = DelayType.DEFAULT,
                on: bool = True,
                d1_f_back: int = 20,
                d1_hi_cut: int = 14,
                d1_level: int = 50,
                d1_time_h: int = 0,
                d1_time_l: int = 100,
                d1_time: int = 100,
                d2_f_back: int = 20,
                d2_hi_cut: int = 14,
                d2_level: int = 50,
                d2_time_h: int = 3,
                d2_time_l: int = 16,
                d2_time: int = 400,
                delay_time_h: int = 1,
                delay_time_l: int = 48,
                delay_time: int = 176,
                direct_mix: int = 100,
                effect_level: int = 0,
                f_back: int = 35,
                high_cut: int = 12,
                mod_depth: int = 50,
                mod_rate: int = 40,
                tap_time: int = 50,
                vtg_effect_phase: int = 0,
                vtg_feedback_phase: int = 0,
                vtg_filter: int = 0,
                vtg_lpf: int = 0,
                vtg_mod_sw: int = 0,
                **kwargs
    ):
        super().__init__('delay', on)
        self.type = _type
        self.d1_f_back = d1_f_back
        self.d1_hi_cut = d1_hi_cut
        self.d1_level = d1_level
        self.d1_time_h = d1_time_h
        self.d1_time_l = d1_time_l
        self.d1_time = d1_time
        self.d2_f_back = d2_f_back
        self.d2_hi_cut = d2_hi_cut
        self.d2_level = d2_level
        self.d2_time_h = d2_time_h
        self.d2_time_l = d2_time_l
        self.d2_time = d2_time
        self.delay_time_h = delay_time_h
        self.delay_time_l = delay_time_l
        self.delay_time = delay_time
        self.direct_mix = direct_mix
        self.effect_level = effect_level
        self.f_back = f_back
        self.high_cut = high_cut
        self.mod_depth = mod_depth
        self.mod_rate = mod_rate
        self.tap_time = tap_time
        self.vtg_effect_phase = vtg_effect_phase
        self.vtg_feedback_phase = vtg_feedback_phase
        self.vtg_filter = vtg_filter
        self.vtg_lpf = vtg_lpf
        self.vtg_mod_sw = vtg_mod_sw


#!/usr/bin/python3

import numpy as np
from numpy.linalg.linalg import LinAlgError

def almost_meeting_lines(a1, b1, a2, b2):
    a = np.array([[a1, -1], [a2, -1]])
    b = np.array([-b1, -b2])
    c = None
    try:
        c = np.linalg.solve(a,b)
        return (c, True)
    except LinAlgError:
        c = np.linalg.lstsq(a,b)[0]
        return (c, False)

def main():
    a1=1
    b1=2
    a2=-1
    b2=0

    (x, y), exact = almost_meeting_lines(a1, b1, a2, b2)
    if exact:
        print(f"Lines meet at x={x} and y={y}")

    a1=a2=1
    b1=2
    b2=-2
    (x, y), exact = almost_meeting_lines(a1, b1, a1, b2)
    if exact:
        print(f"Lines meet at x={x} and y={y}")
    else:
        print(f"Closest point at x={x} and y={y}")

    a1=1
    b1=2
    (x, y), exact = almost_meeting_lines(a1, b1, a1, b1)
    if exact:
        print(f"Lines meet at x={x} and y={y}")
    else:
        print(f"Closest point at x={x} and y={y}")

    a1=1
    b1=2
    a2=1
    b2=1
    (x, y), exact = almost_meeting_lines(a1, b1, a2, b2)
    if exact:
        print(f"Lines meet at x={x} and y={y}")
    else:
        print(f"Closest point at x={x} and y={y}")

if __name__ == "__main__":
    main()


import boto3
import json
import time

def lambda_handler(event, context):
    # Retrieve the cluster name from the input event
    cluster_name = event.get('cluster_name')

    # Initialize an EKS client
    eks_client = boto3.client('eks')

    # Retrieve the list of nodegroup names
    nodegroup_names = eks_client.list_nodegroups(clusterName=cluster_name)['nodegroups']

    # Update the scaling configuration for each nodegroup to set the desired capacity to 0
    for nodegroup_name in nodegroup_names:
        try:
            eks_client.update_nodegroup_config(
                clusterName=cluster_name,
                nodegroupName=nodegroup_name,
                scalingConfig={
                    'desiredSize': 0,
                    'maxSize': 0,
                    'minSize': 0
                }
            )
        except Exception as e:
            return {
                'statusCode': 500,
                'body': json.dumps(f'Error updating scaling config for nodegroup {nodegroup_name} in EKS cluster {cluster_name}: {e}')
            }

    return {
        'statusCode': 200,
        'body': json.dumps(f'EKS cluster {cluster_name} disabled.')
    }


from flask_restful import Resource
from db.swen_344_db_utils import exec_get_all, exec_commit
import json

class Menu(Resource):

    # retrive full menu from the server
    def get_menu() -> str:
        data = []
        query = """
            SELECT * FROM menu
            """
        result = exec_get_all(query, )

        for entry in result:
            data.append(dict(
                id = entry[0],
                name = entry[1],
                category = entry[2],
                calories = entry[3],
                totalFat = entry[4],
                saturatedFat = entry[5],
                transFat = entry[6],
                protein = entry[7],
                carbohydrate = entry[8],
            ))
        jdata = json.dumps(data)
        return jdata

    def get_item(id) -> str:
        data = []
        query = """
            SELECT * FROM menu
            WHERE menu.id=%s
            """
        result = exec_get_all(query, (id,))

        for entry in result:
            data.append(dict(
                id = entry[0],
                name = entry[1],
                category = entry[2],
                calories = entry[3],
                totalFat = entry[4],
                saturatedFat = entry[5],
                transFat = entry[6],
                protein = entry[7],
                carbohydrate = entry[8],
            ))
        jdata = json.dumps(data)
        return jdata

    # modify nutrition data for existing food items
    def update_item(id, name, category, calories, total_fat, saturated_fat, trans_fat, protein, carbohydrate) -> str:
        query = """
            UPDATE menu
            SET
                name=%s,
                category=%s,
                calories=%s,
                total_fat=%s,
                saturated_fat=%s,
                trans_fat=%s,
                protein=%s,
                carbohydrate=%s
            WHERE menu.id=%s
            """
        exec_commit(query, (name, category, calories, total_fat, saturated_fat, trans_fat, protein, carbohydrate, id,))
        data = dict(
            category=category,
            calories=calories,
            total_fat=total_fat,
            saturated_fat=saturated_fat,
            trans_fat=trans_fat,
            protein=protein,
            carbohydrate=carbohydrate
        )
        jdata = json.dumps(data)
        return jdata

    # create new food items in an existing category
    def add_item(name, category, calories, total_fat, saturated_fat, trans_fat, protein, carbohydrate) -> str:
        exec_commit("""
            SELECT pg_catalog.setval(pg_get_serial_sequence('menu', 'id'),
                (SELECT MAX(id) FROM menu));
            """,)

        query = """
                INSERT INTO menu (
                    name, category, calories, total_fat, saturated_fat,
                    trans_fat, protein, carbohydrate
                )
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
                """
        exec_commit(query, (name, category, calories, total_fat, saturated_fat, trans_fat, protein, carbohydrate,))
        data = dict(
            name=name,
            category=category,
            calories=calories,
            total_fat=total_fat,
            saturated_fat=saturated_fat,
            trans_fat=trans_fat,
            protein=protein,
            carbohydrate=carbohydrate
        )
        jdata = json.dumps(data)
        return jdata

    # delete a particular food item
    def delete_item(id) -> str:
        query = """
                DELETE FROM menu
                WHERE menu.id=%s
                """
        exec_commit(query, (id,))
        data = dict(
            id=id
        )
        jdata = json.dumps(data)
        return jdata


#!/usr/bin/python3

import sys
import boto3

try:
    (tagName,tagValue) = sys.argv[1].split('=')
    newVolSize = int(sys.argv[2])
except:
    print(f"usage: {sys.argv[0]} TagName=TagValue NewSize")
    print(f"Resize EC2 with TagName=TagValue instance's root volume to NewSize")
    exit(10)

err = False

filter = [{
    'Name': f'tag:{tagName}',
    'Values': [f'{tagValue}']
}]

ec2 = boto3.client('ec2')
response = ec2.describe_instances(Filters=filter)

for instance in response['Reservations'][0]['Instances']:
    print(instance['RootDeviceName'])
    if instance['RootDeviceType'] != 'ebs':
        continue
    for dev in instance['BlockDeviceMappings']:
        if dev['DeviceName'] == instance['RootDeviceName']:
            instance['RootDeviceId'] = dev['Ebs']['VolumeId']
    print(f"resizing instance's {instance['InstanceId']} volume {instance['RootDeviceId']} to {newVolSize}GB: ", end="")
    try:
        ec2.modify_volume(VolumeId=instance['RootDeviceId'],Size=newVolSize)
    except Exception as e:
        print(f"[ERROR] {e}")
        err = True
    else:
        print("[OK]")

if err:
    exit(1)


import os.path as osp
from collections import OrderedDict
import math

import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.cuda.amp import GradScaler, autocast

from clip import clip
from clip.simple_tokenizer import SimpleTokenizer as _Tokenizer

_tokenizer = _Tokenizer()

def load_clip_to_cpu(cfg):
    backbone_name = cfg.MODEL.ARCH
    url = clip._MODELS[backbone_name]
    model_path = clip._download(url)

    try:
        # loading JIT archive
        model = torch.jit.load(model_path, map_location="cpu").eval()
        state_dict = None

    except RuntimeError:
        state_dict = torch.load(model_path, map_location="cpu")
    design_details = {"trainer": 'ViFi_CLIP',
                      "vision_depth": cfg.TRAINER.ViFi_CLIP.PROMPT_DEPTH_VISION,
                      "language_depth": cfg.TRAINER.ViFi_CLIP.PROMPT_DEPTH_TEXT,
                      "vision_ctx": cfg.TRAINER.ViFi_CLIP.N_CTX_VISION,
                      "language_ctx": cfg.TRAINER.ViFi_CLIP.N_CTX_TEXT}
    model = clip.build_model(state_dict or model.state_dict(), design_details)

    return model

class TextEncoder(nn.Module):
    def __init__(self, clip_model):
        super().__init__()
        self.transformer = clip_model.transformer
        self.positional_embedding = clip_model.positional_embedding
        self.ln_final = clip_model.ln_final
        self.text_projection = clip_model.text_projection
        self.dtype = clip_model.dtype

    def forward(self, prompts, tokenized_prompts):
        x = prompts + self.positional_embedding.type(self.dtype)
        x = x.permute(1, 0, 2)  # NLD -> LND
        x = self.transformer(x)
        x = x.permute(1, 0, 2)  # LND -> NLD
        x = self.ln_final(x).type(self.dtype)

        # x.shape = [batch_size, n_ctx, transformer.width]
        # take features from the eot embedding (eot_token is the highest number in each sequence)
        x = x[torch.arange(x.shape[0]), tokenized_prompts.argmax(dim=-1)] @ self.text_projection

        return x

class VLPromptLearner(nn.Module):
    def __init__(self, cfg, classnames, clip_model, logger):
        super().__init__()
        dtype = clip_model.dtype
        self.use_prompt_stage = cfg.TRAINER.ViFi_CLIP.PROMPT_MODEL
        ctx_init = cfg.TRAINER.ViFi_CLIP.CTX_INIT
        ZS_evaluation = cfg.TRAINER.ViFi_CLIP.ZS_EVAL
        if ZS_evaluation:
            text_aug = f"{{}}"
            tokenized_prompts = torch.cat([clip.tokenize(text_aug.format(c), context_length=77) for c in classnames])
            embedding = clip_model.token_embedding(tokenized_prompts).type(dtype).cuda()
            self.register_buffer("complete_text_embeddings", embedding)
            self.tokenized_prompts = tokenized_prompts  # torch.Tensor
        elif self.use_prompt_stage:
            n_cls = len(classnames)
            # Make sure Language depth >= 1
            assert cfg.TRAINER.ViFi_CLIP.PROMPT_DEPTH_TEXT >= 1, "In VL prompting, Language prompt depth should be >=1" \
                                                        "\nPlease use VPT trainer if you want to learn only vision " \
                                                        "branch  "
            n_ctx = cfg.TRAINER.ViFi_CLIP.N_CTX_TEXT
            ctx_dim = clip_model.ln_final.weight.shape[0]

            if ctx_init and (n_ctx) <= 4:
                # use given words to initialize context vectors
                ctx_init = ctx_init.replace("_", " ")
                n_ctx = n_ctx
                prompt = clip.tokenize(ctx_init)
                with torch.no_grad():
                    embedding = clip_model.token_embedding(prompt).type(dtype)
                ctx_vectors = embedding[0, 1: 1 + n_ctx, :]
                prompt_prefix = ctx_init
            else:
                # random initialization
                ctx_vectors = torch.empty(n_ctx, ctx_dim, dtype=dtype)
                nn.init.normal_(ctx_vectors, std=0.02)
                prompt_prefix = " ".join(["X"] * n_ctx)
            logger.info(f"V-L design")
            logger.info(f'Initial text context: "{prompt_prefix}"')
            logger.info(f"Number of context words (tokens) for Language prompting: {n_ctx}")
            logger.info(f"Number of context words (tokens) for Vision prompting: {cfg.TRAINER.ViFi_CLIP.N_CTX_VISION}")
            self.ctx = nn.Parameter(ctx_vectors)

            classnames = [name.replace("_", " ") for name in classnames]
            prompts = [prompt_prefix + " " + name + "." for name in classnames]

            tokenized_prompts = torch.cat([clip.tokenize(p) for p in prompts])  # (n_cls, n_tkn)
            with torch.no_grad():
                embedding = clip_model.token_embedding(tokenized_prompts).type(dtype)

            # These token vectors will be saved when in save_model(),
            # but they should be ignored in load_model() as we want to use
            # those computed using the current class names
            self.register_buffer("token_prefix", embedding[:, :1, :])  # SOS
            self.register_buffer("token_suffix", embedding[:, 1 + n_ctx:, :])  # CLS, EOS
            self.n_cls = n_cls
            self.tokenized_prompts = tokenized_prompts  # torch.Tensor
        else:
            # No prompting
            ctx_init = ctx_init.replace("_", " ")
            prompt_prefix = ctx_init
            prompts = [prompt_prefix + " " + name + "." for name in classnames]
            tokenized_prompts = torch.cat([clip.tokenize(p) for p in prompts])  # (n_cls, n_tkn)
            with torch.no_grad():
                embedding = clip_model.token_embedding(tokenized_prompts).type(dtype)
            self.register_buffer("complete_text_embeddings", embedding)
            self.tokenized_prompts = tokenized_prompts  # torch.Tensor

    def construct_prompts(self, ctx, prefix, suffix, label=None):
        # dim0 is either batch_size (during training) or n_cls (during testing)
        # ctx: context tokens, with shape of (dim0, n_ctx, ctx_dim)
        # prefix: the sos token, with shape of (n_cls, 1, ctx_dim)
        # suffix: remaining tokens, with shape of (n_cls, *, ctx_dim)

        if label is not None:
            prefix = prefix[label]
            suffix = suffix[label]

        prompts = torch.cat(
            [
                prefix,  # (dim0, 1, dim)
                ctx,  # (dim0, n_ctx, dim)
                suffix,  # (dim0, *, dim)
            ],
            dim=1,
        )

        return prompts

    def forward(self):
        if self.use_prompt_stage:
            ctx = self.ctx
            if ctx.dim() == 2:
                ctx = ctx.unsqueeze(0).expand(self.n_cls, -1, -1)

            prefix = self.token_prefix
            suffix = self.token_suffix
            prompts = self.construct_prompts(ctx, prefix, suffix)
        else:
            prompts = self.complete_text_embeddings

        return prompts

class ViFiCLIP(nn.Module):
    def __init__(self, cfg, classnames, clip_model, logger):
        super().__init__()
        self.prompt_learner = VLPromptLearner(cfg, classnames, clip_model, logger)
        self.tokenized_prompts = self.prompt_learner.tokenized_prompts
        self.image_encoder = clip_model.visual
        self.text_encoder = TextEncoder(clip_model)
        self.logit_scale = clip_model.logit_scale
        self.dtype = clip_model.dtype
    def forward(self, image):
        tokenized_prompts = self.tokenized_prompts
        logit_scale = self.logit_scale.exp()
        prompts = self.prompt_learner()

        # b = image.shape[0]
        # Lets encode the video into required format
        b, t, c, h, w = image.size()
        # Remove the batch dimensions
        image = image.reshape(-1, c, h, w)
        # Now pass the image into CLIP visual encoder
        image_features = self.image_encoder(image.type(self.dtype))
        # Now again attach the batch dimensions
        image_features = image_features.view(b, t, -1)  # [B, T, 512]
        # Now take the mean along the temporal direction
        image_features = image_features.mean(dim=1, keepdim=False)  # image features are now ready

        # Finally, make the text features
        text_features = self.text_encoder(prompts, tokenized_prompts)

        image_features = image_features / image_features.norm(dim=-1, keepdim=True)
        text_features = text_features / text_features.norm(dim=-1, keepdim=True)
        logits = logit_scale * image_features @ text_features.t()

        return logits

def returnCLIP(config, logger=None,
               class_names=None):
    logger.info(f"Loading CLIP (backbone: {config.MODEL.ARCH})")
    clip_model = load_clip_to_cpu(config)

    logger.info("Building ViFi-CLIP CLIP")
    model = ViFiCLIP(config, class_names, clip_model, logger)

    if config.TRAINER.ViFi_CLIP.PROMPT_MODEL:
        logger.info("Turning off gradients in both the image and the text encoder")
        name_to_update = "prompt_learner"
        for name, param in model.named_parameters():
            if name_to_update not in name:
                # Make sure that VPT prompts are updated
                if "VPT" in name:
                    param.requires_grad_(True)
                else:
                    param.requires_grad_(False)
    else:
        # Now need to control freezing of CLIP for fine-tuning
        train_complete_clip = config.TRAINER.ViFi_CLIP.USE
        if train_complete_clip == "both":
            logger.info("Turning on gradients for COMPLETE ViFi-CLIP model")
            for name, param in model.named_parameters():
                param.requires_grad_(True)
        else:
            if train_complete_clip == "image":
                logger.info("Turning on gradients for image side the ViFi-CLIP model")
                for name, param in model.named_parameters():
                    if "image_encoder" in name:  # replace by "text_encoder" incase you want to freeze text
                        param.requires_grad_(True)
                    else:
                        param.requires_grad_(False)
            else:
                logger.info("Turning on gradients for TEXT side the ViFi-CLIP model")
                for name, param in model.named_parameters():
                    if "text_encoder" in name:  # replace by "text_encoder" incase you want to freeze text
                        param.requires_grad_(True)
                    else:
                        param.requires_grad_(False)
    # Double check
    enabled = set()
    for name, param in model.named_parameters():
        if param.requires_grad:
            enabled.add(name)
    logger.info(f"Parameters to be updated: {enabled}")
    logger.info(f"Total learnable items: {len(enabled)}")
    model.float()
    return model


from absl.testing import parameterized

import numpy as np
import tensorflow.compat.v2 as tf
import tensorflow_probability as tfp

import tf_quant_finance as tff
from tensorflow.python.framework import test_util  # pylint: disable=g-direct-tensorflow-import

@test_util.run_all_in_graph_and_eager_modes
class SimulatedDataCalibrationTest(parameterized.TestCase, tf.test.TestCase):

  @parameterized.named_parameters(
      {
          'testcase_name': 'conjugate_gradient_optimizer',
          'optimizer_fn': tff.math.optimizer.conjugate_gradient_minimize,
      }, {
          'testcase_name': 'bfgs_optimizer',
          'optimizer_fn': tfp.optimizer.bfgs_minimize,
      })
  def test_calibration_correctness(self, optimizer_fn):
    true_parameters = np.array([[0.04, 0.15, 0.5, 0.3, 0.3],
                                [0.02, 0.25, 0.4, 0.25, 0.25]])

    forwards = np.array([5., 6.])
    expiries = np.array([1., 1.])

    strikes = np.array([
        [
            0.24893534, 0.35810619, 0.51515402, 0.74107533, 1.06607467,
            1.53360279, 2.20616584, 3.17368209, 4.56550358, 6.56770979,
            9.44798554, 13.59140914
        ],
        [
            0.8120117, 1.16812025, 1.68040056, 2.41734193, 3.47746967,
            5.00251751, 7.19637661, 10.35235484, 14.89239051, 21.4234634,
            30.8187449, 44.33433659
        ],
    ])

    volatilities = np.array([
        [
            0.53809037, 0.51236712, 0.48535488, 0.45686258, 0.42666483,
            0.39451975, 0.3602712, 0.32435877, 0.29085295, 0.28834027,
            0.3644639, 0.45468296
        ],
        [
            0.60080077, 0.55414627, 0.50349337, 0.44780265, 0.38588647,
            0.31868425, 0.27922126, 0.38249619, 0.51199324, 0.62087246,
            0.71471493, 0.7980863
        ],
    ])

    (model_parameters, converged, _) = self.evaluate(
        tff.experimental.svi.calibration(
            forwards=forwards,
            expiries=expiries,
            strikes=strikes,
            volatilities=volatilities,
            optimizer_fn=optimizer_fn))

    # Assert model convergence to expected parameters.
    self.assertTrue(converged.all())
    self.assertAllClose(model_parameters, true_parameters, atol=1e-4, rtol=1e-3)

  def test_calibration_correctness_bulk(self):
    np.random.seed(321)
    batch_size = 7
    num_strikes = 30
    forwards = 4. + 5. * np.random.random(size=batch_size)
    expiries = 0.5 + np.ones_like(forwards)
    log_moneyness = np.random.normal(size=(batch_size, num_strikes))
    strikes = forwards[:, np.newaxis] * np.exp(log_moneyness)

    svi_a = 0.1 + 0.3 * np.random.random(size=batch_size)
    svi_b = 0.3 * np.random.random(size=batch_size)
    svi_rho = np.random.random(size=batch_size) - 0.5
    svi_m = 0.5 * np.random.normal(size=batch_size)
    svi_sigma = 0.1 + 0.5 * np.random.random(size=batch_size)
    true_parameters = np.transpose([svi_a, svi_b, svi_rho, svi_m, svi_sigma])

    target_volatilities = tff.experimental.svi.implied_volatility_from_raw_svi_parameters(
        svi_parameters=true_parameters,
        log_moneyness=log_moneyness,
        expiries=expiries)

    (model_parameters, converged, _) = self.evaluate(
        tff.experimental.svi.calibration(
            forwards=forwards,
            expiries=expiries,
            strikes=strikes,
            volatilities=target_volatilities,
            optimizer_fn=tfp.optimizer.bfgs_minimize))

    # Assert model convergence to expected parameters.
    self.assertTrue(converged.all())
    self.assertAllClose(model_parameters, true_parameters, atol=1e-3, rtol=1e-2)

  def test_weights_to_handle_outliers(self):
    true_parameters = np.array([[0.04, 0.15, 0.5, 0.3, 0.3]])

    forwards = np.array([5.])
    expiries = np.array([1.])

    strikes = np.array([
        [
            0.24893534, 0.35810619, 0.51515402, 0.74107533, 1.06607467,
            1.53360279, 2.20616584, 3.17368209, 4.56550358, 6.56770979,
            9.44798554, 13.59140914
        ],
    ])

    volatilities = np.array([
        [
            0.53809037, 0.51236712, 0.48535488, 0.45686258, 0.42666483,
            0.39451975, 0.3602712, 0.32435877, 0.29085295, 0.28834027,
            0.3644639, 0.45468296
        ],
    ])
    weights = np.ones_like(volatilities)

    (model_parameters, converged, _) = self.evaluate(
        tff.experimental.svi.calibration(
            forwards=forwards,
            expiries=expiries,
            strikes=strikes,
            volatilities=volatilities,
            weights=weights,
            optimizer_fn=tfp.optimizer.bfgs_minimize))

    with self.subTest('Model without outliers converged'):
      self.assertTrue(converged.all())
    with self.subTest('Parameters correct for model without outliers'):
      self.assertAllClose(
          model_parameters, true_parameters, atol=1e-4, rtol=1e-3)

    # introduce outliers - changes tail volatilities to much higher values
    volatilities[0, 0] = 0.7
    volatilities[0, 0] = 0.8

    (model_parameters, converged, _) = self.evaluate(
        tff.experimental.svi.calibration(
            forwards=forwards,
            expiries=expiries,
            strikes=strikes,
            volatilities=volatilities,
            weights=weights,
            optimizer_fn=tfp.optimizer.bfgs_minimize))
    with self.subTest('Model with outliers did not converge'):
      self.assertFalse(converged.all())
    with self.subTest('Parameters incorrect for model with outliers'):
      self.assertNotAllClose(
          model_parameters, true_parameters, atol=1e-4, rtol=1e-3)

    # zero out optimization weights, corresponding to outliers
    weights[0, 0] = 0
    weights[0, -1] = 0

    (model_parameters, converged, _) = self.evaluate(
        tff.experimental.svi.calibration(
            forwards=forwards,
            expiries=expiries,
            strikes=strikes,
            volatilities=volatilities,
            weights=weights,
            optimizer_fn=tfp.optimizer.bfgs_minimize))

    with self.subTest('Model with weighted out outliers converged'):
      self.assertTrue(converged.all())
    with self.subTest(
        'Parameters correct for model with weighted out outliers'):
      self.assertAllClose(
          model_parameters, true_parameters, atol=1e-4, rtol=1e-3)

@test_util.run_all_in_graph_and_eager_modes
class RealMarketDataCalibrationTest(parameterized.TestCase, tf.test.TestCase):
  r"""Tests are loosely based on real market prices for GOOG call options.

  The quotes for GOOG210820C* were taken on 2021-05-28 from
  https://finance.yahoo.com/quote/GOOG/options?date=1629417600
  """

  def setUp(self):
    super().setUp()
    self.forwards = np.array([2402.])
    self.expiries = np.array([0.23])
    self.strikes = np.array([[
        1700., 1800., 1900., 2000., 2050., 2100., 2200., 2250., 2350., 2400.,
        2450., 2500., 2550., 2600., 2650., 2700., 2750., 2800., 2850., 2900.,
        2950., 3000.
    ]])
    self.volatilities = np.array([[
        0.5335, 0.4882, 0.4389, 0.3937, 0.3749, 0.3569, 0.3259, 0.3135, 0.29,
        0.283, 0.2717, 0.2667, 0.2592, 0.2566, 0.2564, 0.2574, 0.2595, 0.2621,
        0.2669, 0.2732, 0.2826, 0.2967
    ]])

  @parameterized.named_parameters(
      {
          'testcase_name':
              'conjugate_gradient_optimizer',
          'optimizer_fn':
              tff.math.optimizer.conjugate_gradient_minimize,
          'expected_parameters':
              np.array([[-0.1705, 0.3222, -0.0772, 0.0514, 0.5781]])
      }, {
          'testcase_name':
              'bfgs_optimizer',
          'optimizer_fn':
              tfp.optimizer.bfgs_minimize,
          'expected_parameters':
              np.array([[-0.1825, 0.3306, -0.0988, 0.0368, 0.6011]])
      })
  def test_real_market_data_calibration(self, optimizer_fn,
                                        expected_parameters):
    svi_parameters, converged, _ = self.evaluate(
        tff.experimental.svi.calibration(
            forwards=self.forwards,
            expiries=self.expiries,
            strikes=self.strikes,
            volatilities=self.volatilities,
            optimizer_fn=optimizer_fn,
            tolerance=1e-4))
    self.assertTrue(converged.all())
    self.assertAllClose(
        svi_parameters, expected_parameters, atol=1e-4, rtol=2e-2)

  @parameterized.named_parameters(
      {
          'testcase_name': 'conjugate_gradient_optimizer',
          'optimizer_fn': tff.math.optimizer.conjugate_gradient_minimize,
          'atol': 0.01,
          'rtol': 0.02
      }, {
          'testcase_name': 'bfgs_optimizer',
          'optimizer_fn': tfp.optimizer.bfgs_minimize,
          'atol': 0.01,
          'rtol': 0.02
      })
  def test_model_well_approximates_target_volatilities(self, optimizer_fn, atol,
                                                       rtol):
    svi_parameters, converged, _ = self.evaluate(
        tff.experimental.svi.calibration(
            forwards=self.forwards,
            expiries=self.expiries,
            strikes=self.strikes,
            volatilities=self.volatilities,
            optimizer_fn=optimizer_fn,
            tolerance=1e-4))
    self.assertTrue(converged.all())

    model_volatilities = self.evaluate(
        tff.experimental.svi.implied_volatility_from_raw_svi_parameters(
            svi_parameters=svi_parameters,
            forwards=self.forwards,
            strikes=self.strikes,
            expiries=self.expiries))
    self.assertAllClose(
        model_volatilities, self.volatilities, atol=atol, rtol=rtol)

  @parameterized.named_parameters(
      {
          'testcase_name': 'conjugate_gradient_optimizer',
          'optimizer_fn': tff.math.optimizer.conjugate_gradient_minimize,
          'rtol': 0.04
      }, {
          'testcase_name': 'bfgs_optimizer',
          'optimizer_fn': tfp.optimizer.bfgs_minimize,
          'rtol': 0.05
      })
  def test_model_well_approximates_target_variance(self, optimizer_fn, rtol):
    svi_parameters, converged, _ = self.evaluate(
        tff.experimental.svi.calibration(
            forwards=self.forwards,
            expiries=self.expiries,
            strikes=self.strikes,
            volatilities=self.volatilities,
            optimizer_fn=optimizer_fn,
            tolerance=1e-4))
    self.assertTrue(converged.all())

    total_variance = self.volatilities**2 * self.expiries
    model_variance = self.evaluate(
        tff.experimental.svi.total_variance_from_raw_svi_parameters(
            svi_parameters=svi_parameters,
            forwards=self.forwards,
            strikes=self.strikes))
    self.assertAllClose(model_variance, total_variance, rtol=rtol, atol=1e-4)

if __name__ == '__main__':
  tf.test.main()


# *******
# DICA:#
# ***********************************************
# não passei o arguemento blank nem null como #
#  True então esse campo é obrigatório        #
# **********************************************

from django.db import models

class Task(models.Model):

    STATUS = (("doing", "Doing"), ("done", "Done"))

    title = models.CharField("title", max_length=100)

    resumetask = models.TextField(
        "resumetask",
        max_length=400,
        blank=True,
        null=True,
    )

    done = models.CharField(
        max_length=5,
        choices=STATUS,
    )

    def __str__(self):
        return self.title


from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('list/user/', views.ListUsuariosView.as_view(), name='list-user'),
    path('create/user/', views.CreateUsuarioView.as_view(), name='create-user'),
    path('update/user/<pk>/', views.UpdateUsuarioView.as_view(), name='update-user'),
    path('delete/user/<pk>/', views.DeleteUsuarioView.as_view(), name='delete-user'),

    path('list/resenia/', views.ListReseniaView.as_view(), name='list-resenia'),
    path('create/resenia/', views.CreateReseniaView.as_view(), name='create-resenia'),
    path('update/resenia/<pk>/', views.UpdateReseniaView.as_view(), name='update-resenia'),
    path('delete/resenia/<pk>/', views.DeleteReseniaView.as_view(), name='delete-resenia'),
]


from enum import Enum

class Reflector:

    def __init__(self, etype, wiring):
        self.wiring = dict(wiring)
        self.wiring_type = WiringType.Std
        self.eType = etype

    def encode(self, char_in):
        # Input Validation
        if not isinstance(char_in, str) or char_in not in self.wiring:
            raise ValueError(f"{char_in} is not a valid input. Input must be an UPPERCASE character between A and Z included")
        char_out = self.wiring[char_in]
        return char_out

    def swap_wiring(self, new_wiring):
        new_wiring_dict = dict(new_wiring)
        if self.wiring != new_wiring_dict:
            self.wiring = new_wiring_dict
            self.wiring_type = WiringType.Mod

    def reset_std_wiring(self):
        self.wiring = dict(get_wiring_by_ReflectorType(self.eType))
        self.wiring_type = WiringType.Std

    # find the swapped pairs in the reflector with respect to the standard wiring
    def find_wiring_changes(self):
        if self.wiring_type == WiringType.Std:
            # no changes, return an empty list
            return []
        std_wiring = get_wiring_by_ReflectorType(self.wiring_type)
        mod_wiring = self.wiring.items()
        # find the connections which were modified
        mod_pairs = [x for x in mod_wiring if x not in std_wiring]
        # removed complementary pairs
        for x, y in mod_pairs:
            if (y, x) in mod_pairs:
                idx = mod_pairs.index((y, x))
                mod_pairs.pop(idx)
        mod_pairs = [x+y for x, y in mod_pairs]
        return mod_pairs

    # two reflector are equal if they are of the same type
    def __eq__(self, other):
        return self.eType == other.eType

# # Enumerator class to identify reflector
class ReflectorType(Enum):
    ND = 0
    A = 1
    B = 2
    C = 3

# Enumerator class to identify if a reflector's wiring has been manually modified or not
class WiringType(Enum):
    ND = 0
    Std = 1
    Mod = 2

def reflectorType_from_name(reflector_name):
    if reflector_name == "A":
        reflector_type = ReflectorType.A
    elif reflector_name == "B":
        reflector_type = ReflectorType.B
    elif reflector_name == "C":
        reflector_type = ReflectorType.C
    else:
        raise ValueError(f"Reflector {reflector_name} does not exist")
    return reflector_type

def reflector_from_name(reflector_name):
    reflector_type = reflectorType_from_name(reflector_name)
    wiring = get_wiring_by_ReflectorType(reflector_type)
    reflector = Reflector(reflector_type, wiring)
    return reflector

def get_wiring_by_ReflectorType(reflector_type):
    base_contact = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

    wiring_matrix = [
                   ["E", "J", "M", "Z", "A", "L", "Y", "X", "V", "B", "W", "F", "C", "R", "Q", "U", "O", "N", "T", "S", "P", "I", "K", "H", "G", "D"],  # A
                   ['Y', 'R', 'U', 'H', 'Q', 'S', 'L', 'D', 'P', 'X', 'N', 'G', 'O', 'K', 'M', 'I', 'E', 'B', 'F', 'Z', 'C', 'W', 'V', 'J', 'A', 'T'],  # B
                   ['F', 'V', 'P', 'J', 'I', 'A', 'O', 'Y', 'E', 'D', 'R', 'Z', 'X', 'W', 'G', 'C', 'T', 'K', 'U', 'Q', 'S', 'B', 'N', 'M', 'H', 'L']]  # C

    wiring = list(zip(wiring_matrix[reflector_type.value - 1], base_contact))
    return wiring

if __name__ == "__main__":
    reflector = reflector_from_name("A")
    assert(reflector.encode("A") == "E")
    assert(reflector.encode("E") == "A")


width, height = input("Input: ").split(" ")

if not width.isdigit() or not height.isdigit():
    print("Invalid Input")
    exit()
else:
    width = int(width)
    height = int(height)

if not 1 < width < 9 and not 1 < height < 9:
    print("Invalid Input")
    exit()

start = 1
end = width + 1

for r in range(1, height+1):
    if r % 2 != 0: # odd row
        for c in range(start, width + 1):
            print(c, end="")

        for i in range(1, start):
            print(i, end="")

        print()
        end -= 1

    else:  # even row
        for c in range(end, 0, -1):
            print(c, end="")

        for i in range(width, end, -1):
            print(i, end="")

        print()
        start += 1


""" Binary Search Trees by Ravi Dugh"""

class BinarySearchTree:
    def __init__(self):
        self.root = None
        self.size = 0

    def __len__(self):
        return self.length()

    def __iter__(self):
        return self.root.__iter__()

    def __setitem__(self, k, v):
        self.put(k, v)

    def __getitem__(self, k):
        return self.get(k)

    def __contains__(self, k):
        #if self._get(key, self.root):
        #    return True
        #else:
        #    return False

        return self._get(k, self.root) is not None

    def __delitem__(self, k):
        self.delete(k)

    def length(self):
        return self.size

    def put(self, key, val):
        if self.root:
            self._put(key, val, self.root)
        else:  # the tree is non-existient
            self.root = TreeNode(key, val)

        self.size += 1

    def _put(self, key, val, current_node):
        if key < current_node.key:
            if current_node.has_left_child():
                self._put(key, val, current_node.left_child)
            else:
                current_node.left_child = TreeNode(key, val, parent=current_node)
        else:
            if current_node.has_right_child():
                self._put(key, val, current_node.right_child)
            else:
                current_node.right_child = TreeNode(key, val, parent=current_node)

    def get(self, key):
        if self.root:
            res = self._get(key, self.root)
            if res:
                # return the value of our TreeNode with matching key
                return res.payload
            else:
                return None
        else:
            return None

    def _get(self, key, current_node):
        if not current_node:
            return None
        elif current_node.key == key:
            return current_node
        elif key < current_node.key:
            return self._get(key, current_node.left_child)
        else:
            return self._get(key, current_node.right_child)

    def delete(self, key):
        if self.size > 1:
            node_to_remove = self._get(key, self.root)
            if node_to_remove:
                self.remove(node_to_remove)
                self.size -= 1
            else:
                raise KeyError("Key not found in tree!")
        elif self.size == 1 and self.root.key == key:
            # tree is completely removed, since it was only one node
            self.root = None
            self.size -= 1
        else:
            raise KeyError("Key not found in tree!")

    def remove(self, current_node):
        if current_node.is_leaf():  # leaf
            #if current_node == current_node.parent.left_child:
            if current_node.is_left_child():
                current_node.parent.left_child = None
            else:
                current_node.parent.right_child = None
        elif current_node.has_both_children():  # interior
            succ = current_node.find_successor()
            succ.splice_out()
            current_node.key = succ.key
            current_node.payload = succ.payload
        else:  # node has one child
            if current_node.has_left_child():
                if current_node.is_left_child():
                    current_node.left_child.parent = current_node.parent
                    current_node.parent.left_child = current_node.left_child
                elif current_node.is_right_child():
                    current_node.left_child.parent = current_node.parent
                    current_node.parent.right_child = current_node.left_child
                else:
                    current_node.replace_node_data(current_node.left_child.key,
                                                   current_node.left_child.payload,
                                                   current_node.left_child.left_child,
                                                   current_node.left_child.right_child)
            else:
                if current_node.is_left_child():
                    current_node.right_child.parent = current_node.parent
                    current_node.parent.left_child = current_node.right_child
                elif current_node.is_right_child():
                    current_node.right_child.parent = current_node.parent
                    current_node.parent.right_child = current_node.right_child
                else:
                    current_node.replace_node_data(current_node.right_child.key,
                                                   current_node.right_child.payload,
                                                   current_node.right_child.left_child,
                                                   current_node.right_child.right_child)
    def __repr__(self):
        return f"BinarySearchTree: < {(self.size)} >"

class TreeNode:
    def __init__(self, key, val, left=None, right=None, parent=None):
        self.key = key
        self.payload = val
        self.left_child = left
        self.right_child= right
        self.parent = parent

    def __iter__(self):
        if self:
            if self.has_left_child():
                for elem in self.left_child:
                    yield elem

            yield self.key

            if self.has_right_child():
                for elem in self.right_child:
                    yield elem

    def has_left_child(self):
        return self.left_child

    def has_right_child(self):
        return self.right_child

    def is_left_child(self):
        return self.parent and self.parent.left_child is self

    def is_right_child(self):
        return self.parent and self.parent.right_child is self

    def is_root(self):
        return not self.parent

    def is_leaf(self):
        return not self.left_child and not self.right_child

    def has_any_children(self):
        return self.right_child or self.left_child

    def has_both_children(self):
        return self.right_child and self.left_child

    def replace_node_data(self, key, value, lc, rc):
        self.key = key
        self.payload = value
        self.left_child = lc
        self.right_child = rc

        if self.has_left_child():
            self.left_child.parent = self

        if self.has_right_child():
            self.right_child.parent = self

    def splice_out(self):
        if self.is_leaf():
            if self.is_left_child():
                self.parent.left_child = None
            else:
                self.parent.right_child = None
        elif self.has_any_children():
            if self.has_left_child():
                if self.is_left_child():
                    self.parent.left_child = self.left_child
                else:
                    self.parent.right_child = self.left_child

                self.left_child.parent = self.parent
            else:  # has a right child
                if self.is_left_child():
                    self.parent.left_child = self.right_child
                else:
                    self.parent.right_child = self.right_child

                self.right_child.parent = self.parent

    def find_successor(self):
        succ = None

        if self.has_right_child():
            succ = self.right_child.find_min()
        else:  # no right child? Then we work on left child
            if self.parent:  # it is an intermediate node
                if self.is_left_child():
                    succ = self.parent
                else:  # is a right child
                    self.parent.right_child = None
                    succ = self.parent.find_successor()
                    self.parent.right_child = self
        return succ

    def find_min(self):
        current = self

        while current.has_left_child():
            current = current.left_child

        return current


# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.

import unittest

from iptest import IronPythonTestCase, is_cli, is_netcoreapp21, is_posix, run_test, skipUnlessIronPython

if is_cli:
    import clr
    import clrtype

    clr.AddReference("System.Xml")

    import System
    from System.Reflection import BindingFlags

    class IProduct(object, metaclass=clrtype.ClrInterface):
        __metaclass__ = clrtype.ClrInterface # https://github.com/IronLanguages/ironpython3/issues/836

        _clrnamespace = "IronPython.Samples.ClrType"

        @property
        @clrtype.accepts()
        @clrtype.returns(str)
        def Name(self): raise RuntimeError("this should not get called")

        @property
        @clrtype.accepts()
        @clrtype.returns(float)
        def Cost(self): raise RuntimeError("this should not get called")

        @clrtype.accepts()
        @clrtype.returns(bool)
        def IsAvailable(self): raise RuntimeError("this should not get called")

    class Product(IProduct, metaclass=clrtype.ClrClass):
        __metaclass__ = clrtype.ClrClass # https://github.com/IronLanguages/ironpython3/issues/836

        _clrnamespace = "IronPython.Samples.ClrType"

        _clrfields = {
            "name" : str,
            "cost" : float,
            "_quantity" : int
        }

        CLSCompliant = clrtype.attribute(System.CLSCompliantAttribute)
        clr.AddReference("System.Xml")
        XmlRoot = clrtype.attribute(System.Xml.Serialization.XmlRootAttribute)

        _clrclassattribs = [
            # Use System.Attribute subtype directly for custom attributes without arguments
            System.ObsoleteAttribute,
            # Use clrtype.attribute for custom attributes with arguments (either positional, named, or both)
            CLSCompliant(False),
            XmlRoot("product", Namespace="www.contoso.com")
        ]

        def __init__(self, name, cost, quantity):
            self.name = name
            self.cost = cost
            self._quantity = quantity

        # IProduct methods
        def Name(self): return self.name
        def Cost(self): return self.cost
        def IsAvailable(self): return self.quantity != 0

        @property
        @clrtype.accepts()
        @clrtype.returns(int)
        def quantity(self): return self._quantity

        @quantity.setter
        @clrtype.accepts(int)
        @clrtype.returns()
        def quantity(self, value): self._quantity = value

        @clrtype.accepts(float)
        @clrtype.returns(float)
        def calc_total(self, discount=0.0):
            return (self.cost - discount) * self.quantity

    if not is_netcoreapp21 and not is_posix:
        class NativeMethods(object, metaclass=clrtype.ClrClass):
            # Note that you could also the "ctypes" modules instead of pinvoke declarations
            __metaclass__ = clrtype.ClrClass # https://github.com/IronLanguages/ironpython3/issues/836

            from System.Runtime.InteropServices import DllImportAttribute, PreserveSigAttribute
            DllImport = clrtype.attribute(DllImportAttribute)
            PreserveSig = clrtype.attribute(PreserveSigAttribute)

            @staticmethod
            @DllImport("user32.dll")
            @PreserveSig()
            @clrtype.accepts(System.Char)
            @clrtype.returns(System.Boolean)
            def IsCharAlpha(c): raise RuntimeError("this should not get called")

            @staticmethod
            @DllImport("user32.dll")
            @PreserveSig()
            @clrtype.accepts(System.IntPtr, System.String, System.String, System.UInt32)
            @clrtype.returns(System.Int32)
            def MessageBox(hwnd, text, caption, type): raise RuntimeError("this should not get called")

@skipUnlessIronPython()
class ClrTypeTest(IronPythonTestCase):
    def setUp(self):
        super(ClrTypeTest, self).setUp()
        self.p = Product("Widget", 10.0, 42)

    @unittest.skipIf(is_netcoreapp21, 'No DefinePInvokeMethod')
    @unittest.skipIf(is_posix, 'Windows specific P/Invoke')
    def test_pinvoke_method(self):
        self.assertTrue(NativeMethods.IsCharAlpha('A'))
        # Call statically-typed method from another .NET language (simulated using Reflection)
        isCharAlpha = clr.GetClrType(NativeMethods).GetMethod('IsCharAlpha')
        args = System.Array[object](('1'.Chars[0],))
        self.assertFalse(isCharAlpha.Invoke(None, args))

    def test_classattributes(self):
        t = clr.GetClrType(self.p.GetType())
        oa = t.GetCustomAttributes(System.ObsoleteAttribute, True)[0]
        clsc = t.GetCustomAttributes(System.CLSCompliantAttribute, True)[0]
        xmlr = t.GetCustomAttributes(System.Xml.Serialization.XmlRootAttribute, True)[0]

        self.assertEqual(oa.Message, None)
        self.assertFalse(clsc.IsCompliant)
        self.assertEqual(xmlr.ElementName, 'product')
        self.assertEqual(xmlr.Namespace, 'www.contoso.com')

    def test_clrtypeinfo(self):
        t = self.p.GetType()
        self.assertEqual(t.FullName, 'IronPython.Samples.ClrType.Product')

        # fields and properties
        bf = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy
        f = [field.Name for field in t.GetFields(bf)]
        self.assertTrue('name' in f)
        self.assertTrue('cost' in f)
        self.assertTrue('_quantity' in f)

        p = [property.Name for property in t.GetProperties(bf)]
        self.assertTrue('quantity' in p)

        # methods
        m = [method.Name for method in t.GetMethods() if method.DeclaringType == method.ReflectedType]
        self.assertTrue('calc_total' in m)
        self.assertTrue('quantity' in m)

    def test_interface_members(self):
        # Calling IProduct.Name and IProduct.IsAvailable as a strongly-typed members
        name = clr.GetClrType(IProduct).GetProperty("Name").GetGetMethod()
        self.assertEqual(name.Invoke(self.p, None), 'Widget')
        isAvailable = clr.GetClrType(IProduct).GetMethod("IsAvailable")
        self.assertTrue(isAvailable.Invoke(self.p, None))

    def _call_typed_method(self):
        """Calling calc_total as a strongly-typed method using Reflection"""
        calc_total = self.p.GetType().GetMethod("calc_total")
        args = System.Array[object]( (1.0,) )
        res = calc_total.Invoke(self.p, args)
        return res

    # these methods are named with numbers because they need to run in a specific order

    def test_0typed_method(self):
        self.assertEqual(self._call_typed_method(), 378.0)

    def test_1python_dynamism(self):
        # The object is still a Python object, and so allows setting new attributes
        self.p.sale_discount = 2.0

        # The class is also a Python class, and can also be modified
        def new_calc_total(self, discount=0.0):
            return (self.cost - (discount + self.sale_discount)) * self.quantity
        Product.calc_total = new_calc_total
        self.assertTrue(self._call_typed_method(), 294.0)

run_test(__name__)


from django.urls import path, re_path
from . import views

urlpatterns = [
    path('login', views.login, name="admin_login"),
    path('logout', views.logout, name="admin_logout"),
    path('login/validate', views.validate_admin_login, name="validate_admin_login"),
    path('', views.dashboard, name="admin_dashboard"),
    path('message/<int:id>/send/<int:uid>', views.send_message_customers, name="admin_send_message_customers"),

    # ajax
    path('ajax/datatables/customers', views.admin_datatable_ajax_customers_list, name="admin_datatable_ajax_customers_list"),
    path('ajax/datatables/staffs', views.admin_datatable_ajax_staffs, name="admin_datatable_ajax_staffs"),
    path('ajax/datatables/managers', views.admin_datatable_ajax_managers, name="admin_datatable_ajax_managers"),
    path('ajax/datatables/customers/followup', views.admin_datatable_ajax_customers_followup, name="admin_datatable_ajax_customers_followup"),
    path('ajax/datatables/followup', views.admin_datatable_ajax_followup, name="admin_datatable_ajax_followup"),
    path('ajax/datatables/message', views.admin_datatable_ajax_message, name="admin_datatable_ajax_message"),
    path('ajax/datatables/purchases', views.admin_datatable_ajax_customers_purchases, name="admin_datatable_ajax_customers_purchases"),
    path('ajax/datatables/payments', views.admin_datatable_ajax_customers_payments, name="admin_datatable_ajax_customers_payments"),
    path('ajax/datatables/refunds', views.admin_datatable_ajax_customers_refunds, name="admin_datatable_ajax_customers_refunds"),
    path('ajax/datatables/extras', views.admin_datatable_ajax_customers_extras, name="admin_datatable_ajax_customers_extras"),
    path('ajax/datatables/subscriptions', views.admin_datatable_ajax_customers_subscriptions, name="admin_datatable_ajax_customers_subscriptions"),
    path('ajax/datatables/extraless', views.admin_datatable_ajax_customers_extraless, name="admin_datatable_ajax_customers_extraless"),
    path('ajax/datatables/vacations', views.admin_datatable_ajax_customers_vacations, name="admin_datatable_ajax_customers_vacations"),
    path('ajax/datatables/reports/payments', views.admin_datatable_ajax_payments_report, name="admin_datatable_ajax_payments_report"),
    path('ajax/delivery/info', views.get_delivery_info, name="admin_get_delivery_info"),
    path('ajax/purchase/info', views.get_purchase_info, name="admin_get_purchase_info"),
    path('ajax/routes/customers', views.get_customers_of_route, name="admin_get_customers_of_route"),
    path('ajax/message/customers/date', views.get_message_date_of_customer, name="admin_get_message_date_of_customer"),
    path('ajax/routes/route-order/save', views.save_route_order, name="admin_save_route_order"),
    path('ajax/routes/customers/change', views.change_customers_route, name="admin_change_customers_route"),
    path('ajax/routes/customers/assign', views.assign_customers_route, name="admin_assign_customers_route"),
    path('ajax/routes/customers/assignations/clear', views.clear_customers_route_assignation, name="admin_clear_customers_route_assignation"),
    path('ajax/routes/customers/assignations/clear/all', views.clear_all_route_assignation, name="admin_clear_all_route_assignation"),

    #edit
    path('customers/edit/<int:id>', views.customers_edit, name="admin_customers_edit"),
    path('staffs/edit/<int:id>', views.staffs_edit, name="admin_staffs_edit"),
    path('managers/edit/<int:id>', views.managers_edit, name="admin_managers_edit"),
    path('payments/edit/<int:id>', views.payments_edit, name="admin_payments_edit"),
    path('refunds/edit/<int:id>', views.refunds_edit, name="admin_refunds_edit"),
    path('extras/edit/<int:id>', views.extras_edit, name="admin_extras_edit"),
    path('followup/edit/<int:id>', views.followup_edit, name="admin_followup_edit"),
    path('subscriptions/<int:id>', views.subscriptions_edit, name="admin_subscriptions_edit"),
    path('vacations/<int:id>', views.vacations_edit, name="admin_vacations_edit"),
    path('extraless/<int:id>', views.extraless_edit, name="admin_extraless_edit"),

    # create
    path('customers/create', views.customers_create, name="admin_customers_create"),
    path('staffs/create', views.staffs_create, name="admin_staffs_create"),
    path('managers/create', views.managers_create, name="admin_managers_create"),
    path('payments/create', views.payments_create, name="admin_payments_create"),
    path('refunds/create', views.refunds_create, name="admin_refunds_create"),
    path('extras/create', views.extras_create, name="admin_extras_create"),
    path('subscriptions/create', views.subscriptions_create, name="admin_subscriptions_create"),
    path('extraless/create', views.extraless_create, name="admin_extraless_create"),
    path('vacations/create', views.vacations_create, name="admin_vacations_create"),
    path('message/create', views.message_create, name="admin_message_create"),
    path('followup/add', views.add_followup_customer, name="admin_add_followup_customer"),

    # views
    path('customers/transactions/purchases', views.customers_purchases, name="admin_customers_purchases"),
    path('customers/transactions/payments', views.customers_payments, name="admin_customers_payments"),
    path('customers/transactions/refunds', views.customers_refunds, name="admin_customers_refunds"),
    path('customers/transactions/extras', views.customers_extras, name="admin_customers_extras"),
    path('customers/transactions/<int:id>', views.customer_transactions, name="admin_customers_transactions"),
    path('customers/subscriptions', views.customer_subscriptions, name="admin_customers_subscriptions"),
    path('customers/extraless', views.customer_extraless, name="admin_customers_extraless"),
    path('customers/vacations', views.customer_vacations, name="admin_customers_vacations"),
    path('customers/list', views.customers_list, name="admin_customers_list"),
    path('staffs/list', views.staff_list, name="admin_staff_list"),
    path('managers/list', views.manager_list, name="admin_manager_list"),
    path('customers/followup', views.customers_followup, name="admin_customers_followup"),
    path('followup', views.followup, name="admin_followup"),
    path('message', views.message, name="admin_message"),
    path('message/<int:id>/customers', views.message_customers, name="admin_message_customers"),
    path('route/order', views.route_ordering, name="admin_route_ordering"),
    path('reports/payments', views.payments_report, name="admin_payments_report"),

    # delete
    path('customers/delete/<int:id>', views.customer_delete, name="admin_customer_delete"),
    path('staffs/delete/<int:id>', views.staff_delete, name="admin_staff_delete"),
    path('managers/delete/<int:id>', views.manager_delete, name="admin_manager_delete"),
    path('payments/delete/<int:id>', views.payment_delete, name="admin_payment_delete"),
    path('refunds/delete/<int:id>', views.refund_delete, name="admin_refund_delete"),
    path('extras/delete/<int:id>', views.extra_delete, name="admin_extra_delete"),
    path('subscriptions/delete/<int:id>', views.subscription_delete, name="admin_subscription_delete"),
    path('extraless/delete/<int:id>', views.extraless_delete, name="admin_extraless_delete"),
    path('vacation/delete/<int:id>', views.vacation_delete, name="admin_vacation_delete"),
    path('followup/remove/<int:id>', views.remove_customer_followup, name="admin_remove_customer_followup"),
    path('message/delete/<int:id>', views.delete_message, name="admin_delete_message"),
    path('followup/remove/all', views.remove_all_customer_followup, name="admin_remove_all_customer_followup"),

    # end
    path('subscriptions/end/<int:id>', views.subscription_end, name="admin_subscription_end"),
    path('vacations/end/<int:id>', views.vacation_end, name="admin_vacation_end"),
    path('extraless/end/<int:id>', views.extraless_end, name="admin_extraless_end"),
]


fname = input("filename: ")
with open(fname, "w") as fh:
  fh.write(input("Enter file data:"))

fh = open(fname,'r')
freq = list()
words=[]
for line in fh:
    words += line.split()
words.sort()

print("The most freq words are:")

for word in words:
    if words.count(str(word))>1:
        if word not in freq:
            freq.append(word)
print(freq)


import tensorflow.compat.v2 as tf
import tf_quant_finance as tff

from tf_quant_finance.experimental.pricing_platform.framework.rate_instruments.interest_rate_swap import proto_utils
from tensorflow.python.framework import test_util  # pylint: disable=g-direct-tensorflow-import

framework = tff.experimental.pricing_platform.framework
business_days = framework.core.business_days
currencies = framework.core.currencies
daycount_conventions = framework.core.daycount_conventions

instrument_protos = tff.experimental.pricing_platform.instrument_protos
date_pb2 = instrument_protos.date
decimal_pb2 = instrument_protos.decimal
ir_swap = instrument_protos.interest_rate_swap
period_pb2 = instrument_protos.period

rate_instruments = tff.experimental.pricing_platform.framework.rate_instruments
interest_rate_swap = rate_instruments.interest_rate_swap

market_data = tff.experimental.pricing_platform.framework.market_data
market_data_config = market_data.config

DayCountConventions = daycount_conventions.DayCountConventions
BusinessDayConvention = business_days.BusinessDayConvention
RateIndex = instrument_protos.rate_indices.RateIndex
Currency = currencies.Currency

@test_util.run_all_in_graph_and_eager_modes
class ProtoUtilsTest(tf.test.TestCase):

  def setUp(self):
    self._pay_notional = 1000000
    self._receive_notional = 1200000
    self._swap_1 = ir_swap.InterestRateSwap(
        effective_date=date_pb2.Date(year=2019, month=10, day=3),
        maturity_date=date_pb2.Date(year=2029, month=10, day=3),
        currency=Currency.USD(),
        pay_leg=ir_swap.SwapLeg(
            fixed_leg=ir_swap.FixedLeg(
                currency=Currency.USD(),
                coupon_frequency=period_pb2.Period(type="MONTH", amount=6),
                notional_amount=decimal_pb2.Decimal(
                    units=self._pay_notional),
                fixed_rate=decimal_pb2.Decimal(nanos=31340000),
                daycount_convention=DayCountConventions.ACTUAL_360(),
                business_day_convention=BusinessDayConvention.
                MODIFIED_FOLLOWING(),
                settlement_days=2)),
        receive_leg=ir_swap.SwapLeg(
            floating_leg=ir_swap.FloatingLeg(
                currency=Currency.USD(),
                coupon_frequency=period_pb2.Period(type="MONTH", amount=3),
                reset_frequency=period_pb2.Period(type="MONTH", amount=3),
                notional_amount=decimal_pb2.Decimal(
                    units=self._receive_notional),
                floating_rate_type=RateIndex(type="LIBOR_3M"),
                daycount_convention=DayCountConventions.ACTUAL_360(),
                business_day_convention=BusinessDayConvention.
                MODIFIED_FOLLOWING(),
                settlement_days=2)))
    self._swap_2 = ir_swap.InterestRateSwap(
        effective_date=date_pb2.Date(year=2019, month=10, day=8),
        maturity_date=date_pb2.Date(year=2031, month=4, day=27),
        currency=Currency.CAD(),
        receive_leg=ir_swap.SwapLeg(
            fixed_leg=ir_swap.FixedLeg(
                currency=Currency.CAD(),
                coupon_frequency=period_pb2.Period(type="MONTH", amount=3),
                notional_amount=decimal_pb2.Decimal(
                    units=self._receive_notional),
                fixed_rate=decimal_pb2.Decimal(nanos=31340000),
                daycount_convention=DayCountConventions.ACTUAL_360(),
                business_day_convention=BusinessDayConvention.
                MODIFIED_FOLLOWING(),
                settlement_days=2)),
        pay_leg=ir_swap.SwapLeg(
            floating_leg=ir_swap.FloatingLeg(
                currency=Currency.CAD(),
                coupon_frequency=period_pb2.Period(type="MONTH", amount=3),
                reset_frequency=period_pb2.Period(type="MONTH", amount=3),
                notional_amount=decimal_pb2.Decimal(
                    units=self._pay_notional),
                floating_rate_type=RateIndex(type="LIBOR_3M"),
                daycount_convention=DayCountConventions.ACTUAL_360(),
                business_day_convention=BusinessDayConvention.
                MODIFIED_FOLLOWING(),
                settlement_days=2)))
    super(ProtoUtilsTest, self).setUp()

  def test_group_protos(self):
    proto_dict = proto_utils.group_protos(
        [self._swap_1, self._swap_2, self._swap_1])
    with self.subTest("NumGroups"):
      self.assertLen(proto_dict.keys(), 2)
    with self.subTest("CorrectBatches"):
      proto_list_1, proto_list_2 = proto_dict.values()
      # One of the lists contains two identical protos
      if len(proto_list_1) == 2:
        self.assertProtoEquals(proto_list_1[0], proto_list_1[1])
      else:
        self.assertProtoEquals(proto_list_2[0], proto_list_2[1])

  def test_from_protos(self):
    """Test that from_protos keeps pay leg as a fixed leg."""
    values_dict = proto_utils.from_protos([self._swap_2])
    values = list(values_dict.values())[0]
    # Notional amounts should have negative sign
    pay_leg_notional = values["pay_leg"].notional_amount[0]
    receive_leg_notional = values["receive_leg"].notional_amount[0]
    with self.subTest("PayLegNotional"):
      self.assertEqual(pay_leg_notional, -self._receive_notional)
    with self.subTest("PayLegFixed"):
      self.assertEqual(type(values["pay_leg"]),
                       rate_instruments.coupon_specs.FixedCouponSpecs)
    with self.subTest("ReceiveLegNotional"):
      self.assertEqual(receive_leg_notional, -self._pay_notional)
    with self.subTest("ReceiveLegFixed"):
      self.assertEqual(type(values["receive_leg"]),
                       rate_instruments.coupon_specs.FloatCouponSpecs)

if __name__ == "__main__":
  tf.test.main()


from aws_syncr.amazon.common import AmazonMixin
from aws_syncr.differ import Differ

from botocore.exceptions import ClientError
import boto3

import logging
import json
import os

log = logging.getLogger("aws_syncr.amazon.iam")

class Iam(AmazonMixin, object):
    def __init__(self, amazon, environment, accounts, dry_run):
        self.amazon = amazon
        self.dry_run = dry_run

        self.accounts = accounts
        self.account_id = accounts[environment]
        self.environment = environment

        self.client = self.amazon.session.client("iam")
        self.resource = self.amazon.session.resource('iam')

    def role_info(self, role_name):
        role = self.resource.Role(role_name.split('/')[-1])
        with self.ignore_missing():
            role.load()
            return role

    def create_role(self, name, trust_document, policies, attached_policies):
        with self.catch_boto_400("Couldn't Make role", "{0} assume document".format(name), trust_document, role=name):
            for _ in self.change("+", "role", role=name, document=trust_document):
                kwargs = {"RoleName": name, "AssumeRolePolicyDocument": trust_document}
                if '/' in name:
                    kwargs["RoleName"] = name.split('/')[-1]
                    kwargs["Path"] = "/{0}/".format('/'.join(name.split('/')[:-1]))
                self.resource.create_role(**kwargs)

        if policies:
            for policy_name, document in policies.items():
                if document:
                    with self.catch_boto_400("Couldn't add policy", "{0} - {1} Permission document".format(name, policy_name), document, role=name, policy_name=policy_name):
                        for _ in self.change("+", "role_policy", role=name, policy=policy_name, document=document):
                            self.resource.RolePolicy(name.split('/')[-1], policy_name).put(PolicyDocument=document)

        self.modify_attached_policies(name, attached_policies)

    def modify_role(self, role_info, name, trust_document, policies, attached_policies):
        changes = list(Differ.compare_two_documents(json.dumps(role_info.assume_role_policy_document), trust_document))
        if changes:
            with self.catch_boto_400("Couldn't modify trust document", "{0} assume document".format(name), trust_document, role=name):
                for _ in self.change("M", "trust_document", role=name, changes=changes):
                    self.resource.AssumeRolePolicy(name.split('/')[-1]).update(PolicyDocument=trust_document)

        with self.catch_boto_400("Couldn't get policies for a role", role=name):
            current_policies = dict((policy.name, policy) for policy in role_info.policies.all())
        unknown = [key for key in current_policies if key not in policies]

        if unknown:
            log.info("Role has unknown policies that will be disassociated\trole=%s\tunknown=%s", name, unknown)
            for policy in unknown:
                with self.catch_boto_400("Couldn't delete a policy from a role", policy=policy, role=name):
                    for _ in self.change("-", "role_policy", role=name, policy=policy):
                        current_policies[policy].delete()

        for policy, document in policies.items():
            has_statements = document and bool(json.loads(document)["Statement"])
            if not has_statements:
                if policy in current_policies:
                    with self.catch_boto_400("Couldn't delete a policy from a role", policy=policy, role=name):
                        for _ in self.change("-", "policy", role=name, policy=policy):
                            current_policies[policy].delete()
            else:
                needed = False
                changes = None

                if policy in current_policies:
                    changes = list(Differ.compare_two_documents(json.dumps(current_policies.get(policy).policy_document), document))
                    if changes:
                        log.info("Overriding existing policy\trole=%s\tpolicy=%s", name, policy)
                        needed = True
                else:
                    log.info("Adding policy to existing role\trole=%s\tpolicy=%s", name, policy)
                    needed = True

                if needed:
                    with self.catch_boto_400("Couldn't add policy document", "{0} - {1} policy document".format(name, policy), document, role=name, policy=policy):
                        symbol = "M" if changes else "+"
                        for _ in self.change(symbol, "role_policy", role=name, policy=policy, changes=changes, document=document):
                            if policy in current_policies:
                                current_policies[policy].put(PolicyDocument=document)
                            else:
                                self.client.put_role_policy(RoleName=name.split("/")[-1], PolicyName=policy, PolicyDocument=document)

            self.modify_attached_policies(name, attached_policies)

    def make_instance_profile(self, name):
        role_name = name.split('/')[-1]
        existing_roles_in_profile = None
        with self.ignore_missing():
            existing_roles_in_profile = self.resource.InstanceProfile(role_name).roles

        if existing_roles_in_profile is None:
            with self.catch_boto_400("Couldn't create instance profile", instance_profile=name):
                for _ in self.change("+", "instance_profile", profile=role_name):
                    self.client.create_instance_profile(InstanceProfileName=role_name)

        if existing_roles_in_profile and any(rl.name != role_name for rl in existing_roles_in_profile):
            for role in [rl for rl in existing_roles_in_profile if rl.name != role_name]:
                with self.catch_boto_400("Couldn't remove role from an instance profile", profile=role_name, role=role):
                    for _ in self.change("-", "instance_profile_role", profile=role_name, role=role):
                        self.resource.InstanceProfile(role_name).remove_role(RoleName=role)

        if not existing_roles_in_profile or not any(rl.name == role_name for rl in existing_roles_in_profile):
            try:
                with self.catch_boto_400("Couldn't add role to an instance profile", role=name, instance_profile=role_name):
                    for _ in self.change("+", "instance_profile_role", profile=role_name, role=role_name):
                        self.resource.InstanceProfile(role_name).add_role(RoleName=role_name)
            except ClientError as error:
                if error.response["ResponseMetadata"]["HTTPStatusCode"] == 409:
                    # I'd rather ignore this conflict, than list all the instance_profiles
                    # Basically, the instance exists but isn't associated with the role
                    pass
                else:
                    raise

    def modify_attached_policies(self, role_name, new_policies):
        """Make sure this role has just the new policies"""
        parts = role_name.split('/', 1)
        if len(parts) == 2:
            prefix, name = parts
            prefix = "/{0}/".format(prefix)
        else:
            prefix = "/"
            name = parts[0]

        current_attached_policies = []
        with self.ignore_missing():
            current_attached_policies = self.client.list_attached_role_policies(RoleName=name)
            current_attached_policies = [p['PolicyArn'] for p in current_attached_policies["AttachedPolicies"]]

        new_attached_policies = ["arn:aws:iam::aws:policy/{0}".format(p) for p in new_policies]

        changes = list(Differ.compare_two_documents(current_attached_policies, new_attached_policies))
        if changes:
            with self.catch_boto_400("Couldn't modify attached policies", role=role_name):
                for policy in new_attached_policies:
                    if policy not in current_attached_policies:
                        for _ in self.change("+", "attached_policy", role=role_name, policy=policy):
                            self.client.attach_role_policy(RoleName=name, PolicyArn=policy)

                for policy in current_attached_policies:
                    if policy not in new_attached_policies:
                        for _ in self.change("-", "attached_policy", role=role_name, changes=changes, policy=policy):
                            self.client.detach_role_policy(RoleName=name, PolicyArn=policy)

    def assume_role_credentials(self, arn):
        """Return the environment variables for an assumed role"""
        log.info("Assuming role as %s", arn)

        # Clear out empty values
        for name in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN']:
            if name in os.environ and not os.environ[name]:
                del os.environ[name]

        sts = self.amazon.session.client("sts")
        with self.catch_boto_400("Couldn't assume role", arn=arn):
            creds = sts.assume_role(RoleArn=arn, RoleSessionName="aws_syncr")

        return {
              'AWS_ACCESS_KEY_ID': creds["Credentials"]["AccessKeyId"]
            , 'AWS_SECRET_ACCESS_KEY': creds["Credentials"]["SecretAccessKey"]
            , 'AWS_SECURITY_TOKEN': creds["Credentials"]["SessionToken"]
            , 'AWS_SESSION_TOKEN': creds["Credentials"]["SessionToken"]
            }


# -*- coding: utf-8 -*-
"""
Created on Thu Nov  5 12:13:11 2020

@author: scott
"""

import serial
import msvcrt
import time

character = '';
ser = serial.Serial('com3', timeout=0.001)
while True:
    # part 1
    # num = ser.inWaiting()
    # x = ser.read(num)
    # print(type(x))
    # print(len(x))
    # print(x[-1])
    # time.sleep(0.2)

    # part 2
    # if (msvcrt.kbhit() == True):
    #     character = msvcrt.getch()
    #     ser.write(character)

    # part 3
    # if (msvcrt.kbhit() == True):
    #     character = msvcrt.getch()
    #     if (ord(character) == 119):
    #         ser.write(character)
    #     if(ord(character) == 113):
    #         ser.write(character)
    # if(ser.inWaiting() > 0):
    #     num = ser.inWaiting()
    #     x = ser.read(num)
    #     print(x[-1])

    # part 4
    if (msvcrt.kbhit() == True):
         character = msvcrt.getch()
         if (ord(character) == 119):
             ser.write(character)
         if(ord(character) == 113):
             ser.write(character)
    if(ser.inWaiting() >= 10):
        num = ser.inWaiting()
        x = ser.read(num)
        index = x.find(48)
        print(x[index+1], x[index+2])
ser.close()