import os
import requests
from asana.util import get_value_in_data_file
from furl import furl

try:
    ASANA_TOKEN = os.environ['ASANA_TOKEN']
except:
    raise KeyError("Please set ASANA_TOKEN as an environment variable.")

URL = 'https://app.asana.com/api/1.0'
HEADERS = {
    'Accept': 'application/json',
    'Authorization': f'Bearer {ASANA_TOKEN}'}

class AsanaAPI:

    def __init__(self):
        self.url = URL
        self.headers = HEADERS
        self.workspace = get_value_in_data_file('workspace', 'gid')
        self.assignee = get_value_in_data_file('user', 'gid')

    def get_user_info(self):
        """
        Gets the current user of Asana's API.
        return dict: eg: {'gid': str, 'email': [users email]. 'name': [users first and last name]}
        """
        r = self._get('users/me')
        return r.json()['data']

    def get_user_workspaces(self):
        """
        Gets all workspaces visible to authorized user
        return [dict]: eg: {'gid': str, 'name': [name of workspace], 'resource_type': 'workspace'}
        """
        r = self._get('workspaces')
        return r.json()['data']

    def get_projects(self):
        """
        Gets all projects visible to authorized user
        return [dict]: eg: {'gid': str, 'name': [name of project], 'resource_type': 'project'}
        """
        r = self._get('projects')
        return r.json()['data']

    def get_tasks(self, workspace, **params):
        """
        Gets all tasks assigned to authorized user
        return [dict]: eg: {'gid': str, 'name': [name of task], 'resource_type': 'task'}
        """
        r = self._get(f'workspaces/{workspace}/tasks/search', **params)
        return r.json()['data']

    def get_project_tasks(self, project_gid):
        """
        Gets all tasks assigned to authorized user in given project
        return [dict]: eg: [{'gid': str, 'name': [name of task], 'resource_type': 'task'},]
        """
        r = self._get(f'projects/{project_gid}/tasks')
        return r.json()['data']

    def get_project_sections(self, project_gid):
        r = self._get(f'projects/{project_gid}/sections')
        return r.json()['data']

    def get_tasks_details(self, task_gid):
        """
        Gets additial detils on each task. ie: assignee, completed, etc.
        """
        r = self._get(f'tasks/{task_gid}')
        return r.json()['data']

    def update_task(self, task_gid, **kwargs):
        """
        Updates the given task from task_gid
        """
        r = self._put(f'tasks/{task_gid}', data=kwargs)
        return r.json()['data']

    def get_tasks_from_section(self, section_gid):
        """
        Gets all tasks from a given section
        :param section_gid: section id to get tasks in
        :return:
        """
        r = self._get(f'sections/{section_gid}/tasks')
        return r.json()['data']

    def add_task_to_section(self, section_gid, **kwargs):
        """
        Adds a task on the board in the specific section
        :param task_name: name of task
        :param section_gid: section id to add task in
        """
        r = self._post(f'/sections/{section_gid}/addTask', data=kwargs)
        return r.json()['data']

    def _get(self, endpoint: str, data: dict = None, **params):

        url = f'{self.url}/{endpoint}'
        if params:
            params = self.__manipulate_kwargs(params)
            url = self.__with_parameters(url, params)

        r = requests.get(
            url=url,
            headers=self.headers,
            data=data)
        if int(r.status_code) == 200 or int(r.status_code) == 201:
            return r
        # raise HTTPError(f'{r.status_code}: {r.content}')

    def _post(self, endpoint: str, data: dict):
        r = requests.post(
            url=f'{self.url}/{endpoint}',
            headers=HEADERS,
            data=data)
        if int(r.status_code) == 200 or int(r.status_code) == 201:
            return r
        # raise HTTPError(f'{r.status_code}: {r.content}')

    def _put(self, endpoint: str, data: dict):
        r = requests.put(
            url=f'{self.url}/{endpoint}',
            headers=HEADERS,
            data=data)
        if int(r.status_code) == 200 or int(r.status_code) == 201:
            return r
        # raise HTTPError(f'{r.status_code}: {r.content}')

    @staticmethod
    def __with_parameters(url, params):
        unfurled = furl(url)
        unfurled.add(query_params=params)
        return unfurled.url

    @staticmethod
    def __manipulate_kwargs(kwargs):
        if 'assignee' in kwargs.keys():
            kwargs['assignee.any'] = kwargs.pop('assignee')
        if 'sections' in kwargs.keys():
            kwargs['sections.any'] = kwargs.pop('sections')
        return kwargs


# Welcome to the python challenges of version 73.

"""
Write a Python program that calculates and prints the nth Fibonacci number.

The value of n represents the position of the element in the sequence.

The initial value of n should be 0.

You may assume that the value of n is a non-negative integer.
"""
n = int(input("Enter the number : "))
lists = []

for x in range(0, n+1):
    if x == 0 or x == 1:
        lists.append(x)
    else:
        lists.append((lists[-1] + lists[-2]))

print(lists[n])


# -*- coding:utf-8 -*-
# ！/usr/bin/env python
# @Time : 2023/5/26 10:24
# @Author : waxberry
# @File : dubbo_api.py
# @Software : PyCharm

import json
import telnetlib

from PyQt5.QtCore.QUrl import port

class Dubbo(telnetlib.Telnet):
    prompt = 'dubbo>'

    def __init__(self, host=None, port=0):
        super().__init__(host, port)
        self.write(b'\n')

    def command(self, flag, str_=''):
        data = self.read_until(flag.encode())
        self.write(str_.encode() + b'\n')
        return data

    def invoke(self, service_name, method_name):
        command_str = 'invoke {0}.{1}()'.format(service_name, method_name)
        self.command(Dubbo.prompt, command_str)
        data = self.command(Dubbo.prompt, '')
        data = json.loads(data.decode(Dubbo.coding, errors='ignore').split('\n')[0].strip())

if __name__ == '__main__':
    conn = Dubbo('serviceIp', port)
    result = conn.invoke(
        'serviceName',
        'serviceName.method'
    )
    print(result)


# coding:utf-8
# 第1种解法
'''
1.把nums中所有元素存储到一维列表temp中
2.利用python切片在temp中截取所需的值
'''
def matrixReshape(nums,r,c):
    a = len(nums)
    b = len(nums[0])
    temp = []
    re_nums = []
    for i in range(a):
        for j in range(b):
            temp.append(nums[i][j])
    if a * b == r * c:
        for i in range(r):
            re_nums.append(temp[c * i:c + c * i])
        return re_nums
    else:
        return nums
print(matrixReshape([[1,2,3],[4,5,6]],3,2))

# 第2种解法
'''
1.熟悉python的生成器
2.yield from后面的参数必须是可迭代对象而yield不需要
'''
def matrixReshape2(nums,r,c):
    if r * c != len(nums) * len(nums[0]):
        return nums
    def gen(nums):
        for i in nums:
            yield from i
    it = gen(nums)
    return [[next(it) for _ in range(c)] for _ in range(r)]
print(matrixReshape2([[1,2,3],[4,5,6]],3,2))


#!/usr/bin/python3
"""Entry point of HBNB command interpreter"""

import cmd
from models.base_model import BaseModel
from models.user import User
from models.city import City
from models.state import State
from models.amenity import Amenity
from models.place import Place
from models.review import Review
from models import storage
from ast import literal_eval
import re

class HBNBCommand(cmd.Cmd):
    """Command interpreter class"""

    prompt = '(hbnb) '

    def do_create(self, class_name):
        """Creates a new instance of BaseModel"""

        if not class_name:
            print("** class name missing **")
        elif globals().get(class_name) is None:
            print("** class doesn't exist **")
        else:
            instance = storage.class_list()[class_name]()
            instance.save()
            print(instance.id)

    def do_show(self, line):
        """Prints the string representation of an instance"""

        line = line.split()
        if len(line) < 1:
            print("** class name missing **")
        elif globals().get(line[0]) is None:
            print("** class doesn't exist **")
        elif len(line) < 2:
            print("** instance id missing **")
        elif f"{line[0]}.{line[1]}" not in storage.all():
            print("** no instance found **")
        else:
            print(storage.all()[f"{line[0]}.{line[1]}"])

    def do_destroy(self, line):
        """Deletes an instance based on the class name and id"""

        line = line.split()
        if len(line) < 1:
            print("** class name missing **")
        elif globals().get(line[0]) is None:
            print("** class doesn't exist **")
        elif len(line) < 2:
            print("** instance id missing **")
        elif f"{line[0]}.{line[1]}" not in storage.all():
            print("** no instance found **")
        else:
            del (storage.all()[f"{line[0]}.{line[1]}"])

    def do_all(self, class_name):
        """Prints all string representation of all instances"""

        if not class_name:
            print(list(str(instance) for instance in storage.all().values()))
        else:
            if globals().get(class_name) is None:
                print("** class doesn't exist **")
            else:
                print(list(str(instance) for instance in storage.all(
                ).values() if type(instance).__name__ == class_name))

    def do_update(self, line):
        """Updates an instance based on the class name and id"""

        # Usage: update <class name> <id> <attribute name> "<attribute value>"
        line = line.split()
        if len(line) < 1:
            print("** class name missing **")
        elif globals().get(line[0]) is None:
            print("** class doesn't exist **")
        elif len(line) < 2:
            print("** instance id missing **")
        elif f"{line[0]}.{line[1]}" not in storage.all():
            print("** no instance found **")
        elif len(line) < 3:
            print("** attribute name missing **")
        elif len(line) < 4:
            print("** value missing **")
        else:
            class_name = line[0]
            instance_id = line[1]
            attribute_name = line[2]
            attribute_value = literal_eval(line[3])

            instance = storage.all()[f"{class_name}.{instance_id}"]
            setattr(instance, attribute_name, attribute_value)
            instance.save()

    def do_EOF(self, line):
        """Quits the command interpreter when it receives EOF signal"""
        print()
        return True

    def do_quit(self, line):
        """Quits out of the command interpreter"""
        return True

    def emptyline(self):
        pass

    def default(self, line):
        ''' implements the default commands  '''
        objects = storage.all().values()
        argv = line.split('.', 1)

        if len(argv) != 2 or argv[0] not in storage.class_list():
            print('*** unknown syntax:', line)
            return

        if argv[0] in storage.class_list() and argv[1].endswith('()'):
            command = argv[1][:-2]

            if command not in ['all', 'count']:
                print('*** unknown syntax:', line)
                return

            if command == 'all':
                attrs = \
                    [obj for obj in objects if type(obj).__name__ == argv[0]]
                [print(att, end=', ' if att != attrs[-1] else '\n')
                    for att in attrs]
                return

            if command == 'count':
                count = 0
                for obj in objects:
                    if type(obj).__name__ == argv[0]:
                        count += 1
                print(count)
                return

        cls_name = argv[0]
        param = re.search(r"\((.*?)\)", argv[1])
        attributes = re.search(r"\{(.*?)\}", param[1])

        if param:
            method = argv[1][:param.span()[0]]
            param_list = param[1].split(', ', 2)
            id = param_list[0][1:-1]
            if len(param_list) == 1:
                line = ' '.join([cls_name, id])
                eval('self.do_' + method)(line)
            elif not attributes:
                param_list = ' '.join(param_list)
                line = ' '.join([cls_name, param_list])
                eval('self.do_' + method)(line)
            else:
                param_list = param[1].split(', ', 1)
                attr_dict = param_list[1].replace("'", '"')
                line = ' '.join([cls_name, id, attr_dict])
                eval('self.do_' + method)(line)

if __name__ == '__main__':
    HBNBCommand().cmdloop()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#############
# by Jeehyun
# 01 ~ 19년까지 경기가 있던 날 / 지역의 날씨 데이터를 하나의 csv 파일로 합침
# (4월1일부터 11월30일까지의 데이터)
#############

import pandas as pd

w_data = pd.read_csv("../Data/weather/2001.csv",  encoding='cp949')

for i in range(2002, 2020):
    filename = "../Data/weather/" + str(i) + ".csv"
    tmp = pd.read_csv(filename, encoding='cp949')
    w_data = w_data.append(tmp)

for i in range(1, 9):
    filename = "../Data/weather/add/" + str(i) + ".csv"
    tmp = pd.read_csv(filename, encoding='cp949')
    w_data = w_data.append(tmp)

w_data.to_csv("../Data/weather.csv")


import csv
from datetime import datetime

