from postgres import Postgres
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import json
import pandas
import os
import sys
from math import ceil
import argparse

parser = argparse.ArgumentParser()
# Run control arguments
parser.add_argument("--schema", type=str, help="The name of the schema", default='socialnet7')
parser.add_argument("--metrics", type=str,nargs='*', help="List of metrics to run (default to all)")
parser.add_argument("--nowarn", action="store_true", default=False,help="Plot cohorts using scored metrics for all (not just skewed)")

class MetricCalculator:

	def __init__(self,schema):
		'''
		Initialize metric calculator from schema name.  Loads parameter json from the adjacent conf directory.
		Loads date range from the configuration. Makes postgres connection with environment variables.
		:param schema:
		'''

		with open('../conf/%s_metrics.json' % schema, 'r') as myfile:
			self.metric_dict = json.loads(myfile.read())

		self.schema=schema
		self.from_date = self.metric_dict['date_range']['from_date']
		self.to_date = self.metric_dict['date_range']['to_date']

		self.non_metrics=('date_range','event_properties')

		self.URI=  f"postgresql://localhost/{os.environ['CHURN_DB']}?user={os.environ['CHURN_DB_USER']}&password={os.environ['CHURN_DB_PASS']}"
		self.db = Postgres(self.URI)

		with open('../sql/qa_metric.sql', 'r') as myfile:
			self.qa_sql = myfile.read().replace('\n', ' ')

	def remove_old_metrics_from_db(self, run_mets=None, no_warn=False):
		'''
		Delete values of existing metrics. If no metrics are specified, it truncates the metric table. Otherwise
		just delete the specified metrics.
		:param run_mets: list of strings, metric names; or else None meaning truncate all metrics
		:return:
		'''
		if run_mets is None:
			print('TRUNCATING *Metrics* in schema -> %s <-  ...' % schema)
			if not no_warn and input("are you sure? (enter %s to proceed) " % schema) == schema:
				exit(0)
			self.db.run('truncate table %s.metric' % schema)
			self.db.run('truncate table %s.metric_name' % schema)
		else:
			if isinstance(run_mets,str): run_mets=[run_mets]
			if len(run_mets)>1 and not no_warn:
				print('DELETING * %d * Metrics in schema -> %s <-  ...' % (len(run_mets),schema))
				if input("are you sure? (enter %s to proceed) " % schema) != schema:
					exit(0)
			for m in run_mets:
				id =self.get_metric_id(m)
				if id is not None:
					deletSql="delete from %s.metric where metric_name_id=%d and metric_time between '%s'::timestamp and '%s'::timestamp"  \
						   % (schema,id,self.from_date,self.to_date)
					print('Clearing old values: ' + deletSql)
					self.db.run(deletSql)

	def get_metric_id(self,metric_name):
		'''
		Get the id of one metric from the database by name
		:param metric_name: string name of the metric
		:return: id number of the metric, assuming one was found; or else SQL returns NULL as None in Python
		'''
		sql = "select metric_name_id from %s.metric_name where metric_name='%s'" % (self.schema, metric_name)
		return self.db.one(sql)

	def add_metric_id(self,metric):
		'''
		Add an id for a metric if it doesn't already exist
		:param metric: string name of the metric
		:return:
		'''
		id = self.get_metric_id(metric)
		if id is None:
			id = self.db.one('select max(metric_name_id)+1 from %s.metric_name' % schema)
			if id is None: id = 0
			insertNameSql = "insert into %s.metric_name (metric_name_id,metric_name) values (%d,'%s')" % (
			schema, id, metric)
			self.db.run(insertNameSql)
			print('Inserted metric %s.%s as id %d' % (schema,metric,id))

		return id

	def metric_qa_plot(self,metric,args):

		save_path = '../../../fight-churn-output/' + self.schema + '/'
		os.makedirs(save_path, exist_ok=True)

		print('Checking metric %s.%s' % (self.schema, metric))
		id = self.get_metric_id(metric)
		if id is None:
			"No ID found for metric %s" % metric
			return
		aSql = self.qa_sql.replace('%metric_name_id', str(id))
		aSql = aSql.replace('%schema', self.schema)
		aSql = aSql.replace('%from_date', self.from_date)
		aSql = aSql.replace('%to_date', self.to_date)

		print(aSql)
		res = pandas.read_sql_query(aSql, self.URI)
		if res.shape[0] == 0 or res['avg_val'].isnull().values.all():
			print('\t*** No result for %s' % metric)
			return

		cleanedName = ''.join(e for e in metric if e.isalnum())
		# res.to_csv(save_path+cleanedName+'_metric_qa.csv',index=False) # uncomment to save details

		plt.figure(figsize=(8, 10))
		plt.subplot(4, 1, 1)
		plt.plot('calc_date', 'max_val', data=res, marker='', color='black', linewidth=2, label="max")
		if args.hideax: plt.gca().get_xaxis().set_visible(False)  # Hiding y axis labels on the count
		plt.ylim(0, ceil(1.1 * res['max_val'].dropna().max()))
		plt.legend()
		plt.title(metric)
		plt.subplot(4, 1, 2)
		plt.plot('calc_date', 'avg_val', data=res, marker='', color='black', linewidth=2, label='avg')
		if args.hideax: plt.gca().get_xaxis().set_visible(False)  # Hiding y axis labels on the count
		plt.ylim(0, ceil(1.1 * res['avg_val'].dropna().max()))
		plt.legend()
		plt.subplot(4, 1, 3)
		plt.plot('calc_date', 'min_val', data=res, marker='', color='black', linewidth=2, label='min')
		if args.hideax: plt.gca().get_xaxis().set_visible(False)  # Hiding y axis labels on the count
		# plt.ylim(0, ceil(2*res['min_val'].dropna().max()))
		plt.legend()
		plt.subplot(4, 1, 4)
		plt.plot('calc_date', 'n_calc', data=res, marker='', color='black', linewidth=2, label="n_calc")
		plt.ylim(0, ceil(1.1 * res['n_calc'].dropna().max()))
		plt.legend()
		plt.gca().figure.autofmt_xdate()
		if args.hideax:
			plt.gca().get_yaxis().set_visible(False)  # Hiding y axis labels on the count
			monthFormat = mdates.DateFormatter('%b')
			plt.gca().get_xaxis().set_major_formatter(monthFormat)
		else:
			plt.gcf().autofmt_xdate()

		plt.savefig(save_path + 'metric_valqa_' + cleanedName + '.' + args.format)
		plt.close()

	def qa_metrics(self,args):
		'''
		Loops over the configured metrics and makes the QA plot of each.  If a list was provided, it only runs the ones
		in the list.
		:param run_mets: list of strings, metric names; or else None meaning calculate all configured metrics
		:param args: from argparse
		:return:
		'''

		if args.metrics is None:
			for metric in self.metric_dict.keys():
				if metric in self.non_metrics: continue
				self.metric_qa_plot(metric,args)
		else:
			for metric in args.metrics:
				self.metric_qa_plot(metric,args)

	def run_one_metric_calculation(self,metric):
		'''
		Calculate one metric, by name.  First adds the id, then loads the raw sql from the file.  To set the bind
		variables it starts out with the second level dictionary for this metric from the main metric dictionary.
		Then it adds all of the metric parameters that are common to all metric calcultions, such as from and to
		 dates, the metric name id, a schema and the value name.  These are put into the SQL template with a simple
		 replace (did not use the Postgres bind system because it was not flexible enough.) Finally, it runs the SQL.
		:param metric: string name of the metric
		:return:
		'''

		assert metric in self.metric_dict, "No metric %s in metric dictionary!" % metric

		id = self.add_metric_id(metric)

		with open('../sql/%s.sql' % self.metric_dict[metric]['sql'], 'r') as myfile:
			sql = myfile.read().replace('\n', ' ')

		params = self.metric_dict[metric]
		params['metric_name_val'] = metric
		params['schema'] = schema
		params['from_date'] = self.from_date
		params['to_date'] = self.to_date
		params['metric_name_id'] = id
		bind_char='%'
		for p in params.keys():
			sql = sql.replace(bind_char + p, str(params[p]))
		print(sql)

		self.db.run(sql)

	def calculate_metrics(self,run_mets=None):
		'''
		Loops over the configured metrics and runs them.  If a list was provided, it only runs the ones in the list.
		:param run_mets: list of strings, metric names; or else None meaning calculate all configured metrics
		:return:
		'''

		for metric in self.metric_dict.keys():
			if (run_mets is not None and metric not in run_mets) or metric in self.non_metrics:
				continue

			self.run_one_metric_calculation(metric)

'''
####################################################################################################
The main script for calculating Fight Churn With Data metrics in batch: If there are command line arguments,
use them. Otherwise defaults are hard coded

'''

if __name__ == "__main__":

	args, _ = parser.parse_known_args()

	schema=args.schema
	run_mets = args.metrics
	no_warn = args.nowarn

	met_calc = MetricCalculator(schema)
	met_calc.remove_old_metrics_from_db(run_mets,no_warn)
	met_calc.calculate_metrics(run_mets)


import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog
from PIL import Image, ImageTk, ImageFile
import subprocess
import os
import json

from constants import *
from logic import get_page_maps

ImageFile.LOAD_TRUNCATED_IMAGES = True

class ToolBar(tk.Frame):
    def __init__(self, master, vars, **kwargs):
        super().__init__(master, **kwargs)

        self.vars = vars
        self.search = ""

        left_frame = tk.Frame(self)
        left_frame.pack(side= tk.LEFT)

        center_frame = tk.Frame(self)
        center_frame.pack(side= tk.RIGHT)

        search_entry = tk.Entry(left_frame, textvariable=self.vars["search_word"])
        search_button = ttk.Button(left_frame, text="搜索", width=6)
        kind_selector = ttk.Combobox(left_frame, width=15, values=SUGGEST,
                                     textvariable=self.vars["kind_selector"])
        search_reset = ttk.Button(left_frame, text="重置", width=6)

        left_button = ttk.Button(center_frame, text="上一页")
        page_label = tk.Label(center_frame, text="当前页面: ")
        page_i_label = tk.Label(center_frame, textvariable=self.vars["page_index"])
        page_label2 = tk.Label(center_frame, text="总地图数量: ")
        nums_label = tk.Label(center_frame, textvariable=self.vars["nums_count"])
        right_button = ttk.Button(center_frame, text="下一页")

        search_entry.grid(row=0, column=0)
        search_button.grid(row=0, column=1, padx=5)
        kind_selector.grid(row=0, column=2)
        search_reset.grid(row=0, column=3, padx=5)

        left_button.grid(row=0, column=0)
        page_label.grid(row=0, column=1)
        page_i_label.grid(row=0, column=2, padx=10)
        page_label2.grid(row=0, column=3)
        nums_label.grid(row=0, column=4, padx=10)
        right_button.grid(row=0, column=5)

        self.widgets = {
            "left": left_button,
            "right": right_button,
            "search": search_button,
            "reset": search_reset,

            "return_search":  search_entry,
            "select_search": kind_selector
        }

    def bind_funcs(self, **funcs):
        for k in funcs:
            if k.startswith("return") and k in self.widgets:
                self.widgets[k].bind("<Return>", funcs[k])
            elif k.startswith("select") and k in self.widgets:
                self.widgets[k].bind("<<ComboboxSelected>>", funcs[k])
            elif k in self.widgets:
                self.widgets[k].config(command=funcs[k])

