#!/usr/bin/env python3

import socket

def main():
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
  s.bind(("127.0.0.1", 24000))
  s.listen(1)
  conn, addr = s.accept()
  data = conn.recv(1024, socket.MSG_WAITALL)
  print(data)
  s.close()

if __name__ == '__main__':
  main()


# -*- coding: utf-8 -*-
import gensim
import numpy as np
from scipy import spatial
from gensim.models.word2vec import Word2Vec
import numpy as np
import settings
import string

def avg_feature_vector(sentence, model, num_features, index2word_set):
    words = sentence.split()
    feature_vec = np.zeros((num_features, ), dtype='float32')
    n_words = 0
    for word in words:
        if word in settings.index2word_set:
            n_words += 1
            feature_vec = np.add(feature_vec, settings.model[word])
    if (n_words > 0):
        feature_vec = np.divide(feature_vec, n_words)
    return feature_vec

def chat(uinput):
    ans = ""
    translator = str.maketrans('', '', string.punctuation)
    #check for weather service keywords
    uinput =uinput.translate(translator).lower()
    i = 0
    s1 = uinput
    max_sim = 0
    for question in settings.q:
        s2 = question
        s1_afv = avg_feature_vector(s1, model=settings.model, num_features=100, index2word_set=settings.index2word_set)
        s2_afv = avg_feature_vector(s2, model=settings.model, num_features=100, index2word_set=settings.index2word_set)
        sim = 1 - spatial.distance.cosine(s1_afv, s2_afv)
        print(sim)
        if (sim>max_sim and sim>0.6):
            max_sim = sim
            ans = settings.a[i]
        i = i + 1

    if ans=="" or ans is None: ans = u"Я не знаю ответ на этот вопрос. Я все еще учусь."
    return ans


from base import *

import content
import scraper
import releases
import debrid
from ui import ui_settings
from ui.ui_print import *
from settings import *

#import uvicorn

config_dir = ""
service_mode = False

class option:
    def __init__(self, name, cls, key):
        self.name = name
        self.cls = cls
        self.key = key

    def input(self):
        func = getattr(self.cls, self.key)
        func()

def ignored():
    back = False
    while not back:
        ui_cls('Options/Ignored Media/')
        if len(content.classes.ignore.ignored) == 0:
            library = content.classes.library()[0]()
            if len(library) > 0:
                # get entire plex_watchlist
                plex_watchlist = content.services.plex.watchlist()
                # get entire trakt_watchlist
                trakt_watchlist = content.services.trakt.watchlist()
                print('checking new content ...')
                for iterator in itertools.zip_longest(plex_watchlist, trakt_watchlist):
                    for element in iterator:
                        if hasattr(element, 'uncollected') and hasattr(element, 'watched'):
                            element.watched()
                            element.uncollected(library)
            print()
        print('0) Back')
        indices = []
        for index, element in enumerate(content.classes.ignore.ignored):
            print(str(index + 1) + ') ' + element.query())
            indices += [str(index + 1)]
        print()
        choice = input('Choose a media item that you want to remove from the ignored list: ')
        if choice in indices:
            print("Media item: " + content.classes.ignore.ignored[int(choice) - 1].query() + ' removed from ignored list.')
            content.classes.ignore.ignored[int(choice) - 1].unwatch()
            time.sleep(3)
        elif choice == '0':
            back = True
    options()

def scrape():
    ui_cls('Options/Scraper/')
    print('Press Enter to return to the main menu.')
    print()
    print("Please choose a version to scrape for: ")
    print()
    obj = releases.release('', '', '', [], 0, [])
    indices = []
    for index, version in enumerate(releases.sort.versions):
        print(str(index + 1) + ') ' + version[0] + (' (disabled)' if '\u0336' in version[0] else ''))
        indices += [str(index + 1)]
    print(str(index + 2) + ') Scrape without defining a version')
    indices += [str(index + 2)]
    print()
    choice = input("Choose a version: ")
    if choice in indices and not choice == str(index + 2):
        obj.version = releases.sort.version(releases.sort.versions[int(choice) - 1][0],
                                            releases.sort.versions[int(choice) - 1][1],
                                            releases.sort.versions[int(choice) - 1][2],
                                            releases.sort.versions[int(choice) - 1][3])
    elif choice == str(index + 2):
        obj.version = None
    else:
        return
    while True:
        ui_cls('Options/Scraper/')
        print('Press Enter to return to the main menu.')
        print()
        query = input("Enter a query: ")
        if query == '':
            return
        print()
        if hasattr(obj,"version"):
            if not obj.version == None:
                for trigger, operator, value in obj.version.triggers:
                    if trigger == "scraper sources":
                        if operator in ["==","include"]:
                            if value in scraper.services.active:
                                scraper.services.overwrite += [value]
                        elif operator == "exclude":
                            if value in scraper.services.active:
                                for s in scraper.services.active:
                                    if not s == value:
                                        scraper.services.overwrite += [s]
                    if trigger == "scraping adjustment":
                        if operator == "add text before title":
                            query = value + query
                        elif operator == "add text after title":
                            query = query + value
        scraped_releases = scraper.scrape(query)
        if len(scraped_releases) > 0:
            obj.Releases = scraped_releases
            debrid.check(obj, force=True)
            scraped_releases = obj.Releases
            if not obj.version == None:
                releases.sort(scraped_releases, obj.version)
            back = False
            while not back:
                ui_cls('Options/Scraper/')
                print("0) Back")
                releases.print_releases(scraped_releases)
                print()
                print("Type 'auto' to automatically download the first cached release.")
                print()
                choice = input("Choose a release to download: ")
                try:
                    if choice == 'auto':
                        release = scraped_releases[0]
                        release.Releases = scraped_releases
                        release.type = ("show" if regex.search(r'(S[0-9]+|SEASON|E[0-9]+|EPISODE|[0-9]+-[0-9])',release.title,regex.I) else "movie")
                        if debrid.download(release, stream=True, query=query, force=True):
                            content.classes.media.collect(release)
                            scraped_releases.remove(scraped_releases[0])
                            time.sleep(3)
                        else:
                            print()
                            print("These releases do not seem to be cached on your debrid services. Add uncached torrent?")
                            print()
                            print("0) Back")
                            print("1) Add uncached torrent")
                            print()
                            choice = input("Choose an action: ")
                            if choice == '1':
                                debrid.download(release, stream=False, query=query, force=True)
                                content.classes.media.collect(release)
                                scraped_releases.remove(scraped_releases[0])
                                time.sleep(3)
                    elif int(choice) <= len(scraped_releases) and not int(choice) <= 0:
                        release = scraped_releases[int(choice) - 1]
                        release.Releases = [release, ]
                        release.type = ("show" if regex.search(r'(S[0-9]+|SEASON|E[0-9]+|EPISODE|[0-9]+-[0-9])',release.title,regex.I) else "movie")
                        if debrid.download(release, stream=True, query=release.title, force=True):
                            content.classes.media.collect(release)
                            scraped_releases.remove(scraped_releases[int(choice) - 1])
                            time.sleep(3)
                        else:
                            print()
                            print(
                                "This release does not seem to be cached on your debrid services. Add uncached torrent?")
                            print()
                            print("0) Back")
                            print("1) Add uncached torrent")
                            print()
                            choice2 = input("Choose an action: ")
                            if choice2 == '1':
                                if debrid.download(release, stream=False, query=query, force=True):
                                    content.classes.media.collect(release)
                                    scraped_releases.remove(scraped_releases[int(choice) - 1])
                                    time.sleep(3)
                                else:
                                    print()
                                    print(
                                        "There was an error adding this uncached torrent to your debrid service. Choose another release?")
                    elif choice == '0':
                        back = True
                except:
                    back = False
        else:
            print("No releases were found!")
            time.sleep(3)

def settings():
    back = False
    while not back:
        list = settings_list
        ui_cls('Options/Settings/')
        print('0) Back')
        indices = []
        for index, category in enumerate(list):
            print(str(index + 1) + ') ' + category[0])
            indices += [str(index + 1)]
        print()
        print('Type "discard" to go back and discard changes.')
        print()
        choice = input('Choose an action: ')
        if choice in indices:
            ui_cls('Options/Settings/' + list[int(choice) - 1][0] + '/')
            settings = []
            for index, setting in enumerate(list[int(choice) - 1][1]):
                if not setting.hidden:
                    settings += [setting]
            if len(settings) > 1:
                print('0) Back')
                for index, setting in enumerate(settings):
                    if not setting.hidden:
                        print(str(index + 1) + ') ' + setting.name)
                print()
                choice2 = input('Choose an action: ')
            else:
                choice2 = '1'
            for index, setting in enumerate(list[int(choice) - 1][1]):
                if choice2 == str(index + 1) and not setting.hidden:
                    ui_cls('Options/Settings/' + list[int(choice) - 1][0] + '/' + setting.name)
                    setting.input()
        elif choice == '0':
            save()
            back = True
        elif choice == 'discard':
            load(doprint=True)
            back = True

def options():
    current_module = sys.modules[__name__]
    list = [
        option('Run', current_module, 'download_script_run'),
        option('Settings', current_module, 'settings'),
        option('Ignored Media', current_module, 'ignored'),
        option('Scraper', current_module, 'scrape'),
    ]
    ui_cls('Options/',update=update_available())
    for index, option_ in enumerate(list):
        print(str(index + 1) + ') ' + option_.name)
    print()
    print('Type exit to quit.')
    print()
    choice = input('Choose an action: ')
    if choice == 'exit':
        exit()
    for index, option_ in enumerate(list):
        if choice == str(index + 1):
            option_.input()
    options()

def setup():
    if os.path.exists(config_dir + '/settings.json'):
        if os.path.getsize(config_dir + '/settings.json') > 0 and os.path.isfile(config_dir + '/settings.json'):
            with open(config_dir + '/settings.json', 'r') as f:
                settings = json.loads(f.read())
            if settings['Show Menu on Startup'] == "false" or service_mode == True:
                return False
            load()
            return True
    ui_cls('Initial Setup')
    try:
        input('Press Enter to continue: ')
    except:
        print("Error: It seems this terminal is not interactive! Please make sure to allow user input in this terminal. For docker, add the 'interactive' flag ('-ti').")
        time.sleep(10)
        exit()
    for category, settings in settings_list:
        for setting in settings:
            if setting.required:
                ui_cls('Options/Settings/' + category + '/' + setting.name)
                setting.setup()
    ui_cls('Done!')
    input('Press Enter to continue to the main menu: ')
    save()
    return True

