from model_layer.vehicle import Vehicle
from model_layer.vehicle_type import VehicleType

class VehicleUI():
# Constants
    REGISTER = "Register new vehicle"
    FIND = "Find a vehicle"
    VIEW_ALL = "View all vehicles"
    VEHICLE_RATES = "Vehicle rates"
    AVAILABLE = "View available vehicles"

    def __init__(self, ui_helper, logic_api):
    # Use of logic_api and ui_helper is essential for the program
        self.logic_api = logic_api
        self.ui_helper = ui_helper

# Menu for the vehicle section part
    def show_options(self, error_msg=""):
        # Available options in vehicle section depends on what kind
        # of employee is the user.
        if self.ui_helper.header_string == "Office Employee":
            options_dict = {
                "1": self.VIEW_ALL,
                "2": self.FIND,
                "3": self.VEHICLE_RATES,
                "4": self.AVAILABLE
            }
        else:
            options_dict = {
                "1": self.VIEW_ALL,
                "2": self.FIND,
                "3": self.VEHICLE_RATES,
                "4": self.AVAILABLE,
                "5": self.REGISTER
            }

        options_list = self.ui_helper.dict_to_list(options_dict)

        while True:
            opt_str = "Select task"

            self.ui_helper.clear()

            self.ui_helper.print_header()
            self.ui_helper.print_options(options_list, opt_str)
            self.ui_helper.print_footer()
            print(error_msg)
            user_choice = self.ui_helper.get_user_menu_choice(options_list)
            if user_choice != None:

                if user_choice.lower() == self.ui_helper.BACK:
                    return

                elif user_choice.lower() == self.ui_helper.QUIT:
                    self.ui_helper.quit_prompt()

                else:

                    if options_dict[user_choice] == self.REGISTER:
                        self.register_vehicle()

                    elif options_dict[user_choice] == self.FIND:
                        self.find_vehicle()

                    elif options_dict[user_choice] == self.VIEW_ALL:
                        self.get_all_vehicles()

                    elif options_dict[user_choice] == self.VEHICLE_RATES:
                        self.vehicle_rate_menu()

                    elif options_dict[user_choice] == self.AVAILABLE:
                        self.available_vehicles()

            else:
                error_msg = "Please select an option from the menu"

# Start of list vehicles section
    def get_all_vehicles(self, error_msg=""):
        ''' Gets all vehicles from logic and calls list_vehicles menu, which gets input from user to quit or back'''
        vehicles = self.logic_api.all_vehicles_to_list()
        self.list_vehicles_menu(vehicles)

    def available_vehicles(self, error_msg=""):
        ''' Gets available vehicles from logic, if user is an airport staff, gets vehicles from their location, if office, they have to select a location '''
        if self.ui_helper.user_location.upper() != "KEF":
            location = self.logic_api.find_destination(self.ui_helper.user_location).airport

        else:
            dest = self.ui_helper.get_location("Select a location to view available vehicles:")
            if dest == None:
                return
            else:
                location = self.logic_api.find_destination(dest).airport

        vehicles = self.logic_api.availble_vehicles_by_location(location)
        self.list_vehicles_menu(vehicles)

    def list_vehicles_menu(self, vehicles, error_msg=""):
        ''' Shows a list of vehicles '''
        vehicle_dict = {vehicle.id: vehicle for vehicle in vehicles }               #Allows user to select a vehicle id from the list
        vehicle_list = self.ui_helper.dict_to_list(vehicle_dict)
        while True:
            self.ui_helper.clear()
            self.ui_helper.print_header()
            self.ui_helper.print_line("Vehicle overview, enter vehicle id to view")
            self.ui_helper.print_blank_line()
            self.print_vehicle_list(vehicles)
            self.ui_helper.print_blank_line()
            self.ui_helper.print_footer()
            print(error_msg)
            user_choice = self.ui_helper.get_user_menu_choice(vehicle_list)
            if user_choice != None:                                 #If user input a valid option, ie back or quit

                if user_choice.lower() == self.ui_helper.BACK:
                    return

                elif user_choice.lower() == self.ui_helper.QUIT:
                    self.ui_helper.quit_prompt()

                else:
                    self.vehicle_options(vehicle_dict[user_choice])

            else:
                error_msg = f"Please enter a valid vehicle ID, or {self.ui_helper.QUIT.upper()} to quit and {self.ui_helper.BACK.upper()} to go back"
# End of list section

# Start of help functions
    def vehicle_not_found(self):
        ''' Informs user that no vehicle was found, and to press enter to return'''
        self.ui_helper.clear()
        self.ui_helper.print_header()
        self.ui_helper.print_line("    No vehicle with this ID number found!")
        self.ui_helper.print_line("    Press enter to try again")
        self.ui_helper.print_blank_line()
        self.ui_helper.print_footer()
        print()
        _user_choice = input("Input: ")

    def print_vehicle_list(self, vehicle_list):
        ''' Prints vehicle attributes as columns, including a header '''
        manu_str = "<< MANUFACTURER >>"
        model_str = "<< MODEL >>"
        type_str = "<< TYPE >>"
        year_str = "<< YEAR >>"
        color_str = "<< COLOR >>"
        status_str = "<< STATUS >>"
        licence_str = "<< LICENCE >>"
        location_str = "<< LOCATION >>"
        id_str = "<< ID >>"
        self.ui_helper.n_columns([id_str, manu_str, model_str, type_str, year_str, color_str, status_str, licence_str, location_str])

        for vehicle in vehicle_list:
            manu = vehicle.manufacturer
            model = vehicle.model
            vtype = vehicle.type
            year = vehicle.year
            color = vehicle.color
            status = vehicle.status
            licence = vehicle.license_type
            location = vehicle.location
            id_nr = vehicle.id
            self.ui_helper.n_columns([id_nr, manu, model, vtype, year, color, status, licence, location])
# End of help functions

# Start of new/register vehicle section
    def register_vehicle(self, error_msg=""):
        new_vehicle = Vehicle("", "", "", "rentable", "", "", "", self.ui_helper.user_location, None)
        attribute_list = ["manufacturer", "model", "type", "year", "color", "license_type",]
        for attribute in attribute_list:
            while True:                                           #To make back and quit options functional
                attr_key = attribute.replace(" ", "_")
                placeholder_text = f"<< Enter {attribute} >>"
                setattr(new_vehicle, attr_key, placeholder_text)
                self.ui_helper.clear()
                self.ui_helper.print_header()
                self.view_vehicle_details(new_vehicle)
                self.ui_helper.print_blank_line()
                self.ui_helper.print_footer()
                print(error_msg)
                attr_value = input(f"Input: ")

                if attr_value.lower() == self.ui_helper.BACK.lower():
                    back_choice = self.unsaved_changes(new_vehicle)
                    if back_choice.lower() in self.ui_helper.YES:
                        return
                    else:
                        continue

                elif attr_value.lower() == self.ui_helper.QUIT:
                    self.ui_helper.quit_prompt()
                    continue

                else:
                    if attribute == "type":                                                 #to allow user to create a new vehicle type if they want
                        temp_type = self.logic_api.check_attribute(attr_value, "type")
                        if temp_type != None:
                            new_type = temp_type
                        else:
                            new_type = self.new_type_prompt(attr_value)

                        if new_type == None:
                            return

                        elif new_type.lower() == "no":
                            continue

                        else:
                            new_type =  new_type.capitalize()
                            setattr(new_vehicle, attr_key, new_type)
                            break

                    else:
                        attr_value = self.logic_api.check_attribute(attr_value, attr_key)
                        if attr_value != None:
                            setattr(new_vehicle, attr_key, attr_value)     #Sets attribute to input
                            break

                        else:                                      #Goes to next value in for loop
                            error_msg = f"Please enter a valid {attribute}"

        while True:
            self.ui_helper.clear()
            self.ui_helper.print_header()
            self.ui_helper.print_line("Confirm new vehicle? (y/n)")
            self.view_vehicle_details(new_vehicle)
            self.ui_helper.print_blank_line()
            self.ui_helper.print_footer()
            print()
            user_choice = input("Input: ")
            if user_choice in self.ui_helper.YES:
                self.logic_api.register_new_vehicle(new_vehicle)
                return

            elif user_choice.lower() == self.ui_helper.BACK:
                back_choice = self.unsaved_changes(new_vehicle)

                if back_choice in self.ui_helper.YES:
                    return
                else:
                    continue

            elif user_choice.lower() == self.ui_helper.QUIT:
                self.ui_helper.quit_prompt()

            else:
                error_msg = "Please select an option, or enter 9 to quit and 0 to go back"
# End of new/register vehicle section

