import logging
import random
from typing import cast

import torch
import torch.utils.data
from PIL.Image import Image
from torch import nn
from torchvision import models, transforms
from torchvision.models import EfficientNet_V2_M_Weights
from torchvision.transforms import _functional_pil as F_pil
from torchvision.transforms import functional as F

TASK_CLASSIFICATION = "classification"
TASK_ORDINAL_REGRESSION = "ordinal-regression"

DatasetFolderItem = tuple[Image, int]

def create_model(
    device: torch.device,
    num_classes: int,
    task_type: str,
    freeze_pretrained_layers: bool = True,
) -> nn.Module:
    model = models.efficientnet_v2_m(weights=EfficientNet_V2_M_Weights.DEFAULT)
    if freeze_pretrained_layers:
        model.requires_grad_(False)

    lastconv_output_channels = cast(nn.Linear, model.classifier[1]).in_features
    final_output_channels = (
        num_classes - 1 if task_type == TASK_ORDINAL_REGRESSION else num_classes
    )
    model.classifier = nn.Sequential(
        nn.Dropout(0.3, inplace=True),
        nn.Linear(lastconv_output_channels, 512),
        nn.ReLU(),
        nn.Dropout(0.3),
        nn.Linear(512, 512),
        nn.ReLU(),
        nn.Dropout(0.3),
        nn.Linear(512, 128),
        nn.ReLU(),
        nn.Dropout(0.3),
        nn.Linear(128, final_output_channels),
    ).requires_grad_(True)

    return model.to(device)

def get_device() -> torch.device:
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    logging.info(f"Using device {device}.")
    return device

def get_train_transform(resize_to: int) -> transforms.Compose:
    return transforms.Compose(
        [
            transforms.RandomHorizontalFlip(),
            transforms.Lambda(random_crop_long_side),
            transforms.Lambda(pad_to_square),
            transforms.Resize(resize_to),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
        ]
    )

def get_val_transform(resize_to: int) -> transforms.Compose:
    return transforms.Compose(
        [
            transforms.Lambda(pad_to_square),
            transforms.Resize((resize_to, resize_to)),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
        ]
    )

def pad_to_square(img: Image) -> Image:
    w, h = img.size
    if w == h:
        return img
    elif w < h:
        padding = (h - w) // 2
        return F_pil.pad(img, [padding, 0, padding, 0], fill=0)
    else:
        padding = (w - h) // 2
        return F_pil.pad(img, [0, padding, 0, padding], fill=0)

def random_crop_long_side(img: Image) -> Image:
    w, h = img.size
    if w < h:
        new_w = w
        new_h = int(h * random.triangular(0.9, 1, 1))
    else:
        new_w = int(w * random.triangular(0.9, 1, 1))
        new_h = h
    return F.center_crop(img, (new_h, new_w))  # type: ignore


# 003 - 获取并修改图像中的像素点

import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt

# 创建全黑的图像，3表示三个色彩通道; 第一个参数指图像大小；第二个参数指为一个图像
img = np.zeros((256, 256, 3), np.uint8)

# 显示图像
plt.imshow(img[:, :, ::-1])
plt.show()

# 获取像素，对于BGR图像，返回的是一个列表
bgr_pixel = img[100, 100]

# 只返回某一个通道的值
b_pixel = img[100, 100, 0]

# 将 100x100 处的像素写为红色，注意事项BGR通道
img[100, 100] = (0, 0, 255)

print(img[100, 100])
plt.imshow(img[:, :, ::-1])
plt.show()

####################################################

# 获取图像属性
# 图像形状
print(img.shape)  # (256, 256, 3)

# 数值类型
print(img.dtype)  # uint8

# 图像的像素数
print(img.size)  #  196608


import sqlite3 as sql

class StudentInfo:
    def __init__(self):
        self.con = sql.connect('database.db')
        self.cursor = self.con.cursor()
        self.cursor.execute("CREATE TABLE IF NOT EXISTS StudentInfo (id INTEGER, name TEXT, branch TEXT)")
        self.con.commit()

    def insert(self):
        id = int(input('Enter ID :'))
        name = input('Enter Name : ')
        branch = input('Enter Branch : ')
        self.cursor.execute("INSERT INTO StudentInfo values (?,?,?)", (id, name, branch))
        self.con.commit()

    def display(self):
        id  = int(input('Enter ID : '))
        self.cursor.execute("SELECT * FROM StudentInfo WHERE id=?", (id,))
        for Id, name, branch in  self.cursor.fetchall():
            print('ID :', Id)
            print('Name :', name)
            print('Branch', branch)

    def update(self):
        id = int(input('Enter ID :'))
        name = input('Enter Name : ')
        branch = input('Enter Branch : ')
        self.cursor.execute('UPDATE StudentInfo SET name = ?, branch = ? where id =?', (name, branch, id))
        self.con.commit()

    def delete(self):
        id = int(input('Enter ID : '))
        self.cursor.execute('DELETE FROM StudentInfo where id = ?', (id,))
        self.con.commit()

    def display_all(self):
        self.cursor.execute('SELECT * FROM StudentInfo')
        print('ID \t', 'Name \t', 'Branch')
        for Id, name, branch in  self.cursor.fetchall():
            print(Id,'\t',name,'\t',branch)

if __name__ == '__main__':
    sinfo = StudentInfo()
    sinfo.insert()
    sinfo.update()
    sinfo.delete()
    sinfo.display_all()


import xml.etree.ElementTree
import clr
clr.AddReferenceByPartialName("Interop.QBXMLRP2")

# IronPython needs to add Class to request processor to instantiate requests
from  Interop.QBXMLRP2 import RequestProcessor2Class

# Will look for open file if no filename provided
QBFILE = ''

sessionManager = RequestProcessor2Class()
sessionManager.OpenConnection(QBFILE, 'Test qbXML Request')
ticket = sessionManager.BeginSession("", 0)

# Send query and receive response
qbxml_query = """
<?qbxml version="6.0"?>
<QBXML>
   <QBXMLMsgsRq onError="stopOnError">
      <InventoryAdjustmentQueryRq metaData="MetaDataAndResponseData">
      </InventoryAdjustmentQueryRq>
   </QBXMLMsgsRq>
</QBXML>
"""
response_string = sessionManager.ProcessRequest(ticket, qbxml_query)

# Disconnect from Quickbooks
sessionManager.EndSession(ticket)     # Close the company file
sessionManager.CloseConnection()      # Close the connection

# print string is there to study response
# print(response_string)

# Parse the response into an Element Tree and peel away the layers of response
QBXML = xml.etree.ElementTree.fromstring(response_string)
QBXMLMsgsRs = QBXML.find('QBXMLMsgsRs')
InventoryAdjustmentQueryRs = QBXMLMsgsRs.getiterator("InventoryAdjustmentRet")
for InvAdjRet in InventoryAdjustmentQueryRs:
    txnid = InvAdjRet.find('TxnID').text
    try:
        # in case memo is not entered on adjustment
        memo = InvAdjRet.find('Memo').text
    except:
        memo = "No Memo"

    print(txnid, memo)


import numpy as np
import scipy.optimize
import uncertainties as unc
import uncertainties.unumpy as unp
from scipy import optimize
import scipy.constants as const
kboltzmann = const.k
import matplotlib.pyplot as plt
from uncertainties import ufloat
from uncertainties import correlated_values, correlation_matrix
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
from matrix2latex import matrix2latex

k_B=1.3806485e-23
e=1.602e-19

#################################
### Our statistical functions ###
#################################

def mittel(x, deltadof=1):
    return ufloat(np.mean(x),np.std(x,ddof=deltadof)/np.sqrt(len(x)))

########################################
### Our helper functions (fits, etc) ###
########################################

def linfit(x,a,b):
    return a*x+b

def hyp(x,a,b):
    return a/x+b

def lin(x,a,offset=0):
    return a*x + offset

def exp(x,a,b,c):
    return a*np.exp(x*b)+c

def lnint(T,current,heatingRate):
	array = np.array([])
	for t in T:
		array = np.append(array,[np.trapz(current[T>=t],T[T>=t])/(current[T == t]*heatingRate)])
	return array

########################
### Reading the data ###
########################

temp1_2, current1_2 = np.genfromtxt('data/1_2.txt', unpack=True)
temp2, current2 = np.genfromtxt('data/2.txt', unpack=True)
# Temp in Celsius, Current in pA (10^-12)
temps = [temp1_2, temp2] # Eine Liste der beiden Temperaturmessreihen (1_2 und 2)
currents = [current1_2, current2]

############################
### Untergrund bestimmen ###   Vielleicht sind hier die Werte für i einfach so klein dass er da nichts findet... ist mir erst zu spät eingefallen....
############################

expfitx1=np.append(temp1_2[5:19],temp1_2[55:72])
expfity1=np.append(current1_2[5:19], current1_2[55:72])

params1, covariance_matrix = optimize.curve_fit(exp, expfitx1, expfity1)
a,b,c= correlated_values(params1, covariance_matrix)
print('Fit für 1.2K/min:')
print('a=', a)
print('b=', b)
print('c=', c)

expfitx2=np.append(temp2[11:17],temp2[37:51])
expfity2=np.append(current2[11:17], current2[37:51])

params2, covariance_matrix = optimize.curve_fit(exp, expfitx2, expfity2)
a, b, c= correlated_values(params2, covariance_matrix)
print('Fit für 2K/min:')
print('a=', a)
print('b=', b)
print('c=', c)

expfitx=[expfitx1, expfitx2]
expfity=[expfity1, expfity2]
params=[params1, params2]
############################
### Plot the actual data ###
############################

labels = ['Niedigere Heizrate', 'Höhere Heizrate']
names = ['build/depolarisationskurve_1_2.pdf', 'build/depolarisationskurve_2.pdf']
x=np.linspace(-100,100,1000)
xlims = [-70,65]
ylims = [-12.5,17.5]

for i in (0,1):
    plt.plot(temps[i], currents[i], 'bx', alpha=0.75, mew=0.5, label = labels[i])
    plt.plot(expfitx[i], expfity[i], 'rx', label = 'Werte für den Fit')
    plt.plot(x, exp(x, *params[i]),'g-', label='Ausgleichsrechnung', linewidth=0.5)
    plt.plot(temps[i], currents[i]-exp(temps[i],*params[i]), 'gx', mew=0.5,  label='Messwerte mit Untergrundkorrektur')
    plt.ylim(ylims)
    plt.xlim(xlims)
    plt.grid()
    plt.xlabel(r'$T/$°C')
    plt.ylabel(r'$I/$pA')
    plt.legend(loc='best')
    plt.savefig(names[i])
    plt.clf()


from bs4 import BeautifulSoup
import re
import csv

RPP = 30
NEED = 3100
N_PG = int(NEED/RPP) + 1

def read_soup(url, decode_type=None):
    import requests
    r = requests.get(url)
    encoding = r.encoding if 'charset' in r.headers.get('content-type', '').lower() else None
    soup = BeautifulSoup(r.content, 'html.parser', from_encoding=encoding)
    return soup