def main():
    try:
        current_date_and_time = datetime.now()
        products = read_products("products.csv")
        print("GIANT EAGLE")
        print()
        num_and_price = process_requests("request.csv", products)
        print()
        print(f"Number of Items: {num_and_price[0]}")
        print(f"Subtotal: {num_and_price[1]}")
        sales_tax = .06
        sales_tax = round(num_and_price[1]*sales_tax,2)
        print(f"Sales Tax: {sales_tax}")
        total= sales_tax+num_and_price[1]
        print(f"Total: {total}")
        print()
        print("Thank you, come again!")
        print(f"{current_date_and_time:%a %b %d %I:%M.%S %Y}")

    except FileNotFoundError as file_not_found_err:
        print(f"Error: cannot open file"
                "because it doesn't exist.")
    except PermissionError as perm_err:
        print(f"Error: cannot read from file"
                "because you don't have permission.")
    except KeyError as key_err:
        print(type(key_err).__name__, key_err)

def read_products(filename):
    prod_dict ={}
    PRODUCT_INDEX= 0
    NAME_INDEX= 1
    PRICE_INDEX=2
    with open(filename, "rt") as product_file:
        reader =csv.reader(product_file)
        next(reader)

        for row in reader:
            prod_num = row[PRODUCT_INDEX]
            prod_name = row[NAME_INDEX]
            prod_price = float(row[PRICE_INDEX])

            prod_dict[prod_num] = [prod_name, prod_price]

    return prod_dict

def process_requests(filename, products):
    with open(filename, "rt") as request_file:
        reader = csv.reader(request_file)
        next(reader)
        quantity=0
        total=0

        for row in reader:
            product = row[0]
            new_quantity = int(row[1])

            if product in products:
                value = products[product]
                name_of_product = value[0]
                price_of_product= float(value[1])
                print(f"{name_of_product}: {new_quantity} @ {price_of_product}")
                quantity += new_quantity
                new_total = new_quantity * price_of_product
                total += new_total
            else:
                print("User odered non-existent item.")

    return  quantity, total

if __name__ == "__main__":
    main()


import time

print('''\nSeja bem vindo a Air Python viagens!
Asseguir iremos calcular o valor da sua viagem!\n''')

distancia = float(input('Digite a distancia da viagem em KM: '))
print('Aguarde, calculando valor...\n')
time.sleep(3)

if distancia <= 200:
    curta = distancia * 0.50
    print('O valor da sua viagem saira entorno de: R${:.2f}'.format(curta))

if distancia > 200:
    longa = distancia * 0.45
    print('O valor da sua viagem com desconto saira entorno de: RS{:.2f}'.format(longa))

print('Tenha uma boa viagem!')


def generator_function(num):
    for i in range(num):
        yield i

# yield only keeps the most recent data in memory, unlike lists which store all items
# this makes it a lot faster

for item in generator_function(1000):
    print(item)

def gen2(num):
    for i in range(num):
        yield i * 2

# yield pauses the function and comes back when next is called

g = gen2(100)
print(next(g))  # this returns 0, it runs 0 * 2 and that is it. List run all range

h = gen2(100)
next(h)  # 0*2=0
next(h)  # 1*2=2
print(next(h))  # 2*2=4


import adal
from urllib.parse import urljoin
# AADTokenCredentials for multi-factor authentication
from msrestazure.azure_active_directory import AADTokenCredentials

class Profile:
    """
    A Class representing user profile.
    """

    def __init__(self, client_id, tenant, resource, authority_url):
        self.client_id = client_id
        self.tenant = tenant
        self.resource = resource
        self.authority_url = authority_url

    def _get_authentication_context(self):
        auth_url = urljoin(self.authority_url, self.tenant)

        return adal.AuthenticationContext(
            authority=auth_url,
            api_version=None)

    def authenticate_device_code(self):
        """
        Authenticate the end-user using device auth.
        """
        context = self._get_authentication_context()

        code = context.acquire_user_code(
            resource=self.resource,
            client_id=self.client_id)

        print(code['message'])

        mgmt_token = context.acquire_token_with_device_code(
            resource=self.resource,
            user_code_info=code,
            client_id=self.client_id)

        credentials = AADTokenCredentials(
            token=mgmt_token,
            client_id=self.client_id)

        return credentials.token


# Day 35: Pangram

def check_pangram(string):
    alphabet = "abcdefghijklmnopqrstuvwxyz"
    for letter in alphabet:
        if letter not in string:
            return False
    return True

sentence = "the quick brown fox jumps over a lazy dog"
print(check_pangram(sentence))

print('-'*35)

# Extra Challenge: Find my Position

def find_index(lst, num):
    if num in lst:
        return [index for index, i in enumerate(lst) if i == num]
    return [num for j in lst]

list1 = [1, 2, 4, 6, 7, 7]

print(find_index(list1, 7))
print(find_index(list1, 8))


import sqlite3
import json
import os
import sys
from addons import utils
from addons.checks import checks
from discord.ext import commands
from discord import utils as discord

class Service(commands.Cog):
    """
    Service commands (owner only)
    """

    #Construct
    def __init__(self, bot):
        self.bot = bot
        print('Addon "{}" loaded'.format(self.__class__.__name__))

    #send message
    #async def send(self, ctx, msg):
    #    await self.ctx.send(msg)

    #commands
    @commands.command()
    @checks.is_access_allowed(required_level=9000)
    async def load(self, ctx, name : str):
        extension = "addons.{}".format(name)
        try:
            self.bot.load_extension(extension)
            print("{} loaded".format(extension))
            await ctx.message.channel.send("{} loaded".format(extension))
        except Exception as e:
            print('{} failed to load.\n{}: {}'.format(extension, type(e).__name__, e))
            await ctx.message.channel.send('{} failed to load.\n{}: {}'.format(extension, type(e).__name__, e))

    @commands.command()
    @checks.is_access_allowed(required_level=9000)
    async def unload(self, ctx, name: str):
        extension = "addons.{}".format(name)
        self.bot.unload_extension(extension)
        print("{} unloaded".format(extension))
        await ctx.message.channel.send("{} unloaded".format(extension))

    @commands.command()
    @checks.is_access_allowed(required_level=9000)
    async def reload(self, ctx):
        """Reload addons, db and config (owner only)"""

        #Reload configuration file so we can apply some settings on the fly
        #might be useful
        with open('config.json') as data:
            self.bot.config = json.load(data)

        #TESTING: potentially unsafe and might lead to data corruption.
        #commit all changes and close connection before proceed
        self.bot.db.commit()
        self.bot.db.close()
        #Reinitialize connection to database
        self.bot.db = sqlite3.connect('main.db')

        #reload extensions
        for extension in self.bot.config['extensions']:
            try:
                self.bot.unload_extension(extension['name'])
                self.bot.load_extension(extension['name'])
            except Exception as e:
                print('{} failed to load.\n{}: {}'.format(extension['name'], type(e).__name__, e))
                await ctx.message.channel.send('{} failed to load.\n{}: {}'.format(extension['name'], type(e).__name__, e))
        await ctx.message.channel.send("Reload complete!")

    @commands.command()
    @checks.is_access_allowed(required_level=9000)
    async def shutdown(self, ctx):
        """This kills the bot"""

        await ctx.message.channel.send("bye fren :(")

        sys.exit(0)

    @commands.group()
    async def roles(self, ctx):
        """Roles management"""
        if ctx.invoked_subcommand is None:
            msg = "Have you ever tried `apu help roles`? I suggest you to do it now, fren"
            await ctx.message.channel.send(msg)

    @roles.command(name="list")
    @checks.is_access_allowed(required_level=2)
    async def roles_list(self, ctx):
        """ - Returns roles list for this server (Level 2)"""
        cursor = self.bot.db.cursor()

        if not await utils.db_check(self.bot, ctx.message, cursor, "roles"):
            return

        msg = "```List of roles:\n"
        cursor.execute("SELECT * FROM roles WHERE serverid=?", (ctx.message.guild.id,))
        data = cursor.fetchall()
        cursor.close()
        if data:
            for row in data:
                msg += "ID: {} | Role name: {} | Level: {}\n".format(row[1], row[2], row[3])
        else:
            msg += "Empty"
        msg += "```"
        await  ctx.message.channel.send(msg)

    @roles.command(name="add")
    @checks.is_access_allowed(required_level=3)
    async def roles_add(self, ctx, id : int, level : int):
        """ - Add role"""
        cursor = self.bot.db.cursor()

        if not await utils.db_check(self.bot, ctx.message, cursor, "roles"):
            return

        role = discord.get(ctx.message.guild.roles, id=id)

        if role is None:
            print("Role wasn't found")
            await ctx.message.channel.send("Role wasn't found, fren")
            return

        db = self.bot.db

        record = (role.id, role.name.lower(), level, ctx.message.guild.id)
        query = 'INSERT INTO roles(role_id, role, level, serverid) VALUES (?,?,?,?)'

        try:
            db.execute(query, record)
            db.commit()
            #Add role
            self.bot.access_roles[ctx.message.guild.id].update({id : level})
            await ctx.message.channel.send("Your record has been successfully added, fren")
        except sqlite3.Error as e:
            await ctx.message.channel.send("Failed to add new record, fren :(\n"
                                           "```{}```".format(str(e)))

    @roles.command(name="rm")
    @checks.is_access_allowed(required_level=3)
    async def roles_remove(self, ctx, id : int):
        """ - Remove role"""
        cursor = self.bot.db.cursor()

        if not await utils.db_check(self.bot, ctx, cursor, "roles"):
            return

        role = discord.get(ctx.message.guild.roles, id=id)

        if role is None:
            print("Role wasn't found")
            await ctx.message.channel.send("Role wasn't found, fren")
            return

        db = self.bot.db

        record = (role.name.lower(), ctx.message.guild.id)
        query = 'DELETE FROM roles WHERE role=? AND serverid=?'
        if db.execute(query, record).rowcount == 0:
            await ctx.message.channel.send("Failed to remove this record, fren")
        else:
            db.commit()
            #Remove role from storage
            self.bot.access_roles[ctx.message.guild.id].pop(role.id)
            await ctx.message.channel.send("This record has been successfully removed, fren")

    @commands.group()
    async def db(self, ctx):
        """Database management (owner only)"""
        if ctx.invoked_subcommand is None:
            msg = "Have you ever tried `apu help db`? I suggest you to do it now, fren"
            await ctx.message.channel.send(msg)

    @db.command(name="init")
    @checks.is_access_allowed(required_level=9000)
    async def db_init(self, ctx):
        """Initializes db (required on first start)"""
        db = self.bot.db

        try:
            roles = [
                ('commander', 3, 87159376091033600), ('moderator', 2, 87159376091033600)
            ]
            db.executemany('INSERT INTO roles(role, level, serverid) VALUES (?,?,?)', roles)

            db.commit()

            #put roles in storage
            #role[0] - role name
            #role[1] - access level
            for role in roles:
                self.bot.access_roles[ctx.message.guild.id].update({role[0] : role[1]})

            await ctx.message.channel.send("Database has been initialized, fren!")
        except sqlite3.Error as e:
            await ctx.message.channel.send("Failed to initialize db, fren :(")

    @db.command(name="add")
    @checks.is_access_allowed(required_level=9000)
    async def db_add(self, ctx, table : str, name : str, content : str):
        """ - Add record"""
        db = self.bot.db
        record = ('{}'.format(name), '{}'.format(content))
        query = 'INSERT INTO {} VALUES (?,?)'.format(table)

        try:
            db.execute(query, record)
            db.commit()
            await ctx.message.channel.send("Your record has been successfully added, fren")
        except sqlite3.Error:
            await ctx.message.channel.send("Failed to add new record, fren :(")

    @db.command(name="edit")
    @checks.is_access_allowed(required_level=9000)
    async def db_edit(self, ctx, table : str, name : str, column : str, value : str):
        """ - Edit record"""
        db = self.bot.db
        record = (name,)
        query = 'UPDATE {} SET {} = "{}" WHERE name=?'.format(table, column, value)
        if db.execute(query, record).rowcount == 0:
            await ctx.message.channel.send("This record wasn't found, fren")
        else:
            db.commit()
            await ctx.message.channel.send("This record has been successfully edited, fren")

    @db.command(name="rm")
    @checks.is_access_allowed(required_level=9000)
    async def db_remove(self, ctx, table : str, name : str):
        """ - Remove record"""

        db = self.bot.db
        record = (name,)
        query = 'DELETE FROM {} WHERE name=?'.format(table)
        if db.execute(query, record).rowcount == 0:
            await ctx.message.channel.send("Failed to remove this record, fren")
        else:
            db.commit()
            await ctx.message.channel.send("This record has been successfully removed, fren")

