"""
Test the general functionality of Pysep
"""
from re import L
import pytest
import os
import yaml
from glob import glob
from pysep import Pysep, logger

@pytest.fixture
def config_file():
    """
    Test config file for a 2009 Anchorage earthquake
    """
    return "./test_data/test_config_anchorage.yaml"

@pytest.fixture
def test_pysep(config_file):
    """
    Test Pysep instance based on a Config file, gather event and StationXML
    """
    pysep = Pysep(config_file=config_file, log_level=None)
    pysep.load()
    pysep.check()
    pysep.c = pysep.get_client()
    pysep.event = pysep.get_event()
    pysep.inv = pysep.get_stations()

    return pysep

def test_get_client(test_pysep):
    """
    Simple check that we're looking at IRIS for our client
    """
    assert(test_pysep.c.base_url == "http://service.iris.edu")

def test_get_event(test_pysep):
    """
    Simple check that the event created by User parameters is right
    """
    assert(test_pysep.event.preferred_magnitude().mag == 4.6)

def test_get_inventory(test_pysep):
    """
    Check that the collected stations are correct
    :param test_pysep:
    :return:
    """
    inv = test_pysep.inv
    assert(len(inv.get_contents()["channels"]) == 9)
    assert(f"{inv[0].code}{inv[0][0].code}{inv[0][0][0].code}" == "AKATKABHE")

def test_get_waveform(test_pysep):
    """
    Get waveforms for a few test stations from IRIS
    :param test_pysep:
    :return:
    """
    st = test_pysep.get_waveforms()
    assert(len(st) == 11)
    assert(st[-1].get_id() == "YV.ALPI..BHZ")

def test_curtail_stations(test_pysep):
    """
    Exclude a station based on maximum distance getting exceeded
    """
    inv = test_pysep.curtail_stations()

    nsta_pre_curtail = len(test_pysep.inv.get_contents()["channels"])
    nsta_post_curtail = len(inv.get_contents()["channels"])

    assert(nsta_pre_curtail - nsta_post_curtail == 6)

def test_config_files_have_correct_parameters(tmpdir, test_pysep):
    """
    Check that all the config files have the correct parameters based on what
    PySEP writes to ensure that the config files are up to date with codebase
    """
    # Write a config file from the Pysep instance and read in the yaml file
    fid = os.path.join(tmpdir, "test_config.yaml")
    test_pysep.write_config(fid=fid)
    config = set(yaml.safe_load(open(fid)).keys())

    # Get the directory containing the example config files
    config_dir = "../configs/"

    # Iterate over all the yaml files in the directory
    for dir_ in glob(os.path.join(config_dir, "*")):
        if not os.path.isdir(dir_):
            continue
        for fid in glob(os.path.join(dir_, "*")):
            if not fid.endswith(".yaml"):
                continue
            with open(fid, "r") as f:
                config_check = set(yaml.safe_load(f).keys())
                assert(config.issubset(config_check)), \
                    f"Config file {fid} does not have the correct parameters"


import sys
from collections import deque

N, K = map(int, sys.stdin.readline().rstrip('\n').split(" "))
q = deque(range(1, N+1))
josephus_seq = []
while q:
    for _ in range(K-1):
        q.append(q.popleft())
    josephus_seq.append(q.popleft())

print(f"<{str(josephus_seq)[1:-1]}>")


import datetime
import enum

class AssignmentAppData:
    def __init__(self):
        self.categories = []
        self.finished = []
        self.preferences = {}

    def add_category(self, name, color="#FFFFFF"):
        category = Category(name, color)
        self.categories.append(category)

    def add_assignment(self, category_name, id, title, due_date, notes,
                       priority):
        assignment = Assignment(id, title, due_date, notes, priority)
        for category in self.categories:
            if category.name == category_name:
                category.add_assignment(assignment)

    def add_preference(self, name, value):
        self.preferences[name] = value

    def clear_all_data(self):
        self.categories = []
        self.finished = []

    def complete_assignment(self, assignment):
        for c in self.categories:
            for a in c.assignments:
                if a.id == assignment.id:
                    finished_assignment = FinishedAssignment(
                        assignment, datetime.datetime.now(), c.name)
                    self.finished.append(finished_assignment)
                    c.assignments.remove(assignment)
                    break

    def delete_assignment(self, assignment):
        for c in self.categories:
            for a in c.assignments:
                if a.id == assignment.id:
                    c.assignments.remove(assignment)
                    break

    def get_category_names(self):
        return [category.name for category in self.categories]

    def get_soonest_n_assignments(self, n):
        all_assignments_with_categories = []
        for category in self.categories:
            for assignment in category.assignments:
                all_assignments_with_categories.append(
                    (assignment, category.color))
        all_assignments_with_categories = sorted(
            all_assignments_with_categories, key=lambda x: x[0].due_date)
        return all_assignments_with_categories[:n]

    def __str__(self):
        string = ""
        string += "Categories:\n\n"
        for category in self.categories:
            string += category.name + ", " + category.color + "\n"
            string += str(category.assignments)
            string += "\n"
        # TODO add the other attributes here also
        return string

class Category:
    def __init__(self, name, color):
        self.name = name
        self.color = color
        self.assignments = []  # should be sorted newest to oldest date

    def add_assignment(self, assignment):
        self.assignments.append(assignment)
        self.assignments = sorted(self.assignments, key=lambda a: a.due_date)

class Assignment:
    def __init__(self, id, title, due_date, notes, priority):
        self.id = id  # unique
        self.title = title
        self.due_date = due_date
        self.notes = notes
        self.priority = priority

class FinishedAssignment:
    def __init__(self, assignment, finished_date, category):
        self.assignment = assignment
        self.finished_date = finished_date
        self.category = category

class Priority(enum.Enum):
    none = 0
    low = 1
    medium = 2
    high = 3


import numpy
import pandas
from matplotlib import pyplot as plt
from util import plot_answer_prob_curve, fit_linear_stan

column_names=["length_A", "length_B", "abs_difference_percent", "answer", "answer_correct", "duration"]
df = pandas.read_csv("data/rcg_test.csv", names=column_names)

df['difference_A_minus_B'] = df['length_A'] - df['length_B']
df['distance_min'] = df[['length_A', "length_B"]].min(axis=1)
df['difference_relative'] = df['difference_A_minus_B']/df['distance_min']
# print(df.head(3))

n_bins = 20
# ax = plot_answer_prob_curve(df, bins=n_bins); plt.show()

for rel_diff_range_param in [0.10]:
    df_filtered = df[(df['difference_relative'] < rel_diff_range_param).values * (df['difference_relative'] > -rel_diff_range_param).values]
    for frac in [0.01, 0.03, 0.1, 0.3, 1.0]:

        df_to_fit = df_filtered.sample(frac=frac)
        rdiffs = df_to_fit["difference_relative"].values
        answers = df_to_fit["answer"].values

        for n_iter in [1000, 10000]:
            print("-----------------------------------------------")
            print("Sampling using params", rel_diff_range_param, len(rdiffs), frac, n_iter)
            fit = fit_linear_stan(rdiffs, answers, verbose=False)
            x_intercept = fit.extract()['x_intercept']
            print("Results for rel_diff_range " + str(rel_diff_range_param))
            print("Precise values (5th perc., median, 95th perc.) for the x_intercept:", numpy.percentile(x_intercept, [5, 50, 95]))
            print("Error margin", numpy.percentile(x_intercept, 95) - numpy.percentile(x_intercept, 5))
            print("-----------------------------------------------")


import streamlit as st
import json
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
import requests
from streamlit_lottie import st_lottie

header =st.container()
dataset=st.container()
model_training=st.container()

def load_lottiefile(filepath: str):
    with open(filepath, "r") as f:
        return json.load(f)

def load_lottieurl(url: str):
    r = requests.get(url)
    if r.status_code != 200:
        return None
    return r.json()

lottie_coding = load_lottiefile("lottiefile.json")  # replace link to local lottie file
lottie_hello = load_lottieurl("https://assets3.lottiefiles.com/packages/lf20_atgvstog.json")

st_lottie(
    lottie_hello,
    speed=1,
    reverse=False,
    loop=True,
    quality="low", # medium ; high # canvas
    height=None,
    width=None,
    key=None,
)

@st.cache
def get_data():
    taxi_data=pd.read_csv(filename)
    return get_data

# Use local CSS
def local_css(file_name):
    with open(file_name) as f:
        st.markdown(f"", unsafe_allow_html=True)
local_css("style/style.css")

# Load Animation
animation_symbol = "❄"

st.markdown(
    f"""

{animation_symbol}

{animation_symbol}

{animation_symbol}

{animation_symbol}

{animation_symbol}

{animation_symbol}

{animation_symbol}

{animation_symbol}

{animation_symbol}

    """,
    unsafe_allow_html=True,
)

with header:
    st.title("Welcome to my awesome data science project")
    st.text('In this project I look into the transction of taxi in Ney York..... ')

with dataset:
    st.header("NYC taxi dataset")
    taxi_data=pd.read_csv('data/Taxi_data.csv')
    st.subheader("Pick-up Location ID distribution on the NYC dataset")
    pulocation_dict =pd.DataFrame(taxi_data['PULocationID'].value_counts()).head(50)
    st.bar_chart(pulocation_dict)

with model_training:
    st.header("Time to train the model")
    st.text("Here you get to choose the hyperparameters of the model and see how the performance changes!")

    sel_col, disp_col=st.columns(2)

    max_depth=sel_col.slider("What should be the max_depth of the model?", min_value=10, max_value=100, value=20, step=10)

    n_estimators = sel_col.selectbox("How many trees should there be?", options=[100,200,300,'No Limit'], index=0)

    sel_col.text("Here is a list of features in my data:")
    sel_col.write(taxi_data.columns)

    input_features =sel_col.text_input("Which features should be used as the input features?", "PULocationID")

    if n_estimators =="No Limit":
        regr = RandomForestRegressor(max_depth=max_depth)
    else:
        regr = RandomForestRegressor(max_depth=max_depth, n_estimators=n_estimators)

    X =taxi_data[[input_features]]
    y = taxi_data[['trip_distance']]

    regr.fit(X,y)
    prediction=regr.predict(y)

    disp_col.subheader("Mean absolute error of the model is:")
    disp_col.write(mean_absolute_error(y, prediction))

    disp_col.subheader("Mean squared error of the model is:")
    disp_col.write(mean_squared_error(y, prediction))

    disp_col.subheader("R squared score of the model is:")
    disp_col.write(r2_score(y, prediction))


import yaml
from bounds import BoundsExperiment
path="C:/Users/Shruti Jadon/Desktop/IndependentStudies/IS/SampleBounds/src/main/resources/"
with open(path+"config.yml") as f:
    list_doc = yaml.load(f)

distribution=["normal","uniform","exponential","beta","mix_gauss_2_sym_uni","mix_gauss_2_sym_multi","mix_gauss_2_nonsym_uni","mix_gauss_2_nonsym_multi","mix_gauss_4_sym_uni","mix_gauss_4_sym_multi","mix_gauss_4_nonsym_uni","mix_gauss_4_nonsym_multi","student_t_3","student_t_5","double_exponential","mix_double_exponential"]
for dis in distribution:
    list_doc["sample_statistics"]["distribution"]=dis
    with open(path + "config.yml", "w") as f:
        yaml.dump(list_doc, f)
    B = BoundsExperiment(algo=["ORDSTAT","CLT","CHERNOFF_HOEFFDING","MASSART"])
    B.run_experiments()
    print (list_doc["sample_statistics"]["distribution"] +" done")


import sys
from collections import *
from util import *

def parse(line):
    return ints(line.strip())

xs = list(map(parse, sys.stdin))

if xs[0] == [2, 18, -2, 15]:
    width = 20
    row = 10
else:
    width = 4000000
    row = 2000000
    print("this takes a while...")

check = Interval(0, width)

intervals = defaultdict(Intervals)
row_bxs = set()
for sx, sy , bx, by in xs:
    if by == row:
        row_bxs.add(bx)

    m = manhattan(sx, sy, bx, by)

    miny = max(sy - m, 0)
    maxy = min(sy + m, width)

    for yy in range(miny, maxy):
        dx = m - abs(yy - sy)
        s = Interval(sx - dx, sx + dx)

        if s:
            intervals[yy].add(s)