class Restaurant:
    def __init__(self, idx, name, single_page_url):
        self.id = idx
        self.name = name
        self.url = single_page_url
        self.rate = None
        self.reviews = None
        self.money = None
        self.type = list()
        self.address_street = None
        self.address_locality = None
        self.phone = None
        self.sun_hours = None
        self.mon_hours = None
        self.tues_hours = None
        self.wed_hours = None
        self.thur_hours = None
        self.fri_hours = None
        self.sat_hours = None
        self.crawl_from_url()

    def set_hours(self, day_text, hours):
        if day_text == "Sunday":
            self.sun_hours = hours
        elif day_text == "Monday":
            self.mon_hours = hours
        elif day_text == "Tuesday":
            self.tues_hours = hours
        elif day_text == "Wednesday":
            self.wed_hours = hours
        elif day_text == "Thursday":
            self.thur_hours = hours
        elif day_text == "Friday":
            self.fri_hours = hours
        elif day_text == "Saturday":
            self.sat_hours = hours

    def crawl_from_url(self):
        try:
            soup = read_soup(self.url)
            header_rating = soup.find(class_="header_rating")
            self.rate = header_rating.find("span", {"property": "ratingValue"})["content"]
            self.reviews = header_rating.find("span", {"property": "count"}).text.replace(",", "")
            header_money = soup.find(class_="header_tags rating_and_popularity")
            self.money = header_money.text if header_money else None
            header_types = soup.find(class_="header_links rating_and_popularity")
            self.type = [t.text for t in header_types.find_all("a")] if header_types else list()
            header_street = soup.find(class_="street-address")
            self.address_street = header_street.text if header_street else None
            header_locality = soup.find(class_="locality")
            self.address_locality = header_locality.text if header_locality else None
            header_phone = soup.find(class_="ui_icon phone").next_sibling
            self.phone = header_phone.text if header_phone else None
            hours = soup.find(class_="hours content")
            if hours:
                week = hours.find(class_="detail")
                while week:
                    self.set_hours(week.find(class_="day").text, week.find(class_="hoursRange").text)
                    week = week.next_sibling.next_sibling
        except Exception as e:
            print(e)
            print("{} {} \n{}".format(self.id, self.name, self.url))

    def writerow_to_csv(self, csvwriter):
        info = [self.id, self.name, self.rate, self.reviews, self.money]
        for i in range(3):
            try:
                info.append(self.type[i])
            except IndexError:
                info.append(None)
        info.extend([self.address_street, self.address_locality, self.phone])
        info.extend([self.sun_hours, self.mon_hours, self.tues_hours, self.wed_hours, self.thur_hours, self.fri_hours, self.sat_hours])
        csvwriter.writerow(info)

# crawl website information
idx = 1
restaurants = list()
print("Start crawling")
for page in range(N_PG):
    API_url = 'https://www.tripadvisor.com/RestaurantSearch?Action=PAGE&geo=32655&ajax=1&itags=10591&sortOrder=relevance&o=a{}&availSearchEnabled=false'\
            .format(page*30)
    soup = read_soup(API_url)
    reslist_regex = re.compile(".*listing.*")
    reslist = soup.find_all("div", class_=reslist_regex)
    for res in reslist:
        title = res.find(class_="property_title")
        name = title.text.strip()
        url = "https://www.tripadvisor.com" + title['href']
        r_object = Restaurant(idx, name, url)
        restaurants.append(r_object)
        idx += 1

# convert to csv
print("Start convert to csv")

with open('tripadvisor_la.csv', 'w', newline='') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',',
                           quotechar='"', quoting=csv.QUOTE_MINIMAL)
    csvwriter.writerow(["id", "name", "rate", "n_reviews", "money", "type_1", "type_2", "type_3", "address_street", "address_locality", "phone", \
                        "sun_hours", "mon_hours", "tue_hours", "wed_hours", "thur_hours", "fri_hours", "sat_hours"])
    for robj in restaurants:
        robj.writerow_to_csv(csvwriter)


import socket
import traceback
import time
import random

class SocketServer():
    def __init__(self, host="127.0.0.1", port=8080):
        self.host = host
        self.port = port
        self.sock = None

    def initialize(self):
        # AF_INET : IPV4
        # SOCK_STREAM: TCP
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def listen(self):
        try:
            # () -> tuple (any, any) -> (int, str)
            self.sock.bind((self.host, self.port))
            # time out
            # self.sock.settimeout(2)
            print(f"listen on {self.host}, {self.port}")
            self.sock.listen(1) # wait blocking -> sleep
            (conn, address) = self.sock.accept()
            """
               listen : 8080
               client -> server 44468 -> 8080
               44468
            """
            print(f"Succesfully from {address}")
            return conn
        except:
            traceback.print_exc()

    def send_text(self, conn, text):
        #send non-blocking
        """
        byte 0x121245
        str "1234"
        utf-8
        0~128 0xff -> utf-8
        """
        print(message)
        conn.send(text.encode('utf-8')) # bytes

        """
        1. send
        2. send_all 6000000 / (4096 | 1024)
        """

    def recv_text(self, conn):
        msg = conn.recv(4096)
        return msg

    def close_conn(self,conn):
        conn.close()

    def close_socket(self):
        self.sock.close()

if __name__ == "__main__":

    socket_server = SocketServer("127.0.0.1", 9999)
    """ 1024 up"""
    socket_server.initialize()
    conn = socket_server.listen() #from  (conn, address) = self.sock.accept()
    while True:
        # message = input("What do you want to send: ")
        x = input("r for random data/ q for quit: ")
        if x == "r":
            message = ""
            for i in range(15):
                message += str(round(random.uniform(1,10),2))
                message += ","

            message = message[:-1]
            socket_server.send_text(conn, message)
            msg = socket_server.recv_text(conn)
            print(msg)
            # time.sleep(1)
            # print(message)

        if x == "q":
            print("quit")
            #socket.SHUT_RDWR
            '''
            conn.close()
            socket.SHUT_RDWR
            socket.close()
            '''
            message = "q"
            socket_server.send_text(conn, message)
            msg = socket_server.recv_text(conn)
            print(msg)
            socket_server.close_conn(conn)
            break

        # socket_server.send_text(conn, message)
        # msg = socket_server.recv_text(conn)
        # print(msg)
        # # time.sleep(1)

    socket_server.close_socket()


import itertools
import warnings
import statsmodels.api as sm
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import pyplot
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.stattools import adfuller
import seaborn as sns
from statsmodels.tsa.arima_model import ARIMAResults

# from statsmodels.tsa.arima_model import SARIMAResults

warnings.filterwarnings('ignore')

def adfuller_test(sales):
    """Method will test weather data is stationary or not"""
    rolmean = pd.Series(sales).rolling(window=12).mean()
    rolstd = pd.Series(sales).rolling(window=12).std()

    # plt.plot(sales, color='blue', label='Original')
    # plt.plot(rolmean, color='red', label='Rolling Mean')
    # plt.plot(rolstd, color='black', label='Rolling Std')
    # plt.legend(loc='best')
    # plt.title('Rolling Mean & Standard Deviation')
    # plt.xlabel("Date")
    # plt.ylabel('No Of Booking Requests')
    # plt.show()

    result = adfuller(sales)
    labels = ['ADF Test Statistic', 'p-value', '#Lags Used', 'Number of Observations Used']
    for value, label in zip(result, labels):
        print(label + ' : ' + str(value))
    if result[1] <= 0.05:
        print("strong evidence against the null hypothesis(Ho), reject the null hypothesis. "
              "Data has no unit root and is stationary")
    else:
        print("weak evidence against null hypothesis, time series has a unit root, indicating it is non-stationary ")

def train_arima_sarima(df):
    df.dropna(inplace=True)
    df["no_of_requests"] = 1
    print(df["no_of_requests"].describe())
    df.rename(columns={'index': 'filedate'}, inplace=True)
    df['filedate'] = pd.to_datetime(df['filedate'])
    df["no_of_requests"] = df["no_of_requests"].apply(pd.to_numeric, errors='coerce')
    df = df.resample('d', on='filedate').sum().dropna(how='all')
    print(df["no_of_requests"].describe())
    # sns.set_style('darkgrid')
    # df["no_of_requests"].plot(kind='line', legend='reverse', title='Visualizing average number of request plot')
    # plt.xlabel("Month'S")
    # plt.ylabel('No Of Booking Requests')
    # plt.legend(loc='upper right', shadow=True)
    # plt.show()

    # result = seasonal_decompose(df["no_of_requests"])
    # result.plot()
    # pyplot.show()

    adfuller_test(df["no_of_requests"])

    df['Booking First Difference'] = df['no_of_requests'] - df['no_of_requests'].shift(1)

    # print(df["Booking First Difference"].describe())
    adfuller_test(df["Booking First Difference"].dropna())

    # fig = plt.figure(figsize=(12, 8))
    # ax1 = fig.add_subplot(211)
    # fig = sm.graphics.tsa.plot_acf(df["Booking First Difference"].iloc[6:], lags=13, ax=ax1)
    # ax2 = fig.add_subplot(212)
    # fig = sm.graphics.tsa.plot_pacf(df["Booking First Difference"].iloc[6:], lags=13, ax=ax2)
    # plt.show()

    train = df["no_of_requests"].dropna()[:100]
    test = df["no_of_requests"].dropna()[100:]
    print(train.head())

    param_dict = {}
    p = d = q = range(0, 5)
    pdq = list(itertools.product(p, d, q))

    for param in pdq:
        try:
            model = ARIMA(train, order=param)
            results = model.fit(disp=0)
            print(param, results.aic)
            param_dict[abs(results.aic)] = param
        except:
            continue

    arima_param = param_dict.get(min(list(param_dict.keys())))
    print("Training on order", arima_param)
    model = ARIMA(train, order=arima_param)
    results = model.fit(disp=0)
    prediction = results.forecast(steps=36)[0]
    plt.plot(test.values)
    plt.plot(prediction, color='red')
    plt.xlabel("Day'S")
    plt.ylabel('No Of Booking Requests')
    plt.show()
    print(prediction)

    results.save('model_arima.pkl')
    # load model
    loaded = ARIMAResults.load('model_arima.pkl')
    future = loaded.forecast(steps=20)[0]
    print(future)

    # seasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))]
    # print('Seasonal ARIMA result...')
    # for param in pdq:
    #     for param_seasonal in seasonal_pdq:
    #         try:
    #             mod = sm.tsa.statespace.SARIMAX(train,
    #                                             order=param,
    #                                             seasonal_order=param_seasonal,
    #                                             enforce_stationarity=True,
    #                                             enforce_invertibility=False)
    #             results = mod.fit(disp=0)
    #             print('ARIMA{}x{}12 - AIC:{}'.format(param, param_seasonal, results.aic))
    #         except:
    #             continue

    mod = sm.tsa.statespace.SARIMAX(train,
                                    order=arima_param,
                                    seasonal_order=(0, 1, 0, 52),
                                    enforce_stationarity=True,
                                    enforce_invertibility=False)
    results = mod.fit(disp=0)
    prediction = results.forecast(steps=36)
    print("Prediction", prediction)
    results.save('model_sarima.pkl')
    # load model
    loaded = ARIMAResults.load('model_sarima.pkl')
    # plt.plot(test.values)
    # plt.plot(prediction.values, color='red')
    # plt.xlabel("Day'S")
    # plt.ylabel('No Of Booking Requests')
    # plt.show()

# if __name__ == '__main__':
#
#     df = pd.read_csv('../Models/feature_file.csv')
#     predict_sas(df)


#-*- coding: UTF-8 -*-
import os

g = os.walk("./")

for path,dir_list,file_list in g:
    for dir_name in file_list:
    	    if(dir_name.endswith(".md")):
            	print(os.path.join(path, dir_name) )
#print('中国')