def save(doprint=True):
    save_settings = {}
    for category, settings in settings_list:
        for setting in settings:
            save_settings[setting.name] = setting.get()
    try:
        with open(config_dir + '/settings.json', 'w') as f:
            json.dump(save_settings, f, indent=4)
        if doprint:
            print('Current settings saved!')
            time.sleep(2)
    except:
        print()
        print("Error: It looks like plex_debrid can not write your settings into a config file. Make sure you are running the script with write or administator privilege.")
        print()
        input("Press enter to exit: ")
        exit()

def load(doprint=False, updated=False):
    with open(config_dir + '/settings.json', 'r') as f:
        settings = json.loads(f.read())
    if 'version' not in settings:
        update(settings, ui_settings.version)
        updated = True
    elif not settings['version'][0] == ui_settings.version[0] and not ui_settings.version[2] == []:
        update(settings, ui_settings.version)
        updated = True
    #compatability code for updating from <2.10
    if 'Library Service' in settings:
        settings['Library collection service'] = settings['Library Service']
        if settings['Library Service'] == ["Plex Library"]:
            if 'Plex \"movies\" library' in settings and 'Plex \"shows\" library' in settings:
                settings['Plex library refresh'] = [settings['Plex \"movies\" library'],settings['Plex \"shows\" library']]
            settings['Library update services'] = ["Plex Libraries"]
        elif settings['Library Service'] == ["Trakt Collection"]:
            settings['Library update services'] = ["Trakt Collection"]
            settings['Trakt refresh user'] = settings['Trakt library user']
    #compatability code for updating from <2.20
    if not 'Library ignore services' in settings:
        if settings['Library collection service'] == ["Plex Library"]:
            settings['Library ignore services'] = ["Plex Discover Watch Status"]
            settings["Plex ignore user"] = settings["Plex users"][0][0]
        elif settings['Library collection service'] == ["Trakt Collection"]:
            settings['Library ignore services'] = ["Trakt Watch Status"]
            settings["Trakt ignore user"] = settings["Trakt users"][0]
    for category, load_settings in settings_list:
        for setting in load_settings:
            if setting.name in settings and not setting.name == 'version' and not setting.name == 'Content Services':
                setting.set(settings[setting.name])
    if doprint:
        print('Last settings loaded!')
        time.sleep(2)
    save(doprint=updated)

def preflight():
    missing = []
    for category, settings in settings_list:
        for setting in settings:
            if setting.preflight:
                if len(setting.get()) == 0:
                    missing += [setting]
    if len(missing) > 0:
        print()
        print('Looks like your current settings didnt pass preflight checks. Please edit the following setting/s: ')
        for setting in missing:
            print(setting.name + ': Please add at least one ' + setting.entry + '.')
        print()
        input('Press Enter to return to the main menu: ')
        return False
    return True

def run(cdir = "", smode = False):
    global config_dir
    global service_mode
    config_dir = cdir
    service_mode = smode
    set_log_dir(config_dir)
    if setup():
        #uvicorn.run("webui:app", port=8008, reload=True)
        options()
    else:
        load()
        #uvicorn.run("webui:app", port=8008, reload=True)
        download_script_run()
        options()

def update_available():
    try:
        response = requests.get('https://raw.githubusercontent.com/itsToggle/plex_debrid/main/ui/ui_settings.py',timeout=0.25)
        response = response.content.decode()
        if regex.search("(?<=')([0-9]+\.[0-9]+)(?=')",response):
            v = regex.search("(?<=')([0-9]+\.[0-9]+)(?=')",response).group()
            if float(ui_settings.version[0]) < float(v):
                return " | [v"+v+"] available!"
            return ""
        return ""
    except:
        return ""

def update(settings, version):
    ui_cls('/Update ' + version[0] + '/')
    print('There has been an update to plex_debrid, which is not compatible with your current settings:')
    print()
    print(version[1])
    print()
    print('This update will overwrite the following setting/s: ' + str(version[2]))
    print('A backup file (old.json) with your old settings will be created.')
    print()
    input('Press Enter to update your settings:')
    with open(config_dir + "/old.json", "w+") as f:
        json.dump(settings, f, indent=4)
    for category, load_settings in settings_list:
        for setting in load_settings:
            for setting_name in version[2]:
                if setting.name == setting_name:
                    settings[setting.name] = setting.get()
                elif setting.name == 'version':
                    settings[setting.name] = setting.get()

def unique(lst):
    unique_objects = []
    for obj in lst:
        is_unique = True
        for unique_obj in unique_objects:
            if unique_obj == obj:
                is_unique = False
                break
        if is_unique:
            unique_objects.append(obj)
    return unique_objects

def threaded(stop):
    ui_cls()
    if service_mode == True:
        print("Running in service mode, user input not supported.")
    else:
        print("Type 'exit' to return to the main menu.")
    timeout = 5
    regular_check = 1800
    timeout_counter = 0
    library = content.classes.library()[0]()
    # get entire plex_watchlist
    plex_watchlist = content.services.plex.watchlist()
    # get entire trakt_watchlist
    trakt_watchlist = content.services.trakt.watchlist()
    # get all overseerr request
    overseerr_requests = content.services.overseerr.requests()
    # combine all content, sort by newest
    watchlists = plex_watchlist + trakt_watchlist + overseerr_requests
    try:
        watchlists.data.sort(key=lambda s: s.watchlistedAt,reverse=True)
    except:
        ui_print("couldnt sort monitored media by newest, using default order.", ui_settings.debug)
    if len(library) > 0:
        ui_print('checking new content ...')
        t0 = time.time()
        for element in unique(watchlists):
            if hasattr(element, 'download'):
                element.download(library=library)
                t1 = time.time()
                #if more than 5 seconds have passed, check for newly watchlisted content
                if t1-t0 >= 5:
                    if plex_watchlist.update() or overseerr_requests.update() or trakt_watchlist.update():
                        library = content.classes.library()[0]()
                        if len(library) == 0:
                            continue
                        new_watchlists = plex_watchlist + trakt_watchlist + overseerr_requests
                        try:
                            new_watchlists.data.sort(key=lambda s: s.watchlistedAt,reverse=True)
                        except:
                            ui_print("couldnt sort monitored media by newest, using default order.", ui_settings.debug)
                        new_watchlists = unique(new_watchlists)
                        for element in new_watchlists[:]:
                            if element in watchlists:
                                new_watchlists.remove(element)
                        ui_print('checking new content ...')
                        for element in new_watchlists:
                            if hasattr(element, 'download'):
                                element.download(library=library)
                        ui_print('done')
                    t0 = time.time()
        ui_print('done')
    while not stop():
        if plex_watchlist.update() or overseerr_requests.update() or trakt_watchlist.update():
            library = content.classes.library()[0]()
            if len(library) == 0:
                continue
            watchlists = plex_watchlist + trakt_watchlist + overseerr_requests
            try:
                watchlists.data.sort(key=lambda s: s.watchlistedAt,reverse=True)
            except:
                ui_print("couldnt sort monitored media by newest, using default order.", ui_settings.debug)
            ui_print('checking new content ...')
            for element in unique(watchlists):
                if hasattr(element, 'download'):
                    newly_added = True
                    if element.type == "show":
                        for season in element.Seasons:
                            if season in content.classes.media.ignore_queue or not newly_added:
                                newly_added = False
                                break
                            for episode in season.Episodes:
                                if episode in content.classes.media.ignore_queue:
                                    newly_added = False
                                    break
                    if newly_added:
                        element.download(library=library)
            ui_print('done')
        elif timeout_counter >= regular_check:
            # get entire plex_watchlist
            plex_watchlist = content.services.plex.watchlist()
            # get entire trakt_watchlist
            trakt_watchlist = content.services.trakt.watchlist()
            # get all overseerr request, match content to plex media type and add to monitored list
            overseerr_requests = content.services.overseerr.requests()
            # combine all content, sort by newest
            watchlists = plex_watchlist + trakt_watchlist + overseerr_requests
            try:
                watchlists.data.sort(key=lambda s: s.watchlistedAt,reverse=True)
            except:
                ui_print("couldnt sort monitored media by newest, using default order.", ui_settings.debug)
            library = content.classes.library()[0]()
            timeout_counter = 0
            if len(library) == 0:
                continue
            ui_print('checking new content ...')
            t0 = time.time()
            for element in unique(watchlists):
                if hasattr(element, 'download'):
                    element.download(library=library)
                    t1 = time.time()
                    #if more than 5 seconds have passed, check for newly watchlisted content
                    if t1-t0 >= 5:
                        if plex_watchlist.update() or overseerr_requests.update() or trakt_watchlist.update():
                            library = content.classes.library()[0]()
                            if len(library) == 0:
                                continue
                            new_watchlists = plex_watchlist + trakt_watchlist + overseerr_requests
                            try:
                                new_watchlists.data.sort(key=lambda s: s.watchlistedAt,reverse=True)
                            except:
                                ui_print("couldnt sort monitored media by newest, using default order.", ui_settings.debug)
                            new_watchlists = unique(new_watchlists)
                            for element in new_watchlists[:]:
                                if element in watchlists:
                                    new_watchlists.remove(element)
                            ui_print('checking new content ...')
                            for element in new_watchlists:
                                if hasattr(element, 'download'):
                                    element.download(library=library)
                            ui_print('done')
                        t0 = time.time()
            ui_print('done')
        else:
            timeout_counter += timeout
        time.sleep(timeout)

def download_script_run():
    if preflight():
        global stop
        stop = False
        t = Thread(target=threaded, args=(lambda: stop,))
        t.start()
        if service_mode == True:
            print("Running in service mode, user input not supported.")
        else:
            while not stop:
                text = input("")
                if text == 'exit':
                    stop = True
                else:
                    print("Type 'exit' to return to the main menu.")
        print("Waiting for the download automation to stop ... ")
        while t.is_alive():
            time.sleep(1)


from pico2d import *
import math
import main_game
import framework
from BehaviorTree import BehaviorTree, SelectorNode, SequenceNode, LeafNode
import bullet
import game_world
import default_enemy
import random
PIXEL_PER_KILOMETER = 5
QUAD_PI = math.pi / 4
HALF_OF_QUAD_PI = QUAD_PI / 2

LEFT, BOTTOM = 257, 1

IMAGE_WIDTH, IMAGE_HEIGHT = 324 - 257, 308 - 255
SIZE_PROPOTION = IMAGE_WIDTH / IMAGE_HEIGHT

SIZE_KM = 7
SPEED_KMPS = 50