# Start of find vehicle section
    def find_vehicle(self):
        ''' takes vehicle id number from user and finds the vehicle, or none if it doesn't exist '''
        while True:
            self.ui_helper.clear()
            self.ui_helper.print_header()
            self.ui_helper.print_line("    Enter vehicle ID number")
            self.ui_helper.print_blank_line()
            self.ui_helper.print_footer()
            print()
            vehicle_id = input("Input: ")
            if vehicle_id.lower() == self.ui_helper.BACK:
                return
            elif vehicle_id.lower() == self.ui_helper.QUIT:
                self.ui_helper.quit_prompt()

            else:   #Search for the vehicle in database
                the_vehicle = self.logic_api.find_vehicle(vehicle_id)
                if the_vehicle == None:
                    self.vehicle_not_found()
                self.vehicle_options(the_vehicle)
                return

    def vehicle_options(self, the_vehicle, error_msg=""):
        ''' Views a vehicle and asks user what to do '''
        if self.ui_helper.user_location != "KEF":                                                       #Office staff cant change vehicle status
            opt_change_status = "C"
        else:
            opt_change_status = ""    #bugfix

        while True:
            self.ui_helper.clear()
            self.ui_helper.print_header()
            self.ui_helper.print_line("    Vehicle details:")
            self.ui_helper.print_blank_line()
            self.view_vehicle_details(the_vehicle)
            if self.ui_helper.user_location != "KEF":                                                   #Office staff cant change vehicle status
                self.ui_helper.print_line(f"    ({opt_change_status})hange: Change Vehicle Status")
            else:
                self.ui_helper.print_blank_line()
            self.ui_helper.print_footer()
            print()
            user_choice = input("Input: ")

            if user_choice.lower() == opt_change_status.lower() and self.ui_helper.user_location != "KEF":  #Office staff cant change vehicle status
                self.change_vehicle_status(the_vehicle)

            elif user_choice.lower() == self.ui_helper.BACK:
                return

            elif user_choice.lower() == self.ui_helper.QUIT:
                self.ui_helper.quit_prompt()

            else:
                error_msg = f"Please select an option, or enter {self.ui_helper.QUIT.upper()} to quit and {self.ui_helper.BACK.upper()} to go back"

    def view_vehicle_details(self, a_vehicle):
        ''' Shows all attributes of a vehicle '''
        self.ui_helper.print_line(f"        MANUFACTURER:............{a_vehicle.manufacturer}")
        self.ui_helper.print_line(f"        MODEL:...................{a_vehicle.model}")
        self.ui_helper.print_line(f"        VEHICLE TYPE:............{a_vehicle.type}")
        self.ui_helper.print_line(f"        MODEL YEAR:..............{a_vehicle.year}")
        self.ui_helper.print_line(f"        COLOR:...................{a_vehicle.color}")
        self.ui_helper.print_line(f"        STATUS:..................{a_vehicle.status}")
        self.ui_helper.print_line(f"        LICENCE REQUIREMENTS:....{a_vehicle.license_type}")
        self.ui_helper.print_line(f"        LOCATION:................{a_vehicle.location}")
        if a_vehicle.id != None:
            self.ui_helper.print_line(f"        ID NUMBER:...............{a_vehicle.id}")
        else:
            self.ui_helper.print_blank_line()
        self.ui_helper.print_blank_line()

    def unsaved_changes(self, a_vehicle):
        ''' Asks user if they want to go back without saving their changes '''
        self.ui_helper.clear()
        self.ui_helper.print_header()
        self.view_vehicle_details(a_vehicle)
        self.ui_helper.unsaved_prompt()
        self.ui_helper.print_blank_line()
        self.ui_helper.print_hash_line()
        print()
        return input("Input: ")

    def change_vehicle_status(self, a_vehicle, error_msg=""):
        ''' Asks user what to change vehicle status to and changes it '''

        options_dict = {
            "R": "rentable",
            "W": "workshop"
        }
        options_list = self.ui_helper.dict_to_list(options_dict)
        while True:
            self.ui_helper.clear()
            self.ui_helper.print_header()
            opt_str = "    What do you want to change the vehicle status to?"
            self.ui_helper.print_options(options_list, opt_str)
            self.ui_helper.print_footer()
            print(error_msg)
            user_choice = self.ui_helper.get_user_menu_choice(options_list)
            if user_choice == None:
                error_msg = "Please select an option from the menu"
            else:
                if user_choice.lower() == self.ui_helper.BACK:
                    return

                elif user_choice.lower() == self.ui_helper.QUIT:
                    self.ui_helper.quit_prompt()

                elif user_choice in options_dict:
                    setattr(a_vehicle, "status", options_dict[user_choice.upper()])
                    confirm_choice = self.confirm_status(a_vehicle)

                    if confirm_choice in self.ui_helper.YES:                                        #Saves changes if input is y or yes, not case sensetive
                        self.logic_api.change_vehicle_condition(a_vehicle.id, a_vehicle.status)
                        return

                    else:
                        return
# End of find vehicle section

# Start of new vehicle type rate section
    def confirm_status(self, a_vehicle):
        ''' Asks user to confirm new status, returning the user input '''
        self.ui_helper.clear()
        self.ui_helper.print_header()
        self.view_vehicle_details(a_vehicle)
        self.ui_helper.print_line("    Do you want to confirm these changes? (y/n)")
        self.ui_helper.print_blank_line()
        self.ui_helper.print_hash_line()
        print()
        return input("Input: ")

    def vehicle_rate_menu(self, error_msg=""):
        ''' The vehicle type rate menu, shows all available vehicle types'''
        vehicle_type_list = self.logic_api.get_vehicle_types()
        available_options = []
        new_type = "n"
        while True:
            self.ui_helper.clear()
            self.ui_helper.print_header()
            self.ui_helper.print_line("Select vehicle type to change rate")
            self.ui_helper.print_blank_line()
            for ind, vehicle_type in enumerate(vehicle_type_list):
                available_options.append((str(ind + 1), vehicle_type))
                v_type = vehicle_type.name
                v_rate = vehicle_type.rate
                self.ui_helper.print_line("{: >3}.  {:.<32}{}".format(str(ind + 1), v_type, v_rate))
            available_options.append(("n", "new_type"))
            self.ui_helper.print_blank_line()
            self.ui_helper.print_line(f"    ({new_type.upper()})ew type: Create new vehicle type")
            self.ui_helper.print_footer()
            print(error_msg)
            user_choice = self.ui_helper.get_user_menu_choice(available_options)
            options_dict = dict(available_options)
            if user_choice != None:

                if user_choice.lower() == self.ui_helper.BACK:
                    return

                elif user_choice.lower() == self.ui_helper.QUIT:
                    self.ui_helper.quit_prompt()

                elif user_choice.lower() == new_type:
                    self.new_vehicle_type()
                    vehicle_type_list = self.logic_api.get_vehicle_types()   # To refresh list after creating a new one.

                else:
                    the_type = options_dict[user_choice].name
                    the_rate = self.new_vehicle_type_rate()
                    if the_rate == None:
                        continue
                    else:
                        self.logic_api.change_types_rate(the_type, the_rate)
                        vehicle_type_list = self.logic_api.get_vehicle_types()

            else:
                error_msg = "Please select an option from the list"
# End of new vehicle type rate section

# Start of new vehicle type section
    def new_vehicle_type(self,error_msg=""):
        ''' Creates a new vehicle type '''
        error_msg = "Please choose an option from the menu."
        while True:
            type_name = self.new_vehicle_type_name()
            if type_name.lower() == self.ui_helper.BACK:
                return
            elif type_name.lower() == self.ui_helper.QUIT:
                self.ui_helper.quit_prompt()
            else:
                type_rate = self.new_vehicle_type_rate()
                if type_rate == None:
                    return
                new_vehicle_type = VehicleType(type_name, type_rate)
                user_choice = self.v_type_info_check(new_vehicle_type)
                if user_choice != None:
                    if user_choice.lower() == self.ui_helper.NO:
                        return
                    elif user_choice.lower() == self.ui_helper.BACK:
                        return
                    elif user_choice.lower() == self.ui_helper.QUIT:
                        self.ui_helper.quit_prompt()
                    elif user_choice.lower() in self.ui_helper.YES:
                        self.logic_api.create_new_type(new_vehicle_type)
                        return
                    else:
                        return
                else:
                    error_msg = "Please choose an option from the menu."
                    return

    def new_vehicle_type_name(self):
        self.ui_helper.clear()
        self.ui_helper.print_header()
        self.ui_helper.print_blank_line()
        self.ui_helper.print_line("    Enter a new vehicle type name:")
        self.ui_helper.print_blank_line()
        self.ui_helper.print_hash_line()
        user_choice = input("Input: ")
        return user_choice

    def new_vehicle_type_rate(self,error_msg=""):
        while True:
            self.ui_helper.clear()
            self.ui_helper.print_header()
            self.ui_helper.print_blank_line()
            self.ui_helper.print_line("    Enter a new rate for the vehicle type:")
            self.ui_helper.print_blank_line()
            self.ui_helper.print_footer()
            print(error_msg)
            user_choice = input("Input: ")
            if user_choice.lower() == self.ui_helper.BACK:
                return
            elif user_choice.lower() == self.ui_helper.QUIT:
                self.ui_helper.quit_prompt()
            else:
                user_choice = self.logic_api.check_if_only_number(user_choice)
                if user_choice != None:
                    return user_choice
                else:
                    error_msg = "Please input a fee containing only numbers."
                    continue

    def v_type_info_check(self, vehicle_type):
        self.ui_helper.clear()
        self.ui_helper.print_header()
        self.ui_helper.print_blank_line()
        self.ui_helper.print_line("    Is this information correct? (y/n)")
        self.ui_helper.print_blank_line()
        v_type = vehicle_type.name
        v_rate = vehicle_type.rate
        self.ui_helper.print_line("    {:.<36}{}".format(v_type, v_rate))
        self.ui_helper.print_blank_line()
        self.ui_helper.print_hash_line()
        print()
        user_choice = input("Input: ")
        return user_choice

    def new_type_prompt(self, type_name, error_msg=""):
        ''' Informs user that type doesnt exist, asks if they want to create one, returning the type name if they do and none if they don't '''
        while True:
            self.ui_helper.clear()
            self.ui_helper.print_header()
            self.ui_helper.print_line(f"Vehicle type: {type_name} doesn't exist, do you want to create it (y/n)")
            self.ui_helper.print_blank_line()
            self.ui_helper.print_footer()
            print(error_msg)
            user_choice = input("Input: ")
            if user_choice.lower() in self.ui_helper.YES:

                while True:
                    type_rate = self.new_vehicle_type_rate()
                    if type_rate == None:
                        return
                    new_vehicle_type = VehicleType(type_name, type_rate)
                    user_choice = self.v_type_info_check(new_vehicle_type)
                    if user_choice != None:
                        if user_choice.lower() == self.ui_helper.BACK:
                            return

                        elif user_choice.lower() == self.ui_helper.QUIT:
                            self.ui_helper.quit_prompt()

                        elif user_choice.lower() in self.ui_helper.YES:
                            self.logic_api.create_new_type(new_vehicle_type)
                            return new_vehicle_type.name

                        else:
                            return
                    else:
                        error_msg = "Please choose an option from the menu."

            elif user_choice.lower() == self.ui_helper.QUIT:
                self.ui_helper.quit_prompt()
                continue

            elif user_choice.lower() in self.ui_helper.NO:  #If user doesnt want to create
                return "no"

            else:
                return None