from stringSearching.arrangedStringNode import ArrangedStringNode
from stringSearching.arrangedStringNode import sortable_score_basic

class ArrangedStringTree:
    def __init__(self):
        self.root = None

    def print_preorder(self, print_func=print):
        ArrangedStringTree._print_preorder(self.root, print_func)

    def add(self, string):
        node = ArrangedStringNode(string)
        self.root = ArrangedStringTree._add(self.root, node)

    def cast_net(self, inputted_str, percent_range=10.0, look_range=10,
                 sorting_score=sortable_score_basic):
        """Used to search the tree for similar strings.

        :param inputted_str: The string that is being looked for.
        :param percent_range: The percentage of difference the strings being
            looked at can differ from the inputted_str.
        :param look_range: An int that is how many levels of the tree it goes down
            after it finds its first similar string.
        :param sorting_score: The score that the tree is sorted with.
        :return: An list of strings similar to the one inputted.
        """
        input_sort_value = sorting_score(inputted_str)
        return ArrangedStringTree._find_similar_net(input_sort_value, self.root,
                                                    percent_range, look_range)

    @staticmethod
    def _print_preorder(node, print_func, space=""):
        if node is None:
            return
        print(space + str(node.cmd) + ":" + str(node.value) + "\n")
        space += "  "
        if node.right is not None:
            ArrangedStringTree._print_preorder(node.right, print_func, space)
        if node.left is not None:
            ArrangedStringTree._print_preorder(node.left, print_func, space)

    @staticmethod
    def _add(root, joker_cmd):
        if root is None:
            return joker_cmd
        elif root.right is not None:
            if root.value < joker_cmd.value:
                if root.right.right is None:
                    temp = root.right
                    root.right = ArrangedStringNode("", (temp.value + joker_cmd.value) / 2)
                    if root.right.value > joker_cmd.value:
                        root.right.right = temp
                        root.right.left = joker_cmd
                    else:
                        root.right.right = joker_cmd
                        root.right.left = temp
                    return root
            else:
                if root.left.left is None:
                    temp = root.left
                    root.left = ArrangedStringNode("", (temp.value + joker_cmd.value) / 2)
                    if root.left.value <= joker_cmd.value:
                        root.left.left = temp
                        root.left.right = joker_cmd
                    else:
                        root.left.left = joker_cmd
                        root.left.right = temp
                    return root

        else:
            temp = root
            root = ArrangedStringNode("", (temp.value + joker_cmd.value) / 2)
            if root.value > joker_cmd.value:
                root.right = temp
                root.left = joker_cmd
            else:
                root.right = joker_cmd
                root.left = temp
            return root
        if joker_cmd.value >= root.value:
            root.right = ArrangedStringTree._add(root.right, joker_cmd)
        else:
            root.left = ArrangedStringTree._add(root.left, joker_cmd)
        return root

    @staticmethod
    def _find_similar_net(input_sort_value, node, percent_range, look_range,
                          adding=False, net=[]):
        if node is None or look_range is 0:
            return net
        right = node.right
        left = node.left
        if not adding:
            similar_val = find_percent_dif(node.value, input_sort_value) <= percent_range
            if similar_val:
                ArrangedStringTree._find_similar_net(input_sort_value,
                                                     node, percent_range,
                                                     look_range,
                                                     True, net)
            else:
                if input_sort_value >= node.value:
                    ArrangedStringTree._find_similar_net(input_sort_value,
                                                         right, percent_range,
                                                         look_range,
                                                         False, net)
                if input_sort_value <= node.value:
                    ArrangedStringTree._find_similar_net(input_sort_value,
                                                         left, percent_range,
                                                         look_range,
                                                         False, net)
        else:
            if node.right is None and find_percent_dif(node.value, input_sort_value) <= percent_range:
                net.append(node)
            else:
                ArrangedStringTree._find_similar_net(input_sort_value,
                                                     right, percent_range,
                                                     look_range - 1,
                                                     True, net)
                ArrangedStringTree._find_similar_net(input_sort_value,
                                                     left, percent_range,
                                                     look_range - 1,
                                                     True, net)
        return net

def find_percent_dif(num1, num2):
    return abs((num1 - num2) / num1 * 100.0)


class Solution:
    """
    把一个数组，看成两个数组，一个新的数组，一个当前需要遍历的数组，
    * 遍历旧数组，判断当前遍历到的元素，能不能放到新的数组中
    """
    def remove_duplicates(self, nums: list[int]) -> int:
        if len(nums) <= 2:
            return len(nums)

        # index 指向新数组的位置
        index = 2

        # i 遍历数组
        for i in range(2, len(nums)):
            # 检查是否与新数组中的前两个元素相同
            if nums[i] != nums[index-2]:
                nums[index] = nums[i]
                index += 1

        print(nums[:index])
        return index

if __name__ == "__main__":
    solution = Solution()
    # nums = [1,1,1,2,2,3]
    nums = [0, 0, 1, 1, 1, 1, 2, 3, 3]
    print(solution.remove_duplicates(nums))


# Write string in contents list in files in filenames list
# and store it in files directory

contents = ['This is content for the doc.txt file.',
'This is content for write multiple files.',
'This is content for writing files in diffrent directory.']

filenames = ['doc.txt', 'sample.txt', 'presentation.txt']

for content, filename in zip(contents,filenames):
	file = open(f'../files/{filename}', 'w')
	file.write(content)
	file.close()


import sys
sys.stdin=open("input.txt", "rt")

n=int(input())
num=list(map(int, input().split()))
m=int(input())

a=0
b=0
for _ in range(m):
    ma=0
    mi=100
    for i in range(n):
        if num[i]>ma:
            ma=num[i]
            a=i
    for j in range(n):
        if num[j]<mi:
            mi=num[j]
            b=j
    num[a]=num[a]-1
    num[b]=num[b]+1

print(max(num)-min(num))


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

# implementing this with DFS
class Solution:
    def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
        reference = None
        def traverseTree(original, cloned, target):
            # something new I learned, nonlocal keywork to bring in a non local variable
            nonlocal reference
            if cloned is not None:
                if cloned.val == target.val:
                    reference = cloned
                    return
                else:
                    # implementing DFS on BOTH tree to traverse from left to right
                    traverseTree(cloned.left, target)
                    traverseTree( cloned.right, target)
            else:
                return
        traverseTree(cloned, target)
        return reference

# anothery way to implement this with BFS
class Solution:
    def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
        queue = [cloned]
        while len(queue) > 0:
            current = queue.pop(0)
            if current.val == target.val:
                return current
            else:
                if current.left is not None:
                    queue.append(current.left)
                if current.right is not None:
                    queue.append(current.right)


import frappe
from frappe.model.document import Document
from frappe import _, throw

class EmployeePayrollDetails(Document):

    def validate(self):
        self.validate_share_percentage()
        self.validate_project()
        self.validate_dates()

    def validate_dates(self):
        employee_project = frappe.get_list(
			"Employee Payroll Details",
			filters = {
				"docstatus": 1,
				"employee": self.employee,
				"from_date": ["<=", self.from_date],
				"to_date": [">=", self.to_date]
			},
			fields=["name"]
		)
        if employee_project:
            throw(
				_("There is overlaping with another 'Employee Projects Payroll': {0}.")
				.format(frappe.bold(employee_project.name)))

    def validate_share_percentage(self):
        total_percentage = self.company_share
        for i in self.project_share:
            total_percentage = total_percentage + i.share
        if total_percentage != 100:
            throw(_("Total of 'Share (%)' for all 'Projects' and 'Company Share (%)' can not be more or less than 100 %."))

    def validate_project(self):
        projects = []
        for i in self.project_share:
            if i.project in projects:
                throw(_("There is duplicate on 'Project': {0}.").format(frappe.bold(i.project)))
            projects.append(i.project)


"""Strings encoder and decoder."""
from typing import List

class Codec:
    """Strings encoder and decoder."""

    SEPARATOR = ":"

    def encode(self, strs: List[str]) -> str:
        """Encodes a list of strings to a single string."""
        return "".join(f"%d{Codec.SEPARATOR}%s" % (len(s), s) for s in strs)

    def decode(self, s: str) -> List[str]:
        """Decodes a single string to a list of strings."""
        idx = 0
        strs: List[str] = []

        while idx < len(s):
            sep_idx = s.find(Codec.SEPARATOR, idx)
            s_len = int(s[idx:sep_idx])
            idx = sep_idx + 1 + s_len
            strs.append(s[sep_idx + 1 : idx])

        return strs

if __name__ == "__main__":
    codec = Codec()
    strs = ["Hello", "World", "This is cse", "from sust."]
    e_str = codec.encode(strs)
    print(f"Encoded: {e_str}, type={type(e_str)}")
    d_str = codec.decode(e_str)
    print(f"Decoded: {d_str}, type={type(d_str)}")
    assert d_str == strs


import subprocess

delays = [10, 20, 50, 100]
factors = [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000]
random_seeds = [42, 43, 44]
# 'sbatch' needs quotations around value otherwise it will split on ','.
cvg_thresholds = "\"[0.8,0.8,0.6,0.6,0.3,0.4,0.4,0.7,0.7]\""
resume = False
dynamic_weights = True
script = 'scripts/train/segmenter/spartan/array/train_segmenter_miccai_9_regions_convergence_part_6.slurm'

for factor in factors:
    for delay in delays:
        for random_seed in random_seeds:
            run_name = f"factor-{factor}-delay-{delay}-seed-{random_seed}"
            export = f'ALL,DYNAMIC_WEIGHTS_CONVERGENCE_DELAY={delay},DYNAMIC_WEIGHTS_CONVERGENCE_THRESHOLDS={cvg_thresholds},DYNAMIC_WEIGHTS_FACTOR={factor},RANDOM_SEED={random_seed},RESUME={resume},RUN_NAME={run_name},USE_DYNAMIC_WEIGHTS={dynamic_weights}'
            command = f'sbatch --array=0 --export={export} {script}'
            print(command)
            process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
            process.communicate()


def breakeven(fixed, gen, sell):
    benefit = sell - gen
    if benefit <= 0:
        return -1
    breakevenpt = fixed//benefit + 1
    # even the remainder: fixed % benefit is 0, add 1 more computer
    # there should be profit, we are not getting the point of selling cost being equal to making cost
    # print("Cost for making {0} computers: {1}".format(breakevenpt, fixed + gen*breakevenpt))
    # print("Cost for selling {0} computers: {1}".format(breakevenpt, sell*breakevenpt))
    return breakevenpt

if __name__ == "__main__":
    comp = input()
    lst = comp.split(" ")
    print(breakeven(int(lst[0]), int(lst[1]), int(lst[2])))


from torchvision.datasets.folder import *
import numpy as np
import ipdb

class ImageFolder(DatasetFolder):

    def __init__(self, root, transform=None, target_transform=None,
                 loader=default_loader, is_valid_file=None, return_path=False, split=None):
        super(ImageFolder, self).__init__(root, loader, IMG_EXTENSIONS if is_valid_file is None else None,
                                          transform=transform,
                                          target_transform=target_transform,
                                          is_valid_file=is_valid_file)

        if split:
            assert "/" in split
            i, j = split.split("/")
            N = len(self.samples)
            idx = np.array_split(np.arange(N), int(j))[int(i)-1]
            self.samples = [self.samples[i] for i in idx]

        self.imgs = self.samples
        self.idx_to_class = {v:k for k, v in self.class_to_idx.items()}
        self.return_path = return_path

    def __getitem__(self, index):
        """
        Args:
            index (int): Index

        Returns:
            tuple: (sample, target) where target is class_index of the target class.
        """
        path, target = self.samples[index]
        sample = self.loader(path)
        if self.transform is not None:
            sample = self.transform(sample)
        if self.target_transform is not None:
            target = self.target_transform(target)

        if self.return_path:
            return path, sample, target
        else:
            return sample, target


# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
# 迭代
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if pHead==None or pHead.next==None:
            return pHead
        pre = None
        cur = pHead
        while cur!=None:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre

# 递归
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None: return head
        pHead = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return pHead


import json
import random
import time
import urllib
import re

from scrapy.utils.misc import load_object
from scrapy.http import Request
from scrapy.conf import settings
import redis

from crawler.schedulers.redis.dupefilter import RFPDupeFilter
from crawler.schedulers.redis.queue import RedisPriorityQueue

try:
    import cPickle as pickle
except ImportError:
    import pickle

class DistributedScheduler(object):
    '''
    Scrapy request scheduler that utilizes Priority Queues
    to moderate scrape requests within a distributed scrapy
    cluster
    '''
    redis_conn = None  # the redis connection
    queue = None  # the queue to use for crawling
    spider = None  # the spider using this scheduler
    queue_class = None  # the class to use for the queue
    dupefilter = None  # the redis dupefilter
    item_retries = 0  # the number of extra tries to get an item

    def __init__(self, server, persist, timeout, retries):
        '''
        Initialize the scheduler
        '''
        self.redis_conn = server
        self.persist = persist
        self.rfp_timeout = timeout
        self.item_retires = retries

    def setup(self):
        '''
        Used to initialize things when using mock
        spider.name is not set yet
        '''
        self.queue = RedisPriorityQueue(self.redis_conn,
                                        self.spider.name + ":queue")

    @classmethod
    def from_settings(cls, settings):
        server = redis.Redis(host=settings.get('REDIS_HOST'),
                             port=settings.get('REDIS_PORT'))
        persist = settings.get('SCHEDULER_PERSIST', True)
        timeout = settings.get('DUPEFILTER_TIMEOUT', 600)
        retries = settings.get('SCHEDULER_ITEM_RETRIES', 3)

        return cls(server, persist, timeout, retries)

    @classmethod
    def from_crawler(cls, crawler):
        return cls.from_settings(crawler.settings)

    def open(self, spider):
        self.spider = spider
        self.setup()
        self.dupefilter = RFPDupeFilter(self.redis_conn,
                                        self.spider.name + ':dupefilter', self.rfp_timeout)

    def close(self, reason):
        if not self.persist:
            self.dupefilter.clear()
            self.queue.clear()

    def is_blacklisted(self, appid, crawlid):
        '''
        Checks the redis blacklist for crawls that should not be propagated
        either from expiring or stopped
        @return: True if the appid crawlid combo is blacklisted
        '''
        key_check = '{appid}||{crawlid}'.format(appid=appid,
                                                crawlid=crawlid)
        redis_key = self.spider.name + ":blacklist"
        return self.redis_conn.sismember(redis_key, key_check)

    def enqueue_request(self, request):
        '''
        Pushes a request from the spider back into the queue
        '''
        if not request.dont_filter and self.dupefilter.request_seen(request):
            return
        req_dict = self.request_to_dict(request)

        if not self.is_blacklisted(req_dict['meta']['appid'],
                                   req_dict['meta']['crawlid']):
            key = "{sid}:queue".format(sid=req_dict['meta']['spiderid'])
            curr_time = time.time()

            # insert if crawl never expires (0) or time < expires
            if req_dict['meta']['expires'] == 0 or \
                            curr_time < req_dict['meta']['expires']:
                self.queue.push(req_dict, req_dict['meta']['priority'])

    def request_to_dict(self, request):
        '''
        Convert Request object to a dict.
        modified from scrapy.utils.reqser
        '''
        req_dict = {
            # urls should be safe (safe_string_url)
            'url': request.url.decode('ascii'),
            'method': request.method,
            'headers': dict(request.headers),
            'body': request.body,
            'cookies': request.cookies,
            'meta': request.meta,
            '_encoding': request._encoding,
            'priority': request.priority,
            'dont_filter': request.dont_filter,
        }
        return req_dict

    def find_item(self):
        '''
        Finds an item from the queue
        '''
        count = 0

        while count <= self.item_retries:
            item = self.queue.pop()
            if item:
                # very basic limiter
                time.sleep(1)
                return item
            # we want the spiders to get slightly out of sync
            # with each other for better performance
            time.sleep(random.random())
            count = count + 1

        return None

    def next_request(self):
        '''
        Logic to handle getting a new url request
        '''
        t = time.time()

        item = self.find_item()
        if item:
            try:
                req = Request(item['url'])
            except ValueError:
                # need absolute url
                # need better url validation here
                req = Request('http://' + item['url'])

            if 'meta' in item:
                item = item['meta']

            # defaults
            if "attrs" not in item:
                item["attrs"] = {}
            if "allowed_domains" not in item:
                item["allowed_domains"] = ()
            if "allow_regex" not in item:
                item["allow_regex"] = ()
            if "deny_regex" not in item:
                item["deny_regex"] = ()
            if "deny_extensions" not in item:
                item["deny_extensions"] = None
            if 'curdepth' not in item:
                item['curdepth'] = 0
            if "maxdepth" not in item:
                item["maxdepth"] = 0
            if "priority" not in item:
                item['priority'] = 0
            if "retry_times" not in item:
                item['retry_times'] = 0
            if "expires" not in item:
                item['expires'] = 0

            for key in ('attrs', 'allowed_domains', 'curdepth', 'maxdepth',
                        'appid', 'crawlid', 'spiderid', 'priority', 'retry_times',
                        'expires', 'allow_regex', 'deny_regex', 'deny_extensions'):
                req.meta[key] = item[key]

            return req

        return None

    def has_pending_requests(self):
        '''
        We never want to say we have pending requests
        If this returns True scrapy sometimes hangs.
        '''
        return False


import pandas as pd
UNWANTED = ['.DS_Store', '.gitkeep']

def add_stats(table, axis=1, descriptive_cols=0):
    '''
    Function that will add stats to either axis of a dataframe.
    '''
    i = descriptive_cols
    table = table.copy()
    if axis == 0:
        index = ['ave']
        # index = ['sum','ave']

        df = pd.DataFrame(index=index, columns=table.columns)
        # df.loc['sum'] = table.astype(float).sum(axis=axis, numeric_only=True)
        df.loc['ave'] = table.astype(float).mean(axis=axis)
    else:
        df = pd.DataFrame(index=table.index)
        # df['sum'] = table.iloc[:,i:].astype(float).sum(axis=axis, numeric_only=True)
        df['ave'] = table.iloc[:,i:].astype(float).mean(axis=axis)
    return pd.concat([table, df], axis=axis)


#Usage
# python train_test_split.py
import os
import config
import shutil
import random

class DataSpliter ():

  def buildDataset(self, imagesPath, dtype):
    try:
      path = os.path.join(config.BASE_PATH, dtype)

      if os.path.isdir(path):
        shutil.rmtree(path)

      if not os.path.isdir(path):
        os.mkdir(path)

      for imgPath in imagesPath:
        imagePath = imgPath
        # annotation file full path
        annotationName = imgPath.split(os.path.sep)[-1].replace('.jpg', '.xml')
        annotationPath = os.path.join(config.ANNOTATIONS_PATH, annotationName)
        # coopy images and annotations to corresponding file
        shutil.copy2(imagePath, path)
        shutil.copy2(annotationPath, path)
    except Exception as e:
      raise e

  def split(self):
    try:
      # garb the full path of all images
      imagesPath = [os.path.join(config.IMAGES_PATH, imageName) for imageName in os.listdir(config.IMAGES_PATH)]
      random.shuffle(imagesPath)
      # split the images list into test and train
      limit = int(len(imagesPath) * config.SPLIT)

      trainset = imagesPath[:limit]
      testset = imagesPath[limit:]
      #build test and train dataset
      self.buildDataset(trainset, 'train')
      self.buildDataset(testset, 'test')
    except Exception as e:
      raise e

if __name__ == '__main__':
  spliter = DataSpliter()
  spliter.split()


from onto_tool import onto_tool
import csv
from rdflib import Graph, URIRef, Literal
from rdflib.namespace import RDFS, SKOS

def lists_equal(list_one, list_two):
    return len(list_one) == len(list_two) and sorted(list_one) == sorted(list_two)

def test_sparql_queries():
    onto_tool.main([
        'bundle', '-v', 'output', 'tests-output/bundle', 'tests/bundle/sparql.yaml'
    ])
    with open('tests-output/bundle/sparql.csv') as csvfile:
        actual = list(row for row in csv.DictReader(csvfile))
    expected = [
        {'s': 'https://data.clientX.com/d/topOntology',
         'p': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type',
         'o': 'http://www.w3.org/2002/07/owl#Ontology'},
        {'s': 'https://data.clientX.com/d/topOntology',
         'p': 'http://www.w3.org/2000/01/rdf-schema#definedBy',
         'o': 'urn:test-sparql-queries'}
    ]
    assert actual == expected

def test_sparql_updates():
    onto_tool.main([
        '-k', 'bundle', '-v', 'output', 'tests-output/bundle/endpoint_sparql', 'tests/bundle/sparql_update.yaml'
    ])

    with open('tests-output/bundle/endpoint_sparql/sparql_update_select.csv') as csvfile:
        actual = list(row for row in csv.DictReader(csvfile))
    expected = [
        {'person': 'http://example.com/John',
         'name': 'John'},
        {'person': 'http://example.com/Jane',
         'name': 'Jane'},
    ]
    assert actual == expected

    constructed_graph = Graph()
    constructed_graph.parse('tests-output/bundle/endpoint_sparql/sparql_update_construct.xml', format='xml')
    labels = list(constructed_graph.subject_objects(SKOS.prefLabel))
    assert lists_equal([(URIRef('http://example.com/John'), Literal('John Johnson')),
                        (URIRef('http://example.com/Jane'), Literal('Jane Johnson'))],
                       labels)

def test_each_file():
    onto_tool.main([
        'bundle', '-v', 'output', 'tests-output/bundle', 'tests/bundle/sparql-each.yaml'
    ])

    # Verify CONSTRUCT
    constructed_graph = Graph()
    constructed_graph.parse('tests-output/bundle/each/construct/upper_ontology.ttl', format='turtle')
    labels = list(constructed_graph.subject_objects(SKOS.prefLabel))
    assert len(labels) == 5
    constructed_graph = Graph()
    constructed_graph.parse('tests-output/bundle/each/construct/domain_ontology.ttl', format='turtle')
    labels = list(constructed_graph.subject_objects(SKOS.prefLabel))
    assert len(labels) == 6

    # Verify SELECT
    with open('tests-output/bundle/each/select/upper_ontology.csv') as csvfile:
        actual = list(row['label'] for row in csv.DictReader(csvfile))
    expected = ["Person", "Upper Ontology", "has phone number", "is friend of", "is private"]
    assert actual == expected
    with open('tests-output/bundle/each/select/domain_ontology.csv') as csvfile:
        actual = list(row['label'] for row in csv.DictReader(csvfile))
    expected = ["Domain Ontology", "School", "Student", "Teacher", "teaches", "works for"]
    assert actual == expected

    # Verify UPDATE
    assert actual == expected
    constructed_graph = Graph()
    constructed_graph.parse('tests-output/bundle/each/update/upper_ontology.ttl', format='turtle')
    labels = list(constructed_graph.subject_objects(SKOS.prefLabel))
    assert len(labels) == 5
    assert not list(constructed_graph.subject_objects(RDFS.label))
    constructed_graph = Graph()
    constructed_graph.parse('tests-output/bundle/each/update/domain_ontology.ttl', format='turtle')
    labels = list(constructed_graph.subject_objects(SKOS.prefLabel))
    assert len(labels) == 6
    assert not list(constructed_graph.subject_objects(RDFS.label))


