import os
import calculate
from PIL import Image
from model import MyModel
from skimage import io

# s = "(3+657579)/2+7="
def cal(s):
    s+="="
    # print(s)
    stknum= []
    stkope= []
    i = 0
    p = 0
    q = 0
    while 1:
        if p==0:
            #print "i=",i,
            ope = s[i]
            if ope>='0' and ope<='9':
                #print ope
                num = 0
                while s[i] >= '0' and s[i]<= '9':
                    num *= 10
                    num += int(s[i])
                    i =i+1
                    #print "++",
                stknum.append(float(num))
                ope = s[i]
        #print stknum,stkope,
        if len(stkope)==0 or ope == '(' or (stkope[len(stkope)-1] == '(' and ope != ')') :
            #print "kk",
            stkope.append(ope)
        elif (stkope[len(stkope)-1] == '-' or stkope[len(stkope)-1] == '+') and (ope == '*' or ope == '/'):
            stkope.append(ope)
        elif stkope[len(stkope)-1] == '(' and ope == ')':
            stkope.pop()
        else:
            num1 = stknum[len(stknum)-1]
            stknum.pop()
            num2 = stknum[len(stknum)-1]
            stknum.pop()
            val = 0
            if stkope[len(stkope)-1] == '+':
                val = num2+num1
            if stkope[len(stkope)-1] == '-':
                val = num2-num1
            if stkope[len(stkope)-1] == '*':
                val = num2 * num1
            if stkope[len(stkope)-1] == '/':
                val = num2 / num1
            stkope.pop()
            stknum.append(val)
            i =i-1

            if ope == '=':
                if len(stkope)==0:
                    #print "!!!!!",
                    print ('%s %.3f'%(s,stknum[len(stknum)-1]) )
                    stknum.pop()
                    q = 1
                else:
                    p = 1
        #print stknum,stkope
        i = i+1
        if i==len(s):
            break
        if q==1:
            break
# cal(s)

def splitimage(src, dstpath):
    mystr=''
    img = Image.open(src)
    w, h = img.size
    colnum = int(w/100)
    # print(colnum)
    rownum = 1
    if rownum <= h and colnum <= w:
        # print('Original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
        print('开始识别, 请稍候...')

        s = os.path.split(src)
        if dstpath == '':
            dstpath = s[0]
        fn = s[1].split('.')
        basename = fn[0]
        ext = fn[-1]

        num = 0
        rowheight = h // rownum
        colwidth = w // colnum
        for r in range(rownum):
            for c in range(colnum):
                box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)
                img.crop(box).save(os.path.join(dstpath, basename + '_' + str(num) + '.' + ext))
                infile = basename + '_' + str(num) + '.' + ext
                # print(infile)
                outfile = os.path.splitext(infile)[0] + ".jpg"
                try:
                    Image.open(infile).save(outfile)
                    model = MyModel()
                    singleImage = io.imread(outfile, as_grey=True)
                    # print(model.recognize(singleImage))
                    mystr+=model.recognize(singleImage)
                except IOError:
                    print("load....")

                num = num + 1

        print('图片识别完毕，共识别出 %s 个字符' % num)
    else:
        print('不合法的行列切割参数！')
    cal(mystr)

src = input('请输入图片文件路径：')
if os.path.isfile(src):
    dstpath =''
    if (dstpath == '') or os.path.exists(dstpath):
        splitimage(src, dstpath)

    # else:
    #     print('图片输出目录 %s 不存在！' % dstpath)
else:
    print('图片文件 %s 不存在！' % src)


from appium import webdriver
import unittest
import time

class Hy(unittest.TestCase):
    def setUp(self):
        desired_caps = {
            'platformName': 'Android',
            'platformVersion': '5.1.1',
            'deviceName': '127.0.0.1:5555',
            'appPackage': 'com.duowan.kiwi',
            'appActivity': 'com.duowan.kiwi.simpleactivity.SplashActivity'
        }
        self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
        self.driver.implicitly_wait(8)

    def test_getWindows(self):
        time.sleep(5)
        windows = self.driver.get_window_size()
        print(windows)

if __name__ == '__main__':
    hy = Hy()
    hy.test_getWindows()


# import os
# import concurrent.futures
# import cv2
# import numpy as np

# # Define the directory path
# dir_path = 'data'

# # Initialize an empty list to store the file contents
# file_contents = []
# img1 = cv2.imread('image_not_available.jpg')
# # Loop through all the files in the directory and its subdirectories
# for root, dirs, files in os.walk(dir_path):
#     for file in files:
#         img2 = cv2.imread(os.path.join(root, file))
#         try:
#             mse = np.mean((img1 - img2) ** 2)
#             if mse < 10:
#                 print("The images are similar")
#             else:
#                 print("The images are different")
#         except ValueError:
#             pass

import os
import concurrent.futures
import cv2
import numpy as np
from PIL import Image

# Define the directory path
dir_path = '../data'

# Initialize an empty list to store the file contents
file_contents = []
img1 = cv2.imread('image_not_available.jpg')

# Define a function to compare two images
def compare_images(img2, loc):
    try:
        mse = np.mean((img1 - img2) ** 2)
        if mse < 10:
            os.remove(loc)
            print("deleted, score: ", str(mse))
        else:
            print("The images are different")
    except ValueError:
        pass

def remove_mp4(img2):
    imgval = img2[:-4]
    img2_name = imgval.split("_")
    if "mp4" == img2_name[-1] or "gif" == img2_name[-1]:
        os.remove(img2)
        print("deleted mp4")

def corrupted_img(img2):
    try:
        with Image.open(img2) as img:
            img.verify()
    except Exception as e:
        print("damn")
    # except (IOError, SyntaxError) as e:
    #     os.remove(img2)
    #     print("deleted corrupted image")

# 0 - COMPARE IMAGE DELETION ACC TO IMGUR TEMPLATE
# 1 - MP4, GIF DELETION
# 2 - CORRUPTED IMAGE DELETION
flag = 2

# Loop through all the files in the directory and its subdirectories
with concurrent.futures.ThreadPoolExecutor(max_workers=50) as executor:
    for root, dirs, files in os.walk(dir_path):
        print("Hello")
        for file in files:
            if flag == 0:
                img2 = cv2.imread(os.path.join(root, file))
                loc = os.path.join(root, file)
                executor.submit(compare_images, img2, loc)
            elif flag == 1:
                img2 = os.path.join(root, file)
                executor.submit(remove_mp4, img2)
            elif flag == 2:
                img2 = os.path.join(root, file)
                executor.submit(corrupted_img, img2)


import pygame
from pygame.constants import QUIT
from settings import *
from level import Level
from game_data import level_0
#Pygame setup

pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Platform game')
clock = pygame.time.Clock()
level = Level(level_0, screen)

#Main game loop
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()

    screen.fill('grey')
    level.run()

    pygame.display.update()
    clock.tick(FPS)


import run_umls_classifier_2 as ruc
from tqdm import tqdm
import csv
from absl import app, flags,logging
import os
from collections import defaultdict
FLAGS = flags.FLAGS

def count_lines(filein):
    'Count total number of lines present in a file, helps with presenting correct loading bar via tqdm'
    return sum(1 for line in open(filein))

def gen_mrc_atom(mrc_atoms_fp, ulms_fp,id):
    print('in gen_mrc_atoms...')
    """Given mrconso_master file, converts to mrc_atoms dictionary where key = aui_id, value = CUI,LUI, SCUI,SG, STR, ID

    Args:
        mrc_atoms_fp (string): filepath where you want to store mrc_atoms dictionary
        ulms_fp (string): mrconso_master filepath
        id (int): integer to put as unique ID

    Returns:
        dict: key is AUI and value is dictionary containing CUI, LUI, SCUI, SG, STR, ID
        int: last unused integer for ID
    """
    if(os.path.isfile(mrc_atoms_fp)):
        logging.info('MRC_ATOMS found')
        return ruc.load_pickle(mrc_atoms_fp), id
    else:
        aui_dict = dict()
        logging.info('generating MRC_ATOM...')
        with open(ulms_fp, 'r') as f:
            reader = csv.DictReader(f, fieldnames=FLAGS.mrconso_master_fields, delimiter=FLAGS.delimiter)
            with tqdm(total = count_lines(ulms_fp)) as pbar:
                for idx,row in enumerate(reader):
                    pbar.update(1)
                    aui_dict[row['AUI']] = {'CUI': row['CUI'], 'LUI':row['LUI'], 'SCUI': row['SCUI'], 'SG':row['SG'], 'STR': row['STR'], 'ID': id}
                    id += 1

        #euc_test_dict(aui_dict) #save for unit testing
        ruc.dump_pickle(aui_dict, mrc_atoms_fp)
        return aui_dict, id

def compare(ab_mrc_atoms, aa_mrc_atoms, paths):
    """Takes in mrc_atoms dictionary and finds which auis intersect and which are unique to 2020AB, stores multiple dicts

    Args:
        aa_mrc_atoms (dict): mrc_atoms for UMLS version 2020AA
        ab_mrc_atoms (dict): mrc_atoms for UMLS version 2020AB
        intersect_id2aui_pickle_fp (string): filepath to write dictionary of auis present in both 2020AA and 2020AB, key = (int) id , value = aui id
        unique_id2aui_pickle_fp (string): filepath of dictionary of auis unique to 2020AB, key = (int) id, value = aui_id
        intersect_aui2id_pickle_fp (string): filepath of dictionary where key = aui_id, value = (int) id
        unique_aui2id_pickle_fp (string): filepath of dictionary of auis unique to 2020AB, key = aui_id, value = (int) id
    """
    intersect_id2aui = dict()
    unique_id2aui = dict()

    intersect_aui2id = dict()
    unique_aui2id = dict()

    intersect_sg2id = defaultdict(list)
    unique_sg2id = defaultdict(list)
    aui_info = dict()
    for aui, row in ab_mrc_atoms.items():
        temp_dict = {'AUI': aui, 'CUI': row['CUI'], "SG": row["SG"]}

        if aui in aa_mrc_atoms:
            intersect_id2aui[row['ID']] = aui
            intersect_aui2id[aui] = row['ID']
            sg = row["SG"].split(",")[0]
            if FLAGS.use_sg:
                intersect_sg2id[sg].append(row['ID'])
        else:
            unique_id2aui[row['ID']] = aui
            unique_aui2id[aui] = row['ID']
            if FLAGS.use_sg:
                unique_sg2id[sg].append(row['ID'])
                temp_dict["IDX"] = len(unique_sg2id[sg]) - 1
        aui_info[row["ID"]] = temp_dict

    logging.info('generating intersect, unique_terms pickles...')
    ruc.dump_pickle(intersect_id2aui, paths['intersect_id2aui_pickle_fp'])
    ruc.dump_pickle(intersect_aui2id, paths['intersect_aui2id_pickle_fp'])
    ruc.dump_pickle(unique_id2aui, paths['unique_id2aui_pickle_fp'])
    ruc.dump_pickle(unique_aui2id, paths['unique_aui2id_pickle_fp'])
    ruc.dump_pickle(aui_info, paths['aui_info_fp'])
    if FLAGS.use_sg:
        ruc.dump_pickle(unique_sg2id, paths['unique_sg2id_pickle_fp'])
        ruc.dump_pickle(intersect_sg2id, paths['intersect_sg2id_pickle_fp'])