# part 1
ps = set()
for interval in intervals[row]:
    for x in interval:
        ps.add(x)

print(len(ps - row_bxs))

# part 2
# find row with more than one interval, there's only one
row, iss = item(filter(lambda item: len(item[1]) > 1, intervals.items()))

# take the first span
print((iss[0].end + 1) * 4000000 + row)


import cv2
import numpy as np
img = cv2.imread("assets/images/data.png")
size = img.shape
image_points_2D = np.array([
        (378, 450),
        (378+581, 450),
        (378, 450),
        (378+581, 450+270),
    ], dtype="double")

figure_points_3D = np.array([
    (0.0, 1.0, 0.0),             # left top
    (1.0, 1.0, 0.0),        # right top
    (0.0, 0.0, 0.0),     # left bottom
    (1.0, 0.0, 0.0),      # right bottom
])

distortion_coeffs = np.zeros((4,1))
focal_length = size[1]
center = (size[1]/2, size[0]/2)
matrix_camera = np.array(
    [[focal_length, 0, center[0]],
    [0, focal_length, center[1]],
    [0, 0, 1]], dtype = "double"
)
success, vector_rotation, vector_translation = cv2.solvePnP(figure_points_3D, image_points_2D, matrix_camera, distortion_coeffs, flags=0)
nose_end_point2D, jacobian = cv2.projectPoints(np.array([(0.0, 0.0, 1000.0)]), vector_rotation, vector_translation, matrix_camera, distortion_coeffs)
for p in image_points_2D:
    cv2.circle(img, (int(p[0]), int(p[1])), 3, (0,0,255), -1)

for i in range(len(image_points_2D)):
    point1 = ( int(image_points_2D[i][0]), int(image_points_2D[i][1]))

    point2 = ( int(nose_end_point2D[0][0][0]), int(nose_end_point2D[0][0][1]))

    cv2.line(img, point1, point2, (255,255,255), 2)

cv2.imwrite('tmp/projection.png', img)
print(vector_rotation, vector_translation)
print(vector_rotation.shape, vector_translation.shape)
np.save('data/vr.npy', vector_rotation)
np.save('data/vt.npy', vector_translation)
# cv2.imshow("Final",img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()


# 内容图片路径
CONTENT_IMAGE = 'images/content/Beauty.jpg'

# 风格图片路径
STYLE_IMAGE = 'images/style/style_post-impressionism.jpg'

# 输出图片路径
OUTPUT_IMAGE = 'output/Beauty/Beauty_output'

# 预训练的vgg模型路径(VGG模型需自行下载)
VGG_MODEL_PATH = 'imagenet-vgg-verydeep-19.mat'

# 图片宽度
IMAGE_WIDTH = 300

# 图片高度
IMAGE_HEIGHT = 450

# 定义计算内容损失的VGG-19层名称及对应权重的列表
CONTENT_LOSS_LAYERS = [('conv4_2', 0.5), ('conv5_2', 0.5)]

# 定义计算风格损失的VGG-19层名称及对应权重的列表
STYLE_LOSS_LAYERS = [('conv1_1', 0.2), ('conv2_1', 0.2), ('conv3_1', 0.2), ('conv4_1', 0.2), ('conv5_1', 0.2)]

# 噪音比率（用于生成一张随机噪声图片，根据风格和内容loss来不断调整其）
NOISE = 0.5

# 图片RGB均值（将像素矩阵中的所有元素归一化）
IMAGE_MEAN_VALUE = [128.0, 128.0, 128.0]

# 内容损失权重
ALPHA = 1

# 风格损失权重
BETA = 500

# 训练次数
TRAIN_STEPS = 1000


#coding: utf-8
''' mbinary
#######################################################################
# File : hammingDistance.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-12-17  17:36
# Description:
    hamming distance is the number of different position (or binary bit for number) of two strings.
    eg   'abac', 'ab': 2            1010,11 : 3
#######################################################################
'''

def hammingDistance(a, b):
    if isinstance(a, int):
        n = a ^ b
        ct = 0
        while n:
            ct += n % 2
            n >>= 1
        return ct
    else:
        n, m = len(a), len(b)
        ret = 0
        for i, j in zip(a, b):
            ret += i == j
        return ret+abs(n-m)

def totalHammingDistance(lst):
    '''return sum of any two items(num or lst( str)) in lst'''
    length = len(lst)
    if length == 0:
        return 0
    if isinstance(lst[0], int):
        bits = [0] * len(bin(max(lst)))
        for n in lst:
            ct = 0
            while n:
                if n % 2 == 1:
                    bits[ct] += 1
                ct += 1
                n >>= 1
        return sum(i*(length-i) for i in bits)
    else:
        mx = len(max(lst, key=len))
        position = [dict() for i in range(mx)]
        for li in lst:
            for i, x in enumerate(li):
                if x in position[i]:
                    position[i][x] += 1
                else:
                    position[i][x] = 1
        ret = 0
        for dic in position:
            left = length
            for i in dic.values():
                ret += i*(left-i)  # key step
                left -= i        # key step
        return ret


#from Adafruit_PWM_Servo_Driver import PWM
import socket
import time
import threading
from transform import *

localIP     = ""
localPort   = 8080
bufferSize  = 1024
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")

teams = ["Tuesday", "Wednesday", "Thursday", "Friday"]
TIME_DELAY = 5
ROBOT_NAME = str(input("Enter team name:")) #Im stupid
while not(ROBOT_NAME in teams):
    ROBOT_NAME = str(input("Enter valid team name:"))
PWM_FREQ = 50

LEFT_MOT = int(input("Left Mot(0):"))
RIGHT_MOT = int(input("Right Mot(1):"))
LEFT_MANIP = int(input("Left Manip(4):")) #One manipulator for Intake/Rotation
RIGHT_MANIP = int(input("Right Manip(5):")) #Second manipualtor for intake/rotation

#pwm = PWM(0x40)

leftMtr = 0
rightMtr = 0

def getData():
    bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
    message = bytesAddressPair[0]
    address = bytesAddressPair[1]

    data = str(message).split(":")
    print(data)
    #print(data[0][2:])
    data[0] = data[0][2:]
    data[len(data)-1] = data[len(data)-1][:-1]
    return list(map(float, data)) #CHANGE PARSING HERE FOR FURTHER DATA INPUTS, last data element [:-1]

'''
def setServoPulse(channel, pulse):
    pulseLength = 1000000  # 1,000,000 us per second
    pulseLength /= PWM_FREQ  # 50 Hz
    # print "%d us per period" % pulseLength
    pulseLength /= 4096  # 12 bits of resolution
    # print "%d us per bit" % pulseLength
    pulse /= pulseLength
    # print "%d tick" % pulse
    pwm.setPWM(channel, 0, int(pulse)) # change: casted pulse to int

pwm.setPWMFreq(50)
'''
m_left = 0
m_right = 0
last_left = 0
last_right = 0
last_time = time.time()
stop_thread = False

def motor_update():
    global m_left
    global m_right
    global last_left
    global last_right
    global last_time
    global stop_thread
    while True:
        if stop_thread:
            break
        data = getData()
        last_left = m_left
        last_right = m_right
        last_time = time.time()
        m_left = data[1]
        m_right = data[0]
        trigger_1 = data[2]
        trigger_2 = data[3]
        a_press = data[4]
        b_press = data[5]

        if ROBOT_NAME == "Tuesday":
            L, R, ML, MR = tuesdayTransform(m_left, m_right, trigger_1, trigger_2, a_press, b_press)
        elif ROBOT_NAME == "Wednesday":
            L, R, ML, MR = wednesdayTransform(m_left, m_right, trigger_1, trigger_2, a_press, b_press)
        elif ROBOT_NAME == "Thursday":
            L, R, ML, MR = thursdayTransform(m_left, m_right, trigger_1, trigger_2, a_press, b_press)
        elif ROBOT_NAME == "Friday":
            L, R, ML, MR = fridayTransform(m_left, m_right, trigger_1, trigger_2, a_press, b_press)
        else:
            print("no team name configured")
            L, R, ML, MR = 0, 0, 0, 0
        list = [L, R, ML, MR]
        print(list)
        #setServoPulse(LEFT_MOT, L)
        #setServoPulse(RIGHT_MOT, R)
        #setServoPulse(LEFT_MANIP, ML)
        #setServoPulse(RIGHT_MANIP, MR)

m_thread = threading.Thread(target=motor_update, args=(), daemon=True)

def motor_watch():
    global last_time
    global m_left
    global m_right
    global last_left
    global last_right
    global stop_thread
    while True:
        if ((time.time() - last_time) > TIME_DELAY):
            if ((last_left == m_left) and (last_right == m_right) and (last_left != 0.0) and (last_right != 0.0)):
                stop_thread = True
                #setServoPulse(LEFT_MOT, 0)
                #setServoPulse(RIGHT_MOT, 0)
                #setServoPulse(LEFT_MANIP, 0)
                #setServoPulse(RIGHT_MANIP, 0)
                print("Data reception went overtime!")
                break

m_watch = threading.Thread(target = motor_watch, args = ())

m_thread.start()
m_watch.start()


import os
import yaml
import pytest
from py.xml import html

@pytest.fixture
def yaml_data_from_header(filepath):
    """Load data from YAML header of a markdown document."""

    basedir = os.path.dirname( os.path.realpath(__file__) )
    realpath = os.path.join(basedir, "..", filepath)

    def get_yaml(f):
        pointer = f.tell()
        if f.readline() != '---\n':
          f.seek(pointer)
          return ''
        readline = iter(f.readline, '')
        readline = iter(readline.__next__, '---\n')
        return ''.join(readline)

    with open(realpath, encoding='UTF-8') as f:
        data = list(yaml.load_all(get_yaml(f), Loader=yaml.SafeLoader))
        return(data)

@pytest.fixture
def yaml_data_from_filepath(filepath):
    """Load data from a YAML document at filepath."""
    basedir = os.path.dirname( os.path.realpath(__file__) )
    realpath = os.path.join(basedir, "..", filepath)
    with open(realpath, "r", encoding='UTF-8') as yamlfile:
        data = yaml.safe_load(yamlfile)
        return(data)

def pytest_html_report_title(report):
    report.title = "DSA Docs Test Results"

def pytest_html_results_table_header(cells):
    del cells[1:]
    cells.append(html.th("File"))
    cells.append(html.th("Name"))
    cells.append(html.th("Parameters"))
    cells.append(html.th("Description"))

def pytest_html_results_table_row(report, cells):
    del cells[1:]
    cells.append(html.td(report.testfile))
    cells.append(html.td(report.testname))
    cells.append(html.td(report.testargs))
    cells.append(html.td(report.description))

def pytest_html_results_table_html(report, data):
    if report.passed:
        del data[:]
        data.append(html.div('Foo output captured.', class_='empty log'))

@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()

    nodeid = report.nodeid
    (testfile,test) = nodeid.split("::")
    (testname, testargs) = test.split("[")
    testargs = testargs.replace("]","")

    report.description = str(item.function.__doc__)
    report.testfile = testfile
    report.testname = testname
    report.testargs = testargs


'''
11. Write a Python program to multiply all the items in a dictionary

'''

my_dict = {'data1':5,'data2':-5,'data3':3}

total = 1

for key,value in my_dict.items():
    total *= value

print(total)


import numpy as np
from env.kernel_bandit_env import KernelBanditEnv, kernel_bandit_generator
from scipy import linalg
import util
from simulator import Simulator
from scheduler import Scheduler
import matplotlib.pyplot as plt
from alg.alg import Alg
from alg.opkb import OPKB
from neural_network import NN
import torch

from alg.opkb import kernel_optimal_design

device = 'cuda' if torch.cuda.is_available() else 'cpu'