import numpy as np

from squanch import gates

__all__ = ["QError", "AttenuationError", "RandomUnitaryError", "SystematicUnitaryError"]

class QError:
    '''A generalized quantum error model'''

    def __init__(self, qchannel):
        '''
        Base initialization class; extend in child methods by overwriting along with QError.__init__(self, qchannel)

        :param qchannel: the quantum channel this error model is being used on
        '''
        self.qchannel = qchannel

    def apply(self, qubit):
        '''
        Applies the error to the transmitted qubit. Overwrite this method in child classes while maintaining the
        Qubit->(Qubit | None) signature

        :param Qubit qubit: the qubit being withdrawn from the quantum channel with channel.get(); possibly None
        :return: the modified qubit
        '''
        if qubit is not None:
            # Implement error logic here
            pass
        return qubit

class AttenuationError(QError):
    '''Simulate the possible loss of a qubit in a fiber optic channel due to attenuation effects'''

    def __init__(self, qchannel, attenuation_coefficient = -0.16):
        '''
        Instatiate the error class

        :param QChannel qchannel: parent quantum channel
        :param float attenuation_coefficient: attenuation of fiber in dB/km; default: -.16 dB/km, from Yin, et al
        '''
        QError.__init__(self, qchannel)
        decibel_loss = qchannel.length * attenuation_coefficient
        self.attenuation = 10 ** (decibel_loss / 10)  # Total attenuation along the fiber

    def apply(self, qubit):
        '''
        Simulates possible loss + measurement of qubit

        :param Qubit qubit: qubit from quantum channel
        :return: either unchanged qubit or None
        '''
        if np.random.rand() > self.attenuation and qubit is not None:
            # Photon was lost due to attenuation effects; collapse state and return nothing
            qubit.measure()
            qubit = None
        return qubit

class RandomUnitaryError(QError):
    '''Simualates a random rotation along X and Z with a Gaussian distribution of rotation angles'''

    def __init__(self, qchannel, variance):
        '''
        Instatiate the error class

        :param QChannel qchannel: parent quantum channel
        :param float variance: variance to use in the Gaussian sampling of X and Z rotation angles
        '''
        QError.__init__(self, qchannel)
        self.variance = variance

    def apply(self, qubit):
        '''
        Simulates random rotations on X and Z of a qubit

        :param Qubit qubit: qubit from quantum channel
        :return: rotated qubit
        '''
        if qubit is not None:
            x_angle, z_angle = np.random.normal(0, self.variance, 2)
            gates.RX(qubit, x_angle)
            gates.RZ(qubit, z_angle)
        return qubit

class SystematicUnitaryError(QError):
    '''Simulates a random unitary error that is the same for each qubit'''

    def __init__(self, qchannel, operator = None, variance = None):
        '''
        Instantiate the systematic unitary error class

        :param QChannel qchannel: parent quantum channel
        :param np.array operator:
        :param float variance:
        '''
        QError.__init__(self, qchannel)
        assert operator is not None or variance is not None, \
            "Provide either a random operator or a variance value to use for sampling."

        if operator is not None:
            self.operator = operator
        elif variance is not None:
            x_angle, z_angle = np.random.normal(0, variance, 2)
            Rx = np.cos(x_angle / 2.0) * gates._I - 1j * np.sin(x_angle / 2.0) * gates._X
            Rz = np.cos(z_angle / 2.0) * gates._I - 1j * np.sin(z_angle / 2.0) * gates._Z
            self.operator = np.dot(Rz, Rx)

    def apply(self, qubit):
        '''
        Simulates the application of the unitary error

        :param Qubit qubit: qubit from quantum channel
        :return: rotated qubit
        '''
        if qubit is not None:
            qubit.qsystem.apply(self.operator)
        return qubit


import sys
sys.stdin = open('input.txt')

def find(a):
    if parent[a] != a:
        return find(parent[a])
    return a

def union(a, b):
    a = find(a)
    b = find(b)
    if a < b:
        parent[b] = a
    else:
        parent[a] = b

N, M = map(int, input().split())
know_list = list(map(int, input().split()))
know_cnt, know = know_list[0], know_list[1:]
parent = [i for i in range(N+1)]

party_cnt = 0
if not know_cnt:
    party_cnt = M
else:
    head = min(know)
    for num in know:
        parent[num] = head
    parties = []
    for _ in range(M):
        party_list = list(map(int, input().split()))
        party_people, party = party_list[0], party_list[1:]
        parties.append(party)
        for j in range(0, len(party) - 1):
            for k in range(j + 1, len(party)):
                union(party[j], party[k])

    true = []
    head_p = find(head)
    for i in range(1, N+1):
        if find(i) == head_p:
            true.append(i)
    for i in range(0, len(parties)):
        flag = True
        for j in range(0, len(parties[i])):
            if parties[i][j] in true:
                flag = False
                break
        if flag:
            party_cnt += 1
print(party_cnt)


while True:
    num1 = input("Введіть перше число (або 'quit' для виходу): ")
    if num1 == "quit":
        break

    operator = input("Введіть математичний оператор (+, -, *, /): ")
    if operator == "quit":
        break

    num2 = input("Введіть друге число (або 'quit' для виходу): ")
    if num2 == "quit":
        break

    num1 = float(num1)
    num2 = float(num2)

    if operator == "+":
        result = num1 + num2
    elif operator == "-":
        result = num1 - num2
    elif operator == "*":
        result = num1 * num2
    elif operator == "/":
        if num2 == 0:
            print("Ошыбка: нельзя делить на ноль ")
            continue
        result = num1 / num2
    else:
        print("неподдерживаемый оператор")
        continue

    print("Результат: ", result)


import requests
from datetime import timedelta
import datetime
import json
from time import sleep
import config
url = "https://app.najva.com/api/v1/notifications/"
#print(url)
currentDT = datetime.datetime.now()
now_plus_10s=currentDT+timedelta(seconds=+10)
now = now_plus_10s.strftime("%Y-%m-%dT%H:%M:%SZ")
#print(currentDT)
#print(now_plus_10s)
#time = datetime.datetime.now() + timedelta(minutes=10) # this time is an example. replace it with your own time.
#print(time)
#print("+++++++++++++")
#print(now_plus_5m.strftime("%Y/%m/%d - %H:%M:%S"))
symbol='BNBUSDT'
price =270
data={
  "api_key":config.apikey,
    "title":symbol,
    "body":f"{symbol} Triggered on {price}",
    "onclick_action":"open-link",
    "url":f"https://www.binance.com/en/trade/{symbol}?layout=pro",
    "content":f"{symbol} Price : {price}",
    # "content":"image should be ۳۶۰×۷۲۰ or 720x300",
    "icon":"https://cdn.jsdelivr.net/gh/atomiclabs/cryptocurrency-icons@9ab8d6934b83a4aa8ae5e8711609a70ca0ab1b2b/128/icon/bnb.png",
    # "image":"https://cdn.jsdelivr.net/gh/atomiclabs/cryptocurrency-icons@9ab8d6934b83a4aa8ae5e8711609a70ca0ab1b2b/128/icon/bnb.png",
    "sent_time": now ,
    "one_signal_enabled":"false"
}
#print(data)
payload = json.dumps(data)
headers = {
    'authorization': f"Token {config.token}",
    'content-type': "application/json",
    'cache-control': "no-cache",
    }

response = requests.request("POST", url, data=payload, headers=headers)
print(response.json())
#print(response.text)


from typing import List

from .common import c_enum_const, c_name, mcgen
from .gen import QAPISchemaModularCVisitor, build_params, ifcontext
from .schema import (
    QAPISchema,
    QAPISchemaEnumMember,
    QAPISchemaFeature,
    QAPISchemaObjectType,
)
from .source import QAPISourceInfo
from .types import gen_enum, gen_enum_lookup

def build_handler_name(name: str) -> str:
    return 'qapi_%s_handler' % name.lower()

def build_event_handler_proto(name: str,
                              arg_type: QAPISchemaObjectType,
                              boxed: bool) -> str:
    return 'typedef void (*%(handler)s)(%(param)s)' % {
        'handler': build_handler_name(name),
        'param': build_params(arg_type, boxed, extra='void *ctx')}

def gen_event_dispatch_decl(name: str,
                            arg_type: QAPISchemaObjectType,
                            boxed: bool) -> str:
    return mcgen('''

%(proto)s;
void qapi_event_dispatch_%(name)s(%(handler_type)s handler, CFDictionaryRef data, void *ctx);
''',
                 proto=build_event_handler_proto(name, arg_type, boxed),
                 name=name,
                 handler_type=build_handler_name(name))

# Calling the handler
def gen_call_handler(typ: QAPISchemaObjectType) -> str:
    if typ:
        assert not typ.variants
        ret = ''
        sep = ''
        for memb in typ.members:
            ret += sep
            sep = ', '
            if memb.optional:
                ret += 'arg->has_' + c_name(memb.name) + sep
            ret += 'arg->' + c_name(memb.name)
        ret += sep + 'ctx'
        return ret
    else:
        return 'ctx'

def gen_event_dispatch(name: str,
                       arg_type: QAPISchemaObjectType,
                       boxed: bool,
                       event_enum_name: str,
                       event_dispatch: str) -> str:
    # FIXME: Our declaration of local variables (and of 'errp' in the
    # parameter list) can collide with exploded members of the event's
    # data type passed in as parameters.  If this collision ever hits in
    # practice, we can rename our local variables with a leading _ prefix,
    # or split the code into a wrapper function that creates a boxed
    # 'param' object then calls another to do the real work.
    have_args = boxed or (arg_type and not arg_type.is_empty())
    ret = mcgen('''

void qapi_event_dispatch_%(name)s(%(handler_type)s handler, CFDictionaryRef data, void *ctx)
{
''',
                name=name, handler_type=build_handler_name(name))

    if have_args:
        ret += mcgen('''
    %(c_name)s *arg;
    Visitor *v;
''',
                    c_name=arg_type.c_name())

    if have_args:
        ret += mcgen('''
    v = cf_input_visitor_new(data);
''')
        ret += mcgen('''
    visit_start_struct(v, "event", NULL, 0, &error_abort);
    visit_type_%(c_name)s(v, "data", &arg, &error_abort);
    visit_end_struct(v, NULL);
''',
                         name=name, c_name=arg_type.c_name())

    ret += mcgen('''
    handler(%(param)s);

''',
                 param='arg' if boxed else gen_call_handler(arg_type))

    if have_args:
        ret += mcgen('''
    visit_free(v);
    v = qapi_dealloc_visitor_new();
    visit_type_%(c_name)s(v, "unused", &arg, NULL);
    visit_free(v);
''',
                c_name=arg_type.c_name())
    ret += mcgen('''
}
''')
    return ret