class Wei(default_enemy.DefaultEnemy):
    def load_image(self):
        if Wei.image is None:
            Wei.image = load_image('resources\\character\\enemys.png')

    def reset_status(self):
        self.size = SIZE_KM * PIXEL_PER_KILOMETER
        self.ran_dir = 0
        self.shoot_delay = 1
        self.damage_amount = 5
        self.max_HP = 10
        self.HP = 10
        self.speed_per_hp = SPEED_KMPS / self.HP
        self.set_speed(self.speed_per_hp)
        self.size_propotion = SIZE_PROPOTION
        pass

    def find_player(self):
        player = main_game.get_player()
        self.dir = math.atan2(player.x - self.x, player.y - self.y) + self.ran_dir
        return BehaviorTree.SUCCESS

    def delay_time(self):
        if self.shoot_count > self.shoot_delay:
            self.shoot_count -= self.shoot_delay
            return BehaviorTree.SUCCESS
        else:
            return BehaviorTree.FAIL
        pass

    def build_behavior_tree(self):
        find_player_node = LeafNode("Find Player", self.find_player)
        delay_node = LeafNode("Delay", self.delay_time)
        shoot_to_player = LeafNode("Shoot", self.attack)
        chase_node = SequenceNode("Chase")
        chase_node.add_children(find_player_node, delay_node, shoot_to_player)
        self.bt = BehaviorTree(chase_node)

        pass

    def get_damaged(self, damage):
        self.ran_dir = random.randint(-5000, 5000) / 10000
        self.HP -= damage
        self.set_speed(self.kmps + damage * self.speed_per_hp)
        self.hp_bar.change_hp()
        if self.HP < 0:
            main_game.add_delete_list(self)

    def attack(self):
        self.get_damaged(1)
        return BehaviorTree.SUCCESS

    def draw(self, screen):
        self.image.clip_draw(LEFT, BOTTOM, IMAGE_WIDTH, IMAGE_HEIGHT, self.x - screen.x, self.y - screen.y,
                               self.size * SIZE_PROPOTION, self.size)
        if self.HP < self.max_HP:
            self.hp_bar.draw(screen)


def abs(x):
    if x >= 0:
        a = x
    else:
        a = -1*x
    return a
num = int(input("Enter the number\n"))
print("The absolute value of", num, "is", abs(num))

'''
float has issue with - and int has issue with decimal numbers
'''

Python Programming for Data Science /08_Chapter_Functions/10_Absolute_Value.py


import os
import argparse
import itertools
from pywebcat.utils import WebCAT

def main():
    """Command line function for saving frames of webCAT videos.
    """
    (
        directory,
        station,
        year,
        month,
        day,
        time,
        interval,
        no_meta,
        quality,
        verbose,
    ) = parse_args()
    wc = WebCAT()
    for item in itertools.product(station, year, month, day, time):
        try:
            wc.generate_url(*item)  # generate url from the input data
            tmp_dir = os.path.join(directory, item[0], wc.name)  # dir to save frames in
            if not os.path.exists(tmp_dir):
                os.makedirs(tmp_dir)  # mkdir if not exist
            if verbose:
                print(f"Saving frames of {wc.name}...")
            wc.save_frames(
                interval, tmp_dir, not no_meta, quality, verbose
            )  # save frames
        except Exception as e:
            if verbose:
                url = f"http://webcat-video.axds.co/{item[0]}/raw/{item[1]}/{item[1]}_{item[2]:02}/{item[1]}_{item[2]:02}_{item[3]:02}/{item[0]}.{item[1]}-{item[2]:02}-{item[3]:02}_{item[4]:04}.mp4"
                print(f"Error for url: {url}. Traceback: {e} Skipping this url.")

def parse_args():
    parser = argparse.ArgumentParser(
        description="CLI for saving frames of webCAT video(s)."
    )
    required = parser.add_argument_group("required arguments")
    # below I'm using --arg with "required" to allow for multiple "nargs"
    required.add_argument(
        "-dir",
        "--directory",
        type=dir_path,
        help="Absolute path of directory to save frames in.",
        required=True,
    )
    required.add_argument(
        "-s",
        "--station",
        nargs="+",
        type=str,
        help="The station name, e.g., buxtoncoastalcam.",
        required=True,
    )
    required.add_argument(
        "-y",
        "--year",
        nargs="+",
        type=int,
        help="The video year(s), e.g., 2019 2020.",
        required=True,
    )
    required.add_argument(
        "-m",
        "--month",
        nargs="+",
        type=int,
        help="The video month(s), e.g., 9 10 11.",
        required=True,
    )
    required.add_argument(
        "-d",
        "--day",
        nargs="+",
        type=int,
        help="The video day(s) e.g., 1 11 21.",
        required=True,
    )
    required.add_argument(
        "-t",
        "--time",
        nargs="+",
        type=int,
        help="The video time(s), e.g., 1000 1330 1510.",
        required=True,
    )
    parser.add_argument(
        "-i",
        "--interval",
        default=10,
        type=int,
        help="Interval in seconds between video frames to save (default: 10).",
    )
    parser.add_argument(
        "-n",
        "--no_meta",
        action="store_true",
        help="Don't save .csv file of metadata of saved video frames.",
    )
    parser.add_argument(
        "-q",
        "--quality",
        default=95,
        type=int,
        help="Quality of saved frames between 0 (lowest) and 100 (highest) (default: 95).",
    )
    parser.add_argument(
        "-v", "--verbose", action="store_true", help="Print program status."
    )
    args = parser.parse_args()

    return (
        args.directory,
        args.station,
        args.year,
        args.month,
        args.day,
        args.time,
        args.interval,
        args.no_meta,
        args.quality,
        args.verbose,
    )

def dir_path(path: str):
    """Utility function for argparse to check existence of a passed directory.

    Parameters
    ----------
    path : str
        Absolute path to local directory.

    """

    if os.path.isdir(path):
        return path
    else:
        raise argparse.ArgumentTypeError(
            f"readable_dir:{path} is not a valid directory path."
        )

if __name__ == "__main__":
    main()


#!/usr/bin/env python3

from pwn import *

context.terminal = ['tmux', 'split', '-h']
context.arch = 'amd64'
context.binary = "/home/myfs/myfs"
# context.log_level = "debug"

# p = process("./fullchain-buff")
p = gdb.debug("/home/myfs/myfs", """
b mock
b *mock+687
""")

p.interactive()


import logging
import time
from typing import Optional

import pytest  # type: ignore
import requests

from tests.conftest import TrackedContainer, find_free_port

LOGGER = logging.getLogger(__name__)

@pytest.mark.parametrize(
    "env,expected_command,expected_start,expected_warnings",
    [
        (None, "jupyter lab", True, []),
        (["DOCKER_STACKS_JUPYTER_CMD=lab"], "jupyter lab", True, []),
        (["RESTARTABLE=yes"], "run-one-constantly jupyter lab", True, []),
        (["DOCKER_STACKS_JUPYTER_CMD=notebook"], "jupyter notebook", True, []),
        (["DOCKER_STACKS_JUPYTER_CMD=server"], "jupyter server", True, []),
        (["DOCKER_STACKS_JUPYTER_CMD=nbclassic"], "jupyter nbclassic", True, []),
        (
            ["JUPYTERHUB_API_TOKEN=my_token"],
            "jupyterhub-singleuser",
            False,
            ["WARNING: using start-singleuser.py"],
        ),
    ],
)
def test_start_notebook(
    container: TrackedContainer,
    http_client: requests.Session,
    env: Optional[list[str]],
    expected_command: str,
    expected_start: bool,
    expected_warnings: list[str],
) -> None:
    """Test the notebook start-notebook.py script"""
    LOGGER.info(
        f"Test that the start-notebook.py launches the {expected_command} server from the env {env} ..."
    )
    host_port = find_free_port()
    running_container = container.run_detached(
        tty=True,
        environment=env,
        ports={"8888/tcp": host_port},
    )
    # sleeping some time to let the server start
    time.sleep(1)
    logs = running_container.logs().decode("utf-8")
    LOGGER.debug(logs)
    # checking that the expected command is launched
    assert (
        f"Executing the command: {expected_command}" in logs
    ), f"Not the expected command ({expected_command}) was launched"
    # checking errors and warnings in logs
    assert "ERROR" not in logs, "ERROR(s) found in logs"
    for exp_warning in expected_warnings:
        assert exp_warning in logs, f"Expected warning {exp_warning} not found in logs"
    warnings = TrackedContainer.get_warnings(logs)
    assert len(expected_warnings) == len(warnings)
    # checking if the server is listening
    if expected_start:
        resp = http_client.get(f"http://localhost:{host_port}")
        assert resp.status_code == 200, "Server is not listening"

def test_tini_entrypoint(
    container: TrackedContainer, pid: int = 1, command: str = "tini"
) -> None:
    """Check that tini is launched as PID 1

    Credits to the following answer for the ps options used in the test:
    https://superuser.com/questions/632979/if-i-know-the-pid-number-of-a-process-how-can-i-get-its-name
    """
    LOGGER.info(f"Test that {command} is launched as PID {pid} ...")
    running_container = container.run_detached(
        tty=True,
        command=["start.sh"],
    )
    # Select the PID 1 and get the corresponding command
    cmd = running_container.exec_run(f"ps -p {pid} -o comm=")
    output = cmd.output.decode("utf-8").strip("\n")
    assert "ERROR" not in output
    assert "WARNING" not in output
    assert output == command, f"{command} shall be launched as pid {pid}, got {output}"


import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import Dropout, Flatten, Dense, GlobalAveragePooling2D, Input
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras import optimizers
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
import matplotlib.pyplot as plt
import math
import os
import os.path
import time

# utility functions
def graph_training_history(history, save_fig=False, save_path=None):
    plt.rcParams["figure.figsize"] = (12, 9)

    plt.style.use('ggplot')

    plt.figure(1)

    # summarize history for accuracy

    plt.subplot(211)
    plt.plot(history.history['acc'])
    plt.plot(history.history['val_acc'])
    plt.title('Model Accuracy')
    plt.ylabel('Accuracy')
    plt.xlabel('Epoch')
    plt.legend(['Training', 'Validation'], loc='lower right')

    # summarize history for loss

    plt.subplot(212)
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('Model Loss')
    plt.ylabel('Loss')
    plt.xlabel('Epoch')
    plt.legend(['Training', 'Validation'], loc='upper right')

    plt.tight_layout()

    if save_fig:
        plt.savefig(save_path, bbox_inches='tight', dpi=300)
    else:
        plt.show()

    # clear and close the current figure
    plt.clf()
    plt.close()

# util function to calculate the class weights based on the number of samples on each class
# this is useful with datasets that are highly skewed (datasets where
# the number of samples in each class differs vastly)
def get_class_weights(class_data_dir):
    labels_count = dict()
    for img_class in [ic for ic in os.listdir(class_data_dir) if ic[0] != '.']:
        labels_count[img_class] = len(os.listdir(os.path.join(class_data_dir, img_class)))
    total_count = sum(labels_count.values())
    class_weights = {cls: total_count / count for cls, count in
                    enumerate(labels_count.values())}
    return class_weights