class OPNN(OPKB):
    name = 'opnn'
    config = {
        'm': 2048,
        'L': 3,
        'tol': 0.0001,
        'gamma': 100,
        'mixture_probability': 0.1,
        'beta_scale': 20,
        'mu_scale': 1 / 50,
        'e_scale': 0.01,
        'g_scale': 0.01,
        'epsilon_scale': 1.5,
        'j_star': 4,
        'change_detection': False,
        'J': 1000,
        'batch_size': 4096,
        'eta': 1e-8,
        'optimizer': 'sgd',
        'lambda': 0.001,
        'seed': None,
    }

    def __init__(self, env, config):
        if 'seed' in config and config['seed'] is not None:
            torch.manual_seed(config['seed'])
            del config['seed']

        self.env = env

        for k, v in config.items():
            if k not in self.config:
                raise Exception(f'Invalid config "{k}"')
            self.config[k] = v
        C = self.config

        N, d = env.A.shape
        self.gamma = C['gamma'] / env.T
        self.model = NN(d, int(C['m']), int(C['L']))
        self.Phi = self.model.feature_map(env.A).cpu().numpy()
        self.Phi0 = self.Phi.copy()
        self.deltas0 = {}
        self.pi = kernel_optimal_design(self.Phi, C['gamma'] / env.T)

        self.information_gain = util.InformationGain(self.Phi, env.T, C['gamma'])
        self.gamma_T = self.information_gain.get_exact(env.T)
        self.E = int(np.ceil(
            4 * self.gamma_T * np.log(8 * env.N * env.T * np.log2(env.T) / C['tol']) * C['e_scale']
        ))
        self.alpha = C['gamma'] / (4 * np.log(8 * env.T * np.log2(env.T) * env.N / C['tol']))
        self._initialize(1)

        self.detection_count = 0

    def _end_of_block_update(self, t, a, r):
        self.block_end_time[self.m] = t
        C = self.config

        self.model.initialize()
        self.model.train(self.env.A, self.history, C)
        self.Phi = self.model.feature_map(self.env.A).cpu().numpy()
        self.information_gain = util.InformationGain(self.Phi, self.env.T, C['gamma'])
        self.pi = kernel_optimal_design(self.Phi, self.gamma)

        self.gram_inv = [
            util.s_inv(util.S(p, self.Phi, self.gamma)) for p in self.ps
        ]
        z = np.zeros((self.m + 1, self.env.N))
        for m in range(self.m + 1):
            history = self.history[:self.block_end_time[m]]
            R_hat, delta = self._compute_delta(history)
            self.reward_estimates[m] = R_hat
            self.deltas[m] = delta.copy()

        R_hat = self.reward_estimates[self.m]
        _, delta = self._compute_delta(history)
        self.beta = self._compute_beta(self.m + 1)
        self.mu = self._compute_mu(self.m + 1)
        x = util.OP(self.Phi, delta, self.beta, self.gamma)
        G = delta <= 2 * self.alpha * self.gamma_T / self.beta * C['beta_scale'] * C['g_scale']
        g_regrets = [self.env.regret(t, aa) for aa in np.arange(self.env.N)[G]]
        if sum(G) == self.env.N:
            pG = self.pi
        elif sum(G) == 1:
            pG = G.astype(float)
        else:
            # TODO: cache
            Phi = self.Phi[G, :][:, G]
            p = kernel_optimal_design(Phi, C['gamma'] / self.env.T)
            pG = np.zeros(self.env.N)
            pG[G] = p

        mixture = C['mixture_probability']
        self.p = (1 - self.mu) * (x * (1 - mixture) + pG * mixture) + self.mu * self.pi
        self.ps.append(self.p)
        self.gram_inv.append(
            util.s_inv(util.S(self.p, self.Phi, self.gamma))
        )

        self.tau = t + 1
        self.m += 1
        self.scheduler = Scheduler(self.m, self.E, j_star=int(C['j_star']))


# testSIF = "123456789012"
testSIF = open("input.txt", 'r').read()
# testSIF = "0222112222120000"
x_size = 25
y_size = 6

layer_count = len(testSIF) // (x_size * y_size)
layers = []
index = 0
for z in range(layer_count):
    layer = []
    for y in range(y_size):
        for x in range(x_size):
            layer += testSIF[index]
            index += 1
    layers.append(layer)

print(len(layers) * y_size * x_size)
print(len(testSIF))

def decode_pixel(layers, index):
    color = "2"
    for l in layers:
        if color == "2":
            color = l[index]
    return color

index = 0
for y in range(y_size):
    line = ""
    for x in range(x_size):
        line += ("0" if (decode_pixel(layers, index) == "1") else " ") + " "
        index += 1
    print(line)


import numpy as np
from matplotlib import pyplot as plt

def get_pdf(points, mean_value, cov):
    cov = [cov]
    cov_inv = 1/cov[0]
    cov_inv = [cov_inv]
    diff = points - mean_value
    diff_trans = np.transpose(diff)
    # return pdf value of these points
    return (2.0 * np.pi) ** (-1 / 2.0) * (1.0 / cov[0] ** 0.5) * \
        np.exp(-0.5 * np.multiply(np.multiply(diff_trans, cov_inv), diff))

def gaussian():
    mu1 = 3
    mu2 = 0
    mu3 = 2

    sigma1 = 0.5
    sigma2 = 1
    sigma3 = 0.3

    s1 = np.random.normal(mu1, sigma1, 50)
    s2 = np.random.normal(mu2, sigma2, 50)
    s3 = np.random.normal(mu3, sigma3, 50)
    x_data = np.array(list(s1) + list(s2) + list(s3))

    np.random.shuffle(x_data)

    bins = np.linspace(np.min(x_data), np.max(x_data), 100)

    plt.figure(figsize=(10, 7))
    plt.xlabel("$x$")
    plt.ylabel("pdf")
    plt.scatter(x_data, [0.005] * len(x_data), color='navy', s=30, marker=2, label="Train data")
    plt.title('True pdf ')
    # combined pdf func
    plt.plot(bins, get_pdf(bins, mu1, sigma1) + get_pdf(bins, mu2, sigma2) + get_pdf(bins, mu3, sigma3), color='red',
             lw=2, label="True pdf")
    plt.legend(loc='upper right')
    plt.savefig('True_pdf_with.png')

    return bins, mu1, mu2, mu3, sigma1, sigma2, sigma3, x_data

def expectation_maximization():
    bins, mu1, mu2, mu3, sigma1, sigma2, sigma3, x_data = gaussian()
    k = 3
    weights = np.ones(k) / k
    means = np.random.choice(x_data, k)
    variances = np.random.random_sample(size=k)
    # visualize the training data
    k = 2
    z = 0
    eps = 0.00001
    iterations = 50
    iterations_completed = 0
    log_likelihood = []
    while iterations_completed < iterations:
        z += 1
    # calculate the maximum likelihood of each observation xi
        likelihood_list = []
        log_likelihood_list = []

        # Expectation step
        for j in range(k):
            likelihood_list.append(get_pdf(x_data, means[j], np.sqrt(variances[j])))
            log_likelihood_list.append(get_pdf(x_data, means[j], np.sqrt(variances[j]))*weights[j])

        likelihood_list = np.array(likelihood_list)
        log_likelihood_list = np.array(log_likelihood_list).T
        likelihood_sum = np.sum(log_likelihood_list, axis=1)
        log_value = np.sum(np.log(likelihood_sum))
        log_likelihood.append(log_value)

        b = []

        # Maximization step
        for j in range(k):
            # use the current values for the parameters to evaluate the posterior
            # probabilities of the data to have been generanted by each gaussian
            b.append((likelihood_list[j] * weights[j]) / (np.sum([likelihood_list[i] * weights[i] for i in range(k)],
                                                                 axis=0) + eps))
            # update mean and variance
            means[j] = np.sum(b[j] * x_data) / (np.sum(b[j]+eps))
            variances[j] = np.sum(b[j] * np.square(x_data - means[j])) / (np.sum(b[j] + eps))
            # update the weights
            weights[j] = np.mean(b[j])

        if len(log_likelihood) < 2:
            continue
        if np.abs(log_value - log_likelihood[-2]) < eps:
            plt.figure(figsize=(10, 7))
            plt.xlabel("$x$")
            plt.ylabel("pdf")
            plt.title(" Best result reached at Iteration {}".format(iterations_completed))
            plt.scatter(x_data, [0.005] * len(x_data), color='navy', s=30, marker=2,
                        label="Randomly generated data points")
            # Draw true pdf
            plt.plot(bins, get_pdf(bins, mu1, sigma1) + get_pdf(bins, mu2, sigma2) + get_pdf(bins, mu3, sigma3),
                     color='red', lw=2, label="True pdf")
            # Draw pdf after training
            plt.plot(bins, get_pdf(bins, means[0], variances[0]) + get_pdf(bins, means[1], variances[1]) +
                     get_pdf(bins, means[2], variances[2]), color='blue', lw=2, label="Trained pdf")
            plt.legend(loc='upper left')
            plt.savefig('pdf_after_training.png')
            plt.show()
            break
        iterations_completed += 1

if __name__ == "__main__":
    # Generate plots to show successful implementation of expectation maximization algorithm
    expectation_maximization()


# Variant 1
def create_design_of_the_door(N, M):
    sym = ".|."
    word = "WELCOME"
    dif = "-"
    j = 1
    for i in range(0, M):
        if i != N:
            if i == (N-1)/2:
                print(word.center(M, dif))
                j += - 25
            elif N-i > (N+1)/2:
                print((sym*j).center(M, dif))
                j += 2
            elif N-i < (N+1)/2:
                print((sym*j).center(M, dif))
                j += - 2
        else:
            break

# Variant 2
def create_design_of_the_door2(N, M):
    sym_1, sym_2, central_word = ".|.", "-", "WELCOME"
    pattern = [(sym_1*(2*i+1)).center(M, sym_2) for i in range(0, M)]
    print("\n".join(pattern[:int(N/2)] + [central_word.center(M, sym_2)] + pattern[int(N/2)-1::-1]))

N, M = map(int, input().split())
create_design_of_the_door2(N, M)


import subprocess
import os

INKSCAPE_PATH: str = "C:/Program Files/Inkscape/bin/inkscape.exe"
SIZE: int = 512

origin: str = "./svg"
destination: str = "./png"

os.makedirs(destination, exist_ok=True)

svgs = os.listdir(origin)
for i, path_end in enumerate(svgs):
    path = os.path.join(origin, path_end)
    path_name, path_ext = os.path.splitext(path)
    assert path_ext == ".svg", "Only SVG files are supported!"

    output: str = os.path.join(destination, os.path.basename(path_name) + ".png")

    print(f"Rendering '{path}' to '{output}'... ({i} / {len(svgs)})")
    subprocess.run([INKSCAPE_PATH, '--export-type=png', f'--export-filename={os.path.abspath(output)}', f'--export-width={SIZE}', f'--export-height={SIZE}', os.path.abspath(path)]).check_returncode()


from gtts import gTTS, lang

import os

from tkinter import *
root = Tk()

canvas = Canvas(root, width=400, height=500)
canvas.pack()

def texttospeech():
    text = entry.get()
    language = 'en'
    output = gTTS(text=text, lang=language, slow=False)
    output.save('output.mp3')
    os.system("start output.mp3")

label = Label(text="TEXT TO SPEECH CONVERTER")
canvas.create_window(200, 100, window=label)

entry = Entry(root)
canvas.create_window(200, 180, window=entry)

button = Button(text="start", command=texttospeech)
canvas.create_window(200, 230, window=button)

root.mainloop()


import copy
import numpy as np

import cv2

from liegroups import SE3
import viso2

from pyslam.problem import Options, Problem
from pyslam.sensors import StereoCamera, RGBDCamera
from pyslam.residuals import ReprojectionMotionOnlyBatchResidual
from pyslam.losses import L2Loss

from pyslam.pipelines.keyframes import SparseStereoKeyframe, SparseRGBDKeyframe
from pyslam.pipelines.ransac import FrameToFrameRANSAC