def gen_intersect_unique(paths, logger):
     global logging
     logging = logger
     ruc.logger = logger
     aa_mrc_atoms, end_id = gen_mrc_atom(paths['aa_mrc_atoms_fp'], paths['aa_umls_fp'],0)
     ab_mrc_atoms, _ = gen_mrc_atom(paths['ab_mrc_atoms_fp'], paths['ab_umls_fp'],end_id)
     compare(ab_mrc_atoms, aa_mrc_atoms, paths)


from pyramid.config import Configurator

from sqlalchemy import engine_from_config

from vote2map.models import initialize_sql

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    engine = engine_from_config(settings, 'sqlalchemy.')
    initialize_sql(engine)
    config = Configurator(settings=settings)
    config.add_static_view('static', 'vote2map:static', cache_max_age=3600)

    config.add_route('home', '/')
    config.add_view('vote2map.views.home', route_name='home', renderer='index.mako')

    config.add_route('setup_js', '/setup_js')
    config.add_view('vote2map.views.setup_js', route_name='setup_js', renderer='setup_js.mako')

    config.add_route('data', '/data')
    config.add_view('vote2map.views.data', route_name='data')

    config.add_route('unit.search', '/unit/search')
    config.add_view('vote2map.views.unit_search', route_name='unit.search', renderer='json')

    config.add_route('unit.browse', '/unit')
    config.add_view('vote2map.views.unit_browse', route_name='unit.browse', renderer='browse.mako')

    config.add_route('unit.update_stat', '/unit/update_stat')
    config.add_view('vote2map.views.unit_update_stat', route_name='unit.update_stat')

    # config.add_route('home', '/')
    # config.add_view('vote2map.views.my_view',
    #                 route_name='home',
    #                 renderer='templates/mytemplate.pt')
    return config.make_wsgi_app()


import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import warnings
warnings.filterwarnings('ignore')

data = pd.read_csv('/kaggle/input/quora-question-pairs/train.csv.zip')
print(data.head())

print(data.shape)

print(data.info())

print(data.isnull().sum())

# Drop rows with missing values
data.dropna(inplace=True)

# Split the data into question pairs and labels
questions = data[['question1', 'question2']]
labels = data['is_duplicate']

questions_train, questions_test, labels_train, labels_test = train_test_split(questions, labels, test_size=0.2, random_state=42)
tfidf = TfidfVectorizer()
tfidf_train = tfidf.fit_transform(questions_train['question1'] + ' ' + questions_train['question2'])

model = LogisticRegression()
model.fit(tfidf_train, labels_train)

tfidf_test = tfidf.transform(questions_test['question1'] + ' ' + questions_test['question2'])
predictions = model.predict(tfidf_test)

accuracy = accuracy_score(labels_test, predictions)
print("Accuracy:", accuracy)


import pygame
import random

# Setting up constants
WIDTH, HEIGHT = 800, 600
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GRAY = (211, 211, 211)

# Initialize Pygame
pygame.init()
programIcon = pygame.image.load('assets/icon.png')
pygame.display.set_icon(programIcon)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Maze Generator")

# Grid settings
GRID_SIZE = 20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
DIRS = [(0, -1), (1, 0), (0, 1), (-1, 0)]

# Initialize the maze
maze = [[1 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]

def is_valid(x, y):
    return 0 <= x < GRID_WIDTH and 0 <= y < GRID_HEIGHT

def generate_maze(x, y):
    maze[y][x] = 0
    random.shuffle(DIRS)
    for dx, dy in DIRS:
        nx, ny = x + dx * 2, y + dy * 2
        if is_valid(nx, ny) and maze[ny][nx] == 1:
            maze[y + dy][x + dx] = 0
            generate_maze(nx, ny)

generate_maze(0, 0)

# Start and finish positions
start_x, start_y = 0, 0
finish_x, finish_y = GRID_WIDTH - 2, GRID_HEIGHT - 2

# Player position
player_x, player_y = start_x, start_y

def move_player(dx, dy):
    global player_x, player_y, has_moved, completed
    new_x, new_y = player_x + dx, player_y + dy
    if is_valid(new_x, new_y) and maze[new_y][new_x] == 0:
        player_x, player_y = new_x, new_y
        has_moved = True  # Update the flag when the player moves
        # Check for completion
        if player_x == finish_x and player_y == finish_y:
            completed = True

def get_possible_moves_and_highlight(x, y):
    moves = []
    for dx, dy in DIRS:
        nx, ny = x + dx, y + dy
        if is_valid(nx, ny) and maze[ny][nx] == 0:
            if dx == 1: moves.append("Right")
            if dx == -1: moves.append("Left")
            if dy == 1: moves.append("Down")
            if dy == -1: moves.append("Up")
            # Highlight possible moves
            pygame.draw.rect(screen, GRAY, (nx * GRID_SIZE, ny * GRID_SIZE, GRID_SIZE, GRID_SIZE))
    return moves

# Additional flags
has_moved = True
completion_message_printed = False
possible_moves = []
completed = False

# Main game loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif not completed and event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                move_player(0, -1)
            elif event.key == pygame.K_s:
                move_player(0, 1)
            elif event.key == pygame.K_a:
                move_player(-1, 0)
            elif event.key == pygame.K_d:
                move_player(1, 0)

    screen.fill(WHITE)
    # Draw the maze
    for y in range(GRID_HEIGHT):
        for x in range(GRID_WIDTH):
            if maze[y][x] == 1:
                pygame.draw.rect(screen, BLACK, (x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE))

    # Draw start and finish points
    pygame.draw.rect(screen, GREEN, (start_x * GRID_SIZE, start_y * GRID_SIZE, GRID_SIZE, GRID_SIZE))
    pygame.draw.rect(screen, GREEN, (finish_x * GRID_SIZE, finish_y * GRID_SIZE, GRID_SIZE, GRID_SIZE))

    # Draw the player
    pygame.draw.rect(screen, RED, (player_x * GRID_SIZE, player_y * GRID_SIZE, GRID_SIZE, GRID_SIZE))

    if not completed:
        if has_moved:
            # Highlight and get possible moves only if player has moved
            possible_moves = get_possible_moves_and_highlight(player_x, player_y)
            print("Possible Moves:", possible_moves)
            has_moved = False
        else:
            # Highlight possible moves without updating the list
            get_possible_moves_and_highlight(player_x, player_y)

    if completed:
        if not completion_message_printed:
            print("Congratulations! You've completed the maze!")
            completion_message_printed = True
        # Display completion message
        font = pygame.font.Font(None, 60)
        text = font.render("Congratulations! Maze Completed!", True, RED)
        text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2))
        screen.blit(text, text_rect)

    pygame.display.flip()

pygame.quit()


# -*- coding: utf-8 -*-
"""
This files makes up the main point of the backend of the system

Created on Tue Dec  3 18:02:46 2019

@authors: Basem Rizk, Ibram Medhat, Steven Nassef
"""

# from schedule_parser import ScheduleParser
from schedule_parser_with_teachers import ScheduleParserWithTeachers
from query_formater import QueryFormater
from pyswip import Prolog

parser = ScheduleParserWithTeachers(filename="MET_Winter19_schedule_31131.xlsx",
                                    teachers_filename="modifiedSchedule2.xlsx",
                                    list_of_discarded_subjects=['ae','as',
                                                                'en', 'de',
                                                                'physics',
                                                                'embedded systems',
                                                                'video & audio'])

# hadwa pasha is teaching video-and-audio-lab, and csen-lab at the same time
days_schedules, sheet_names, headers = parser.parse_schedule()
teachers_schedules = parser.parse_teachers_schedules()
all_slots = parser.listify_slots()
query_formater = QueryFormater()
all_slots = query_formater.clean_formatted_slots(all_slots)

# parser.convert_to_excel(all_slots)
# to_json_fixture(all_slots)

all_slots_digitized = query_formater.digitize(all_slots)

holidays = [0, 1]
group = "5 csen i"
compensation_slots = query_formater.get_holiday_to_compensate(all_slots,
                                                              specific_group=None,
                                                              holidays=holidays,
                                                              limit=20,
                                                              verbose=True)

query_statement = query_formater.create_query(all_slots_digitized,
                                              compensation_slots,
                                              holidays)

limit = 2
print("INIT PROLOG")
prolog = Prolog()
prolog.consult("constraint_based_approach.pl")
query_answers = prolog.query(query_statement)
num_of_sols = 0
for soln in prolog.query(query_statement):
    num_of_sols += 1
    print("Solution " + str(num_of_sols) + " :: "  + str(soln))
    if limit == num_of_sols:
        break
print("END PROLOG")

def sample_weekson_dict(query_formater, all_slots):
    all_groups = query_formater.get_all_groups(all_slots)
    weekson_dict = {}
    for group in list(all_groups):
        if "1engineering" in group:
            weekson_dict[group] = [0] + [i for i in range(3, 15)]
        else:
            weekson_dict[group] = [0] + [i for i in range(1, 13)]
    return weekson_dict

def to_json_fixture(query_formater, all_slots, model_name = "api.slot"):
    import json

    weekson_dict = sample_weekson_dict(query_formater, all_slots)

    slot_counter = 0
    all_slots_records = []
    for slot in all_slots:
        slot_num, slot_subject, slot_type,\
        slot_group, slot_subgroup, slot_location, slot_teacher = slot

        weekson = weekson_dict[slot_group]
        if not weekson:
            print("WARNING:: HALTING..")
            return

        for slot_week in weekson:
            slot_record = {}
            slot_record["slot_num"] = slot_num
            slot_record["slot_subject"] = slot_subject
            slot_record["slot_type"] = slot_type
            slot_record["slot_group"] = slot_group
            slot_record["slot_subgroup"] = slot_subgroup
            slot_record["slot_location"] = slot_location
            slot_record["slot_teacher"] = slot_teacher
            slot_record["slot_week"] = slot_week
    #        slot_record = json.dumps(slot_record)
            # print(slot_record)

            db_record = {}
            db_record["model"] = model_name
            slot_counter += 1
            db_record["pk"] = slot_counter
            db_record["fields"] = slot_record
    #        db_record = json.dumps(db_record)
            all_slots_records.append(db_record)
            # print(db_record)

    all_slots_records = json.dumps(all_slots_records)
    with open("schedule_slots_fixture.json", "w") as f:
        f.write(all_slots_records)

#
with open("query_example.txt", "w") as f:
    query_rest = query_statement
    while(True):
        limit = 1000
        if len(query_rest) < limit:
            break
        f.write(query_rest[:limit])
        f.write("\n")
        query_rest = query_rest[limit:]
    f.write(query_rest)


import tkinter as tk
from PIL import Image,ImageTk
from tkinter import Toplevel
import numpy as np

length = 80
side_margin = 50
top_margin = 80
line_thickness = 2
font_style = "Times New Roman"
box_top_margin = top_margin + 10