# End of new vehicle type section


from math import sqrt

def is_prime(x):
    if x < 2:
        return False
    if x % 2 == 0:
        return x == 2
    root = int(sqrt(x))
    for i in range(3, root + 1, 2):
        if x % i == 0:
            return False
    return True

a = int(input())
b = int(input())
for i in range(a, b + 1):
    if is_prime(i):
        print(i)


keys = ['one', 'two', 'three', 'four']
vals = [1, 2, 3, 4, 5, 6, 7]
vals2 = [1, 2]

def createDict(keys, vals):

    result_dict = {}
    i = 0
    for key in keys:
        if len(vals) <= i:
            val = None
        else:
            val = vals[i]
        result_dict[str(key)] = val
        i += 1
        result_dict.clear
    return result_dict

dict1 = createDict(keys, vals)
dict2 = createDict(keys, vals2)
print(dict1)
print(dict2)


# coding=utf-8

# integrate all steps for backtest

from sqlalchemy import create_engine
import queue
import pandas as pd

from wts.datahandler import DailyDataHandler
from wts.event import NextLoopEvent
from wts.portfoliohandler import SimPortfolioHandler
from wts.executionhandler import SimExecutionHandler
from wts.performance import backtest_metric

# Set up the backtest parameter

# start and end of backtest period
START_DATE = "20100101"
END_DATE = "20170101"

# set decay+lookback<DIDX_START to ensure all alpha's orders
# to have same rebalance date
DIDX_START = 100

# rebalance frequency, capital, leverage ratio, allocation method
FREQ = 20
CAP = 10000000.0
LEVERAGE = 0.8
ALLO = 'AD'

# transaction spread and fees
SPREAD = 0.001
FEE = 0.0005

# Population postgresql
path_stock_inter = "postgresql://chenxutao:@localhost/chinesestock_pg_inter"
engine_stock = create_engine(path_stock_inter)

events_queue = queue.Queue()
datahandler = DailyDataHandler(engine_stock, START_DATE, END_DATE)

def run(strategy):
    portfoliohandler = SimPortfolioHandler(events_queue, freq=FREQ,
                                           initial_cap=CAP,
                                           leverage=LEVERAGE, allo=ALLO)
    executionHandler = SimExecutionHandler(events_queue, datahandler,
                                           spread=SPREAD, fee=FEE)

    nextloop_event = NextLoopEvent(didx=DIDX_START)
    events_queue.put(nextloop_event)

    while not events_queue.empty():
        event = events_queue.get()
        if event.type == "NextLoopEvent":
            strategy.update_signal(event)

        elif event.type == "SignalEvent":
            portfoliohandler.update_order(event)

        elif event.type == "OrderEvent":
            executionHandler.execute_order(event)

        elif event.type == "FillEvent" or event.type == "NotFillEvent":
            portfoliohandler.update_fill(event)

    all_holding, all_position, all_order = portfoliohandler.to_dataframe()
    date = pd.DataFrame(strategy.date, columns=['date'])
    all_holding = all_holding.merge(date, how='left', left_index=True,
                                    right_index=True)
    all_position = all_position.merge(date, how='left', left_index=True,
                                      right_index=True)
    all_order = all_order.merge(date, how='left', left_index=True,
                                right_index=True)

    all_holding.set_index(keys='date', drop=True, inplace=True)
    all_holding.index = pd.to_datetime(all_holding.index)

    all_position.set_index(keys='date', drop=True, inplace=True)
    all_position.index = pd.to_datetime(all_position.index)

    all_order.set_index(keys='date', drop=True, inplace=True)
    all_order.index = pd.to_datetime(all_order.index)

    all_holding.to_csv('../backtest_output/all_holding.csv')
    all_position.to_csv('../backtest_output/all_position.csv')
    all_order.to_csv('../backtest_output/all_order.csv')

    # Show the performance metrics
    backtest_metric()

    print('Backtest Finish!')


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def numComponents(
            self, head: Optional[ListNode],
            nums: List[int]) -> int:  # 28.38% 8.52%
        out = []
        set_nums = set(nums)
        seen = set()
        cur = set()
        while head.next:
            if head.val in set_nums and head.next.val in set_nums:
                cur.update([head.val, head.next.val])
                seen.update([head.val, head.next.val])
            else:
                if cur:
                    out.append(cur)
                cur = set()
            head = head.next
        if cur:
            out.append(cur)
        return len(out) + len(set_nums-seen)

    def numComponents_v2(
            self, head: Optional[ListNode],
            nums: List[int]) -> int:  # 70.96% 72.49%
        out = []
        set_nums = set(nums)
        cur = set()
        while head.next:
            if head.val in set_nums and head.next.val in set_nums:
                cur.update([head.val, head.next.val])
                set_nums.discard(head.val)
            else:
                if cur:
                    if head.val in set_nums:
                        cur.add(head.val)
                        set_nums.discard(head.val)
                    out.append(cur)
                cur = set()
            head = head.next
        if cur:
            out.append(cur)
            set_nums.discard(head.val)
        return len(out) + len(set_nums)

    def numComponents_best_speed(self, head, nums) -> int:
        nums = set(nums)
        cnt = 0
        while head:
            if head.val not in nums:
                head = head.next
            else:
                while head and head.val in nums:
                    head = head.next
                cnt += 1
        return cnt

800 - 899/817 - Linked List Components/817 - Linked List Components.py


'''
这里将 文件路径对应的图片读取出来
'''
import csv

import torch

import pic_tensor1
import tansor_case

#csv_reader = csv.reader(open("E:\\BaiduNetdiskDownload\\baokemeng\\pokemon\\images.csv"))
csv_reader = csv.reader(open("E:\\BaiduNetdiskDownload\\baokemeng\\pokemon\\images1.csv"))

'''
csv.reader：以列表的形式返回读取的数据。
csv.writer：以列表的形式写入数据。
csv.DictReader：以字典的形式返回读取的数据。
csv.DictWriter：以字典的形式写入数据。
'''
imgData = torch.ones(1, 3, 600, 600)
imgLab = tansor_case.newTansor1(99)
imgLab=imgLab.unsqueeze(0)
i = 1
for imgPath, data2 in csv_reader:
    imgPath = imgPath.replace('\\', '/')
    imgPath = "E:/BaiduNetdiskDownload/baokemeng/" + imgPath
    k1 = pic_tensor1.imgToTensor(imgPath)
    k1 = k1.unsqueeze(0)

    imgData = torch.cat([imgData, k1], 0)
    # 这里我选择及时释放k1 但我还没有考虑后果
    del (k1)

    k2 = tansor_case.newTansor1(int(data2))
    k2 = k2.unsqueeze(0)
    imgLab=torch.cat([imgLab,k2],0)
    del(k2)

    print(i, ":", imgPath, data2)
    i = i + 1
# dir 方法可以看类内部方法和变量
# print(dir(csv_reader))
# print(len(csv_reader))

# 1000+的数据直接干碎我的内存
# 1167行数据
# print(csv_reader.line_num)

# E:/BaiduNetdiskDownload/baokemeng/pokemon/mewtwo/00000239.jpg 2
print(imgData.shape)
imgData = tansor_case.del_tansor_ele(imgData, 0)
imgLab=tansor_case.del_tansor_ele(imgLab,0)
#print(imgLab)
#print(imgData.shape,imgLab.shape)


import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
#with outlier removal
cd={}
cdl={}
entries=os.listdir('data/Milano_WeatherPhenomena')
for i,entry in enumerate(entries):
    entries[i]=entries[i][9:-4]
    cd[i]=pd.read_csv('data/Milano_WeatherPhenomena/mi_meteo_'+entries[i]+'.csv', usecols=[1,2],names=['time','val'], converters= {'time': pd.to_datetime})
    q1=cd[i]['val'].quantile(0.25)
    q3=cd[i]['val'].quantile(0.75)
    iqr=q3-q1
    cd[i]=cd[i][~((cd[i]['val']<(q1-1.5*iqr)) | (cd[i]['val']>(q3+1.5*iqr)))]
for i,entry in enumerate(cd):
    cd[i].sort_values(by=['time'])
    cd[i]['val'].apply(lambda x: (x - cd[i]['val'].mean()) / (cd[i]['val'].max() - cd[i]['val'].min()))
cor=np.zeros([len(cd),len(cd)],float)
for i in range(0,len(cd)):
    for j in range(i,len(cd)):
        joined_mat= cd[i].set_index('time').join(cd[j].set_index('time'), on='time', how='inner', lsuffix='_left',
                                            rsuffix='_right', sort=True)
        cor[i][j]=joined_mat.corr().loc['val_left']['val_right']
        cor[j][i]=cor[i][j]