# util function to get the initial epoch number from the checkpoint name
def get_init_epoch(checkpoint_path):
    filename = os.path.basename(checkpoint_path)
    filename = os.path.splitext(filename)[0]
    init_epoch = filename.split("-")[1]
    return int(init_epoch)

run_training = True
run_finetune = True

class_indices_path = 'class_indices.npy'
initial_model_path = 'bird_classify_finetune_initial.h5'
final_model_path = 'bird_classify_finetune_final.h5'

# check which of the training steps still need to complete
# if saved model file is already there, then that step is considered complete
if os.path.isfile(initial_model_path):
    run_training = False
    print("[Info] Initial model exists '{}'. Skipping training step.".format(initial_model_path))

if os.path.isfile(final_model_path):
    run_finetune = False
    print("[Info] Fine-tuned model exists '{}'. Skipping fine-tuning step.".format(final_model_path))

load_from_checkpoint_train = False

training_checkpoint_dir = 'checkpoints/training'
if run_training and len(os.listdir(training_checkpoint_dir)) > 0:
    # the checkpoint to load and continue from
    training_checkpoint = os.path.join(training_checkpoint_dir, os.listdir(training_checkpoint_dir)[len(os.listdir(training_checkpoint_dir))-1])
    load_from_checkpoint_train = True

init_epoch_train = 0
if load_from_checkpoint_train:
    # get the epoch number to continue from
    print(training_checkpoint)
    init_epoch_train = get_init_epoch(training_checkpoint)
    print("[Info] Training checkpoint found for epoch {}. Will continue from that step.".format(init_epoch_train))

load_from_checkpoint_finetune = False

finetune_checkpoint_dir = 'checkpoints/finetune'
if run_finetune and len(os.listdir(finetune_checkpoint_dir)) > 0:
    # the checkpoint to load and continue from
    finetune_checkpoint = os.path.join(finetune_checkpoint_dir, os.listdir(finetune_checkpoint_dir)[len(os.listdir(finetune_checkpoint_dir))-1])
    load_from_checkpoint_finetune = True

init_epoch_finetune = 0
if load_from_checkpoint_finetune:
    # get the epoch number to continue from
    init_epoch_finetune = get_init_epoch(finetune_checkpoint)
    print("[Info] Training checkpoint found for epoch {}. Will continue from that step.".format(init_epoch_finetune))

# start time of the script
start_time = time.time()

# dimensions of our images.
img_width, img_height = 224, 224

train_data_dir = 'data/train'
validation_data_dir = 'data/validation'

# number of epochs to train
epochs = 50

# batch size used by flow_from_directory
batch_size = 16

# this is the augmentation configuration we will use for training
train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

# this is the augmentation configuration we will use for testing:
# only rescaling
test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='categorical')

# the number of classes/categories
num_classes = len(train_generator.class_indices)

# save the class indices for use in the predictions
np.save(class_indices_path, train_generator.class_indices)

# calculate the training steps
nb_train_samples = len(train_generator.filenames)
train_steps = int(math.ceil(nb_train_samples / batch_size))

# calculate the validation steps
nb_validation_samples = len(validation_generator.filenames)
validation_steps = int(math.ceil(nb_validation_samples / batch_size))

# get the class weights
class_weights = get_class_weights(train_data_dir)

if run_training:
    if load_from_checkpoint_train:
        model = load_model(training_checkpoint)
    else:
        # create the base pre-trained model
        base_model = InceptionV3(
            weights='imagenet',
            include_top=False,
            input_tensor=Input(shape=(img_width, img_height, 3))
            )

        # add a global spatial average pooling layer
        x = base_model.output
        x = GlobalAveragePooling2D()(x)
        x = Dense(512, activation='relu')(x)
        predictions = Dense(num_classes, activation='softmax')(x)

        # this is the model we will train
        model = Model(inputs=base_model.input, outputs=predictions)

        # first: train only the top layers (which were randomly initialized)
        # i.e. freeze all convolutional layers
        for layer in base_model.layers:
            layer.trainable = False

        # compile the model (should be done *after* setting layers to non-trainable)
        model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])

    filepath = training_checkpoint_dir + "/model-{epoch:02d}-{val_acc:.2f}-{val_loss:.2f}.h5"
    checkpoint = ModelCheckpoint(
                                filepath,
                                monitor="val_acc",
                                verbose=1,
                                save_best_only=True,
                                save_weights_only=False,
                                mode="max"
                                )

    early_stop = EarlyStopping(
                                monitor="val_acc",
                                mode="max",
                                verbose=1,
                                patience=5,
                                restore_best_weights=True
                                )

    callbacks_list = [checkpoint, early_stop]

    history = model.fit(
                        train_generator,
                        steps_per_epoch=train_steps,
                        epochs=epochs,
                        validation_data=validation_generator,
                        validation_steps=validation_steps,
                        class_weight=class_weights,
                        max_queue_size=15,
                        workers=8,
                        initial_epoch=init_epoch_train,
                        callbacks=callbacks_list
                        )

    model.save(initial_model_path)

    (eval_loss, eval_accuracy) = model.evaluate(
        validation_generator, steps=validation_steps)

    print("\n")

    print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100))
    print("[INFO] Loss: {}".format(eval_loss))

    graph_training_history(history, save_fig=True, save_path='training.png')

else:
    # training step is already completed
    # load the already trained model
    model = load_model(initial_model_path)

# Run Fine-tuning on our model
if run_finetune:
    # number of epochs to fine-tune
    ft_epochs = 25

    # reset our data generators
    train_generator.reset()
    validation_generator.reset()

    if load_from_checkpoint_finetune:
        model = load_model(finetune_checkpoint)
    else:
        # we chose to train the last convolution block from the base model
        for layer in model.layers[:249]:
            layer.trainable = False
        for layer in model.layers[249:]:
            layer.trainable = True

        # we need to recompile the model for these modifications to take effect
        # we use SGD with a low learning rate
        model.compile(
            optimizer=optimizers.SGD(lr=0.0001, momentum=0.9),
            loss='categorical_crossentropy',
            metrics=['acc']
            )

    filepath = finetune_checkpoint_dir + "/model-{epoch:02d}-{val_acc:.2f}-{val_loss:.2f}.h5"
    checkpoint = ModelCheckpoint(
                                filepath,
                                monitor="val_acc",
                                verbose=1,
                                save_best_only=True,
                                save_weights_only=False,
                                mode="max"
                                )

    early_stop = EarlyStopping(
                                monitor="val_acc",
                                mode="max",
                                verbose=1,
                                patience=5,
                                restore_best_weights=True
                                )

    callbacks_list = [checkpoint, early_stop]

    history = model.fit(
                        train_generator,
                        steps_per_epoch=train_steps,
                        epochs=ft_epochs,
                        validation_data=validation_generator,
                        validation_steps=validation_steps,
                        class_weight=class_weights,
                        max_queue_size=15,
                        workers=8,
                        initial_epoch=init_epoch_finetune,
                        callbacks=callbacks_list
                        )

    model.save(final_model_path)

    (eval_loss, eval_accuracy) = model.evaluate(
        validation_generator, steps=validation_steps)

    print("\n")

    print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100))
    print("[INFO] Loss: {}".format(eval_loss))

    graph_training_history(history, save_fig=True, save_path='finetune.png')

    end_time = time.time()

    training_duration = end_time - start_time
    print("[INFO] Total Time for training: {} seconds".format(training_duration))


# TIE-02106 Introduction to Programming
# Lecture example: One dice game
# Version 1: the number of players is fixed to two and the whole program is
# implemented using this logic.

# UNFINISHED! We will continue from here in the next lecture by for example
# adding the dice pictures.

from tkinter import *
import random

WINPOINTS = 50

PLAYER_1 = 1
PLAYER_2 = 2

class Dicegame:
    def __init__(self):
        # Creating the window and the components
        self.__window = Tk()
        self.__window.title("Dicegame")
        self.__window.option_add("*Font", "Verdana 14")

        self.__dice_label = Label(self.__window, font="Verdana 72 bold",
                                  width=1, borderwidth=6, relief=RAISED)

        self.__throw_button \
            = Button(self.__window, text="throw", command=self.throw)
        self.__hand_over_button \
            = Button(self.__window, text="hand over", command=self.hand_over)
        self.__new_game_button \
            = Button(self.__window, text="new game", command=self.new_game)
        self.__quit_button \
            = Button(self.__window, text="quit", command=self.quit)

        self.__player1_points_title_label \
            = Label(self.__window, text="Player 1 points:")
        self.__player2_points_title_label \
            = Label(self.__window, text="Player 2 points:")
        self.__points_accumulated_title_label \
            = Label(self.__window, text="Accumulated points:")
        self.__instructions_label = Label(self.__window, anchor=E, text="@")

        self.__player1_points_label = Label(self.__window, width=3, anchor=E)
        self.__player2_points_label = Label(self.__window, width=3, anchor=E)
        self.__points_accumulated_label = Label(self.__window, width=3, anchor=E)

        # Placing the components
        self.__dice_label.grid(row=0, column=1, rowspan=3, sticky=N + E + S + W)

        self.__throw_button.grid(row=0, column=0, sticky=E + W)
        self.__hand_over_button.grid(row=1, column=0, sticky=E + W)
        self.__new_game_button.grid(row=2, column=0, sticky=E + W)
        self.__quit_button.grid(row=3, column=0, sticky=E + W)

        self.__player1_points_title_label.grid(row=0, column=2, sticky=E)
        self.__player2_points_title_label.grid(row=1, column=2, sticky=E)
        self.__points_accumulated_title_label.grid(row=2, column=2, sticky=E)

        self.__instructions_label.grid(row=3, column=1, columnspan=3, sticky=E + W)
        self.__player1_points_label.grid(row=0, column=3, sticky=E)
        self.__player2_points_label.grid(row=1, column=3, sticky=E)
        self.__points_accumulated_label.grid(row=2, column=3, sticky=E)

        self.new_game()

        # Start the userinterface
        self.__window.mainloop()

    def new_game(self):
        self.__player1_points = 0
        self.__player2_points = 0
        self.__accumulated_points = 0
        self.__number_of_turns = 0
        self.__whose_turn = PLAYER_1
        self.update_ui()

    def update_ui(self):
        self.__player1_points_label["text"] = self.__player1_points
        self.__player2_points_label["text"] = self.__player2_points
        self.__points_accumulated_label["text"] = self.__accumulated_points
        self.__instructions_label["text"] = "Player "+str(self.__whose_turn)+\
                                            " throw the dice or hand over the turn"

    def throw(self):
        dice = random.randint(1, 6)
        self.__dice_label["text"] = dice

        if dice == 1:
            self.__accumulated_points = 0
            if self.__whose_turn == PLAYER_1:
                self.__whose_turn = PLAYER_2
            else:
                self.__whose_turn = PLAYER_1
        else:
            self.__accumulated_points += dice
        self.update_ui()

    def hand_over(self):
        if self.__whose_turn == PLAYER_1:
            self.__player1_points += self.__accumulated_points
            self.__whose_turn = PLAYER_2
        else:
            self.__player2_points += self.__accumulated_points
            self.__whose_turn = PLAYER_1

        self.__accumulated_points = 0
        self.update_ui()

    def quit(self):
        self.__window.destroy()