def get_min_tuple(tuple_list):
    min_cell = list(map(min, zip(*tuple_list)))
    min_cell = (min_cell[0], min_cell[1])
    if min_cell not in tuple_list:
        min_cell = tuple_list[0]
        for index, cell in enumerate(tuple_list):
            if index == len(tuple_list) - 1:
                break

            next_cell = tuple_list[index + 1]
            if next_cell[1] < min_cell[1]:
                min_cell = next_cell

            elif next_cell[1] == min_cell[1]:
                if next_cell[0] < min_cell[0]:
                    min_cell = next_cell
    return min_cell

def prepare_solution(solutions, board_size):
    sol = np.zeros((board_size, board_size), dtype=np.int8)
    for element in solutions:
        values = solutions[element]
        for i, e in enumerate(element):
            i1 = e[0] - 1
            i2 = e[1] - 1
            sol[i2][i1] = values[i]
    return sol

def draw_group_condition(canvas, cell, op, number):
    number = '(' + str(number) + ')'
    op = '' if(op == '.') else op
    txt = number + ' ' + op
    offset = 10 if (len(number)<3) else 16
    top_offset = offset - 2 if (len(number)<3) else offset - 5
    col = cell[0] - 1
    row = cell[1] - 1
    r_start = box_top_margin + row * length
    start = side_margin + col * length
    canvas.create_text(3 + offset + start, top_offset + r_start, text = txt, font=(font_style, 10), fill="red")

def draw_cell_bh_line(canvas, cell):
    col = cell[0]
    row = cell[1]
    # bottom horizontal line
    x1 = side_margin + (col-1) * length
    x2 = x1 + length
    y1 = box_top_margin + row * length
    canvas.create_line(x1, y1, x2, y1, fill="black", width=line_thickness)

def draw_cell_rv_line(canvas, cell):
    col = cell[0]
    row = cell[1]
    # right vertical line
    x1 = side_margin + col * length
    y1 = box_top_margin + (row-1) * length
    y2 = y1 + length
    canvas.create_line(x1, y1, x1, y2, fill="black", width=line_thickness)

def draw_groups_borders(canvas, groups, board_size):
    for g in groups:
        cells_list = g[0]
        min_cell = get_min_tuple(cells_list)
        op = g[1]
        num = g[2]
        draw_group_condition(canvas, min_cell, op, num)
        if len(cells_list) == 1:
            draw_cell_bh_line(canvas, cells_list[0])
            draw_cell_rv_line(canvas, cells_list[0])
        else:
            for cell in cells_list:
                # skip the last cell
                if cell == (board_size, board_size):
                    continue
                # check if the right next cell is not in the group of the current cell, then draw vertical line
                # and make sure that this is not a cell in the last column
                right_next_cell = (cell[0]+1, cell[1])
                # right_next_cell[0] += 1
                if cell[0] != board_size and right_next_cell not in cells_list:
                    draw_cell_rv_line(canvas, cell)

                # check if the below cell is in the group of the current cell, then draw horizontal line
                # and make sure that this is not a cell in the last row
                below_cell = (cell[0], cell[1]+1)
                if cell[1] != board_size and below_cell not in cells_list:
                    draw_cell_bh_line(canvas, cell)

def draw_border_grid(canvas, board_size):
    ## draw thick four lines around the whole grid
    box_top_margin = top_margin + 10
    size = board_size * length
    # top line
    canvas.create_line(side_margin, box_top_margin, side_margin + size, box_top_margin, fill="black", width=line_thickness)
    # bottom line
    canvas.create_line(side_margin, size + box_top_margin, side_margin + size, size + box_top_margin, fill="black", width=line_thickness)
    # left line
    canvas.create_line(side_margin, box_top_margin, side_margin, size + box_top_margin, fill="black", width=line_thickness)
    # right line
    canvas.create_line(size + side_margin, box_top_margin, size + side_margin, size + box_top_margin, fill="black", width=line_thickness)

def create_grid(canvas, board_size, sol_arr):
    for row in range(board_size):
        r_start = box_top_margin + row * length
        r_end = box_top_margin + (row+1) * length
        for i in range(board_size):
            start = side_margin + i * length
            end = side_margin + (i+1) * length
            canvas.create_rectangle(start, r_start, end, r_end, outline="grey", fill="white")
            ## write numbers inside the cell
            offset = length/2
            txt = str(sol_arr[row][i])
            canvas.create_text(offset + start, offset + r_start, text = txt, font=(font_style, 20), fill="black")

def solve(window, board_size, groups, solutions):
    # Create board
    size = board_size * length
    width = 2 * side_margin + size
    height = 2 * top_margin + size
    geometry = str(width) + "x" + str(height)
    board = Toplevel(window)
    board.title("Solution Board "+ str(board_size) + "x"+ str(board_size))
    board.iconphoto(False, tk.PhotoImage(file='assets/logo.png'))
    board.geometry(geometry)
    board.resizable(False, False)

    if board_size > 8:
        board.resizable(True, True)
        v = tk.Scrollbar(board, orient='vertical')
        v.pack(side = tk.RIGHT, fill = tk.Y)

    # Creating a canvas to put all the widgets inside
    canvas = tk.Canvas(board, width = 600, height = 360)
    canvas.pack(fill='both', expand = True)

    # Load logo image in the script
    img= (Image.open("assets/wide_logo.png"))
    #Resize the Image using resize method
    resized_logo= img.resize((200,33), Image.ANTIALIAS)
    logo= ImageTk.PhotoImage(resized_logo)
    canvas.create_image(width/2, 40, image=logo, anchor = "center")

    # Now Solve
    sol_arr = prepare_solution(solutions, board_size)
    create_grid(canvas, board_size, sol_arr)
    draw_border_grid(canvas, board_size)
    draw_groups_borders(canvas, groups, board_size)
    board.mainloop()
    return canvas, board

# def solve(window, board_size, groups, solutions):
#     canvas, board = create_board_new_window(window, board_size)
#     sol_arr = prepare_solution(solutions, board_size)
#     create_grid(canvas, board_size, sol_arr)
#     draw_border_grid(canvas, board_size)
#     draw_groups_borders(canvas, groups, board_size)
#     board.mainloop()


#!/usr/bin/env python
"""
Threadpool.

######################################################################
# @author      : Linus Fernandes (linusfernandes at gmail dot com)
# @file        : threadpool
# @created     : Friday Nov 17, 2023 12:29:10 IST
# @description :
# -*- coding: utf-8 -*-'
######################################################################
"""
# SuperFastPython.com
# example of a parallel for loop with the ThreadPool class
from multiprocessing.pool import ThreadPool
from secrets import randbelow
from time import sleep

def task(value):
    """execute a task"""
    # add your work here...
    sleep(randbelow(3))
    # ...
    # return a result, if needed
    return value

# protect the entry point
if __name__ == '__main__':
    # create the pool with the default number of workers
    with ThreadPool() as pool:
        # issue one task for each call to the function
        for result in pool.map(task, range(100)):
            # handle the result
            print(f'>got {result}')
    # report that all tasks are completed
    print('Done')


from collections import deque
import sys
sys.stdin = open('./inputs/S_16523.txt','r', encoding='utf-8')
di,dj = [1,0,-1,0],[0,1,0,-1]

def bfs(i, j, G, C):
    q = deque()
    q.append([i, j])
    C[i][j] = True
    while q:
        i, j = q.popleft()
        for k in range(4):
            ii = i + di[k]
            jj = j + dj[k]
            if 0 <= ii < N and 0 <= jj < N and C[ii][jj] == False and G[ii][jj] != 1:
                if G[ii][jj] == 2:
                    return 1
                C[ii][jj] = True
                q.append([ii, jj])
    return 0

for t in range(1,int(input())+1):
    N = int(input())
    G = []
    for i in range(N):
        G.append(list(map(int, input().strip())))
        for j in range(N):
            if G[i][j] == 3:
                pos_i = i
                pos_j = j

    C = [[False]*N for _ in range(N)]

    sol = bfs(pos_i,pos_j,G,C)
    print(f'#{t} {sol}')


import tkinter
import streamlit as st
import pandas as pd
import utils as ul
from urllib.error import URLError

def draw_graph(df):
    st.markdown('''

    The following data illustrates the estimation of burned down houses in each village around Kanbalu and Ye U District.

    ''', unsafe_allow_html = True)
    condition = st.multiselect("Choose Region:", list(df.Region.unique()), ["Kanbalu"])
    select_region = df[df['Region'].isin(condition)]
    #st.bar_chart(df.Number)
    if select_region.empty :
        st.bar_chart(df.Number)

    else:
        st.bar_chart(select_region.Number)

st.subheader("Data Visualization with Chart ðŸ“Š")
#file_path = "C:\\Users\\Nwe Ni\\Desktop\\Python\\house.csv"
try:
    df = ul.read_file()
    draw_graph(df)
except URLError as e:
    st.error(
        """
        **This demo requires internet access.**
        Connection error: ...
        The updated data cannot be shown
    """

    )
    df = ul.read_local_data()
    #st.write(df)
    draw_graph(df)


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

from flask import request
from . import item_versions_blueprint
from app.api.utils.response import dict_response_deco
from app.api.utils import request_util
from app.api.mod_item.validate import validate_for_item_modify
from app.api.models.version import ResourceVersion
from app.api.models.base import Resource
from app.api.models.item import Item

def parse_request_args(request):
    op_info = request_util.parse_request(request)

    offset = request_util.url_param_check(op_info, "offset")
    limit = request_util.url_param_check(op_info, "limit")
    order = request_util.url_param_check(op_info, "order")

    op_info.set_offset(offset)
    op_info.set_limit(limit)

    if order == "desc":
        op_info.desc = True
    else:
        op_info.desc = False

    return op_info

def get_item_versions(item_id, limit=100, offset=0, desc=True):
    total = ResourceVersion.get_versions_count(item_id, Resource.Type.ITEM)
    versions = ResourceVersion.get_all_versions(
        item_id, Resource.Type.ITEM,
        limit=limit, offset=offset, desc=desc
    )

    return total, versions

@item_versions_blueprint.route("", methods=["GET"])
@dict_response_deco
def item_version_display(item_id):
    op_info = parse_request_args(request)

    validate_for_item_modify(op_info.user_hash, item_id)

    total, versions = get_item_versions(item_id, limit=op_info.limit, offset=op_info.offset, desc=op_info.desc)
    return {
        "msg": "OK",
        "data": {
            "total": total,
            "versions": [{
                "id": version.version_id,
                "item_id": version.resource_id,
                "content": version.resource_content,
                "type": Item.Type.to_str(version.type),
                "visibility": version.resource_visibility,
                "updated_time": str(version.updated_at)
            } for version in versions]
        }
    }


from unicodedata import category
from django.db import models

# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=50, null=True)

class Prodcut(models.Model):
    name = models.TextField(null=True)
    price = models.FloatField()
    # seller = models.ForeignKey(null=True, on_delete=models.CASCADE)
    img = models.FileField()
    createdAt = models.DateTimeField(auto_now_add=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)