def setup(bot):
    bot.add_cog(Service(bot))


from random import randint as rint
import os
abc = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ"
frase = "MECOMOLOSMOCOS"
coords = [[2, 2],[2, 3],[2, 4],[2, 5],[2, 6],[2, 7],[3, 7],[4, 7],[5, 7],[5, 6],[5, 5],[5, 4],[5, 3],[5, 2]]
def main():
    grid = [[{"revealed": False, "char": abc[rint(0, 31)]} for c in range(14)] for r in range(6)]
    for i, pos in enumerate(coords):
        grid[pos[0]][pos[1]]["char"] = frase[i]
    while True:
        update(grid)
        cell = input().upper()
        row = abc.index(cell[0])
        cell = abc.index(cell[1])
        try:
            for pos in get_neighbors(row, cell):
                grid[pos[0]][pos[1]]["revealed"] = True
        except IndexError:
            print("Esa coordenada no existe. Ten en mente que el formato es [FILA][COLUMNA]")
            input("Enter para continuar: ")
def get_neighbors(row, cell):
    returnValue = []
    row = 1 if row == 0 else 4 if row == 5 else row
    cell = 1 if cell == 0 else 12 if cell == 13 else cell
    for r in range(-1, 2):
        for c in range(-1, 2):
            returnValue.append([row+r, cell+c])
    return returnValue
def update(grid):
    os.system("cls")
    print("[ ]", end=" ")
    for i in range(14):
        print(" " + abc[i], end=" ")
    print()
    r = 0
    for row in grid:
        print(" " + abc[r] + " ", end=" ")
        r += 1
        for cell in row:
            if cell["revealed"]:
                print("[" + cell["char"] + "]", end="")
                continue
            print("[.]", end="")
        print()
if __name__ == "__main__":
    main()


from .const import *

class Draw:

    @staticmethod
    def draw_tiles():
        WIN.fill(COL_BLACK)
        x, y = 0, 0
        for row in range(ROWS):
            x = 0
            for col in range(COLS):
                WIN.blit(TILE_IMG, (x, y))
                x = x + TILE_SIZE
            y = y + TILE_SIZE

    @staticmethod
    def draw_piece(colour, x_pos, y_pos):
        if colour == "white":
            WIN.blit(WHITE_IMG, (x_pos, y_pos))
        else:
            WIN.blit(BLACK_IMG, (x_pos, y_pos))

    @staticmethod
    def draw_info(turn):
        text = font.render(f'Turn: {turn.upper()}', True, COL_WHITE, COL_BLACK)
        WIN.blit(text, (10, 510))

    @staticmethod
    def draw_winner(winner):
        if winner == 'black' or winner == 'white':
            text = font.render(f' {winner.upper()} WON THE GAME !!!', True, COL_WHITE, COL_BLACK)
            WIN.blit(text, (10, 510))
        else:
            text = font.render(f'ITS  A  {winner.upper()} !!!', True, COL_WHITE, COL_BLACK)
            WIN.blit(text, (10, 510))


def preberi(ime_datoteke):
    t = open(ime_datoteke, "r", encoding="utf-8")
    st = 1
    slovar = {}
    for vrstica in t:
        vrstica = vrstica.rstrip()
        seznam = []
        for stevilka in vrstica.split(" "):
            seznam.append(int(stevilka))
        #print(seznam)
        seznam = preobrni(seznam)
        #print(seznam)
        slovar[st] = seznam

        st += 1
    t.close()
    return slovar

def preobrni(seznam):
    najmanjse = min (zip(seznam, range(0,len(seznam))))
    #print(list(zip(seznam, range(0,len(seznam)))))
    #print(najmanjse)
    st = 0
    nov_seznam = []
    while st < len(seznam):
        nov_seznam.append(seznam[(st+najmanjse[1])%len(seznam)])
        st += 1
    return nov_seznam

def mozna_pot(pot, zemljevid):
    #print("\n",zemljevid)
    #print(pot)

    def my_rek(pot,prejsen):
        #print(pot)
        if not pot:
            return True
        e = pot[0]
        pot = pot[1:]
        if len(zemljevid[e]) == 1:
            return False
        if prejsen in zemljevid[e]:
            if my_rek(pot,e):
                return True
        else:
            #print("hello ", prejsen , zemljevid[e])
            return False

    return len(zemljevid[pot[0]]) == 1 and len(zemljevid[pot[-1]]) == 1 and my_rek(pot[1:-1],pot[0]) and pot[0] in zemljevid[pot[1]]

def hamiltonova(pot, zemljevid):
    return mozna_pot(pot,zemljevid) and len(pot) == len(set(pot)) and all(len(zemljevid[e]) == 1 for e in list(set(list(zemljevid.keys())) - set(pot)))

def navodila(pot, zemljevid):
    return list(((zemljevid[krozisce].index(izhod)-zemljevid[krozisce].index(vhod))%len(zemljevid[krozisce])) for (vhod,krozisce,izhod) in zip(pot,pot[1:],pot[2:]))

def prevozi(zacetek, navodila, zemljevid):
    trenutni = zemljevid[zacetek][0]
    prejsen = zacetek
    #print(trenutni)
    seznam = []
    seznam.append(zacetek)
    seznam.append(trenutni)
    for st in navodila:
        x = zemljevid[trenutni][(zemljevid[trenutni].index(prejsen) + st) % len(zemljevid[trenutni])]
        prejsen = trenutni
        trenutni = x
        seznam.append(trenutni)
    return seznam

def sosedi(doslej, zemljevid):
    #print("Doslej:",doslej)
    mnozica = set()
    for e in doslej:
        for i in zemljevid[e]:
            if i not in doslej:
                mnozica.add(i)
    #print(mnozica)
    return mnozica

def razdalja(x, y, zemljevid):
    globina = 0
    x = [x]
    while y not in x:
        x = sosedi(x, zemljevid)
        globina += 1
    return globina

def najkrajsa_navodila(x, y, zemljevid):
    x = [x]
    seznam_slovarjev = []
    while y not in x:
        x = podobno_sosedi(x,zemljevid)
        seznam_slovarjev.append(x)
    pot = []
    for e in seznam_slovarjev[::-1]:
        #print(y)
        pot.append(y)
        y = e[y]
    pot.append(y)
    return navodila(pot[::-1],zemljevid)

def podobno_sosedi(doslej, zemljevid):
    seznam = {}
    for e in doslej:
        for i in zemljevid[e]:
            if i not in doslej:
                seznam[i] = e
    return seznam

import unittest
from random import randint
import os

class Test06(unittest.TestCase):
    maxDiff = 100000

    def test_01_preberi(self):
        self.assertEqual(
            preberi("zemljevid.txt"),
            {1: [3],
             2: [4],
             3: [1, 8, 7, 6, 4],
             4: [2, 3, 6, 5],
             5: [4, 11, 10],
             6: [3, 11, 4],
             7: [3, 8, 11],
             8: [3, 16, 9, 7],
             9: [8, 16, 14, 11],
             10: [5, 11, 13],
             11: [5, 6, 7, 9, 14, 10],
             12: [13],
             13: [10, 14, 12],
             14: [9, 16, 13, 11],
             15: [16],
             16: [8, 15, 14, 9]})

        fname = "z{:05}.bla".format(randint(10000, 99999))
        with open(fname, "w") as f:
            f.write("2\n3 1\n2")
        try:
            self.assertEqual(preberi(fname), {1:[2], 2: [1, 3], 3: [2]})
        finally:
            try:
                os.remove(fname)
            except:
                print("Ne morem pobrisati {}. (Je na Dropboxu?) Briši sam(a).".format(fname))

    def test_02_mozna_pot(self):
        zemljevid = preberi("zemljevid.txt")
        self.assertTrue(mozna_pot([1, 3, 7, 3, 4, 2], zemljevid))
        self.assertTrue(mozna_pot([1, 3, 7, 3, 4, 2][::-1], zemljevid))
        self.assertTrue(mozna_pot([1, 3, 7, 3, 4, 5, 4, 3, 1], zemljevid))
        self.assertTrue(mozna_pot([1, 3, 7, 3, 4, 5, 4, 3, 1][::-1], zemljevid))
        self.assertTrue(mozna_pot([1, 3, 8, 16, 15], zemljevid))
        self.assertTrue(mozna_pot([1, 3, 8, 16, 15][::-1], zemljevid))
        self.assertTrue(mozna_pot([15, 16, 15], zemljevid))

        # Ne začne/konča se na vhodih/izhodih
        self.assertFalse(mozna_pot([1, 3, 7, 11, 14, 16], zemljevid))
        self.assertFalse(mozna_pot([3, 7, 11, 14, 16, 15], zemljevid))

        # Vmes gre ven
        self.assertFalse(mozna_pot([1, 3, 6, 4, 2, 4, 5, 11, 14, 13, 12], zemljevid))
        self.assertFalse(mozna_pot([1, 3, 6, 4, 2, 2, 4, 5, 11, 14, 13, 12], zemljevid))

        # Ponovi eno križišče
        self.assertFalse(mozna_pot([1, 3, 8, 8, 16, 15], zemljevid))

        # Ni povezave
        self.assertFalse(mozna_pot([1, 3, 16, 15], zemljevid))
        self.assertFalse(mozna_pot([1, 15], zemljevid))

        zemljevid2 = {1: [2], 2: [1, 3], 3: [2]}
        self.assertTrue(mozna_pot([1, 2, 3], zemljevid2))
        self.assertFalse(mozna_pot([1, 3], zemljevid2))

        zemljevid2 = {1: [2], 2: [1, 3], 3: [2, 4], 4: [3]}
        self.assertTrue(mozna_pot([1, 2, 3, 4], zemljevid2))
        self.assertTrue(mozna_pot([4, 3, 2, 1], zemljevid2))
        self.assertFalse(mozna_pot([1, 3, 4], zemljevid2))
        self.assertFalse(mozna_pot([1, 4], zemljevid2))

    def test_03_hamiltonova(self):
        zemljevid = preberi("zemljevid.txt")
        self.assertTrue(hamiltonova([1, 3, 7, 8, 16, 9, 14, 11, 6, 4, 5, 10, 13, 12], zemljevid))
        self.assertTrue(hamiltonova([1, 3, 7, 8, 16, 9, 14, 11, 6, 4, 5, 10, 13, 12][::-1], zemljevid))

        # Ena manjka
        self.assertFalse(hamiltonova([1, 3, 8, 16, 9, 14, 11, 6, 4, 5, 10, 13, 12], zemljevid))

        # Ni začetka/konca
        self.assertFalse(hamiltonova([3, 8, 16, 9, 14, 11, 6, 4, 5, 10, 13, 12], zemljevid))
        self.assertFalse(hamiltonova([1, 3, 7, 8, 16, 9, 14, 11, 6, 4, 5, 10, 13], zemljevid))

        # Ponavljenje
        self.assertFalse(hamiltonova([1, 3, 8, 16, 9, 14, 11, 6, 4, 5, 10, 11, 14, 13, 12], zemljevid))
        self.assertFalse(hamiltonova([1, 3, 7, 8, 16, 9, 14, 11, 6, 3, 4, 5, 10, 13, 12], zemljevid))

        zemljevid2 = {1: [2], 2: [1, 3], 3: [2, 4], 4: [3]}
        self.assertTrue(hamiltonova([1, 2, 3, 4], zemljevid2))
        self.assertTrue(hamiltonova([4, 3, 2, 1], zemljevid2))
        self.assertFalse(hamiltonova([1, 2, 4], zemljevid2))

class Test07(unittest.TestCase):
    maxDiff = 100000

    def test_01_navodila(self):
        zemljevid = preberi("zemljevid.txt")
        self.assertEqual(navodila([1, 3, 8, 16, 15], zemljevid), [1, 1, 1])
        self.assertEqual(navodila([1, 3, 6, 4, 2], zemljevid), [3, 2, 2])
        self.assertEqual(navodila([1, 3, 6, 11, 14, 16, 15], zemljevid), [3, 1, 3, 2, 3])
        self.assertEqual(navodila([12, 13, 14, 11, 9, 8, 7, 3, 4, 2], zemljevid), [2, 1, 5, 1, 1, 2, 2, 3])
        self.assertEqual(navodila([2, 4, 2], zemljevid), [0])
        self.assertEqual(navodila([15, 16, 14, 11, 9, 16, 14, 11, 9, 16, 15], zemljevid), [1, 2, 5, 2, 3, 2, 5, 2, 2])