class SparseVOPipeline:
    """Base class for sparse VO pipelines"""

    def __init__(self, camera, first_pose=SE3.identity()):
        self.camera = camera
        """Camera model"""
        self.first_pose = first_pose
        """First pose"""
        self.keyframes = []
        """List of keyframes"""
        self.T_c_w = [first_pose]
        """List of camera poses"""
        self.motion_options = Options()
        """Optimizer parameters for motion estimation"""

        # Default optimizer parameters for motion estimation
        self.motion_options.allow_nondecreasing_steps = True
        self.motion_options.max_nondecreasing_steps = 5
        self.motion_options.min_cost_decrease = 0.99
        self.motion_options.max_iters = 30
        self.motion_options.num_threads = 1
        self.motion_options.linesearch_max_iters = 0

        self.keyframe_trans_thresh = 3.0  # meters
        """Translational distance threshold to drop new keyframes"""
        self.keyframe_rot_thresh = 0.3  # rad
        """Rotational distance threshold to drop new keyframes"""

        self.matcher_params = viso2.Matcher_parameters()
        """Parameters for libviso2 matcher"""
        self.matcher = viso2.Matcher(self.matcher_params)
        """libviso2 matcher"""
        self.matcher_mode = 0
        """libviso2 matching mode 0=flow 1=stereo 2=quad"""

        self.ransac = FrameToFrameRANSAC(self.camera)
        """RANSAC outlier rejection"""

        self.reprojection_stiffness = np.diag([1., 1., 1.])
        """Reprojection error stiffness matrix"""
        self.mode = 'map'
        """Create new keyframes or localize against existing ones? ['map'|'track']"""

        self.loss = L2Loss()
        """Loss function"""

    def set_mode(self, mode):
        """Set the localization mode to ['map'|'track']"""
        self.mode = mode
        if self.mode == 'track':
            self.active_keyframe_idx = 0
            self.T_c_w = []

    def track(self, trackframe):
        """ Track an image.

            Args:
                trackframe  : frame to track
        """
        if len(self.keyframes) == 0:
            # First frame, so don't track anything yet
            self.keyframes.append(trackframe)
            self.active_keyframe_idx = 0
            active_keyframe = self.keyframes[0]
        else:
            # Default behaviour for second frame and beyond
            active_keyframe = self.keyframes[self.active_keyframe_idx]

            # Estimate pose change from keyframe to tracking frame
            T_track_ref = self._compute_frame_to_frame_motion(
                active_keyframe, trackframe)
            T_track_ref.normalize()  # Numerical instability problems otherwise
            self.T_c_w.append(T_track_ref.dot(active_keyframe.T_c_w))

            # Threshold the distance from the active keyframe to drop a new one
            se3_vec = SE3.log(T_track_ref)
            trans_dist = np.linalg.norm(se3_vec[0:3])
            rot_dist = np.linalg.norm(se3_vec[3:6])

            if trans_dist > self.keyframe_trans_thresh or \
                    rot_dist > self.keyframe_rot_thresh:
                if self.mode is 'map':
                    trackframe.T_c_w = self.T_c_w[-1]
                    self.keyframes.append(trackframe)

                    print('Dropped new keyframe. '
                          'Trans dist was {:.3f}. Rot dist was {:.3f}.'.format(
                              trans_dist, rot_dist))

                self.active_keyframe_idx += 1
                print('Active keyframe idx: {}'.format(
                    self.active_keyframe_idx))

class SparseStereoPipeline(SparseVOPipeline):
    """Sparse stereo VO pipeine"""

    def __init__(self, camera, first_pose=SE3.identity()):
        super().__init__(camera, first_pose)
        self.matcher_mode = 2  # stereo quad matching
        self.matcher.setIntrinsics(camera.fu, camera.cu, camera.cv, camera.b)

    def track(self, im_left, im_right):
        if len(self.keyframes) == 0:
            # First frame, so create first keyframe with given initial pose
            trackframe = SparseStereoKeyframe(im_left, im_right, self.T_c_w[0])
        else:
            # Default behaviour for second frame and beyond
            trackframe = SparseStereoKeyframe(im_left, im_right)

        super().track(trackframe)

    def _compute_frame_to_frame_motion(self, ref_frame, track_frame):
        # Get feature matches
        self.matcher.pushBack(ref_frame.im_left, ref_frame.im_right)
        self.matcher.pushBack(track_frame.im_left, track_frame.im_right)
        self.matcher.matchFeatures(self.matcher_mode)
        matches = self.matcher.getMatches()
        # print('libviso2 matched {} features.'.format(matches.size()))

        # Stereo observations (uvd)
        self.obs_0 = [np.array([m.u1p, m.v1p, m.u1p - m.u2p]) for m in matches]
        self.obs_1 = [np.array([m.u1c, m.v1c, m.u1c - m.u2c]) for m in matches]

        # Prune all observations with disparity <= 0
        keep_mask = (self.obs_0[:, 2] > 0) & (self.obs_1[:, 2] > 0)
        self.obs_0 = self.obs_0[keep_mask, :]
        self.obs_1 = self.obs_1[keep_mask, :]
        # print('Matches after pruning: {} '.format(len(self.obs_0)))

        # RANSAC
        self.ransac.set_obs(self.obs_0, self.obs_1)
        T_1_0_guess, obs_0_inliers, obs_1_inliers, _ = self.ransac.perform_ransac()

        # Optimize with inliers
        residual = ReprojectionMotionOnlyBatchResidual(
            self.camera, obs_0_inliers, obs_1_inliers, self.reprojection_stiffness)

        problem = Problem(self.motion_options)
        problem.add_residual_block(residual, ['T_1_0'], loss=self.loss)

        params = {'T_1_0': T_1_0_guess}
        problem.initialize_params(params)
        params = problem.solve()

        return params['T_1_0']

class SparseRGBDPipeline(SparseVOPipeline):
    """Sparse RGBD VO pipeline"""

    def __init__(self, camera, first_pose=SE3.identity()):
        super().__init__(camera, first_pose)
        self.matcher_mode = 0  # mono-to-mono

    def track(self, image, depth):
        if len(self.keyframes) == 0:
            # First frame, so create first keyframe with given initial pose
            trackframe = SparseRGBDKeyframe(image, depth, self.T_c_w[0])
        else:
            # Default behaviour for second frame and beyond
            trackframe = SparseRGBDKeyframe(image, depth)

        super().track(trackframe)

    def _compute_frame_to_frame_motion(self, ref_frame, track_frame):
        # Get feature matches
        self.matcher.pushBack(ref_frame.image)
        self.matcher.pushBack(track_frame.image)
        self.matcher.matchFeatures(self.matcher_mode)
        matches = self.matcher.getMatches()
        # print('libviso2 matched {} features.'.format(matches.size()))

        # RGB-D observations (uvz)
        self.obs_0 = np.array(
            [[m.u1p, m.v1p, ref_frame.depth[int(m.v1p), int(m.u1p)]] for m in matches])
        self.obs_1 = np.array(
            [[m.u1c, m.v1c, track_frame.depth[int(m.v1c), int(m.u1c)]] for m in matches])

        # Prune all observations with depth <= 0
        keep_mask = (self.obs_0[:, 2] > 0) & (self.obs_1[:, 2] > 0)
        self.obs_0 = self.obs_0[keep_mask, :]
        self.obs_1 = self.obs_1[keep_mask, :]
        # print('Matches after pruning: {} '.format(self.obs_0.shape[0]))

        # RANSAC
        self.ransac.set_obs(self.obs_0, self.obs_1)
        T_1_0_guess, obs_0_inliers, obs_1_inliers, _ = self.ransac.perform_ransac()

        # Optimize with inliers
        residual = ReprojectionMotionOnlyBatchResidual(
            self.camera, obs_0_inliers, obs_1_inliers, self.reprojection_stiffness)

        problem = Problem(self.motion_options)
        problem.add_residual_block(residual, ['T_1_0'], loss=self.loss)

        params = {'T_1_0': T_1_0_guess}
        problem.initialize_params(params)
        params = problem.solve()

        return params['T_1_0']


from flask import Flask, render_template, url_for, request
import pandas as pd
import pickle
from sklearn.feature_extraction.text import CountVectorizer
import os

app=Flask(__name__)

port = int(os.environ.get('PORT', 5000))

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/back')
def back():
	return render_template("index.html")

@app.route('/predict',methods=['POST'])
def predict():
    df=pd.read_csv('NationalNames.csv')
    df.Gender.replace({'F':0,'M':1},inplace=True)
    df_data = df[["Name","Gender"]]
    X=df_data['Name']
    filename = 'finalized_model.sav'
    cv = CountVectorizer()
    X1=cv.fit_transform(X)
    classifier = pickle.load(open(filename, 'rb'))
    if request.method=='POST':
        nm=request.form['name']
        data=[nm]
        vect = cv.transform(data).toarray()
        my_prediction = classifier.predict(vect)
        return render_template('result.html',prediction = my_prediction, name=nm)
if __name__=='__main__':
   app.run(host='0.0.0.0', port=port, debug=True)


from pprint import pprint
from typing import List

def solution(arr):
    size = len(arr)
    results = []
    stack = []
    flags = [False] * size

    def backtrack():
        if len(stack) == size:
            results.append(stack.copy())
            return

        for i in range(size):
            if not flags[i]:
                stack.append(arr[i])
                flags[i] = True
                backtrack()
                stack.pop()
                flags[i] = False

    backtrack()
    return results

class Solution2:
    def permute(self, nums: List[int]) -> List[List[int]]:
        results = []
        route = []
        # cache_sum = 0
        total_sum = sum(nums)
        # print(total_sum)
        def backtrack(t_sum, total_sum):

            if len(route) == len(nums) and t_sum == total_sum:
                results.append(route[:])
                return
            elif len(route) == len(nums) and t_sum != total_sum:
                return
            for item in nums:
                t_sum += item
                route.append(item)
                backtrack(t_sum,total_sum)
                t_sum -= route.pop()

        backtrack(0, total_sum)
        return results

if __name__ == '__main__':
    # pprint(solution([1, 2, 3, 4]))
    pprint(Solution2().permute([1, 2, 3, 4]))


import random
import pygame

from typing import List
import aiohttp
import discord
from discord.ext import commands
from discord import ActionRow, ButtonStyle, user, app_commands
from discord.ui import Button
from discord.ext.commands import Context

import dislash

class TicTacToeButton(discord.ui.Button['TicTacToe']):
    def __init__(self, x: int, y: int):
        super().__init__(style=discord.ButtonStyle.secondary, label='\u200b', row=y)
        self.x = x
        self.y = y

    # This function is called whenever this particular button is pressed
    # This is part of the "meat" of the game logic
    async def callback(self, interaction: discord.Interaction):

        global player1
        global player2

        content = None

        assert self.view is not None
        view: TicTacToe = self.view
        state = view.board[self.y][self.x]
        if state in (view.X, view.O):
            return

        if view.current_player == view.X:
            if interaction.user.id != player1:
                await interaction.response.send_message("Its not your Turn!", ephemeral=True)
            else:
                self.style = discord.ButtonStyle.danger
                self.label = 'X'
                self.disabled = True
                view.board[self.y][self.x] = view.X
                view.current_player = view.O
                content = f"It is now <@{player2}>(O's) turn"

        else:
            if interaction.user.id != player2:
                await interaction.response.send_message("Its not your Turn!", ephemeral=True)
            else:
                self.style = discord.ButtonStyle.success
                self.label = 'O'
                self.disabled = True
                view.board[self.y][self.x] = view.O
                view.current_player = view.X
                content = f"It is now <@{player1}>(X's) turn"

        winner = view.check_board_winner()
        if winner is not None:
            if winner == view.X:
                content = f'<@{player1}>(X) won!'
            elif winner == view.O:
                content = f'<@{player2}>(O) won!'
            else:
                content = "It's a tie!"

            for child in view.children:
                child.disabled = True

            view.stop()
        if content != None:
            await interaction.response.edit_message(content=content, view=view)