"""
Tourism tags: {'aquarium', 'yes', 'chalet', 'alpine_hut', 'motel', 'attraction', 'viewpoint', 'museum',
'zoo', 'camp_site', 'hotel', 'theme_park', 'spa_resort', 'hostel', 'caravan_site', 'picnic_site',
'information', 'camp_pitch', 'apartment', 'guest_house', 'ruins', 'wilderness_hut', 'wine_cellar',
'artwork', 'gallery'}
"""

# Library for loading open street map data
# Introduction docs: https://github.com/osmcode/pyosmium/blob/master/doc/intro.rst
import osmium
import pandas as pd
import sys

class TourismCounterHandler(osmium.SimpleHandler):
    def __init__(self):
        super().__init__()

        # collect geo points while traversing through the loaded data
        self.geo_points = []

        # track how many data points we currently still ignore
        self.num_uncounted = 0

        self.tags = set()  # all possible tags found in the data

        # tags we consider touristic
        self.tag_tourism = 'tourism'

          # tags we consider human activity, but not touristic
        self.tags_non_tourism = {
            'cinema',
            'toilets',
            'playground',
            'memorial',
            'recycling',
            'shop',
            'school',
            'fire_hydrant',
            'post_box',
            # 'railway',
            # 'highway',
            'route',
            'wholesale',
            'agricultural',
            'healthcare',
            'station',
            'ferry',
            'police',
            'sport',
            'takeaway',
            'preschool',
            'vending',
            'service',
            'health_facility',
            'railway',
            'cargo',
            'transportation',
            'toilets',
            'place',
            'kids_area',
            'townhall',
            'clinic',
            'building',
            'club',
            'community_centre'}

    def node(self, node):

        # gather all raw tags from dataset, even though we filter out many of these
        for type_, subtype_ in node.tags:
            self.tags.add(type_)

        node_type = node_subtype = None

        # Case A: Tourism Node
        tourism_tag = node.tags.get(self.tag_tourism)
        if tourism_tag:
            node_type = 'tourism'
            node_subtype = tourism_tag

        # Case B: Non-tourism node
        else:
            for tag in self.tags_non_tourism:
                tag_value = node.tags.get(tag)
                if tag_value:
                    node_type = tag
                    node_subtype = tag_value

                    # so that we do not add a single location twice (it may have multiple tags)
                    break

        if node_type:
            point = (node.location.lat, node.location.lon, node_type, node_subtype)
            self.geo_points.append(point)

    def way(self, w):
        # TODO: include ways by finding a mean location or something
        if w.tags.get('tourism'):
            self.num_uncounted += 1

    def relation(self, r):
        # TODO: include relation by finding a mean location or something
        if r.tags.get('tourism'):
            self.num_uncounted += 1

    def get_dataframe(self):
        """
        Return a pandas dataframe of the aggregated geo data
        """
        return pd.DataFrame(data=self.geo_points,
                            columns=['lat', 'lon', 'type', 'subtype'])

def get_tourist_activity(lat, lng, when, radius=5):
    """
    Determine the tourism activity at a given location.
    """
    raise NotImplementedError

def load(fname):
    print(f"Loading {fname}")
    h = TourismCounterHandler()

    h.apply_file(fname,
                 locations=True,  # enable processing geometries of ways and areas
                 idx='flex_mem')  # cache that works for mid-sized data. Won;t be enough for Europe or planet

    print(f"Number of nodes: {len(h.geo_points)}")
    print(f"Uncounted tourism locations: {h.num_uncounted}")
    print(f"Tags: {h.tags}")

    return h

if __name__ == "__main__":
    for region in ['asturias',
                   'castilla_y_leon',
                   'galicia',
                   'myanmar',
                   'california']:

        path_from = f'data/{region}.osm.pbf'
        path_to = f'tourism/data_{region}.csv'

        print(f"Loading from: {path_from}")

        handler = load(path_from)

        print(f"Writing to: {path_to}")

        df = handler.get_dataframe()
        df.to_csv(path_to)


#!/usr/bin/env python
""" Parse player from HTML file """
import sys
import re
import dateutil.parser as parser
import logging

from bs4 import BeautifulSoup
from bs4.element import NavigableString

from player import parse_admin
from . import parse_profile

LOG = logging.getLogger(__package__)

def parse_fromfile(path, playerid):
    LOG.debug("%s %s", path, playerid)
    import player.load

    try:
        parsed_player = parse_admin.parse_player(playerid, soup=player.load.from_file("{}/admin-player-{}.html".format(path, playerid)))
        parsed_player = parse_profile.parse_games(parsed_player, soup=player.load.from_file("{}/player-{}.html".format(path, playerid)))
        parsed_player = parse_profile.parse_team(parsed_player, soup=player.load.from_file("{}/player-{}.html".format(path, playerid)))

        if not parsed_player["journeyman"] and parsed_player["status"]["active"]["reason"] == "no status":
            LOG.warning("%s %s %s %s has no status", parsed_player["team"], playerid, parsed_player["playername"],
                     parsed_player["position"])
        return parsed_player
    except:
        LOG.exception("Exception while parsing %s in %s", playerid, path)

def main():
    log_format = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s ] %(message)s"
    #logging.basicConfig(level=logging.DEBUG, format=log_format)
    logging.basicConfig(level=logging.DEBUG)
    import pprint
    if len(sys.argv) < 2:
        sys.exit("path and playerid required")
    path = sys.argv[1] if not sys.argv[1].isdigit() else "input/html/player"
    players = sys.argv[1:] if sys.argv[1].isdigit() else sys.argv[2:]

    for player_id in players:
        if player_id.isdigit():
            parsed_player = parse_fromfile(path, player_id)
            pprint.PrettyPrinter(indent=4).pprint(parsed_player)

if __name__ == "__main__":
    main()


from ExpAdaRacos import ExpAdaRacosOptimization, Experts
import numpy as np
from Components import Dimension
import FileOperator as fo
import time
from Run_Racos import time_formulate
import torch
from Racos import RacosOptimization
from ExpRacos import ExpRacosOptimization
from ExpLearn import ImageNet
from ParamsHelper import ParamsHelper
import lightgbm as lgb
from sklearn.metrics import f1_score
from Tools import BenchmarkHelper
import pandas as pd
import os

os.environ["CUDA_VISIBLE_DEVICES"] = '0'

path = '/data/ExpAdaptation'
sample_size = 10  # the instance number of sampling in an iteration
budget = 30  # budget in online style
positive_num = 2  # the set size of PosPop
rand_probability = 0.99  # the probability of sample in model
uncertain_bit = 1  # the dimension size that is sampled randomly
adv_threshold = 10  # advance sample size
opt_repeat = 5
eta = 0.9
step = 1

index = 0

log_buffer = []
source_data = "australian,breast,electricity,buggyCrx,cmc,contraceptive,credit-a,GAMETES_Epistasis_2-Way_1000atts_0," \
              "GAMETES_Epistasis_2-Way_20atts_0,GAMETES_Epistasis_3-Way_20atts_0,GAMETES_Heterogeneity_20atts_1600_Het_0," \
              "Hill_Valley_without_noise,Hill_Valley_with_noise,mfeat-karhunen,mfeat-morphological,mfeat-pixel," \
              "mfeat-zernike,monk2,parity5+5,pima,tic-tac-toe,tokyo1,vehicle,wine-quality-red,yeast,airlines,titanic," \
              "twonorm,glass,horse-colic".split(',')
target_data = "messidor,adult,balance-scale,cnae,credit-g,crx,cylinder,flare,solar-flare_2,german".split(',')
method = ['racos', 'ave', 'ada']

class ExpContainer(object):

    def __init__(self, prob_name='', prob_index=0, predictor=None):
        self.prob_name = prob_name
        self.prob_index = prob_index
        self.predictor = predictor
        return

def get_hyper_space():
    hyper_space = {
        'boosting_type': ('str', ('gbdt', 'rf', 'dart')),
        'learning_rate': ('float', (0.01, 0.2)),
        'n_estimators': ('int', (50, 100)),
        'num_leaves': ('int', (2, 1000)),
        'colsample_bytree': ('float', (0.1, 1)),
        'subsample': ('float', (0.1, 1)),
        'subsample_freq': ('int', (1, 100)),
        'reg_alpha': ('float', (0.1, 1)),
        'reg_lambda': ('float', (0.1, 1)),
        'min_child_weight': ('float', (0, 0.01)),
        'min_child_samples': ('int', (10, 30)),
    }
    return hyper_space

def get_dimension(param_input):
    '''
    get dimension params by param input
    :param param_input: params input
    :return: dimension and the label coder
    '''
    dimension = Dimension()
    label_coder = ParamsHelper()
    dimension.set_dimension_size(len(param_input))
    index = 0
    for k, (type, obj) in param_input.items():
        dimension.set_region(*label_coder.encode(type=type, index=index, key=k, objs=obj))
        index = index + 1
    return dimension, label_coder

# loading predictors
def get_predicotrs():
    predictors = []
    nets = []
    print('Loading learner files...')

    for i, name in enumerate(source_data):
        learner_path = path + '/ExpLearner/RealProbsLearner/' + name + '/dimension11/DirectionalModel/'
        learner_file = learner_path + os.listdir(learner_path)[0]

        this_learner = torch.load(learner_file)
        nets.append(this_learner)
        this_predictor = ExpContainer(prob_name=name, prob_index=i, predictor=this_learner)
        predictors.append(this_predictor)

    print('Learner files loaded!')

    return predictors, nets

def run_for_real_problem(problem_name, type):
    dtrain, dtest, dvalid = mlbp.get_train_test_data(problem_name)
    opt_error_list = []
    gen_error_list = []
    print(type, ' optimize ', problem_name, '===================================================')
    log_buffer.append(type + ' optimize ' + problem_name + '===================================================')

    for j in range(opt_repeat):
        print(j)
        log_buffer.append(str(j))
        model = lgb.LGBMClassifier()
        start_t = time.time()

        def score_fun(x):
            ## here is the score function
            hyper_param = (sample_codec.sample_decode(x))
            model.set_params(**hyper_param)
            bst = model.fit(dtrain[:, :-1], dtrain[:, -1])
            pred = bst.predict(dvalid[:, :-1])
            fitness = -f1_score(dvalid[:, -1], pred, average='macro')
            return fitness

        if type == 'racos':
            optimizer = RacosOptimization(dimension)
            optimizer.clear()
            optimizer.mix_opt(obj_fct=score_fun, ss=sample_size, bud=budget, pn=positive_num, rp=rand_probability,
                              ub=uncertain_bit)
        elif type == 'ave':
            optimizer = ExpRacosOptimization(dimension, nets)
            log = optimizer.exp_mix_opt(obj_fct=score_fun, ss=sample_size, bud=budget, pn=positive_num,
                                        rp=rand_probability,
                                        ub=uncertain_bit, at=adv_threshold)
            for line in log:
                log_buffer.append(line)
        elif type == 'ada':
            optimizer = ExpAdaRacosOptimization(dimension, expert)
            optimizer.clear()
            log = optimizer.exp_ada_mix_opt(obj_fct=score_fun, ss=sample_size, bud=budget, pn=positive_num,
                                            rp=rand_probability,
                                            ub=uncertain_bit, at=adv_threshold, step=step)
            for line in log:
                log_buffer.append(line)
        else:
            print('Wrong type!')
            return

        end_t = time.time()

        print('total budget is ', budget)
        log_buffer.append('total budget is ' + str(budget))

        hour, minute, second = time_formulate(start_t, end_t)
        print('spending time: ', hour, ':', minute, ':', second)
        log_buffer.append('spending time: ' + str(hour) + '+' + str(minute) + '+' + str(second))

        optimal = optimizer.get_optimal()
        opt_error = optimal.get_fitness()
        optimal_x = optimal.get_features()
        hyper_param = (sample_codec.sample_decode(optimal_x))
        model = lgb.LGBMClassifier()
        model.set_params(**hyper_param)
        train = np.concatenate((dtrain, dvalid), axis=0)
        bst = model.fit(train[:, :-1], train[:, -1])
        pred = bst.predict(dtest[:, :-1])
        gen_error = -f1_score(dtest[:, -1], pred, average='macro')

        gen_error_list.append(gen_error)
        opt_error_list.append(opt_error)
        print('***********validation optimal value: ', opt_error)
        log_buffer.append('***********validation optimal value: ' + str(opt_error))
        print('***********generalize optimal value: ', gen_error)
        log_buffer.append('***********generalize optimal value: ' + str(gen_error))
        print('optimal x: ', optimal_x)
        # log_buffer.append('optimal nn structure: ' + list2string(optimal_x))

    opt_mean = np.mean(np.array(opt_error_list))
    opt_std = np.std(np.array(opt_error_list))
    gen_mean = np.mean(np.array(gen_error_list))
    gen_std = np.std(np.array(gen_error_list))

    return -opt_mean, opt_std, -gen_mean, gen_std