class Test08(unittest.TestCase):
    maxDiff = 100000

    def test_01_prevozi(self):
        zemljevid = preberi("zemljevid.txt")
        self.assertEqual(prevozi(1, [1, 1, 1], zemljevid), [1, 3, 8, 16, 15])
        self.assertEqual(prevozi(1, [3, 2, 2], zemljevid), [1, 3, 6, 4, 2])
        self.assertEqual(prevozi(1, [3, 1, 3, 2, 3], zemljevid), [1, 3, 6, 11, 14, 16, 15])
        self.assertEqual(prevozi(12, [2, 1, 5, 1, 1, 2, 2, 3], zemljevid), [12, 13, 14, 11, 9, 8, 7, 3, 4, 2])
        self.assertEqual(prevozi(2, [0], zemljevid), [2, 4, 2])
        self.assertEqual(prevozi(15, [1, 2, 5, 2, 3, 2, 5, 2, 2], zemljevid), [15, 16, 14, 11, 9, 16, 14, 11, 9, 16, 15])

class Test09(unittest.TestCase):
    maxDiff = 100000

    def test_01_sosedi(self):
        zemljevid = preberi("zemljevid.txt")
        self.assertEqual(sosedi({15}, zemljevid), {16})
        self.assertEqual(sosedi({15, 16}, zemljevid), {14, 9, 8})
        self.assertEqual(sosedi({15, 16, 14, 9, 8}, zemljevid), {3, 7, 11, 13})
        self.assertEqual(sosedi({15, 16, 14, 9, 8, 3, 7, 11, 13}, zemljevid), {1, 4, 6, 5, 10, 12})
        self.assertEqual(sosedi({15, 16, 14, 9, 8, 3, 7, 11, 13, 1, 4, 6, 5, 10, 12}, zemljevid), {2})
        self.assertEqual(sosedi({15, 16, 14, 9, 8, 3, 7, 11, 13, 1, 4, 6, 5, 10, 12, 2}, zemljevid), set())

        self.assertEqual(sosedi({6}, zemljevid), {4, 3, 11})
        self.assertEqual(sosedi({6, 4, 3, 11}, zemljevid), {2, 5, 1, 7, 8, 9, 14, 10})

    def test_02_razdalja(self):
        zemljevid = preberi("zemljevid.txt")
        self.assertEqual(razdalja(15, 16, zemljevid), 1)

        self.assertEqual(razdalja(15, 14, zemljevid), 2)
        self.assertEqual(razdalja(15, 9, zemljevid), 2)
        self.assertEqual(razdalja(15, 8, zemljevid), 2)

        self.assertEqual(razdalja(15, 7, zemljevid), 3)
        self.assertEqual(razdalja(15, 13, zemljevid), 3)

        self.assertEqual(razdalja(15, 5, zemljevid), 4)
        self.assertEqual(razdalja(15, 10, zemljevid), 4)

        self.assertEqual(razdalja(15, 2, zemljevid), 5)

        self.assertEqual(razdalja(6, 4, zemljevid), 1)
        self.assertEqual(razdalja(6, 5, zemljevid), 2)
        self.assertEqual(razdalja(6, 10, zemljevid), 2)
        self.assertEqual(razdalja(6, 13, zemljevid), 3)
        self.assertEqual(razdalja(6, 12, zemljevid), 4)

class Test10(unittest.TestCase):
    maxDiff = 100000

    def test_01_najkrajsa_pot(self):
        zemljevid = preberi("zemljevid.txt")
        self.assertEqual(najkrajsa_navodila(1, 15, zemljevid), [1, 1, 1])
        self.assertEqual(najkrajsa_navodila(1, 2, zemljevid), [4, 3])
        self.assertEqual(najkrajsa_navodila(2, 15, zemljevid), [1, 2, 1, 1])
        self.assertEqual(najkrajsa_navodila(2, 12, zemljevid), [3, 2, 2, 2])
        self.assertEqual(najkrajsa_navodila(15, 12, zemljevid), [1, 1, 1])

        self.assertEqual(najkrajsa_navodila(15, 1, zemljevid), [3, 3, 4])
        self.assertEqual(najkrajsa_navodila(2, 1, zemljevid), [1, 1])
        self.assertEqual(najkrajsa_navodila(15, 2, zemljevid), [3, 3, 3, 3])
        self.assertEqual(najkrajsa_navodila(12, 2, zemljevid), [1, 1, 1, 1])
        self.assertEqual(najkrajsa_navodila(12, 15, zemljevid), [2, 3, 3])

        navodila = najkrajsa_navodila(1, 12, zemljevid)
        self.assertEqual(len(navodila), 5)
        self.assertEqual(prevozi(1, navodila, zemljevid)[-1], 12)

        navodila = najkrajsa_navodila(12, 1, zemljevid)
        self.assertEqual(len(navodila), 5)
        self.assertEqual(prevozi(12, navodila, zemljevid)[-1], 1)

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


import pydicom as pyd
import copy
import cv2
import numpy as np
from PIL import Image
from pydicom.pixel_data_handlers import apply_rescale, apply_voi_lut

# def read_cxr_image(path):

def get_bits_stored(dcm: pyd.FileDataset):
    return dcm[0x0028, 0x0101].value

def get_bits_allocted(dcm: pyd.FileDataset):
    return dcm[0x0028, 0x0100].value

def invert_pixel_array(
    pixel_array: np.ndarray, dcm: pyd.FileDataset, use_dcm_header=False
):
    """
    invert dicom pixel array
    return : inverted pixel array
    """

    if use_dcm_header:
        bits_stored = get_bits_stored(dcm)
        max_value = 2 ** int(bits_stored) - 1
    else:
        max_value = np.max(pixel_array)

    return max_value - pixel_array

def save_image_uint16(image, path):
    image = image.astype(np.uint16)
    array_buffer = image.tobytes()
    output = Image.new("I", image.T.shape)
    output.frombytes(array_buffer, "raw", "I;16")
    output.save(path)

def get_image_from_dcm(
    dicom,
    output_path=None,
    use_dcm_header=False,
):
    """
    dcm : str or pyd.FileDataset
    return : np.array
    """
    if isinstance(dicom, str):
        dcm = pyd.dcmread(dicom)
    elif isinstance(dicom, pyd.FileDataset):
        dcm = copy.deepcopy(dicom)

    pixel_array = dcm.pixel_array
    pixel_array = apply_rescale(pixel_array, dcm)

    # check
    # print(dcm[0x0028, 0x0004].value)
    # origin = dcm[0x0028, 0x0004].value
    # converted = str(origin).upper().strip()
    # if origin != converted:
    #     print(origin, converted, dicom)
    #     dcm[0x0028, 0x0004].value = "MONOCHROME1"
    # dcm[0x0028, 0x0004].value = str(origin).upper().strip()

    if use_dcm_header:
        pixel_array = apply_voi_lut(pixel_array, dcm)

    if get_photometric_interpretation(dcm) == "MONOCHROME1":
        pixel_array = invert_pixel_array(pixel_array, dcm, use_dcm_header)

    # min max normalization
    max_value = np.max(pixel_array)
    min_value = np.min(pixel_array)
    pixel_array = (pixel_array - min_value) / (max_value - min_value)
    pixel_array *= 2**16 - 1

    assert np.max(pixel_array) == 65535 and np.min(pixel_array) == 0

    if output_path is not None:
        save_image_uint16(pixel_array, output_path)
    return pixel_array

def get_bitsstored_bitsallocated(dcm: pyd.FileDataset):
    bits_stored = get_bits_stored(dcm)
    bits_allocated = get_bits_allocted(dcm)
    return bits_stored, bits_allocated

def get_photometric_interpretation(dcm: pyd.FileDataset):
    """
    get photometric interpretation value from dicom

    return : 'MONOCHROME1' or 'MONOCHROME2'
    """
    photometric = str(dcm[0x0028, 0x0004].value)
    photometric = "MONOCHROME2" if photometric is None else photometric
    photometric = photometric.upper().strip()

    return photometric

def from_uint16_to_float32(pixel_array: np.ndarray, dcm: pyd.FileDataset):
    """ """
    bits_stored = get_bits_stored(dcm)
    max_value = (
        2 ** int(bits_stored) - 1 if bits_stored is not None else np.max(pixel_array)
    )
    return pixel_array.astype(np.float32) / max_value

def get_max_contour(contours):
    max_size = -1
    max_contour = None
    for contour in contours[0]:
        if cv2.contourArea(contour) > max_size:
            max_contour = contour
            max_size = cv2.contourArea(contour)
    return max_contour

def get_box_from_mask(path_mask, output_format="cxcywh"):
    # from torchvision.ops.boxes import box_convert

    mask: np.array = cv2.imread(path_mask, cv2.IMREAD_UNCHANGED).astype(np.uint8)
    height, width = mask.shape[:2]
    contours = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if len(contours[0]) != 1:
        raise ValueError(f"{path_mask} has multiple contours")

    max_contour = get_max_contour(contours)
    x, y, w, h = cv2.boundingRect(max_contour)

    x = x / width
    w = w / width

    y = y / height
    h = h / height

    cx = x + w / 2
    cy = y + h / 2
    # output = box_convert(box, in_fmt="xywh", out_fmt=output_format)[0]
    return np.array([cx, cy, w, h])

# output_arr = utils_cxr.from_uint16_to_float32(pixel_array,dcm)
# output_arr = Image.fromarray(output_arr)
# output_path = path_dcm.replace(".dcm", ".tiff")
# output_path = output_path.replace("dicom", "png")
# output_arr.save(output_path)


__author__ = 'minhtule'

from parameter import *
import urllib2
import logging
import utility

def append_parameter(parameters, parameter_creator_func, value, is_required=False):
    if is_required or value is not None:
        param = parameter_creator_func(value)
        parameters.append(param)

class HTTPRequest(object):
    """

    """

    GOOGLE_ANALYTICS_HOST = "http://www.google-analytics.com/collect"

    def __init__(self, tracker, hit_type, other_parameters):
        self.__tracker = tracker
        self.__params = []
        self.__params.append(ProtocolVersion())  # Protocol Version
        self.__params.append(TrackingID(tracker.tracking_id))  # Tracking ID
        self.__params.append(ClientID(tracker.client_id))  # Client ID
        self.__params.append(HitType(hit_type))  # Hit type
        self.__params.append(CacheBuster())  # Cache Buster, random number to clear cache
        append_parameter(self.__params, UserLanguage, tracker.original_request_language)
        self.__params.extend(other_parameters)

    def add_custom_dimension(self, index, value):
        self.__params.append(CustomDimension(CustomDimension.key_for_index(index), value))

    def add_custom_metric(self, index, value):
        self.__params.append(CustomMetric(CustomMetric.key_for_index(index), value))

    def send(self):
        request = urllib2.Request(self.GOOGLE_ANALYTICS_HOST,
                                  origin_req_host=self.__tracker.original_request_ip)
        request.add_header("User-Agent", self.__tracker.original_request_user_agent)

        data_payload = self.__build_data_payload()
        request.add_data(data_payload)

        result = urllib2.urlopen(request)

        logging.debug(LOGGING_PREFIX + data_payload)

        if result.code == 200:
            return True
        else:
            logging.error(LOGGING_PREFIX + "Request to GA server failed with code " + result.code)
            return False

    def __build_data_payload(self):
        return "&".join([param.url_format() for param in self.__params])

class PageTrackingRequest(HTTPRequest):
    PAGE_TRACKING_HIT_TYPE = "pageview"

    def __init__(self, tracker, document_hostname=None, document_path=None, document_title=None):
        other_params = []
        append_parameter(other_params, DocumentHostName, document_hostname, is_required=False)
        append_parameter(other_params, DocumentPath, document_path, is_required=False)
        append_parameter(other_params, DocumentTitle, document_title, is_required=False)
        super(PageTrackingRequest, self).__init__(tracker, self.PAGE_TRACKING_HIT_TYPE, other_params)