# This is our actual board View
class TicTacToe(discord.ui.View):
    # This tells the IDE or linter that all our children will be TicTacToeButtons
    # This is not required
    children: List[TicTacToeButton]
    X = -1
    O = 1
    Tie = 2

    def __init__(self):
        super().__init__()
        self.current_player = self.X
        self.board = [
            [0, 0, 0],
            [0, 0, 0],
            [0, 0, 0],
        ]

        # Our board is made up of 3 by 3 TicTacToeButtons
        # The TicTacToeButton maintains the callbacks and helps steer
        # the actual game.
        for x in range(3):
            for y in range(3):
                self.add_item(TicTacToeButton(x, y))

    # This method checks for the board winner -- it is used by the TicTacToeButton
    def check_board_winner(self):
        for across in self.board:
            value = sum(across)
            if value == 3:
                return self.O
            elif value == -3:
                return self.X

        # Check vertical
        for line in range(3):
            value = self.board[0][line] + self.board[1][line] + self.board[2][line]
            if value == 3:
                return self.O
            elif value == -3:
                return self.X

        # Check diagonals
        diag = self.board[0][2] + self.board[1][1] + self.board[2][0]
        if diag == 3:
            return self.O
        elif diag == -3:
            return self.X

        diag = self.board[0][0] + self.board[1][1] + self.board[2][2]
        if diag == 3:
            return self.O
        elif diag == -3:
            return self.X

        # If we're here, we need to check if a tie was made
        if all(i != 0 for row in self.board for i in row):
            return self.Tie

        return None