class MapBoard(tk.Frame):
    def __init__(self, master, map_path, size, cr):
        super().__init__(master)
        self.map_path = map_path
        self.size = size
        self.c = cr[0]
        self.r = cr[1]

        self.img_list = [None for _ in range(self.r * self.c)]
        self.label_list = [None for _ in range(self.r * self.c)]
        self.text_list = [None for _ in range(self.r * self.c)]
        self.page_info = get_page_maps(self.map_path, page=0, nums=self.r * self.c)

        self.vars = {}

    def set_vars_map(self, vars):
        self.vars = vars

    def refresh_with_setting(self, **kwargs):
        """
        :param kwargs: dict, keys:map_path, size, cr,
        """
        if "map_path" in kwargs:
            self.map_path = kwargs["map_path"]
        if "size" in kwargs:
            self.size = kwargs["size"]
        if "cr" in kwargs:
            self.c, self.r = kwargs["cr"]

        lst = self.grid_slaves()
        for l in lst:
            l.destroy()

        self.img_list = [None for _ in range(self.r * self.c)]
        self.label_list = [None for _ in range(self.r * self.c)]
        self.text_list = [None for _ in range(self.r * self.c)]
        self.page_info = get_page_maps(self.map_path, page=0, nums=self.r * self.c)
        self.show_page_by_index(0)

    def refresh_vars(self):
        if "page_index" in self.vars:
            pi_str = "%s / %s" % (self.page_info["page"] + 1, self.page_info["pages"])
            self.vars["page_index"].set(pi_str)

        if "nums_count" in self.vars:
            self.vars["nums_count"].set(self.page_info["total"])

        if "left_button" in self.vars:
            if self.page_info.get("prev"):
                self.vars["left_button"].config(state=tk.NORMAL)
            else:
                self.vars["left_button"].config(state=tk.DISABLED)

        if "right_button" in self.vars:
            if self.page_info.get("next"):
                self.vars["right_button"].config(state=tk.NORMAL)
            else:
                self.vars["right_button"].config(state=tk.DISABLED)

        if "show_info" in self.vars:
            if os.path.exists(self.map_path):
                self.vars["show_info"].set("")
            else:
                self.vars["show_info"].set("你的地图文件夹不存在或已丢失")

    def show_page_by_index(self, index):
        if os.path.exists(self.map_path):
            key = self.vars["search_val"]
            self.page_info = get_page_maps(self.map_path, page=index, nums=self.r * self.c, filter=key)
        else:
            self.page_info = {}
        for i in range(self.r * self.c):
            ri = i // self.c
            ci = i % self.c

            if i < len(self.page_info["maps"]):
                map_info = self.page_info["maps"][i]
                if "art_tga" in map_info:
                    self.img_list[i] = Image.open(map_info["art_tga"])
                elif "tga" in map_info:
                    self.img_list[i] = Image.open(map_info["tga"])
                else:
                    self.img_list[i] = Image.new("RGB", IMG_SIZE[self.size], (0, 0, 0))

                # print(map_info["dir"])
                # if map_info["dir"] == "D:/Documents/Red Alert 3/other\(as)kuzhanmaqinuo1.6":
                #     print("debug")
                self.img_list[i] = self.img_list[i].resize(IMG_SIZE[self.size])
                self.img_list[i] = ImageTk.PhotoImage(self.img_list[i])

                if self.label_list[i] is None:
                    self.label_list[i] = tk.Label(self, image=self.img_list[i])
                    self.label_list[i].grid(row=ri * 2, column=ci)
                    self.label_list[i].bind("<Double-Button-1>", lambda e, i=i: self.click_map(i))
                else:
                    self.label_list[i].config(image=self.img_list[i])

                if self.text_list[i] is None:
                    tr = LINES[self.size]
                    # self.text_list[i] = tk.Label(self, text=map_info["map"][:self.max_width], width=self.max_width)
                    self.text_list[i] = tk.Text(self, width=MAX_WIDTH[self.size], height=tr, background=TEXT_BG)
                    self.text_list[i].insert(tk.END, map_info["map"])
                    self.text_list[i].grid(row=ri * 2 + 1, column=ci)
                    self.text_list[i].configure(state='disabled')
                else:
                    self.text_list[i].configure(state='normal')
                    self.text_list[i].delete("1.0", "end")
                    self.text_list[i].insert(tk.END, map_info["map"])
                    self.text_list[i].configure(state='disabled')
            else:
                # 最后一页的空白位置
                self.img_list[i] = Image.new("RGB", IMG_SIZE[self.size], BLANK)
                self.img_list[i] = ImageTk.PhotoImage(self.img_list[i])

                if self.label_list[i] is None:
                    self.label_list[i] = tk.Label(self, image=self.img_list[i])
                    self.label_list[i].grid(row=ri * 2, column=ci)
                    self.label_list[i].bind("<Double-Button-1>", lambda e, i=i: self.click_map(i))
                else:
                    self.label_list[i].config(image=self.img_list[i])

                if self.text_list[i] is None:
                    tr = LINES[self.size]
                    self.text_list[i] = tk.Text(self, width=MAX_WIDTH[self.size], height=tr, background=TEXT_BG)
                    self.text_list[i].grid(row=ri * 2 + 1, column=ci)
                    self.text_list[i].configure(state='disabled')
                else:
                    self.text_list[i].configure(state='normal')
                    self.text_list[i].delete("1.0", "end")
                    self.text_list[i].configure(state='disabled')

        self.refresh_vars()

    def click_map(self, index):
        if "maps" in self.page_info and index <len(self.page_info["maps"]):
            map_info = self.page_info["maps"][index]
            dir_path = map_info["dir"]

            dir_path= dir_path.replace("/", "\\")
            subprocess.Popen(r'explorer /select,"%s"' % dir_path)

    def search(self, event=None):
        if self.vars["search_val"] != self.vars["search_word"].get():
            self.vars["search_val"] = self.vars["search_word"].get()
            self.show_page_by_index(0)

    def reset_search(self):
        self.vars["search_word"].set("")
        self.vars["search_val"] = ""

        self.show_page_by_index(0)

    def select_search(self, event=None):
        val = self.vars["kind_selector"].get()
        if val in SUGGEST and val != SUGGEST[0]:
            self.vars["search_val"] = val
            self.show_page_by_index(0)

    def prev_page(self):
        if self.page_info.get("prev"):
            prev_index = self.page_info["page"] - 1
            self.show_page_by_index(prev_index)

    def next_page(self):
        if self.page_info.get("next"):
            next_index = self.page_info["page"] + 1
            self.show_page_by_index(next_index)

class MainBoard(tk.Frame):
    def __init__(self, master, **kwargs):
        super().__init__(master, **kwargs)
        self.setting = {}
        self.vars = {}

    def set_setting(self, **setting):
        """
        :param setting: dict, keys: map_path, size, cr, font
        """
        self.setting.update(setting)

    def set_vars_main(self, vars):
        self.vars = vars

    def refresh(self):
        self.map_board.refresh_with_setting(
            map_path=self.setting["map_path"], size=self.setting["size"], cr=self.setting["cr"])

    def init(self):
        frame_top = ToolBar(self, self.vars)
        frame_top.pack(fill="x")

        self.map_board = MapBoard(self, self.setting["map_path"], self.setting["size"], self.setting["cr"])
        self.map_board.set_vars_map(self.vars)
        self.map_board.show_page_by_index(0)
        self.map_board.pack()

        frame_bottom = tk.Frame(self)
        frame_bottom.pack()
        tk.Label(frame_bottom, text="双击地图图片，即可在文件浏览器中打开地图文件夹", font=self.setting["font_1"]).grid()
        tk.Label(frame_bottom, textvariable=self.vars["show_info"], font=self.setting["font_1"], fg="#FF69B4").grid()

        self.map_board.refresh_vars()

        frame_top.bind_funcs(left=self.map_board.prev_page, right=self.map_board.next_page,
                             search=self.map_board.search, reset=self.map_board.reset_search,
                             return_search=self.map_board.search, select_search=self.map_board.select_search)

        self.master.bind('<Left>', lambda e: self.map_board.prev_page())
        self.master.bind('<Right>', lambda e: self.map_board.next_page())

class SettingBoard(tk.Frame):
    def __init__(self, master):
        super().__init__(master)

        self.init_done = False

        self.local_vars = {}
        self.local_vars["r"] = tk.IntVar(self, 0)
        self.local_vars["c"] = tk.IntVar(self, 0)
        self.local_vars["size"] = tk.StringVar(self, "S")

    def read_setting(self, main_board):
        self.local_vars["mb"] = main_board
        self.local_vars["size"].set(main_board.setting["size"])
        self.local_vars["c"].set(main_board.setting["cr"][0])
        self.local_vars["r"].set(main_board.setting["cr"][1])

    def set_vars(self, vars):
        """
        :param vars: dict, keys: map_path(StringVar), setting_info(StringVar)
        """
        self.vars = vars

    def init(self):
        ROW1 = tk.Frame(self)
        ROW2 = tk.Frame(self)
        ROW3 = tk.Frame(self)
        ROW1.pack()
        ROW2.pack()
        ROW3.pack()
        label0 = ttk.Label(ROW1, textvariable=self.vars["show_info"], foreground="red")
        label0.grid(row=0, columnspan=2, pady=10)

        b0 = ttk.Button(ROW1, text="修改地图文件夹", command=self.select_dir)
        b0.grid(row=1, column=0)

        label_1 = ttk.Entry(ROW1, textvariable=self.vars["map_path"], state="disabled", width=80)
        label_1.grid(row=1, column=1, columnspan=2)

        ttk.Label(ROW2, text="行数：").grid(row=0, column=0)
        ttk.Label(ROW2, text="列数：").grid(row=1, column=0)

        tk.Scale(ROW2, from_=ROW_RANGE[0], to=ROW_RANGE[1], variable=self.local_vars["r"], orient='horizontal',
                 length=RANGE_WIDTH * (ROW_RANGE[1] - ROW_RANGE[0])).grid(row=0, column=1, columnspan=3)
        tk.Scale(ROW2, from_=COLUMN_RANGE[0], to=COLUMN_RANGE[1], variable=self.local_vars["c"], orient='horizontal',
                 length=RANGE_WIDTH * (COLUMN_RANGE[1] - COLUMN_RANGE[0])).grid(row=1, column=1, columnspan=3, padx=10)

        ttk.Label(ROW2, textvariable=self.local_vars["r"]).grid(row=0, column=4)
        ttk.Label(ROW2, textvariable=self.local_vars["c"]).grid(row=1, column=4)

        ttk.Label(ROW2, text="图片大小：").grid(row=2, column=0, padx=10, pady=10)
        tk.Radiobutton(ROW2, text="小", variable=self.local_vars["size"], value="S", width=7,
                       indicatoron=False).grid(row=2, column=1)
        tk.Radiobutton(ROW2, text="中", variable=self.local_vars["size"], value="M", width=7,
                       indicatoron=False).grid(row=2, column=2)
        tk.Radiobutton(ROW2, text="大", variable=self.local_vars["size"], value="L", width=7,
                       indicatoron=False).grid(row=2, column=3)

        tk.Button(self, text="保存并退出", command=self.save).pack(pady=10)
        tk.Button(self, text="返回", command=self.back).pack(pady=10)
        self.init_done = True

    def save(self):
        map_path = self.vars["map_path"].get()
        c = self.local_vars["c"].get()
        r = self.local_vars["r"].get()
        size = self.local_vars["size"].get()
        self.pack_forget()

        data = {
            "size": size,
            "c": c,
            "r": r
        }

        with open(JSON_NAME, "w") as f:
            json.dump(data, f)

        self.local_vars["mb"].set_setting(map_path=map_path, size=size, cr=(c, r))
        self.local_vars["mb"].refresh()

        self.local_vars["mb"].pack()

    def back(self):
        self.pack_forget()
        self.local_vars["mb"].pack()

    def select_dir(self):
        try:
            dir = filedialog.askdirectory()
            if dir:
                self.vars["map_path"].set(dir)
                print(dir)

            self.vars["show_info"].set("")
        except Exception as e:
            self.vars["show_info"].set(str(e))

def open_setting(gvars):
    gvars["mb"].pack_forget()
    gvars["sb"].read_setting(gvars["mb"])
    if not gvars["sb"].init_done:
        gvars["sb"].init()
    gvars["sb"].pack()


import os
import glob
import cv2 as cv

