import sys,time,os,random

def colors(col):
    if col.lower().strip() == 'red':
        return '\033[31m'
    elif col.lower().strip() == 'green':
        return '\033[32m'
    elif col.lower().strip() == 'yellow':
        return '\033[33m'
    elif col.lower().strip() == 'blue':
        return '\033[34m'
    elif col.lower().strip() == 'magenta':
        return '\033[35m'
    elif col.lower().strip() == 'cyan':
        return '\033[36m'
    elif col.lower().strip() == 'white':
        return '\033[37m'
    else:
        return '\033[0m'

counter = 0

def title_checker():
    w = open('my.ideas.txt','a+')
    r =  open('my.ideas.txt','r')
    lines = r.readlines()
    try:
        if lines[0] != 'Your ideas!\n':
            lines[0] = 'Your ideas!\n\n'
            r.close()
            r = open('my.ideas.txt','w')
            r.writelines(lines)
            r.close()
            w.close()
        else:
            r.close()
            w.close()
    except:
        counter = 0
        w.write('Your ideas!\n\n')
        w.close()

def rand_col():
    colors_list = ['red','green','yellow','blue','magenta','cyan','white']
    num = random.randint(0,len(colors_list)-1)
    return colors(colors_list[num])

def string_printer(str):
    for i in str:
        print(rand_col(),i,end='',sep = '')
        sys.stdout.flush()
        time.sleep(0.1)

def space(pos):
  space_ = ''
  print(f"{space_:{pos}}", end='')

def adder():
    ideas = []
    # global counter
    os.system('cls')
    r = open('my.ideas.txt','r')
    lines = r.readlines()
    for i in range(len(lines)):
        lines[i] = lines[i].strip()
        lines[i] = lines[i][3:]

    ideas = lines[2:]
    r.close()

    while True:
        print(colors('yellow'),end='')
        idea = input('Input your random idea> ')
        # counter+=1
        idea_ = idea.title().strip()
        if idea_ in ideas:
            print()
            print(colors('red'),'Looks like you already added this! Please try again',colors('yellow'),sep='')
            print()
            continue
        else:
            ideas.append(idea_)
            break

    w = open('my.ideas.txt','a')
    string = f"{len(ideas)}- {idea_}"
    w.write(f"{string}\n")
    w.close()

    os.system('cls')
    print('Adding')
    cc = 10
    while True:
        string_printer('...')
        print()
        sys.stdout.write("\033[F")
        if cc == 0:
            break
        else:
            cc -= 1

    os.system('cls')
    print(colors('green'),'Successfully added!',colors('yellow'))
    print()

    while True:
        user__ = input('Add more or return to menu(a/m)> ')
        if user__.lower().strip() == 'a':
            adder()
        elif user__.lower().strip() == 'm':
            global main
            main()
        else:
            print()
            print(colors('red'),'Error, Please try again!',colors('yellow'))
            print()
            continue

def random_generator():
    global main
    os.system('cls')
    r = open('my.ideas.txt','r')
    lines = r.readlines()
    ideas = lines[2:]
    for i in range(len(ideas)):
        ideas[i] = ideas[i].strip()
        ideas[i] = ideas[i][3:]
    r.close()

    if len(ideas) < 1:
        print('Looks like your list is empty!')
        print()
        print('Returning to main menu...')
        time.sleep(5)
        main()

    print('Generating!')
    cc = 5
    while True:
        string_printer('...')
        print()
        sys.stdout.write("\033[F")
        if cc == 0:
            break
        else:
            cc -= 1

    idea_chosen = random.randint(0,len(ideas)-1)
    os.system('cls')

    print(colors('green'),ideas[idea_chosen],colors('yellow'))
    print()

    while True:
        user__ = input('Generate again or return to menu(r/m)> ')
        if user__.lower().strip() == 'r':
            random_generator()
        elif user__.lower().strip() == 'm':

            main()
        else:
            print()
            print(colors('red'),'Error, Please try again!',colors('yellow'))
            print()
            continue

def previewer():
    os.system('cls')
    r = open('my.ideas.txt','r')
    lines = r.readlines()
    ideas = lines[2:]
    r.close()
    for i in range(len(ideas)):
        ideas[i] = ideas[i].strip()

    for i in ideas:
        print(i,'\n')

    while True:
        user__ = input('Return to menu(m)> ')
        if user__.lower().strip() == 'm':
            global main
            main()
        else:
            print()
            print(colors('red'),'Error, Please try again!',colors('yellow'))
            print()

def idea_clearer():
    os.system('cls')
    f = open("my.ideas.txt","w")
    f.close()
    print(colors('green'),'Cleared successfully 💣',colors('yellow'))
    print()
    while True:
        user__ = input('Return to menu(m)> ')
        if user__.lower().strip() == 'm':
            global main
            main()
        else:
            print()
            print(colors('red'),'Error, Please try again!',colors('yellow'))
            print()

def main():
    title_checker()
    os.system('cls')
    print('\033[?25l',end='')
    string_printer('⭐Idea Storage⭐')
    print()
    print()
    space('>25')
    print(colors('yellow'),'Options')
    print()
    print()
    time.sleep(0.5)
    print(colors('blue'),'a - Add an idea!',end='')
    sys.stdout.flush()
    time.sleep(0.5)
    print(colors('green'),"                        r - See a random idea!")
    print()
    time.sleep(0.5)
    print(colors('cyan'),'p - Preview your ideas!',end='')
    sys.stdout.flush()
    time.sleep(0.5)
    print(colors('magenta'),"                        c - Clear list!")
    print()
    print()
    time.sleep(0.5)
    while True:
        print(colors('yellow'),end='')
        user = input('a/r/p/c> ')
        if user.lower().strip() == 'a':
            adder()
        elif user.lower().strip() == 'r':
            random_generator()
        elif user.lower().strip() == 'p':
            previewer()
        elif user.lower().strip() == 'c':
            idea_clearer()
        else:
            print()
            print(colors('red'),'Error! Please try again',colors('yellow'))
            print()
            continue

main()


import prompt

def run_game(greeting, get_round_data):
    name = prompt.string('May I have your name? ')
    print(f'Hello, {name}!')
    print(greeting)

    max_runds = 3
    correct_answers = 0

    while correct_answers < max_runds:
        question, answer = get_round_data()
        print(f'Question: {question}')
        user_answer = prompt.string('Your answer: ')

        if user_answer == answer:
            print('Correct!')
            correct_answers += 1
        else:
            # linter: line too long (88 > 80 characters)
            path1 = f"'{user_answer}' is wrong answer ;(."
            path2 = f"Correct answer was '{answer}'."
            print(path1, path2)
            print(f"Let's try again, {name}!")
            return

    print(f"Congratulations, {name}!")


# Based on https://gist.github.com/ageitgey/1c1cb1c60ace321868f7410d48c228e1

import dlib
import cv2
import logging
import os

from .util import get_basename, mkdir_if_not_exists
from skimage import io

logger = logging.getLogger(__name__)