class EventTrackingRequest(HTTPRequest):
    EVENT_TRACKING_HIT_TYPE = "event"

    def __init__(self, tracker, category, action, label=None, value=None):
        other_params = []
        append_parameter(other_params, EventCategory, category, is_required=True)
        append_parameter(other_params, EventAction, action, is_required=True)
        append_parameter(other_params, EventLabel, label, is_required=False)
        append_parameter(other_params, EventValue, value, is_required=False)

        super(EventTrackingRequest, self).__init__(tracker, self.EVENT_TRACKING_HIT_TYPE, other_params)

class TransactionTrackingRequest(HTTPRequest):
    TRANSACTION_TRACKING_HIT_TYPE = 'transaction'

    def __init__(self, tracker, transaction_id, transaction_affiliation=None, transaction_revenue=None, transaction_shipping=None, transaction_tax=None, currency_code=None):
        other_params = []

        append_parameter(other_params, TransactionID, transaction_id, is_required=True)
        append_parameter(other_params, TransactionAffiliation, transaction_affiliation, is_required=False)
        append_parameter(other_params, TransactionRevenue, transaction_revenue, is_required=False)
        append_parameter(other_params, TransactionShipping, transaction_shipping, is_required=False)
        append_parameter(other_params, TransactionTax, transaction_tax, is_required=False)
        append_parameter(other_params, CurrencyCode, currency_code, is_required=False)

        super(TransactionTrackingRequest, self).__init__(tracker, self.TRANSACTION_TRACKING_HIT_TYPE, other_params)

class ItemTrackingRequest(HTTPRequest):
    ITEM_TRACKING_HIT_TYPE = 'item'

    def __init__(self, tracker, transaction_id, item_name, item_price=None, item_quantity=None, item_code=None, item_category=None, currency_code=None):
        other_params = []

        append_parameter(other_params, TransactionID, transaction_id, is_required=True)
        append_parameter(other_params, ItemName, item_name, is_required=True)
        append_parameter(other_params, ItemPrice, item_price, is_required=False)
        append_parameter(other_params, ItemQuantity, item_quantity, is_required=False)
        append_parameter(other_params, ItemCode, item_code, is_required=False)
        append_parameter(other_params, ItemCategory, item_category, is_required=False)
        append_parameter(other_params, CurrencyCode, currency_code, is_required=False)

        super(ItemTrackingRequest, self).__init__(tracker, self.ITEM_TRACKING_HIT_TYPE, other_params)


from zrb.helper.typecheck import typechecked
import libcst as cst

@typechecked
class TaskTransformer(cst.CSTTransformer):
    def __init__(self, task_name: str, upstream_task_name: str):
        super().__init__()
        self.task_name: str = task_name
        self.upstream_task_name: str = upstream_task_name
        self._on_task_call = False
        self._upstream_added = False

    def _is_task(self, node: cst.Call) -> bool:
        if (
            not isinstance(node.func, cst.Name)
            or node.func.value != "Task"
        ):
            return False
        # Look for name keyword
        for name_arg in node.args:
            if (
                isinstance(name_arg, cst.Arg)
                and name_arg.keyword.value == "name"
                and name_arg.value.evaluated_value == self.task_name
            ):
                return True
        return False

    def visit_Call(self, node: cst.Call):
        # Visit all function call (or class initiation)
        # If it is the task we seek, flag it
        if self._is_task(node):
            self._on_task_call = True

    def leave_Call(
        self, original_node: cst.Call, updated_node: cst.Call
    ) -> cst.Call:
        # Remove flags.
        # If upstreams argument not found (see: self.leave_Arg), add it
        if not self._is_task(updated_node):
            return updated_node
        self._on_task_call = False
        if self._upstream_added:
            return updated_node
        new_args = [arg for arg in updated_node.args]
        new_args.append(cst.Arg(
            keyword=cst.parse_expression('upstreams'),
            value=cst.List([
                cst.Element(cst.parse_expression(self.upstream_task_name))
            ])
        ))
        self._upstream_added = True
        return updated_node.with_changes(
            args=new_args
        )

    def leave_Arg(self, orginnal_node: cst.Arg, updated_node: cst.Arg):
        # Once the flag was set (see: self.visit_Call), look for
        # `upstreams` argument and modify the value
        if (
            not self._on_task_call
            or updated_node.keyword is None
            or updated_node.keyword.value != 'upstreams'
        ):
            return updated_node
        new_elements = [
            old_element for old_element in updated_node.value.elements
        ]
        new_elements.append(cst.Element(
            value=cst.parse_expression(self.upstream_task_name)
        ))
        self._upstream_added = True
        return updated_node.with_changes(
            value=cst.List(new_elements)
        )

@typechecked
def add_upstream_to_task(
    code: str, task_name: str, upstream_task_name: str
) -> str:
    """
    Transformer to add an upstream task to a Task object.

    Args:
        code (str): The code to modify.
        task_name (str): Name of the task to modify.
        upstream_task_name (str): Name of the upstream task to add.

    Returns:
        A modified version of the input code with the upstream task added.
    """
    transformer: TaskTransformer = TaskTransformer(
        task_name, upstream_task_name
    )
    original_tree: cst.Module = cst.parse_module(code)
    modified_tree: cst.Module = original_tree.visit(transformer)
    return modified_tree.code


from ciscoepnmclient.models import EpnmModelStructure

class EpnmCeDataModel(EpnmModelStructure):
    pass

class EpnmCeDataServiceModel(EpnmCeDataModel):

    _required_fields = [
        ("bundling", bool),
        ("ce_vlan_id_preservation", bool),
        ("mtu", int)
    ]

    _optional_fields = [
        ("ce_vlan_cos_preservation", bool),
        ("enable_cfm", bool),
        ("cfm_domain_name", str),
        ("cfm_domain_level", str),
        ("ccm_interval", str),
        ("configure_remote_mep", bool),
        ("fault_management_map", dict),
        ("max_uni_endpoints", int),
        ("vpn_id", int),
        ("auto_allocate_vlan_id", bool)

    ]

    _dict_fields = {
        "bundling": "sa.bundling",
        "ce_vlan_id_preservation": "sa.ce-vlan-id-preservation",
        "ce_vlan_cos_preservation": "sa.ce-vlan-cos-preservation",
        "mtu": "sa.mtu-size",
        "enable_cfm": "sa.enable-cfm",
        "cfm_domain_name": "sa.cfm-domain-name",
        "cfm_domain_level": "sa.cfm-domain-level",
        "ccm_interval": "sa.ccm_interval",
        "configure_remote_mep": "sa.configure-remote-mep",
        "fault_management_map": "sa.fault-management-map",
        "max_uni_endpoints": "sa.max-uni-endpoints",
        "vpn_id": "sa.vpn-id",
        "auto_allocate_vlan_id": "sa.auto-allocate-vlan-id"
    }


# Sloane Luckiewicz

import turtle
turtle.bgcolor("skyblue")
turtle.setup(500,500)

# set up pen
pen = turtle.Turtle()
pen.color("black")
pen.fillcolor("red")
pen.hideturtle()
pen.speed(0)

# get the uhaul size
size = turtle.numinput( "U-Haul", "Size (1-10):" ,4,1,10)
uhualWidth = size * 50
boxWidth = uhualWidth * .75
cabWidth = uhualWidth - boxWidth
boxHeight = uhualWidth / 2
cabHeight = boxHeight / 2
tireRadius = uhualWidth * .1

# draw the UHaul Body
pen.up()
pen.setpos(-uhualWidth/2, 0)
pen.down()
pen.begin_fill()
pen.forward(uhualWidth)
pen.left(90)
pen.forward(cabHeight)
pen.left(90)
pen.forward(cabWidth)
pen.right(90)
pen.forward(boxHeight-cabHeight)
pen.left(90)
pen.forward(boxWidth)
pen.left(90)
pen.forward(boxHeight)
pen.end_fill()

# UHaul left tire
pen.up()
pen.setheading(0)
pen.setpos(-uhualWidth/4, -tireRadius)
pen.down()
pen.fillcolor("black")
pen.begin_fill()
pen.circle(tireRadius)
pen.end_fill()

# right tire
pen.up()
pen.setheading(0)
pen.setpos(uhualWidth/4, -tireRadius)
pen.down()
pen.fillcolor("black")
pen.begin_fill()
pen.circle(tireRadius)
pen.end_fill()

turtle.done()


# This piece of source code has been inspired by Padmamala ma'am's notes and geeksforgeeks.org.
# Link: https://www.geeksforgeeks.org/strongly-connected-components/
# Status of this code: Rough; works on all inputs, but still need to clean it.
import collections

# Padmamala ma'am had taught us about post-order numbering where we assign a discovery number to a vertex at the very end,
# i.e., after it has been explored completely. And then, we should reverse the graph and start with the vertex with the highest
# post-order number. The same effect can be achieved using a stack. Although both approaches are equally good (probably the
# post-order numbering is slightly better as we don't have to create a stack and thus save space) I found the stack approach
# a little easier to imagine and code; hence this variant.
# This function creates a stack of vertices where each vertex is pushed after it has been completely explored. It achieves the
# same goal as post-order numbering. After reversing the graph, we keep popping off vertices to find out the SSCs.
# The graph, a source vertex and an empty stack are taken as input. The final stack is stored in the stack object sent as input
def createDFSStack(graph, v, stack):
    try:                                # Python does not support static variables as C does, this is a small bodge
                                        # to emulate the same effect
        createDFSStack.count += 1       # try incrementing the function counter variable..
    except AttributeError:              # if it has not yet been defined, then Python will throw an error..
        createDFSStack.count = 0        # initialise the counter. It is used to assign a discovery number to each vertex

    v.dfsNum = createDFSStack.count     # assign the next discovery number to the current vertex 'v'
    v.status = "Visited"                # Mark 'v' as Visited

    for neighbour in v.adjVertices:                     # for each neighbour of v, do the following..
        if neighbour.status != "Visited":               # if the neighbour is unvisited..
            createDFSStack(graph, neighbour, stack)     # call the same function on the neighbouring vertex

    stack.append(v)                                     # push the vertex into the stack at the very end

    if v.dfsNum == 0:                                   # If this is the first instance of the function..
        for vertex in graph.vertices:
            if vertex.status != "Visited":              # ..then check if any of the nodes have not yet been visited..
                createDFSStack(graph, vertex, stack)    # if so, run DFS on them..

# Performs a basic DFS on the graph object starting from vertex 'v' and writes the output to file object fout
def basicDFS(graph, v, fout):
    v.status = "Visited"                        # Mark vertex 'v' as visited
    fout.write(v.name + " ")
    for neighbour in v.adjVertices:             # for each neighbour..
        if neighbour.status != "Visited":       # if it has not yet been visited..
            basicDFS(graph, neighbour, fout)    # run DFS on them..

# Finds the strongly connected components. Input: the reversed graph, the stack containing vertices in order of
# exploration-completion time and the output file object
def findSSCs(graph, stack, fout):
    while len(stack) != 0:              # continue until the stack is empty
        v = stack.pop()                 # pop the vertex 'v' on top of the stack
        if v.status != "Visited":       # if it has not yet been visited..
            fout.write("{")             # then, it is a new component..
            basicDFS(graph, v, fout)    # run a basic DFS starting from that vertex
            fout.write("}\t")           # after the DFS call, we know all vertices of that component have been explored

def SSCDriver(graph, fout):                             # A driver function to find out the SSCs
    stack = collections.deque()                         # Create an empty stack
    createDFSStack(graph, graph.vertices[0], stack)     # create a stack of vertices which achieves the same goal as
    graph.revGraph()                                    # post-order numbering..and reverse the graph
    findSSCs(graph, stack, fout)                        # finally, find out the strongly connected components


"""
Observer
"""
from abc import abstractmethod

class Subject(object):
    def __init__(self):
        self._observers = []

    def attach(self, observer):
        if not observer in self._observers:
            self._observers.append(observer)

    def detach(self, observer):
        try:
            self._observers.remove(observer)
        except ValueError:
            pass

    def notify(self, modifier=None):
        for observer in self._observers:
            if modifier != observer:
                observer.update(self)

# Example usage
class Data(Subject):
    def __init__(self, name=''):
        Subject.__init__(self)
        self.name = name
        self._data: int = 0

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, value):
        self._data = value
        self.notify()

class Observer:
    @abstractmethod
    def update(self):
        pass

class HexViewer(Observer):
    def update(self, subject: Subject):
        print(
            f'HexViewer: Subject<{subject.name}> has data {hex(subject.data).upper()}')