def main():
    game = Dicegame()

main()


import torchvision.models as models
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
import model
import data_preparation
import numpy as np
import pickle
import os
import glob
import argparse
from datetime import datetime
import minerl
import matplotlib.pyplot as plt
import matplotlib.animation as animation

transform = torchvision.transforms.Compose([
    torchvision.transforms.ToTensor(),
    torchvision.transforms.Normalize(
        mean=[0.485, 0.456, 0.406],
        std=[0.229, 0.224, 0.225],
    ),
])

def iterate_episode(d):
    current_states ,actions ,_ ,next_states,_ = d

    assert len(current_states['pov']) == len(actions['camera'])

    num_frames = len(current_states['pov'])

    frames = []
    angles = []

    cur_angle = 0
    for i in range(num_frames):
        angles.append(cur_angle)
        frames.append(current_states['pov'][i])
        cur_angle -= actions['camera'][i][0]
        if cur_angle > 90:
            cur_angle = 90
        if cur_angle < -90:
            cur_angle = -90

    frames = np.asarray(frames)
    angles = np.asarray(angles, dtype=np.float32)

    return frames, angles

def get_data(EP_id):

    data = minerl.data.make('MineRLTreechop-v0', data_dir='../TestData/')
    trajectories = data.get_trajectory_names()

    d = data._load_data_pyfunc(os.path.join('../TestData/MineRLTreechop-v0', trajectories[EP_id]), -1, None)
    f, a = iterate_episode(d)

    return f, a

def predict_angles(net, frames):

    predict_angles = []
    for frame in frames:

        predicted_angle = net(torch.unsqueeze(transform(frame), axis=0)).detach().numpy()[0][0]
        predict_angles.append(predicted_angle)

    return predict_angles

def run1(c):
        l1.set_array(frames[c])

def visualize(frames, groundtruth, predictions):

    def run2(c, x, y1, y2, line):

        if c >= 10:
            if ((c+10) < len(x)):
                l2.set_data(x[(c-10):(c+10)], y1[(c-10):(c+10)])
                l2.axes.axis([x[c-10], x[c+10], -100, 100])

                l4.set_data(x[(c-10):(c+10)], y2[(c-10):(c+10)])
                l4.axes.axis([x[c-10], x[c+10], -100, 100])
            else:
                l2.set_data(x[(c-10):], y1[(c-10):])
                l2.axes.axis([x[c-10], x[-1], -100, 100])

                l4.set_data(x[(c-10):], y2[(c-10):])
                l4.axes.axis([x[c-10], x[-1], -100, 100])
        else:
            l2.set_data(x[:(c+10)], y1[0:(c+10)])
            l2.axes.axis([x[0], x[c+10], -100, 100])

            l4.set_data(x[:(c+10)], y2[0:(c+10)])
            l4.axes.axis([x[0], x[c+10], -100, 100])

        l5.set_xdata(c)
        asp = np.diff(l2.axes.get_xlim())[0] / np.diff(l2.axes.get_ylim())[0]
        l2.axes.set_aspect(asp)
        l1.set_array(frames[c])

        return l2, l1, l4, l5,

    x = [x for x in range(len(frames))]
    y1 = groundtruth
    y2 = predictions
    Writer = animation.writers['ffmpeg']
    writer = Writer(fps=30, metadata=dict(artist='Me'), bitrate=1800)

    fig = plt.figure()

    p1 = fig.add_subplot(121)
    p1.axis('off')

    p2 = fig.add_subplot(122)
    p2.grid()

    l1 = p1.imshow(frames[0])
    l2, = p2.plot(x, y1)
    l4, = p2.plot(x, y2)
    l5 = p2.axvline(0, c='black')

    p2.legend([l2, l4], ['Groundtruth', 'Model-Prediction'], bbox_to_anchor=(0,1.02), loc="lower left")

    ani2 = animation.FuncAnimation(fig, run2 ,interval=30, frames=len(frames), fargs=[x, y1, y2, l2],  blit=False)

    ani2.save('im.mp4', writer=writer)

    plt.show()

if __name__ == '__main__':

    device = torch.device('cpu')
    net = model.AnglePredictor()
    net.load_state_dict(torch.load('./batchsize=128_maxepochs=100/SavedModels/MostRecent100', map_location=device))

    test_frames, groundtruth = get_data(0)

    predictions = predict_angles(net, test_frames)

    visualize(test_frames, groundtruth, predictions)


import json
#import csv
import requests
from bs4 import BeautifulSoup

from query_parameters import Query

class HtmlRequest:
    """
    Create an HTML request (GET and POST) with user parsed info using USPTO API

    """

    #Base url and query categories
    BASE_URL = "http://www.patentsview.org/api/patents/query"
    RESULT_FIELDS = ['patent_number', 'patent_date', 'patent_title', 'patent_abstract']

    def __init__(self):
        self.query = Query()  #Import query parameter for parsing

    def getBuilder(self, comp_name, num_pat=10000, start_year="2007"):
        """Get corresponding json data from GET request

        Parameters
        ----------
        comp_name : str
            Company name to parse
        num_pat : int
            Number of patents to parse
        start_year : str
            Year to start parsing patents

        Returns
        -------
        data : json
            Data from USPTO API for corresponding query parameter

        """

        start_date = start_year + "-01-01"  #Create full year

        parameters = self.query.getParameter(comp_name, num_pat, start_date, self.RESULT_FIELDS)

        print("Processing GET request...")

        # Create GET request and convert to json
        r = requests.get(self.BASE_URL, params=parameters)
        data = r.json()

        print("Completed GET request")

        return data

    def postBuilder(self, comp_name, num_pat=10000, start_year="2007"):
        """Get corresponding json data from POST request

        Parameters
        ----------
        comp_name : str
            Company name to parse
        num_pat : int
            Number of patents to parse
        start_year : str
            Year to start parsing patents

        Returns
        -------
        data : json
            Data from USPTO API for corresponding query parameter

        """

        start_date = start_year + "-01-01"  #Create full year

        query_parameters = self.query.postParameters(comp_name, num_pat, start_date, self.RESULT_FIELDS)

        # Create json object using parameters
        q = json.dumps(query_parameters)

        print("Processing POST request...")

        # Create POST request and convert to json
        r = requests.post(self.BASE_URL, data=q)
        data = r.json()

        print("Completed POST request")

        return data


from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.kernel_ridge import KernelRidge
from sklearn.svm import SVR
import numpy as np
import matplotlib.pyplot as plt
from sklearn import preprocessing
import time

class Regression:

    def __init__(self, dataset):
        x = dataset.drop(['charges'], axis=1)
        y = dataset.charges
        self.x_train, self.x_test, self.y_train, self.y_test = train_test_split(x, y, random_state=0)

        # data normalization
        scalerX = preprocessing.MinMaxScaler()
        self.x_train = scalerX.fit_transform(self.x_train)
        self.x_test = scalerX.transform(self.x_test)

    def scatterPlot(self, y_test_pred, title):
        plt.title(title)
        plt.scatter(self.y_test, y_test_pred)
        tmp = [min(np.concatenate((self.y_test, y_test_pred))),
               max(np.concatenate((self.y_test, y_test_pred)))]
        plt.plot(tmp, tmp, 'r')
        plt.xlabel('Predicted Value')
        plt.ylabel('Actual Value')
        plt.show()

    def linearRegression(self):
        startTime = time.time()
        lr = LinearRegression().fit(self.x_train, self.y_train)
        y_test_pred = lr.predict(self.x_test)
        print("##### RESULTS FOR LINEAR REGRESSION #####")
        print('Accuracy (R^2): ' + str(lr.score(self.x_test, self.y_test)))
        err = np.mean(np.abs(self.y_test - y_test_pred))
        print("Model MAE: ", err)
        print("execution time: ", time.time() - startTime, "s")
        self.scatterPlot(y_test_pred, 'Linear Regression')

    def randomForest(self):
        startTime = time.time()
        rfr = RandomForestRegressor(n_estimators=100, max_features='auto')
        rfr.fit(self.x_train, self.y_train)
        y_test_pred = rfr.predict(self.x_test)
        print("##### RESULTS FOR RANDOM FOREST REGRESSION #####")
        print('Accuracy (R^2): ' + str(rfr.score(self.x_test, self.y_test)))
        err = np.mean(np.abs(self.y_test - y_test_pred))
        print("Model MAE: ", err)
        print("execution time: ", time.time() - startTime, "s")
        plt.figure(figsize=(8, 6))
        self.scatterPlot(y_test_pred, 'Random Forest')

    def supportVectorRegression(self):
        startTime = time.time()
        # parameters selection phase
        grid = {'C': np.logspace(-4, 3, 10), 'kernel': ['rbf'], 'gamma': np.logspace(-4, 3, 10), 'epsilon': [0, 0.1]}
        CV = GridSearchCV(estimator=SVR(), param_grid=grid, scoring='neg_mean_absolute_error', cv=10, verbose=0)
        H = CV.fit(self.x_train, self.y_train)

        svr = SVR(C=H.best_params_['C'], kernel='rbf', gamma=H.best_params_['gamma'], epsilon=H.best_params_['epsilon'])
        svr.fit(self.x_train, self.y_train)
        y_test_pred = svr.predict(self.x_test)
        print("##### RESULTS FOR SUPPORT VECTOR REGRESSION #####")
        print('Selected hyperparameters:')
        print("C = " + str(H.best_params_['C']) + ", gamma = " + str(H.best_params_['gamma']) +
              ", epsilon = " + str(H.best_params_['epsilon']))
        print('Accuracy (R^2) : ' + str(svr.score(self.x_test, self.y_test)))
        err = np.mean(np.abs(self.y_test - y_test_pred))
        print("Model MAE: ", err)
        print("execution time: ", time.time() - startTime, "s")
        self.scatterPlot(y_test_pred, 'SVR')

    def KRLS(self):
        startTime = time.time()
        # parameters selection phase
        grid = {'alpha': np.logspace(-4, 3, 10), 'kernel': ['rbf'], 'gamma': np.logspace(-4, 3, 10)}
        CV = GridSearchCV(estimator=KernelRidge(), param_grid=grid, scoring='neg_mean_absolute_error', cv=10, verbose=0)
        H = CV.fit(self.x_train, self.y_train)
        krls = KernelRidge(alpha=H.best_params_['alpha'], kernel='rbf', gamma=H.best_params_['gamma'])
        krls.fit(self.x_train, self.y_train)
        y_test_pred = krls.predict(self.x_test)
        print("##### RESULTS FOR KRLS #####")
        print('Selected hyperparameters: ')
        print("alpha = " + str(H.best_params_['alpha']) + ", gamma = " + str(H.best_params_['gamma']))
        print('Accuracy (R^2): ' + str(krls.score(self.x_test, self.y_test)))
        err = np.mean(np.abs(self.y_test - y_test_pred))
        print("Model MAE: ", err)
        print("execution time: ", time.time() - startTime, "s")
        self.scatterPlot(y_test_pred, 'KRLS')