class Detect:
    def __init__(self):
        self.detector = dlib.get_frontal_face_detector()

    def _get_faces(self, image):
        logging.debug(f"Getting faces for {image}")
        img = io.imread(image)
        faces = self.detector(img)

        if len(faces) == 0:
            logging.debug(f"No faces in {image}")

        return faces

    def count(self, image):
        faces = self._get_faces(image)
        return len(faces)

    def crop(self, image, outpath):
        logging.debug(f"Cropping {image} to {outpath}")
        mkdir_if_not_exists(outpath)
        rects = self.locate(image)
        img = cv2.imread(image, cv2.IMREAD_COLOR)
        basename = get_basename(image)

        for index, rect in enumerate(rects):
            outfile = f"{outpath}/{basename}-{index}.jpg"
            x, y, x2, y2 = rect
            crop = img[y:y2, x:x2]
            cv2.imwrite(outfile, crop)
            logging.debug(f"Cropped to {outfile}")

    def locate(self, image, output = None, to_directory = None):
        faces = self._get_faces(image)
        rects = []

        if to_directory:
            mkdir_if_not_exists(output)

        logging.debug(f"Getting rects")

        for index, rect in enumerate(faces):
            rects.append([
                rect.left(),
                rect.top(),
                rect.right(),
                rect.bottom()
            ])

        if output:
            logging.debug(f"Writing bounding boxes to {output}")

            out = cv2.imread(str(image), cv2.IMREAD_COLOR)

            for rect in rects:
                logging.debug(f"Plotting rect: {rect}")
                x, y, x2, y2 = rect
                p1 = (x, y)
                p2 = (x2, y2)
                c = (255, 0, 0)
                logging.debug(f"{p1}, {p2}")
                cv2.rectangle(out, p1, p2, c, 5)

            # If output is a directory, generate a name based on the
            # input filename
            if to_directory:
                outpath = f"{output}/{get_basename(image)}-crop.jpg"
            else:
                outpath = output

            logging.debug(f"Writing to {outpath}")

            cv2.imwrite(outpath, out)

        return rects


import pytest
import torch

from mmdet3d.models.builder import build_neck

def test_imvoxel_neck():
    if not torch.cuda.is_available():
        pytest.skip('test requires GPU and torch+cuda')

    neck_cfg = dict(
        type='OutdoorImVoxelNeck', in_channels=64, out_channels=256)
    neck = build_neck(neck_cfg).cuda()
    inputs = torch.rand([1, 64, 216, 248, 12], device='cuda')
    outputs = neck(inputs)
    assert outputs[0].shape == (1, 256, 248, 216)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 28 02:20:21 2019