if __name__ == '__main__':
    hyper_space = get_hyper_space()
    dimension, sample_codec = get_dimension(hyper_space)

    log_buffer.append('+++++++++++++++++++++++++++++++')
    log_buffer.append('optimization parameters')
    log_buffer.append('sample size: ' + str(sample_size))
    log_buffer.append('budget: ' + str(budget))
    log_buffer.append('positive num: ' + str(positive_num))
    log_buffer.append('random probability: ' + str(rand_probability))
    log_buffer.append('uncertain bits: ' + str(uncertain_bit))
    log_buffer.append('advance num: ' + str(adv_threshold))
    log_buffer.append('num of datasets in one group: ' + str(step))
    log_buffer.append('methods: ' + str(method))
    log_buffer.append('+++++++++++++++++++++++++++++++')

    mlbp = BenchmarkHelper()
    predictors, nets = get_predicotrs()
    expert = Experts(predictors=predictors, eta=eta, step=step)
    dataset = ['flare']  # source_data+target_data

    res = []
    col_name = []
    for problem_name in dataset:
        print('optimize ', problem_name, '===================================================')
        log_buffer.append('optimize ' + problem_name + '===================================================')
        line = []
        for type in method:
            opt_mean, opt_std, gen_mean, gen_std = run_for_real_problem(problem_name, type)
            print('--------------------------------------------------')
            print(type + ' optimization result: ', opt_mean, '#', opt_std)
            print(type + ' generalization result: ', gen_mean, '#', gen_std)
            log_buffer.append('--------------------------------------------------')
            log_buffer.append(type + ' optimization result: ' + str(opt_mean) + '#' + str(opt_std))
            log_buffer.append(type + ' generalization result: ' + str(gen_mean) + '#' + str(gen_std))
            col_name += [type + '-opt', type + '-opt-std', type + '-gen', type + '-gen-std']
            line += [opt_mean, opt_std, gen_mean, gen_std]
        res.append(line)

    result_path = path + '/Results/RealProbs/'

    optimization_log_file = result_path + 'running-log-method-' + str(len(method)) + '-budget-' + str(
        budget) + '-' + str(index) + '.txt'
    print('optimization logging: ', optimization_log_file)
    fo.FileWriter(optimization_log_file, log_buffer, style='w')
    pd.DataFrame(columns=col_name, index=dataset,
                 data=res).to_csv(
        result_path + 'result-method-' + str(len(method)) + '-budget-' + str(budget) + '-' + str(index) + '.csv')


from googleapiclient import discovery
from google.oauth2 import service_account
from googleapiclient.errors import HttpError

import os
import time
import json
import sys

class SA360:
    """
    The SA 360 class is scoped to the ADVERTISER.
    Each class instance will be associated with the advertiser, and can be re-used to retrieve multiple reports.
    Best practice though is probably to generate 1 instance per report.
    """

    def __init__(self, key, agency_id, advertiser_id):
        self.key=key
        self.agency_id=agency_id
        self.advertiser_id=advertiser_id
        self.file_id = None
        self.filenamepathdict={}

        credentials = service_account.Credentials.from_service_account_info(self.key)
        self.service = discovery.build('doubleclicksearch', 'v2', credentials=credentials)

#https://developers.google.com/search-ads/v2/how-tos/reporting/asynchronous-requests
    def generate_request(self, sdate, edate, reportType, columns, filters):
        """construct a report request"""

        columnlist = []
        filterclauselist = []

        for each in columns:
            dict = {'columnName': each}
            columnlist.append(dict)

        if filters == '':
            requestbody={
                'reportScope': {
                    'agencyId': self.agency_id,
                    'advertiserId': self.advertiser_id},
                'reportType': reportType,
                'columns': columnlist,
                'timeRange': {
                    'startDate': sdate,
                    'endDate': edate},
                'includeDeletedEntities': True,
                'includeRemovedEntities': True,
                'verifySingleTimeZone':False,
                'downloadFormat': 'csv',
                'statisticsCurrency': 'agency',
                'maxRowsPerFile': 100000000
            }

        elif filters != '':
            for each in filters:
                dict = {
                        'column': {
                            'columnName': each[0]},
                        'operator': each[1],
                        'values': [each[2]]}
                filterclauselist.append(dict)

            requestbody = {
                'reportScope': {
                    'agencyId': self.agency_id,
                    'advertiserId': self.advertiser_id},
                'reportType': reportType,
                'columns': columnlist,
                'timeRange': {
                    'startDate': sdate,
                    'endDate': edate},
                'filters':filterclauselist,
                'includeDeletedEntities': True,
                'includeRemovedEntities': True,
                'verifySingleTimeZone': True,
                'downloadFormat': 'csv',
                'statisticsCurrency': 'agency',
                'maxRowsPerFile': 100000000
            }

        return requestbody

    def find_file(self, requestbody):

        # execute the report request. if request is valid, SA360 will return response with file_id
        service = self.service
        request = service.reports().request(body=requestbody)
        response = request.execute()

        self.reportfile_id=response['id']

        return self.reportfile_id

    def generate_filename(self, name, reportfile_id, report_fragment):
        """Generates a report file name per fragment based on the file metadata."""

        service = self.service
        request = service.reports().get(reportId=reportfile_id)

        response=request.execute()

        # craft the filename
        file_name = 'sa360' \
                    + '_' \
                    + name \
                    + '_' \
                    + 'fragment-' \
                    + report_fragment \
                    + '_' \
                    + response['id'] \
                    + '_' \
                    + response['request']['timeRange']['startDate'] \
                    + '_' \
                    + response['request']['timeRange']['endDate'] \
                    + '.' \
                    + response['request']['downloadFormat']

        return file_name

    def generate_filename_path(self, file_name):
        """Generates a report file name and path based on the file metadata."""

        path = os.getcwd()
        filename_path = path + '/' + file_name

        return filename_path

    def download_files(self, name, reportfile_id, report_fragment, filename_path):
        """Generate and print sample report.

        Args:
          service: An authorized Doubleclicksearch service.
          report_id: The ID DS has assigned to a report.
          report_fragment: The 0-based index of the file fragment from the files array.
        """
        service = self.service
        request = service.reports().getFile(
            reportId=reportfile_id,
            reportFragment=report_fragment)

        f=open(filename_path, 'w')
        f.write(request.execute())
        f.close()

        return print(f'file fragment {report_fragment} has been downloaded and written to {filename_path}')

    def poll_download_file(self, name, reportfile_id):
        service = self.service

        for _ in range(10):
            try:
                request = service.reports().get(reportId=reportfile_id)
                response = request.execute()
                if response['isReportReady']:
                    print('The report is ready.')

                    # For large reports, DS automatically fragments the report into multiple
                    # files. The 'files' property in the JSON object that DS returns contains
                    # the list of URLs for file fragment. To download a report, DS needs to
                    # know the report ID and the index of a file fragment.
                    for i in range(len(response['files'])):
                        print('Downloading fragment ' + str(i) + ' for report ' + reportfile_id)
                        file_name = self.generate_filename(name=name,
                                                           reportfile_id=reportfile_id,
                                                           report_fragment=str(i))
                        filename_path = self.generate_filename_path(file_name)

                        self.filenamepathdict.update({file_name:filename_path})

                        self.download_files(name=name,
                                            reportfile_id=reportfile_id,
                                            report_fragment=str(i),
                                            filename_path=filename_path)

                    return print(f'all files downloaded')

                else:
                    retrytime=60
                    print(f'Report is not ready. I will try again in {retrytime}s.')
                    for i in range(retrytime, 0, -1):
                        sys.stdout.write(str(i) + ' ')
                        sys.stdout.flush()
                        time.sleep(1)
                    time.sleep(retrytime)

            except HttpError as e:
                error = json.loads(e.content)['error']['errors'][0]

                # See Response Codes
                print('HTTP code %d, reason %s' % (e.resp.status, error['reason']))
                break

    def download_files(self, name, reportfile_id, report_fragment, filename_path):
        """Generate and print sample report.

        Args:
          service: An authorized Doubleclicksearch service.
          report_id: The ID DS has assigned to a report.
          report_fragment: The 0-based index of the file fragment from the files array.
        """
        service = self.service
        request = service.reports().getFile(
            reportId=reportfile_id,
            reportFragment=report_fragment)
        response=request.execute()

        f=open(filename_path, 'wb')
        f.write(response)
        f.close()


import numpy as np
from MEC import bruteF_MEC, welzl, welzl_mtf, get_points
from time import time
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

total_points = 100

def get_runtime_stats(method, P, runs=10):
    times = []
    for _ in range(runs):
        start = time()
        method(P)
        times.append(time()-start)
    return dict(mean=np.mean(times), min=np.min(times), max=np.max(times))

def plot_runtimes(ax, runtimes, label, normalize=False, **kwargs):
    x = list(runtimes.keys())
    means, mins, maxs = zip(*[(v['mean'], v['min'], v['max']) for v in runtimes.values()])
    means, mins, maxs = np.asarray(means), np.asarray(mins), np.asarray(maxs)
    if normalize:
        means = means/means.max()
        mins = mins/mins.max()
        maxs = maxs/maxs.max()
    # ax.plot(x, means, c="#FFD700", label=label, **kwargs)
    # ax.fill_between(x, mins, maxs, facecolor="#FFD700", alpha=0.1, **kwargs)
    ax.plot(x, means, c="r", label=label, **kwargs)
    ax.fill_between(x, mins, maxs, facecolor="r", alpha=0.1, **kwargs)