X_path = glob.glob(os.path.join('DiretorioEscolhido/NomePasta', '*'))

X = []

for f in X_path:
    try:
        cv.imwrite(f,cv.resize(cv.imread(f), (224, 224), interpolation=cv.INTER_AREA))

    except:
        print(f)


import copy
from collections import defaultdict

from game_board import GameBoard

########################################################################################################################
# PUBLIC INTERFACE
########################################################################################################################
def solve(input_board, max_iterations):
    """ Entry point to the solvers. Just calling this function, by default, should yield "good" results.

    The idea is that it'll call whatever solver happens to be the best at some point, depending on what's implemented.
    """
    # Define a pipeline of solvers to use. Since the intermediate solutions of each solver should be valid, the
    # intermediate results can be fed into one another.
    solvers = [
        _deductive,
        _backtrack
    ]

    intermediate_board = input_board
    for solver in solvers:
        intermediate_board = solver(intermediate_board, max_iterations)
        if intermediate_board.is_solved():
            break

    return intermediate_board

########################################################################################################################
# INTERNALS (here be dragons)
########################################################################################################################
def report_start(solver_name, occupancy):
    print(f"[{solver_name}] starting. Starting board occupancy at {occupancy:.2f}.")

def report_progress(solver_name, iterations, max_iterations):
    if iterations % 100 == 0:
        print(f"[{solver_name}]: {(iterations/max_iterations)*100:.2f}% of max_iterations.", end="\r")

def report_result(solver_name, solved, occupancy, reached_max_iterations):
    print(f"[{solver_name}] finished. Solved? {solved}. Final occupancy: {occupancy:.2f}. Reached maximum iterations? {reached_max_iterations}")

def _backtrack(input_board, max_iterations):
    """ Use the backtrack method to solve a board.

    The backtrack method is usually described/implemented as a recursive call, but I'm allergic to recursive programs.

    Since this was always going to be a lengthy function, I decided to break up the main loop into sub-functions that
    operate on the function's shared state and describe the atomic functions of the algorithm. This allowed me to define
    the main loop in almost 1-to-1 correspondence with the algorithm. This allows me to both understand the algorithm as
    a composition of operations, and perhaps move out functionality in the future.

    I'm not sure about this structure, but I'll leave it as an example. Perhaps a class would've been a better
    representation.

    Reference: https://en.wikipedia.org/wiki/Sudoku_solving_algorithms#Backtracking
    """
    # Duplicate the input board so we don't change it in place:
    board = copy.deepcopy(input_board)

    # Initilise state
    report_start("Backtrack", board.occupancy())
    cells = list(board.board_iterator())
    current_cell_idx = 0
    iterations = 0

    # Basic functions on state
    def get_current_value():
        i, j = cells[current_cell_idx]
        val = board.value(i, j)

        return val

    def initialise():
        i, j = cells[current_cell_idx]
        board.value(i, j, 1)

    def increment():
        i, j = cells[current_cell_idx]
        board.increment(i, j)

    def backtrack():
        nonlocal current_cell_idx
        # Clear cell and backtrack
        i, j = cells[current_cell_idx]
        board.erase(i, j)
        current_cell_idx -= 1

        # Skip over fixed cells
        while current_cell_idx > 0 and board.is_fixed(*cells[current_cell_idx]):
            current_cell_idx -= 1

    def advance():
        nonlocal current_cell_idx
        current_cell_idx += 1

        # Skip over fixed cells
        while current_cell_idx < len(cells) and board.is_fixed(*cells[current_cell_idx]):
            current_cell_idx += 1

    # The main loop is split into three essential clauses:
    # * If the value is empty, it's initialised as 1.
    # * If the value is out of bounds, we backtrack to the previous element we were looking at.
    # * If the board is not valid, we increment the current value.
    # If none of these clauses get triggered, we simply move on to the next cell.
    while not board.is_solved() and iterations < max_iterations and current_cell_idx < 81:
        iterations += 1
        curr_value = get_current_value()
        report_progress("Backtrack", iterations, max_iterations)

        # If the cell is empty, we set it to 1 and move on
        if curr_value == None:
            initialise()
            continue

        # If the cell or board is not a valid value anymore, we erase it and move back
        if curr_value not in board._valid_values:
            backtrack()
            increment()
            continue

        # If the current value is a valid number, we increment it
        if not board.is_valid():
            increment()
            continue

        # And if the board remains valid, we move on
        advance()

    report_result("Backtrack", board.is_solved(), board.occupancy(), iterations == max_iterations)

    return board

def _deductive(input_board, max_iterations):
    """ Implements a deductive method for solving the given board.

    This is based on the common heuristic everyone uses (I assume) where we pencil in the possible values for each cell
    and then unravel the puzzle from there.
    """
    # Duplicate the input board so we don't change it in place:
    board = copy.deepcopy(input_board)
    report_start("Deductive", board.occupancy())

    # We'll keep the pencilled-in numbers here
    pencil_board = defaultdict(set)
    valid_values = board._valid_values

    # Sub-functions
    def generate_pencil_board():
        print("[Deductive] solver generating pencil board.")
        for i, j in board.board_iterator():
            # Only work on empty cells
            if board.value(i, j) == None:
                # Iterate over all valid values
                for val in valid_values:
                    # Try adding, if it works it's a possible value
                    if try_adding_value(i, j, val):
                        key = (i, j)
                        pencil_board[key].add(val)
                        board.erase(i, j)

    def try_adding_value(i, j, value):
        """ Adds a value to the board only if the resulting board is valid.

        Returns whether the value stuck.
        """
        board.value(i, j, value)
        if not board.is_valid():
            board.erase(i, j)
            return False

        return True

    # Start by pencilling in all possibilities
    generate_pencil_board()

    iterations = 0
    while iterations < max_iterations and not board.is_solved() and len(pencil_board) > 0:
        iterations += 1
        report_progress("Deductive", iterations, max_iterations)

        # Iterate over the pencilled board
        for (i, j), values in pencil_board.items():
            # If there's only one possible value for a given cell, we write it in
            if len(values) == 1:
                # TODO: why would this not be valid?
                # TODO: surely we can get stuff from the set without making it into a list
                try_adding_value(i, j, list(values)[0])
                pencil_board[(i, j)] = []
                continue

            # If the current value is the only possible position for this value in this sub-board, we write it in
            sub_board_positions = board.sub_board_positions(*board.sub_board_from_indices(i, j))
            for value in values:
                # Evaluate whether the value is the only possibility for this value in this sub-board
                only_possibility_in_sub_board = True
                for sub_i, sub_j in sub_board_positions:
                    # Only check the pencil board if the key exists, since accessing the defaultdict on a non-existing
                    # key will add it to the dict and, thus, crash us as we're changing the dict mid-iteration.
                    if (sub_i, sub_j) in pencil_board.keys():
                        only_possibility_in_sub_board = not (value in pencil_board[(sub_i, sub_j)])

                # Write the value in and break early since we won't have another value for the current cell
                if only_possibility_in_sub_board:
                    board.value(i, j, value)
                    pencil_board[(i, j)].remove(value)
                    break

    report_result("Deductive", board.is_solved(), board.occupancy(), iterations == max_iterations)

    return board


def helper(n, newDict) -> int:
    sum = 0
    temp = n
    while n > 0:
        sum += (n % 10) ** 2
        n = n // 10

    if temp not in newDict:
        newDict[temp] = sum

    if sum == 1:
        return True

    if sum in newDict:
        return False
    return helper(sum, newDict)