@author: ansh
"""
import re
import string
import requests
import pickle
import xgboost as xgb
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

from bs4 import BeautifulSoup
from bs4.element import Comment

import spacy
import stanfordnlp

stop = set(stopwords.words('english'))
exclude = set(string.punctuation)

# Cleaning the text sentences so that punctuation marks, stop words & digits are removed
def clean_text(doc, lower=False, url_token='URL', fin_fig_token='MONEY', keep_date=True):

    if lower: doc = doc.lower()
    #remove email like tokens
    email_removed = ' '.join([item for item in doc.split() if '@' not in item])
    #remove urls
    url_removed = re.sub(r"http[s]?:\/{2}[^\s]*", 'URL', email_removed)
    url_removed = re.sub(r"\w*www.\w*.\w*", 'URL', url_removed)
    # remove financial figures
    fin_fig_removed = re.sub(r"\$\d+[.,]?\d*", 'MONEY', url_removed)

    # remove document source name
    source_removed = fin_fig_removed.replace('Share this article', ' ')
    source_removed = source_removed.replace('PRNewswire', '').replace('globe newswire', '')

    tokenized = word_tokenize(source_removed)
    # remove stop-words
    stop_free = " ".join([i for i in tokenized if i.lower() not in stop])
    # remove punctuations
    punc_free = stop_free.replace('-', ' ')
    punc_free = ''.join(ch for ch in punc_free if ch not in exclude)
    # remove months & years
#    date_removed = ' '.join([word for word in punc_free.split() if word.lower() not in months])
    date_removed = re.sub(r"\b(19|20)\d{2}\b", 'YEAR', punc_free)
    # lemmatize
#    normalized = ' '.join(lemma.lemmatize(word) for word in date_removed.split())
#    stemmed = ' '.join([stemmer(word) for word in date_removed.split()])

    # remove all remaining digits
    digits_removed = re.sub(r"\d+", ' ', date_removed)
    out = ' '.join([x for x in digits_removed.split()])

    return out

def get_doc_from_url(url):
    response = requests.get(url)
    if (response.status_code == 200):
        soup = BeautifulSoup(response.text, "html.parser")
        doc_text = soup.find_all(['p', 'tr']) # fixed code to extract text from tables as well.
        doc_text = ''.join([x.text for x in doc_text])
    cleaned_doc = clean_text(doc_text, lower=True)
    return cleaned_doc

def live_classify(url):

    tokenizer_handle = 'model/tokenizer.pickle'
    encoder_handle = 'model/encoder.pickle'
    model_handle = 'model/xgb_tr0.96_te0.87_tr0.95.model'

    doc = [get_doc_from_url(url)]
    with open(tokenizer_handle, 'rb') as handle:
        tokenizer = pickle.load(handle)
    with open(encoder_handle, 'rb') as handle:
        encoder = pickle.load(handle)

    x=tokenizer.texts_to_matrix(doc, mode='tfidf')
    d = xgb.DMatrix(data=x)

    bst = xgb.Booster({'nthread': 1})  # init model
    bst.load_model(model_handle)
    return (encoder.inverse_transform([int(bst.predict(d)[0])])[0])

def get_org_name(url):

    response = requests.get(url)
    if (response.status_code == 200):
        soup = BeautifulSoup(response.text, "html.parser")
        doc_text = soup.find_all(['p', 'tr']) # fixed code to extract text from tables as well.
        doc_text = ''.join([x.text for x in doc_text])
    doc = clean_text(doc_text, lower=False)

    nlp = spacy.load('en_core_web_sm')
    stf_nlp = stanfordnlp.Pipeline(processors='tokenize,mwt,pos')
    doc = doc[:250].split()
    doc =  ' '.join([x for x in doc if x.lower().find('newswire') == -1])

    orgs = set()
    spacy_doc = ' '.join(doc.split()).strip()
    nlp_doc = nlp(spacy_doc)
    for ent in nlp_doc.ents:
        if(ent.label_ == 'ORG'):
            orgs.add(ent.text)

    sf_doc = stf_nlp(doc)

    for sent in sf_doc.sentences:
        for word in sent.words:
            if(word.xpos=='NNP' and word.upos=='PROPN'):
                orgs.add(word.text)

    return ', '.join(list(orgs))


import csv
import json
import logging
from functools import partial
from itertools import combinations
from typing import Callable

import numpy as np
import pandas as pd

from lmentry.analysis.accuracy import get_accuracy_and_certainty
from lmentry.constants import (
    simple_answer_index_task_names, RESULTS_DIR, paper_models, get_short_model_name,
    PREDICTIONS_ROOT_DIR, TASKS_DATA_DIR
)
from lmentry.tasks.lmentry_tasks import core_tasks, all_tasks

logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%Y/%m/%d %H:%M:%S', level=logging.INFO)

argument_content_robustness_task_argument_subsets = {
    "first_alphabetically": [
        "far_first_letter",
        "different_first_letter",
        "consecutive_first_letter",
        "same_first_letter"
    ],
    "all_words_from_category": [
        "0_distractors",
        "1_distractors",
        "2_distractors"
    ],
    "any_words_from_category": [
        "5_distractors",
        "4_distractors",
        "3_distractors"
    ],
    "rhyming_word": [
        "orthographically_similar",
        "orthographically_different"
    ],
    "more_letters": [
        "length_diff_3plus",
        "length_diff_1"
    ],
    "less_letters": [
        "length_diff_3plus",
        "length_diff_1"
    ]
}

adjacent_tasks_by_definition_pairs = {
    ("bigger_number", "smaller_number"): "bigger/smaller_number",
    ("more_letters", "less_letters"): "more/less_letters",
    ("word_after", "word_before"): "word_after/before",
    ("most_associated_word", "least_associated_word"): "most/least_associated_word",
    ("any_words_from_category", "all_words_from_category"): "any/all_words_from_category"
}
adjacent_tasks_explicit_negation_pairs = {
    ("sentence_containing", "sentence_not_containing"): "sentence_(not)_containing",
    ("word_containing", "word_not_containing"): "word_(not)_containing"
}
adjacent_tasks_character_awareness_pairs = {
    ("starts_with_word", "starts_with_letter"): "starts_with_word/letter",
    ("ends_with_word", "ends_with_letter"): "ends_with_word/letter",
    ("sentence_containing", "word_containing"): "sentence/word_containing",
    ("sentence_not_containing", "word_not_containing"): "sentence/word_not_containing",
    ("first_word", "first_letter"): "first_word/letter",
    ("last_word", "last_letter"): "last_word/letter"
}
adjacent_tasks_by_first_vs_last_pairs = {
    ("starts_with_word", "ends_with_word"): "starts/ends_with_word",
    ("starts_with_letter", "ends_with_letter"): "starts/ends_with_letter",
    ("first_word", "last_word"): "first/last_word",
    ("first_letter", "last_letter"): "first/last_letter"
}
adjacent_tasks_tasks_pairs = {
    **adjacent_tasks_by_definition_pairs,
    **adjacent_tasks_explicit_negation_pairs,
    **adjacent_tasks_character_awareness_pairs,
    **adjacent_tasks_by_first_vs_last_pairs
}

def robustness_func(accs: list[float]):

    max_difference = 0
    for acc1, acc2 in combinations(accs, 2):
        diff = abs(acc1 - acc2)
        if diff > max_difference:
            max_difference = diff

    return 100 - max_difference

def get_simple_answer_index_bias(task_name: str, model_name: str) -> dict:

    # load scored predictions
    prediction_path = PREDICTIONS_ROOT_DIR.joinpath(task_name).joinpath(f"{model_name}.json")
    if not prediction_path.exists():
        logging.warning(f"No predictions exist in {prediction_path}")
        return dict()

    with open(prediction_path) as f_predictions:
        predictions = json.load(f_predictions)

    # load task data (for template_id and answer_index)
    task_data_path = TASKS_DATA_DIR.joinpath(f"{task_name}.json")
    with open(task_data_path) as f_task:
        task_data = json.load(f_task)
    examples = task_data["examples"]
    settings = task_data["settings"]

    # get per-template number of correct answers w.r.t answer index
    num_input_templates = len(settings["input_templates"])
    output = {f"template{i}": {"n_correct": 0,
                               "n_answer_index_0": 0,
                               "n_answer_index_1": 0,
                               "n_correct_answer_index_0": 0,
                               "n_correct_answer_index_1": 0,
                               }
              for i in range(num_input_templates)
              }
    for id_, prediction_entry in predictions.items():
        score = prediction_entry["score"]
        answer_index = examples[id_]["metadata"]["answer_index"]
        template_id = examples[id_]["metadata"]["template_id"]
        output[f"template{template_id}"][f"n_answer_index_{answer_index}"] += 1
        if score == 1:
            output[f"template{template_id}"][f"n_correct"] += 1
            output[f"template{template_id}"][f"n_correct_answer_index_{answer_index}"] += 1

    # calculate pre-template accuracy and accuracy w.r.t answer index
    num_examples_per_template = task_data["settings"]["num_examples_per_template"]
    for template in output:
        output[template]["accuracy"] = output[template]["n_correct"] / num_examples_per_template
        for answer_index in [0, 1]:
            n_answer_index = output[template][f"n_answer_index_{answer_index}"]
            n_correct_answer_index = output[template][f"n_correct_answer_index_{answer_index}"]
            output[template][f"accuracy_answer_index_{answer_index}"] = (
                0 if n_correct_answer_index == 0
                else n_correct_answer_index / n_answer_index
            )
        # round to one decimal digit
        for metric in ["accuracy", "accuracy_answer_index_0", "accuracy_answer_index_1"]:
            output[template][metric] = round(output[template][metric] * 100, 1)

    task_results = dict()
    # calculate overall (across all templates) counts
    for metric in ["n_correct", "n_answer_index_0", "n_answer_index_1",
                   "n_correct_answer_index_0", "n_correct_answer_index_1"]:
        task_results[metric] = sum([output[f"template{id_}"][metric]
                                    for id_ in range(num_input_templates)]
                                   )
    # calculate overall (across all templates) accuracy and accuracy w.r.t answer index
    n_task_examples = num_examples_per_template * num_input_templates
    task_results["accuracy"] = task_results["n_correct"] / n_task_examples
    for answer_index in [0, 1]:
        n_answer_index = task_results[f"n_answer_index_{answer_index}"]
        n_correct_answer_index = task_results[f"n_correct_answer_index_{answer_index}"]
        task_results[f"accuracy_answer_index_{answer_index}"] = (
            0 if n_correct_answer_index == 0
            else n_correct_answer_index / n_answer_index
        )
    # round to two decimal digits
    for metric in ["accuracy", "accuracy_answer_index_0", "accuracy_answer_index_1"]:
        task_results[metric] = round(task_results[metric] * 100, 2)

    output["task"] = task_results

    return output

def get_task_argument_order_robustness(task_name: str, model_name: str, func: Callable = robustness_func):

    answer_index_metrics = get_simple_answer_index_bias(task_name, model_name)
    accuracy_index_0 = answer_index_metrics["task"]["accuracy_answer_index_0"]
    accuracy_index_1 = answer_index_metrics["task"]["accuracy_answer_index_1"]

    robustness = func([accuracy_index_0, accuracy_index_1])

    return robustness

def get_argument_order_robustness(model_name: str, task_names: list[str] = None,
                                  func: Callable = robustness_func):

    task_names = task_names or simple_answer_index_task_names

    return np.mean([
        get_task_argument_order_robustness(task_name=task_name, model_name=model_name, func=func)
        for task_name in task_names
    ])

def get_argument_content_robustness(model_name: str, func: Callable = robustness_func,
                                    tasks_argument_subsets: dict[str, list[str]] = None):

    tasks_argument_subsets = tasks_argument_subsets or argument_content_robustness_task_argument_subsets

    argument_content_biases = []

    for task_name, argument_subset_names in tasks_argument_subsets.items():

        task_group_accuracies = []
        for argument_subset_name in argument_subset_names:
            metrics = get_accuracy_and_certainty(f"{task_name}_{argument_subset_name}", model_name)
            task_accuracy = metrics["task"]["accuracy"]
            task_group_accuracies.append(task_accuracy)

        argument_content_bias = func(task_group_accuracies)
        argument_content_biases.append(argument_content_bias)

    return np.mean(argument_content_biases)

def get_task_template_robustness(task_name: str, model_name: str, func: Callable = robustness_func):

    metrics = get_accuracy_and_certainty(task_name, model_name)
    accuracy_template_0 = metrics["template0"]["accuracy"]
    accuracy_template_1 = metrics["template1"]["accuracy"]
    accuracy_template_2 = metrics["template2"]["accuracy"]

    template_robustness = func([accuracy_template_0, accuracy_template_1, accuracy_template_2])

    return template_robustness

def get_template_robustness(model_name: str, func: Callable = robustness_func, task_names: list[str] = None):

    task_names = task_names or list(core_tasks)

    template_robustness_per_task = []
    for task_name in task_names:
        task_template_robustness = get_task_template_robustness(task_name, model_name, func=func)
        template_robustness_per_task.append(task_template_robustness)

    return np.mean(template_robustness_per_task)

def get_adjacent_tasks_pair_robustness(task_pair: tuple[str, str], model_name: str,
                                       func: Callable = robustness_func):
    task_pair_accuracies = []
    for task_name in task_pair:
        metrics = get_accuracy_and_certainty(task_name, model_name)
        task_accuracy = metrics["task"]["accuracy"]
        task_pair_accuracies.append(task_accuracy)

    robustness = func(task_pair_accuracies)

    return robustness

def get_adjacent_tasks_robustness(model_name: str, func: Callable = robustness_func,
                                  task_pairs: dict[tuple[str, str], str] = None):

    task_pairs = task_pairs or adjacent_tasks_tasks_pairs

    return np.mean([
        get_adjacent_tasks_pair_robustness(task_pair=task_pair, model_name=model_name, func=func)
        for task_pair in task_pairs
    ])

main_metric_name_to_metric = {
    "argument_order": get_argument_order_robustness,
    "argument_content": get_argument_content_robustness,
    "template": get_template_robustness,
    "adjacent_tasks": get_adjacent_tasks_robustness
}

adjacent_tasks_type_metric_name_to_metric = {
    "adjacent_by_definition":
        partial(get_adjacent_tasks_robustness, task_pairs=adjacent_tasks_by_definition_pairs),
    "adjacent_by_explicit_negation":
        partial(get_adjacent_tasks_robustness, task_pairs=adjacent_tasks_explicit_negation_pairs),
    "adjacent_by_character_awareness":
        partial(get_adjacent_tasks_robustness, task_pairs=adjacent_tasks_character_awareness_pairs),
    "adjacent_by_first_vs_last":
        partial(get_adjacent_tasks_robustness, task_pairs=adjacent_tasks_by_first_vs_last_pairs)
}

metric_name_to_metric = main_metric_name_to_metric | adjacent_tasks_type_metric_name_to_metric

def get_model_robustness(model_name, func: Callable = robustness_func):

    metrics = main_metric_name_to_metric.values()

    return np.mean(
        [metric(model_name=model_name, func=func) for metric in metrics]
    ).round(1)

def create_argument_order_robustness_csv(model_names: list[str] = None,
                                         task_names: list[str] = None,
                                         output_path=None
                                         ):
    model_names = model_names or list(paper_models)
    task_names = task_names or simple_answer_index_task_names

    rows: list[list] = list()
    first_row = [""]
    for task_name in task_names:
        first_row.extend([task_name] * 2)  # replicating the model name for easy conversion to a multiindex df
    rows.append(first_row)

    second_row = [""]
    second_row.extend(["acc ans is w1", "acc when ans is w2"] * len(task_names))
    rows.append(second_row)

    # the rest of the rows are the results
    for model_name in model_names:
        row = [model_name]
        for task_name in task_names:
            answer_index_metrics = get_simple_answer_index_bias(task_name, model_name)
            accuracy_index_0 = answer_index_metrics["task"]["accuracy_answer_index_0"]
            row.append(round(accuracy_index_0, 1))
            accuracy_index_1 = answer_index_metrics["task"]["accuracy_answer_index_1"]
            row.append(round(accuracy_index_1, 1))

        rows.append(row)

    output_path = output_path or RESULTS_DIR.joinpath("argument_order_robustness.csv")

    with open(output_path, "w", newline="") as f_output:
        writer = csv.writer(f_output)
        writer.writerows(rows)

def create_template_robustness_csv(model_names: list[str] = None, task_names: list[str] = None,
                                   func: Callable = robustness_func, output_path=None):

    model_names = model_names or list(paper_models)
    task_names = task_names or list(core_tasks)

    rows: list[list] = list()

    first_row = [""] + [get_short_model_name(model_name) for model_name in model_names]  # shorten model names
    rows.append(first_row)

    # the rest of the rows are the results
    for task_name in task_names:
        row = list()
        row.append(task_name)

        for model_name in model_names:
            template_robustness = get_task_template_robustness(task_name, model_name, func=func)
            row.append(round(template_robustness, 1))

        rows.append(row)

    output_path = output_path or RESULTS_DIR.joinpath("template_robustness.csv")

    with open(output_path, "w", newline="") as f_output:
        writer = csv.writer(f_output)
        writer.writerows(rows)

def create_robustness_csv(model_names: list[str] = None, func: Callable = robustness_func,
                          include_mean=True, include_adjacent_tasks_breakdown=False,
                          output_path=None):

    model_names = model_names or list(paper_models)

    rows: list[list] = list()
    metric_names = list(main_metric_name_to_metric)
    if include_adjacent_tasks_breakdown:
        metric_names.extend(adjacent_tasks_type_metric_name_to_metric)

    first_row = [""] + metric_names
    rows.append(first_row)

    # the rest of the rows are the results
    for model_name in model_names:
        row = list()

        row.append(get_short_model_name(model_name))

        for metric_name in metric_names:
            metric = metric_name_to_metric[metric_name]
            robustness_value = metric(model_name=model_name, func=func)
            row.append(round(robustness_value, 1))

        rows.append(row)

    # create output path
    if include_adjacent_tasks_breakdown:
        filename = f"robustness_with_adjacent_tasks_breakdown.csv"
    else:
        filename = f"robustness.csv"
    output_path = output_path or RESULTS_DIR.joinpath(filename)

    with open(output_path, "w", newline="") as f_output:
        writer = csv.writer(f_output)
        writer.writerows(rows)

    if not include_mean:
        return

    # add a "mean" column as the first column
    df = pd.read_csv(output_path, header=0, index_col=0)
    main_metrics_df = df[list(main_metric_name_to_metric)]
    means_column = main_metrics_df.mean(axis="columns").round(1)
    df.insert(0, "mean", means_column)

    df.to_csv(output_path)

def homophones_accuracy_per_distractor_type(model_name="text-davinci-002"):
    task = core_tasks["homophones"]

    with open(task.default_data_path) as f_task_data:
        task_data = json.load(f_task_data)
    examples = task_data["examples"]

    predictions_path = task.predictions_dir.joinpath(f"{model_name}.json")
    with open(predictions_path) as f_predictions:
        predictions = json.load(f_predictions)

    results = {
        "easy_distractor_count": 0,
        "easy_distractor_score": 0,
        "semantic_distractor_count": 0,
        "semantic_distractor_score": 0
    }

    for id_ in predictions:

        type_ = examples[id_]["metadata"]["distractor_type"]
        results[f"{type_}_distractor_count"] += 1

        score = predictions[id_]["score"]
        results[f"{type_}_distractor_score"] += score

    print(f"easy count: {results['easy_distractor_count']}")
    print(f"easy acc: {results['easy_distractor_score'] / results['easy_distractor_count']}")
    print(f"semantic count: {results['semantic_distractor_count']}")
    print(f"semantic acc: {results['semantic_distractor_score'] / results['semantic_distractor_count']}")

def all_words_from_category_accuracy_per_num_distractors(subset_name="", model_name="text-davinci-002"):

    if subset_name:
        subset_name = f"_{subset_name}"

    task = all_tasks[f"all_words_from_category{subset_name}"]()

    with open(task.default_data_path) as f_task_data:
        task_data = json.load(f_task_data)
    examples = task_data["examples"]

    predictions_path = task.predictions_dir.joinpath(f"{model_name}.json")
    with open(predictions_path) as f_predictions:
        predictions = json.load(f_predictions)

    results = {
        "dist0_count": 0,
        "dist0_score": 0,
        "dist1_count": 0,
        "dist1_score": 0,
        "dist2_count": 0,
        "dist2_score": 0,
    }

    for id_ in predictions:

        n_dist = examples[id_]["metadata"]["num_distractors"]
        results[f"dist{n_dist}_count"] += 1

        score = predictions[id_]["score"]
        results[f"dist{n_dist}_score"] += score

    for i in [0, 1, 2]:
        print(f"dist{i} count: {results[f'dist{i}_count']}")
        print(f"dist{i} score: {results[f'dist{i}_score'] / (results[f'dist{i}_count'] or 0.0001)}")

def any_words_from_category_accuracy_per_num_distractors(model_name="text-davinci-002"):

    task = core_tasks[f"any_words_from_category"]()

    with open(task.default_data_path) as f_task_data:
        task_data = json.load(f_task_data)
    examples = task_data["examples"]

    predictions_path = task.predictions_dir.joinpath(f"{model_name}.json")
    with open(predictions_path) as f_predictions:
        predictions = json.load(f_predictions)

    results = {
        "dist4_count": 0,
        "dist4_score": 0,
        "dist5_count": 0,
        "dist5_score": 0,
    }

    for id_ in predictions:

        n_dist = examples[id_]["metadata"]["num_distractors"]
        results[f"dist{n_dist}_count"] += 1

        score = predictions[id_]["score"]
        results[f"dist{n_dist}_score"] += score

    for i in [4, 5]:
        print(f"dist{i} count: {results[f'dist{i}_count']}")
        print(f"dist{i} score: {results[f'dist{i}_score'] / (results[f'dist{i}_count'] or 0.0001)}")


def addBinary(a, b):
    # initialise a carry variable
    carry = 0

    # set up two pointers, both at the right hand side of the input strings
    i = len(a) - 1
    j = len(b) - 1

    # initialise a results variable
    result = ""

    # while there are digits left to be processed in a or b
    while i >= 0 or j >= 0:
        # initialise the sum to the value of carry. 0 to begin with
        sum = carry
        # take the char at element i and j of each input string, convert it to a number
        # if you've reached the left of the string (index is 0) then set a default value of
        # 0 as this won't affect the maths
        numA = int(a[i]) if i >= 0 else 0
        numB = int(b[j]) if j >= 0 else 0

        # sum up the two chars (carry has been added as sum was initialise to carry's value)
        sum += numA + numB

        # the new carry is sum floor divided by 2.
        # this will be 0 if sum is 0 or 1, but will be 1 if sum is 2
        carry = sum // 2
        # update sum to be sum % 2. this will be 0 if sum is 0, 1 if sum is 1
        # and 0 if sum is 2
        sum = sum % 2

        # convert the sum back to a str and concatenate it to the start of the result string
        result = str(sum) + result
        # decrement both pointers
        i -= 1
        j -= 1

    # once the while loop has exited, the carry variable may have a value of 1 still
    # so we need to concatenate it too. We only want to do this if it has a value though,
    # otherwise we may end up with an unnecessary leading 0
    if carry > 0:
        result = str(carry) + result

    return result


T = int(input())
for tc in range(T):
    K, N, M = map(int, input().split())  # 이동횟수, 종점, 충전기
    number = list(map(int, input().split()))
    now = 0
    cnt = 0
    back = False
    while now + K < N:
        if back == True:
            break
        for i in range(K, 0, -1):
            if (now + i) not in number:  # 갔는데 충전소가 없으면
                if i == 1:  # 이동거리가 1인데도 충전소가 없으면
                    back = True  # 끝내는 변수에 True할당
                    break
                continue  # 돌아가서 K를 1 줄여라
            else:   # 충전소가 있으면 아래 시행하고 다시 while
                cnt += 1
                now += i
                break
    if back == True:
        print(f'#{tc+1} 0')
    else:
        print(f'#{tc+1} {cnt}')


from django.shortcuts import render
from course.models import Course, Subscription, WordDetails

# Create your views here.
def home_page_view(request):
    context = {}
    user = request.user
    if user.is_authenticated:
        subscribed_courses = Subscription.objects.filter(user=user)
        words = WordDetails.objects.all().filter(user=user, is_learnt=True)
        number_words_learned = len(words)
        context['subscriptions'] = subscribed_courses
        context['profile'] = user
        context['words_learned'] = number_words_learned
        return render(request, "dashboard.html", context)
    else:
        return render(request, "home_page.html")

def register_view(request):
    return render(request, "account/register.html")


from parser import parse
import json
import sys
sys.path.insert(0, 'src/vendor')
import requests

url = 'https://www.geomar.de/service/wetter'

def handler(event, context):
    content = requests.get(url).text
    (label, ts, direction, speed) = parse(content)
    result = {
        'spot': label,
        'timestamp': ts,
        'direction': direction,
        'speed': speed
    }

    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(result, ensure_ascii=False)
    }


from tkinter import ttk
import json
import tkinter as tk
import os
import re

def find_file(known_path:str=None, name:str=None) -> (bool, str):
    """
    Function to find a file on the user's computer.
    :param known_path: the part of the path that is constant or known by the user.
    :param name: the name (with the extension) of the file.
    :return: the path to the file or False if the file was not found.
    """
    if os.name == 'nt': # Windows OS
        # Gettings all possible drives on which the file may be found
        hdds = [f'{drive}:{os.path.sep}' for drive in 'CDEIJKRSTVWXY' if os.path.exists(f'{drive}:{os.path.sep}')]

        for drive in hdds:
            this_path = f'{drive}{known_path}{os.path.sep}{name}'
            if os.path.exists(this_path):
                return this_path
        return False
    else: # Unix OS
        return False

def read_file(path:str=None) -> (dict, str):
    """
    Function to read a file.
    :param path: the full path to the file.
    :return: the content of the file.
    """
    if path == False:
        return None

    with open(path, 'r') as f:
        if path[-5:] == '.json':
            data = json.load(f)
        else:
            data = f.read()
    return data

# Get the LoL file where the options are saved
try:
    persisted_settings:dict = read_file(
        find_file(
            known_path=f'Riot Games{os.path.sep}League of Legends{os.path.sep}Config',
            name='PersistedSettings.json'
        )
    )
except:
    raise ValueError('Unable to locate the League of Legends Config folder.')
else:
    print('Successfuly loaded the League of Legends Config folder.')

# Keyboard layouts
keyboard_layout = {
    'azerty': {
        'keys': [
            ['esc'] + [f'F{i}' for i in range(1, 13)] + ['del'],
            [c for c in '²&é"\'(-èçà)='] + ['back'],
            ['tab'] + [c for c in 'AZERTYUIOP^$*'],
            ['capslk'] + [c for c in "QSDFGHJKLMù"] + ['enter'],
            ['lshift'] + [c for c in 'WXCVBN,;:!'] + ['rshift'],
            ['lctrl', 'super', 'lalt', 'space',
             'ralt', 'fn', 'menu', 'rctrl']
        ],
        'spans': {key: 2 for key in ('enter', 'lshift', 'rshift', 'back')}
    },
    "qwerty": {
        'keys': [
            ['esc'] + [f'F{i}' for i in range(1, 13)] + ['del'],
            [c for c in '`1234567890-='] + ['back'],
            ['tab'] + [c for c in 'QWERTYUIOP[]\\'],
            ['capslk'] + [c for c in "ASDFGHJKL;'"] + ['enter'],
            ['lshift'] + [c for c in 'ZXCVBNM,./'] + ['rshift'],
            ['lctrl', 'super', 'lalt', 'space',
             'ralt', 'fn', 'menu', 'rctrl']
        ],
        'spans': {key: 2 for key in ('enter', 'lshift', 'rshift')}
    }
}

# Color code
color_code = {
    'attack_move': 'gray',
    'back': 'aqua',
    'camera_select_ally': 'skyblue1',
    'camera_snap_self': 'lightsteelblue',
    'champion_spell': 'tomato',
    'default_color': 'lightgreen',
    'enemy_vision': 'chocolate3',
    'open_shop': 'orange',
    'show_character_menu': 'chartreuse2',
    'summoner_spell': 'yellow',
    'show_scoreboard': 'darkorchid1',
    'use_item': 'pink',
    'ward': 'gold'
}

##################################
# User Interface
##################################
class User_Interface(tk.Frame):
    def __init__(self, master:tk.Tk=None):
        super().__init__(master)
        self.size = (1010, 275 + ((len(color_code) + (len(color_code) % 2)) * 23))
        self.master = master
        self.master.title('League of Legends keyboard parameters UI')
        # self.master.iconbitmap(f'{os.path.sep.join(__file__.split(os.path.sep)[:-1])}{os.path.sep}league_of_help_icon.ico')
        self.master.overrideredirect(False)
        self.master.geometry(f'{self.size[0]}x{self.size[1]}')
        self.master.maxsize(width=self.size[0], height=self.size[1])
        self.master.minsize(width=self.size[0], height=self.size[1])
        self.master['bg'] = '#13181B'

        self.keyboard = 'qwerty'

        self.pack()
        self.load()

    def move_window(self, event):
        self.master.geometry(f'+{event.x_root}+{event.y_root}')

    def load(self, keyboard:str=None):
        self.create_menu_bar()
        self.display_keyboard(keyboard)
        self.display_colors()

    def display_colors(self) -> None:
        for index, color in enumerate(color_code):
            tk.Button(
                self, width=6, bg=color_code[color]
            ).grid(
                row=(len(keyboard_layout[self.keyboard]['keys']) + (index // 2) + 1),
                column=(index % 2) * (len(keyboard_layout[self.keyboard]['keys'][0]) // 2),
                ipadx=6, ipady=10
            )
            tk.Label(
                self, text=color.replace('_', ' '),
                width=6, anchor='w'
            ).grid(
                row=(len(keyboard_layout[self.keyboard]['keys']) + (index // 2) + 1),
                column=((index % 2) * (len(keyboard_layout[self.keyboard]['keys'][0]) // 2) + 1),
                ipadx=(19 * 2), ipady=10, columnspan=2
            )

    def create_menu_bar(self) -> None:
        # Create the title bar
        # title_bar = tk.Frame(self.master, bg='pink', relief='raised', bd=2)
        # close_button = tk.Button(title_bar, text='X', command=self.master.destroy)
        # title_bar.bind('<B1-Motion>', self.move_window)

        # Create the main menu
        menu_bar = tk.Menu(self.master)

        file_menu = tk.Menu(menu_bar, tearoff=0)
        file_menu.add_command(label='Save')
        file_menu.add_command(label='Save as...')
        file_menu.add_separator()
        file_menu.add_command(label='Exit', command=root.quit)

        edit_menu = tk.Menu(menu_bar, tearoff=0)

        assign_key_menu = tk.Menu(edit_menu, tearoff=0)
        assign_option_menus = [
            {
                'menu': tk.Menu(assign_key_menu, tearoff=0),
                'label': persisted_settings['files'][i][j][k]['name'],
                'cascade': [
                    persisted_settings['files'][i][j][k]['settings'][l]['name'][4:]
                    if persisted_settings['files'][i][j][k]['settings'][l]['name'][3] == 't'
                    else persisted_settings['files'][i][j][k]['settings'][l]['name'][3:]
                    for l in range(len(persisted_settings['files'][i][j][k]['settings']))
                ]
            } if 'Events' in persisted_settings['files'][i][j][k]['name'] else None
            for i in range(len(persisted_settings['files']))
            for j in persisted_settings['files'][i]
            for k in range(len([d for d in persisted_settings['files'][i][j] if isinstance(d, dict)]))
        ]
        for o in [p for p in assign_option_menus if p is not None]:
            assign_key_menu.add_cascade(label=o['label'], menu=o['menu'])
            for p in o['cascade']:
                o['menu'].add_command(label=p)

        edit_menu.add_cascade(label='Assign Key', menu=assign_key_menu)
        edit_menu.add_separator()
        edit_menu.add_command(label='Reset')

        option_menu = tk.Menu(menu_bar, tearoff=0)

        keyboards_menu = tk.Menu(option_menu, tearoff=0)
        for keyboard in keyboard_layout.keys():
            keyboards_menu.add_command(label=keyboard, command=lambda real_keyboard=keyboard: self.load(keyboard=real_keyboard))

        help_menu = tk.Menu(menu_bar, tearoff=0)
        help_menu.add_command(label='Welcome')
        help_menu.add_command(label='Documentation')
        help_menu.add_command(label='Release Notes')
        help_menu.add_separator()
        help_menu.add_command(label='About')

        # title_bar.pack(expand=1, fill='x')
        # close_button.pack(side='right')
        option_menu.add_cascade(label='Keyboard', menu=keyboards_menu)
        menu_bar.add_cascade(label='File', menu=file_menu)
        menu_bar.add_cascade(label='Edit', menu=edit_menu)
        menu_bar.add_cascade(label='Option', menu=option_menu)
        menu_bar.add_cascade(label='Help', menu=help_menu)
        self.master['menu'] = menu_bar

    def display_keyboard(self, keyboard_configuration:str=None) -> None:
        if keyboard_configuration == None or keyboard_configuration != self.keyboard:
            # Remove every widget
            for widget in self.winfo_children()[:len(color_code)]:
                widget.destroy()

            self.keyboard = keyboard_configuration if keyboard_configuration in keyboard_layout else 'qwerty'

            buttons_lines = [
                [tk.Button(self, text=letter, width=6, relief='groove', bg='#ddd') for letter in line]
                for line in keyboard_layout[self.keyboard]['keys']
            ]

            for i in range(len(buttons_lines)):
                bonus_index = 0
                for index, character_button in enumerate(buttons_lines[i]):
                    for section in persisted_settings['files'][1]['sections']:
                        for jndex, key in enumerate(section['settings']):
                            if any(e in key['value'].split(',') for e in (
                                f"[{character_button['text'].lower()}]",
                                f"[{character_button['text'][0].upper()}{character_button['text'][1:].lower()}]",
                                f"[{character_button['text']}]")
                            ):
                                setting_name = section['settings'][jndex]['name']

                                if setting_name in ('evtCameraSnap', 'evtSelectSelf'):
                                    character_button['bg'] = color_code['camera_snap_self']
                                elif 'evtCastAvatarSpell' in setting_name:
                                    character_button['bg'] = color_code['summoner_spell']
                                elif 'evtCastSpell' in setting_name:
                                    character_button['bg'] = color_code['champion_spell']
                                elif setting_name == 'evtOpenShop':
                                    character_button['bg'] = color_code['open_shop']
                                elif 'evtPlayerAttackMove' in setting_name:
                                    character_button['bg'] = color_code['attack_move']
                                elif setting_name == 'evtPlayerPingAreaIsWarded':
                                    character_button['bg'] = color_code['enemy_vision']
                                elif 'evtSelectAlly' in setting_name:
                                    character_button['bg'] = color_code['camera_select_ally']
                                elif setting_name == 'evtShowCharacterMenu':
                                    character_button['bg'] = color_code['show_character_menu']
                                elif any(f'evtUseItem{i}' == setting_name for i in range(7)):
                                    character_button['bg'] = color_code['use_item']
                                elif setting_name == 'evtUseItem7':
                                    character_button['bg'] = color_code['back']
                                elif setting_name == 'evtUseVisionItem':
                                    character_button['bg'] = color_code['ward']
                                elif 'Tab' in section['settings'][jndex]['value'] or setting_name == 'evtShowScoreBoard':
                                    character_button['bg'] = color_code['show_scoreboard']
                                else:
                                    character_button['bg'] = color_code['default_color']
                                break

                    # Grid button
                    if character_button['text'] in keyboard_layout[self.keyboard]['spans']:
                        character_button.grid(
                            row=i, column=index + bonus_index,
                            ipadx=int(19 * keyboard_layout[self.keyboard]['spans'][character_button['text']]),
                            ipady=10,
                            columnspan=keyboard_layout[self.keyboard]['spans'][character_button['text']]
                        )
                        bonus_index += keyboard_layout[self.keyboard]['spans'][character_button['text']] - 1
                    elif character_button['text'] == 'space':
                        character_button.grid(row=i, column=index + bonus_index, ipadx=200, ipady=10, columnspan=7)
                        bonus_index += 6
                    else:
                        character_button.grid(row=i, column=index + bonus_index, ipadx=6, ipady=10)

root = tk.Tk()
ui = User_Interface(master=root)
ui.mainloop()


import random  #import number
loop = "y"  #looping to guess over and over
while loop=="y":  #while looping
    number= random.randrange(500)+ 1 #random number is an integer
    guess = int(input("Guess a number between 1 and 500: "))  #integer converted to string
    number = 75    #correct guess is 75
    if guess > 75:      #if number is higher than 75
        print ("Too high, try again:")    #display too high, try again
        guess = int (input("Guess again: "))  #integer converted to string
        guess= random          #number must be equal to 75

    if guess < 75:    #if number is lower than 75
        print ("Too low, try again:")    #display too low, try again
        guess = (int(input("Guess again: ")))   #integer converted to string. User has to guess again
        guess= random        #number must be equal to 75

    if guess : 75   #if guess is equal to 75
    print ("You guessed the number!! ")    #output will say user guessed the correct number

    loop = "y"     #start again when game is over


import tensorflow as tf
import tensorflow_gan as tfgan

from tensorflow.keras import layers

# TF-GAN tutorial google collab, with some changes (small for now)

def input_fn(mode, params):

    assert 'batch_size' in params
    assert 'noise_dims' in params

    bs = params['batch_size']
    nd = params['noise_dims']

    folder = './data/train' if mode == tf.estimator.ModeKeys.TRAIN else './data/test'

    shuffle = (mode == tf.estimator.ModeKeys.TRAIN)

    just_noise = (mode == tf.estimator.ModeKeys.PREDICT)

    noise_ds = (tf.data.Dataset.from_tensors(0).repeat()
                .map(lambda _: tf.random.normal([bs, nd])))

    # Explain this
    if just_noise:
        return noise_ds

    def _preprocess(element):
        # Map [0, 255] to [-1, 1].
        images = (element - 127.5) / 127.5
        return images

    images_ds = tf.keras.preprocessing.image_dataset_from_directory(
        folder,
        seed=123,
        image_size=(256, 256),
        batch_size=bs,
        label_mode=None  # Eventually changed
    ).map(_preprocess).cache().repeat()

    if shuffle:
        images_ds = images_ds.shuffle(
            buffer_size=10000, reshuffle_each_iteration=True)

    images_ds = (images_ds.batch(bs, drop_remainder=True)
                 .prefetch(tf.data.experimental.AUTOTUNE))

    return tf.data.Dataset.zip((noise_ds, images_ds))

params = {'batch_size':100, 'noise_dims':100}

#TODO define what generated_inputs is, right now is it just the noise?
# may not even need to use the inputs, but have to take in constructor function args ?
def discriminator_fn(generated_image, generated_inputs):

    # Test dropout a bit

    model = tf.keras.Sequential()
    model.add(layers.Conv2D(16, (5, 5), strides=(2, 2),
              padding='same', input_shape=(256, 256, 3)))
    model.add(layers.BatchNormalization())
    model.add(layers.LeakyReLU(alpha=0.2))
    model.add(layers.Dropout(0.3))

    model.add(layers.Conv2D(32, (5, 5), strides=(2, 2), padding='same'))
    model.add(layers.BatchNormalization())
    model.add(layers.LeakyReLU(alpha=0.2))
    model.add(layers.Dropout(0.3))

    model.add(tf.keras.layers.Flatten())
    model.add(tf.keras.layers.Dense(1))

    return model

# noise parameter is from the TFGAN gan_model() constructor, default generator_inputs is just noise tensor?
def generator_fn(noise_tensor):

    # Have to figure out what exactly these parameters do and the best structure for the network, sort of messing around right now

    # Conv2DTranspose upsamples and performs a convolution, sort of like a "learned" upsample
    # A stride over 1 adds gaps to the input image, which does the upsampling
    # From a tutorial: "It is also good practice to use a kernel size that is a factor of the stride (e.g. double) to avoid a checkerboard pattern
    # that can sometimes be observed when upsampling.""

    # alpha at 0.2 best practice? more info

    # NOTE: I think this input shape is where each label has to have some influence
    model = tf.keras.Sequential()
    model.add(tf.keras.Input(tensor=noise_tensor))
    model.add(layers.Dense(16 * 32 * 32, activation='relu'))
    # Transformation that maintains the mean output close to 0 and SD close to 1
    model.add(layers.BatchNormalization())
    # Question whether to have this before or after activation function
    model.add(layers.ReLU())

    model.add(layers.Reshape((32, 32, 16)))
    print(model.output.shape)

    model.add(layers.Conv2DTranspose(8, (8, 8), strides=(2, 2),
              padding='same', use_bias=False))  # 32 64 x 64 filters
    print(model.output.shape)
    model.add(layers.BatchNormalization())
    model.add(layers.ReLU())

    # model.add(layers.Conv2DTranspose(16, (12, 12), strides=(2, 2),
      #        padding='same', use_bias=False))  # 16 128 * 128 filters
    #print(model.output.shape)
    #model.add(layers.BatchNormalization())
    #model.add(layers.ReLU())

    # Important note: probably want more than one filter here, next layer defines final image
    model.add(layers.Conv2DTranspose(4, (16, 16), strides=(4, 4),
              padding='same', use_bias=False))  # 8 256 * 256 filters
    print(model.output.shape)
    model.add(layers.BatchNormalization())
    model.add(layers.ReLU())

    # This output layer has 3 256 * 256 filters (rgb), tanh makes values between -1 and 1
    model.add(layers.Conv2D(3, (3, 3), activation='tanh', padding='same'))
    print(model.output.shape)

    return model

# Learning Rates
generator_lr = 0.001
discriminator_lr = 0.0002

# Assembles and manages the pieces of the whole GAN model
gan_estimator = tfgan.estimator.GANEstimator(
    generator_fn=generator_fn,
    discriminator_fn=discriminator_fn,
    generator_loss_fn=tfgan.losses.wasserstein_generator_loss,
    discriminator_loss_fn=tfgan.losses.wasserstein_discriminator_loss,
    params=params,
    # Tutoial passes a function here to change the learning rate after 100 steps, this is static
    generator_optimizer=tf.keras.optimizers.Adam(generator_lr),
    discriminator_optimizer=tf.keras.optimizers.Adam(discriminator_lr, 0.5),
)

gan_estimator.train(input_fn, max_steps=100)


import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
screen.listen()

scoreboard = Scoreboard()
turtle = Player()
manager = CarManager()
screen.onkey(fun=turtle.move_forward, key="Up")

game_is_on = True
while game_is_on:
    time.sleep(0.1)
    manager.generate_car()
    manager.move_cars()

    if manager.detect_collision(turtle):
        scoreboard.game_over()
        game_is_on = False

    if turtle.ycor() >= 280:
        scoreboard.level_up()
        manager.add_speed()
        turtle.reset_player()

    screen.update()

screen.exitonclick()


n, k = map(int, input().split())
count = 0

while(n != 1):
    if n<k:
        count += n+1
        break
    num =  n - (n//k * k)
    count += num
    k -= num

    n = n//k
    count +=1

print(count)


import difflib
import pprint

from cdpcli.arguments import BaseCLIArgument, CustomArgument
from cdpcli.clidriver import (
    CLICommand, CLIDriver, ServiceCommand, ServiceOperation)
from cdpcli.compat import OrderedDict
from cdpcli.completer import Completer
from cdpcli.help import ProviderHelpCommand
import mock
from tests import unittest

class BaseCompleterTest(unittest.TestCase):
    def setUp(self):
        self.clidriver_creator = MockCLIDriverFactory()

    def assert_completion(self, completer, cmdline, expected_results,
                          point=None):
        if point is None:
            point = len(cmdline)
        actual = set(completer.complete(cmdline, point))
        expected = set(expected_results)

        if not actual == expected:
            # Borrowed from assertDictEqual, though this doesn't
            # handle the case when unicode literals are used in one
            # dict but not in the other (and we want to consider them
            # as being equal).
            pretty_d1 = pprint.pformat(actual, width=1).splitlines()
            pretty_d2 = pprint.pformat(expected, width=1).splitlines()
            diff = ('\n' + '\n'.join(difflib.ndiff(pretty_d1, pretty_d2)))
            raise AssertionError("Results are not equal:\n%s" % diff)
        self.assertEqual(actual, expected)

class TestCompleter(BaseCompleterTest):
    def test_complete_services(self):
        commands = {
            'subcommands': {
                'foo': {},
                'bar': {
                    'subcommands': {
                        'baz': {}
                    }
                }
            },
            'arguments': []
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp ', ['foo', 'bar'])

    def test_complete_partial_service_name(self):
        commands = {
            'subcommands': {
                'cloudfront': {},
                'cloudformation': {},
                'cloudhsm': {},
                'sts': {}
            },
            'arguments': []
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp cloud', [
            'cloudfront', 'cloudformation', 'cloudhsm'])
        self.assert_completion(completer, 'cdp cloudf', [
            'cloudfront', 'cloudformation'])
        self.assert_completion(completer, 'cdp cloudfr', ['cloudfront'])
        self.assert_completion(completer, 'cdp cloudfront', [])

    def test_complete_on_invalid_service(self):
        commands = {
            'subcommands': {
                'foo': {},
                'bar': {
                    'subcommands': {
                        'baz': {}
                    }
                }
            },
            'arguments': []
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp bin', [])

    def test_complete_cli_enum_options(self):
        commands = {
            'subcommands': {},
            'arguments': ['version', 'output', 'color']
        }
        clidriver = self.clidriver_creator.create_clidriver(commands)
        clidriver._cli_data = {
            "options": {
                "version": {
                    "action": "version",
                    "help": "
Display the version of this tool.
"
                },
                "output": {
                    "choices": [
                        "json",
                        "text",
                        "table"
                    ],
                    "help": "
The formatting style for command output.
"
                },
                "color": {
                    "choices": [
                        "on",
                        "off",
                        "auto"
                    ],
                    "default": "auto",
                    "help": "
Turn on/off color output.
"
                }
            }
        }
        completer = Completer(clidriver)
        self.assert_completion(completer, 'cdp --output ', ['json', 'text', 'table'])
        self.assert_completion(completer, 'cdp --color ', ['on', 'off', 'auto'])

    def test_complete_top_level_args(self):
        commands = {
            'subcommands': {},
            'arguments': ['foo', 'bar']
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp --', ['--foo', '--bar'])

    def test_complete_partial_top_level_arg(self):
        commands = {
            'subcommands': {},
            'arguments': ['foo', 'bar', 'foobar', 'fubar']
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp --f', [
            '--foo', '--fubar', '--foobar'])
        self.assert_completion(completer, 'cdp --fo', [
            '--foo', '--foobar'])
        self.assert_completion(completer, 'cdp --foob', ['--foobar'])
        self.assert_completion(completer, 'cdp --foobar', [])

    def test_complete_top_level_arg_with_arg_already_used(self):
        commands = {
            'subcommands': {
                'baz': {}
            },
            'arguments': ['foo', 'bar']
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp --foo --f', [])

    def test_complete_service_commands(self):
        commands = {
            'subcommands': {
                'foo': {
                    'subcommands': {
                        'bar': {
                            'arguments': ['bin']
                        },
                        'baz': {}
                    }
                }
            },
            'arguments': []
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp foo ', ['bar', 'baz'])

    def test_complete_partial_service_commands(self):
        commands = {
            'subcommands': {
                'foo': {
                    'subcommands': {
                        'barb': {
                            'arguments': ['nil']
                        },
                        'baz': {},
                        'biz': {},
                        'foobar': {}
                    }
                }
            },
            'arguments': []
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp foo b', ['barb', 'baz', 'biz'])
        self.assert_completion(completer, 'cdp foo ba', ['barb', 'baz'])
        self.assert_completion(completer, 'cdp foo bar', ['barb'])
        self.assert_completion(completer, 'cdp foo barb', [])

    def test_complete_service_arguments(self):
        commands = {
            'subcommands': {
                'foo': {}
            },
            'arguments': ['baz', 'bin']
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp foo --', ['--baz', '--bin'])

    def test_complete_partial_service_arguments(self):
        commands = {
            'subcommands': {
                'biz': {}
            },
            'arguments': ['foo', 'bar', 'foobar', 'fubar']
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp biz --f', [
            '--foo', '--fubar', '--foobar'])
        self.assert_completion(completer, 'cdp biz --fo', [
            '--foo', '--foobar'])
        self.assert_completion(completer, 'cdp biz --foob', ['--foobar'])

    def test_complete_service_arg_with_arg_already_used(self):
        commands = {
            'subcommands': {
                'baz': {}
            },
            'arguments': ['foo', 'bar']
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp baz --foo --f', [])

    def test_complete_operation_arguments(self):
        commands = {
            'subcommands': {
                'foo': {'subcommands': {
                    'bar': {'arguments': ['baz']}
                }}
            },
            'arguments': ['bin']
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp foo bar --', ['--baz', '--bin'])

    def test_complete_partial_operation_arguments(self):
        commands = {
            'subcommands': {
                'foo': {'subcommands': {
                    'bar': {'arguments': ['base', 'baz', 'air']}
                }}
            },
            'arguments': ['bin']
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp foo bar --b', [
            '--base', '--baz', '--bin'])
        self.assert_completion(completer, 'cdp foo bar --ba', [
            '--base', '--baz'])
        self.assert_completion(completer, 'cdp foo bar --bas', ['--base'])
        self.assert_completion(completer, 'cdp foo bar --base', [])

    def test_complete_operation_arg_when_arg_already_used(self):
        commands = {
            'subcommands': {
                'foo': {'subcommands': {
                    'bar': {'arguments': ['baz']}
                }}
            },
            'arguments': []
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp foo bar --baz --b', [])

    def test_complete_positional_argument(self):
        commands = {
            'subcommands': {
                'foo': {'subcommands': {
                    'bar': {'arguments': [
                        'baz',
                        CustomArgument('bin', positional_arg=True)
                    ]}
                }}
            },
            'arguments': []
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp foo bar --bin ', [])
        self.assert_completion(completer, 'cdp foo bar --bin blah --',
                               ['--baz'])

    def test_complete_undocumented_command(self):
        class UndocumentedCommand(CLICommand):
            _UNDOCUMENTED = True
        commands = {
            'subcommands': {
                'foo': {},
                'bar': UndocumentedCommand()
            },
            'arguments': []
        }
        completer = Completer(
            self.clidriver_creator.create_clidriver(commands))
        self.assert_completion(completer, 'cdp ', ['foo'])

class MockModel:
    is_hidden = False
    is_deprecated = False

class MockCLIDriverFactory(object):
    def create_clidriver(self, commands=None):
        clidriver = mock.Mock(spec=CLIDriver)
        clidriver._create_help_command.return_value = \
            self._create_top_level_help(clidriver, commands)

        return clidriver

    def _create_top_level_help(self, clidriver, commands):
        command_table = self.create_command_table(
            clidriver,
            commands.get('subcommands', {}), self._create_service_command)
        argument_table = self.create_argument_table(
            commands.get('arguments', []))
        return ProviderHelpCommand(
            command_table, argument_table, None, None, None)

    def _create_service_command(self, clidriver, name, command):
        command_table = self.create_command_table(
            clidriver,
            command.get('subcommands', {}), self._create_operation_command)
        service_command = ServiceCommand(clidriver, name)
        service_command._service_model = {}
        service_command._command_table = command_table
        return service_command

    def _create_operation_command(self, clidriver, name, command):
        argument_table = self.create_argument_table(
            command.get('arguments', []))
        operation = ServiceOperation(clidriver, name, 'parent', None, MockModel())
        operation._arg_table = argument_table
        return operation

    def create_command_table(self, clidriver, commands, command_creator):
        if not commands:
            return OrderedDict()
        command_table = OrderedDict()
        for name, command in commands.items():
            if isinstance(command, CLICommand):
                # Already a valid command, no need to fake one
                command_table[name] = command
            else:
                command_table[name] = command_creator(clidriver, name, command)
        return command_table

    def create_argument_table(self, arguments):
        if not arguments:
            return OrderedDict()
        argument_table = OrderedDict()
        for arg in arguments:
            if isinstance(arg, BaseCLIArgument):
                argument_table[arg.name] = arg
            else:
                argument_table[arg] = BaseCLIArgument(arg)
        return argument_table