def gen_dispatcher_proto(name: str) -> str:
    return mcgen('''

void %(name)s(const char *event, CFDictionaryRef data, void *ctx);
''',
                name=name)

def gen_dispatcher(name: str,
                   event_enum_name: str,
                   events) -> str:
    ret = mcgen('''

void %(name)s(const char *event, CFDictionaryRef data, void *ctx)
{
    %(event_enum)s num;

    num = (%(event_enum)s)qapi_enum_parse(&%(event_enum)s_lookup, event, 0, &error_abort);
    switch (num) {
        default:
            assert(0);
            break;
''',
                event_enum=event_enum_name, name=name)

    for event in events:
        ret += event[0].gen_if()
        ret += mcgen('''
        case %(enum_name)s:
            if (qapi_enum_handler_registry_data.%(handler_name)s) {
                %(event_name)s(qapi_enum_handler_registry_data.%(handler_name)s, data, ctx);
            }
            break;
''',
                enum_name=event[1], event_name=event[2], handler_name=event[3])
        ret += event[0].gen_endif()

    ret += mcgen('''
    }
}
''')
    return ret

def gen_registry(events) -> str:
    ret = mcgen('''

typedef struct {
''')

    for event in events:
        ret += event[0].gen_if()
        ret += mcgen('''
    %(handler_name)s %(handler_name)s;
''',
                handler_name=event[3])
        ret += event[0].gen_endif()

    ret += mcgen('''
} qapi_enum_handler_registry;

extern qapi_enum_handler_registry qapi_enum_handler_registry_data;
''')
    return ret

class QAPISchemaGenEventVisitor(QAPISchemaModularCVisitor):

    def __init__(self, prefix: str):
        super().__init__(
            prefix, 'qapi-events',
            ' * Schema-defined QAPI/QMP events', None, __doc__)
        self._event_enum_name = c_name(prefix + 'QAPIEvent', protect=False)
        self._event_registry = []
        self._event_enum_members: List[QAPISchemaEnumMember] = []
        self._event_dispatch_name = c_name(prefix + 'qapi_event_dispatch')

    def _begin_user_module(self, name: str) -> None:
        events = self._module_basename('qapi-events', name)
        types = self._module_basename('qapi-types', name)
        visit = self._module_basename('qapi-visit', name)
        self._genc.add(mcgen('''
#include "qemu-compat.h"
#include "%(prefix)sqapi-emit-events.h"
#include "%(events)s.h"
#include "%(visit)s.h"
#include "error.h"
#include "cf-input-visitor.h"
#include "dealloc-visitor.h"

''',
                             events=events, visit=visit,
                             prefix=self._prefix))
        self._genh.add(mcgen('''
#include "util.h"
#include "%(types)s.h"
''',
                             types=types))

    def visit_end(self) -> None:
        self._add_module('./emit', ' * QAPI Events emission')
        self._genc.preamble_add(mcgen('''
#include "qemu-compat.h"
#include "%(prefix)sqapi-emit-events.h"
#include "error.h"
''',
                                      prefix=self._prefix))
        self._genh.preamble_add(mcgen('''
#include "qapi-events.h"
#include "util.h"
'''))
        self._genh.add(gen_enum(self._event_enum_name,
                                self._event_enum_members))
        self._genc.add(gen_enum_lookup(self._event_enum_name,
                                       self._event_enum_members))
        self._genh.add(gen_registry(self._event_registry))
        self._genh.add(gen_dispatcher_proto(self._event_dispatch_name))
        self._genc.add(gen_dispatcher(self._event_dispatch_name,
                                      self._event_enum_name,
                                      self._event_registry))

    def visit_event(self,
                    name: str,
                    info: QAPISourceInfo,
                    ifcond: List[str],
                    features: List[QAPISchemaFeature],
                    arg_type: QAPISchemaObjectType,
                    boxed: bool) -> None:
        with ifcontext(ifcond, self._genh, self._genc):
            self._genh.add(gen_event_dispatch_decl(name, arg_type, boxed))
            self._genc.add(gen_event_dispatch(name, arg_type, boxed,
                                          self._event_enum_name,
                                          self._event_dispatch_name))
            self._event_registry.append((ifcond, c_enum_const(self._event_enum_name, name), 'qapi_event_dispatch_%s' % name, build_handler_name(name)))
        # Note: we generate the enum member regardless of @ifcond, to
        # keep the enumeration usable in target-independent code.
        self._event_enum_members.append(QAPISchemaEnumMember(name, None))

def gen_events(schema: QAPISchema,
               output_dir: str,
               prefix: str) -> None:
    vis = QAPISchemaGenEventVisitor(prefix)
    schema.visit(vis)
    vis.write(output_dir)


import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

def data_init():
    spreadsheet_file = pd.ExcelFile('data.xlsx')
    worksheets = spreadsheet_file.sheet_names
    island_coordinates = []
    island_numbers = []
    locationDF = pd.read_excel('data.xlsx', sheet_name="Locations", header=None, skiprows=1)
    for index, row in locationDF.iterrows():
        island_coordinates.append([row[1], row[2]])
        island_numbers.append(row[0])
    return [island_numbers, island_coordinates]

def storm_init():
    storms = []
    stormDF = pd.read_excel('data.xlsx', sheet_name="Storms", header=None, skiprows=2)
    for index, row in stormDF.iterrows():
        storms.append([row[0], row[1], row[2]])
    return storms

def main():
    island_numbers, island_coordinates = data_init()
    storms = storm_init()
    #optimum_route = [1, 23, 6, 4, 22, 13, 2, 3, 5, 28, 20, 11, 18, 16, 24, 30, 21, 15, 27, 12, 19, 8, 29, 9, 10, 25, 26, 17, 14, 7, 1]
    #optimum_route = [1, 23, 13, 28, 6, 4, 22, 2, 3, 5, 20, 11, 18, 16, 24, 30, 21, 15, 27, 12, 19, 8, 29, 9, 10, 25, 26, 17, 14, 7, 1]
    optimum_route = [1, 23, 13, 2, 22, 5, 3, 4, 6, 28, 18, 24, 16, 11, 20, 10, 9, 29, 8, 19, 12, 27, 15, 30, 21, 26, 25, 17, 14, 7, 1]
    data = np.array(island_coordinates)
    x, y = data.T
    plt.scatter(x, y)

    for i in range(len(island_coordinates)):
        x = island_coordinates[i][0]
        y = island_coordinates[i][1]
        plt.plot(x, y, 'bo')
        plt.text(x * (1 + 0.01), y * (1 + 0.01), i + 1, fontsize=12)

    for i in range(len(island_coordinates) - 1):
        # i = 0 .... n-1
        plt.plot([island_coordinates[optimum_route[i] - 1][0], island_coordinates[optimum_route[i+1] - 1][0]],
                 [island_coordinates[optimum_route[i] - 1][1], island_coordinates[optimum_route[i+1] - 1][1]], 'green', linestyle=':', marker='')

    for i in range(len(storms)):
        x = storms[i][0]
        y = storms[i][1]
        r = storms[i][2]
        circle1 = plt.Circle((x, y), r, color='r', alpha=0.3, fill=False, label="storm:" + str(i + 1))
        label = plt.annotate(i + 1, xy=(x, y), fontsize=12,
                            verticalalignment='center', horizontalalignment='center')
        plt.gcf().gca().add_artist(circle1)

    plt.gca().set_aspect('equal', adjustable='box')
    plt.draw()

    plt.show()
    plt.savefig('plot.png', dpi=100)

if __name__ == '__main__':
    main()


csv = open("csv_data.txt", "r")
lines = csv.readlines()
csv.close()

lines = [line.strip() for line in lines[1:]]

print(lines)

for line in lines:
    person_data = line.split(',')
    name = person_data[0].title()
    age = person_data[1]
    university = person_data[2].capitalize()
    degree = person_data[3].title()

    print(f"{name} is {age} studying {degree} at {university}")

list_name = ['Matt', '30', 'OSU', 'Computer Science']
sampleValue = ','.join(list_name)
print(sampleValue)
csv = open("csv_data.txt", "a")
csv.write(sampleValue)
csv.close()


import sgtk
import datetime
from sgtk.platform.qt import QtGui, QtCore
from tank_vendor import six
from .label_base_widget import LabelBaseWidget
from .shotgun_field_meta import ShotgunFieldMeta

shotgun_globals = sgtk.platform.import_framework(
    "tk-framework-shotgunutils", "shotgun_globals"
)

@six.add_metaclass(ShotgunFieldMeta)
class DateAndTimeWidget(LabelBaseWidget):
    """
    Display a ``date_time`` field value as returned by the Shotgun API.
    """

    _DISPLAY_TYPE = "date_time"

    def _display_value(self, value):
        """
        Set the value displayed by the widget.

        :param value: The value returned by the Shotgun API to be displayed
        """
        self.setText(self._string_value(value))
        self.setToolTip(self._tooltip_value(value, postfix=" %I:%M%p"))

    def _ensure_datetime(self, value):
        """
        Ensures the supplied value is a python datetime object.
        """

        # shotgun_model converts datetimes to floats representing unix time so
        # handle that as a valid value as well
        if not isinstance(value, datetime.datetime):
            value = datetime.datetime.fromtimestamp(value)
        return value

    def _string_value(self, value):
        """
        Convert the Shotgun value for this field into a string

        :param value: The value to convert into a string
        :type value: :class:`datetime.datetime` or a float representing unix time
        """
        dt = self._ensure_datetime(value)

        # return a human readable time format. The postfix formatter used here
        # is '%I:%M%p' which is:
        #
        #   %I = Hour (12-hour clock) as a decimal number [01,12]
        #   %M = Minute as a decimal number [00,59]
        #   %p = Locale's equivalent of either AM or PM
        #
        # resulting in a value like: 01:37AM
        return shotgun_globals.create_human_readable_timestamp(dt, postfix=" %I:%M%p")

    def _tooltip_value(self, value, postfix=""):
        """
        Convert the Shotgun value for this field into a tooltip string

        :param value: The value to convert into a string
        :type value: :class:`datetime.datetime` or a float representing unix time
        """
        dt = self._ensure_datetime(value)
        return dt.strftime("%x" + postfix)

@six.add_metaclass(ShotgunFieldMeta)
class DateAndTimeEditorWidget(QtGui.QDateTimeEdit):
    """
    Allows editing of a ``date_time`` field value as returned by the Shotgun API.

    Pressing ``Enter`` or ``Return`` when the widget has focus will cause the
    value to be applied and the ``value_changed`` signal to be emitted.
    """

    _EDITOR_TYPE = "date_time"

    # minimum width just to prevent the widget from being too squished
    _MINIMUM_WIDTH = 100

    def get_value(self):
        """
        :return: The internal value being displayed by the widget.
        """
        value = self.dateTime()

        try:
            # pyside
            return value.toPython()
        except AttributeError:
            # pyqt
            return value.toPyDateTime()

    def keyPressEvent(self, event):
        """
        Provides shortcuts for applying modified values.

        :param event: The key press event object
        :type event: :class:`~PySide.QtGui.QKeyEvent`
        """

        if event.key() in [QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return]:
            self.value_changed.emit()
        else:
            super(DateAndTimeEditorWidget, self).keyPressEvent(event)

    def setup_widget(self):
        """
        Prepare the widget for display.

        Called by the metaclass during initialization.
        """
        self.setCalendarPopup(True)
        self.setMinimumWidth(self._MINIMUM_WIDTH)

    def _display_default(self):
        """
        Display the default value of the widget.
        """
        self.clear()

    def _display_value(self, value):
        """
        Set the value displayed by the widget.

        :param value: The value returned by the Shotgun API to be displayed
        """
        # shotgun_model converts datetimes to floats representing unix time so
        # handle that as a valid value as well
        if not isinstance(value, datetime.datetime):
            value = datetime.datetime.fromtimestamp(value)
        self.setDateTime(value)