#!/usr/bin/python3

""" Write a Python program to check whether a variable is an integer or string. """

def chckType(var):
    if isinstance(var,int):
        print(var, "is an integer")
    else:
        print(var, "is not an integer")

    if isinstance(var,str):
        print(var, "is a string")
    else:
        print(var, "is not a string")

    if not (isinstance(var,int) or isinstance(var,str)):
        print(var, "is nor a string or an integer")

if __name__ == "__main__":
    var1 = 12
    var2 = "12"
    var3 = [12]

    chckType(var1)
    chckType(var2)
    chckType(var3)


# coding:UTF-8
# フィボナッチ数列表示

# 表示回数
n = 10

#再帰
print("再帰で実現")
def fbnc(first, second, num):
    num -= 1
    print(second, end=" ")
    if num <= 0:
        return
    fbnc(second, (first + second), num)
fbnc(0, 1, n)

#ループ
print()
print("ループで実現")
start = 1
nextval = 0
for i in range(n):
    start, nextval = nextval, nextval + start
    print(nextval, end=" ")


class Game_Stats():
    """Tracks statistics for Alien Invasion."""
    def __init__(self, setting_obj):
        """Initialize statistics."""
        self.setting_obj = setting_obj
        self.reset_stats()
        # Start Alien Invasion in an active state.
        self.game_active = False
        # high score should never be reset
        self.high_score = 0

    def reset_stats(self):
        """Initialize statistics that can change during the game"""
        self.rockets_left = self.setting_obj.rocket_limit
        self.score = 0
        self.level = 1


### FUNCTION DEFINITIONS ###
def read_triple(file_path: str, entity2id: dict, relation2id: dict) -> list:
    """Reads triples and maps them to IDs.

    Args:
        file_path: str
            path to the file which contains the data to read
        entity2id: dict
            dictionary mapping an entity to its ID
        relation2id: dict
            dictionary mapping a relation to its ID
    Returns:
        triples: list[(int, int, int)]
            list of triples, representing each entity/relation by their IDs (head, relation, tail)
    """
    triples = []
    with open(file_path) as f:
        for line in f:
            h, r, t = line.strip().split("\t")
            triples.append((entity2id[h], relation2id[r], entity2id[t]))
    return triples

def load_entities(file_path: str) -> dict:
    """Loads the entities.

    Args:
        file_path: str
            path to the file which contains the data to read
    Returns:
        entity2id: dict
            dictionary mapping an entity to its ID
    """
    with open(file_path) as f:
        entity2id = {}
        for line in f:
            e_id, entity = line.strip().split("\t")
            entity2id[entity] = int(e_id)
    return entity2id

def load_relations(file_path: str) -> dict:
    """Loads the relations.

    Args:
        file_path: str
            path to the file which contains the data to read
    Returns:
        relation2id: dict
            dictionary mapping a relation to its ID
    """
    with open(file_path) as f:
        relation2id = {}
        for line in f:
            r_id, relation = line.strip().split("\t")
            relation2id[relation] = int(r_id)
    return relation2id

def separate_triples(triples):
    """Separates the triples in two lists.

    Given a list of triples (s, r, o), creates a list of tuples (s, r) and a list of o.

    Args:
        triples: List[(int, int, int)]
            triples to separate
    Returns:
        x: List[(int, int)]
            list of pairs of (source entity, relation)
        y: List[int]
            list of associated target entity
    """
    dict_source = {}
    for triple in triples:
        source = triple[0]
        relation = triple[1]
        target = triple[2]

        if source not in dict_source:
            dict_source[source] = {relation: [target]}
        else:
            if relation not in dict_source[source]:
                dict_source[source][relation] = [target]
            else:
                dict_source[source][relation].append(target)

    x = []
    y = []
    for i, triple in enumerate(triples):
        x.append((triple[0], triple[1]))
        y.append(dict_source[triple[0]][triple[1]])
    return x, y


from src.logger import logging
from src.exception import CustomException
from src.components.data_ingesion import DataInsgest
from src.utils import load_obj
import sys
import os
import pandas as pd
import numpy as np
from dataclasses import dataclass

from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline, Pipeline

@dataclass
class DataPipeConfig:
    data, matches, tables = DataInsgest().initiate_ingesion()
    preprocessor = os.path.join('artifacts', 'preprocessor.pkl')
    model = os.path.join('artifacts', 'model.pkl')

class DataTransformationPipe:
    def __init__(self):
        self.config = DataPipeConfig()

    def data_transform_pipe(self):
        num_cols = ['Runs_left', 'Balls_left', 'Wicket_left', 'Total_run', 'crr', 'rrr']
        cat_cols = ['Batting', 'Bowling', 'City']
        num_pipe = make_pipeline(
            SimpleImputer(strategy='median'),
            StandardScaler()
        )
        cat_pipe = make_pipeline(
            SimpleImputer(strategy='most_frequent'),
            OneHotEncoder()
        )
        transform_obj = ColumnTransformer([
            ('num_pipe', num_pipe, num_cols),
            ('cat_pipe', cat_pipe, cat_cols)
        ], remainder='passthrough')
        return transform_obj

    def predict_result(self, input_data):
        try:
            df = pd.DataFrame(input_data)
            preprocessor = load_obj(self.config.preprocessor)
            model = load_obj(self.config.model)
            test_array = preprocessor.transform(df)
            predicted = np.round(model.predict_proba(test_array)*100)
            return predicted
        except Exception as e:
            raise CustomException(e, sys)


import os
import tempfile
import shutil
import tarfile
import unittest
from unittest import mock

from gather_package_deps import GatherPackageDeps

class GatherPackageDepsTests(unittest.TestCase):

    source_dir = None
    package_json_path = None
    meta_far_path = None
    output_dir = None

    def setUp(self):
        self.source_dir = tempfile.TemporaryDirectory()
        self.output_dir = tempfile.TemporaryDirectory()

        self.package_json_path = os.path.join(self.source_dir.name, 'pkg.json')
        self.meta_far_path = os.path.join(self.source_dir.name, 'meta.far')

        # Create placeholder files.
        open(self.package_json_path, 'a').close()
        open(self.meta_far_path, 'a').close()

    def tearDown(self):
        self.source_dir.cleanup()
        self.output_dir.cleanup()

    def test_init(self):
        GatherPackageDeps(
            self.package_json_path, self.meta_far_path, self.output_dir.name)

        with self.assertRaises(ValueError):
            GatherPackageDeps('', self.meta_far_path, self.output_dir.name)
        with self.assertRaises(ValueError):
            GatherPackageDeps(None, self.meta_far_path, self.output_dir.name)

        with self.assertRaises(ValueError):
            GatherPackageDeps(self.package_json_path, '', self.output_dir.name)
        with self.assertRaises(ValueError):
            GatherPackageDeps(
                self.package_json_path, None, self.output_dir.name)

        with self.assertRaises(ValueError):
            GatherPackageDeps(self.package_json_path, self.meta_far_path, '')
        with self.assertRaises(ValueError):
            GatherPackageDeps(self.package_json_path, self.meta_far_path, None)

    def test_parse_package_json(self):

        gatherer = GatherPackageDeps(
            self.package_json_path, self.meta_far_path, self.output_dir.name)

        with open(self.package_json_path, 'w') as f:
            f.write('noooot JSOOOOON')
        with self.assertRaises(ValueError):
            gatherer.parse_package_json()

        with open(self.package_json_path, 'w') as f:
            f.write(r'{ }')
        with self.assertRaises(KeyError):
            gatherer.parse_package_json()

        with open(self.package_json_path, 'w') as f:
            f.write(r'{ "blobs": [] }')
        manifest_dict = gatherer.parse_package_json()
        self.assertDictEqual(manifest_dict, {})

        with open(self.package_json_path, 'w') as f:
            f.write(
                """{ "blobs":
                        [ { "source_path": "some/path/A", "path": "path/A" } ]
                   }
                """)
        manifest_dict = gatherer.parse_package_json()
        self.assertDictEqual(manifest_dict, {'path/A': 'some/path/A'})

        with open(self.package_json_path, 'w') as f:
            f.write(
                """{ "blobs":
                        [
                            { "source_path": "some/path/A", "path": "path/A" },
                            { "source_path": "some/path/B", "path": "path/B" }
                        ]
                    }
                """)
        manifest_dict = gatherer.parse_package_json()
        self.assertDictEqual(
            manifest_dict, {
                'path/A': 'some/path/A',
                'path/B': 'some/path/B'
            })

    @unittest.mock.patch.object(shutil, 'copyfile', autospec=True)
    def test_copy_meta_far(self, copyfile_mock):
        gatherer = GatherPackageDeps(
            self.package_json_path, self.meta_far_path, self.output_dir.name)
        gatherer.copy_meta_far()
        copyfile_mock.assert_called_once_with(
            self.meta_far_path, os.path.join(self.output_dir.name, 'meta.far'))

    @unittest.mock.patch.object(shutil, 'copyfile', autospec=True)
    @unittest.mock.patch.object(os, 'makedirs', autospec=True)
    def test_copy_to_output_dir(self, makedirs_mock, copyfile_mock):
        gatherer = GatherPackageDeps(
            self.package_json_path, self.meta_far_path, self.output_dir.name)
        test_dict = {
            'path/A': '../../../thing/A',
            'path/B': 'thing/B',
            'path/to/C': '/abs/path/C'
        }
        gatherer.copy_to_output_dir(test_dict)

        self.assertEqual(3, makedirs_mock.call_count)
        self.assertEqual(3, copyfile_mock.call_count)

        self.assertDictEqual(
            test_dict, {
                'path/A': 'thing/A',
                'path/B': 'thing/B',
                'path/to/C': 'abs/path/C'
            })

    def test_write_new_manifest(self):

        gatherer = GatherPackageDeps(
            self.package_json_path, self.meta_far_path, self.output_dir.name)

        gatherer.write_new_manifest(
            {
                'path/A': 'some/path/A',
                'path/B': 'some/path/B'
            })
        with open(os.path.join(self.output_dir.name, 'package.manifest'),
                  'r') as f:
            manifest_data = f.read()
            self.assertIn('path/A=some/path/A', manifest_data)
            self.assertIn('path/B=some/path/B', manifest_data)
            self.assertIn('meta/package=meta.far', manifest_data)

    def test_archive_output(self):
        tar_path = os.path.join(self.output_dir.name, 'package.tar')
        self.assertFalse(os.path.isfile(tar_path))
        gatherer = GatherPackageDeps(
            self.package_json_path, self.meta_far_path, self.output_dir.name)
        gatherer.archive_output()
        self.assertTrue(os.path.isfile(tar_path))

        file_a = os.path.join(self.output_dir.name, 'fileA')
        file_b = os.path.join(self.output_dir.name, 'sub', 'fileB')
        file_c = os.path.join(self.output_dir.name, 'another', 'dir', 'fileC')
        with open(file_a, 'w') as f:
            f.write('A')
        os.makedirs(os.path.dirname(file_b), exist_ok=False)
        with open(file_b, 'w') as f:
            f.write('BB')
        os.makedirs(os.path.dirname(file_c), exist_ok=False)
        with open(file_c, 'w') as f:
            f.write('CCC')

        gatherer.archive_output()
        self.assertTrue(os.path.isfile(tar_path))

        # Main thing we need to check here is that the paths within the archive
        # are relative instead of absolute, because absolute paths relative to the
        # system that created the archive are meaningless for anyone unarchiving.
        size_index = {'./fileA': 1, 'sub/fileB': 2, 'another/dir/fileC': 3}
        with tarfile.open(tar_path, 'r') as tar:
            for member in tar.getmembers():
                self.assertIn(member.name, size_index)
                self.assertEqual(member.size, size_index[member.name])

    def test_run(self):

        backup_cwd = os.getcwd()
        os.chdir(self.source_dir.name)

        file_meta = 'meta.far'
        file_a = 'fileA'
        file_b = os.path.join('sub', 'fileB')
        file_c = os.path.join('another', 'dir', 'fileC')
        open(file_meta, 'a').close()
        open(file_a, 'a').close()
        os.makedirs(os.path.dirname(file_b), exist_ok=False)
        open(file_b, 'a').close()
        os.makedirs(os.path.dirname(file_c), exist_ok=False)
        open(file_c, 'a').close()

        with open(self.package_json_path, 'w') as f:
            f.write(
                """{{ "blobs":
                        [
                            {{ "source_path": "{}", "path": "path/A" }},
                            {{ "source_path": "{}", "path": "path/B" }},
                            {{ "source_path": "{}", "path": "path/C" }}
                        ]
                    }}
                """.format(file_a, file_b, file_c))

        gatherer = GatherPackageDeps(
            self.package_json_path, self.meta_far_path, self.output_dir.name)
        gatherer.run()
        expected_files = {
            './package.manifest', './meta.far', './fileA', 'sub/fileB',
            'another/dir/fileC'
        }
        observed_files = set()
        expected_manifest_lines = {
            'path/A=fileA', 'path/B=sub/fileB', 'path/C=another/dir/fileC',
            'meta/package=meta.far'
        }
        observed_manifest_lines = set()
        with tarfile.open(os.path.join(self.output_dir.name, 'package.tar'),
                          'r') as tar:
            for member in tar.getmembers():
                observed_files.add(member.name)
                if member.name == './package.manifest':
                    for line in tar.extractfile(member).readlines():
                        observed_manifest_lines.add(
                            line.decode("utf-8").strip())
        self.assertEqual(observed_files, expected_files)
        self.assertEqual(observed_manifest_lines, expected_manifest_lines)

        os.chdir(backup_cwd)