class DecimalViewer(Observer):
    def update(self, subject):
        print(f'DecViewer: Subject<{subject.name}> has data  {subject.data}')

# client
def main():
    data1 = Data('Data 1')
    data2 = Data('Data 2')
    view1 = DecimalViewer()
    view2 = HexViewer()
    data1.attach(view1)
    data1.attach(view2)
    data2.attach(view2)
    data2.attach(view1)

    print("Setting <Data 1> = 10")
    data1.data = 10
    print("Setting <Data 2>= 15")
    data2.data = 15
    print("Setting <Data 1> = 3")
    data1.data = 3
    print("Setting <Data 2> = 5")
    data2.data = 5
    print("Detach HexViewer from data1 and data2.")
    data1.detach(view2)
    data2.detach(view2)
    print("Setting <Data 1> = 10")
    data1.data = 10
    print("Setting <Data 2> = 15")
    data2.data = 15

if __name__ == '__main__':
    main()


import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn import metrics

def wine_filter(inputf, t_size=0.2):
    dtset = pd.read_csv(inputf, delimiter=";", index_col=None)
    X = dtset.iloc[:, :-1].values
    Y = dtset.iloc[:, -1].values
    X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=t_size, random_state=3)
    sc_x = StandardScaler()
    X_train = sc_x.fit_transform(X_train)
    X_test = sc_x.transform(X_test)
    return X_train, X_test, Y_train, Y_test

X_train, X_test, Y_train, Y_test =  wine_filter('winequality-white.csv',0.2)
clf = RandomForestClassifier(n_estimators=1000,random_state=2000)
clf.fit(X_train, Y_train)
Y_pred=clf.predict(X_test)
print (metrics.accuracy_score(Y_test,Y_pred))


import json
import os
import sys
import boto3
import random
import urllib.request
# AWS lambda expects all the code to be in /var/task/ directory. for this project dir is below (shared/python has custom code)
# sh-4.2# ls -la /var/task/
# total 40
# drwxr-xr-x 1 root root 4096 Aug 19 23:47 .
# drwxr-xr-x 1 root root 4096 Aug 19 23:46 ..
# drwxrwxr-x 2 root root 4096 Aug 19 23:12 handle_portfolio_update
# -rw-r--r-- 1 root root    0 Aug 19 23:12 __init__.py
# drwxrwxr-x 2 root root 4096 Aug 19 23:12 schedule_listener
# drwxr-xr-x 1 root root 4096 Aug 19 23:47 shared
# drwxrwxr-x 2 root root 4096 Aug 19 23:12 system_event_listener
# drwxrwxr-x 2 root root 4096 Aug 19 23:12 test_custom_layer
if (True):
    try:
        sys.path.append('/var/task/shared/python')
        import aws_quant_infra as aq_i
        print(f"import aws_quant_infra is done!")
        print(aq_i.__file__)
        import aws_quant_risk as aq_r
        print(f"import aws_quant_risk is done!")
        print(aq_r.__file__)
    except Exception as exc:
        print(f'error importing:{exc}')
else:
    pass

REGION = os.environ['AWS_REGION']
print(f'aws region: {REGION}')

def boto3_test():
    print('Starting tests to check various boto3 calls')
    env, app = aqi_test()
    aqr_test(env, app)

def aqi_test():
    print('Testing aws_quant_infra.get_app_config_from_paramstore')
    env_config = aq_i.get_app_config_from_paramstore(REGION)
    print(env_config)

    print('Testing appconfig call')
    env = 'dev'
    app_config_details = json.loads(env_config.get('Mvp-PortfolioMonitoring-AppConfigDetails'))
    app = app_config_details.get('Application')
    config = app_config_details.get('Configuration')
    version = app_config_details.get(env)
    print(f'App: {app} Config: {config} Version: {version}')
    app_config = (boto3.client('appconfig'). \
                      get_configuration(Application=app
                                        ,Environment=env
                                        ,Configuration=config
                                        , ClientId=f'{random.randint(-sys.maxsize,sys.maxsize)}'
                                        ,ClientConfigurationVersion=version
                                        ).get('Content').read())
    # app_config = urllib.request.urlopen(
    #     f'http://localhost:2772/applications/{app}/environments/{env}/configurations/{config}'
    # ).read()

    app_config=json.loads(app_config.decode('utf-8'))
    print(app_config)

    print('Testing aws_quant_infra.get_secret')
    secret_name = app_config.get('secrets')[0]
    # secret = f'MvpPortfolioMonitoring-{secret_name}'
    secret = f'{secret_name}'
    secret_data = aq_i.get_secret(secret, REGION)
    print(secret_data)
    try:
        print('Testing format of response')
        print(secret_data[secret])
    except:
        print('get_secret response in wrong format!!!')

    return env_config, app_config

def aqr_test(env_config, app_config):
    print('Testing Batch call')
    batch_client = boto3.client('batch')
    batch_jobs_resp = batch_client.list_jobs(jobQueue='MvpPortfolioMonitoring_q_ec2')
    print(batch_jobs_resp)

    print('Testing aws_quant_risk.PortfolioTrackerFactory')
    PTF = aq_r.PortfolioTrackerFactory(env_config, app_config, 'Mvp-')
    print(str(PTF))

    print('Testing aq_r.PTF.get_all_portfolios (Dynamodb call)')
    PTF.load_all_portfolios()
    print(PTF.all_portfolios)

    print('Testing Events calls')
    for rule_name in [ 'trading_EOD', 'trading_SOD']:
        print(f'Checking call for rule name: {rule_name}')
        print(boto3.client('events').list_targets_by_rule(Rule=rule_name))

    print('Testing timestream call')
    timestream_db = env_config.get('Mvp-PortfolioMonitoring-TimestreamDb')
    timestream_table = 'iex_realtime_data'
    print('Checking for query endpoints')
    query = f'SELECT * FROM {timestream_db}.{timestream_table} LIMIT 10'
    print(boto3.client('timestream-query').query(
        QueryString=query,
    ))
    print('Checking for write endpoints')
    print(boto3.client('timestream-write').describe_database(
        DatabaseName=timestream_db
    ))

def lambda_handler(event, context):
    # TODO implement
    dirs = ['/var/task/', '/var/task/shared', '/var/task/shared/python']
    for one_dir in dirs:
        try:
            print(f"dir list {one_dir}:", os.listdir(one_dir),"\n")
        except:
            print(f"NO dir: {one_dir}","\n")
    print("PYTHONPATH:", os.environ.get('PYTHONPATH'),"\n")
    print("PATH:", os.environ.get('PATH'),"\n")
    print("LD_LIBRARY_PATH:", os.environ.get('LD_LIBRARY_PATH'),"\n")
    print("sys.path:", sys.path,"\n")
    print("incoming event:", event,"\n")

    boto3_test()

    return {
            'statusCode': 200,
            'body': json.dumps('Hello from Lambda!')
        }


# -*- coding: utf-8 -*-
"""
Created on Mon Dec 17 21:21:43 2018

@author: Mikko Impiö
"""
import pandas as pd
import numpy as np
from utils import find_similar

if __name__ == "__main__":

    # IMAGE CLASSIFICATION LABELS
    labelpath = 'C:\\koodia\\huawei\\food-101\\food-101\\meta\\labels.txt'
    classpath = 'C:\\koodia\\huawei\\food-101\\food-101\\meta\\classes.txt'
    label_names = pd.read_csv(labelpath, header=None)
    label_names = label_names.values.flatten().tolist()

    class_names = pd.read_csv(classpath, header=None)
    class_names = class_names.values.flatten().tolist()

    # RECIPE NAMES
    recipepath = "C:\\koodia\\huawei\\Yummly28K\\data_records_27638.txt"
    recipes = pd.read_csv(recipepath, header=None)
    orig_recipes = pd.read_csv(recipepath, header=None, sep='\t')

    recipes = recipes.replace("\d|\t", "",regex=True)
    recipes = recipes.replace("-|_", " ",regex=True)

    rem_words = ["My recipes",
                 "My Recipes",
                 "Myrecipes",
                 "MyRecipes",

                 "Allrecipes",
                 "AllRecipes",
                 "All recipes",
                 "All Recipes",

                 "Martha Stewart",
                 "Epicurious"]

    for word in rem_words:
        recipes = recipes.replace(word, "", regex=True)

    ## FIND SIMILAR
    from difflib import SequenceMatcher

    def diff(a, b):
        return SequenceMatcher(None, a, b).ratio()

    recipelist = recipes.values.flatten().tolist()

#    diffs = {}
#    for label in label_names:
#        diffs[label] = []
#        for i in range(len(recipelist)):
#            dif = diff(recipelist[i], label)
#            diffs[label].append(dif)
#            print("{}: {}".format(label, i))

#    np.save('diffs.npy',diffs)

#    similars = {}
#    sim_indices = {}
#    for key in diffs.keys():
#        top_5 = np.asarray(diffs[key]).argsort(axis=0)[-10::][::-1]
#        recipe = np.asarray(recipelist)[top_5]
#        similars[key] = recipe
#        sim_indices[key] = top_5

    diffs, similars, sim_indices = find_similar(label_names, recipelist)
    diffs = np.load('diffs.npy').item()

    # MAP THE CORRESPONDING RECIPE TO EACH LABEL
    food_mappings = {}
    # GO THROUGH FIRST ONES IN PROPOSED SIMILARS LIST
    for i,name in enumerate(label_names):
        food_index = sim_indices[name][0]
        food = recipelist[food_index]
        food_mappings[name] = [food, food_index]

    #  GO THROUGH ALTERNATIVE NAMES FROM THE SIMILARS LIST
    alts = pd.read_csv('C:\\Users\\Mikko Impiö\\Google Drive\\koodia\\huawei\\CO2_classifier\\recipe_alt_place_indices.txt', sep=",")
    for i, name in enumerate(alts.name.values):
        ind = alts.ind.values[i]
        food_index = sim_indices[name][ind]
        food = recipelist[food_index]
        food_mappings[name] = [food, food_index]

    # GO THROUGH MANUALLY SELECTED RECIPES
    alts = pd.read_csv('C:\\Users\\Mikko Impiö\\Google Drive\\koodia\\huawei\\CO2_classifier\\recipe_notfound_indices.txt', sep="\t")
    for i, name in enumerate(alts.name.values):
        food_index = alts.ind.values[i]
        if food_index != -1:
            food = recipelist[food_index]
            food_mappings[name] = [food, food_index]
        else:
            food_mappings[name] = ['nan', -1]

    np.save('food_mappings.npy',food_mappings)


from datetime import datetime, timedelta
from calendar import HTMLCalendar
from .models import Event

class Calendar(HTMLCalendar):
    def __init__(self, year=None, month=None):
        self.year = year
        self.month = month
        super(Calendar, self).__init__()

    def format_day(self, day):
        day_number = ''
        if day != 0:
            return f"{day}
 {day_number}
	"
        return '	'

    def format_week(self, theweek):
        week = ''
        for day_number, weekday in theweek:
            week += self.format_day(day_number)
        return f'
 {week}
'

    def format_month(self, withyear=True):
        cal = f'
\n'
        cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n'
        cal += f'{self.formatweekheader()}\n'
        for week in self.monthdays2calendar(self.year, self.month):
            cal += f'{self.format_week(week)}\n'
        cal += "
"
        return cal


LIMITE_DE_SAQUES = 3

extrato = ''
limite = 500
numero_de_saques = 0
saldo = 0000

menu = '''
############################# BEM VINDO AO BANCO PYTHON!#############################

[0]Depositar
[1]Extrato
[2]Sacar
[3]Sair

############################# BEM VINDO AO BANCO PYTHON! #############################

'''

while True :
    opcao = input(menu)

    if opcao == '0' :
       print("\n#####Depositar#####")
       valor = float(input("Quanto gostaria de depositar : "))

       if valor > 0 :
           saldo += valor
           extrato += f"Deposito de R${valor :.2f}\n"

       else:
           print("Não é possivel realizar o deposito ")

    elif opcao == '1' :
        print("#####Extrato#####")
        print("Não foi realizada nenhuma movimentação " if not extrato else extrato)
        print(f"seu saldo é de : {saldo:.2f} ")

        print("##########################################################")

    elif opcao == '2' :
        print("\n#####Saque#####")
        valor = float(input("Quanto gostaria de sacar : "))
        if numero_de_saques == LIMITE_DE_SAQUES: break
        numero_de_saques += 1

        if saldo <= 0 :
            print("Você não pode fazer essa opreção, pois está zerado!")
            break

        if valor > 500 :
            print("Você não pode tirar mais que R$500.00 por saque")
            break

        saldo -=  valor
        extrato += f"Saque : R${valor:.2f}"
        print("##########################################################")

    elif opcao == '3' :
        print("\n#####Fechando aplicativo#####")
        print("Obrigado por usar nosso banco ! ")
        print("##########################################################")
        break

    else :
        print("Operação Inválida, tente novamente")