def plot_order_four(ax, domain, C_range=(0.8e-8,8e-8), **kwargs):
    y = np.asarray(domain)**4
    lower = C_range[0]*y
    upper = C_range[1]*y
    ax.plot(domain, lower, c='orange', marker='o', markersize=3.5, label='0.1cn^4',**kwargs)
    ax.plot(domain, upper, c='orange', marker='s', markersize=3.5, label='cn^4',**kwargs)
    ax.fill_between(domain, lower, upper, alpha=0.1, facecolor='orange', **kwargs)

def plot_order_one(ax, domain, C_range=(0.8e-5,8e-5), **kwargs):
    y = np.asarray(domain)
    lower = C_range[0]*y
    upper = C_range[1]*y
    ax.plot(domain, lower, c='orange', marker='o', markersize=3.5, label='0.1cn',**kwargs)
    ax.plot(domain, upper, c='orange', marker='s', markersize=3.5, label='cn',**kwargs)
    ax.fill_between(domain, lower, upper, alpha=0.1, facecolor='orange', **kwargs)

def f(x, c):
    return c*x

P = get_points(total_points)

N = np.asarray(range(3, len(P)))
runtimes_bf = {}
# base = get_runtime_stats(bruteF_MEC, P, runs=1)
for i in N:
    runtimes_bf[i] = get_runtime_stats(bruteF_MEC, P[:i], runs=1)

means = np.asarray([v['mean'] for v in runtimes_bf.values()])
# means = means/means.max()
# print(curve_fit(f, N, means, [2e-8]))

fig, ax = plt.subplots()
plot_runtimes(ax, runtimes_bf, label='Brute Force')
plot_order_four(ax, N[::3])
plt.xlabel("Number of points (N)")
plt.ylabel("Time (s)")
plt.legend()
plt.show()

# N = np.asarray(range(3, len(P)))
# runtimes_welzl = {}
# # base = get_runtime_stats(bruteF_MEC, P, runs=1)
# for i in N:
#     runtimes_welzl[i] = get_runtime_stats(welzl, P[:i], runs=10)
#
# means = np.asarray([v['mean'] for v in runtimes_welzl.values()])
# # means = means/means.max()
# print(curve_fit(f, N, means, [1]))
#
# fig, ax = plt.subplots()
# plot_runtimes(ax, runtimes_welzl, label='Welzl')
# plot_order_one(ax, N[::3])
# plt.xlabel("Number of points (N)")
# plt.ylabel("Time (s)")
# plt.legend()
# plt.show()


import injector

from apps.media import services
from apps.media.logic import interfaces

class MediaInfrastructureServicesModule(injector.Module):
    """Setup di for media infrastructure services."""

    def configure(self, binder: injector.Binder) -> None:
        """Bind services."""
        binder.bind(
            interfaces.IImageDownloadService,
            services.ImageDownloadService,
        )
        binder.bind(
            interfaces.ICleanupMediaFilesService,
            services.CleanupMediaFilesService,
        )


import pygame
from program_variables import settings

class LevelMap():
	def __init__(self):
		self.screen = settings.screen

		self.image = pygame.image.load('.\\Images\\Maps\\Lobby\\Lobby_Test_Wall.png')
		#self.image = pygame.image.load('.\\Images\\Maps\\map_background_test.png')
		self.rect = self.image.get_rect()
		self.rect.x = self.screen.rect.x
		self.rect.y = self.screen.rect.y

		self.image_overlay = pygame.image.load('.\\Images\\Maps\\Lobby\\Lobby_Test_Art.png')
		#self.image_overlay = pygame.image.load('.\\Images\\Maps\\map_test_overlay.png')
		self.rect_overlay = self.image_overlay.get_rect()
		self.rect_overlay.x = self.screen.rect.x
		self.rect_overlay.y = self.screen.rect.y

	def blitme(self):
		self.screen.display.blit(self.image, self.rect)
	def blit_overlay(self):
		self.screen.display.blit(self.image_overlay, self.rect_overlay)


"""
https://www.practicepython.org

Exercise 17: Decode a Web Page
4 chilis

Use the BeautifulSoup and requests Python packages to print out a
list of all the article titles on the New York Times homepage.

"""
# need to go to bash shell
# then run:   pipenv install requests
# then run:   pipenv shell
# then run    pip install beautifulsoup4

import requests
from bs4 import BeautifulSoup

url = 'https://www.nytimes.com'
r = requests.get(url)
r_html = r.text

soup = BeautifulSoup(r_html, "html.parser")
#for story_title in soup.find_all(class_ = 'story-heading'):
for story_title in soup.find_all(True , 'story-heading'):
    if story_title.a:
        #print(story_title.a.text.replace("\n", " ").strip())
        print(story_title.a.text.strip())
    else:
        print(story_title.contents[0].strip())

#for tag in soup.find_all('div'):
#    tag = soup.li
#    print(tag.name)
#    print(tag.attrs)


import os
import connexion
from .plugins import db, ma

def create_app(spec=None, config=None):

    connex_app = connexion.App(
        __name__,
        specification_dir=spec,
        options={"swagger_ui": False, "serve_spec": False},
    )

    connex_app.add_api("v1.yml", strict_validation=True)

    flask_app = connex_app.app

    if config is None:
        config = os.path.join(flask_app.root_path, os.environ.get('FLASK_APPLICATION_SETTINGS'))

    flask_app.config.from_pyfile(config)

    #initalize plugins
    db.init_app(flask_app)
    ma.init_app(flask_app)

    #import routes
    from .resources import v1

    # Register Blueprints ...

    return flask_app