if __name__ == '__main__':
    unittest.main()


#! /usr/bin/env python3

if(__name__ == "__main__"):
    list1 = input().split(' ')
    s1, s2 = list1[0], list1[2]
    key1, key2 = list1[1], list1[3]
    count1, count2 = 0, 0
    for i in s1:
        if i == key1:
            count1 = count1 + 1
    for i in s2:
        if i == key2:
            count2 = count2 + 1
    A = key1*count1
    B = key2*count2
    if A == '':
        A = '0'
    if B == '':
        B ='0'
    print("%d" %(int(A)+ int(B)))


#-*- coding:utf-8 -*-
import sys
# from importlib import reload            # python 3
reload(sys)
sys.setdefaultencoding('utf-8')       # python 3 doesn't need this

import cv2
import copy
import numpy as np
import math
import time
import argparse
import requests
import tensorflow as tf

# from crop_frames import CropFrames
from crop_frames_frontPerson import CropFrames
from TFModel import MultiscaleI3D, LSTM

from darknet.python.darknet import *

with open('categories.txt') as f:
    lines = map(lambda x: x.strip(), f.readlines())
ix2label = dict(zip(range(len(lines)), lines))

lines = ['<PAD>'] + lines
label2ix = dict(zip(lines, range(len(lines))))

def sampling_frames(input_frames, sampling_num):
    total_num = len(input_frames)

    interval = 1
    if len(input_frames) > sampling_num:
        interval = math.floor(float(total_num) / sampling_num)
    print("sampling interval : {}".format(interval))
    interval = int(interval)

    out_frames = []
    for n in range(min(len(input_frames), sampling_num)):
        out_frames.append(input_frames[n*interval])

    # padding
    if len(out_frames) < sampling_num:
        print("before padding : {}".format(len(out_frames)))
        for k in range(sampling_num - len(out_frames)):
            out_frames.append(input_frames[-1])

    return out_frames

def pred_action(frames):
    result, confidence, top_3 = action_model.run_demo_wrapper(np.expand_dims(frames, 0))

    if confidence > 0.7:
        if result not in ['stretching arm', 'brushing', 'reading', 'drinking', 'waving hands']:
            result = None

        return result, confidence, top_3

    else:
        result = None

    return result, confidence, top_3

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="test TF on a single video")
    parser.add_argument('--action_video_length', type=int, default=64)
    parser.add_argument('--action_thresh', type=int, default=2)
    parser.add_argument('--frame_thresh', type=int, default=20)
    parser.add_argument('--frame_diff_thresh', type=int, default=0.4)
    parser.add_argument('--waiting_time', type=int, default=8)

    parser.add_argument('--cam', type=int, default=0)  # 0~9 / 10: color / 11: ir1 / 12: ir2 / 13: ir1 + ir2
    parser.add_argument('--width', type=int,
                        default=640)  # RGB(YUY2): 1920x1080, 1280x720, 960x540, 848x480, 640x480, 640x360, 424x240, 320x240, 320x180
    parser.add_argument('--height', type=int,
                        default=480)  # DEPTH : 1280x720, 848x480, 640x480, 640x360, 480x270, 424x240
    parser.add_argument('--fps', type=int, default=10)  # 6, 15(1920~424), 30(1280~320), 60
    parser.add_argument('--name', type=str, default="user")

    parser.add_argument('--mtsi3d_weights', type=str, default="mtsi3d")
    parser.add_argument('--lstm_weights', type=str, default="lstm")

    args = parser.parse_args()

    log_dir = "./logs"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    log_file = os.path.join(log_dir, time.strftime("%Y-%m-%d"))
    with open(log_file, 'a') as f:
        f.write("---{}---\n".format(args.name))

    action_model = MultiscaleI3D(args.mtsi3d_weights)

    cap = cv2.VideoCapture(args.cam)

    cap.set(3, args.width)
    cap.set(4, args.height)
    cap.set(5, args.fps)

    frames = []
    result = None
    action_list = []

    yolo = load_net("./darknet/cfg/yolov3.cfg", "./darknet/cfg/yolov3.weights", 0)
    meta = load_meta("./darknet/cfg/coco.data")

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        # for streaming
        ret, jpeg = cv2.imencode('.jpg', frame)
        stream = jpeg.tobytes()

        requests.post("http://127.0.0.1:5001/update_stream", data=stream)

        frame = cv2.resize(frame, (224, 224))

        frames.append(frame)

        if len(frames) >= 64:
            sampled_frames = sampling_frames(frames, args.action_video_length)
            print('number of sampled frames : {}'.format(len(sampled_frames)))

            # crop all images
            cropped_frames = np.array(CropFrames(yolo, meta, sampled_frames))

            cv2.imwrite('tmp/img.jpg', cropped_frames[0])

            result, confidence, top_3 = pred_action(cropped_frames)
            # print("{}, {}, {}\n".format(result, confidence, top_3))

            if result == None:
                result = 'Waiting...'

            if not result == 'Waiting...':
                action_list.append(result)

                print("{}, {}, {}\n".format(result, confidence, top_3))

            requests.get('http://127.0.0.1:5001/state/set/action', params={'action': result})

            # initialization
            frames = []
            result = None

            if len(action_list) >= args.action_thresh:
                break

        if cv2.waitKey(1) & 0xFF == ord('q'):
            cap.release()
            cv2.destroyAllWindows()
            break

    cap.release()
    cv2.destroyAllWindows()

    """
    # get RNN result
    # input : action_list
    # output : predicted last action

    """
    tf.reset_default_graph()
    seq_model = LSTM(args.lstm_weights)

    next_action = ""

    if len(action_list) == 0:
        next_action = "NO ACTION DETECTED"

    else:
        actions_idx = [label2ix[a] for a in action_list]
        actions_idx = np.expand_dims(actions_idx, 0)

        next_action = seq_model.run_demo_wrapper(actions_idx)

        next_action = [ix2label[a-1] for a in next_action]
        next_action = next_action[0]

    print("\n*** results ***")
    print("Input actions: {}".format(action_list))
    print("Prediction: {}\n".format(next_action))

    with open(log_file, 'a') as f:
        f.write("{} | actions: {} | prediction: {}\n\n".format(time.strftime("%Y-%m-%d_%H-%M-%S"), action_list, next_action))


import numpy as np
import random
import pandas as pd

random.seed(1)
np.random.seed(1)

class Lieu:

    def __init__(self, x, y):
        self.x = float(x)
        self.y = float(y)

    @classmethod
    def distance(cls, lieu1, lieu2):
        return np.sqrt((lieu1.x-lieu2.x)**2 + (lieu1.y-lieu2.y)**2)