f = plt.figure(figsize=(15, 15))
plt.subplot(1,2,1)
plt.imshow(abs(cor))
plt.xticks(range(len(entries)), entries, fontsize=12, rotation=90)
plt.yticks(range(len(entries)), entries, fontsize=12)
plt.ylabel('Sensor ID')
plt.xlabel('Sensor ID')
plt.title('Without outliers', y=1.08)
cb = plt.colorbar()
cb.ax.tick_params(labelsize=14)
#without outlier removal
cd2={}
for i,entry in enumerate(entries):
    cd2[i]=pd.read_csv('data/Milano_WeatherPhenomena/mi_meteo_'+entries[i]+'.csv', usecols=[1,2],names=['time','val'], converters= {'time': pd.to_datetime})
for i,entry in enumerate(cd2):
    cd2[i].sort_values(by=['time'])
    cd2[i]['val'].apply(lambda x: (x - cd2[i]['val'].mean()) / (cd2[i]['val'].max() - cd2[i]['val'].min()))
cor2=np.zeros([len(cd2),len(cd2)],float)
for i in range(0,len(cd2)):
    for j in range(i,len(cd2)):
        joined_mat= cd2[i].set_index('time').join(cd2[j].set_index('time'), on='time', how='inner', lsuffix='_left',
                                            rsuffix='_right', sort=True)
        cor2[i][j]=joined_mat.corr().loc['val_left']['val_right']
        cor2[j][i]=cor2[i][j]
plt.subplot(1,2,2)
plt.imshow(abs(cor2))
plt.xticks(range(len(entries)), entries, fontsize=12, rotation=90)
plt.yticks(range(len(entries)), entries, fontsize=12)
plt.ylabel('Sensor ID')
plt.xlabel('Sensor ID')
plt.title('With outliers', y=1.08)
cb = plt.colorbar()
cb.ax.tick_params(labelsize=14)
plt.show()


import numpy as np
import pandas as pd
from flask import Flask, request, render_template
import joblib

app = Flask(__name__)
rfc = joblib.load("Customer_churn.pkl")
df = pd.DataFrame()

@app.route('/')
def home():
    return render_template('avi.html')

@app.route('/predict' ,methods=['POST'])
def predict():
    global df

    # Get the values from the form and convert them to integers
    independent_var = [int(x) for x in request.form.values()]
    features_value = np.array(independent_var)

    # Perform the prediction using the model (rfc in this case)
    output = rfc.predict([features_value]).round(2)

    df = pd.concat([df, pd.DataFrame({'credit_score':independent_var[0], 'age':independent_var[1],'tenure':independent_var[2] , 'balance':independent_var[3], 'products_number':independent_var[4],'credit_card':independent_var[5],'estimated_salary':independent_var[6] ,'Predicted Sales':[output]})], ignore_index=True)

    df.to_csv("resultant.csv")

    return render_template('avi.html', prediction_text='{} CHURN'.format(output, int(features_value[0])))

if __name__== "__main__" :
    app.run()


# This function convert the string to numbers and plus or minus
# make the calculation
# convert the result to the word format of the numbers

def CalculWords(s):
    res = 0
    start = 0
    op = []
    i= 0
    for j in range(1,len(s)+1):
        if s[i:j] == 'zero':
            start = start*10
            i = j
        if s[i:j] == 'one':
            start = start*10 + 1
            i = j
            #print(start)
        if s[i:j] == 'two':
            start = start*10 + 2
            i = j
            #print(start)
        if s[i:j] == 'three':
            start = start*10 + 3
            i = j
        if s[i:j] == 'four':
            start = start*10 + 4
            i = j
        if s[i:j] == 'five':
            start = start*10 + 5
            i = j
        if s[i:j] == 'six':
            start = start*10 + 6
            i = j
        if s[i:j] == 'seven':
            start = start*10 + 7
            i = j
        if s[i:j] == 'eight':
            start = start*10 + 8
            i = j
        if s[i:j] == 'nine':
            start = start*10 + 9
            i = j
        if s[i:j] == 'plus':
            if(len(op) == 0):
                res = start
                start = 0
                op = ['+']
            elif(op[0]=='+'):
                res+=start
                start = 0
                op = ['+']
            else:
                res-=start
                start = 0
                op = ['+']
            i = j
        if s[i:j] == 'minus':
            if(len(op) == 0):
                res = start
                start = 0
                op = ['-']
            elif(op[0]=='+'):
                res+=start
                start = 0
                op = ['-']
            else:
                res-=start
                start = 0
                op = ['-']
            i = j
    #print(s[i:j])
    if s[i:j] == 'zero':
        start = start*10
    if s[i:j] == 'one':
        start = start*10 + 1
    if s[i:j] == 'two':
        start = start*10 + 2
        #print(start)
    if s[i:j] == 'three':
        start = start*10 + 3
    if s[i:j] == 'four':
        start = start*10 + 4
    if s[i:j] == 'five':
        start = start*10 + 5
    if s[i:j] == 'six':
        start = start*10 + 6
    if s[i:j] == 'seven':
        start = start*10 + 7
    if s[i:j] == 'eight':
        start = start*10 + 8
    if s[i:j] == 'nine':
        start = start*10 + 9
    if(len(op) == 0):
        res = start
        start = 0
    else:
        if(op[0]=='+'):
            res+=start
            start = 0
        if(op[0]=='-'):
            res-=start
            start = 0
    strres = ''
    if(res<0):
        strres = strres+'negative'
        res = res * (-1)
    listres = []
    listres[:0] = str(res)
    for k in listres:
        if k == '0':
            strres = strres+'zero'
        if k == '1':
            strres = strres+'one'
        if k == '2':
            strres = strres+'two'
        if k == '3':
            strres = strres+'three'
        if k == '4':
            strres = strres+'four'
        if k == '5':
            strres = strres+'five'
        if k == '6':
            strres = strres+'six'
        if k == '7':
            strres = strres+'seven'
        if k == '8':
            strres = strres+'eight'
        if k == '9':
            strres = strres+'nine'
    return strres

a = 'onetwoplusfiveminusfourplustwotwozerominusfourfivesix'
print(CalculWords(a))


from functions import forcePlayerRespondPvP,forcePlayerAnswerChoice,checkResult
shouldBePvP = forcePlayerRespondPvP()
if shouldBePvP.casefold() == ' Y'.casefold() or shouldBePvP.casefold() == 'Y'.casefold():
    #PvP = True
    choices = ["rock", "paper", "scissors"]
    player1Response = forcePlayerAnswerChoice(choices)
    player2Response = forcePlayerAnswerChoice(choices)
    finalResult = checkResult(player1Response,player2Response, None)

elif shouldBePvP.casefold() == 'N'.casefold() or shouldBePvP.casefold() == 'N'.casefold():
    #PvP = False
    import random
    choices = ["rock", "paper", "scissors"]
    computerChoice = random.choice(choices)
    player1Response = forcePlayerAnswerChoice(choices)
    finalResult = checkResult(player1Response, None, computerChoice)
else:
    print("exit code 0: Can not recognize input. Please restart program and try again.")


import numpy as np
import IPython
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from mpl_toolkits.axes_grid1 import make_axes_locatable
from  matplotlib.colors import LinearSegmentedColormap
import seaborn as sns
import pandas as pd

def plot_grid(Nx, Ny, state_grid_map, kk, constraints=None, trajectories=None,  optimal_policy=None):
    """
    Plots the skeleton of the grid world
    :param ax:
    :return:
    """

    UP = 0
    DOWN = 1
    LEFT = 2
    RIGHT = 3
    act_dict = {}
    dx_dy = 0.1
    act_dict[0] = (0, -dx_dy)
    act_dict[1] = (0, dx_dy)
    act_dict[2] = (-dx_dy, 0)
    act_dict[3] = (dx_dy, 0)

    fig, ax = plt.subplots()

    for i in range(Ny + 1):
        ax.plot(np.arange(Nx + 1) - 0.5, np.ones(Nx + 1) * i - 0.5, color='k')
    for i in range(Nx + 1):
        ax.plot(np.ones(Ny + 1) * i - 0.5, np.arange(Ny + 1) - 0.5, color='k')

    y_grid = np.arange(Ny)
    x_grid = np.arange(Nx)
    if optimal_policy != None:
        cnt = 0
        for y in y_grid:
            for x in x_grid:
                if y==0 and x==0:
                    cnt += 1
                    continue
                else:
                    act = optimal_policy[cnt]
                    tup = act_dict[act]
                    ax.arrow(x - tup[0], y - tup[1], tup[0], tup[1], head_width=0.15, head_length=0.2, fc='k', ec='k')
                    cnt += 1

    # ax.plot(0,0,'x',color='green', markersize=15, markeredgewidth=5)

    data = np.ones((Ny, Nx))

        # data[cnstr[0], cnstr[1]] = 10

    # data = np.zeros((Ny, Nx))
    if trajectories != None:
        for i in trajectories:
            cnstr = state_grid_map[i[0]]
            data[Ny - 1 - cnstr[1], cnstr[0]] += 1
            # data[cnstr[0], cnstr[1]] = 10
    for ind in np.nonzero(constraints)[0]:
        cnstr = state_grid_map[ind]
        data[Ny - 1 - cnstr[1], cnstr[0]] = 0

    ax.axes.xaxis.set_ticks([])
    ax.axes.yaxis.set_ticks([])
    # cmap = colors.ListedColormap(['white', 'red'])
    # bounds = [0, 10, 20]
    # norm = colors.BoundaryNorm(bounds, cmap.N)

    # im1 = plt.imshow(data2, cmap=plt.cm.viridis)
    cmap=plt.cm.viridis#mpl.cm.get_cmap("OrRd").copy()
    cmap.set_under('r')

    # cmap = colors.ListedColormap(['white', 'red'])
    bounds = [0, 10, 20]
    norm = colors.BoundaryNorm(bounds, cmap.N)
    im = plt.imshow(data, vmin=0.1, cmap=cmap)

    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax)
    # ax.set_xlabel('x')
    # ax.set_ylabel('y')
    ax.grid()
    # plt.savefig('plot_act/MAP_results_' + str(kk) + '.png')

    plt.show()

    # return ax