class Solution:
    def isHappy(self, n: int) -> bool:
        newDict = {}
        return helper(n, newDict)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""BMP 室温気圧センサー."""

import logging
from datetime import datetime

import Adafruit_BMP.BMP085 as BMP085

from db import MongoDB

class Bmp(MongoDB):
    """BMP180 IO."""

    def __init__(self):
        """イニシャライザ."""
        super().__init__()

        # センサー
        self.sensor = BMP085.BMP085()

        # MongoDB
        db_name = 'bmp'
        self.db = self.client[db_name]

    def __str__(self):
        return "bmp"

    def get_sensor(self):
        """Get センサー値.

        Returns
        -------
        dict
            各センサー値

        """
        try:
            return {
                'btemp': float(self.sensor.read_temperature()),
                'press': round(float(self.sensor.read_pressure()) / 100, 1),
                'alti': round(float(self.sensor.read_altitude()) / 100, 1),
                'sealev': float(self.sensor.read_sealevel_pressure()),
                'timestamp': datetime.now()
            }

        except Exception as e:
            logging.error('SensorError: {}'.format(e))
            return None


import numpy as np
import plotly.offline as pyo
import plotly.graph_objs as go
np.random.seed(56)

# data
x_values = np.linspace(0,1,100)
y_values = np.random.randn(100)

# edited this to make a line chart
trace0 = go.Scatter(x=x_values, y=y_values+5,
                   mode='markers+lines',
                   name='markers')

trace1 = go.Scatter(x=x_values, y=y_values,
                   mode='lines',
                   name='lines')
# data list
data=[trace0, trace1] #needs to be a list in plotly

# Layout is optional to edit titles, axis, etc
layout = go.Layout(title='Line Chart')

fig = go.Figure(data=data, layout=layout)
pyo.plot(fig)


'''
Created on 06/01/2014

@author: jcpenuela
'''
def modifica(lista):
    lista[0]=100

def original():
    lista = [0,1,2,3]
    print(lista)
    modifica(lista)
    print(lista)

if __name__ == '__main__':
    print('prueba')
    original()


import sys
input = sys.stdin.readline

N = int(input())
cnt = 0
letter = []
no = False
for _ in range(N):
    for i in input().strip():
        if not i in letter:
            letter.append(i)
        else:
            if i == letter[-1]:
                continue
            else:
                no = True
    letter = []
    if no:
        no = False
        continue
    else:
        cnt += 1
print(cnt)

백준/Silver/1316. 그룹 단어 체커/그룹 단어 체커.py


import sys
import numpy as np
from fractions import Fraction

if __name__ == "__main__":
    readFile = open(sys.argv[1], "r")
    writeFile = open("out.txt", "w")

    numeroCasos = int(readFile.readline())
    casoMinimo = int(sys.argv[2])
    casoMaximo = int(sys.argv[3])

    for _ in range(casoMinimo-1):
        readFile.readline()
        readFile.readline()

    for caseNumber in range(casoMinimo, casoMaximo+1):
        numeroEntradas = int(readFile.readline())
        valores = readFile.readline().split()
        valores = list(map(int,valores))
        lcmVal = np.lcm.reduce(valores)

        newValores = [i * lcmVal for i in valores]
        sumaCaramelos = sum(newValores)
        numer = Fraction(sumaCaramelos,len(newValores)).numerator
        denom = Fraction(sumaCaramelos,len(newValores)).denominator
        print("Case #%i: %i/%i\n" % (caseNumber, numer, denom))
        writeFile.write("Case #%i: %i/%i\n" % (caseNumber, numer, denom))


from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn import metrics
from sklearn.experimental import enable_halving_search_cv
from sklearn.model_selection import RepeatedStratifiedKFold, GridSearchCV, HalvingGridSearchCV
from functions import *
import numpy as np

#%%

with open('feature_matrix.pkl', 'rb') as f:
    feat_matrix = pickle.load(f)

rawTruth = read_truth_data()
truths = truthimport(rawTruth)
labels = truths['same']
results = []
#%%

#deal with Nan values, normalize data #split into train and test sets
cv = RepeatedStratifiedKFold(n_splits=5)
imputer = SimpleImputer(missing_values=np.nan, strategy='mean')
input_matrix = normalize(imputer.fit_transform(feat_matrix))
X_train, X_test, y_train, y_test = split_data(input_matrix, labels)

#%%
lg = LogisticRegression(C=0.01, penalty='l2', solver='newton-cg', max_iter=1000)
#lg = LogisticRegression()

lg.fit(X_train, y_train)
lg_pred = lg.predict(X_test)
lg_acc = metrics.accuracy_score(y_test, lg_pred)
lg_auc = metrics.roc_auc_score(y_test, lg_pred)
lg_rep = metrics.classification_report(y_test, lg_pred)

#%%
svm = SVC(C=5, gamma=0.01, kernel='rbf')
#svm = SVC()

svm.fit(X_train, y_train)
svm_pred = svm.predict(X_test)
svm_acc = metrics.accuracy_score(y_test, svm_pred)
svm_auc = metrics.roc_auc_score(y_test, svm_pred)
svm_rep = metrics.classification_report(y_test, svm_pred)

#%%

rf = RandomForestClassifier(max_depth=90, max_features=2, min_samples_leaf=3, min_samples_split=10, n_estimators=200)
#rf = RandomForestClassifier()

rf.fit(X_train, y_train)
rf_pred = rf.predict(X_test)
rf_acc = metrics.accuracy_score(y_test, rf_pred)
rf_auc = metrics.roc_auc_score(y_test, rf_pred)
rf_rep = metrics.classification_report(y_test, rf_pred)

#%%
mlp = MLPClassifier(activation='relu', alpha=0.0001, hidden_layer_sizes=(100,), learning_rate='constant', solver='adam', max_iter=1000)
#mlp = MLPClassifier(max_iter=1000)

mlp.fit(X_train, y_train)
mlp_pred = mlp.predict(X_test)
mlp_acc = metrics.accuracy_score(y_test, mlp_pred)
mlp_auc = metrics.roc_auc_score(y_test, mlp_pred)
mlp_rep = metrics.classification_report(y_test, mlp_pred)

#%%#Leave-one_out method to see which features contribute

# acc_scores = []
# for i in range(len(feat_matrix.T)):
#     print(i)
#     lg_i = LogisticRegression()
#     X_train_i = np.delete(X_train, obj = i, axis = 1 )
#     X_test_i = np.delete(X_test, obj = i, axis = 1 )
#     lg_i.fit(X_train_i, y_train)
#     lg_pred_i = lg_i.predict(X_test_i)
#     lg_acc_i = metrics.accuracy_score(y_test, lg_pred_i)
#     acc_scores.append(lg_acc_i)


from functools import partial
from typing import Callable, Dict, Tuple

import jax
import jax.numpy as jnp
from chex import dataclass, Array, Scalar, PRNGKey
from tensorflow_probability.substrates import jax as tfp

from ml4wifi.utils.wifi_specs import *
from ml4wifi.utils.measurement_manager import measurement_manager, MeasurementState

tfd = tfp.distributions
tfb = tfp.bijectors

# mean value based on ns-3 equal distance simulation scenario, 1 STA, const MCS
FRAMES_PER_SECOND = 188

# If first measurement is in time t=0s, Kalman filter refuses to work
FIRST_MEASUREMENT_SHIFT = 0.001

N_SAMPLES = 1000

@dataclass
class FTMEstimates:
    distance_estimated: Scalar
    distance_uncertainty: Scalar
    distance_ci_low: Scalar
    distance_ci_high: Scalar
    snr_estimated: Scalar
    snr_uncertainty: Scalar
    snr_ci_low: Scalar
    snr_ci_high: Scalar
    rate_estimated: Scalar
    rate_uncertainty: Scalar
    mcs_estimated: jnp.int32

@dataclass
class SimulationParameters:
    confidence_level: Scalar
    measurement_interval: Scalar
    seed: jnp.int32
    simulation_time: Scalar
    start_position: Scalar
    velocity: Scalar
    total_frames: jnp.int32

@dataclass
class SimulationResults:
    time: Array
    distance: Dict
    snr: Dict
    mcs: Dict
    rate: Dict

@jax.jit
def ftmrate_log_distance(
        distance_dist: tfd.Distribution,
        confidence_level: jnp.float32,
        key: PRNGKey
) -> FTMEstimates:
    """
    Estimates distance, SNR and MCS from distance samples.

    Parameters
    ----------
    distance_dist : tfd.Distribution
        Distribution of distance estimation
    confidence_level : jnp.float32
        Confidence level of the estimations
    key : PRNGKey
        Seed

    Returns
    -------
    estimates : FTMEstimates
        Dataclass with all the estimations, uncertainties and the selected mcs
    """

    alpha = 1 - confidence_level

    snr_dist = distance_to_snr(tfb.Softplus()(distance_dist))
    rate_dist = expected_rates_log_distance(DEFAULT_TX_POWER)(tfb.Softplus()(distance_dist))

    rate_estimated = rate_dist.quantile(0.5)
    mcs_estimated = jnp.argmax(rate_estimated)

    return FTMEstimates(
        distance_estimated=distance_dist.quantile(0.5),
        distance_uncertainty=0.0,
        distance_ci_low=distance_dist.quantile(alpha / 2),
        distance_ci_high=distance_dist.quantile(1 - alpha / 2),
        snr_estimated=snr_dist.quantile(0.5),
        snr_uncertainty=0.0,
        snr_ci_low=snr_dist.quantile(alpha / 2),
        snr_ci_high=snr_dist.quantile(1 - alpha / 2),
        rate_estimated=rate_estimated,
        rate_uncertainty=0.0,
        mcs_estimated=mcs_estimated,
    )

@jax.jit
def ftmrate_log_distance_monte_carlo(
        distance_dist: tfd.Distribution,
        confidence_level: jnp.float32,
        key: PRNGKey
) -> FTMEstimates:
    """
    Estimates distance, SNR and MCS from distance samples.

    Parameters
    ----------
    distance_dist : tfd.Distribution
        Distribution of distance estimation
    confidence_level : jnp.float32
        Confidence level of the estimations
    key : PRNGKey
        Seed

    Returns
    -------
    estimates : FTMEstimates
        Dataclass with all the estimations, uncertainties and the selected mcs
    """

    alpha = 1 - confidence_level

    distance_samples = distance_dist.sample(N_SAMPLES, key)
    distance_estimated = distance_samples.mean()
    distance_uncertainty = distance_samples.std()

    snr_samples = distance_to_snr(jnp.abs(distance_samples))
    snr_estimated = jnp.mean(snr_samples)
    snr_uncertainty = jnp.std(snr_samples)

    p_s_samples = jax.vmap(success_probability_log_distance)(snr_samples)
    rate_samples = p_s_samples * wifi_modes_rates
    rate_estimated = jnp.mean(rate_samples, axis=0)
    rate_uncertainty = jnp.std(rate_samples, axis=0)

    mcs_estimated = ideal_mcs_log_distance(DEFAULT_TX_POWER)(distance_estimated)

    return FTMEstimates(
        distance_estimated=distance_estimated,
        distance_uncertainty=distance_uncertainty,
        distance_ci_low=jnp.quantile(distance_samples, alpha / 2),
        distance_ci_high=jnp.quantile(distance_samples, 1 - alpha / 2),
        snr_estimated=snr_estimated,
        snr_uncertainty=snr_uncertainty,
        snr_ci_low=jnp.quantile(snr_samples, alpha / 2),
        snr_ci_high=jnp.quantile(snr_samples, 1 - alpha / 2),
        rate_estimated=rate_estimated,
        rate_uncertainty=rate_uncertainty,
        mcs_estimated=mcs_estimated,
    )

@partial(jax.jit, static_argnames=['agent_fn', 'frames_total'])
def run_simulation(
        agent_fn: Callable,
        params: SimulationParameters,
        frames_total: jnp.int32
) -> SimulationResults:
    """
    Run one simple simulation of SNR estimation based on noisy distance measurements. The station moves away from
    the AP at constant velocity from some start position and receives noisy measurements at some time intervals.

    Parameters
    ----------
    agent_fn : callable
        Function that initializes the agent.
    params : SimulationParameters
        Parameters of the simulation.
    frames_total : int
        Total number of samples in the simulation.

    Returns
    -------
    results : SimulationResults
        Results of the simulation.
    """

    key = jax.random.PRNGKey(params.seed)
    key, init_key = jax.random.split(key)

    measurements_manager = measurement_manager(params.measurement_interval)
    agent = agent_fn()

    time = jnp.linspace(0.0, params.simulation_time, frames_total) + FIRST_MEASUREMENT_SHIFT
    true_distance = jnp.linspace(0.0, params.velocity * params.simulation_time, frames_total) + params.start_position

    distance = {
        'true': jnp.abs(true_distance),
        'measurement': jnp.empty(frames_total),
        'estimated': jnp.empty(frames_total),
        'uncertainty': jnp.zeros(frames_total),
        'ci_low': jnp.zeros(frames_total),
        'ci_high': jnp.zeros(frames_total),
    }

    snr = {
        'true': distance_to_snr(distance['true']),
        'estimated': jnp.empty(frames_total),
        'uncertainty': jnp.zeros(frames_total),
        'ci_low': jnp.zeros(frames_total),
        'ci_high': jnp.zeros(frames_total),
    }

    mcs = {
        'true': jax.vmap(partial(ideal_mcs_log_distance, tx_power=DEFAULT_TX_POWER))(distance['true']),
        'estimated': jnp.empty(frames_total),
    }

    rate = {
        'true': wifi_modes_rates[mcs['true']],
        'estimated': jnp.empty((frames_total, len(wifi_modes_rates))),
        'uncertainty': jnp.zeros((frames_total, len(wifi_modes_rates)))
    }

    def fori_fn(i: jnp.int32, carry: Tuple) -> Tuple:
        results, state, m_state, key = carry
        key, noise_key, update_key, sample_key, results_key = jax.random.split(key, 5)

        m_state, measured = measurements_manager.update(m_state, distance['true'][i], time[i], noise_key)
        state = jax.lax.cond(measured, lambda: agent.update(state, update_key, m_state.distance, time[i]), lambda: state)

        distance_distribution = agent.sample(state, sample_key, time[i])
        ftm_estimates = ftmrate_log_distance(distance_distribution, params.confidence_level, results_key)

        return save_estimates(ftm_estimates, m_state, i, *results), state, m_state, key

    init = ((distance, snr, rate, mcs), agent.init(init_key), measurements_manager.init(), key)
    (distance, snr, rate, mcs), *_ = jax.lax.fori_loop(0, frames_total, fori_fn, init)

    return SimulationResults(
        time=time,
        distance=distance,
        snr=snr,
        mcs=mcs,
        rate=rate
    )

@jax.jit
def save_estimates(
        ftm_estimates: FTMEstimates,
        m_state: MeasurementState,
        i: jnp.int32,
        distance: Array,
        snr: Array,
        rate: Array,
        mcs: Array
) -> Tuple:
    distance['measurement'] = distance['measurement'].at[i].set(m_state.distance)
    distance['estimated'] = distance['estimated'].at[i].set(ftm_estimates.distance_estimated)
    distance['uncertainty'] = distance['uncertainty'].at[i].set(ftm_estimates.distance_uncertainty)
    distance['ci_low'] = distance['ci_low'].at[i].set(ftm_estimates.distance_ci_low)
    distance['ci_high'] = distance['ci_high'].at[i].set(ftm_estimates.distance_ci_high)

    snr['estimated'] = snr['estimated'].at[i].set(ftm_estimates.snr_estimated)
    snr['uncertainty'] = snr['uncertainty'].at[i].set(ftm_estimates.snr_uncertainty)
    snr['ci_low'] = snr['ci_low'].at[i].set(ftm_estimates.snr_ci_low)
    snr['ci_high'] = snr['ci_high'].at[i].set(ftm_estimates.snr_ci_high)

    rate['estimated'] = rate['estimated'].at[i].set(ftm_estimates.rate_estimated)
    rate['uncertainty'] = rate['uncertainty'].at[i].set(ftm_estimates.rate_uncertainty)

    mcs['estimated'] = mcs['estimated'].at[i].set(ftm_estimates.mcs_estimated)

    return distance, snr, rate, mcs


from CodeBreakers.Data_structures_interview.LinkedList.LinkedList import LinkedList

def remove_duplicates(lst):
    list_len = lst.length()
    if list_len == 0:
        return lst
    elif list_len == 1:
        return lst

    d = dict()
    current = lst.get_head()
    prev = None
    for i in range(0, list_len):
        if current is None:
            break
        if current.data in d:
            next = current.next_element
            prev.next_element = next
            current.next_element = None
            current = next
        else:
            d[current.data] = current.data
            prev = current
            current = current.next_element
    return lst

def remove_duplicates_optimal(self):
    if self.is_empty():
        return

    current_node = self.get_head()
    prev_node = self.get_head()
    # To store values of nodes which we already visited
    visited_nodes = set()
    # If List is not empty and there is more than 1 element in List
    if not self.is_empty() and current_node.next_element:
        while current_node:
            value = current_node.data
            if value in visited_nodes:
                # current_node is already in the HashSet
                # connect prev_node with current_node's next element
                # to remove it
                prev_node.next_element = current_node.next_element
                current_node = current_node.next_element
                continue
            # Visiting currentNode for first time
            visited_nodes.add(current_node.data)
            prev_node = current_node
            current_node = current_node.next_element
    return

# lst = LinkedList()
# lst.insert_at_tail_myCode(6)
# lst.insert_at_tail_myCode(6)
# lst.insert_at_tail_myCode(9)
# lst.insert_at_tail_myCode(10)
# lst.print_list()
# remove_duplicates(lst)
# lst.print_list()


from flask import Flask, render_template , request
import numpy as np
from utils import CarPrice
app = Flask(__name__)

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

@app.route('/valuation' , methods = ['POST','GET'])
def valuation():
    if request.method == 'POST':
        data = request.form.get

        Name = data('Name')
        Location = data('Location')
        Age = eval(data('Age'))
        Kilometers_Driven = eval(data('Kilometers_Driven'))
        Fuel_Type = data('Fuel_Type')
        Transmission = data('Transmission')
        Owner_Type = data('Owner_Type')
        Mileage = eval(data('Mileage'))
        Engine = eval(data('Engine'))
        Power =eval(data('Power'))
        Seats = int(data('Seats'))

        CP = CarPrice(Name, Location, Age, Kilometers_Driven, Fuel_Type,
        Transmission, Owner_Type, Mileage,Engine,Power,Seats)

        Price = CP.prediction()

        return render_template('index.html' , Predicted_Price = np.around(Price, decimals = 2))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080, debug=False)


from jinja2 import Environment, FileSystemLoader

file_loader = FileSystemLoader('templates_dz')
env = Environment(loader=file_loader)

tm = env.get_template('main_dz.html')
msg = tm.render(title='Домашнее задание')
print(msg)


import numpy as np
from tqdm import tqdm
import networkx as nx
import scipy.sparse as sp
import dgl

import random
from time import time
from collections import defaultdict
import warnings
warnings.filterwarnings('ignore')

n_users = 0
n_items = 0
n_entities = 0
n_relations = 0
n_nodes = 0
train_user_set = defaultdict(list)
test_user_set = defaultdict(list)

def read_cf(file_name):
    inter_mat = list()
    lines = open(file_name, "r").readlines()
    for l in lines:
        tmps = l.strip()
        inters = [int(i) for i in tmps.split(" ")]

        u_id, pos_ids = inters[0], inters[1:]
        pos_ids = list(set(pos_ids))
        for i_id in pos_ids:
            inter_mat.append([u_id, i_id])

    return np.array(inter_mat)

def remap_item(train_data, test_data):
    global n_users, n_items
    n_users = max(max(train_data[:, 0]), max(test_data[:, 0])) + 1
    n_items = max(max(train_data[:, 1]), max(test_data[:, 1])) + 1

    for u_id, i_id in train_data:
        train_user_set[int(u_id)].append(int(i_id))
    for u_id, i_id in test_data:
        test_user_set[int(u_id)].append(int(i_id))

#KGIN이 tiple 개수 두배인거 같은데ㅜ
def read_triplets(file_name):
    global n_entities, n_relations, n_nodes

    can_triplets_np = np.loadtxt(file_name, dtype=np.int32)
    can_triplets_np = np.unique(can_triplets_np, axis=0)

    if args.inverse_r:
        # get triplets with inverse direction like <entity, is-aspect-of, item>
        inv_triplets_np = can_triplets_np.copy()
        inv_triplets_np[:, 0] = can_triplets_np[:, 2]
        inv_triplets_np[:, 2] = can_triplets_np[:, 0]
        inv_triplets_np[:, 1] = can_triplets_np[:, 1] + max(can_triplets_np[:, 1]) + 1
        # consider two additional relations --- 'interact' and 'be interacted'
        can_triplets_np[:, 1] = can_triplets_np[:, 1] + 1
        inv_triplets_np[:, 1] = inv_triplets_np[:, 1] + 1
        # get full version of knowledge graph
        triplets = np.concatenate((can_triplets_np, inv_triplets_np), axis=0)
    else:
        # consider two additional relations --- 'interact'.
        can_triplets_np[:, 1] = can_triplets_np[:, 1] + 1
        triplets = can_triplets_np.copy()

    n_entities = max(max(triplets[:, 0]), max(triplets[:, 2])) + 1  # including items + users
    n_nodes = n_entities + n_users
    n_relations = max(triplets[:, 1]) + 1

    train_kg_dict = defaultdict(list)
    for row in triplets:
        h, r, t = row
        train_kg_dict[h].append((t, r))

    cs = []
    for ii in range(n_relations):
        idx = np.where(triplets[:, 1] == ii)[0]
        cs.append(len(list(set(triplets[idx, 0].tolist()))))
    cs = np.array(cs)
    # cs=cs/np.sum(cs)
    # dim=256
    # cs=cs*dim
    # cs0=np.around(cs)

    return triplets, train_kg_dict, cs

def build_graph(train_data, triplets):
    # ckg_graph = nx.MultiDiGraph()
    rd = defaultdict(list)

    print("Begin to load interaction triples ...")
    for u_id, i_id in tqdm(train_data, ascii=True):
        rd[0].append([u_id, i_id])

    print("\nBegin to load knowledge graph triples ...")
    for h_id, r_id, t_id in tqdm(triplets, ascii=True):
        # ckg_graph.add_edge(h_id, t_id, key=r_id)
        rd[r_id].append([h_id, t_id])
    return rd

def  build_graph_AK(train_data, triplets):
    """build konwledge graph"""
    relation_dict = {}
    relation_num_dict = {}
    for i in range(n_relations):
        idx = np.where(triplets[:, 1] == i)[0]
        node_pair = triplets[:, [0, 2]][idx]
        name = ('item', i, 'item')
        relation_dict[name] = (node_pair[:, 0].tolist(), node_pair[:, 1].tolist())
        relation_num_dict[name] = len(idx)
    graph_AK = dgl.heterograph(relation_dict)

    """build user-item and item-item graph"""
    relation_dict_ui = {}

    name = ('item', 1, 'user')
    relation_dict_ui[name] = (train_data[:, 1], train_data[:, 0])

    name_graph_UIS = {'user': n_users, 'item': n_items}
    graph_UIS = dgl.heterograph(relation_dict_ui, name_graph_UIS)

    return graph_AK, graph_UIS, relation_num_dict

def build_sparse_relational_graph(relation_dict):
    def _bi_norm_lap(adj):
        # D^{-1/2}AD^{-1/2}
        rowsum = np.array(adj.sum(1))

        d_inv_sqrt = np.power(rowsum, -0.5).flatten()
        d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
        d_mat_inv_sqrt = sp.diags(d_inv_sqrt)

        # bi_lap = adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt)
        bi_lap = d_mat_inv_sqrt.dot(adj).dot(d_mat_inv_sqrt)
        return bi_lap.tocoo()

    def _si_norm_lap(adj):
        # D^{-1}A
        rowsum = np.array(adj.sum(1))

        d_inv = np.power(rowsum, -1).flatten()
        d_inv[np.isinf(d_inv)] = 0.
        d_mat_inv = sp.diags(d_inv)

        norm_adj = d_mat_inv.dot(adj)
        return norm_adj.tocoo()

    adj_mat_list = []
    print("Begin to build sparse relation matrix ...")

    for r_id in tqdm(relation_dict.keys()):
        np_mat = np.array(relation_dict[r_id])
        if r_id == 0:
            cf = np_mat.copy()
            cf[:, 1] = cf[:, 1] + n_users  # [0, n_items) -> [n_users, n_users+n_items)
            vals = [1.] * len(cf)
            adj = sp.coo_matrix((vals, (cf[:, 0], cf[:, 1])), shape=(n_nodes, n_nodes))
        else:
            vals = [1.] * len(np_mat)
            adj = sp.coo_matrix((vals, (np_mat[:, 0], np_mat[:, 1])), shape=(n_nodes, n_nodes))
        adj_mat_list.append(adj)

    norm_mat_list = [_bi_norm_lap(mat) for mat in adj_mat_list]
    mean_mat_list = [_si_norm_lap(mat) for mat in adj_mat_list]
    # interaction: user->item, [n_users, n_entities]
    norm_mat_list[0] = norm_mat_list[0].tocsr()[:n_users, n_users:].tocoo()
    mean_mat_list[0] = mean_mat_list[0].tocsr()[:n_users, n_users:].tocoo()

    return adj_mat_list, norm_mat_list, mean_mat_list

def load_data(model_args, device):
    global args
    args = model_args
    device = device
    directory = args.data_path + args.dataset + '/'

    print('reading train and test user-item set ...')
    train_cf = read_cf(directory + 'train.txt')
    test_cf = read_cf(directory + 'test.txt')
    remap_item(train_cf, test_cf)

    print('combinating train_cf and kg data ...')
    triplets, train_kg_dict, r_num  = read_triplets(directory + 'kg_final.txt')

    print('building the graph ...')
    relation_dict = build_graph(train_cf, triplets)
    graph_AK, graph_UIS,relation_num_dict = build_graph_AK(train_cf, triplets)
    graph_AK = graph_AK.to(device)

    print('building the adj mat ...')
    adj_mat_list, norm_mat_list, mean_mat_list = build_sparse_relational_graph(relation_dict)

    n_params = {
        'n_users': int(n_users),
        'n_items': int(n_items),
        'n_entities': int(n_entities),
        'n_nodes': int(n_nodes),
        'n_relations': int(n_relations),
        'n_kg_train': len(triplets),
        'num_r': r_num,
        'num_r0':relation_num_dict
    }
    user_dict = {
        'train_user_set': train_user_set,
        'test_user_set': test_user_set
    }

    return train_cf, test_cf, user_dict, train_kg_dict, n_params, graph_AK, graph_UIS, \
           [adj_mat_list, norm_mat_list, mean_mat_list]


import uuid
from teine import models, personality_operations

DEFAULT_SHOW_TITLE = 'My first show'

def get_by_id(show_id):
    return models.Show.load(show_id)

def update(show_id, title='', author='', tagline='', description='',
           show_hosts=[], image_id='', language='en-us'):
    show = models.Show.load(show_id)
    if show:
        show.title = title
        show.author = author
        show.tagline = tagline
        show.description = description
        show.show_host_ids = personality_operations.people_to_ids(
            show_id, show_hosts)
        show.image_id = image_id
        show.language = language
        return show.save()
    else:
        raise ValueError

def create(user, title='', author='', tagline='', description='',
           show_hosts=[], image_id='', language='en-us'):
    show_id = str(uuid.uuid4())
    user.show_ids.append(show_id)
    user.save()
    show_host_ids = personality_operations.people_to_ids(show_id, show_hosts)
    return models.Show.create(show_id=show_id, owner_user_id=user.user_id,
                              title=title, author=author, tagline=tagline,
                              description=description,
                              show_host_ids=show_host_ids,
                              image_id=image_id, language=language).save()

def create_default(user):
    return create(user, title=DEFAULT_SHOW_TITLE, author=user.user_id)


from azureml.core import Run
import pickle
import argparse
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score

from dataloader import DataLoader

# model params
C = 0.025
kernel = "linear"

# cross validation params
cv = 5

def get_args():
    parser = argparse.ArgumentParser(description='Process arguments')

    parser.add_argument('--data-folder', type=str, dest='data_folder',
                        default='./dataset', help='Output folder')

    parser.add_argument('--output-folder', type=str, dest='output_folder',
                        default='./output_model', help='Output folder')

    args = parser.parse_args()

    return args

def main():
    args = get_args()

    run = Run.get_context()
    is_offline_run = run.id.startswith('OfflineRun')
    print(f"Is Offline Run: {is_offline_run}")
    if is_offline_run:
        dataloader = DataLoader(args.data_folder)
        X_train, y_train = dataloader.load_training_data()
        X_test, y_test = dataloader.load_test_data()
    else:
        training_data = run.input_datasets['training_dataset']
        test_dataset = run.input_datasets['test_dataset']

        training_df = training_data.to_pandas_dataframe()
        test_df = test_dataset.to_pandas_dataframe()

        training_df = training_df.drop(['Path'], axis=1)
        test_df = test_df.drop(['Path'], axis=1)

        X_train, y_train = training_df.iloc[:, :-1].values, training_df.iloc[:, -1].values
        X_test, y_test = test_df.iloc[:, :-1].values, test_df.iloc[:, -1].values

    clf = svm.SVC(kernel=kernel, C=C)
    scores = cross_val_score(clf, X_train, y_train, cv=cv)

    print(f"Cross validation scores: {scores};")

    clf.fit(X_train, y_train)
    y_pred = clf.predict(X_test)

    accuracy = accuracy_score(y_pred, y_test)

    print(f"Accuracy: {accuracy}")

    model_output = f"{args.output_folder}/classifier.pkl"
    pickle.dump(clf, open(model_output, 'wb'))

if __name__ == "__main__":
    main()


#!usr/bin/env python3
#Jacob Foppes Project 6 Game

#game like pokenmon where you go down differnent paths and can run into pokemon on the way.
# Uses random to randomly slect a pokemon from a list for you to fight
# you fight the poken nad it cna wither be cought or run away attacks are effective or ineffective
# differnt color texts for diffenrt poeple or actions
#   ie prof oak one color
#   you heard a rumble in the busehd another
# for random path lengths: print ... in differnt ammouns based on list of []"......","..",".","..................."]
#use turtle to visualize map
#use tkinter to pupup new window when a fight is happeneing.
import time
import random
import os
from pathlib import Path
import sys
'''Intro: Welocme to the game baisic tutorial.
    Choose your name, color '''

# GLOBAL VARIABLES
savedGames = [] #list of all saved games
auth_usr = ""
save = "" # users current location in the game  game
owd = os.getcwd()
wokeDex = {} #authenitcated users wokedex
currentLevel = 0

with open("accounts.txt","r+") as users:
    games = users.read()
    savedGames = games.split("\n")
print(savedGames)

wokemon = {"Wikachu":10,"Wetapod":5,"Wonix":10,"Wortle":5,"Wewtwo":20,"Wurtterfree":3,"Wattata":4}# dictionary of pokemon with health points
waterWokemon = {"Wyaradose":21, "Wlastoise":8, "Wampert": 10, "Wagicarp":4}
fireWokemon = {"Warmander":6,"Wapidash": 8,"Wagmar": 7, "Wimchar": 4, "Winetails":12}
earthWokemon = {"Whydor":3, "Wolem":5,"Wonix": 18,"Weodude":8, "Womastart": 3}
def print_slow(str):# Credit : Sebastian - Stack overflow https://stackoverflow.com/questions/4099422/printing-slowly-simulate-typing
    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(0.05)
def input_slow(str): # Credit: https://www.101computing.net/python-typing-text-effect/
  for character in str:
    sys.stdout.write(character)
    sys.stdout.flush()
    time.sleep(0.05)
  value = input()
  return value
def battle(randWokemon):# take
    rwok = (randWokemon[0],randWokemon[1]) # extract name and healktgh
    while True:
        wok = input_slow("\nChoose your Wokemon:\n"+str(wokeDex)+"\n")
        if wok in wokeDex:
            global cwokhealth
            global pwokhealth
            pwokhealth = int(wokeDex[wok])
            print_slow("\nYour HP: " + str(pwokhealth) + "\n") #print player helath
            cwokhealth = int(rwok[1])
            print_slow("Oponent HP: " + str(cwokhealth) + "\n")# print oponent helath
            print_slow("\nLooks like its " + wok + " vs " + rwok[0] + "\n")
            time.sleep(1)
            def attack():
                global cwokhealth
                global pwokhealth
                phit1 = random.randrange(0,5,1)#randomly genreated player dammage to compouter
                cwokhealth -= phit1 #subtract hit points form health
                print_slow(wok + " Strikes!\nIt does " + str(phit1) + " dammage!\n\n")
                chit1 = random.randrange(0,5,1)#randomly genereated compouter dammage to play
                pwokhealth -= chit1#subtract hit points form health
                print_slow(rwok[0] + " Strikes!\nIt does " + str(chit1) + " dammage!\n\n")
                print_slow("Oponent HP: " + str(cwokhealth) + "\n")
                print_slow("Your HP: " + str(pwokhealth) + "\n\n")
            attack()
        else:
            print("Please choose a Wokemon from your Wokedex")
            continue

        while pwokhealth > 0 and cwokhealth > 0: # while both players health greate than 0 comntinue the attack function
            attack()
        if pwokhealth <= 0 and  pwokhealth <= cwokhealth: #if comoputer wins
            print_slow("Dang..., Thats tough boss. \nLooks like you lost this one.\nTime to head home and heal your Wokemon\n ")
            loby()
        elif cwokhealth <= 0 and pwokhealth >= cwokhealth: # if player wins
            global currentLevel
            currentLevel += 1
            print_slow("You won!!\nYou now have " + rwok[0] + " added to your wokedex!!\nYou will now move on to "+ str(currentLevel)+"!\n\n")
            wokeDex[rwok[0]] = rwok[1]
            savel()
            loby()

def l1():#game level 1
    global wokemon
    print_slow("Welcome to level 1!\n")
    while True:
        path1 = input_slow("You are wlaking down the street and you encounter a set a of 2 trail heads:\n 'Elk Road', and 'Spoon Drive' which do you take \n Enter 'Elk' or 'Spoon'\n").lower()
        if path1 == "elk":
            print_slow("Your walking down the elk path when you spot something in the bushes...\n")
            time.sleep(.75)
            print_slow(".")
            time.sleep(.75)
            print_slow(".")
            time.sleep(.75)
            print_slow(".")
            randWokemon = random.choice(list(wokemon.items())) #chose random Wokemon from dict of wokemon
            rwok = randWokemon[0] # extract just the name
            while True:
                fight1 = input_slow("\nA wild " + rwok + " appears!!\n Do you battle? or Run away?\n Enter 'Battle', or 'Run\n").lower()
                if fight1 == "run":
                    print_slow("You got away just in time! Better head back.\n\n")
                    time.sleep(2)
                    break
                elif fight1 == "battle":
                    battle(randWokemon)
                else:
                    print_slow("Please choose run or battle\n")
                    continue

        elif path1 == "spoon":
            print_slow("\nYour walking down the Spoon Path and you come to a fork in the path\n The left looks like it leads to a river, and the right looks to be more forrest.\n ")
            while True:
                lefRig = input_slow("Do you Turn left or right\n").lower()
                if lefRig == "left":
                    print_slow("\nWhile Crossing the shallow end of the river, you see some splashing...")
                    time.sleep(.75)
                    print_slow(".")
                    time.sleep(.75)
                    print_slow(".")
                    randWokemon = random.choice(list(waterWokemon.items())) #chose random Wokemon from dict of wokemon
                    rwok = randWokemon[0] # extract just the name
                    fight2 = input_slow("\n\nA wild " + rwok + " appears!!\n Do you battle? or Run away?\n Enter 'Battle', or 'Run'\n").lower()
                    if fight2 == "battle":
                        battle(randWokemon)
                    elif fight2 == "run":
                        print_slow("You got away just in time, better head back to that fork in the path...\n\n")
                        continue
                    else:
                        print_slow("Choose battle, or Run.\n")
                elif lefRig == "right":
                    print_slow("Your take a right on Spoon Path when you spot something in the bushes...\n")
                    time.sleep(.75)
                    print_slow(".")
                    time.sleep(.75)
                    print_slow(".")
                    time.sleep(.75)
                    randWokemon = random.choice(list(wokemon.items())) #chose random Wokemon from dict of wokemon
                    rwok = randWokemon[0] # extract just the name
                    fight1 = input_slow("\nA wild " + rwok + " appears!!\n Do you battle? or Run away?\n Enter 'Battle', or n'Run\n").lower()
                    if fight1 == "run":
                        print_slow("You got away just in time! Better head back to that fork in the path.\n\n")
                        time.sleep(2)
                        continue
                    elif fight1 == "battle":
                        battle(randWokemon)
                    else:
                        print_slow("Choose battle, or Run.\n")
                else:
                    print_slow("Please choose left or right\n")
                    continue

def l2():#game level 2
    print_slow("Welcome to Level 2!\n\n")
    print_slow("You have entered a new area now...\n")
    time.sleep(.25)
    print_slow("You see new kinds of terrain ready to explore!\n")
    time.sleep(.25)
    while True:
        print_slow("To your left you see a massive volcano, and to your right you see a vast rocky desert.\n")
        time.sleep(.15)
        path3 = input_slow("Do you visit the desert or the volcano?\nsay 'Desert', or 'Volcano'\n").lower()
        if path3 == "desert":
            print_slow("You begin to wander the desert.\nThe Sun is beating down on you\n")
            time.sleep(.5)
            print_slow("You see something in the distance....\n")
            time.sleep(.5)
            print_slow("You walk closer......\n")
            time.sleep(.75)
            randWokemon = random.choice(list(earthWokemon.items())) #chose random Wokemon from dict of wokemon
            rwok = randWokemon[0] # extract just the name
            while True:
                fight1 = input_slow("\nA wild " + rwok + " appears!!\n Do you battle? or Run away?\n Enter 'Battle', or n'Run\n").lower()
                if fight1 == "run":
                    print_slow("You got away just in time! Better head back.\n\n")
                    time.sleep(2)
                    continue
                elif fight1 == "battle":
                    battle(randWokemon)
                else:
                    print_slow("Choose battle, or Run.\n")
        elif path3 == "volcano":
            print_slow("You start walking towards the volcano.\n")
            time.sleep(.75)
            print_slow("Suddenly a creature rushes twords you!")
            randWokemon = random.choice(list(fireWokemon.items())) #chose random Wokemon from dict of wokemon
            rwok = randWokemon[0] # extract just the name
            while True:
                fight1 = input_slow("\nA wild " + rwok + " appears!!\n Do you battle? or Run away?\n Enter 'Battle', or n'Run\n").lower()
                if fight1 == "run":
                    print_slow("You got away just in time! Better head back.\n\n")
                    time.sleep(2)
                    continue
                elif fight1 == "battle":
                    battle(randWokemon)
                else:
                    print_slow("Choose battle, or Run.\n")
        else:
            print_slow("Please choose desert, or volcano.\n")
            continue
def l3(): #Game level 3
    print("Level 3 Comming Soon!")
    time.sleep(3)
    pass
levels = {1:l1,2:l2,3:l3}

def loby():# lobby is where the player once logged in, can either view thier Wokedex, or continue playing at the start of thier current  level
    global wokeDex
    global currentLevel
    lvl = open("saveG.txt","r")
    currentLevel = int(lvl.read())
    while True:
        lchoice = input("Hello "+auth_usr+" Welcome to the lobby!\n Your Currently at Level: " + str(currentLevel) + "\nSay 'start' to resume your game, 'view' to view your wokedex, 'Prev' to redo a previos level, or 'Exit' to retun to the main screen."+"\n").lower()
        if lchoice == "start":
            level = open("saveG.txt","r").read()# save game file
            level = int(level)
            levels[level]()# read savegame file and call level finciton based on the text in the file. this text is used as a key in a dictionary of all levels where the values are the fucntions that start the levels
        elif lchoice == "prev":
            if currentLevel == 1:
                print_slow("\nYou have not completed any levels yet!. Come back here after you have progressed.\n")
                time.sleep(1)
                continue
            elif currentLevel == 2:
                try:
                    lev = int(input("You can Visit the Following Levels:\nLevel 1, Level 2\nType the number of the level you want to visit\n"))
                    if lev > currentLevel:
                        print("You can not access this yet.")
                    else:
                        levels[lev]()
                except ValueError:
                    print("Level does not exist.\n")
                    continue
            elif currentLevel == 3:
                try:
                    lev = int(input("You can Visit the Following Levels:\nLevel 1, Level 2, Level 3\nType the number of the level you want to visit\n"))
                    if lev > currentLevel:
                        print("You can not access this yet.\n\n")
                    else:
                        levels[lev]()
                except ValueError:
                    print("Level does not exist.\n")
                    continue

        elif lchoice == "view":
            print("\n"+str(wokeDex)+"\n")
            time.sleep(1)
        elif lchoice == "exit":#exit loby and return to welocme/ main directory
            os.chdir(owd)
            wokeDex = {}
            currentLevel = 0
            welcome()
        else:
            print("Select a valid choice\n")
            time.sleep(.5)

def mkuser(): # if the user does not have an account they can make one
    breaker = True
    while breaker ==True:
        print_slow("Prof. Woke: Wecome to WokeyWorld!")
        pname = input("What shall I call you?\n")
        if pname in savedGames or os.path.exists(pname+"/"):
            print("User already exists. Try again ")
            continue
        else:
            global auth_usr
            global wokeDex
            auth_usr = pname
            savedGames.append(pname) # ad new name to the saved games list
            auth = open("accounts.txt","r+")
            auth.write("\n".join(str(line) for line in savedGames))# write easch line of the saved gmaes list  to the accouts file
            auth.close()
            p = Path(pname)
            os.chdir("savedGames") # changes dir to the users folder so that a new game can be saved
            p.mkdir() # make play direcotry
            os.chdir(pname) # enter player direcotry
            global save
            global wokeDex
            sav = open("saveG.txt", "x") # create save file
            wd = open("wokedex.txt", "x") # create save file
            os.chdir(owd)
            print("Account creation sucessfull. Logged in as:", pname,"\n")
            breaker == False
            newGame()
            break
def saveg():## this fuction can be called to save the game durring play by typing save
    os.chdir("savedGames/" + auth_usr)
    dex = open("wokedex.txt","w")
    for key, value in wokeDex.items():
        dex.write('%s %s\n' % (key, value))
    lvl = open("saveG.txt","w")
    lvl.write(str(currentLevel))
def savel():## this fuction can be called to save the game durring play by typing save
    dex = open("wokedex.txt","w")
    for key, value in wokeDex.items():
        dex.write('%s %s\n' % (key, value))
    dex.close()
    lvl = open("saveG.txt","w")
    lvl.write(str(currentLevel))
    lvl.close()
    print("Game Saved. Your currnet level: "+str(currentLevel))

def newGame():# First Sequence in game after user amkes account
    time.sleep(.25)
    print_slow("\nProf Woke: Hello "+auth_usr+" My Name is Professor Woke! Ill show you arround\n")
    time.sleep(.1)
    print_slow("Prof Woke: Im giving you a wokedex.\n")
    time.sleep(.1)
    print_slow("Prof Woke: This is where you will store the wokemon you catch along the way.\n")
    time.sleep(.1)
    print_slow("Prof Woke: I going to start you off with this Wikachu.\n")
    wokeDex["Wikachu"] = 11
    print("\n",auth_usr,"'s Wokedex:",wokeDex,"\n")
    time.sleep(1)
    global currentLevel
    currentLevel = 1
    saveg()
    loby()
    pass

def welcome():# where user logs in to contine or creates new game
    while True:
        print("\n\nWokemon Gotta Snatch em' all!")
        game = input("To start a new game, say 'New', to continue a game, enter 'cont'\n").lower()
        if game == "new":
            mkuser()
        elif game == "cont":
            while True:
                print("Available saved Games:",savedGames,"\n")
                un = input("Enter your username or type 'Exit to return to main menue\n")
                if un == "exit":
                    welcome()
                    break
                elif un not in savedGames:
                    print("\n User not found. Try agian. OR Type Exit to return to the main screen \n")
                    time.sleep(1)
                elif un in savedGames: #checks username agains list of saved games
                    global auth_usr
                    auth_usr = un
                    global wokeDex
                    os.chdir("savedGames/")
                    os.chdir(auth_usr)
                    with open("wokedex.txt", "r+") as wd:
                        for line in wd:
                            (wok,pow) = line.split()# Create tuple of wokemon/powerlevels
                            wokeDex[(wok)] = pow #break the tuple in to doctiuonary key,value

                    print("\n Found Your Game!\n")

                    print(" Lets Get to it ", auth_usr,"\n")
                    loby()
                    break
        else: print("Please select a valid choice")
welcome()


# Import Package
import matplotlib.pyplot as plt
import time

# membuat fungsi integral
def funcSingle(x):
    return (5*x**7) - (9*x**4) + (4*x) - 2

def funcDouble(x, y):
    return (5*x**7) - (9*y**4) + (4*x) - 2

def funcTriple(x, y, z):
    return (5*x**7) - (9*y**4) + (4*z) - 2

# Nilai Exact
lipat1 = 234880.40
lipat2 = 328064.80
lipat3 = 656401.60

# mendeklarasikan rumus perhitungan
def trapezoidSingle(a, b, n):
    h = float(b-a)/n
    hA = h
    result = 0.5*funcSingle(a) + 0.5*funcSingle(b)
    for i in range(n):
        result += funcSingle(a + i*h)
    result *= hA
    return result

def trapezoidDouble(a, b, c, d, n):
    dx = (b - a) / n
    dy = (d - c) / n
    hA = dx * dy
    I = funcDouble(a, c) + funcDouble(b, d)
    for i in range(n):
        for j in range(n):
            xx = a + i * dx
            yy = c + j * dy
            I += funcDouble(xx, yy)
    I *= hA
    return I

def trapezoidTriple(a, b, c, d, g, h, n):
    dx = (b - a) / n
    dy = (d - c) / n
    dz = (h - g) / n
    hA = dx * dy * dz
    I = funcTriple(a, c, g) + funcTriple(b, d, h)
    for i in range(n):
        for j in range(n):
            for k in range(n):
                xx = a + i * dx
                yy = c + j * dy
                zz = g + k * dz
                I += funcTriple(xx, yy, zz)
    I *= hA
    return I

# Memanggil fungsi
mulaiSingleTrapezoid = time.time()
numericalSingleTrapezoid = trapezoidSingle(3, 5, 100)
stopSingleTrapezoid = time.time()
waktuSingleTrapezoid = stopSingleTrapezoid - mulaiSingleTrapezoid

mulaiDoubleTrapezoid = time.time()
numericalDoubleTrapezoid = trapezoidDouble(3, 5, 7, 9, 100)
stopDoubleTrapezoid = time.time()
waktuDoubleTrapezoid = stopDoubleTrapezoid - mulaiDoubleTrapezoid

mulaiTripleTrapezoid = time.time()
numericalTripleTrapezoid = trapezoidTriple(3, 5, 7, 9, 11, 13, 100)
stopTripleTrapezoid = time.time()
waktuTripleTrapezoid = stopTripleTrapezoid - mulaiTripleTrapezoid

print('\nSingle Trapezoid Integration :', numericalSingleTrapezoid)
print('Waktu Komputasi Single Trapezoid :', waktuSingleTrapezoid)
print('Error Single Trapezoid :', ((lipat1 - numericalSingleTrapezoid)/numericalSingleTrapezoid))

print('\nDouble Trapezoid Integration :', numericalDoubleTrapezoid)
print('Waktu Komputasi Double Trapezoid :', waktuDoubleTrapezoid)
print('Error Single Trapezoid :', ((lipat2 - numericalDoubleTrapezoid)/numericalDoubleTrapezoid))

print('\nDouble Trapezoid Integration :', numericalTripleTrapezoid)
print('Waktu Komputasi Triple Trapezoid :', waktuTripleTrapezoid)
print('Error Single Trapezoid :', ((lipat3 - numericalTripleTrapezoid)/numericalTripleTrapezoid))

# Plotting grafik komparasi waktu komputasi dengan jumlah N
data = {'Lipat-1':waktuSingleTrapezoid, 'Lipat-2':waktuDoubleTrapezoid, 'Lipat-3':waktuTripleTrapezoid}
parameter = list(data.keys())
nilai = list(data.values())
plt.bar(parameter, nilai, color='green', width=0.3)
plt.title('Grafik Waktu Komputasi Integrasi Metode Trapezoid')
plt.xlabel('Integal Lipat')
plt.ylabel('Waktu Komputasi')
plt.show()


import torch
import torch.nn as nn
import torch.nn.functional as F

class Upsampler(nn.Module):
    def __init__(self, in_channels=3, ngf=128):
        super(Upsampler, self).__init__()

        self.up = nn.Sequential(
            nn.ConvTranspose2d(in_channels, ngf * 4, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf * 4),
            nn.ReLU(True),
            # state size. (ngf*4) x 8 x 8
            nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),
            nn.BatchNorm2d(ngf * 2),
            nn.ReLU(True),
            # state size. (ngf*2) x 16 x 16
            nn.ConvTranspose2d( ngf * 2, 3, 4, 2, 1, bias=False),
            nn.Tanh()
            # state size. 3 x 32 x 32
        )

    def forward(self, x):
        return self.up(x)

## From: https://github.com/LukeDitria/CNN-VAE

class ResDown(nn.Module):
    """
    Residual down sampling block for the encoder
    """

    def __init__(self, channel_in, channel_out, kernel_size=3):
        super(ResDown, self).__init__()
        self.conv1 = nn.Conv2d(channel_in, channel_out // 2, kernel_size, 2, kernel_size // 2)
        self.bn1 = nn.GroupNorm(channel_out//2, channel_out//2, affine=True)#nn.BatchNorm2d(channel_out // 2, eps=1e-4)
        self.conv2 = nn.Conv2d(channel_out // 2, channel_out, kernel_size, 1, kernel_size // 2)
        self.bn2 = nn.GroupNorm(channel_out, channel_out, affine=True)#nn.BatchNorm2d(channel_out, eps=1e-4)

        self.conv3 = nn.Conv2d(channel_in, channel_out, kernel_size, 2, kernel_size // 2)

        self.act_fnc = nn.ELU()

    def forward(self, x):
        skip = self.conv3(x)
        x = self.act_fnc(self.bn1(self.conv1(x)))
        x = self.conv2(x)
        return self.act_fnc(self.bn2(x + skip))

class ResUp(nn.Module):
    """
    Residual up sampling block for the decoder
    """

    def __init__(self, channel_in, channel_out, kernel_size=3, scale_factor=2):
        super(ResUp, self).__init__()

        self.conv1 = nn.Conv2d(channel_in, channel_out // 2, kernel_size, 1, kernel_size // 2)
        self.bn1 = nn.GroupNorm(channel_out//2, channel_out//2, affine=True)#nn.BatchNorm2d(channel_out // 2, eps=1e-4)
        self.conv2 = nn.Conv2d(channel_out // 2, channel_out, kernel_size, 1, kernel_size // 2)
        self.bn2 = nn.GroupNorm(channel_out, channel_out, affine=True)#nn.BatchNorm2d(channel_out, eps=1e-4)

        self.conv3 = nn.Conv2d(channel_in, channel_out, kernel_size, 1, kernel_size // 2)

        self.up_nn = nn.Upsample(scale_factor=scale_factor, mode="nearest")

        self.act_fnc = nn.ELU()

    def forward(self, x):
        x = self.up_nn(x)
        skip = self.conv3(x)
        x = self.act_fnc(self.bn1(self.conv1(x)))
        x = self.conv2(x)

        return self.act_fnc(self.bn2(x + skip))

class Encoder(nn.Module):
    """
    Encoder block
    Built for a 3x32x32 image and will result in a latent vector of size z x 1 x 1
    As the network is fully convolutional it will work for images LARGER than 64
    For images sized 64 * n where n is a power of 2, (1, 2, 4, 8 etc) the latent feature map size will be z x n x n
    When in .eval() the Encoder will not sample from the distribution and will instead output mu as the encoding vector
    and log_var will be None
    """
    def __init__(self, channels, ch=128, latent_channels=512, ae=False):
        super(Encoder, self).__init__()
        self.ae = ae
        self.conv_in = nn.Conv2d(channels, ch, 7, 1, 3)
        self.conv_label = nn.Conv2d(10, ch, 7, 1, 3)
        self.res_down_block1 = ResDown(ch*2, 4 * ch)
        self.res_down_block2 = ResDown(4 * ch, 8 * ch)
        self.res_down_block3 = ResDown(8 * ch, 16 * ch)
        if self.ae:
            self.conv_latent = nn.Conv2d(16 * ch, latent_channels, 4, 1)
        else:
            self.conv_mu = nn.Conv2d(16 * ch, latent_channels, 4, 1)
            self.conv_log_var = nn.Conv2d(16 * ch, latent_channels, 4, 1)
        self.act_fnc = nn.ELU()

        self.fill = torch.zeros([10, 10, 32, 32]).to('cuda')
        for i in range(10):
            self.fill[i, i, :, :] = 1

    def sample(self, mu, log_var):
        std = torch.exp(0.5*log_var)
        eps = torch.randn_like(std)
        return mu + eps*std

    def forward(self, x, y):
        y = self.fill[y]
        x = self.act_fnc(self.conv_in(x))
        y = self.act_fnc(self.conv_label(y))
        x = torch.cat([x, y], 1)
        x = self.res_down_block1(x)  # 16
        x = self.res_down_block2(x)  # 8
        x = self.res_down_block3(x)  # 4
        if self.ae:
            z = self.conv_latent(x)
            return z
        else:
            mu = self.conv_mu(x)  # 1
            log_var = self.conv_log_var(x)  # 1
            z = self.sample(mu, log_var)
            return mu, log_var, z

class Decoder(nn.Module):
    def __init__(self, channels, ch=128, latent_channels=512):
        super(Decoder, self).__init__()
        self.conv_t_up = nn.ConvTranspose2d(latent_channels, ch * 8, 4, 1)
        self.res_up_block1 = ResUp(ch * 8, ch * 4)
        self.res_up_block2 = ResUp(ch * 4, ch * 2)
        self.res_up_block3 = ResUp(ch * 2, ch)
        self.conv_out = nn.Conv2d(ch, channels, 3, 1, 1)
        self.act_fnc = nn.ELU()

    def forward(self, x):
        x = self.act_fnc(self.conv_t_up(x))  # 4
        x = self.res_up_block1(x)  # 8
        x = self.res_up_block2(x)  # 16
        x = self.res_up_block3(x)  # 32
        x = torch.tanh(self.conv_out(x))

        return x

class ResVAE(nn.Module):
    def __init__(self, channel_in=3, ch=64, latent_size=32, ae=False):
        super(ResVAE, self).__init__()
        self.ae = ae
        self.encoder = Encoder(channel_in, ch=ch, latent_channels=latent_size, ae=self.ae)
        self.decoder = Decoder(channel_in, ch=ch, latent_channels=latent_size)

    def forward(self, x, y):
        if self.ae:
            z = self.encoder(x, y)
        else:
            mu, log_var, z = self.encoder(x, y)
        recon_img = self.decoder(z)
        if self.ae:
            return recon_img, z
        return recon_img, mu, log_var, z


import sys

if len(sys.argv) == 2:
    file_path = sys.argv[1]
    if not file_path.endswith('.py'):
        print("Not a Python file")
        sys.exit(1)
    try:
        with open(file_path, "r") as file:
            lines = file.readlines()
            count = 0
            for line in lines:
                if not line.lstrip().startswith("#") and not line.isspace():
                    count += 1
            print (count)
    except FileNotFoundError:
        print ("File does not exist")

elif len(sys.argv) < 2:
    print ("Too few command-line arguments")
    sys.exit(1)
else:
    print ("Too many command-line arguments")
    sys.exit(1)


import wargaming
from datetime import datetime, timedelta
#I use pretty print to print dictionary nicely since returned data is in json structure
import pprint

#My account ID is 1012192478

wotb = wargaming.WoTB('demo', language='en', region='na', enable_parser=True)
#Wargaming .NET
wgn = wargaming.WGN('demo', language='en', region='na')
clan = wotb.clans.list(search='2BOOM')[0]
#print(clan)
clan_id = str(clan['clan_id'])
clan_info = wotb.clans.info(clan_id=clan['clan_id'])[clan_id]
#print(clan_info)
members_ids = clan_info['members_ids']
#print(members_ids)
accounts = wotb.account.info(account_id=members_ids)
#accounts=dict(accounts)
#pprint.pprint(accounts)

#Prints my stats
maxBattles=0
for ID in members_ids:
    account=accounts[ID]
    battlesCount=account['statistics']['all']['battles']
    if battlesCount > maxBattles:
        maxBattles=battlesCount
    if account['nickname']=='sunnydog':
        #pprint.pprint(dict(account))
        pass
print()
#print('Max Battles: ' , maxBattles)
print()
myAchievments = wotb.account.achievements(account_id='1012192478')
#pprint.pprint(dict(myAchievments))
print()
allTanks=wotb.encyclopedia.vehicles()
tanksAndIds={}
#Finds names for all the tank IDs
for tank_id in allTanks:
    name=allTanks[tank_id]['name']
    tanksAndIds[name]=tank_id
#pprint.pprint(tanksAndIds)

#pprint.pprint(dict(allTanks))
tankStats=wotb.tanks.stats(account_id='1012192478',in_garage='1',access_token='',tank_id=tanksAndIds['SU-152'])
pprint.pprint(dict(tankStats))


from maya import cmds,mel
from PySide import QtGui
from .lib import qt

def cpy():
    mel.eval("timeSliderCopyKey;")

def pst():
    mel.eval("timeSliderPasteKey false;")

def dlt():
    mel.eval("timeSliderClearKey;")

def cut():
    mel.eval("timeSliderCutKey;")

class MainWindow(QtGui.QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle('Set Key')
        self.resize(250,100)

        widget = KeyButton()
        self.setCentralWidget(widget)

class KeyButton(QtGui.QWidget):
    def __init__(self, *args, **kwargs):
        super(KeyButton, self).__init__(*args, **kwargs)
        layout = QtGui.QVBoxLayout()
        self.setLayout(layout)

        button = QtGui.QPushButton('Copy')
        button.clicked.connect(qt.Callback(cpy))
        layout.addWidget(button)

        button = QtGui.QPushButton('Paste')
        button.clicked.connect(qt.Callback(pst))
        layout.addWidget(button)

        button = QtGui.QPushButton('Delete')
        button.clicked.connect(qt.Callback(dlt))
        layout.addWidget(button)

        button = QtGui.QPushButton('Cut')
        button.clicked.connect(qt.Callback(cut))
        layout.addWidget(button)

def main():
    app = MainWindow(qt.getMayaWindow())
    app.show()


"""
helper.py   Walid Zeineldin     Virginia Tech       Dec 5th, 2020
This file holdes the helper classes that are used by optimizer
Track: holds track information and track realted functions
Vehical: holds vehical infromation
VelocityMap: Holds and updates velocity map for a specific car, around a specific path
"""
from math import sqrt
import numpy as np

class Track:
    def __init__(self,left,right):
        self.left = left
        self.right = right
        self.size = self.left[0].size - 1 # -1 since the track is closed the first and last points are the same
        self.diff = self.right - self.left
    def alphas_to_point(self,alphas):
      alphas = np.append(alphas, alphas[0])
      i = np.nonzero(alphas != -1)[0]
      return self.left[:,i] + (alphas[i] * self.diff[:,i])
    def points_to_alphas(self, points):
      return (points-self.left)/self.diff

class Vehical:
    def __init__(self,mass = 200, friction = 1.5, engineForce = 3114):
        self.mass = mass
        self.friCof = friction
        self.engineForce = engineForce

class VelocityMap:
    def __init__(self, vehicle):
        self.vehicle = vehicle

    def reset(self,samples,sample_max, curv):
        self.samples = samples
        self.sample_max = sample_max
        self.curv = curv
        self.limit_vel()
        self.limit_acc(self.curv)
        self.limit_decel(self.curv)
        self.v_final = np.minimum(self.v_acclim, self.v_declim)

    def traction(self, v, curv ):
        friction_force = self.vehicle.friCof * self.vehicle.mass * 9.81
        centriptal_froce = self.vehicle.mass * v**2 * curv
        if friction_force <= centriptal_froce:
            return 0
        else:
            return sqrt(friction_force**2-centriptal_froce**2)
    def engine_force(self, v):
        return self.vehicle.engineForce

    def limit_vel(self):
        self.v = np.sqrt(self.vehicle.friCof*(9.81/self.curv)) #max velocity to match centriptal force
    def limit_acc(self,curv_in):
        start = np.argmin(self.v)
        v = np.array(self.v)
        k = curv_in
        s = self.samples
        for i in range(start, self.samples.size+start):
            prev = (i-1)%self.samples.size
            curr = i%self.samples.size
            if self.sample_max is None: continue
            if v[curr] > v[prev]:
                traction = self.traction(v[prev], k[prev])
                force = min(self.engine_force(v[prev]), traction)
                accel = force / self.vehicle.mass
                ds =  s[curr] - s[prev] if curr != 0 else self.sample_max - curr
                vlim = sqrt(v[prev]**2 + 2*accel*ds)
                v[curr] = min(v[curr], vlim)

        self.v_acclim = v

    def limit_decel(self, curv_in):

        start = np.argmin(self.v)
        v = np.array(self.v)
        k = curv_in
        s = self.samples

        for i in range(start, start - self.samples.size , -1):
            next = (i+1)%self.samples.size
            curr = i%self.samples.size
            if self.sample_max is None: continue
            if v[curr] > v[next]:
                traction = self.traction(v[next], k[next])
                decel = traction / self.vehicle.mass

                #change in distance
                ds =  s[next] - s[curr] if next != 0 else self.sample_max - s[curr]
                vlim = sqrt(v[next]**2 + 2*decel*ds)
                v[curr] = min(v[curr], vlim)

        self.v_declim = v


def grade():
    average = float(input("What is your average for the course? "))
    if average >= 90:
        print("A")
    elif average >= 80:
        print("B")
    elif average >= 70:
        print("C")
    else:
        print("You can do better! ")
    return

if __name__ == "__main__":
    grade()


'''
asyncio task loop to validate ledger close time and UNL status
using keys stored in an exiting database.
'''

import asyncio
import logging
import supplemental_data.get_data

def sup_data_loop(settings):
    '''
    Run the .asyncio event loop.

    :param settings: Configuration file
    '''
    loop = asyncio.get_event_loop()

    if settings.ASYNCIO_DEBUG is True:
        loop.set_debug(True)
        logging.info("asyncio debugging enabled.")

    while True:
        try:
            loop.run_until_complete(
                supplemental_data.get_data.DomainVerification().run_verification(settings)
            )
            loop.run_forever()
        except KeyboardInterrupt:
            logging.critical("Keyboard interrupt detected. Exiting supplemental data logging.")
            break