class Graph:

    def __init__(self, largeur, hauteur, array_lieux, nb_lieux=10):
        self.LARGEUR = largeur
        self.HAUTEUR = hauteur
        if np.any(array_lieux) :
            self.liste_lieux = self.creer_liste_lieux(array_lieux)
        else :
            self.liste_lieux = self.creer_liste_lieux_aleatoire(nb_lieux)
        self.NB_LIEUX = len(self.liste_lieux)
        self.matrice_od = self.calcul_matrice_cout_od()
        self.ordre_aleatoire = Route.def_ordre(self.NB_LIEUX)
        self.distance = Route.calcul_distance_route(self.ordre_aleatoire, self.matrice_od)

    def creer_liste_lieux(self, array):
        liste_lieux=[]
        for k in range(len(array)):
            liste_lieux.append(Lieu(array[k,0], array[k,1]))
        return liste_lieux

    def creer_liste_lieux_aleatoire(self,nb_lieux):
        self.liste_lieux=[]
        for i in range(nb_lieux):
            x = random.uniform(0, self.LARGEUR)
            y = random.uniform(0, self.HAUTEUR)
            point = Lieu(x,y)
            self.liste_lieux.append(point)
        return self.liste_lieux

    def calcul_matrice_cout_od(self):
        self.matrice_od = np.zeros((self.NB_LIEUX, self.NB_LIEUX))
        for i in range(self.NB_LIEUX):
            for j in range(self.NB_LIEUX):
                if i == j:
                    self.matrice_od[i,j] = np.inf
                if i != j:
                    self.matrice_od[i,j] = Lieu.distance(self.liste_lieux[i], self.liste_lieux[j])
        return self.matrice_od

    @classmethod
    def plus_proche_voisin(cls, lieu, matrice_od) :
        cls.le_plus_proche_voisin = np.argmin(matrice_od[lieu])
        return cls.le_plus_proche_voisin

    def sauvegarder_graph(self, path):
        self.df = pd.DataFrame([(lieu.x, lieu.y) for lieu in self.liste_lieux], columns =['x','y'])
        self.df.to_csv(path, index=False)

    @classmethod
    def charger_graph(cls, path):
        return pd.read_csv(path).values

class Route:

    @classmethod
    def def_ordre(cls, nb_lieux):
        cls.ordre = [0]
        tmp = list(range(1,nb_lieux))
        random.shuffle(tmp)
        cls.ordre.extend(tmp)
        cls.ordre.append(0)
        return cls.ordre

    @classmethod
    def calcul_distance_route(cls, ordre, matrice_od) :
        cls.distance = 0
        for i in range(len(ordre)-1):
            cls.distance += matrice_od[ordre[i],ordre[i+1]]
        return cls.distance


from django.shortcuts import render
from products.models import Products
from cart.models import Cart
from .models import Orders
from django.core import serializers
import datetime

def orderPage(request):
    orders, created = Orders.objects.get_or_create(customer=request.user)
    cartProducts = Cart.objects.get(customer=request.user).products.all()
    orders.products.set(cartProducts)
    orders.save()
    if orders.date_ordered == None:
        orders.date_ordered = datetime.datetime.now()
        orders.save()
    else:
        pass

    #delete cart products after buying
    cart = Cart.objects.get(customer=request.user)
    for product in cartProducts:
        cart.products.remove(product)
    return render(request,'orders/order.html',{"products":orders.products.all(),"order":orders})


import time
import traceback

from servicecatalog_puppet import serialisation_utils
from servicecatalog_puppet.serialisation_utils import unwrap
from servicecatalog_puppet.waluigi.constants import (
    BLOCKED,
    COMPLETED,
    CONTROL_EVENT__COMPLETE,
    ERRORED,
    IN_PROGRESS,
    NOT_SET,
    QUEUE_STATUS,
    RESOURCES_REQUIRED,
)
from servicecatalog_puppet.waluigi.dag_utils import logger
from servicecatalog_puppet.waluigi.locks.external import (
    are_resources_are_free_for_task_dict,
)
from servicecatalog_puppet.workflow.dependencies import task_factory

def has_dependencies_remaining(task_to_run, all_tasks):
    is_currently_blocked = False
    is_permanently_blocked = False
    for dependency in task_to_run.get("dependencies_by_reference"):
        if all_tasks.get(dependency):
            dependency_status = all_tasks[dependency].get(QUEUE_STATUS, NOT_SET)
            if dependency_status in [ERRORED, BLOCKED]:
                is_currently_blocked = is_permanently_blocked = True
                return is_currently_blocked, is_permanently_blocked
            else:
                if dependency_status != COMPLETED:
                    is_currently_blocked = True
                    return is_currently_blocked, is_permanently_blocked
    return is_currently_blocked, is_permanently_blocked

def get_next_task_to_run(tasks_to_run, resources, all_tasks):
    task_permanently_blocked_status = list()
    for task_reference_to_run in tasks_to_run:
        task_to_run = all_tasks[task_reference_to_run]
        status = task_to_run.get(QUEUE_STATUS, NOT_SET)
        # check if not running or has previously run
        if status == IN_PROGRESS:
            task_permanently_blocked_status.append(False)
        elif status == NOT_SET:
            is_currently_blocked, is_permanently_blocked = has_dependencies_remaining(
                task_to_run, all_tasks
            )
            if is_permanently_blocked:
                task_to_run[QUEUE_STATUS] = BLOCKED
                all_tasks[task_reference_to_run] = task_to_run
            task_permanently_blocked_status.append(is_permanently_blocked)
            if not is_currently_blocked:
                are_resources_are_free, _ = are_resources_are_free_for_task_dict(
                    task_to_run, resources
                )
                if are_resources_are_free:
                    return task_to_run, False
    return None, all(task_permanently_blocked_status)

def lock_next_task_to_run(next_task, resources, all_tasks):
    task_reference = next_task["task_reference"]
    next_task[QUEUE_STATUS] = IN_PROGRESS
    all_tasks[task_reference] = next_task
    for r in next_task.get(RESOURCES_REQUIRED, []):
        resources[r] = task_reference

def setup_next_task_to_run(lock, tasks_to_run, resources, all_tasks):
    with lock:
        next_task, can_shut_down = get_next_task_to_run(
            tasks_to_run, resources, all_tasks
        )
        if next_task is not None:
            lock_next_task_to_run(next_task, resources, all_tasks)
    return next_task, can_shut_down

def set_task_as_run(lock, next_task, all_tasks, resources, result):
    with lock:
        for r in next_task.get(RESOURCES_REQUIRED, []):
            try:
                del resources[r]
            except KeyError:
                logger.warn(
                    f"{next_task.get('task_reference')} tried to unlock {r} but it wasn't present"
                )
        next_task[QUEUE_STATUS] = result
        all_tasks[next_task["task_reference"]] = next_task

def worker_task(
    thread_name,
    lock,
    task_queue,
    results_queue,
    task_processing_time_queue,
    task_trace_queue,
    control_queue,
    control_event,
    manifest_files_path,
    manifest_task_reference_file_path,
    puppet_account_id,
    resources_file_path,
    all_tasks,
    resources,
    tasks_to_run,
):
    logger.info(f"starting up")
    should_run = True

    while should_run:
        next_task = None
        while next_task is None:
            next_task, can_shut_down = setup_next_task_to_run(
                lock, tasks_to_run, resources, all_tasks
            )
            if can_shut_down:
                if control_queue:
                    control_queue.put(CONTROL_EVENT__COMPLETE)
                if control_event:
                    control_event.set()
                return
            time.sleep(1)

        task_reference = next_task["task_reference"]
        task = task_factory.create(
            manifest_files_path=manifest_files_path,
            manifest_task_reference_file_path=manifest_task_reference_file_path,
            puppet_account_id=puppet_account_id,
            parameters_to_use=next_task,
        )
        logger.info(f"executing task: {task_reference}")
        task.on_task_start()
        start = time.time()
        task_type, task_details = task.get_processing_time_details()
        task_trace_queue.put((start, task_type, task_details, True, thread_name),)
        try:
            task.execute()
        except Exception as e:
            end = time.time()
            duration = end - start
            result = ERRORED
            logger.error(f"executed task [failure]: {task_reference} failures: {e}")
            try:
                logger.error(f"---- START OF ERROR----")
                logger.error(f"Task {task_type}:")
                for l in serialisation_utils.dump(unwrap(task_details)).split("\n"):
                    logger.error(l)
                for l in traceback.format_exception(
                    etype=type(e), value=e, tb=e.__traceback__,
                ):
                    for sl in l.split("\n"):
                        logger.error(f"{sl}")
                logger.error(f"---- END OF ERROR ----")
            except Exception as e2:
                logger.error(f"Exception raised: {e2}  whilst logging exection: {e}")
            task.on_task_failure(e, duration)
        else:
            end = time.time()
            duration = end - start
            result = COMPLETED
            logger.info(f"executed task [{result}]: {task_reference}")
            task.on_task_success(duration)

        task_processing_time_queue.put((duration, task_type, task_details,),)
        task_trace_queue.put((end, task_type, task_details, False, thread_name),)

        # print(f"{pid} Worker {task_reference} waiting for lock to unlock resources", flush=True)
        logger.info(f"executed task [success]: {task_reference}")
        set_task_as_run(lock, next_task, all_tasks, resources, result)
        time.sleep(0.01)

    logger.info(f"shutting down")


# 设计RandomPool结构
# 题目 设计一种结构,在该结构中有如下三个功能：
# insert(key):将某个key加入到该结构,做到不重复加入
# delete(key):将原来在结构中的某个key移除。
# getRandom():等概率随机返回结构中的任何一个key
# 要求：Inset,delete和getRandom方法的时间复杂度都是O(1)
import random
class RandomPool:
    def __init__(self):
        self.inputDic={}
        self.outDic={}
        self.size=0
    def insert(self,key):
        if key not in self.inputDic:
            self.inputDic[key]=self.size
            self.outDic[self.size]=key
            self.size+=1
    def delelte(self,key):
        if key not in self.inputDic.keys():
            print("error")
            return
        num=self.inputDic[key]
        self.size-=1
        if self.size==0 or self.inputDic[key]==self.size:
            del self.inputDic[key]
            del self.outDic[num]

        else:
            del self.inputDic[key]
            tmp=self.outDic[self.size]
            self.inputDic[tmp]=num
            del self.outDic[self.size]
            self.outDic[num]=tmp
    def getRandom(self):
        if not self.size:return None
        num=int(random.random()*self.size)
        return self.outDic[num]
if __name__=="__main__":
    test=RandomPool()
    test.insert('a')
    test.insert('b')
    test.insert('a')
    test.insert('c')
    print(test.inputDic)
    print(test.delelte('d'))
    print(test.inputDic)
    print(test.getRandom())