import gym
import minihack  # pylint: disable=unused-import
import nle  # pylint: disable=unused-import
from minihack.scripts.env_list import skip_envs_list

from nle_language_wrapper import NLELanguageWrapper

def main(nethack_env_name):
    """
    Play a NLE based environment using the nle-language-wrapper.
    """
    env = NLELanguageWrapper(
        gym.make(
            nethack_env_name,
            observation_keys=[
                "glyphs",
                "blstats",
                "tty_chars",
                "inv_letters",
                "inv_strs",
                "tty_cursor",
                "tty_colors",
            ],
        )
    )
    obsv = env.reset()
    total_reward = 0.0
    shown_help = False
    done = False

    while True:
        output = ""
        output += f"Inventory:\n{obsv['text_inventory']}\n\n"
        output += f"Stats:\n{obsv['text_blstats']}\n\n"
        output += f"Cursor:{obsv['text_cursor']}\n\n"
        output += f"Observation:\n{obsv['text_glyphs']}\n\n"
        output += f"Message:\n{obsv['text_message']}"
        if output[-1] != "\n":
            output += "\n"
        print(output)
        print("------")
        if done:
            return total_reward
        valid_action = False
        while not valid_action:
            if not shown_help:
                print(
                    'Type "instructions" anytime to see '
                    "the instructions on how to play"
                )
                print(
                    'Type "actions" anytime to see valid actions '
                    "for the current environment"
                )
                print('Type "render" anytime to render the nle environment')
                shown_help = True
            action = input("Action: ")
            if action == "actions":
                print("")
                print("Actions")
                max_key_len = max(
                    len(repr(k)) for k, _ in env.action_str_enum_map.items()
                )
                for action_str, nle_action_enum in env.action_str_enum_map.items():
                    key_str = f"{repr(action_str)}"
                    print(
                        key_str
                        + (max_key_len - len(key_str)) * " "
                        + f":{str(nle_action_enum)}"
                    )
                print("")
                continue
            if action == "instructions":
                print("")
                print("Instructions")
                print(
                    "To play, write a text action at the prompt, "
                    'e.g "north" will move you north.'
                )
                print(
                    "For the complete list of actions supported "
                    'in the current environment type "actions"'
                )
                print('To render the current display type "render"')
                print("")
                continue
            if action == ("render"):
                env.render()
                continue
            try:
                (
                    obsv,
                    reward,
                    done,
                    _,
                ) = env.step(action)
                total_reward += reward
                valid_action = True
            except ValueError as exception:
                print(exception)
    return total_reward

if __name__ == "__main__":
    while True:
        nle_env_names = [
            env_spec.id
            for env_spec in gym.envs.registry.all()
            if "MiniHack" in env_spec.id and env_spec.id not in skip_envs_list
        ]
        nle_env_names.append("NetHackChallenge-v0")
        for i, env_name in enumerate(nle_env_names):
            print(f"{i}: {env_name}")
        selected_name = int(
            input(
                f"Which base env would you like to use [0-{len(nle_env_names) - 1}]? "
            )
        )
        nle_env_name = nle_env_names[selected_name]
        total_reward = main(nle_env_name)
        print("Done!")
        print(f"Total Reward: {total_reward}")
        if input("Play again? [y,n]:") != "y":
            break


import cufflinks as cf
cf.go_offline()
cf.set_config_file(offline=False, world_readable=True)
import torch
import numpy as np
from Utils import *

def train_step(x ,y, model, loss_fn, optimizer):
# Sets model to train mode
    model.train()

    # Makes predictions
    ypred = model(x)

    # Computes loss
    loss = loss_fn(y, ypred)

    # Computes gradients
    loss.backward()

    # Updates parameters and zeroes gradients
    optimizer.step()
    optimizer.zero_grad()

    # Returns the loss
    return loss.item()

def fit_train(n_epochs, train_dl, valid_dl, model, loss_function, optimizer, batch_size, input_dim):
    train_losses = []
    val_losses = []
    device = "cuda" if torch.cuda.is_available() else "cpu" # check if cuda available.
    print("Training is starting...")
    for epoch in range(1, n_epochs + 1):

        batch_losses = []
        for x_batch, y_batch in train_dl:
            x_batch = x_batch.view([batch_size, -1, input_dim]).to(device)
            y_batch = y_batch.to(device)
            # use train step to train the model
            loss = train_step(x_batch, y_batch, model=model, loss_fn=loss_function, optimizer=optimizer)
            batch_losses.append(loss)
        # append losses to global variables
        training_loss = np.mean(batch_losses)
        train_losses.append(training_loss)

        # check if validation set is available
        if valid_dl is not None:

            with torch.no_grad():
                batch_val_losses = []
                for x_val, y_val in valid_dl:
                    # model in evaluation mode
                    model.eval()
                    x_val = x_val.view([batch_size, -1, input_dim]).to(device)
                    y_val = y_val.to(device)
                    # make prediction
                    yhat = model(x_val)
                    val_loss = loss_function(y_val, yhat).item()
                    batch_val_losses.append(val_loss)

                # vallid global losses
                validation_loss = np.mean(batch_val_losses)
                val_losses.append(validation_loss)

            if (epoch <= 10) | (epoch % 50 == 0):
                # if validation available print all
                print(
                    f"[{epoch}/{n_epochs}] Training loss: {training_loss:.4f}\t Validation loss: {validation_loss:.4f}")
        else:
            # print only train loss if no validation available
            print(f"[{epoch}/{n_epochs}] Training loss: {training_loss:.4f}")
    return [train_losses, val_losses]

def test_fit(model, test_dl_one, input_dim):
    batch_size = 1
    device = "cuda" if torch.cuda.is_available() else "cpu"  # check if cuda available.
    with torch.no_grad():
        predictions = []
        values = []
        for x_test, y_test in test_dl_one:
            # reshape
            x_test = x_test.view([batch_size, -1, input_dim]).to(device)
            y_test = y_test.to(device)

            model.eval()
            # make prediction in evaluation mode the model
            yhat = model(x_test)
            predictions.append(yhat.to(device).detach().numpy())
            values.append(y_test.to(device).detach().numpy())
    return predictions, values


import pandas as pd
import transformers
from transformers import BertModel, BertTokenizer
import torch
from torch import nn, optim
from torch.utils.data import Dataset, DataLoader
from torch.optim.lr_scheduler import LambdaLR

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
def preprocess_data(df):
    print("Preprocessing data...")
    encoded_reviews = tokenizer(
        df['text'].tolist(),
        add_special_tokens=True,
        max_length=128,
        padding='max_length',
        truncation=True,
        return_attention_mask=True,
        return_tensors='pt'
    )
    input_ids = encoded_reviews['input_ids']
    print(input_ids.shape)
    attention_masks = encoded_reviews['attention_mask']
    print(attention_masks.shape)
    labels = torch.tensor(df['label'].values)
    print(labels.shape)
    return input_ids, attention_masks, labels

class AmazonReviewDataset(Dataset):
    def __init__(self, input_ids, attention_masks, labels):
        self.input_ids = input_ids
        self.attention_mask = attention_masks
        self.labels = labels

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

    def __getitem__(self, idx):
        return {
            'input_ids': self.input_ids[idx],
            'attention_mask': self.attention_mask[idx],
            'labels': self.labels[idx]
        }


from dbs.DbConnection import DbConnection

def insert_sample_data():

    db = DbConnection().db
    cursor = db.cursor()

    expenses = [
        ("food", "bread", 5),
        ("transport", "fuel", 200),
        ("food", "apples", 7),
        ("kids", "toys", 70),
        ("transport", "bus", 3.5)
    ]

    cursor.executemany("INSERT INTO expenses (category, name, amount) VALUES (?, ?, ?)", expenses)

    income = [
        ("Anna", "project", 500),
        ("Tom", "salary", 3000),
        ("Anna", "salary", 3000)
    ]

    cursor.executemany("INSERT INTO income (category, name, amount) VALUES (?, ?, ?)", income)

    db.commit()
    db.close()

    print("Data has been added.")

if __name__ == '__main__':
    insert_sample_data()


## Question no.3 to find height ##
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def height(root):
    if root is None:
        return 0
    leftAns = height(root.left)
    rightAns = height(root.right)
    return max(leftAns, rightAns) + 1

root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)

print("Height of the binary tree is: " + str(height(root)))

## Question no.4 to find no. of nodes ##

class node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key

def left_height(node):
    ht = 0
    while(node):
        ht += 1
        node = node.left
    return ht

def right_height(node):
    ht = 0
    while(node):
        ht += 1
        node = node.right
    return ht

def TotalNodes(root):

    if(root == None):
        return 0

    lh = left_height(root)
    rh = right_height(root)

    if(lh == rh):
        return (1 << lh) - 1
    return 1 + TotalNodes(root.left) + TotalNodes(root.right)

root = node(1)
root.left = node(2)
root.right = node(3)
root.left.left = node(4)
root.left.right = node(5)
root.right.left = node(9)
root.right.right = node(8)
root.left.left.left = node(6)
root.left.left.right = node(7)

print(TotalNodes(root))

## Question no.5 to list all leave nodes ##
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def printLeafNodes(root: Node) -> None:
    if (not root):
        return
    if (not root.left and
        not root.right):
        print(root.data,
              end = " ")
        return

    if root.left:
        printLeafNodes(root.left)

    if root.right:
        printLeafNodes(root.right)

if __name__ == "__main__":

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.left.left = Node(4)
    root.right.left = Node(5)
    root.right.right = Node(8)
    root.right.left.left = Node(6)
    root.right.left.right = Node(7)
    root.right.right.left = Node(9)
    root.right.right.right = Node(10)

    printLeafNodes(root)

#

DS&A (Data Structures & Algorithms)/HW: Binary Algorithms.py


#! cd .. && python -m demo.echoclient

from mpgameserver import UdpClient, Timer
import time
import sys

def main():  # pragma: no cover

    addr = ('localhost', 1474)

    # the duration of each 'frame'
    interval = 1/30

    def send_message():
        if client.connected():
            client.conn.send(b"hello")

    def onConnect(connected):
        if not connected:
            print("unable to connect to server")
            sys.exit(1)

    client = UdpClient()
    client.connect(addr, callback=onConnect)
    timer = Timer(.5, send_message)

    try:
        while True:
            timer.update(interval)
            client.update()

            for seqnum, msg in client.getMessages():
                print("received: %r" % msg, "Latency: %dms" % int(1000*client.latency()))
            time.sleep(interval)
    except KeyboardInterrupt as e:
        pass

    client.disconnect()
    client.waitForDisconnect()

if __name__ == '__main__':
    main()


""" Conversation class for MySpaceIM

    Nothing special here except for 'zap' functionality - a zap is an action that can be sent from one user to another.
    """
import logging
import common
import util.callbacks as callbacks
log = logging.getLogger('msim.conversation')

class Zap(object):

    @property
    def name(self):
        raise NotImplementedError

    def received(self, from_who):
        raise NotImplementedError

    def sent(self, to_who):
        raise NotImplementedError

    def nice_name(self):
        raise NotImplementedError