"""Ingredient table updated

Revision ID: f35bf66d6d65
Revises: 5088979dc35a
Create Date: 2018-12-07 10:29:28.704630

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'f35bf66d6d65'
down_revision = '5088979dc35a'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_unique_constraint(None, 'ingredient', ['name'])
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'ingredient', type_='unique')
    # ### end Alembic commands ###


from django.shortcuts import render
from .models import Todo
# Create your views here.

def index(request):
    todos = Todo.objects.all()
    context = {
        'todos' : todos ,
    }
    return render(request, 'todos/index.html', context)

def detail(request, pk):
    todo = Todo.objects.get(pk=pk)
    context = {
        'todo' : todo,
    }
    return render(request, 'todos/detail.html', context)

def new(request):

    return render(request, 'todos/new.html')

def create(request):
    # new 에서 보낸 사용자 데이터를 받음
    title = request.GET.get('title')
    content = request.GET.get('content')
    # completed = request.GET.get('completed')
    priority = request.GET.get('priority')
    created_at = request.GET.get('created_at')
    deadline = request.GET.get('deadline')

    # 받은 데이터를 DB에 저장

    Todo.objects.create(title=title,content=content,priority=priority,created_at=created_at,deadline=deadline)
    #
    # 결과 페이지 반환
    return render(request, 'todos/create.html')


from multiprocessing import context
from django.shortcuts import render, redirect, get_object_or_404
from users.forms import *
from django.contrib.messages.views import SuccessMessageMixin
from users.models import *
from dashboard.models import *
from django.contrib import messages
from django.urls import reverse_lazy
from django.views.generic.edit import  DeleteView, CreateView, UpdateView, CreateView
from django.contrib import messages
from django.core.paginator import Paginator
from django.contrib.auth.decorators import login_required
from django.db.models import Q

@login_required
def dashboard(request):
    # startdate = datetime.today()
    # end_date = startdate + timedelta(days=30)

    # biometries = [prof for prof in Profile.objects if prof.is_due() ]
    all_users = User.objects.all().count()
    all_rejected = Profile.objects.filter(rejected =True).count()
    # all_success = Profile.objects.filter(is_success =True).count()
    total_profile_revenues = 0
    total_revenues = 0
    total_expenses = 0
    all_revenue = Cashmemo.objects.all()
    for revenue in all_revenue:
        total_revenues+= revenue.amount

    all_expenses = AccountsExpense.objects.all()
    for expense in all_expenses:
        total_expenses+= expense.amount

    all_profiles_paid = Profile.objects.filter(has_paid =True)
    for profile_revenue in all_profiles_paid:
        total_profile_revenues+= profile_revenue.amount_paid_so_far

    total_revenues = int(total_revenues +total_profile_revenues)

    total_profits = int(total_revenues)-int(total_expenses)

    context ={
        # 'biometries': biometries,
        'all_users': all_users,
        'all_rejected': all_rejected,
        'total_revenues': total_revenues,
        'total_expenses': total_expenses,
        'total_profits': total_profits,
    }

    return render(request, 'dashboard/dashboard.html', context)

@login_required
def profiles(request):
    # user = User.objects.get(id = request.user.id)
    profiles = User.objects.all()
    # page_number = request.GET.get('page',1)
    paginator = Paginator(profiles, 5)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    context = {
        "profiles": profiles,
        "paginator": paginator,
        "page_number": page_number,
        "page_obj": page_obj,
    }
    return render(request, 'dashboard/profiles.html', context)
#to change this in function based view

# class Profiles(ListView):
#     template_name='dashboard/profiles.html'
#     model= Profile
#     context_object_name = 'profiles'
#     ordering = ['-email']

def Profile_detail(request, pk):
    users = User.objects.filter(pk = pk)
    context = {'users': users}
    return render(request, 'dashboard/profile_detail.html', context)

class Profile_create(CreateView):
    template_name='dashboard/profile_create.html'
    model= User
    # fields = '__all__'
    success_url = reverse_lazy('dashboard:profiles')
    form_class=RegisterUserCreationForm

class Profile_update(SuccessMessageMixin, UpdateView):
    template_name='dashboard/profile_update.html'
    model= User
    context_object_name = 'profile'
    success_message = "Profile Was updated Successfully"
    success_url = reverse_lazy('dashboard:profiles')
    fields = ('first_name', 'last_name', 'gender', 'phone', 'birth_date', 'country_of_orgin', 'country_of_destination', \
        'nationality', 'next_of_kin', 'next_of_kin_phone_number', 'has_paid', 'has_done_biometry_before', 'has_done_biometry', 'has_obtained_visa_before',\
         'rejected', 'passport_document', 'covid_certificate', 'yellow_fever')

class Profile_delete(SuccessMessageMixin, DeleteView):
    template_name='dashboard/profile_delete.html'
    model= User
    context_object_name = 'profile'
    success_message = "Profile Was Deleted Successfully"
    success_url = reverse_lazy('dashboard:profiles')

def search_profile(request):
    profiles = None
    if 'keyword' in request.GET:
        keyword = request.GET['keyword']
        if keyword:
            profiles = User.objects.order_by('id').filter(Q(first_name__icontains=keyword)| Q(last_name__icontains= keyword) |Q(country_of_destination__icontains= keyword)|Q(phone__icontains= keyword)) # fielter treats , as a and
    context = {
        'profiles':profiles,
    }
    return render(request, 'dashboard/profiles.html',context )

# def add_profile(request):
#     form=ProfileCreateForm(request.POST)
#     if form.is_valid():
#         form.save()
#         # fullname = form.cleaned_data.get('username')
#         fullname = Profile.full_name
#         messages.success(request, f'Account created for {fullname}')
#         return redirect('dashboard:profiles')
#     else:
#         form = ProfileCreateForm()
#         context = {
#             'form': form
#         }
#     context ={"form":form}
#     return render(request, 'dashboard/profile_add.html',context)


from train import create_model_train
import numpy as np
from sklearn.preprocessing import LabelEncoder
from data_prepare import get_data

#get test data
x_test,y_test = get_data(mode = "test")

#process the data
x_test = np.expand_dims(x_test, axis=3)
en_t = LabelEncoder()
en_t.fit(y_test)
y_test_encoded = en_t.transform(y_test)

#prediction
model = create_model_train()
prediction = model.predict(x_test)

#print 10 sample test results
print("10 sample test results")
test_truth = [ y_test_encoded[i] for i in range(10) ]
test_result = [ np.argmax(prediction[i]) for i in range(10) ]
testdata = {'test_truth': test_truth, 'test_result': test_result}
result_table = pd.DataFrame(testdata)
print(result_table)


from django.core.management.base import BaseCommand, CommandError
import pandas as pd
from pathlib import Path
from ...models import Product, Author, RarityType

class Command(BaseCommand):
    help = 'Populates the database with some initial data'

    def handle(self, *args, **options):

        print("Starting Acme NFT population script...")

        # ----------------------------- Load NFTs -----------------------------

        def get_rarity(price, stock, mean):

            index = price/stock

            normaliced_index = index / mean

            if normaliced_index < 0.5:
                return RarityType.common
            elif normaliced_index < 1:
                return RarityType.rare
            elif normaliced_index < 1.5:
                return RarityType.epic
            elif normaliced_index < 2:
                return RarityType.legendary
            elif normaliced_index >= 2:
                return RarityType.mythic

        path = Path(__file__).parent / "../../static/dataset/dataset.csv"

        datos = pd.read_csv(path, sep=",", header=0, names=["title", "name", "creator", "art_series", "price", "symbol", "type", "likes", "nsfw", "tokens", "year" , "rights", "royalty", "cid", "path"])

        mean_price_per_stock = (datos["price"]/datos["tokens"]).mean()

        for index, row in datos.iterrows():

            # Find or create the author
            try:
                author = Author.objects.get(name=row["creator"])
            except Author.DoesNotExist:
                author = Author(name=row["creator"])
                author.save()

            rarity = get_rarity(float(row["price"]), int(row["tokens"]), mean_price_per_stock)
            showcase = rarity == RarityType.mythic or rarity == RarityType.legendary
            # Create and save the product
            product = Product(name=row["name"], collection=row["title"], price=float(row["price"]), stock=int(row["tokens"]), image_url=row["path"].replace("./", ""), offer_price=None, rarity=rarity, author=author, showcase=showcase)
            product.save()

        print("Done! Your product database is now populated with some initial data.")


from bs4 import BeautifulSoup
import requests

url_va = 'http://historical.elections.virginia.gov/elections/search/year_from:1924/year_to:2016/office_id:1/stage:General'

# just things you do every time
req_va = requests.get(url_va)
html_va = req_va.content #getting the contents of the website
soup = BeautifulSoup(html_va,'html.parser') #turning it into a soup object so you can manipulate in python

#open the html of url_va (you can do this if you right click anywhere on page and select 'view page source'
#search for '80871' when you look at the HTML of the page.
#what kind of tag comes in front?:

#find 'tr' tags with class 'election_item because these contain the ID'
tags = soup.find_all('tr','election_item')

#if you just want to look at 2016's data
lastyear = tags[0]
lastyear_id = lastyear['id'] #text of id
lastyear_id = lastyear['id'][-5:] #you only want the last five characters

#printing all of the year/id pairs
for t in tags:
    year = t.td.text
    year_id = t['id'][-5:]
    print(year, year_id)
#...now do the same thing, but put it all in a list called ELECTION_ID
#maybe you can do this with a list comprehension!

#the base URL that all downloads pages have
base = 'http://historical.elections.virginia.gov/elections/download/{}/precincts_include:0/'

#the url for 2016
lastyear_url = base.format('80871')
lastyear_text = requests.get(lastyear_url).text

#writing 2016 to a csv
with open('2016.csv', 'w') as output:
    output.write(requests.get(lastyear_url).text)


import speech_recognition as sr
import subprocess

def main():
    recognizer = sr.Recognizer()

    # システムを起動させるためのワードを格納する
    boot_word = 'あいうえお'

    with sr.Microphone() as source:
        print("【あいうえお】を待機しています...")
        audio = recognizer.listen(source)

    try:
        # 音声認識を実行して、認識したテキストとして変数に格納する
        recognized_text = recognizer.recognize_google(audio, language='ja-JP')

        print("認識結果:", recognized_text)

        # 認識した音声と設定したboot_wordが一致するか判定。一致したときは「audio_2.py」を実行する。
        if boot_word in recognized_text:
            print("match")
            subprocess.run(["python", "backend//audio_2.py"])
        else:
            print("not match")

    # エラー処理
    except sr.UnknownValueError:
        print("音声を認識出来ませんでした。")
    except sr.RequestError as e:
        print(f"Google Web Speech APIにアクセス出来ませんでした: {e}")

if __name__ == "__main__":
    main()


from django.shortcuts import render

from product.forms import ProductForm

def product_creation(request):
    if request != 'POST':
        form = ProductForm()
    else:
        # post has been filled, ready for processing
        form = ProductForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()

    context = {
        "form": form
    }
    return render(request, 'product/product_creation.html', context)


# baekjoon s2 로또
# https://www.acmicpc.net/problem/6603

from itertools import combinations
import sys
input = sys.stdin.readline

while True:
    temp = input().split()
    if len(temp) == 1 and temp[0] == '0':
        break
    K = int(temp[0])
    S = temp[1:]
    for c in combinations(S, 6):
        print(' '.join(c))
    print()


import pytest

from ocean_lib.ocean.util import get_address_of_type
from ocean_lib.web3_internal.constants import ZERO_ADDRESS
from ocean_lib.web3_internal.contract_base import ContractBase
from tests.resources.helper_functions import get_wallet

class MyFactory(ContractBase):
    CONTRACT_NAME = "ERC721Factory"

@pytest.mark.unit
def test_name_is_None(config):
    with pytest.raises(Exception):
        # self.name will become None, triggering the error
        ContractBase(config, None)

@pytest.mark.unit
def test_main(config):
    alice_wallet = get_wallet(1)
    # test super-simple functionality of child
    nft_factory_address = get_address_of_type(config, "ERC721Factory")
    factory = MyFactory(config, nft_factory_address)
    factory.deployERC721Contract(
        "NFT",
        "NFTS",
        1,
        ZERO_ADDRESS,
        ZERO_ADDRESS,
        "http://someurl",
        True,
        alice_wallet.address,
        {"from": alice_wallet},
    )

    # test attributes
    assert factory.contract_name == "ERC721Factory"
    assert factory.contract is not None
    assert factory.contract.address == nft_factory_address
    assert ContractBase.to_checksum_address(nft_factory_address) == nft_factory_address

    # test methods
    assert factory.contract_name == "ERC721Factory"
    assert factory.address == nft_factory_address
    assert str(factory) == f"{factory.contract_name} @ {factory.address}"
    assert factory.createToken
    assert factory.getCurrentTokenCount
    assert factory.getTokenTemplate


import pygame
from pygame.sprite import Sprite
from program_variables import program_data as pd, settings

class MapEntity(Sprite):
	def __init__(self, x, y):
		super(MapEntity, self).__init__()
		self.x = x
		self.y = y
		self.image = None
		self.rect = None

	def blitme(self):
		pass

class PhysicalMapEntity(MapEntity):
	def __init__(self, x, y):
		super().__init__(x, y)

		self.level_map = pd.level_map
		self.screen = settings.screen
		self.tile_size = settings.tile_size
		self.collisions = pd.collisions

	def blitme(self):
		self.rect.x = self.x
		self.rect.y = self.y
		self.screen.display.blit(self.image, self.rect)

class Carpet(PhysicalMapEntity):
	def __init__(self, x, y):
		super().__init__(x, y)
		self.image = pygame.image.load('.\\Images\\Maps\\carpet_test.png')
		self.rect = self.image.get_rect()


#!/usr/bin/python
# author mawei
import os
import sys
import argparse
import cv2
import random
import colorsys
import requests
from io import BytesIO

import skimage.io
from skimage.measure import find_contours
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import torch
import torch.nn as nn
import torchvision
from torchvision import transforms as pth_transforms
import numpy as np
from PIL import Image
import config as c
from model import *

import utils
def apply_mask(image, mask, color, alpha=0):#?
    for c in range(3):
        image[:, :, c] = image[:, :, c] * (1 - alpha * mask) + alpha * mask * color[c] * 255
    #     在遮掩处将图像遮掩，用alpha表示透明度，并用color在遮掩处给上新值，即颜色区分出来
    return image

def random_colors(N, bright=True):
    """
    Generate random colors.
    """
    brightness = 1.0 if bright else 0.7
    hsv = [(i / N, 1, brightness) for i in range(N)]
    colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
    random.shuffle(colors)
    return colors

# image mask 原图片和attnmask矩阵
def display_instances(image, mask, fname="test", figsize=(5, 5), blur=False, contour=True, alpha=0.5):
    #
    fig = plt.figure(figsize=figsize, frameon=False)
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    ax = plt.gca()#?

    N = 1
    # 增加了一个维度
    mask = mask[None, :, :]
    # Generate random colors
    colors = random_colors(N)

    # Show area outside image boundaries.
    height, width = image.shape[:2]
    margin = 0
    ax.set_ylim(height + margin, -margin)
    ax.set_xlim(-margin, width + margin)
    ax.axis('off')
    masked_image = image.astype(np.uint32).copy()
    for i in range(N):
        color = colors[i]
        _mask = mask[i]
        if blur:
            _mask = cv2.blur(_mask,(10,10))#图像进行模糊处理
        # Mask
        masked_image = apply_mask(masked_image, _mask, color, alpha)
        # Mask Polygon
        # Pad to ensure proper polygons for masks that touch image edges.
        contour = False
        if contour:#找到掩膜的边界，将创建多面性对象将掩膜的边界在轴上画出来
            padded_mask = np.zeros((_mask.shape[0] + 2, _mask.shape[1] + 2))
            padded_mask[1:-1, 1:-1] = _mask#?
            contours = find_contours(padded_mask, 0.5)
            for verts in contours:
                # Subtract the padding and flip (y, x) to (x, y)
                verts = np.fliplr(verts) - 1
                p = Polygon(verts, facecolor=color, edgecolor=color)
                ax.add_patch(p)
    ax.imshow(masked_image.astype(np.uint8), aspect='auto')
    fig.savefig(fname)
    print(f"{fname} saved.")
    return

os.environ['TORCH_HOME'] = 'models\\EfficientNet'
if __name__ == '__main__':
    parser = argparse.ArgumentParser('Visualize Self-Attention maps')
    parser.add_argument('--arch', default='vit_small', type=str,
        choices=['vit_tiny', 'vit_small', 'vit_base'], help='Architecture (support only ViT atm).')
    parser.add_argument('--patch_size', default=16, type=int, help='Patch resolution of the model.')
    parser.add_argument('--pretrained_weights', default='checkpoint/dino_deitsmall8_300ep_pretrain.pth', type=str,
        help="Path to pretrained weights to load.")
    parser.add_argument("--checkpoint_key", default="teacher", type=str,
        help='Key to use in the checkpoint (example: "teacher")')
    parser.add_argument("--image_path", default='data/hazelnut/test/crack/000.png', type=str, help="Path of the image to load.")
    parser.add_argument("--image_size", default=(384, 384), type=int, nargs="+", help="Resize image.")
    parser.add_argument('--output_dir', default='./output', help='Path where to save visualizations.')
    parser.add_argument("--threshold", type=float, default=0.5, help="""We visualize masks
        obtained by thresholding the self-attention maps to keep xx% of the mass.""")
    args = parser.parse_args()

    device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
    # build model or build flow model
    model = load_model(c.modelname)
    model.eval()
    net = model.nf_mlp.module_list
    model_ad = ADwithGlow()
    feature_extractor = model_ad.feature_extractor
    with open(args.image_path, 'rb') as f:
        img = Image.open(f)
        img = img.convert('RGB')

    transform = pth_transforms.Compose([transforms.Resize(c.img_size, Image.ANTIALIAS),
               transforms.CenterCrop(c.img_size),
               transforms.ToTensor(),
               transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
       ])
    img = transform(img)

    # make the image divisible by the patch size
    # 3,384,384
    w, h = img.shape[1] - img.shape[1] % args.patch_size, img.shape[2] - img.shape[2] % args.patch_size
    # batchsize 维度
    img = img[:, :w, :h].unsqueeze(0)

    w_featmap = img.shape[-2] // args.patch_size
    h_featmap = img.shape[-1] // args.patch_size
    inp = list()
    img_inp = feature_extractor(img)
    img_inp = img_inp.transpose(1,2)
    inp.append(img_inp)
    for i in range(9):
        if i==0:
            continue
        if i ==8:
            inp,attentions = net[i](inp, attention=True)
        else:
            inp = net[i](inp)

    nh = 8
    attentions=attentions[:,:,0,1:].reshape(8,-1)

    if args.threshold is not None:
        # we keep only a certain percentage of the mass
        val, idx = torch.sort(attentions)
        val /= torch.sum(val, dim=1, keepdim=True)
        cumval = torch.cumsum(val, dim=1)#第i位为到该位的和
        th_attn = cumval > (1 - args.threshold)#bool矩阵， True代表从初始位到该位置的和大于 1-0.9
        # 获取当前数组中每一个数在原数组中的位置
        idx2 = torch.argsort(idx)
        for head in range(nh):
            # 将bool矩阵按原attn重新归位
            th_attn[head] = th_attn[head][idx2[head]]
        th_attn = th_attn.reshape(nh, w_featmap, h_featmap).float()
        # interpolate 等比例缩放
        th_attn = nn.functional.interpolate(th_attn.unsqueeze(0), scale_factor=args.patch_size, mode="nearest")[0].cpu().numpy()
    #4,24,24
    attentions = attentions.reshape(nh, w_featmap, h_featmap)
    attentions = nn.functional.interpolate(attentions.unsqueeze(0), scale_factor=args.patch_size, mode="nearest")[0].detach().cpu().numpy()

    # save attentions heatmaps
    os.makedirs(args.output_dir, exist_ok=True)
    torchvision.utils.save_image(torchvision.utils.make_grid(img, normalize=True, scale_each=True), os.path.join(args.output_dir, "img.png"))
    for j in range(nh):
        fname = os.path.join(args.output_dir, "attn-head" + str(j) + ".png")
        plt.imsave(fname=fname, arr=attentions[j], format='png')
        print(f"{fname} saved.")

    if args.threshold is not None:
        image = skimage.io.imread(os.path.join(args.output_dir, "img.png"))
        for j in range(nh):
            display_instances(image, th_attn[j], fname=os.path.join(args.output_dir, "mask_th" + str(args.threshold) + "_head" + str(j) +".png"), blur=False)


"""
Sanyerlis Camacaro - CSC235 - Sancamac@uat.edu Assignment:
Assignment 3.1: Your Third Assignment