def plot_grid_mean_constr(Nx, Ny, state_grid_map, kk, mean_constraints=None, trajectories=None,  optimal_policy=None):
    """
    Plots the skeleton of the grid world
    :param ax:
    :return:
    """

    UP = 0
    DOWN = 1
    LEFT = 2
    RIGHT = 3
    act_dict = {}
    dx_dy = 0.1
    act_dict[0] = (0, -dx_dy)
    act_dict[1] = (0, dx_dy)
    act_dict[2] = (-dx_dy, 0)
    act_dict[3] = (dx_dy, 0)

    fig, ax = plt.subplots()

    for i in range(Ny + 1):
        ax.plot(np.arange(Nx + 1) - 0.5, np.ones(Nx + 1) * i - 0.5, color='k')
    for i in range(Nx + 1):
        ax.plot(np.ones(Ny + 1) * i - 0.5, np.arange(Ny + 1) - 0.5, color='k')

    data = np.zeros((Ny, Nx))

        # data[cnstr[0], cnstr[1]] = 10

    for ind in np.nonzero(mean_constraints)[0]:
        # IPython.embed()
        cnstr = state_grid_map[ind]
        data[Ny - 1 - cnstr[1], cnstr[0]] = mean_constraints[ind]

    ax.axes.xaxis.set_ticks([])
    ax.axes.yaxis.set_ticks([])

    cmap = LinearSegmentedColormap.from_list('rg',["w", "r"], N=256)
    # cmap = plt.cm.get_cmap("Reds")
    im = plt.imshow(data, vmin=0.0, vmax=1, cmap=cmap)

    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)

    plt.colorbar(im, cax=cax)
    ax.grid(False)
    plt.savefig('plot_act/mean_results_Scobee_comp'+ str(kk) + '.png')
    # plt.show()
    # plt.pause(3)
    # plt.close()

def plot_performance(list_tupls):
    sns.set(style="whitegrid")
    TPR = []
    FPR = []
    FNR = []

    for tup in list_tupls:
        TPR.append(tup[1])
        FPR.append(tup[2])
        FNR.append(tup[3])
    # IPython.embed()

    plt.clf()

    index = pd.RangeIndex(start=0, stop=len(list(range(tup[0])))+1, step=None, name="Number of Iterations")
    data = np.concatenate((np.expand_dims(np.array(TPR),1), np.expand_dims(np.array(FPR),1),np.expand_dims(np.array(FNR),1)), axis=1)
    palette = {"TPR":"tab:green",
           "FPR":"tab:orange",
           "FNR":"tab:blue"}
    markers = {"TPR": "o", "FPR": "o", "FNR": "o"}
    wide_df = pd.DataFrame(data, index, ["TPR", "FPR", "FNR"])
    sns.scatterplot(data=wide_df, palette=palette, markers=markers,alpha=0.6,edgecolor=None)

    # fig = plt.plot()
    # plt.scatter(list(range(tup[0]+1)),TPR, color='green', label='TPR')
    # plt.scatter(list(range(tup[0]+1)),FPR, color='red', label='FPR')
    # IPython.embed()
    plt.yticks(np.arange(0, 1.01, 0.25))
    plt.xticks(np.arange(0, len(list(range(tup[0])))+2, int((len(list(range(tup[0])))+1)/4)))
    plt.xlabel('Number of Iterations')
    plt.ylabel('Rates')
    plt.legend()
    plt.savefig('plots/perf.png')
    plt.savefig('plots/perf.eps', format='eps')


f = open('input.txt', 'r')
n, k = map(int, f.readline().split())
a = list(map(float, f.read().split()))
mean = sum(a) / n

s = 0

for i in a:
    s += (i - mean)**k

open('output.txt', 'w').write(str(((1/n) * s)))

first_term/E_Центральный_момент.py

E_Центральный_момент.py


from api_calls import closing_bars, hourly_close_bars

symbol = 'TSLA'

def stocks_last_fiveday_avg_close():
    closing_prices_stocks = closing_bars()
    sum_closing_prices= closing_prices_stocks['close'].iloc[-5:].sum()
    daily_average = sum_closing_prices/5
    return float(round(daily_average,2))

def stocks_last_hours_close():
    current_price_stocks = hourly_close_bars()
    return float(current_price_stocks)

def stocks_trade_criteria():
    last_five = float(stocks_last_fiveday_avg_close())
    last_hour = float(stocks_last_hours_close())
    difference = last_hour - last_five
    if last_five < last_hour and difference <= 2.00:
        return True
    else:
        return False


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
import datetime

class Migration(migrations.Migration):

    dependencies = [
        ('cellphones', '0003_auto_20160717_2334'),
    ]

    operations = [
        migrations.AlterField(
            model_name='device',
            name='category',
            field=models.SmallIntegerField(choices=[(1, 'SMARTPHONE'), (2, 'TABLET'), (3, 'LAPTOP')], default=1),
        ),
        migrations.AlterField(
            model_name='producer',
            name='pub_date',
            field=models.DateField(default=datetime.date(2010, 1, 1), verbose_name='published on', null=True, blank=True),
        ),
    ]


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

"""
------------------------------------------
@author: 兴微
@software: PyCharm
@file: Model.py
@time: 2021/4/22 13:59
------------------------------------------
@description：

------------------------------------------
"""

import torch.nn as nn
import torch
from config import DEVICE