class BasicZap(Zap):

    name = None

    def received(self, from_who):
        return self.recv_msg.format(name=from_who)

    def sent(self, to_who):
        return self.sent_msg.format(name=to_who)

    def nice_name(self):
        return self.nice_name

class ZapZap(BasicZap):

    name = u'zap'
    recv_msg = _(u'{name} zapped you')
    sent_msg = _(u'You zapped {name}')
    nice_name = _(u'Zap')

class ZapWhack(BasicZap):

    name = u'whack'
    recv_msg = _(u'{name} whacked you')
    sent_msg = _(u'You whacked {name}')
    nice_name = _(u'Whack')

class ZapTorch(BasicZap):

    name = u'torch'
    recv_msg = _(u'{name} torched you')
    sent_msg = _(u'You torched {name}')
    nice_name = _(u'Torch')

class ZapSmooch(BasicZap):

    name = u'smooch'
    recv_msg = _(u'{name} smooched you')
    sent_msg = _(u'You smooched {name}')
    nice_name = _(u'Smooch')

class ZapSlap(BasicZap):

    name = u'bslap'
    recv_msg = _(u'{name} slapped you')
    sent_msg = _(u'You slapped {name}')
    nice_name = _(u'Slap')

class ZapGoose(BasicZap):

    name = u'goose'
    recv_msg = _(u'{name} goosed you')
    sent_msg = _(u'You goosed {name}')
    nice_name = _(u'Goose')

class ZapHiFive(BasicZap):

    name = u'hi-five'
    recv_msg = _(u'{name} high-fived you')
    sent_msg = _(u'You high-fived {name}')
    nice_name = _(u'High-Five')

class ZapPunk(BasicZap):

    name = u'punk\'d'
    recv_msg = _(u'{name} punk\'d you')
    sent_msg = _(u'You punk\'d {name}')
    nice_name = _(u'Punk')

class ZapRaspberry(BasicZap):

    name = u'raspberry'
    recv_msg = _(u'{name} raspberry\'d you')
    sent_msg = _(u'You raspberry\'d {name}')
    nice_name = _(u'Raspberry')

AllZapTypes = [
               ZapZap,
               ZapWhack,
               ZapTorch,
               ZapSmooch,
               ZapSlap,
               ZapGoose,
               ZapHiFive,
               ZapPunk,
               ZapRaspberry,
               ]

_zaps = dict((z.name, z) for z in (Z() for Z in AllZapTypes))

def zap_sent_text(zapname, to_who):
    z = _zaps.get(zapname)
    if z is None:
        return u''
    else:
        return z.sent(to_who)

def zap_received_text(zapname, from_who):
    z = _zaps.get(zapname)
    if z is None:
        return u''
    else:
        return z.received(from_who)

class MSIMConversation(common.Conversation):

    ischat = False

    def __init__(self, protocol, contact_id):
        common.Conversation.__init__(self, protocol)
        self.contact_id = contact_id
        self.buddy_join(self.contact)

    def __repr__(self):
        return '<%s for contact %r>' % (type(self).__name__, self.contact_id)

    @property
    def self_buddy(self):
        return self.protocol.self_buddy

    @property
    def contact(self):
        return self.protocol.get_buddy(self.contact_id)

    @property
    def buddy(self):
        return self.contact

    @property
    def name(self):
        return self.buddy.alias

    def send_typing_status(self, status):
        self.protocol.send_typing(who=self.buddy.id, typing=status == 'typing')

    def received_typing(self, buddy, typing):
        self.typing_status[buddy] = ('typing' if typing else None)

    @callbacks.callsback
    def _send_message(self, message, callback=None, **k):

        self.protocol.send_message(self.contact, message.format_as('msim'), callback=callback, **k)

    def buddy_join(self, buddy):
        self.room_list.append(buddy)
        self.typing_status[buddy] = None

    def received_group_message(self, group_id, actor_id, msg_text):

        self.ischat = True
        self.group_id = group_id
        if actor_id is None:
            self.process_system_message(msg_text)
        else:
            buddy = self.protocol.get_buddy(actor_id)
            if buddy is None:
                buddy = self.buddy
            log.info('Group message from %r', buddy)
            self.received_message(buddy, msg_text)

    def process_system_message(self, text):
        log.info('Got chat system message: %r', text)

    def received_message(self, buddy, message):
        if isinstance(message, bytes):
            message = message.decode('utf8')
        common.Conversation.received_message(self, buddy, message, content_type='text/html')
        self.typing_status[buddy] = None

    def received_zap(self, buddy, zaptxt):
        self.system_message(zap_received_text(zaptxt, buddy.alias))

    def exit(self):
        if getattr(self, 'ischat', False):
            self.protocol.send_exitchat(self.contact_id, self.group_id)
        common.Conversation.exit(self)


import numpy as np

# np.set_printoptions(threshold=np.inf)

BLOCK_SIZE = 8
LOW_FREQUENCY_THRESHOLD = 9
ELEMENTS_PER_BIN = 42000

def _build_frequency_map():
    m = np.zeros((BLOCK_SIZE, BLOCK_SIZE), dtype=bool)
    for i in range(BLOCK_SIZE):
        for j in range(BLOCK_SIZE):
            m[i, j] = i + j != 0 and i + j < LOW_FREQUENCY_THRESHOLD
    return m

LOW_FREQUENCY_MAP = _build_frequency_map()


from django.urls import path
from api_doc import views

urlpatterns = [
    path('getAllSportSection/', views.getAllSportSection),
    path('getSportSectionById/<int:pk>', views.getSportSectionById),
    path('getSportSectionType/', views.getSportSectionType),
    path('getSportSectionByTypeId/<int:pk>', views.getSportSectionByTypeId),
    # path('deleteSportSection/<int:pk>', views.deleteSportSection),
    # path('updateSportSection/', views.SportSection.updateSportSection),
]


#User function Template for python3
from collections import defaultdict
from collections import deque
class Solution:
    def findOrder(self,alien_dict, N, K):
    # code here
        incoming = defaultdict(int)
        graph = defaultdict(list)
        queue = deque()
        for i in range(N-1):
            other = self.setOrder(alien_dict[i],alien_dict[i+1],graph)
            if other:
                incoming[other] += 1

        for i in range(K):
            if chr(97+i) not in incoming:
                queue.append(chr(97+i))

        result = ""
        while queue:
            letter = queue.popleft()
            result += letter

            for nbr in graph[letter]:
                incoming[nbr] -= 1

                if incoming[nbr] == 0:
                    queue.append(nbr)

        return result

    def setOrder(self,word1,word2,graph):
        size1,size2 = len(word1),len(word2)
        for i in range(min(size2,size1)):
            if word1[i] != word2[i]:
                graph[word1[i]].append(word2[i])
                return word2[i]
        # if word1 == word2[:size1]:
        #     if size2 > size1 and word2[size1] != word1[-1]:
        #         graph[word1[-1]].append(word2[size1])
        #         return word2[size1]
        return None

#{
 # Driver Code Starts
#Initial Template for Python 3

class sort_by_order:
    def __init__(self,s):
        self.priority = {}
        for i in range(len(s)):
            self.priority[s[i]] = i

    def transform(self,word):
        new_word = ''
        for c in word:
            new_word += chr( ord('a') + self.priority[c] )
        return new_word

    def sort_this_list(self,lst):
        lst.sort(key = self.transform)

if __name__ == '__main__':
    t=int(input())
    for _ in range(t):
        line=input().strip().split()
        n=int(line[0])
        k=int(line[1])

        alien_dict = [x for x in input().strip().split()]
        duplicate_dict = alien_dict.copy()
        ob=Solution()
        order = ob.findOrder(alien_dict,n,k)
        s = ""
        for i in range(k):
            s += chr(97+i)
        l = list(order)
        l.sort()
        l = "".join(l)
        if s != l:
            print(0)
        else:
            x = sort_by_order(order)
            x.sort_this_list(duplicate_dict)

            if duplicate_dict == alien_dict:
                print(1)
            else:
                print(0)

# } Driver Code Ends


#!/usr/bin/env python3
#
#	Simplifying SQLite access
#
#	2012-12-14	Created by Pascal Pfiffner
#

import sqlite3
import threading

SQLITE_INSTANCES = {}

class SQLite(object):
	""" SQLite access
	"""

	@classmethod
	def get(cls, database):
		""" Use this to get SQLite instances for a given database. Avoids
		creating multiple instances for the same database.

		We keep instances around per thread per database, maybe there should be
		a way to turn this off. However, here we always release instances for
		threads that are no longer alive. If this is better than just always
		creating a new instance should be tested.
		"""

		global SQLITE_INSTANCES

		# group per thread
		thread_id = threading.current_thread().ident
		if thread_id not in SQLITE_INSTANCES:
			SQLITE_INSTANCES[thread_id] = {}
		by_thread = SQLITE_INSTANCES[thread_id]

		# group per database
		if database not in by_thread:
			sql = SQLite(database)
			by_thread[database] = sql

		# free up memory for terminated threads
		clean = {}
		for alive in threading.enumerate():
			if alive.ident in SQLITE_INSTANCES:
				clean[alive.ident] = SQLITE_INSTANCES[alive.ident]
		SQLITE_INSTANCES = clean

		return by_thread[database]

	def __init__(self, database=None):
		if database is None:
			raise Exception('No database provided')

		self.database = database
		self.handle = None
		self.cursor = None

	def execute(self, sql, params=()):
		""" Executes an SQL command and returns the cursor.execute, which can
		be used as an iterator.
		Supply the params as tuple, i.e. (param,) and (param1, param2, ...)
		"""
		if not sql or 0 == len(sql):
			raise Exception('No SQL to execute')
		if not self.cursor:
			self.connect()

		return self.cursor.execute(sql, params)

	def executeInsert(self, sql, params=()):
		""" Executes an SQL command (should be INSERT OR REPLACE) and returns
		the last row id, 0 on failure.
		"""
		if self.execute(sql, params):
			return self.cursor.lastrowid if self.cursor.lastrowid else 0

		return 0

	def executeUpdate(self, sql, params=()):
		""" Executes an SQL command (should be UPDATE) and returns the number
		of affected rows.
		"""
		if self.execute(sql, params):
			return self.cursor.rowcount

		return 0

	def executeOne(self, sql, params):
		""" Returns the first row returned by executing the command
		"""
		self.execute(sql, params)
		return self.cursor.fetchone()

	def hasTable(self, table_name):
		""" Returns whether the given table exists. """
		sql = 'SELECT COUNT(*) FROM sqlite_master WHERE type="table" and name=?'
		ret = self.executeOne(sql, (table_name,))
		return True if ret and ret[0] > 0 else False

	def create(self, table_name, table_structure):
		""" Executes a CREATE TABLE IF NOT EXISTS query with the given structure.
		Input is NOT sanitized, watch it!
		"""
		create_query = 'CREATE TABLE IF NOT EXISTS %s %s' % (table_name, table_structure)
		self.execute(create_query)
		return True

	def commit(self):
		self.handle.commit()

	def rollback(self):
		self.handle.rollback()

	def connect(self):
		if self.cursor is not None:
			return

		self.handle = sqlite3.connect(self.database)
		self.cursor = self.handle.cursor()

	def close(self):
		if self.cursor is None:
			return

		self.handle.close()
		self.cursor = None
		self.handle = None