"Mido Chat Bot"

Requirements and Expectations:

Create a new Python application.
Give your program the ability to do new things and have new features using 3rd party libraries.
Give your program the ability to do new things and have new features using Python packages.
Your application must do something innovative and interesting, not just demo libraries and objects.
Make a great User experience.
Over comment your code showing your intent and your understanding of what your code does.

Reminder, this code works, but does not open in my computer. Professor Hinton tested it successfully
on his computer.
"""
# Import our libraries
import os
# Import our libraries for the GUI tkinter
import tkinter as tk
# Import our libraries to create a text area with a scrollbar
from tkinter import scrolledtext
# Import our libraries to load our language model and generate responses
from llama_cpp import Llama
# Import our random libraries to generate random numbers
import random
# Import a library to get the current date
import datetime

# Create a global variable for the pathto our model
# If you  use different model later, you need to change this path
############## This is where you change the path to your model ############
model_path = "llama-2-7b-chat.Q5_K_M.gguf"

# Create a global variable to set the version of your application
version = "1.00"

# Get the current date and stuff into a variable
todays_date = datetime.datetime.now().strftime("%Y-%m-%d")

# Create function to load our model
def load_model():
    # check if the model path is valid
    if not os.path.isfile(model_path):
        print("ERROR: The model path is not valid, please check the path in the main.py file")
        print("and make sure the model is in the same folder as the main.py file")
        # If the model path is not valid, exist the program
        exit()

    # If not the model path is valid, load the model
    global model
    model = Llama(
        model_path=model_path,
        seed=random.randint(1, 2**31)
    )

# Create function to generate a response
def generate_response(model, input_tokens, prompt_input_text):
    # Display the input text in the text area response on top
    text_area_display.insert(tk.INSERT, '\n\nUser: ' + prompt_input_text + '\n')

    output_response_text = b""
    count = 0
    output_response_text = b"\n\nHAL9000:"
    text_area_display.insert(tk.INSERT, output_response_text)
    #Generate a response
    for token in model.generate(input_tokens, top_k=40, top_p=0.95, temp=0.72, repeat_penalty=1.1):
        # Extract the response text from the output of the model which is in token
        # format and convert it to a string
        response_text = model.detokenize([token])
        output_response_text = response_text.decode()
        # Display the respone text in the textarea response on top
        text_area_display.insert(tk.INSERT, output_response_text)
        root.update_idletasks()
        count += 1
        # Now that we have a response, we can break out of the loop
        if count > 2000 or (token == model.token_eos()):
            break
        # And we can clear in the input to let the user know the response
        # from the model is complete
        text_area_main_user_input.delete('1.0', 'end')

# Create a function to send a message to the model and display a response
def send_message():
    # Get the text from the textarea input that the user typed in.
    user_prompt_input_text = text_area_main_user_input.get('1.0', 'end-1c')
    # Delete any leading or tralling spaces from the user input.
    user_prompt_input_text = user_prompt_input_text.strip()
    # ecode the message with uft-8
    byte_message = user_prompt_input_text.encode('utf-8')

    # Here is where you can change the prompt formart for the LLM.
    # This is something you will need to experiment to get the best result.
    input_tokens = model.tokenize(b"### Human: " + byte_message + b"\n### Assistant: ")

    # print out the inpt tokens to the console for debugging and information on how this works.
    print("Input tokens:", input_tokens)
    # Call the generate_response function to generate a response
    generate_response(model, input_tokens, user_prompt_input_text)

# Our main function to build to GUI
def main():
    # Load our model when our app starts!
    load_model()
    # Create our GUI
    # Remember root is in this case our main window
    global root
    root =tk.Tk()

    # Set the title of our app
    root.title("Hal900 -v" + version + " - " + todays_date)
    # Create a frame to add a scrollbar to our textarea
    frame_display = tk.Frame(root)
    scrollbar_frame_display = tk.Scrollbar(frame_display)
    # The text area where we will display the response from the model plus the user input together
    # This will allow to see the conversation between the user and the model in one place
    global text_area_display
    text_area_display = scrolledtext.ScrolledText(frame_display, height=25, width=128, yscrollcommand=scrollbar_frame_display.set)
    # Create our color here. You can change these to whatever you want.
    my_light_yellow = "#ffff33"
    my_dark_grey = "#202020"
    # Set the background and foreground colors of the textarea, and font. change these to whatever you want.
    text_area_display.config(background=my_dark_grey, foreground=my_light_yellow, font=("Courier", 12))
    scrollbar_frame_display.config(command=text_area_display.yview)
    text_area_display.pack(side=tk.RIGHT, fill=tk.BOTH)
    scrollbar_frame_display.pack(side=tk.RIGHT, fill=tk.Y)
    # Fill our root window with the frame
    frame_display.pack()

    frame_controls = tk.Frame(root)
    # Create a label to let the user knwo what LLM model and path to the model we are currently using
    model_path_label = tk.Label(frame_controls, text="Model Path: " + model_path, font=("Courier", 12))
    model_path_label.pack(side=tk. LEFT, padx=10)
    frame_controls.pack(fill=tk.BOTH, padx=5, pady=5)

    # Create our frame for the user input, remember this at tthe bottom of out app
    frame_user_input = tk.Frame(root)
    frame_user_input.pack(fill=tk.BOTH)

    frame_main_user_input = tk.Frame(root)
    scrollbar_main_user_input = tk.Scrollbar(frame_main_user_input)

    global text_area_main_user_input
    text_area_main_user_input = scrolledtext.ScrolledText(frame_main_user_input, height=5, width=128, yscrollcommand=scrollbar_main_user_input.set)
    # Set the background and foregroybd colors of tge textarea, abd font. Change these to whatever you want.
    text_area_main_user_input.config(background=my_dark_grey, foreground=my_light_yellow, font=("Courier",12))
    scrollbar_main_user_input.config(command=text_area_main_user_input.yview)
    # Fill our roort window with the frame
    text_area_main_user_input.pack(side=tk.LEFT, fill=tk.BOTH)
    scrollbar_main_user_input.pack(side=tk.RIGHT,fill=tk.Y)
    frame_main_user_input.pack()

    # Create a button to send the user input to the model
    # Remember the enter key will NOT send the user input to the model. You must press the button! Howeever, you can change the
    send_button = tk.Button(root, text="Send", command=send_message)
    # Fill our roort window with the button
    send_button.pack()
    # Must have this run our app
    root.mainloop()

# App start here
if __name__ == "__main__":
    # Call our main function to start the app!
    main()


import collections

def count_islands(ocean_map: list[list[int]], n_rows, n_columns) -> int:
    n_islands = 0
    visited = set()

    def bfs(row, column):
        queue = collections.deque()
        queue.append((row, column))
        while queue:
            row, column = queue.popleft() # to do depth first search just popright()
            visited.add((row, column))
            if row < n_rows and column < n_columns:
                if ocean_map[row][column]:
                    queue.append((row, column+1))
                    queue.append((row+1, column))

    for row in range(n_rows):
        for column in range(n_columns):
            if (row, column) not in visited:
                bfs(row, column)
                n_islands+=ocean_map[row][column]

    return n_islands