import numpy

import matplotlib.pyplot as plt

def display_data(x_array, example_width=None, figsize=(10, 10)):
    """
    Displays 2D data in a nice grid.

    Parameters
    ----------
    x_array : array_like
        The input data of size (m x n) where m is the number of examples and n is the number of
        features.

    example_width : int, optional
        THe width of each 2-D image in pixels. If not provided, the image is assumed to be square,
        and the width is the floor of the square root of total number of pixels.

    figsize : tuple, optional
        A 2-element tuple indicating the width and height of figure in inches.
    """
    # Compute rows, cols
    if x_array.ndim == 2:
        num_examples, num_features = x_array.shape
    elif x_array.ndim == 1:
        num_features = x_array.size
        num_examples = 1
        x_array = x_array[None]  # Promote to a 2 dimensional array
    else:
        raise IndexError('Input x_array should be 1 or 2 dimensional.')

    example_width = example_width or int(numpy.round(numpy.sqrt(num_features)))
    example_height = int(num_features / example_width)

    # Compute number of items to display
    display_rows = int(numpy.floor(numpy.sqrt(num_examples)))
    display_cols = int(numpy.ceil(num_examples / display_rows))

    fig, ax_array = plt.subplots(display_rows, display_cols, figsize=figsize)
    fig.subplots_adjust(wspace=0.025, hspace=0.025)

    ax_array = [ax_array] if num_examples == 1 else ax_array.ravel()

    for i, ax in enumerate(ax_array):
        ax.imshow(x_array[i].reshape(example_height, example_width, order='F'), cmap='gray')
        ax.axis('off')
    fig.show()

    return 0


"""
    导出所有资源到文件中  用于导入到ocean_ctf 平台
"""
import os

import yaml

def find_files(directory, filename):
    results = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file == filename:
                results.append(os.path.join(root, file))
    return results

def main():
    current_directory = os.getcwd()
    if os.path.exists("vulnerability.yaml"):
        # 备份文件
        os.rename("vulnerability.yaml", "_vulnerability.yaml")
    vuln_files = find_files(current_directory, "vulnerability.yaml")
    datas = []
    for vuln_file in vuln_files:
        with open(vuln_file, "r") as f:
            try:
                yaml_data = yaml.safe_load(f)
            except yaml.YAMLError as e:
                print("Error while parsing YAML file:", e)
                continue
        if yaml_data.get("build"):
            print("building {}".format(yaml_data['image']))
            work_dir = os.path.dirname(vuln_file)
            context = yaml_data.get("context", ".")
            dockerfile = yaml_data.get("dockerfile", "Dockerfile")
            os.system(f"cd {work_dir} docker build {context} -t {yaml_data['image']} -f {dockerfile}")
        datas.append(yaml_data)
    print("Export Vulnerability Count {}".format(len(datas)))
    with open("vulnerability.yaml", 'w') as file:
        try:
            yaml.dump(datas, file, default_flow_style=False)
        except yaml.YAMLError as e:
            print("Error while writing YAML file:", e)

if __name__ == "__main__":
    main()


import codecs
from setuptools import setup, find_packages

entry_points = {
    "z3c.autoinclude.plugin": [
        'target = nti.app',
    ],
}

def _read(fname):
    with codecs.open(fname, encoding='utf-8') as f:
        return f.read()

setup(
    name='nti.app.messaging',
    version=_read('version.txt').strip(),
    author='Jason Madden',
    author_email='jason@nextthought.com',
    description="NTI Application Messaging",
    long_description=(_read('README.rst') + '\n\n' + _read('CHANGES.rst')),
    license='Apache',
    keywords='pyramid messaging',
    classifiers=[
        'Intended Audience :: Developers',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: Implementation :: CPython',
    ],
    zip_safe=True,
    packages=find_packages('src'),
    package_dir={'': 'src'},
    include_package_data=True,
    namespace_packages=['nti', 'nti.app'],
    install_requires=[
        'setuptools',
        'nti.messaging',
    ],
    entry_points=entry_points,
)


import torch
from torch.nn import Module
import abc
from typing import Dict, Optional, Callable
from torch.optim.optimizer import Optimizer, required
import math