class RNN(nn.Module):

    def __init__(self,
                 input_size,
                 hidden_size,
                 output_size):
        super(RNN, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size

        self.i2o = nn.Linear(input_size + hidden_size, output_size)
        self.i2h = nn.Linear(input_size + hidden_size, hidden_size)

        self.softmax = nn.Softmax(dim=1)

    # def forward(self, input, hidden):
    #     # 每次只有一个单词，故而batch_size=1
    #     # input: tensor (batch_size=1, input_size)
    #     # hidden: tensor (batch_size=1, hidden_size)
    #     combined = torch.cat((input, hidden), dim=1) # tensor (batch_size=1, input_size + hidden_size)
    #     output = self.i2o(combined) # (batch_size=1, output_size)
    #     hidden = self.i2h(combined) # (batch_size=1, hidden_size)
    #     return output, hidden

    def forward(self, input, hidden):
        # 每次只有一个单词，故而batch_size=1
        # input: tensor (time_step, batch_size=1, input_size)
        # hidden: tensor (batch_size=1, hidden_size)
        for step in range(input.size()[0]):
            combined = torch.cat((input[step].float(), hidden), dim=1) # tensor (batch_size=1, input_size + hidden_size)
            output = self.i2o(combined) # (batch_size=1, output_size)
            hidden = self.i2h(combined) # (batch_size=1, hidden_size)
        return output, hidden

    def init_hidden(self):
        '''
        初始化隐藏层参数
        :return:
        '''
        return torch.zeros((1, self.hidden_size), device=DEVICE) # (batch_size=1, hidden_size)


# -*- coding: utf-8 -*-
from typing import TYPE_CHECKING, Dict, List
from .BaseService import BaseService, BaseServiceStruct

if TYPE_CHECKING:
    from CHRLINE import CHRLINE

class SquareService(BaseService):
    SquareService_REQ_TYPE = 4
    SquareService_RES_TYPE = 4
    SquareService_API_PATH = "/SQS1"

    SQUARE_EXCEPTION = {"code": 1, "message": 3, "metadata": 2}

    def __init__(self):
        self.SquareService_API_PATH = self.LINE_SQUARE_ENDPOINT

    def inviteIntoSquareChat(self, inviteeMids: list, squareChatMid: str):
        """Invite into square chat."""
        METHOD_NAME = "inviteIntoSquareChat"
        params = [[15, 1, [11, inviteeMids]], [11, 2, squareChatMid]]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def inviteToSquare(self, squareMid: str, invitees: list, squareChatMid: str):
        """Invite to square."""
        METHOD_NAME = "inviteToSquare"
        params = [[11, 2, squareMid], [15, 3, [11, invitees]], [11, 4, squareChatMid]]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def getJoinedSquares(self, continuationToken: str = None, limit: int = 50):
        """Get joined squares."""
        METHOD_NAME = "getJoinedSquares"
        params = [[11, 2, continuationToken], [8, 3, limit]]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def markAsRead(self, squareChatMid: str, messageId: str):
        """Mark as read for square chat."""
        METHOD_NAME = "markAsRead"
        params = [[11, 2, squareChatMid], [11, 4, messageId]]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def reactToMessage(self, squareChatMid: str, messageId: str, reactionType: int = 2):
        """
        React to message for square chat message.

        - reactionType
            ALL     = 0,
            UNDO    = 1,
            NICE    = 2,
            LOVE    = 3,
            FUN     = 4,
            AMAZING = 5,
            SAD     = 6,
            OMG     = 7,
        """
        METHOD_NAME = "reactToMessage"
        params = [
            [8, 1, 0],  # reqSeq
            [11, 2, squareChatMid],
            [11, 3, messageId],
            [8, 4, reactionType],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def findSquareByInvitationTicket(self, invitationTicket: str):
        """Find square by invitation ticket."""
        METHOD_NAME = "findSquareByInvitationTicket"
        params = [[11, 2, invitationTicket]]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def fetchMyEvents(
        self,
        subscriptionId: int = 0,
        syncToken: str = None,
        continuationToken: str = None,
        limit: int = 100,
    ):
        """Fetch square events."""
        METHOD_NAME = "fetchMyEvents"
        params = [
            [10, 1, subscriptionId],
            [11, 2, syncToken],
            [8, 3, limit],
            [11, 4, continuationToken],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def fetchSquareChatEvents(
        self,
        squareChatMid: str,
        syncToken: str = None,
        continuationToken: str = None,
        subscriptionId: int = 0,
        limit: int = 100,
    ):
        """Fetch square chat events."""
        METHOD_NAME = "fetchSquareChatEvents"
        fetchType = 1  # DEFAULT(1),PREFETCH_BY_SERVER(2),
        # PREFETCH_BY_CLIENT(3);
        params = [
            [10, 1, subscriptionId],
            [11, 2, squareChatMid],
            [11, 3, syncToken],
            [8, 4, limit],
            [8, 5, 1],  # direction
            [8, 6, 1],  # inclusive
            [11, 7, continuationToken],
            [8, 8, fetchType],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def sendSquareMessage(
        self,
        squareChatMid: str,
        text: str,
        contentType: int = 0,
        contentMetadata: dict = {},
        relatedMessageId: str = None,
    ):
        """Send message for square chat (OLD)."""
        METHOD_NAME = "sendMessage"
        message = [
            # [11, 1, _from],
            [11, 2, squareChatMid],
            [11, 10, text],
            [8, 15, contentType],  # contentType
            [13, 18, [11, 11, contentMetadata]],
        ]
        if relatedMessageId is not None:
            message.append([11, 21, relatedMessageId])
            message.append(
                [
                    8,
                    22,
                    3,
                ]
            )
            message.append([8, 24, 2])
        params = [
            [8, 1, self.getCurrReqId()],
            [11, 2, squareChatMid],
            [
                12,
                3,
                [
                    [12, 1, message],
                    [8, 3, 4],
                ],
            ],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def sendSquareTextMessage(
        self,
        squareChatMid: str,
        text: str,
        contentMetadata: dict = {},
        relatedMessageId: str = None,
    ):
        return self.sendSquareMessage(
            squareChatMid, text, 0, contentMetadata, relatedMessageId
        )

    def getSquare(self, squareMid: str):
        """Get square."""
        METHOD_NAME = "getSquare"
        params = [[11, 2, squareMid]]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def getJoinableSquareChats(
        self, squareMid: str, continuationToken: str = None, limit: int = 100
    ):
        """Get joinable square chats."""
        METHOD_NAME = "getJoinableSquareChats"
        params = [[11, 1, squareMid], [11, 10, continuationToken], [8, 11, limit]]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def createSquare(
        self,
        name: str,
        displayName: str,
        profileImageObsHash: str = "0h6tJf0hQsaVt3H0eLAsAWDFheczgHd3wTCTx2eApNKSoefHNVGRdwfgxbdgUMLi8MSngnPFMeNmpbLi8MSngnPFMeNmpbLi8MSngnOA",
        desc: str = "test with CHRLINE API",
        searchable: bool = True,
        SquareJoinMethodType: int = 0,
    ):
        """
        Create square.

        - SquareJoinMethodType
            NONE(0),
            APPROVAL(1),
            CODE(2);
        """
        METHOD_NAME = "createSquare"
        params = [
            [8, 2, self.getCurrReqId()],
            [
                12,
                2,
                [
                    [11, 2, name],
                    [11, 4, profileImageObsHash],
                    [11, 5, desc],
                    [2, 6, searchable],
                    [8, 7, 1],  # type
                    [8, 8, 1],  # categoryId
                    [10, 10, 0],  # revision
                    [2, 11, True],  # ableToUseInvitationTicket
                    [12, 14, [[8, 1, SquareJoinMethodType]]],
                    [2, 15, False],  # adultOnly
                    [15, 16, [11, []]],  # svcTags
                ],
            ],
            [
                12,
                3,
                [
                    [11, 3, displayName],
                    # [11, 4, profileImageObsHash],
                    [2, 5, True],  # ableToReceiveMessage
                    [10, 9, 0],  # revision
                ],
            ],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def getSquareChatAnnouncements(self, squareMid: str):
        """Get square chat announcements."""
        METHOD_NAME = "getSquareChatAnnouncements"
        params = [
            [11, 2, squareMid],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def leaveSquareChat(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("leaveSquareChat is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "leaveSquareChat", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareChatMember(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getSquareChatMember is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getSquareChatMember", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def searchSquares(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("searchSquares is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "searchSquares", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def updateSquareFeatureSet(
        self,
        updateAttributes: List[int],
        squareMid: str,
        revision: int,
        creatingSecretSquareChat: int = 0,
    ):
        """
        Update square feature set.

        - updateAttributes:
            CREATING_SECRET_SQUARE_CHAT(1),
            INVITING_INTO_OPEN_SQUARE_CHAT(2),
            CREATING_SQUARE_CHAT(3),
            READONLY_DEFAULT_CHAT(4),
            SHOWING_ADVERTISEMENT(5),
            DELEGATE_JOIN_TO_PLUG(6),
            DELEGATE_KICK_OUT_TO_PLUG(7),
            DISABLE_UPDATE_JOIN_METHOD(8),
            DISABLE_TRANSFER_ADMIN(9),
            CREATING_LIVE_TALK(10);
        """
        METHOD_NAME = "updateSquareFeatureSet"
        SquareFeatureSet = [
            [11, 1, squareMid],
            [10, 2, revision],
        ]
        if creatingSecretSquareChat != 0:
            SquareFeatureSet.append(
                [12, 11, [[8, 1, 1], [8, 2, creatingSecretSquareChat]]]
            )
        params = [[14, 2, [8, updateAttributes]], [12, 3, SquareFeatureSet]]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def joinSquare(
        self,
        squareMid,
        displayName,
        ableToReceiveMessage: bool = False,
        passCode: str = None,
    ):
        params = [
            [
                12,
                1,
                [
                    [11, 2, squareMid],
                    [
                        12,
                        3,
                        [
                            [11, 2, squareMid],
                            [11, 3, displayName],
                            [2, 5, ableToReceiveMessage],
                            [10, 9, 0],
                        ],
                    ],
                    [12, 5, [[12, 2, [[11, 1, passCode]]]]],
                ],
            ]
        ]
        sqrd = self.generateDummyProtocol("joinSquare", params, 4)
        return self.postPackDataAndGetUnpackRespData(
            self.LINE_SQUARE_ENDPOINT,
            sqrd,
            4,
            encType=0,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquarePopularKeywords(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getPopularKeywords is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getPopularKeywords", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def reportSquareMessage(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("reportSquareMessage is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "reportSquareMessage", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def updateSquareMemberRelation(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("updateSquareMemberRelation is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "updateSquareMemberRelation", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def leaveSquare(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("leaveSquare is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "leaveSquare", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareMemberRelations(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getSquareMemberRelations is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getSquareMemberRelations", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def removeSquareSubscriptions(self, subscriptionIds: list = []):
        params = [
            [
                12,
                1,
                [
                    [15, 2, [10, subscriptionIds]],
                ],
            ]
        ]
        sqrd = self.generateDummyProtocol("removeSubscriptions", params, 4)
        return self.postPackDataAndGetUnpackRespData(
            self.LINE_SQUARE_ENDPOINT,
            sqrd,
            4,
            encType=0,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareMembers(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getSquareMembers is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getSquareMembers", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def updateSquareChat(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("updateSquareChat is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "updateSquareChat", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareMessageReactions(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getMessageReactions is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getMessageReactions", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def destroySquareMessage(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("destroyMessage is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "destroyMessage", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def reportSquareChat(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("reportSquareChat is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "reportSquareChat", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def unsendSquareMessage(self, squareChatMid: str, messageId: str):
        """
        Unsend message for square.

        2022/09/19: Added.
        """
        METHOD_NAME = "unsendMessage"
        params = SquareServiceStruct.UnsendMessageRequest(squareChatMid, messageId)
        sqrd = self.generateDummyProtocol(
            METHOD_NAME, params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
            readWith=f"{__class__.__name__}.{METHOD_NAME}",
        )

    def deleteSquareChatAnnouncement(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("deleteSquareChatAnnouncement is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "deleteSquareChatAnnouncement", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def createSquareChat(
        self,
        squareChatMid: str,
        name: str,
        chatImageObsHash: str,
        squareChatType: int = 1,
        maxMemberCount: int = 5000,
        ableToSearchMessage: int = 1,
        squareMemberMids: list = [],
    ):
        """
        - SquareChatType:
            OPEN(1),
            SECRET(2),
            ONE_ON_ONE(3),
            SQUARE_DEFAULT(4);
        - ableToSearchMessage:
            NONE(0),
            OFF(1),
            ON(2);
        """
        params = [
            [
                12,
                1,
                [
                    [8, 1, self.getCurrReqId()],
                    [
                        12,
                        2,
                        [
                            [11, 1, squareChatMid],
                            [8, 3, squareChatType],
                            [11, 4, name],
                            [11, 5, chatImageObsHash],
                            [8, 7, maxMemberCount],
                            [8, 11, ableToSearchMessage],
                        ],
                    ],
                    [15, 3, [11, squareMemberMids]],
                ],
            ]
        ]
        sqrd = self.generateDummyProtocol(
            "createSquareChat", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def deleteSquareChat(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("deleteSquareChat is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "deleteSquareChat", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareChatMembers(
        self, squareChatMid: str, continuationToken: str = None, limit: int = 200
    ):
        GetSquareChatMembersRequest = [[11, 1, squareChatMid], [8, 3, limit]]
        if continuationToken is not None:
            GetSquareChatMembersRequest.append([11, 2, continuationToken])
        params = [[12, 1, GetSquareChatMembersRequest]]
        sqrd = self.generateDummyProtocol(
            "getSquareChatMembers", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareFeatureSet(self, squareMid: str):
        """Get square feature set."""
        METHOD_NAME = "getSquareFeatureSet"
        params = [
            [11, 2, squareMid],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def updateSquareAuthority(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("updateSquareAuthority is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "updateSquareAuthority", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def rejectSquareMembers(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("rejectSquareMembers is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "rejectSquareMembers", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def deleteSquare(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("deleteSquare is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "deleteSquare", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def reportSquare(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("reportSquare is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "reportSquare", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareInvitationTicketUrl(self, mid: str):
        params = [
            [
                12,
                1,
                [
                    [11, 2, mid],
                ],
            ]
        ]
        sqrd = self.generateDummyProtocol("getInvitationTicketUrl", params, 4)
        return self.postPackDataAndGetUnpackRespData(
            self.LINE_SQUARE_ENDPOINT,
            sqrd,
            4,
            encType=0,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def updateSquareChatMember(
        self,
        squareMemberMid: str,
        squareChatMid: str,
        notificationForMessage: bool = True,
        notificationForNewMember: bool = True,
        updatedAttrs: list = [6],
    ):
        """
        - SquareChatMemberAttribute:
            MEMBERSHIP_STATE(4),
            NOTIFICATION_MESSAGE(6),
            NOTIFICATION_NEW_MEMBER(7);
        """
        params = [
            [
                12,
                1,
                [
                    [14, 2, [8, updatedAttrs]],
                    [
                        12,
                        3,
                        [
                            [11, 1, squareMemberMid],
                            [11, 2, squareChatMid],
                            [2, 5, notificationForMessage],
                            [2, 6, notificationForNewMember],
                        ],
                    ],
                ],
            ]
        ]
        sqrd = self.generateDummyProtocol("updateSquareChatMember", params, 4)
        return self.postPackDataAndGetUnpackRespData(
            self.LINE_SQUARE_ENDPOINT,
            sqrd,
            4,
            encType=0,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def updateSquareMember(
        self,
        updatedAttrs: list,
        updatedPreferenceAttrs: list,
        squareMemberMid: str,
        squareMid: str,
        revision: int,
        displayName: str = None,
        membershipState: int = None,
        role: int = None,
    ):
        """
        Update square member.

        SquareMemberAttribute:
            DISPLAY_NAME(1),
            PROFILE_IMAGE(2),
            ABLE_TO_RECEIVE_MESSAGE(3),
            MEMBERSHIP_STATE(5),
            ROLE(6),
            PREFERENCE(7);
        SquareMembershipState:
            JOIN_REQUESTED(1),
            JOINED(2),
            REJECTED(3),
            LEFT(4),
            KICK_OUT(5),
            BANNED(6),
            DELETED(7);
        """
        METHOD_NAME = "updateSquareMember"
        squareMember = [[11, 1, squareMemberMid], [11, 2, squareMid]]
        if 1 in updatedAttrs:
            if displayName is None:
                raise ValueError("displayName is None")
            squareMember.append([11, 3, displayName])
        if 5 in updatedAttrs:
            if membershipState is None:
                raise ValueError("membershipState is None")
            squareMember.append([8, 7, membershipState])
        if 6 in updatedAttrs:
            if role is None:
                raise ValueError("role is None")
            squareMember.append([8, 8, role])
        squareMember.append([10, 9, revision])
        params = [
            [14, 2, [8, updatedAttrs]],
            [14, 3, [8, updatedPreferenceAttrs]],
            [12, 4, squareMember],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    # https://discord.com/channels/466066749440393216/1076212330620256296
    def deleteOtherFromSquare(self, sid: str, pid: str):
        """Kick out member for square."""
        UPDATE_PREF_ATTRS = []
        UPDATE_ATTRS = [5]
        MEMBERSHIP_STATE = 5
        getSquareMemberResp = self.getSquareMember(pid)
        squareMember = self.checkAndGetValue(getSquareMemberResp, "squareMember", 1)
        squareMemberRevision = self.checkAndGetValue(squareMember, "revision", 9)
        revision = squareMemberRevision
        self.updateSquareMember(
            UPDATE_ATTRS,
            UPDATE_PREF_ATTRS,
            pid,
            sid,
            revision,
            membershipState=MEMBERSHIP_STATE,
        )

    def updateSquare(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("updateSquare is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "updateSquare", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareAuthorities(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getSquareAuthorities is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getSquareAuthorities", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def updateSquareMembers(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("updateSquareMembers is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "updateSquareMembers", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareChatStatus(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getSquareChatStatus is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getSquareChatStatus", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def approveSquareMembers(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("approveSquareMembers is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "approveSquareMembers", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareStatus(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getSquareStatus is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getSquareStatus", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def searchSquareMembers(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("searchSquareMembers is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "searchSquareMembers", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def checkSquareJoinCode(self, squareMid: str, code: str):
        params = [
            [
                12,
                1,
                [
                    [11, 2, squareMid],
                    [11, 3, code],
                ],
            ]
        ]
        sqrd = self.generateDummyProtocol("checkJoinCode", params, 4)
        return self.postPackDataAndGetUnpackRespData(
            self.LINE_SQUARE_ENDPOINT,
            sqrd,
            4,
            encType=0,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def createSquareChatAnnouncement(
        self,
        squareChatMid: str,
        messageId: str,
        text: str,
        senderSquareMemberMid: str,
        createdAt: int,
        announcementType: int = 0,
    ):
        """
        - SquareChatAnnouncementType:
            TEXT_MESSAGE(0);
        """
        params = [
            [
                12,
                1,
                [
                    [8, 1, self.getCurrReqId()],
                    [11, 2, squareChatMid],
                    [
                        12,
                        3,
                        [
                            [8, 2, announcementType],
                            [
                                12,
                                3,
                                [
                                    [
                                        12,
                                        1,
                                        [
                                            [11, 1, messageId],
                                            [11, 2, text],
                                            [11, 3, senderSquareMemberMid],
                                            [10, 4, createdAt],
                                        ],
                                    ]
                                ],
                            ],
                        ],
                    ],
                ],
            ]
        ]
        sqrd = self.generateDummyProtocol(
            "createSquareChatAnnouncement", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareAuthority(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getSquareAuthority is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getSquareAuthority", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareChat(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getSquareChat is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getSquareChat", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def refreshSquareSubscriptions(self, subscriptions: list):
        params = [
            [
                12,
                1,
                [
                    [15, 2, [10, subscriptions]],
                ],
            ]
        ]
        sqrd = self.generateDummyProtocol("refreshSubscriptions", params, 4)
        return self.postPackDataAndGetUnpackRespData(
            self.LINE_SQUARE_ENDPOINT,
            sqrd,
            4,
            encType=0,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getJoinedSquareChats(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getJoinedSquareChats is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getJoinedSquareChats", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def joinSquareChat(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("joinSquareChat is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "joinSquareChat", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def findSquareByEmid(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("findSquareByEmid is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "findSquareByEmid", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareMemberRelation(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getSquareMemberRelation is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getSquareMemberRelation", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareMember(self, squareMemberMid: str):
        params = [
            [
                12,
                1,
                [
                    [11, 2, squareMemberMid],
                ],
            ]
        ]
        sqrd = self.generateDummyProtocol("getSquareMember", params, 4)
        return self.postPackDataAndGetUnpackRespData(
            self.LINE_SQUARE_ENDPOINT,
            sqrd,
            4,
            encType=0,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def destroySquareMessages(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("destroyMessages is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "destroyMessages", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareCategories(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getCategories is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getCategories", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def reportSquareMember(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("reportSquareMember is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "reportSquareMember", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareNoteStatus(self):
        """
        AUTO_GENERATED_CODE! DONT_USE_THIS_FUNC!!
        """
        raise Exception("getNoteStatus is not implemented")
        params = []
        sqrd = self.generateDummyProtocol(
            "getNoteStatus", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def searchSquareChatMembers(
        self,
        squareChatMid: str,
        displayName: str = "",
        continuationToken: str = None,
        limit: int = 20,
    ):
        SearchSquareChatMembersRequest = [
            [11, 1, squareChatMid],
            [
                12,
                2,
                [
                    [11, 1, displayName],
                    # [2, 2, True]  # includingMe
                ],
            ],
            [8, 4, limit],
        ]
        if continuationToken is not None:
            SearchSquareChatMembersRequest.append([11, 3, continuationToken])
        params = [[12, 1, SearchSquareChatMembersRequest]]
        sqrd = self.generateDummyProtocol(
            "searchSquareChatMembers", params, self.SquareService_REQ_TYPE
        )
        return self.postPackDataAndGetUnpackRespData(
            self.SquareService_API_PATH,
            sqrd,
            self.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
        )

    def getSquareChatFeatureSet(self, squareChatMid: str):
        """Get square chat feature set."""
        METHOD_NAME = "getSquareChatFeatureSet"
        params = [
            [11, 2, squareChatMid],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def getSquareEmid(self, squareMid: str):
        """
        Get square eMid.

        GENERATED BY YinMo0913_DeachSword-DearSakura_v1.0.5.py
        DATETIME: 02/03/2023, 23:02:07
        """
        METHOD_NAME = "getSquareEmid"
        params = [[11, 1, squareMid]]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def getSquareMembersBySquare(self, squareMid: str, squareMemberMids: list):
        """
        Get square members by square.

        GENERATED BY YinMo0913_DeachSword-DearSakura_v1.0.5.py
        DATETIME: 02/03/2023, 23:02:07
        """
        METHOD_NAME = "getSquareMembersBySquare"
        params = [
            [11, 2, squareMid],
            [14, 3, [11, squareMemberMids]],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def manualRepair(self, syncToken: str, limit: int, continuationToken: str):
        """
        Manual repair.

        GENERATED BY YinMo0913_DeachSword-DearSakura_v1.0.5.py
        DATETIME: 02/03/2023, 23:02:07
        """
        METHOD_NAME = "manualRepair"
        params = [
            [11, 1, syncToken],
            [8, 2, limit],
            [11, 3, continuationToken],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def getJoinedSquareChatThreads(
        self, squareChatMid: str, limit: int = 20, continuationToken: str = None
    ):
        """
        Get joined square chat threads.

        ---
        GENERATED BY YinMo0913_DeachSword-DearSakura_v1.0.6.py
        DATETIME: 04/24/2023, 18:07:51
        """
        METHOD_NAME = "getJoinedSquareChatThreads"
        params = [
            [11, 1, squareChatMid],
            [8, 2, limit],
            [11, 3, continuationToken],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def createSquareChatThread(self, squareChatMid: str, squareMid: str, messageId: str):
        """
        Create square chat thread.

        Usages:
            `cl.createSquareChatThread(SQ_CHAT_MID, SQ_MID, MSG_ID)`

        Example:
            `cl.createSquareChatThread("mxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "sxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "123456")`

        ---
        GENERATED BY YinMo0913_DeachSword-DearSakura_v1.0.6.py
        DATETIME: 04/24/2023, 18:07:51
        """
        METHOD_NAME = "createSquareChatThread"
        squareChatThread = [
            [11, 2, squareChatMid],
            [11, 3, squareMid],
            [11, 4, messageId],
        ]
        params = [
            [8, 1, self.getCurrReqId("sq")],
            [12, 2, squareChatThread],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def getSquareChatThread(self, squareChatMid: str, squareChatThreadMid: str):
        """
        Get square chat thread.

        ---
        GENERATED BY YinMo0913_DeachSword-DearSakura_v1.0.6.py
        DATETIME: 04/24/2023, 18:07:51
        """
        METHOD_NAME = "getSquareChatThread"
        params = [
            [11, 1, squareChatMid],
            [11, 2, squareChatThreadMid],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def joinSquareChatThread(self, squareChatMid: str, squareChatThreadMid: str):
        """
        Join square chat thread.

        ---
        GENERATED BY YinMo0913_DeachSword-DearSakura_v1.0.6.py
        DATETIME: 04/24/2023, 18:07:51
        """
        METHOD_NAME = "joinSquareChatThread"
        params = [
            [11, 1, squareChatMid],
            [11, 2, squareChatThreadMid],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

    def syncSquareMembers(self, squareMid: str, squareMembers: Dict[str, int]):
        """
        Sync square members.

        Usages:
            `cl.syncSquareMembers(SQ_MID, {MBER_MID: REV})`

        Example:
            `cl.syncSquareMembers("sxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", {'pxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx': 0})`

        ---
        GENERATED BY YinMo0913_DeachSword-DearSakura_v1.0.6.py
        DATETIME: 04/24/2023, 18:07:51
        """
        METHOD_NAME = "syncSquareMembers"
        params = [
            [11, 1, squareMid],
            [13, 2, [11, 10, squareMembers]],
        ]
        return SquareServiceStruct.SendRequestByName(self, METHOD_NAME, params)

class SquareServiceStruct(BaseServiceStruct):
    @staticmethod
    def UnsendMessageRequest(squareChatMid: str, messageId: str):
        return __class__.BaseRequest([[11, 2, squareChatMid], [11, 3, messageId]])

    @staticmethod
    def SendRequestByName(client: "CHRLINE", name: str, request: str):
        payload = __class__.BaseRequest(request)
        sqrd = client.generateDummyProtocol(
            name, payload, client.SquareService_REQ_TYPE
        )
        return client.postPackDataAndGetUnpackRespData(
            client.SquareService_API_PATH,
            sqrd,
            client.SquareService_RES_TYPE,
            baseException=SquareService.SQUARE_EXCEPTION,
            readWith=f"SquareService.{name}",
        )


import unittest

# import boris_analysis.compute_performance as cp
import pyRserve as pyr
from pyRserve.rexceptions import REvalError
import numpy as np

def get_auc(data):
    # Prepare R connection
    rc = pyr.connect()
    rc.voidEval("library(pROC)")
    rc.r.levels = ['positive', 'negative']

    predictions = list()
    true_classes = list()
    for cursor in data:
        predictions.append(cursor['positive_class_distance'] - cursor['negative_class_distance'])
        # predictions.append(cursor['negative_class_distance'] - cursor['positive_class_distance'])
        true_classes.append(cursor['true_class'])

    rc.r.predictor = np.array(predictions)
    rc.r.response = np.array(true_classes)
    try:
        rc.voidEval("roc <- roc(response = response, predictor = predictor, levels = levels)")
    except REvalError as e:
        print("Error while computing ROC with predictions: '{0}' and true_classes: '{1}. Will re-raise the error."
              .format(str(predictions), str(true_classes)))
        raise e

    auc = rc.eval("roc$auc")

    return auc[0]

class TestAuc(unittest.TestCase):

    def test_perfect_auc(self):
        pc = 'positive'
        nc = 'negative'
        pcd = 'positive_class_distance'
        ncd = 'negative_class_distance'
        tc = 'true_class'

        # positive samples
        d_1 = dict()
        d_1[pcd] = 0.9
        d_1[ncd] = 0.1
        d_1[tc] = pc

        d_5 = d_4 = d_3 = d_2 = d_1

        # d_7 = dict()
        # d_7[pcd] = 0.1
        # d_7[ncd] = 0.9
        # d_7[tc] = pc

        # negative sample
        d_6 = dict()
        d_6[pcd] = 0.1
        d_6[ncd] = 0.9
        d_6[tc] = nc

        d = [d_1, d_2, d_3, d_4, d_5, d_6]

        auc = get_auc(d)

        print("AUC: {0}".format(auc))

        self.assertEqual(auc, 1.0)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        """
        T(n) = O(n) -- traverse n nodes
        S(n) = O(n) -- keepping the queue
        """
        from collections import deque
        ans = []
        # if root is null, return an empty list
        if not root:
            return ans

        dq = deque([root, ])
        lv = 0
        while dq:
            ans.append([])
            for _ in range(len(dq)):
                node = dq.popleft()
                if node:
                    ans[lv].append(node.val)
                # append its left and right children
                if node.left:
                    dq.append(node.left)
                if node.right:
                    dq.append(node.right)
            lv += 1
        return ans

102. Binary Tree Level Order Traversal/LevelOrder.py


import requests
import os
import json
import urllib

cur_dir = os.getcwd()
save_dir = cur_dir + "/USA/GA/Norcross"

if not os.path.exists(save_dir):
	os.makedirs(save_dir)

def scrape_urls():
	with open("response.json", "r") as json_file:
		response = json.load(json_file)
		r_data = response['data']
		total = response['total']
		base_url = 'https://www.norcrossga.net'
		for p in range(total):
			doc_url = r_data[p]['URL']
			output_url = base_url + doc_url

			with open('urls.txt','a') as output:
				output.write(output_url + '\n')
	output.close()

def get_name(line):
	with open("response.json", "r") as json_file:
		response = json.load(json_file)
		r_data = response['data']
		#total = response['total']

		doc_name = r_data[line]['DisplayName']
		return doc_name

def download_data():
	with open('urls.txt', 'r') as in_url:
		for num, line in enumerate(in_url):

			pdf = urllib.request.urlopen(line) # Gets the pdf
			file_name = get_name(num)
			print("Getting " + file_name)
			with open(save_dir + file_name + '.pdf', 'wb') as file:
				file.write(pdf.read())
				file.close()

download_data()


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

from app.modules.user.feed.feed_controller import UserFeedController
from app.modules.user.feed.feed_dto import UserFeedDto
from common.utils.decorator import token_required

# own modules
from common.view import Resource

__author__ = "hoovada.com team"
__maintainer__ = "hoovada.com team"
__email__ = "admin@hoovada.com"
__copyright__ = "Copyright (c) 2020 - 2020 hoovada.com . All Rights Reserved."

api = UserFeedDto.api

@api.route('/feed_all_data')
@api.expect(UserFeedDto.model_user_feed_request)
@api.response(code=200, model=UserFeedDto.model_feed_all_data_response, description='Model for feed of user response (all data).')
class UserGetFeedAllData(Resource):
    @token_required
    def get(self):
        """Get current user's feed with all feed type's data"""

        args = UserFeedDto.model_user_feed_request.parse_args()
        args['get_data'] = True
        controller = UserFeedController()
        return controller.get(args)