class Games(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.hybrid_command(
        name="tictactoe",
        description="play tictactoe"
    )
    async def tictactoe(self, context: Context, enemy: discord.Member):
        global player1
        global player2

        player1 = context.author.id
        player2 = enemy.id

        await context.send(f'Tic Tac Toe: <@{player1}>(X) goes first', view=TicTacToe())

async def setup(bot):
    await bot.add_cog(Games(bot))


# Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.
#
# The output should be two capital letters with a dot separating them.
#
# It should look like this:
#
# Sam Harris => S.H
#
# Patrick Feeney => P.F

name1 = input('Enter name ')
def name_to_initials(name):
    name = name.upper()
    list1 = name.split(' ')
    ni = list1[0][0]
    li = list1[1][0]
    print(f'{ni}.{li}')

name_to_initials(name1)

# def abbrevName(name):
#     name = name.upper()
#     list1 = name.split(' ')
#     ni = list1[0][0]
#     li = list1[1][0]
#     return f'{ni}.{li}'


devices = ['keyboard','mouse','trackballs','scanner','barcode reader','digital camera','joystick','microphone','webcam','touchpad','stylus','touch screen','MIDI keyboard','ocr','omr','micr','monitor','printer','headphone','speakers','plotter','actuator','projector']
start_roll = 1124
ending_roll = 1231
left_roll = [1128,1135,1151,1170,1177,1229]
roll_no = int(input('Your roll no.: '))

rollist=[]
for i in range(start_roll,ending_roll+1):
    rollist.append(i)
newlst = [x for x in rollist if x not in left_roll]
for i, j in enumerate(newlst):
    if j == roll_no:
        c = i%len(devices)
yourproject = devices[c]
print('roll no. ',roll_no,' your project is: ', yourproject)


import os
from Malt.PipelinePlugin import PipelinePlugin, isinstance_str

class PluginExample(PipelinePlugin):

    @classmethod
    def poll_pipeline(self, pipeline):
        return isinstance_str(pipeline, 'NPR_Pipeline')

    @classmethod
    def register_graph_libraries(self, graphs):
        library_path = os.path.join(os.path.dirname(__file__), 'Shaders')
        for graph in graphs.values():
            if graph.language == 'GLSL':
                graph.add_library(library_path)

PLUGIN = PluginExample


from typing import Any

import matplotlib.pyplot as plt
import numpy as np

import data2latex as dtol

# https://stackoverflow.com/a/11352216/9318084
def moving_average(interval: Any, window_size: Any) -> Any:
    window = np.ones(int(window_size)) / float(window_size)
    return np.convolve(
        interval, window, "same"
    )  # pyright: ignore [reportUnknownVariableType]

N = 100
n = 3
X = np.linspace(0, 100, N)
Y = [
    (k * moving_average(y, 10) / 2)
    for y, k in zip(np.random.uniform(0, 100, (n, N)), range(2, 2 + n))
]

# dtol.use_multi_page_standalone()
# dtol.use_one_page_standalone()

dtol.plot(
    [X] * n,
    Y,
    "Different line colors",
    "Time $t$ [s]",
    "Position $x$ [mm]",
    line="-",
    mark=None,
    grid="_",
    legend=[r"$\alpha$", r"$\beta$", r"$\gamma$"],
    width="12cm",
    height="8cm",
    xlimits="exact",
    ylimits=(0, None),
)
dtol.plot(
    [X] * n,
    Y,
    "Different line styles",
    "Time $t$ [s]",
    "Position $x$ [mm]",
    line=["-", "--", "-."],
    line_color="black",
    mark=None,
    grid="_",
    legend=[r"$\alpha$", r"$\beta$", r"$\gamma$"],
    width="12cm",
    height="8cm",
    xlimits="exact",
    ylimits=(0, None),
)
try:
    dtol.finish("plotting")
except:
    print("COMPILATION ERROR")

# plt.plot(  # pyright: ignore [reportUnknownMemberType]
#     np.array([X] * n).T, np.array(Y).T, "-"
# )
# plt.show()  # pyright: ignore [reportUnknownMemberType]


import numpy as np

# Activation Function
def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def sigmoid_derivative(x):
    return x * (1 - x)

# Loss Function
def loss_function(pred_y, real_y):
    return np.sum(np.abs(pred_y - real_y) ** 2, axis=0)

# Neural Network Class
class NeuralNetwork:

    def __init__(self, x, y):
        self.input = x
        self.weights1 = np.random.rand(self.input.shape[1], 4)
        self.weights2 = np.random.rand(4, 1)
        self.y = y
        self.output = np.zeros(y.shape)

    def feedforward(self):
        self.layer1 = sigmoid(np.dot(self.input, self.weights1))
        self.layer2 = sigmoid(np.dot(self.layer1, self.weights2))
        return self.layer2

    def backpropagation(self):
        d_weights2 = np.dot(self.layer1.T, 2 * (self.y - self.output) * sigmoid_derivative(self.output))
        d_weights1 = np.dot(self.input.T, np.dot(2 * (self.y - self.output) * sigmoid_derivative(self.output),
                                                 self.weights2.T) * sigmoid_derivative(self.layer1))

        self.weights1 += d_weights1
        self.weights2 += d_weights2

    def train(self):
        self.output = self.feedforward()
        self.backpropagation()

# Main

X = np.array(([0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]), dtype=float)
Y = np.array(([0], [1], [1], [0]), dtype=float)
NeuralNet = NeuralNetwork(X, Y)

for i in range(2000):
    NeuralNet.train()
    if i % 100 == 0:
        print(loss_function(NeuralNet.output, Y))

print("\n Predicted Y : ", NeuralNet.output)
print("\n Real Y", Y)


from turtle import Turtle

class Paddle(Turtle):
    def __init__(self,xcor) :
        super().__init__()
        self.shape('square')
        self.pu()
        self.color('white')
        self.goto(xcor,0)
        self.setheading(90)
        self.shapesize(stretch_wid=1, stretch_len=5, outline=None)
        # self.resizemode("user")

    def up(self):
        self.setheading(90)
        if self.ycor() <= 235:
            # print(self.ycor())
            self.fd(20)

    def down(self):
        self.setheading(270)
        if self.ycor() >= -210:
            # print(self.ycor())
            self.fd(20)


# pylint: disable=W0611
import pickle
import inspect
import re

from jasmin.protocols.cli.filtersm import MTFILTERS
from jasmin.protocols.cli.managers import PersistableManager, Session
from jasmin.routing.Routes import (DefaultRoute, StaticMTRoute, RandomRoundrobinMTRoute, FailoverMTRoute)
from jasmin.routing.jasminApi import SmppClientConnector

MTROUTES = ['DefaultRoute', 'StaticMTRoute', 'RandomRoundrobinMTRoute', 'FailoverMTRoute']

# A config map between console-configuration keys and Route keys.
MTRouteKeyMap = {'order': 'order', 'type': 'type'}

class InvalidCidSyntax(Exception):
    pass

def validate_typed_connector_id(cid):
    """Used to ensure the cid imput is typed to indicate the connector
    type, some examples:
    - smppc(con_1) would indicate con_1 is a SmppClientConnector

    (connector_type, cid) will be return, otherwise a InvalidCidSyntax
    exception will be throwed.
    """

    m = re.match(r'(smppc)\(([A-Za-z0-9_-]{3,25})\)', cid, re.I)
    if not m:
        raise InvalidCidSyntax('Invalid syntax for connector id, must be smppc(some_id).')

    return m.group(1).lower(), m.group(2)

def MTRouteBuild(fCallback):
    """Parse args and try to build a route from  one of the routes in
       jasmin.routing.Routes instance to pass it to fCallback"""

    def parse_args_and_call_with_instance(self, *args, **kwargs):
        cmd = args[0]
        arg = args[1]

        # Empty line
        if cmd is None:
            return self.protocol.sendData()
        # Initiate a route from jasmin.routing.Routes with sessBuffer content
        if cmd == 'ok':
            # Remove route_class and route_args from self.sessBuffer before checking options
            # as these 2 options are not user-typed
            if len(self.sessBuffer) - 2 < len(self.protocol.sessionCompletitions):
                return self.protocol.sendData('You must set these options before saving: %s' % ', '.join(
                    self.protocol.sessionCompletitions))

            route = {}
            for key, value in self.sessBuffer.items():
                if key not in ['order', 'type', 'route_class', 'route_args']:
                    route[key] = value
            try:
                # Instanciate a Route
                RouteInstance = self.sessBuffer['route_class'](**route)

                # Hand the instance to fCallback
                return fCallback(self, self.sessBuffer['order'], RouteInstance)
            except Exception as e:
                return self.protocol.sendData('Error: %s' % str(e))
        else:
            # Unknown key
            ra = []
            if 'route_args' in self.sessBuffer:
                ra = self.sessBuffer['route_args']
            if cmd not in MTRouteKeyMap and cmd not in ra:
                return self.protocol.sendData('Unknown Route key: %s' % cmd)

            # IF we got the type, check if it's a correct one
            if cmd == 'type':
                _type = None
                for route in MTROUTES:
                    if arg.lower() == route.lower():
                        _type = route
                        break

                if _type is None:
                    return self.protocol.sendData(
                        'Unknown MT Route type:%s, available types: %s' % (arg, ', '.join(MTROUTES)))
                elif _type == 'DefaultRoute':
                    self.sessBuffer['order'] = 0

                # Before setting a new route class, remove any previous route
                # sessBuffer keys
                if 'order' in self.sessBuffer:
                    self.sessBuffer = {'order': self.sessBuffer['order']}
                else:
                    self.sessBuffer = {}

                self.sessBuffer['type'] = _type
                # Route class name must be already imported from jasmin.routing.Routes
                # in order to get it from globals()
                self.sessBuffer['route_class'] = globals()[_type]

                # Show Route help and save Route args
                RouteClassArgs = inspect.getfullargspec(self.sessBuffer['route_class'].__init__).args
                if 'self' in RouteClassArgs:
                    # Remove 'self' from args
                    RouteClassArgs.remove('self')
                self.sessBuffer['route_args'] = RouteClassArgs

                if len(RouteClassArgs) > 0:
                    # Update completitions
                    self.protocol.sessionCompletitions = list(MTRouteKeyMap) + RouteClassArgs

                    return self.protocol.sendData('%s arguments:\n%s' % (
                        self.sessBuffer['route_class'], ', '.join(RouteClassArgs)))
            else:
                # DefaultRoute's order is always zero
                if cmd == 'order':
                    if (arg != '0' and 'type' in self.sessBuffer and
                                self.sessBuffer['type'] == 'DefaultRoute'):
                        self.sessBuffer['order'] = 0
                        return self.protocol.sendData('Route order forced to 0 since it is a DefaultRoute')
                    elif (arg == '0' and 'type' in self.sessBuffer and
                                  self.sessBuffer['type'] != 'DefaultRoute'):
                        return self.protocol.sendData(
                            'This route order (0) is reserved for DefaultRoute only')
                    elif not arg.isdigit() or int(arg) < 0:
                        return self.protocol.sendData('Route order must be a positive integer')
                    else:
                        arg = int(arg)

                # Validate connector
                if cmd == 'connector':
                    try:
                        ctype, cid = validate_typed_connector_id(arg)
                        if ctype == 'smppc':
                            if self.pb['smppcm'].getConnector(cid) is None:
                                raise Exception('Unknown smppc cid: %s' % (cid))

                            # Make instance of SmppClientConnector
                            arg = SmppClientConnector(self.pb['smppcm'].getConnector(cid)['id'])
                        else:
                            raise NotImplementedError("Not implemented yet !")
                    except Exception as e:
                        return self.protocol.sendData(str(e))

                # Validate connectors
                if cmd == 'connectors':
                    CIDs = arg.split(';')
                    if len(CIDs) == 1:
                        return self.protocol.sendData(
                            '%s option value must contain a minimum of 2 connector IDs separated with ";".' % (cmd))

                    arg = []
                    for typed_cid in CIDs:
                        try:
                            ctype, cid = validate_typed_connector_id(typed_cid)
                            if ctype == 'smppc':
                                if self.pb['smppcm'].getConnector(cid) is None:
                                    raise Exception('Unknown smppc cid: %s' % (cid))

                                # Make instance of SmppClientConnector
                                arg.append(SmppClientConnector(self.pb['smppcm'].getConnector(cid)['id']))
                            else:
                                raise NotImplementedError("Not implemented yet !")
                        except Exception as e:
                            return self.protocol.sendData(str(e))

                # Validate rate and convert it to float
                if cmd == 'rate':
                    try:
                        arg = float(arg)
                    except ValueError:
                        return self.protocol.sendData('Incorrect rate (must be float): %s' % (arg))

                # Validate filters
                if cmd == 'filters':
                    FIDs = arg.split(';')

                    arg = []
                    for fid in FIDs:
                        if fid not in self.protocol.managers['filter'].filters:
                            return self.protocol.sendData('Unknown fid: %s' % (fid))
                        else:
                            _Filter = self.protocol.managers['filter'].filters[fid]

                            if _Filter.__class__.__name__ not in MTFILTERS:
                                return self.protocol.sendData(
                                    '%s#%s is not a valid filter for MTRoute (not in MTFILTERS)' % (
                                        _Filter.__class__.__name__, fid))
                            else:
                                arg.append(_Filter)

                # Buffer key for later Route initiating
                if cmd not in ra:
                    RouteKey = MTRouteKeyMap[cmd]
                else:
                    RouteKey = cmd
                self.sessBuffer[RouteKey] = arg

            return self.protocol.sendData()

    return parse_args_and_call_with_instance

class MTRouteExist:
    """Check if a mt route exist with a given order before passing it to fCallback"""

    def __init__(self, order_key):
        self.order_key = order_key

    def __call__(self, fCallback):
        order_key = self.order_key

        def exist_mtroute_and_call(self, *args, **kwargs):
            opts = args[1]
            order = getattr(opts, order_key)

            if not order.isdigit() or int(order) < 0:
                return self.protocol.sendData('MT Route order must be a positive integer')

            if self.pb['router'].getMTRoute(int(order)) is not None:
                return fCallback(self, *args, **kwargs)

            return self.protocol.sendData('Unknown MT Route: %s' % order)

        return exist_mtroute_and_call

class MtRouterManager(PersistableManager):
    """MT Router manager logics"""
    managerName = 'mtrouter'

    def persist(self, arg, opts):
        if self.pb['router'].perspective_persist(opts.profile, 'mtroutes'):
            self.protocol.sendData(
                '%s configuration persisted (profile:%s)' % (self.managerName, opts.profile), prompt=False)
        else:
            self.protocol.sendData(
                'Failed to persist %s configuration (profile:%s)' % (self.managerName, opts.profile),
                prompt=False)

    def load(self, arg, opts):
        r = self.pb['router'].perspective_load(opts.profile, 'mtroutes')

        if r:
            self.protocol.sendData(
                '%s configuration loaded (profile:%s)' % (self.managerName, opts.profile), prompt=False)
        else:
            self.protocol.sendData(
                'Failed to load %s configuration (profile:%s)' % (self.managerName, opts.profile),
                prompt=False)

    def list(self, arg, opts):
        mtroutes = pickle.loads(self.pb['router'].perspective_mtroute_get_all())
        counter = 0

        if (len(mtroutes)) > 0:
            self.protocol.sendData("#%s %s %s %s %s" % (
                'Order'.ljust(5),
                'Type'.ljust(23),
                'Rate'.ljust(10),
                'Connector ID(s)'.ljust(48),
                'Filter(s)'.ljust(64),
            ), prompt=False)

            for e in mtroutes:
                order = list(e)[0]
                mtroute = e[order]
                counter += 1

                connectors = ''
                # Prepare display for connectors
                if isinstance(mtroute.connector, list):
                    for c in mtroute.connector:
                        if connectors != '':
                            connectors += ', '
                        connectors += '%s(%s)' % (c._type, c.cid)
                else:
                    connectors = '%s(%s)' % (mtroute.connector._type, mtroute.connector.cid)

                filters = ''
                # Prepare display for filters
                for _filter in mtroute.filters:
                    if filters != '':
                        filters += ', '
                    filters += repr(_filter)

                # Prepare display for rate:
                # #295
                # jcli: when route is not rated,
                # add some differentiation markup to get the user's attention on it
                if mtroute.getRate() == 0:
                    rate = '0 (!)'
                else:
                    rate = str('%.5f' % mtroute.getRate())

                self.protocol.sendData("#%s %s %s %s %s" % (
                    str(order).ljust(5),
                    str(mtroute.__class__.__name__).ljust(23),
                    rate.ljust(10),
                    connectors.ljust(48),
                    filters.ljust(64),
                ), prompt=False)
                self.protocol.sendData(prompt=False)

        self.protocol.sendData('Total MT Routes: %s' % counter)

    @Session
    @MTRouteBuild
    def add_session(self, order, RouteInstance):
        st = self.pb['router'].perspective_mtroute_add(
            pickle.dumps(RouteInstance, pickle.HIGHEST_PROTOCOL), order)

        if st:
            self.protocol.sendData(
                'Successfully added MTRoute [%s] with order:%s' % (RouteInstance.__class__.__name__, order),
                prompt=False)
            self.stopSession()
        else:
            self.protocol.sendData('Failed adding MTRoute, check log for details')

    def add(self, arg, opts):
        return self.startSession(self.add_session,
                                 annoucement='Adding a new MT Route: (ok: save, ko: exit)',
                                 completitions=list(MTRouteKeyMap))

    @MTRouteExist(order_key='remove')
    def remove(self, arg, opts):
        st = self.pb['router'].perspective_mtroute_remove(int(opts.remove))

        if st:
            self.protocol.sendData('Successfully removed MT Route with order:%s' % opts.remove)
        else:
            self.protocol.sendData('Failed removing MT Route, check log for details')

    @MTRouteExist(order_key='show')
    def show(self, arg, opts):
        r = self.pb['router'].getMTRoute(int(opts.show))
        self.protocol.sendData(str(r))

    def flush(self, arg, opts):
        tableSize = len(pickle.loads(self.pb['router'].perspective_mtroute_get_all()))
        self.pb['router'].perspective_mtroute_flush()
        self.protocol.sendData('Successfully flushed MT Route table (%s flushed entries)' % tableSize)


from dataclasses import dataclass
from Classes.todo_list import *
from Classes.todo_item import *

@dataclass
class CreateTodoItem:
  todo_list: TodoList
  new_item: TodoItem = None
  success: bool = False

  def execute(self) -> None:
    new_task_name = input("\nEnter task name: ")
    new_task_description = input("Enter task description: ")

    if new_task_name in self.todo_list.get_data().keys():
      print("\nERROR: Task name must be unique!")
      input("Press Enter to continue...")
    else:
      self.new_item = self.todo_list.create_item(new_task_name, new_task_description)
      self.todo_list.add_item(self.new_item)
      self.success = True

  def undo(self) -> None:
    if self.success:
      self.todo_list.remove_item(self.new_item)

  def redo(self) -> None:
    if self.success:
      self.todo_list.add_item(self.new_item)

@dataclass
class DeleteTodoItem:
  todo_list: TodoList
  todo_item: TodoItem

  def execute(self) -> None:
    self.todo_list.remove_item(self.todo_item)

  def undo(self) -> None:
    self.todo_list.add_item(self.todo_item)

  def redo(self) -> None:
    self.todo_list.remove_item(self.todo_item)

@dataclass
class Toggle:
  todo_item: TodoItem

  def execute(self) -> None:
    self.todo_item.toggle_status()

  def undo(self) -> None:
    self.todo_item.toggle_status()

  def redo(self) -> None:
    self.todo_item.toggle_status()

@dataclass
class EditTodoItem:
  todo_list: TodoList
  todo_item: TodoItem
  old_name: str = ""
  old_description: str = ""
  new_name: str = ""
  new_description: str = ""
  success: bool = False

  def execute(self) -> None:
    print("\nEDIT TASK:")
    self.new_name = input("\nEnter new task's name: ")

    if self.new_name in self.todo_list.get_data().keys():
      print("\nERROR: Task name must be unique!")
      input("Press Enter to continue...")
    else:
      self.new_description = input("Enter new task's description: ")
      self.old_name = self.todo_item.get_name()
      self.old_description = self.todo_item.get_description()
      self.todo_item.set_name(self.new_name)
      self.todo_item.set_description(self.new_description)
      self.success: bool = True

  def undo(self) -> None:
    if self.success:
      self.todo_item.set_name(self.old_name)
      self.todo_item.set_description(self.old_description)

  def redo(self) -> None:
    if self.success:
      self.todo_item.set_name(self.new_name)
      self.todo_item.set_description(self.new_description)


from fake_useragent import UserAgent

ua = UserAgent()
headers = {'user-agent': ua.random}

import requests
import csv
import time
from tqdm import tqdm

api_url = "https://airtravelinfo.kr/wiki/api.php"

with open('rawdata/항공위키/airwiki_data.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerow(["페이지 번호", "문서 제목", "문서 내용"])

    apcontinue = ''
    for _ in tqdm(range(14)):

        params = {
            "action": "query",
            "format": "json",
            "list": "allpages",
            "aplimit": "max",
            "apcontinue": apcontinue
        }

        time.sleep(0.1)
        response = requests.get(api_url, params=params, headers=headers)
        data = response.json()

        if 'query' in data:
            pages = data['query']['allpages']

            for page in pages:
                page_id = page['pageid']
                page_title = page['title']

                page_params = {
                    "action": "query",
                    "format": "json",
                    "prop": "revisions",
                    "rvprop": "content",
                    "pageids": page_id
                }

                time.sleep(0.1)
                page_response = requests.get(api_url, params=page_params, headers=headers)
                page_data = page_response.json()

                page_content = page_data['query']['pages'][str(page_id)]['revisions'][0]['*']
                if page_content[0:5] != "#넘겨주기" and page_content[0:9] != "#redirect":
                    writer.writerow([page_id, page_title, page_content])

        if 'continue' in data:
            apcontinue = data['continue']['apcontinue']
        else:
            break


from logging import disable
from tkinter import *
from tkinter import ttk
from fpdf import FPDF
from compradores import *

class Ventana(Frame):

    Seller = Client()
    cont = 0
    So = ""

    def __init__(self, master=None):

        super().__init__(master,width=1280, height=720)
        self.master = master
        self.pack()
        self.create_widgets()
        self.bha(5)
        self.habili(5)

    def datos(self,k):
        datos = self.Seller.consulta(k)
        for row in datos:
            self.grid.insert("",END, text= row[0], values=(row[1],row[2],row[3],row[4]))

    def habilib(self,bn):
        if bn == 1:
            self.btnAdd.configure(bg="#2F3E45",fg="white")
            self.btnDelet.configure(bg="#20292E",fg="white")
            self.btnChan.configure(bg="#20292E",fg="white")
            self.btnShow.configure(bg="#20292E",fg="white")
        elif bn == 2:
            self.btnDelet.configure(bg="#2F3E45",fg="white")
            self.btnAdd.configure(bg="#20292E",fg="white")
            self.btnChan.configure(bg="#20292E",fg="white")
            self.btnShow.configure(bg="#20292E",fg="white")
        elif bn == 3:
            self.btnChan.configure(bg="#2F3E45",fg="white")
            self.btnDelet.configure(bg="#20292E",fg="white")
            self.btnAdd.configure(bg="#20292E",fg="white")
            self.btnShow.configure(bg="#20292E",fg="white")
        elif bn ==4:
            self.btnAdd.configure(bg="#20292E",fg="white")
            self.btnDelet.configure(bg="#20292E",fg="white")
            self.btnChan.configure(bg="#20292E",fg="white")
            self.btnShow.configure(bg="#2F3E45",fg="white")
        else:
            self.btnAdd.configure(bg="#20292E",fg="white")
            self.btnDelet.configure(bg="#20292E",fg="white")
            self.btnChan.configure(bg="#20292E",fg="white")
            self.btnShow.configure(bg="#20292E",fg="white")

    def habili(self,bn):
        if bn == 1:
            self.txtName.configure(state="normal")
            self.txtID.configure(state="normal")
            self.txtValue.configure(state="normal")
            self.txtDes.configure(state="normal")
        elif bn == 2:
            self.txtName.configure(state="disabled")
            self.txtID.configure(state="normal")
            self.txtValue.configure(state="disabled")
            self.txtDes.configure(state="disabled")
        elif bn ==3:
            self.txtName.configure(state="disabled")
            self.txtID.configure(state="normal")
            self.txtValue.configure(state="normal")
            self.txtDes.configure(state="normal")

        else:
            self.txtName.configure(state="disabled")
            self.txtID.configure(state="disabled")
            self.txtValue.configure(state="disabled")
    def bha(self,k):
        if k == 1 :
            self.btnAdd.configure(state="normal")
            self.btnShow.configure(state="normal")
            self.btnDelet.configure(state="normal")
            self.btnChan.configure(state="normal")
        else:
            self.btnAdd.configure(state="disabled")
            self.btnShow.configure(state="disabled")
            self.btnDelet.configure(state="disabled")
            self.btnChan.configure(state="disabled")

    def clGrip(self):
        for i in self.grid.get_children():
            self.grid.delete(i)

    def cBox(self):
        self.txtName.delete(0,END)
        self.txtID.delete(0,END)
        self.txtValue.delete(0,END)
        self.txtDes.delete(0,END)
    def gripb (self):
        self.grid.heading("#0", text="#", anchor=CENTER)
        self.grid.heading("col1", text="ID", anchor=CENTER)
        self.grid.heading("col2", text="Nombre", anchor=CENTER)
        self.grid.heading("col3", text="Valor", anchor=CENTER)
        self.grid.heading("col4", text="Descripcíon", anchor=CENTER)

    def Busc(self):

        val=list(self.txtID.get())
        print(val)

        if val[0] == "f":
            self.f="factura"+self.So

            v=self.txtID.get()
            self.vf=v.split("-")
            print(self.vf)

            if self.txtID.get() == "f":

                self.datos(self.f)

            else:
                try:
                    print(self.f)
                    Fa = self.Seller.buscar(self.vf[1],self.f,1);

                    self.grid.heading("#0", text="# Factura", anchor=CENTER)
                    self.grid.heading("col1", text="ID ", anchor=CENTER)
                    self.grid.heading("col2", text="Nombre", anchor=CENTER)
                    self.grid.heading("col3", text="Fecha ", anchor=CENTER)
                    self.grid.heading("col4", text="Valor / Descripcion", anchor=CENTER)

                    self.grid.insert("",END, text= str(Fa[0]), values=(str(Fa[1]),str(Fa[2]),str(Fa[3]),str(Fa[4])))
                    self.grid.insert("",END, text= str(""), values=(str(""),str(""),str(""),Fa[5]))
                    print("6")
                except:
                    self.lbl4.config(text="ID inexistente.")
                    self.datos(self.f)
        else:

            if self.txtID.get() == "0":
                self.datos(self.So)
            else:
                try:
                    datos = self.Seller.STab(self.txtID.get());
                    self.grid.heading("col2", text="Fecha", anchor=CENTER)
                    for row in datos:
                       self.grid.insert("",END, text= row[0], values=(row[1],row[2],row[3],row[4]))

                except:
                    self.lbl4.config(text="ID inexistente.")
                    self.datos(self.So)

    def impri(self,v1,v2,v3,n,i,Nu,d):

        f= str(self.So+ " - "+ str(Nu))
        da=self.Seller.dateNow()
        pdf = FPDF(orientation= 'P', unit= 'mm', format= 'A4')
        pdf.add_page()
        pdf.add_font('Popp', '', 'Poppins-Regular.ttf', uni=True)
        pdf.image('F.png', x = 10, y = 10, w = 190, h = 280)
        pdf.set_font('Popp', '', 15)
        f1= str(self.So+ str(Nu))
        if len(f) > 8:
            pdf.text(x=160, y=40, txt=f)
        elif len(f) > 12:
            pdf.text(x=150, y=40, txt=f)
        else:
            pdf.text(x=165, y=40, txt=f)

        pdf.text(x=68, y= 82, txt=n)
        pdf.text(x=164, y= 125, txt=v1)
        pdf.text(x=40, y= 125, txt=i)
        pdf.text(x=97, y= 125, txt=n)
        pdf.text(x=164, y= 141, txt=v2)
        pdf.text(x=164, y= 157, txt=v3)
        pdf.text(x=40, y= 157, txt=i)
        pdf.text(x=97, y= 157, txt=n)
        pdf.text(x=164, y= 230, txt=v3)
        pdf.text(x=12, y= 62, txt=da)

        pdf.text(x=22, y= 242, txt="Descripcíon:")
        pdf.text(x=25, y= 250, txt=d)

        print(self.So)
        self.Seller.insfa(i,n,da,v3,d,self.So)

        t="./f/{}-{}.pdf".format(f1,i)
        pdf.output(t)

    def Val(self):

        vAc=self.Seller.buscar(self.txtID.get(),self.So,2)
        nV = self.txtValue.get()
        print(vAc)
        nR=str(float(vAc[3]) + float(nV))
        desc = self.txtDes.get()

        self.grid.insert("",END, text= str(vAc[0]), values=(str(vAc[1]),str(vAc[2]),str(vAc[3]),str(vAc[4])))
        self.grid.insert("",END, text= str(""), values=(str(""),str(""),str(nV),desc))
        self.grid.insert("",END, text= str(vAc[0]), values=(str(vAc[1]),str(vAc[2]),str(nR)))

        self.Seller.modifica(vAc[1],str(nR),self.So)
        self.Seller.insTab(vAc[1],str(nR),desc)

        try:
            N=self.Seller.maxI(self.So)
            if N == NONE:
                v = 0
            else:
                a=list(N)
                print(a)
                v=int(a[0])+1

            self.impri(str(vAc[3]),str(nV),str(nR),str(vAc[2]),str(vAc[1]),str(v),desc)

        except:
            self.impri(str(vAc[3]),str(nV),str(nR),str(vAc[2]),str(vAc[1]),str(1),desc)

        self.lbl4.config(text="Valor actualizado.")
        #self.impri(str(vAc[3]),str(nV),str(nR),str(vAc[2]),str(vAc[1]),)

        self.cBox()

    def bSa(self):
        self.clGrip()
        self.So = "sa"
        self.btnSa.configure(bg="#2F3E45",fg="white")
        self.btnSb.configure(bg="#20292E",fg="white")
        self.datos(self.So)
        self.bha(1)

    def bSb(self):
        self.clGrip()
        self.So = "sb"
        self.btnSb.configure(bg="#2F3E45",fg="white")
        self.btnSa.configure(bg="#20292E",fg="white")
        self.datos(self.So)
        self.bha(1)

    def bAdd(self):
        self.lbl4.config(text="")
        self.habili(1)
        self.habilib(1)
        self.cBox()
        self.txtID.focus()
        self.cont = 1
        pass

    def bChan(self):
        self.lbl4.config(text="")
        self.habili(3)
        self.habilib(3)
        self.cBox()
        self.txtID.focus()
        self.cont = 4
        pass

    def bDelet(self):
        self.lbl4.config(text="")
        self.habili(2)
        self.habilib(2)
        self.cBox()
        self.txtID.focus()
        self.cont = 2

    def bShow(self):
        self.lbl4.config(text="")
        self.habili(2)
        self.habilib(4)
        self.txtID.focus()
        self.cBox()
        self.cont = 3

    def bSave(self):
        self.clGrip()
        self.gripb()
        self.grid.heading("col2", text="Nombre", anchor=CENTER)
        if self.cont ==1: #Add
            try:

                self.Seller.inserta(self.txtID.get(),self.txtName.get(),self.txtValue.get(),self.So,self.txtDes.get())
                self.Seller.newTable(self.txtID.get(),self.txtValue.get(),self.txtDes.get())
                self.lbl4.config(text="")
                self.cBox()
                self.datos(self.So)

            except:
                self.lbl4.config(text="Valores invalidos.")

        elif self.cont ==2: #Delet
            try:
                print("1")
                self.Seller.elimina(self.txtID.get(),self.So)
                print("1")
                self.lbl4.config(text="")
                self.cBox()
                self.datos(self.So)

            except:
                self.lbl4.config(text="ID inexistente.")

        elif self.cont == 3: #Show
            self.Busc()

        elif self.cont == 4: #Change
           try:
               self.lbl4.config(text="")
               self.Val()
           except:
               self.lbl4.config(text="ID Erronea.")

    def create_widgets(self):
        frame1 = Frame(self, bg="#20292E")
        frame1.place(x=0,y=0,width=100, height=720)

        self.btnAdd=Button(frame1,text="Añadir", command=self.bAdd, bg="#20292E", fg="white",relief=FLAT, )
        self.btnAdd.place(x=0,y=140,width=110, height=30 )
        self.btnDelet=Button(frame1,text="Eliminar", command=self.bDelet, bg="#20292E", fg="white",relief=FLAT)
        self.btnDelet.place(x=0,y=210,width=110, height=30)
        self.btnShow=Button(frame1,text="Explorar", command=self.bShow, bg="#20292E", fg="white",relief=FLAT)
        self.btnShow.place(x=0,y=280,width=110, height=30)
        self.btnChan=Button(frame1,text="Modificar", command=self.bChan, bg="#20292E", fg="white",relief=FLAT)
        self.btnChan.place(x=0,y=350,width=110, height=30)

        self.btnSa=Button(frame1,text="Sa", command=self.bSa, bg="#20292E", fg="white",relief=FLAT)
        self.btnSa.place(x=0,y=650,width=110, height=30)
        self.btnSb=Button(frame1,text="Sb", command=self.bSb, bg="#20292E", fg="white",relief=FLAT)
        self.btnSb.place(x=0,y=680,width=110, height=30)

        frame2 = Frame(self,bg="#2F3E45" )
        frame2.place(x=100,y=0,width=1200, height=720)
        lbl1 = Label(frame2,text="ID: ",bg="#2F3E45",fg="white")
        lbl1.place(x=30,y=5+100)
        self.txtID=Entry(frame2)
        self.txtID.place(x=30,y=25+100,width=160, height=20)
        lbl2 = Label(frame2,text="Nombre: ",bg="#2F3E45",fg="white")

        lbl2.place(x=30,y=55+110)
        self.txtName=Entry(frame2)
        self.txtName.place(x=30,y=75+110,width=160, height=20)
        lbl3 = Label(frame2,text="Valor: ",bg="#2F3E45",fg="white")
        lbl3.place(x=30,y=105+120)

        self.lbl4 = Label(frame2,text="",bg="#2F3E45",fg="white",font=( NORMAL, 11))

        self.lbl4.place(x=35,y=500)

        self.txtValue=Entry(frame2)
        self.txtValue.place(x=30,y=125+120,width=160, height=20)

        self.btnGuardar =  Button(frame2,text="Guardar", command=self.bSave, bg="#05867B", fg="white",relief=FLAT)
        self.btnGuardar.place(x=70,y=160+200,width=60, height=30)

        lbl5 = Label(frame2,text="Descripción: ",bg="#2F3E45",fg="white")
        lbl5.place(x=120,y=670)
        self.txtDes=Entry(frame2)
        self.txtDes.place(x=207,y=670,width=780, height=20)

        self.grid = ttk.Treeview(self, columns=("col1","col2","col3","col4"))
        self.grid.column("#0",width=20)
        self.grid.column("col1",width=60, anchor=CENTER)
        self.grid.column("col2",width=100, anchor=CENTER)
        self.grid.column("col3",width=90, anchor=CENTER)
        self.grid.column("col4",width=100, anchor=CENTER)

        self.grid.heading("#0", text="#", anchor=CENTER)
        self.grid.heading("col1", text="ID", anchor=CENTER)
        self.grid.heading("col2", text="Nombre", anchor=CENTER)
        self.grid.heading("col3", text="Valor", anchor=CENTER)
        self.grid.heading("col4", text="Descripcíon", anchor=CENTER)

        self.grid.place(x=310,y=0,width=970, height=650)


import protobuf.data_file_pb2 as dfpb
import data_file as df

test = dfpb.DataFile()

test.file = "../../data/gps_20161101_morning"
test.sep = ","
test.has_header = True
test.row_uid = 0
test.row_time = 1
test.coord_sys = dfpb.CoordinateSystem.GCJ02
test.row_lat = 3
test.row_lng = 2

print(test.SerializeToString())
print(test)


#! /usr/bin/env
# Udacity Full Stack Nanodegree Project: Logs Analysis

import psycopg2
import calendar
import time

def connect():
    """Connect to the PostgreSQL database.  Returns a database connection."""
    return psycopg2.connect("dbname=news")

q1_SQL = "select * from ArticleCount limit 3;"

def question1():
    conn = connect()
    cur = conn.cursor()
    cur.execute(q1_SQL)

    for record in cur:
        title = record[0]
        views = record[1]
        print('"%s" - %d views' % (title, views))

    cur.close()
    conn.close()
    return

q2_SQL = """select authorsWork.name, sum(ArticleCount.count) from ArticleCount
         inner join authorsWork on ArticleCount.title=authorsWork.title group
         by authorsWork.name order by sum desc;"""

def question2():
    conn = connect()
    cur = conn.cursor()
    cur.execute(q2_SQL)

    for record in cur:
        name = record[0]
        views = record[1]
        print("%s - %d views" % (name, views))

    cur.close()
    conn.close()
    return

q3_SQL = 'select * from percentError where percent_error>1;'

def question3():
    conn = connect()
    cur = conn.cursor()
    cur.execute(q3_SQL)

    for record in cur:
        month = calendar.month_name[int(record[0])]
        day = int(record[1])
        year = int(record[2])
        percent = record[3]

        print("%s %d, %d - %.1f%% errors " % (month, day, year, percent))

    cur.close()
    conn.close()
    return

print("\nReport generated on %s at %s" % (time.strftime("%d/%m/%Y"),
      time.strftime("%H:%M:%S")))

print("\nThe three most popular articles of all time are:")
question1()

print("\nThe most popular article authors of all time are:")
question2()

print("\nDay(s) when more than 1%s of server requests lead to errors:" % ("%"))
question3()

print("\n")


import random

def get_data(filename):
    """
    This function retrieves the names of the cities and the distances between
    them from a file. It builds and returns a dictionary of city names and a
    list of distances.
    """
    indicies = {}

    distances_file = list(open(filename, 'r'))
    # this list comprehension builds a square array with values initialized as 0
    distances = [[0 for x in range(len(distances_file))] for y in range(len(distances_file))]

    # gets the city name and distances from each line and populates the dictionary and array
    index = 0
    for line in distances_file:
        line = line.strip().split(' ')
        city = line.pop(0)
        indicies[city] = index
        for x in range(len(line)):
            distances[x][index] = int(line[x])
            distances[index][x] = int(line[x])
        index += 1

    return indicies, distances

def test_distances(indicies, distances):
    """
    This is just some debugging code that helped me make sure the array
    of distances was being built properly. It should print the same distance
    from both directions.
    """

    # pick random cities
    city1 = random.randint(0, 9)
    city2 = random.randint(0, 9)

    # get the city names by their index values
    city1_name = ''
    for key in indicies:
        if indicies[key] == city1:
            city1_name = key

    city2_name = ''
    for key in indicies:
        if indicies[key] == city2:
            city2_name = key

    # print the city names and the distance between them
    # distance should be the same whether it's A->B or B->A
    print("The distance between " + city1_name + " and " + city2_name + " is " +
        str(distances[city1][city2]) + " miles or " + str(distances[city2][city1]) + " miles.")

def tripLength(indicies, distances, cities):
    """
    This function calculates the total distance of a trip, given a list of city names.
    """
    distance = 0
    # copy the list so that the original isn't destroyed
    the_cities = cities[:]
    # until you're at the last city
    while len(the_cities) > 1:
        # get the index value of the first city and remove it from the list
        x = indicies[the_cities.pop(0)]
        # get the index value of the second city
        y = indicies[the_cities[0]]
        # use the array of distances to find the corresponding distance
        distance += distances[x][y]

    return distance

def display_results(distance, cities):
    """
    Prints the results of the distance calculation in a nice and neat way.
    """
    print("The distance to go from ", end='')
    last_city = cities.pop()
    for city in cities:
        print(city + " to ", end='')

    print(last_city + " is " + str(distance) + " miles.")

# get the indicies dictionary and the distances array from a text file
indicies, distances = get_data("distances.txt")
# a list of cities to be traveled to
some_cities = ['Greensboro', 'Raleigh', 'Chapel-Hill', 'Elizabeth-City', 'Wilmington']
# get the distance of the trip
distance = tripLength(indicies, distances, some_cities)
# print the results
display_results(distance, some_cities)


from ..utility.col        import *
from ..utility.bi2de      import *
from ..utility.find       import *
from ..utility.LongTensor import *
from ..utility.isempty    import *
from ..utility.indices    import *
from ..utility.sum        import *
from ..topology.poly2ind  import *
from ..topology.ispoly    import *

class Segment(object):
    def __init__(self, A=None, B=None):
        self.A = A
        self.B = B

class SurfaceSegment(Segment):
    def __init__(self, T=None, **kwargs):
        super(SurfaceSegment, self).__init__(**kwargs)
        self.T = T

def meandering_triangle(T, F, iso_target=0.5):
    """
    Returns a collection of segments defined on a surface

    Parameters
    ----------
    T : LongTensor
        the triangle topology tensor
    F : Tensor
        a (N,1,) tensor defining a scalar field on the nodes of the model
    iso_target : float (optional)
        a iso value to track on the surface (default is 0.5)

    Returns
    -------
    list or SurfaceSegment
        a collection of segments defined on the surface of a model
    """

    if not istri(T):
        raise RuntimeError('Topology tensor must be triangles')
    table = LongTensor([[0, 0, 0],
                        [1, 3, 2],
                        [2, 1, 3],
                        [3, 1, 2],
                        [3, 2, 1],
                        [2, 3, 1],
                        [1, 2, 3],
                        [0, 0, 0]], device=T.device)
    code    = lambda v: bi2de(v >= iso_target)
    fetch   = lambda v: table[code(v), :].squeeze(1)
    I, J, K = tri2ind(T)
    C = [[] for i in range(col(F))]
    for f in range(col(F)):
        Fi = torch.cat((F[I, f].unsqueeze(1),
                        F[J, f].unsqueeze(1),
                        F[K, f].unsqueeze(1)), dim=1)
        X  = fetch(Fi)
        n  = find(X[:, 1])
        if not isempty(n):
            X  -= 1
            s   = (numel(n), 3)
            c   = SurfaceSegment(A=torch.zeros(s, dtype=torch.float, device=T.device),
                                 B=torch.zeros(s, dtype=torch.float, device=T.device),
                                 T=n)
            t   = torch.zeros((row(X), 2), dtype=torch.float, device=T.device)
            t[n, :] = torch.cat((((iso_target - Fi[n, X[n, 1]]) / (Fi[n, X[n, 0]] - Fi[n, X[n, 1]])).unsqueeze(1),
                                 ((iso_target - Fi[n, X[n, 2]]) / (Fi[n, X[n, 0]] - Fi[n, X[n, 2]])).unsqueeze(1)), dim=1)

            i = indices(0, numel(n) - 1, device=T.device)
            c.A[i, X[n, 0]] =     t[n, 0]
            c.A[i, X[n, 1]] = 1 - t[n, 0]
            c.A[c.A < 0.01] = 0
            c.A = c.A / sum(c.A, 1)

            c.B[i, X[n, 0]] =     t[n, 1]
            c.B[i, X[n, 2]] = 1 - t[n, 1]
            c.B[c.B < 0.01] = 0
            c.B = c.B / sum(c.B, 1)

            i = find(sum((c.A - c.B)**2, 1) > 0.0001)
            c.A = c.A[i, :]
            c.B = c.B[i, :]
            c.T = c.T[i]
            C[f] = c
    return C if len(C) > 0 else C[0]


from bson.objectid import ObjectId
from pydantic import BaseModel

class MovieSchema(BaseModel):
    id: str
    title: str
    rating: int
    url: str

    class Config:
        orm_mode = True
        allow_population_by_field_name = True
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}

class UserResponseSchema(BaseModel):
    username: str
    active: bool

class UserCreateSchema(BaseModel):
    username: str
    password: str

class TokenSchema(BaseModel):
    access_token: str
    token_type: str

class TokenData(BaseModel):
    username: str


import numpy as np

class  DataClean:

    def __init__(self):
        self.LimitHi = 0
        self.LimitLow = 0
        self.mdn = 0

    def remove_outlier(self, data):

        self.LimitHi=np.mean(data) + 2*np.std(data)
        self.LimitLow=np.mean(data) - 2*np.std(data)

        data = data[(data < self.LimitHi) & (data > self.LimitLow)]

        return data

    def replace_outlier(self, data):

        self.LimitHi=np.mean(data) + 2*np.std(data)
        self.LimitLow=np.mean(data) - 2*np.std(data)

        Flag_Good = (data <= self.LimitHi) & (data >= self.LimitLow)
        Flag_Bad = ~Flag_Good

        data[Flag_Bad] = np.mean(data[Flag_Good])

        return data

    def fill_median(self, data):

        Flag_Good = np.array([element.isdigit() for element in data])
        Flag_Bad = ~Flag_Good

        self.mdn = data[Flag_Good]
        self.mdn = self.mdn.astype(float)

        data[Flag_Bad] = np.median(self.mdn)

        data = data.astype(float)

        return data


from math import *
from Ellepsoide_parametres import *

def cartesian2geo(x, y, z, a, inv_f, epsilon):
    f = 1 / inv_f
    b = a * (1 - f)
    e_squared, e_prime_squared = ellipsoid_parameters(a, inv_f)
    if x != 0:
        lam = atan(y / x)

    else:
        print('lambda cant be calculated because the denominator is null!')
    phi_0 = atan(z/sqrt(pow(x, 2)+pow(y, 2)))
    #e_squared, e_prime_squared = ellipsoid_parameters()
    n_0 = a/sqrt(1-(e_squared*pow(sin(phi_0), 2)))
    h_0 = (sqrt(pow(x, 2)+pow(y, 2))/cos(phi_0))-n_0
    phi_1 = atan((z / sqrt(pow(x, 2) + pow(y, 2))) * (1 / (1 - (e_squared * (n_0 / (n_0 + h_0))))))
    n_1 = a / (sqrt(1 - (e_squared * pow(sin(phi_1), 2))))
    h_1 = (sqrt(pow(x, 2) + pow(y, 2)) / cos(phi_1)) - n_1
    phi_n = phi_1
    phi_n_1 = phi_0
    n_n_1 = n_1
    h_n_1 = h_1
    while fabs((phi_n-phi_n_1)/phi_n) > epsilon:
        phi_n_1 = phi_n

        phi_n = atan((z/sqrt(pow(x, 2)+pow(y, 2)))*(1/(1-(e_squared*(n_n_1/(n_n_1+h_n_1))))))
        n_n = a/(sqrt(1-(e_squared*pow(sin(phi_n), 2))))
        h_n = (sqrt(pow(x, 2)+pow(y, 2))/cos(phi_n))-n_n
        n_n_1 = n_n
        h_n_1 = h_n
    lam = degrees(lam)
    phi = degrees(phi_n_1)
    return phi, lam, h_n_1