def exponential_learning_rate_decay(base_lr, decay_rate, decay_steps, staircase):
    def call(round_i):
        if staircase:
            return base_lr * (decay_rate ** (round_i // decay_steps))
        else:
            return base_lr * (decay_rate ** (round_i / decay_steps))
    return call

def inverse_linear_decay_learning_rate(base_lr, decay_rate, decay_steps, staircase):
    def call(round_i):
        if staircase:
            return base_lr / (1.0 + decay_rate * (round_i // decay_steps))
        else:
            return base_lr / (1.0 + decay_rate * (round_i / decay_steps))
    return call

def inverse_sqrt_decay_learning_rate(base_lr, decay_rate, decay_steps, staircase):
    def call(round_i):
        if staircase:
            return base_lr / math.sqrt(1.0 + decay_rate * (round_i // decay_steps))
        else:
            return base_lr / math.sqrt(1.0 + decay_rate * (round_i / decay_steps))
    return call

def warmup_learning_rate(base_lr: float, warmup_steps: int, fn: Callable[[int], float]) -> Callable[[int], float]:
    if warmup_steps is None or warmup_steps <= 0:
        def call(round_i) -> float:
            return fn(round_i)
        return call
    else:
        def warmup_and_decay_fn(round_num) -> float:
            warmedup_value = base_lr * (round_num + 1) / warmup_steps
            if round_num < warmup_steps:
                return warmedup_value
            else:
                return fn(round_num - warmup_steps)
        return warmup_and_decay_fn

class AdaptiveOptimizer(Optimizer):
    """
    基于论文 Adaptive Federated Optimization实现的服务端的优化器
    """

    def __init__(self, global_model: Module,
                 lr=required,
                 lr_decay_policy: str='constant',
                 decay_rate=None,
                 decay_steps=None,
                 staircase=False,
                 warmup_steps=None,
                 more_defaults: Optional[Dict]=None,
                 weight_decay=0,
                 partial_weight_decay=False):
        """
        创建对象
        :param global_model: 模型
        :param lr:
        :param momentum:
        :param dampening:
        :param weight_decay:
        :param nesterov:
        """
        if lr_decay_policy == 'constant':
            scheduler = warmup_learning_rate(lr, warmup_steps=warmup_steps, fn=lambda _: lr)
        elif lr_decay_policy == 'exp_decay':
            scheduler = warmup_learning_rate(lr, warmup_steps, exponential_learning_rate_decay(lr, decay_rate=decay_rate, decay_steps=decay_steps, staircase=staircase))
        elif lr_decay_policy == 'inv_lin':
            scheduler = warmup_learning_rate(lr, warmup_steps, inverse_linear_decay_learning_rate(lr, decay_rate=decay_rate, decay_steps=decay_steps, staircase=staircase))
        elif lr_decay_policy == 'inv_sqrt':
            scheduler = warmup_learning_rate(lr, warmup_steps, inverse_sqrt_decay_learning_rate(lr, decay_rate=decay_rate, decay_steps=decay_steps, staircase=staircase))
        else:
            raise ValueError(
                'Unrecognized schedule type {!s}'.format(lr_decay_policy))
        self.scheduler = scheduler
        if lr is not required and lr < 0.0:
            raise ValueError("Invalid learning rate: {}".format(lr))
        if weight_decay < 0.0:
            raise ValueError("Invalid weight_decay value: {}".format(weight_decay))

        defaults = dict(lr=lr, weight_decay=weight_decay)
        # 获取模型参数的相关信息, 记录了当前参数的名称, 方便从计算后的 weight diff 中找到对应的参数名
        param_names = []
        params = []
        weight_decay_mask = []
        for k, v in global_model.named_parameters():
            param_names.append(k)
            params.append(v)
            # 检查相关的参数是否需要 wd
            if getattr(v, 'enable_weight_decay', False):
                weight_decay_mask.append(True)
            else:
                if partial_weight_decay:
                    weight_decay_mask.append(False)
                else:
                    weight_decay_mask.append(True)
        defaults.update(param_names=param_names, weight_decay_mask=weight_decay_mask)
        if more_defaults is not None:
            defaults.update(more_defaults)
        super(AdaptiveOptimizer, self).__init__(params, defaults)

    def step_lr_scheduler(self, round_i):
        lr = self.scheduler(round_i)
        for p in self.param_groups:
            p['lr'] = lr

    def get_current_lr(self):
        return self.param_groups[0]['lr']

    @torch.no_grad()
    def step(self, closure=None):
        raise NotImplemented('Must implement the optimizer steps')

    @abc.abstractmethod
    def step_pseudo_grads(self, pseudo_grads: Dict[str, torch.Tensor]):
        """
        :param pseudo_grads: 加权聚合后的模型的参数(在联邦学习中包括了buffer和param)
        :return:
        """
        pass

if __name__ == '__main__':
    scheduler = warmup_learning_rate(1.0, 10, exponential_learning_rate_decay(1.0, decay_rate=0.9,
                                                                                decay_steps=10,
                                                                                staircase=False))
    lr0 = scheduler(0)
    lr1 = scheduler(9)
    lr2 = scheduler(20)
    print(lr0, lr1, lr2)


from gtts import gTTS
from playsound import playsound
from PIL import Image, ImageGrab
import pytesseract
import sys
import os

imageFileName = "image.png"
try:
    im = ImageGrab.grabclipboard()
    im.save(imageFileName,'PNG')
except AttributeError:
    sys.exit("no image in the clipboard!")

text = pytesseract.image_to_string(Image.open(imageFileName) )
filename = "sample.mp3"

lang='en'
tts = gTTS(text=text, lang=lang)
try:
    tts.save(filename)
except PermissionError:
    print('Permission denied! Remove the sample.mp3 file')
playsound(filename)
os.remove(filename)


from window import Window
from windowstringreader import WindowStringReader
from partitionpane import PartitionPane
from readmultext import ReadMulText
from confirmwindow import ConfirmWindow
from actionresult import ActionResult
from device import Device
from installer import BIOSSIZE,ESPSIZE

class CustomPartition(object):
    def __init__(self, maxy, maxx, install_config):
        self.maxx = maxx
        self.maxy = maxy
        self.win_width = maxx - 4
        self.win_height = maxy - 4
        self.install_config = install_config
        self.path_checker = []

        self.win_starty = (self.maxy - self.win_height) // 2
        self.win_startx = (self.maxx - self.win_width) // 2

        self.text_starty = self.win_starty + 4
        self.text_height = self.win_height - 6
        self.text_width = self.win_width - 6
        self.cp_config = {}
        self.cp_config['partitionsnumber'] = 0
        self.devices = None
        self.has_slash = False
        self.has_remain = False
        self.has_empty = False

        self.disk_size = []
        self.disk_to_index = {}

        self.window = Window(self.win_height, self.win_width, self.maxy, self.maxx,
                             'Welcome to the Photon installer', False, can_go_next=False)
        Device.refresh_devices()

    def initialize_devices(self):
        self.devices = Device.refresh_devices_bytes()

        # Subtract BIOS&ESP SIZE from the disk_size since this much is hardcoded for bios
        # and efi partition in installer.py
        for index, device in enumerate(self.devices):
            self.disk_size.append((device.path, int(device.size) / 1048576 - (BIOSSIZE + ESPSIZE + 2)))
            self.disk_to_index[device.path] = index

    def display(self):
        self.initialize_devices()

        if 'autopartition' in self.install_config and self.install_config['autopartition'] == True:
            return ActionResult(True, None)

        self.device_index = self.disk_to_index[self.install_config['disk']]

        self.disk_buttom_items = []
        self.disk_buttom_items.append(('<Next>', self.next))
        self.disk_buttom_items.append(('<Create New>', self.create_function))
        self.disk_buttom_items.append(('<Delete All>', self.delete_function))
        self.disk_buttom_items.append(('<Go Back>', self.go_back))

        self.text_items = []
        self.text_items.append(('Disk', 20))
        self.text_items.append(('Size', 5))
        self.text_items.append(('Type', 5))
        self.text_items.append(('Mountpoint', 20))
        self.table_space = 5

        title = 'Current partitions:\n'
        self.window.addstr(0, (self.win_width - len(title)) // 2, title)

        info = ("Unpartitioned space: " +
                str(self.disk_size[self.device_index][1])+
                " MB, Total size: "+
                str(int(self.devices[self.device_index].size)/ 1048576) + " MB")

        self.partition_pane = PartitionPane(self.text_starty, self.maxx, self.text_width,
                                  self.text_height, self.disk_buttom_items,
                                  config=self.cp_config,
                                  text_items=self.text_items, table_space=self.table_space,
                                  info=info,
                                  size_left=str(self.disk_size[self.device_index][1]))

        self.window.set_action_panel(self.partition_pane)

        return self.window.do_action()

    def validate_partition(self, pstr):
        if not pstr:
            return ActionResult(False, None)
        sizedata = pstr[0]
        mtdata = pstr[2]
        typedata = pstr[1]
        devicedata = self.devices[self.device_index].path

        #no empty fields unless swap
        if (typedata == 'swap' and
                (len(mtdata) != 0 or len(typedata) == 0 or len(devicedata) == 0)):
            return False, "invalid swap data "

        if (typedata != 'swap' and
                (len(sizedata) == 0 or
                 len(mtdata) == 0 or
                 len(typedata) == 0 or
                 len(devicedata) == 0)):
            if not self.has_empty and mtdata and typedata and devicedata:
                self.has_empty = True
            else:
                return False, "Input cannot be empty"

        if typedata not in ['swap', 'ext3', 'ext4', 'xfs', 'btrfs']:
            return False, "Invalid type"

        if len(mtdata) != 0 and mtdata[0] != '/':
            return False, "Invalid path"

        if mtdata in self.path_checker:
            return False, "Path already existed"
        #validate disk: must be one of the existing disks
        i = self.device_index

        #valid size: must not exceed memory limit
        curr_size = self.disk_size[i][1]
        if len(sizedata) != 0:
            try:
                int(sizedata)
            except ValueError:
                return False, "invalid device size"

            if int(curr_size) - int(sizedata) < 0:
                return False, "invalid device size"
            #if valid, update the size and return true
            new_size = (self.disk_size[i][0], int(curr_size)- int(sizedata))
            self.disk_size[i] = new_size

        if mtdata == "/":
            self.has_slash = True

        self.path_checker.append(mtdata)
        return True, None

    def create_function(self):
        self.window.hide_window()

        self.cp_config['partition_disk'] = self.devices[self.device_index].path
        self.partition_items = []
        self.partition_items.append(('Size in MB: ' +
                                     str(self.disk_size[self.device_index][1]) +
                                     ' available'))
        self.partition_items.append(('Type: (ext3, ext4, xfs, btrfs, swap)'))
        self.partition_items.append(('Mountpoint:'))
        self.create_window = ReadMulText(
            self.maxy, self.maxx, 0,
            self.cp_config,
            str(self.cp_config['partitionsnumber']) + 'partition_info',
            self.partition_items,
            None,
            None,
            None,
            self.validate_partition,   #validation function of the input
            None,
            True,
            )
        result = self.create_window.do_action()
        if result.success:
            self.cp_config['partitionsnumber'] = self.cp_config['partitionsnumber'] + 1

        #parse the input in install config
        return self.display()

    def delete_function(self):
        self.delete()
        return self.display()

    def go_back(self):
        self.delete()
        self.window.hide_window()
        self.partition_pane.hide()
        return ActionResult(False, {'goBack':True})

    def next(self):
        if self.cp_config['partitionsnumber'] == 0:
            window_height = 9
            window_width = 40
            window_starty = (self.maxy-window_height) // 2 + 5
            confirm_window = ConfirmWindow(window_height, window_width, self.maxy,
                                           self.maxx, window_starty,
                                           'Partition information cannot be empty',
                                           info=True)
            confirm_window.do_action()
            return self.display()
        #must have /
        if not self.has_slash:
            window_height = 9
            window_width = 40
            window_starty = (self.maxy - window_height) // 2 + 5
            confirm_window = ConfirmWindow(window_height, window_width, self.maxy,
                                           self.maxx, window_starty, 'Missing /',
                                           info=True)
            confirm_window.do_action()
            return self.display()

        self.window.hide_window()
        self.partition_pane.hide()

        partitions = []
        for i in range(int(self.cp_config['partitionsnumber'])):
            if len(self.cp_config[str(i)+'partition_info'+str(0)]) == 0:
                sizedata = 0
            else:
                sizedata = int(self.cp_config[str(i) + 'partition_info' + str(0)])
            mtdata = self.cp_config[str(i) + 'partition_info' + str(2)]
            typedata = self.cp_config[str(i) + 'partition_info'+str(1)]

            partitions = partitions + [{"mountpoint": mtdata,
                                        "size": sizedata,
                                        "filesystem": typedata},]
        self.install_config['partitions'] = partitions

        return ActionResult(True, {'goNext':True})

    def delete(self):
        for i in range(int(self.cp_config['partitionsnumber'])):
            self.cp_config[str(i)+'partition_info'+str(0)] = ''
            self.cp_config[str(i)+'partition_info'+str(1)] = ''
            self.cp_config[str(i)+'partition_info'+str(2)] = ''
            self.cp_config[str(i)+'partition_info'+str(3)] = ''
        del self.disk_size[:]
        for index, device in enumerate(self.devices):
            self.disk_size.append((device.path, int(device.size) / 1048576 - (BIOSSIZE + ESPSIZE + 2)))
        del self.path_checker[:]
        self.has_slash = False
        self.has_remain = False
        self.has_empty = False
        self.cp_config['partitionsnumber'] = 0


import numpy as np
import sys
import math

def get_rmsd(x, y):
    rmsd = (( x - y ) ** 2).sum()
    rmsd = np.sqrt( rmsd / float(len(x)) )
    return rmsd

# load triplet file
data = np.load(sys.argv[1])

# open output log file
log=open(sys.argv[2], "w")

# first and last frame
k0 = int(sys.argv[3])
k1 = int(sys.argv[4])

# number of frames
n = len(data)

# cycle on pairs and write on a separate file
for k in range(k0, k1):
    # map one-dimensional index to two-dimensional indexes
    i = int(n - 2 - math.floor(math.sqrt(-8*k + 4*n*(n-1)-7)/2.0 - 0.5))
    j = int(k + i + 1 - n*(n-1)/2 + (n-i)*((n-i)-1)/2)
    # get rmsd
    rmsd = get_rmsd(data[i], data[j])
    # print on file
    log.write("%6d %6d %6.3f\n" % (i, j, rmsd))

# close file
log.close()


'''
문) bmi.csv 데이터셋을 이용하여 다음과 같이 softmax classifier 모델을 생성하시오.
   조건1> bmi.csv 데이터셋
       -> x변수 : height, weight 칼럼
       -> y변수 : label(3개 범주) 칼럼
    조건2> 딥러닝 최적화 알고리즘 : Adam
    조건3> learning rage : 0.001 or 0.005 선택(분류정확도 높은것)
    조건4> 반복학습, step 단위로 loss : <출력결과> 참고
    조건5> 분류정확도 출력
    조건6> 예측치와 정답 15개 출력

  <출력 결과>
step = 500 , loss = 0.44498476
step = 1000 , loss = 0.34861678
step = 1500 , loss = 0.28995454
step = 2000 , loss = 0.24887484
step = 2500 , loss = 0.2177721
step = 3000 , loss = 0.19313334
step = 3500 , loss = 0.17303815
step = 4000 , loss = 0.15629826
step = 4500 , loss = 0.1421249
step = 5000 , loss = 0.12996733
========================================
accuracy = 0.9769
========================================
y_pred :  [0 0 1 1 1 1 0 2 0 2 1 2 1 0 2]
y_true :  [0 0 1 1 1 1 0 2 0 2 1 2 1 0 2]
========================================
'''

import tensorflow as tf # ver1.x
from sklearn.preprocessing import minmax_scale # x data 정규화(0~1)
from sklearn.metrics import accuracy_score
import numpy as np
import pandas as pd

bmi = pd.read_csv('C:\\ITWILL\\5_Tensoflow\\data/bmi.csv')
print(bmi.info())

# 칼럼 추출
col = list(bmi.columns)
print(col)

# x,y 변수 추출
x_data = bmi[col[:2]] # x변수

# x_data 정규화
x_data = minmax_scale(x_data)

# label one hot encoding
label_map = {"thin": [1,0,0], "normal": [0,1,0], "fat": [0,0,1]}
bmi["label"] = bmi["label"].apply(lambda x : np.array(label_map[x]))

y_data = list(bmi["label"]) # 중첩list : [[1,0,0], [1,0,0]]

# numpy 객체 변환
x_data = np.array(x_data)
y_data = np.array(y_data)

################# X,Y 데이터 전처리 완료 #####################

# 1. X,Y변수 정의 : 공급형 변수
X = tf.constant(x_data, tf.float32)# [? 2]
Y = tf.constant(y_data, tf.float32)# [? 3]

# 2. w,b 변수 정의
w = tf.Variable(tf.random.normal([2, 3])) # [입력수, 출력수]
b = tf.Variable(tf.zeros([3]))  # [출력수]

# 3. 회귀방정식
def linear_model(X) : # train, test
    y_pred = tf.matmul(X, w) + b  # 행렬곱 : [None,3]*[3,1]=[None,1]
    return y_pred

# 4. softmax 활성함수 적용
def soft_fn(X):
    y_pred = linear_model(X)
    soft = tf.nn.softmax(y_pred)
    return soft

# 5. 손실 함수 정의 : 손실계산식 수정
def loss_fn() : #  인수 없음
    soft = soft_fn(X) # 훈련셋 -> 예측치 : 회귀방정식
    loss = -tf.reduce_mean(Y*tf.math.log(soft)+(1-Y)*tf.math.log(1-soft))
    return loss

# 6. 최적화 객체
opt = tf.optimizers.Adam(learning_rate=0.005)

# 7. 반복학습
for step in range(5000):
    opt.minimize(loss=loss_fn, var_list=[w,b])

    # 10 배수 단위 출력
    if (step+1) % 500 == 0:
        print('step=',(step+1),",loss val =", loss_fn().numpy())

# 8. 최적화된 model 검증
y_pred =soft_fn(X).numpy()
print(y_pred)
'''

'''

y_pred.sum(axis = 1)
# array([0.99999994, 0.9999999 , 1.        , 0.99999994, 1.        , 1.        ], dtype=float32)

# index 반환 : 확률 -> 10진수
y_pred = tf.argmax(y_pred, axis = 1)
#print(y_pred.numpy())

# 정답: one hot encoding -> 10진수
y_true = tf.argmax(Y, axis = 1)
#print(y_true.numpy())

acc = accuracy_score(y_true,y_pred)
print('accuracy=',acc)
# accuracy= 1.0

print('y_pred :' ,y_pred[0:14].numpy())
print('y_true :',y_true[0:14].numpy())


# clean investment and acquisition data files for displaying with Question 2.
import pandas as pd

investment_data = pd.read_csv('investments.csv')
aq_data = pd.read_csv('acquisitions.csv')
# convert the existing date column into a TimeSeries for easier manipulation and calculations
investment_data['funded_at'] = pd.to_datetime(investment_data['funded_at'])

# new column that specifies the quarter of the year the investment was made
investment_data['quarter'] = investment_data.funded_at.dt.quarter

# new column that specifies the name of the month that the investment was made
investment_data['month'] = investment_data.funded_at.dt.month_name()

# Clean acquisition data by converting dates to DateTime objects and dropping NA values
aq_data.dropna(subset=['acquired_at'], inplace=True)
aq_data['acquired_at'] = pd.to_datetime(aq_data.acquired_at, errors='coerce')
aq_data.dropna(subset=['acquired_at'], inplace=True)

# new column; month the acquisition was made
aq_data['month'] = aq_data.acquired_at.dt.month_name()
#new column; quarter the acquisition was made
aq_data['quarter'] = aq_data.acquired_at.dt.quarter

investment_data.to_csv('clean_investments.csv')
aq_data.to_csv('clean_acquisitions.csv')